Search is not available for this dataset
repo
stringlengths 2
152
⌀ | file
stringlengths 15
239
| code
stringlengths 0
58.4M
| file_length
int64 0
58.4M
| avg_line_length
float64 0
1.81M
| max_line_length
int64 0
12.7M
| extension_type
stringclasses 364
values |
---|---|---|---|---|---|---|
null |
ceph-main/src/python-common/ceph/__init__.py
| 0 | 0 | 0 |
py
|
|
null |
ceph-main/src/python-common/ceph/utils.py
|
import datetime
import re
import string
from typing import Optional
def datetime_now() -> datetime.datetime:
"""
Return the current local date and time.
:return: Returns an aware datetime object of the current date
and time.
"""
return datetime.datetime.now(tz=datetime.timezone.utc)
def datetime_to_str(dt: datetime.datetime) -> str:
"""
Convert a datetime object into a ISO 8601 string, e.g.
'2019-04-24T17:06:53.039991Z'.
:param dt: The datetime object to process.
:return: Return a string representing the date in
ISO 8601 (timezone=UTC).
"""
return dt.astimezone(tz=datetime.timezone.utc).strftime(
'%Y-%m-%dT%H:%M:%S.%fZ')
def str_to_datetime(string: str) -> datetime.datetime:
"""
Convert an ISO 8601 string into a datetime object.
The following formats are supported:
- 2020-03-03T09:21:43.636153304Z
- 2020-03-03T15:52:30.136257504-0600
- 2020-03-03T15:52:30.136257504
:param string: The string to parse.
:return: Returns an aware datetime object of the given date
and time string.
:raises: :exc:`~exceptions.ValueError` for an unknown
datetime string.
"""
fmts = [
'%Y-%m-%dT%H:%M:%S.%f',
'%Y-%m-%dT%H:%M:%S.%f%z'
]
# In *all* cases, the 9 digit second precision is too much for
# Python's strptime. Shorten it to 6 digits.
p = re.compile(r'(\.[\d]{6})[\d]*')
string = p.sub(r'\1', string)
# Replace trailing Z with -0000, since (on Python 3.6.8) it
# won't parse.
if string and string[-1] == 'Z':
string = string[:-1] + '-0000'
for fmt in fmts:
try:
dt = datetime.datetime.strptime(string, fmt)
# Make sure the datetime object is aware (timezone is set).
# If not, then assume the time is in UTC.
if dt.tzinfo is None:
dt = dt.replace(tzinfo=datetime.timezone.utc)
return dt
except ValueError:
pass
raise ValueError("Time data {} does not match one of the formats {}".format(
string, str(fmts)))
def parse_timedelta(delta: str) -> Optional[datetime.timedelta]:
"""
Returns a timedelta object represents a duration, the difference
between two dates or times.
>>> parse_timedelta('foo')
>>> parse_timedelta('2d') == datetime.timedelta(days=2)
True
>>> parse_timedelta("4w") == datetime.timedelta(days=28)
True
>>> parse_timedelta("5s") == datetime.timedelta(seconds=5)
True
>>> parse_timedelta("-5s") == datetime.timedelta(days=-1, seconds=86395)
True
:param delta: The string to process, e.g. '2h', '10d', '30s'.
:return: The `datetime.timedelta` object or `None` in case of
a parsing error.
"""
parts = re.match(r'(?P<seconds>-?\d+)s|'
r'(?P<minutes>-?\d+)m|'
r'(?P<hours>-?\d+)h|'
r'(?P<days>-?\d+)d|'
r'(?P<weeks>-?\d+)w$',
delta,
re.IGNORECASE)
if not parts:
return None
parts = parts.groupdict()
args = {name: int(param) for name, param in parts.items() if param}
return datetime.timedelta(**args)
def is_hex(s: str, strict: bool = True) -> bool:
"""Simple check that a string contains only hex chars"""
try:
int(s, 16)
except ValueError:
return False
# s is multiple chars, but we should catch a '+/-' prefix too.
if strict:
if s[0] not in string.hexdigits:
return False
return True
| 3,614 | 28.153226 | 80 |
py
|
null |
ceph-main/src/python-common/ceph/deployment/__init__.py
| 0 | 0 | 0 |
py
|
|
null |
ceph-main/src/python-common/ceph/deployment/drive_group.py
|
import enum
import yaml
from ceph.deployment.inventory import Device
from ceph.deployment.service_spec import (
CustomConfig,
GeneralArgList,
PlacementSpec,
ServiceSpec,
)
from ceph.deployment.hostspec import SpecValidationError
try:
from typing import Optional, List, Dict, Any, Union
except ImportError:
pass
class OSDMethod(str, enum.Enum):
raw = 'raw'
lvm = 'lvm'
def to_json(self) -> str:
return self.value
class DeviceSelection(object):
"""
Used within :class:`ceph.deployment.drive_group.DriveGroupSpec` to specify the devices
used by the Drive Group.
Any attributes (even none) can be included in the device
specification structure.
"""
_supported_filters = [
"actuators", "paths", "size", "vendor", "model", "rotational", "limit", "all"
]
def __init__(self,
actuators=None, # type: Optional[int]
paths=None, # type: Optional[List[Dict[str, str]]]
model=None, # type: Optional[str]
size=None, # type: Optional[str]
rotational=None, # type: Optional[bool]
limit=None, # type: Optional[int]
vendor=None, # type: Optional[str]
all=False, # type: bool
):
"""
ephemeral drive group device specification
"""
self.actuators = actuators
#: List of Device objects for devices paths.
self.paths = []
if paths is not None:
for device in paths:
if isinstance(device, dict):
path: str = device.get("path", '')
self.paths.append(Device(path, crush_device_class=device.get("crush_device_class", None))) # noqa E501
else:
self.paths.append(Device(str(device)))
#: A wildcard string. e.g: "SDD*" or "SanDisk SD8SN8U5"
self.model = model
#: Match on the VENDOR property of the drive
self.vendor = vendor
#: Size specification of format LOW:HIGH.
#: Can also take the form :HIGH, LOW:
#: or an exact value (as ceph-volume inventory reports)
self.size: Optional[str] = size
#: is the drive rotating or not
self.rotational = rotational
#: Limit the number of devices added to this Drive Group. Devices
#: are used from top to bottom in the output of ``ceph-volume inventory``
self.limit = limit
#: Matches all devices. Can only be used for data devices
self.all = all
def validate(self, name: str) -> None:
props = [self.actuators, self.model, self.vendor, self.size,
self.rotational] # type: List[Any]
if self.paths and any(p is not None for p in props):
raise DriveGroupValidationError(
name,
'device selection: `paths` and other parameters are mutually exclusive')
is_empty = not any(p is not None and p != [] for p in [self.paths] + props)
if not self.all and is_empty:
raise DriveGroupValidationError(name, 'device selection cannot be empty')
if self.all and not is_empty:
raise DriveGroupValidationError(
name,
'device selection: `all` and other parameters are mutually exclusive. {}'.format(
repr(self)))
@classmethod
def from_json(cls, device_spec):
# type: (dict) -> Optional[DeviceSelection]
if not device_spec:
return None
for applied_filter in list(device_spec.keys()):
if applied_filter not in cls._supported_filters:
raise KeyError(applied_filter)
return cls(**device_spec)
def to_json(self):
# type: () -> Dict[str, Any]
ret: Dict[str, Any] = {}
if self.paths:
ret['paths'] = [p.path for p in self.paths]
if self.model:
ret['model'] = self.model
if self.vendor:
ret['vendor'] = self.vendor
if self.size:
ret['size'] = self.size
if self.rotational is not None:
ret['rotational'] = self.rotational
if self.limit:
ret['limit'] = self.limit
if self.all:
ret['all'] = self.all
return ret
def __repr__(self) -> str:
keys = [
key for key in self._supported_filters + ['limit'] if getattr(self, key) is not None
]
if 'paths' in keys and self.paths == []:
keys.remove('paths')
return "DeviceSelection({})".format(
', '.join('{}={}'.format(key, repr(getattr(self, key))) for key in keys)
)
def __eq__(self, other: Any) -> bool:
return repr(self) == repr(other)
class DriveGroupValidationError(SpecValidationError):
"""
Defining an exception here is a bit problematic, cause you cannot properly catch it,
if it was raised in a different mgr module.
"""
def __init__(self, name: Optional[str], msg: str):
name = name or "<unnamed>"
super(DriveGroupValidationError, self).__init__(
f'Failed to validate OSD spec "{name}": {msg}')
class DriveGroupSpec(ServiceSpec):
"""
Describe a drive group in the same form that ceph-volume
understands.
"""
_supported_features = [
"encrypted", "block_wal_size", "osds_per_device",
"db_slots", "wal_slots", "block_db_size", "placement", "service_id", "service_type",
"data_devices", "db_devices", "wal_devices", "journal_devices",
"data_directories", "osds_per_device", "objectstore", "osd_id_claims",
"journal_size", "unmanaged", "filter_logic", "preview_only", "extra_container_args",
"extra_entrypoint_args", "data_allocate_fraction", "method", "crush_device_class", "config",
]
def __init__(self,
placement=None, # type: Optional[PlacementSpec]
service_id=None, # type: Optional[str]
data_devices=None, # type: Optional[DeviceSelection]
db_devices=None, # type: Optional[DeviceSelection]
wal_devices=None, # type: Optional[DeviceSelection]
journal_devices=None, # type: Optional[DeviceSelection]
data_directories=None, # type: Optional[List[str]]
osds_per_device=None, # type: Optional[int]
objectstore='bluestore', # type: str
encrypted=False, # type: bool
db_slots=None, # type: Optional[int]
wal_slots=None, # type: Optional[int]
osd_id_claims=None, # type: Optional[Dict[str, List[str]]]
block_db_size=None, # type: Union[int, str, None]
block_wal_size=None, # type: Union[int, str, None]
journal_size=None, # type: Union[int, str, None]
service_type=None, # type: Optional[str]
unmanaged=False, # type: bool
filter_logic='AND', # type: str
preview_only=False, # type: bool
extra_container_args: Optional[GeneralArgList] = None,
extra_entrypoint_args: Optional[GeneralArgList] = None,
data_allocate_fraction=None, # type: Optional[float]
method=None, # type: Optional[OSDMethod]
config=None, # type: Optional[Dict[str, str]]
custom_configs=None, # type: Optional[List[CustomConfig]]
crush_device_class=None, # type: Optional[str]
):
assert service_type is None or service_type == 'osd'
super(DriveGroupSpec, self).__init__('osd', service_id=service_id,
placement=placement,
config=config,
unmanaged=unmanaged,
preview_only=preview_only,
extra_container_args=extra_container_args,
extra_entrypoint_args=extra_entrypoint_args,
custom_configs=custom_configs)
#: A :class:`ceph.deployment.drive_group.DeviceSelection`
self.data_devices = data_devices
#: A :class:`ceph.deployment.drive_group.DeviceSelection`
self.db_devices = db_devices
#: A :class:`ceph.deployment.drive_group.DeviceSelection`
self.wal_devices = wal_devices
#: A :class:`ceph.deployment.drive_group.DeviceSelection`
self.journal_devices = journal_devices
#: Set (or override) the "bluestore_block_wal_size" value, in bytes
self.block_wal_size: Union[int, str, None] = block_wal_size
#: Set (or override) the "bluestore_block_db_size" value, in bytes
self.block_db_size: Union[int, str, None] = block_db_size
#: set journal_size in bytes
self.journal_size: Union[int, str, None] = journal_size
#: Number of osd daemons per "DATA" device.
#: To fully utilize nvme devices multiple osds are required.
#: Can be used to split dual-actuator devices across 2 OSDs, by setting the option to 2.
self.osds_per_device = osds_per_device
#: A list of strings, containing paths which should back OSDs
self.data_directories = data_directories
#: ``filestore`` or ``bluestore``
self.objectstore = objectstore
#: ``true`` or ``false``
self.encrypted = encrypted
#: How many OSDs per DB device
self.db_slots = db_slots
#: How many OSDs per WAL device
self.wal_slots = wal_slots
#: Optional: mapping of host -> List of osd_ids that should be replaced
#: See :ref:`orchestrator-osd-replace`
self.osd_id_claims = osd_id_claims or dict()
#: The logic gate we use to match disks with filters.
#: defaults to 'AND'
self.filter_logic = filter_logic.upper()
#: If this should be treated as a 'preview' spec
self.preview_only = preview_only
#: Allocate a fraction of the data device (0,1.0]
self.data_allocate_fraction = data_allocate_fraction
self.method = method
#: Crush device class to assign to OSDs
self.crush_device_class = crush_device_class
@classmethod
def _from_json_impl(cls, json_drive_group):
# type: (dict) -> DriveGroupSpec
"""
Initialize 'Drive group' structure
:param json_drive_group: A valid json string with a Drive Group
specification
"""
args: Dict[str, Any] = json_drive_group.copy()
# legacy json (pre Octopus)
if 'host_pattern' in args and 'placement' not in args:
args['placement'] = {'host_pattern': args['host_pattern']}
del args['host_pattern']
s_id = args.get('service_id', '<unnamed>')
# spec: was not mandatory in octopus
if 'spec' in args:
args['spec'].update(cls._drive_group_spec_from_json(s_id, args['spec']))
args.update(cls._drive_group_spec_from_json(
s_id, {k: v for k, v in args.items() if k != 'spec'}))
return super(DriveGroupSpec, cls)._from_json_impl(args)
@classmethod
def _drive_group_spec_from_json(cls, name: str, json_drive_group: dict) -> dict:
for applied_filter in list(json_drive_group.keys()):
if applied_filter not in cls._supported_features:
raise DriveGroupValidationError(
name,
"Feature `{}` is not supported".format(applied_filter))
try:
def to_selection(key: str, vals: dict) -> Optional[DeviceSelection]:
try:
return DeviceSelection.from_json(vals)
except KeyError as e:
raise DriveGroupValidationError(
f'{name}.{key}',
f"Filtering for `{e.args[0]}` is not supported")
args = {k: (to_selection(k, v) if k.endswith('_devices') else v) for k, v in
json_drive_group.items()}
if not args:
raise DriveGroupValidationError(name, "Didn't find drive selections")
return args
except (KeyError, TypeError) as e:
raise DriveGroupValidationError(name, str(e))
def validate(self):
# type: () -> None
super(DriveGroupSpec, self).validate()
if self.placement.is_empty():
raise DriveGroupValidationError(self.service_id, '`placement` required')
if self.data_devices is None:
raise DriveGroupValidationError(self.service_id, "`data_devices` element is required.")
specs_names = "data_devices db_devices wal_devices journal_devices".split()
specs = dict(zip(specs_names, [getattr(self, k) for k in specs_names]))
for k, s in [ks for ks in specs.items() if ks[1] is not None]:
assert s is not None
s.validate(f'{self.service_id}.{k}')
for s in filter(None, [self.db_devices, self.wal_devices, self.journal_devices]):
if s.all:
raise DriveGroupValidationError(
self.service_id,
"`all` is only allowed for data_devices")
if self.objectstore not in ('bluestore'):
raise DriveGroupValidationError(self.service_id,
f"{self.objectstore} is not supported. Must be "
f"one of ('bluestore')")
if self.block_wal_size is not None and type(self.block_wal_size) not in [int, str]:
raise DriveGroupValidationError(
self.service_id,
'block_wal_size must be of type int or string')
if self.block_db_size is not None and type(self.block_db_size) not in [int, str]:
raise DriveGroupValidationError(
self.service_id,
'block_db_size must be of type int or string')
if self.journal_size is not None and type(self.journal_size) not in [int, str]:
raise DriveGroupValidationError(
self.service_id,
'journal_size must be of type int or string')
if self.filter_logic not in ['AND', 'OR']:
raise DriveGroupValidationError(
self.service_id,
'filter_logic must be either <AND> or <OR>')
if self.method not in [None, 'lvm', 'raw']:
raise DriveGroupValidationError(
self.service_id,
'method must be one of None, lvm, raw')
if self.method == 'raw' and self.objectstore == 'filestore':
raise DriveGroupValidationError(
self.service_id,
'method raw only supports bluestore')
if self.data_devices.paths is not None:
for device in list(self.data_devices.paths):
if not device.path:
raise DriveGroupValidationError(self.service_id, 'Device path cannot be empty') # noqa E501
yaml.add_representer(DriveGroupSpec, DriveGroupSpec.yaml_representer)
| 15,399 | 38.896373 | 123 |
py
|
null |
ceph-main/src/python-common/ceph/deployment/hostspec.py
|
from collections import OrderedDict
import errno
import re
from typing import Optional, List, Any, Dict
def assert_valid_host(name: str) -> None:
p = re.compile('^[a-zA-Z0-9-]+$')
try:
assert len(name) <= 250, 'name is too long (max 250 chars)'
for part in name.split('.'):
assert len(part) > 0, '.-delimited name component must not be empty'
assert len(part) <= 63, '.-delimited name component must not be more than 63 chars'
assert p.match(part), 'name component must include only a-z, 0-9, and -'
except AssertionError as e:
raise SpecValidationError(str(e) + f'. Got "{name}"')
class SpecValidationError(Exception):
"""
Defining an exception here is a bit problematic, cause you cannot properly catch it,
if it was raised in a different mgr module.
"""
def __init__(self,
msg: str,
errno: int = -errno.EINVAL):
super(SpecValidationError, self).__init__(msg)
self.errno = errno
class HostSpec(object):
"""
Information about hosts. Like e.g. ``kubectl get nodes``
"""
def __init__(self,
hostname: str,
addr: Optional[str] = None,
labels: Optional[List[str]] = None,
status: Optional[str] = None,
location: Optional[Dict[str, str]] = None,
):
self.service_type = 'host'
#: the bare hostname on the host. Not the FQDN.
self.hostname = hostname # type: str
#: DNS name or IP address to reach it
self.addr = addr or hostname # type: str
#: label(s), if any
self.labels = labels or [] # type: List[str]
#: human readable status
self.status = status or '' # type: str
self.location = location
def validate(self) -> None:
assert_valid_host(self.hostname)
def to_json(self) -> Dict[str, Any]:
r: Dict[str, Any] = {
'hostname': self.hostname,
'addr': self.addr,
'labels': list(OrderedDict.fromkeys((self.labels))),
'status': self.status,
}
if self.location:
r['location'] = self.location
return r
@classmethod
def from_json(cls, host_spec: dict) -> 'HostSpec':
host_spec = cls.normalize_json(host_spec)
_cls = cls(
host_spec['hostname'],
host_spec['addr'] if 'addr' in host_spec else None,
list(OrderedDict.fromkeys(
host_spec['labels'])) if 'labels' in host_spec else None,
host_spec['status'] if 'status' in host_spec else None,
host_spec.get('location'),
)
return _cls
@staticmethod
def normalize_json(host_spec: dict) -> dict:
labels = host_spec.get('labels')
if labels is not None:
if isinstance(labels, str):
host_spec['labels'] = [labels]
elif (
not isinstance(labels, list)
or any(not isinstance(v, str) for v in labels)
):
raise SpecValidationError(
f'Labels ({labels}) must be a string or list of strings'
)
loc = host_spec.get('location')
if loc is not None:
if (
not isinstance(loc, dict)
or any(not isinstance(k, str) for k in loc.keys())
or any(not isinstance(v, str) for v in loc.values())
):
raise SpecValidationError(
f'Location ({loc}) must be a dictionary of strings to strings'
)
return host_spec
def __repr__(self) -> str:
args = [self.hostname] # type: List[Any]
if self.addr is not None:
args.append(self.addr)
if self.labels:
args.append(self.labels)
if self.status:
args.append(self.status)
if self.location:
args.append(self.location)
return "HostSpec({})".format(', '.join(map(repr, args)))
def __str__(self) -> str:
if self.hostname != self.addr:
return f'{self.hostname} ({self.addr})'
return self.hostname
def __eq__(self, other: Any) -> bool:
# Let's omit `status` for the moment, as it is still the very same host.
if not isinstance(other, HostSpec):
return NotImplemented
return self.hostname == other.hostname and \
self.addr == other.addr and \
sorted(self.labels) == sorted(other.labels) and \
self.location == other.location
| 4,681 | 32.927536 | 95 |
py
|
null |
ceph-main/src/python-common/ceph/deployment/inventory.py
|
try:
from typing import List, Optional, Dict, Any, Union
except ImportError:
pass # for type checking
from ceph.utils import datetime_now, datetime_to_str, str_to_datetime
import datetime
import json
class Devices(object):
"""
A container for Device instances with reporting
"""
def __init__(self, devices):
# type: (List[Device]) -> None
# sort devices by path name so ordering is consistent
self.devices: List[Device] = sorted(devices, key=lambda d: d.path if d.path else '')
def __eq__(self, other: Any) -> bool:
if not isinstance(other, Devices):
return NotImplemented
if len(self.devices) != len(other.devices):
return False
for d1, d2 in zip(other.devices, self.devices):
if d1 != d2:
return False
return True
def to_json(self):
# type: () -> List[dict]
return [d.to_json() for d in self.devices]
@classmethod
def from_json(cls, input):
# type: (List[Dict[str, Any]]) -> Devices
return cls([Device.from_json(i) for i in input])
def copy(self):
# type: () -> Devices
return Devices(devices=list(self.devices))
class Device(object):
report_fields = [
'ceph_device',
'rejected_reasons',
'available',
'path',
'sys_api',
'created',
'lvs',
'human_readable_type',
'device_id',
'lsm_data',
'crush_device_class'
]
def __init__(self,
path, # type: str
sys_api=None, # type: Optional[Dict[str, Any]]
available=None, # type: Optional[bool]
rejected_reasons=None, # type: Optional[List[str]]
lvs=None, # type: Optional[List[Dict[str, str]]]
device_id=None, # type: Optional[str]
lsm_data=None, # type: Optional[Dict[str, Dict[str, str]]]
created=None, # type: Optional[datetime.datetime]
ceph_device=None, # type: Optional[bool]
crush_device_class=None # type: Optional[str]
):
self.path = path
self.sys_api = sys_api if sys_api is not None else {} # type: Dict[str, Any]
self.available = available
self.rejected_reasons = rejected_reasons if rejected_reasons is not None else []
self.lvs = lvs
self.device_id = device_id
self.lsm_data = lsm_data if lsm_data is not None else {} # type: Dict[str, Dict[str, str]]
self.created = created if created is not None else datetime_now()
self.ceph_device = ceph_device
self.crush_device_class = crush_device_class
def __eq__(self, other):
# type: (Any) -> bool
if not isinstance(other, Device):
return NotImplemented
diff = [k for k in self.report_fields if k != 'created' and (getattr(self, k)
!= getattr(other, k))]
return not diff
def to_json(self):
# type: () -> dict
return {
k: (getattr(self, k) if k != 'created'
or not isinstance(getattr(self, k), datetime.datetime)
else datetime_to_str(getattr(self, k)))
for k in self.report_fields
}
@classmethod
def from_json(cls, input):
# type: (Dict[str, Any]) -> Device
if not isinstance(input, dict):
raise ValueError('Device: Expected dict. Got `{}...`'.format(json.dumps(input)[:10]))
ret = cls(
**{
key: (input.get(key, None) if key != 'created'
or not input.get(key, None)
else str_to_datetime(input.get(key, None)))
for key in Device.report_fields
if key != 'human_readable_type'
}
)
if ret.rejected_reasons:
ret.rejected_reasons = sorted(ret.rejected_reasons)
return ret
@property
def human_readable_type(self):
# type: () -> str
if self.sys_api is None or 'rotational' not in self.sys_api:
return "unknown"
return 'hdd' if self.sys_api["rotational"] == "1" else 'ssd'
def __repr__(self) -> str:
device_desc: Dict[str, Union[str, List[str], List[Dict[str, str]]]] = {
'path': self.path if self.path is not None else 'unknown',
'lvs': self.lvs if self.lvs else 'None',
'available': str(self.available),
'ceph_device': str(self.ceph_device),
'crush_device_class': str(self.crush_device_class)
}
if not self.available and self.rejected_reasons:
device_desc['rejection reasons'] = self.rejected_reasons
return "Device({})".format(
', '.join('{}={}'.format(key, device_desc[key]) for key in device_desc.keys())
)
| 4,965 | 34.726619 | 99 |
py
|
null |
ceph-main/src/python-common/ceph/deployment/service_spec.py
|
import fnmatch
import os
import re
import enum
from collections import OrderedDict
from contextlib import contextmanager
from functools import wraps
from ipaddress import ip_network, ip_address
from typing import Optional, Dict, Any, List, Union, Callable, Iterable, Type, TypeVar, cast, \
NamedTuple, Mapping, Iterator
import yaml
from ceph.deployment.hostspec import HostSpec, SpecValidationError, assert_valid_host
from ceph.deployment.utils import unwrap_ipv6, valid_addr
from ceph.utils import is_hex
ServiceSpecT = TypeVar('ServiceSpecT', bound='ServiceSpec')
FuncT = TypeVar('FuncT', bound=Callable)
def handle_type_error(method: FuncT) -> FuncT:
@wraps(method)
def inner(cls: Any, *args: Any, **kwargs: Any) -> Any:
try:
return method(cls, *args, **kwargs)
except (TypeError, AttributeError) as e:
error_msg = '{}: {}'.format(cls.__name__, e)
raise SpecValidationError(error_msg)
return cast(FuncT, inner)
class HostPlacementSpec(NamedTuple):
hostname: str
network: str
name: str
def __str__(self) -> str:
res = ''
res += self.hostname
if self.network:
res += ':' + self.network
if self.name:
res += '=' + self.name
return res
@classmethod
@handle_type_error
def from_json(cls, data: Union[dict, str]) -> 'HostPlacementSpec':
if isinstance(data, str):
return cls.parse(data)
return cls(**data)
def to_json(self) -> str:
return str(self)
@classmethod
def parse(cls, host, require_network=True):
# type: (str, bool) -> HostPlacementSpec
"""
Split host into host, network, and (optional) daemon name parts. The network
part can be an IP, CIDR, or ceph addrvec like '[v2:1.2.3.4:3300,v1:1.2.3.4:6789]'.
e.g.,
"myhost"
"myhost=name"
"myhost:1.2.3.4"
"myhost:1.2.3.4=name"
"myhost:1.2.3.0/24"
"myhost:1.2.3.0/24=name"
"myhost:[v2:1.2.3.4:3000]=name"
"myhost:[v2:1.2.3.4:3000,v1:1.2.3.4:6789]=name"
"""
# Matches from start to : or = or until end of string
host_re = r'^(.*?)(:|=|$)'
# Matches from : to = or until end of string
ip_re = r':(.*?)(=|$)'
# Matches from = to end of string
name_re = r'=(.*?)$'
# assign defaults
host_spec = cls('', '', '')
match_host = re.search(host_re, host)
if match_host:
host_spec = host_spec._replace(hostname=match_host.group(1))
name_match = re.search(name_re, host)
if name_match:
host_spec = host_spec._replace(name=name_match.group(1))
ip_match = re.search(ip_re, host)
if ip_match:
host_spec = host_spec._replace(network=ip_match.group(1))
if not require_network:
return host_spec
networks = list() # type: List[str]
network = host_spec.network
# in case we have [v2:1.2.3.4:3000,v1:1.2.3.4:6478]
if ',' in network:
networks = [x for x in network.split(',')]
else:
if network != '':
networks.append(network)
for network in networks:
# only if we have versioned network configs
if network.startswith('v') or network.startswith('[v'):
# if this is ipv6 we can't just simply split on ':' so do
# a split once and rsplit once to leave us with just ipv6 addr
network = network.split(':', 1)[1]
network = network.rsplit(':', 1)[0]
try:
# if subnets are defined, also verify the validity
if '/' in network:
ip_network(network)
else:
ip_address(unwrap_ipv6(network))
except ValueError as e:
# logging?
raise e
host_spec.validate()
return host_spec
def validate(self) -> None:
assert_valid_host(self.hostname)
class PlacementSpec(object):
"""
For APIs that need to specify a host subset
"""
def __init__(self,
label=None, # type: Optional[str]
hosts=None, # type: Union[List[str],List[HostPlacementSpec], None]
count=None, # type: Optional[int]
count_per_host=None, # type: Optional[int]
host_pattern=None, # type: Optional[str]
):
# type: (...) -> None
self.label = label
self.hosts = [] # type: List[HostPlacementSpec]
if hosts:
self.set_hosts(hosts)
self.count = count # type: Optional[int]
self.count_per_host = count_per_host # type: Optional[int]
#: fnmatch patterns to select hosts. Can also be a single host.
self.host_pattern = host_pattern # type: Optional[str]
self.validate()
def is_empty(self) -> bool:
return (
self.label is None
and not self.hosts
and not self.host_pattern
and self.count is None
and self.count_per_host is None
)
def __eq__(self, other: Any) -> bool:
if isinstance(other, PlacementSpec):
return self.label == other.label \
and self.hosts == other.hosts \
and self.count == other.count \
and self.host_pattern == other.host_pattern \
and self.count_per_host == other.count_per_host
return NotImplemented
def set_hosts(self, hosts: Union[List[str], List[HostPlacementSpec]]) -> None:
# To backpopulate the .hosts attribute when using labels or count
# in the orchestrator backend.
if all([isinstance(host, HostPlacementSpec) for host in hosts]):
self.hosts = hosts # type: ignore
else:
self.hosts = [HostPlacementSpec.parse(x, require_network=False) # type: ignore
for x in hosts if x]
# deprecated
def filter_matching_hosts(self, _get_hosts_func: Callable) -> List[str]:
return self.filter_matching_hostspecs(_get_hosts_func(as_hostspec=True))
def filter_matching_hostspecs(self, hostspecs: Iterable[HostSpec]) -> List[str]:
if self.hosts:
all_hosts = [hs.hostname for hs in hostspecs]
return [h.hostname for h in self.hosts if h.hostname in all_hosts]
if self.label:
return [hs.hostname for hs in hostspecs if self.label in hs.labels]
all_hosts = [hs.hostname for hs in hostspecs]
if self.host_pattern:
return fnmatch.filter(all_hosts, self.host_pattern)
return all_hosts
def get_target_count(self, hostspecs: Iterable[HostSpec]) -> int:
if self.count:
return self.count
return len(self.filter_matching_hostspecs(hostspecs)) * (self.count_per_host or 1)
def pretty_str(self) -> str:
"""
>>> #doctest: +SKIP
... ps = PlacementSpec(...) # For all placement specs:
... PlacementSpec.from_string(ps.pretty_str()) == ps
"""
kv = []
if self.hosts:
kv.append(';'.join([str(h) for h in self.hosts]))
if self.count:
kv.append('count:%d' % self.count)
if self.count_per_host:
kv.append('count-per-host:%d' % self.count_per_host)
if self.label:
kv.append('label:%s' % self.label)
if self.host_pattern:
kv.append(self.host_pattern)
return ';'.join(kv)
def __repr__(self) -> str:
kv = []
if self.count:
kv.append('count=%d' % self.count)
if self.count_per_host:
kv.append('count_per_host=%d' % self.count_per_host)
if self.label:
kv.append('label=%s' % repr(self.label))
if self.hosts:
kv.append('hosts={!r}'.format(self.hosts))
if self.host_pattern:
kv.append('host_pattern={!r}'.format(self.host_pattern))
return "PlacementSpec(%s)" % ', '.join(kv)
@classmethod
@handle_type_error
def from_json(cls, data: dict) -> 'PlacementSpec':
c = data.copy()
hosts = c.get('hosts', [])
if hosts:
c['hosts'] = []
for host in hosts:
c['hosts'].append(HostPlacementSpec.from_json(host))
_cls = cls(**c)
_cls.validate()
return _cls
def to_json(self) -> dict:
r: Dict[str, Any] = {}
if self.label:
r['label'] = self.label
if self.hosts:
r['hosts'] = [host.to_json() for host in self.hosts]
if self.count:
r['count'] = self.count
if self.count_per_host:
r['count_per_host'] = self.count_per_host
if self.host_pattern:
r['host_pattern'] = self.host_pattern
return r
def validate(self) -> None:
if self.hosts and self.label:
# TODO: a less generic Exception
raise SpecValidationError('Host and label are mutually exclusive')
if self.count is not None:
try:
intval = int(self.count)
except (ValueError, TypeError):
raise SpecValidationError("num/count must be a numeric value")
if self.count != intval:
raise SpecValidationError("num/count must be an integer value")
if self.count < 1:
raise SpecValidationError("num/count must be >= 1")
if self.count_per_host is not None:
try:
intval = int(self.count_per_host)
except (ValueError, TypeError):
raise SpecValidationError("count-per-host must be a numeric value")
if self.count_per_host != intval:
raise SpecValidationError("count-per-host must be an integer value")
if self.count_per_host < 1:
raise SpecValidationError("count-per-host must be >= 1")
if self.count_per_host is not None and not (
self.label
or self.hosts
or self.host_pattern
):
raise SpecValidationError(
"count-per-host must be combined with label or hosts or host_pattern"
)
if self.count is not None and self.count_per_host is not None:
raise SpecValidationError("cannot combine count and count-per-host")
if (
self.count_per_host is not None
and self.hosts
and any([hs.network or hs.name for hs in self.hosts])
):
raise SpecValidationError(
"count-per-host cannot be combined explicit placement with names or networks"
)
if self.host_pattern:
if not isinstance(self.host_pattern, str):
raise SpecValidationError('host_pattern must be of type string')
if self.hosts:
raise SpecValidationError('cannot combine host patterns and hosts')
for h in self.hosts:
h.validate()
@classmethod
def from_string(cls, arg):
# type: (Optional[str]) -> PlacementSpec
"""
A single integer is parsed as a count:
>>> PlacementSpec.from_string('3')
PlacementSpec(count=3)
A list of names is parsed as host specifications:
>>> PlacementSpec.from_string('host1 host2')
PlacementSpec(hosts=[HostPlacementSpec(hostname='host1', network='', name=''), HostPlacemen\
tSpec(hostname='host2', network='', name='')])
You can also prefix the hosts with a count as follows:
>>> PlacementSpec.from_string('2 host1 host2')
PlacementSpec(count=2, hosts=[HostPlacementSpec(hostname='host1', network='', name=''), Hos\
tPlacementSpec(hostname='host2', network='', name='')])
You can specify labels using `label:<label>`
>>> PlacementSpec.from_string('label:mon')
PlacementSpec(label='mon')
Labels also support a count:
>>> PlacementSpec.from_string('3 label:mon')
PlacementSpec(count=3, label='mon')
fnmatch is also supported:
>>> PlacementSpec.from_string('data[1-3]')
PlacementSpec(host_pattern='data[1-3]')
>>> PlacementSpec.from_string(None)
PlacementSpec()
"""
if arg is None or not arg:
strings = []
elif isinstance(arg, str):
if ' ' in arg:
strings = arg.split(' ')
elif ';' in arg:
strings = arg.split(';')
elif ',' in arg and '[' not in arg:
# FIXME: this isn't quite right. we want to avoid breaking
# a list of mons with addrvecs... so we're basically allowing
# , most of the time, except when addrvecs are used. maybe
# ok?
strings = arg.split(',')
else:
strings = [arg]
else:
raise SpecValidationError('invalid placement %s' % arg)
count = None
count_per_host = None
if strings:
try:
count = int(strings[0])
strings = strings[1:]
except ValueError:
pass
for s in strings:
if s.startswith('count:'):
try:
count = int(s[len('count:'):])
strings.remove(s)
break
except ValueError:
pass
for s in strings:
if s.startswith('count-per-host:'):
try:
count_per_host = int(s[len('count-per-host:'):])
strings.remove(s)
break
except ValueError:
pass
advanced_hostspecs = [h for h in strings if
(':' in h or '=' in h or not any(c in '[]?*:=' for c in h)) and
'label:' not in h]
for a_h in advanced_hostspecs:
strings.remove(a_h)
labels = [x for x in strings if 'label:' in x]
if len(labels) > 1:
raise SpecValidationError('more than one label provided: {}'.format(labels))
for l in labels:
strings.remove(l)
label = labels[0][6:] if labels else None
host_patterns = strings
if len(host_patterns) > 1:
raise SpecValidationError(
'more than one host pattern provided: {}'.format(host_patterns))
ps = PlacementSpec(count=count,
count_per_host=count_per_host,
hosts=advanced_hostspecs,
label=label,
host_pattern=host_patterns[0] if host_patterns else None)
return ps
_service_spec_from_json_validate = True
class CustomConfig:
"""
Class to specify custom config files to be mounted in daemon's container
"""
_fields = ['content', 'mount_path']
def __init__(self, content: str, mount_path: str) -> None:
self.content: str = content
self.mount_path: str = mount_path
self.validate()
def to_json(self) -> Dict[str, Any]:
return {
'content': self.content,
'mount_path': self.mount_path,
}
@classmethod
def from_json(cls, data: Dict[str, Any]) -> "CustomConfig":
for k in cls._fields:
if k not in data:
raise SpecValidationError(f'CustomConfig must have "{k}" field')
for k in data.keys():
if k not in cls._fields:
raise SpecValidationError(f'CustomConfig got unknown field "{k}"')
return cls(**data)
@property
def filename(self) -> str:
return os.path.basename(self.mount_path)
def __eq__(self, other: Any) -> bool:
if isinstance(other, CustomConfig):
return (
self.content == other.content
and self.mount_path == other.mount_path
)
return NotImplemented
def __repr__(self) -> str:
return f'CustomConfig({self.mount_path})'
def validate(self) -> None:
if not isinstance(self.content, str):
raise SpecValidationError(
f'CustomConfig content must be a string. Got {type(self.content)}')
if not isinstance(self.mount_path, str):
raise SpecValidationError(
f'CustomConfig content must be a string. Got {type(self.mount_path)}')
@contextmanager
def service_spec_allow_invalid_from_json() -> Iterator[None]:
"""
I know this is evil, but unfortunately `ceph orch ls`
may return invalid OSD specs for OSDs not associated to
and specs. If you have a better idea, please!
"""
global _service_spec_from_json_validate
_service_spec_from_json_validate = False
yield
_service_spec_from_json_validate = True
class ArgumentSpec:
"""The ArgumentSpec type represents an argument that can be
passed to an underyling subsystem, like a container engine or
another command line tool.
The ArgumentSpec aims to be backwards compatible with the previous
form of argument, a single string. The string was always assumed
to be indentended to be split on spaces. For example:
`--cpus 8` becomes `["--cpus", "8"]`. This type is converted from
either a string or an json/yaml object. In the object form you
can choose if the string part should be split so an argument like
`--migrate-from=//192.168.5.22/My Documents` can be expressed.
"""
_fields = ['argument', 'split']
class OriginalType(enum.Enum):
OBJECT = 0
STRING = 1
def __init__(
self,
argument: str,
split: bool = False,
*,
origin: OriginalType = OriginalType.OBJECT,
) -> None:
self.argument = argument
self.split = bool(split)
# origin helps with round-tripping between inputs that
# are simple strings or objects (dicts)
self._origin = origin
self.validate()
def to_json(self) -> Union[str, Dict[str, Any]]:
"""Return a json-safe represenation of the ArgumentSpec."""
if self._origin == self.OriginalType.STRING:
return self.argument
return {
'argument': self.argument,
'split': self.split,
}
def to_args(self) -> List[str]:
"""Convert this ArgumentSpec into a list of arguments suitable for
adding to an argv-style command line.
"""
if not self.split:
return [self.argument]
return [part for part in self.argument.split(" ") if part]
def __eq__(self, other: Any) -> bool:
if isinstance(other, ArgumentSpec):
return (
self.argument == other.argument
and self.split == other.split
)
if isinstance(other, object):
# This is a workaround for silly ceph mgr object/type identity
# mismatches due to multiple python interpreters in use.
try:
argument = getattr(other, 'argument')
split = getattr(other, 'split')
return (self.argument == argument and self.split == split)
except AttributeError:
pass
return NotImplemented
def __repr__(self) -> str:
return f'ArgumentSpec({self.argument!r}, {self.split!r})'
def validate(self) -> None:
if not isinstance(self.argument, str):
raise SpecValidationError(
f'ArgumentSpec argument must be a string. Got {type(self.argument)}')
if not isinstance(self.split, bool):
raise SpecValidationError(
f'ArgumentSpec split must be a boolean. Got {type(self.split)}')
@classmethod
def from_json(cls, data: Union[str, Dict[str, Any]]) -> "ArgumentSpec":
"""Convert a json-object (dict) to an ArgumentSpec."""
if isinstance(data, str):
return cls(data, split=True, origin=cls.OriginalType.STRING)
if 'argument' not in data:
raise SpecValidationError(f'ArgumentSpec must have an "argument" field')
for k in data.keys():
if k not in cls._fields:
raise SpecValidationError(f'ArgumentSpec got an unknown field {k!r}')
return cls(**data)
@staticmethod
def map_json(
values: Optional["ArgumentList"]
) -> Optional[List[Union[str, Dict[str, Any]]]]:
"""Given a list of ArgumentSpec objects return a json-safe
representation.of them."""
if values is None:
return None
return [v.to_json() for v in values]
@classmethod
def from_general_args(cls, data: "GeneralArgList") -> "ArgumentList":
"""Convert a list of strs, dicts, or existing ArgumentSpec objects
to a list of only ArgumentSpec objects.
"""
out: ArgumentList = []
for item in data:
if isinstance(item, (str, dict)):
out.append(cls.from_json(item))
elif isinstance(item, cls):
out.append(item)
elif hasattr(item, 'to_json'):
# This is a workaround for silly ceph mgr object/type identity
# mismatches due to multiple python interpreters in use.
# It should be safe because we already have to be able to
# round-trip between json/yaml.
out.append(cls.from_json(item.to_json()))
else:
raise SpecValidationError(f"Unknown type for argument: {type(item)}")
return out
ArgumentList = List[ArgumentSpec]
GeneralArgList = List[Union[str, Dict[str, Any], "ArgumentSpec"]]
class ServiceSpec(object):
"""
Details of service creation.
Request to the orchestrator for a cluster of daemons
such as MDS, RGW, iscsi gateway, MONs, MGRs, Prometheus
This structure is supposed to be enough information to
start the services.
"""
KNOWN_SERVICE_TYPES = 'alertmanager crash grafana iscsi loki promtail mds mgr mon nfs ' \
'node-exporter osd prometheus rbd-mirror rgw agent ceph-exporter ' \
'container ingress cephfs-mirror snmp-gateway jaeger-tracing ' \
'elasticsearch jaeger-agent jaeger-collector jaeger-query'.split()
REQUIRES_SERVICE_ID = 'iscsi mds nfs rgw container ingress '.split()
MANAGED_CONFIG_OPTIONS = [
'mds_join_fs',
]
@classmethod
def _cls(cls: Type[ServiceSpecT], service_type: str) -> Type[ServiceSpecT]:
from ceph.deployment.drive_group import DriveGroupSpec
ret = {
'mon': MONSpec,
'rgw': RGWSpec,
'nfs': NFSServiceSpec,
'osd': DriveGroupSpec,
'mds': MDSSpec,
'iscsi': IscsiServiceSpec,
'alertmanager': AlertManagerSpec,
'ingress': IngressSpec,
'container': CustomContainerSpec,
'grafana': GrafanaSpec,
'node-exporter': MonitoringSpec,
'ceph-exporter': CephExporterSpec,
'prometheus': PrometheusSpec,
'loki': MonitoringSpec,
'promtail': MonitoringSpec,
'snmp-gateway': SNMPGatewaySpec,
'elasticsearch': TracingSpec,
'jaeger-agent': TracingSpec,
'jaeger-collector': TracingSpec,
'jaeger-query': TracingSpec,
'jaeger-tracing': TracingSpec,
}.get(service_type, cls)
if ret == ServiceSpec and not service_type:
raise SpecValidationError('Spec needs a "service_type" key.')
return ret
def __new__(cls: Type[ServiceSpecT], *args: Any, **kwargs: Any) -> ServiceSpecT:
"""
Some Python foo to make sure, we don't have an object
like `ServiceSpec('rgw')` of type `ServiceSpec`. Now we have:
>>> type(ServiceSpec('rgw')) == type(RGWSpec('rgw'))
True
"""
if cls != ServiceSpec:
return object.__new__(cls)
service_type = kwargs.get('service_type', args[0] if args else None)
sub_cls: Any = cls._cls(service_type)
return object.__new__(sub_cls)
def __init__(self,
service_type: str,
service_id: Optional[str] = None,
placement: Optional[PlacementSpec] = None,
count: Optional[int] = None,
config: Optional[Dict[str, str]] = None,
unmanaged: bool = False,
preview_only: bool = False,
networks: Optional[List[str]] = None,
extra_container_args: Optional[GeneralArgList] = None,
extra_entrypoint_args: Optional[GeneralArgList] = None,
custom_configs: Optional[List[CustomConfig]] = None,
):
#: See :ref:`orchestrator-cli-placement-spec`.
self.placement = PlacementSpec() if placement is None else placement # type: PlacementSpec
assert service_type in ServiceSpec.KNOWN_SERVICE_TYPES, service_type
#: The type of the service. Needs to be either a Ceph
#: service (``mon``, ``crash``, ``mds``, ``mgr``, ``osd`` or
#: ``rbd-mirror``), a gateway (``nfs`` or ``rgw``), part of the
#: monitoring stack (``alertmanager``, ``grafana``, ``node-exporter`` or
#: ``prometheus``) or (``container``) for custom containers.
self.service_type = service_type
#: The name of the service. Required for ``iscsi``, ``mds``, ``nfs``, ``osd``, ``rgw``,
#: ``container``, ``ingress``
self.service_id = None
if self.service_type in self.REQUIRES_SERVICE_ID or self.service_type == 'osd':
self.service_id = service_id
#: If set to ``true``, the orchestrator will not deploy nor remove
#: any daemon associated with this service. Placement and all other properties
#: will be ignored. This is useful, if you do not want this service to be
#: managed temporarily. For cephadm, See :ref:`cephadm-spec-unmanaged`
self.unmanaged = unmanaged
self.preview_only = preview_only
#: A list of network identities instructing the daemons to only bind
#: on the particular networks in that list. In case the cluster is distributed
#: across multiple networks, you can add multiple networks. See
#: :ref:`cephadm-monitoring-networks-ports`,
#: :ref:`cephadm-rgw-networks` and :ref:`cephadm-mgr-networks`.
self.networks: List[str] = networks or []
self.config: Optional[Dict[str, str]] = None
if config:
self.config = {k.replace(' ', '_'): v for k, v in config.items()}
self.extra_container_args: Optional[ArgumentList] = None
self.extra_entrypoint_args: Optional[ArgumentList] = None
if extra_container_args:
self.extra_container_args = ArgumentSpec.from_general_args(
extra_container_args)
if extra_entrypoint_args:
self.extra_entrypoint_args = ArgumentSpec.from_general_args(
extra_entrypoint_args)
self.custom_configs: Optional[List[CustomConfig]] = custom_configs
def __setattr__(self, name: str, value: Any) -> None:
if value is not None and name in ('extra_container_args', 'extra_entrypoint_args'):
for v in value:
tname = str(type(v))
if 'ArgumentSpec' not in tname:
raise TypeError(
f"{name} is not all ArgumentSpec values:"
f" {v!r}(is {type(v)} in {value!r}")
super().__setattr__(name, value)
@classmethod
@handle_type_error
def from_json(cls: Type[ServiceSpecT], json_spec: Dict) -> ServiceSpecT:
"""
Initialize 'ServiceSpec' object data from a json structure
There are two valid styles for service specs:
the "old" style:
.. code:: yaml
service_type: nfs
service_id: foo
pool: mypool
namespace: myns
and the "new" style:
.. code:: yaml
service_type: nfs
service_id: foo
config:
some_option: the_value
networks: [10.10.0.0/16]
spec:
pool: mypool
namespace: myns
In https://tracker.ceph.com/issues/45321 we decided that we'd like to
prefer the new style as it is more readable and provides a better
understanding of what fields are special for a give service type.
Note, we'll need to stay compatible with both versions for the
the next two major releases (octopus, pacific).
:param json_spec: A valid dict with ServiceSpec
:meta private:
"""
if not isinstance(json_spec, dict):
raise SpecValidationError(
f'Service Spec is not an (JSON or YAML) object. got "{str(json_spec)}"')
json_spec = cls.normalize_json(json_spec)
c = json_spec.copy()
# kludge to make `from_json` compatible to `Orchestrator.describe_service`
# Open question: Remove `service_id` form to_json?
if c.get('service_name', ''):
service_type_id = c['service_name'].split('.', 1)
if not c.get('service_type', ''):
c['service_type'] = service_type_id[0]
if not c.get('service_id', '') and len(service_type_id) > 1:
c['service_id'] = service_type_id[1]
del c['service_name']
service_type = c.get('service_type', '')
_cls = cls._cls(service_type)
if 'status' in c:
del c['status'] # kludge to make us compatible to `ServiceDescription.to_json()`
return _cls._from_json_impl(c) # type: ignore
@staticmethod
def normalize_json(json_spec: dict) -> dict:
networks = json_spec.get('networks')
if networks is None:
return json_spec
if isinstance(networks, list):
return json_spec
if not isinstance(networks, str):
raise SpecValidationError(f'Networks ({networks}) must be a string or list of strings')
json_spec['networks'] = [networks]
return json_spec
@classmethod
def _from_json_impl(cls: Type[ServiceSpecT], json_spec: dict) -> ServiceSpecT:
args = {} # type: Dict[str, Any]
for k, v in json_spec.items():
if k == 'placement':
v = PlacementSpec.from_json(v)
if k == 'custom_configs':
v = [CustomConfig.from_json(c) for c in v]
if k == 'spec':
args.update(v)
continue
args.update({k: v})
_cls = cls(**args)
if _service_spec_from_json_validate:
_cls.validate()
return _cls
def service_name(self) -> str:
n = self.service_type
if self.service_id:
n += '.' + self.service_id
return n
def get_port_start(self) -> List[int]:
# If defined, we will allocate and number ports starting at this
# point.
return []
def get_virtual_ip(self) -> Optional[str]:
return None
def to_json(self):
# type: () -> OrderedDict[str, Any]
ret: OrderedDict[str, Any] = OrderedDict()
ret['service_type'] = self.service_type
if self.service_id:
ret['service_id'] = self.service_id
ret['service_name'] = self.service_name()
if self.placement.to_json():
ret['placement'] = self.placement.to_json()
if self.unmanaged:
ret['unmanaged'] = self.unmanaged
if self.networks:
ret['networks'] = self.networks
if self.extra_container_args:
ret['extra_container_args'] = ArgumentSpec.map_json(
self.extra_container_args
)
if self.extra_entrypoint_args:
ret['extra_entrypoint_args'] = ArgumentSpec.map_json(
self.extra_entrypoint_args
)
if self.custom_configs:
ret['custom_configs'] = [c.to_json() for c in self.custom_configs]
c = {}
for key, val in sorted(self.__dict__.items(), key=lambda tpl: tpl[0]):
if key in ret:
continue
if hasattr(val, 'to_json'):
val = val.to_json()
if val:
c[key] = val
if c:
ret['spec'] = c
return ret
def validate(self) -> None:
if not self.service_type:
raise SpecValidationError('Cannot add Service: type required')
if self.service_type != 'osd':
if self.service_type in self.REQUIRES_SERVICE_ID and not self.service_id:
raise SpecValidationError('Cannot add Service: id required')
if self.service_type not in self.REQUIRES_SERVICE_ID and self.service_id:
raise SpecValidationError(
f'Service of type \'{self.service_type}\' should not contain a service id')
if self.service_id:
if not re.match('^[a-zA-Z0-9_.-]+$', str(self.service_id)):
raise SpecValidationError('Service id contains invalid characters, '
'only [a-zA-Z0-9_.-] allowed')
if self.placement is not None:
self.placement.validate()
if self.config:
for k, v in self.config.items():
if k in self.MANAGED_CONFIG_OPTIONS:
raise SpecValidationError(
f'Cannot set config option {k} in spec: it is managed by cephadm'
)
for network in self.networks or []:
try:
ip_network(network)
except ValueError as e:
raise SpecValidationError(
f'Cannot parse network {network}: {e}'
)
def __repr__(self) -> str:
y = yaml.dump(cast(dict, self), default_flow_style=False)
return f"{self.__class__.__name__}.from_json(yaml.safe_load('''{y}'''))"
def __eq__(self, other: Any) -> bool:
return (self.__class__ == other.__class__
and
self.__dict__ == other.__dict__)
def one_line_str(self) -> str:
return '<{} for service_name={}>'.format(self.__class__.__name__, self.service_name())
@staticmethod
def yaml_representer(dumper: 'yaml.SafeDumper', data: 'ServiceSpec') -> Any:
return dumper.represent_dict(cast(Mapping, data.to_json().items()))
yaml.add_representer(ServiceSpec, ServiceSpec.yaml_representer)
class NFSServiceSpec(ServiceSpec):
def __init__(self,
service_type: str = 'nfs',
service_id: Optional[str] = None,
placement: Optional[PlacementSpec] = None,
unmanaged: bool = False,
preview_only: bool = False,
config: Optional[Dict[str, str]] = None,
networks: Optional[List[str]] = None,
port: Optional[int] = None,
virtual_ip: Optional[str] = None,
enable_haproxy_protocol: bool = False,
extra_container_args: Optional[GeneralArgList] = None,
extra_entrypoint_args: Optional[GeneralArgList] = None,
custom_configs: Optional[List[CustomConfig]] = None,
):
assert service_type == 'nfs'
super(NFSServiceSpec, self).__init__(
'nfs', service_id=service_id,
placement=placement, unmanaged=unmanaged, preview_only=preview_only,
config=config, networks=networks, extra_container_args=extra_container_args,
extra_entrypoint_args=extra_entrypoint_args, custom_configs=custom_configs)
self.port = port
self.virtual_ip = virtual_ip
self.enable_haproxy_protocol = enable_haproxy_protocol
def get_port_start(self) -> List[int]:
if self.port:
return [self.port]
return []
def rados_config_name(self):
# type: () -> str
return 'conf-' + self.service_name()
yaml.add_representer(NFSServiceSpec, ServiceSpec.yaml_representer)
class RGWSpec(ServiceSpec):
"""
Settings to configure a (multisite) Ceph RGW
.. code-block:: yaml
service_type: rgw
service_id: myrealm.myzone
spec:
rgw_realm: myrealm
rgw_zonegroup: myzonegroup
rgw_zone: myzone
ssl: true
rgw_frontend_port: 1234
rgw_frontend_type: beast
rgw_frontend_ssl_certificate: ...
See also: :ref:`orchestrator-cli-service-spec`
"""
MANAGED_CONFIG_OPTIONS = ServiceSpec.MANAGED_CONFIG_OPTIONS + [
'rgw_zone',
'rgw_realm',
'rgw_zonegroup',
'rgw_frontends',
]
def __init__(self,
service_type: str = 'rgw',
service_id: Optional[str] = None,
placement: Optional[PlacementSpec] = None,
rgw_realm: Optional[str] = None,
rgw_zonegroup: Optional[str] = None,
rgw_zone: Optional[str] = None,
rgw_frontend_port: Optional[int] = None,
rgw_frontend_ssl_certificate: Optional[List[str]] = None,
rgw_frontend_type: Optional[str] = None,
rgw_frontend_extra_args: Optional[List[str]] = None,
unmanaged: bool = False,
ssl: bool = False,
preview_only: bool = False,
config: Optional[Dict[str, str]] = None,
networks: Optional[List[str]] = None,
subcluster: Optional[str] = None, # legacy, only for from_json on upgrade
extra_container_args: Optional[GeneralArgList] = None,
extra_entrypoint_args: Optional[GeneralArgList] = None,
custom_configs: Optional[List[CustomConfig]] = None,
rgw_realm_token: Optional[str] = None,
update_endpoints: Optional[bool] = False,
zone_endpoints: Optional[str] = None # commad separated endpoints list
):
assert service_type == 'rgw', service_type
# for backward compatibility with octopus spec files,
if not service_id and (rgw_realm and rgw_zone):
service_id = rgw_realm + '.' + rgw_zone
super(RGWSpec, self).__init__(
'rgw', service_id=service_id,
placement=placement, unmanaged=unmanaged,
preview_only=preview_only, config=config, networks=networks,
extra_container_args=extra_container_args, extra_entrypoint_args=extra_entrypoint_args,
custom_configs=custom_configs)
#: The RGW realm associated with this service. Needs to be manually created
#: if the spec is being applied directly to cephdam. In case of rgw module
#: the realm is created automatically.
self.rgw_realm: Optional[str] = rgw_realm
#: The RGW zonegroup associated with this service. Needs to be manually created
#: if the spec is being applied directly to cephdam. In case of rgw module
#: the zonegroup is created automatically.
self.rgw_zonegroup: Optional[str] = rgw_zonegroup
#: The RGW zone associated with this service. Needs to be manually created
#: if the spec is being applied directly to cephdam. In case of rgw module
#: the zone is created automatically.
self.rgw_zone: Optional[str] = rgw_zone
#: Port of the RGW daemons
self.rgw_frontend_port: Optional[int] = rgw_frontend_port
#: List of SSL certificates
self.rgw_frontend_ssl_certificate: Optional[List[str]] = rgw_frontend_ssl_certificate
#: civetweb or beast (default: beast). See :ref:`rgw_frontends`
self.rgw_frontend_type: Optional[str] = rgw_frontend_type
#: List of extra arguments for rgw_frontend in the form opt=value. See :ref:`rgw_frontends`
self.rgw_frontend_extra_args: Optional[List[str]] = rgw_frontend_extra_args
#: enable SSL
self.ssl = ssl
self.rgw_realm_token = rgw_realm_token
self.update_endpoints = update_endpoints
self.zone_endpoints = zone_endpoints
def get_port_start(self) -> List[int]:
return [self.get_port()]
def get_port(self) -> int:
if self.rgw_frontend_port:
return self.rgw_frontend_port
if self.ssl:
return 443
else:
return 80
def validate(self) -> None:
super(RGWSpec, self).validate()
if self.rgw_realm and not self.rgw_zone:
raise SpecValidationError(
'Cannot add RGW: Realm specified but no zone specified')
if self.rgw_zone and not self.rgw_realm:
raise SpecValidationError('Cannot add RGW: Zone specified but no realm specified')
if self.rgw_frontend_type is not None:
if self.rgw_frontend_type not in ['beast', 'civetweb']:
raise SpecValidationError(
'Invalid rgw_frontend_type value. Valid values are: beast, civetweb.\n'
'Additional rgw type parameters can be passed using rgw_frontend_extra_args.'
)
yaml.add_representer(RGWSpec, ServiceSpec.yaml_representer)
class IscsiServiceSpec(ServiceSpec):
def __init__(self,
service_type: str = 'iscsi',
service_id: Optional[str] = None,
pool: Optional[str] = None,
trusted_ip_list: Optional[str] = None,
api_port: Optional[int] = 5000,
api_user: Optional[str] = 'admin',
api_password: Optional[str] = 'admin',
api_secure: Optional[bool] = None,
ssl_cert: Optional[str] = None,
ssl_key: Optional[str] = None,
placement: Optional[PlacementSpec] = None,
unmanaged: bool = False,
preview_only: bool = False,
config: Optional[Dict[str, str]] = None,
networks: Optional[List[str]] = None,
extra_container_args: Optional[GeneralArgList] = None,
extra_entrypoint_args: Optional[GeneralArgList] = None,
custom_configs: Optional[List[CustomConfig]] = None,
):
assert service_type == 'iscsi'
super(IscsiServiceSpec, self).__init__('iscsi', service_id=service_id,
placement=placement, unmanaged=unmanaged,
preview_only=preview_only,
config=config, networks=networks,
extra_container_args=extra_container_args,
extra_entrypoint_args=extra_entrypoint_args,
custom_configs=custom_configs)
#: RADOS pool where ceph-iscsi config data is stored.
self.pool = pool
#: list of trusted IP addresses
self.trusted_ip_list = trusted_ip_list
#: ``api_port`` as defined in the ``iscsi-gateway.cfg``
self.api_port = api_port
#: ``api_user`` as defined in the ``iscsi-gateway.cfg``
self.api_user = api_user
#: ``api_password`` as defined in the ``iscsi-gateway.cfg``
self.api_password = api_password
#: ``api_secure`` as defined in the ``iscsi-gateway.cfg``
self.api_secure = api_secure
#: SSL certificate
self.ssl_cert = ssl_cert
#: SSL private key
self.ssl_key = ssl_key
if not self.api_secure and self.ssl_cert and self.ssl_key:
self.api_secure = True
def get_port_start(self) -> List[int]:
return [self.api_port or 5000]
def validate(self) -> None:
super(IscsiServiceSpec, self).validate()
if not self.pool:
raise SpecValidationError(
'Cannot add ISCSI: No Pool specified')
# Do not need to check for api_user and api_password as they
# now default to 'admin' when setting up the gateway url. Older
# iSCSI specs from before this change should be fine as they will
# have been required to have an api_user and api_password set and
# will be unaffected by the new default value.
yaml.add_representer(IscsiServiceSpec, ServiceSpec.yaml_representer)
class IngressSpec(ServiceSpec):
def __init__(self,
service_type: str = 'ingress',
service_id: Optional[str] = None,
config: Optional[Dict[str, str]] = None,
networks: Optional[List[str]] = None,
placement: Optional[PlacementSpec] = None,
backend_service: Optional[str] = None,
frontend_port: Optional[int] = None,
ssl_cert: Optional[str] = None,
ssl_key: Optional[str] = None,
ssl_dh_param: Optional[str] = None,
ssl_ciphers: Optional[List[str]] = None,
ssl_options: Optional[List[str]] = None,
monitor_port: Optional[int] = None,
monitor_user: Optional[str] = None,
monitor_password: Optional[str] = None,
enable_stats: Optional[bool] = None,
keepalived_password: Optional[str] = None,
virtual_ip: Optional[str] = None,
virtual_ips_list: Optional[List[str]] = None,
virtual_interface_networks: Optional[List[str]] = [],
use_keepalived_multicast: Optional[bool] = False,
vrrp_interface_network: Optional[str] = None,
first_virtual_router_id: Optional[int] = 50,
unmanaged: bool = False,
ssl: bool = False,
keepalive_only: bool = False,
enable_haproxy_protocol: bool = False,
extra_container_args: Optional[GeneralArgList] = None,
extra_entrypoint_args: Optional[GeneralArgList] = None,
custom_configs: Optional[List[CustomConfig]] = None,
):
assert service_type == 'ingress'
super(IngressSpec, self).__init__(
'ingress', service_id=service_id,
placement=placement, config=config,
networks=networks,
extra_container_args=extra_container_args,
extra_entrypoint_args=extra_entrypoint_args,
custom_configs=custom_configs
)
self.backend_service = backend_service
self.frontend_port = frontend_port
self.ssl_cert = ssl_cert
self.ssl_key = ssl_key
self.ssl_dh_param = ssl_dh_param
self.ssl_ciphers = ssl_ciphers
self.ssl_options = ssl_options
self.monitor_port = monitor_port
self.monitor_user = monitor_user
self.monitor_password = monitor_password
self.keepalived_password = keepalived_password
self.virtual_ip = virtual_ip
self.virtual_ips_list = virtual_ips_list
self.virtual_interface_networks = virtual_interface_networks or []
self.use_keepalived_multicast = use_keepalived_multicast
self.vrrp_interface_network = vrrp_interface_network
self.first_virtual_router_id = first_virtual_router_id
self.unmanaged = unmanaged
self.ssl = ssl
self.keepalive_only = keepalive_only
self.enable_haproxy_protocol = enable_haproxy_protocol
def get_port_start(self) -> List[int]:
ports = []
if self.frontend_port is not None:
ports.append(cast(int, self.frontend_port))
if self.monitor_port is not None:
ports.append(cast(int, self.monitor_port))
return ports
def get_virtual_ip(self) -> Optional[str]:
return self.virtual_ip
def validate(self) -> None:
super(IngressSpec, self).validate()
if not self.backend_service:
raise SpecValidationError(
'Cannot add ingress: No backend_service specified')
if not self.keepalive_only and not self.frontend_port:
raise SpecValidationError(
'Cannot add ingress: No frontend_port specified')
if not self.monitor_port:
raise SpecValidationError(
'Cannot add ingress: No monitor_port specified')
if not self.virtual_ip and not self.virtual_ips_list:
raise SpecValidationError(
'Cannot add ingress: No virtual_ip provided')
if self.virtual_ip is not None and self.virtual_ips_list is not None:
raise SpecValidationError(
'Cannot add ingress: Single and multiple virtual IPs specified')
yaml.add_representer(IngressSpec, ServiceSpec.yaml_representer)
class CustomContainerSpec(ServiceSpec):
def __init__(self,
service_type: str = 'container',
service_id: Optional[str] = None,
config: Optional[Dict[str, str]] = None,
networks: Optional[List[str]] = None,
placement: Optional[PlacementSpec] = None,
unmanaged: bool = False,
preview_only: bool = False,
image: Optional[str] = None,
entrypoint: Optional[str] = None,
uid: Optional[int] = None,
gid: Optional[int] = None,
volume_mounts: Optional[Dict[str, str]] = {},
# args are for the container runtime, not entrypoint
args: Optional[GeneralArgList] = [],
envs: Optional[List[str]] = [],
privileged: Optional[bool] = False,
bind_mounts: Optional[List[List[str]]] = None,
ports: Optional[List[int]] = [],
dirs: Optional[List[str]] = [],
files: Optional[Dict[str, Any]] = {},
extra_container_args: Optional[GeneralArgList] = None,
extra_entrypoint_args: Optional[GeneralArgList] = None,
custom_configs: Optional[List[CustomConfig]] = None,
):
assert service_type == 'container'
assert service_id is not None
assert image is not None
super(CustomContainerSpec, self).__init__(
service_type, service_id,
placement=placement, unmanaged=unmanaged,
preview_only=preview_only, config=config,
networks=networks, extra_container_args=extra_container_args,
extra_entrypoint_args=extra_entrypoint_args,
custom_configs=custom_configs)
self.image = image
self.entrypoint = entrypoint
self.uid = uid
self.gid = gid
self.volume_mounts = volume_mounts
self.args = args
self.envs = envs
self.privileged = privileged
self.bind_mounts = bind_mounts
self.ports = ports
self.dirs = dirs
self.files = files
def config_json(self) -> Dict[str, Any]:
"""
Helper function to get the value of the `--config-json` cephadm
command line option. It will contain all specification properties
that haven't a `None` value. Such properties will get default
values in cephadm.
:return: Returns a dictionary containing all specification
properties.
"""
config_json = {}
for prop in ['image', 'entrypoint', 'uid', 'gid', 'args',
'envs', 'volume_mounts', 'privileged',
'bind_mounts', 'ports', 'dirs', 'files']:
value = getattr(self, prop)
if value is not None:
config_json[prop] = value
return config_json
def validate(self) -> None:
super(CustomContainerSpec, self).validate()
if self.args and self.extra_container_args:
raise SpecValidationError(
'"args" and "extra_container_args" are mutually exclusive '
'(and both serve the same purpose)')
if self.files and self.custom_configs:
raise SpecValidationError(
'"files" and "custom_configs" are mutually exclusive '
'(and both serve the same purpose)')
yaml.add_representer(CustomContainerSpec, ServiceSpec.yaml_representer)
class MonitoringSpec(ServiceSpec):
def __init__(self,
service_type: str,
service_id: Optional[str] = None,
config: Optional[Dict[str, str]] = None,
networks: Optional[List[str]] = None,
placement: Optional[PlacementSpec] = None,
unmanaged: bool = False,
preview_only: bool = False,
port: Optional[int] = None,
extra_container_args: Optional[GeneralArgList] = None,
extra_entrypoint_args: Optional[GeneralArgList] = None,
custom_configs: Optional[List[CustomConfig]] = None,
):
assert service_type in ['grafana', 'node-exporter', 'prometheus', 'alertmanager',
'loki', 'promtail']
super(MonitoringSpec, self).__init__(
service_type, service_id,
placement=placement, unmanaged=unmanaged,
preview_only=preview_only, config=config,
networks=networks, extra_container_args=extra_container_args,
extra_entrypoint_args=extra_entrypoint_args,
custom_configs=custom_configs)
self.service_type = service_type
self.port = port
def get_port_start(self) -> List[int]:
return [self.get_port()]
def get_port(self) -> int:
if self.port:
return self.port
else:
return {'prometheus': 9095,
'node-exporter': 9100,
'alertmanager': 9093,
'grafana': 3000,
'loki': 3100,
'promtail': 9080}[self.service_type]
yaml.add_representer(MonitoringSpec, ServiceSpec.yaml_representer)
class AlertManagerSpec(MonitoringSpec):
def __init__(self,
service_type: str = 'alertmanager',
service_id: Optional[str] = None,
placement: Optional[PlacementSpec] = None,
unmanaged: bool = False,
preview_only: bool = False,
user_data: Optional[Dict[str, Any]] = None,
config: Optional[Dict[str, str]] = None,
networks: Optional[List[str]] = None,
port: Optional[int] = None,
secure: bool = False,
extra_container_args: Optional[GeneralArgList] = None,
extra_entrypoint_args: Optional[GeneralArgList] = None,
custom_configs: Optional[List[CustomConfig]] = None,
):
assert service_type == 'alertmanager'
super(AlertManagerSpec, self).__init__(
'alertmanager', service_id=service_id,
placement=placement, unmanaged=unmanaged,
preview_only=preview_only, config=config, networks=networks, port=port,
extra_container_args=extra_container_args, extra_entrypoint_args=extra_entrypoint_args,
custom_configs=custom_configs)
# Custom configuration.
#
# Example:
# service_type: alertmanager
# service_id: xyz
# user_data:
# default_webhook_urls:
# - "https://foo"
# - "https://bar"
#
# Documentation:
# default_webhook_urls - A list of additional URL's that are
# added to the default receivers'
# <webhook_configs> configuration.
self.user_data = user_data or {}
self.secure = secure
def get_port_start(self) -> List[int]:
return [self.get_port(), 9094]
def validate(self) -> None:
super(AlertManagerSpec, self).validate()
if self.port == 9094:
raise SpecValidationError(
'Port 9094 is reserved for AlertManager cluster listen address')
yaml.add_representer(AlertManagerSpec, ServiceSpec.yaml_representer)
class GrafanaSpec(MonitoringSpec):
def __init__(self,
service_type: str = 'grafana',
service_id: Optional[str] = None,
placement: Optional[PlacementSpec] = None,
unmanaged: bool = False,
preview_only: bool = False,
config: Optional[Dict[str, str]] = None,
networks: Optional[List[str]] = None,
port: Optional[int] = None,
protocol: Optional[str] = 'https',
initial_admin_password: Optional[str] = None,
anonymous_access: Optional[bool] = True,
extra_container_args: Optional[GeneralArgList] = None,
extra_entrypoint_args: Optional[GeneralArgList] = None,
custom_configs: Optional[List[CustomConfig]] = None,
):
assert service_type == 'grafana'
super(GrafanaSpec, self).__init__(
'grafana', service_id=service_id,
placement=placement, unmanaged=unmanaged,
preview_only=preview_only, config=config, networks=networks, port=port,
extra_container_args=extra_container_args, extra_entrypoint_args=extra_entrypoint_args,
custom_configs=custom_configs)
self.initial_admin_password = initial_admin_password
self.anonymous_access = anonymous_access
self.protocol = protocol
def validate(self) -> None:
super(GrafanaSpec, self).validate()
if self.protocol not in ['http', 'https']:
err_msg = f"Invalid protocol '{self.protocol}'. Valid values are: 'http', 'https'."
raise SpecValidationError(err_msg)
if not self.anonymous_access and not self.initial_admin_password:
err_msg = ('Either initial_admin_password must be set or anonymous_access '
'must be set to true. Otherwise the grafana dashboard will '
'be inaccessible.')
raise SpecValidationError(err_msg)
yaml.add_representer(GrafanaSpec, ServiceSpec.yaml_representer)
class PrometheusSpec(MonitoringSpec):
def __init__(self,
service_type: str = 'prometheus',
service_id: Optional[str] = None,
placement: Optional[PlacementSpec] = None,
unmanaged: bool = False,
preview_only: bool = False,
config: Optional[Dict[str, str]] = None,
networks: Optional[List[str]] = None,
port: Optional[int] = None,
retention_time: Optional[str] = None,
retention_size: Optional[str] = None,
extra_container_args: Optional[GeneralArgList] = None,
extra_entrypoint_args: Optional[GeneralArgList] = None,
custom_configs: Optional[List[CustomConfig]] = None,
):
assert service_type == 'prometheus'
super(PrometheusSpec, self).__init__(
'prometheus', service_id=service_id,
placement=placement, unmanaged=unmanaged,
preview_only=preview_only, config=config, networks=networks, port=port,
extra_container_args=extra_container_args, extra_entrypoint_args=extra_entrypoint_args,
custom_configs=custom_configs)
self.retention_time = retention_time.strip() if retention_time else None
self.retention_size = retention_size.strip() if retention_size else None
def validate(self) -> None:
super(PrometheusSpec, self).validate()
if self.retention_time:
valid_units = ['y', 'w', 'd', 'h', 'm', 's']
m = re.search(rf"^(\d+)({'|'.join(valid_units)})$", self.retention_time)
if not m:
units = ', '.join(valid_units)
raise SpecValidationError(f"Invalid retention time. Valid units are: {units}")
if self.retention_size:
valid_units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB']
m = re.search(rf"^(\d+)({'|'.join(valid_units)})$", self.retention_size)
if not m:
units = ', '.join(valid_units)
raise SpecValidationError(f"Invalid retention size. Valid units are: {units}")
yaml.add_representer(PrometheusSpec, ServiceSpec.yaml_representer)
class SNMPGatewaySpec(ServiceSpec):
class SNMPVersion(str, enum.Enum):
V2c = 'V2c'
V3 = 'V3'
def to_json(self) -> str:
return self.value
class SNMPAuthType(str, enum.Enum):
MD5 = 'MD5'
SHA = 'SHA'
def to_json(self) -> str:
return self.value
class SNMPPrivacyType(str, enum.Enum):
DES = 'DES'
AES = 'AES'
def to_json(self) -> str:
return self.value
valid_destination_types = [
'Name:Port',
'IPv4:Port'
]
def __init__(self,
service_type: str = 'snmp-gateway',
snmp_version: Optional[SNMPVersion] = None,
snmp_destination: str = '',
credentials: Dict[str, str] = {},
engine_id: Optional[str] = None,
auth_protocol: Optional[SNMPAuthType] = None,
privacy_protocol: Optional[SNMPPrivacyType] = None,
placement: Optional[PlacementSpec] = None,
unmanaged: bool = False,
preview_only: bool = False,
port: Optional[int] = None,
extra_container_args: Optional[GeneralArgList] = None,
extra_entrypoint_args: Optional[GeneralArgList] = None,
custom_configs: Optional[List[CustomConfig]] = None,
):
assert service_type == 'snmp-gateway'
super(SNMPGatewaySpec, self).__init__(
service_type,
placement=placement,
unmanaged=unmanaged,
preview_only=preview_only,
extra_container_args=extra_container_args,
extra_entrypoint_args=extra_entrypoint_args,
custom_configs=custom_configs)
self.service_type = service_type
self.snmp_version = snmp_version
self.snmp_destination = snmp_destination
self.port = port
self.credentials = credentials
self.engine_id = engine_id
self.auth_protocol = auth_protocol
self.privacy_protocol = privacy_protocol
@classmethod
def _from_json_impl(cls, json_spec: dict) -> 'SNMPGatewaySpec':
cpy = json_spec.copy()
types = [
('snmp_version', SNMPGatewaySpec.SNMPVersion),
('auth_protocol', SNMPGatewaySpec.SNMPAuthType),
('privacy_protocol', SNMPGatewaySpec.SNMPPrivacyType),
]
for d in cpy, cpy.get('spec', {}):
for key, enum_cls in types:
try:
if key in d:
d[key] = enum_cls(d[key])
except ValueError:
raise SpecValidationError(f'{key} unsupported. Must be one of '
f'{", ".join(enum_cls)}')
return super(SNMPGatewaySpec, cls)._from_json_impl(cpy)
@property
def ports(self) -> List[int]:
return [self.port or 9464]
def get_port_start(self) -> List[int]:
return self.ports
def validate(self) -> None:
super(SNMPGatewaySpec, self).validate()
if not self.credentials:
raise SpecValidationError(
'Missing authentication information (credentials). '
'SNMP V2c and V3 require credential information'
)
elif not self.snmp_version:
raise SpecValidationError(
'Missing SNMP version (snmp_version)'
)
creds_requirement = {
'V2c': ['snmp_community'],
'V3': ['snmp_v3_auth_username', 'snmp_v3_auth_password']
}
if self.privacy_protocol:
creds_requirement['V3'].append('snmp_v3_priv_password')
missing = [parm for parm in creds_requirement[self.snmp_version]
if parm not in self.credentials]
# check that credentials are correct for the version
if missing:
raise SpecValidationError(
f'SNMP {self.snmp_version} credentials are incomplete. Missing {", ".join(missing)}'
)
if self.engine_id:
if 10 <= len(self.engine_id) <= 64 and \
is_hex(self.engine_id) and \
len(self.engine_id) % 2 == 0:
pass
else:
raise SpecValidationError(
'engine_id must be a string containing 10-64 hex characters. '
'Its length must be divisible by 2'
)
else:
if self.snmp_version == 'V3':
raise SpecValidationError(
'Must provide an engine_id for SNMP V3 notifications'
)
if not self.snmp_destination:
raise SpecValidationError(
'SNMP destination (snmp_destination) must be provided'
)
else:
valid, description = valid_addr(self.snmp_destination)
if not valid:
raise SpecValidationError(
f'SNMP destination (snmp_destination) is invalid: {description}'
)
if description not in self.valid_destination_types:
raise SpecValidationError(
f'SNMP destination (snmp_destination) type ({description}) is invalid. '
f'Must be either: {", ".join(sorted(self.valid_destination_types))}'
)
yaml.add_representer(SNMPGatewaySpec, ServiceSpec.yaml_representer)
class MDSSpec(ServiceSpec):
def __init__(self,
service_type: str = 'mds',
service_id: Optional[str] = None,
placement: Optional[PlacementSpec] = None,
config: Optional[Dict[str, str]] = None,
unmanaged: bool = False,
preview_only: bool = False,
extra_container_args: Optional[GeneralArgList] = None,
extra_entrypoint_args: Optional[GeneralArgList] = None,
custom_configs: Optional[List[CustomConfig]] = None,
):
assert service_type == 'mds'
super(MDSSpec, self).__init__('mds', service_id=service_id,
placement=placement,
config=config,
unmanaged=unmanaged,
preview_only=preview_only,
extra_container_args=extra_container_args,
extra_entrypoint_args=extra_entrypoint_args,
custom_configs=custom_configs)
def validate(self) -> None:
super(MDSSpec, self).validate()
if str(self.service_id)[0].isdigit():
raise SpecValidationError('MDS service id cannot start with a numeric digit')
yaml.add_representer(MDSSpec, ServiceSpec.yaml_representer)
class MONSpec(ServiceSpec):
def __init__(self,
service_type: str,
service_id: Optional[str] = None,
placement: Optional[PlacementSpec] = None,
count: Optional[int] = None,
config: Optional[Dict[str, str]] = None,
unmanaged: bool = False,
preview_only: bool = False,
networks: Optional[List[str]] = None,
extra_container_args: Optional[GeneralArgList] = None,
extra_entrypoint_args: Optional[GeneralArgList] = None,
custom_configs: Optional[List[CustomConfig]] = None,
crush_locations: Optional[Dict[str, List[str]]] = None,
):
assert service_type == 'mon'
super(MONSpec, self).__init__('mon', service_id=service_id,
placement=placement,
count=count,
config=config,
unmanaged=unmanaged,
preview_only=preview_only,
networks=networks,
extra_container_args=extra_container_args,
extra_entrypoint_args=extra_entrypoint_args,
custom_configs=custom_configs)
self.crush_locations = crush_locations
self.validate()
def validate(self) -> None:
if self.crush_locations:
for host, crush_locs in self.crush_locations.items():
try:
assert_valid_host(host)
except SpecValidationError as e:
err_str = f'Invalid hostname found in spec crush locations: {e}'
raise SpecValidationError(err_str)
for cloc in crush_locs:
if '=' not in cloc or len(cloc.split('=')) != 2:
err_str = ('Crush locations must be of form <bucket>=<location>. '
f'Found crush location: {cloc}')
raise SpecValidationError(err_str)
yaml.add_representer(MONSpec, ServiceSpec.yaml_representer)
class TracingSpec(ServiceSpec):
SERVICE_TYPES = ['elasticsearch', 'jaeger-collector', 'jaeger-query', 'jaeger-agent']
def __init__(self,
service_type: str,
es_nodes: Optional[str] = None,
without_query: bool = False,
service_id: Optional[str] = None,
config: Optional[Dict[str, str]] = None,
networks: Optional[List[str]] = None,
placement: Optional[PlacementSpec] = None,
unmanaged: bool = False,
preview_only: bool = False
):
assert service_type in TracingSpec.SERVICE_TYPES + ['jaeger-tracing']
super(TracingSpec, self).__init__(
service_type, service_id,
placement=placement, unmanaged=unmanaged,
preview_only=preview_only, config=config,
networks=networks)
self.without_query = without_query
self.es_nodes = es_nodes
def get_port_start(self) -> List[int]:
return [self.get_port()]
def get_port(self) -> int:
return {'elasticsearch': 9200,
'jaeger-agent': 6799,
'jaeger-collector': 14250,
'jaeger-query': 16686}[self.service_type]
def get_tracing_specs(self) -> List[ServiceSpec]:
assert self.service_type == 'jaeger-tracing'
specs: List[ServiceSpec] = []
daemons: Dict[str, Optional[PlacementSpec]] = {
daemon: None for daemon in TracingSpec.SERVICE_TYPES}
if self.es_nodes:
del daemons['elasticsearch']
if self.without_query:
del daemons['jaeger-query']
if self.placement:
daemons.update({'jaeger-collector': self.placement})
for daemon, daemon_placement in daemons.items():
specs.append(TracingSpec(service_type=daemon,
es_nodes=self.es_nodes,
placement=daemon_placement,
unmanaged=self.unmanaged,
config=self.config,
networks=self.networks,
preview_only=self.preview_only
))
return specs
yaml.add_representer(TracingSpec, ServiceSpec.yaml_representer)
class TunedProfileSpec():
def __init__(self,
profile_name: str,
placement: Optional[PlacementSpec] = None,
settings: Optional[Dict[str, str]] = None,
):
self.profile_name = profile_name
self.placement = placement or PlacementSpec(host_pattern='*')
self.settings = settings or {}
self._last_updated: str = ''
@classmethod
def from_json(cls, spec: Dict[str, Any]) -> 'TunedProfileSpec':
data = {}
if 'profile_name' not in spec:
raise SpecValidationError('Tuned profile spec must include "profile_name" field')
data['profile_name'] = spec['profile_name']
if not isinstance(data['profile_name'], str):
raise SpecValidationError('"profile_name" field must be a string')
if 'placement' in spec:
data['placement'] = PlacementSpec.from_json(spec['placement'])
if 'settings' in spec:
data['settings'] = spec['settings']
return cls(**data)
def to_json(self) -> Dict[str, Any]:
res: Dict[str, Any] = {}
res['profile_name'] = self.profile_name
res['placement'] = self.placement.to_json()
res['settings'] = self.settings
return res
def __eq__(self, other: Any) -> bool:
if isinstance(other, TunedProfileSpec):
if (
self.placement == other.placement
and self.profile_name == other.profile_name
and self.settings == other.settings
):
return True
return False
return NotImplemented
def __repr__(self) -> str:
return f'TunedProfile({self.profile_name})'
def copy(self) -> 'TunedProfileSpec':
# for making deep copies so you can edit the settings in one without affecting the other
# mostly for testing purposes
return TunedProfileSpec(self.profile_name, self.placement, self.settings.copy())
class CephExporterSpec(ServiceSpec):
def __init__(self,
service_type: str = 'ceph-exporter',
sock_dir: Optional[str] = None,
addrs: str = '',
port: Optional[int] = None,
prio_limit: Optional[int] = 5,
stats_period: Optional[int] = 5,
placement: Optional[PlacementSpec] = None,
unmanaged: bool = False,
preview_only: bool = False,
extra_container_args: Optional[GeneralArgList] = None,
extra_entrypoint_args: Optional[GeneralArgList] = None,
):
assert service_type == 'ceph-exporter'
super(CephExporterSpec, self).__init__(
service_type,
placement=placement,
unmanaged=unmanaged,
preview_only=preview_only,
extra_container_args=extra_container_args,
extra_entrypoint_args=extra_entrypoint_args)
self.service_type = service_type
self.sock_dir = sock_dir
self.addrs = addrs
self.port = port
self.prio_limit = prio_limit
self.stats_period = stats_period
def validate(self) -> None:
super(CephExporterSpec, self).validate()
if not isinstance(self.prio_limit, int):
raise SpecValidationError(
f'prio_limit must be an integer. Got {type(self.prio_limit)}')
if not isinstance(self.stats_period, int):
raise SpecValidationError(
f'stats_period must be an integer. Got {type(self.stats_period)}')
yaml.add_representer(CephExporterSpec, ServiceSpec.yaml_representer)
| 76,595 | 38.300154 | 100 |
py
|
null |
ceph-main/src/python-common/ceph/deployment/translate.py
|
import logging
try:
from typing import Optional, List, Dict
except ImportError:
pass
from ceph.deployment.drive_selection.selector import DriveSelection
logger = logging.getLogger(__name__)
# TODO refactor this to a DriveSelection method
class to_ceph_volume(object):
_supported_device_classes = [
"hdd", "ssd", "nvme"
]
def __init__(self,
selection, # type: DriveSelection
osd_id_claims=None, # type: Optional[List[str]]
preview=False # type: bool
):
self.selection = selection
self.spec = selection.spec
self.preview = preview
self.osd_id_claims = osd_id_claims
def prepare_devices(self):
# type: () -> Dict[str, List[str]]
lvcount: Dict[str, List[str]] = dict()
"""
Default entry for the global crush_device_class definition;
if there's no global definition at spec level, we do not want
to apply anything to the provided devices, hence we need to run
a ceph-volume command without that option, otherwise we init an
entry for the globally defined crush_device_class.
"""
if self.spec.crush_device_class:
lvcount[self.spec.crush_device_class] = []
# entry where the drives that don't require a crush_device_class
# option are collected
lvcount["no_crush"] = []
"""
for each device, check if it's just a path or it has a crush_device
class definition, and append an entry to the right crush_device_
class group
"""
for device in self.selection.data_devices():
# iterate on List[Device], containing both path and
# crush_device_class
path = device.path
crush_device_class = device.crush_device_class
if path is None:
raise ValueError("Device path can't be empty")
"""
if crush_device_class is specified for the current Device path
we should either init the array for this group or append the
drive path to the existing entry
"""
if crush_device_class:
if crush_device_class in lvcount.keys():
lvcount[crush_device_class].append(path)
else:
lvcount[crush_device_class] = [path]
continue
"""
if no crush_device_class is specified for the current path
but a global definition is present in the spec, so we group
the drives together
"""
if crush_device_class is None and self.spec.crush_device_class:
lvcount[self.spec.crush_device_class].append(path)
continue
else:
# default use case
lvcount["no_crush"].append(path)
continue
return lvcount
def run(self):
# type: () -> List[str]
""" Generate ceph-volume commands based on the DriveGroup filters """
db_devices = [x.path for x in self.selection.db_devices()]
wal_devices = [x.path for x in self.selection.wal_devices()]
if not self.selection.data_devices():
return []
cmds: List[str] = []
devices = self.prepare_devices()
# get the total number of devices provided by the Dict[str, List[str]]
devices_count = len(sum(list(devices.values()), []))
if devices and db_devices:
if (devices_count != len(db_devices)) and (self.spec.method == 'raw'):
raise ValueError('Number of data devices must match number of '
'db devices for raw mode osds')
if devices and wal_devices:
if (devices_count != len(wal_devices)) and (self.spec.method == 'raw'):
raise ValueError('Number of data devices must match number of '
'wal devices for raw mode osds')
for d in devices.keys():
data_devices: Optional[List[str]] = devices.get(d)
if not data_devices:
continue
if self.spec.method == 'raw':
assert self.spec.objectstore == 'bluestore'
# ceph-volume raw prepare only support 1:1 ratio of data to db/wal devices
# for raw prepare each data device needs its own prepare command
dev_counter = 0
# reversing the lists as we're assigning db_devices sequentially
db_devices.reverse()
wal_devices.reverse()
while dev_counter < len(data_devices):
cmd = "raw prepare --bluestore"
cmd += " --data {}".format(data_devices[dev_counter])
if db_devices:
cmd += " --block.db {}".format(db_devices.pop())
if wal_devices:
cmd += " --block.wal {}".format(wal_devices.pop())
if d in self._supported_device_classes:
cmd += " --crush-device-class {}".format(d)
cmds.append(cmd)
dev_counter += 1
elif self.spec.objectstore == 'bluestore':
# for lvm batch we can just do all devices in one command
cmd = "lvm batch --no-auto {}".format(" ".join(data_devices))
if db_devices:
cmd += " --db-devices {}".format(" ".join(db_devices))
if wal_devices:
cmd += " --wal-devices {}".format(" ".join(wal_devices))
if self.spec.block_wal_size:
cmd += " --block-wal-size {}".format(self.spec.block_wal_size)
if self.spec.block_db_size:
cmd += " --block-db-size {}".format(self.spec.block_db_size)
if d in self._supported_device_classes:
cmd += " --crush-device-class {}".format(d)
cmds.append(cmd)
for i in range(len(cmds)):
if self.spec.encrypted:
cmds[i] += " --dmcrypt"
if self.spec.osds_per_device:
cmds[i] += " --osds-per-device {}".format(self.spec.osds_per_device)
if self.spec.data_allocate_fraction:
cmds[i] += " --data-allocate-fraction {}".format(self.spec.data_allocate_fraction)
if self.osd_id_claims:
cmds[i] += " --osd-ids {}".format(" ".join(self.osd_id_claims))
if self.spec.method != 'raw':
cmds[i] += " --yes"
cmds[i] += " --no-systemd"
# set the --crush-device-class option when:
# - crush_device_class is specified at spec level (global for all the osds) # noqa E501
# - crush_device_class is allowed
# - there's no override at osd level
if (
self.spec.crush_device_class and
self.spec.crush_device_class in self._supported_device_classes and # noqa E501
"crush-device-class" not in cmds[i]
):
cmds[i] += " --crush-device-class {}".format(self.spec.crush_device_class) # noqa E501
if self.preview:
cmds[i] += " --report"
cmds[i] += " --format json"
return cmds
| 7,462 | 36.502513 | 103 |
py
|
null |
ceph-main/src/python-common/ceph/deployment/utils.py
|
import ipaddress
import socket
from typing import Tuple, Optional
from urllib.parse import urlparse
def unwrap_ipv6(address):
# type: (str) -> str
if address.startswith('[') and address.endswith(']'):
return address[1:-1]
return address
def wrap_ipv6(address):
# type: (str) -> str
# We cannot assume it's already wrapped or even an IPv6 address if
# it's already wrapped it'll not pass (like if it's a hostname) and trigger
# the ValueError
try:
if ipaddress.ip_address(address).version == 6:
return f"[{address}]"
except ValueError:
pass
return address
def is_ipv6(address):
# type: (str) -> bool
address = unwrap_ipv6(address)
try:
return ipaddress.ip_address(address).version == 6
except ValueError:
return False
def valid_addr(addr: str) -> Tuple[bool, str]:
"""check that an address string is valid
Valid in this case means that a name is resolvable, or the
IP address string is a correctly formed IPv4 or IPv6 address,
with or without a port
Args:
addr (str): address
Returns:
Tuple[bool, str]: Validity of the address, either
True, address type (IPv4[:Port], IPv6[:Port], Name[:Port])
False, <error description>
"""
def _dns_lookup(addr: str, port: Optional[int]) -> Tuple[bool, str]:
try:
socket.getaddrinfo(addr, None)
except socket.gaierror:
# not resolvable
return False, 'DNS lookup failed'
return True, 'Name:Port' if port else 'Name'
def _ip_lookup(addr: str, port: Optional[int]) -> Tuple[bool, str]:
unwrapped = unwrap_ipv6(addr)
try:
ip_addr = ipaddress.ip_address(unwrapped)
except ValueError:
return False, 'Invalid IP v4 or v6 address format'
return True, f'IPv{ip_addr.version}:Port' if port else f'IPv{ip_addr.version}'
dots = addr.count('.')
colons = addr.count(':')
addr_as_url = f'http://{addr}'
try:
res = urlparse(addr_as_url)
except ValueError as e:
if str(e) == 'Invalid IPv6 URL':
return False, 'Address has incorrect/incomplete use of enclosing brackets'
return False, f'Unknown urlparse error {str(e)} for {addr_as_url}'
addr = res.netloc
port = None
try:
port = res.port
if port:
addr = addr[:-len(f':{port}')]
except ValueError:
if colons == 1:
return False, 'Port must be numeric'
elif ']:' in addr:
return False, 'Port must be numeric'
if addr.startswith('[') and dots:
return False, "IPv4 address wrapped in brackets is invalid"
# catch partial address like 10.8 which would be valid IPaddress schemes
# but are classed as invalid here since they're not usable
if dots and addr[0].isdigit() and dots != 3:
return False, 'Invalid partial IPv4 address'
if addr[0].isalpha() and '.' in addr:
return _dns_lookup(addr, port)
return _ip_lookup(addr, port)
| 3,124 | 29.339806 | 86 |
py
|
null |
ceph-main/src/python-common/ceph/deployment/drive_selection/__init__.py
|
from .selector import DriveSelection # NOQA
from .matchers import Matcher, SubstringMatcher, EqualityMatcher, AllMatcher, SizeMatcher # NOQA
| 143 | 47 | 97 |
py
|
null |
ceph-main/src/python-common/ceph/deployment/drive_selection/example.yaml
|
# default:
# target: 'data*'
# data_devices:
# size: 20G
# db_devices:
# size: 10G
# rotational: 1
# allflash:
# target: 'fast_nodes*'
# data_devices:
# size: 100G
# db_devices:
# size: 50G
# rotational: 0
# This is the default configuration and
# will create an OSD on all available drives
default:
target: 'fnmatch_target'
data_devices:
all: true
| 394 | 16.954545 | 44 |
yaml
|
null |
ceph-main/src/python-common/ceph/deployment/drive_selection/filter.py
|
# -*- coding: utf-8 -*-
import logging
from ceph.deployment.drive_group import DeviceSelection
try:
from typing import Generator
except ImportError:
pass
from .matchers import Matcher, SubstringMatcher, AllMatcher, SizeMatcher, EqualityMatcher
logger = logging.getLogger(__name__)
class FilterGenerator(object):
def __init__(self, device_filter):
# type: (DeviceSelection) -> None
self.device_filter = device_filter
def __iter__(self):
# type: () -> Generator[Matcher, None, None]
if self.device_filter.actuators:
yield EqualityMatcher('actuators', self.device_filter.actuators)
if self.device_filter.size:
yield SizeMatcher('size', self.device_filter.size)
if self.device_filter.model:
yield SubstringMatcher('model', self.device_filter.model)
if self.device_filter.vendor:
yield SubstringMatcher('vendor', self.device_filter.vendor)
if self.device_filter.rotational is not None:
val = '1' if self.device_filter.rotational else '0'
yield EqualityMatcher('rotational', val)
if self.device_filter.all:
yield AllMatcher('all', str(self.device_filter.all))
| 1,234 | 32.378378 | 89 |
py
|
null |
ceph-main/src/python-common/ceph/deployment/drive_selection/matchers.py
|
# -*- coding: utf-8 -*-
from typing import Tuple, Optional, Any, Union, Iterator
from ceph.deployment.inventory import Device
import re
import logging
logger = logging.getLogger(__name__)
class _MatchInvalid(Exception):
pass
# pylint: disable=too-few-public-methods
class Matcher(object):
""" The base class to all Matchers
It holds utility methods such as _get_disk_key
and handles the initialization.
"""
def __init__(self, key, value):
# type: (str, Any) -> None
""" Initialization of Base class
:param str key: Attribute like 'model, size or vendor'
:param str value: Value of attribute like 'X123, 5G or samsung'
"""
self.key = key
self.value = value
self.fallback_key = '' # type: Optional[str]
def _get_disk_key(self, device):
# type: (Device) -> Any
""" Helper method to safely extract values form the disk dict
There is a 'key' and a _optional_ 'fallback' key that can be used.
The reason for this is that the output of ceph-volume is not always
consistent (due to a bug currently, but you never know).
There is also a safety measure for a disk_key not existing on
virtual environments. ceph-volume apparently sources its information
from udev which seems to not populate certain fields on VMs.
:raises: A generic Exception when no disk_key could be found.
:return: A disk value
:rtype: str
"""
# using the . notation, but some keys are nested, and hidden behind
# a different hierarchy, which makes it harder to access programatically
# hence, make it a dict.
disk = device.to_json()
def findkeys(node: Union[list, dict], key_val: str) -> Iterator[str]:
""" Find keys in non-flat dict recursively """
if isinstance(node, list):
for i in node:
for key in findkeys(i, key_val):
yield key
elif isinstance(node, dict):
if key_val in node:
yield node[key_val]
for j in node.values():
for key in findkeys(j, key_val):
yield key
disk_value = list(findkeys(disk, self.key))
if not disk_value and self.fallback_key:
disk_value = list(findkeys(disk, self.fallback_key))
if disk_value:
return disk_value[0]
else:
raise _MatchInvalid("No value found for {} or {}".format(
self.key, self.fallback_key))
def compare(self, disk):
# type: (Device) -> bool
""" Implements a valid comparison method for a SubMatcher
This will get overwritten by the individual classes
:param dict disk: A disk representation
"""
raise NotImplementedError
# pylint: disable=too-few-public-methods
class SubstringMatcher(Matcher):
""" Substring matcher subclass
"""
def __init__(self, key, value, fallback_key=None):
# type: (str, str, Optional[str]) -> None
Matcher.__init__(self, key, value)
self.fallback_key = fallback_key
def compare(self, disk):
# type: (Device) -> bool
""" Overwritten method to match substrings
This matcher does substring matching
:param dict disk: A disk representation (see base for examples)
:return: True/False if the match succeeded
:rtype: bool
"""
if not disk:
return False
disk_value = self._get_disk_key(disk)
if str(self.value) in disk_value:
return True
return False
# pylint: disable=too-few-public-methods
class AllMatcher(Matcher):
""" All matcher subclass
"""
def __init__(self, key, value, fallback_key=None):
# type: (str, Any, Optional[str]) -> None
Matcher.__init__(self, key, value)
self.fallback_key = fallback_key
def compare(self, disk):
# type: (Device) -> bool
""" Overwritten method to match all
A rather dumb matcher that just accepts all disks
(regardless of the value)
:param dict disk: A disk representation (see base for examples)
:return: always True
:rtype: bool
"""
if not disk:
return False
return True
# pylint: disable=too-few-public-methods
class EqualityMatcher(Matcher):
""" Equality matcher subclass
"""
def __init__(self, key, value):
# type: (str, Any) -> None
Matcher.__init__(self, key, value)
def compare(self, disk):
# type: (Device) -> bool
""" Overwritten method to match equality
This matcher does value comparison
:param dict disk: A disk representation
:return: True/False if the match succeeded
:rtype: bool
"""
if not disk:
return False
disk_value = self._get_disk_key(disk)
ret = disk_value == self.value
if not ret:
logger.debug('{} != {}'.format(disk_value, self.value))
return ret
class SizeMatcher(Matcher):
""" Size matcher subclass
"""
SUFFIXES = (
["KB", "MB", "GB", "TB"],
["K", "M", "G", "T"],
[1e+3, 1e+6, 1e+9, 1e+12]
)
supported_suffixes = SUFFIXES[0] + SUFFIXES[1]
# pylint: disable=too-many-instance-attributes
def __init__(self, key, value):
# type: (str, str) -> None
# The 'key' value is overwritten here because
# the user_defined attribute does not necessarily
# correspond to the desired attribute
# requested from the inventory output
Matcher.__init__(self, key, value)
self.key = "human_readable_size"
self.fallback_key = "size"
self._high = None # type: Optional[str]
self._high_suffix = None # type: Optional[str]
self._low = None # type: Optional[str]
self._low_suffix = None # type: Optional[str]
self._exact = None # type: Optional[str]
self._exact_suffix = None # type: Optional[str]
self._parse_filter()
@property
def low(self):
# type: () -> Tuple[Optional[str], Optional[str]]
""" Getter for 'low' matchers
"""
return self._low, self._low_suffix
@low.setter
def low(self, low):
# type: (Tuple[str, str]) -> None
""" Setter for 'low' matchers
"""
self._low, self._low_suffix = low
@property
def high(self):
# type: () -> Tuple[Optional[str], Optional[str]]
""" Getter for 'high' matchers
"""
return self._high, self._high_suffix
@high.setter
def high(self, high):
# type: (Tuple[str, str]) -> None
""" Setter for 'high' matchers
"""
self._high, self._high_suffix = high
@property
def exact(self):
# type: () -> Tuple[Optional[str], Optional[str]]
""" Getter for 'exact' matchers
"""
return self._exact, self._exact_suffix
@exact.setter
def exact(self, exact):
# type: (Tuple[str, str]) -> None
""" Setter for 'exact' matchers
"""
self._exact, self._exact_suffix = exact
@classmethod
def _normalize_suffix(cls, suffix):
# type: (str) -> str
""" Normalize any supported suffix
Since the Drive Groups are user facing, we simply
can't make sure that all users type in the requested
form. That's why we have to internally agree on one format.
It also checks if any of the supported suffixes was used
and raises an Exception otherwise.
:param str suffix: A suffix ('G') or ('M')
:return: A normalized output
:rtype: str
"""
suffix = suffix.upper()
if suffix not in cls.supported_suffixes:
raise _MatchInvalid("Unit '{}' not supported".format(suffix))
return dict(zip(
cls.SUFFIXES[1],
cls.SUFFIXES[0],
)).get(suffix, suffix)
@classmethod
def _parse_suffix(cls, obj):
# type: (str) -> str
""" Wrapper method to find and normalize a prefix
:param str obj: A size filtering string ('10G')
:return: A normalized unit ('GB')
:rtype: str
"""
return cls._normalize_suffix(re.findall(r"[a-zA-Z]+", obj)[0])
@classmethod
def _get_k_v(cls, data):
# type: (str) -> Tuple[str, str]
""" Helper method to extract data from a string
It uses regex to extract all digits and calls _parse_suffix
which also uses a regex to extract all letters and normalizes
the resulting suffix.
:param str data: A size filtering string ('10G')
:return: A Tuple with normalized output (10, 'GB')
:rtype: tuple
"""
return re.findall(r"\d+\.?\d*", data)[0], cls._parse_suffix(data)
def _parse_filter(self) -> None:
""" Identifies which type of 'size' filter is applied
There are four different filtering modes:
1) 10G:50G (high-low)
At least 10G but at max 50G of size
2) :60G
At max 60G of size
3) 50G:
At least 50G of size
4) 20G
Exactly 20G in size
This method uses regex to identify and extract this information
and raises if none could be found.
"""
low_high = re.match(r"\d+[A-Z]{1,2}:\d+[A-Z]{1,2}", self.value)
if low_high is not None:
lowpart, highpart = low_high.group().split(":")
self.low = self._get_k_v(lowpart)
self.high = self._get_k_v(highpart)
low = re.match(r"\d+[A-Z]{1,2}:$", self.value)
if low:
self.low = self._get_k_v(low.group())
high = re.match(r"^:\d+[A-Z]{1,2}", self.value)
if high:
self.high = self._get_k_v(high.group())
exact = re.match(r"^\d+\.?\d*[A-Z]{1,2}$", self.value)
if exact:
self.exact = self._get_k_v(exact.group())
if not self.low and not self.high and not self.exact:
raise _MatchInvalid("Couldn't parse {}".format(self.value))
@staticmethod
# pylint: disable=inconsistent-return-statements
def to_byte(tpl):
# type: (Tuple[Optional[str], Optional[str]]) -> float
""" Convert any supported unit to bytes
:param tuple tpl: A tuple with ('10', 'GB')
:return: The converted byte value
:rtype: float
"""
val_str, suffix = tpl
value = float(val_str) if val_str is not None else 0.0
return dict(zip(
SizeMatcher.SUFFIXES[0],
SizeMatcher.SUFFIXES[2],
)).get(str(suffix), 0.00) * value
@staticmethod
def str_to_byte(input):
# type: (str) -> float
return SizeMatcher.to_byte(SizeMatcher._get_k_v(input))
# pylint: disable=inconsistent-return-statements, too-many-return-statements
def compare(self, disk):
# type: (Device) -> bool
""" Convert MB/GB/TB down to bytes and compare
1) Extracts information from the to-be-inspected disk.
2) Depending on the mode, apply checks and return
# This doesn't seem very solid and _may_
be re-factored
"""
if not disk:
return False
disk_value = self._get_disk_key(disk)
# This doesn't necessarily have to be a float.
# The current output from ceph-volume gives a float..
# This may change in the future..
# todo: harden this paragraph
if not disk_value:
logger.warning("Could not retrieve value for disk")
return False
disk_size = re.findall(r"\d+\.\d+", disk_value)[0]
disk_suffix = self._parse_suffix(disk_value)
disk_size_in_byte = self.to_byte((disk_size, disk_suffix))
if all(self.high) and all(self.low):
if disk_size_in_byte <= self.to_byte(
self.high) and disk_size_in_byte >= self.to_byte(self.low):
return True
# is a else: return False necessary here?
# (and in all other branches)
logger.debug("Disk didn't match for 'high/low' filter")
elif all(self.low) and not all(self.high):
if disk_size_in_byte >= self.to_byte(self.low):
return True
logger.debug("Disk didn't match for 'low' filter")
elif all(self.high) and not all(self.low):
if disk_size_in_byte <= self.to_byte(self.high):
return True
logger.debug("Disk didn't match for 'high' filter")
elif all(self.exact):
if disk_size_in_byte == self.to_byte(self.exact):
return True
logger.debug("Disk didn't match for 'exact' filter")
else:
logger.debug("Neither high, low, nor exact was given")
raise _MatchInvalid("No filters applied")
return False
| 13,115 | 30.757869 | 80 |
py
|
null |
ceph-main/src/python-common/ceph/deployment/drive_selection/selector.py
|
import logging
from typing import List, Optional, Dict, Callable
from ..inventory import Device
from ..drive_group import DriveGroupSpec, DeviceSelection, DriveGroupValidationError
from .filter import FilterGenerator
from .matchers import _MatchInvalid
logger = logging.getLogger(__name__)
def to_dg_exception(f: Callable) -> Callable[['DriveSelection', str,
Optional['DeviceSelection']],
List['Device']]:
def wrapper(self: 'DriveSelection', name: str, ds: Optional['DeviceSelection']) -> List[Device]:
try:
return f(self, ds)
except _MatchInvalid as e:
raise DriveGroupValidationError(f'{self.spec.service_id}.{name}', e.args[0])
return wrapper
class DriveSelection(object):
def __init__(self,
spec, # type: DriveGroupSpec
disks, # type: List[Device]
existing_daemons=None, # type: Optional[int]
):
self.disks = disks.copy()
self.spec = spec
self.existing_daemons = existing_daemons or 0
self._data = self.assign_devices('data_devices', self.spec.data_devices)
self._wal = self.assign_devices('wal_devices', self.spec.wal_devices)
self._db = self.assign_devices('db_devices', self.spec.db_devices)
self._journal = self.assign_devices('journal_devices', self.spec.journal_devices)
def data_devices(self):
# type: () -> List[Device]
return self._data
def wal_devices(self):
# type: () -> List[Device]
return self._wal
def db_devices(self):
# type: () -> List[Device]
return self._db
def journal_devices(self):
# type: () -> List[Device]
return self._journal
def _limit_reached(self, device_filter, len_devices,
disk_path):
# type: (DeviceSelection, int, str) -> bool
""" Check for the <limit> property and apply logic
If a limit is set in 'device_attrs' we have to stop adding
disks at some point.
If limit is set (>0) and len(devices) >= limit
:param int len_devices: Length of the already populated device set/list
:param str disk_path: The disk identifier (for logging purposes)
:return: True/False if the device should be added to the list of devices
:rtype: bool
"""
limit = device_filter.limit or 0
if limit > 0 and (len_devices + self.existing_daemons >= limit):
logger.debug("Refuse to add {} due to limit policy of <{}>".format(
disk_path, limit))
return True
return False
@staticmethod
def _has_mandatory_idents(disk):
# type: (Device) -> bool
""" Check for mandatory identification fields
"""
if disk.path:
logger.debug("Found matching disk: {}".format(disk.path))
return True
else:
raise Exception(
"Disk {} doesn't have a 'path' identifier".format(disk))
@to_dg_exception
def assign_devices(self, device_filter):
# type: (Optional[DeviceSelection]) -> List[Device]
""" Assign drives based on used filters
Do not add disks when:
1) Filter didn't match
2) Disk doesn't have a mandatory identification item (path)
3) The set :limit was reached
After the disk was added we make sure not to re-assign this disk
for another defined type[wal/db/journal devices]
return a sorted(by path) list of devices
"""
if not device_filter:
logger.debug('device_filter is None')
return []
if not self.spec.data_devices:
logger.debug('data_devices is None')
return []
if device_filter.paths:
logger.debug('device filter is using explicit paths')
return device_filter.paths
devices = list() # type: List[Device]
for disk in self.disks:
logger.debug("Processing disk {}".format(disk.path))
if not disk.available and not disk.ceph_device:
logger.debug(
("Ignoring disk {}. "
"Disk is unavailable due to {}".format(disk.path, disk.rejected_reasons))
)
continue
if not disk.available and disk.ceph_device and disk.lvs:
other_osdspec_affinity = ''
for lv in disk.lvs:
if lv['osdspec_affinity'] != self.spec.service_id:
other_osdspec_affinity = lv['osdspec_affinity']
break
if other_osdspec_affinity:
logger.debug("{} is already used in spec {}, "
"skipping it.".format(disk.path, other_osdspec_affinity))
continue
if not self._has_mandatory_idents(disk):
logger.debug(
"Ignoring disk {}. Missing mandatory idents".format(
disk.path))
continue
# break on this condition.
if self._limit_reached(device_filter, len(devices), disk.path):
logger.debug("Ignoring disk {}. Limit reached".format(
disk.path))
break
if disk in devices:
continue
if self.spec.filter_logic == 'AND':
if not all(m.compare(disk) for m in FilterGenerator(device_filter)):
logger.debug(
"Ignoring disk {}. Not all filter did match the disk".format(
disk.path))
continue
if self.spec.filter_logic == 'OR':
if not any(m.compare(disk) for m in FilterGenerator(device_filter)):
logger.debug(
"Ignoring disk {}. No filter matched the disk".format(
disk.path))
continue
logger.debug('Adding disk {}'.format(disk.path))
devices.append(disk)
# This disk is already taken and must not be re-assigned.
for taken_device in devices:
if taken_device in self.disks:
self.disks.remove(taken_device)
return sorted([x for x in devices], key=lambda dev: dev.path)
def __repr__(self) -> str:
selection: Dict[str, List[str]] = {
'data devices': [d.path for d in self._data],
'wal_devices': [d.path for d in self._wal],
'db devices': [d.path for d in self._db],
'journal devices': [d.path for d in self._journal]
}
return "DeviceSelection({})".format(
', '.join('{}={}'.format(key, selection[key]) for key in selection.keys())
)
| 6,941 | 35.34555 | 100 |
py
|
null |
ceph-main/src/python-common/ceph/rgw/__init__.py
|
import logging
log = logging.getLogger(__name__)
| 50 | 11.75 | 33 |
py
|
null |
ceph-main/src/python-common/ceph/rgw/diff.py
|
class ZoneEPs:
def __init__(self):
self.endpoints = set()
def add(self, ep):
if not ep:
return
self.endpoints.add(ep)
def diff(self, zep):
return list(self.endpoints.difference(zep.endpoints))
def get_all(self):
for ep in self.endpoints:
yield ep
class RealmEPs:
def __init__(self):
self.zones = {}
def add(self, zone, ep=None):
if not zone:
return
z = self.zones.get(zone)
if not z:
z = ZoneEPs()
self.zones[zone] = z
z.add(ep)
def diff(self, rep):
result = {}
for z, zep in rep.zones.items():
myzep = self.zones.get(z)
if not myzep:
continue
d = myzep.diff(zep)
if len(d) > 0:
result[z] = myzep.diff(zep)
return result
def get_all(self):
for z, zep in self.zones.items():
eps = []
for ep in zep.get_all():
eps.append(ep)
yield z, eps
class RealmsEPs:
def __init__(self):
self.realms = {}
def add(self, realm, zone=None, ep=None):
if not realm:
return
r = self.realms.get(realm)
if not r:
r = RealmEPs()
self.realms[realm] = r
r.add(zone, ep)
def diff(self, rep):
result = {}
for r, rep in rep.realms.items():
myrealm = self.realms.get(r)
if not myrealm:
continue
d = myrealm.diff(rep)
if d:
result[r] = d
return result
def get_all(self):
result = {}
for r, rep in self.realms.items():
zs = {}
for z, eps in rep.get_all():
zs[z] = eps
result[r] = zs
return result
| 1,898 | 19.202128 | 61 |
py
|
null |
ceph-main/src/python-common/ceph/rgw/rgwam_core.py
|
# -*- mode:python -*-
# vim: ts=4 sw=4 smarttab expandtab
#
# Processed in Makefile to add python #! line and version variable
#
#
import random
import string
import json
import socket
import base64
import logging
import errno
from .types import RGWAMException, RGWAMCmdRunException, RGWPeriod, RGWUser, RealmToken
from .diff import RealmsEPs
DEFAULT_PORT = 8000
log = logging.getLogger(__name__)
def bool_str(x):
return 'true' if x else 'false'
def rand_alphanum_lower(k):
return ''.join(random.choices(string.ascii_lowercase + string.digits, k=k))
def gen_name(prefix, suffix_len):
return prefix + rand_alphanum_lower(suffix_len)
def set_or_gen(val, gen, prefix):
if val:
return val
if gen:
return gen_name(prefix, 8)
return None
def get_endpoints(endpoints, period=None):
if endpoints:
return endpoints
hostname = socket.getfqdn()
port = DEFAULT_PORT
while True:
ep = 'http://%s:%d' % (hostname, port)
if not period or not period.endpoint_exists(ep):
return ep
port += 1
class EnvArgs:
def __init__(self, mgr):
self.mgr = mgr
class EntityKey:
def __init__(self, name=None, id=None):
self.name = name
self.id = id
def safe_vals(ek):
if not ek:
return None, None
return ek.name, ek.id
class EntityName(EntityKey):
def __init__(self, name=None):
super().__init__(name=name)
class EntityID(EntityKey):
def __init__(self, id=None):
super().__init__(id=id)
class ZoneEnv:
def __init__(self, env: EnvArgs, realm: EntityKey = None, zg: EntityKey = None,
zone: EntityKey = None):
self.env = env
self.realm = realm
self.zg = zg
self.zone = zone
def set(self, env: EnvArgs = None, realm: EntityKey = None, zg: EntityKey = None,
zone: EntityKey = None):
if env:
self.env = env
if realm:
self.realm = realm
if zg:
self.zg = zg
if zone:
self.zone = zone
return self
def _init_entity(self, ek: EntityKey, gen, prefix):
name, id = EntityKey.safe_vals(ek)
name = set_or_gen(name, gen, prefix)
return EntityKey(name, id)
def init_realm(self, realm: EntityKey = None, gen=False):
self.realm = self._init_entity(realm, gen, 'realm-')
return self
def init_zg(self, zg: EntityKey = None, gen=False):
self.zg = self._init_entity(zg, gen, 'zg-')
return self
def init_zone(self, zone: EntityKey = None, gen=False):
self.zone = self._init_entity(zone, gen, 'zone-')
return self
def opt_arg(params, cmd, arg):
if arg:
params += [cmd, arg]
def opt_arg_bool(params, flag, arg):
if arg:
params += [flag]
class RGWCmdBase:
def __init__(self, prog, zone_env: ZoneEnv):
self.env = zone_env.env
self.mgr = self.env.mgr
self.prog = prog
self.cmd_suffix = []
if zone_env.realm:
opt_arg(self.cmd_suffix, '--rgw-realm', zone_env.realm.name)
opt_arg(self.cmd_suffix, '--realm-id', zone_env.realm.id)
if zone_env.zg:
opt_arg(self.cmd_suffix, '--rgw-zonegroup', zone_env.zg.name)
opt_arg(self.cmd_suffix, '--zonegroup-id', zone_env.zg.id)
if zone_env.zone:
opt_arg(self.cmd_suffix, '--rgw-zone', zone_env.zone.name)
opt_arg(self.cmd_suffix, '--zone-id', zone_env.zone.id)
def run(self, cmd):
args = cmd + self.cmd_suffix
cmd, returncode, stdout, stderr = self.mgr.tool_exec(self.prog, args)
log.debug('cmd=%s' % str(cmd))
log.debug('stdout=%s' % stdout)
if returncode != 0:
cmd_str = ' '.join(cmd)
log.error('ERROR: command exited with error status (%d): %s\nstdout=%s\nstderr=%s' %
(returncode, cmd_str, stdout, stderr))
raise RGWAMCmdRunException(cmd_str, -returncode, stdout, stderr)
return (stdout, stderr)
class RGWAdminCmd(RGWCmdBase):
def __init__(self, zone_env: ZoneEnv):
super().__init__('radosgw-admin', zone_env)
class RGWAdminJSONCmd(RGWAdminCmd):
def __init__(self, zone_env: ZoneEnv):
super().__init__(zone_env)
def run(self, cmd):
stdout, _ = RGWAdminCmd.run(self, cmd)
return json.loads(stdout)
class RGWCmd(RGWCmdBase):
def __init__(self, zone_env: ZoneEnv):
super().__init__('radosgw', zone_env)
class RealmOp:
def __init__(self, env: EnvArgs):
self.env = env
def list(self):
try:
ze = ZoneEnv(self.env)
params = ['realm', 'list']
output = RGWAdminJSONCmd(ze).run(params)
return output.get('realms') or []
except RGWAMException as e:
logging.info(f'Exception while listing realms {e.message}')
# in case the realm list is empty an exception is raised
return []
def get(self, realm: EntityKey = None):
ze = ZoneEnv(self.env, realm=realm)
params = ['realm', 'get']
return RGWAdminJSONCmd(ze).run(params)
def create(self, realm: EntityKey = None):
ze = ZoneEnv(self.env).init_realm(realm=realm, gen=True)
params = ['realm', 'create']
return RGWAdminJSONCmd(ze).run(params)
def pull(self, realm, url, access_key, secret):
params = ['realm',
'pull',
'--url', url,
'--access-key', access_key,
'--secret', secret]
ze = ZoneEnv(self.env, realm=realm)
return RGWAdminJSONCmd(ze).run(params)
class ZonegroupOp:
def __init__(self, env: EnvArgs):
self.env = env
def list(self):
try:
ze = ZoneEnv(self.env)
params = ['zonegroup', 'list']
output = RGWAdminJSONCmd(ze).run(params)
return output.get('zonegroups') or []
except RGWAMException as e:
logging.info(f'Exception while listing zonegroups {e.message}')
return []
def get(self, zonegroup: EntityKey = None):
ze = ZoneEnv(self.env)
params = ['zonegroup', 'get']
opt_arg(params, '--rgw-zonegroup', zonegroup)
return RGWAdminJSONCmd(ze).run(params)
def create(self, realm: EntityKey, zg: EntityKey = None, endpoints=None, is_master=True):
ze = ZoneEnv(self.env, realm=realm).init_zg(zg, gen=True)
params = ['zonegroup',
'create']
opt_arg_bool(params, '--master', is_master)
opt_arg(params, '--endpoints', endpoints)
stdout, _ = RGWAdminCmd(ze).run(params)
return json.loads(stdout)
def modify(self, realm: EntityKey, zg: EntityKey, endpoints=None):
ze = ZoneEnv(self.env, realm=realm, zg=zg)
params = ['zonegroup', 'modify']
opt_arg(params, '--endpoints', endpoints)
return RGWAdminJSONCmd(ze).run(params)
class ZoneOp:
def __init__(self, env: EnvArgs):
self.env = env
def list(self):
try:
ze = ZoneEnv(self.env)
params = ['zone', 'list']
output = RGWAdminJSONCmd(ze).run(params)
return output.get('zones') or []
except RGWAMException as e:
logging.info(f'Exception while listing zones {e.message}')
return []
def get(self, zone: EntityKey):
ze = ZoneEnv(self.env, zone=zone)
params = ['zone',
'get']
return RGWAdminJSONCmd(ze).run(params)
def create(self, realm: EntityKey, zonegroup: EntityKey, zone: EntityKey = None,
endpoints=None, is_master=True,
access_key=None, secret=None):
ze = ZoneEnv(self.env, realm=realm, zg=zonegroup).init_zone(zone, gen=True)
params = ['zone',
'create']
opt_arg_bool(params, '--master', is_master)
opt_arg(params, '--access-key', access_key)
opt_arg(params, '--secret', secret)
opt_arg(params, '--endpoints', endpoints)
return RGWAdminJSONCmd(ze).run(params)
def modify(self, zone: EntityKey, zg: EntityKey, is_master=None,
access_key=None, secret=None, endpoints=None):
ze = ZoneEnv(self.env, zone=zone, zg=zg)
params = ['zone',
'modify']
opt_arg_bool(params, '--master', is_master)
opt_arg(params, '--access-key', access_key)
opt_arg(params, '--secret', secret)
opt_arg(params, '--endpoints', endpoints)
return RGWAdminJSONCmd(ze).run(params)
class PeriodOp:
def __init__(self, env):
self.env = env
def update(self, realm: EntityKey, zonegroup: EntityKey, zone: EntityKey, commit=True):
master_zone_info = self.get_master_zone(realm, zonegroup)
master_zone = EntityName(master_zone_info['name']) if master_zone_info else zone
master_zonegroup_info = self.get_master_zonegroup(realm)
master_zonegroup = EntityName(master_zonegroup_info['name']) \
if master_zonegroup_info else zonegroup
ze = ZoneEnv(self.env, realm=realm, zg=master_zonegroup, zone=master_zone)
params = ['period', 'update']
opt_arg_bool(params, '--commit', commit)
return RGWAdminJSONCmd(ze).run(params)
def get_master_zone(self, realm, zonegroup=None):
try:
ze = ZoneEnv(self.env, realm=realm, zg=zonegroup)
params = ['zone', 'get']
return RGWAdminJSONCmd(ze).run(params)
except RGWAMCmdRunException:
return None
def get_master_zone_ep(self, realm, zonegroup=None):
try:
ze = ZoneEnv(self.env, realm=realm, zg=zonegroup)
params = ['period', 'get']
output = RGWAdminJSONCmd(ze).run(params)
for zg in output['period_map']['zonegroups']:
if not bool(zg['is_master']):
continue
for zone in zg['zones']:
if zone['id'] == zg['master_zone']:
return zone['endpoints']
return None
except RGWAMCmdRunException:
return None
def get_master_zonegroup(self, realm):
try:
ze = ZoneEnv(self.env, realm=realm)
params = ['zonegroup', 'get']
return RGWAdminJSONCmd(ze).run(params)
except RGWAMCmdRunException:
return None
def get(self, realm=None):
ze = ZoneEnv(self.env, realm=realm)
params = ['period', 'get']
return RGWAdminJSONCmd(ze).run(params)
class UserOp:
def __init__(self, env):
self.env = env
def create(self, zone: EntityKey, zg: EntityKey, uid=None, uid_prefix=None, display_name=None,
email=None, is_system=False):
ze = ZoneEnv(self.env, zone=zone, zg=zg)
u = uid or gen_name(uid_prefix or 'user-', 6)
dn = display_name or u
params = ['user',
'create',
'--uid', u,
'--display-name', dn]
opt_arg(params, '--email', email)
opt_arg_bool(params, '--system', is_system)
return RGWAdminJSONCmd(ze).run(params)
def info(self, zone: EntityKey, zg: EntityKey, uid=None, access_key=None):
ze = ZoneEnv(self.env, zone=zone, zg=zg)
params = ['user',
'info']
opt_arg(params, '--uid', uid)
opt_arg(params, '--access-key', access_key)
return RGWAdminJSONCmd(ze).run(params)
def rm(self, zone: EntityKey, zg: EntityKey, uid=None, access_key=None):
ze = ZoneEnv(self.env, zone=zone, zg=zg)
params = ['user',
'rm']
opt_arg(params, '--uid', uid)
opt_arg(params, '--access-key', access_key)
return RGWAdminCmd(ze).run(params)
def rm_key(self, zone: EntityKey, zg: EntityKey, access_key=None):
ze = ZoneEnv(self.env, zone=zone, zg=zg)
params = ['key',
'remove']
opt_arg(params, '--access-key', access_key)
return RGWAdminCmd(ze).run(params)
class RGWAM:
def __init__(self, env):
self.env = env
def realm_op(self):
return RealmOp(self.env)
def period_op(self):
return PeriodOp(self.env)
def zonegroup_op(self):
return ZonegroupOp(self.env)
def zone_op(self):
return ZoneOp(self.env)
def user_op(self):
return UserOp(self.env)
def get_realm(self, realm_name):
try:
realm_info = self.realm_op().get(EntityName(realm_name))
realm = EntityKey(realm_info['name'], realm_info['id'])
return realm
except RGWAMException:
raise None
def create_realm(self, realm_name):
try:
realm_info = self.realm_op().create(EntityName(realm_name))
realm = EntityKey(realm_info['name'], realm_info['id'])
logging.info(f'Created realm name={realm.name} id={realm.id}')
return realm
except RGWAMException as e:
raise RGWAMException('failed to create realm', e)
def create_zonegroup(self, realm, zonegroup_name, zonegroup_is_master, endpoints=None):
try:
zg_info = self.zonegroup_op().create(realm,
EntityName(zonegroup_name),
endpoints,
is_master=zonegroup_is_master)
zonegroup = EntityKey(zg_info['name'], zg_info['id'])
logging.info(f'Created zonegroup name={zonegroup.name} id={zonegroup.id}')
return zonegroup
except RGWAMException as e:
raise RGWAMException('failed to create zonegroup', e)
def create_zone(self, realm, zg, zone_name, zone_is_master, access_key=None,
secret=None, endpoints=None):
try:
zone_info = self.zone_op().create(realm, zg,
EntityName(zone_name),
endpoints,
is_master=zone_is_master,
access_key=access_key,
secret=secret)
zone = EntityKey(zone_info['name'], zone_info['id'])
logging.info(f'Created zone name={zone.name} id={zone.id}')
return zone
except RGWAMException as e:
raise RGWAMException('failed to create zone', e)
def create_system_user(self, realm, zonegroup, zone):
try:
sys_user_info = self.user_op().create(zone,
zonegroup,
uid=f'sysuser-{realm.name}',
uid_prefix='user-sys',
is_system=True)
sys_user = RGWUser(sys_user_info)
logging.info(f'Created system user: {sys_user.uid} on'
'{realm.name}/{zonegroup.name}/{zone.name}')
return sys_user
except RGWAMException as e:
raise RGWAMException('failed to create system user', e)
def create_normal_user(self, zg, zone, uid=None):
try:
user_info = self.user_op().create(zone, zg, uid=uid, is_system=False)
user = RGWUser(user_info)
logging.info('Created regular user {user.uid} on'
'{realm.name}/{zonegroup.name}/{zone.name}')
return user
except RGWAMException as e:
raise RGWAMException('failed to create user', e)
def update_period(self, realm, zg, zone=None):
try:
period_info = self.period_op().update(realm, zg, zone, commit=True)
period = RGWPeriod(period_info)
logging.info('Period: ' + period.id)
except RGWAMCmdRunException as e:
raise RGWAMException('failed to update period', e)
def realm_bootstrap(self, rgw_spec, start_radosgw=True):
realm_name = rgw_spec.rgw_realm
zonegroup_name = rgw_spec.rgw_zonegroup
zone_name = rgw_spec.rgw_zone
# Some sanity checks
if realm_name in self.realm_op().list():
raise RGWAMException(f'Realm {realm_name} already exists')
if zonegroup_name in self.zonegroup_op().list():
raise RGWAMException(f'Zonegroup {zonegroup_name} already exists')
if zone_name in self.zone_op().list():
raise RGWAMException(f'Zone {zone_name} already exists')
# Create RGW entities and update the period
realm = self.create_realm(realm_name)
zonegroup = self.create_zonegroup(realm, zonegroup_name, zonegroup_is_master=True)
zone = self.create_zone(realm, zonegroup, zone_name, zone_is_master=True)
self.update_period(realm, zonegroup)
# Create system user, normal user and update the master zone
sys_user = self.create_system_user(realm, zonegroup, zone)
rgw_acces_key = sys_user.get_key(0)
access_key = rgw_acces_key.access_key if rgw_acces_key else ''
secret = rgw_acces_key.secret_key if rgw_acces_key else ''
self.zone_op().modify(zone, zonegroup, None,
access_key, secret, endpoints=rgw_spec.zone_endpoints)
self.update_period(realm, zonegroup)
if start_radosgw and rgw_spec.zone_endpoints is None:
# Instruct the orchestrator to start RGW daemons, asynchronically, this will
# call back the rgw module to update the master zone with the corresponding endpoints
realm_token = RealmToken(realm_name,
realm.id,
None, # no endpoint
access_key, secret)
realm_token_b = realm_token.to_json().encode('utf-8')
realm_token_s = base64.b64encode(realm_token_b).decode('utf-8')
rgw_spec.rgw_realm_token = realm_token_s
rgw_spec.update_endpoints = True
self.env.mgr.apply_rgw(rgw_spec)
def realm_new_zone_creds(self, realm_name, endpoints, sys_uid):
try:
period_info = self.period_op().get(EntityName(realm_name))
except RGWAMException as e:
raise RGWAMException('failed to fetch period info', e)
period = RGWPeriod(period_info)
master_zg = EntityID(period.master_zonegroup)
master_zone = EntityID(period.master_zone)
try:
zone_info = self.zone_op().get(zone=master_zone)
except RGWAMException as e:
raise RGWAMException('failed to access master zone', e)
zone_id = zone_info['id']
logging.info('Period: ' + period.id)
logging.info('Master zone: ' + period.master_zone)
if period.master_zone != zone_id:
return (-errno.EINVAL, '', 'Command needs to run on master zone')
ep = ''
if not endpoints:
eps = period.get_zone_endpoints(period.master_zonegroup, period.master_zone)
else:
eps = endpoints.split(',')
if len(eps) > 0:
ep = eps[0]
try:
sys_user_info = self.user_op().create(master_zone, master_zg, uid=sys_uid,
uid_prefix='user-sys', is_system=True)
except RGWAMException as e:
raise RGWAMException('failed to create system user', e)
sys_user = RGWUser(sys_user_info)
logging.info('Created system user: %s' % sys_user.uid)
sys_access_key = ''
sys_secret = ''
if len(sys_user.keys) > 0:
sys_access_key = sys_user.keys[0].access_key
sys_secret = sys_user.keys[0].secret_key
realm_token = RealmToken(realm_name, period.realm_id, ep, sys_access_key, sys_secret)
logging.info(realm_token.to_json())
realm_token_b = realm_token.to_json().encode('utf-8')
return (0, 'Realm Token: %s' % base64.b64encode(realm_token_b).decode('utf-8'), '')
def realm_rm_zone_creds(self, realm_token_b64):
if not realm_token_b64:
raise RGWAMException('missing realm token')
realm_token = RealmToken.from_base64_str(realm_token_b64)
try:
period_info = self.period_op().get(EntityID(realm_token.realm_id))
except RGWAMException as e:
raise RGWAMException('failed to fetch period info', e)
period = RGWPeriod(period_info)
master_zg = EntityID(period.master_zonegroup)
master_zone = EntityID(period.master_zone)
logging.info('Period: ' + period.id)
logging.info('Master zone: ' + period.master_zone)
try:
zone_info = self.zone_op().get(zone=master_zone)
except RGWAMException as e:
raise RGWAMException('failed to access master zone', e)
if period.master_zone != zone_info['id']:
return (-errno.EINVAL, '', 'Command needs to run on master zone')
access_key = realm_token.access_key
try:
user_info = self.user_op().info(master_zone, master_zg, access_key=access_key)
except RGWAMException as e:
raise RGWAMException('failed to get the system user information', e)
user = RGWUser(user_info)
only_key = True
for k in user.keys:
if k.access_key != access_key:
only_key = False
break
success_message = ''
if only_key:
# the only key this user has is the one defined in the token
# can remove the user completely
try:
self.user_op().rm(master_zone, master_zg, uid=user.uid)
except RGWAMException as e:
raise RGWAMException('failed removing user ' + user, user.uid, e)
success_message = 'Removed uid ' + user.uid
else:
try:
self.user_op().rm_key(master_zone, master_zg, access_key=access_key)
except RGWAMException as e:
raise RGWAMException('failed removing access key ' +
access_key + '(uid = ' + user.uid + ')', e)
success_message = 'Removed access key ' + access_key + '(uid = ' + user.uid + ')'
return (0, success_message, '')
def zone_modify(self, realm_name, zonegroup_name, zone_name, endpoints, realm_token_b64):
if not realm_token_b64:
raise RGWAMException('missing realm access config')
if zone_name is None:
raise RGWAMException('Zone name is a mandatory parameter')
realm_token = RealmToken.from_base64_str(realm_token_b64)
access_key = realm_token.access_key
secret = realm_token.secret
realm_name = realm_token.realm_name
realm_id = realm_token.realm_id
logging.info(f'Using realm {realm_name} {realm_id}')
realm = EntityID(realm_id)
period_info = self.period_op().get(realm)
period = RGWPeriod(period_info)
logging.info('Period: ' + period.id)
zonegroup = period.find_zonegroup_by_name(zonegroup_name)
if not zonegroup:
raise RGWAMException(f'zonegroup {zonegroup_name} not found')
zg = EntityName(zonegroup.name)
zone = EntityName(zone_name)
master_zone_info = self.period_op().get_master_zone(realm, zg)
success_message = f'Modified zone {realm_name} {zonegroup_name} {zone_name}'
logging.info(success_message)
try:
self.zone_op().modify(zone, zg, access_key=access_key,
secret=secret, endpoints=','.join(endpoints))
# we only update the zonegroup endpoints if the zone being
# modified is a master zone
if zone_name == master_zone_info['name']:
self.zonegroup_op().modify(realm, zg, endpoints=','.join(endpoints))
except RGWAMException as e:
raise RGWAMException('failed to modify zone', e)
# done, let's update the period
try:
period_info = self.period_op().update(realm, zg, zone, True)
except RGWAMException as e:
raise RGWAMException('failed to update period', e)
period = RGWPeriod(period_info)
logging.debug(period.to_json())
return (0, success_message, '')
def get_realms_info(self):
realms_info = []
for realm_name in self.realm_op().list():
realm = self.get_realm(realm_name)
master_zone_inf = self.period_op().get_master_zone(realm)
zone_ep = self.period_op().get_master_zone_ep(realm)
if master_zone_inf and 'system_key' in master_zone_inf:
access_key = master_zone_inf['system_key']['access_key']
secret = master_zone_inf['system_key']['secret_key']
else:
access_key = ''
secret = ''
realms_info.append({"realm_name": realm_name,
"realm_id": realm.id,
"master_zone_id": master_zone_inf['id'] if master_zone_inf else '',
"endpoint": zone_ep[0] if zone_ep else None,
"access_key": access_key,
"secret": secret})
return realms_info
def zone_create(self, rgw_spec, start_radosgw):
if not rgw_spec.rgw_realm_token:
raise RGWAMException('missing realm token')
if rgw_spec.rgw_zone is None:
raise RGWAMException('Zone name is a mandatory parameter')
if rgw_spec.rgw_zone in self.zone_op().list():
raise RGWAMException(f'Zone {rgw_spec.rgw_zone} already exists')
realm_token = RealmToken.from_base64_str(rgw_spec.rgw_realm_token)
if realm_token.endpoint is None:
raise RGWAMException('Provided realm token has no endpoint')
access_key = realm_token.access_key
secret = realm_token.secret
try:
realm_info = self.realm_op().pull(EntityName(realm_token.realm_name),
realm_token.endpoint, access_key, secret)
except RGWAMException as e:
raise RGWAMException('failed to pull realm', e)
logging.info(f"Pulled realm {realm_info['name']} ({realm_info['id']})")
realm_name = realm_info['name']
realm_id = realm_info['id']
realm = EntityID(realm_id)
period_info = self.period_op().get(realm)
period = RGWPeriod(period_info)
logging.info('Period: ' + period.id)
zonegroup = period.get_master_zonegroup()
if not zonegroup:
raise RGWAMException('Cannot find master zonegroup of realm {realm_name}')
zone = self.create_zone(realm, zonegroup, rgw_spec.rgw_zone,
False, # secondary zone
access_key, secret, endpoints=rgw_spec.zone_endpoints)
self.update_period(realm, zonegroup, zone)
period = RGWPeriod(period_info)
logging.debug(period.to_json())
if start_radosgw and rgw_spec.zone_endpoints is None:
secondary_realm_token = RealmToken(realm_name,
realm_id,
None, # no endpoint
realm_token.access_key,
realm_token.secret)
realm_token_b = secondary_realm_token.to_json().encode('utf-8')
realm_token_s = base64.b64encode(realm_token_b).decode('utf-8')
rgw_spec.update_endpoints = True
rgw_spec.rgw_token = realm_token_s
rgw_spec.rgw_zonegroup = zonegroup.name # master zonegroup is used
self.env.mgr.apply_rgw(rgw_spec)
def _get_daemon_eps(self, realm_name=None, zonegroup_name=None, zone_name=None):
# get running daemons info
service_name = None
if realm_name and zone_name:
service_name = 'rgw.%s.%s' % (realm_name, zone_name)
daemon_type = 'rgw'
daemon_id = None
hostname = None
refresh = True
daemons = self.env.mgr.list_daemons(service_name,
daemon_type,
daemon_id=daemon_id,
host=hostname,
refresh=refresh)
rep = RealmsEPs()
for s in daemons:
for p in s.ports:
svc_id = s.service_id()
sp = svc_id.split('.')
if len(sp) < 2:
log.error('ERROR: service id cannot be parsed: (svc_id=%s)' % svc_id)
continue
svc_realm = sp[0]
svc_zone = sp[1]
if realm_name and svc_realm != realm_name:
log.debug('skipping realm %s' % svc_realm)
continue
if zone_name and svc_zone != zone_name:
log.debug('skipping zone %s' % svc_zone)
continue
ep = 'http://%s:%d' % (s.hostname, p) # ssl?
rep.add(svc_realm, svc_zone, ep)
return rep
def _get_rgw_eps(self, realm_name=None, zonegroup_name=None, zone_name=None):
rep = RealmsEPs()
try:
realms = self.realm_op().list()
except RGWAMException as e:
raise RGWAMException('failed to list realms', e)
zones_map = {}
for realm in realms:
if realm_name and realm != realm_name:
log.debug('skipping realm %s' % realm)
continue
period_info = self.period_op().get(EntityName(realm))
period = RGWPeriod(period_info)
zones_map[realm] = {}
for zg in period.iter_zonegroups():
if zonegroup_name and zg.name != zonegroup_name:
log.debug('skipping zonegroup %s' % zg.name)
continue
for zone in zg.iter_zones():
if zone_name and zone.name != zone_name:
log.debug('skipping zone %s' % zone.name)
continue
zones_map[realm][zone.name] = zg.name
if len(zone.endpoints) == 0:
rep.add(realm, zone.name, None)
continue
for ep in zone.endpoints:
rep.add(realm, zone.name, ep)
return (rep, zones_map)
def realm_reconcile(self, realm_name=None, zonegroup_name=None, zone_name=None, update=False):
daemon_rep = self._get_daemon_eps(realm_name, zonegroup_name, zone_name)
rgw_rep, zones_map = self._get_rgw_eps(realm_name, zonegroup_name, zone_name)
diff = daemon_rep.diff(rgw_rep)
diffj = json.dumps(diff)
if not update:
return (0, diffj, '')
for realm, realm_diff in diff.items():
for zone, endpoints in realm_diff.items():
zg = zones_map[realm][zone]
try:
self.zone_op().modify(EntityName(zone), EntityName(zg),
endpoints=','.join(diff[realm][zone]))
except RGWAMException as e:
raise RGWAMException('failed to modify zone', e)
try:
self.period_op().update(EntityName(realm), EntityName(zg), EntityName(zone), True)
except RGWAMException as e:
raise RGWAMException('failed to update period', e)
return (0, 'Updated: ' + diffj, '')
def run_radosgw(self, port=None, log_file=None, debug_ms=None, debug_rgw=None):
fe_cfg = 'beast'
if port:
fe_cfg += ' port=%s' % port
params = ['--rgw-frontends', fe_cfg]
if log_file:
params += ['--log-file', log_file]
if debug_ms:
params += ['--debug-ms', debug_ms]
if debug_rgw:
params += ['--debug-rgw', debug_rgw]
(retcode, stdout, stderr) = RGWCmd(self.env).run(params)
return (retcode, stdout, stderr)
| 32,681 | 33.842217 | 99 |
py
|
null |
ceph-main/src/python-common/ceph/rgw/types.py
|
import json
import base64
import binascii
import errno
from abc import abstractmethod
class RGWAMException(Exception):
def __init__(self, message, orig=None):
if orig:
self.message = message + ': ' + orig.message
self.retcode = orig.retcode
self.stdout = orig.stdout
self.stderr = orig.stdout
else:
self.message = message
self.retcode = -errno.EINVAL
self.stdout = ''
self.stderr = message
class RGWAMCmdRunException(RGWAMException):
def __init__(self, cmd, retcode, stdout, stderr):
super().__init__('Command error (%d): %s\nstdout:%s\nstderr:%s' %
(retcode, cmd, stdout, stderr))
self.retcode = retcode
self.stdout = stdout
self.stderr = stderr
class RGWAMEnvMgr:
@abstractmethod
def tool_exec(self, prog, args):
pass
@abstractmethod
def apply_rgw(self, spec):
pass
@abstractmethod
def list_daemons(self, service_name, daemon_type=None, daemon_id=None, hostname=None,
refresh=True):
pass
class JSONObj:
def to_json(self):
return json.dumps(self, default=lambda o: o.__dict__, indent=4)
class RealmToken(JSONObj):
def __init__(self, realm_name, realm_id, endpoint, access_key, secret):
self.realm_name = realm_name
self.realm_id = realm_id
self.endpoint = endpoint
self.access_key = access_key
self.secret = secret
@classmethod
def from_base64_str(cls, realm_token_b64):
try:
realm_token_b = base64.b64decode(realm_token_b64)
realm_token_s = realm_token_b.decode('utf-8')
realm_token = json.loads(realm_token_s)
return cls(**realm_token)
except binascii.Error:
return None
class RGWZone(JSONObj):
def __init__(self, zone_dict):
self.id = zone_dict['id']
self.name = zone_dict['name']
self.endpoints = zone_dict['endpoints']
class RGWZoneGroup(JSONObj):
def __init__(self, zg_dict):
self.id = zg_dict['id']
self.name = zg_dict['name']
self.api_name = zg_dict['api_name']
self.is_master = zg_dict['is_master']
self.endpoints = zg_dict['endpoints']
self.zones_by_id = {}
self.zones_by_name = {}
self.all_endpoints = []
for zone in zg_dict['zones']:
z = RGWZone(zone)
self.zones_by_id[zone['id']] = z
self.zones_by_name[zone['name']] = z
self.all_endpoints += z.endpoints
def endpoint_exists(self, endpoint):
for ep in self.all_endpoints:
if ep == endpoint:
return True
return False
def get_zone_endpoints(self, zone_id):
z = self.zones_by_id.get(zone_id)
if not z:
return None
return z.endpoints
def iter_zones(self):
for zone in self.zones_by_id.values():
yield zone
class RGWPeriod(JSONObj):
def __init__(self, period_dict):
self.id = period_dict['id']
self.epoch = period_dict['epoch']
self.master_zone = period_dict['master_zone']
self.master_zonegroup = period_dict['master_zonegroup']
self.realm_name = period_dict['realm_name']
self.realm_id = period_dict['realm_id']
pm = period_dict['period_map']
self.zonegroups_by_id = {}
self.zonegroups_by_name = {}
for zg in pm['zonegroups']:
self.zonegroups_by_id[zg['id']] = RGWZoneGroup(zg)
self.zonegroups_by_name[zg['name']] = RGWZoneGroup(zg)
def endpoint_exists(self, endpoint):
for _, zg in self.zonegroups_by_id.items():
if zg.endpoint_exists(endpoint):
return True
return False
def find_zonegroup_by_name(self, zonegroup):
if not zonegroup:
return self.find_zonegroup_by_id(self.master_zonegroup)
return self.zonegroups_by_name.get(zonegroup)
def get_master_zonegroup(self):
return self.find_zonegroup_by_id(self.master_zonegroup)
def find_zonegroup_by_id(self, zonegroup):
return self.zonegroups_by_id.get(zonegroup)
def get_zone_endpoints(self, zonegroup_id, zone_id):
zg = self.zonegroups_by_id.get(zonegroup_id)
if not zg:
return None
return zg.get_zone_endpoints(zone_id)
def iter_zonegroups(self):
for zg in self.zonegroups_by_id.values():
yield zg
class RGWAccessKey(JSONObj):
def __init__(self, d):
self.uid = d['user']
self.access_key = d['access_key']
self.secret_key = d['secret_key']
class RGWUser(JSONObj):
def __init__(self, d):
self.uid = d['user_id']
self.display_name = d['display_name']
self.email = d['email']
self.keys = []
for k in d['keys']:
self.keys.append(RGWAccessKey(k))
is_system = d.get('system') or 'false'
self.system = (is_system == 'true')
def add_key(self, access_key, secret):
self.keys.append(RGWAccessKey({'user': self.uid,
'access_key': access_key,
'secret_key': secret}))
def get_key(self, index):
return self.keys[index] if index < len(self.keys) else None
| 5,423 | 28.005348 | 89 |
py
|
null |
ceph-main/src/python-common/ceph/tests/__init__.py
| 0 | 0 | 0 |
py
|
|
null |
ceph-main/src/python-common/ceph/tests/factories.py
|
from ceph.deployment.inventory import Device
class InventoryFactory(object):
def __init__(self):
self.taken_paths = []
def _make_path(self, ident='b'):
return "/dev/{}{}".format(self.prefix, ident)
def _find_new_path(self):
cnt = 0
if len(self.taken_paths) >= 25:
raise Exception(
"Double-character disks are not implemetend. Maximum amount"
"of disks reached.")
while self.path in self.taken_paths:
ident = chr(ord('b') + cnt)
self.path = "/dev/{}{}".format(self.prefix, ident)
cnt += 1
def assemble(self):
if self.empty:
return {}
self._find_new_path()
inventory_sample = {
'available': self.available,
'lvs': [],
'path': self.path,
'rejected_reasons': self.rejected_reason,
'sys_api': {
'human_readable_size': self.human_readable_size,
'locked': 1,
'model': self.model,
'nr_requests': '256',
'partitions':
{ # partitions are not as relevant for now, todo for later
'sda1': {
'sectors': '41940992',
'sectorsize': 512,
'size': self.human_readable_size,
'start': '2048'
}
},
'path': self.path,
'removable': '0',
'rev': '',
'ro': '0',
'rotational': str(self.rotational),
'sas_address': '',
'sas_device_handle': '',
'scheduler_mode': 'mq-deadline',
'sectors': 0,
'sectorsize': '512',
'size': self.size,
'support_discard': '',
'vendor': self.vendor
}
}
if self.available:
self.taken_paths.append(self.path)
return inventory_sample
return {}
def _init(self, **kwargs):
self.prefix = 'sd'
self.path = kwargs.get('path', self._make_path())
self.human_readable_size = kwargs.get('human_readable_size',
'50.00 GB')
self.vendor = kwargs.get('vendor', 'samsung')
self.model = kwargs.get('model', '42-RGB')
self.available = kwargs.get('available', True)
self.rejected_reason = kwargs.get('rejected_reason', [''])
self.rotational = kwargs.get('rotational', '1')
if not self.available:
self.rejected_reason = ['locked']
self.empty = kwargs.get('empty', False)
self.size = kwargs.get('size', 5368709121)
def produce(self, pieces=1, **kwargs):
if kwargs.get('path') and pieces > 1:
raise Exception("/path/ and /pieces/ are mutually exclusive")
# Move to custom init to track _taken_paths.
# class is invoked once in each context.
# if disks with different properties are being created
# we'd have to re-init the class and loose track of the
# taken_paths
self._init(**kwargs)
return [self.assemble() for x in range(0, pieces)]
class DeviceFactory(object):
def __init__(self, device_setup):
self.device_setup = device_setup
self.pieces = device_setup.get('pieces', 1)
self.device_conf = device_setup.get('device_config', {})
def produce(self):
return [Device(**self.device_conf) for x in range(0, self.pieces)]
| 3,626 | 34.558824 | 76 |
py
|
null |
ceph-main/src/python-common/ceph/tests/test_datetime.py
|
import datetime
import pytest
from ceph.utils import datetime_now, datetime_to_str, str_to_datetime
def test_datetime_to_str_1():
dt = datetime.datetime.now()
assert type(datetime_to_str(dt)) is str
def test_datetime_to_str_2():
# note: tz isn't specified in the string, so explicitly store this as UTC
dt = datetime.datetime.strptime(
'2019-04-24T17:06:53.039991',
'%Y-%m-%dT%H:%M:%S.%f'
).replace(tzinfo=datetime.timezone.utc)
assert datetime_to_str(dt) == '2019-04-24T17:06:53.039991Z'
def test_datetime_to_str_3():
dt = datetime.datetime.strptime('2020-11-02T04:40:12.748172-0800',
'%Y-%m-%dT%H:%M:%S.%f%z')
assert datetime_to_str(dt) == '2020-11-02T12:40:12.748172Z'
def test_str_to_datetime_1():
dt = str_to_datetime('2020-03-03T09:21:43.636153304Z')
assert type(dt) is datetime.datetime
assert dt.tzinfo is not None
def test_str_to_datetime_2():
dt = str_to_datetime('2020-03-03T15:52:30.136257504-0600')
assert type(dt) is datetime.datetime
assert dt.tzinfo is not None
def test_str_to_datetime_3():
dt = str_to_datetime('2020-03-03T15:52:30.136257504')
assert type(dt) is datetime.datetime
assert dt.tzinfo is not None
def test_str_to_datetime_invalid_format_1():
with pytest.raises(ValueError):
str_to_datetime('2020-03-03 15:52:30.136257504')
def test_str_to_datetime_invalid_format_2():
with pytest.raises(ValueError):
str_to_datetime('2020-03-03')
def test_datetime_now_1():
dt = str_to_datetime('2020-03-03T09:21:43.636153304Z')
dt_now = datetime_now()
assert type(dt_now) is datetime.datetime
assert dt_now.tzinfo is not None
assert dt < dt_now
| 1,744 | 27.145161 | 77 |
py
|
null |
ceph-main/src/python-common/ceph/tests/test_disk_selector.py
|
# flake8: noqa
import pytest
from ceph.deployment.drive_selection.matchers import _MatchInvalid
from ceph.deployment.inventory import Devices, Device
from ceph.deployment.drive_group import DriveGroupSpec, DeviceSelection, \
DriveGroupValidationError
from ceph.deployment import drive_selection
from ceph.deployment.service_spec import PlacementSpec
from ceph.tests.factories import InventoryFactory
from ceph.tests.utils import _mk_inventory, _mk_device
class TestMatcher(object):
""" Test Matcher base class
"""
def test_get_disk_key_3(self):
"""
virtual is False
key is found
retrun value of key is expected
"""
disk_map = Device(path='/dev/vdb', sys_api={'foo': 'bar'})
ret = drive_selection.Matcher('foo', 'bar')._get_disk_key(disk_map)
assert ret is disk_map.sys_api.get('foo')
def test_get_disk_key_4(self):
"""
virtual is False
key is not found
expect raise Exception
"""
disk_map = Device(path='/dev/vdb')
with pytest.raises(Exception):
drive_selection.Matcher('bar', 'foo')._get_disk_key(disk_map)
pytest.fail("No disk_key found for foo or None")
class TestSubstringMatcher(object):
def test_compare(self):
disk_dict = Device(path='/dev/vdb', sys_api=dict(model='samsung'))
matcher = drive_selection.SubstringMatcher('model', 'samsung')
ret = matcher.compare(disk_dict)
assert ret is True
def test_compare_false(self):
disk_dict = Device(path='/dev/vdb', sys_api=dict(model='nothing_matching'))
matcher = drive_selection.SubstringMatcher('model', 'samsung')
ret = matcher.compare(disk_dict)
assert ret is False
class TestEqualityMatcher(object):
def test_compare(self):
disk_dict = Device(path='/dev/vdb', sys_api=dict(rotates='1'))
matcher = drive_selection.EqualityMatcher('rotates', '1')
ret = matcher.compare(disk_dict)
assert ret is True
def test_compare_false(self):
disk_dict = Device(path='/dev/vdb', sys_api=dict(rotates='1'))
matcher = drive_selection.EqualityMatcher('rotates', '0')
ret = matcher.compare(disk_dict)
assert ret is False
class TestAllMatcher(object):
def test_compare(self):
disk_dict = Device(path='/dev/vdb')
matcher = drive_selection.AllMatcher('all', 'True')
ret = matcher.compare(disk_dict)
assert ret is True
def test_compare_value_not_true(self):
disk_dict = Device(path='/dev/vdb')
matcher = drive_selection.AllMatcher('all', 'False')
ret = matcher.compare(disk_dict)
assert ret is True
class TestSizeMatcher(object):
def test_parse_filter_exact(self):
""" Testing exact notation with 20G """
matcher = drive_selection.SizeMatcher('size', '20G')
assert isinstance(matcher.exact, tuple)
assert matcher.exact[0] == '20'
assert matcher.exact[1] == 'GB'
def test_parse_filter_exact_GB_G(self):
""" Testing exact notation with 20G """
matcher = drive_selection.SizeMatcher('size', '20GB')
assert isinstance(matcher.exact, tuple)
assert matcher.exact[0] == '20'
assert matcher.exact[1] == 'GB'
def test_parse_filter_high_low(self):
""" Testing high-low notation with 20G:50G """
matcher = drive_selection.SizeMatcher('size', '20G:50G')
assert isinstance(matcher.exact, tuple)
assert matcher.low[0] == '20'
assert matcher.high[0] == '50'
assert matcher.low[1] == 'GB'
assert matcher.high[1] == 'GB'
def test_parse_filter_max_high(self):
""" Testing high notation with :50G """
matcher = drive_selection.SizeMatcher('size', ':50G')
assert isinstance(matcher.exact, tuple)
assert matcher.high[0] == '50'
assert matcher.high[1] == 'GB'
def test_parse_filter_min_low(self):
""" Testing low notation with 20G: """
matcher = drive_selection.SizeMatcher('size', '50G:')
assert isinstance(matcher.exact, tuple)
assert matcher.low[0] == '50'
assert matcher.low[1] == 'GB'
def test_to_byte_KB(self):
""" I doubt anyone ever thought we'd need to understand KB """
ret = drive_selection.SizeMatcher('size', '4K').to_byte(('4', 'KB'))
assert ret == 4 * 1e+3
def test_to_byte_GB(self):
""" Pretty nonesense test.."""
ret = drive_selection.SizeMatcher('size', '10G').to_byte(('10', 'GB'))
assert ret == 10 * 1e+9
def test_to_byte_MB(self):
""" Pretty nonesense test.."""
ret = drive_selection.SizeMatcher('size', '10M').to_byte(('10', 'MB'))
assert ret == 10 * 1e+6
def test_to_byte_TB(self):
""" Pretty nonesense test.."""
ret = drive_selection.SizeMatcher('size', '10T').to_byte(('10', 'TB'))
assert ret == 10 * 1e+12
def test_to_byte_PB(self):
""" Expect to raise """
with pytest.raises(_MatchInvalid):
drive_selection.SizeMatcher('size', '10P').to_byte(('10', 'PB'))
assert 'Unit \'P\' is not supported'
def test_compare_exact(self):
matcher = drive_selection.SizeMatcher('size', '20GB')
disk_dict = Device(path='/dev/vdb', sys_api=dict(size='20.00 GB'))
ret = matcher.compare(disk_dict)
assert ret is True
def test_compare_exact_decimal(self):
matcher = drive_selection.SizeMatcher('size', '20.12GB')
disk_dict = Device(path='/dev/vdb', sys_api=dict(size='20.12 GB'))
ret = matcher.compare(disk_dict)
assert ret is True
@pytest.mark.parametrize("test_input,expected", [
("1.00 GB", False),
("20.00 GB", True),
("50.00 GB", True),
("100.00 GB", True),
("101.00 GB", False),
("1101.00 GB", False),
])
def test_compare_high_low(self, test_input, expected):
matcher = drive_selection.SizeMatcher('size', '20GB:100GB')
disk_dict = Device(path='/dev/vdb', sys_api=dict(size=test_input))
ret = matcher.compare(disk_dict)
assert ret is expected
@pytest.mark.parametrize("test_input,expected", [
("1.00 GB", True),
("20.00 GB", True),
("50.00 GB", True),
("100.00 GB", False),
("101.00 GB", False),
("1101.00 GB", False),
])
def test_compare_high(self, test_input, expected):
matcher = drive_selection.SizeMatcher('size', ':50GB')
disk_dict = Device(path='/dev/vdb', sys_api=dict(size=test_input))
ret = matcher.compare(disk_dict)
assert ret is expected
@pytest.mark.parametrize("test_input,expected", [
("1.00 GB", False),
("20.00 GB", False),
("50.00 GB", True),
("100.00 GB", True),
("101.00 GB", True),
("1101.00 GB", True),
])
def test_compare_low(self, test_input, expected):
matcher = drive_selection.SizeMatcher('size', '50GB:')
disk_dict = Device(path='/dev/vdb', sys_api=dict(size=test_input))
ret = matcher.compare(disk_dict)
assert ret is expected
@pytest.mark.parametrize("test_input,expected", [
("1.00 GB", False),
("20.00 GB", False),
("50.00 GB", False),
("100.00 GB", False),
("101.00 GB", False),
("1101.00 GB", True),
("9.10 TB", True),
])
def test_compare_at_least_1TB(self, test_input, expected):
matcher = drive_selection.SizeMatcher('size', '1TB:')
disk_dict = Device(path='/dev/sdz', sys_api=dict(size=test_input))
ret = matcher.compare(disk_dict)
assert ret is expected
def test_compare_raise(self):
matcher = drive_selection.SizeMatcher('size', 'None')
disk_dict = Device(path='/dev/vdb', sys_api=dict(size='20.00 GB'))
with pytest.raises(Exception):
matcher.compare(disk_dict)
pytest.fail("Couldn't parse size")
@pytest.mark.parametrize("test_input,expected", [
("10G", ('10', 'GB')),
("20GB", ('20', 'GB')),
("10g", ('10', 'GB')),
("20gb", ('20', 'GB')),
])
def test_get_k_v(self, test_input, expected):
assert drive_selection.SizeMatcher('size', '10G')._get_k_v(test_input) == expected
@pytest.mark.parametrize("test_input,expected", [
("10G", ('GB')),
("10g", ('GB')),
("20GB", ('GB')),
("20gb", ('GB')),
("20TB", ('TB')),
("20tb", ('TB')),
("20T", ('TB')),
("20t", ('TB')),
("20MB", ('MB')),
("20mb", ('MB')),
("20M", ('MB')),
("20m", ('MB')),
])
def test_parse_suffix(self, test_input, expected):
assert drive_selection.SizeMatcher('size', '10G')._parse_suffix(test_input) == expected
@pytest.mark.parametrize("test_input,expected", [
("G", 'GB'),
("GB", 'GB'),
("TB", 'TB'),
("T", 'TB'),
("MB", 'MB'),
("M", 'MB'),
])
def test_normalize_suffix(self, test_input, expected):
assert drive_selection.SizeMatcher('10G', 'size')._normalize_suffix(test_input) == expected
def test_normalize_suffix_raises(self):
with pytest.raises(_MatchInvalid):
drive_selection.SizeMatcher('10P', 'size')._normalize_suffix("P")
pytest.fail("Unit 'P' not supported")
class TestDriveGroup(object):
@pytest.fixture(scope='class')
def test_fix(self, empty=None):
def make_sample_data(empty=empty,
data_limit=0,
wal_limit=0,
db_limit=0,
osds_per_device='',
disk_format='bluestore'):
raw_sample_bluestore = {
'service_type': 'osd',
'service_id': 'foo',
'placement': {'host_pattern': 'data*'},
'data_devices': {
'size': '30G:50G',
'model': '42-RGB',
'vendor': 'samsung',
'limit': data_limit
},
'wal_devices': {
'model': 'fast',
'limit': wal_limit
},
'db_devices': {
'size': ':20G',
'limit': db_limit
},
'db_slots': 5,
'wal_slots': 5,
'block_wal_size': '5G',
'block_db_size': '10G',
'objectstore': disk_format,
'osds_per_device': osds_per_device,
'encrypted': True,
}
raw_sample_filestore = {
'service_type': 'osd',
'service_id': 'foo',
'placement': {'host_pattern': 'data*'},
'objectstore': 'filestore',
'data_devices': {
'size': '30G:50G',
'model': 'foo',
'vendor': '1x',
'limit': data_limit
},
'journal_devices': {
'size': ':20G'
},
'journal_size': '5G',
'osds_per_device': osds_per_device,
'encrypted': True,
}
if disk_format == 'filestore':
raw_sample = raw_sample_filestore
else:
raw_sample = raw_sample_bluestore
if empty:
raw_sample = {
'service_type': 'osd',
'service_id': 'foo',
'placement': {'host_pattern': 'data*'},
'data_devices': {
'all': True
},
}
dgo = DriveGroupSpec.from_json(raw_sample)
return dgo
return make_sample_data
def test_encryption_prop(self, test_fix):
test_fix = test_fix()
assert test_fix.encrypted is True
def test_encryption_prop_empty(self, test_fix):
test_fix = test_fix(empty=True)
assert test_fix.encrypted is False
def test_db_slots_prop(self, test_fix):
test_fix = test_fix()
assert test_fix.db_slots == 5
def test_db_slots_prop_empty(self, test_fix):
test_fix = test_fix(empty=True)
assert test_fix.db_slots is None
def test_wal_slots_prop(self, test_fix):
test_fix = test_fix()
assert test_fix.wal_slots == 5
def test_wal_slots_prop_empty(self, test_fix):
test_fix = test_fix(empty=True)
assert test_fix.wal_slots is None
def test_block_wal_size_prop(self, test_fix):
test_fix = test_fix()
assert test_fix.block_wal_size == '5G'
def test_block_wal_size_prop_empty(self, test_fix):
test_fix = test_fix(empty=True)
assert test_fix.block_wal_size is None
def test_block_db_size_prop(self, test_fix):
test_fix = test_fix()
assert test_fix.block_db_size == '10G'
def test_block_db_size_prop_empty(self, test_fix):
test_fix = test_fix(empty=True)
assert test_fix.block_db_size is None
def test_data_devices_prop(self, test_fix):
test_fix = test_fix()
assert test_fix.data_devices == DeviceSelection(
model='42-RGB',
size='30G:50G',
vendor='samsung',
limit=0,
)
def test_data_devices_prop_empty(self, test_fix):
test_fix = test_fix(empty=True)
assert test_fix.db_devices is None
def test_db_devices_prop(self, test_fix):
test_fix = test_fix()
assert test_fix.db_devices == DeviceSelection(
size=':20G',
limit=0,
)
def test_db_devices_prop_empty(self, test_fix):
test_fix = test_fix(empty=True)
assert test_fix.db_devices is None
def test_wal_device_prop(self, test_fix):
test_fix = test_fix()
assert test_fix.wal_devices == DeviceSelection(
model='fast',
limit=0,
)
def test_wal_device_prop_empty(self, test_fix):
test_fix = test_fix(empty=True)
assert test_fix.wal_devices is None
def test_bluestore_format_prop(self, test_fix):
test_fix = test_fix(disk_format='bluestore')
assert test_fix.objectstore == 'bluestore'
def test_default_format_prop(self, test_fix):
test_fix = test_fix(empty=True)
assert test_fix.objectstore == 'bluestore'
def test_osds_per_device(self, test_fix):
test_fix = test_fix(osds_per_device='3')
assert test_fix.osds_per_device == '3'
def test_osds_per_device_default(self, test_fix):
test_fix = test_fix()
assert test_fix.osds_per_device == ''
def test_journal_size_empty(self, test_fix):
test_fix = test_fix(empty=True)
assert test_fix.journal_size is None
@pytest.fixture
def inventory(self, available=True):
def make_sample_data(available=available,
data_devices=10,
wal_devices=0,
db_devices=2,
human_readable_size_data='50.00 GB',
human_readable_size_wal='20.00 GB',
size=5368709121,
human_readable_size_db='20.00 GB'):
factory = InventoryFactory()
inventory_sample = []
data_disks = factory.produce(
pieces=data_devices,
available=available,
size=size,
human_readable_size=human_readable_size_data)
wal_disks = factory.produce(
pieces=wal_devices,
human_readable_size=human_readable_size_wal,
rotational='0',
model='ssd_type_model',
size=size,
available=available)
db_disks = factory.produce(
pieces=db_devices,
human_readable_size=human_readable_size_db,
rotational='0',
size=size,
model='ssd_type_model',
available=available)
inventory_sample.extend(data_disks)
inventory_sample.extend(wal_disks)
inventory_sample.extend(db_disks)
return Devices(devices=inventory_sample)
return make_sample_data
class TestDriveSelection(object):
testdata = [
(
DriveGroupSpec(
placement=PlacementSpec(host_pattern='*'),
service_id='foobar',
data_devices=DeviceSelection(all=True)),
_mk_inventory(_mk_device() * 5),
['/dev/sda', '/dev/sdb', '/dev/sdc', '/dev/sdd', '/dev/sde'], []
),
(
DriveGroupSpec(
placement=PlacementSpec(host_pattern='*'),
service_id='foobar',
data_devices=DeviceSelection(all=True, limit=3),
db_devices=DeviceSelection(all=True)
),
_mk_inventory(_mk_device() * 5),
['/dev/sda', '/dev/sdb', '/dev/sdc'], ['/dev/sdd', '/dev/sde']
),
(
DriveGroupSpec(
placement=PlacementSpec(host_pattern='*'),
service_id='foobar',
data_devices=DeviceSelection(rotational=True),
db_devices=DeviceSelection(rotational=False)
),
_mk_inventory(_mk_device(rotational=False) + _mk_device(rotational=True)),
['/dev/sdb'], ['/dev/sda']
),
(
DriveGroupSpec(
placement=PlacementSpec(host_pattern='*'),
service_id='foobar',
data_devices=DeviceSelection(rotational=True),
db_devices=DeviceSelection(rotational=False)
),
_mk_inventory(_mk_device(rotational=True)*2 + _mk_device(rotational=False)),
['/dev/sda', '/dev/sdb'], ['/dev/sdc']
),
(
DriveGroupSpec(
placement=PlacementSpec(host_pattern='*'),
service_id='foobar',
data_devices=DeviceSelection(rotational=True),
db_devices=DeviceSelection(rotational=False)
),
_mk_inventory(_mk_device(rotational=True)*2),
['/dev/sda', '/dev/sdb'], []
),
]
@pytest.mark.parametrize("spec,inventory,expected_data,expected_db", testdata)
def test_disk_selection(self, spec, inventory, expected_data, expected_db):
sel = drive_selection.DriveSelection(spec, inventory)
assert [d.path for d in sel.data_devices()] == expected_data
assert [d.path for d in sel.db_devices()] == expected_db
def test_disk_selection_raise(self):
spec = DriveGroupSpec(
placement=PlacementSpec(host_pattern='*'),
service_id='foobar',
data_devices=DeviceSelection(size='wrong'),
)
inventory = _mk_inventory(_mk_device(rotational=True)*2)
m = 'Failed to validate OSD spec "foobar.data_devices": No filters applied'
with pytest.raises(DriveGroupValidationError, match=m):
drive_selection.DriveSelection(spec, inventory)
| 19,479 | 33.785714 | 99 |
py
|
null |
ceph-main/src/python-common/ceph/tests/test_drive_group.py
|
# flake8: noqa
import re
import pytest
import yaml
from ceph.deployment import drive_selection, translate
from ceph.deployment.hostspec import HostSpec, SpecValidationError
from ceph.deployment.inventory import Device
from ceph.deployment.service_spec import PlacementSpec
from ceph.tests.utils import _mk_inventory, _mk_device
from ceph.deployment.drive_group import DriveGroupSpec, DeviceSelection, \
DriveGroupValidationError
@pytest.mark.parametrize("test_input",
[
( # new style json
"""service_type: osd
service_id: testing_drivegroup
placement:
host_pattern: hostname
crush_device_class: ssd
data_devices:
paths:
- /dev/sda
"""
),
(
"""service_type: osd
service_id: testing_drivegroup
placement:
host_pattern: hostname
data_devices:
paths:
- path: /dev/sda
crush_device_class: ssd"""
),
(
"""service_type: osd
service_id: testing_drivegroup
placement:
host_pattern: hostname
spec:
osds_per_device: 2
data_devices:
paths:
- path: /dev/sda
crush_device_class: hdd"""
),
])
def test_DriveGroup(test_input):
dg = DriveGroupSpec.from_json(yaml.safe_load(test_input))
assert dg.service_id == 'testing_drivegroup'
assert all([isinstance(x, Device) for x in dg.data_devices.paths])
if isinstance(dg.data_devices.paths[0].path, str):
assert dg.data_devices.paths[0].path == '/dev/sda'
@pytest.mark.parametrize("match,test_input",
[
(
re.escape('Service Spec is not an (JSON or YAML) object. got "None"'),
''
),
(
'Failed to validate OSD spec "<unnamed>": `placement` required',
"""data_devices:
all: True
"""
),
(
'Failed to validate OSD spec "mydg.data_devices": device selection cannot be empty', """
service_type: osd
service_id: mydg
placement:
host_pattern: '*'
data_devices:
limit: 1
"""
),
(
'Failed to validate OSD spec "mydg": filter_logic must be either <AND> or <OR>', """
service_type: osd
service_id: mydg
placement:
host_pattern: '*'
data_devices:
all: True
filter_logic: XOR
"""
),
(
'Failed to validate OSD spec "mydg": `data_devices` element is required.', """
service_type: osd
service_id: mydg
placement:
host_pattern: '*'
spec:
db_devices:
model: model
"""
),
(
'Failed to validate OSD spec "mydg.db_devices": Filtering for `unknown_key` is not supported', """
service_type: osd
service_id: mydg
placement:
host_pattern: '*'
spec:
db_devices:
unknown_key: 1
"""
),
(
'Failed to validate OSD spec "mydg": Feature `unknown_key` is not supported', """
service_type: osd
service_id: mydg
placement:
host_pattern: '*'
spec:
db_devices:
all: true
unknown_key: 1
"""
),
])
def test_DriveGroup_fail(match, test_input):
with pytest.raises(SpecValidationError, match=match):
osd_spec = DriveGroupSpec.from_json(yaml.safe_load(test_input))
osd_spec.validate()
def test_drivegroup_pattern():
dg = DriveGroupSpec(
PlacementSpec(host_pattern='node[1-3]'),
service_id='foobar',
data_devices=DeviceSelection(all=True))
assert dg.placement.filter_matching_hostspecs([HostSpec('node{}'.format(i)) for i in range(10)]) == ['node1', 'node2', 'node3']
def test_drive_selection():
devs = DeviceSelection(paths=['/dev/sda'])
spec = DriveGroupSpec(
PlacementSpec('node_name'),
service_id='foobar',
data_devices=devs)
assert all([isinstance(x, Device) for x in spec.data_devices.paths])
assert spec.data_devices.paths[0].path == '/dev/sda'
with pytest.raises(DriveGroupValidationError, match='exclusive'):
ds = DeviceSelection(paths=['/dev/sda'], rotational=False)
ds.validate('')
def test_ceph_volume_command_0():
spec = DriveGroupSpec(placement=PlacementSpec(host_pattern='*'),
service_id='foobar',
data_devices=DeviceSelection(all=True)
)
spec.validate()
inventory = _mk_inventory(_mk_device()*2)
sel = drive_selection.DriveSelection(spec, inventory)
cmds = translate.to_ceph_volume(sel, []).run()
assert all(cmd == 'lvm batch --no-auto /dev/sda /dev/sdb --yes --no-systemd' for cmd in cmds), f'Expected {cmd} in {cmds}'
def test_ceph_volume_command_1():
spec = DriveGroupSpec(placement=PlacementSpec(host_pattern='*'),
service_id='foobar',
data_devices=DeviceSelection(rotational=True),
db_devices=DeviceSelection(rotational=False)
)
spec.validate()
inventory = _mk_inventory(_mk_device(rotational=True)*2 + _mk_device(rotational=False)*2)
sel = drive_selection.DriveSelection(spec, inventory)
cmds = translate.to_ceph_volume(sel, []).run()
assert all(cmd == ('lvm batch --no-auto /dev/sda /dev/sdb '
'--db-devices /dev/sdc /dev/sdd --yes --no-systemd') for cmd in cmds), f'Expected {cmd} in {cmds}'
def test_ceph_volume_command_2():
spec = DriveGroupSpec(placement=PlacementSpec(host_pattern='*'),
service_id='foobar',
data_devices=DeviceSelection(size='200GB:350GB', rotational=True),
db_devices=DeviceSelection(size='200GB:350GB', rotational=False),
wal_devices=DeviceSelection(size='10G')
)
spec.validate()
inventory = _mk_inventory(_mk_device(rotational=True, size="300.00 GB")*2 +
_mk_device(rotational=False, size="300.00 GB")*2 +
_mk_device(size="10.0 GB", rotational=False)*2
)
sel = drive_selection.DriveSelection(spec, inventory)
cmds = translate.to_ceph_volume(sel, []).run()
assert all(cmd == ('lvm batch --no-auto /dev/sda /dev/sdb '
'--db-devices /dev/sdc /dev/sdd --wal-devices /dev/sde /dev/sdf '
'--yes --no-systemd') for cmd in cmds), f'Expected {cmd} in {cmds}'
def test_ceph_volume_command_3():
spec = DriveGroupSpec(placement=PlacementSpec(host_pattern='*'),
service_id='foobar',
data_devices=DeviceSelection(size='200GB:350GB', rotational=True),
db_devices=DeviceSelection(size='200GB:350GB', rotational=False),
wal_devices=DeviceSelection(size='10G'),
encrypted=True
)
spec.validate()
inventory = _mk_inventory(_mk_device(rotational=True, size="300.00 GB")*2 +
_mk_device(rotational=False, size="300.00 GB")*2 +
_mk_device(size="10.0 GB", rotational=False)*2
)
sel = drive_selection.DriveSelection(spec, inventory)
cmds = translate.to_ceph_volume(sel, []).run()
assert all(cmd == ('lvm batch --no-auto /dev/sda /dev/sdb '
'--db-devices /dev/sdc /dev/sdd '
'--wal-devices /dev/sde /dev/sdf --dmcrypt '
'--yes --no-systemd') for cmd in cmds), f'Expected {cmd} in {cmds}'
def test_ceph_volume_command_4():
spec = DriveGroupSpec(placement=PlacementSpec(host_pattern='*'),
service_id='foobar',
data_devices=DeviceSelection(size='200GB:350GB', rotational=True),
db_devices=DeviceSelection(size='200GB:350GB', rotational=False),
wal_devices=DeviceSelection(size='10G'),
block_db_size='500M',
block_wal_size='500M',
osds_per_device=3,
encrypted=True
)
spec.validate()
inventory = _mk_inventory(_mk_device(rotational=True, size="300.00 GB")*2 +
_mk_device(rotational=False, size="300.00 GB")*2 +
_mk_device(size="10.0 GB", rotational=False)*2
)
sel = drive_selection.DriveSelection(spec, inventory)
cmds = translate.to_ceph_volume(sel, []).run()
assert all(cmd == ('lvm batch --no-auto /dev/sda /dev/sdb '
'--db-devices /dev/sdc /dev/sdd --wal-devices /dev/sde /dev/sdf '
'--block-wal-size 500M --block-db-size 500M --dmcrypt '
'--osds-per-device 3 --yes --no-systemd') for cmd in cmds), f'Expected {cmd} in {cmds}'
def test_ceph_volume_command_5():
spec = DriveGroupSpec(placement=PlacementSpec(host_pattern='*'),
service_id='foobar',
data_devices=DeviceSelection(rotational=True),
objectstore='filestore'
)
with pytest.raises(DriveGroupValidationError):
spec.validate()
inventory = _mk_inventory(_mk_device(rotational=True)*2)
sel = drive_selection.DriveSelection(spec, inventory)
cmds = translate.to_ceph_volume(sel, []).run()
assert all(cmd == 'lvm batch --no-auto /dev/sda /dev/sdb --filestore --yes --no-systemd' for cmd in cmds), f'Expected {cmd} in {cmds}'
def test_ceph_volume_command_6():
spec = DriveGroupSpec(placement=PlacementSpec(host_pattern='*'),
service_id='foobar',
data_devices=DeviceSelection(rotational=False),
journal_devices=DeviceSelection(rotational=True),
journal_size='500M',
objectstore='filestore'
)
with pytest.raises(DriveGroupValidationError):
spec.validate()
inventory = _mk_inventory(_mk_device(rotational=True)*2 + _mk_device(rotational=False)*2)
sel = drive_selection.DriveSelection(spec, inventory)
cmds = translate.to_ceph_volume(sel, []).run()
assert all(cmd == ('lvm batch --no-auto /dev/sdc /dev/sdd '
'--journal-size 500M --journal-devices /dev/sda /dev/sdb '
'--filestore --yes --no-systemd') for cmd in cmds), f'Expected {cmd} in {cmds}'
def test_ceph_volume_command_7():
spec = DriveGroupSpec(placement=PlacementSpec(host_pattern='*'),
service_id='foobar',
data_devices=DeviceSelection(all=True),
osd_id_claims={'host1': ['0', '1']}
)
spec.validate()
inventory = _mk_inventory(_mk_device(rotational=True)*2)
sel = drive_selection.DriveSelection(spec, inventory)
cmds = translate.to_ceph_volume(sel, ['0', '1']).run()
assert all(cmd == 'lvm batch --no-auto /dev/sda /dev/sdb --osd-ids 0 1 --yes --no-systemd' for cmd in cmds), f'Expected {cmd} in {cmds}'
def test_ceph_volume_command_8():
spec = DriveGroupSpec(placement=PlacementSpec(host_pattern='*'),
service_id='foobar',
data_devices=DeviceSelection(rotational=True, model='INTEL SSDS'),
db_devices=DeviceSelection(model='INTEL SSDP'),
filter_logic='OR',
osd_id_claims={}
)
spec.validate()
inventory = _mk_inventory(_mk_device(rotational=True, size='1.82 TB', model='ST2000DM001-1ER1') + # data
_mk_device(rotational=False, size="223.0 GB", model='INTEL SSDSC2KG24') + # data
_mk_device(rotational=False, size="349.0 GB", model='INTEL SSDPED1K375GA') # wal/db
)
sel = drive_selection.DriveSelection(spec, inventory)
cmds = translate.to_ceph_volume(sel, []).run()
assert all(cmd == 'lvm batch --no-auto /dev/sda /dev/sdb --db-devices /dev/sdc --yes --no-systemd' for cmd in cmds), f'Expected {cmd} in {cmds}'
def test_ceph_volume_command_9():
spec = DriveGroupSpec(placement=PlacementSpec(host_pattern='*'),
service_id='foobar',
data_devices=DeviceSelection(all=True),
data_allocate_fraction=0.8
)
spec.validate()
inventory = _mk_inventory(_mk_device()*2)
sel = drive_selection.DriveSelection(spec, inventory)
cmds = translate.to_ceph_volume(sel, []).run()
assert all(cmd == 'lvm batch --no-auto /dev/sda /dev/sdb --data-allocate-fraction 0.8 --yes --no-systemd' for cmd in cmds), f'Expected {cmd} in {cmds}'
@pytest.mark.parametrize("test_input_base",
[
(
"""service_type: osd
service_id: testing_drivegroup
placement:
host_pattern: hostname
crush_device_class: ssd
data_devices:
paths:
- /dev/sda
"""
),
])
def test_ceph_volume_command_10(test_input_base):
spec = DriveGroupSpec.from_json(yaml.safe_load(test_input_base))
spec.validate()
drive = drive_selection.DriveSelection(spec, spec.data_devices.paths)
cmds = translate.to_ceph_volume(drive, []).run()
assert all(cmd == 'lvm batch --no-auto /dev/sda --crush-device-class ssd --yes --no-systemd' for cmd in cmds), f'Expected {cmd} in {cmds}'
@pytest.mark.parametrize("test_input1",
[
(
"""service_type: osd
service_id: testing_drivegroup
placement:
host_pattern: hostname
crush_device_class: ssd
data_devices:
paths:
- path: /dev/sda
crush_device_class: hdd
- path: /dev/sdb
crush_device_class: hdd
"""
),
])
def test_ceph_volume_command_11(test_input1):
spec = DriveGroupSpec.from_json(yaml.safe_load(test_input1))
spec.validate()
drive = drive_selection.DriveSelection(spec, spec.data_devices.paths)
cmds = translate.to_ceph_volume(drive, []).run()
assert all(cmd == 'lvm batch --no-auto /dev/sda /dev/sdb --crush-device-class hdd --yes --no-systemd' for cmd in cmds), f'Expected {cmd} in {cmds}'
@pytest.mark.parametrize("test_input2",
[
(
"""service_type: osd
service_id: testing_drivegroup
placement:
host_pattern: hostname
crush_device_class: ssd
data_devices:
paths:
- path: /dev/sda
crush_device_class: hdd
- path: /dev/sdb
"""
),
])
def test_ceph_volume_command_12(test_input2):
spec = DriveGroupSpec.from_json(yaml.safe_load(test_input2))
spec.validate()
drive = drive_selection.DriveSelection(spec, spec.data_devices.paths)
cmds = translate.to_ceph_volume(drive, []).run()
assert (cmds[0] == 'lvm batch --no-auto /dev/sdb --crush-device-class ssd --yes --no-systemd') # noqa E501
assert (cmds[1] == 'lvm batch --no-auto /dev/sda --crush-device-class hdd --yes --no-systemd') # noqa E501
@pytest.mark.parametrize("test_input3",
[
(
"""service_type: osd
service_id: testing_drivegroup
placement:
host_pattern: hostname
data_devices:
paths:
- path: /dev/sda
crush_device_class: hdd
- path: /dev/sdb
"""
),
])
def test_ceph_volume_command_13(test_input3):
spec = DriveGroupSpec.from_json(yaml.safe_load(test_input3))
spec.validate()
drive = drive_selection.DriveSelection(spec, spec.data_devices.paths)
cmds = translate.to_ceph_volume(drive, []).run()
assert (cmds[0] == 'lvm batch --no-auto /dev/sdb --yes --no-systemd') # noqa E501
assert (cmds[1] == 'lvm batch --no-auto /dev/sda --crush-device-class hdd --yes --no-systemd') # noqa E501
@pytest.mark.parametrize("test_input4",
[
(
"""service_type: osd
service_id: testing_drivegroup
placement:
host_pattern: hostname
data_devices:
paths:
- crush_device_class: hdd
"""
),
])
def test_ceph_volume_command_14(test_input4):
with pytest.raises(DriveGroupValidationError, match='Device path'):
spec = DriveGroupSpec.from_json(yaml.safe_load(test_input4))
spec.validate()
def test_raw_ceph_volume_command_0():
spec = DriveGroupSpec(placement=PlacementSpec(host_pattern='*'),
service_id='foobar',
data_devices=DeviceSelection(rotational=True),
db_devices=DeviceSelection(rotational=False),
method='raw',
)
spec.validate()
inventory = _mk_inventory(_mk_device(rotational=True) + # data
_mk_device(rotational=True) + # data
_mk_device(rotational=False) + # db
_mk_device(rotational=False) # db
)
exp_cmds = ['raw prepare --bluestore --data /dev/sda --block.db /dev/sdc', 'raw prepare --bluestore --data /dev/sdb --block.db /dev/sdd']
sel = drive_selection.DriveSelection(spec, inventory)
cmds = translate.to_ceph_volume(sel, []).run()
assert all(cmd in exp_cmds for cmd in cmds), f'Expected {exp_cmds} to match {cmds}'
def test_raw_ceph_volume_command_1():
spec = DriveGroupSpec(placement=PlacementSpec(host_pattern='*'),
service_id='foobar',
data_devices=DeviceSelection(rotational=True),
db_devices=DeviceSelection(rotational=False),
method='raw',
)
spec.validate()
inventory = _mk_inventory(_mk_device(rotational=True) + # data
_mk_device(rotational=True) + # data
_mk_device(rotational=False) # db
)
sel = drive_selection.DriveSelection(spec, inventory)
with pytest.raises(ValueError):
cmds = translate.to_ceph_volume(sel, []).run()
@pytest.mark.parametrize("test_input5",
[
(
"""service_type: osd
service_id: testing_drivegroup
placement:
host_pattern: hostname
method: raw
data_devices:
paths:
- path: /dev/sda
crush_device_class: hdd
- path: /dev/sdb
crush_device_class: hdd
- path: /dev/sdc
crush_device_class: hdd
db_devices:
paths:
- /dev/sdd
- /dev/sde
- /dev/sdf
"""
),
])
def test_raw_ceph_volume_command_2(test_input5):
spec = DriveGroupSpec.from_json(yaml.safe_load(test_input5))
spec.validate()
drive = drive_selection.DriveSelection(spec, spec.data_devices.paths)
cmds = translate.to_ceph_volume(drive, []).run()
assert cmds[0] == 'raw prepare --bluestore --data /dev/sda --block.db /dev/sdd --crush-device-class hdd'
assert cmds[1] == 'raw prepare --bluestore --data /dev/sdb --block.db /dev/sde --crush-device-class hdd'
assert cmds[2] == 'raw prepare --bluestore --data /dev/sdc --block.db /dev/sdf --crush-device-class hdd'
@pytest.mark.parametrize("test_input6",
[
(
"""service_type: osd
service_id: testing_drivegroup
placement:
host_pattern: hostname
method: raw
data_devices:
paths:
- path: /dev/sda
crush_device_class: hdd
- path: /dev/sdb
crush_device_class: hdd
- path: /dev/sdc
crush_device_class: ssd
db_devices:
paths:
- /dev/sdd
- /dev/sde
- /dev/sdf
"""
),
])
def test_raw_ceph_volume_command_3(test_input6):
spec = DriveGroupSpec.from_json(yaml.safe_load(test_input6))
spec.validate()
drive = drive_selection.DriveSelection(spec, spec.data_devices.paths)
cmds = translate.to_ceph_volume(drive, []).run()
assert cmds[0] == 'raw prepare --bluestore --data /dev/sda --block.db /dev/sdd --crush-device-class hdd'
assert cmds[1] == 'raw prepare --bluestore --data /dev/sdb --block.db /dev/sde --crush-device-class hdd'
assert cmds[2] == 'raw prepare --bluestore --data /dev/sdc --block.db /dev/sdf --crush-device-class ssd'
@pytest.mark.parametrize("test_input7",
[
(
"""service_type: osd
service_id: testing_drivegroup
placement:
host_pattern: hostname
method: raw
data_devices:
paths:
- path: /dev/sda
crush_device_class: hdd
- path: /dev/sdb
crush_device_class: nvme
- path: /dev/sdc
crush_device_class: ssd
db_devices:
paths:
- /dev/sdd
- /dev/sde
- /dev/sdf
wal_devices:
paths:
- /dev/sdg
- /dev/sdh
- /dev/sdi
"""
),
])
def test_raw_ceph_volume_command_4(test_input7):
spec = DriveGroupSpec.from_json(yaml.safe_load(test_input7))
spec.validate()
drive = drive_selection.DriveSelection(spec, spec.data_devices.paths)
cmds = translate.to_ceph_volume(drive, []).run()
assert cmds[0] == 'raw prepare --bluestore --data /dev/sda --block.db /dev/sdd --block.wal /dev/sdg --crush-device-class hdd'
assert cmds[1] == 'raw prepare --bluestore --data /dev/sdb --block.db /dev/sdf --block.wal /dev/sdi --crush-device-class nvme'
assert cmds[2] == 'raw prepare --bluestore --data /dev/sdc --block.db /dev/sde --block.wal /dev/sdh --crush-device-class ssd'
| 20,737 | 33.971332 | 155 |
py
|
null |
ceph-main/src/python-common/ceph/tests/test_hostspec.py
|
# flake8: noqa
import json
import yaml
import pytest
from ceph.deployment.hostspec import HostSpec, SpecValidationError
@pytest.mark.parametrize(
"test_input,expected",
[
({"hostname": "foo"}, HostSpec('foo')),
({"hostname": "foo", "labels": "l1"}, HostSpec('foo', labels=['l1'])),
({"hostname": "foo", "labels": ["l1", "l2"]}, HostSpec('foo', labels=['l1', 'l2'])),
({"hostname": "foo", "location": {"rack": "foo"}}, HostSpec('foo', location={'rack': 'foo'})),
]
)
def test_parse_host_specs(test_input, expected):
hs = HostSpec.from_json(test_input)
assert hs == expected
@pytest.mark.parametrize(
"bad_input",
[
({"hostname": "foo", "labels": 124}),
({"hostname": "foo", "labels": {"a", "b"}}),
({"hostname": "foo", "labels": {"a", "b"}}),
({"hostname": "foo", "labels": ["a", 2]}),
({"hostname": "foo", "location": "rack=bar"}),
({"hostname": "foo", "location": ["a"]}),
({"hostname": "foo", "location": {"rack", 1}}),
({"hostname": "foo", "location": {1: "rack"}}),
]
)
def test_parse_host_specs(bad_input):
with pytest.raises(SpecValidationError):
hs = HostSpec.from_json(bad_input)
| 1,239 | 29.243902 | 102 |
py
|
null |
ceph-main/src/python-common/ceph/tests/test_inventory.py
|
import datetime
import json
import os
import pytest
from ceph.deployment.inventory import Devices, Device
from ceph.utils import datetime_now
@pytest.mark.parametrize("filename",
[
os.path.dirname(__file__) + '/c-v-inventory.json',
os.path.dirname(__file__) + '/../../../pybind/mgr/test_orchestrator/du'
'mmy_data.json',
])
def test_from_json(filename):
with open(filename) as f:
data = json.load(f)
if 'inventory' in data:
data = data['inventory']
ds = Devices.from_json(data)
assert len(ds.devices) == len(data)
assert Devices.from_json(ds.to_json()) == ds
class TestDevicesEquality():
created_time1 = datetime_now()
created_time2 = created_time1 + datetime.timedelta(seconds=30)
@pytest.mark.parametrize(
"old_devices, new_devices, expected_equal",
[
( # identical list should be equal
Devices([Device('/dev/sdb', available=True, created=created_time1),
Device('/dev/sdc', available=True, created=created_time1)]),
Devices([Device('/dev/sdb', available=True, created=created_time1),
Device('/dev/sdc', available=True, created=created_time1)]),
True,
),
( # differing only in created time should still be equal
Devices([Device('/dev/sdb', available=True, created=created_time1),
Device('/dev/sdc', available=True, created=created_time1)]),
Devices([Device('/dev/sdb', available=True, created=created_time2),
Device('/dev/sdc', available=True, created=created_time2)]),
True,
),
( # differing in some other field should make them not equal
Devices([Device('/dev/sdb', available=True, created=created_time1),
Device('/dev/sdc', available=True, created=created_time1)]),
Devices([Device('/dev/sdb', available=False, created=created_time1),
Device('/dev/sdc', available=True, created=created_time1)]),
False,
),
( # different amount of devices should not pass equality
Devices([Device('/dev/sdb', available=True, created=created_time1),
Device('/dev/sdc', available=True, created=created_time1)]),
Devices([Device('/dev/sdb', available=True, created=created_time1),
Device('/dev/sdc', available=True, created=created_time1),
Device('/dev/sdd', available=True, created=created_time1)]),
False,
),
( # differing order should not affect equality
Devices([Device('/dev/sdb', available=True, created=created_time1),
Device('/dev/sdc', available=True, created=created_time1)]),
Devices([Device('/dev/sdc', available=True, created=created_time1),
Device('/dev/sdb', available=True, created=created_time1)]),
True,
),
])
def test_equality(self, old_devices, new_devices, expected_equal):
assert (old_devices == new_devices) == expected_equal
| 3,427 | 46.611111 | 100 |
py
|
null |
ceph-main/src/python-common/ceph/tests/test_service_spec.py
|
# flake8: noqa
import json
import re
import yaml
import pytest
from ceph.deployment.service_spec import (
AlertManagerSpec,
ArgumentSpec,
CustomContainerSpec,
GrafanaSpec,
HostPlacementSpec,
IscsiServiceSpec,
NFSServiceSpec,
PlacementSpec,
PrometheusSpec,
RGWSpec,
ServiceSpec,
)
from ceph.deployment.drive_group import DriveGroupSpec
from ceph.deployment.hostspec import SpecValidationError
@pytest.mark.parametrize("test_input,expected, require_network",
[("myhost", ('myhost', '', ''), False),
("myhost=sname", ('myhost', '', 'sname'), False),
("myhost:10.1.1.10", ('myhost', '10.1.1.10', ''), True),
("myhost:10.1.1.10=sname", ('myhost', '10.1.1.10', 'sname'), True),
("myhost:10.1.1.0/32", ('myhost', '10.1.1.0/32', ''), True),
("myhost:10.1.1.0/32=sname", ('myhost', '10.1.1.0/32', 'sname'), True),
("myhost:[v1:10.1.1.10:6789]", ('myhost', '[v1:10.1.1.10:6789]', ''), True),
("myhost:[v1:10.1.1.10:6789]=sname", ('myhost', '[v1:10.1.1.10:6789]', 'sname'), True),
("myhost:[v1:10.1.1.10:6789,v2:10.1.1.11:3000]", ('myhost', '[v1:10.1.1.10:6789,v2:10.1.1.11:3000]', ''), True),
("myhost:[v1:10.1.1.10:6789,v2:10.1.1.11:3000]=sname", ('myhost', '[v1:10.1.1.10:6789,v2:10.1.1.11:3000]', 'sname'), True),
])
def test_parse_host_placement_specs(test_input, expected, require_network):
ret = HostPlacementSpec.parse(test_input, require_network=require_network)
assert ret == expected
assert str(ret) == test_input
ps = PlacementSpec.from_string(test_input)
assert ps.pretty_str() == test_input
assert ps == PlacementSpec.from_string(ps.pretty_str())
# Testing the old verbose way of generating json. Don't remove:
assert ret == HostPlacementSpec.from_json({
'hostname': ret.hostname,
'network': ret.network,
'name': ret.name
})
assert ret == HostPlacementSpec.from_json(ret.to_json())
@pytest.mark.parametrize(
"spec, raise_exception, msg",
[
(GrafanaSpec(protocol=''), True, '^Invalid protocol'),
(GrafanaSpec(protocol='invalid'), True, '^Invalid protocol'),
(GrafanaSpec(protocol='-http'), True, '^Invalid protocol'),
(GrafanaSpec(protocol='-https'), True, '^Invalid protocol'),
(GrafanaSpec(protocol='http'), False, ''),
(GrafanaSpec(protocol='https'), False, ''),
(GrafanaSpec(anonymous_access=False), True, '^Either initial'), # we require inital_admin_password if anonymous_access is False
(GrafanaSpec(anonymous_access=False, initial_admin_password='test'), False, ''),
])
def test_apply_grafana(spec: GrafanaSpec, raise_exception: bool, msg: str):
if raise_exception:
with pytest.raises(SpecValidationError, match=msg):
spec.validate()
else:
spec.validate()
@pytest.mark.parametrize(
"spec, raise_exception, msg",
[
# Valid retention_time values (valid units: 'y', 'w', 'd', 'h', 'm', 's')
(PrometheusSpec(retention_time='1y'), False, ''),
(PrometheusSpec(retention_time=' 10w '), False, ''),
(PrometheusSpec(retention_time=' 1348d'), False, ''),
(PrometheusSpec(retention_time='2000h '), False, ''),
(PrometheusSpec(retention_time='173847m'), False, ''),
(PrometheusSpec(retention_time='200s'), False, ''),
(PrometheusSpec(retention_time=' '), False, ''), # default value will be used
# Invalid retention_time values
(PrometheusSpec(retention_time='100k'), True, '^Invalid retention time'), # invalid unit
(PrometheusSpec(retention_time='10'), True, '^Invalid retention time'), # no unit
(PrometheusSpec(retention_time='100.00y'), True, '^Invalid retention time'), # invalid value and valid unit
(PrometheusSpec(retention_time='100.00k'), True, '^Invalid retention time'), # invalid value and invalid unit
(PrometheusSpec(retention_time='---'), True, '^Invalid retention time'), # invalid value
# Valid retention_size values (valid units: 'B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB')
(PrometheusSpec(retention_size='123456789B'), False, ''),
(PrometheusSpec(retention_size=' 200KB'), False, ''),
(PrometheusSpec(retention_size='99999MB '), False, ''),
(PrometheusSpec(retention_size=' 10GB '), False, ''),
(PrometheusSpec(retention_size='100TB'), False, ''),
(PrometheusSpec(retention_size='500PB'), False, ''),
(PrometheusSpec(retention_size='200EB'), False, ''),
(PrometheusSpec(retention_size=' '), False, ''), # default value will be used
# Invalid retention_size values
(PrometheusSpec(retention_size='100b'), True, '^Invalid retention size'), # invalid unit (case sensitive)
(PrometheusSpec(retention_size='333kb'), True, '^Invalid retention size'), # invalid unit (case sensitive)
(PrometheusSpec(retention_size='2000'), True, '^Invalid retention size'), # no unit
(PrometheusSpec(retention_size='200.00PB'), True, '^Invalid retention size'), # invalid value and valid unit
(PrometheusSpec(retention_size='400.B'), True, '^Invalid retention size'), # invalid value and invalid unit
(PrometheusSpec(retention_size='10.000s'), True, '^Invalid retention size'), # invalid value and invalid unit
(PrometheusSpec(retention_size='...'), True, '^Invalid retention size'), # invalid value
# valid retention_size and valid retention_time
(PrometheusSpec(retention_time='1y', retention_size='100GB'), False, ''),
# invalid retention_time and valid retention_size
(PrometheusSpec(retention_time='1j', retention_size='100GB'), True, '^Invalid retention time'),
# valid retention_time and invalid retention_size
(PrometheusSpec(retention_time='1y', retention_size='100gb'), True, '^Invalid retention size'),
# valid retention_time and invalid retention_size
(PrometheusSpec(retention_time='1y', retention_size='100gb'), True, '^Invalid retention size'),
# invalid retention_time and invalid retention_size
(PrometheusSpec(retention_time='1i', retention_size='100gb'), True, '^Invalid retention time'),
])
def test_apply_prometheus(spec: PrometheusSpec, raise_exception: bool, msg: str):
if raise_exception:
with pytest.raises(SpecValidationError, match=msg):
spec.validate()
else:
spec.validate()
@pytest.mark.parametrize(
"test_input,expected",
[
('', "PlacementSpec()"),
("count:2", "PlacementSpec(count=2)"),
("3", "PlacementSpec(count=3)"),
("host1 host2", "PlacementSpec(hosts=[HostPlacementSpec(hostname='host1', network='', name=''), HostPlacementSpec(hostname='host2', network='', name='')])"),
("host1;host2", "PlacementSpec(hosts=[HostPlacementSpec(hostname='host1', network='', name=''), HostPlacementSpec(hostname='host2', network='', name='')])"),
("host1,host2", "PlacementSpec(hosts=[HostPlacementSpec(hostname='host1', network='', name=''), HostPlacementSpec(hostname='host2', network='', name='')])"),
("host1 host2=b", "PlacementSpec(hosts=[HostPlacementSpec(hostname='host1', network='', name=''), HostPlacementSpec(hostname='host2', network='', name='b')])"),
("host1=a host2=b", "PlacementSpec(hosts=[HostPlacementSpec(hostname='host1', network='', name='a'), HostPlacementSpec(hostname='host2', network='', name='b')])"),
("host1:1.2.3.4=a host2:1.2.3.5=b", "PlacementSpec(hosts=[HostPlacementSpec(hostname='host1', network='1.2.3.4', name='a'), HostPlacementSpec(hostname='host2', network='1.2.3.5', name='b')])"),
("myhost:[v1:10.1.1.10:6789]", "PlacementSpec(hosts=[HostPlacementSpec(hostname='myhost', network='[v1:10.1.1.10:6789]', name='')])"),
('2 host1 host2', "PlacementSpec(count=2, hosts=[HostPlacementSpec(hostname='host1', network='', name=''), HostPlacementSpec(hostname='host2', network='', name='')])"),
('label:foo', "PlacementSpec(label='foo')"),
('3 label:foo', "PlacementSpec(count=3, label='foo')"),
('*', "PlacementSpec(host_pattern='*')"),
('3 data[1-3]', "PlacementSpec(count=3, host_pattern='data[1-3]')"),
('3 data?', "PlacementSpec(count=3, host_pattern='data?')"),
('3 data*', "PlacementSpec(count=3, host_pattern='data*')"),
("count-per-host:4 label:foo", "PlacementSpec(count_per_host=4, label='foo')"),
])
def test_parse_placement_specs(test_input, expected):
ret = PlacementSpec.from_string(test_input)
assert str(ret) == expected
assert PlacementSpec.from_string(ret.pretty_str()) == ret, f'"{ret.pretty_str()}" != "{test_input}"'
@pytest.mark.parametrize(
"test_input",
[
("host=a host*"),
("host=a label:wrong"),
("host? host*"),
('host=a count-per-host:0'),
('host=a count-per-host:-10'),
('count:2 count-per-host:1'),
('host1=a host2=b count-per-host:2'),
('host1:10/8 count-per-host:2'),
('count-per-host:2'),
]
)
def test_parse_placement_specs_raises(test_input):
with pytest.raises(SpecValidationError):
PlacementSpec.from_string(test_input)
@pytest.mark.parametrize("test_input",
# wrong subnet
[("myhost:1.1.1.1/24"),
# wrong ip format
("myhost:1"),
])
def test_parse_host_placement_specs_raises_wrong_format(test_input):
with pytest.raises(ValueError):
HostPlacementSpec.parse(test_input)
@pytest.mark.parametrize(
"p,hosts,size",
[
(
PlacementSpec(count=3),
['host1', 'host2', 'host3', 'host4', 'host5'],
3
),
(
PlacementSpec(host_pattern='*'),
['host1', 'host2', 'host3', 'host4', 'host5'],
5
),
(
PlacementSpec(count_per_host=2, host_pattern='*'),
['host1', 'host2', 'host3', 'host4', 'host5'],
10
),
(
PlacementSpec(host_pattern='foo*'),
['foo1', 'foo2', 'bar1', 'bar2'],
2
),
(
PlacementSpec(count_per_host=2, host_pattern='foo*'),
['foo1', 'foo2', 'bar1', 'bar2'],
4
),
])
def test_placement_target_size(p, hosts, size):
assert p.get_target_count(
[HostPlacementSpec(n, '', '') for n in hosts]
) == size
def _get_dict_spec(s_type, s_id):
dict_spec = {
"service_id": s_id,
"service_type": s_type,
"placement":
dict(hosts=["host1:1.1.1.1"])
}
if s_type == 'nfs':
pass
elif s_type == 'iscsi':
dict_spec['pool'] = 'pool'
dict_spec['api_user'] = 'api_user'
dict_spec['api_password'] = 'api_password'
elif s_type == 'osd':
dict_spec['spec'] = {
'data_devices': {
'all': True
}
}
elif s_type == 'rgw':
dict_spec['rgw_realm'] = 'realm'
dict_spec['rgw_zone'] = 'zone'
return dict_spec
@pytest.mark.parametrize(
"s_type,o_spec,s_id",
[
("mgr", ServiceSpec, 'test'),
("mon", ServiceSpec, 'test'),
("mds", ServiceSpec, 'test'),
("rgw", RGWSpec, 'realm.zone'),
("nfs", NFSServiceSpec, 'test'),
("iscsi", IscsiServiceSpec, 'test'),
("osd", DriveGroupSpec, 'test'),
])
def test_servicespec_map_test(s_type, o_spec, s_id):
spec = ServiceSpec.from_json(_get_dict_spec(s_type, s_id))
assert isinstance(spec, o_spec)
assert isinstance(spec.placement, PlacementSpec)
assert isinstance(spec.placement.hosts[0], HostPlacementSpec)
assert spec.placement.hosts[0].hostname == 'host1'
assert spec.placement.hosts[0].network == '1.1.1.1'
assert spec.placement.hosts[0].name == ''
assert spec.validate() is None
ServiceSpec.from_json(spec.to_json())
@pytest.mark.parametrize(
"realm, zone, frontend_type, raise_exception, msg",
[
('realm', 'zone1', 'beast', False, ''),
('realm', 'zone2', 'civetweb', False, ''),
('realm', None, 'beast', True, 'Cannot add RGW: Realm specified but no zone specified'),
(None, 'zone1', 'beast', True, 'Cannot add RGW: Zone specified but no realm specified'),
('realm', 'zone', 'invalid-beast', True, '^Invalid rgw_frontend_type value'),
('realm', 'zone', 'invalid-civetweb', True, '^Invalid rgw_frontend_type value'),
])
def test_rgw_servicespec_parse(realm, zone, frontend_type, raise_exception, msg):
spec = RGWSpec(service_id='foo',
rgw_realm=realm,
rgw_zone=zone,
rgw_frontend_type=frontend_type)
if raise_exception:
with pytest.raises(SpecValidationError, match=msg):
spec.validate()
else:
spec.validate()
def test_osd_unmanaged():
osd_spec = {"placement": {"host_pattern": "*"},
"service_id": "all-available-devices",
"service_name": "osd.all-available-devices",
"service_type": "osd",
"spec": {"data_devices": {"all": True}, "filter_logic": "AND", "objectstore": "bluestore"},
"unmanaged": True}
dg_spec = ServiceSpec.from_json(osd_spec)
assert dg_spec.unmanaged == True
@pytest.mark.parametrize("y",
"""service_type: crash
service_name: crash
placement:
host_pattern: '*'
---
service_type: crash
service_name: crash
placement:
host_pattern: '*'
unmanaged: true
---
service_type: rgw
service_id: default-rgw-realm.eu-central-1.1
service_name: rgw.default-rgw-realm.eu-central-1.1
placement:
hosts:
- ceph-001
networks:
- 10.0.0.0/8
- 192.168.0.0/16
spec:
rgw_frontend_type: civetweb
rgw_realm: default-rgw-realm
rgw_zone: eu-central-1
---
service_type: osd
service_id: osd_spec_default
service_name: osd.osd_spec_default
placement:
host_pattern: '*'
spec:
data_devices:
model: MC-55-44-XZ
db_devices:
model: SSD-123-foo
filter_logic: AND
objectstore: bluestore
wal_devices:
model: NVME-QQQQ-987
---
service_type: alertmanager
service_name: alertmanager
spec:
port: 1234
user_data:
default_webhook_urls:
- foo
---
service_type: grafana
service_name: grafana
spec:
anonymous_access: true
port: 1234
protocol: https
---
service_type: grafana
service_name: grafana
spec:
anonymous_access: true
initial_admin_password: secure
port: 1234
protocol: https
---
service_type: ingress
service_id: rgw.foo
service_name: ingress.rgw.foo
placement:
hosts:
- host1
- host2
- host3
spec:
backend_service: rgw.foo
first_virtual_router_id: 50
frontend_port: 8080
monitor_port: 8081
virtual_ip: 192.168.20.1/24
---
service_type: nfs
service_id: mynfs
service_name: nfs.mynfs
spec:
port: 1234
---
service_type: iscsi
service_id: iscsi
service_name: iscsi.iscsi
networks:
- ::0/8
spec:
api_password: admin
api_port: 5000
api_user: admin
pool: pool
trusted_ip_list:
- ::1
- ::2
---
service_type: container
service_id: hello-world
service_name: container.hello-world
spec:
args:
- --foo
bind_mounts:
- - type=bind
- source=lib/modules
- destination=/lib/modules
- ro=true
dirs:
- foo
- bar
entrypoint: /usr/bin/bash
envs:
- FOO=0815
files:
bar.conf:
- foo
- bar
foo.conf: 'foo
bar'
gid: 2000
image: docker.io/library/hello-world:latest
ports:
- 8080
- 8443
uid: 1000
volume_mounts:
foo: /foo
---
service_type: snmp-gateway
service_name: snmp-gateway
placement:
count: 1
spec:
credentials:
snmp_community: public
snmp_destination: 192.168.1.42:162
snmp_version: V2c
---
service_type: snmp-gateway
service_name: snmp-gateway
placement:
count: 1
spec:
auth_protocol: MD5
credentials:
snmp_v3_auth_password: mypassword
snmp_v3_auth_username: myuser
engine_id: 8000C53F00000000
port: 9464
snmp_destination: 192.168.1.42:162
snmp_version: V3
---
service_type: snmp-gateway
service_name: snmp-gateway
placement:
count: 1
spec:
credentials:
snmp_v3_auth_password: mypassword
snmp_v3_auth_username: myuser
snmp_v3_priv_password: mysecret
engine_id: 8000C53F00000000
privacy_protocol: AES
snmp_destination: 192.168.1.42:162
snmp_version: V3
""".split('---\n'))
def test_yaml(y):
data = yaml.safe_load(y)
object = ServiceSpec.from_json(data)
assert yaml.dump(object) == y
assert yaml.dump(ServiceSpec.from_json(object.to_json())) == y
def test_alertmanager_spec_1():
spec = AlertManagerSpec()
assert spec.service_type == 'alertmanager'
assert isinstance(spec.user_data, dict)
assert len(spec.user_data.keys()) == 0
assert spec.get_port_start() == [9093, 9094]
def test_alertmanager_spec_2():
spec = AlertManagerSpec(user_data={'default_webhook_urls': ['foo']})
assert isinstance(spec.user_data, dict)
assert 'default_webhook_urls' in spec.user_data.keys()
def test_repr():
val = """ServiceSpec.from_json(yaml.safe_load('''service_type: crash
service_name: crash
placement:
count: 42
'''))"""
obj = eval(val)
assert obj.service_type == 'crash'
assert val == repr(obj)
@pytest.mark.parametrize("spec1, spec2, eq",
[
(
ServiceSpec(
service_type='mon'
),
ServiceSpec(
service_type='mon'
),
True
),
(
ServiceSpec(
service_type='mon'
),
ServiceSpec(
service_type='mon',
service_id='foo'
),
True
),
# Add service_type='mgr'
(
ServiceSpec(
service_type='osd'
),
ServiceSpec(
service_type='osd',
),
True
),
(
ServiceSpec(
service_type='osd'
),
DriveGroupSpec(),
True
),
(
ServiceSpec(
service_type='osd'
),
ServiceSpec(
service_type='osd',
service_id='foo',
),
False
),
(
ServiceSpec(
service_type='rgw',
service_id='foo',
),
RGWSpec(service_id='foo'),
True
),
])
def test_spec_hash_eq(spec1: ServiceSpec,
spec2: ServiceSpec,
eq: bool):
assert (spec1 == spec2) is eq
@pytest.mark.parametrize(
"s_type,s_id,s_name",
[
('mgr', 's_id', 'mgr'),
('mon', 's_id', 'mon'),
('mds', 's_id', 'mds.s_id'),
('rgw', 's_id', 'rgw.s_id'),
('nfs', 's_id', 'nfs.s_id'),
('iscsi', 's_id', 'iscsi.s_id'),
('osd', 's_id', 'osd.s_id'),
])
def test_service_name(s_type, s_id, s_name):
spec = ServiceSpec.from_json(_get_dict_spec(s_type, s_id))
spec.validate()
assert spec.service_name() == s_name
@pytest.mark.parametrize(
's_type,s_id',
[
('mds', 's:id'), # MDS service_id cannot contain an invalid char ':'
('mds', '1abc'), # MDS service_id cannot start with a numeric digit
('mds', ''), # MDS service_id cannot be empty
('rgw', '*s_id'),
('nfs', 's/id'),
('iscsi', 's@id'),
('osd', 's;id'),
])
def test_service_id_raises_invalid_char(s_type, s_id):
with pytest.raises(SpecValidationError):
spec = ServiceSpec.from_json(_get_dict_spec(s_type, s_id))
spec.validate()
def test_custom_container_spec():
spec = CustomContainerSpec(service_id='hello-world',
image='docker.io/library/hello-world:latest',
entrypoint='/usr/bin/bash',
uid=1000,
gid=2000,
volume_mounts={'foo': '/foo'},
args=['--foo'],
envs=['FOO=0815'],
bind_mounts=[
[
'type=bind',
'source=lib/modules',
'destination=/lib/modules',
'ro=true'
]
],
ports=[8080, 8443],
dirs=['foo', 'bar'],
files={
'foo.conf': 'foo\nbar',
'bar.conf': ['foo', 'bar']
})
assert spec.service_type == 'container'
assert spec.entrypoint == '/usr/bin/bash'
assert spec.uid == 1000
assert spec.gid == 2000
assert spec.volume_mounts == {'foo': '/foo'}
assert spec.args == ['--foo']
assert spec.envs == ['FOO=0815']
assert spec.bind_mounts == [
[
'type=bind',
'source=lib/modules',
'destination=/lib/modules',
'ro=true'
]
]
assert spec.ports == [8080, 8443]
assert spec.dirs == ['foo', 'bar']
assert spec.files == {
'foo.conf': 'foo\nbar',
'bar.conf': ['foo', 'bar']
}
def test_custom_container_spec_config_json():
spec = CustomContainerSpec(service_id='foo', image='foo', dirs=None)
config_json = spec.config_json()
for key in ['entrypoint', 'uid', 'gid', 'bind_mounts', 'dirs']:
assert key not in config_json
def test_ingress_spec():
yaml_str = """service_type: ingress
service_id: rgw.foo
placement:
hosts:
- host1
- host2
- host3
spec:
virtual_ip: 192.168.20.1/24
backend_service: rgw.foo
frontend_port: 8080
monitor_port: 8081
"""
yaml_file = yaml.safe_load(yaml_str)
spec = ServiceSpec.from_json(yaml_file)
assert spec.service_type == "ingress"
assert spec.service_id == "rgw.foo"
assert spec.virtual_ip == "192.168.20.1/24"
assert spec.frontend_port == 8080
assert spec.monitor_port == 8081
@pytest.mark.parametrize("y, error_match", [
("""
service_type: rgw
service_id: foo
placement:
count_per_host: "twelve"
""", "count-per-host must be a numeric value",),
("""
service_type: rgw
service_id: foo
placement:
count_per_host: "2"
""", "count-per-host must be an integer value",),
("""
service_type: rgw
service_id: foo
placement:
count_per_host: 7.36
""", "count-per-host must be an integer value",),
("""
service_type: rgw
service_id: foo
placement:
count: "fifteen"
""", "num/count must be a numeric value",),
("""
service_type: rgw
service_id: foo
placement:
count: "4"
""", "num/count must be an integer value",),
("""
service_type: rgw
service_id: foo
placement:
count: 7.36
""", "num/count must be an integer value",),
("""
service_type: rgw
service_id: foo
placement:
count: 0
""", "num/count must be >= 1",),
("""
service_type: rgw
service_id: foo
placement:
count_per_host: 0
""", "count-per-host must be >= 1",),
("""
service_type: snmp-gateway
service_name: snmp-gateway
placement:
count: 1
spec:
credentials:
snmp_v3_auth_password: mypassword
snmp_v3_auth_username: myuser
snmp_v3_priv_password: mysecret
port: 9464
engine_id: 8000c53f0000000000
privacy_protocol: WEIRD
snmp_destination: 192.168.122.1:162
auth_protocol: BIZARRE
snmp_version: V3
""", "auth_protocol unsupported. Must be one of MD5, SHA"),
("""
---
service_type: snmp-gateway
service_name: snmp-gateway
placement:
count: 1
spec:
credentials:
snmp_community: public
snmp_destination: 192.168.1.42:162
snmp_version: V4
""", 'snmp_version unsupported. Must be one of V2c, V3'),
("""
---
service_type: snmp-gateway
service_name: snmp-gateway
placement:
count: 1
spec:
credentials:
snmp_community: public
port: 9464
snmp_destination: 192.168.1.42:162
""", re.escape('Missing SNMP version (snmp_version)')),
("""
---
service_type: snmp-gateway
service_name: snmp-gateway
placement:
count: 1
spec:
credentials:
snmp_v3_auth_username: myuser
snmp_v3_auth_password: mypassword
port: 9464
auth_protocol: wah
snmp_destination: 192.168.1.42:162
snmp_version: V3
""", 'auth_protocol unsupported. Must be one of MD5, SHA'),
("""
---
service_type: snmp-gateway
service_name: snmp-gateway
placement:
count: 1
spec:
credentials:
snmp_v3_auth_username: myuser
snmp_v3_auth_password: mypassword
snmp_v3_priv_password: mysecret
port: 9464
auth_protocol: SHA
privacy_protocol: weewah
snmp_destination: 192.168.1.42:162
snmp_version: V3
""", 'privacy_protocol unsupported. Must be one of DES, AES'),
("""
---
service_type: snmp-gateway
service_name: snmp-gateway
placement:
count: 1
spec:
credentials:
snmp_v3_auth_username: myuser
snmp_v3_auth_password: mypassword
snmp_v3_priv_password: mysecret
port: 9464
auth_protocol: SHA
privacy_protocol: AES
snmp_destination: 192.168.1.42:162
snmp_version: V3
""", 'Must provide an engine_id for SNMP V3 notifications'),
("""
---
service_type: snmp-gateway
service_name: snmp-gateway
placement:
count: 1
spec:
credentials:
snmp_community: public
port: 9464
snmp_destination: 192.168.1.42
snmp_version: V2c
""", re.escape('SNMP destination (snmp_destination) type (IPv4) is invalid. Must be either: IPv4:Port, Name:Port')),
("""
---
service_type: snmp-gateway
service_name: snmp-gateway
placement:
count: 1
spec:
credentials:
snmp_v3_auth_username: myuser
snmp_v3_auth_password: mypassword
snmp_v3_priv_password: mysecret
port: 9464
auth_protocol: SHA
privacy_protocol: AES
engine_id: bogus
snmp_destination: 192.168.1.42:162
snmp_version: V3
""", 'engine_id must be a string containing 10-64 hex characters. Its length must be divisible by 2'),
("""
---
service_type: snmp-gateway
service_name: snmp-gateway
placement:
count: 1
spec:
credentials:
snmp_v3_auth_username: myuser
snmp_v3_auth_password: mypassword
port: 9464
auth_protocol: SHA
engine_id: 8000C53F0000000000
snmp_version: V3
""", re.escape('SNMP destination (snmp_destination) must be provided')),
("""
---
service_type: snmp-gateway
service_name: snmp-gateway
placement:
count: 1
spec:
credentials:
snmp_v3_auth_username: myuser
snmp_v3_auth_password: mypassword
snmp_v3_priv_password: mysecret
port: 9464
auth_protocol: SHA
privacy_protocol: AES
engine_id: 8000C53F0000000000
snmp_destination: my.imaginary.snmp-host
snmp_version: V3
""", re.escape('SNMP destination (snmp_destination) is invalid: DNS lookup failed')),
("""
---
service_type: snmp-gateway
service_name: snmp-gateway
placement:
count: 1
spec:
credentials:
snmp_v3_auth_username: myuser
snmp_v3_auth_password: mypassword
snmp_v3_priv_password: mysecret
port: 9464
auth_protocol: SHA
privacy_protocol: AES
engine_id: 8000C53F0000000000
snmp_destination: 10.79.32.10:fred
snmp_version: V3
""", re.escape('SNMP destination (snmp_destination) is invalid: Port must be numeric')),
("""
---
service_type: snmp-gateway
service_name: snmp-gateway
placement:
count: 1
spec:
credentials:
snmp_v3_auth_username: myuser
snmp_v3_auth_password: mypassword
snmp_v3_priv_password: mysecret
port: 9464
auth_protocol: SHA
privacy_protocol: AES
engine_id: 8000C53
snmp_destination: 10.79.32.10:162
snmp_version: V3
""", 'engine_id must be a string containing 10-64 hex characters. Its length must be divisible by 2'),
("""
---
service_type: snmp-gateway
service_name: snmp-gateway
placement:
count: 1
spec:
credentials:
snmp_v3_auth_username: myuser
snmp_v3_auth_password: mypassword
snmp_v3_priv_password: mysecret
port: 9464
auth_protocol: SHA
privacy_protocol: AES
engine_id: 8000C53DOH!
snmp_destination: 10.79.32.10:162
snmp_version: V3
""", 'engine_id must be a string containing 10-64 hex characters. Its length must be divisible by 2'),
("""
---
service_type: snmp-gateway
service_name: snmp-gateway
placement:
count: 1
spec:
credentials:
snmp_v3_auth_username: myuser
snmp_v3_auth_password: mypassword
snmp_v3_priv_password: mysecret
port: 9464
auth_protocol: SHA
privacy_protocol: AES
engine_id: 8000C53FCA7344403DC611EC9B985254002537A6C53FCA7344403DC6112537A60
snmp_destination: 10.79.32.10:162
snmp_version: V3
""", 'engine_id must be a string containing 10-64 hex characters. Its length must be divisible by 2'),
("""
---
service_type: snmp-gateway
service_name: snmp-gateway
placement:
count: 1
spec:
credentials:
snmp_v3_auth_username: myuser
snmp_v3_auth_password: mypassword
snmp_v3_priv_password: mysecret
port: 9464
auth_protocol: SHA
privacy_protocol: AES
engine_id: 8000C53F00000
snmp_destination: 10.79.32.10:162
snmp_version: V3
""", 'engine_id must be a string containing 10-64 hex characters. Its length must be divisible by 2'),
])
def test_service_spec_validation_error(y, error_match):
data = yaml.safe_load(y)
with pytest.raises(SpecValidationError) as err:
specObj = ServiceSpec.from_json(data)
assert err.match(error_match)
@pytest.mark.parametrize("y, ec_args, ee_args, ec_final_args, ee_final_args", [
pytest.param("""
service_type: container
service_id: hello-world
service_name: container.hello-world
spec:
args:
- --foo
bind_mounts:
- - type=bind
- source=lib/modules
- destination=/lib/modules
- ro=true
dirs:
- foo
- bar
entrypoint: /usr/bin/bash
envs:
- FOO=0815
files:
bar.conf:
- foo
- bar
foo.conf: 'foo
bar'
gid: 2000
image: docker.io/library/hello-world:latest
ports:
- 8080
- 8443
uid: 1000
volume_mounts:
foo: /foo
""",
None,
None,
None,
None,
id="no_extra_args"),
pytest.param("""
service_type: container
service_id: hello-world
service_name: container.hello-world
spec:
args:
- --foo
extra_entrypoint_args:
- "--lasers=blue"
- "--enable-confetti"
bind_mounts:
- - type=bind
- source=lib/modules
- destination=/lib/modules
- ro=true
dirs:
- foo
- bar
entrypoint: /usr/bin/bash
envs:
- FOO=0815
files:
bar.conf:
- foo
- bar
foo.conf: 'foo
bar'
gid: 2000
image: docker.io/library/hello-world:latest
ports:
- 8080
- 8443
uid: 1000
volume_mounts:
foo: /foo
""",
None,
["--lasers=blue", "--enable-confetti"],
None,
["--lasers=blue", "--enable-confetti"],
id="only_extra_entrypoint_args_spec"),
pytest.param("""
service_type: container
service_id: hello-world
service_name: container.hello-world
spec:
args:
- --foo
bind_mounts:
- - type=bind
- source=lib/modules
- destination=/lib/modules
- ro=true
dirs:
- foo
- bar
entrypoint: /usr/bin/bash
envs:
- FOO=0815
files:
bar.conf:
- foo
- bar
foo.conf: 'foo
bar'
gid: 2000
image: docker.io/library/hello-world:latest
ports:
- 8080
- 8443
uid: 1000
volume_mounts:
foo: /foo
extra_entrypoint_args:
- "--lasers blue"
- "--enable-confetti"
""",
None,
["--lasers blue", "--enable-confetti"],
None,
["--lasers", "blue", "--enable-confetti"],
id="only_extra_entrypoint_args_toplevel"),
pytest.param("""
service_type: nfs
service_id: mynfs
service_name: nfs.mynfs
spec:
port: 1234
extra_entrypoint_args:
- "--lasers=blue"
- "--title=Custom NFS Options"
extra_container_args:
- "--cap-add=CAP_NET_BIND_SERVICE"
- "--oom-score-adj=12"
""",
["--cap-add=CAP_NET_BIND_SERVICE", "--oom-score-adj=12"],
["--lasers=blue", "--title=Custom NFS Options"],
["--cap-add=CAP_NET_BIND_SERVICE", "--oom-score-adj=12"],
["--lasers=blue", "--title=Custom", "NFS", "Options"],
id="both_kinds_nfs"),
pytest.param("""
service_type: container
service_id: hello-world
service_name: container.hello-world
spec:
args:
- --foo
bind_mounts:
- - type=bind
- source=lib/modules
- destination=/lib/modules
- ro=true
dirs:
- foo
- bar
entrypoint: /usr/bin/bash
envs:
- FOO=0815
files:
bar.conf:
- foo
- bar
foo.conf: 'foo
bar'
gid: 2000
image: docker.io/library/hello-world:latest
ports:
- 8080
- 8443
uid: 1000
volume_mounts:
foo: /foo
extra_entrypoint_args:
- argument: "--lasers=blue"
split: true
- argument: "--enable-confetti"
""",
None,
[
{"argument": "--lasers=blue", "split": True},
{"argument": "--enable-confetti", "split": False},
],
None,
[
"--lasers=blue",
"--enable-confetti",
],
id="only_extra_entrypoint_args_obj_toplevel"),
pytest.param("""
service_type: container
service_id: hello-world
service_name: container.hello-world
spec:
args:
- --foo
bind_mounts:
- - type=bind
- source=lib/modules
- destination=/lib/modules
- ro=true
dirs:
- foo
- bar
entrypoint: /usr/bin/bash
envs:
- FOO=0815
files:
bar.conf:
- foo
- bar
foo.conf: 'foo
bar'
gid: 2000
image: docker.io/library/hello-world:latest
ports:
- 8080
- 8443
uid: 1000
volume_mounts:
foo: /foo
extra_entrypoint_args:
- argument: "--lasers=blue"
split: true
- argument: "--enable-confetti"
""",
None,
[
{"argument": "--lasers=blue", "split": True},
{"argument": "--enable-confetti", "split": False},
],
None,
[
"--lasers=blue",
"--enable-confetti",
],
id="only_extra_entrypoint_args_obj_indented"),
pytest.param("""
service_type: nfs
service_id: mynfs
service_name: nfs.mynfs
spec:
port: 1234
extra_entrypoint_args:
- argument: "--lasers=blue"
- argument: "--title=Custom NFS Options"
extra_container_args:
- argument: "--cap-add=CAP_NET_BIND_SERVICE"
- argument: "--oom-score-adj=12"
""",
[
{"argument": "--cap-add=CAP_NET_BIND_SERVICE", "split": False},
{"argument": "--oom-score-adj=12", "split": False},
],
[
{"argument": "--lasers=blue", "split": False},
{"argument": "--title=Custom NFS Options", "split": False},
],
[
"--cap-add=CAP_NET_BIND_SERVICE",
"--oom-score-adj=12",
],
[
"--lasers=blue",
"--title=Custom NFS Options",
],
id="both_kinds_obj_nfs"),
])
def test_extra_args_handling(y, ec_args, ee_args, ec_final_args, ee_final_args):
data = yaml.safe_load(y)
spec_obj = ServiceSpec.from_json(data)
assert ArgumentSpec.map_json(spec_obj.extra_container_args) == ec_args
assert ArgumentSpec.map_json(spec_obj.extra_entrypoint_args) == ee_args
if ec_final_args is None:
assert spec_obj.extra_container_args is None
else:
ec_res = []
for args in spec_obj.extra_container_args:
ec_res.extend(args.to_args())
assert ec_res == ec_final_args
if ee_final_args is None:
assert spec_obj.extra_entrypoint_args is None
else:
ee_res = []
for args in spec_obj.extra_entrypoint_args:
ee_res.extend(args.to_args())
assert ee_res == ee_final_args
| 37,163 | 28.239969 | 201 |
py
|
null |
ceph-main/src/python-common/ceph/tests/test_utils.py
|
import pytest
from ceph.deployment.utils import is_ipv6, unwrap_ipv6, wrap_ipv6, valid_addr
from typing import NamedTuple
def test_is_ipv6():
for good in ("[::1]", "::1",
"fff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"):
assert is_ipv6(good)
for bad in ("127.0.0.1",
"ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffg",
"1:2:3:4:5:6:7:8:9", "fd00::1::1", "[fg::1]"):
assert not is_ipv6(bad)
def test_unwrap_ipv6():
def unwrap_test(address, expected):
assert unwrap_ipv6(address) == expected
tests = [
('::1', '::1'), ('[::1]', '::1'),
('[fde4:8dba:82e1:0:5054:ff:fe6a:357]', 'fde4:8dba:82e1:0:5054:ff:fe6a:357'),
('can actually be any string', 'can actually be any string'),
('[but needs to be stripped] ', '[but needs to be stripped] ')]
for address, expected in tests:
unwrap_test(address, expected)
def test_wrap_ipv6():
def wrap_test(address, expected):
assert wrap_ipv6(address) == expected
tests = [
('::1', '[::1]'), ('[::1]', '[::1]'),
('fde4:8dba:82e1:0:5054:ff:fe6a:357', '[fde4:8dba:82e1:0:5054:ff:fe6a:357]'),
('myhost.example.com', 'myhost.example.com'), ('192.168.0.1', '192.168.0.1'),
('', ''), ('fd00::1::1', 'fd00::1::1')]
for address, expected in tests:
wrap_test(address, expected)
class Address(NamedTuple):
addr: str
status: bool
description: str
@pytest.mark.parametrize('addr_object', [
Address('www.ibm.com', True, 'Name'),
Address('www.google.com:162', True, 'Name:Port'),
Address('my.big.domain.name.for.big.people', False, 'DNS lookup failed'),
Address('192.168.122.1', True, 'IPv4'),
Address('[192.168.122.1]', False, 'IPv4 address wrapped in brackets is invalid'),
Address('10.40003.200', False, 'Invalid partial IPv4 address'),
Address('10.7.5', False, 'Invalid partial IPv4 address'),
Address('10.7', False, 'Invalid partial IPv4 address'),
Address('192.168.122.5:7090', True, 'IPv4:Port'),
Address('fe80::7561:c8fb:d3d7:1fa4', True, 'IPv6'),
Address('[fe80::7561:c8fb:d3d7:1fa4]:9464', True, 'IPv6:Port'),
Address('[fe80::7561:c8fb:d3d7:1fa4]', True, 'IPv6'),
Address('[fe80::7561:c8fb:d3d7:1fa4', False,
'Address has incorrect/incomplete use of enclosing brackets'),
Address('fe80::7561:c8fb:d3d7:1fa4]', False,
'Address has incorrect/incomplete use of enclosing brackets'),
Address('fred.knockinson.org', False, 'DNS lookup failed'),
Address('tumbleweed.pickles.gov.au', False, 'DNS lookup failed'),
Address('192.168.122.5:00PS', False, 'Port must be numeric'),
Address('[fe80::7561:c8fb:d3d7:1fa4]:DOH', False, 'Port must be numeric')
])
def test_valid_addr(addr_object: Address):
valid, description = valid_addr(addr_object.addr)
assert valid == addr_object.status
assert description == addr_object.description
| 2,957 | 37.921053 | 85 |
py
|
null |
ceph-main/src/python-common/ceph/tests/utils.py
|
from ceph.deployment.inventory import Devices, Device
try:
from typing import Any, List
except ImportError:
pass # for type checking
def _mk_device(rotational=True,
locked=False,
size="394.27 GB",
vendor='Vendor',
model='Model'):
return [Device(
path='??',
sys_api={
"rotational": '1' if rotational else '0',
"vendor": vendor,
"human_readable_size": size,
"partitions": {},
"locked": int(locked),
"sectorsize": "512",
"removable": "0",
"path": "??",
"support_discard": "",
"model": model,
"ro": "0",
"nr_requests": "128",
"size": 423347879936 # ignore coversion from human_readable_size
},
available=not locked,
rejected_reasons=['locked'] if locked else [],
lvs=[],
device_id="Model-Vendor-foobar"
)]
def _mk_inventory(devices):
# type: (Any) -> List[Device]
devs = []
for dev_, name in zip(devices, map(chr, range(ord('a'), ord('z')))):
dev = Device.from_json(dev_.to_json())
dev.path = '/dev/sd' + name
dev.sys_api = dict(dev_.sys_api, path='/dev/sd' + name)
devs.append(dev)
return Devices(devices=devs).devices
| 1,359 | 27.93617 | 77 |
py
|
null |
ceph-main/src/rbd_fuse/rbd-fuse.cc
|
/*
* rbd-fuse
*/
#include "include/int_types.h"
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <pthread.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <getopt.h>
#include <assert.h>
#include <string>
#include <mutex>
#include <limits.h>
#if defined(__FreeBSD__)
#include <sys/param.h>
#endif
#include "include/compat.h"
#include "include/rbd/librbd.h"
#include "include/ceph_assert.h"
#include "common/ceph_argparse.h"
#include "common/ceph_context.h"
#include "include/ceph_fuse.h"
#include "global/global_init.h"
#include "global/global_context.h"
static int gotrados = 0;
char *pool_name;
char *nspace_name;
char *mount_image_name;
rados_t cluster;
rados_ioctx_t ioctx;
std::mutex readdir_lock;
struct rbd_stat {
u_char valid;
rbd_image_info_t rbd_info;
};
struct rbd_options {
char *pool_name;
char *nspace_name;
char *image_name;
};
struct rbd_image {
char *image_name;
struct rbd_image *next;
};
struct rbd_image_data {
struct rbd_image *images;
rbd_image_spec_t *image_specs;
size_t image_spec_count;
};
struct rbd_image_data rbd_image_data;
struct rbd_openimage {
char *image_name;
rbd_image_t image;
struct rbd_stat rbd_stat;
};
#define MAX_RBD_IMAGES 128
struct rbd_openimage opentbl[MAX_RBD_IMAGES];
struct rbd_options rbd_options = {(char*) "rbd", (char*) "", NULL};
#define rbdsize(fd) opentbl[fd].rbd_stat.rbd_info.size
#define rbdblksize(fd) opentbl[fd].rbd_stat.rbd_info.obj_size
#define rbdblkcnt(fd) opentbl[fd].rbd_stat.rbd_info.num_objs
uint64_t imagesize = 1024ULL * 1024 * 1024;
uint64_t imageorder = 22ULL;
uint64_t imagefeatures = 1ULL;
// Minimize calls to rbd_list: marks bracketing of opendir/<ops>/releasedir
int in_opendir;
/* prototypes */
int connect_to_cluster(rados_t *pcluster);
void enumerate_images(struct rbd_image_data *data);
int open_rbd_image(const char *image_name);
int find_openrbd(const char *path);
void simple_err(const char *msg, int err);
void
enumerate_images(struct rbd_image_data *data)
{
struct rbd_image **head = &data->images;
struct rbd_image *im, *next;
int ret;
if (*head != NULL) {
for (im = *head; im != NULL;) {
next = im->next;
free(im);
im = next;
}
*head = NULL;
rbd_image_spec_list_cleanup(data->image_specs,
data->image_spec_count);
free(data->image_specs);
data->image_specs = NULL;
data->image_spec_count = 0;
}
while (true) {
ret = rbd_list2(ioctx, data->image_specs,
&data->image_spec_count);
if (ret == -ERANGE) {
data->image_specs = static_cast<rbd_image_spec_t *>(
realloc(data->image_specs,
sizeof(rbd_image_spec_t) * data->image_spec_count));
} else if (ret < 0) {
simple_err("Failed to list images", ret);
} else {
break;
}
}
if (*nspace_name != '\0') {
fprintf(stderr, "pool/namespace %s/%s: ", pool_name, nspace_name);
} else {
fprintf(stderr, "pool %s: ", pool_name);
}
for (size_t idx = 0; idx < data->image_spec_count; ++idx) {
if ((mount_image_name == NULL) ||
((strlen(mount_image_name) > 0) &&
(strcmp(data->image_specs[idx].name, mount_image_name) == 0))) {
fprintf(stderr, "%s, ", data->image_specs[idx].name);
im = static_cast<rbd_image*>(malloc(sizeof(*im)));
im->image_name = data->image_specs[idx].name;
im->next = *head;
*head = im;
}
}
fprintf(stderr, "\n");
}
int
find_openrbd(const char *path)
{
int i;
/* find in opentbl[] entry if already open */
for (i = 0; i < MAX_RBD_IMAGES; i++) {
if ((opentbl[i].image_name != NULL) &&
(strcmp(opentbl[i].image_name, path) == 0)) {
return i;
}
}
return -1;
}
int
open_rbd_image(const char *image_name)
{
struct rbd_image *im;
struct rbd_openimage *rbd = NULL;
int fd;
if (image_name == (char *)NULL)
return -1;
// relies on caller to keep rbd_image_data up to date
for (im = rbd_image_data.images; im != NULL; im = im->next) {
if (strcmp(im->image_name, image_name) == 0) {
break;
}
}
if (im == NULL)
return -1;
/* find in opentbl[] entry if already open */
if ((fd = find_openrbd(image_name)) != -1) {
rbd = &opentbl[fd];
} else {
int i;
// allocate an opentbl[] and open the image
for (i = 0; i < MAX_RBD_IMAGES; i++) {
if (opentbl[i].image == NULL) {
fd = i;
rbd = &opentbl[fd];
rbd->image_name = strdup(image_name);
break;
}
}
if (i == MAX_RBD_IMAGES || !rbd)
return -1;
int ret = rbd_open(ioctx, rbd->image_name, &(rbd->image), NULL);
if (ret < 0) {
simple_err("open_rbd_image: can't open: ", ret);
return ret;
}
}
rbd_stat(rbd->image, &(rbd->rbd_stat.rbd_info),
sizeof(rbd_image_info_t));
rbd->rbd_stat.valid = 1;
return fd;
}
static void
iter_images(void *cookie,
void (*iter)(void *cookie, const char *image))
{
struct rbd_image *im;
readdir_lock.lock();
for (im = rbd_image_data.images; im != NULL; im = im->next)
iter(cookie, im->image_name);
readdir_lock.unlock();
}
static void count_images_cb(void *cookie, const char *image)
{
(*((unsigned int *)cookie))++;
}
static int count_images(void)
{
unsigned int count = 0;
readdir_lock.lock();
enumerate_images(&rbd_image_data);
readdir_lock.unlock();
iter_images(&count, count_images_cb);
return count;
}
extern "C" {
static int rbdfs_getattr(const char *path, struct stat *stbuf
#if FUSE_VERSION >= FUSE_MAKE_VERSION(3, 0)
, struct fuse_file_info *fi
#endif
)
{
int fd;
time_t now;
if (!gotrados)
return -ENXIO;
if (path[0] == 0)
return -ENOENT;
memset(stbuf, 0, sizeof(struct stat));
if (strcmp(path, "/") == 0) {
now = time(NULL);
stbuf->st_mode = S_IFDIR + 0755;
stbuf->st_nlink = 2+count_images();
stbuf->st_uid = getuid();
stbuf->st_gid = getgid();
stbuf->st_size = 1024;
stbuf->st_blksize = 1024;
stbuf->st_blocks = 1;
stbuf->st_atime = now;
stbuf->st_mtime = now;
stbuf->st_ctime = now;
return 0;
}
if (!in_opendir) {
readdir_lock.lock();
enumerate_images(&rbd_image_data);
readdir_lock.unlock();
}
fd = open_rbd_image(path + 1);
if (fd < 0)
return -ENOENT;
now = time(NULL);
stbuf->st_mode = S_IFREG | 0666;
stbuf->st_nlink = 1;
stbuf->st_uid = getuid();
stbuf->st_gid = getgid();
stbuf->st_size = rbdsize(fd);
stbuf->st_blksize = rbdblksize(fd);
stbuf->st_blocks = rbdblkcnt(fd);
stbuf->st_atime = now;
stbuf->st_mtime = now;
stbuf->st_ctime = now;
return 0;
}
static int rbdfs_open(const char *path, struct fuse_file_info *fi)
{
int fd;
if (!gotrados)
return -ENXIO;
if (path[0] == 0)
return -ENOENT;
readdir_lock.lock();
enumerate_images(&rbd_image_data);
readdir_lock.unlock();
fd = open_rbd_image(path + 1);
if (fd < 0)
return -ENOENT;
fi->fh = fd;
return 0;
}
static int rbdfs_read(const char *path, char *buf, size_t size,
off_t offset, struct fuse_file_info *fi)
{
size_t numread;
struct rbd_openimage *rbd;
if (!gotrados)
return -ENXIO;
rbd = &opentbl[fi->fh];
numread = 0;
while (size > 0) {
ssize_t ret;
ret = rbd_read(rbd->image, offset, size, buf);
if (ret <= 0)
break;
buf += ret;
size -= ret;
offset += ret;
numread += ret;
}
return numread;
}
static int rbdfs_write(const char *path, const char *buf, size_t size,
off_t offset, struct fuse_file_info *fi)
{
size_t numwritten;
struct rbd_openimage *rbd;
if (!gotrados)
return -ENXIO;
rbd = &opentbl[fi->fh];
numwritten = 0;
while (size > 0) {
ssize_t ret;
if ((size_t)(offset + size) > rbdsize(fi->fh)) {
int r;
fprintf(stderr, "rbdfs_write resizing %s to 0x%" PRIxMAX "\n",
path, offset+size);
r = rbd_resize(rbd->image, offset+size);
if (r < 0)
return r;
r = rbd_stat(rbd->image, &(rbd->rbd_stat.rbd_info),
sizeof(rbd_image_info_t));
if (r < 0)
return r;
}
ret = rbd_write(rbd->image, offset, size, buf);
if (ret < 0)
break;
buf += ret;
size -= ret;
offset += ret;
numwritten += ret;
}
return numwritten;
}
static void rbdfs_statfs_image_cb(void *num, const char *image)
{
int fd;
((uint64_t *)num)[0]++;
fd = open_rbd_image(image);
if (fd >= 0)
((uint64_t *)num)[1] += rbdsize(fd);
}
static int rbdfs_statfs(const char *path, struct statvfs *buf)
{
uint64_t num[2];
if (!gotrados)
return -ENXIO;
num[0] = 1;
num[1] = 0;
readdir_lock.lock();
enumerate_images(&rbd_image_data);
readdir_lock.unlock();
iter_images(num, rbdfs_statfs_image_cb);
#define RBDFS_BSIZE 4096
buf->f_bsize = RBDFS_BSIZE;
buf->f_frsize = RBDFS_BSIZE;
buf->f_blocks = num[1] / RBDFS_BSIZE;
buf->f_bfree = 0;
buf->f_bavail = 0;
buf->f_files = num[0];
buf->f_ffree = 0;
buf->f_favail = 0;
buf->f_fsid = 0;
buf->f_flag = 0;
buf->f_namemax = PATH_MAX;
return 0;
}
static int rbdfs_fsync(const char *path, int datasync,
struct fuse_file_info *fi)
{
if (!gotrados)
return -ENXIO;
rbd_flush(opentbl[fi->fh].image);
return 0;
}
static int rbdfs_opendir(const char *path, struct fuse_file_info *fi)
{
// only one directory, so global "in_opendir" flag should be fine
readdir_lock.lock();
in_opendir++;
enumerate_images(&rbd_image_data);
readdir_lock.unlock();
return 0;
}
struct rbdfs_readdir_info {
void *buf;
fuse_fill_dir_t filler;
};
static void rbdfs_readdir_cb(void *_info, const char *name)
{
struct rbdfs_readdir_info *info = (struct rbdfs_readdir_info*) _info;
filler_compat(info->filler, info->buf, name, NULL, 0);
}
static int rbdfs_readdir(const char *path, void *buf, fuse_fill_dir_t filler,
off_t offset, struct fuse_file_info *fi
#if FUSE_VERSION >= FUSE_MAKE_VERSION(3, 0)
, enum fuse_readdir_flags
#endif
)
{
struct rbdfs_readdir_info info = { buf, filler };
if (!gotrados)
return -ENXIO;
if (!in_opendir)
fprintf(stderr, "in readdir, but not inside opendir?\n");
if (strcmp(path, "/") != 0)
return -ENOENT;
filler_compat(filler, buf, ".", NULL, 0);
filler_compat(filler, buf, "..", NULL, 0);
iter_images(&info, rbdfs_readdir_cb);
return 0;
}
static int rbdfs_releasedir(const char *path, struct fuse_file_info *fi)
{
// see opendir comments
readdir_lock.lock();
in_opendir--;
readdir_lock.unlock();
return 0;
}
void *
rbdfs_init(struct fuse_conn_info *conn
#if FUSE_VERSION >= FUSE_MAKE_VERSION(3, 0)
, struct fuse_config *cfg
#endif
)
{
int ret;
// init cannot fail, so if we fail here, gotrados remains at 0,
// causing other operations to fail immediately with ENXIO
ret = connect_to_cluster(&cluster);
if (ret < 0)
exit(90);
pool_name = rbd_options.pool_name;
nspace_name = rbd_options.nspace_name;
mount_image_name = rbd_options.image_name;
ret = rados_ioctx_create(cluster, pool_name, &ioctx);
if (ret < 0)
exit(91);
#if FUSE_VERSION >= FUSE_MAKE_VERSION(2, 8) && FUSE_VERSION < FUSE_MAKE_VERSION(3, 0)
conn->want |= FUSE_CAP_BIG_WRITES;
#endif
rados_ioctx_set_namespace(ioctx, nspace_name);
gotrados = 1;
// init's return value shows up in fuse_context.private_data,
// also to void (*destroy)(void *); useful?
return NULL;
}
void
rbdfs_destroy(void *unused)
{
if (!gotrados)
return;
for (int i = 0; i < MAX_RBD_IMAGES; ++i) {
if (opentbl[i].image) {
rbd_close(opentbl[i].image);
opentbl[i].image = NULL;
}
}
rados_ioctx_destroy(ioctx);
rados_shutdown(cluster);
}
int
rbdfs_checkname(const char *checkname)
{
const char *extra[] = {"@", "/"};
std::string strCheckName(checkname);
if (strCheckName.empty())
return -EINVAL;
unsigned int sz = sizeof(extra) / sizeof(const char*);
for (unsigned int i = 0; i < sz; i++)
{
std::string ex(extra[i]);
if (std::string::npos != strCheckName.find(ex))
return -EINVAL;
}
return 0;
}
// return -errno on error. fi->fh is not set until open time
int
rbdfs_create(const char *path, mode_t mode, struct fuse_file_info *fi)
{
int r;
int order = imageorder;
r = rbdfs_checkname(path+1);
if (r != 0)
{
return r;
}
r = rbd_create2(ioctx, path+1, imagesize, imagefeatures, &order);
return r;
}
int
rbdfs_rename(const char *path, const char *destname
#if FUSE_VERSION >= FUSE_MAKE_VERSION(3, 0)
, unsigned int flags
#endif
)
{
int r;
r = rbdfs_checkname(destname+1);
if (r != 0)
{
return r;
}
if (strcmp(path, "/") == 0)
return -EINVAL;
return rbd_rename(ioctx, path+1, destname+1);
}
int
rbdfs_utimens(const char *path, const struct timespec tv[2]
#if FUSE_VERSION >= FUSE_MAKE_VERSION(3, 0)
, struct fuse_file_info *fi
#endif
)
{
// called on create; not relevant
return 0;
}
int
rbdfs_unlink(const char *path)
{
int fd = find_openrbd(path+1);
if (fd != -1) {
struct rbd_openimage *rbd = &opentbl[fd];
rbd_close(rbd->image);
rbd->image = 0;
free(rbd->image_name);
rbd->rbd_stat.valid = 0;
}
return rbd_remove(ioctx, path+1);
}
int
rbdfs_truncate(const char *path, off_t size
#if FUSE_VERSION >= FUSE_MAKE_VERSION(3, 0)
, struct fuse_file_info *fi
#endif
)
{
int fd;
int r;
struct rbd_openimage *rbd;
if ((fd = open_rbd_image(path+1)) < 0)
return -ENOENT;
rbd = &opentbl[fd];
fprintf(stderr, "truncate %s to %" PRIdMAX " (0x%" PRIxMAX ")\n",
path, size, size);
r = rbd_resize(rbd->image, size);
if (r < 0)
return r;
r = rbd_stat(rbd->image, &(rbd->rbd_stat.rbd_info),
sizeof(rbd_image_info_t));
if (r < 0)
return r;
return 0;
}
/**
* set an xattr on path, with name/value, length size.
* Presumably flags are from Linux, as in XATTR_CREATE or
* XATTR_REPLACE (both "set", but fail if exist vs fail if not exist.
*
* We accept xattrs only on the root node.
*
* All values converted with strtoull, so can be expressed in any base
*/
struct rbdfuse_attr {
char *attrname;
uint64_t *attrvalp;
} attrs[] = {
{ (char*) "user.rbdfuse.imagesize", &imagesize },
{ (char*) "user.rbdfuse.imageorder", &imageorder },
{ (char*) "user.rbdfuse.imagefeatures", &imagefeatures },
{ NULL, NULL }
};
int
rbdfs_setxattr(const char *path, const char *name, const char *value,
size_t size,
int flags
#if defined(DARWIN)
,uint32_t pos
#endif
)
{
struct rbdfuse_attr *ap;
if (strcmp(path, "/") != 0)
return -EINVAL;
for (ap = attrs; ap->attrname != NULL; ap++) {
if (strcmp(name, ap->attrname) == 0) {
*ap->attrvalp = strtoull(value, NULL, 0);
fprintf(stderr, "rbd-fuse: %s set to 0x%" PRIx64 "\n",
ap->attrname, *ap->attrvalp);
return 0;
}
}
return -EINVAL;
}
int
rbdfs_getxattr(const char *path, const char *name, char *value,
size_t size
#if defined(DARWIN)
,uint32_t position
#endif
)
{
struct rbdfuse_attr *ap;
char buf[128];
// allow gets on other files; ls likes to ask for things like
// security.*
for (ap = attrs; ap->attrname != NULL; ap++) {
if (strcmp(name, ap->attrname) == 0) {
sprintf(buf, "%" PRIu64, *ap->attrvalp);
if (value != NULL && size >= strlen(buf))
strcpy(value, buf);
fprintf(stderr, "rbd-fuse: get %s\n", ap->attrname);
return (strlen(buf));
}
}
return 0;
}
int
rbdfs_listxattr(const char *path, char *list, size_t len)
{
struct rbdfuse_attr *ap;
size_t required_len = 0;
if (strcmp(path, "/") != 0)
return -EINVAL;
for (ap = attrs; ap->attrname != NULL; ap++)
required_len += strlen(ap->attrname) + 1;
if (len >= required_len) {
for (ap = attrs; ap->attrname != NULL; ap++) {
sprintf(list, "%s", ap->attrname);
list += strlen(ap->attrname) + 1;
}
}
return required_len;
}
const static struct fuse_operations rbdfs_oper = {
getattr: rbdfs_getattr,
readlink: 0,
#if FUSE_VERSION < FUSE_MAKE_VERSION(3, 0)
getdir: 0,
#endif
mknod: 0,
mkdir: 0,
unlink: rbdfs_unlink,
rmdir: 0,
symlink: 0,
rename: rbdfs_rename,
link: 0,
chmod: 0,
chown: 0,
truncate: rbdfs_truncate,
#if FUSE_VERSION < FUSE_MAKE_VERSION(3, 0)
utime: 0,
#endif
open: rbdfs_open,
read: rbdfs_read,
write: rbdfs_write,
statfs: rbdfs_statfs,
flush: 0,
release: 0,
fsync: rbdfs_fsync,
setxattr: rbdfs_setxattr,
getxattr: rbdfs_getxattr,
listxattr: rbdfs_listxattr,
removexattr: 0,
opendir: rbdfs_opendir,
readdir: rbdfs_readdir,
releasedir: rbdfs_releasedir,
fsyncdir: 0,
init: rbdfs_init,
destroy: rbdfs_destroy,
access: 0,
create: rbdfs_create,
#if FUSE_VERSION < FUSE_MAKE_VERSION(3, 0)
ftruncate: 0,
fgetattr: 0,
#endif
lock: 0,
utimens: rbdfs_utimens,
/* skip unimplemented */
};
} /* extern "C" */
enum {
KEY_HELP,
KEY_VERSION,
KEY_RADOS_POOLNAME,
KEY_RADOS_POOLNAME_LONG,
KEY_RADOS_NSPACENAME,
KEY_RADOS_NSPACENAME_LONG,
KEY_RBD_IMAGENAME,
KEY_RBD_IMAGENAME_LONG
};
static struct fuse_opt rbdfs_opts[] = {
FUSE_OPT_KEY("-h", KEY_HELP),
FUSE_OPT_KEY("--help", KEY_HELP),
FUSE_OPT_KEY("-V", KEY_VERSION),
FUSE_OPT_KEY("--version", KEY_VERSION),
{"-p %s", offsetof(struct rbd_options, pool_name), KEY_RADOS_POOLNAME},
{"--poolname=%s", offsetof(struct rbd_options, pool_name),
KEY_RADOS_POOLNAME_LONG},
{"-s %s", offsetof(struct rbd_options, nspace_name), KEY_RADOS_NSPACENAME},
{"--namespace=%s", offsetof(struct rbd_options, nspace_name),
KEY_RADOS_NSPACENAME_LONG},
{"-r %s", offsetof(struct rbd_options, image_name), KEY_RBD_IMAGENAME},
{"--image=%s", offsetof(struct rbd_options, image_name),
KEY_RBD_IMAGENAME_LONG},
FUSE_OPT_END
};
static void usage(const char *progname)
{
fprintf(stderr,
"Usage: %s mountpoint [options]\n"
"\n"
"General options:\n"
" -h --help print help\n"
" -V --version print version\n"
" -c --conf ceph configuration file [/etc/ceph/ceph.conf]\n"
" -p --poolname rados pool name [rbd]\n"
" -s --namespace rados namespace name []\n"
" -r --image RBD image name\n"
"\n", progname);
}
static int rbdfs_opt_proc(void *data, const char *arg, int key,
struct fuse_args *outargs)
{
if (key == KEY_HELP) {
usage(outargs->argv[0]);
fuse_opt_add_arg(outargs, "-ho");
fuse_main(outargs->argc, outargs->argv, &rbdfs_oper, NULL);
exit(1);
}
if (key == KEY_VERSION) {
fuse_opt_add_arg(outargs, "--version");
fuse_main(outargs->argc, outargs->argv, &rbdfs_oper, NULL);
exit(0);
}
if (key == KEY_RADOS_POOLNAME) {
if (rbd_options.pool_name != NULL) {
free(rbd_options.pool_name);
rbd_options.pool_name = NULL;
}
rbd_options.pool_name = strdup(arg+2);
return 0;
}
if (key == KEY_RADOS_NSPACENAME) {
if (rbd_options.nspace_name != NULL) {
free(rbd_options.nspace_name);
rbd_options.nspace_name = NULL;
}
rbd_options.nspace_name = strdup(arg+2);
return 0;
}
if (key == KEY_RBD_IMAGENAME) {
if (rbd_options.image_name!= NULL) {
free(rbd_options.image_name);
rbd_options.image_name = NULL;
}
rbd_options.image_name = strdup(arg+2);
return 0;
}
return 1;
}
void
simple_err(const char *msg, int err)
{
fprintf(stderr, "%s: %s\n", msg, strerror(-err));
return;
}
int
connect_to_cluster(rados_t *pcluster)
{
int r;
global_init_postfork_start(g_ceph_context);
common_init_finish(g_ceph_context);
global_init_postfork_finish(g_ceph_context);
r = rados_create_with_context(pcluster, g_ceph_context);
if (r < 0) {
simple_err("Could not create cluster handle", r);
return r;
}
r = rados_connect(*pcluster);
if (r < 0) {
simple_err("Error connecting to cluster", r);
rados_shutdown(*pcluster);
return r;
}
return 0;
}
#define OPT_NOT_FOUND -1
int main(int argc, const char *argv[])
{
memset(&rbd_image_data, 0, sizeof(rbd_image_data));
// librados will filter out -r/-f/-d options from command-line
std::map<std::string, int> filter_options = {
{"-r", OPT_NOT_FOUND},
{"-f", OPT_NOT_FOUND},
{"-d", OPT_NOT_FOUND}};
std::set<std::string> require_arg_options = {"-r"};
std::vector<const char*> arg_vector;
for (auto idx = 0; idx < argc; ++idx) {
auto it = filter_options.find(argv[idx]);
if (it != filter_options.end()) {
it->second = idx;
}
arg_vector.push_back(argv[idx]);
}
auto cct = global_init(NULL, arg_vector, CEPH_ENTITY_TYPE_CLIENT,
CODE_ENVIRONMENT_DAEMON,
CINIT_FLAG_UNPRIVILEGED_DAEMON_DEFAULTS);
g_ceph_context->_conf.set_val_or_die("pid_file", "");
g_ceph_context->_conf.set_val_or_die("daemonize", "true");
if (global_init_prefork(g_ceph_context) < 0) {
fprintf(stderr, "Failed to initialize librados\n");
exit(1);
}
for (auto& it : filter_options) {
if (it.second != OPT_NOT_FOUND) {
arg_vector.push_back(it.first.c_str());
if (require_arg_options.count(it.first) &&
it.second + 1 < argc) {
arg_vector.push_back(argv[it.second + 1]);
}
}
}
struct fuse_args args = FUSE_ARGS_INIT((int)arg_vector.size(),
(char**)&arg_vector.front());
if (fuse_opt_parse(&args, &rbd_options, rbdfs_opts,
rbdfs_opt_proc) == -1) {
exit(1);
}
return fuse_main(args.argc, args.argv, &rbdfs_oper, NULL);
}
| 21,241 | 20.944215 | 85 |
cc
|
null |
ceph-main/src/rbd_replay/ActionTypes.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#include "rbd_replay/ActionTypes.h"
#include "include/ceph_assert.h"
#include "include/byteorder.h"
#include "include/stringify.h"
#include "common/Formatter.h"
#include <iostream>
#include <boost/variant.hpp>
namespace rbd_replay {
namespace action {
namespace {
bool byte_swap_required(__u8 version) {
#if defined(CEPH_LITTLE_ENDIAN)
return (version == 0);
#else
return false;
#endif
}
void decode_big_endian_string(std::string &str, bufferlist::const_iterator &it) {
using ceph::decode;
#if defined(CEPH_LITTLE_ENDIAN)
uint32_t length;
decode(length, it);
length = swab(length);
str.clear();
it.copy(length, str);
#else
ceph_abort();
#endif
}
class EncodeVisitor : public boost::static_visitor<void> {
public:
explicit EncodeVisitor(bufferlist &bl) : m_bl(bl) {
}
template <typename Action>
inline void operator()(const Action &action) const {
using ceph::encode;
encode(static_cast<uint8_t>(Action::ACTION_TYPE), m_bl);
action.encode(m_bl);
}
private:
bufferlist &m_bl;
};
class DecodeVisitor : public boost::static_visitor<void> {
public:
DecodeVisitor(__u8 version, bufferlist::const_iterator &iter)
: m_version(version), m_iter(iter) {
}
template <typename Action>
inline void operator()(Action &action) const {
action.decode(m_version, m_iter);
}
private:
__u8 m_version;
bufferlist::const_iterator &m_iter;
};
class DumpVisitor : public boost::static_visitor<void> {
public:
explicit DumpVisitor(Formatter *formatter) : m_formatter(formatter) {}
template <typename Action>
inline void operator()(const Action &action) const {
ActionType action_type = Action::ACTION_TYPE;
m_formatter->dump_string("action_type", stringify(action_type));
action.dump(m_formatter);
}
private:
ceph::Formatter *m_formatter;
};
} // anonymous namespace
void Dependency::encode(bufferlist &bl) const {
using ceph::encode;
encode(id, bl);
encode(time_delta, bl);
}
void Dependency::decode(bufferlist::const_iterator &it) {
decode(1, it);
}
void Dependency::decode(__u8 version, bufferlist::const_iterator &it) {
using ceph::decode;
decode(id, it);
decode(time_delta, it);
if (byte_swap_required(version)) {
id = swab(id);
time_delta = swab(time_delta);
}
}
void Dependency::dump(Formatter *f) const {
f->dump_unsigned("id", id);
f->dump_unsigned("time_delta", time_delta);
}
void Dependency::generate_test_instances(std::list<Dependency *> &o) {
o.push_back(new Dependency());
o.push_back(new Dependency(1, 123456789));
}
void ActionBase::encode(bufferlist &bl) const {
using ceph::encode;
encode(id, bl);
encode(thread_id, bl);
encode(dependencies, bl);
}
void ActionBase::decode(__u8 version, bufferlist::const_iterator &it) {
using ceph::decode;
decode(id, it);
decode(thread_id, it);
if (version == 0) {
uint32_t num_successors;
decode(num_successors, it);
uint32_t num_completion_successors;
decode(num_completion_successors, it);
}
if (byte_swap_required(version)) {
id = swab(id);
thread_id = swab(thread_id);
uint32_t dep_count;
decode(dep_count, it);
dep_count = swab(dep_count);
dependencies.resize(dep_count);
for (uint32_t i = 0; i < dep_count; ++i) {
dependencies[i].decode(0, it);
}
} else {
decode(dependencies, it);
}
}
void ActionBase::dump(Formatter *f) const {
f->dump_unsigned("id", id);
f->dump_unsigned("thread_id", thread_id);
f->open_array_section("dependencies");
for (size_t i = 0; i < dependencies.size(); ++i) {
f->open_object_section("dependency");
dependencies[i].dump(f);
f->close_section();
}
f->close_section();
}
void ImageActionBase::encode(bufferlist &bl) const {
using ceph::encode;
ActionBase::encode(bl);
encode(imagectx_id, bl);
}
void ImageActionBase::decode(__u8 version, bufferlist::const_iterator &it) {
using ceph::decode;
ActionBase::decode(version, it);
decode(imagectx_id, it);
if (byte_swap_required(version)) {
imagectx_id = swab(imagectx_id);
}
}
void ImageActionBase::dump(Formatter *f) const {
ActionBase::dump(f);
f->dump_unsigned("imagectx_id", imagectx_id);
}
void IoActionBase::encode(bufferlist &bl) const {
using ceph::encode;
ImageActionBase::encode(bl);
encode(offset, bl);
encode(length, bl);
}
void IoActionBase::decode(__u8 version, bufferlist::const_iterator &it) {
using ceph::decode;
ImageActionBase::decode(version, it);
decode(offset, it);
decode(length, it);
if (byte_swap_required(version)) {
offset = swab(offset);
length = swab(length);
}
}
void IoActionBase::dump(Formatter *f) const {
ImageActionBase::dump(f);
f->dump_unsigned("offset", offset);
f->dump_unsigned("length", length);
}
void OpenImageAction::encode(bufferlist &bl) const {
using ceph::encode;
ImageActionBase::encode(bl);
encode(name, bl);
encode(snap_name, bl);
encode(read_only, bl);
}
void OpenImageAction::decode(__u8 version, bufferlist::const_iterator &it) {
using ceph::decode;
ImageActionBase::decode(version, it);
if (byte_swap_required(version)) {
decode_big_endian_string(name, it);
decode_big_endian_string(snap_name, it);
} else {
decode(name, it);
decode(snap_name, it);
}
decode(read_only, it);
}
void OpenImageAction::dump(Formatter *f) const {
ImageActionBase::dump(f);
f->dump_string("name", name);
f->dump_string("snap_name", snap_name);
f->dump_bool("read_only", read_only);
}
void AioOpenImageAction::encode(bufferlist &bl) const {
using ceph::encode;
ImageActionBase::encode(bl);
encode(name, bl);
encode(snap_name, bl);
encode(read_only, bl);
}
void AioOpenImageAction::decode(__u8 version, bufferlist::const_iterator &it) {
using ceph::decode;
ImageActionBase::decode(version, it);
if (byte_swap_required(version)) {
decode_big_endian_string(name, it);
decode_big_endian_string(snap_name, it);
} else {
decode(name, it);
decode(snap_name, it);
}
decode(read_only, it);
}
void AioOpenImageAction::dump(Formatter *f) const {
ImageActionBase::dump(f);
f->dump_string("name", name);
f->dump_string("snap_name", snap_name);
f->dump_bool("read_only", read_only);
}
void UnknownAction::encode(bufferlist &bl) const {
ceph_abort();
}
void UnknownAction::decode(__u8 version, bufferlist::const_iterator &it) {
}
void UnknownAction::dump(Formatter *f) const {
}
void ActionEntry::encode(bufferlist &bl) const {
ENCODE_START(1, 1, bl);
boost::apply_visitor(EncodeVisitor(bl), action);
ENCODE_FINISH(bl);
}
void ActionEntry::decode(bufferlist::const_iterator &it) {
DECODE_START(1, it);
decode_versioned(struct_v, it);
DECODE_FINISH(it);
}
void ActionEntry::decode_unversioned(bufferlist::const_iterator &it) {
decode_versioned(0, it);
}
void ActionEntry::decode_versioned(__u8 version, bufferlist::const_iterator &it) {
using ceph::decode;
uint8_t action_type;
decode(action_type, it);
// select the correct action variant based upon the action_type
switch (action_type) {
case ACTION_TYPE_START_THREAD:
action = StartThreadAction();
break;
case ACTION_TYPE_STOP_THREAD:
action = StopThreadAction();
break;
case ACTION_TYPE_READ:
action = ReadAction();
break;
case ACTION_TYPE_WRITE:
action = WriteAction();
break;
case ACTION_TYPE_DISCARD:
action = DiscardAction();
break;
case ACTION_TYPE_AIO_READ:
action = AioReadAction();
break;
case ACTION_TYPE_AIO_WRITE:
action = AioWriteAction();
break;
case ACTION_TYPE_AIO_DISCARD:
action = AioDiscardAction();
break;
case ACTION_TYPE_OPEN_IMAGE:
action = OpenImageAction();
break;
case ACTION_TYPE_CLOSE_IMAGE:
action = CloseImageAction();
break;
case ACTION_TYPE_AIO_OPEN_IMAGE:
action = AioOpenImageAction();
break;
case ACTION_TYPE_AIO_CLOSE_IMAGE:
action = AioCloseImageAction();
break;
}
boost::apply_visitor(DecodeVisitor(version, it), action);
}
void ActionEntry::dump(Formatter *f) const {
boost::apply_visitor(DumpVisitor(f), action);
}
void ActionEntry::generate_test_instances(std::list<ActionEntry *> &o) {
Dependencies dependencies;
dependencies.push_back(Dependency(3, 123456789));
dependencies.push_back(Dependency(4, 234567890));
o.push_back(new ActionEntry(StartThreadAction()));
o.push_back(new ActionEntry(StartThreadAction(1, 123456789, dependencies)));
o.push_back(new ActionEntry(StopThreadAction()));
o.push_back(new ActionEntry(StopThreadAction(1, 123456789, dependencies)));
o.push_back(new ActionEntry(ReadAction()));
o.push_back(new ActionEntry(ReadAction(1, 123456789, dependencies, 3, 4, 5)));
o.push_back(new ActionEntry(WriteAction()));
o.push_back(new ActionEntry(WriteAction(1, 123456789, dependencies, 3, 4,
5)));
o.push_back(new ActionEntry(DiscardAction()));
o.push_back(new ActionEntry(DiscardAction(1, 123456789, dependencies, 3, 4,
5)));
o.push_back(new ActionEntry(AioReadAction()));
o.push_back(new ActionEntry(AioReadAction(1, 123456789, dependencies, 3, 4,
5)));
o.push_back(new ActionEntry(AioWriteAction()));
o.push_back(new ActionEntry(AioWriteAction(1, 123456789, dependencies, 3, 4,
5)));
o.push_back(new ActionEntry(AioDiscardAction()));
o.push_back(new ActionEntry(AioDiscardAction(1, 123456789, dependencies, 3, 4,
5)));
o.push_back(new ActionEntry(OpenImageAction()));
o.push_back(new ActionEntry(OpenImageAction(1, 123456789, dependencies, 3,
"image_name", "snap_name",
true)));
o.push_back(new ActionEntry(CloseImageAction()));
o.push_back(new ActionEntry(CloseImageAction(1, 123456789, dependencies, 3)));
o.push_back(new ActionEntry(AioOpenImageAction()));
o.push_back(new ActionEntry(AioOpenImageAction(1, 123456789, dependencies, 3,
"image_name", "snap_name",
true)));
o.push_back(new ActionEntry(AioCloseImageAction()));
o.push_back(new ActionEntry(AioCloseImageAction(1, 123456789, dependencies, 3)));
}
std::ostream &operator<<(std::ostream &out,
const ActionType &type) {
using namespace rbd_replay::action;
switch (type) {
case ACTION_TYPE_START_THREAD:
out << "StartThread";
break;
case ACTION_TYPE_STOP_THREAD:
out << "StopThread";
break;
case ACTION_TYPE_READ:
out << "Read";
break;
case ACTION_TYPE_WRITE:
out << "Write";
break;
case ACTION_TYPE_DISCARD:
out << "Discard";
break;
case ACTION_TYPE_AIO_READ:
out << "AioRead";
break;
case ACTION_TYPE_AIO_WRITE:
out << "AioWrite";
break;
case ACTION_TYPE_AIO_DISCARD:
out << "AioDiscard";
break;
case ACTION_TYPE_OPEN_IMAGE:
out << "OpenImage";
break;
case ACTION_TYPE_CLOSE_IMAGE:
out << "CloseImage";
break;
case ACTION_TYPE_AIO_OPEN_IMAGE:
out << "AioOpenImage";
break;
case ACTION_TYPE_AIO_CLOSE_IMAGE:
out << "AioCloseImage";
break;
default:
out << "Unknown (" << static_cast<uint32_t>(type) << ")";
break;
}
return out;
}
} // namespace action
} // namespace rbd_replay
| 11,577 | 25.800926 | 83 |
cc
|
null |
ceph-main/src/rbd_replay/ActionTypes.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#ifndef CEPH_RBD_REPLAY_ACTION_TYPES_H
#define CEPH_RBD_REPLAY_ACTION_TYPES_H
#include "include/int_types.h"
#include "include/buffer_fwd.h"
#include "include/encoding.h"
#include <iosfwd>
#include <list>
#include <string>
#include <vector>
#include <boost/variant/variant.hpp>
namespace ceph { class Formatter; }
namespace rbd_replay {
namespace action {
typedef uint64_t imagectx_id_t;
typedef uint64_t thread_id_t;
/// Even IDs are normal actions, odd IDs are completions.
typedef uint32_t action_id_t;
static const std::string BANNER("rbd-replay-trace");
/**
* Dependencies link actions to earlier actions or completions.
* If an action has a dependency \c d then it waits until \c d.time_delta
* nanoseconds after the action or completion with ID \c d.id has fired.
*/
struct Dependency {
/// ID of the action or completion to wait for.
action_id_t id;
/// Nanoseconds of delay to wait until after the action or completion fires.
uint64_t time_delta;
/**
* @param id ID of the action or completion to wait for.
* @param time_delta Nanoseconds of delay to wait after the action or
* completion fires.
*/
Dependency() : id(0), time_delta(0) {
}
Dependency(action_id_t id, uint64_t time_delta)
: id(id), time_delta(time_delta) {
}
void encode(bufferlist &bl) const;
void decode(bufferlist::const_iterator &it);
void decode(__u8 version, bufferlist::const_iterator &it);
void dump(Formatter *f) const;
static void generate_test_instances(std::list<Dependency *> &o);
};
WRITE_CLASS_ENCODER(Dependency);
typedef std::vector<Dependency> Dependencies;
enum ActionType {
ACTION_TYPE_START_THREAD = 0,
ACTION_TYPE_STOP_THREAD = 1,
ACTION_TYPE_READ = 2,
ACTION_TYPE_WRITE = 3,
ACTION_TYPE_AIO_READ = 4,
ACTION_TYPE_AIO_WRITE = 5,
ACTION_TYPE_OPEN_IMAGE = 6,
ACTION_TYPE_CLOSE_IMAGE = 7,
ACTION_TYPE_AIO_OPEN_IMAGE = 8,
ACTION_TYPE_AIO_CLOSE_IMAGE = 9,
ACTION_TYPE_DISCARD = 10,
ACTION_TYPE_AIO_DISCARD = 11
};
struct ActionBase {
action_id_t id;
thread_id_t thread_id;
Dependencies dependencies;
ActionBase() : id(0), thread_id(0) {
}
ActionBase(action_id_t id, thread_id_t thread_id,
const Dependencies &dependencies)
: id(id), thread_id(thread_id), dependencies(dependencies) {
}
void encode(bufferlist &bl) const;
void decode(__u8 version, bufferlist::const_iterator &it);
void dump(Formatter *f) const;
};
struct StartThreadAction : public ActionBase {
static const ActionType ACTION_TYPE = ACTION_TYPE_START_THREAD;
StartThreadAction() {
}
StartThreadAction(action_id_t id, thread_id_t thread_id,
const Dependencies &dependencies)
: ActionBase(id, thread_id, dependencies) {
}
};
struct StopThreadAction : public ActionBase {
static const ActionType ACTION_TYPE = ACTION_TYPE_STOP_THREAD;
StopThreadAction() {
}
StopThreadAction(action_id_t id, thread_id_t thread_id,
const Dependencies &dependencies)
: ActionBase(id, thread_id, dependencies) {
}
};
struct ImageActionBase : public ActionBase {
imagectx_id_t imagectx_id;
ImageActionBase() : imagectx_id(0) {
}
ImageActionBase(action_id_t id, thread_id_t thread_id,
const Dependencies &dependencies, imagectx_id_t imagectx_id)
: ActionBase(id, thread_id, dependencies), imagectx_id(imagectx_id) {
}
void encode(bufferlist &bl) const;
void decode(__u8 version, bufferlist::const_iterator &it);
void dump(Formatter *f) const;
};
struct IoActionBase : public ImageActionBase {
uint64_t offset;
uint64_t length;
IoActionBase() : offset(0), length(0) {
}
IoActionBase(action_id_t id, thread_id_t thread_id,
const Dependencies &dependencies, imagectx_id_t imagectx_id,
uint64_t offset, uint64_t length)
: ImageActionBase(id, thread_id, dependencies, imagectx_id),
offset(offset), length(length) {
}
void encode(bufferlist &bl) const;
void decode(__u8 version, bufferlist::const_iterator &it);
void dump(Formatter *f) const;
};
struct ReadAction : public IoActionBase {
static const ActionType ACTION_TYPE = ACTION_TYPE_READ;
ReadAction() {
}
ReadAction(action_id_t id, thread_id_t thread_id,
const Dependencies &dependencies, imagectx_id_t imagectx_id,
uint64_t offset, uint64_t length)
: IoActionBase(id, thread_id, dependencies, imagectx_id, offset, length) {
}
};
struct WriteAction : public IoActionBase {
static const ActionType ACTION_TYPE = ACTION_TYPE_WRITE;
WriteAction() {
}
WriteAction(action_id_t id, thread_id_t thread_id,
const Dependencies &dependencies, imagectx_id_t imagectx_id,
uint64_t offset, uint64_t length)
: IoActionBase(id, thread_id, dependencies, imagectx_id, offset, length) {
}
};
struct DiscardAction : public IoActionBase {
static const ActionType ACTION_TYPE = ACTION_TYPE_DISCARD;
DiscardAction() {
}
DiscardAction(action_id_t id, thread_id_t thread_id,
const Dependencies &dependencies, imagectx_id_t imagectx_id,
uint64_t offset, uint64_t length)
: IoActionBase(id, thread_id, dependencies, imagectx_id, offset, length) {
}
};
struct AioReadAction : public IoActionBase {
static const ActionType ACTION_TYPE = ACTION_TYPE_AIO_READ;
AioReadAction() {
}
AioReadAction(action_id_t id, thread_id_t thread_id,
const Dependencies &dependencies, imagectx_id_t imagectx_id,
uint64_t offset, uint64_t length)
: IoActionBase(id, thread_id, dependencies, imagectx_id, offset, length) {
}
};
struct AioWriteAction : public IoActionBase {
static const ActionType ACTION_TYPE = ACTION_TYPE_AIO_WRITE;
AioWriteAction() {
}
AioWriteAction(action_id_t id, thread_id_t thread_id,
const Dependencies &dependencies, imagectx_id_t imagectx_id,
uint64_t offset, uint64_t length)
: IoActionBase(id, thread_id, dependencies, imagectx_id, offset, length) {
}
};
struct AioDiscardAction : public IoActionBase {
static const ActionType ACTION_TYPE = ACTION_TYPE_AIO_DISCARD;
AioDiscardAction() {
}
AioDiscardAction(action_id_t id, thread_id_t thread_id,
const Dependencies &dependencies, imagectx_id_t imagectx_id,
uint64_t offset, uint64_t length)
: IoActionBase(id, thread_id, dependencies, imagectx_id, offset, length) {
}
};
struct OpenImageAction : public ImageActionBase {
static const ActionType ACTION_TYPE = ACTION_TYPE_OPEN_IMAGE;
std::string name;
std::string snap_name;
bool read_only;
OpenImageAction() : read_only(false) {
}
OpenImageAction(action_id_t id, thread_id_t thread_id,
const Dependencies &dependencies, imagectx_id_t imagectx_id,
const std::string &name, const std::string &snap_name,
bool read_only)
: ImageActionBase(id, thread_id, dependencies, imagectx_id),
name(name), snap_name(snap_name), read_only(read_only) {
}
void encode(bufferlist &bl) const;
void decode(__u8 version, bufferlist::const_iterator &it);
void dump(Formatter *f) const;
};
struct CloseImageAction : public ImageActionBase {
static const ActionType ACTION_TYPE = ACTION_TYPE_CLOSE_IMAGE;
CloseImageAction() {
}
CloseImageAction(action_id_t id, thread_id_t thread_id,
const Dependencies &dependencies, imagectx_id_t imagectx_id)
: ImageActionBase(id, thread_id, dependencies, imagectx_id) {
}
};
struct AioOpenImageAction : public ImageActionBase {
static const ActionType ACTION_TYPE = ACTION_TYPE_AIO_OPEN_IMAGE;
std::string name;
std::string snap_name;
bool read_only;
AioOpenImageAction() : read_only(false) {
}
AioOpenImageAction(action_id_t id, thread_id_t thread_id,
const Dependencies &dependencies, imagectx_id_t imagectx_id,
const std::string &name, const std::string &snap_name,
bool read_only)
: ImageActionBase(id, thread_id, dependencies, imagectx_id),
name(name), snap_name(snap_name), read_only(read_only) {
}
void encode(bufferlist &bl) const;
void decode(__u8 version, bufferlist::const_iterator &it);
void dump(Formatter *f) const;
};
struct AioCloseImageAction : public ImageActionBase {
static const ActionType ACTION_TYPE = ACTION_TYPE_AIO_CLOSE_IMAGE;
AioCloseImageAction() {
}
AioCloseImageAction(action_id_t id, thread_id_t thread_id,
const Dependencies &dependencies, imagectx_id_t imagectx_id)
: ImageActionBase(id, thread_id, dependencies, imagectx_id) {
}
};
struct UnknownAction {
static const ActionType ACTION_TYPE = static_cast<ActionType>(-1);
void encode(bufferlist &bl) const;
void decode(__u8 version, bufferlist::const_iterator &it);
void dump(Formatter *f) const;
};
typedef boost::variant<StartThreadAction,
StopThreadAction,
ReadAction,
WriteAction,
DiscardAction,
AioReadAction,
AioWriteAction,
AioDiscardAction,
OpenImageAction,
CloseImageAction,
AioOpenImageAction,
AioCloseImageAction,
UnknownAction> Action;
class ActionEntry {
public:
Action action;
ActionEntry() : action(UnknownAction()) {
}
ActionEntry(const Action &action) : action(action) {
}
void encode(bufferlist &bl) const;
void decode(bufferlist::const_iterator &it);
void decode_unversioned(bufferlist::const_iterator &it);
void dump(Formatter *f) const;
static void generate_test_instances(std::list<ActionEntry *> &o);
private:
void decode_versioned(__u8 version, bufferlist::const_iterator &it);
};
WRITE_CLASS_ENCODER(ActionEntry);
std::ostream &operator<<(std::ostream &out,
const rbd_replay::action::ActionType &type);
} // namespace action
} // namespace rbd_replay
#endif // CEPH_RBD_REPLAY_ACTION_TYPES_H
| 10,290 | 29.267647 | 79 |
h
|
null |
ceph-main/src/rbd_replay/BoundedBuffer.hpp
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#ifndef _INCLUDED_BOUNDED_BUFFER_HPP
#define _INCLUDED_BOUNDED_BUFFER_HPP
#include <boost/bind/bind.hpp>
#include <boost/circular_buffer.hpp>
#include <boost/thread/condition.hpp>
#include <boost/thread/mutex.hpp>
/**
Blocking, fixed-capacity, thread-safe FIFO queue useful for communicating between threads.
This code was taken from the Boost docs: http://www.boost.org/doc/libs/1_55_0/libs/circular_buffer/example/circular_buffer_bound_example.cpp
*/
template <class T>
class BoundedBuffer {
public:
typedef boost::circular_buffer<T> container_type;
typedef typename container_type::size_type size_type;
typedef typename container_type::value_type value_type;
typedef typename boost::call_traits<value_type>::param_type param_type;
explicit BoundedBuffer(size_type capacity) : m_unread(0), m_container(capacity) {
}
/**
Inserts an element into the queue.
Blocks if the queue is full.
*/
void push_front(typename boost::call_traits<value_type>::param_type item) {
// `param_type` represents the "best" way to pass a parameter of type `value_type` to a method.
boost::mutex::scoped_lock lock(m_mutex);
m_not_full.wait(lock, boost::bind(&BoundedBuffer<value_type>::is_not_full, this));
m_container.push_front(item);
++m_unread;
lock.unlock();
m_not_empty.notify_one();
}
/**
Removes an element from the queue.
Blocks if the queue is empty.
*/
void pop_back(value_type* pItem) {
boost::mutex::scoped_lock lock(m_mutex);
m_not_empty.wait(lock, boost::bind(&BoundedBuffer<value_type>::is_not_empty, this));
*pItem = m_container[--m_unread];
lock.unlock();
m_not_full.notify_one();
}
private:
BoundedBuffer(const BoundedBuffer&); // Disabled copy constructor.
BoundedBuffer& operator= (const BoundedBuffer&); // Disabled assign operator.
bool is_not_empty() const {
return m_unread > 0;
}
bool is_not_full() const {
return m_unread < m_container.capacity();
}
size_type m_unread;
container_type m_container;
boost::mutex m_mutex;
boost::condition m_not_empty;
boost::condition m_not_full;
};
#endif
| 2,248 | 30.236111 | 143 |
hpp
|
null |
ceph-main/src/rbd_replay/BufferReader.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#include "rbd_replay/BufferReader.h"
#include "include/ceph_assert.h"
#include "include/intarith.h"
namespace rbd_replay {
BufferReader::BufferReader(int fd, size_t min_bytes, size_t max_bytes)
: m_fd(fd), m_min_bytes(min_bytes), m_max_bytes(max_bytes),
m_bl_it(m_bl.begin()), m_eof_reached(false) {
ceph_assert(m_min_bytes <= m_max_bytes);
}
int BufferReader::fetch(bufferlist::const_iterator **it) {
if (m_bl_it.get_remaining() < m_min_bytes) {
ssize_t bytes_to_read = round_up_to(m_max_bytes - m_bl_it.get_remaining(),
CEPH_PAGE_SIZE);
while (!m_eof_reached && bytes_to_read > 0) {
int r = m_bl.read_fd(m_fd, CEPH_PAGE_SIZE);
if (r < 0) {
return r;
}
if (r == 0) {
m_eof_reached = true;
}
ceph_assert(r <= bytes_to_read);
bytes_to_read -= r;
}
}
*it = &m_bl_it;
return 0;
}
} // namespace rbd_replay
| 1,026 | 26.026316 | 78 |
cc
|
null |
ceph-main/src/rbd_replay/BufferReader.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
#ifndef CEPH_RBD_REPLAY_BUFFER_READER_H
#define CEPH_RBD_REPLAY_BUFFER_READER_H
#include "include/int_types.h"
#include "include/buffer.h"
namespace rbd_replay {
class BufferReader {
public:
static const size_t DEFAULT_MIN_BYTES = 1<<20;
static const size_t DEFAULT_MAX_BYTES = 1<<22;
BufferReader(int fd, size_t min_bytes = DEFAULT_MIN_BYTES,
size_t max_bytes = DEFAULT_MAX_BYTES);
int fetch(bufferlist::const_iterator **it);
private:
int m_fd;
size_t m_min_bytes;
size_t m_max_bytes;
bufferlist m_bl;
bufferlist::const_iterator m_bl_it;
bool m_eof_reached;
};
} // namespace rbd_replay
#endif // CEPH_RBD_REPLAY_BUFFER_READER_H
| 773 | 21.114286 | 70 |
h
|
null |
ceph-main/src/rbd_replay/ImageNameMap.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2014 Adam Crume <[email protected]>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#include "ImageNameMap.hpp"
using namespace std;
using namespace rbd_replay;
bool ImageNameMap::parse_mapping(string mapping_string, Mapping *mapping) const {
string fields[2];
int field = 0;
for (size_t i = 0, n = mapping_string.length(); i < n; i++) {
char c = mapping_string[i];
switch (c) {
case '\\':
if (i != n - 1 && mapping_string[i + 1] == '=') {
i++;
fields[field].push_back('=');
} else {
fields[field].push_back('\\');
}
break;
case '=':
if (field == 1) {
return false;
}
field = 1;
break;
default:
fields[field].push_back(c);
}
}
if (field == 0) {
return false;
}
if (!mapping->first.parse(fields[0])) {
return false;
}
if (!mapping->second.parse(fields[1])) {
return false;
}
return true;
}
void ImageNameMap::add_mapping(const Mapping& mapping) {
m_map.insert(mapping);
}
rbd_loc ImageNameMap::map(const rbd_loc& name) const {
std::map<rbd_loc, rbd_loc>::const_iterator p(m_map.find(name));
if (p == m_map.end()) {
return name;
} else {
return p->second;
}
}
| 1,538 | 20.985714 | 81 |
cc
|
null |
ceph-main/src/rbd_replay/ImageNameMap.hpp
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2014 Adam Crume <[email protected]>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#ifndef _INCLUDED_RBD_REPLAY_IMAGENAMEMAP_HPP
#define _INCLUDED_RBD_REPLAY_IMAGENAMEMAP_HPP
#include <map>
#include <string>
#include "rbd_loc.hpp"
namespace rbd_replay {
/**
Maps image names.
*/
class ImageNameMap {
public:
typedef std::pair<rbd_loc, rbd_loc> Mapping;
/**
Parses a mapping.
If parsing fails, the contents of \c mapping are undefined.
@param[in] mapping_string string representation of the mapping
@param[out] mapping stores the parsed mapping
@retval true parsing was successful
*/
bool parse_mapping(std::string mapping_string, Mapping *mapping) const;
void add_mapping(const Mapping& mapping);
/**
Maps an image name.
If no mapping matches the name, it is returned unmodified.
*/
rbd_loc map(const rbd_loc& name) const;
private:
std::map<rbd_loc, rbd_loc> m_map;
};
}
#endif
| 1,287 | 22.418182 | 73 |
hpp
|
null |
ceph-main/src/rbd_replay/PendingIO.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2014 Adam Crume <[email protected]>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#include "PendingIO.hpp"
#include "rbd_replay_debug.hpp"
#define dout_context g_ceph_context
using namespace rbd_replay;
extern "C"
void rbd_replay_pending_io_callback(librbd::completion_t cb, void *arg) {
PendingIO *io = static_cast<PendingIO*>(arg);
io->completed(cb);
}
PendingIO::PendingIO(action_id_t id,
ActionCtx &worker)
: m_id(id),
m_completion(new librbd::RBD::AioCompletion(this, rbd_replay_pending_io_callback)),
m_worker(worker) {
}
PendingIO::~PendingIO() {
m_completion->release();
}
void PendingIO::completed(librbd::completion_t cb) {
dout(ACTION_LEVEL) << "Completed pending IO #" << m_id << dendl;
ssize_t r = m_completion->get_return_value();
assertf(r >= 0, "id = %d, r = %d", m_id, r);
m_worker.remove_pending(shared_from_this());
}
| 1,220 | 26.133333 | 87 |
cc
|
null |
ceph-main/src/rbd_replay/PendingIO.hpp
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2014 Adam Crume <[email protected]>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#ifndef _INCLUDED_RBD_REPLAY_PENDINGIO_HPP
#define _INCLUDED_RBD_REPLAY_PENDINGIO_HPP
#include <boost/enable_shared_from_this.hpp>
#include "actions.hpp"
/// Do not call outside of rbd_replay::PendingIO.
extern "C"
void rbd_replay_pending_io_callback(librbd::completion_t cb, void *arg);
namespace rbd_replay {
/**
A PendingIO is an I/O operation that has been started but not completed.
*/
class PendingIO : public boost::enable_shared_from_this<PendingIO> {
public:
typedef boost::shared_ptr<PendingIO> ptr;
PendingIO(action_id_t id,
ActionCtx &worker);
~PendingIO();
action_id_t id() const {
return m_id;
}
ceph::bufferlist &bufferlist() {
return m_bl;
}
librbd::RBD::AioCompletion &completion() {
return *m_completion;
}
private:
void completed(librbd::completion_t cb);
friend void ::rbd_replay_pending_io_callback(librbd::completion_t cb, void *arg);
const action_id_t m_id;
ceph::bufferlist m_bl;
librbd::RBD::AioCompletion *m_completion;
ActionCtx &m_worker;
};
}
#endif
| 1,474 | 21.692308 | 83 |
hpp
|
null |
ceph-main/src/rbd_replay/Replayer.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2014 Adam Crume <[email protected]>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#include "Replayer.hpp"
#include "common/errno.h"
#include "include/scope_guard.h"
#include "rbd_replay/ActionTypes.h"
#include "rbd_replay/BufferReader.h"
#include <boost/foreach.hpp>
#include <chrono>
#include <condition_variable>
#include <thread>
#include <fstream>
#include "global/global_context.h"
#include "rbd_replay_debug.hpp"
#define dout_context g_ceph_context
using std::cerr;
using std::cout;
using namespace rbd_replay;
namespace {
bool is_versioned_replay(BufferReader &buffer_reader) {
bufferlist::const_iterator *it;
int r = buffer_reader.fetch(&it);
if (r < 0) {
return false;
}
if (it->get_remaining() < action::BANNER.size()) {
return false;
}
std::string banner;
it->copy(action::BANNER.size(), banner);
bool versioned = (banner == action::BANNER);
if (!versioned) {
it->seek(0);
}
return versioned;
}
} // anonymous namespace
Worker::Worker(Replayer &replayer)
: m_replayer(replayer),
m_buffer(100),
m_done(false) {
}
void Worker::start() {
m_thread = std::make_shared<std::thread>(&Worker::run, this);
}
// Should only be called by StopThreadAction
void Worker::stop() {
m_done = true;
}
void Worker::join() {
m_thread->join();
}
void Worker::send(Action::ptr action) {
ceph_assert(action);
m_buffer.push_front(action);
}
void Worker::add_pending(PendingIO::ptr io) {
ceph_assert(io);
std::scoped_lock lock{m_pending_ios_mutex};
assertf(m_pending_ios.count(io->id()) == 0, "id = %d", io->id());
m_pending_ios[io->id()] = io;
}
void Worker::run() {
dout(THREAD_LEVEL) << "Worker thread started" << dendl;
while (!m_done) {
Action::ptr action;
m_buffer.pop_back(&action);
m_replayer.wait_for_actions(action->predecessors());
action->perform(*this);
m_replayer.set_action_complete(action->id());
}
{
std::unique_lock lock{m_pending_ios_mutex};
bool first_time = true;
while (!m_pending_ios.empty()) {
if (!first_time) {
dout(THREAD_LEVEL) << "Worker thread trying to stop, still waiting for " << m_pending_ios.size() << " pending IOs to complete:" << dendl;
std::pair<action_id_t, PendingIO::ptr> p;
BOOST_FOREACH(p, m_pending_ios) {
dout(THREAD_LEVEL) << "> " << p.first << dendl;
}
}
m_pending_ios_empty.wait_for(lock, std::chrono::seconds(1));
first_time = false;
}
}
dout(THREAD_LEVEL) << "Worker thread stopped" << dendl;
}
void Worker::remove_pending(PendingIO::ptr io) {
ceph_assert(io);
m_replayer.set_action_complete(io->id());
std::scoped_lock lock{m_pending_ios_mutex};
size_t num_erased = m_pending_ios.erase(io->id());
assertf(num_erased == 1, "id = %d", io->id());
if (m_pending_ios.empty()) {
m_pending_ios_empty.notify_all();
}
}
librbd::Image* Worker::get_image(imagectx_id_t imagectx_id) {
return m_replayer.get_image(imagectx_id);
}
void Worker::put_image(imagectx_id_t imagectx_id, librbd::Image* image) {
ceph_assert(image);
m_replayer.put_image(imagectx_id, image);
}
void Worker::erase_image(imagectx_id_t imagectx_id) {
m_replayer.erase_image(imagectx_id);
}
librbd::RBD* Worker::rbd() {
return m_replayer.get_rbd();
}
librados::IoCtx* Worker::ioctx() {
return m_replayer.get_ioctx();
}
void Worker::set_action_complete(action_id_t id) {
m_replayer.set_action_complete(id);
}
bool Worker::readonly() const {
return m_replayer.readonly();
}
rbd_loc Worker::map_image_name(std::string image_name, std::string snap_name) const {
return m_replayer.image_name_map().map(rbd_loc("", image_name, snap_name));
}
Replayer::Replayer(int num_action_trackers)
: m_rbd(NULL), m_ioctx(0),
m_latency_multiplier(1.0),
m_readonly(false), m_dump_perf_counters(false),
m_num_action_trackers(num_action_trackers),
m_action_trackers(new action_tracker_d[m_num_action_trackers]) {
assertf(num_action_trackers > 0, "num_action_trackers = %d", num_action_trackers);
}
Replayer::~Replayer() {
delete[] m_action_trackers;
}
Replayer::action_tracker_d &Replayer::tracker_for(action_id_t id) {
return m_action_trackers[id % m_num_action_trackers];
}
void Replayer::run(const std::string& replay_file) {
{
librados::Rados rados;
rados.init(NULL);
int r = rados.init_with_context(g_ceph_context);
if (r) {
cerr << "Failed to initialize RADOS: " << cpp_strerror(r) << std::endl;
goto out;
}
r = rados.connect();
if (r) {
cerr << "Failed to connect to cluster: " << cpp_strerror(r) << std::endl;
goto out;
}
if (m_pool_name.empty()) {
r = rados.conf_get("rbd_default_pool", m_pool_name);
if (r < 0) {
cerr << "Failed to retrieve default pool: " << cpp_strerror(r)
<< std::endl;
goto out;
}
}
m_ioctx = new librados::IoCtx();
{
r = rados.ioctx_create(m_pool_name.c_str(), *m_ioctx);
if (r) {
cerr << "Failed to open pool " << m_pool_name << ": "
<< cpp_strerror(r) << std::endl;
goto out2;
}
m_rbd = new librbd::RBD();
std::map<thread_id_t, Worker*> workers;
int fd = open(replay_file.c_str(), O_RDONLY|O_BINARY);
if (fd < 0) {
std::cerr << "Failed to open " << replay_file << ": "
<< cpp_strerror(errno) << std::endl;
exit(1);
}
auto close_fd = make_scope_guard([fd] { close(fd); });
BufferReader buffer_reader(fd);
bool versioned = is_versioned_replay(buffer_reader);
while (true) {
action::ActionEntry action_entry;
try {
bufferlist::const_iterator *it;
int r = buffer_reader.fetch(&it);
if (r < 0) {
std::cerr << "Failed to read from trace file: " << cpp_strerror(r)
<< std::endl;
exit(-r);
}
if (it->get_remaining() == 0) {
break;
}
if (versioned) {
action_entry.decode(*it);
} else {
action_entry.decode_unversioned(*it);
}
} catch (const buffer::error &err) {
std::cerr << "Failed to decode trace action: " << err.what() << std::endl;
exit(1);
}
Action::ptr action = Action::construct(action_entry);
if (!action) {
// unknown / unsupported action
continue;
}
if (action->is_start_thread()) {
Worker *worker = new Worker(*this);
workers[action->thread_id()] = worker;
worker->start();
} else {
workers[action->thread_id()]->send(action);
}
}
dout(THREAD_LEVEL) << "Waiting for workers to die" << dendl;
std::pair<thread_id_t, Worker*> w;
BOOST_FOREACH(w, workers) {
w.second->join();
delete w.second;
}
clear_images();
delete m_rbd;
m_rbd = NULL;
}
out2:
delete m_ioctx;
m_ioctx = NULL;
}
out:
;
}
librbd::Image* Replayer::get_image(imagectx_id_t imagectx_id) {
std::scoped_lock lock{m_images_mutex};
return m_images[imagectx_id];
}
void Replayer::put_image(imagectx_id_t imagectx_id, librbd::Image *image) {
ceph_assert(image);
std::unique_lock lock{m_images_mutex};
ceph_assert(m_images.count(imagectx_id) == 0);
m_images[imagectx_id] = image;
}
void Replayer::erase_image(imagectx_id_t imagectx_id) {
std::unique_lock lock{m_images_mutex};
librbd::Image* image = m_images[imagectx_id];
if (m_dump_perf_counters) {
std::string command = "perf dump";
cmdmap_t cmdmap;
JSONFormatter jf(true);
bufferlist out;
std::stringstream ss;
g_ceph_context->do_command(command, cmdmap, &jf, ss, &out);
jf.flush(cout);
cout << std::endl;
cout.flush();
}
delete image;
m_images.erase(imagectx_id);
}
void Replayer::set_action_complete(action_id_t id) {
dout(DEPGRAPH_LEVEL) << "ActionTracker::set_complete(" << id << ")" << dendl;
auto now = std::chrono::system_clock::now();
action_tracker_d &tracker = tracker_for(id);
std::unique_lock lock{tracker.mutex};
ceph_assert(tracker.actions.count(id) == 0);
tracker.actions[id] = now;
tracker.condition.notify_all();
}
bool Replayer::is_action_complete(action_id_t id) {
action_tracker_d &tracker = tracker_for(id);
std::shared_lock lock{tracker.mutex};
return tracker.actions.count(id) > 0;
}
void Replayer::wait_for_actions(const action::Dependencies &deps) {
auto release_time = std::chrono::time_point<std::chrono::system_clock>::min();
for(auto& dep : deps) {
dout(DEPGRAPH_LEVEL) << "Waiting for " << dep.id << dendl;
auto start_time = std::chrono::system_clock::now();
action_tracker_d &tracker = tracker_for(dep.id);
std::unique_lock lock{tracker.mutex};
bool first_time = true;
while (tracker.actions.count(dep.id) == 0) {
if (!first_time) {
dout(DEPGRAPH_LEVEL) << "Still waiting for " << dep.id << dendl;
}
tracker.condition.wait_for(lock, std::chrono::seconds(1));
first_time = false;
}
auto action_completed_time(tracker.actions[dep.id]);
lock.unlock();
auto end_time = std::chrono::system_clock::now();
auto micros = std::chrono::duration_cast<std::chrono::microseconds>(end_time - start_time).count();
dout(DEPGRAPH_LEVEL) << "Finished waiting for " << dep.id << " after " << micros << " microseconds" << dendl;
// Apparently the nanoseconds constructor is optional:
// http://www.boost.org/doc/libs/1_46_0/doc/html/date_time/details.html#compile_options
auto sub_release_time{action_completed_time +
std::chrono::microseconds{static_cast<long long>(dep.time_delta * m_latency_multiplier / 1000)}};
if (sub_release_time > release_time) {
release_time = sub_release_time;
}
}
if (release_time > std::chrono::system_clock::now()) {
auto sleep_for = release_time - std::chrono::system_clock::now();
dout(SLEEP_LEVEL) << "Sleeping for "
<< std::chrono::duration_cast<std::chrono::microseconds>(sleep_for).count()
<< " microseconds" << dendl;
std::this_thread::sleep_until(release_time);
}
}
void Replayer::clear_images() {
std::shared_lock lock{m_images_mutex};
if (m_dump_perf_counters && !m_images.empty()) {
std::string command = "perf dump";
cmdmap_t cmdmap;
JSONFormatter jf(true);
bufferlist out;
std::stringstream ss;
g_ceph_context->do_command(command, cmdmap, &jf, ss, &out);
jf.flush(cout);
cout << std::endl;
cout.flush();
}
for (auto& p : m_images) {
delete p.second;
}
m_images.clear();
}
void Replayer::set_latency_multiplier(float f) {
assertf(f >= 0, "f = %f", f);
m_latency_multiplier = f;
}
bool Replayer::readonly() const {
return m_readonly;
}
void Replayer::set_readonly(bool readonly) {
m_readonly = readonly;
}
std::string Replayer::pool_name() const {
return m_pool_name;
}
void Replayer::set_pool_name(std::string pool_name) {
m_pool_name = pool_name;
}
| 11,257 | 26.525672 | 138 |
cc
|
null |
ceph-main/src/rbd_replay/Replayer.hpp
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2014 Adam Crume <[email protected]>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#ifndef _INCLUDED_RBD_REPLAY_REPLAYER_HPP
#define _INCLUDED_RBD_REPLAY_REPLAYER_HPP
#include <chrono>
#include <mutex>
#include <thread>
#include <condition_variable>
#include "rbd_replay/ActionTypes.h"
#include "BoundedBuffer.hpp"
#include "ImageNameMap.hpp"
#include "PendingIO.hpp"
namespace rbd_replay {
class Replayer;
/**
Performs Actions within a single thread.
*/
class Worker : public ActionCtx {
public:
explicit Worker(Replayer &replayer);
void start();
/// Should only be called by StopThreadAction
void stop() override;
void join();
void send(Action::ptr action);
void add_pending(PendingIO::ptr io) override;
void remove_pending(PendingIO::ptr io) override;
librbd::Image* get_image(imagectx_id_t imagectx_id) override;
void put_image(imagectx_id_t imagectx_id, librbd::Image* image) override;
void erase_image(imagectx_id_t imagectx_id) override;
librbd::RBD* rbd() override;
librados::IoCtx* ioctx() override;
void set_action_complete(action_id_t id) override;
bool readonly() const override;
rbd_loc map_image_name(std::string image_name, std::string snap_name) const override;
private:
void run();
Replayer &m_replayer;
BoundedBuffer<Action::ptr> m_buffer;
std::shared_ptr<std::thread> m_thread;
std::map<action_id_t, PendingIO::ptr> m_pending_ios;
std::mutex m_pending_ios_mutex;
std::condition_variable_any m_pending_ios_empty;
bool m_done;
};
class Replayer {
public:
explicit Replayer(int num_action_trackers);
~Replayer();
void run(const std::string &replay_file);
librbd::RBD* get_rbd() {
return m_rbd;
}
librados::IoCtx* get_ioctx() {
return m_ioctx;
}
librbd::Image* get_image(imagectx_id_t imagectx_id);
void put_image(imagectx_id_t imagectx_id, librbd::Image *image);
void erase_image(imagectx_id_t imagectx_id);
void set_action_complete(action_id_t id);
bool is_action_complete(action_id_t id);
void wait_for_actions(const action::Dependencies &deps);
std::string pool_name() const;
void set_pool_name(std::string pool_name);
void set_latency_multiplier(float f);
bool readonly() const;
void set_readonly(bool readonly);
void set_image_name_map(const ImageNameMap &map) {
m_image_name_map = map;
}
void set_dump_perf_counters(bool dump_perf_counters) {
m_dump_perf_counters = dump_perf_counters;
}
const ImageNameMap &image_name_map() const {
return m_image_name_map;
}
private:
struct action_tracker_d {
/// Maps an action ID to the time the action completed
std::map<action_id_t, std::chrono::system_clock::time_point> actions;
std::shared_mutex mutex;
std::condition_variable_any condition;
};
void clear_images();
action_tracker_d &tracker_for(action_id_t id);
/// Disallow copying
Replayer(const Replayer& rhs);
/// Disallow assignment
const Replayer& operator=(const Replayer& rhs);
librbd::RBD* m_rbd;
librados::IoCtx* m_ioctx;
std::string m_pool_name;
float m_latency_multiplier;
bool m_readonly;
ImageNameMap m_image_name_map;
bool m_dump_perf_counters;
std::map<imagectx_id_t, librbd::Image*> m_images;
std::shared_mutex m_images_mutex;
/// Actions are hashed across the trackers by ID.
/// Number of trackers should probably be larger than the number of cores and prime.
/// Should definitely be odd.
const int m_num_action_trackers;
action_tracker_d* m_action_trackers;
};
}
#endif
| 3,876 | 22.077381 | 87 |
hpp
|
null |
ceph-main/src/rbd_replay/actions.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2014 Adam Crume <[email protected]>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#include "actions.hpp"
#include <boost/foreach.hpp>
#include <cstdlib>
#include "PendingIO.hpp"
#include "rbd_replay_debug.hpp"
#define dout_context g_ceph_context
using std::cerr;
using namespace rbd_replay;
namespace {
std::string create_fake_data() {
char data[1 << 20]; // 1 MB
for (unsigned int i = 0; i < sizeof(data); i++) {
data[i] = (char) i;
}
return std::string(data, sizeof(data));
}
struct ConstructVisitor : public boost::static_visitor<Action::ptr> {
inline Action::ptr operator()(const action::StartThreadAction &action) const {
return Action::ptr(new StartThreadAction(action));
}
inline Action::ptr operator()(const action::StopThreadAction &action) const{
return Action::ptr(new StopThreadAction(action));
}
inline Action::ptr operator()(const action::ReadAction &action) const {
return Action::ptr(new ReadAction(action));
}
inline Action::ptr operator()(const action::AioReadAction &action) const {
return Action::ptr(new AioReadAction(action));
}
inline Action::ptr operator()(const action::WriteAction &action) const {
return Action::ptr(new WriteAction(action));
}
inline Action::ptr operator()(const action::AioWriteAction &action) const {
return Action::ptr(new AioWriteAction(action));
}
inline Action::ptr operator()(const action::DiscardAction &action) const {
return Action::ptr(new DiscardAction(action));
}
inline Action::ptr operator()(const action::AioDiscardAction &action) const {
return Action::ptr(new AioDiscardAction(action));
}
inline Action::ptr operator()(const action::OpenImageAction &action) const {
return Action::ptr(new OpenImageAction(action));
}
inline Action::ptr operator()(const action::CloseImageAction &action) const {
return Action::ptr(new CloseImageAction(action));
}
inline Action::ptr operator()(const action::AioOpenImageAction &action) const {
return Action::ptr(new AioOpenImageAction(action));
}
inline Action::ptr operator()(const action::AioCloseImageAction &action) const {
return Action::ptr(new AioCloseImageAction(action));
}
inline Action::ptr operator()(const action::UnknownAction &action) const {
return Action::ptr();
}
};
} // anonymous namespace
std::ostream& rbd_replay::operator<<(std::ostream& o, const Action& a) {
return a.dump(o);
}
Action::ptr Action::construct(const action::ActionEntry &action_entry) {
return boost::apply_visitor(ConstructVisitor(), action_entry.action);
}
void StartThreadAction::perform(ActionCtx &ctx) {
cerr << "StartThreadAction should never actually be performed" << std::endl;
exit(1);
}
void StopThreadAction::perform(ActionCtx &ctx) {
dout(ACTION_LEVEL) << "Performing " << *this << dendl;
ctx.stop();
}
void AioReadAction::perform(ActionCtx &worker) {
dout(ACTION_LEVEL) << "Performing " << *this << dendl;
librbd::Image *image = worker.get_image(m_action.imagectx_id);
ceph_assert(image);
PendingIO::ptr io(new PendingIO(pending_io_id(), worker));
worker.add_pending(io);
int r = image->aio_read(m_action.offset, m_action.length, io->bufferlist(), &io->completion());
assertf(r >= 0, "id = %d, r = %d", id(), r);
}
void ReadAction::perform(ActionCtx &worker) {
dout(ACTION_LEVEL) << "Performing " << *this << dendl;
librbd::Image *image = worker.get_image(m_action.imagectx_id);
PendingIO::ptr io(new PendingIO(pending_io_id(), worker));
worker.add_pending(io);
ssize_t r = image->read(m_action.offset, m_action.length, io->bufferlist());
assertf(r >= 0, "id = %d, r = %d", id(), r);
worker.remove_pending(io);
}
void AioWriteAction::perform(ActionCtx &worker) {
static const std::string fake_data(create_fake_data());
dout(ACTION_LEVEL) << "Performing " << *this << dendl;
librbd::Image *image = worker.get_image(m_action.imagectx_id);
PendingIO::ptr io(new PendingIO(pending_io_id(), worker));
uint64_t remaining = m_action.length;
while (remaining > 0) {
uint64_t n = std::min(remaining, (uint64_t)fake_data.length());
io->bufferlist().append(fake_data.data(), n);
remaining -= n;
}
worker.add_pending(io);
if (worker.readonly()) {
worker.remove_pending(io);
} else {
int r = image->aio_write(m_action.offset, m_action.length, io->bufferlist(), &io->completion());
assertf(r >= 0, "id = %d, r = %d", id(), r);
}
}
void WriteAction::perform(ActionCtx &worker) {
dout(ACTION_LEVEL) << "Performing " << *this << dendl;
librbd::Image *image = worker.get_image(m_action.imagectx_id);
PendingIO::ptr io(new PendingIO(pending_io_id(), worker));
worker.add_pending(io);
io->bufferlist().append_zero(m_action.length);
if (!worker.readonly()) {
ssize_t r = image->write(m_action.offset, m_action.length, io->bufferlist());
assertf(r >= 0, "id = %d, r = %d", id(), r);
}
worker.remove_pending(io);
}
void AioDiscardAction::perform(ActionCtx &worker) {
dout(ACTION_LEVEL) << "Performing " << *this << dendl;
librbd::Image *image = worker.get_image(m_action.imagectx_id);
PendingIO::ptr io(new PendingIO(pending_io_id(), worker));
worker.add_pending(io);
if (worker.readonly()) {
worker.remove_pending(io);
} else {
int r = image->aio_discard(m_action.offset, m_action.length, &io->completion());
assertf(r >= 0, "id = %d, r = %d", id(), r);
}
}
void DiscardAction::perform(ActionCtx &worker) {
dout(ACTION_LEVEL) << "Performing " << *this << dendl;
librbd::Image *image = worker.get_image(m_action.imagectx_id);
PendingIO::ptr io(new PendingIO(pending_io_id(), worker));
worker.add_pending(io);
if (!worker.readonly()) {
ssize_t r = image->discard(m_action.offset, m_action.length);
assertf(r >= 0, "id = %d, r = %d", id(), r);
}
worker.remove_pending(io);
}
void OpenImageAction::perform(ActionCtx &worker) {
dout(ACTION_LEVEL) << "Performing " << *this << dendl;
PendingIO::ptr io(new PendingIO(pending_io_id(), worker));
worker.add_pending(io);
librbd::Image *image = new librbd::Image();
librbd::RBD *rbd = worker.rbd();
rbd_loc name(worker.map_image_name(m_action.name, m_action.snap_name));
int r;
if (m_action.read_only || worker.readonly()) {
r = rbd->open_read_only(*worker.ioctx(), *image, name.image.c_str(), name.snap.c_str());
} else {
r = rbd->open(*worker.ioctx(), *image, name.image.c_str(), name.snap.c_str());
}
if (r) {
cerr << "Unable to open image '" << m_action.name
<< "' with snap '" << m_action.snap_name
<< "' (mapped to '" << name.str()
<< "') and readonly " << m_action.read_only
<< ": (" << -r << ") " << strerror(-r) << std::endl;
exit(1);
}
worker.put_image(m_action.imagectx_id, image);
worker.remove_pending(io);
}
void CloseImageAction::perform(ActionCtx &worker) {
dout(ACTION_LEVEL) << "Performing " << *this << dendl;
worker.erase_image(m_action.imagectx_id);
worker.set_action_complete(pending_io_id());
}
void AioOpenImageAction::perform(ActionCtx &worker) {
dout(ACTION_LEVEL) << "Performing " << *this << dendl;
// TODO: Make it async
PendingIO::ptr io(new PendingIO(pending_io_id(), worker));
worker.add_pending(io);
librbd::Image *image = new librbd::Image();
librbd::RBD *rbd = worker.rbd();
rbd_loc name(worker.map_image_name(m_action.name, m_action.snap_name));
int r;
if (m_action.read_only || worker.readonly()) {
r = rbd->open_read_only(*worker.ioctx(), *image, name.image.c_str(), name.snap.c_str());
} else {
r = rbd->open(*worker.ioctx(), *image, name.image.c_str(), name.snap.c_str());
}
if (r) {
cerr << "Unable to open image '" << m_action.name
<< "' with snap '" << m_action.snap_name
<< "' (mapped to '" << name.str()
<< "') and readonly " << m_action.read_only
<< ": (" << -r << ") " << strerror(-r) << std::endl;
exit(1);
}
worker.put_image(m_action.imagectx_id, image);
worker.remove_pending(io);
}
void AioCloseImageAction::perform(ActionCtx &worker) {
dout(ACTION_LEVEL) << "Performing " << *this << dendl;
// TODO: Make it async
worker.erase_image(m_action.imagectx_id);
worker.set_action_complete(pending_io_id());
}
| 8,538 | 33.01992 | 100 |
cc
|
null |
ceph-main/src/rbd_replay/actions.hpp
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2014 Adam Crume <[email protected]>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#ifndef _INCLUDED_RBD_REPLAY_ACTIONS_HPP
#define _INCLUDED_RBD_REPLAY_ACTIONS_HPP
#include <boost/shared_ptr.hpp>
#include "include/rbd/librbd.hpp"
#include "common/Formatter.h"
#include "rbd_replay/ActionTypes.h"
#include "rbd_loc.hpp"
#include <iostream>
// Stupid Doxygen requires this or else the typedef docs don't appear anywhere.
/// @file rbd_replay/actions.hpp
namespace rbd_replay {
typedef uint64_t imagectx_id_t;
typedef uint64_t thread_id_t;
/// Even IDs are normal actions, odd IDs are completions.
typedef uint32_t action_id_t;
class PendingIO;
/**
%Context through which an Action interacts with its environment.
*/
class ActionCtx {
public:
virtual ~ActionCtx() {
}
/**
Returns the image with the given ID.
The image must have been previously tracked with put_image(imagectx_id_t,librbd::Image*).
*/
virtual librbd::Image* get_image(imagectx_id_t imagectx_id) = 0;
/**
Tracks an image.
put_image(imagectx_id_t,librbd::Image*) must not have been called previously with the same ID,
and the image must not be NULL.
*/
virtual void put_image(imagectx_id_t imagectx_id, librbd::Image* image) = 0;
/**
Stops tracking an Image and release it.
This deletes the C++ object, not the image itself.
The image must have been previously tracked with put_image(imagectx_id_t,librbd::Image*).
*/
virtual void erase_image(imagectx_id_t imagectx_id) = 0;
virtual librbd::RBD* rbd() = 0;
virtual librados::IoCtx* ioctx() = 0;
virtual void add_pending(boost::shared_ptr<PendingIO> io) = 0;
virtual bool readonly() const = 0;
virtual void remove_pending(boost::shared_ptr<PendingIO> io) = 0;
virtual void set_action_complete(action_id_t id) = 0;
virtual void stop() = 0;
/**
Maps an image name from the name in the original trace to the name that should be used when replaying.
@param image_name name of the image in the original trace
@param snap_name name of the snap in the original trace
@return image name to replay against
*/
virtual rbd_loc map_image_name(std::string image_name, std::string snap_name) const = 0;
};
/**
Performs an %IO or a maintenance action such as starting or stopping a thread.
Actions are read from a replay file and scheduled by Replayer.
Corresponds to the IO class, except that Actions are executed by rbd-replay,
and IOs are used by rbd-replay-prep for processing the raw trace.
*/
class Action {
public:
typedef boost::shared_ptr<Action> ptr;
virtual ~Action() {
}
virtual void perform(ActionCtx &ctx) = 0;
/// Returns the ID of the completion corresponding to this action.
action_id_t pending_io_id() {
return id() + 1;
}
// There's probably a better way to do this, but oh well.
virtual bool is_start_thread() {
return false;
}
virtual action_id_t id() const = 0;
virtual thread_id_t thread_id() const = 0;
virtual const action::Dependencies& predecessors() const = 0;
virtual std::ostream& dump(std::ostream& o) const = 0;
static ptr construct(const action::ActionEntry &action_entry);
};
template <typename ActionType>
class TypedAction : public Action {
public:
explicit TypedAction(const ActionType &action) : m_action(action) {
}
action_id_t id() const override {
return m_action.id;
}
thread_id_t thread_id() const override {
return m_action.thread_id;
}
const action::Dependencies& predecessors() const override {
return m_action.dependencies;
}
std::ostream& dump(std::ostream& o) const override {
o << get_action_name() << ": ";
ceph::JSONFormatter formatter(false);
formatter.open_object_section("");
m_action.dump(&formatter);
formatter.close_section();
formatter.flush(o);
return o;
}
protected:
const ActionType m_action;
virtual const char *get_action_name() const = 0;
};
/// Writes human-readable debug information about the action to the stream.
/// @related Action
std::ostream& operator<<(std::ostream& o, const Action& a);
class StartThreadAction : public TypedAction<action::StartThreadAction> {
public:
explicit StartThreadAction(const action::StartThreadAction &action)
: TypedAction<action::StartThreadAction>(action) {
}
bool is_start_thread() override {
return true;
}
void perform(ActionCtx &ctx) override;
protected:
const char *get_action_name() const override {
return "StartThreadAction";
}
};
class StopThreadAction : public TypedAction<action::StopThreadAction> {
public:
explicit StopThreadAction(const action::StopThreadAction &action)
: TypedAction<action::StopThreadAction>(action) {
}
void perform(ActionCtx &ctx) override;
protected:
const char *get_action_name() const override {
return "StartThreadAction";
}
};
class AioReadAction : public TypedAction<action::AioReadAction> {
public:
explicit AioReadAction(const action::AioReadAction &action)
: TypedAction<action::AioReadAction>(action) {
}
void perform(ActionCtx &ctx) override;
protected:
const char *get_action_name() const override {
return "AioReadAction";
}
};
class ReadAction : public TypedAction<action::ReadAction> {
public:
explicit ReadAction(const action::ReadAction &action)
: TypedAction<action::ReadAction>(action) {
}
void perform(ActionCtx &ctx) override;
protected:
const char *get_action_name() const override {
return "ReadAction";
}
};
class AioWriteAction : public TypedAction<action::AioWriteAction> {
public:
explicit AioWriteAction(const action::AioWriteAction &action)
: TypedAction<action::AioWriteAction>(action) {
}
void perform(ActionCtx &ctx) override;
protected:
const char *get_action_name() const override {
return "AioWriteAction";
}
};
class WriteAction : public TypedAction<action::WriteAction> {
public:
explicit WriteAction(const action::WriteAction &action)
: TypedAction<action::WriteAction>(action) {
}
void perform(ActionCtx &ctx) override;
protected:
const char *get_action_name() const override {
return "WriteAction";
}
};
class AioDiscardAction : public TypedAction<action::AioDiscardAction> {
public:
explicit AioDiscardAction(const action::AioDiscardAction &action)
: TypedAction<action::AioDiscardAction>(action) {
}
void perform(ActionCtx &ctx) override;
protected:
const char *get_action_name() const override {
return "AioDiscardAction";
}
};
class DiscardAction : public TypedAction<action::DiscardAction> {
public:
explicit DiscardAction(const action::DiscardAction &action)
: TypedAction<action::DiscardAction>(action) {
}
void perform(ActionCtx &ctx) override;
protected:
const char *get_action_name() const override {
return "DiscardAction";
}
};
class OpenImageAction : public TypedAction<action::OpenImageAction> {
public:
explicit OpenImageAction(const action::OpenImageAction &action)
: TypedAction<action::OpenImageAction>(action) {
}
void perform(ActionCtx &ctx) override;
protected:
const char *get_action_name() const override {
return "OpenImageAction";
}
};
class CloseImageAction : public TypedAction<action::CloseImageAction> {
public:
explicit CloseImageAction(const action::CloseImageAction &action)
: TypedAction<action::CloseImageAction>(action) {
}
void perform(ActionCtx &ctx) override;
protected:
const char *get_action_name() const override {
return "CloseImageAction";
}
};
class AioOpenImageAction : public TypedAction<action::AioOpenImageAction> {
public:
explicit AioOpenImageAction(const action::AioOpenImageAction &action)
: TypedAction<action::AioOpenImageAction>(action) {
}
void perform(ActionCtx &ctx) override;
protected:
const char *get_action_name() const override {
return "AioOpenImageAction";
}
};
class AioCloseImageAction : public TypedAction<action::AioCloseImageAction> {
public:
explicit AioCloseImageAction(const action::AioCloseImageAction &action)
: TypedAction<action::AioCloseImageAction>(action) {
}
void perform(ActionCtx &ctx) override;
protected:
const char *get_action_name() const override {
return "AioCloseImageAction";
}
};
}
#endif
| 8,631 | 24.02029 | 107 |
hpp
|
null |
ceph-main/src/rbd_replay/ios.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2014 Adam Crume <[email protected]>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
// This code assumes that IO IDs and timestamps are related monotonically.
// In other words, (a.id < b.id) == (a.timestamp < b.timestamp) for all IOs a and b.
#include "ios.hpp"
#include "rbd_replay/ActionTypes.h"
using namespace std;
using namespace rbd_replay;
namespace {
bool compare_dependencies_by_start_time(const action::Dependency &lhs,
const action::Dependency &rhs) {
return lhs.time_delta < rhs.time_delta;
}
action::Dependencies convert_dependencies(uint64_t start_time,
const io_set_t &deps) {
action::Dependencies action_deps;
action_deps.reserve(deps.size());
for (io_set_t::const_iterator it = deps.begin(); it != deps.end(); ++it) {
boost::shared_ptr<IO> io = *it;
uint64_t time_delta = 0;
if (start_time >= io->start_time()) {
time_delta = start_time - io->start_time();
}
action_deps.push_back(action::Dependency(io->ionum(), time_delta));
}
std::sort(action_deps.begin(), action_deps.end(),
compare_dependencies_by_start_time);
return action_deps;
}
} // anonymous namespace
void IO::write_debug_base(ostream& out, const string &type) const {
out << m_ionum << ": " << m_start_time / 1000000.0 << ": " << type << ", thread = " << m_thread_id << ", deps = {";
bool first = true;
for (io_set_t::iterator itr = m_dependencies.begin(), end = m_dependencies.end(); itr != end; ++itr) {
if (first) {
first = false;
} else {
out << ", ";
}
out << (*itr)->m_ionum << ": " << m_start_time - (*itr)->m_start_time;
}
out << "}";
}
ostream& operator<<(ostream &out, const IO::ptr &io) {
io->write_debug(out);
return out;
}
void StartThreadIO::encode(bufferlist &bl) const {
using ceph::encode;
action::Action action((action::StartThreadAction(
ionum(), thread_id(), convert_dependencies(start_time(), dependencies()))));
encode(action, bl);
}
void StartThreadIO::write_debug(std::ostream& out) const {
write_debug_base(out, "start thread");
}
void StopThreadIO::encode(bufferlist &bl) const {
using ceph::encode;
action::Action action((action::StopThreadAction(
ionum(), thread_id(), convert_dependencies(start_time(), dependencies()))));
encode(action, bl);
}
void StopThreadIO::write_debug(std::ostream& out) const {
write_debug_base(out, "stop thread");
}
void ReadIO::encode(bufferlist &bl) const {
using ceph::encode;
action::Action action((action::ReadAction(
ionum(), thread_id(), convert_dependencies(start_time(), dependencies()),
m_imagectx, m_offset, m_length)));
encode(action, bl);
}
void ReadIO::write_debug(std::ostream& out) const {
write_debug_base(out, "read");
out << ", imagectx=" << m_imagectx << ", offset=" << m_offset << ", length=" << m_length << "]";
}
void WriteIO::encode(bufferlist &bl) const {
using ceph::encode;
action::Action action((action::WriteAction(
ionum(), thread_id(), convert_dependencies(start_time(), dependencies()),
m_imagectx, m_offset, m_length)));
encode(action, bl);
}
void WriteIO::write_debug(std::ostream& out) const {
write_debug_base(out, "write");
out << ", imagectx=" << m_imagectx << ", offset=" << m_offset << ", length=" << m_length << "]";
}
void DiscardIO::encode(bufferlist &bl) const {
using ceph::encode;
action::Action action((action::DiscardAction(
ionum(), thread_id(), convert_dependencies(start_time(), dependencies()),
m_imagectx, m_offset, m_length)));
encode(action, bl);
}
void DiscardIO::write_debug(std::ostream& out) const {
write_debug_base(out, "discard");
out << ", imagectx=" << m_imagectx << ", offset=" << m_offset << ", length=" << m_length << "]";
}
void AioReadIO::encode(bufferlist &bl) const {
using ceph::encode;
action::Action action((action::AioReadAction(
ionum(), thread_id(), convert_dependencies(start_time(), dependencies()),
m_imagectx, m_offset, m_length)));
encode(action, bl);
}
void AioReadIO::write_debug(std::ostream& out) const {
write_debug_base(out, "aio read");
out << ", imagectx=" << m_imagectx << ", offset=" << m_offset << ", length=" << m_length << "]";
}
void AioWriteIO::encode(bufferlist &bl) const {
using ceph::encode;
action::Action action((action::AioWriteAction(
ionum(), thread_id(), convert_dependencies(start_time(), dependencies()),
m_imagectx, m_offset, m_length)));
encode(action, bl);
}
void AioWriteIO::write_debug(std::ostream& out) const {
write_debug_base(out, "aio write");
out << ", imagectx=" << m_imagectx << ", offset=" << m_offset << ", length=" << m_length << "]";
}
void AioDiscardIO::encode(bufferlist &bl) const {
using ceph::encode;
action::Action action((action::AioDiscardAction(
ionum(), thread_id(), convert_dependencies(start_time(), dependencies()),
m_imagectx, m_offset, m_length)));
encode(action, bl);
}
void AioDiscardIO::write_debug(std::ostream& out) const {
write_debug_base(out, "aio discard");
out << ", imagectx=" << m_imagectx << ", offset=" << m_offset << ", length=" << m_length << "]";
}
void OpenImageIO::encode(bufferlist &bl) const {
using ceph::encode;
action::Action action((action::OpenImageAction(
ionum(), thread_id(), convert_dependencies(start_time(), dependencies()),
m_imagectx, m_name, m_snap_name, m_readonly)));
encode(action, bl);
}
void OpenImageIO::write_debug(std::ostream& out) const {
write_debug_base(out, "open image");
out << ", imagectx=" << m_imagectx << ", name='" << m_name << "', snap_name='" << m_snap_name << "', readonly=" << m_readonly;
}
void CloseImageIO::encode(bufferlist &bl) const {
using ceph::encode;
action::Action action((action::CloseImageAction(
ionum(), thread_id(), convert_dependencies(start_time(), dependencies()),
m_imagectx)));
encode(action, bl);
}
void CloseImageIO::write_debug(std::ostream& out) const {
write_debug_base(out, "close image");
out << ", imagectx=" << m_imagectx;
}
void AioOpenImageIO::encode(bufferlist &bl) const {
using ceph::encode;
action::Action action((action::AioOpenImageAction(
ionum(), thread_id(), convert_dependencies(start_time(), dependencies()),
m_imagectx, m_name, m_snap_name, m_readonly)));
encode(action, bl);
}
void AioOpenImageIO::write_debug(std::ostream& out) const {
write_debug_base(out, "aio open image");
out << ", imagectx=" << m_imagectx << ", name='" << m_name << "', snap_name='" << m_snap_name << "', readonly=" << m_readonly;
}
void AioCloseImageIO::encode(bufferlist &bl) const {
using ceph::encode;
action::Action action((action::AioCloseImageAction(
ionum(), thread_id(), convert_dependencies(start_time(), dependencies()),
m_imagectx)));
encode(action, bl);
}
void AioCloseImageIO::write_debug(std::ostream& out) const {
write_debug_base(out, "aio close image");
out << ", imagectx=" << m_imagectx;
}
| 7,319 | 32.122172 | 128 |
cc
|
null |
ceph-main/src/rbd_replay/ios.hpp
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2014 Adam Crume <[email protected]>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#ifndef _INCLUDED_RBD_REPLAY_IOS_HPP
#define _INCLUDED_RBD_REPLAY_IOS_HPP
// This code assumes that IO IDs and timestamps are related monotonically.
// In other words, (a.id < b.id) == (a.timestamp < b.timestamp) for all IOs a and b.
#include "include/buffer_fwd.h"
#include <boost/enable_shared_from_this.hpp>
#include <boost/shared_ptr.hpp>
#include <iostream>
#include <map>
#include <set>
#include <vector>
#include "actions.hpp"
namespace rbd_replay {
class IO;
typedef std::set<boost::shared_ptr<IO> > io_set_t;
typedef std::map<action_id_t, boost::shared_ptr<IO> > io_map_t;
/**
Used by rbd-replay-prep for processing the raw trace.
Corresponds to the Action class, except that Actions are executed by rbd-replay,
and IOs are used by rbd-replay-prep for processing the raw trace.
*/
class IO : public boost::enable_shared_from_this<IO> {
public:
typedef boost::shared_ptr<IO> ptr;
typedef std::vector<ptr> ptrs;
/**
@param ionum ID of this %IO
@param start_time time the %IO started, in nanoseconds
@param thread_id ID of the thread that issued the %IO
*/
IO(action_id_t ionum,
uint64_t start_time,
thread_id_t thread_id,
const io_set_t& deps)
: m_ionum(ionum),
m_start_time(start_time),
m_dependencies(deps),
m_thread_id(thread_id),
m_completed(false) {
}
virtual ~IO() {
}
uint64_t start_time() const {
return m_start_time;
}
io_set_t& dependencies() {
return m_dependencies;
}
const io_set_t& dependencies() const {
return m_dependencies;
}
virtual void encode(bufferlist &bl) const = 0;
void set_ionum(action_id_t ionum) {
m_ionum = ionum;
}
action_id_t ionum() const {
return m_ionum;
}
thread_id_t thread_id() const {
return m_thread_id;
}
virtual void write_debug(std::ostream& out) const = 0;
protected:
void write_debug_base(std::ostream& out, const std::string &iotype) const;
private:
action_id_t m_ionum;
uint64_t m_start_time;
io_set_t m_dependencies;
thread_id_t m_thread_id;
bool m_completed;
};
/// Used for dumping debug info.
/// @related IO
std::ostream& operator<<(std::ostream &out, const IO::ptr &io);
class StartThreadIO : public IO {
public:
StartThreadIO(action_id_t ionum,
uint64_t start_time,
thread_id_t thread_id)
: IO(ionum, start_time, thread_id, io_set_t()) {
}
void encode(bufferlist &bl) const override;
void write_debug(std::ostream& out) const override;
};
class StopThreadIO : public IO {
public:
StopThreadIO(action_id_t ionum,
uint64_t start_time,
thread_id_t thread_id,
const io_set_t& deps)
: IO(ionum, start_time, thread_id, deps) {
}
void encode(bufferlist &bl) const override;
void write_debug(std::ostream& out) const override;
};
class ReadIO : public IO {
public:
ReadIO(action_id_t ionum,
uint64_t start_time,
thread_id_t thread_id,
const io_set_t& deps,
imagectx_id_t imagectx,
uint64_t offset,
uint64_t length)
: IO(ionum, start_time, thread_id, deps),
m_imagectx(imagectx),
m_offset(offset),
m_length(length) {
}
void encode(bufferlist &bl) const override;
void write_debug(std::ostream& out) const override;
private:
imagectx_id_t m_imagectx;
uint64_t m_offset;
uint64_t m_length;
};
class WriteIO : public IO {
public:
WriteIO(action_id_t ionum,
uint64_t start_time,
thread_id_t thread_id,
const io_set_t& deps,
imagectx_id_t imagectx,
uint64_t offset,
uint64_t length)
: IO(ionum, start_time, thread_id, deps),
m_imagectx(imagectx),
m_offset(offset),
m_length(length) {
}
void encode(bufferlist &bl) const override;
void write_debug(std::ostream& out) const override;
private:
imagectx_id_t m_imagectx;
uint64_t m_offset;
uint64_t m_length;
};
class DiscardIO : public IO {
public:
DiscardIO(action_id_t ionum,
uint64_t start_time,
thread_id_t thread_id,
const io_set_t& deps,
imagectx_id_t imagectx,
uint64_t offset,
uint64_t length)
: IO(ionum, start_time, thread_id, deps),
m_imagectx(imagectx),
m_offset(offset),
m_length(length) {
}
void encode(bufferlist &bl) const override;
void write_debug(std::ostream& out) const override;
private:
imagectx_id_t m_imagectx;
uint64_t m_offset;
uint64_t m_length;
};
class AioReadIO : public IO {
public:
AioReadIO(action_id_t ionum,
uint64_t start_time,
thread_id_t thread_id,
const io_set_t& deps,
imagectx_id_t imagectx,
uint64_t offset,
uint64_t length)
: IO(ionum, start_time, thread_id, deps),
m_imagectx(imagectx),
m_offset(offset),
m_length(length) {
}
void encode(bufferlist &bl) const override;
void write_debug(std::ostream& out) const override;
private:
imagectx_id_t m_imagectx;
uint64_t m_offset;
uint64_t m_length;
};
class AioWriteIO : public IO {
public:
AioWriteIO(action_id_t ionum,
uint64_t start_time,
thread_id_t thread_id,
const io_set_t& deps,
imagectx_id_t imagectx,
uint64_t offset,
uint64_t length)
: IO(ionum, start_time, thread_id, deps),
m_imagectx(imagectx),
m_offset(offset),
m_length(length) {
}
void encode(bufferlist &bl) const override;
void write_debug(std::ostream& out) const override;
private:
imagectx_id_t m_imagectx;
uint64_t m_offset;
uint64_t m_length;
};
class AioDiscardIO : public IO {
public:
AioDiscardIO(action_id_t ionum,
uint64_t start_time,
thread_id_t thread_id,
const io_set_t& deps,
imagectx_id_t imagectx,
uint64_t offset,
uint64_t length)
: IO(ionum, start_time, thread_id, deps),
m_imagectx(imagectx),
m_offset(offset),
m_length(length) {
}
void encode(bufferlist &bl) const override;
void write_debug(std::ostream& out) const override;
private:
imagectx_id_t m_imagectx;
uint64_t m_offset;
uint64_t m_length;
};
class OpenImageIO : public IO {
public:
OpenImageIO(action_id_t ionum,
uint64_t start_time,
thread_id_t thread_id,
const io_set_t& deps,
imagectx_id_t imagectx,
const std::string& name,
const std::string& snap_name,
bool readonly)
: IO(ionum, start_time, thread_id, deps),
m_imagectx(imagectx),
m_name(name),
m_snap_name(snap_name),
m_readonly(readonly) {
}
void encode(bufferlist &bl) const override;
imagectx_id_t imagectx() const {
return m_imagectx;
}
void write_debug(std::ostream& out) const override;
private:
imagectx_id_t m_imagectx;
std::string m_name;
std::string m_snap_name;
bool m_readonly;
};
class CloseImageIO : public IO {
public:
CloseImageIO(action_id_t ionum,
uint64_t start_time,
thread_id_t thread_id,
const io_set_t& deps,
imagectx_id_t imagectx)
: IO(ionum, start_time, thread_id, deps),
m_imagectx(imagectx) {
}
void encode(bufferlist &bl) const override;
imagectx_id_t imagectx() const {
return m_imagectx;
}
void write_debug(std::ostream& out) const override;
private:
imagectx_id_t m_imagectx;
};
class AioOpenImageIO : public IO {
public:
AioOpenImageIO(action_id_t ionum,
uint64_t start_time,
thread_id_t thread_id,
const io_set_t& deps,
imagectx_id_t imagectx,
const std::string& name,
const std::string& snap_name,
bool readonly)
: IO(ionum, start_time, thread_id, deps),
m_imagectx(imagectx),
m_name(name),
m_snap_name(snap_name),
m_readonly(readonly) {
}
void encode(bufferlist &bl) const override;
imagectx_id_t imagectx() const {
return m_imagectx;
}
void write_debug(std::ostream& out) const override;
private:
imagectx_id_t m_imagectx;
std::string m_name;
std::string m_snap_name;
bool m_readonly;
};
class AioCloseImageIO : public IO {
public:
AioCloseImageIO(action_id_t ionum,
uint64_t start_time,
thread_id_t thread_id,
const io_set_t& deps,
imagectx_id_t imagectx)
: IO(ionum, start_time, thread_id, deps),
m_imagectx(imagectx) {
}
void encode(bufferlist &bl) const override;
imagectx_id_t imagectx() const {
return m_imagectx;
}
void write_debug(std::ostream& out) const override;
private:
imagectx_id_t m_imagectx;
};
}
#endif
| 8,880 | 21.09204 | 84 |
hpp
|
null |
ceph-main/src/rbd_replay/rbd-replay-prep.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2014 Adam Crume <[email protected]>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
// This code assumes that IO IDs and timestamps are related monotonically.
// In other words, (a.id < b.id) == (a.timestamp < b.timestamp) for all IOs a and b.
#include "include/compat.h"
#include "common/errno.h"
#include "rbd_replay/ActionTypes.h"
#include <babeltrace/babeltrace.h>
#include <babeltrace/ctf/events.h>
#include <babeltrace/ctf/iterator.h>
#include <sys/types.h>
#include <fcntl.h>
#include <cstdlib>
#include <string>
#include <assert.h>
#include <fstream>
#include <set>
#include <boost/thread/thread.hpp>
#include <boost/scope_exit.hpp>
#include "ios.hpp"
using namespace std;
using namespace rbd_replay;
#define ASSERT_EXIT(check, str) \
if (!(check)) { \
std::cerr << str << std::endl; \
exit(1); \
}
class Thread {
public:
typedef boost::shared_ptr<Thread> ptr;
Thread(thread_id_t id,
uint64_t window)
: m_id(id),
m_window(window),
m_latest_io(IO::ptr()),
m_max_ts(0) {
}
void insert_ts(uint64_t ts) {
if (m_max_ts == 0 || ts > m_max_ts) {
m_max_ts = ts;
}
}
uint64_t max_ts() const {
return m_max_ts;
}
void issued_io(IO::ptr io, std::set<IO::ptr> *latest_ios) {
ceph_assert(io);
if (m_latest_io.get() != NULL) {
latest_ios->erase(m_latest_io);
}
m_latest_io = io;
latest_ios->insert(io);
}
thread_id_t id() const {
return m_id;
}
IO::ptr latest_io() {
return m_latest_io;
}
private:
thread_id_t m_id;
uint64_t m_window;
IO::ptr m_latest_io;
uint64_t m_max_ts;
};
class AnonymizedImage {
public:
void init(const string &image_name, int index) {
ceph_assert(m_image_name == "");
m_image_name = image_name;
ostringstream oss;
oss << "image" << index;
m_anonymized_image_name = oss.str();
}
string image_name() const {
return m_image_name;
}
pair<string, string> anonymize(string snap_name) {
if (snap_name == "") {
return pair<string, string>(m_anonymized_image_name, "");
}
string& anonymized_snap_name(m_snaps[snap_name]);
if (anonymized_snap_name == "") {
ostringstream oss;
oss << "snap" << m_snaps.size();
anonymized_snap_name = oss.str();
}
return pair<string, string>(m_anonymized_image_name, anonymized_snap_name);
}
private:
string m_image_name;
string m_anonymized_image_name;
map<string, string> m_snaps;
};
static void usage(const string &prog) {
std::stringstream str;
str << "Usage: " << prog << " ";
std::cout << str.str() << "[ --window <seconds> ] [ --anonymize ] [ --verbose ]" << std::endl
<< std::string(str.str().size(), ' ') << "<trace-input> <replay-output>" << endl;
}
__attribute__((noreturn)) static void usage_exit(const string &prog, const string &msg) {
cerr << msg << endl;
usage(prog);
exit(1);
}
class Processor {
public:
Processor()
: m_window(1000000000ULL), // 1 billion nanoseconds, i.e., one second
m_io_count(0),
m_anonymize(false),
m_verbose(false) {
}
void run(vector<string> args) {
string input_file_name;
string output_file_name;
bool got_input = false;
bool got_output = false;
for (int i = 1, nargs = args.size(); i < nargs; i++) {
const string& arg(args[i]);
if (arg == "--window") {
if (i == nargs - 1) {
usage_exit(args[0], "--window requires an argument");
}
m_window = (uint64_t)(1e9 * atof(args[++i].c_str()));
} else if (arg.compare(0, 9, "--window=") == 0) {
m_window = (uint64_t)(1e9 * atof(arg.c_str() + sizeof("--window=")));
} else if (arg == "--anonymize") {
m_anonymize = true;
} else if (arg == "--verbose") {
m_verbose = true;
} else if (arg == "-h" || arg == "--help") {
usage(args[0]);
exit(0);
} else if (arg.compare(0, 1, "-") == 0) {
usage_exit(args[0], "Unrecognized argument: " + arg);
} else if (!got_input) {
input_file_name = arg;
got_input = true;
} else if (!got_output) {
output_file_name = arg;
got_output = true;
} else {
usage_exit(args[0], "Too many arguments");
}
}
if (!got_output) {
usage_exit(args[0], "Not enough arguments");
}
struct bt_context *ctx = bt_context_create();
int trace_handle = bt_context_add_trace(ctx,
input_file_name.c_str(), // path
"ctf", // format
NULL, // packet_seek
NULL, // stream_list
NULL); // metadata
ASSERT_EXIT(trace_handle >= 0, "Error loading trace file");
uint64_t start_time_ns = bt_trace_handle_get_timestamp_begin(ctx, trace_handle, BT_CLOCK_REAL);
ASSERT_EXIT(start_time_ns != -1ULL,
"Error extracting creation time from trace");
struct bt_ctf_iter *itr = bt_ctf_iter_create(ctx,
NULL, // begin_pos
NULL); // end_pos
ceph_assert(itr);
struct bt_iter *bt_itr = bt_ctf_get_iter(itr);
int fd = open(output_file_name.c_str(), O_WRONLY | O_CREAT | O_EXCL | O_BINARY, 0644);
ASSERT_EXIT(fd >= 0, "Error opening output file " << output_file_name <<
": " << cpp_strerror(errno));
BOOST_SCOPE_EXIT( (fd) ) {
close(fd);
} BOOST_SCOPE_EXIT_END;
write_banner(fd);
uint64_t trace_start = 0;
bool first = true;
while(true) {
struct bt_ctf_event *evt = bt_ctf_iter_read_event(itr);
if(!evt) {
break;
}
uint64_t ts = bt_ctf_get_timestamp(evt);
ASSERT_EXIT(ts != -1ULL, "Error extracting event timestamp");
if (first) {
trace_start = ts;
first = false;
}
ts -= trace_start;
ts += 4; // This is so we have room to insert two events (thread start and open image) at unique timestamps before whatever the first event is.
IO::ptrs ptrs;
process_event(ts, evt, &ptrs);
serialize_events(fd, ptrs);
int r = bt_iter_next(bt_itr);
ASSERT_EXIT(r == 0, "Error advancing event iterator");
}
bt_ctf_iter_destroy(itr);
insert_thread_stops(fd);
}
private:
void write_banner(int fd) {
bufferlist bl;
bl.append(rbd_replay::action::BANNER);
int r = bl.write_fd(fd);
ASSERT_EXIT(r >= 0, "Error writing to output file: " << cpp_strerror(r));
}
void serialize_events(int fd, const IO::ptrs &ptrs) {
for (IO::ptrs::const_iterator it = ptrs.begin(); it != ptrs.end(); ++it) {
IO::ptr io(*it);
bufferlist bl;
io->encode(bl);
int r = bl.write_fd(fd);
ASSERT_EXIT(r >= 0, "Error writing to output file: " << cpp_strerror(r));
if (m_verbose) {
io->write_debug(std::cout);
std::cout << std::endl;
}
}
}
void insert_thread_stops(int fd) {
IO::ptrs ios;
for (map<thread_id_t, Thread::ptr>::const_iterator itr = m_threads.begin(),
end = m_threads.end(); itr != end; ++itr) {
Thread::ptr thread(itr->second);
ios.push_back(IO::ptr(new StopThreadIO(next_id(), thread->max_ts(),
thread->id(),
m_recent_completions)));
}
serialize_events(fd, ios);
}
void process_event(uint64_t ts, struct bt_ctf_event *evt,
IO::ptrs *ios) {
const char *event_name = bt_ctf_event_name(evt);
const struct bt_definition *scope_context = bt_ctf_get_top_level_scope(evt,
BT_STREAM_EVENT_CONTEXT);
ASSERT_EXIT(scope_context != NULL, "Error retrieving event context");
const struct bt_definition *scope_fields = bt_ctf_get_top_level_scope(evt,
BT_EVENT_FIELDS);
ASSERT_EXIT(scope_fields != NULL, "Error retrieving event fields");
const struct bt_definition *pthread_id_field = bt_ctf_get_field(evt, scope_context, "pthread_id");
ASSERT_EXIT(pthread_id_field != NULL, "Error retrieving thread id");
thread_id_t threadID = bt_ctf_get_uint64(pthread_id_field);
Thread::ptr &thread(m_threads[threadID]);
if (!thread) {
thread.reset(new Thread(threadID, m_window));
IO::ptr io(new StartThreadIO(next_id(), ts - 4, threadID));
ios->push_back(io);
}
thread->insert_ts(ts);
class FieldLookup {
public:
FieldLookup(struct bt_ctf_event *evt,
const struct bt_definition *scope)
: m_evt(evt),
m_scope(scope) {
}
const char* string(const char* name) {
const struct bt_definition *field = bt_ctf_get_field(m_evt, m_scope, name);
ASSERT_EXIT(field != NULL, "Error retrieving field '" << name << "'");
const char* c = bt_ctf_get_string(field);
int err = bt_ctf_field_get_error();
ASSERT_EXIT(c && err == 0, "Error retrieving field value '" << name <<
"': error=" << err);
return c;
}
int64_t int64(const char* name) {
const struct bt_definition *field = bt_ctf_get_field(m_evt, m_scope, name);
ASSERT_EXIT(field != NULL, "Error retrieving field '" << name << "'");
int64_t val = bt_ctf_get_int64(field);
int err = bt_ctf_field_get_error();
ASSERT_EXIT(err == 0, "Error retrieving field value '" << name <<
"': error=" << err);
return val;
}
uint64_t uint64(const char* name) {
const struct bt_definition *field = bt_ctf_get_field(m_evt, m_scope, name);
ASSERT_EXIT(field != NULL, "Error retrieving field '" << name << "'");
uint64_t val = bt_ctf_get_uint64(field);
int err = bt_ctf_field_get_error();
ASSERT_EXIT(err == 0, "Error retrieving field value '" << name <<
"': error=" << err);
return val;
}
private:
struct bt_ctf_event *m_evt;
const struct bt_definition *m_scope;
} fields(evt, scope_fields);
if (strcmp(event_name, "librbd:open_image_enter") == 0) {
string name(fields.string("name"));
string snap_name(fields.string("snap_name"));
bool readonly = fields.uint64("read_only");
imagectx_id_t imagectx = fields.uint64("imagectx");
action_id_t ionum = next_id();
pair<string, string> aname(map_image_snap(name, snap_name));
IO::ptr io(new OpenImageIO(ionum, ts, threadID, m_recent_completions,
imagectx, aname.first, aname.second,
readonly));
thread->issued_io(io, &m_latest_ios);
ios->push_back(io);
} else if (strcmp(event_name, "librbd:open_image_exit") == 0) {
completed(thread->latest_io());
boost::shared_ptr<OpenImageIO> io(boost::dynamic_pointer_cast<OpenImageIO>(thread->latest_io()));
ceph_assert(io);
m_open_images.insert(io->imagectx());
} else if (strcmp(event_name, "librbd:close_image_enter") == 0) {
imagectx_id_t imagectx = fields.uint64("imagectx");
action_id_t ionum = next_id();
IO::ptr io(new CloseImageIO(ionum, ts, threadID, m_recent_completions,
imagectx));
thread->issued_io(io, &m_latest_ios);
ios->push_back(thread->latest_io());
} else if (strcmp(event_name, "librbd:close_image_exit") == 0) {
completed(thread->latest_io());
boost::shared_ptr<CloseImageIO> io(boost::dynamic_pointer_cast<CloseImageIO>(thread->latest_io()));
ceph_assert(io);
m_open_images.erase(io->imagectx());
} else if (strcmp(event_name, "librbd:aio_open_image_enter") == 0) {
string name(fields.string("name"));
string snap_name(fields.string("snap_name"));
bool readonly = fields.uint64("read_only");
imagectx_id_t imagectx = fields.uint64("imagectx");
uint64_t completion = fields.uint64("completion");
action_id_t ionum = next_id();
pair<string, string> aname(map_image_snap(name, snap_name));
IO::ptr io(new AioOpenImageIO(ionum, ts, threadID, m_recent_completions,
imagectx, aname.first, aname.second,
readonly));
thread->issued_io(io, &m_latest_ios);
ios->push_back(io);
m_pending_ios[completion] = io;
} else if (strcmp(event_name, "librbd:aio_close_image_enter") == 0) {
imagectx_id_t imagectx = fields.uint64("imagectx");
uint64_t completion = fields.uint64("completion");
action_id_t ionum = next_id();
IO::ptr io(new AioCloseImageIO(ionum, ts, threadID, m_recent_completions,
imagectx));
thread->issued_io(io, &m_latest_ios);
ios->push_back(thread->latest_io());
m_pending_ios[completion] = io;
} else if (strcmp(event_name, "librbd:read_enter") == 0 ||
strcmp(event_name, "librbd:read2_enter") == 0) {
string name(fields.string("name"));
string snap_name(fields.string("snap_name"));
bool readonly = fields.int64("read_only");
imagectx_id_t imagectx = fields.uint64("imagectx");
uint64_t offset = fields.uint64("offset");
uint64_t length = fields.uint64("length");
require_image(ts, thread, imagectx, name, snap_name, readonly, ios);
action_id_t ionum = next_id();
IO::ptr io(new ReadIO(ionum, ts, threadID, m_recent_completions, imagectx,
offset, length));
thread->issued_io(io, &m_latest_ios);
ios->push_back(io);
} else if (strcmp(event_name, "librbd:read_exit") == 0) {
completed(thread->latest_io());
} else if (strcmp(event_name, "librbd:write_enter") == 0 ||
strcmp(event_name, "librbd:write2_enter") == 0) {
string name(fields.string("name"));
string snap_name(fields.string("snap_name"));
bool readonly = fields.int64("read_only");
uint64_t offset = fields.uint64("off");
uint64_t length = fields.uint64("buf_len");
imagectx_id_t imagectx = fields.uint64("imagectx");
require_image(ts, thread, imagectx, name, snap_name, readonly, ios);
action_id_t ionum = next_id();
IO::ptr io(new WriteIO(ionum, ts, threadID, m_recent_completions,
imagectx, offset, length));
thread->issued_io(io, &m_latest_ios);
ios->push_back(io);
} else if (strcmp(event_name, "librbd:write_exit") == 0) {
completed(thread->latest_io());
} else if (strcmp(event_name, "librbd:discard_enter") == 0) {
string name(fields.string("name"));
string snap_name(fields.string("snap_name"));
bool readonly = fields.int64("read_only");
uint64_t offset = fields.uint64("off");
uint64_t length = fields.uint64("len");
imagectx_id_t imagectx = fields.uint64("imagectx");
require_image(ts, thread, imagectx, name, snap_name, readonly, ios);
action_id_t ionum = next_id();
IO::ptr io(new DiscardIO(ionum, ts, threadID, m_recent_completions,
imagectx, offset, length));
thread->issued_io(io, &m_latest_ios);
ios->push_back(io);
} else if (strcmp(event_name, "librbd:discard_exit") == 0) {
completed(thread->latest_io());
} else if (strcmp(event_name, "librbd:aio_read_enter") == 0 ||
strcmp(event_name, "librbd:aio_read2_enter") == 0) {
string name(fields.string("name"));
string snap_name(fields.string("snap_name"));
bool readonly = fields.int64("read_only");
uint64_t completion = fields.uint64("completion");
imagectx_id_t imagectx = fields.uint64("imagectx");
uint64_t offset = fields.uint64("offset");
uint64_t length = fields.uint64("length");
require_image(ts, thread, imagectx, name, snap_name, readonly, ios);
action_id_t ionum = next_id();
IO::ptr io(new AioReadIO(ionum, ts, threadID, m_recent_completions,
imagectx, offset, length));
ios->push_back(io);
thread->issued_io(io, &m_latest_ios);
m_pending_ios[completion] = io;
} else if (strcmp(event_name, "librbd:aio_write_enter") == 0 ||
strcmp(event_name, "librbd:aio_write2_enter") == 0) {
string name(fields.string("name"));
string snap_name(fields.string("snap_name"));
bool readonly = fields.int64("read_only");
uint64_t offset = fields.uint64("off");
uint64_t length = fields.uint64("len");
uint64_t completion = fields.uint64("completion");
imagectx_id_t imagectx = fields.uint64("imagectx");
require_image(ts, thread, imagectx, name, snap_name, readonly, ios);
action_id_t ionum = next_id();
IO::ptr io(new AioWriteIO(ionum, ts, threadID, m_recent_completions,
imagectx, offset, length));
thread->issued_io(io, &m_latest_ios);
ios->push_back(io);
m_pending_ios[completion] = io;
} else if (strcmp(event_name, "librbd:aio_discard_enter") == 0) {
string name(fields.string("name"));
string snap_name(fields.string("snap_name"));
bool readonly = fields.int64("read_only");
uint64_t offset = fields.uint64("off");
uint64_t length = fields.uint64("len");
uint64_t completion = fields.uint64("completion");
imagectx_id_t imagectx = fields.uint64("imagectx");
require_image(ts, thread, imagectx, name, snap_name, readonly, ios);
action_id_t ionum = next_id();
IO::ptr io(new AioDiscardIO(ionum, ts, threadID, m_recent_completions,
imagectx, offset, length));
thread->issued_io(io, &m_latest_ios);
ios->push_back(io);
m_pending_ios[completion] = io;
} else if (strcmp(event_name, "librbd:aio_complete_enter") == 0) {
uint64_t completion = fields.uint64("completion");
map<uint64_t, IO::ptr>::iterator itr = m_pending_ios.find(completion);
if (itr != m_pending_ios.end()) {
IO::ptr completedIO(itr->second);
m_pending_ios.erase(itr);
completed(completedIO);
}
}
}
action_id_t next_id() {
action_id_t id = m_io_count;
m_io_count += 2;
return id;
}
void completed(IO::ptr io) {
uint64_t limit = (io->start_time() < m_window ?
0 : io->start_time() - m_window);
for (io_set_t::iterator itr = m_recent_completions.begin();
itr != m_recent_completions.end(); ) {
IO::ptr recent_comp(*itr);
if ((recent_comp->start_time() < limit ||
io->dependencies().count(recent_comp) != 0) &&
m_latest_ios.count(recent_comp) == 0) {
m_recent_completions.erase(itr++);
} else {
++itr;
}
}
m_recent_completions.insert(io);
}
pair<string, string> map_image_snap(string image_name, string snap_name) {
if (!m_anonymize) {
return pair<string, string>(image_name, snap_name);
}
AnonymizedImage& m(m_anonymized_images[image_name]);
if (m.image_name() == "") {
m.init(image_name, m_anonymized_images.size());
}
return m.anonymize(snap_name);
}
void require_image(uint64_t ts,
Thread::ptr thread,
imagectx_id_t imagectx,
const string& name,
const string& snap_name,
bool readonly,
IO::ptrs *ios) {
ceph_assert(thread);
if (m_open_images.count(imagectx) > 0) {
return;
}
action_id_t ionum = next_id();
pair<string, string> aname(map_image_snap(name, snap_name));
IO::ptr io(new OpenImageIO(ionum, ts - 2, thread->id(),
m_recent_completions, imagectx, aname.first,
aname.second, readonly));
thread->issued_io(io, &m_latest_ios);
ios->push_back(io);
completed(io);
m_open_images.insert(imagectx);
}
uint64_t m_window;
map<thread_id_t, Thread::ptr> m_threads;
uint32_t m_io_count;
io_set_t m_recent_completions;
set<imagectx_id_t> m_open_images;
// keyed by completion
map<uint64_t, IO::ptr> m_pending_ios;
std::set<IO::ptr> m_latest_ios;
bool m_anonymize;
map<string, AnonymizedImage> m_anonymized_images;
bool m_verbose;
};
int main(int argc, char** argv) {
vector<string> args;
for (int i = 0; i < argc; i++) {
args.push_back(string(argv[i]));
}
Processor p;
p.run(args);
}
| 20,311 | 33.721368 | 149 |
cc
|
null |
ceph-main/src/rbd_replay/rbd-replay.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2014 Adam Crume <[email protected]>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#include <vector>
#include <boost/thread.hpp>
#include "common/ceph_argparse.h"
#include "global/global_init.h"
#include "Replayer.hpp"
#include "rbd_replay_debug.hpp"
#include "ImageNameMap.hpp"
using namespace std;
using namespace rbd_replay;
static const char* get_remainder(const char *string, const char *prefix) {
while (*prefix) {
if (*prefix++ != *string++) {
return NULL;
}
}
return string;
}
static void usage(const char* program) {
cout << "Usage: " << program << " --conf=<config_file> <replay_file>" << std::endl;
cout << "Options:" << std::endl;
cout << " -p, --pool-name <pool> Name of the pool to use. Default: rbd" << std::endl;
cout << " --latency-multiplier <float> Multiplies inter-request latencies. Default: 1" << std::endl;
cout << " --read-only Only perform non-destructive operations." << std::endl;
cout << " --map-image <rule> Add a rule to map image names in the trace to" << std::endl;
cout << " image names in the replay cluster." << std::endl;
cout << " --dump-perf-counters *Experimental*" << std::endl;
cout << " Dump performance counters to standard out before" << std::endl;
cout << " an image is closed. Performance counters may be dumped" << std::endl;
cout << " multiple times if multiple images are closed, or if" << std::endl;
cout << " the same image is opened and closed multiple times." << std::endl;
cout << " Performance counters and their meaning may change between" << std::endl;
cout << " versions." << std::endl;
cout << std::endl;
cout << "Image mapping rules:" << std::endl;
cout << "A rule of image1@snap1=image2@snap2 would map snap1 of image1 to snap2 of" << std::endl;
cout << "image2." << std::endl;
}
int main(int argc, const char **argv) {
auto args = argv_to_vec(argc, argv);
if (args.empty()) {
cerr << argv[0] << ": -h or --help for usage" << std::endl;
exit(1);
}
if (ceph_argparse_need_usage(args)) {
usage(argv[0]);
exit(0);
}
auto cct = global_init(NULL, args, CEPH_ENTITY_TYPE_CLIENT,
CODE_ENVIRONMENT_UTILITY, 0);
std::vector<const char*>::iterator i;
string pool_name;
float latency_multiplier = 1;
bool readonly = false;
ImageNameMap image_name_map;
std::string val;
std::ostringstream err;
bool dump_perf_counters = false;
for (i = args.begin(); i != args.end(); ) {
if (ceph_argparse_double_dash(args, i)) {
break;
} else if (ceph_argparse_witharg(args, i, &val, "-p", "--pool", (char*)NULL)) {
pool_name = val;
} else if (ceph_argparse_witharg(args, i, &latency_multiplier, err, "--latency-multiplier",
(char*)NULL)) {
if (!err.str().empty()) {
cerr << err.str() << std::endl;
return 1;
}
} else if (ceph_argparse_flag(args, i, "--read-only", (char*)NULL)) {
readonly = true;
} else if (ceph_argparse_witharg(args, i, &val, "--map-image", (char*)NULL)) {
ImageNameMap::Mapping mapping;
if (image_name_map.parse_mapping(val, &mapping)) {
image_name_map.add_mapping(mapping);
} else {
cerr << "Unable to parse mapping string: '" << val << "'" << std::endl;
return 1;
}
} else if (ceph_argparse_flag(args, i, "--dump-perf-counters", (char*)NULL)) {
dump_perf_counters = true;
} else if (get_remainder(*i, "-")) {
cerr << "Unrecognized argument: " << *i << std::endl;
return 1;
} else {
++i;
}
}
common_init_finish(g_ceph_context);
string replay_file;
if (!args.empty()) {
replay_file = args[0];
}
if (replay_file.empty()) {
cerr << "No replay file specified." << std::endl;
return 1;
}
unsigned int nthreads = boost::thread::hardware_concurrency();
Replayer replayer(2 * nthreads + 1);
replayer.set_latency_multiplier(latency_multiplier);
replayer.set_pool_name(pool_name);
replayer.set_readonly(readonly);
replayer.set_image_name_map(image_name_map);
replayer.set_dump_perf_counters(dump_perf_counters);
replayer.run(replay_file);
}
| 4,707 | 35.215385 | 117 |
cc
|
null |
ceph-main/src/rbd_replay/rbd_loc.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2014 Adam Crume <[email protected]>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#include "rbd_loc.hpp"
#include "include/ceph_assert.h"
using namespace std;
using namespace rbd_replay;
rbd_loc::rbd_loc() {
}
rbd_loc::rbd_loc(const string &pool, const string &image, const string &snap)
: pool(pool),
image(image),
snap(snap) {
}
bool rbd_loc::parse(string name_string) {
int field = 0;
string fields[3];
bool read_slash = false;
bool read_at = false;
for (size_t i = 0, n = name_string.length(); i < n; i++) {
char c = name_string[i];
switch (c) {
case '/':
if (read_slash || read_at) {
return false;
}
ceph_assert(field == 0);
field++;
read_slash = true;
break;
case '@':
if (read_at) {
return false;
}
ceph_assert(field < 2);
field++;
read_at = true;
break;
case '\\':
if (i == n - 1) {
return false;
}
fields[field].push_back(name_string[++i]);
break;
default:
fields[field].push_back(c);
}
}
if (read_slash) {
pool = fields[0];
image = fields[1];
// note that if read_at is false, then fields[2] is the empty string,
// so this is still correct
snap = fields[2];
} else {
pool = "";
image = fields[0];
// note that if read_at is false, then fields[1] is the empty string,
// so this is still correct
snap = fields[1];
}
return true;
}
static void write(const string &in, string *out) {
for (size_t i = 0, n = in.length(); i < n; i++) {
char c = in[i];
if (c == '@' || c == '/' || c == '\\') {
out->push_back('\\');
}
out->push_back(c);
}
}
string rbd_loc::str() const {
string out;
if (!pool.empty()) {
write(pool, &out);
out.push_back('/');
}
write(image, &out);
if (!snap.empty()) {
out.push_back('@');
write(snap, &out);
}
return out;
}
int rbd_loc::compare(const rbd_loc& rhs) const {
int c = pool.compare(rhs.pool);
if (c) {
return c;
}
c = image.compare(rhs.image);
if (c) {
return c;
}
c = snap.compare(rhs.snap);
if (c) {
return c;
}
return 0;
}
bool rbd_loc::operator==(const rbd_loc& rhs) const {
return compare(rhs) == 0;
}
bool rbd_loc::operator<(const rbd_loc& rhs) const {
return compare(rhs) < 0;
}
| 2,670 | 19.389313 | 77 |
cc
|
null |
ceph-main/src/rbd_replay/rbd_loc.hpp
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2014 Adam Crume <[email protected]>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#ifndef _INCLUDED_RBD_REPLAY_RBD_LOC_HPP
#define _INCLUDED_RBD_REPLAY_RBD_LOC_HPP
#include <string>
namespace rbd_replay {
/**
Stores a pool, image name, and snap name triple.
rbd_locs can be converted to/from strings with the format pool/image\@snap.
The slash and at signs can be omitted if the pool and snap are empty, respectively.
Backslashes can be used to escape slashes and at signs in names.
Examples:
|Pool | Image | Snap | String |
|------|-------|------|--------------------|
|rbd | vm | 1 | rbd/vm\@1 |
|rbd | vm | | rbd/vm |
| | vm | 1 | vm\@1 |
| | vm | | vm |
|rbd | | 1 | rbd/\@1 |
|rbd\@x| vm/y | 1 | rbd\\\@x/vm\\/y\@1 |
(The empty string should obviously be avoided as the image name.)
Note that the non-canonical forms /vm\@1 and rbd/vm\@ can also be parsed,
although they will be formatted as vm\@1 and rbd/vm.
*/
struct rbd_loc {
/**
Constructs an rbd_loc with the empty string for the pool, image, and snap.
*/
rbd_loc();
/**
Constructs an rbd_loc with the given pool, image, and snap.
*/
rbd_loc(const std::string &pool, const std::string &image, const std::string &snap);
/**
Parses an rbd_loc from the given string.
If parsing fails, the contents are unmodified.
@retval true if parsing succeeded
*/
bool parse(std::string name_string);
/**
Returns the string representation of the locator.
*/
std::string str() const;
/**
Compares the locators lexicographically by pool, then image, then snap.
*/
int compare(const rbd_loc& rhs) const;
/**
Returns true if the locators have identical pool, image, and snap.
*/
bool operator==(const rbd_loc& rhs) const;
/**
Compares the locators lexicographically by pool, then image, then snap.
*/
bool operator<(const rbd_loc& rhs) const;
std::string pool;
std::string image;
std::string snap;
};
}
#endif
| 2,490 | 26.373626 | 86 |
hpp
|
null |
ceph-main/src/rbd_replay/rbd_replay_debug.hpp
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2014 Adam Crume <[email protected]>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#ifndef _INCLUDED_RBD_REPLAY_DEBUG_H
#define _INCLUDED_RBD_REPLAY_DEBUG_H
#include "common/debug.h"
#include "include/ceph_assert.h"
namespace rbd_replay {
static const int ACTION_LEVEL = 11;
static const int DEPGRAPH_LEVEL = 12;
static const int SLEEP_LEVEL = 13;
static const int THREAD_LEVEL = 10;
}
#define dout_subsys ceph_subsys_rbd_replay
#undef dout_prefix
#define dout_prefix *_dout << "rbd_replay: "
#endif
| 847 | 23.228571 | 70 |
hpp
|
null |
ceph-main/src/rgw/MAINTAINERS.md
|
# RGW Maintainers
Maintainers are the default assignee for related tracker issues and pull requests.
| Component | Name |
|---------------------------------|---------------------------------|
| auth, STS | Pritha Srivastava |
| bucket index, resharding | J. Eric Ivancich |
| bucket notifications | Yuval Lifshitz |
| data caching | Mark Kogan |
| garbage collection | Pritha Srivastava |
| http frontends | Casey Bodley |
| lifecycle | Matt Benjamin |
| lua scripting | Yuval Lifshitz |
| multisite | Casey Bodley |
| object i/o | Casey Bodley |
| rgw orchestration, admin APIs | Ali Maredia |
| radosgw-admin | Daniel Gryniewicz |
| rest ops | Daniel Gryniewicz |
| rgw-nfs | Matt Benjamin |
| performance | Mark Kogan |
| s3 select | Gal Salomon |
| storage abstraction layer | Daniel Gryniewicz |
# Looking for maintainer
* security (crypto, SSE, CVEs)
* swift api
| 1,503 | 50.862069 | 82 |
md
|
null |
ceph-main/src/rgw/librgw.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2022 New Dream Network
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#include <sys/types.h>
#include <string.h>
#include <chrono>
#include "include/rados/librgw.h"
#include "include/str_list.h"
#include "common/ceph_argparse.h"
#include "common/ceph_context.h"
#include "common/dout.h"
#include "rgw_lib.h"
#include <errno.h>
#include <thread>
#include <string>
#include <mutex>
#define dout_subsys ceph_subsys_rgw
namespace rgw {
bool global_stop = false;
static std::mutex librgw_mtx;
static RGWLib rgwlib;
} // namespace rgw
extern "C" {
int librgw_create(librgw_t* rgw, int argc, char **argv)
{
using namespace rgw;
int rc = -EINVAL;
g_rgwlib = &rgwlib;
if (! g_ceph_context) {
std::lock_guard<std::mutex> lg(librgw_mtx);
if (! g_ceph_context) {
std::vector<std::string> spl_args;
// last non-0 argument will be split and consumed
if (argc > 1) {
const std::string spl_arg{argv[(--argc)]};
get_str_vec(spl_arg, " \t", spl_args);
}
auto args = argv_to_vec(argc, argv);
// append split args, if any
for (const auto& elt : spl_args) {
args.push_back(elt.c_str());
}
rc = rgwlib.init(args);
}
}
*rgw = g_ceph_context->get();
return rc;
}
void librgw_shutdown(librgw_t rgw)
{
using namespace rgw;
CephContext* cct = static_cast<CephContext*>(rgw);
rgwlib.stop();
dout(1) << "final shutdown" << dendl;
cct->put();
}
} /* extern "C" */
| 1,794 | 18.944444 | 70 |
cc
|
null |
ceph-main/src/rgw/rgw_acl.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include <string.h>
#include <iostream>
#include <map>
#include "include/types.h"
#include "common/Formatter.h"
#include "rgw_acl.h"
#include "rgw_acl_s3.h"
#include "rgw_user.h"
#define dout_subsys ceph_subsys_rgw
using namespace std;
bool operator==(const ACLPermission& lhs, const ACLPermission& rhs) {
return lhs.flags == rhs.flags;
}
bool operator!=(const ACLPermission& lhs, const ACLPermission& rhs) {
return !(lhs == rhs);
}
bool operator==(const ACLGranteeType& lhs, const ACLGranteeType& rhs) {
return lhs.type == rhs.type;
}
bool operator!=(const ACLGranteeType& lhs, const ACLGranteeType& rhs) {
return lhs.type != rhs.type;
}
bool operator==(const ACLGrant& lhs, const ACLGrant& rhs) {
return lhs.type == rhs.type && lhs.id == rhs.id
&& lhs.email == rhs.email && lhs.permission == rhs.permission
&& lhs.name == rhs.name && lhs.group == rhs.group
&& lhs.url_spec == rhs.url_spec;
}
bool operator!=(const ACLGrant& lhs, const ACLGrant& rhs) {
return !(lhs == rhs);
}
bool operator==(const ACLReferer& lhs, const ACLReferer& rhs) {
return lhs.url_spec == rhs.url_spec && lhs.perm == rhs.perm;
}
bool operator!=(const ACLReferer& lhs, const ACLReferer& rhs) {
return !(lhs == rhs);
}
bool operator==(const RGWAccessControlList& lhs,
const RGWAccessControlList& rhs) {
return lhs.acl_user_map == rhs.acl_user_map
&& lhs.acl_group_map == rhs.acl_group_map
&& lhs.referer_list == rhs.referer_list
&& lhs.grant_map == rhs.grant_map;
}
bool operator!=(const RGWAccessControlList& lhs,
const RGWAccessControlList& rhs) {
return !(lhs == rhs);
}
bool operator==(const ACLOwner& lhs, const ACLOwner& rhs) {
return lhs.id == rhs.id && lhs.display_name == rhs.display_name;
}
bool operator!=(const ACLOwner& lhs, const ACLOwner& rhs) {
return !(lhs == rhs);
}
bool operator==(const RGWAccessControlPolicy& lhs,
const RGWAccessControlPolicy& rhs) {
return lhs.acl == rhs.acl && lhs.owner == rhs.owner;
}
bool operator!=(const RGWAccessControlPolicy& lhs,
const RGWAccessControlPolicy& rhs) {
return !(lhs == rhs);
}
void RGWAccessControlList::_add_grant(ACLGrant *grant)
{
ACLPermission& perm = grant->get_permission();
ACLGranteeType& type = grant->get_type();
switch (type.get_type()) {
case ACL_TYPE_REFERER:
referer_list.emplace_back(grant->get_referer(), perm.get_permissions());
/* We're specially handling the Swift's .r:* as the S3 API has a similar
* concept and thus we can have a small portion of compatibility here. */
if (grant->get_referer() == RGW_REFERER_WILDCARD) {
acl_group_map[ACL_GROUP_ALL_USERS] |= perm.get_permissions();
}
break;
case ACL_TYPE_GROUP:
acl_group_map[grant->get_group()] |= perm.get_permissions();
break;
default:
{
rgw_user id;
if (!grant->get_id(id)) {
ldout(cct, 0) << "ERROR: grant->get_id() failed" << dendl;
}
acl_user_map[id.to_str()] |= perm.get_permissions();
}
}
}
void RGWAccessControlList::add_grant(ACLGrant *grant)
{
rgw_user id;
grant->get_id(id); // not that this will return false for groups, but that's ok, we won't search groups
grant_map.insert(pair<string, ACLGrant>(id.to_str(), *grant));
_add_grant(grant);
}
void RGWAccessControlList::remove_canon_user_grant(rgw_user& user_id)
{
auto multi_map_iter = grant_map.find(user_id.to_str());
if(multi_map_iter != grant_map.end()) {
auto grants = grant_map.equal_range(user_id.to_str());
grant_map.erase(grants.first, grants.second);
}
auto map_iter = acl_user_map.find(user_id.to_str());
if (map_iter != acl_user_map.end()){
acl_user_map.erase(map_iter);
}
}
uint32_t RGWAccessControlList::get_perm(const DoutPrefixProvider* dpp,
const rgw::auth::Identity& auth_identity,
const uint32_t perm_mask)
{
ldpp_dout(dpp, 5) << "Searching permissions for identity=" << auth_identity
<< " mask=" << perm_mask << dendl;
return perm_mask & auth_identity.get_perms_from_aclspec(dpp, acl_user_map);
}
uint32_t RGWAccessControlList::get_group_perm(const DoutPrefixProvider *dpp,
ACLGroupTypeEnum group,
const uint32_t perm_mask) const
{
ldpp_dout(dpp, 5) << "Searching permissions for group=" << (int)group
<< " mask=" << perm_mask << dendl;
const auto iter = acl_group_map.find((uint32_t)group);
if (iter != acl_group_map.end()) {
ldpp_dout(dpp, 5) << "Found permission: " << iter->second << dendl;
return iter->second & perm_mask;
}
ldpp_dout(dpp, 5) << "Permissions for group not found" << dendl;
return 0;
}
uint32_t RGWAccessControlList::get_referer_perm(const DoutPrefixProvider *dpp,
const uint32_t current_perm,
const std::string http_referer,
const uint32_t perm_mask)
{
ldpp_dout(dpp, 5) << "Searching permissions for referer=" << http_referer
<< " mask=" << perm_mask << dendl;
/* This function is basically a transformation from current perm to
* a new one that takes into consideration the Swift's HTTP referer-
* based ACLs. We need to go through all items to respect negative
* grants. */
uint32_t referer_perm = current_perm;
for (const auto& r : referer_list) {
if (r.is_match(http_referer)) {
referer_perm = r.perm;
}
}
ldpp_dout(dpp, 5) << "Found referer permission=" << referer_perm << dendl;
return referer_perm & perm_mask;
}
uint32_t RGWAccessControlPolicy::get_perm(const DoutPrefixProvider* dpp,
const rgw::auth::Identity& auth_identity,
const uint32_t perm_mask,
const char * const http_referer,
bool ignore_public_acls)
{
ldpp_dout(dpp, 20) << "-- Getting permissions begin with perm_mask=" << perm_mask
<< dendl;
uint32_t perm = acl.get_perm(dpp, auth_identity, perm_mask);
if (auth_identity.is_owner_of(owner.get_id())) {
perm |= perm_mask & (RGW_PERM_READ_ACP | RGW_PERM_WRITE_ACP);
}
if (perm == perm_mask) {
return perm;
}
/* should we continue looking up? */
if (!ignore_public_acls && ((perm & perm_mask) != perm_mask)) {
perm |= acl.get_group_perm(dpp, ACL_GROUP_ALL_USERS, perm_mask);
if (false == auth_identity.is_owner_of(rgw_user(RGW_USER_ANON_ID))) {
/* this is not the anonymous user */
perm |= acl.get_group_perm(dpp, ACL_GROUP_AUTHENTICATED_USERS, perm_mask);
}
}
/* Should we continue looking up even deeper? */
if (nullptr != http_referer && (perm & perm_mask) != perm_mask) {
perm = acl.get_referer_perm(dpp, perm, http_referer, perm_mask);
}
ldpp_dout(dpp, 5) << "-- Getting permissions done for identity=" << auth_identity
<< ", owner=" << owner.get_id()
<< ", perm=" << perm << dendl;
return perm;
}
bool RGWAccessControlPolicy::verify_permission(const DoutPrefixProvider* dpp,
const rgw::auth::Identity& auth_identity,
const uint32_t user_perm_mask,
const uint32_t perm,
const char * const http_referer,
bool ignore_public_acls)
{
uint32_t test_perm = perm | RGW_PERM_READ_OBJS | RGW_PERM_WRITE_OBJS;
uint32_t policy_perm = get_perm(dpp, auth_identity, test_perm, http_referer, ignore_public_acls);
/* the swift WRITE_OBJS perm is equivalent to the WRITE obj, just
convert those bits. Note that these bits will only be set on
buckets, so the swift READ permission on bucket will allow listing
the bucket content */
if (policy_perm & RGW_PERM_WRITE_OBJS) {
policy_perm |= (RGW_PERM_WRITE | RGW_PERM_WRITE_ACP);
}
if (policy_perm & RGW_PERM_READ_OBJS) {
policy_perm |= (RGW_PERM_READ | RGW_PERM_READ_ACP);
}
uint32_t acl_perm = policy_perm & perm & user_perm_mask;
ldpp_dout(dpp, 10) << " identity=" << auth_identity
<< " requested perm (type)=" << perm
<< ", policy perm=" << policy_perm
<< ", user_perm_mask=" << user_perm_mask
<< ", acl perm=" << acl_perm << dendl;
return (perm == acl_perm);
}
bool RGWAccessControlPolicy::is_public(const DoutPrefixProvider *dpp) const
{
static constexpr auto public_groups = {ACL_GROUP_ALL_USERS,
ACL_GROUP_AUTHENTICATED_USERS};
return std::any_of(public_groups.begin(), public_groups.end(),
[&, dpp](ACLGroupTypeEnum g) {
auto p = acl.get_group_perm(dpp, g, RGW_PERM_FULL_CONTROL);
return (p != RGW_PERM_NONE) && (p != RGW_PERM_INVALID);
}
);
}
void ACLPermission::generate_test_instances(list<ACLPermission*>& o)
{
ACLPermission *p = new ACLPermission;
p->set_permissions(RGW_PERM_WRITE_ACP);
o.push_back(p);
o.push_back(new ACLPermission);
}
void ACLPermission::dump(Formatter *f) const
{
f->dump_int("flags", flags);
}
void ACLGranteeType::dump(Formatter *f) const
{
f->dump_unsigned("type", type);
}
void ACLGrant::dump(Formatter *f) const
{
f->open_object_section("type");
type.dump(f);
f->close_section();
f->dump_string("id", id.to_str());
f->dump_string("email", email);
f->open_object_section("permission");
permission.dump(f);
f->close_section();
f->dump_string("name", name);
f->dump_int("group", (int)group);
f->dump_string("url_spec", url_spec);
}
void ACLGrant::generate_test_instances(list<ACLGrant*>& o)
{
rgw_user id("rgw");
string name, email;
name = "Mr. RGW";
email = "r@gw";
ACLGrant *g1 = new ACLGrant;
g1->set_canon(id, name, RGW_PERM_READ);
g1->email = email;
o.push_back(g1);
ACLGrant *g2 = new ACLGrant;
g1->set_group(ACL_GROUP_AUTHENTICATED_USERS, RGW_PERM_WRITE);
o.push_back(g2);
o.push_back(new ACLGrant);
}
void ACLGranteeType::generate_test_instances(list<ACLGranteeType*>& o)
{
ACLGranteeType *t = new ACLGranteeType;
t->set(ACL_TYPE_CANON_USER);
o.push_back(t);
o.push_back(new ACLGranteeType);
}
void RGWAccessControlList::generate_test_instances(list<RGWAccessControlList*>& o)
{
RGWAccessControlList *acl = new RGWAccessControlList(NULL);
list<ACLGrant *> glist;
list<ACLGrant *>::iterator iter;
ACLGrant::generate_test_instances(glist);
for (iter = glist.begin(); iter != glist.end(); ++iter) {
ACLGrant *grant = *iter;
acl->add_grant(grant);
delete grant;
}
o.push_back(acl);
o.push_back(new RGWAccessControlList(NULL));
}
void ACLOwner::generate_test_instances(list<ACLOwner*>& o)
{
ACLOwner *owner = new ACLOwner;
owner->id = "rgw";
owner->display_name = "Mr. RGW";
o.push_back(owner);
o.push_back(new ACLOwner);
}
void RGWAccessControlPolicy::generate_test_instances(list<RGWAccessControlPolicy*>& o)
{
list<RGWAccessControlList *> acl_list;
list<RGWAccessControlList *>::iterator iter;
for (iter = acl_list.begin(); iter != acl_list.end(); ++iter) {
RGWAccessControlList::generate_test_instances(acl_list);
iter = acl_list.begin();
RGWAccessControlPolicy *p = new RGWAccessControlPolicy(NULL);
RGWAccessControlList *l = *iter;
p->acl = *l;
string name = "radosgw";
rgw_user id("rgw");
p->owner.set_name(name);
p->owner.set_id(id);
o.push_back(p);
delete l;
}
o.push_back(new RGWAccessControlPolicy(NULL));
}
void RGWAccessControlList::dump(Formatter *f) const
{
map<string, int>::const_iterator acl_user_iter = acl_user_map.begin();
f->open_array_section("acl_user_map");
for (; acl_user_iter != acl_user_map.end(); ++acl_user_iter) {
f->open_object_section("entry");
f->dump_string("user", acl_user_iter->first);
f->dump_int("acl", acl_user_iter->second);
f->close_section();
}
f->close_section();
map<uint32_t, int>::const_iterator acl_group_iter = acl_group_map.begin();
f->open_array_section("acl_group_map");
for (; acl_group_iter != acl_group_map.end(); ++acl_group_iter) {
f->open_object_section("entry");
f->dump_unsigned("group", acl_group_iter->first);
f->dump_int("acl", acl_group_iter->second);
f->close_section();
}
f->close_section();
multimap<string, ACLGrant>::const_iterator giter = grant_map.begin();
f->open_array_section("grant_map");
for (; giter != grant_map.end(); ++giter) {
f->open_object_section("entry");
f->dump_string("id", giter->first);
f->open_object_section("grant");
giter->second.dump(f);
f->close_section();
f->close_section();
}
f->close_section();
}
void ACLOwner::dump(Formatter *f) const
{
encode_json("id", id.to_str(), f);
encode_json("display_name", display_name, f);
}
void ACLOwner::decode_json(JSONObj *obj) {
string id_str;
JSONDecoder::decode_json("id", id_str, obj);
id.from_str(id_str);
JSONDecoder::decode_json("display_name", display_name, obj);
}
void RGWAccessControlPolicy::dump(Formatter *f) const
{
encode_json("acl", acl, f);
encode_json("owner", owner, f);
}
ACLGroupTypeEnum ACLGrant::uri_to_group(string& uri)
{
// this is required for backward compatibility
return ACLGrant_S3::uri_to_group(uri);
}
| 13,781 | 30.110609 | 105 |
cc
|
null |
ceph-main/src/rgw/rgw_acl.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#pragma once
#include <map>
#include <string>
#include <string_view>
#include <include/types.h>
#include <boost/optional.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include "common/debug.h"
#include "rgw_basic_types.h" //includes rgw_acl_types.h
class ACLGrant
{
protected:
ACLGranteeType type;
rgw_user id;
std::string email;
mutable rgw_user email_id;
ACLPermission permission;
std::string name;
ACLGroupTypeEnum group;
std::string url_spec;
public:
ACLGrant() : group(ACL_GROUP_NONE) {}
virtual ~ACLGrant() {}
/* there's an assumption here that email/uri/id encodings are
different and there can't be any overlap */
bool get_id(rgw_user& _id) const {
switch(type.get_type()) {
case ACL_TYPE_EMAIL_USER:
_id = email; // implies from_str() that parses the 't:u' syntax
return true;
case ACL_TYPE_GROUP:
case ACL_TYPE_REFERER:
return false;
default:
_id = id;
return true;
}
}
const rgw_user* get_id() const {
switch(type.get_type()) {
case ACL_TYPE_EMAIL_USER:
email_id.from_str(email);
return &email_id;
case ACL_TYPE_GROUP:
case ACL_TYPE_REFERER:
return nullptr;
default:
return &id;
}
}
ACLGranteeType& get_type() { return type; }
const ACLGranteeType& get_type() const { return type; }
ACLPermission& get_permission() { return permission; }
const ACLPermission& get_permission() const { return permission; }
ACLGroupTypeEnum get_group() const { return group; }
const std::string& get_referer() const { return url_spec; }
void encode(bufferlist& bl) const {
ENCODE_START(5, 3, bl);
encode(type, bl);
std::string s;
id.to_str(s);
encode(s, bl);
std::string uri;
encode(uri, bl);
encode(email, bl);
encode(permission, bl);
encode(name, bl);
__u32 g = (__u32)group;
encode(g, bl);
encode(url_spec, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& bl) {
DECODE_START_LEGACY_COMPAT_LEN(5, 3, 3, bl);
decode(type, bl);
std::string s;
decode(s, bl);
id.from_str(s);
std::string uri;
decode(uri, bl);
decode(email, bl);
decode(permission, bl);
decode(name, bl);
if (struct_v > 1) {
__u32 g;
decode(g, bl);
group = (ACLGroupTypeEnum)g;
} else {
group = uri_to_group(uri);
}
if (struct_v >= 5) {
decode(url_spec, bl);
} else {
url_spec.clear();
}
DECODE_FINISH(bl);
}
void dump(Formatter *f) const;
static void generate_test_instances(std::list<ACLGrant*>& o);
ACLGroupTypeEnum uri_to_group(std::string& uri);
void set_canon(const rgw_user& _id, const std::string& _name, const uint32_t perm) {
type.set(ACL_TYPE_CANON_USER);
id = _id;
name = _name;
permission.set_permissions(perm);
}
void set_group(ACLGroupTypeEnum _group, const uint32_t perm) {
type.set(ACL_TYPE_GROUP);
group = _group;
permission.set_permissions(perm);
}
void set_referer(const std::string& _url_spec, const uint32_t perm) {
type.set(ACL_TYPE_REFERER);
url_spec = _url_spec;
permission.set_permissions(perm);
}
friend bool operator==(const ACLGrant& lhs, const ACLGrant& rhs);
friend bool operator!=(const ACLGrant& lhs, const ACLGrant& rhs);
};
WRITE_CLASS_ENCODER(ACLGrant)
struct ACLReferer {
std::string url_spec;
uint32_t perm;
ACLReferer() : perm(0) {}
ACLReferer(const std::string& url_spec,
const uint32_t perm)
: url_spec(url_spec),
perm(perm) {
}
bool is_match(std::string_view http_referer) const {
const auto http_host = get_http_host(http_referer);
if (!http_host || http_host->length() < url_spec.length()) {
return false;
}
if ("*" == url_spec) {
return true;
}
if (http_host->compare(url_spec) == 0) {
return true;
}
if ('.' == url_spec[0]) {
/* Wildcard support: a referer matches the spec when its last char are
* perfectly equal to spec. */
return boost::algorithm::ends_with(http_host.value(), url_spec);
}
return false;
}
void encode(bufferlist& bl) const {
ENCODE_START(1, 1, bl);
encode(url_spec, bl);
encode(perm, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& bl) {
DECODE_START_LEGACY_COMPAT_LEN(1, 1, 1, bl);
decode(url_spec, bl);
decode(perm, bl);
DECODE_FINISH(bl);
}
void dump(Formatter *f) const;
friend bool operator==(const ACLReferer& lhs, const ACLReferer& rhs);
friend bool operator!=(const ACLReferer& lhs, const ACLReferer& rhs);
private:
boost::optional<std::string_view> get_http_host(const std::string_view url) const {
size_t pos = url.find("://");
if (pos == std::string_view::npos || boost::algorithm::starts_with(url, "://") ||
boost::algorithm::ends_with(url, "://") || boost::algorithm::ends_with(url, "@")) {
return boost::none;
}
std::string_view url_sub = url.substr(pos + strlen("://"));
pos = url_sub.find('@');
if (pos != std::string_view::npos) {
url_sub = url_sub.substr(pos + 1);
}
pos = url_sub.find_first_of("/:");
if (pos == std::string_view::npos) {
/* no port or path exists */
return url_sub;
}
return url_sub.substr(0, pos);
}
};
WRITE_CLASS_ENCODER(ACLReferer)
namespace rgw {
namespace auth {
class Identity;
}
}
using ACLGrantMap = std::multimap<std::string, ACLGrant>;
class RGWAccessControlList
{
protected:
CephContext *cct;
/* FIXME: in the feature we should consider switching to uint32_t also
* in data structures. */
std::map<std::string, int> acl_user_map;
std::map<uint32_t, int> acl_group_map;
std::list<ACLReferer> referer_list;
ACLGrantMap grant_map;
void _add_grant(ACLGrant *grant);
public:
explicit RGWAccessControlList(CephContext *_cct) : cct(_cct) {}
RGWAccessControlList() : cct(NULL) {}
void set_ctx(CephContext *ctx) {
cct = ctx;
}
virtual ~RGWAccessControlList() {}
uint32_t get_perm(const DoutPrefixProvider* dpp,
const rgw::auth::Identity& auth_identity,
uint32_t perm_mask);
uint32_t get_group_perm(const DoutPrefixProvider *dpp, ACLGroupTypeEnum group, uint32_t perm_mask) const;
uint32_t get_referer_perm(const DoutPrefixProvider *dpp, uint32_t current_perm,
std::string http_referer,
uint32_t perm_mask);
void encode(bufferlist& bl) const {
ENCODE_START(4, 3, bl);
bool maps_initialized = true;
encode(maps_initialized, bl);
encode(acl_user_map, bl);
encode(grant_map, bl);
encode(acl_group_map, bl);
encode(referer_list, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& bl) {
DECODE_START_LEGACY_COMPAT_LEN(4, 3, 3, bl);
bool maps_initialized;
decode(maps_initialized, bl);
decode(acl_user_map, bl);
decode(grant_map, bl);
if (struct_v >= 2) {
decode(acl_group_map, bl);
} else if (!maps_initialized) {
ACLGrantMap::iterator iter;
for (iter = grant_map.begin(); iter != grant_map.end(); ++iter) {
ACLGrant& grant = iter->second;
_add_grant(&grant);
}
}
if (struct_v >= 4) {
decode(referer_list, bl);
}
DECODE_FINISH(bl);
}
void dump(Formatter *f) const;
static void generate_test_instances(std::list<RGWAccessControlList*>& o);
void add_grant(ACLGrant *grant);
void remove_canon_user_grant(rgw_user& user_id);
ACLGrantMap& get_grant_map() { return grant_map; }
const ACLGrantMap& get_grant_map() const { return grant_map; }
void create_default(const rgw_user& id, std::string name) {
acl_user_map.clear();
acl_group_map.clear();
referer_list.clear();
ACLGrant grant;
grant.set_canon(id, name, RGW_PERM_FULL_CONTROL);
add_grant(&grant);
}
friend bool operator==(const RGWAccessControlList& lhs, const RGWAccessControlList& rhs);
friend bool operator!=(const RGWAccessControlList& lhs, const RGWAccessControlList& rhs);
};
WRITE_CLASS_ENCODER(RGWAccessControlList)
class ACLOwner
{
protected:
rgw_user id;
std::string display_name;
public:
ACLOwner() {}
ACLOwner(const rgw_user& _id) : id(_id) {}
~ACLOwner() {}
void encode(bufferlist& bl) const {
ENCODE_START(3, 2, bl);
std::string s;
id.to_str(s);
encode(s, bl);
encode(display_name, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& bl) {
DECODE_START_LEGACY_COMPAT_LEN(3, 2, 2, bl);
std::string s;
decode(s, bl);
id.from_str(s);
decode(display_name, bl);
DECODE_FINISH(bl);
}
void dump(Formatter *f) const;
void decode_json(JSONObj *obj);
static void generate_test_instances(std::list<ACLOwner*>& o);
void set_id(const rgw_user& _id) { id = _id; }
void set_name(const std::string& name) { display_name = name; }
rgw_user& get_id() { return id; }
const rgw_user& get_id() const { return id; }
std::string& get_display_name() { return display_name; }
const std::string& get_display_name() const { return display_name; }
friend bool operator==(const ACLOwner& lhs, const ACLOwner& rhs);
friend bool operator!=(const ACLOwner& lhs, const ACLOwner& rhs);
};
WRITE_CLASS_ENCODER(ACLOwner)
class RGWAccessControlPolicy
{
protected:
CephContext *cct;
RGWAccessControlList acl;
ACLOwner owner;
public:
explicit RGWAccessControlPolicy(CephContext *_cct) : cct(_cct), acl(_cct) {}
RGWAccessControlPolicy() : cct(NULL), acl(NULL) {}
virtual ~RGWAccessControlPolicy() {}
void set_ctx(CephContext *ctx) {
cct = ctx;
acl.set_ctx(ctx);
}
uint32_t get_perm(const DoutPrefixProvider* dpp,
const rgw::auth::Identity& auth_identity,
uint32_t perm_mask,
const char * http_referer,
bool ignore_public_acls=false);
bool verify_permission(const DoutPrefixProvider* dpp,
const rgw::auth::Identity& auth_identity,
uint32_t user_perm_mask,
uint32_t perm,
const char * http_referer = nullptr,
bool ignore_public_acls=false);
void encode(bufferlist& bl) const {
ENCODE_START(2, 2, bl);
encode(owner, bl);
encode(acl, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& bl) {
DECODE_START_LEGACY_COMPAT_LEN(2, 2, 2, bl);
decode(owner, bl);
decode(acl, bl);
DECODE_FINISH(bl);
}
void dump(Formatter *f) const;
static void generate_test_instances(std::list<RGWAccessControlPolicy*>& o);
void decode_owner(bufferlist::const_iterator& bl) { // sometimes we only need that, should be faster
DECODE_START_LEGACY_COMPAT_LEN(2, 2, 2, bl);
decode(owner, bl);
DECODE_FINISH(bl);
}
void set_owner(ACLOwner& o) { owner = o; }
ACLOwner& get_owner() {
return owner;
}
void create_default(const rgw_user& id, std::string& name) {
acl.create_default(id, name);
owner.set_id(id);
owner.set_name(name);
}
RGWAccessControlList& get_acl() {
return acl;
}
const RGWAccessControlList& get_acl() const {
return acl;
}
virtual bool compare_group_name(std::string& id, ACLGroupTypeEnum group) { return false; }
bool is_public(const DoutPrefixProvider *dpp) const;
friend bool operator==(const RGWAccessControlPolicy& lhs, const RGWAccessControlPolicy& rhs);
friend bool operator!=(const RGWAccessControlPolicy& lhs, const RGWAccessControlPolicy& rhs);
};
WRITE_CLASS_ENCODER(RGWAccessControlPolicy)
| 11,762 | 27.344578 | 107 |
h
|
null |
ceph-main/src/rgw/rgw_acl_s3.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include <string.h>
#include <iostream>
#include <map>
#include "include/types.h"
#include "rgw_acl_s3.h"
#include "rgw_user.h"
#include "rgw_sal.h"
#define dout_subsys ceph_subsys_rgw
#define RGW_URI_ALL_USERS "http://acs.amazonaws.com/groups/global/AllUsers"
#define RGW_URI_AUTH_USERS "http://acs.amazonaws.com/groups/global/AuthenticatedUsers"
using namespace std;
static string rgw_uri_all_users = RGW_URI_ALL_USERS;
static string rgw_uri_auth_users = RGW_URI_AUTH_USERS;
void ACLPermission_S3::to_xml(ostream& out)
{
if ((flags & RGW_PERM_FULL_CONTROL) == RGW_PERM_FULL_CONTROL) {
out << "<Permission>FULL_CONTROL</Permission>";
} else {
if (flags & RGW_PERM_READ)
out << "<Permission>READ</Permission>";
if (flags & RGW_PERM_WRITE)
out << "<Permission>WRITE</Permission>";
if (flags & RGW_PERM_READ_ACP)
out << "<Permission>READ_ACP</Permission>";
if (flags & RGW_PERM_WRITE_ACP)
out << "<Permission>WRITE_ACP</Permission>";
}
}
bool ACLPermission_S3::
xml_end(const char *el)
{
const char *s = data.c_str();
if (strcasecmp(s, "READ") == 0) {
flags |= RGW_PERM_READ;
return true;
} else if (strcasecmp(s, "WRITE") == 0) {
flags |= RGW_PERM_WRITE;
return true;
} else if (strcasecmp(s, "READ_ACP") == 0) {
flags |= RGW_PERM_READ_ACP;
return true;
} else if (strcasecmp(s, "WRITE_ACP") == 0) {
flags |= RGW_PERM_WRITE_ACP;
return true;
} else if (strcasecmp(s, "FULL_CONTROL") == 0) {
flags |= RGW_PERM_FULL_CONTROL;
return true;
}
return false;
}
class ACLGranteeType_S3 {
public:
static const char *to_string(ACLGranteeType& type) {
switch (type.get_type()) {
case ACL_TYPE_CANON_USER:
return "CanonicalUser";
case ACL_TYPE_EMAIL_USER:
return "AmazonCustomerByEmail";
case ACL_TYPE_GROUP:
return "Group";
default:
return "unknown";
}
}
static void set(const char *s, ACLGranteeType& type) {
if (!s) {
type.set(ACL_TYPE_UNKNOWN);
return;
}
if (strcmp(s, "CanonicalUser") == 0)
type.set(ACL_TYPE_CANON_USER);
else if (strcmp(s, "AmazonCustomerByEmail") == 0)
type.set(ACL_TYPE_EMAIL_USER);
else if (strcmp(s, "Group") == 0)
type.set(ACL_TYPE_GROUP);
else
type.set(ACL_TYPE_UNKNOWN);
}
};
class ACLID_S3 : public XMLObj
{
public:
ACLID_S3() {}
~ACLID_S3() override {}
string& to_str() { return data; }
};
class ACLURI_S3 : public XMLObj
{
public:
ACLURI_S3() {}
~ACLURI_S3() override {}
};
class ACLEmail_S3 : public XMLObj
{
public:
ACLEmail_S3() {}
~ACLEmail_S3() override {}
};
class ACLDisplayName_S3 : public XMLObj
{
public:
ACLDisplayName_S3() {}
~ACLDisplayName_S3() override {}
};
bool ACLOwner_S3::xml_end(const char *el) {
ACLID_S3 *acl_id = static_cast<ACLID_S3 *>(find_first("ID"));
ACLID_S3 *acl_name = static_cast<ACLID_S3 *>(find_first("DisplayName"));
// ID is mandatory
if (!acl_id)
return false;
id = acl_id->get_data();
// DisplayName is optional
if (acl_name)
display_name = acl_name->get_data();
else
display_name = "";
return true;
}
void ACLOwner_S3::to_xml(ostream& out) {
string s;
id.to_str(s);
if (s.empty())
return;
out << "<Owner>" << "<ID>" << s << "</ID>";
if (!display_name.empty())
out << "<DisplayName>" << display_name << "</DisplayName>";
out << "</Owner>";
}
bool ACLGrant_S3::xml_end(const char *el) {
ACLGrantee_S3 *acl_grantee;
ACLID_S3 *acl_id;
ACLURI_S3 *acl_uri;
ACLEmail_S3 *acl_email;
ACLPermission_S3 *acl_permission;
ACLDisplayName_S3 *acl_name;
string uri;
acl_grantee = static_cast<ACLGrantee_S3 *>(find_first("Grantee"));
if (!acl_grantee)
return false;
string type_str;
if (!acl_grantee->get_attr("xsi:type", type_str))
return false;
ACLGranteeType_S3::set(type_str.c_str(), type);
acl_permission = static_cast<ACLPermission_S3 *>(find_first("Permission"));
if (!acl_permission)
return false;
permission = *acl_permission;
id.clear();
name.clear();
email.clear();
switch (type.get_type()) {
case ACL_TYPE_CANON_USER:
acl_id = static_cast<ACLID_S3 *>(acl_grantee->find_first("ID"));
if (!acl_id)
return false;
id = acl_id->to_str();
acl_name = static_cast<ACLDisplayName_S3 *>(acl_grantee->find_first("DisplayName"));
if (acl_name)
name = acl_name->get_data();
break;
case ACL_TYPE_GROUP:
acl_uri = static_cast<ACLURI_S3 *>(acl_grantee->find_first("URI"));
if (!acl_uri)
return false;
uri = acl_uri->get_data();
group = uri_to_group(uri);
break;
case ACL_TYPE_EMAIL_USER:
acl_email = static_cast<ACLEmail_S3 *>(acl_grantee->find_first("EmailAddress"));
if (!acl_email)
return false;
email = acl_email->get_data();
break;
default:
// unknown user type
return false;
};
return true;
}
void ACLGrant_S3::to_xml(CephContext *cct, ostream& out) {
ACLPermission_S3& perm = static_cast<ACLPermission_S3 &>(permission);
/* only show s3 compatible permissions */
if (!(perm.get_permissions() & RGW_PERM_ALL_S3))
return;
string uri;
out << "<Grant>" <<
"<Grantee xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"" << ACLGranteeType_S3::to_string(type) << "\">";
switch (type.get_type()) {
case ACL_TYPE_CANON_USER:
out << "<ID>" << id << "</ID>";
if (name.size()) {
out << "<DisplayName>" << name << "</DisplayName>";
}
break;
case ACL_TYPE_EMAIL_USER:
out << "<EmailAddress>" << email << "</EmailAddress>";
break;
case ACL_TYPE_GROUP:
if (!group_to_uri(group, uri)) {
ldout(cct, 0) << "ERROR: group_to_uri failed with group=" << (int)group << dendl;
break;
}
out << "<URI>" << uri << "</URI>";
break;
default:
break;
}
out << "</Grantee>";
perm.to_xml(out);
out << "</Grant>";
}
bool ACLGrant_S3::group_to_uri(ACLGroupTypeEnum group, string& uri)
{
switch (group) {
case ACL_GROUP_ALL_USERS:
uri = rgw_uri_all_users;
return true;
case ACL_GROUP_AUTHENTICATED_USERS:
uri = rgw_uri_auth_users;
return true;
default:
return false;
}
}
bool RGWAccessControlList_S3::xml_end(const char *el) {
XMLObjIter iter = find("Grant");
ACLGrant_S3 *grant = static_cast<ACLGrant_S3 *>(iter.get_next());
while (grant) {
add_grant(grant);
grant = static_cast<ACLGrant_S3 *>(iter.get_next());
}
return true;
}
void RGWAccessControlList_S3::to_xml(ostream& out) {
multimap<string, ACLGrant>::iterator iter;
out << "<AccessControlList>";
for (iter = grant_map.begin(); iter != grant_map.end(); ++iter) {
ACLGrant_S3& grant = static_cast<ACLGrant_S3 &>(iter->second);
grant.to_xml(cct, out);
}
out << "</AccessControlList>";
}
struct s3_acl_header {
int rgw_perm;
const char *http_header;
};
static const char *get_acl_header(const RGWEnv *env,
const struct s3_acl_header *perm)
{
const char *header = perm->http_header;
return env->get(header, NULL);
}
static int parse_grantee_str(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver, string& grantee_str,
const struct s3_acl_header *perm, ACLGrant& grant)
{
string id_type, id_val_quoted;
int rgw_perm = perm->rgw_perm;
int ret;
ret = parse_key_value(grantee_str, id_type, id_val_quoted);
if (ret < 0)
return ret;
string id_val = rgw_trim_quotes(id_val_quoted);
if (strcasecmp(id_type.c_str(), "emailAddress") == 0) {
std::unique_ptr<rgw::sal::User> user;
ret = driver->get_user_by_email(dpp, id_val, null_yield, &user);
if (ret < 0)
return ret;
grant.set_canon(user->get_id(), user->get_display_name(), rgw_perm);
} else if (strcasecmp(id_type.c_str(), "id") == 0) {
std::unique_ptr<rgw::sal::User> user = driver->get_user(rgw_user(id_val));
ret = user->load_user(dpp, null_yield);
if (ret < 0)
return ret;
grant.set_canon(user->get_id(), user->get_display_name(), rgw_perm);
} else if (strcasecmp(id_type.c_str(), "uri") == 0) {
ACLGroupTypeEnum gid = grant.uri_to_group(id_val);
if (gid == ACL_GROUP_NONE)
return -EINVAL;
grant.set_group(gid, rgw_perm);
} else {
return -EINVAL;
}
return 0;
}
static int parse_acl_header(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver,
const RGWEnv *env, const struct s3_acl_header *perm,
std::list<ACLGrant>& _grants)
{
std::list<string> grantees;
std::string hacl_str;
const char *hacl = get_acl_header(env, perm);
if (hacl == NULL)
return 0;
hacl_str = hacl;
get_str_list(hacl_str, ",", grantees);
for (list<string>::iterator it = grantees.begin(); it != grantees.end(); ++it) {
ACLGrant grant;
int ret = parse_grantee_str(dpp, driver, *it, perm, grant);
if (ret < 0)
return ret;
_grants.push_back(grant);
}
return 0;
}
int RGWAccessControlList_S3::create_canned(ACLOwner& owner, ACLOwner& bucket_owner, const string& canned_acl)
{
acl_user_map.clear();
grant_map.clear();
ACLGrant owner_grant;
rgw_user bid = bucket_owner.get_id();
string bname = bucket_owner.get_display_name();
/* owner gets full control */
owner_grant.set_canon(owner.get_id(), owner.get_display_name(), RGW_PERM_FULL_CONTROL);
add_grant(&owner_grant);
if (canned_acl.size() == 0 || canned_acl.compare("private") == 0) {
return 0;
}
ACLGrant bucket_owner_grant;
ACLGrant group_grant;
if (canned_acl.compare("public-read") == 0) {
group_grant.set_group(ACL_GROUP_ALL_USERS, RGW_PERM_READ);
add_grant(&group_grant);
} else if (canned_acl.compare("public-read-write") == 0) {
group_grant.set_group(ACL_GROUP_ALL_USERS, RGW_PERM_READ);
add_grant(&group_grant);
group_grant.set_group(ACL_GROUP_ALL_USERS, RGW_PERM_WRITE);
add_grant(&group_grant);
} else if (canned_acl.compare("authenticated-read") == 0) {
group_grant.set_group(ACL_GROUP_AUTHENTICATED_USERS, RGW_PERM_READ);
add_grant(&group_grant);
} else if (canned_acl.compare("bucket-owner-read") == 0) {
bucket_owner_grant.set_canon(bid, bname, RGW_PERM_READ);
if (bid.compare(owner.get_id()) != 0)
add_grant(&bucket_owner_grant);
} else if (canned_acl.compare("bucket-owner-full-control") == 0) {
bucket_owner_grant.set_canon(bid, bname, RGW_PERM_FULL_CONTROL);
if (bid.compare(owner.get_id()) != 0)
add_grant(&bucket_owner_grant);
} else {
return -EINVAL;
}
return 0;
}
int RGWAccessControlList_S3::create_from_grants(std::list<ACLGrant>& grants)
{
if (grants.empty())
return -EINVAL;
acl_user_map.clear();
grant_map.clear();
for (std::list<ACLGrant>::iterator it = grants.begin(); it != grants.end(); ++it) {
ACLGrant g = *it;
add_grant(&g);
}
return 0;
}
bool RGWAccessControlPolicy_S3::xml_end(const char *el) {
RGWAccessControlList_S3 *s3acl =
static_cast<RGWAccessControlList_S3 *>(find_first("AccessControlList"));
if (!s3acl)
return false;
acl = *s3acl;
ACLOwner *owner_p = static_cast<ACLOwner_S3 *>(find_first("Owner"));
if (!owner_p)
return false;
owner = *owner_p;
return true;
}
void RGWAccessControlPolicy_S3::to_xml(ostream& out) {
out << "<AccessControlPolicy xmlns=\"" << XMLNS_AWS_S3 << "\">";
ACLOwner_S3& _owner = static_cast<ACLOwner_S3 &>(owner);
RGWAccessControlList_S3& _acl = static_cast<RGWAccessControlList_S3 &>(acl);
_owner.to_xml(out);
_acl.to_xml(out);
out << "</AccessControlPolicy>";
}
static const s3_acl_header acl_header_perms[] = {
{RGW_PERM_READ, "HTTP_X_AMZ_GRANT_READ"},
{RGW_PERM_WRITE, "HTTP_X_AMZ_GRANT_WRITE"},
{RGW_PERM_READ_ACP,"HTTP_X_AMZ_GRANT_READ_ACP"},
{RGW_PERM_WRITE_ACP, "HTTP_X_AMZ_GRANT_WRITE_ACP"},
{RGW_PERM_FULL_CONTROL, "HTTP_X_AMZ_GRANT_FULL_CONTROL"},
{0, NULL}
};
int RGWAccessControlPolicy_S3::create_from_headers(const DoutPrefixProvider *dpp,
rgw::sal::Driver* driver,
const RGWEnv *env, ACLOwner& _owner)
{
std::list<ACLGrant> grants;
int r = 0;
for (const struct s3_acl_header *p = acl_header_perms; p->rgw_perm; p++) {
r = parse_acl_header(dpp, driver, env, p, grants);
if (r < 0) {
return r;
}
}
RGWAccessControlList_S3& _acl = static_cast<RGWAccessControlList_S3 &>(acl);
r = _acl.create_from_grants(grants);
owner = _owner;
return r;
}
/*
can only be called on object that was parsed
*/
int RGWAccessControlPolicy_S3::rebuild(const DoutPrefixProvider *dpp,
rgw::sal::Driver* driver, ACLOwner *owner,
RGWAccessControlPolicy& dest, std::string &err_msg)
{
if (!owner)
return -EINVAL;
ACLOwner *requested_owner = static_cast<ACLOwner_S3 *>(find_first("Owner"));
if (requested_owner) {
rgw_user& requested_id = requested_owner->get_id();
if (!requested_id.empty() && requested_id.compare(owner->get_id()) != 0)
return -EPERM;
}
std::unique_ptr<rgw::sal::User> user = driver->get_user(owner->get_id());
if (user->load_user(dpp, null_yield) < 0) {
ldpp_dout(dpp, 10) << "owner info does not exist" << dendl;
err_msg = "Invalid id";
return -EINVAL;
}
ACLOwner& dest_owner = dest.get_owner();
dest_owner.set_id(owner->get_id());
dest_owner.set_name(user->get_display_name());
ldpp_dout(dpp, 20) << "owner id=" << owner->get_id() << dendl;
ldpp_dout(dpp, 20) << "dest owner id=" << dest.get_owner().get_id() << dendl;
RGWAccessControlList& dst_acl = dest.get_acl();
multimap<string, ACLGrant>& grant_map = acl.get_grant_map();
multimap<string, ACLGrant>::iterator iter;
for (iter = grant_map.begin(); iter != grant_map.end(); ++iter) {
ACLGrant& src_grant = iter->second;
ACLGranteeType& type = src_grant.get_type();
ACLGrant new_grant;
bool grant_ok = false;
rgw_user uid;
RGWUserInfo grant_user;
switch (type.get_type()) {
case ACL_TYPE_EMAIL_USER:
{
string email;
rgw_user u;
if (!src_grant.get_id(u)) {
ldpp_dout(dpp, 0) << "ERROR: src_grant.get_id() failed" << dendl;
return -EINVAL;
}
email = u.id;
ldpp_dout(dpp, 10) << "grant user email=" << email << dendl;
if (driver->get_user_by_email(dpp, email, null_yield, &user) < 0) {
ldpp_dout(dpp, 10) << "grant user email not found or other error" << dendl;
err_msg = "The e-mail address you provided does not match any account on record.";
return -ERR_UNRESOLVABLE_EMAIL;
}
grant_user = user->get_info();
uid = grant_user.user_id;
}
case ACL_TYPE_CANON_USER:
{
if (type.get_type() == ACL_TYPE_CANON_USER) {
if (!src_grant.get_id(uid)) {
ldpp_dout(dpp, 0) << "ERROR: src_grant.get_id() failed" << dendl;
err_msg = "Invalid id";
return -EINVAL;
}
}
if (grant_user.user_id.empty()) {
user = driver->get_user(uid);
if (user->load_user(dpp, null_yield) < 0) {
ldpp_dout(dpp, 10) << "grant user does not exist:" << uid << dendl;
err_msg = "Invalid id";
return -EINVAL;
} else {
grant_user = user->get_info();
}
}
ACLPermission& perm = src_grant.get_permission();
new_grant.set_canon(uid, grant_user.display_name, perm.get_permissions());
grant_ok = true;
rgw_user new_id;
new_grant.get_id(new_id);
ldpp_dout(dpp, 10) << "new grant: " << new_id << ":" << grant_user.display_name << dendl;
}
break;
case ACL_TYPE_GROUP:
{
string uri;
if (ACLGrant_S3::group_to_uri(src_grant.get_group(), uri)) {
new_grant = src_grant;
grant_ok = true;
ldpp_dout(dpp, 10) << "new grant: " << uri << dendl;
} else {
ldpp_dout(dpp, 10) << "bad grant group:" << (int)src_grant.get_group() << dendl;
err_msg = "Invalid group uri";
return -EINVAL;
}
}
default:
break;
}
if (grant_ok) {
dst_acl.add_grant(&new_grant);
}
}
return 0;
}
bool RGWAccessControlPolicy_S3::compare_group_name(string& id, ACLGroupTypeEnum group)
{
switch (group) {
case ACL_GROUP_ALL_USERS:
return (id.compare(RGW_USER_ANON_ID) == 0);
case ACL_GROUP_AUTHENTICATED_USERS:
return (id.compare(rgw_uri_auth_users) == 0);
default:
return id.empty();
}
// shouldn't get here
return false;
}
XMLObj *RGWACLXMLParser_S3::alloc_obj(const char *el)
{
XMLObj * obj = NULL;
if (strcmp(el, "AccessControlPolicy") == 0) {
obj = new RGWAccessControlPolicy_S3(cct);
} else if (strcmp(el, "Owner") == 0) {
obj = new ACLOwner_S3();
} else if (strcmp(el, "AccessControlList") == 0) {
obj = new RGWAccessControlList_S3(cct);
} else if (strcmp(el, "ID") == 0) {
obj = new ACLID_S3();
} else if (strcmp(el, "DisplayName") == 0) {
obj = new ACLDisplayName_S3();
} else if (strcmp(el, "Grant") == 0) {
obj = new ACLGrant_S3();
} else if (strcmp(el, "Grantee") == 0) {
obj = new ACLGrantee_S3();
} else if (strcmp(el, "Permission") == 0) {
obj = new ACLPermission_S3();
} else if (strcmp(el, "URI") == 0) {
obj = new ACLURI_S3();
} else if (strcmp(el, "EmailAddress") == 0) {
obj = new ACLEmail_S3();
}
return obj;
}
ACLGroupTypeEnum ACLGrant_S3::uri_to_group(string& uri)
{
if (uri.compare(rgw_uri_all_users) == 0)
return ACL_GROUP_ALL_USERS;
else if (uri.compare(rgw_uri_auth_users) == 0)
return ACL_GROUP_AUTHENTICATED_USERS;
return ACL_GROUP_NONE;
}
| 17,626 | 26.371118 | 135 |
cc
|
null |
ceph-main/src/rgw/rgw_acl_s3.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#pragma once
#include <map>
#include <string>
#include <iosfwd>
#include <include/types.h>
#include "include/str_list.h"
#include "rgw_xml.h"
#include "rgw_acl.h"
#include "rgw_sal_fwd.h"
class RGWUserCtl;
class ACLPermission_S3 : public ACLPermission, public XMLObj
{
public:
ACLPermission_S3() {}
virtual ~ACLPermission_S3() override {}
bool xml_end(const char *el) override;
void to_xml(std::ostream& out);
};
class ACLGrantee_S3 : public ACLGrantee, public XMLObj
{
public:
ACLGrantee_S3() {}
virtual ~ACLGrantee_S3() override {}
bool xml_start(const char *el, const char **attr);
};
class ACLGrant_S3 : public ACLGrant, public XMLObj
{
public:
ACLGrant_S3() {}
virtual ~ACLGrant_S3() override {}
void to_xml(CephContext *cct, std::ostream& out);
bool xml_end(const char *el) override;
bool xml_start(const char *el, const char **attr);
static ACLGroupTypeEnum uri_to_group(std::string& uri);
static bool group_to_uri(ACLGroupTypeEnum group, std::string& uri);
};
class RGWAccessControlList_S3 : public RGWAccessControlList, public XMLObj
{
public:
explicit RGWAccessControlList_S3(CephContext *_cct) : RGWAccessControlList(_cct) {}
virtual ~RGWAccessControlList_S3() override {}
bool xml_end(const char *el) override;
void to_xml(std::ostream& out);
int create_canned(ACLOwner& owner, ACLOwner& bucket_owner, const std::string& canned_acl);
int create_from_grants(std::list<ACLGrant>& grants);
};
class ACLOwner_S3 : public ACLOwner, public XMLObj
{
public:
ACLOwner_S3() {}
virtual ~ACLOwner_S3() override {}
bool xml_end(const char *el) override;
void to_xml(std::ostream& out);
};
class RGWEnv;
class RGWAccessControlPolicy_S3 : public RGWAccessControlPolicy, public XMLObj
{
public:
explicit RGWAccessControlPolicy_S3(CephContext *_cct) : RGWAccessControlPolicy(_cct) {}
virtual ~RGWAccessControlPolicy_S3() override {}
bool xml_end(const char *el) override;
void to_xml(std::ostream& out);
int rebuild(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver, ACLOwner *owner,
RGWAccessControlPolicy& dest, std::string &err_msg);
bool compare_group_name(std::string& id, ACLGroupTypeEnum group) override;
virtual int create_canned(ACLOwner& _owner, ACLOwner& bucket_owner, const std::string& canned_acl) {
RGWAccessControlList_S3& _acl = static_cast<RGWAccessControlList_S3 &>(acl);
if (_owner.get_id() == rgw_user("anonymous")) {
owner = bucket_owner;
} else {
owner = _owner;
}
int ret = _acl.create_canned(owner, bucket_owner, canned_acl);
return ret;
}
int create_from_headers(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver,
const RGWEnv *env, ACLOwner& _owner);
};
/**
* Interfaces with the webserver's XML handling code
* to parse it in a way that makes sense for the rgw.
*/
class RGWACLXMLParser_S3 : public RGWXMLParser
{
CephContext *cct;
XMLObj *alloc_obj(const char *el) override;
public:
explicit RGWACLXMLParser_S3(CephContext *_cct) : cct(_cct) {}
};
| 3,136 | 26.043103 | 102 |
h
|
null |
ceph-main/src/rgw/rgw_acl_swift.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include <string.h>
#include <vector>
#include <boost/algorithm/string/predicate.hpp>
#include "common/ceph_json.h"
#include "rgw_common.h"
#include "rgw_user.h"
#include "rgw_acl_swift.h"
#include "rgw_sal.h"
#define dout_subsys ceph_subsys_rgw
#define SWIFT_PERM_READ RGW_PERM_READ_OBJS
#define SWIFT_PERM_WRITE RGW_PERM_WRITE_OBJS
/* FIXME: do we really need separate RW? */
#define SWIFT_PERM_RWRT (SWIFT_PERM_READ | SWIFT_PERM_WRITE)
#define SWIFT_PERM_ADMIN RGW_PERM_FULL_CONTROL
#define SWIFT_GROUP_ALL_USERS ".r:*"
using namespace std;
static int parse_list(const char* uid_list,
std::vector<std::string>& uids) /* out */
{
char *s = strdup(uid_list);
if (!s) {
return -ENOMEM;
}
char *tokctx;
const char *p = strtok_r(s, " ,", &tokctx);
while (p) {
if (*p) {
string acl = p;
uids.push_back(acl);
}
p = strtok_r(NULL, " ,", &tokctx);
}
free(s);
return 0;
}
static bool is_referrer(const std::string& designator)
{
return designator.compare(".r") == 0 ||
designator.compare(".ref") == 0 ||
designator.compare(".referer") == 0 ||
designator.compare(".referrer") == 0;
}
static bool uid_is_public(const string& uid)
{
if (uid[0] != '.' || uid[1] != 'r')
return false;
int pos = uid.find(':');
if (pos < 0 || pos == (int)uid.size())
return false;
string sub = uid.substr(0, pos);
string after = uid.substr(pos + 1);
if (after.compare("*") != 0)
return false;
return is_referrer(sub);
}
static boost::optional<ACLGrant> referrer_to_grant(std::string url_spec,
const uint32_t perm)
{
/* This function takes url_spec as non-ref std::string because of the trim
* operation that is essential to preserve compliance with Swift. It can't
* be easily accomplished with std::string_view. */
try {
bool is_negative;
ACLGrant grant;
if ('-' == url_spec[0]) {
url_spec = url_spec.substr(1);
boost::algorithm::trim(url_spec);
is_negative = true;
} else {
is_negative = false;
}
if (url_spec != RGW_REFERER_WILDCARD) {
if ('*' == url_spec[0]) {
url_spec = url_spec.substr(1);
boost::algorithm::trim(url_spec);
}
if (url_spec.empty() || url_spec == ".") {
return boost::none;
}
} else {
/* Please be aware we're specially handling the .r:* in _add_grant()
* of RGWAccessControlList as the S3 API has a similar concept, and
* thus we can have a small portion of compatibility. */
}
grant.set_referer(url_spec, is_negative ? 0 : perm);
return grant;
} catch (const std::out_of_range&) {
return boost::none;
}
}
static ACLGrant user_to_grant(const DoutPrefixProvider *dpp,
CephContext* const cct,
rgw::sal::Driver* driver,
const std::string& uid,
const uint32_t perm)
{
RGWUserInfo grant_user;
ACLGrant grant;
std::unique_ptr<rgw::sal::User> user;
user = driver->get_user(rgw_user(uid));
if (user->load_user(dpp, null_yield) < 0) {
ldpp_dout(dpp, 10) << "grant user does not exist: " << uid << dendl;
/* skipping silently */
grant.set_canon(user->get_id(), std::string(), perm);
} else {
grant.set_canon(user->get_id(), user->get_display_name(), perm);
}
return grant;
}
int RGWAccessControlPolicy_SWIFT::add_grants(const DoutPrefixProvider *dpp,
rgw::sal::Driver* driver,
const std::vector<std::string>& uids,
const uint32_t perm)
{
for (const auto& uid : uids) {
boost::optional<ACLGrant> grant;
ldpp_dout(dpp, 20) << "trying to add grant for ACL uid=" << uid << dendl;
/* Let's check whether the item has a separator potentially indicating
* a special meaning (like an HTTP referral-based grant). */
const size_t pos = uid.find(':');
if (std::string::npos == pos) {
/* No, it don't have -- we've got just a regular user identifier. */
grant = user_to_grant(dpp, cct, driver, uid, perm);
} else {
/* Yes, *potentially* an HTTP referral. */
auto designator = uid.substr(0, pos);
auto designatee = uid.substr(pos + 1);
/* Swift strips whitespaces at both beginning and end. */
boost::algorithm::trim(designator);
boost::algorithm::trim(designatee);
if (! boost::algorithm::starts_with(designator, ".")) {
grant = user_to_grant(dpp, cct, driver, uid, perm);
} else if ((perm & SWIFT_PERM_WRITE) == 0 && is_referrer(designator)) {
/* HTTP referrer-based ACLs aren't acceptable for writes. */
grant = referrer_to_grant(designatee, perm);
}
}
if (grant) {
acl.add_grant(&*grant);
} else {
return -EINVAL;
}
}
return 0;
}
int RGWAccessControlPolicy_SWIFT::create(const DoutPrefixProvider *dpp,
rgw::sal::Driver* driver,
const rgw_user& id,
const std::string& name,
const char* read_list,
const char* write_list,
uint32_t& rw_mask)
{
acl.create_default(id, name);
owner.set_id(id);
owner.set_name(name);
rw_mask = 0;
if (read_list) {
std::vector<std::string> uids;
int r = parse_list(read_list, uids);
if (r < 0) {
ldpp_dout(dpp, 0) << "ERROR: parse_list for read returned r="
<< r << dendl;
return r;
}
r = add_grants(dpp, driver, uids, SWIFT_PERM_READ);
if (r < 0) {
ldpp_dout(dpp, 0) << "ERROR: add_grants for read returned r="
<< r << dendl;
return r;
}
rw_mask |= SWIFT_PERM_READ;
}
if (write_list) {
std::vector<std::string> uids;
int r = parse_list(write_list, uids);
if (r < 0) {
ldpp_dout(dpp, 0) << "ERROR: parse_list for write returned r="
<< r << dendl;
return r;
}
r = add_grants(dpp, driver, uids, SWIFT_PERM_WRITE);
if (r < 0) {
ldpp_dout(dpp, 0) << "ERROR: add_grants for write returned r="
<< r << dendl;
return r;
}
rw_mask |= SWIFT_PERM_WRITE;
}
return 0;
}
void RGWAccessControlPolicy_SWIFT::filter_merge(uint32_t rw_mask,
RGWAccessControlPolicy_SWIFT *old)
{
/* rw_mask&SWIFT_PERM_READ => setting read acl,
* rw_mask&SWIFT_PERM_WRITE => setting write acl
* when bit is cleared, copy matching elements from old.
*/
if (rw_mask == (SWIFT_PERM_READ|SWIFT_PERM_WRITE)) {
return;
}
rw_mask ^= (SWIFT_PERM_READ|SWIFT_PERM_WRITE);
for (auto &iter: old->acl.get_grant_map()) {
ACLGrant& grant = iter.second;
uint32_t perm = grant.get_permission().get_permissions();
rgw_user id;
string url_spec;
if (!grant.get_id(id)) {
if (grant.get_group() != ACL_GROUP_ALL_USERS) {
url_spec = grant.get_referer();
if (url_spec.empty()) {
continue;
}
if (perm == 0) {
/* We need to carry also negative, HTTP referrer-based ACLs. */
perm = SWIFT_PERM_READ;
}
}
}
if (perm & rw_mask) {
acl.add_grant(&grant);
}
}
}
void RGWAccessControlPolicy_SWIFT::to_str(string& read, string& write)
{
multimap<string, ACLGrant>& m = acl.get_grant_map();
multimap<string, ACLGrant>::iterator iter;
for (iter = m.begin(); iter != m.end(); ++iter) {
ACLGrant& grant = iter->second;
const uint32_t perm = grant.get_permission().get_permissions();
rgw_user id;
string url_spec;
if (!grant.get_id(id)) {
if (grant.get_group() == ACL_GROUP_ALL_USERS) {
id = SWIFT_GROUP_ALL_USERS;
} else {
url_spec = grant.get_referer();
if (url_spec.empty()) {
continue;
}
id = (perm != 0) ? ".r:" + url_spec : ".r:-" + url_spec;
}
}
if (perm & SWIFT_PERM_READ) {
if (!read.empty()) {
read.append(",");
}
read.append(id.to_str());
} else if (perm & SWIFT_PERM_WRITE) {
if (!write.empty()) {
write.append(",");
}
write.append(id.to_str());
} else if (perm == 0 && !url_spec.empty()) {
/* only X-Container-Read headers support referers */
if (!read.empty()) {
read.append(",");
}
read.append(id.to_str());
}
}
}
void RGWAccessControlPolicy_SWIFTAcct::add_grants(const DoutPrefixProvider *dpp,
rgw::sal::Driver* driver,
const std::vector<std::string>& uids,
const uint32_t perm)
{
for (const auto& uid : uids) {
ACLGrant grant;
if (uid_is_public(uid)) {
grant.set_group(ACL_GROUP_ALL_USERS, perm);
acl.add_grant(&grant);
} else {
std::unique_ptr<rgw::sal::User> user = driver->get_user(rgw_user(uid));
if (user->load_user(dpp, null_yield) < 0) {
ldpp_dout(dpp, 10) << "grant user does not exist:" << uid << dendl;
/* skipping silently */
grant.set_canon(user->get_id(), std::string(), perm);
acl.add_grant(&grant);
} else {
grant.set_canon(user->get_id(), user->get_display_name(), perm);
acl.add_grant(&grant);
}
}
}
}
bool RGWAccessControlPolicy_SWIFTAcct::create(const DoutPrefixProvider *dpp,
rgw::sal::Driver* driver,
const rgw_user& id,
const std::string& name,
const std::string& acl_str)
{
acl.create_default(id, name);
owner.set_id(id);
owner.set_name(name);
JSONParser parser;
if (!parser.parse(acl_str.c_str(), acl_str.length())) {
ldpp_dout(dpp, 0) << "ERROR: JSONParser::parse returned error=" << dendl;
return false;
}
JSONObjIter iter = parser.find_first("admin");
if (!iter.end() && (*iter)->is_array()) {
std::vector<std::string> admin;
decode_json_obj(admin, *iter);
ldpp_dout(dpp, 0) << "admins: " << admin << dendl;
add_grants(dpp, driver, admin, SWIFT_PERM_ADMIN);
}
iter = parser.find_first("read-write");
if (!iter.end() && (*iter)->is_array()) {
std::vector<std::string> readwrite;
decode_json_obj(readwrite, *iter);
ldpp_dout(dpp, 0) << "read-write: " << readwrite << dendl;
add_grants(dpp, driver, readwrite, SWIFT_PERM_RWRT);
}
iter = parser.find_first("read-only");
if (!iter.end() && (*iter)->is_array()) {
std::vector<std::string> readonly;
decode_json_obj(readonly, *iter);
ldpp_dout(dpp, 0) << "read-only: " << readonly << dendl;
add_grants(dpp, driver, readonly, SWIFT_PERM_READ);
}
return true;
}
boost::optional<std::string> RGWAccessControlPolicy_SWIFTAcct::to_str() const
{
std::vector<std::string> admin;
std::vector<std::string> readwrite;
std::vector<std::string> readonly;
/* Parition the grant map into three not-overlapping groups. */
for (const auto& item : get_acl().get_grant_map()) {
const ACLGrant& grant = item.second;
const uint32_t perm = grant.get_permission().get_permissions();
rgw_user id;
if (!grant.get_id(id)) {
if (grant.get_group() != ACL_GROUP_ALL_USERS) {
continue;
}
id = SWIFT_GROUP_ALL_USERS;
} else if (owner.get_id() == id) {
continue;
}
if (SWIFT_PERM_ADMIN == (perm & SWIFT_PERM_ADMIN)) {
admin.insert(admin.end(), id.to_str());
} else if (SWIFT_PERM_RWRT == (perm & SWIFT_PERM_RWRT)) {
readwrite.insert(readwrite.end(), id.to_str());
} else if (SWIFT_PERM_READ == (perm & SWIFT_PERM_READ)) {
readonly.insert(readonly.end(), id.to_str());
} else {
// FIXME: print a warning
}
}
/* If there is no grant to serialize, let's exit earlier to not return
* an empty JSON object which brakes the functional tests of Swift. */
if (admin.empty() && readwrite.empty() && readonly.empty()) {
return boost::none;
}
/* Serialize the groups. */
JSONFormatter formatter;
formatter.open_object_section("acl");
if (!readonly.empty()) {
encode_json("read-only", readonly, &formatter);
}
if (!readwrite.empty()) {
encode_json("read-write", readwrite, &formatter);
}
if (!admin.empty()) {
encode_json("admin", admin, &formatter);
}
formatter.close_section();
std::ostringstream oss;
formatter.flush(oss);
return oss.str();
}
| 12,827 | 28.220957 | 87 |
cc
|
null |
ceph-main/src/rgw/rgw_acl_swift.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#pragma once
#include <map>
#include <vector>
#include <string>
#include <include/types.h>
#include <boost/optional.hpp>
#include "rgw_acl.h"
class RGWUserCtl;
class RGWAccessControlPolicy_SWIFT : public RGWAccessControlPolicy
{
int add_grants(const DoutPrefixProvider *dpp, rgw::sal::Driver* driver,
const std::vector<std::string>& uids,
uint32_t perm);
public:
explicit RGWAccessControlPolicy_SWIFT(CephContext* const cct)
: RGWAccessControlPolicy(cct) {
}
~RGWAccessControlPolicy_SWIFT() override = default;
int create(const DoutPrefixProvider *dpp,
rgw::sal::Driver* driver,
const rgw_user& id,
const std::string& name,
const char* read_list,
const char* write_list,
uint32_t& rw_mask);
void filter_merge(uint32_t mask, RGWAccessControlPolicy_SWIFT *policy);
void to_str(std::string& read, std::string& write);
};
class RGWAccessControlPolicy_SWIFTAcct : public RGWAccessControlPolicy
{
public:
explicit RGWAccessControlPolicy_SWIFTAcct(CephContext * const cct)
: RGWAccessControlPolicy(cct) {
}
~RGWAccessControlPolicy_SWIFTAcct() override {}
void add_grants(const DoutPrefixProvider *dpp,
rgw::sal::Driver* driver,
const std::vector<std::string>& uids,
uint32_t perm);
bool create(const DoutPrefixProvider *dpp,
rgw::sal::Driver* driver,
const rgw_user& id,
const std::string& name,
const std::string& acl_str);
boost::optional<std::string> to_str() const;
};
| 1,709 | 27.983051 | 73 |
h
|
null |
ceph-main/src/rgw/rgw_acl_types.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2019 Red Hat, Inc.
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
/* N.B., this header defines fundamental serialized types. Do not
* introduce changes or include files which can only be compiled in
* radosgw or OSD contexts (e.g., rgw_sal.h, rgw_common.h)
*/
#pragma once
#include <string>
#include <list>
#include <fmt/format.h>
#include "include/types.h"
#include "common/Formatter.h"
#define RGW_PERM_NONE 0x00
#define RGW_PERM_READ 0x01
#define RGW_PERM_WRITE 0x02
#define RGW_PERM_READ_ACP 0x04
#define RGW_PERM_WRITE_ACP 0x08
#define RGW_PERM_READ_OBJS 0x10
#define RGW_PERM_WRITE_OBJS 0x20
#define RGW_PERM_FULL_CONTROL ( RGW_PERM_READ | RGW_PERM_WRITE | \
RGW_PERM_READ_ACP | RGW_PERM_WRITE_ACP )
#define RGW_PERM_ALL_S3 RGW_PERM_FULL_CONTROL
#define RGW_PERM_INVALID 0xFF00
static constexpr char RGW_REFERER_WILDCARD[] = "*";
struct RGWAccessKey {
std::string id; // AccessKey
std::string key; // SecretKey
std::string subuser;
RGWAccessKey() {}
RGWAccessKey(std::string _id, std::string _key)
: id(std::move(_id)), key(std::move(_key)) {}
void encode(bufferlist& bl) const {
ENCODE_START(2, 2, bl);
encode(id, bl);
encode(key, bl);
encode(subuser, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& bl) {
DECODE_START_LEGACY_COMPAT_LEN_32(2, 2, 2, bl);
decode(id, bl);
decode(key, bl);
decode(subuser, bl);
DECODE_FINISH(bl);
}
void dump(Formatter *f) const;
void dump_plain(Formatter *f) const;
void dump(Formatter *f, const std::string& user, bool swift) const;
static void generate_test_instances(std::list<RGWAccessKey*>& o);
void decode_json(JSONObj *obj);
void decode_json(JSONObj *obj, bool swift);
};
WRITE_CLASS_ENCODER(RGWAccessKey)
struct RGWSubUser {
std::string name;
uint32_t perm_mask;
RGWSubUser() : perm_mask(0) {}
void encode(bufferlist& bl) const {
ENCODE_START(2, 2, bl);
encode(name, bl);
encode(perm_mask, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& bl) {
DECODE_START_LEGACY_COMPAT_LEN_32(2, 2, 2, bl);
decode(name, bl);
decode(perm_mask, bl);
DECODE_FINISH(bl);
}
void dump(Formatter *f) const;
void dump(Formatter *f, const std::string& user) const;
static void generate_test_instances(std::list<RGWSubUser*>& o);
void decode_json(JSONObj *obj);
};
WRITE_CLASS_ENCODER(RGWSubUser)
class RGWUserCaps
{
std::map<std::string, uint32_t> caps;
int get_cap(const std::string& cap, std::string& type, uint32_t *perm);
int add_cap(const std::string& cap);
int remove_cap(const std::string& cap);
public:
static int parse_cap_perm(const std::string& str, uint32_t *perm);
int add_from_string(const std::string& str);
int remove_from_string(const std::string& str);
void encode(bufferlist& bl) const {
ENCODE_START(1, 1, bl);
encode(caps, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& bl) {
DECODE_START(1, bl);
decode(caps, bl);
DECODE_FINISH(bl);
}
int check_cap(const std::string& cap, uint32_t perm) const;
bool is_valid_cap_type(const std::string& tp);
void dump(Formatter *f) const;
void dump(Formatter *f, const char *name) const;
void decode_json(JSONObj *obj);
};
WRITE_CLASS_ENCODER(RGWUserCaps)
enum ACLGranteeTypeEnum {
/* numbers are encoded, should not change */
ACL_TYPE_CANON_USER = 0,
ACL_TYPE_EMAIL_USER = 1,
ACL_TYPE_GROUP = 2,
ACL_TYPE_UNKNOWN = 3,
ACL_TYPE_REFERER = 4,
};
enum ACLGroupTypeEnum {
/* numbers are encoded should not change */
ACL_GROUP_NONE = 0,
ACL_GROUP_ALL_USERS = 1,
ACL_GROUP_AUTHENTICATED_USERS = 2,
};
class ACLPermission
{
protected:
int flags;
public:
ACLPermission() : flags(0) {}
~ACLPermission() {}
uint32_t get_permissions() const { return flags; }
void set_permissions(uint32_t perm) { flags = perm; }
void encode(bufferlist& bl) const {
ENCODE_START(2, 2, bl);
encode(flags, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& bl) {
DECODE_START_LEGACY_COMPAT_LEN(2, 2, 2, bl);
decode(flags, bl);
DECODE_FINISH(bl);
}
void dump(Formatter *f) const;
static void generate_test_instances(std::list<ACLPermission*>& o);
friend bool operator==(const ACLPermission& lhs, const ACLPermission& rhs);
friend bool operator!=(const ACLPermission& lhs, const ACLPermission& rhs);
};
WRITE_CLASS_ENCODER(ACLPermission)
class ACLGranteeType
{
protected:
__u32 type;
public:
ACLGranteeType() : type(ACL_TYPE_UNKNOWN) {}
virtual ~ACLGranteeType() {}
// virtual const char *to_string() = 0;
ACLGranteeTypeEnum get_type() const { return (ACLGranteeTypeEnum)type; }
void set(ACLGranteeTypeEnum t) { type = t; }
// virtual void set(const char *s) = 0;
void encode(bufferlist& bl) const {
ENCODE_START(2, 2, bl);
encode(type, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& bl) {
DECODE_START_LEGACY_COMPAT_LEN(2, 2, 2, bl);
decode(type, bl);
DECODE_FINISH(bl);
}
void dump(Formatter *f) const;
static void generate_test_instances(std::list<ACLGranteeType*>& o);
friend bool operator==(const ACLGranteeType& lhs, const ACLGranteeType& rhs);
friend bool operator!=(const ACLGranteeType& lhs, const ACLGranteeType& rhs);
};
WRITE_CLASS_ENCODER(ACLGranteeType)
class ACLGrantee
{
public:
ACLGrantee() {}
~ACLGrantee() {}
};
| 5,909 | 26.616822 | 79 |
h
|
null |
ceph-main/src/rgw/rgw_admin.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include <errno.h>
#include <iostream>
#include <sstream>
#include <string>
#include <boost/optional.hpp>
extern "C" {
#include <liboath/oath.h>
}
#include <fmt/format.h>
#include "auth/Crypto.h"
#include "compressor/Compressor.h"
#include "common/armor.h"
#include "common/ceph_json.h"
#include "common/config.h"
#include "common/ceph_argparse.h"
#include "common/Formatter.h"
#include "common/errno.h"
#include "common/safe_io.h"
#include "common/fault_injector.h"
#include "include/util.h"
#include "cls/rgw/cls_rgw_types.h"
#include "cls/rgw/cls_rgw_client.h"
#include "include/utime.h"
#include "include/str_list.h"
#include "rgw_user.h"
#include "rgw_otp.h"
#include "rgw_rados.h"
#include "rgw_acl.h"
#include "rgw_acl_s3.h"
#include "rgw_datalog.h"
#include "rgw_lc.h"
#include "rgw_log.h"
#include "rgw_formats.h"
#include "rgw_usage.h"
#include "rgw_orphan.h"
#include "rgw_sync.h"
#include "rgw_trim_bilog.h"
#include "rgw_trim_datalog.h"
#include "rgw_trim_mdlog.h"
#include "rgw_data_sync.h"
#include "rgw_rest_conn.h"
#include "rgw_realm_watcher.h"
#include "rgw_role.h"
#include "rgw_reshard.h"
#include "rgw_http_client_curl.h"
#include "rgw_zone.h"
#include "rgw_pubsub.h"
#include "rgw_bucket_sync.h"
#include "rgw_sync_checkpoint.h"
#include "rgw_lua.h"
#include "rgw_sal.h"
#include "rgw_sal_config.h"
#include "services/svc_sync_modules.h"
#include "services/svc_cls.h"
#include "services/svc_bilog_rados.h"
#include "services/svc_mdlog.h"
#include "services/svc_meta_be_otp.h"
#include "services/svc_user.h"
#include "services/svc_zone.h"
#include "driver/rados/rgw_bucket.h"
#include "driver/rados/rgw_sal_rados.h"
#define dout_context g_ceph_context
#define SECRET_KEY_LEN 40
#define PUBLIC_ID_LEN 20
using namespace std;
static rgw::sal::Driver* driver = NULL;
static constexpr auto dout_subsys = ceph_subsys_rgw;
static const DoutPrefixProvider* dpp() {
struct GlobalPrefix : public DoutPrefixProvider {
CephContext *get_cct() const override { return dout_context; }
unsigned get_subsys() const override { return dout_subsys; }
std::ostream& gen_prefix(std::ostream& out) const override { return out; }
};
static GlobalPrefix global_dpp;
return &global_dpp;
}
#define CHECK_TRUE(x, msg, err) \
do { \
if (!x) { \
cerr << msg << std::endl; \
return err; \
} \
} while (0)
#define CHECK_SUCCESS(x, msg) \
do { \
int _x_val = (x); \
if (_x_val < 0) { \
cerr << msg << ": " << cpp_strerror(-_x_val) << std::endl; \
return _x_val; \
} \
} while (0)
static inline int posix_errortrans(int r)
{
switch(r) {
case ERR_NO_SUCH_BUCKET:
r = ENOENT;
break;
default:
break;
}
return r;
}
static const std::string LUA_CONTEXT_LIST("prerequest, postrequest, background, getdata, putdata");
void usage()
{
cout << "usage: radosgw-admin <cmd> [options...]" << std::endl;
cout << "commands:\n";
cout << " user create create a new user\n" ;
cout << " user modify modify user\n";
cout << " user info get user info\n";
cout << " user rename rename user\n";
cout << " user rm remove user\n";
cout << " user suspend suspend a user\n";
cout << " user enable re-enable user after suspension\n";
cout << " user check check user info\n";
cout << " user stats show user stats as accounted by quota subsystem\n";
cout << " user list list users\n";
cout << " caps add add user capabilities\n";
cout << " caps rm remove user capabilities\n";
cout << " subuser create create a new subuser\n" ;
cout << " subuser modify modify subuser\n";
cout << " subuser rm remove subuser\n";
cout << " key create create access key\n";
cout << " key rm remove access key\n";
cout << " bucket list list buckets (specify --allow-unordered for\n";
cout << " faster, unsorted listing)\n";
cout << " bucket limit check show bucket sharding stats\n";
cout << " bucket link link bucket to specified user\n";
cout << " bucket unlink unlink bucket from specified user\n";
cout << " bucket stats returns bucket statistics\n";
cout << " bucket rm remove bucket\n";
cout << " bucket check check bucket index\n";
cout << " bucket chown link bucket to specified user and update its object ACLs\n";
cout << " bucket reshard reshard bucket\n";
cout << " bucket rewrite rewrite all objects in the specified bucket\n";
cout << " bucket sync checkpoint poll a bucket's sync status until it catches up to its remote\n";
cout << " bucket sync disable disable bucket sync\n";
cout << " bucket sync enable enable bucket sync\n";
cout << " bucket radoslist list rados objects backing bucket's objects\n";
cout << " bi get retrieve bucket index object entries\n";
cout << " bi put store bucket index object entries\n";
cout << " bi list list raw bucket index entries\n";
cout << " bi purge purge bucket index entries\n";
cout << " object rm remove object\n";
cout << " object put put object\n";
cout << " object stat stat an object for its metadata\n";
cout << " object unlink unlink object from bucket index\n";
cout << " object rewrite rewrite the specified object\n";
cout << " object reindex reindex the object(s) indicated by --bucket and either --object or --objects-file\n";
cout << " objects expire run expired objects cleanup\n";
cout << " objects expire-stale list list stale expired objects (caused by reshard)\n";
cout << " objects expire-stale rm remove stale expired objects\n";
cout << " period rm remove a period\n";
cout << " period get get period info\n";
cout << " period get-current get current period info\n";
cout << " period pull pull a period\n";
cout << " period push push a period\n";
cout << " period list list all periods\n";
cout << " period update update the staging period\n";
cout << " period commit commit the staging period\n";
cout << " quota set set quota params\n";
cout << " quota enable enable quota\n";
cout << " quota disable disable quota\n";
cout << " ratelimit get get ratelimit params\n";
cout << " ratelimit set set ratelimit params\n";
cout << " ratelimit enable enable ratelimit\n";
cout << " ratelimit disable disable ratelimit\n";
cout << " global quota get view global quota params\n";
cout << " global quota set set global quota params\n";
cout << " global quota enable enable a global quota\n";
cout << " global quota disable disable a global quota\n";
cout << " global ratelimit get view global ratelimit params\n";
cout << " global ratelimit set set global ratelimit params\n";
cout << " global ratelimit enable enable a ratelimit quota\n";
cout << " global ratelimit disable disable a ratelimit quota\n";
cout << " realm create create a new realm\n";
cout << " realm rm remove a realm\n";
cout << " realm get show realm info\n";
cout << " realm get-default get default realm name\n";
cout << " realm list list realms\n";
cout << " realm list-periods list all realm periods\n";
cout << " realm rename rename a realm\n";
cout << " realm set set realm info (requires infile)\n";
cout << " realm default set realm as default\n";
cout << " realm pull pull a realm and its current period\n";
cout << " zonegroup add add a zone to a zonegroup\n";
cout << " zonegroup create create a new zone group info\n";
cout << " zonegroup default set default zone group\n";
cout << " zonegroup delete delete a zone group info\n";
cout << " zonegroup get show zone group info\n";
cout << " zonegroup modify modify an existing zonegroup\n";
cout << " zonegroup set set zone group info (requires infile)\n";
cout << " zonegroup rm remove a zone from a zonegroup\n";
cout << " zonegroup rename rename a zone group\n";
cout << " zonegroup list list all zone groups set on this cluster\n";
cout << " zonegroup placement list list zonegroup's placement targets\n";
cout << " zonegroup placement get get a placement target of a specific zonegroup\n";
cout << " zonegroup placement add add a placement target id to a zonegroup\n";
cout << " zonegroup placement modify modify a placement target of a specific zonegroup\n";
cout << " zonegroup placement rm remove a placement target from a zonegroup\n";
cout << " zonegroup placement default set a zonegroup's default placement target\n";
cout << " zone create create a new zone\n";
cout << " zone rm remove a zone\n";
cout << " zone get show zone cluster params\n";
cout << " zone modify modify an existing zone\n";
cout << " zone set set zone cluster params (requires infile)\n";
cout << " zone list list all zones set on this cluster\n";
cout << " zone rename rename a zone\n";
cout << " zone placement list list zone's placement targets\n";
cout << " zone placement get get a zone placement target\n";
cout << " zone placement add add a zone placement target\n";
cout << " zone placement modify modify a zone placement target\n";
cout << " zone placement rm remove a zone placement target\n";
cout << " metadata sync status get metadata sync status\n";
cout << " metadata sync init init metadata sync\n";
cout << " metadata sync run run metadata sync\n";
cout << " data sync status get data sync status of the specified source zone\n";
cout << " data sync init init data sync for the specified source zone\n";
cout << " data sync run run data sync for the specified source zone\n";
cout << " pool add add an existing pool for data placement\n";
cout << " pool rm remove an existing pool from data placement set\n";
cout << " pools list list placement active set\n";
cout << " policy read bucket/object policy\n";
cout << " log list list log objects\n";
cout << " log show dump a log from specific object or (bucket + date\n";
cout << " + bucket-id)\n";
cout << " (NOTE: required to specify formatting of date\n";
cout << " to \"YYYY-MM-DD-hh\")\n";
cout << " log rm remove log object\n";
cout << " usage show show usage (by user, by bucket, date range)\n";
cout << " usage trim trim usage (by user, by bucket, date range)\n";
cout << " usage clear reset all the usage stats for the cluster\n";
cout << " gc list dump expired garbage collection objects (specify\n";
cout << " --include-all to list all entries, including unexpired)\n";
cout << " gc process manually process garbage (specify\n";
cout << " --include-all to process all entries, including unexpired)\n";
cout << " lc list list all bucket lifecycle progress\n";
cout << " lc get get a lifecycle bucket configuration\n";
cout << " lc process manually process lifecycle\n";
cout << " lc reshard fix fix LC for a resharded bucket\n";
cout << " metadata get get metadata info\n";
cout << " metadata put put metadata info\n";
cout << " metadata rm remove metadata info\n";
cout << " metadata list list metadata info\n";
cout << " mdlog list list metadata log\n";
cout << " mdlog autotrim auto trim metadata log\n";
cout << " mdlog trim trim metadata log (use marker)\n";
cout << " mdlog status read metadata log status\n";
cout << " bilog list list bucket index log\n";
cout << " bilog trim trim bucket index log (use start-marker, end-marker)\n";
cout << " bilog status read bucket index log status\n";
cout << " bilog autotrim auto trim bucket index log\n";
cout << " datalog list list data log\n";
cout << " datalog trim trim data log\n";
cout << " datalog status read data log status\n";
cout << " datalog type change datalog type to --log_type={fifo,omap}\n";
cout << " orphans find deprecated -- init and run search for leaked rados objects (use job-id, pool)\n";
cout << " orphans finish deprecated -- clean up search for leaked rados objects\n";
cout << " orphans list-jobs deprecated -- list the current job-ids for orphans search\n";
cout << " * the three 'orphans' sub-commands are now deprecated; consider using the `rgw-orphan-list` tool\n";
cout << " role create create a AWS role for use with STS\n";
cout << " role delete remove a role\n";
cout << " role get get a role\n";
cout << " role list list roles with specified path prefix\n";
cout << " role-trust-policy modify modify the assume role policy of an existing role\n";
cout << " role-policy put add/update permission policy to role\n";
cout << " role-policy list list policies attached to a role\n";
cout << " role-policy get get the specified inline policy document embedded with the given role\n";
cout << " role-policy delete remove policy attached to a role\n";
cout << " role update update max_session_duration of a role\n";
cout << " reshard add schedule a resharding of a bucket\n";
cout << " reshard list list all bucket resharding or scheduled to be resharded\n";
cout << " reshard status read bucket resharding status\n";
cout << " reshard process process of scheduled reshard jobs\n";
cout << " reshard cancel cancel resharding a bucket\n";
cout << " reshard stale-instances list list stale-instances from bucket resharding\n";
cout << " reshard stale-instances delete cleanup stale-instances from bucket resharding\n";
cout << " sync error list list sync error\n";
cout << " sync error trim trim sync error\n";
cout << " mfa create create a new MFA TOTP token\n";
cout << " mfa list list MFA TOTP tokens\n";
cout << " mfa get show MFA TOTP token\n";
cout << " mfa remove delete MFA TOTP token\n";
cout << " mfa check check MFA TOTP token\n";
cout << " mfa resync re-sync MFA TOTP token\n";
cout << " topic list list bucket notifications topics\n";
cout << " topic get get a bucket notifications topic\n";
cout << " topic rm remove a bucket notifications topic\n";
cout << " script put upload a lua script to a context\n";
cout << " script get get the lua script of a context\n";
cout << " script rm remove the lua scripts of a context\n";
cout << " script-package add add a lua package to the scripts allowlist\n";
cout << " script-package rm remove a lua package from the scripts allowlist\n";
cout << " script-package list get the lua packages allowlist\n";
cout << " notification list list bucket notifications configuration\n";
cout << " notification get get a bucket notifications configuration\n";
cout << " notification rm remove a bucket notifications configuration\n";
cout << "options:\n";
cout << " --tenant=<tenant> tenant name\n";
cout << " --user_ns=<namespace> namespace of user (oidc in case of users authenticated with oidc provider)\n";
cout << " --uid=<id> user id\n";
cout << " --new-uid=<id> new user id\n";
cout << " --subuser=<name> subuser name\n";
cout << " --access-key=<key> S3 access key\n";
cout << " --email=<email> user's email address\n";
cout << " --secret/--secret-key=<key>\n";
cout << " specify secret key\n";
cout << " --gen-access-key generate random access key (for S3)\n";
cout << " --gen-secret generate random secret key\n";
cout << " --key-type=<type> key type, options are: swift, s3\n";
cout << " --temp-url-key[-2]=<key> temp url key\n";
cout << " --access=<access> Set access permissions for sub-user, should be one\n";
cout << " of read, write, readwrite, full\n";
cout << " --display-name=<name> user's display name\n";
cout << " --max-buckets max number of buckets for a user\n";
cout << " --admin set the admin flag on the user\n";
cout << " --system set the system flag on the user\n";
cout << " --op-mask set the op mask on the user\n";
cout << " --bucket=<bucket> Specify the bucket name. Also used by the quota command.\n";
cout << " --pool=<pool> Specify the pool name. Also used to scan for leaked rados objects.\n";
cout << " --object=<object> object name\n";
cout << " --objects-file=<file> file containing a list of object names to process\n";
cout << " --object-version=<version> object version\n";
cout << " --date=<date> date in the format yyyy-mm-dd\n";
cout << " --start-date=<date> start date in the format yyyy-mm-dd\n";
cout << " --end-date=<date> end date in the format yyyy-mm-dd\n";
cout << " --bucket-id=<bucket-id> bucket id\n";
cout << " --bucket-new-name=<bucket>\n";
cout << " for bucket link: optional new name\n";
cout << " --shard-id=<shard-id> optional for: \n";
cout << " mdlog list\n";
cout << " data sync status\n";
cout << " required for: \n";
cout << " mdlog trim\n";
cout << " --gen=<gen-id> optional for: \n";
cout << " bilog list\n";
cout << " bilog trim\n";
cout << " bilog status\n";
cout << " --max-entries=<entries> max entries for listing operations\n";
cout << " --metadata-key=<key> key to retrieve metadata from with metadata get\n";
cout << " --remote=<remote> zone or zonegroup id of remote gateway\n";
cout << " --period=<id> period id\n";
cout << " --url=<url> url for pushing/pulling period/realm\n";
cout << " --epoch=<number> period epoch\n";
cout << " --commit commit the period during 'period update'\n";
cout << " --staging get staging period info\n";
cout << " --master set as master\n";
cout << " --master-zone=<id> master zone id\n";
cout << " --rgw-realm=<name> realm name\n";
cout << " --realm-id=<id> realm id\n";
cout << " --realm-new-name=<name> realm new name\n";
cout << " --rgw-zonegroup=<name> zonegroup name\n";
cout << " --zonegroup-id=<id> zonegroup id\n";
cout << " --zonegroup-new-name=<name>\n";
cout << " zonegroup new name\n";
cout << " --rgw-zone=<name> name of zone in which radosgw is running\n";
cout << " --zone-id=<id> zone id\n";
cout << " --zone-new-name=<name> zone new name\n";
cout << " --source-zone specify the source zone (for data sync)\n";
cout << " --default set entity (realm, zonegroup, zone) as default\n";
cout << " --read-only set zone as read-only (when adding to zonegroup)\n";
cout << " --redirect-zone specify zone id to redirect when response is 404 (not found)\n";
cout << " --placement-id placement id for zonegroup placement commands\n";
cout << " --storage-class storage class for zonegroup placement commands\n";
cout << " --tags=<list> list of tags for zonegroup placement add and modify commands\n";
cout << " --tags-add=<list> list of tags to add for zonegroup placement modify command\n";
cout << " --tags-rm=<list> list of tags to remove for zonegroup placement modify command\n";
cout << " --endpoints=<list> zone endpoints\n";
cout << " --index-pool=<pool> placement target index pool\n";
cout << " --data-pool=<pool> placement target data pool\n";
cout << " --data-extra-pool=<pool> placement target data extra (non-ec) pool\n";
cout << " --placement-index-type=<type>\n";
cout << " placement target index type (normal, indexless, or #id)\n";
cout << " --placement-inline-data=<true>\n";
cout << " set whether the placement target is configured to store a data\n";
cout << " chunk inline in head objects\n";
cout << " --compression=<type> placement target compression type (plugin name or empty/none)\n";
cout << " --tier-type=<type> zone tier type\n";
cout << " --tier-config=<k>=<v>[,...]\n";
cout << " set zone tier config keys, values\n";
cout << " --tier-config-rm=<k>[,...]\n";
cout << " unset zone tier config keys\n";
cout << " --sync-from-all[=false] set/reset whether zone syncs from all zonegroup peers\n";
cout << " --sync-from=[zone-name][,...]\n";
cout << " set list of zones to sync from\n";
cout << " --sync-from-rm=[zone-name][,...]\n";
cout << " remove zones from list of zones to sync from\n";
cout << " --bucket-index-max-shards override a zone/zonegroup's default bucket index shard count\n";
cout << " --fix besides checking bucket index, will also fix it\n";
cout << " --check-objects bucket check: rebuilds bucket index according to\n";
cout << " actual objects state\n";
cout << " --format=<format> specify output format for certain operations: xml,\n";
cout << " json\n";
cout << " --purge-data when specified, user removal will also purge all the\n";
cout << " user data\n";
cout << " --purge-keys when specified, subuser removal will also purge all the\n";
cout << " subuser keys\n";
cout << " --purge-objects remove a bucket's objects before deleting it\n";
cout << " (NOTE: required to delete a non-empty bucket)\n";
cout << " --sync-stats option to 'user stats', update user stats with current\n";
cout << " stats reported by user's buckets indexes\n";
cout << " --reset-stats option to 'user stats', reset stats in accordance with user buckets\n";
cout << " --show-config show configuration\n";
cout << " --show-log-entries=<flag> enable/disable dump of log entries on log show\n";
cout << " --show-log-sum=<flag> enable/disable dump of log summation on log show\n";
cout << " --skip-zero-entries log show only dumps entries that don't have zero value\n";
cout << " in one of the numeric field\n";
cout << " --infile=<file> file to read in when setting data\n";
cout << " --categories=<list> comma separated list of categories, used in usage show\n";
cout << " --caps=<caps> list of caps (e.g., \"usage=read, write; user=read\")\n";
cout << " --op-mask=<op-mask> permission of user's operations (e.g., \"read, write, delete, *\")\n";
cout << " --yes-i-really-mean-it required for certain operations\n";
cout << " --warnings-only when specified with bucket limit check, list\n";
cout << " only buckets nearing or over the current max\n";
cout << " objects per shard value\n";
cout << " --bypass-gc when specified with bucket deletion, triggers\n";
cout << " object deletions by not involving GC\n";
cout << " --inconsistent-index when specified with bucket deletion and bypass-gc set to true,\n";
cout << " ignores bucket index consistency\n";
cout << " --min-rewrite-size min object size for bucket rewrite (default 4M)\n";
cout << " --max-rewrite-size max object size for bucket rewrite (default ULLONG_MAX)\n";
cout << " --min-rewrite-stripe-size min stripe size for object rewrite (default 0)\n";
cout << " --trim-delay-ms time interval in msec to limit the frequency of sync error log entries trimming operations,\n";
cout << " the trimming process will sleep the specified msec for every 1000 entries trimmed\n";
cout << " --max-concurrent-ios maximum concurrent ios for bucket operations (default: 32)\n";
cout << " --enable-feature enable a zone/zonegroup feature\n";
cout << " --disable-feature disable a zone/zonegroup feature\n";
cout << "\n";
cout << "<date> := \"YYYY-MM-DD[ hh:mm:ss]\"\n";
cout << "\nQuota options:\n";
cout << " --max-objects specify max objects (negative value to disable)\n";
cout << " --max-size specify max size (in B/K/M/G/T, negative value to disable)\n";
cout << " --quota-scope scope of quota (bucket, user)\n";
cout << "\nRate limiting options:\n";
cout << " --max-read-ops specify max requests per minute for READ ops per RGW (GET and HEAD request methods), 0 means unlimited\n";
cout << " --max-read-bytes specify max bytes per minute for READ ops per RGW (GET and HEAD request methods), 0 means unlimited\n";
cout << " --max-write-ops specify max requests per minute for WRITE ops per RGW (Not GET or HEAD request methods), 0 means unlimited\n";
cout << " --max-write-bytes specify max bytes per minute for WRITE ops per RGW (Not GET or HEAD request methods), 0 means unlimited\n";
cout << " --ratelimit-scope scope of rate limiting: bucket, user, anonymous\n";
cout << " anonymous can be configured only with global rate limit\n";
cout << "\nOrphans search options:\n";
cout << " --num-shards num of shards to use for keeping the temporary scan info\n";
cout << " --orphan-stale-secs num of seconds to wait before declaring an object to be an orphan (default: 86400)\n";
cout << " --job-id set the job id (for orphans find)\n";
cout << " --detail detailed mode, log and stat head objects as well\n";
cout << "\nOrphans list-jobs options:\n";
cout << " --extra-info provide extra info in job list\n";
cout << "\nRole options:\n";
cout << " --role-name name of the role to create\n";
cout << " --path path to the role\n";
cout << " --assume-role-policy-doc the trust relationship policy document that grants an entity permission to assume the role\n";
cout << " --policy-name name of the policy document\n";
cout << " --policy-doc permission policy document\n";
cout << " --path-prefix path prefix for filtering roles\n";
cout << "\nMFA options:\n";
cout << " --totp-serial a string that represents the ID of a TOTP token\n";
cout << " --totp-seed the secret seed that is used to calculate the TOTP\n";
cout << " --totp-seconds the time resolution that is being used for TOTP generation\n";
cout << " --totp-window the number of TOTP tokens that are checked before and after the current token when validating token\n";
cout << " --totp-pin the valid value of a TOTP token at a certain time\n";
cout << "\nBucket notifications options:\n";
cout << " --topic bucket notifications topic name\n";
cout << " --notification-id bucket notifications id\n";
cout << "\nScript options:\n";
cout << " --context context in which the script runs. one of: "+LUA_CONTEXT_LIST+"\n";
cout << " --package name of the lua package that should be added/removed to/from the allowlist\n";
cout << " --allow-compilation package is allowed to compile C code as part of its installation\n";
cout << "\nradoslist options:\n";
cout << " --rgw-obj-fs the field separator that will separate the rados\n";
cout << " object name from the rgw object name;\n";
cout << " additionally rados objects for incomplete\n";
cout << " multipart uploads will not be output\n";
cout << "\n";
generic_client_usage();
}
class SimpleCmd {
public:
struct Def {
string cmd;
std::any opt;
};
using Aliases = std::vector<std::set<string> >;
using Commands = std::vector<Def>;
private:
struct Node {
map<string, Node> next;
set<string> expected; /* separate un-normalized list */
std::any opt;
};
Node cmd_root;
map<string, string> alias_map;
string normalize_alias(const string& s) const {
auto iter = alias_map.find(s);
if (iter == alias_map.end()) {
return s;
}
return iter->second;
}
void init_alias_map(Aliases& aliases) {
for (auto& alias_set : aliases) {
std::optional<string> first;
for (auto& alias : alias_set) {
if (!first) {
first = alias;
} else {
alias_map[alias] = *first;
}
}
}
}
bool gen_next_expected(Node *node, vector<string> *expected, bool ret) {
for (auto& next_cmd : node->expected) {
expected->push_back(next_cmd);
}
return ret;
}
Node root;
public:
SimpleCmd() {}
SimpleCmd(std::optional<Commands> cmds,
std::optional<Aliases> aliases) {
if (aliases) {
add_aliases(*aliases);
}
if (cmds) {
add_commands(*cmds);
}
}
void add_aliases(Aliases& aliases) {
init_alias_map(aliases);
}
void add_commands(std::vector<Def>& cmds) {
for (auto& cmd : cmds) {
vector<string> words;
get_str_vec(cmd.cmd, " ", words);
auto node = &cmd_root;
for (auto& word : words) {
auto norm = normalize_alias(word);
auto parent = node;
node->expected.insert(word);
node = &node->next[norm];
if (norm == "[*]") { /* optional param at the end */
parent->next["*"] = *node; /* can be also looked up by '*' */
parent->opt = cmd.opt;
}
}
node->opt = cmd.opt;
}
}
template <class Container>
bool find_command(Container& args,
std::any *opt_cmd,
vector<string> *extra_args,
string *error,
vector<string> *expected) {
auto node = &cmd_root;
std::optional<std::any> found_opt;
for (auto& arg : args) {
string norm = normalize_alias(arg);
auto iter = node->next.find(norm);
if (iter == node->next.end()) {
iter = node->next.find("*");
if (iter == node->next.end()) {
*error = string("ERROR: Unrecognized argument: '") + arg + "'";
return gen_next_expected(node, expected, false);
}
extra_args->push_back(arg);
if (!found_opt) {
found_opt = node->opt;
}
}
node = &(iter->second);
}
*opt_cmd = found_opt.value_or(node->opt);
if (!opt_cmd->has_value()) {
*error ="ERROR: Unknown command";
return gen_next_expected(node, expected, false);
}
return true;
}
};
namespace rgw_admin {
enum class OPT {
NO_CMD,
USER_CREATE,
USER_INFO,
USER_MODIFY,
USER_RENAME,
USER_RM,
USER_SUSPEND,
USER_ENABLE,
USER_CHECK,
USER_STATS,
USER_LIST,
SUBUSER_CREATE,
SUBUSER_MODIFY,
SUBUSER_RM,
KEY_CREATE,
KEY_RM,
BUCKETS_LIST,
BUCKET_LIMIT_CHECK,
BUCKET_LINK,
BUCKET_UNLINK,
BUCKET_LAYOUT,
BUCKET_STATS,
BUCKET_CHECK,
BUCKET_SYNC_CHECKPOINT,
BUCKET_SYNC_INFO,
BUCKET_SYNC_STATUS,
BUCKET_SYNC_MARKERS,
BUCKET_SYNC_INIT,
BUCKET_SYNC_RUN,
BUCKET_SYNC_DISABLE,
BUCKET_SYNC_ENABLE,
BUCKET_RM,
BUCKET_REWRITE,
BUCKET_RESHARD,
BUCKET_CHOWN,
BUCKET_RADOS_LIST,
BUCKET_SHARD_OBJECTS,
BUCKET_OBJECT_SHARD,
POLICY,
POOL_ADD,
POOL_RM,
POOLS_LIST,
LOG_LIST,
LOG_SHOW,
LOG_RM,
USAGE_SHOW,
USAGE_TRIM,
USAGE_CLEAR,
OBJECT_PUT,
OBJECT_RM,
OBJECT_UNLINK,
OBJECT_STAT,
OBJECT_REWRITE,
OBJECT_REINDEX,
OBJECTS_EXPIRE,
OBJECTS_EXPIRE_STALE_LIST,
OBJECTS_EXPIRE_STALE_RM,
BI_GET,
BI_PUT,
BI_LIST,
BI_PURGE,
OLH_GET,
OLH_READLOG,
QUOTA_SET,
QUOTA_ENABLE,
QUOTA_DISABLE,
GC_LIST,
GC_PROCESS,
LC_LIST,
LC_GET,
LC_PROCESS,
LC_RESHARD_FIX,
ORPHANS_FIND,
ORPHANS_FINISH,
ORPHANS_LIST_JOBS,
RATELIMIT_GET,
RATELIMIT_SET,
RATELIMIT_ENABLE,
RATELIMIT_DISABLE,
ZONEGROUP_ADD,
ZONEGROUP_CREATE,
ZONEGROUP_DEFAULT,
ZONEGROUP_DELETE,
ZONEGROUP_GET,
ZONEGROUP_MODIFY,
ZONEGROUP_SET,
ZONEGROUP_LIST,
ZONEGROUP_REMOVE,
ZONEGROUP_RENAME,
ZONEGROUP_PLACEMENT_ADD,
ZONEGROUP_PLACEMENT_MODIFY,
ZONEGROUP_PLACEMENT_RM,
ZONEGROUP_PLACEMENT_LIST,
ZONEGROUP_PLACEMENT_GET,
ZONEGROUP_PLACEMENT_DEFAULT,
ZONE_CREATE,
ZONE_DELETE,
ZONE_GET,
ZONE_MODIFY,
ZONE_SET,
ZONE_LIST,
ZONE_RENAME,
ZONE_DEFAULT,
ZONE_PLACEMENT_ADD,
ZONE_PLACEMENT_MODIFY,
ZONE_PLACEMENT_RM,
ZONE_PLACEMENT_LIST,
ZONE_PLACEMENT_GET,
CAPS_ADD,
CAPS_RM,
METADATA_GET,
METADATA_PUT,
METADATA_RM,
METADATA_LIST,
METADATA_SYNC_STATUS,
METADATA_SYNC_INIT,
METADATA_SYNC_RUN,
MDLOG_LIST,
MDLOG_AUTOTRIM,
MDLOG_TRIM,
MDLOG_FETCH,
MDLOG_STATUS,
SYNC_ERROR_LIST,
SYNC_ERROR_TRIM,
SYNC_GROUP_CREATE,
SYNC_GROUP_MODIFY,
SYNC_GROUP_GET,
SYNC_GROUP_REMOVE,
SYNC_GROUP_FLOW_CREATE,
SYNC_GROUP_FLOW_REMOVE,
SYNC_GROUP_PIPE_CREATE,
SYNC_GROUP_PIPE_MODIFY,
SYNC_GROUP_PIPE_REMOVE,
SYNC_POLICY_GET,
BILOG_LIST,
BILOG_TRIM,
BILOG_STATUS,
BILOG_AUTOTRIM,
DATA_SYNC_STATUS,
DATA_SYNC_INIT,
DATA_SYNC_RUN,
DATALOG_LIST,
DATALOG_STATUS,
DATALOG_AUTOTRIM,
DATALOG_TRIM,
DATALOG_TYPE,
DATALOG_PRUNE,
REALM_CREATE,
REALM_DELETE,
REALM_GET,
REALM_GET_DEFAULT,
REALM_LIST,
REALM_LIST_PERIODS,
REALM_RENAME,
REALM_SET,
REALM_DEFAULT,
REALM_PULL,
PERIOD_DELETE,
PERIOD_GET,
PERIOD_GET_CURRENT,
PERIOD_PULL,
PERIOD_PUSH,
PERIOD_LIST,
PERIOD_UPDATE,
PERIOD_COMMIT,
GLOBAL_QUOTA_GET,
GLOBAL_QUOTA_SET,
GLOBAL_QUOTA_ENABLE,
GLOBAL_QUOTA_DISABLE,
GLOBAL_RATELIMIT_GET,
GLOBAL_RATELIMIT_SET,
GLOBAL_RATELIMIT_ENABLE,
GLOBAL_RATELIMIT_DISABLE,
SYNC_INFO,
SYNC_STATUS,
ROLE_CREATE,
ROLE_DELETE,
ROLE_GET,
ROLE_TRUST_POLICY_MODIFY,
ROLE_LIST,
ROLE_POLICY_PUT,
ROLE_POLICY_LIST,
ROLE_POLICY_GET,
ROLE_POLICY_DELETE,
ROLE_UPDATE,
RESHARD_ADD,
RESHARD_LIST,
RESHARD_STATUS,
RESHARD_PROCESS,
RESHARD_CANCEL,
MFA_CREATE,
MFA_REMOVE,
MFA_GET,
MFA_LIST,
MFA_CHECK,
MFA_RESYNC,
RESHARD_STALE_INSTANCES_LIST,
RESHARD_STALE_INSTANCES_DELETE,
PUBSUB_TOPIC_LIST,
PUBSUB_TOPIC_GET,
PUBSUB_TOPIC_RM,
PUBSUB_NOTIFICATION_LIST,
PUBSUB_NOTIFICATION_GET,
PUBSUB_NOTIFICATION_RM,
PUBSUB_TOPIC_STATS,
SCRIPT_PUT,
SCRIPT_GET,
SCRIPT_RM,
SCRIPT_PACKAGE_ADD,
SCRIPT_PACKAGE_RM,
SCRIPT_PACKAGE_LIST
};
}
using namespace rgw_admin;
static SimpleCmd::Commands all_cmds = {
{ "user create", OPT::USER_CREATE },
{ "user info", OPT::USER_INFO },
{ "user modify", OPT::USER_MODIFY },
{ "user rename", OPT::USER_RENAME },
{ "user rm", OPT::USER_RM },
{ "user suspend", OPT::USER_SUSPEND },
{ "user enable", OPT::USER_ENABLE },
{ "user check", OPT::USER_CHECK },
{ "user stats", OPT::USER_STATS },
{ "user list", OPT::USER_LIST },
{ "subuser create", OPT::SUBUSER_CREATE },
{ "subuser modify", OPT::SUBUSER_MODIFY },
{ "subuser rm", OPT::SUBUSER_RM },
{ "key create", OPT::KEY_CREATE },
{ "key rm", OPT::KEY_RM },
{ "buckets list", OPT::BUCKETS_LIST },
{ "bucket list", OPT::BUCKETS_LIST },
{ "bucket limit check", OPT::BUCKET_LIMIT_CHECK },
{ "bucket link", OPT::BUCKET_LINK },
{ "bucket unlink", OPT::BUCKET_UNLINK },
{ "bucket layout", OPT::BUCKET_LAYOUT },
{ "bucket stats", OPT::BUCKET_STATS },
{ "bucket check", OPT::BUCKET_CHECK },
{ "bucket sync checkpoint", OPT::BUCKET_SYNC_CHECKPOINT },
{ "bucket sync info", OPT::BUCKET_SYNC_INFO },
{ "bucket sync status", OPT::BUCKET_SYNC_STATUS },
{ "bucket sync markers", OPT::BUCKET_SYNC_MARKERS },
{ "bucket sync init", OPT::BUCKET_SYNC_INIT },
{ "bucket sync run", OPT::BUCKET_SYNC_RUN },
{ "bucket sync disable", OPT::BUCKET_SYNC_DISABLE },
{ "bucket sync enable", OPT::BUCKET_SYNC_ENABLE },
{ "bucket rm", OPT::BUCKET_RM },
{ "bucket rewrite", OPT::BUCKET_REWRITE },
{ "bucket reshard", OPT::BUCKET_RESHARD },
{ "bucket chown", OPT::BUCKET_CHOWN },
{ "bucket radoslist", OPT::BUCKET_RADOS_LIST },
{ "bucket rados list", OPT::BUCKET_RADOS_LIST },
{ "bucket shard objects", OPT::BUCKET_SHARD_OBJECTS },
{ "bucket shard object", OPT::BUCKET_SHARD_OBJECTS },
{ "bucket object shard", OPT::BUCKET_OBJECT_SHARD },
{ "policy", OPT::POLICY },
{ "pool add", OPT::POOL_ADD },
{ "pool rm", OPT::POOL_RM },
{ "pool list", OPT::POOLS_LIST },
{ "pools list", OPT::POOLS_LIST },
{ "log list", OPT::LOG_LIST },
{ "log show", OPT::LOG_SHOW },
{ "log rm", OPT::LOG_RM },
{ "usage show", OPT::USAGE_SHOW },
{ "usage trim", OPT::USAGE_TRIM },
{ "usage clear", OPT::USAGE_CLEAR },
{ "object put", OPT::OBJECT_PUT },
{ "object rm", OPT::OBJECT_RM },
{ "object unlink", OPT::OBJECT_UNLINK },
{ "object stat", OPT::OBJECT_STAT },
{ "object rewrite", OPT::OBJECT_REWRITE },
{ "object reindex", OPT::OBJECT_REINDEX },
{ "objects expire", OPT::OBJECTS_EXPIRE },
{ "objects expire-stale list", OPT::OBJECTS_EXPIRE_STALE_LIST },
{ "objects expire-stale rm", OPT::OBJECTS_EXPIRE_STALE_RM },
{ "bi get", OPT::BI_GET },
{ "bi put", OPT::BI_PUT },
{ "bi list", OPT::BI_LIST },
{ "bi purge", OPT::BI_PURGE },
{ "olh get", OPT::OLH_GET },
{ "olh readlog", OPT::OLH_READLOG },
{ "quota set", OPT::QUOTA_SET },
{ "quota enable", OPT::QUOTA_ENABLE },
{ "quota disable", OPT::QUOTA_DISABLE },
{ "ratelimit get", OPT::RATELIMIT_GET },
{ "ratelimit set", OPT::RATELIMIT_SET },
{ "ratelimit enable", OPT::RATELIMIT_ENABLE },
{ "ratelimit disable", OPT::RATELIMIT_DISABLE },
{ "gc list", OPT::GC_LIST },
{ "gc process", OPT::GC_PROCESS },
{ "lc list", OPT::LC_LIST },
{ "lc get", OPT::LC_GET },
{ "lc process", OPT::LC_PROCESS },
{ "lc reshard fix", OPT::LC_RESHARD_FIX },
{ "orphans find", OPT::ORPHANS_FIND },
{ "orphans finish", OPT::ORPHANS_FINISH },
{ "orphans list jobs", OPT::ORPHANS_LIST_JOBS },
{ "orphans list-jobs", OPT::ORPHANS_LIST_JOBS },
{ "zonegroup add", OPT::ZONEGROUP_ADD },
{ "zonegroup create", OPT::ZONEGROUP_CREATE },
{ "zonegroup default", OPT::ZONEGROUP_DEFAULT },
{ "zonegroup delete", OPT::ZONEGROUP_DELETE },
{ "zonegroup get", OPT::ZONEGROUP_GET },
{ "zonegroup modify", OPT::ZONEGROUP_MODIFY },
{ "zonegroup set", OPT::ZONEGROUP_SET },
{ "zonegroup list", OPT::ZONEGROUP_LIST },
{ "zonegroups list", OPT::ZONEGROUP_LIST },
{ "zonegroup remove", OPT::ZONEGROUP_REMOVE },
{ "zonegroup remove zone", OPT::ZONEGROUP_REMOVE },
{ "zonegroup rename", OPT::ZONEGROUP_RENAME },
{ "zonegroup placement add", OPT::ZONEGROUP_PLACEMENT_ADD },
{ "zonegroup placement modify", OPT::ZONEGROUP_PLACEMENT_MODIFY },
{ "zonegroup placement rm", OPT::ZONEGROUP_PLACEMENT_RM },
{ "zonegroup placement list", OPT::ZONEGROUP_PLACEMENT_LIST },
{ "zonegroup placement get", OPT::ZONEGROUP_PLACEMENT_GET },
{ "zonegroup placement default", OPT::ZONEGROUP_PLACEMENT_DEFAULT },
{ "zone create", OPT::ZONE_CREATE },
{ "zone delete", OPT::ZONE_DELETE },
{ "zone get", OPT::ZONE_GET },
{ "zone modify", OPT::ZONE_MODIFY },
{ "zone set", OPT::ZONE_SET },
{ "zone list", OPT::ZONE_LIST },
{ "zones list", OPT::ZONE_LIST },
{ "zone rename", OPT::ZONE_RENAME },
{ "zone default", OPT::ZONE_DEFAULT },
{ "zone placement add", OPT::ZONE_PLACEMENT_ADD },
{ "zone placement modify", OPT::ZONE_PLACEMENT_MODIFY },
{ "zone placement rm", OPT::ZONE_PLACEMENT_RM },
{ "zone placement list", OPT::ZONE_PLACEMENT_LIST },
{ "zone placement get", OPT::ZONE_PLACEMENT_GET },
{ "caps add", OPT::CAPS_ADD },
{ "caps rm", OPT::CAPS_RM },
{ "metadata get [*]", OPT::METADATA_GET },
{ "metadata put [*]", OPT::METADATA_PUT },
{ "metadata rm [*]", OPT::METADATA_RM },
{ "metadata list [*]", OPT::METADATA_LIST },
{ "metadata sync status", OPT::METADATA_SYNC_STATUS },
{ "metadata sync init", OPT::METADATA_SYNC_INIT },
{ "metadata sync run", OPT::METADATA_SYNC_RUN },
{ "mdlog list", OPT::MDLOG_LIST },
{ "mdlog autotrim", OPT::MDLOG_AUTOTRIM },
{ "mdlog trim", OPT::MDLOG_TRIM },
{ "mdlog fetch", OPT::MDLOG_FETCH },
{ "mdlog status", OPT::MDLOG_STATUS },
{ "sync error list", OPT::SYNC_ERROR_LIST },
{ "sync error trim", OPT::SYNC_ERROR_TRIM },
{ "sync policy get", OPT::SYNC_POLICY_GET },
{ "sync group create", OPT::SYNC_GROUP_CREATE },
{ "sync group modify", OPT::SYNC_GROUP_MODIFY },
{ "sync group get", OPT::SYNC_GROUP_GET },
{ "sync group remove", OPT::SYNC_GROUP_REMOVE },
{ "sync group flow create", OPT::SYNC_GROUP_FLOW_CREATE },
{ "sync group flow remove", OPT::SYNC_GROUP_FLOW_REMOVE },
{ "sync group pipe create", OPT::SYNC_GROUP_PIPE_CREATE },
{ "sync group pipe modify", OPT::SYNC_GROUP_PIPE_MODIFY },
{ "sync group pipe remove", OPT::SYNC_GROUP_PIPE_REMOVE },
{ "bilog list", OPT::BILOG_LIST },
{ "bilog trim", OPT::BILOG_TRIM },
{ "bilog status", OPT::BILOG_STATUS },
{ "bilog autotrim", OPT::BILOG_AUTOTRIM },
{ "data sync status", OPT::DATA_SYNC_STATUS },
{ "data sync init", OPT::DATA_SYNC_INIT },
{ "data sync run", OPT::DATA_SYNC_RUN },
{ "datalog list", OPT::DATALOG_LIST },
{ "datalog status", OPT::DATALOG_STATUS },
{ "datalog autotrim", OPT::DATALOG_AUTOTRIM },
{ "datalog trim", OPT::DATALOG_TRIM },
{ "datalog type", OPT::DATALOG_TYPE },
{ "datalog prune", OPT::DATALOG_PRUNE },
{ "realm create", OPT::REALM_CREATE },
{ "realm rm", OPT::REALM_DELETE },
{ "realm get", OPT::REALM_GET },
{ "realm get default", OPT::REALM_GET_DEFAULT },
{ "realm get-default", OPT::REALM_GET_DEFAULT },
{ "realm list", OPT::REALM_LIST },
{ "realm list periods", OPT::REALM_LIST_PERIODS },
{ "realm list-periods", OPT::REALM_LIST_PERIODS },
{ "realm rename", OPT::REALM_RENAME },
{ "realm set", OPT::REALM_SET },
{ "realm default", OPT::REALM_DEFAULT },
{ "realm pull", OPT::REALM_PULL },
{ "period delete", OPT::PERIOD_DELETE },
{ "period get", OPT::PERIOD_GET },
{ "period get-current", OPT::PERIOD_GET_CURRENT },
{ "period get current", OPT::PERIOD_GET_CURRENT },
{ "period pull", OPT::PERIOD_PULL },
{ "period push", OPT::PERIOD_PUSH },
{ "period list", OPT::PERIOD_LIST },
{ "period update", OPT::PERIOD_UPDATE },
{ "period commit", OPT::PERIOD_COMMIT },
{ "global quota get", OPT::GLOBAL_QUOTA_GET },
{ "global quota set", OPT::GLOBAL_QUOTA_SET },
{ "global quota enable", OPT::GLOBAL_QUOTA_ENABLE },
{ "global quota disable", OPT::GLOBAL_QUOTA_DISABLE },
{ "global ratelimit get", OPT::GLOBAL_RATELIMIT_GET },
{ "global ratelimit set", OPT::GLOBAL_RATELIMIT_SET },
{ "global ratelimit enable", OPT::GLOBAL_RATELIMIT_ENABLE },
{ "global ratelimit disable", OPT::GLOBAL_RATELIMIT_DISABLE },
{ "sync info", OPT::SYNC_INFO },
{ "sync status", OPT::SYNC_STATUS },
{ "role create", OPT::ROLE_CREATE },
{ "role delete", OPT::ROLE_DELETE },
{ "role get", OPT::ROLE_GET },
{ "role-trust-policy modify", OPT::ROLE_TRUST_POLICY_MODIFY },
{ "role list", OPT::ROLE_LIST },
{ "role policy put", OPT::ROLE_POLICY_PUT },
{ "role-policy put", OPT::ROLE_POLICY_PUT },
{ "role policy list", OPT::ROLE_POLICY_LIST },
{ "role-policy list", OPT::ROLE_POLICY_LIST },
{ "role policy get", OPT::ROLE_POLICY_GET },
{ "role-policy get", OPT::ROLE_POLICY_GET },
{ "role policy delete", OPT::ROLE_POLICY_DELETE },
{ "role-policy delete", OPT::ROLE_POLICY_DELETE },
{ "role update", OPT::ROLE_UPDATE },
{ "reshard bucket", OPT::BUCKET_RESHARD },
{ "reshard add", OPT::RESHARD_ADD },
{ "reshard list", OPT::RESHARD_LIST },
{ "reshard status", OPT::RESHARD_STATUS },
{ "reshard process", OPT::RESHARD_PROCESS },
{ "reshard cancel", OPT::RESHARD_CANCEL },
{ "mfa create", OPT::MFA_CREATE },
{ "mfa remove", OPT::MFA_REMOVE },
{ "mfa get", OPT::MFA_GET },
{ "mfa list", OPT::MFA_LIST },
{ "mfa check", OPT::MFA_CHECK },
{ "mfa resync", OPT::MFA_RESYNC },
{ "reshard stale-instances list", OPT::RESHARD_STALE_INSTANCES_LIST },
{ "reshard stale list", OPT::RESHARD_STALE_INSTANCES_LIST },
{ "reshard stale-instances delete", OPT::RESHARD_STALE_INSTANCES_DELETE },
{ "reshard stale delete", OPT::RESHARD_STALE_INSTANCES_DELETE },
{ "topic list", OPT::PUBSUB_TOPIC_LIST },
{ "topic get", OPT::PUBSUB_TOPIC_GET },
{ "topic rm", OPT::PUBSUB_TOPIC_RM },
{ "notification list", OPT::PUBSUB_NOTIFICATION_LIST },
{ "notification get", OPT::PUBSUB_NOTIFICATION_GET },
{ "notification rm", OPT::PUBSUB_NOTIFICATION_RM },
{ "topic stats", OPT::PUBSUB_TOPIC_STATS },
{ "script put", OPT::SCRIPT_PUT },
{ "script get", OPT::SCRIPT_GET },
{ "script rm", OPT::SCRIPT_RM },
{ "script-package add", OPT::SCRIPT_PACKAGE_ADD },
{ "script-package rm", OPT::SCRIPT_PACKAGE_RM },
{ "script-package list", OPT::SCRIPT_PACKAGE_LIST },
};
static SimpleCmd::Aliases cmd_aliases = {
{ "delete", "del" },
{ "remove", "rm" },
{ "rename", "mv" },
};
BIIndexType get_bi_index_type(const string& type_str) {
if (type_str == "plain")
return BIIndexType::Plain;
if (type_str == "instance")
return BIIndexType::Instance;
if (type_str == "olh")
return BIIndexType::OLH;
return BIIndexType::Invalid;
}
log_type get_log_type(const string& type_str) {
if (strcasecmp(type_str.c_str(), "fifo") == 0)
return log_type::fifo;
if (strcasecmp(type_str.c_str(), "omap") == 0)
return log_type::omap;
return static_cast<log_type>(0xff);
}
static void show_user_info(RGWUserInfo& info, Formatter *formatter)
{
encode_json("user_info", info, formatter);
formatter->flush(cout);
cout << std::endl;
}
static void show_perm_policy(string perm_policy, Formatter* formatter)
{
formatter->open_object_section("role");
formatter->dump_string("Permission policy", perm_policy);
formatter->close_section();
formatter->flush(cout);
}
static void show_policy_names(std::vector<string> policy_names, Formatter* formatter)
{
formatter->open_array_section("PolicyNames");
for (const auto& it : policy_names) {
formatter->dump_string("policyname", it);
}
formatter->close_section();
formatter->flush(cout);
}
static void show_role_info(rgw::sal::RGWRole* role, Formatter* formatter)
{
formatter->open_object_section("role");
role->dump(formatter);
formatter->close_section();
formatter->flush(cout);
}
static void show_roles_info(vector<std::unique_ptr<rgw::sal::RGWRole>>& roles, Formatter* formatter)
{
formatter->open_array_section("Roles");
for (const auto& it : roles) {
formatter->open_object_section("role");
it->dump(formatter);
formatter->close_section();
}
formatter->close_section();
formatter->flush(cout);
}
static void show_reshard_status(
const list<cls_rgw_bucket_instance_entry>& status, Formatter *formatter)
{
formatter->open_array_section("status");
for (const auto& entry : status) {
formatter->open_object_section("entry");
formatter->dump_string("reshard_status", to_string(entry.reshard_status));
formatter->close_section();
}
formatter->close_section();
formatter->flush(cout);
}
class StoreDestructor {
rgw::sal::Driver* driver;
public:
explicit StoreDestructor(rgw::sal::Driver* _s) : driver(_s) {}
~StoreDestructor() {
DriverManager::close_storage(driver);
rgw_http_client_cleanup();
}
};
static int init_bucket(rgw::sal::User* user, const rgw_bucket& b,
std::unique_ptr<rgw::sal::Bucket>* bucket)
{
return driver->get_bucket(dpp(), user, b, bucket, null_yield);
}
static int init_bucket(rgw::sal::User* user,
const string& tenant_name,
const string& bucket_name,
const string& bucket_id,
std::unique_ptr<rgw::sal::Bucket>* bucket)
{
rgw_bucket b{tenant_name, bucket_name, bucket_id};
return init_bucket(user, b, bucket);
}
static int read_input(const string& infile, bufferlist& bl)
{
int fd = 0;
if (infile.size()) {
fd = open(infile.c_str(), O_RDONLY);
if (fd < 0) {
int err = -errno;
cerr << "error reading input file " << infile << std::endl;
return err;
}
}
#define READ_CHUNK 8196
int r;
int err;
do {
char buf[READ_CHUNK];
r = safe_read(fd, buf, READ_CHUNK);
if (r < 0) {
err = -errno;
cerr << "error while reading input" << std::endl;
goto out;
}
bl.append(buf, r);
} while (r > 0);
err = 0;
out:
if (infile.size()) {
close(fd);
}
return err;
}
template <class T>
static int read_decode_json(const string& infile, T& t)
{
bufferlist bl;
int ret = read_input(infile, bl);
if (ret < 0) {
cerr << "ERROR: failed to read input: " << cpp_strerror(-ret) << std::endl;
return ret;
}
JSONParser p;
if (!p.parse(bl.c_str(), bl.length())) {
cout << "failed to parse JSON" << std::endl;
return -EINVAL;
}
try {
decode_json_obj(t, &p);
} catch (const JSONDecoder::err& e) {
cout << "failed to decode JSON input: " << e.what() << std::endl;
return -EINVAL;
}
return 0;
}
template <class T, class K>
static int read_decode_json(const string& infile, T& t, K *k)
{
bufferlist bl;
int ret = read_input(infile, bl);
if (ret < 0) {
cerr << "ERROR: failed to read input: " << cpp_strerror(-ret) << std::endl;
return ret;
}
JSONParser p;
if (!p.parse(bl.c_str(), bl.length())) {
cout << "failed to parse JSON" << std::endl;
return -EINVAL;
}
try {
t.decode_json(&p, k);
} catch (const JSONDecoder::err& e) {
cout << "failed to decode JSON input: " << e.what() << std::endl;
return -EINVAL;
}
return 0;
}
template <class T>
static bool decode_dump(const char *field_name, bufferlist& bl, Formatter *f)
{
T t;
auto iter = bl.cbegin();
try {
decode(t, iter);
} catch (buffer::error& err) {
return false;
}
encode_json(field_name, t, f);
return true;
}
static bool dump_string(const char *field_name, bufferlist& bl, Formatter *f)
{
string val = bl.to_str();
f->dump_string(field_name, val.c_str() /* hide encoded null termination chars */);
return true;
}
bool set_ratelimit_info(RGWRateLimitInfo& ratelimit, OPT opt_cmd, int64_t max_read_ops, int64_t max_write_ops,
int64_t max_read_bytes, int64_t max_write_bytes,
bool have_max_read_ops, bool have_max_write_ops,
bool have_max_read_bytes, bool have_max_write_bytes)
{
bool ratelimit_configured = true;
switch (opt_cmd) {
case OPT::RATELIMIT_ENABLE:
case OPT::GLOBAL_RATELIMIT_ENABLE:
ratelimit.enabled = true;
break;
case OPT::RATELIMIT_SET:
case OPT::GLOBAL_RATELIMIT_SET:
ratelimit_configured = false;
if (have_max_read_ops) {
if (max_read_ops >= 0) {
ratelimit.max_read_ops = max_read_ops;
ratelimit_configured = true;
}
}
if (have_max_write_ops) {
if (max_write_ops >= 0) {
ratelimit.max_write_ops = max_write_ops;
ratelimit_configured = true;
}
}
if (have_max_read_bytes) {
if (max_read_bytes >= 0) {
ratelimit.max_read_bytes = max_read_bytes;
ratelimit_configured = true;
}
}
if (have_max_write_bytes) {
if (max_write_bytes >= 0) {
ratelimit.max_write_bytes = max_write_bytes;
ratelimit_configured = true;
}
}
break;
case OPT::RATELIMIT_DISABLE:
case OPT::GLOBAL_RATELIMIT_DISABLE:
ratelimit.enabled = false;
break;
default:
break;
}
return ratelimit_configured;
}
void set_quota_info(RGWQuotaInfo& quota, OPT opt_cmd, int64_t max_size, int64_t max_objects,
bool have_max_size, bool have_max_objects)
{
switch (opt_cmd) {
case OPT::QUOTA_ENABLE:
case OPT::GLOBAL_QUOTA_ENABLE:
quota.enabled = true;
// falling through on purpose
case OPT::QUOTA_SET:
case OPT::GLOBAL_QUOTA_SET:
if (have_max_objects) {
if (max_objects < 0) {
quota.max_objects = -1;
} else {
quota.max_objects = max_objects;
}
}
if (have_max_size) {
if (max_size < 0) {
quota.max_size = -1;
} else {
quota.max_size = rgw_rounded_kb(max_size) * 1024;
}
}
break;
case OPT::QUOTA_DISABLE:
case OPT::GLOBAL_QUOTA_DISABLE:
quota.enabled = false;
break;
default:
break;
}
}
int set_bucket_quota(rgw::sal::Driver* driver, OPT opt_cmd,
const string& tenant_name, const string& bucket_name,
int64_t max_size, int64_t max_objects,
bool have_max_size, bool have_max_objects)
{
std::unique_ptr<rgw::sal::Bucket> bucket;
int r = driver->get_bucket(dpp(), nullptr, tenant_name, bucket_name, &bucket, null_yield);
if (r < 0) {
cerr << "could not get bucket info for bucket=" << bucket_name << ": " << cpp_strerror(-r) << std::endl;
return -r;
}
set_quota_info(bucket->get_info().quota, opt_cmd, max_size, max_objects, have_max_size, have_max_objects);
r = bucket->put_info(dpp(), false, real_time(), null_yield);
if (r < 0) {
cerr << "ERROR: failed writing bucket instance info: " << cpp_strerror(-r) << std::endl;
return -r;
}
return 0;
}
int set_bucket_ratelimit(rgw::sal::Driver* driver, OPT opt_cmd,
const string& tenant_name, const string& bucket_name,
int64_t max_read_ops, int64_t max_write_ops,
int64_t max_read_bytes, int64_t max_write_bytes,
bool have_max_read_ops, bool have_max_write_ops,
bool have_max_read_bytes, bool have_max_write_bytes)
{
std::unique_ptr<rgw::sal::Bucket> bucket;
int r = driver->get_bucket(dpp(), nullptr, tenant_name, bucket_name, &bucket, null_yield);
if (r < 0) {
cerr << "could not get bucket info for bucket=" << bucket_name << ": " << cpp_strerror(-r) << std::endl;
return -r;
}
RGWRateLimitInfo ratelimit_info;
auto iter = bucket->get_attrs().find(RGW_ATTR_RATELIMIT);
if(iter != bucket->get_attrs().end()) {
try {
bufferlist& bl = iter->second;
auto biter = bl.cbegin();
decode(ratelimit_info, biter);
} catch (buffer::error& err) {
ldpp_dout(dpp(), 0) << "ERROR: failed to decode rate limit" << dendl;
return -EIO;
}
}
bool ratelimit_configured = set_ratelimit_info(ratelimit_info, opt_cmd, max_read_ops, max_write_ops,
max_read_bytes, max_write_bytes,
have_max_read_ops, have_max_write_ops,
have_max_read_bytes, have_max_write_bytes);
if (!ratelimit_configured) {
ldpp_dout(dpp(), 0) << "ERROR: no rate limit values have been specified" << dendl;
return -EINVAL;
}
bufferlist bl;
ratelimit_info.encode(bl);
rgw::sal::Attrs attr;
attr[RGW_ATTR_RATELIMIT] = bl;
r = bucket->merge_and_store_attrs(dpp(), attr, null_yield);
if (r < 0) {
cerr << "ERROR: failed writing bucket instance info: " << cpp_strerror(-r) << std::endl;
return -r;
}
return 0;
}
int set_user_ratelimit(OPT opt_cmd, std::unique_ptr<rgw::sal::User>& user,
int64_t max_read_ops, int64_t max_write_ops,
int64_t max_read_bytes, int64_t max_write_bytes,
bool have_max_read_ops, bool have_max_write_ops,
bool have_max_read_bytes, bool have_max_write_bytes)
{
RGWRateLimitInfo ratelimit_info;
user->load_user(dpp(), null_yield);
auto iter = user->get_attrs().find(RGW_ATTR_RATELIMIT);
if(iter != user->get_attrs().end()) {
try {
bufferlist& bl = iter->second;
auto biter = bl.cbegin();
decode(ratelimit_info, biter);
} catch (buffer::error& err) {
ldpp_dout(dpp(), 0) << "ERROR: failed to decode rate limit" << dendl;
return -EIO;
}
}
bool ratelimit_configured = set_ratelimit_info(ratelimit_info, opt_cmd, max_read_ops, max_write_ops,
max_read_bytes, max_write_bytes,
have_max_read_ops, have_max_write_ops,
have_max_read_bytes, have_max_write_bytes);
if (!ratelimit_configured) {
ldpp_dout(dpp(), 0) << "ERROR: no rate limit values have been specified" << dendl;
return -EINVAL;
}
bufferlist bl;
ratelimit_info.encode(bl);
rgw::sal::Attrs attr;
attr[RGW_ATTR_RATELIMIT] = bl;
int r = user->merge_and_store_attrs(dpp(), attr, null_yield);
if (r < 0) {
cerr << "ERROR: failed writing user instance info: " << cpp_strerror(-r) << std::endl;
return -r;
}
return 0;
}
int show_user_ratelimit(std::unique_ptr<rgw::sal::User>& user, Formatter *formatter)
{
RGWRateLimitInfo ratelimit_info;
user->load_user(dpp(), null_yield);
auto iter = user->get_attrs().find(RGW_ATTR_RATELIMIT);
if(iter != user->get_attrs().end()) {
try {
bufferlist& bl = iter->second;
auto biter = bl.cbegin();
decode(ratelimit_info, biter);
} catch (buffer::error& err) {
ldpp_dout(dpp(), 0) << "ERROR: failed to decode rate limit" << dendl;
return -EIO;
}
}
formatter->open_object_section("user_ratelimit");
encode_json("user_ratelimit", ratelimit_info, formatter);
formatter->close_section();
formatter->flush(cout);
cout << std::endl;
return 0;
}
int show_bucket_ratelimit(rgw::sal::Driver* driver, const string& tenant_name,
const string& bucket_name, Formatter *formatter)
{
std::unique_ptr<rgw::sal::Bucket> bucket;
int r = driver->get_bucket(dpp(), nullptr, tenant_name, bucket_name, &bucket, null_yield);
if (r < 0) {
cerr << "could not get bucket info for bucket=" << bucket_name << ": " << cpp_strerror(-r) << std::endl;
return -r;
}
RGWRateLimitInfo ratelimit_info;
auto iter = bucket->get_attrs().find(RGW_ATTR_RATELIMIT);
if (iter != bucket->get_attrs().end()) {
try {
bufferlist& bl = iter->second;
auto biter = bl.cbegin();
decode(ratelimit_info, biter);
} catch (buffer::error& err) {
ldpp_dout(dpp(), 0) << "ERROR: failed to decode rate limit" << dendl;
return -EIO;
}
}
formatter->open_object_section("bucket_ratelimit");
encode_json("bucket_ratelimit", ratelimit_info, formatter);
formatter->close_section();
formatter->flush(cout);
cout << std::endl;
return 0;
}
int set_user_bucket_quota(OPT opt_cmd, RGWUser& user, RGWUserAdminOpState& op_state, int64_t max_size, int64_t max_objects,
bool have_max_size, bool have_max_objects)
{
RGWUserInfo& user_info = op_state.get_user_info();
set_quota_info(user_info.quota.bucket_quota, opt_cmd, max_size, max_objects, have_max_size, have_max_objects);
op_state.set_bucket_quota(user_info.quota.bucket_quota);
string err;
int r = user.modify(dpp(), op_state, null_yield, &err);
if (r < 0) {
cerr << "ERROR: failed updating user info: " << cpp_strerror(-r) << ": " << err << std::endl;
return -r;
}
return 0;
}
int set_user_quota(OPT opt_cmd, RGWUser& user, RGWUserAdminOpState& op_state, int64_t max_size, int64_t max_objects,
bool have_max_size, bool have_max_objects)
{
RGWUserInfo& user_info = op_state.get_user_info();
set_quota_info(user_info.quota.user_quota, opt_cmd, max_size, max_objects, have_max_size, have_max_objects);
op_state.set_user_quota(user_info.quota.user_quota);
string err;
int r = user.modify(dpp(), op_state, null_yield, &err);
if (r < 0) {
cerr << "ERROR: failed updating user info: " << cpp_strerror(-r) << ": " << err << std::endl;
return -r;
}
return 0;
}
int check_min_obj_stripe_size(rgw::sal::Driver* driver, rgw::sal::Object* obj, uint64_t min_stripe_size, bool *need_rewrite)
{
int ret = obj->get_obj_attrs(null_yield, dpp());
if (ret < 0) {
ldpp_dout(dpp(), -1) << "ERROR: failed to stat object, returned error: " << cpp_strerror(-ret) << dendl;
return ret;
}
map<string, bufferlist>::iterator iter;
iter = obj->get_attrs().find(RGW_ATTR_MANIFEST);
if (iter == obj->get_attrs().end()) {
*need_rewrite = (obj->get_obj_size() >= min_stripe_size);
return 0;
}
RGWObjManifest manifest;
try {
bufferlist& bl = iter->second;
auto biter = bl.cbegin();
decode(manifest, biter);
} catch (buffer::error& err) {
ldpp_dout(dpp(), 0) << "ERROR: failed to decode manifest" << dendl;
return -EIO;
}
map<uint64_t, RGWObjManifestPart>& objs = manifest.get_explicit_objs();
map<uint64_t, RGWObjManifestPart>::iterator oiter;
for (oiter = objs.begin(); oiter != objs.end(); ++oiter) {
RGWObjManifestPart& part = oiter->second;
if (part.size >= min_stripe_size) {
*need_rewrite = true;
return 0;
}
}
*need_rewrite = false;
return 0;
}
int check_obj_locator_underscore(rgw::sal::Object* obj, bool fix, bool remove_bad, Formatter *f) {
f->open_object_section("object");
f->open_object_section("key");
f->dump_string("type", "head");
f->dump_string("name", obj->get_name());
f->dump_string("instance", obj->get_instance());
f->close_section();
string oid;
string locator;
get_obj_bucket_and_oid_loc(obj->get_obj(), oid, locator);
f->dump_string("oid", oid);
f->dump_string("locator", locator);
std::unique_ptr<rgw::sal::Object::ReadOp> read_op = obj->get_read_op();
int ret = read_op->prepare(null_yield, dpp());
bool needs_fixing = (ret == -ENOENT);
f->dump_bool("needs_fixing", needs_fixing);
string status = (needs_fixing ? "needs_fixing" : "ok");
if ((needs_fixing || remove_bad) && fix) {
ret = static_cast<rgw::sal::RadosStore*>(driver)->getRados()->fix_head_obj_locator(dpp(), obj->get_bucket()->get_info(), needs_fixing, remove_bad, obj->get_key(), null_yield);
if (ret < 0) {
cerr << "ERROR: fix_head_object_locator() returned ret=" << ret << std::endl;
goto done;
}
status = "fixed";
}
done:
f->dump_string("status", status);
f->close_section();
return 0;
}
int check_obj_tail_locator_underscore(RGWBucketInfo& bucket_info, rgw_obj_key& key, bool fix, Formatter *f) {
f->open_object_section("object");
f->open_object_section("key");
f->dump_string("type", "tail");
f->dump_string("name", key.name);
f->dump_string("instance", key.instance);
f->close_section();
bool needs_fixing;
string status;
int ret = static_cast<rgw::sal::RadosStore*>(driver)->getRados()->fix_tail_obj_locator(dpp(), bucket_info, key, fix, &needs_fixing, null_yield);
if (ret < 0) {
cerr << "ERROR: fix_tail_object_locator_underscore() returned ret=" << ret << std::endl;
status = "failed";
} else {
status = (needs_fixing && !fix ? "needs_fixing" : "ok");
}
f->dump_bool("needs_fixing", needs_fixing);
f->dump_string("status", status);
f->close_section();
return 0;
}
int do_check_object_locator(const string& tenant_name, const string& bucket_name,
bool fix, bool remove_bad, Formatter *f)
{
if (remove_bad && !fix) {
cerr << "ERROR: can't have remove_bad specified without fix" << std::endl;
return -EINVAL;
}
std::unique_ptr<rgw::sal::Bucket> bucket;
string bucket_id;
f->open_object_section("bucket");
f->dump_string("bucket", bucket_name);
int ret = init_bucket(nullptr, tenant_name, bucket_name, bucket_id, &bucket);
if (ret < 0) {
cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
return ret;
}
int count = 0;
int max_entries = 1000;
string prefix;
string delim;
string marker;
vector<rgw_bucket_dir_entry> result;
string ns;
rgw::sal::Bucket::ListParams params;
rgw::sal::Bucket::ListResults results;
params.prefix = prefix;
params.delim = delim;
params.marker = rgw_obj_key(marker);
params.ns = ns;
params.enforce_ns = true;
params.list_versions = true;
f->open_array_section("check_objects");
do {
ret = bucket->list(dpp(), params, max_entries - count, results, null_yield);
if (ret < 0) {
cerr << "ERROR: driver->list_objects(): " << cpp_strerror(-ret) << std::endl;
return -ret;
}
count += results.objs.size();
for (vector<rgw_bucket_dir_entry>::iterator iter = results.objs.begin(); iter != results.objs.end(); ++iter) {
std::unique_ptr<rgw::sal::Object> obj = bucket->get_object(iter->key);
if (obj->get_name()[0] == '_') {
ret = check_obj_locator_underscore(obj.get(), fix, remove_bad, f);
if (ret >= 0) {
ret = check_obj_tail_locator_underscore(bucket->get_info(), obj->get_key(), fix, f);
if (ret < 0) {
cerr << "ERROR: check_obj_tail_locator_underscore(): " << cpp_strerror(-ret) << std::endl;
return -ret;
}
}
}
}
f->flush(cout);
} while (results.is_truncated && count < max_entries);
f->close_section();
f->close_section();
f->flush(cout);
return 0;
}
/// search for a matching zone/zonegroup id and return a connection if found
static boost::optional<RGWRESTConn> get_remote_conn(rgw::sal::RadosStore* driver,
const RGWZoneGroup& zonegroup,
const std::string& remote)
{
boost::optional<RGWRESTConn> conn;
if (remote == zonegroup.get_id()) {
conn.emplace(driver->ctx(), driver, remote, zonegroup.endpoints, zonegroup.api_name);
} else {
for (const auto& z : zonegroup.zones) {
const auto& zone = z.second;
if (remote == zone.id) {
conn.emplace(driver->ctx(), driver, remote, zone.endpoints, zonegroup.api_name);
break;
}
}
}
return conn;
}
/// search each zonegroup for a connection
static boost::optional<RGWRESTConn> get_remote_conn(rgw::sal::RadosStore* driver,
const RGWPeriodMap& period_map,
const std::string& remote)
{
boost::optional<RGWRESTConn> conn;
for (const auto& zg : period_map.zonegroups) {
conn = get_remote_conn(driver, zg.second, remote);
if (conn) {
break;
}
}
return conn;
}
// we expect a very small response
static constexpr size_t MAX_REST_RESPONSE = 128 * 1024;
static int send_to_remote_gateway(RGWRESTConn* conn, req_info& info,
bufferlist& in_data, JSONParser& parser)
{
if (!conn) {
return -EINVAL;
}
ceph::bufferlist response;
rgw_user user;
int ret = conn->forward(dpp(), user, info, nullptr, MAX_REST_RESPONSE, &in_data, &response, null_yield);
int parse_ret = parser.parse(response.c_str(), response.length());
if (parse_ret < 0) {
cerr << "failed to parse response" << std::endl;
return parse_ret;
}
return ret;
}
static int send_to_url(const string& url,
std::optional<string> opt_region,
const string& access,
const string& secret, req_info& info,
bufferlist& in_data, JSONParser& parser)
{
if (access.empty() || secret.empty()) {
cerr << "An --access-key and --secret must be provided with --url." << std::endl;
return -EINVAL;
}
RGWAccessKey key;
key.id = access;
key.key = secret;
param_vec_t params;
RGWRESTSimpleRequest req(g_ceph_context, info.method, url, NULL, ¶ms, opt_region);
bufferlist response;
int ret = req.forward_request(dpp(), key, info, MAX_REST_RESPONSE, &in_data, &response, null_yield);
int parse_ret = parser.parse(response.c_str(), response.length());
if (parse_ret < 0) {
cout << "failed to parse response" << std::endl;
return parse_ret;
}
return ret;
}
static int send_to_remote_or_url(RGWRESTConn *conn, const string& url,
std::optional<string> opt_region,
const string& access, const string& secret,
req_info& info, bufferlist& in_data,
JSONParser& parser)
{
if (url.empty()) {
return send_to_remote_gateway(conn, info, in_data, parser);
}
return send_to_url(url, opt_region, access, secret, info, in_data, parser);
}
static int commit_period(rgw::sal::ConfigStore* cfgstore,
RGWRealm& realm, rgw::sal::RealmWriter& realm_writer,
RGWPeriod& period, string remote, const string& url,
std::optional<string> opt_region,
const string& access, const string& secret,
bool force)
{
auto& master_zone = period.get_master_zone().id;
if (master_zone.empty()) {
cerr << "cannot commit period: period does not have a master zone of a master zonegroup" << std::endl;
return -EINVAL;
}
// are we the period's master zone?
if (driver->get_zone()->get_id() == master_zone) {
// read the current period
RGWPeriod current_period;
int ret = cfgstore->read_period(dpp(), null_yield, realm.current_period,
std::nullopt, current_period);
if (ret < 0) {
cerr << "failed to load current period: " << cpp_strerror(ret) << std::endl;
return ret;
}
// the master zone can commit locally
ret = rgw::commit_period(dpp(), null_yield, cfgstore, driver,
realm, realm_writer, current_period,
period, cerr, force);
if (ret < 0) {
cerr << "failed to commit period: " << cpp_strerror(-ret) << std::endl;
}
return ret;
}
if (remote.empty() && url.empty()) {
// use the new master zone's connection
remote = master_zone;
cerr << "Sending period to new master zone " << remote << std::endl;
}
boost::optional<RGWRESTConn> conn;
RGWRESTConn *remote_conn = nullptr;
if (!remote.empty()) {
conn = get_remote_conn(static_cast<rgw::sal::RadosStore*>(driver), period.get_map(), remote);
if (!conn) {
cerr << "failed to find a zone or zonegroup for remote "
<< remote << std::endl;
return -ENOENT;
}
remote_conn = &*conn;
}
// push period to the master with an empty period id
period.set_id(string());
RGWEnv env;
req_info info(g_ceph_context, &env);
info.method = "POST";
info.request_uri = "/admin/realm/period";
// json format into a bufferlist
JSONFormatter jf(false);
encode_json("period", period, &jf);
bufferlist bl;
jf.flush(bl);
JSONParser p;
int ret = send_to_remote_or_url(remote_conn, url, opt_region, access, secret, info, bl, p);
if (ret < 0) {
cerr << "request failed: " << cpp_strerror(-ret) << std::endl;
// did we parse an error message?
auto message = p.find_obj("Message");
if (message) {
cerr << "Reason: " << message->get_data() << std::endl;
}
return ret;
}
// decode the response and driver it back
try {
decode_json_obj(period, &p);
} catch (const JSONDecoder::err& e) {
cout << "failed to decode JSON input: " << e.what() << std::endl;
return -EINVAL;
}
if (period.get_id().empty()) {
cerr << "Period commit got back an empty period id" << std::endl;
return -EINVAL;
}
// the master zone gave us back the period that it committed, so it's
// safe to save it as our latest epoch
constexpr bool exclusive = false;
ret = cfgstore->create_period(dpp(), null_yield, exclusive, period);
if (ret < 0) {
cerr << "Error storing committed period " << period.get_id() << ": "
<< cpp_strerror(ret) << std::endl;
return ret;
}
ret = rgw::reflect_period(dpp(), null_yield, cfgstore, period);
if (ret < 0) {
cerr << "Error updating local objects: " << cpp_strerror(ret) << std::endl;
return ret;
}
(void) cfgstore->realm_notify_new_period(dpp(), null_yield, period);
return ret;
}
static int update_period(rgw::sal::ConfigStore* cfgstore,
const string& realm_id, const string& realm_name,
const string& period_epoch, bool commit,
const string& remote, const string& url,
std::optional<string> opt_region,
const string& access, const string& secret,
Formatter *formatter, bool force)
{
RGWRealm realm;
std::unique_ptr<rgw::sal::RealmWriter> realm_writer;
int ret = rgw::read_realm(dpp(), null_yield, cfgstore,
realm_id, realm_name,
realm, &realm_writer);
if (ret < 0) {
cerr << "failed to load realm " << cpp_strerror(-ret) << std::endl;
return ret;
}
std::optional<epoch_t> epoch;
if (!period_epoch.empty()) {
epoch = atoi(period_epoch.c_str());
}
RGWPeriod period;
ret = cfgstore->read_period(dpp(), null_yield, realm.current_period,
epoch, period);
if (ret < 0) {
cerr << "failed to load current period: " << cpp_strerror(-ret) << std::endl;
return ret;
}
// convert to the realm's staging period
rgw::fork_period(dpp(), period);
// update the staging period with all of the realm's zonegroups
ret = rgw::update_period(dpp(), null_yield, cfgstore, period);
if (ret < 0) {
return ret;
}
constexpr bool exclusive = false;
ret = cfgstore->create_period(dpp(), null_yield, exclusive, period);
if (ret < 0) {
cerr << "failed to driver period: " << cpp_strerror(-ret) << std::endl;
return ret;
}
if (commit) {
ret = commit_period(cfgstore, realm, *realm_writer, period, remote, url,
opt_region, access, secret, force);
if (ret < 0) {
cerr << "failed to commit period: " << cpp_strerror(-ret) << std::endl;
return ret;
}
}
encode_json("period", period, formatter);
formatter->flush(cout);
return 0;
}
static int init_bucket_for_sync(rgw::sal::User* user,
const string& tenant, const string& bucket_name,
const string& bucket_id,
std::unique_ptr<rgw::sal::Bucket>* bucket)
{
int ret = init_bucket(user, tenant, bucket_name, bucket_id, bucket);
if (ret < 0) {
cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
return ret;
}
return 0;
}
static int do_period_pull(rgw::sal::ConfigStore* cfgstore,
RGWRESTConn *remote_conn, const string& url,
std::optional<string> opt_region,
const string& access_key, const string& secret_key,
const string& realm_id, const string& realm_name,
const string& period_id, const string& period_epoch,
RGWPeriod *period)
{
RGWEnv env;
req_info info(g_ceph_context, &env);
info.method = "GET";
info.request_uri = "/admin/realm/period";
map<string, string> ¶ms = info.args.get_params();
if (!realm_id.empty())
params["realm_id"] = realm_id;
if (!realm_name.empty())
params["realm_name"] = realm_name;
if (!period_id.empty())
params["period_id"] = period_id;
if (!period_epoch.empty())
params["epoch"] = period_epoch;
bufferlist bl;
JSONParser p;
int ret = send_to_remote_or_url(remote_conn, url, opt_region, access_key, secret_key,
info, bl, p);
if (ret < 0) {
cerr << "request failed: " << cpp_strerror(-ret) << std::endl;
return ret;
}
try {
decode_json_obj(*period, &p);
} catch (const JSONDecoder::err& e) {
cout << "failed to decode JSON input: " << e.what() << std::endl;
return -EINVAL;
}
constexpr bool exclusive = false;
ret = cfgstore->create_period(dpp(), null_yield, exclusive, *period);
if (ret < 0) {
cerr << "Error storing period " << period->get_id() << ": " << cpp_strerror(ret) << std::endl;
}
return 0;
}
void flush_ss(stringstream& ss, list<string>& l)
{
if (!ss.str().empty()) {
l.push_back(ss.str());
}
ss.str("");
}
stringstream& push_ss(stringstream& ss, list<string>& l, int tab = 0)
{
flush_ss(ss, l);
if (tab > 0) {
ss << setw(tab) << "" << setw(1);
}
return ss;
}
static void get_md_sync_status(list<string>& status)
{
RGWMetaSyncStatusManager sync(static_cast<rgw::sal::RadosStore*>(driver), static_cast<rgw::sal::RadosStore*>(driver)->svc()->rados->get_async_processor());
int ret = sync.init(dpp());
if (ret < 0) {
status.push_back(string("failed to retrieve sync info: sync.init() failed: ") + cpp_strerror(-ret));
return;
}
rgw_meta_sync_status sync_status;
ret = sync.read_sync_status(dpp(), &sync_status);
if (ret < 0) {
status.push_back(string("failed to read sync status: ") + cpp_strerror(-ret));
return;
}
string status_str;
switch (sync_status.sync_info.state) {
case rgw_meta_sync_info::StateInit:
status_str = "init";
break;
case rgw_meta_sync_info::StateBuildingFullSyncMaps:
status_str = "preparing for full sync";
break;
case rgw_meta_sync_info::StateSync:
status_str = "syncing";
break;
default:
status_str = "unknown";
}
status.push_back(status_str);
uint64_t full_total = 0;
uint64_t full_complete = 0;
int num_full = 0;
int num_inc = 0;
int total_shards = 0;
set<int> shards_behind_set;
for (auto marker_iter : sync_status.sync_markers) {
full_total += marker_iter.second.total_entries;
total_shards++;
if (marker_iter.second.state == rgw_meta_sync_marker::SyncState::FullSync) {
num_full++;
full_complete += marker_iter.second.pos;
int shard_id = marker_iter.first;
shards_behind_set.insert(shard_id);
} else {
full_complete += marker_iter.second.total_entries;
}
if (marker_iter.second.state == rgw_meta_sync_marker::SyncState::IncrementalSync) {
num_inc++;
}
}
stringstream ss;
push_ss(ss, status) << "full sync: " << num_full << "/" << total_shards << " shards";
if (num_full > 0) {
push_ss(ss, status) << "full sync: " << full_total - full_complete << " entries to sync";
}
push_ss(ss, status) << "incremental sync: " << num_inc << "/" << total_shards << " shards";
map<int, RGWMetadataLogInfo> master_shards_info;
string master_period = static_cast<rgw::sal::RadosStore*>(driver)->svc()->zone->get_current_period_id();
ret = sync.read_master_log_shards_info(dpp(), master_period, &master_shards_info);
if (ret < 0) {
status.push_back(string("failed to fetch master sync status: ") + cpp_strerror(-ret));
return;
}
map<int, string> shards_behind;
if (sync_status.sync_info.period != master_period) {
status.push_back(string("master is on a different period: master_period=" +
master_period + " local_period=" + sync_status.sync_info.period));
} else {
for (auto local_iter : sync_status.sync_markers) {
int shard_id = local_iter.first;
auto iter = master_shards_info.find(shard_id);
if (iter == master_shards_info.end()) {
/* huh? */
derr << "ERROR: could not find remote sync shard status for shard_id=" << shard_id << dendl;
continue;
}
auto master_marker = iter->second.marker;
if (local_iter.second.state == rgw_meta_sync_marker::SyncState::IncrementalSync &&
master_marker > local_iter.second.marker) {
shards_behind[shard_id] = local_iter.second.marker;
shards_behind_set.insert(shard_id);
}
}
}
// fetch remote log entries to determine the oldest change
std::optional<std::pair<int, ceph::real_time>> oldest;
if (!shards_behind.empty()) {
map<int, rgw_mdlog_shard_data> master_pos;
ret = sync.read_master_log_shards_next(dpp(), sync_status.sync_info.period, shards_behind, &master_pos);
if (ret < 0) {
derr << "ERROR: failed to fetch master next positions (" << cpp_strerror(-ret) << ")" << dendl;
} else {
for (auto iter : master_pos) {
rgw_mdlog_shard_data& shard_data = iter.second;
if (shard_data.entries.empty()) {
// there aren't any entries in this shard, so we're not really behind
shards_behind.erase(iter.first);
shards_behind_set.erase(iter.first);
} else {
rgw_mdlog_entry& entry = shard_data.entries.front();
if (!oldest) {
oldest.emplace(iter.first, entry.timestamp);
} else if (!ceph::real_clock::is_zero(entry.timestamp) && entry.timestamp < oldest->second) {
oldest.emplace(iter.first, entry.timestamp);
}
}
}
}
}
int total_behind = shards_behind.size() + (sync_status.sync_info.num_shards - num_inc);
if (total_behind == 0) {
push_ss(ss, status) << "metadata is caught up with master";
} else {
push_ss(ss, status) << "metadata is behind on " << total_behind << " shards";
push_ss(ss, status) << "behind shards: " << "[" << shards_behind_set << "]";
if (oldest) {
push_ss(ss, status) << "oldest incremental change not applied: "
<< oldest->second << " [" << oldest->first << ']';
}
}
flush_ss(ss, status);
}
static void get_data_sync_status(const rgw_zone_id& source_zone, list<string>& status, int tab)
{
stringstream ss;
RGWZone *sz;
if (!(sz = static_cast<rgw::sal::RadosStore*>(driver)->svc()->zone->find_zone(source_zone))) {
push_ss(ss, status, tab) << string("zone not found");
flush_ss(ss, status);
return;
}
if (!static_cast<rgw::sal::RadosStore*>(driver)->svc()->zone->zone_syncs_from(static_cast<rgw::sal::RadosStore*>(driver)->svc()->zone->get_zone(), *sz)) {
push_ss(ss, status, tab) << string("not syncing from zone");
flush_ss(ss, status);
return;
}
RGWDataSyncStatusManager sync(static_cast<rgw::sal::RadosStore*>(driver), static_cast<rgw::sal::RadosStore*>(driver)->svc()->rados->get_async_processor(), source_zone, nullptr);
int ret = sync.init(dpp());
if (ret < 0) {
push_ss(ss, status, tab) << string("failed to retrieve sync info: ") + cpp_strerror(-ret);
flush_ss(ss, status);
return;
}
rgw_data_sync_status sync_status;
ret = sync.read_sync_status(dpp(), &sync_status);
if (ret < 0 && ret != -ENOENT) {
push_ss(ss, status, tab) << string("failed read sync status: ") + cpp_strerror(-ret);
return;
}
set<int> recovering_shards;
ret = sync.read_recovering_shards(dpp(), sync_status.sync_info.num_shards, recovering_shards);
if (ret < 0 && ret != ENOENT) {
push_ss(ss, status, tab) << string("failed read recovering shards: ") + cpp_strerror(-ret);
return;
}
string status_str;
switch (sync_status.sync_info.state) {
case rgw_data_sync_info::StateInit:
status_str = "init";
break;
case rgw_data_sync_info::StateBuildingFullSyncMaps:
status_str = "preparing for full sync";
break;
case rgw_data_sync_info::StateSync:
status_str = "syncing";
break;
default:
status_str = "unknown";
}
push_ss(ss, status, tab) << status_str;
uint64_t full_total = 0;
uint64_t full_complete = 0;
int num_full = 0;
int num_inc = 0;
int total_shards = 0;
set<int> shards_behind_set;
for (auto marker_iter : sync_status.sync_markers) {
full_total += marker_iter.second.total_entries;
total_shards++;
if (marker_iter.second.state == rgw_data_sync_marker::SyncState::FullSync) {
num_full++;
full_complete += marker_iter.second.pos;
int shard_id = marker_iter.first;
shards_behind_set.insert(shard_id);
} else {
full_complete += marker_iter.second.total_entries;
}
if (marker_iter.second.state == rgw_data_sync_marker::SyncState::IncrementalSync) {
num_inc++;
}
}
push_ss(ss, status, tab) << "full sync: " << num_full << "/" << total_shards << " shards";
if (num_full > 0) {
push_ss(ss, status, tab) << "full sync: " << full_total - full_complete << " buckets to sync";
}
push_ss(ss, status, tab) << "incremental sync: " << num_inc << "/" << total_shards << " shards";
map<int, RGWDataChangesLogInfo> source_shards_info;
ret = sync.read_source_log_shards_info(dpp(), &source_shards_info);
if (ret < 0) {
push_ss(ss, status, tab) << string("failed to fetch source sync status: ") + cpp_strerror(-ret);
return;
}
map<int, string> shards_behind;
for (auto local_iter : sync_status.sync_markers) {
int shard_id = local_iter.first;
auto iter = source_shards_info.find(shard_id);
if (iter == source_shards_info.end()) {
/* huh? */
derr << "ERROR: could not find remote sync shard status for shard_id=" << shard_id << dendl;
continue;
}
auto master_marker = iter->second.marker;
if (local_iter.second.state == rgw_data_sync_marker::SyncState::IncrementalSync &&
master_marker > local_iter.second.marker) {
shards_behind[shard_id] = local_iter.second.marker;
shards_behind_set.insert(shard_id);
}
}
std::optional<std::pair<int, ceph::real_time>> oldest;
if (!shards_behind.empty()) {
map<int, rgw_datalog_shard_data> master_pos;
ret = sync.read_source_log_shards_next(dpp(), shards_behind, &master_pos);
if (ret < 0) {
derr << "ERROR: failed to fetch next positions (" << cpp_strerror(-ret) << ")" << dendl;
} else {
for (auto iter : master_pos) {
rgw_datalog_shard_data& shard_data = iter.second;
if (shard_data.entries.empty()) {
// there aren't any entries in this shard, so we're not really behind
shards_behind.erase(iter.first);
shards_behind_set.erase(iter.first);
} else {
rgw_datalog_entry& entry = shard_data.entries.front();
if (!oldest) {
oldest.emplace(iter.first, entry.timestamp);
} else if (!ceph::real_clock::is_zero(entry.timestamp) && entry.timestamp < oldest->second) {
oldest.emplace(iter.first, entry.timestamp);
}
}
}
}
}
int total_behind = shards_behind.size() + (sync_status.sync_info.num_shards - num_inc);
int total_recovering = recovering_shards.size();
if (total_behind == 0 && total_recovering == 0) {
push_ss(ss, status, tab) << "data is caught up with source";
} else if (total_behind > 0) {
push_ss(ss, status, tab) << "data is behind on " << total_behind << " shards";
push_ss(ss, status, tab) << "behind shards: " << "[" << shards_behind_set << "]" ;
if (oldest) {
push_ss(ss, status, tab) << "oldest incremental change not applied: "
<< oldest->second << " [" << oldest->first << ']';
}
}
if (total_recovering > 0) {
push_ss(ss, status, tab) << total_recovering << " shards are recovering";
push_ss(ss, status, tab) << "recovering shards: " << "[" << recovering_shards << "]";
}
flush_ss(ss, status);
}
static void tab_dump(const string& header, int width, const list<string>& entries)
{
string s = header;
for (auto e : entries) {
cout << std::setw(width) << s << std::setw(1) << " " << e << std::endl;
s.clear();
}
}
// return features that are supported but not enabled
static auto get_disabled_features(const rgw::zone_features::set& enabled) {
auto features = rgw::zone_features::set{rgw::zone_features::supported.begin(),
rgw::zone_features::supported.end()};
for (const auto& feature : enabled) {
features.erase(feature);
}
return features;
}
static void sync_status(Formatter *formatter)
{
const rgw::sal::ZoneGroup& zonegroup = driver->get_zone()->get_zonegroup();
rgw::sal::Zone* zone = driver->get_zone();
int width = 15;
cout << std::setw(width) << "realm" << std::setw(1) << " " << zone->get_realm_id() << " (" << zone->get_realm_name() << ")" << std::endl;
cout << std::setw(width) << "zonegroup" << std::setw(1) << " " << zonegroup.get_id() << " (" << zonegroup.get_name() << ")" << std::endl;
cout << std::setw(width) << "zone" << std::setw(1) << " " << zone->get_id() << " (" << zone->get_name() << ")" << std::endl;
cout << std::setw(width) << "current time" << std::setw(1) << " "
<< to_iso_8601(ceph::real_clock::now(), iso_8601_format::YMDhms) << std::endl;
const auto& rzg =
static_cast<const rgw::sal::RadosZoneGroup&>(zonegroup).get_group();
cout << std::setw(width) << "zonegroup features enabled: " << rzg.enabled_features << std::endl;
if (auto d = get_disabled_features(rzg.enabled_features); !d.empty()) {
cout << std::setw(width) << " disabled: " << d << std::endl;
}
list<string> md_status;
if (driver->is_meta_master()) {
md_status.push_back("no sync (zone is master)");
} else {
get_md_sync_status(md_status);
}
tab_dump("metadata sync", width, md_status);
list<string> data_status;
auto& zone_conn_map = static_cast<rgw::sal::RadosStore*>(driver)->svc()->zone->get_zone_conn_map();
for (auto iter : zone_conn_map) {
const rgw_zone_id& source_id = iter.first;
string source_str = "source: ";
string s = source_str + source_id.id;
std::unique_ptr<rgw::sal::Zone> sz;
if (driver->get_zone()->get_zonegroup().get_zone_by_id(source_id.id, &sz) == 0) {
s += string(" (") + sz->get_name() + ")";
}
data_status.push_back(s);
get_data_sync_status(source_id, data_status, source_str.size());
}
tab_dump("data sync", width, data_status);
}
struct indented {
int w; // indent width
std::string_view header;
indented(int w, std::string_view header = "") : w(w), header(header) {}
};
std::ostream& operator<<(std::ostream& out, const indented& h) {
return out << std::setw(h.w) << h.header << std::setw(1) << ' ';
}
static int bucket_source_sync_status(const DoutPrefixProvider *dpp, rgw::sal::RadosStore* driver, const RGWZone& zone,
const RGWZone& source, RGWRESTConn *conn,
const RGWBucketInfo& bucket_info,
rgw_sync_bucket_pipe pipe,
int width, std::ostream& out)
{
out << indented{width, "source zone"} << source.id << " (" << source.name << ")" << std::endl;
// syncing from this zone?
if (!driver->svc()->zone->zone_syncs_from(zone, source)) {
out << indented{width} << "does not sync from zone\n";
return 0;
}
if (!pipe.source.bucket) {
ldpp_dout(dpp, -1) << __func__ << "(): missing source bucket" << dendl;
return -EINVAL;
}
std::unique_ptr<rgw::sal::Bucket> source_bucket;
int r = init_bucket(nullptr, *pipe.source.bucket, &source_bucket);
if (r < 0) {
ldpp_dout(dpp, -1) << "failed to read source bucket info: " << cpp_strerror(r) << dendl;
return r;
}
out << indented{width, "source bucket"} << source_bucket->get_key() << std::endl;
pipe.source.bucket = source_bucket->get_key();
pipe.dest.bucket = bucket_info.bucket;
uint64_t gen = 0;
std::vector<rgw_bucket_shard_sync_info> shard_status;
// check for full sync status
rgw_bucket_sync_status full_status;
r = rgw_read_bucket_full_sync_status(dpp, driver, pipe, &full_status, null_yield);
if (r >= 0) {
if (full_status.state == BucketSyncState::Init) {
out << indented{width} << "init: bucket sync has not started\n";
return 0;
}
if (full_status.state == BucketSyncState::Stopped) {
out << indented{width} << "stopped: bucket sync is disabled\n";
return 0;
}
if (full_status.state == BucketSyncState::Full) {
out << indented{width} << "full sync: " << full_status.full.count << " objects completed\n";
return 0;
}
gen = full_status.incremental_gen;
shard_status.resize(full_status.shards_done_with_gen.size());
} else if (r == -ENOENT) {
// no full status, but there may be per-shard status from before upgrade
const auto& logs = source_bucket->get_info().layout.logs;
if (logs.empty()) {
out << indented{width} << "init: bucket sync has not started\n";
return 0;
}
const auto& log = logs.front();
if (log.gen > 0) {
// this isn't the backward-compatible case, so we just haven't started yet
out << indented{width} << "init: bucket sync has not started\n";
return 0;
}
if (log.layout.type != rgw::BucketLogType::InIndex) {
ldpp_dout(dpp, -1) << "unrecognized log layout type " << log.layout.type << dendl;
return -EINVAL;
}
// use shard count from our log gen=0
shard_status.resize(rgw::num_shards(log.layout.in_index));
} else {
lderr(driver->ctx()) << "failed to read bucket full sync status: " << cpp_strerror(r) << dendl;
return r;
}
r = rgw_read_bucket_inc_sync_status(dpp, driver, pipe, gen, &shard_status);
if (r < 0) {
lderr(driver->ctx()) << "failed to read bucket incremental sync status: " << cpp_strerror(r) << dendl;
return r;
}
const int total_shards = shard_status.size();
out << indented{width} << "incremental sync on " << total_shards << " shards\n";
rgw_bucket_index_marker_info remote_info;
BucketIndexShardsManager remote_markers;
r = rgw_read_remote_bilog_info(dpp, conn, source_bucket->get_key(),
remote_info, remote_markers, null_yield);
if (r < 0) {
ldpp_dout(dpp, -1) << "failed to read remote log: " << cpp_strerror(r) << dendl;
return r;
}
std::set<int> shards_behind;
for (const auto& r : remote_markers.get()) {
auto shard_id = r.first;
if (r.second.empty()) {
continue; // empty bucket index shard
}
if (shard_id >= total_shards) {
// unexpected shard id. we don't have status for it, so we're behind
shards_behind.insert(shard_id);
continue;
}
auto& m = shard_status[shard_id];
const auto pos = BucketIndexShardsManager::get_shard_marker(m.inc_marker.position);
if (pos < r.second) {
shards_behind.insert(shard_id);
}
}
if (!shards_behind.empty()) {
out << indented{width} << "bucket is behind on " << shards_behind.size() << " shards\n";
out << indented{width} << "behind shards: [" << shards_behind << "]\n" ;
} else {
out << indented{width} << "bucket is caught up with source\n";
}
return 0;
}
void encode_json(const char *name, const RGWBucketSyncFlowManager::pipe_set& pset, Formatter *f)
{
Formatter::ObjectSection top_section(*f, name);
Formatter::ArraySection as(*f, "entries");
for (auto& pipe_handler : pset) {
Formatter::ObjectSection hs(*f, "handler");
encode_json("source", pipe_handler.source, f);
encode_json("dest", pipe_handler.dest, f);
}
}
static std::vector<string> convert_bucket_set_to_str_vec(const std::set<rgw_bucket>& bs)
{
std::vector<string> result;
result.reserve(bs.size());
for (auto& b : bs) {
result.push_back(b.get_key());
}
return result;
}
static void get_hint_entities(const std::set<rgw_zone_id>& zones, const std::set<rgw_bucket>& buckets,
std::set<rgw_sync_bucket_entity> *hint_entities)
{
for (auto& zone_id : zones) {
for (auto& b : buckets) {
std::unique_ptr<rgw::sal::Bucket> hint_bucket;
int ret = init_bucket(nullptr, b, &hint_bucket);
if (ret < 0) {
ldpp_dout(dpp(), 20) << "could not init bucket info for hint bucket=" << b << " ... skipping" << dendl;
continue;
}
hint_entities->insert(rgw_sync_bucket_entity(zone_id, hint_bucket->get_key()));
}
}
}
static rgw_zone_id resolve_zone_id(const string& s)
{
std::unique_ptr<rgw::sal::Zone> zone;
int ret = driver->get_zone()->get_zonegroup().get_zone_by_id(s, &zone);
if (ret < 0)
ret = driver->get_zone()->get_zonegroup().get_zone_by_name(s, &zone);
if (ret < 0)
return rgw_zone_id(s);
return rgw_zone_id(zone->get_id());
}
rgw_zone_id validate_zone_id(const rgw_zone_id& zone_id)
{
return resolve_zone_id(zone_id.id);
}
static int sync_info(std::optional<rgw_zone_id> opt_target_zone, std::optional<rgw_bucket> opt_bucket, Formatter *formatter)
{
rgw_zone_id zone_id = opt_target_zone.value_or(driver->get_zone()->get_id());
auto zone_policy_handler = driver->get_zone()->get_sync_policy_handler();
RGWBucketSyncPolicyHandlerRef bucket_handler;
std::optional<rgw_bucket> eff_bucket = opt_bucket;
auto handler = zone_policy_handler;
if (eff_bucket) {
std::unique_ptr<rgw::sal::Bucket> bucket;
int ret = init_bucket(nullptr, *eff_bucket, &bucket);
if (ret < 0 && ret != -ENOENT) {
cerr << "ERROR: init_bucket failed: " << cpp_strerror(-ret) << std::endl;
return ret;
}
if (ret >= 0) {
rgw::sal::Attrs attrs = bucket->get_attrs();
bucket_handler.reset(handler->alloc_child(bucket->get_info(), std::move(attrs)));
} else {
cerr << "WARNING: bucket not found, simulating result" << std::endl;
bucket_handler.reset(handler->alloc_child(*eff_bucket, nullopt));
}
ret = bucket_handler->init(dpp(), null_yield);
if (ret < 0) {
cerr << "ERROR: failed to init bucket sync policy handler: " << cpp_strerror(-ret) << " (ret=" << ret << ")" << std::endl;
return ret;
}
handler = bucket_handler;
}
std::set<rgw_sync_bucket_pipe> sources;
std::set<rgw_sync_bucket_pipe> dests;
handler->get_pipes(&sources, &dests, std::nullopt);
auto source_hints_vec = convert_bucket_set_to_str_vec(handler->get_source_hints());
auto target_hints_vec = convert_bucket_set_to_str_vec(handler->get_target_hints());
std::set<rgw_sync_bucket_pipe> resolved_sources;
std::set<rgw_sync_bucket_pipe> resolved_dests;
rgw_sync_bucket_entity self_entity(zone_id, opt_bucket);
set<rgw_zone_id> source_zones;
set<rgw_zone_id> target_zones;
zone_policy_handler->reflect(dpp(), nullptr, nullptr,
nullptr, nullptr,
&source_zones,
&target_zones,
false); /* relaxed: also get all zones that we allow to sync to/from */
std::set<rgw_sync_bucket_entity> hint_entities;
get_hint_entities(source_zones, handler->get_source_hints(), &hint_entities);
get_hint_entities(target_zones, handler->get_target_hints(), &hint_entities);
for (auto& hint_entity : hint_entities) {
if (!hint_entity.zone ||
!hint_entity.bucket) {
continue; /* shouldn't really happen */
}
auto zid = validate_zone_id(*hint_entity.zone);
auto& hint_bucket = *hint_entity.bucket;
RGWBucketSyncPolicyHandlerRef hint_bucket_handler;
int r = driver->get_sync_policy_handler(dpp(), zid, hint_bucket, &hint_bucket_handler, null_yield);
if (r < 0) {
ldpp_dout(dpp(), 20) << "could not get bucket sync policy handler for hint bucket=" << hint_bucket << " ... skipping" << dendl;
continue;
}
hint_bucket_handler->get_pipes(&resolved_dests,
&resolved_sources,
self_entity); /* flipping resolved dests and sources as these are
relative to the remote entity */
}
{
Formatter::ObjectSection os(*formatter, "result");
encode_json("sources", sources, formatter);
encode_json("dests", dests, formatter);
{
Formatter::ObjectSection hints_section(*formatter, "hints");
encode_json("sources", source_hints_vec, formatter);
encode_json("dests", target_hints_vec, formatter);
}
{
Formatter::ObjectSection resolved_hints_section(*formatter, "resolved-hints-1");
encode_json("sources", resolved_sources, formatter);
encode_json("dests", resolved_dests, formatter);
}
{
Formatter::ObjectSection resolved_hints_section(*formatter, "resolved-hints");
encode_json("sources", handler->get_resolved_source_hints(), formatter);
encode_json("dests", handler->get_resolved_dest_hints(), formatter);
}
}
formatter->flush(cout);
return 0;
}
static int bucket_sync_info(rgw::sal::Driver* driver, const RGWBucketInfo& info,
std::ostream& out)
{
const rgw::sal::ZoneGroup& zonegroup = driver->get_zone()->get_zonegroup();
rgw::sal::Zone* zone = driver->get_zone();
constexpr int width = 15;
out << indented{width, "realm"} << zone->get_realm_id() << " (" << zone->get_realm_name() << ")\n";
out << indented{width, "zonegroup"} << zonegroup.get_id() << " (" << zonegroup.get_name() << ")\n";
out << indented{width, "zone"} << zone->get_id() << " (" << zone->get_name() << ")\n";
out << indented{width, "bucket"} << info.bucket << "\n\n";
if (!static_cast<rgw::sal::RadosStore*>(driver)->ctl()->bucket->bucket_imports_data(info.bucket, null_yield, dpp())) {
out << "Sync is disabled for bucket " << info.bucket.name << '\n';
return 0;
}
RGWBucketSyncPolicyHandlerRef handler;
int r = driver->get_sync_policy_handler(dpp(), std::nullopt, info.bucket, &handler, null_yield);
if (r < 0) {
ldpp_dout(dpp(), -1) << "ERROR: failed to get policy handler for bucket (" << info.bucket << "): r=" << r << ": " << cpp_strerror(-r) << dendl;
return r;
}
auto& sources = handler->get_sources();
for (auto& m : sources) {
auto& zone = m.first;
out << indented{width, "source zone"} << zone << std::endl;
for (auto& pipe_handler : m.second) {
out << indented{width, "bucket"} << *pipe_handler.source.bucket << std::endl;
}
}
return 0;
}
static int bucket_sync_status(rgw::sal::Driver* driver, const RGWBucketInfo& info,
const rgw_zone_id& source_zone_id,
std::optional<rgw_bucket>& opt_source_bucket,
std::ostream& out)
{
const rgw::sal::ZoneGroup& zonegroup = driver->get_zone()->get_zonegroup();
rgw::sal::Zone* zone = driver->get_zone();
constexpr int width = 15;
out << indented{width, "realm"} << zone->get_realm_id() << " (" << zone->get_realm_name() << ")\n";
out << indented{width, "zonegroup"} << zonegroup.get_id() << " (" << zonegroup.get_name() << ")\n";
out << indented{width, "zone"} << zone->get_id() << " (" << zone->get_name() << ")\n";
out << indented{width, "bucket"} << info.bucket << "\n";
out << indented{width, "current time"}
<< to_iso_8601(ceph::real_clock::now(), iso_8601_format::YMDhms) << "\n\n";
if (!static_cast<rgw::sal::RadosStore*>(driver)->ctl()->bucket->bucket_imports_data(info.bucket, null_yield, dpp())) {
out << "Sync is disabled for bucket " << info.bucket.name << " or bucket has no sync sources" << std::endl;
return 0;
}
RGWBucketSyncPolicyHandlerRef handler;
int r = driver->get_sync_policy_handler(dpp(), std::nullopt, info.bucket, &handler, null_yield);
if (r < 0) {
ldpp_dout(dpp(), -1) << "ERROR: failed to get policy handler for bucket (" << info.bucket << "): r=" << r << ": " << cpp_strerror(-r) << dendl;
return r;
}
auto sources = handler->get_all_sources();
auto& zone_conn_map = static_cast<rgw::sal::RadosStore*>(driver)->svc()->zone->get_zone_conn_map();
set<rgw_zone_id> zone_ids;
if (!source_zone_id.empty()) {
std::unique_ptr<rgw::sal::Zone> zone;
int ret = driver->get_zone()->get_zonegroup().get_zone_by_id(source_zone_id.id, &zone);
if (ret < 0) {
ldpp_dout(dpp(), -1) << "Source zone not found in zonegroup "
<< zonegroup.get_name() << dendl;
return -EINVAL;
}
auto c = zone_conn_map.find(source_zone_id);
if (c == zone_conn_map.end()) {
ldpp_dout(dpp(), -1) << "No connection to zone " << zone->get_name() << dendl;
return -EINVAL;
}
zone_ids.insert(source_zone_id);
} else {
std::list<std::string> ids;
int ret = driver->get_zone()->get_zonegroup().list_zones(ids);
if (ret == 0) {
for (const auto& entry : ids) {
zone_ids.insert(entry);
}
}
}
for (auto& zone_id : zone_ids) {
auto z = static_cast<rgw::sal::RadosStore*>(driver)->svc()->zone->get_zonegroup().zones.find(zone_id.id);
if (z == static_cast<rgw::sal::RadosStore*>(driver)->svc()->zone->get_zonegroup().zones.end()) { /* should't happen */
continue;
}
auto c = zone_conn_map.find(zone_id.id);
if (c == zone_conn_map.end()) { /* should't happen */
continue;
}
for (auto& entry : sources) {
auto& pipe = entry.second;
if (opt_source_bucket &&
pipe.source.bucket != opt_source_bucket) {
continue;
}
if (pipe.source.zone.value_or(rgw_zone_id()) == z->second.id) {
bucket_source_sync_status(dpp(), static_cast<rgw::sal::RadosStore*>(driver), static_cast<rgw::sal::RadosStore*>(driver)->svc()->zone->get_zone(), z->second,
c->second,
info, pipe,
width, out);
}
}
}
return 0;
}
static void parse_tier_config_param(const string& s, map<string, string, ltstr_nocase>& out)
{
int level = 0;
string cur_conf;
list<string> confs;
for (auto c : s) {
if (c == ',') {
if (level == 0) {
confs.push_back(cur_conf);
cur_conf.clear();
continue;
}
}
if (c == '{') {
++level;
} else if (c == '}') {
--level;
}
cur_conf += c;
}
if (!cur_conf.empty()) {
confs.push_back(cur_conf);
}
for (auto c : confs) {
ssize_t pos = c.find("=");
if (pos < 0) {
out[c] = "";
} else {
out[c.substr(0, pos)] = c.substr(pos + 1);
}
}
}
static int check_pool_support_omap(const rgw_pool& pool)
{
librados::IoCtx io_ctx;
int ret = static_cast<rgw::sal::RadosStore*>(driver)->getRados()->get_rados_handle()->ioctx_create(pool.to_str().c_str(), io_ctx);
if (ret < 0) {
// the pool may not exist at this moment, we have no way to check if it supports omap.
return 0;
}
ret = io_ctx.omap_clear("__omap_test_not_exist_oid__");
if (ret == -EOPNOTSUPP) {
io_ctx.close();
return ret;
}
io_ctx.close();
return 0;
}
int check_reshard_bucket_params(rgw::sal::Driver* driver,
const string& bucket_name,
const string& tenant,
const string& bucket_id,
bool num_shards_specified,
int num_shards,
int yes_i_really_mean_it,
std::unique_ptr<rgw::sal::Bucket>* bucket)
{
if (bucket_name.empty()) {
cerr << "ERROR: bucket not specified" << std::endl;
return -EINVAL;
}
if (!num_shards_specified) {
cerr << "ERROR: --num-shards not specified" << std::endl;
return -EINVAL;
}
if (num_shards > (int)static_cast<rgw::sal::RadosStore*>(driver)->getRados()->get_max_bucket_shards()) {
cerr << "ERROR: num_shards too high, max value: " << static_cast<rgw::sal::RadosStore*>(driver)->getRados()->get_max_bucket_shards() << std::endl;
return -EINVAL;
}
if (num_shards < 0) {
cerr << "ERROR: num_shards must be non-negative integer" << std::endl;
return -EINVAL;
}
int ret = init_bucket(nullptr, tenant, bucket_name, bucket_id, bucket);
if (ret < 0) {
cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
return ret;
}
int num_source_shards = rgw::current_num_shards((*bucket)->get_info().layout);
if (num_shards <= num_source_shards && !yes_i_really_mean_it) {
cerr << "num shards is less or equal to current shards count" << std::endl
<< "do you really mean it? (requires --yes-i-really-mean-it)" << std::endl;
return -EINVAL;
}
return 0;
}
static int scan_totp(CephContext *cct, ceph::real_time& now, rados::cls::otp::otp_info_t& totp, vector<string>& pins,
time_t *pofs)
{
#define MAX_TOTP_SKEW_HOURS (24 * 7)
time_t start_time = ceph::real_clock::to_time_t(now);
time_t time_ofs = 0, time_ofs_abs = 0;
time_t step_size = totp.step_size;
if (step_size == 0) {
step_size = OATH_TOTP_DEFAULT_TIME_STEP_SIZE;
}
uint32_t count = 0;
int sign = 1;
uint32_t max_skew = MAX_TOTP_SKEW_HOURS * 3600;
while (time_ofs_abs < max_skew) {
int rc = oath_totp_validate2(totp.seed_bin.c_str(), totp.seed_bin.length(),
start_time,
step_size,
time_ofs,
1,
nullptr,
pins[0].c_str());
if (rc != OATH_INVALID_OTP) {
// oath_totp_validate2 is an external library function, cannot fix internally
// Further, step_size is a small number and unlikely to overflow
// coverity[store_truncates_time_t:SUPPRESS]
rc = oath_totp_validate2(totp.seed_bin.c_str(), totp.seed_bin.length(),
start_time,
step_size,
time_ofs - step_size, /* smaller time_ofs moves time forward */
1,
nullptr,
pins[1].c_str());
if (rc != OATH_INVALID_OTP) {
*pofs = time_ofs - step_size + step_size * totp.window / 2;
ldpp_dout(dpp(), 20) << "found at time=" << start_time - time_ofs << " time_ofs=" << time_ofs << dendl;
return 0;
}
}
sign = -sign;
time_ofs_abs = (++count) * step_size;
time_ofs = sign * time_ofs_abs;
}
return -ENOENT;
}
static int trim_sync_error_log(int shard_id, const string& marker, int delay_ms)
{
auto oid = RGWSyncErrorLogger::get_shard_oid(RGW_SYNC_ERROR_LOG_SHARD_PREFIX,
shard_id);
// call cls_log_trim() until it returns -ENODATA
for (;;) {
int ret = static_cast<rgw::sal::RadosStore*>(driver)->svc()->cls->timelog.trim(dpp(), oid, {}, {}, {}, marker, nullptr,
null_yield);
if (ret == -ENODATA) {
return 0;
}
if (ret < 0) {
return ret;
}
if (delay_ms) {
std::this_thread::sleep_for(std::chrono::milliseconds(delay_ms));
}
}
// unreachable
}
static bool symmetrical_flow_opt(const string& opt)
{
return (opt == "symmetrical" || opt == "symmetric");
}
static bool directional_flow_opt(const string& opt)
{
return (opt == "directional" || opt == "direction");
}
template <class T>
static bool require_opt(std::optional<T> opt, bool extra_check = true)
{
if (!opt || !extra_check) {
return false;
}
return true;
}
template <class T>
static bool require_non_empty_opt(std::optional<T> opt, bool extra_check = true)
{
if (!opt || opt->empty() || !extra_check) {
return false;
}
return true;
}
template <class T>
static void show_result(T& obj,
Formatter *formatter,
ostream& os)
{
encode_json("obj", obj, formatter);
formatter->flush(cout);
}
void init_optional_bucket(std::optional<rgw_bucket>& opt_bucket,
std::optional<string>& opt_tenant,
std::optional<string>& opt_bucket_name,
std::optional<string>& opt_bucket_id)
{
if (opt_tenant || opt_bucket_name || opt_bucket_id) {
opt_bucket.emplace();
if (opt_tenant) {
opt_bucket->tenant = *opt_tenant;
}
if (opt_bucket_name) {
opt_bucket->name = *opt_bucket_name;
}
if (opt_bucket_id) {
opt_bucket->bucket_id = *opt_bucket_id;
}
}
}
class SyncPolicyContext
{
rgw::sal::ConfigStore* cfgstore;
RGWZoneGroup zonegroup;
std::unique_ptr<rgw::sal::ZoneGroupWriter> zonegroup_writer;
std::optional<rgw_bucket> b;
std::unique_ptr<rgw::sal::Bucket> bucket;
rgw_sync_policy_info *policy{nullptr};
std::optional<rgw_user> owner;
public:
SyncPolicyContext(rgw::sal::ConfigStore* cfgstore,
std::optional<rgw_bucket> _bucket)
: cfgstore(cfgstore), b(std::move(_bucket)) {}
int init(const string& zonegroup_id, const string& zonegroup_name) {
int ret = rgw::read_zonegroup(dpp(), null_yield, cfgstore,
zonegroup_id, zonegroup_name,
zonegroup, &zonegroup_writer);
if (ret < 0) {
cerr << "failed to init zonegroup: " << cpp_strerror(-ret) << std::endl;
return ret;
}
if (!b) {
policy = &zonegroup.sync_policy;
return 0;
}
ret = init_bucket(nullptr, *b, &bucket);
if (ret < 0) {
cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
return ret;
}
owner = bucket->get_info().owner;
if (!bucket->get_info().sync_policy) {
rgw_sync_policy_info new_policy;
bucket->get_info().set_sync_policy(std::move(new_policy));
}
policy = &(*bucket->get_info().sync_policy);
return 0;
}
int write_policy() {
if (!b) {
int ret = zonegroup_writer->write(dpp(), null_yield, zonegroup);
if (ret < 0) {
cerr << "failed to update zonegroup: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
return 0;
}
int ret = bucket->put_info(dpp(), false, real_time(), null_yield);
if (ret < 0) {
cerr << "failed to driver bucket info: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
return 0;
}
rgw_sync_policy_info& get_policy() {
return *policy;
}
std::optional<rgw_user>& get_owner() {
return owner;
}
};
void resolve_zone_id_opt(std::optional<string>& zone_name, std::optional<rgw_zone_id>& zone_id)
{
if (!zone_name || zone_id) {
return;
}
zone_id.emplace();
std::unique_ptr<rgw::sal::Zone> zone;
int ret = driver->get_zone()->get_zonegroup().get_zone_by_name(*zone_name, &zone);
if (ret < 0) {
cerr << "WARNING: cannot find source zone id for name=" << *zone_name << std::endl;
zone_id = rgw_zone_id(*zone_name);
} else {
zone_id->id = zone->get_id();
}
}
void resolve_zone_ids_opt(std::optional<vector<string> >& names, std::optional<vector<rgw_zone_id> >& ids)
{
if (!names || ids) {
return;
}
ids.emplace();
for (auto& name : *names) {
rgw_zone_id zid;
std::unique_ptr<rgw::sal::Zone> zone;
int ret = driver->get_zone()->get_zonegroup().get_zone_by_name(name, &zone);
if (ret < 0) {
cerr << "WARNING: cannot find source zone id for name=" << name << std::endl;
zid = rgw_zone_id(name);
} else {
zid.id = zone->get_id();
}
ids->push_back(zid);
}
}
static vector<rgw_zone_id> zone_ids_from_str(const string& val)
{
vector<rgw_zone_id> result;
vector<string> v;
get_str_vec(val, v);
for (auto& z : v) {
result.push_back(rgw_zone_id(z));
}
return result;
}
class JSONFormatter_PrettyZone : public JSONFormatter {
class Handler : public JSONEncodeFilter::Handler<rgw_zone_id> {
void encode_json(const char *name, const void *pval, ceph::Formatter *f) const override {
auto zone_id = *(static_cast<const rgw_zone_id *>(pval));
string zone_name;
std::unique_ptr<rgw::sal::Zone> zone;
if (driver->get_zone()->get_zonegroup().get_zone_by_id(zone_id.id, &zone) == 0) {
zone_name = zone->get_name();
} else {
cerr << "WARNING: cannot find zone name for id=" << zone_id << std::endl;
zone_name = zone_id.id;
}
::encode_json(name, zone_name, f);
}
} zone_id_type_handler;
JSONEncodeFilter encode_filter;
public:
JSONFormatter_PrettyZone(bool pretty_format) : JSONFormatter(pretty_format) {
encode_filter.register_type(&zone_id_type_handler);
}
void *get_external_feature_handler(const std::string& feature) override {
if (feature != "JSONEncodeFilter") {
return nullptr;
}
return &encode_filter;
}
};
void init_realm_param(CephContext *cct, string& var, std::optional<string>& opt_var, const string& conf_name)
{
var = cct->_conf.get_val<string>(conf_name);
if (!var.empty()) {
opt_var = var;
}
}
int main(int argc, const char **argv)
{
auto args = argv_to_vec(argc, argv);
if (args.empty()) {
cerr << argv[0] << ": -h or --help for usage" << std::endl;
exit(1);
}
if (ceph_argparse_need_usage(args)) {
usage();
exit(0);
}
auto cct = rgw_global_init(NULL, args, CEPH_ENTITY_TYPE_CLIENT,
CODE_ENVIRONMENT_UTILITY, 0);
// for region -> zonegroup conversion (must happen before common_init_finish())
if (!g_conf()->rgw_region.empty() && g_conf()->rgw_zonegroup.empty()) {
g_conf().set_val_or_die("rgw_zonegroup", g_conf()->rgw_region.c_str());
}
rgw_user user_id_arg;
std::unique_ptr<rgw::sal::User> user;
string tenant;
string user_ns;
rgw_user new_user_id;
std::string access_key, secret_key, user_email, display_name;
std::string bucket_name, pool_name, object;
rgw_pool pool;
std::string date, subuser, access, format;
std::string start_date, end_date;
std::string key_type_str;
std::string period_id, period_epoch, remote, url;
std::optional<string> opt_region;
std::string master_zone;
std::string realm_name, realm_id, realm_new_name;
std::optional<string> opt_realm_name, opt_realm_id;
std::string zone_name, zone_id, zone_new_name;
std::optional<string> opt_zone_name, opt_zone_id;
std::string zonegroup_name, zonegroup_id, zonegroup_new_name;
std::optional<string> opt_zonegroup_name, opt_zonegroup_id;
std::string api_name;
std::string role_name, path, assume_role_doc, policy_name, perm_policy_doc, path_prefix, max_session_duration;
std::string redirect_zone;
bool redirect_zone_set = false;
list<string> endpoints;
int tmp_int;
int sync_from_all_specified = false;
bool sync_from_all = false;
list<string> sync_from;
list<string> sync_from_rm;
int is_master_int;
int set_default = 0;
bool is_master = false;
bool is_master_set = false;
int read_only_int;
bool read_only = false;
int is_read_only_set = false;
int commit = false;
int staging = false;
int key_type = KEY_TYPE_UNDEFINED;
std::unique_ptr<rgw::sal::Bucket> bucket;
uint32_t perm_mask = 0;
RGWUserInfo info;
OPT opt_cmd = OPT::NO_CMD;
int gen_access_key = 0;
int gen_secret_key = 0;
bool set_perm = false;
bool set_temp_url_key = false;
map<int, string> temp_url_keys;
string bucket_id;
string new_bucket_name;
std::unique_ptr<Formatter> formatter;
std::unique_ptr<Formatter> zone_formatter;
int purge_data = false;
int pretty_format = false;
int show_log_entries = true;
int show_log_sum = true;
int skip_zero_entries = false; // log show
int purge_keys = false;
int yes_i_really_mean_it = false;
int delete_child_objects = false;
int fix = false;
int remove_bad = false;
int check_head_obj_locator = false;
int max_buckets = -1;
bool max_buckets_specified = false;
map<string, bool> categories;
string caps;
int check_objects = false;
RGWBucketAdminOpState bucket_op;
string infile;
string metadata_key;
RGWObjVersionTracker objv_tracker;
string marker;
string start_marker;
string end_marker;
int max_entries = -1;
bool max_entries_specified = false;
int admin = false;
bool admin_specified = false;
int system = false;
bool system_specified = false;
int shard_id = -1;
bool specified_shard_id = false;
string client_id;
string op_id;
string op_mask_str;
string quota_scope;
string ratelimit_scope;
std::string objects_file;
string object_version;
string placement_id;
std::optional<string> opt_storage_class;
list<string> tags;
list<string> tags_add;
list<string> tags_rm;
int placement_inline_data = true;
bool placement_inline_data_specified = false;
int64_t max_objects = -1;
int64_t max_size = -1;
int64_t max_read_ops = 0;
int64_t max_write_ops = 0;
int64_t max_read_bytes = 0;
int64_t max_write_bytes = 0;
bool have_max_objects = false;
bool have_max_size = false;
bool have_max_write_ops = false;
bool have_max_read_ops = false;
bool have_max_write_bytes = false;
bool have_max_read_bytes = false;
int include_all = false;
int allow_unordered = false;
int sync_stats = false;
int reset_stats = false;
int bypass_gc = false;
int warnings_only = false;
int inconsistent_index = false;
int verbose = false;
int extra_info = false;
uint64_t min_rewrite_size = 4 * 1024 * 1024;
uint64_t max_rewrite_size = ULLONG_MAX;
uint64_t min_rewrite_stripe_size = 0;
BIIndexType bi_index_type = BIIndexType::Plain;
std::optional<log_type> opt_log_type;
string job_id;
int num_shards = 0;
bool num_shards_specified = false;
std::optional<int> bucket_index_max_shards;
int max_concurrent_ios = 32;
uint64_t orphan_stale_secs = (24 * 3600);
int detail = false;
std::string val;
std::ostringstream errs;
string err;
string source_zone_name;
rgw_zone_id source_zone; /* zone id */
string tier_type;
bool tier_type_specified = false;
map<string, string, ltstr_nocase> tier_config_add;
map<string, string, ltstr_nocase> tier_config_rm;
boost::optional<string> index_pool;
boost::optional<string> data_pool;
boost::optional<string> data_extra_pool;
rgw::BucketIndexType placement_index_type = rgw::BucketIndexType::Normal;
bool index_type_specified = false;
boost::optional<std::string> compression_type;
string totp_serial;
string totp_seed;
string totp_seed_type = "hex";
vector<string> totp_pin;
int totp_seconds = 0;
int totp_window = 0;
int trim_delay_ms = 0;
string topic_name;
string notification_id;
string sub_name;
string event_id;
std::optional<uint64_t> gen;
std::optional<std::string> str_script_ctx;
std::optional<std::string> script_package;
int allow_compilation = false;
std::optional<string> opt_group_id;
std::optional<string> opt_status;
std::optional<string> opt_flow_type;
std::optional<vector<string> > opt_zone_names;
std::optional<vector<rgw_zone_id> > opt_zone_ids;
std::optional<string> opt_flow_id;
std::optional<string> opt_source_zone_name;
std::optional<rgw_zone_id> opt_source_zone_id;
std::optional<string> opt_dest_zone_name;
std::optional<rgw_zone_id> opt_dest_zone_id;
std::optional<vector<string> > opt_source_zone_names;
std::optional<vector<rgw_zone_id> > opt_source_zone_ids;
std::optional<vector<string> > opt_dest_zone_names;
std::optional<vector<rgw_zone_id> > opt_dest_zone_ids;
std::optional<string> opt_pipe_id;
std::optional<rgw_bucket> opt_bucket;
std::optional<string> opt_tenant;
std::optional<string> opt_bucket_name;
std::optional<string> opt_bucket_id;
std::optional<rgw_bucket> opt_source_bucket;
std::optional<string> opt_source_tenant;
std::optional<string> opt_source_bucket_name;
std::optional<string> opt_source_bucket_id;
std::optional<rgw_bucket> opt_dest_bucket;
std::optional<string> opt_dest_tenant;
std::optional<string> opt_dest_bucket_name;
std::optional<string> opt_dest_bucket_id;
std::optional<string> opt_effective_zone_name;
std::optional<rgw_zone_id> opt_effective_zone_id;
std::optional<string> opt_prefix;
std::optional<string> opt_prefix_rm;
std::optional<int> opt_priority;
std::optional<string> opt_mode;
std::optional<rgw_user> opt_dest_owner;
ceph::timespan opt_retry_delay_ms = std::chrono::milliseconds(2000);
ceph::timespan opt_timeout_sec = std::chrono::seconds(60);
std::optional<std::string> inject_error_at;
std::optional<int> inject_error_code;
std::optional<std::string> inject_abort_at;
rgw::zone_features::set enable_features;
rgw::zone_features::set disable_features;
SimpleCmd cmd(all_cmds, cmd_aliases);
bool raw_storage_op = false;
std::optional<std::string> rgw_obj_fs; // radoslist field separator
init_realm_param(cct.get(), realm_id, opt_realm_id, "rgw_realm_id");
init_realm_param(cct.get(), zonegroup_id, opt_zonegroup_id, "rgw_zonegroup_id");
init_realm_param(cct.get(), zone_id, opt_zone_id, "rgw_zone_id");
for (std::vector<const char*>::iterator i = args.begin(); i != args.end(); ) {
if (ceph_argparse_double_dash(args, i)) {
break;
} else if (ceph_argparse_witharg(args, i, &val, "-i", "--uid", (char*)NULL)) {
user_id_arg.from_str(val);
if (user_id_arg.empty()) {
cerr << "no value for uid" << std::endl;
exit(1);
}
} else if (ceph_argparse_witharg(args, i, &val, "--new-uid", (char*)NULL)) {
new_user_id.from_str(val);
} else if (ceph_argparse_witharg(args, i, &val, "--tenant", (char*)NULL)) {
tenant = val;
opt_tenant = val;
} else if (ceph_argparse_witharg(args, i, &val, "--user_ns", (char*)NULL)) {
user_ns = val;
} else if (ceph_argparse_witharg(args, i, &val, "--access-key", (char*)NULL)) {
access_key = val;
} else if (ceph_argparse_witharg(args, i, &val, "--subuser", (char*)NULL)) {
subuser = val;
} else if (ceph_argparse_witharg(args, i, &val, "--secret", "--secret-key", (char*)NULL)) {
secret_key = val;
} else if (ceph_argparse_witharg(args, i, &val, "-e", "--email", (char*)NULL)) {
user_email = val;
} else if (ceph_argparse_witharg(args, i, &val, "-n", "--display-name", (char*)NULL)) {
display_name = val;
} else if (ceph_argparse_witharg(args, i, &val, "-b", "--bucket", (char*)NULL)) {
bucket_name = val;
opt_bucket_name = val;
} else if (ceph_argparse_witharg(args, i, &val, "-p", "--pool", (char*)NULL)) {
pool_name = val;
pool = rgw_pool(pool_name);
} else if (ceph_argparse_witharg(args, i, &val, "-o", "--object", (char*)NULL)) {
object = val;
} else if (ceph_argparse_witharg(args, i, &val, "--objects-file", (char*)NULL)) {
objects_file = val;
} else if (ceph_argparse_witharg(args, i, &val, "--object-version", (char*)NULL)) {
object_version = val;
} else if (ceph_argparse_witharg(args, i, &val, "--client-id", (char*)NULL)) {
client_id = val;
} else if (ceph_argparse_witharg(args, i, &val, "--op-id", (char*)NULL)) {
op_id = val;
} else if (ceph_argparse_witharg(args, i, &val, "--op-mask", (char*)NULL)) {
op_mask_str = val;
} else if (ceph_argparse_witharg(args, i, &val, "--key-type", (char*)NULL)) {
key_type_str = val;
if (key_type_str.compare("swift") == 0) {
key_type = KEY_TYPE_SWIFT;
} else if (key_type_str.compare("s3") == 0) {
key_type = KEY_TYPE_S3;
} else {
cerr << "bad key type: " << key_type_str << std::endl;
exit(1);
}
} else if (ceph_argparse_witharg(args, i, &val, "--job-id", (char*)NULL)) {
job_id = val;
} else if (ceph_argparse_binary_flag(args, i, &gen_access_key, NULL, "--gen-access-key", (char*)NULL)) {
// do nothing
} else if (ceph_argparse_binary_flag(args, i, &gen_secret_key, NULL, "--gen-secret", (char*)NULL)) {
// do nothing
} else if (ceph_argparse_binary_flag(args, i, &show_log_entries, NULL, "--show-log-entries", (char*)NULL)) {
// do nothing
} else if (ceph_argparse_binary_flag(args, i, &show_log_sum, NULL, "--show-log-sum", (char*)NULL)) {
// do nothing
} else if (ceph_argparse_binary_flag(args, i, &skip_zero_entries, NULL, "--skip-zero-entries", (char*)NULL)) {
// do nothing
} else if (ceph_argparse_binary_flag(args, i, &admin, NULL, "--admin", (char*)NULL)) {
admin_specified = true;
} else if (ceph_argparse_binary_flag(args, i, &system, NULL, "--system", (char*)NULL)) {
system_specified = true;
} else if (ceph_argparse_binary_flag(args, i, &verbose, NULL, "--verbose", (char*)NULL)) {
// do nothing
} else if (ceph_argparse_binary_flag(args, i, &staging, NULL, "--staging", (char*)NULL)) {
// do nothing
} else if (ceph_argparse_binary_flag(args, i, &commit, NULL, "--commit", (char*)NULL)) {
// do nothing
} else if (ceph_argparse_witharg(args, i, &val, "--min-rewrite-size", (char*)NULL)) {
min_rewrite_size = (uint64_t)atoll(val.c_str());
} else if (ceph_argparse_witharg(args, i, &val, "--max-rewrite-size", (char*)NULL)) {
max_rewrite_size = (uint64_t)atoll(val.c_str());
} else if (ceph_argparse_witharg(args, i, &val, "--min-rewrite-stripe-size", (char*)NULL)) {
min_rewrite_stripe_size = (uint64_t)atoll(val.c_str());
} else if (ceph_argparse_witharg(args, i, &val, "--max-buckets", (char*)NULL)) {
max_buckets = (int)strict_strtol(val.c_str(), 10, &err);
if (!err.empty()) {
cerr << "ERROR: failed to parse max buckets: " << err << std::endl;
return EINVAL;
}
max_buckets_specified = true;
} else if (ceph_argparse_witharg(args, i, &val, "--max-entries", (char*)NULL)) {
max_entries = (int)strict_strtol(val.c_str(), 10, &err);
max_entries_specified = true;
if (!err.empty()) {
cerr << "ERROR: failed to parse max entries: " << err << std::endl;
return EINVAL;
}
} else if (ceph_argparse_witharg(args, i, &val, "--max-size", (char*)NULL)) {
max_size = strict_iec_cast<long long>(val, &err);
if (!err.empty()) {
cerr << "ERROR: failed to parse max size: " << err << std::endl;
return EINVAL;
}
have_max_size = true;
} else if (ceph_argparse_witharg(args, i, &val, "--max-objects", (char*)NULL)) {
max_objects = (int64_t)strict_strtoll(val.c_str(), 10, &err);
if (!err.empty()) {
cerr << "ERROR: failed to parse max objects: " << err << std::endl;
return EINVAL;
}
have_max_objects = true;
} else if (ceph_argparse_witharg(args, i, &val, "--max-read-ops", (char*)NULL)) {
max_read_ops = (int64_t)strict_strtoll(val.c_str(), 10, &err);
if (!err.empty()) {
cerr << "ERROR: failed to parse max read requests: " << err << std::endl;
return EINVAL;
}
have_max_read_ops = true;
} else if (ceph_argparse_witharg(args, i, &val, "--max-write-ops", (char*)NULL)) {
max_write_ops = (int64_t)strict_strtoll(val.c_str(), 10, &err);
if (!err.empty()) {
cerr << "ERROR: failed to parse max write requests: " << err << std::endl;
return EINVAL;
}
have_max_write_ops = true;
} else if (ceph_argparse_witharg(args, i, &val, "--max-read-bytes", (char*)NULL)) {
max_read_bytes = (int64_t)strict_strtoll(val.c_str(), 10, &err);
if (!err.empty()) {
cerr << "ERROR: failed to parse max read bytes: " << err << std::endl;
return EINVAL;
}
have_max_read_bytes = true;
} else if (ceph_argparse_witharg(args, i, &val, "--max-write-bytes", (char*)NULL)) {
max_write_bytes = (int64_t)strict_strtoll(val.c_str(), 10, &err);
if (!err.empty()) {
cerr << "ERROR: failed to parse max write bytes: " << err << std::endl;
return EINVAL;
}
have_max_write_bytes = true;
} else if (ceph_argparse_witharg(args, i, &val, "--date", "--time", (char*)NULL)) {
date = val;
if (end_date.empty())
end_date = date;
} else if (ceph_argparse_witharg(args, i, &val, "--start-date", "--start-time", (char*)NULL)) {
start_date = val;
} else if (ceph_argparse_witharg(args, i, &val, "--end-date", "--end-time", (char*)NULL)) {
end_date = val;
} else if (ceph_argparse_witharg(args, i, &val, "--num-shards", (char*)NULL)) {
num_shards = (int)strict_strtol(val.c_str(), 10, &err);
if (!err.empty()) {
cerr << "ERROR: failed to parse num shards: " << err << std::endl;
return EINVAL;
}
num_shards_specified = true;
} else if (ceph_argparse_witharg(args, i, &val, "--bucket-index-max-shards", (char*)NULL)) {
bucket_index_max_shards = (int)strict_strtol(val.c_str(), 10, &err);
if (!err.empty()) {
cerr << "ERROR: failed to parse bucket-index-max-shards: " << err << std::endl;
return EINVAL;
}
} else if (ceph_argparse_witharg(args, i, &val, "--max-concurrent-ios", (char*)NULL)) {
max_concurrent_ios = (int)strict_strtol(val.c_str(), 10, &err);
if (!err.empty()) {
cerr << "ERROR: failed to parse max concurrent ios: " << err << std::endl;
return EINVAL;
}
} else if (ceph_argparse_witharg(args, i, &val, "--orphan-stale-secs", (char*)NULL)) {
orphan_stale_secs = (uint64_t)strict_strtoll(val.c_str(), 10, &err);
if (!err.empty()) {
cerr << "ERROR: failed to parse orphan stale secs: " << err << std::endl;
return EINVAL;
}
} else if (ceph_argparse_witharg(args, i, &val, "--shard-id", (char*)NULL)) {
shard_id = (int)strict_strtol(val.c_str(), 10, &err);
if (!err.empty()) {
cerr << "ERROR: failed to parse shard id: " << err << std::endl;
return EINVAL;
}
specified_shard_id = true;
} else if (ceph_argparse_witharg(args, i, &val, "--gen", (char*)NULL)) {
gen = strict_strtoll(val.c_str(), 10, &err);
if (!err.empty()) {
cerr << "ERROR: failed to parse gen id: " << err << std::endl;
return EINVAL;
}
} else if (ceph_argparse_witharg(args, i, &val, "--access", (char*)NULL)) {
access = val;
perm_mask = rgw_str_to_perm(access.c_str());
set_perm = true;
} else if (ceph_argparse_witharg(args, i, &val, "--temp-url-key", (char*)NULL)) {
temp_url_keys[0] = val;
set_temp_url_key = true;
} else if (ceph_argparse_witharg(args, i, &val, "--temp-url-key2", "--temp-url-key-2", (char*)NULL)) {
temp_url_keys[1] = val;
set_temp_url_key = true;
} else if (ceph_argparse_witharg(args, i, &val, "--bucket-id", (char*)NULL)) {
bucket_id = val;
opt_bucket_id = val;
if (bucket_id.empty()) {
cerr << "no value for bucket-id" << std::endl;
exit(1);
}
} else if (ceph_argparse_witharg(args, i, &val, "--bucket-new-name", (char*)NULL)) {
new_bucket_name = val;
} else if (ceph_argparse_witharg(args, i, &val, "--format", (char*)NULL)) {
format = val;
} else if (ceph_argparse_witharg(args, i, &val, "--categories", (char*)NULL)) {
string cat_str = val;
list<string> cat_list;
list<string>::iterator iter;
get_str_list(cat_str, cat_list);
for (iter = cat_list.begin(); iter != cat_list.end(); ++iter) {
categories[*iter] = true;
}
} else if (ceph_argparse_binary_flag(args, i, &delete_child_objects, NULL, "--purge-objects", (char*)NULL)) {
// do nothing
} else if (ceph_argparse_binary_flag(args, i, &pretty_format, NULL, "--pretty-format", (char*)NULL)) {
// do nothing
} else if (ceph_argparse_binary_flag(args, i, &purge_data, NULL, "--purge-data", (char*)NULL)) {
delete_child_objects = purge_data;
} else if (ceph_argparse_binary_flag(args, i, &purge_keys, NULL, "--purge-keys", (char*)NULL)) {
// do nothing
} else if (ceph_argparse_binary_flag(args, i, &yes_i_really_mean_it, NULL, "--yes-i-really-mean-it", (char*)NULL)) {
// do nothing
} else if (ceph_argparse_binary_flag(args, i, &fix, NULL, "--fix", (char*)NULL)) {
// do nothing
} else if (ceph_argparse_binary_flag(args, i, &remove_bad, NULL, "--remove-bad", (char*)NULL)) {
// do nothing
} else if (ceph_argparse_binary_flag(args, i, &check_head_obj_locator, NULL, "--check-head-obj-locator", (char*)NULL)) {
// do nothing
} else if (ceph_argparse_binary_flag(args, i, &check_objects, NULL, "--check-objects", (char*)NULL)) {
// do nothing
} else if (ceph_argparse_binary_flag(args, i, &sync_stats, NULL, "--sync-stats", (char*)NULL)) {
// do nothing
} else if (ceph_argparse_binary_flag(args, i, &reset_stats, NULL, "--reset-stats", (char*)NULL)) {
// do nothing
} else if (ceph_argparse_binary_flag(args, i, &include_all, NULL, "--include-all", (char*)NULL)) {
// do nothing
} else if (ceph_argparse_binary_flag(args, i, &allow_unordered, NULL, "--allow-unordered", (char*)NULL)) {
// do nothing
} else if (ceph_argparse_binary_flag(args, i, &extra_info, NULL, "--extra-info", (char*)NULL)) {
// do nothing
} else if (ceph_argparse_binary_flag(args, i, &bypass_gc, NULL, "--bypass-gc", (char*)NULL)) {
// do nothing
} else if (ceph_argparse_binary_flag(args, i, &warnings_only, NULL, "--warnings-only", (char*)NULL)) {
// do nothing
} else if (ceph_argparse_binary_flag(args, i, &inconsistent_index, NULL, "--inconsistent-index", (char*)NULL)) {
// do nothing
} else if (ceph_argparse_binary_flag(args, i, &placement_inline_data, NULL, "--placement-inline-data", (char*)NULL)) {
placement_inline_data_specified = true;
// do nothing
} else if (ceph_argparse_witharg(args, i, &val, "--caps", (char*)NULL)) {
caps = val;
} else if (ceph_argparse_witharg(args, i, &val, "--infile", (char*)NULL)) {
infile = val;
} else if (ceph_argparse_witharg(args, i, &val, "--metadata-key", (char*)NULL)) {
metadata_key = val;
} else if (ceph_argparse_witharg(args, i, &val, "--marker", (char*)NULL)) {
marker = val;
} else if (ceph_argparse_witharg(args, i, &val, "--start-marker", (char*)NULL)) {
start_marker = val;
} else if (ceph_argparse_witharg(args, i, &val, "--end-marker", (char*)NULL)) {
end_marker = val;
} else if (ceph_argparse_witharg(args, i, &val, "--quota-scope", (char*)NULL)) {
quota_scope = val;
} else if (ceph_argparse_witharg(args, i, &val, "--ratelimit-scope", (char*)NULL)) {
ratelimit_scope = val;
} else if (ceph_argparse_witharg(args, i, &val, "--index-type", (char*)NULL)) {
string index_type_str = val;
bi_index_type = get_bi_index_type(index_type_str);
if (bi_index_type == BIIndexType::Invalid) {
cerr << "ERROR: invalid bucket index entry type" << std::endl;
return EINVAL;
}
} else if (ceph_argparse_witharg(args, i, &val, "--log-type", (char*)NULL)) {
string log_type_str = val;
auto l = get_log_type(log_type_str);
if (l == static_cast<log_type>(0xff)) {
cerr << "ERROR: invalid log type" << std::endl;
return EINVAL;
}
opt_log_type = l;
} else if (ceph_argparse_binary_flag(args, i, &is_master_int, NULL, "--master", (char*)NULL)) {
is_master = (bool)is_master_int;
is_master_set = true;
} else if (ceph_argparse_binary_flag(args, i, &set_default, NULL, "--default", (char*)NULL)) {
/* do nothing */
} else if (ceph_argparse_witharg(args, i, &val, "--redirect-zone", (char*)NULL)) {
redirect_zone = val;
redirect_zone_set = true;
} else if (ceph_argparse_binary_flag(args, i, &read_only_int, NULL, "--read-only", (char*)NULL)) {
read_only = (bool)read_only_int;
is_read_only_set = true;
} else if (ceph_argparse_witharg(args, i, &val, "--master-zone", (char*)NULL)) {
master_zone = val;
} else if (ceph_argparse_witharg(args, i, &val, "--period", (char*)NULL)) {
period_id = val;
} else if (ceph_argparse_witharg(args, i, &val, "--epoch", (char*)NULL)) {
period_epoch = val;
} else if (ceph_argparse_witharg(args, i, &val, "--remote", (char*)NULL)) {
remote = val;
} else if (ceph_argparse_witharg(args, i, &val, "--url", (char*)NULL)) {
url = val;
} else if (ceph_argparse_witharg(args, i, &val, "--region", (char*)NULL)) {
opt_region = val;
} else if (ceph_argparse_witharg(args, i, &val, "--realm-id", (char*)NULL)) {
realm_id = val;
opt_realm_id = val;
g_conf().set_val("rgw_realm_id", val);
} else if (ceph_argparse_witharg(args, i, &val, "--realm-new-name", (char*)NULL)) {
realm_new_name = val;
} else if (ceph_argparse_witharg(args, i, &val, "--zonegroup-id", (char*)NULL)) {
zonegroup_id = val;
opt_zonegroup_id = val;
g_conf().set_val("rgw_zonegroup_id", val);
} else if (ceph_argparse_witharg(args, i, &val, "--zonegroup-new-name", (char*)NULL)) {
zonegroup_new_name = val;
} else if (ceph_argparse_witharg(args, i, &val, "--placement-id", (char*)NULL)) {
placement_id = val;
} else if (ceph_argparse_witharg(args, i, &val, "--storage-class", (char*)NULL)) {
opt_storage_class = val;
} else if (ceph_argparse_witharg(args, i, &val, "--tags", (char*)NULL)) {
get_str_list(val, ",", tags);
} else if (ceph_argparse_witharg(args, i, &val, "--tags-add", (char*)NULL)) {
get_str_list(val, ",", tags_add);
} else if (ceph_argparse_witharg(args, i, &val, "--tags-rm", (char*)NULL)) {
get_str_list(val, ",", tags_rm);
} else if (ceph_argparse_witharg(args, i, &val, "--api-name", (char*)NULL)) {
api_name = val;
} else if (ceph_argparse_witharg(args, i, &val, "--zone-id", (char*)NULL)) {
zone_id = val;
opt_zone_id = val;
g_conf().set_val("rgw_zone_id", val);
} else if (ceph_argparse_witharg(args, i, &val, "--zone-new-name", (char*)NULL)) {
zone_new_name = val;
} else if (ceph_argparse_witharg(args, i, &val, "--endpoints", (char*)NULL)) {
get_str_list(val, endpoints);
} else if (ceph_argparse_witharg(args, i, &val, "--sync-from", (char*)NULL)) {
get_str_list(val, sync_from);
} else if (ceph_argparse_witharg(args, i, &val, "--sync-from-rm", (char*)NULL)) {
get_str_list(val, sync_from_rm);
} else if (ceph_argparse_binary_flag(args, i, &tmp_int, NULL, "--sync-from-all", (char*)NULL)) {
sync_from_all = (bool)tmp_int;
sync_from_all_specified = true;
} else if (ceph_argparse_witharg(args, i, &val, "--source-zone", (char*)NULL)) {
source_zone_name = val;
opt_source_zone_name = val;
} else if (ceph_argparse_witharg(args, i, &val, "--source-zone-id", (char*)NULL)) {
opt_source_zone_id = val;
} else if (ceph_argparse_witharg(args, i, &val, "--dest-zone", (char*)NULL)) {
opt_dest_zone_name = val;
} else if (ceph_argparse_witharg(args, i, &val, "--dest-zone-id", (char*)NULL)) {
opt_dest_zone_id = val;
} else if (ceph_argparse_witharg(args, i, &val, "--tier-type", (char*)NULL)) {
tier_type = val;
tier_type_specified = true;
} else if (ceph_argparse_witharg(args, i, &val, "--tier-config", (char*)NULL)) {
parse_tier_config_param(val, tier_config_add);
} else if (ceph_argparse_witharg(args, i, &val, "--tier-config-rm", (char*)NULL)) {
parse_tier_config_param(val, tier_config_rm);
} else if (ceph_argparse_witharg(args, i, &val, "--index-pool", (char*)NULL)) {
index_pool = val;
} else if (ceph_argparse_witharg(args, i, &val, "--data-pool", (char*)NULL)) {
data_pool = val;
} else if (ceph_argparse_witharg(args, i, &val, "--data-extra-pool", (char*)NULL)) {
data_extra_pool = val;
} else if (ceph_argparse_witharg(args, i, &val, "--placement-index-type", (char*)NULL)) {
if (val == "normal") {
placement_index_type = rgw::BucketIndexType::Normal;
} else if (val == "indexless") {
placement_index_type = rgw::BucketIndexType::Indexless;
} else {
placement_index_type = (rgw::BucketIndexType)strict_strtol(val.c_str(), 10, &err);
if (!err.empty()) {
cerr << "ERROR: failed to parse index type index: " << err << std::endl;
return EINVAL;
}
}
index_type_specified = true;
} else if (ceph_argparse_witharg(args, i, &val, "--compression", (char*)NULL)) {
compression_type = val;
} else if (ceph_argparse_witharg(args, i, &val, "--role-name", (char*)NULL)) {
role_name = val;
} else if (ceph_argparse_witharg(args, i, &val, "--path", (char*)NULL)) {
path = val;
} else if (ceph_argparse_witharg(args, i, &val, "--assume-role-policy-doc", (char*)NULL)) {
assume_role_doc = val;
} else if (ceph_argparse_witharg(args, i, &val, "--policy-name", (char*)NULL)) {
policy_name = val;
} else if (ceph_argparse_witharg(args, i, &val, "--policy-doc", (char*)NULL)) {
perm_policy_doc = val;
} else if (ceph_argparse_witharg(args, i, &val, "--path-prefix", (char*)NULL)) {
path_prefix = val;
} else if (ceph_argparse_witharg(args, i, &val, "--max-session-duration", (char*)NULL)) {
max_session_duration = val;
} else if (ceph_argparse_witharg(args, i, &val, "--totp-serial", (char*)NULL)) {
totp_serial = val;
} else if (ceph_argparse_witharg(args, i, &val, "--totp-pin", (char*)NULL)) {
totp_pin.push_back(val);
} else if (ceph_argparse_witharg(args, i, &val, "--totp-seed", (char*)NULL)) {
totp_seed = val;
} else if (ceph_argparse_witharg(args, i, &val, "--totp-seed-type", (char*)NULL)) {
totp_seed_type = val;
} else if (ceph_argparse_witharg(args, i, &val, "--totp-seconds", (char*)NULL)) {
totp_seconds = atoi(val.c_str());
} else if (ceph_argparse_witharg(args, i, &val, "--totp-window", (char*)NULL)) {
totp_window = atoi(val.c_str());
} else if (ceph_argparse_witharg(args, i, &val, "--trim-delay-ms", (char*)NULL)) {
trim_delay_ms = atoi(val.c_str());
} else if (ceph_argparse_witharg(args, i, &val, "--topic", (char*)NULL)) {
topic_name = val;
} else if (ceph_argparse_witharg(args, i, &val, "--notification-id", (char*)NULL)) {
notification_id = val;
} else if (ceph_argparse_witharg(args, i, &val, "--subscription", (char*)NULL)) {
sub_name = val;
} else if (ceph_argparse_witharg(args, i, &val, "--event-id", (char*)NULL)) {
event_id = val;
} else if (ceph_argparse_witharg(args, i, &val, "--group-id", (char*)NULL)) {
opt_group_id = val;
} else if (ceph_argparse_witharg(args, i, &val, "--status", (char*)NULL)) {
opt_status = val;
} else if (ceph_argparse_witharg(args, i, &val, "--flow-type", (char*)NULL)) {
opt_flow_type = val;
} else if (ceph_argparse_witharg(args, i, &val, "--zones", "--zone-names", (char*)NULL)) {
vector<string> v;
get_str_vec(val, v);
opt_zone_names = std::move(v);
} else if (ceph_argparse_witharg(args, i, &val, "--zone-ids", (char*)NULL)) {
opt_zone_ids = zone_ids_from_str(val);
} else if (ceph_argparse_witharg(args, i, &val, "--source-zones", "--source-zone-names", (char*)NULL)) {
vector<string> v;
get_str_vec(val, v);
opt_source_zone_names = std::move(v);
} else if (ceph_argparse_witharg(args, i, &val, "--source-zone-ids", (char*)NULL)) {
opt_source_zone_ids = zone_ids_from_str(val);
} else if (ceph_argparse_witharg(args, i, &val, "--dest-zones", "--dest-zone-names", (char*)NULL)) {
vector<string> v;
get_str_vec(val, v);
opt_dest_zone_names = std::move(v);
} else if (ceph_argparse_witharg(args, i, &val, "--dest-zone-ids", (char*)NULL)) {
opt_dest_zone_ids = zone_ids_from_str(val);
} else if (ceph_argparse_witharg(args, i, &val, "--flow-id", (char*)NULL)) {
opt_flow_id = val;
} else if (ceph_argparse_witharg(args, i, &val, "--pipe-id", (char*)NULL)) {
opt_pipe_id = val;
} else if (ceph_argparse_witharg(args, i, &val, "--source-tenant", (char*)NULL)) {
opt_source_tenant = val;
} else if (ceph_argparse_witharg(args, i, &val, "--source-bucket", (char*)NULL)) {
opt_source_bucket_name = val;
} else if (ceph_argparse_witharg(args, i, &val, "--source-bucket-id", (char*)NULL)) {
opt_source_bucket_id = val;
} else if (ceph_argparse_witharg(args, i, &val, "--dest-tenant", (char*)NULL)) {
opt_dest_tenant = val;
} else if (ceph_argparse_witharg(args, i, &val, "--dest-bucket", (char*)NULL)) {
opt_dest_bucket_name = val;
} else if (ceph_argparse_witharg(args, i, &val, "--dest-bucket-id", (char*)NULL)) {
opt_dest_bucket_id = val;
} else if (ceph_argparse_witharg(args, i, &val, "--effective-zone-name", "--effective-zone", (char*)NULL)) {
opt_effective_zone_name = val;
} else if (ceph_argparse_witharg(args, i, &val, "--effective-zone-id", (char*)NULL)) {
opt_effective_zone_id = rgw_zone_id(val);
} else if (ceph_argparse_witharg(args, i, &val, "--prefix", (char*)NULL)) {
opt_prefix = val;
} else if (ceph_argparse_witharg(args, i, &val, "--prefix-rm", (char*)NULL)) {
opt_prefix_rm = val;
} else if (ceph_argparse_witharg(args, i, &val, "--priority", (char*)NULL)) {
opt_priority = atoi(val.c_str());
} else if (ceph_argparse_witharg(args, i, &val, "--mode", (char*)NULL)) {
opt_mode = val;
} else if (ceph_argparse_witharg(args, i, &val, "--dest-owner", (char*)NULL)) {
opt_dest_owner.emplace(val);
opt_dest_owner = val;
} else if (ceph_argparse_witharg(args, i, &val, "--retry-delay-ms", (char*)NULL)) {
opt_retry_delay_ms = std::chrono::milliseconds(atoi(val.c_str()));
} else if (ceph_argparse_witharg(args, i, &val, "--timeout-sec", (char*)NULL)) {
opt_timeout_sec = std::chrono::seconds(atoi(val.c_str()));
} else if (ceph_argparse_witharg(args, i, &val, "--inject-error-at", (char*)NULL)) {
inject_error_at = val;
} else if (ceph_argparse_witharg(args, i, &val, "--inject-error-code", (char*)NULL)) {
inject_error_code = atoi(val.c_str());
} else if (ceph_argparse_witharg(args, i, &val, "--inject-abort-at", (char*)NULL)) {
inject_abort_at = val;
} else if (ceph_argparse_binary_flag(args, i, &detail, NULL, "--detail", (char*)NULL)) {
// do nothing
} else if (ceph_argparse_witharg(args, i, &val, "--context", (char*)NULL)) {
str_script_ctx = val;
} else if (ceph_argparse_witharg(args, i, &val, "--package", (char*)NULL)) {
script_package = val;
} else if (ceph_argparse_binary_flag(args, i, &allow_compilation, NULL, "--allow-compilation", (char*)NULL)) {
// do nothing
} else if (ceph_argparse_witharg(args, i, &val, "--rgw-obj-fs", (char*)NULL)) {
rgw_obj_fs = val;
} else if (ceph_argparse_witharg(args, i, &val, "--enable-feature", (char*)NULL)) {
if (!rgw::zone_features::supports(val)) {
std::cerr << "ERROR: Cannot enable unrecognized zone feature \"" << val << "\"" << std::endl;
return EINVAL;
}
enable_features.insert(val);
} else if (ceph_argparse_witharg(args, i, &val, "--disable-feature", (char*)NULL)) {
disable_features.insert(val);
} else if (strncmp(*i, "-", 1) == 0) {
cerr << "ERROR: invalid flag " << *i << std::endl;
return EINVAL;
} else {
++i;
}
}
/* common_init_finish needs to be called after g_conf().set_val() */
common_init_finish(g_ceph_context);
std::unique_ptr<rgw::sal::ConfigStore> cfgstore;
if (args.empty()) {
usage();
exit(1);
}
else {
std::vector<string> extra_args;
std::vector<string> expected;
std::any _opt_cmd;
if (!cmd.find_command(args, &_opt_cmd, &extra_args, &err, &expected)) {
if (!expected.empty()) {
cerr << err << std::endl;
cerr << "Expected one of the following:" << std::endl;
for (auto& exp : expected) {
if (exp == "*" || exp == "[*]") {
continue;
}
cerr << " " << exp << std::endl;
}
} else {
cerr << "Command not found:";
for (auto& arg : args) {
cerr << " " << arg;
}
cerr << std::endl;
}
exit(1);
}
opt_cmd = std::any_cast<OPT>(_opt_cmd);
/* some commands may have an optional extra param */
if (!extra_args.empty()) {
switch (opt_cmd) {
case OPT::METADATA_GET:
case OPT::METADATA_PUT:
case OPT::METADATA_RM:
case OPT::METADATA_LIST:
metadata_key = extra_args[0];
break;
default:
break;
}
}
// not a raw op if 'period update' needs to commit to master
bool raw_period_update = opt_cmd == OPT::PERIOD_UPDATE && !commit;
// not a raw op if 'period pull' needs to read zone/period configuration
bool raw_period_pull = opt_cmd == OPT::PERIOD_PULL && !url.empty();
std::set<OPT> raw_storage_ops_list = {OPT::ZONEGROUP_ADD, OPT::ZONEGROUP_CREATE,
OPT::ZONEGROUP_DELETE,
OPT::ZONEGROUP_GET, OPT::ZONEGROUP_LIST,
OPT::ZONEGROUP_SET, OPT::ZONEGROUP_DEFAULT,
OPT::ZONEGROUP_RENAME, OPT::ZONEGROUP_MODIFY,
OPT::ZONEGROUP_REMOVE,
OPT::ZONEGROUP_PLACEMENT_ADD, OPT::ZONEGROUP_PLACEMENT_RM,
OPT::ZONEGROUP_PLACEMENT_MODIFY, OPT::ZONEGROUP_PLACEMENT_LIST,
OPT::ZONEGROUP_PLACEMENT_GET,
OPT::ZONEGROUP_PLACEMENT_DEFAULT,
OPT::ZONE_CREATE, OPT::ZONE_DELETE,
OPT::ZONE_GET, OPT::ZONE_SET, OPT::ZONE_RENAME,
OPT::ZONE_LIST, OPT::ZONE_MODIFY, OPT::ZONE_DEFAULT,
OPT::ZONE_PLACEMENT_ADD, OPT::ZONE_PLACEMENT_RM,
OPT::ZONE_PLACEMENT_MODIFY, OPT::ZONE_PLACEMENT_LIST,
OPT::ZONE_PLACEMENT_GET,
OPT::REALM_CREATE,
OPT::PERIOD_DELETE, OPT::PERIOD_GET,
OPT::PERIOD_GET_CURRENT, OPT::PERIOD_LIST,
OPT::GLOBAL_QUOTA_GET, OPT::GLOBAL_QUOTA_SET,
OPT::GLOBAL_QUOTA_ENABLE, OPT::GLOBAL_QUOTA_DISABLE,
OPT::GLOBAL_RATELIMIT_GET, OPT::GLOBAL_RATELIMIT_SET,
OPT::GLOBAL_RATELIMIT_ENABLE, OPT::GLOBAL_RATELIMIT_DISABLE,
OPT::REALM_DELETE, OPT::REALM_GET, OPT::REALM_LIST,
OPT::REALM_LIST_PERIODS,
OPT::REALM_GET_DEFAULT,
OPT::REALM_RENAME, OPT::REALM_SET,
OPT::REALM_DEFAULT, OPT::REALM_PULL};
std::set<OPT> readonly_ops_list = {
OPT::USER_INFO,
OPT::USER_STATS,
OPT::BUCKETS_LIST,
OPT::BUCKET_LIMIT_CHECK,
OPT::BUCKET_LAYOUT,
OPT::BUCKET_STATS,
OPT::BUCKET_SYNC_CHECKPOINT,
OPT::BUCKET_SYNC_INFO,
OPT::BUCKET_SYNC_STATUS,
OPT::BUCKET_SYNC_MARKERS,
OPT::BUCKET_SHARD_OBJECTS,
OPT::BUCKET_OBJECT_SHARD,
OPT::LOG_LIST,
OPT::LOG_SHOW,
OPT::USAGE_SHOW,
OPT::OBJECT_STAT,
OPT::BI_GET,
OPT::BI_LIST,
OPT::OLH_GET,
OPT::OLH_READLOG,
OPT::GC_LIST,
OPT::LC_LIST,
OPT::ORPHANS_LIST_JOBS,
OPT::ZONEGROUP_GET,
OPT::ZONEGROUP_LIST,
OPT::ZONEGROUP_PLACEMENT_LIST,
OPT::ZONEGROUP_PLACEMENT_GET,
OPT::ZONE_GET,
OPT::ZONE_LIST,
OPT::ZONE_PLACEMENT_LIST,
OPT::ZONE_PLACEMENT_GET,
OPT::METADATA_GET,
OPT::METADATA_LIST,
OPT::METADATA_SYNC_STATUS,
OPT::MDLOG_LIST,
OPT::MDLOG_STATUS,
OPT::SYNC_ERROR_LIST,
OPT::SYNC_GROUP_GET,
OPT::SYNC_POLICY_GET,
OPT::BILOG_LIST,
OPT::BILOG_STATUS,
OPT::DATA_SYNC_STATUS,
OPT::DATALOG_LIST,
OPT::DATALOG_STATUS,
OPT::REALM_GET,
OPT::REALM_GET_DEFAULT,
OPT::REALM_LIST,
OPT::REALM_LIST_PERIODS,
OPT::PERIOD_GET,
OPT::PERIOD_GET_CURRENT,
OPT::PERIOD_LIST,
OPT::GLOBAL_QUOTA_GET,
OPT::GLOBAL_RATELIMIT_GET,
OPT::SYNC_INFO,
OPT::SYNC_STATUS,
OPT::ROLE_GET,
OPT::ROLE_LIST,
OPT::ROLE_POLICY_LIST,
OPT::ROLE_POLICY_GET,
OPT::RESHARD_LIST,
OPT::RESHARD_STATUS,
OPT::PUBSUB_TOPIC_LIST,
OPT::PUBSUB_NOTIFICATION_LIST,
OPT::PUBSUB_TOPIC_GET,
OPT::PUBSUB_NOTIFICATION_GET,
OPT::PUBSUB_TOPIC_STATS ,
OPT::SCRIPT_GET,
};
std::set<OPT> gc_ops_list = {
OPT::GC_LIST,
OPT::GC_PROCESS,
OPT::OBJECT_RM,
OPT::BUCKET_RM, // --purge-objects
OPT::USER_RM, // --purge-data
OPT::OBJECTS_EXPIRE,
OPT::OBJECTS_EXPIRE_STALE_RM,
OPT::LC_PROCESS,
OPT::BUCKET_SYNC_RUN,
OPT::DATA_SYNC_RUN,
OPT::BUCKET_REWRITE,
OPT::OBJECT_REWRITE
};
raw_storage_op = (raw_storage_ops_list.find(opt_cmd) != raw_storage_ops_list.end() ||
raw_period_update || raw_period_pull);
bool need_cache = readonly_ops_list.find(opt_cmd) == readonly_ops_list.end();
bool need_gc = (gc_ops_list.find(opt_cmd) != gc_ops_list.end()) && !bypass_gc;
DriverManager::Config cfg = DriverManager::get_config(true, g_ceph_context);
auto config_store_type = g_conf().get_val<std::string>("rgw_config_store");
cfgstore = DriverManager::create_config_store(dpp(), config_store_type);
if (!cfgstore) {
cerr << "couldn't init config storage provider" << std::endl;
return EIO;
}
if (raw_storage_op) {
driver = DriverManager::get_raw_storage(dpp(),
g_ceph_context,
cfg);
} else {
driver = DriverManager::get_storage(dpp(),
g_ceph_context,
cfg,
false,
false,
false,
false,
false,
false,
null_yield,
need_cache && g_conf()->rgw_cache_enabled,
need_gc);
}
if (!driver) {
cerr << "couldn't init storage provider" << std::endl;
return EIO;
}
/* Needs to be after the driver is initialized. Note, user could be empty here. */
user = driver->get_user(user_id_arg);
init_optional_bucket(opt_bucket, opt_tenant,
opt_bucket_name, opt_bucket_id);
init_optional_bucket(opt_source_bucket, opt_source_tenant,
opt_source_bucket_name, opt_source_bucket_id);
init_optional_bucket(opt_dest_bucket, opt_dest_tenant,
opt_dest_bucket_name, opt_dest_bucket_id);
if (tenant.empty()) {
tenant = user->get_tenant();
} else {
if (rgw::sal::User::empty(user) && opt_cmd != OPT::ROLE_CREATE
&& opt_cmd != OPT::ROLE_DELETE
&& opt_cmd != OPT::ROLE_GET
&& opt_cmd != OPT::ROLE_TRUST_POLICY_MODIFY
&& opt_cmd != OPT::ROLE_LIST
&& opt_cmd != OPT::ROLE_POLICY_PUT
&& opt_cmd != OPT::ROLE_POLICY_LIST
&& opt_cmd != OPT::ROLE_POLICY_GET
&& opt_cmd != OPT::ROLE_POLICY_DELETE
&& opt_cmd != OPT::ROLE_UPDATE
&& opt_cmd != OPT::RESHARD_ADD
&& opt_cmd != OPT::RESHARD_CANCEL
&& opt_cmd != OPT::RESHARD_STATUS
&& opt_cmd != OPT::PUBSUB_TOPIC_LIST
&& opt_cmd != OPT::PUBSUB_NOTIFICATION_LIST
&& opt_cmd != OPT::PUBSUB_TOPIC_GET
&& opt_cmd != OPT::PUBSUB_NOTIFICATION_GET
&& opt_cmd != OPT::PUBSUB_TOPIC_RM
&& opt_cmd != OPT::PUBSUB_NOTIFICATION_RM
&& opt_cmd != OPT::PUBSUB_TOPIC_STATS ) {
cerr << "ERROR: --tenant is set, but there's no user ID" << std::endl;
return EINVAL;
}
user->set_tenant(tenant);
}
if (user_ns.empty()) {
user_ns = user->get_id().ns;
} else {
user->set_ns(user_ns);
}
if (!new_user_id.empty() && !tenant.empty()) {
new_user_id.tenant = tenant;
}
/* check key parameter conflict */
if ((!access_key.empty()) && gen_access_key) {
cerr << "ERROR: key parameter conflict, --access-key & --gen-access-key" << std::endl;
return EINVAL;
}
if ((!secret_key.empty()) && gen_secret_key) {
cerr << "ERROR: key parameter conflict, --secret & --gen-secret" << std::endl;
return EINVAL;
}
}
// default to pretty json
if (format.empty()) {
format = "json";
pretty_format = true;
}
if (format == "xml")
formatter = make_unique<XMLFormatter>(pretty_format);
else if (format == "json")
formatter = make_unique<JSONFormatter>(pretty_format);
else {
cerr << "unrecognized format: " << format << std::endl;
exit(1);
}
zone_formatter = std::make_unique<JSONFormatter_PrettyZone>(pretty_format);
realm_name = g_conf()->rgw_realm;
zone_name = g_conf()->rgw_zone;
zonegroup_name = g_conf()->rgw_zonegroup;
if (!realm_name.empty()) {
opt_realm_name = realm_name;
}
if (!zone_name.empty()) {
opt_zone_name = zone_name;
}
if (!zonegroup_name.empty()) {
opt_zonegroup_name = zonegroup_name;
}
RGWStreamFlusher stream_flusher(formatter.get(), cout);
RGWUserAdminOpState user_op(driver);
if (!user_email.empty()) {
user_op.user_email_specified=true;
}
if (!source_zone_name.empty()) {
std::unique_ptr<rgw::sal::Zone> zone;
if (driver->get_zone()->get_zonegroup().get_zone_by_name(source_zone_name, &zone) < 0) {
cerr << "WARNING: cannot find source zone id for name=" << source_zone_name << std::endl;
source_zone = source_zone_name;
} else {
source_zone.id = zone->get_id();
}
}
rgw_http_client_init(g_ceph_context);
struct rgw_curl_setup {
rgw_curl_setup() {
rgw::curl::setup_curl(boost::none);
}
~rgw_curl_setup() {
rgw::curl::cleanup_curl();
}
} curl_cleanup;
oath_init();
StoreDestructor store_destructor(driver);
if (raw_storage_op) {
switch (opt_cmd) {
case OPT::PERIOD_DELETE:
{
if (period_id.empty()) {
cerr << "missing period id" << std::endl;
return EINVAL;
}
int ret = cfgstore->delete_period(dpp(), null_yield, period_id);
if (ret < 0) {
cerr << "ERROR: couldn't delete period: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
}
break;
case OPT::PERIOD_GET:
{
std::optional<epoch_t> epoch;
if (!period_epoch.empty()) {
epoch = atoi(period_epoch.c_str());
}
if (staging) {
RGWRealm realm;
int ret = rgw::read_realm(dpp(), null_yield, cfgstore.get(),
realm_id, realm_name, realm);
if (ret < 0 ) {
cerr << "failed to load realm: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
realm_id = realm.get_id();
realm_name = realm.get_name();
period_id = RGWPeriod::get_staging_id(realm_id);
epoch = 1;
}
if (period_id.empty()) {
// use realm's current period
RGWRealm realm;
int ret = rgw::read_realm(dpp(), null_yield, cfgstore.get(),
realm_id, realm_name, realm);
if (ret < 0 ) {
cerr << "failed to load realm: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
period_id = realm.current_period;
}
RGWPeriod period;
int ret = cfgstore->read_period(dpp(), null_yield, period_id,
epoch, period);
if (ret < 0) {
cerr << "failed to load period: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
encode_json("period", period, formatter.get());
formatter->flush(cout);
}
break;
case OPT::PERIOD_GET_CURRENT:
{
RGWRealm realm;
int ret = rgw::read_realm(dpp(), null_yield, cfgstore.get(),
realm_id, realm_name, realm);
if (ret < 0) {
std::cerr << "failed to load realm: " << cpp_strerror(ret) << std::endl;
return -ret;
}
formatter->open_object_section("period_get_current");
encode_json("current_period", realm.current_period, formatter.get());
formatter->close_section();
formatter->flush(cout);
}
break;
case OPT::PERIOD_LIST:
{
Formatter::ObjectSection periods_list{*formatter, "periods_list"};
Formatter::ArraySection periods{*formatter, "periods"};
rgw::sal::ListResult<std::string> listing;
std::array<std::string, 1000> period_ids; // list in pages of 1000
do {
int ret = cfgstore->list_period_ids(dpp(), null_yield, listing.next,
period_ids, listing);
if (ret < 0) {
std::cerr << "failed to list periods: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
for (const auto& id : listing.entries) {
encode_json("id", id, formatter.get());
}
} while (!listing.next.empty());
} // close sections periods and periods_list
formatter->flush(cout);
break;
case OPT::PERIOD_UPDATE:
{
int ret = update_period(cfgstore.get(), realm_id, realm_name,
period_epoch, commit, remote, url,
opt_region, access_key, secret_key,
formatter.get(), yes_i_really_mean_it);
if (ret < 0) {
return -ret;
}
}
break;
case OPT::PERIOD_PULL:
{
boost::optional<RGWRESTConn> conn;
RGWRESTConn *remote_conn = nullptr;
if (url.empty()) {
// load current period for endpoints
RGWRealm realm;
int ret = rgw::read_realm(dpp(), null_yield, cfgstore.get(),
realm_id, realm_name, realm);
if (ret < 0 ) {
cerr << "failed to load realm: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
period_id = realm.current_period;
RGWPeriod current_period;
ret = cfgstore->read_period(dpp(), null_yield, period_id,
std::nullopt, current_period);
if (ret < 0) {
cerr << "failed to load current period: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
if (remote.empty()) {
// use realm master zone as remote
remote = current_period.get_master_zone().id;
}
conn = get_remote_conn(static_cast<rgw::sal::RadosStore*>(driver), current_period.get_map(), remote);
if (!conn) {
cerr << "failed to find a zone or zonegroup for remote "
<< remote << std::endl;
return -ENOENT;
}
remote_conn = &*conn;
}
RGWPeriod period;
int ret = do_period_pull(cfgstore.get(), remote_conn, url,
opt_region, access_key, secret_key,
realm_id, realm_name, period_id, period_epoch,
&period);
if (ret < 0) {
cerr << "period pull failed: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
encode_json("period", period, formatter.get());
formatter->flush(cout);
}
break;
case OPT::GLOBAL_RATELIMIT_GET:
case OPT::GLOBAL_RATELIMIT_SET:
case OPT::GLOBAL_RATELIMIT_ENABLE:
case OPT::GLOBAL_RATELIMIT_DISABLE:
{
if (realm_id.empty()) {
if (!realm_name.empty()) {
// look up realm_id for the given realm_name
int ret = cfgstore->read_realm_id(dpp(), null_yield,
realm_name, realm_id);
if (ret < 0) {
cerr << "ERROR: failed to read realm for " << realm_name
<< ": " << cpp_strerror(-ret) << std::endl;
return -ret;
}
} else {
// use default realm_id when none is given
int ret = cfgstore->read_default_realm_id(dpp(), null_yield,
realm_id);
if (ret < 0 && ret != -ENOENT) { // on ENOENT, use empty realm_id
cerr << "ERROR: failed to read default realm: "
<< cpp_strerror(-ret) << std::endl;
return -ret;
}
}
}
RGWPeriodConfig period_config;
int ret = cfgstore->read_period_config(dpp(), null_yield, realm_id,
period_config);
if (ret < 0 && ret != -ENOENT) {
cerr << "ERROR: failed to read period config: "
<< cpp_strerror(-ret) << std::endl;
return -ret;
}
bool ratelimit_configured = true;
formatter->open_object_section("period_config");
if (ratelimit_scope == "bucket") {
ratelimit_configured = set_ratelimit_info(period_config.bucket_ratelimit, opt_cmd,
max_read_ops, max_write_ops,
max_read_bytes, max_write_bytes,
have_max_read_ops, have_max_write_ops,
have_max_read_bytes, have_max_write_bytes);
encode_json("bucket_ratelimit", period_config.bucket_ratelimit, formatter.get());
} else if (ratelimit_scope == "user") {
ratelimit_configured = set_ratelimit_info(period_config.user_ratelimit, opt_cmd,
max_read_ops, max_write_ops,
max_read_bytes, max_write_bytes,
have_max_read_ops, have_max_write_ops,
have_max_read_bytes, have_max_write_bytes);
encode_json("user_ratelimit", period_config.user_ratelimit, formatter.get());
} else if (ratelimit_scope == "anonymous") {
ratelimit_configured = set_ratelimit_info(period_config.anon_ratelimit, opt_cmd,
max_read_ops, max_write_ops,
max_read_bytes, max_write_bytes,
have_max_read_ops, have_max_write_ops,
have_max_read_bytes, have_max_write_bytes);
encode_json("anonymous_ratelimit", period_config.anon_ratelimit, formatter.get());
} else if (ratelimit_scope.empty() && opt_cmd == OPT::GLOBAL_RATELIMIT_GET) {
// if no scope is given for GET, print both
encode_json("bucket_ratelimit", period_config.bucket_ratelimit, formatter.get());
encode_json("user_ratelimit", period_config.user_ratelimit, formatter.get());
encode_json("anonymous_ratelimit", period_config.anon_ratelimit, formatter.get());
} else {
cerr << "ERROR: invalid rate limit scope specification. Please specify "
"either --ratelimit-scope=bucket, or --ratelimit-scope=user or --ratelimit-scope=anonymous" << std::endl;
return EINVAL;
}
if (!ratelimit_configured) {
cerr << "ERROR: no rate limit values have been specified" << std::endl;
return EINVAL;
}
formatter->close_section();
if (opt_cmd != OPT::GLOBAL_RATELIMIT_GET) {
// write the modified period config
constexpr bool exclusive = false;
ret = cfgstore->write_period_config(dpp(), null_yield, exclusive,
realm_id, period_config);
if (ret < 0) {
cerr << "ERROR: failed to write period config: "
<< cpp_strerror(-ret) << std::endl;
return -ret;
}
if (!realm_id.empty()) {
cout << "Global ratelimit changes saved. Use 'period update' to apply "
"them to the staging period, and 'period commit' to commit the "
"new period." << std::endl;
} else {
cout << "Global ratelimit changes saved. They will take effect as "
"the gateways are restarted." << std::endl;
}
}
formatter->flush(cout);
}
break;
case OPT::GLOBAL_QUOTA_GET:
case OPT::GLOBAL_QUOTA_SET:
case OPT::GLOBAL_QUOTA_ENABLE:
case OPT::GLOBAL_QUOTA_DISABLE:
{
if (realm_id.empty()) {
if (!realm_name.empty()) {
// look up realm_id for the given realm_name
int ret = cfgstore->read_realm_id(dpp(), null_yield,
realm_name, realm_id);
if (ret < 0) {
cerr << "ERROR: failed to read realm for " << realm_name
<< ": " << cpp_strerror(-ret) << std::endl;
return -ret;
}
} else {
// use default realm_id when none is given
int ret = cfgstore->read_default_realm_id(dpp(), null_yield,
realm_id);
if (ret < 0 && ret != -ENOENT) { // on ENOENT, use empty realm_id
cerr << "ERROR: failed to read default realm: "
<< cpp_strerror(-ret) << std::endl;
return -ret;
}
}
}
RGWPeriodConfig period_config;
int ret = cfgstore->read_period_config(dpp(), null_yield, realm_id,
period_config);
if (ret < 0 && ret != -ENOENT) {
cerr << "ERROR: failed to read period config: "
<< cpp_strerror(-ret) << std::endl;
return -ret;
}
formatter->open_object_section("period_config");
if (quota_scope == "bucket") {
set_quota_info(period_config.quota.bucket_quota, opt_cmd,
max_size, max_objects,
have_max_size, have_max_objects);
encode_json("bucket quota", period_config.quota.bucket_quota, formatter.get());
} else if (quota_scope == "user") {
set_quota_info(period_config.quota.user_quota, opt_cmd,
max_size, max_objects,
have_max_size, have_max_objects);
encode_json("user quota", period_config.quota.user_quota, formatter.get());
} else if (quota_scope.empty() && opt_cmd == OPT::GLOBAL_QUOTA_GET) {
// if no scope is given for GET, print both
encode_json("bucket quota", period_config.quota.bucket_quota, formatter.get());
encode_json("user quota", period_config.quota.user_quota, formatter.get());
} else {
cerr << "ERROR: invalid quota scope specification. Please specify "
"either --quota-scope=bucket, or --quota-scope=user" << std::endl;
return EINVAL;
}
formatter->close_section();
if (opt_cmd != OPT::GLOBAL_QUOTA_GET) {
// write the modified period config
constexpr bool exclusive = false;
ret = cfgstore->write_period_config(dpp(), null_yield, exclusive,
realm_id, period_config);
if (ret < 0) {
cerr << "ERROR: failed to write period config: "
<< cpp_strerror(-ret) << std::endl;
return -ret;
}
if (!realm_id.empty()) {
cout << "Global quota changes saved. Use 'period update' to apply "
"them to the staging period, and 'period commit' to commit the "
"new period." << std::endl;
} else {
cout << "Global quota changes saved. They will take effect as "
"the gateways are restarted." << std::endl;
}
}
formatter->flush(cout);
}
break;
case OPT::REALM_CREATE:
{
if (realm_name.empty()) {
cerr << "missing realm name" << std::endl;
return EINVAL;
}
RGWRealm realm;
realm.name = realm_name;
constexpr bool exclusive = true;
int ret = rgw::create_realm(dpp(), null_yield, cfgstore.get(),
exclusive, realm);
if (ret < 0) {
cerr << "ERROR: couldn't create realm " << realm_name << ": " << cpp_strerror(-ret) << std::endl;
return -ret;
}
if (set_default) {
ret = rgw::set_default_realm(dpp(), null_yield, cfgstore.get(), realm);
if (ret < 0) {
cerr << "failed to set realm " << realm_name << " as default: " << cpp_strerror(-ret) << std::endl;
}
}
encode_json("realm", realm, formatter.get());
formatter->flush(cout);
}
break;
case OPT::REALM_DELETE:
{
if (realm_id.empty() && realm_name.empty()) {
cerr << "missing realm name or id" << std::endl;
return EINVAL;
}
RGWRealm realm;
std::unique_ptr<rgw::sal::RealmWriter> writer;
int ret = rgw::read_realm(dpp(), null_yield, cfgstore.get(),
realm_id, realm_name, realm, &writer);
if (ret < 0) {
cerr << "failed to load realm: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
ret = writer->remove(dpp(), null_yield);
if (ret < 0) {
cerr << "failed to remove realm: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
}
break;
case OPT::REALM_GET:
{
RGWRealm realm;
int ret = rgw::read_realm(dpp(), null_yield, cfgstore.get(),
realm_id, realm_name, realm);
if (ret < 0) {
if (ret == -ENOENT && realm_name.empty() && realm_id.empty()) {
cerr << "missing realm name or id, or default realm not found" << std::endl;
} else {
cerr << "failed to load realm: " << cpp_strerror(-ret) << std::endl;
}
return -ret;
}
encode_json("realm", realm, formatter.get());
formatter->flush(cout);
}
break;
case OPT::REALM_GET_DEFAULT:
{
string default_id;
int ret = cfgstore->read_default_realm_id(dpp(), null_yield, default_id);
if (ret == -ENOENT) {
cout << "No default realm is set" << std::endl;
return -ret;
} else if (ret < 0) {
cerr << "Error reading default realm: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
cout << "default realm: " << default_id << std::endl;
}
break;
case OPT::REALM_LIST:
{
std::string default_id;
int ret = cfgstore->read_default_realm_id(dpp(), null_yield,
default_id);
if (ret < 0 && ret != -ENOENT) {
cerr << "could not determine default realm: " << cpp_strerror(-ret) << std::endl;
}
Formatter::ObjectSection realms_list{*formatter, "realms_list"};
encode_json("default_info", default_id, formatter.get());
Formatter::ArraySection realms{*formatter, "realms"};
rgw::sal::ListResult<std::string> listing;
std::array<std::string, 1000> names; // list in pages of 1000
do {
ret = cfgstore->list_realm_names(dpp(), null_yield, listing.next,
names, listing);
if (ret < 0) {
std::cerr << "failed to list realms: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
for (const auto& name : listing.entries) {
encode_json("name", name, formatter.get());
}
} while (!listing.next.empty());
} // close sections realms and realms_list
formatter->flush(cout);
break;
case OPT::REALM_LIST_PERIODS:
{
// use realm's current period
RGWRealm realm;
int ret = rgw::read_realm(dpp(), null_yield, cfgstore.get(),
realm_id, realm_name, realm);
if (ret < 0) {
cerr << "failed to load realm: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
period_id = realm.current_period;
Formatter::ObjectSection periods_list{*formatter, "realm_periods_list"};
encode_json("current_period", period_id, formatter.get());
Formatter::ArraySection periods{*formatter, "periods"};
while (!period_id.empty()) {
RGWPeriod period;
ret = cfgstore->read_period(dpp(), null_yield, period_id,
std::nullopt, period);
if (ret < 0) {
cerr << "failed to load period id " << period_id
<< ": " << cpp_strerror(-ret) << std::endl;
return -ret;
}
encode_json("id", period_id, formatter.get());
period_id = period.predecessor_uuid;
}
} // close sections periods and realm_periods_list
formatter->flush(cout);
break;
case OPT::REALM_RENAME:
{
if (realm_new_name.empty()) {
cerr << "missing realm new name" << std::endl;
return EINVAL;
}
if (realm_name.empty() && realm_id.empty()) {
cerr << "missing realm name or id" << std::endl;
return EINVAL;
}
RGWRealm realm;
std::unique_ptr<rgw::sal::RealmWriter> writer;
int ret = rgw::read_realm(dpp(), null_yield, cfgstore.get(),
realm_id, realm_name, realm, &writer);
if (ret < 0) {
cerr << "failed to load realm: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
ret = writer->rename(dpp(), null_yield, realm, realm_new_name);
if (ret < 0) {
cerr << "rename failed: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
cout << "Realm name updated. Note that this change only applies to "
"the current cluster, so this command must be run separately "
"on each of the realm's other clusters." << std::endl;
}
break;
case OPT::REALM_SET:
{
if (realm_id.empty() && realm_name.empty()) {
cerr << "no realm name or id provided" << std::endl;
return EINVAL;
}
bool new_realm = false;
RGWRealm realm;
std::unique_ptr<rgw::sal::RealmWriter> writer;
int ret = rgw::read_realm(dpp(), null_yield, cfgstore.get(),
realm_id, realm_name, realm, &writer);
if (ret < 0 && ret != -ENOENT) {
cerr << "failed to init realm: " << cpp_strerror(-ret) << std::endl;
return -ret;
} else if (ret == -ENOENT) {
new_realm = true;
}
ret = read_decode_json(infile, realm);
if (ret < 0) {
return 1;
}
if (!realm_name.empty() && realm.get_name() != realm_name) {
cerr << "mismatch between --rgw-realm " << realm_name << " and json input file name " <<
realm.get_name() << std::endl;
return EINVAL;
}
/* new realm */
if (new_realm) {
cout << "clearing period and epoch for new realm" << std::endl;
realm.clear_current_period_and_epoch();
constexpr bool exclusive = true;
ret = rgw::create_realm(dpp(), null_yield, cfgstore.get(),
exclusive, realm);
if (ret < 0) {
cerr << "ERROR: couldn't create new realm: " << cpp_strerror(-ret) << std::endl;
return 1;
}
} else {
ret = writer->write(dpp(), null_yield, realm);
if (ret < 0) {
cerr << "ERROR: couldn't driver realm info: " << cpp_strerror(-ret) << std::endl;
return 1;
}
}
if (set_default) {
ret = rgw::set_default_realm(dpp(), null_yield, cfgstore.get(), realm);
if (ret < 0) {
cerr << "failed to set realm " << realm_name << " as default: " << cpp_strerror(-ret) << std::endl;
}
}
encode_json("realm", realm, formatter.get());
formatter->flush(cout);
}
break;
case OPT::REALM_DEFAULT:
{
RGWRealm realm;
int ret = rgw::read_realm(dpp(), null_yield, cfgstore.get(),
realm_id, realm_name, realm);
if (ret < 0) {
cerr << "failed to load realm: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
ret = rgw::set_default_realm(dpp(), null_yield, cfgstore.get(), realm);
if (ret < 0) {
cerr << "failed to set realm as default: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
}
break;
case OPT::REALM_PULL:
{
if (url.empty()) {
cerr << "A --url must be provided." << std::endl;
return EINVAL;
}
RGWEnv env;
req_info info(g_ceph_context, &env);
info.method = "GET";
info.request_uri = "/admin/realm";
map<string, string> ¶ms = info.args.get_params();
if (!realm_id.empty())
params["id"] = realm_id;
if (!realm_name.empty())
params["name"] = realm_name;
bufferlist bl;
JSONParser p;
int ret = send_to_url(url, opt_region, access_key, secret_key, info, bl, p);
if (ret < 0) {
cerr << "request failed: " << cpp_strerror(-ret) << std::endl;
if (ret == -EACCES) {
cerr << "If the realm has been changed on the master zone, the "
"master zone's gateway may need to be restarted to recognize "
"this user." << std::endl;
}
return -ret;
}
RGWRealm realm;
try {
decode_json_obj(realm, &p);
} catch (const JSONDecoder::err& e) {
cerr << "failed to decode JSON response: " << e.what() << std::endl;
return EINVAL;
}
RGWPeriod period;
auto& current_period = realm.get_current_period();
if (!current_period.empty()) {
// pull the latest epoch of the realm's current period
ret = do_period_pull(cfgstore.get(), nullptr, url, opt_region,
access_key, secret_key,
realm_id, realm_name, current_period, "",
&period);
if (ret < 0) {
cerr << "could not fetch period " << current_period << std::endl;
return -ret;
}
}
constexpr bool exclusive = false;
ret = rgw::create_realm(dpp(), null_yield, cfgstore.get(),
exclusive, realm);
if (ret < 0) {
cerr << "Error storing realm " << realm.get_id() << ": "
<< cpp_strerror(ret) << std::endl;
return -ret;
}
if (set_default) {
ret = rgw::set_default_realm(dpp(), null_yield, cfgstore.get(), realm);
if (ret < 0) {
cerr << "failed to set realm " << realm_name << " as default: " << cpp_strerror(-ret) << std::endl;
}
}
encode_json("realm", realm, formatter.get());
formatter->flush(cout);
}
break;
case OPT::ZONEGROUP_ADD:
{
if (zonegroup_id.empty() && zonegroup_name.empty()) {
cerr << "no zonegroup name or id provided" << std::endl;
return EINVAL;
}
// load the zonegroup and zone params
RGWZoneGroup zonegroup;
std::unique_ptr<rgw::sal::ZoneGroupWriter> zonegroup_writer;
int ret = rgw::read_zonegroup(dpp(), null_yield, cfgstore.get(),
zonegroup_id, zonegroup_name,
zonegroup, &zonegroup_writer);
if (ret < 0) {
cerr << "failed to load zonegroup " << zonegroup_name << " id "
<< zonegroup_id << ": " << cpp_strerror(-ret) << std::endl;
return -ret;
}
RGWZoneParams zone_params;
std::unique_ptr<rgw::sal::ZoneWriter> zone_writer;
ret = rgw::read_zone(dpp(), null_yield, cfgstore.get(),
zone_id, zone_name, zone_params, &zone_writer);
if (ret < 0) {
cerr << "unable to load zone: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
// update zone_params if necessary
bool need_zone_update = false;
if (zone_params.realm_id != zonegroup.realm_id) {
if (!zone_params.realm_id.empty()) {
cerr << "WARNING: overwriting zone realm_id=" << zone_params.realm_id
<< " to match zonegroup realm_id=" << zonegroup.realm_id << std::endl;
}
zone_params.realm_id = zonegroup.realm_id;
need_zone_update = true;
}
for (auto a : tier_config_add) {
ret = zone_params.tier_config.set(a.first, a.second);
if (ret < 0) {
cerr << "ERROR: failed to set configurable: " << a << std::endl;
return EINVAL;
}
need_zone_update = true;
}
if (need_zone_update) {
ret = zone_writer->write(dpp(), null_yield, zone_params);
if (ret < 0) {
cerr << "failed to save zone info: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
}
const bool *pis_master = (is_master_set ? &is_master : nullptr);
const bool *pread_only = (is_read_only_set ? &read_only : nullptr);
const bool *psync_from_all = (sync_from_all_specified ? &sync_from_all : nullptr);
const string *predirect_zone = (redirect_zone_set ? &redirect_zone : nullptr);
// validate --tier-type if specified
const string *ptier_type = (tier_type_specified ? &tier_type : nullptr);
if (ptier_type) {
auto sync_mgr = static_cast<rgw::sal::RadosStore*>(driver)->svc()->sync_modules->get_manager();
if (!sync_mgr->get_module(*ptier_type, nullptr)) {
ldpp_dout(dpp(), -1) << "ERROR: could not find sync module: "
<< *ptier_type << ", valid sync modules: "
<< sync_mgr->get_registered_module_names() << dendl;
return EINVAL;
}
}
if (enable_features.empty()) { // enable all features by default
enable_features.insert(rgw::zone_features::supported.begin(),
rgw::zone_features::supported.end());
}
// add/update the public zone information stored in the zonegroup
ret = rgw::add_zone_to_group(dpp(), zonegroup, zone_params,
pis_master, pread_only, endpoints,
ptier_type, psync_from_all,
sync_from, sync_from_rm,
predirect_zone, bucket_index_max_shards,
enable_features, disable_features);
if (ret < 0) {
return -ret;
}
// write the updated zonegroup
ret = zonegroup_writer->write(dpp(), null_yield, zonegroup);
if (ret < 0) {
cerr << "failed to write updated zonegroup " << zonegroup.get_name()
<< ": " << cpp_strerror(-ret) << std::endl;
return -ret;
}
encode_json("zonegroup", zonegroup, formatter.get());
formatter->flush(cout);
}
break;
case OPT::ZONEGROUP_CREATE:
{
if (zonegroup_name.empty()) {
cerr << "Missing zonegroup name" << std::endl;
return EINVAL;
}
RGWRealm realm;
int ret = rgw::read_realm(dpp(), null_yield, cfgstore.get(),
realm_id, realm_name, realm);
if (ret < 0) {
cerr << "failed to init realm: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
RGWZoneGroup zonegroup;
zonegroup.name = zonegroup_name;
zonegroup.is_master = is_master;
zonegroup.realm_id = realm.get_id();
zonegroup.endpoints = endpoints;
zonegroup.api_name = (api_name.empty() ? zonegroup_name : api_name);
zonegroup.enabled_features = enable_features;
if (zonegroup.enabled_features.empty()) { // enable features by default
zonegroup.enabled_features.insert(rgw::zone_features::enabled.begin(),
rgw::zone_features::enabled.end());
}
for (const auto& feature : disable_features) {
auto i = zonegroup.enabled_features.find(feature);
if (i == zonegroup.enabled_features.end()) {
ldout(cct, 1) << "WARNING: zone feature \"" << feature
<< "\" was not enabled in zonegroup " << zonegroup_name << dendl;
continue;
}
zonegroup.enabled_features.erase(i);
}
constexpr bool exclusive = true;
ret = rgw::create_zonegroup(dpp(), null_yield, cfgstore.get(),
exclusive, zonegroup);
if (ret < 0) {
cerr << "failed to create zonegroup " << zonegroup_name << ": " << cpp_strerror(-ret) << std::endl;
return -ret;
}
if (set_default) {
ret = rgw::set_default_zonegroup(dpp(), null_yield, cfgstore.get(),
zonegroup);
if (ret < 0) {
cerr << "failed to set zonegroup " << zonegroup_name << " as default: " << cpp_strerror(-ret) << std::endl;
}
}
encode_json("zonegroup", zonegroup, formatter.get());
formatter->flush(cout);
}
break;
case OPT::ZONEGROUP_DEFAULT:
{
if (zonegroup_id.empty() && zonegroup_name.empty()) {
cerr << "no zonegroup name or id provided" << std::endl;
return EINVAL;
}
RGWZoneGroup zonegroup;
int ret = rgw::read_zonegroup(dpp(), null_yield, cfgstore.get(),
zonegroup_id, zonegroup_name,
zonegroup);
if (ret < 0) {
cerr << "failed to init zonegroup: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
ret = rgw::set_default_zonegroup(dpp(), null_yield, cfgstore.get(),
zonegroup);
if (ret < 0) {
cerr << "failed to set zonegroup as default: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
}
break;
case OPT::ZONEGROUP_DELETE:
{
if (zonegroup_id.empty() && zonegroup_name.empty()) {
cerr << "no zonegroup name or id provided" << std::endl;
return EINVAL;
}
RGWZoneGroup zonegroup;
std::unique_ptr<rgw::sal::ZoneGroupWriter> writer;
int ret = rgw::read_zonegroup(dpp(), null_yield, cfgstore.get(),
zonegroup_id, zonegroup_name,
zonegroup, &writer);
if (ret < 0) {
cerr << "failed to load zonegroup: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
ret = writer->remove(dpp(), null_yield);
if (ret < 0) {
cerr << "ERROR: couldn't delete zonegroup: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
}
break;
case OPT::ZONEGROUP_GET:
{
RGWZoneGroup zonegroup;
int ret = rgw::read_zonegroup(dpp(), null_yield, cfgstore.get(),
zonegroup_id, zonegroup_name, zonegroup);
if (ret < 0) {
cerr << "failed to load zonegroup: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
encode_json("zonegroup", zonegroup, formatter.get());
formatter->flush(cout);
}
break;
case OPT::ZONEGROUP_LIST:
{
RGWZoneGroup default_zonegroup;
int ret = rgw::read_zonegroup(dpp(), null_yield, cfgstore.get(),
{}, {}, default_zonegroup);
if (ret < 0 && ret != -ENOENT) {
cerr << "could not determine default zonegroup: " << cpp_strerror(-ret) << std::endl;
}
Formatter::ObjectSection zonegroups_list{*formatter, "zonegroups_list"};
encode_json("default_info", default_zonegroup.id, formatter.get());
Formatter::ArraySection zonegroups{*formatter, "zonegroups"};
rgw::sal::ListResult<std::string> listing;
std::array<std::string, 1000> names; // list in pages of 1000
do {
ret = cfgstore->list_zonegroup_names(dpp(), null_yield, listing.next,
names, listing);
if (ret < 0) {
std::cerr << "failed to list zonegroups: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
for (const auto& name : listing.entries) {
encode_json("name", name, formatter.get());
}
} while (!listing.next.empty());
} // close sections zonegroups and zonegroups_list
formatter->flush(cout);
break;
case OPT::ZONEGROUP_MODIFY:
{
RGWZoneGroup zonegroup;
std::unique_ptr<rgw::sal::ZoneGroupWriter> writer;
int ret = rgw::read_zonegroup(dpp(), null_yield, cfgstore.get(),
zonegroup_id, zonegroup_name,
zonegroup, &writer);
if (ret < 0) {
cerr << "failed to init zonegroup: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
bool need_update = false;
if (!master_zone.empty()) {
zonegroup.master_zone = master_zone;
need_update = true;
}
if (is_master_set) {
zonegroup.is_master = is_master;
need_update = true;
}
if (!endpoints.empty()) {
zonegroup.endpoints = endpoints;
need_update = true;
}
if (!api_name.empty()) {
zonegroup.api_name = api_name;
need_update = true;
}
if (!realm_id.empty()) {
zonegroup.realm_id = realm_id;
need_update = true;
} else if (!realm_name.empty()) {
// get realm id from name
ret = cfgstore->read_realm_id(dpp(), null_yield, realm_name,
zonegroup.realm_id);
if (ret < 0) {
cerr << "failed to find realm by name " << realm_name << std::endl;
return -ret;
}
need_update = true;
}
if (bucket_index_max_shards) {
for (auto& [name, zone] : zonegroup.zones) {
zone.bucket_index_max_shards = *bucket_index_max_shards;
}
need_update = true;
}
for (const auto& feature : enable_features) {
zonegroup.enabled_features.insert(feature);
need_update = true;
}
for (const auto& feature : disable_features) {
auto i = zonegroup.enabled_features.find(feature);
if (i == zonegroup.enabled_features.end()) {
ldout(cct, 1) << "WARNING: zone feature \"" << feature
<< "\" was not enabled in zonegroup "
<< zonegroup.get_name() << dendl;
continue;
}
zonegroup.enabled_features.erase(i);
need_update = true;
}
if (need_update) {
ret = writer->write(dpp(), null_yield, zonegroup);
if (ret < 0) {
cerr << "failed to update zonegroup: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
}
if (set_default) {
ret = rgw::set_default_zonegroup(dpp(), null_yield, cfgstore.get(),
zonegroup);
if (ret < 0) {
cerr << "failed to set zonegroup " << zonegroup_name << " as default: " << cpp_strerror(-ret) << std::endl;
}
}
encode_json("zonegroup", zonegroup, formatter.get());
formatter->flush(cout);
}
break;
case OPT::ZONEGROUP_SET:
{
RGWRealm realm;
int ret = rgw::read_realm(dpp(), null_yield, cfgstore.get(),
realm_id, realm_name, realm);
bool default_realm_not_exist = (ret == -ENOENT && realm_id.empty() && realm_name.empty());
if (ret < 0 && !default_realm_not_exist) {
cerr << "failed to init realm: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
RGWZoneGroup zonegroup;
ret = read_decode_json(infile, zonegroup);
if (ret < 0) {
return 1;
}
if (zonegroup.realm_id.empty() && !default_realm_not_exist) {
zonegroup.realm_id = realm.get_id();
}
// validate zonegroup features
for (const auto& feature : zonegroup.enabled_features) {
if (!rgw::zone_features::supports(feature)) {
std::cerr << "ERROR: Unrecognized zonegroup feature \""
<< feature << "\"" << std::endl;
return EINVAL;
}
}
for (const auto& [name, zone] : zonegroup.zones) {
// validate zone features
for (const auto& feature : zone.supported_features) {
if (!rgw::zone_features::supports(feature)) {
std::cerr << "ERROR: Unrecognized zone feature \""
<< feature << "\" in zone " << zone.name << std::endl;
return EINVAL;
}
}
// zone must support everything zonegroup does
for (const auto& feature : zonegroup.enabled_features) {
if (!zone.supports(feature)) {
std::cerr << "ERROR: Zone " << name << " does not support feature \""
<< feature << "\" required by zonegroup" << std::endl;
return EINVAL;
}
}
}
// create/overwrite the zonegroup info
constexpr bool exclusive = false;
ret = rgw::create_zonegroup(dpp(), null_yield, cfgstore.get(),
exclusive, zonegroup);
if (ret < 0) {
cerr << "ERROR: couldn't create zonegroup info: " << cpp_strerror(-ret) << std::endl;
return 1;
}
if (set_default) {
ret = rgw::set_default_zonegroup(dpp(), null_yield, cfgstore.get(),
zonegroup);
if (ret < 0) {
cerr << "failed to set zonegroup " << zonegroup_name << " as default: " << cpp_strerror(-ret) << std::endl;
}
}
encode_json("zonegroup", zonegroup, formatter.get());
formatter->flush(cout);
}
break;
case OPT::ZONEGROUP_REMOVE:
{
RGWZoneGroup zonegroup;
std::unique_ptr<rgw::sal::ZoneGroupWriter> writer;
int ret = rgw::read_zonegroup(dpp(), null_yield, cfgstore.get(),
zonegroup_id, zonegroup_name,
zonegroup, &writer);
if (ret < 0) {
cerr << "failed to init zonegroup: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
if (zone_id.empty()) {
if (zone_name.empty()) {
cerr << "no --zone-id or --rgw-zone name provided" << std::endl;
return EINVAL;
}
// look up zone id by name
for (auto& z : zonegroup.zones) {
if (zone_name == z.second.name) {
zone_id = z.second.id;
break;
}
}
if (zone_id.empty()) {
cerr << "zone name " << zone_name << " not found in zonegroup "
<< zonegroup.get_name() << std::endl;
return ENOENT;
}
}
ret = rgw::remove_zone_from_group(dpp(), zonegroup, zone_id);
if (ret < 0) {
cerr << "failed to remove zone: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
ret = writer->write(dpp(), null_yield, zonegroup);
if (ret < 0) {
cerr << "failed to write zonegroup: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
encode_json("zonegroup", zonegroup, formatter.get());
formatter->flush(cout);
}
break;
case OPT::ZONEGROUP_RENAME:
{
if (zonegroup_new_name.empty()) {
cerr << " missing zonegroup new name" << std::endl;
return EINVAL;
}
if (zonegroup_id.empty() && zonegroup_name.empty()) {
cerr << "no zonegroup name or id provided" << std::endl;
return EINVAL;
}
RGWZoneGroup zonegroup;
std::unique_ptr<rgw::sal::ZoneGroupWriter> writer;
int ret = rgw::read_zonegroup(dpp(), null_yield, cfgstore.get(),
zonegroup_id, zonegroup_name,
zonegroup, &writer);
if (ret < 0) {
cerr << "failed to load zonegroup: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
ret = writer->rename(dpp(), null_yield, zonegroup, zonegroup_new_name);
if (ret < 0) {
cerr << "failed to rename zonegroup: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
}
break;
case OPT::ZONEGROUP_PLACEMENT_LIST:
{
RGWZoneGroup zonegroup;
int ret = rgw::read_zonegroup(dpp(), null_yield, cfgstore.get(),
zonegroup_id, zonegroup_name, zonegroup);
if (ret < 0) {
cerr << "failed to load zonegroup: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
encode_json("placement_targets", zonegroup.placement_targets, formatter.get());
formatter->flush(cout);
}
break;
case OPT::ZONEGROUP_PLACEMENT_GET:
{
if (placement_id.empty()) {
cerr << "ERROR: --placement-id not specified" << std::endl;
return EINVAL;
}
RGWZoneGroup zonegroup;
int ret = rgw::read_zonegroup(dpp(), null_yield, cfgstore.get(),
zonegroup_id, zonegroup_name, zonegroup);
if (ret < 0) {
cerr << "failed to load zonegroup: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
auto p = zonegroup.placement_targets.find(placement_id);
if (p == zonegroup.placement_targets.end()) {
cerr << "failed to find a zonegroup placement target named '" << placement_id << "'" << std::endl;
return -ENOENT;
}
encode_json("placement_targets", p->second, formatter.get());
formatter->flush(cout);
}
break;
case OPT::ZONEGROUP_PLACEMENT_ADD:
case OPT::ZONEGROUP_PLACEMENT_MODIFY:
case OPT::ZONEGROUP_PLACEMENT_RM:
case OPT::ZONEGROUP_PLACEMENT_DEFAULT:
{
if (placement_id.empty()) {
cerr << "ERROR: --placement-id not specified" << std::endl;
return EINVAL;
}
rgw_placement_rule rule;
rule.from_str(placement_id);
if (!rule.storage_class.empty() && opt_storage_class &&
rule.storage_class != *opt_storage_class) {
cerr << "ERROR: provided contradicting storage class configuration" << std::endl;
return EINVAL;
} else if (rule.storage_class.empty()) {
rule.storage_class = opt_storage_class.value_or(string());
}
RGWZoneGroup zonegroup;
std::unique_ptr<rgw::sal::ZoneGroupWriter> writer;
int ret = rgw::read_zonegroup(dpp(), null_yield, cfgstore.get(),
zonegroup_id, zonegroup_name,
zonegroup, &writer);
if (ret < 0) {
cerr << "failed to init zonegroup: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
if (opt_cmd == OPT::ZONEGROUP_PLACEMENT_ADD ||
opt_cmd == OPT::ZONEGROUP_PLACEMENT_MODIFY) {
RGWZoneGroupPlacementTarget& target = zonegroup.placement_targets[placement_id];
if (!tags.empty()) {
target.tags.clear();
for (auto& t : tags) {
target.tags.insert(t);
}
}
target.name = placement_id;
for (auto& t : tags_rm) {
target.tags.erase(t);
}
for (auto& t : tags_add) {
target.tags.insert(t);
}
target.storage_classes.insert(rule.get_storage_class());
/* Tier options */
bool tier_class = false;
std::string storage_class = rule.get_storage_class();
RGWZoneGroupPlacementTier t{storage_class};
RGWZoneGroupPlacementTier *pt = &t;
auto ptiter = target.tier_targets.find(storage_class);
if (ptiter != target.tier_targets.end()) {
pt = &ptiter->second;
tier_class = true;
} else if (tier_type_specified) {
if (tier_type == "cloud-s3") {
/* we support only cloud-s3 tier-type for now.
* Once set cant be reset. */
tier_class = true;
pt->tier_type = tier_type;
pt->storage_class = storage_class;
} else {
cerr << "ERROR: Invalid tier-type specified" << std::endl;
return EINVAL;
}
}
if (tier_class) {
if (tier_config_add.size() > 0) {
JSONFormattable tconfig;
for (auto add : tier_config_add) {
int r = tconfig.set(add.first, add.second);
if (r < 0) {
cerr << "ERROR: failed to set configurable: " << add << std::endl;
return EINVAL;
}
}
int r = pt->update_params(tconfig);
if (r < 0) {
cerr << "ERROR: failed to update tier_config options"<< std::endl;
}
}
if (tier_config_rm.size() > 0) {
JSONFormattable tconfig;
for (auto add : tier_config_rm) {
int r = tconfig.set(add.first, add.second);
if (r < 0) {
cerr << "ERROR: failed to set configurable: " << add << std::endl;
return EINVAL;
}
}
int r = pt->clear_params(tconfig);
if (r < 0) {
cerr << "ERROR: failed to update tier_config options"<< std::endl;
}
}
target.tier_targets.emplace(std::make_pair(storage_class, *pt));
}
if (zonegroup.default_placement.empty()) {
zonegroup.default_placement.init(rule.name, RGW_STORAGE_CLASS_STANDARD);
}
} else if (opt_cmd == OPT::ZONEGROUP_PLACEMENT_RM) {
if (!opt_storage_class || opt_storage_class->empty()) {
zonegroup.placement_targets.erase(placement_id);
if (zonegroup.default_placement.name == placement_id) {
// clear default placement
zonegroup.default_placement.clear();
}
} else {
auto iter = zonegroup.placement_targets.find(placement_id);
if (iter != zonegroup.placement_targets.end()) {
RGWZoneGroupPlacementTarget& info = zonegroup.placement_targets[placement_id];
info.storage_classes.erase(*opt_storage_class);
if (zonegroup.default_placement == rule) {
// clear default storage class
zonegroup.default_placement.storage_class.clear();
}
auto ptiter = info.tier_targets.find(*opt_storage_class);
if (ptiter != info.tier_targets.end()) {
info.tier_targets.erase(ptiter);
}
}
}
} else if (opt_cmd == OPT::ZONEGROUP_PLACEMENT_DEFAULT) {
if (!zonegroup.placement_targets.count(placement_id)) {
cerr << "failed to find a zonegroup placement target named '"
<< placement_id << "'" << std::endl;
return -ENOENT;
}
zonegroup.default_placement = rule;
}
ret = writer->write(dpp(), null_yield, zonegroup);
if (ret < 0) {
cerr << "failed to update zonegroup: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
encode_json("placement_targets", zonegroup.placement_targets, formatter.get());
formatter->flush(cout);
}
break;
case OPT::ZONE_CREATE:
{
if (zone_name.empty()) {
cerr << "zone name not provided" << std::endl;
return EINVAL;
}
RGWZoneGroup zonegroup;
std::unique_ptr<rgw::sal::ZoneGroupWriter> zonegroup_writer;
/* if the user didn't provide zonegroup info , create stand alone zone */
if (!zonegroup_id.empty() || !zonegroup_name.empty()) {
int ret = rgw::read_zonegroup(dpp(), null_yield, cfgstore.get(),
zonegroup_id, zonegroup_name,
zonegroup, &zonegroup_writer);
if (ret < 0) {
cerr << "failed to load zonegroup " << zonegroup_name << ": " << cpp_strerror(-ret) << std::endl;
return -ret;
}
if (realm_id.empty() && realm_name.empty()) {
realm_id = zonegroup.realm_id;
}
}
// create the local zone params
RGWZoneParams zone_params;
zone_params.id = zone_id;
zone_params.name = zone_name;
zone_params.system_key.id = access_key;
zone_params.system_key.key = secret_key;
zone_params.realm_id = realm_id;
for (const auto& a : tier_config_add) {
int r = zone_params.tier_config.set(a.first, a.second);
if (r < 0) {
cerr << "ERROR: failed to set configurable: " << a << std::endl;
return EINVAL;
}
}
if (zone_params.realm_id.empty()) {
RGWRealm realm;
int ret = rgw::read_realm(dpp(), null_yield, cfgstore.get(),
realm_id, realm_name, realm);
if (ret < 0 && ret != -ENOENT) {
cerr << "failed to load realm: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
zone_params.realm_id = realm.id;
cerr << "NOTICE: set zone's realm_id=" << realm.id << std::endl;
}
constexpr bool exclusive = true;
int ret = rgw::create_zone(dpp(), null_yield, cfgstore.get(),
exclusive, zone_params);
if (ret < 0) {
cerr << "failed to create zone " << zone_name << ": " << cpp_strerror(-ret) << std::endl;
return -ret;
}
if (zonegroup_writer) {
const bool *pis_master = (is_master_set ? &is_master : nullptr);
const bool *pread_only = (is_read_only_set ? &read_only : nullptr);
const bool *psync_from_all = (sync_from_all_specified ? &sync_from_all : nullptr);
const string *predirect_zone = (redirect_zone_set ? &redirect_zone : nullptr);
// validate --tier-type if specified
const string *ptier_type = (tier_type_specified ? &tier_type : nullptr);
if (ptier_type) {
auto sync_mgr = static_cast<rgw::sal::RadosStore*>(driver)->svc()->sync_modules->get_manager();
if (!sync_mgr->get_module(*ptier_type, nullptr)) {
ldpp_dout(dpp(), -1) << "ERROR: could not find sync module: "
<< *ptier_type << ", valid sync modules: "
<< sync_mgr->get_registered_module_names() << dendl;
return EINVAL;
}
}
if (enable_features.empty()) { // enable all features by default
enable_features.insert(rgw::zone_features::supported.begin(),
rgw::zone_features::supported.end());
}
// add/update the public zone information stored in the zonegroup
ret = rgw::add_zone_to_group(dpp(), zonegroup, zone_params,
pis_master, pread_only, endpoints,
ptier_type, psync_from_all,
sync_from, sync_from_rm,
predirect_zone, bucket_index_max_shards,
enable_features, disable_features);
if (ret < 0) {
return -ret;
}
// write the updated zonegroup
ret = zonegroup_writer->write(dpp(), null_yield, zonegroup);
if (ret < 0) {
cerr << "failed to add zone " << zone_name << " to zonegroup " << zonegroup.get_name()
<< ": " << cpp_strerror(-ret) << std::endl;
return -ret;
}
}
if (set_default) {
ret = rgw::set_default_zone(dpp(), null_yield, cfgstore.get(),
zone_params);
if (ret < 0) {
cerr << "failed to set zone " << zone_name << " as default: " << cpp_strerror(-ret) << std::endl;
}
}
encode_json("zone", zone_params, formatter.get());
formatter->flush(cout);
}
break;
case OPT::ZONE_DEFAULT:
{
if (zone_id.empty() && zone_name.empty()) {
cerr << "no zone name or id provided" << std::endl;
return EINVAL;
}
RGWZoneParams zone_params;
int ret = rgw::read_zone(dpp(), null_yield, cfgstore.get(),
zone_id, zone_name, zone_params);
if (ret < 0) {
cerr << "unable to load zone: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
ret = rgw::set_default_zone(dpp(), null_yield, cfgstore.get(),
zone_params);
if (ret < 0) {
cerr << "failed to set zone as default: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
}
break;
case OPT::ZONE_DELETE:
{
if (zone_id.empty() && zone_name.empty()) {
cerr << "no zone name or id provided" << std::endl;
return EINVAL;
}
RGWZoneParams zone_params;
std::unique_ptr<rgw::sal::ZoneWriter> writer;
int ret = rgw::read_zone(dpp(), null_yield, cfgstore.get(),
zone_id, zone_name, zone_params, &writer);
if (ret < 0) {
cerr << "failed to load zone: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
ret = rgw::delete_zone(dpp(), null_yield, cfgstore.get(),
zone_params, *writer);
if (ret < 0) {
cerr << "failed to delete zone " << zone_params.get_name()
<< ": " << cpp_strerror(-ret) << std::endl;
return -ret;
}
}
break;
case OPT::ZONE_GET:
{
RGWZoneParams zone_params;
int ret = rgw::read_zone(dpp(), null_yield, cfgstore.get(),
zone_id, zone_name, zone_params);
if (ret < 0) {
cerr << "failed to load zone: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
encode_json("zone", zone_params, formatter.get());
formatter->flush(cout);
}
break;
case OPT::ZONE_SET:
{
RGWZoneParams zone;
std::unique_ptr<rgw::sal::ZoneWriter> writer;
int ret = rgw::read_zone(dpp(), null_yield, cfgstore.get(),
zone_id, zone_name, zone, &writer);
if (ret < 0 && ret != -ENOENT) {
cerr << "failed to load zone: " << cpp_strerror(ret) << std::endl;
return -ret;
}
string orig_id = zone.get_id();
ret = read_decode_json(infile, zone);
if (ret < 0) {
return 1;
}
if (zone.realm_id.empty()) {
RGWRealm realm;
ret = rgw::read_realm(dpp(), null_yield, cfgstore.get(),
realm_id, realm_name, realm);
if (ret < 0 && ret != -ENOENT) {
cerr << "failed to load realm: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
zone.realm_id = realm.get_id();
cerr << "NOTICE: set zone's realm_id=" << zone.realm_id << std::endl;
}
if (!zone_name.empty() && !zone.get_name().empty() && zone.get_name() != zone_name) {
cerr << "Error: zone name " << zone_name << " is different than the zone name " << zone.get_name() << " in the provided json " << std::endl;
return EINVAL;
}
if (zone.get_name().empty()) {
zone.set_name(zone_name);
if (zone.get_name().empty()) {
cerr << "no zone name specified" << std::endl;
return EINVAL;
}
}
zone_name = zone.get_name();
if (zone.get_id().empty()) {
zone.set_id(orig_id);
}
constexpr bool exclusive = false;
ret = rgw::create_zone(dpp(), null_yield, cfgstore.get(),
exclusive, zone);
if (ret < 0) {
cerr << "ERROR: couldn't create zone: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
if (set_default) {
ret = rgw::set_default_zone(dpp(), null_yield, cfgstore.get(), zone);
if (ret < 0) {
cerr << "failed to set zone " << zone_name << " as default: " << cpp_strerror(-ret) << std::endl;
}
}
encode_json("zone", zone, formatter.get());
formatter->flush(cout);
}
break;
case OPT::ZONE_LIST:
{
RGWZoneParams default_zone_params;
int ret = rgw::read_zone(dpp(), null_yield, cfgstore.get(),
{}, {}, default_zone_params);
if (ret < 0 && ret != -ENOENT) {
cerr << "could not determine default zone: " << cpp_strerror(-ret) << std::endl;
}
Formatter::ObjectSection zones_list{*formatter, "zones_list"};
encode_json("default_info", default_zone_params.id, formatter.get());
Formatter::ArraySection zones{*formatter, "zones"};
rgw::sal::ListResult<std::string> listing;
std::array<std::string, 1000> names; // list in pages of 1000
do {
ret = cfgstore->list_zone_names(dpp(), null_yield, listing.next,
names, listing);
if (ret < 0) {
std::cerr << "failed to list zones: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
for (const auto& name : listing.entries) {
encode_json("name", name, formatter.get());
}
} while (!listing.next.empty());
} // close sections zones and zones_list
formatter->flush(cout);
break;
case OPT::ZONE_MODIFY:
{
RGWZoneParams zone_params;
std::unique_ptr<rgw::sal::ZoneWriter> zone_writer;
int ret = rgw::read_zone(dpp(), null_yield, cfgstore.get(),
zone_id, zone_name, zone_params, &zone_writer);
if (ret < 0) {
cerr << "failed to load zone: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
bool need_zone_update = false;
if (!access_key.empty()) {
zone_params.system_key.id = access_key;
need_zone_update = true;
}
if (!secret_key.empty()) {
zone_params.system_key.key = secret_key;
need_zone_update = true;
}
if (!realm_id.empty()) {
zone_params.realm_id = realm_id;
need_zone_update = true;
} else if (!realm_name.empty()) {
// get realm id from name
ret = cfgstore->read_realm_id(dpp(), null_yield,
realm_name, zone_params.realm_id);
if (ret < 0) {
cerr << "failed to find realm by name " << realm_name << std::endl;
return -ret;
}
need_zone_update = true;
}
for (const auto& add : tier_config_add) {
ret = zone_params.tier_config.set(add.first, add.second);
if (ret < 0) {
cerr << "ERROR: failed to set configurable: " << add << std::endl;
return EINVAL;
}
need_zone_update = true;
}
for (const auto& rm : tier_config_rm) {
if (!rm.first.empty()) { /* otherwise will remove the entire config */
zone_params.tier_config.erase(rm.first);
need_zone_update = true;
}
}
if (need_zone_update) {
ret = zone_writer->write(dpp(), null_yield, zone_params);
if (ret < 0) {
cerr << "failed to save zone info: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
}
RGWZoneGroup zonegroup;
std::unique_ptr<rgw::sal::ZoneGroupWriter> zonegroup_writer;
ret = rgw::read_zonegroup(dpp(), null_yield, cfgstore.get(),
zonegroup_id, zonegroup_name,
zonegroup, &zonegroup_writer);
if (ret < 0) {
cerr << "failed to load zonegroup: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
const bool *pis_master = (is_master_set ? &is_master : nullptr);
const bool *pread_only = (is_read_only_set ? &read_only : nullptr);
const bool *psync_from_all = (sync_from_all_specified ? &sync_from_all : nullptr);
const string *predirect_zone = (redirect_zone_set ? &redirect_zone : nullptr);
// validate --tier-type if specified
const string *ptier_type = (tier_type_specified ? &tier_type : nullptr);
if (ptier_type) {
auto sync_mgr = static_cast<rgw::sal::RadosStore*>(driver)->svc()->sync_modules->get_manager();
if (!sync_mgr->get_module(*ptier_type, nullptr)) {
ldpp_dout(dpp(), -1) << "ERROR: could not find sync module: "
<< *ptier_type << ", valid sync modules: "
<< sync_mgr->get_registered_module_names() << dendl;
return EINVAL;
}
}
if (enable_features.empty()) { // enable all features by default
enable_features.insert(rgw::zone_features::supported.begin(),
rgw::zone_features::supported.end());
}
// add/update the public zone information stored in the zonegroup
ret = rgw::add_zone_to_group(dpp(), zonegroup, zone_params,
pis_master, pread_only, endpoints,
ptier_type, psync_from_all,
sync_from, sync_from_rm,
predirect_zone, bucket_index_max_shards,
enable_features, disable_features);
if (ret < 0) {
return -ret;
}
// write the updated zonegroup
ret = zonegroup_writer->write(dpp(), null_yield, zonegroup);
if (ret < 0) {
cerr << "failed to update zonegroup: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
if (set_default) {
ret = rgw::set_default_zone(dpp(), null_yield, cfgstore.get(),
zone_params);
if (ret < 0) {
cerr << "failed to set zone " << zone_name << " as default: " << cpp_strerror(-ret) << std::endl;
}
}
encode_json("zone", zone_params, formatter.get());
formatter->flush(cout);
}
break;
case OPT::ZONE_RENAME:
{
if (zone_new_name.empty()) {
cerr << " missing zone new name" << std::endl;
return EINVAL;
}
if (zone_id.empty() && zone_name.empty()) {
cerr << "no zone name or id provided" << std::endl;
return EINVAL;
}
RGWZoneParams zone_params;
std::unique_ptr<rgw::sal::ZoneWriter> zone_writer;
int ret = rgw::read_zone(dpp(), null_yield, cfgstore.get(),
zone_id, zone_name, zone_params, &zone_writer);
if (ret < 0) {
cerr << "failed to load zone: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
ret = zone_writer->rename(dpp(), null_yield, zone_params, zone_new_name);
if (ret < 0) {
cerr << "failed to rename zone " << zone_name << " to " << zone_new_name << ": " << cpp_strerror(-ret)
<< std::endl;
return -ret;
}
RGWZoneGroup zonegroup;
std::unique_ptr<rgw::sal::ZoneGroupWriter> zonegroup_writer;
ret = rgw::read_zonegroup(dpp(), null_yield, cfgstore.get(),
zonegroup_id, zonegroup_name,
zonegroup, &zonegroup_writer);
if (ret < 0) {
cerr << "WARNING: failed to load zonegroup " << zonegroup_name << std::endl;
return EXIT_SUCCESS;
}
auto z = zonegroup.zones.find(zone_params.id);
if (z == zonegroup.zones.end()) {
return EXIT_SUCCESS;
}
z->second.name = zone_params.name;
ret = zonegroup_writer->write(dpp(), null_yield, zonegroup);
if (ret < 0) {
cerr << "Error in zonegroup rename for " << zone_name << ": " << cpp_strerror(-ret) << std::endl;
return -ret;
}
}
break;
case OPT::ZONE_PLACEMENT_ADD:
case OPT::ZONE_PLACEMENT_MODIFY:
case OPT::ZONE_PLACEMENT_RM:
{
if (placement_id.empty()) {
cerr << "ERROR: --placement-id not specified" << std::endl;
return EINVAL;
}
// validate compression type
if (compression_type && *compression_type != "random"
&& !Compressor::get_comp_alg_type(*compression_type)) {
std::cerr << "Unrecognized compression type" << std::endl;
return EINVAL;
}
RGWZoneParams zone;
std::unique_ptr<rgw::sal::ZoneWriter> writer;
int ret = rgw::read_zone(dpp(), null_yield, cfgstore.get(),
zone_id, zone_name, zone, &writer);
if (ret < 0) {
cerr << "failed to init zone: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
if (opt_cmd == OPT::ZONE_PLACEMENT_ADD ||
opt_cmd == OPT::ZONE_PLACEMENT_MODIFY) {
RGWZoneGroup zonegroup;
ret = rgw::read_zonegroup(dpp(), null_yield, cfgstore.get(),
zonegroup_id, zonegroup_name, zonegroup);
if (ret < 0) {
cerr << "failed to init zonegroup: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
auto ptiter = zonegroup.placement_targets.find(placement_id);
if (ptiter == zonegroup.placement_targets.end()) {
cerr << "ERROR: placement id '" << placement_id << "' is not configured in zonegroup placement targets" << std::endl;
return EINVAL;
}
string storage_class = rgw_placement_rule::get_canonical_storage_class(opt_storage_class.value_or(string()));
if (ptiter->second.storage_classes.find(storage_class) == ptiter->second.storage_classes.end()) {
cerr << "ERROR: storage class '" << storage_class << "' is not defined in zonegroup '" << placement_id << "' placement target" << std::endl;
return EINVAL;
}
if (ptiter->second.tier_targets.find(storage_class) != ptiter->second.tier_targets.end()) {
cerr << "ERROR: storage class '" << storage_class << "' is of tier type in zonegroup '" << placement_id << "' placement target" << std::endl;
return EINVAL;
}
RGWZonePlacementInfo& info = zone.placement_pools[placement_id];
string opt_index_pool = index_pool.value_or(string());
string opt_data_pool = data_pool.value_or(string());
if (!opt_index_pool.empty()) {
info.index_pool = opt_index_pool;
}
if (info.index_pool.empty()) {
cerr << "ERROR: index pool not configured, need to specify --index-pool" << std::endl;
return EINVAL;
}
if (opt_data_pool.empty()) {
const RGWZoneStorageClass *porig_sc{nullptr};
if (info.storage_classes.find(storage_class, &porig_sc)) {
if (porig_sc->data_pool) {
opt_data_pool = porig_sc->data_pool->to_str();
}
}
if (opt_data_pool.empty()) {
cerr << "ERROR: data pool not configured, need to specify --data-pool" << std::endl;
return EINVAL;
}
}
rgw_pool dp = opt_data_pool;
info.storage_classes.set_storage_class(storage_class, &dp, compression_type.get_ptr());
if (data_extra_pool) {
info.data_extra_pool = *data_extra_pool;
}
if (index_type_specified) {
info.index_type = placement_index_type;
}
if (placement_inline_data_specified) {
info.inline_data = placement_inline_data;
}
ret = check_pool_support_omap(info.get_data_extra_pool());
if (ret < 0) {
cerr << "ERROR: the data extra (non-ec) pool '" << info.get_data_extra_pool()
<< "' does not support omap" << std::endl;
return ret;
}
} else if (opt_cmd == OPT::ZONE_PLACEMENT_RM) {
if (!opt_storage_class ||
opt_storage_class->empty()) {
zone.placement_pools.erase(placement_id);
} else {
auto iter = zone.placement_pools.find(placement_id);
if (iter != zone.placement_pools.end()) {
RGWZonePlacementInfo& info = zone.placement_pools[placement_id];
info.storage_classes.remove_storage_class(*opt_storage_class);
}
}
}
ret = writer->write(dpp(), null_yield, zone);
if (ret < 0) {
cerr << "failed to save zone info: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
encode_json("zone", zone, formatter.get());
formatter->flush(cout);
}
break;
case OPT::ZONE_PLACEMENT_LIST:
{
RGWZoneParams zone;
int ret = rgw::read_zone(dpp(), null_yield, cfgstore.get(),
zone_id, zone_name, zone);
if (ret < 0) {
cerr << "unable to initialize zone: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
encode_json("placement_pools", zone.placement_pools, formatter.get());
formatter->flush(cout);
}
break;
case OPT::ZONE_PLACEMENT_GET:
{
if (placement_id.empty()) {
cerr << "ERROR: --placement-id not specified" << std::endl;
return EINVAL;
}
RGWZoneParams zone;
int ret = rgw::read_zone(dpp(), null_yield, cfgstore.get(),
zone_id, zone_name, zone);
if (ret < 0) {
cerr << "unable to initialize zone: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
auto p = zone.placement_pools.find(placement_id);
if (p == zone.placement_pools.end()) {
cerr << "ERROR: zone placement target '" << placement_id << "' not found" << std::endl;
return ENOENT;
}
encode_json("placement_pools", p->second, formatter.get());
formatter->flush(cout);
}
default:
break;
}
return 0;
}
resolve_zone_id_opt(opt_effective_zone_name, opt_effective_zone_id);
resolve_zone_id_opt(opt_source_zone_name, opt_source_zone_id);
resolve_zone_id_opt(opt_dest_zone_name, opt_dest_zone_id);
resolve_zone_ids_opt(opt_zone_names, opt_zone_ids);
resolve_zone_ids_opt(opt_source_zone_names, opt_source_zone_ids);
resolve_zone_ids_opt(opt_dest_zone_names, opt_dest_zone_ids);
bool non_master_cmd = (!driver->is_meta_master() && !yes_i_really_mean_it);
std::set<OPT> non_master_ops_list = {OPT::USER_CREATE, OPT::USER_RM,
OPT::USER_MODIFY, OPT::USER_ENABLE,
OPT::USER_SUSPEND, OPT::SUBUSER_CREATE,
OPT::SUBUSER_MODIFY, OPT::SUBUSER_RM,
OPT::BUCKET_LINK, OPT::BUCKET_UNLINK,
OPT::BUCKET_RM,
OPT::BUCKET_CHOWN, OPT::METADATA_PUT,
OPT::METADATA_RM, OPT::MFA_CREATE,
OPT::MFA_REMOVE, OPT::MFA_RESYNC,
OPT::CAPS_ADD, OPT::CAPS_RM,
OPT::ROLE_CREATE, OPT::ROLE_DELETE,
OPT::ROLE_POLICY_PUT, OPT::ROLE_POLICY_DELETE};
bool print_warning_message = (non_master_ops_list.find(opt_cmd) != non_master_ops_list.end() &&
non_master_cmd);
if (print_warning_message) {
cerr << "Please run the command on master zone. Performing this operation on non-master zone leads to inconsistent metadata between zones" << std::endl;
cerr << "Are you sure you want to go ahead? (requires --yes-i-really-mean-it)" << std::endl;
return EINVAL;
}
if (!rgw::sal::User::empty(user)) {
user_op.set_user_id(user->get_id());
bucket_op.set_user_id(user->get_id());
}
if (!display_name.empty())
user_op.set_display_name(display_name);
if (!user_email.empty())
user_op.set_user_email(user_email);
if (!rgw::sal::User::empty(user)) {
user_op.set_new_user_id(new_user_id);
}
if (!access_key.empty())
user_op.set_access_key(access_key);
if (!secret_key.empty())
user_op.set_secret_key(secret_key);
if (!subuser.empty())
user_op.set_subuser(subuser);
if (!caps.empty())
user_op.set_caps(caps);
user_op.set_purge_data(purge_data);
if (purge_keys)
user_op.set_purge_keys();
if (gen_access_key)
user_op.set_generate_key();
if (gen_secret_key)
user_op.set_gen_secret(); // assume that a key pair should be created
if (max_buckets_specified)
user_op.set_max_buckets(max_buckets);
if (admin_specified)
user_op.set_admin(admin);
if (system_specified)
user_op.set_system(system);
if (set_perm)
user_op.set_perm(perm_mask);
if (set_temp_url_key) {
map<int, string>::iterator iter = temp_url_keys.begin();
for (; iter != temp_url_keys.end(); ++iter) {
user_op.set_temp_url_key(iter->second, iter->first);
}
}
if (!op_mask_str.empty()) {
uint32_t op_mask;
int ret = rgw_parse_op_type_list(op_mask_str, &op_mask);
if (ret < 0) {
cerr << "failed to parse op_mask: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
user_op.set_op_mask(op_mask);
}
if (key_type != KEY_TYPE_UNDEFINED)
user_op.set_key_type(key_type);
// set suspension operation parameters
if (opt_cmd == OPT::USER_ENABLE)
user_op.set_suspension(false);
else if (opt_cmd == OPT::USER_SUSPEND)
user_op.set_suspension(true);
if (!placement_id.empty()) {
rgw_placement_rule target_rule;
target_rule.name = placement_id;
target_rule.storage_class = opt_storage_class.value_or("");
if (!driver->valid_placement(target_rule)) {
cerr << "NOTICE: invalid dest placement: " << target_rule.to_str() << std::endl;
return EINVAL;
}
user_op.set_default_placement(target_rule);
}
if (!tags.empty()) {
user_op.set_placement_tags(tags);
}
// RGWUser to use for user operations
RGWUser ruser;
int ret = 0;
if (!(rgw::sal::User::empty(user) && access_key.empty()) || !subuser.empty()) {
ret = ruser.init(dpp(), driver, user_op, null_yield);
if (ret < 0) {
cerr << "user.init failed: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
}
/* populate bucket operation */
bucket_op.set_bucket_name(bucket_name);
bucket_op.set_object(object);
bucket_op.set_check_objects(check_objects);
bucket_op.set_delete_children(delete_child_objects);
bucket_op.set_fix_index(fix);
bucket_op.set_max_aio(max_concurrent_ios);
// required to gather errors from operations
std::string err_msg;
bool output_user_info = true;
switch (opt_cmd) {
case OPT::USER_INFO:
if (rgw::sal::User::empty(user) && access_key.empty()) {
cerr << "ERROR: --uid or --access-key required" << std::endl;
return EINVAL;
}
break;
case OPT::USER_CREATE:
if (!user_op.has_existing_user()) {
user_op.set_generate_key(); // generate a new key by default
}
ret = ruser.add(dpp(), user_op, null_yield, &err_msg);
if (ret < 0) {
cerr << "could not create user: " << err_msg << std::endl;
if (ret == -ERR_INVALID_TENANT_NAME)
ret = -EINVAL;
return -ret;
}
if (!subuser.empty()) {
ret = ruser.subusers.add(dpp(),user_op, null_yield, &err_msg);
if (ret < 0) {
cerr << "could not create subuser: " << err_msg << std::endl;
return -ret;
}
}
break;
case OPT::USER_RM:
ret = ruser.remove(dpp(), user_op, null_yield, &err_msg);
if (ret < 0) {
cerr << "could not remove user: " << err_msg << std::endl;
return -ret;
}
output_user_info = false;
break;
case OPT::USER_RENAME:
if (yes_i_really_mean_it) {
user_op.set_overwrite_new_user(true);
}
ret = ruser.rename(user_op, null_yield, dpp(), &err_msg);
if (ret < 0) {
if (ret == -EEXIST) {
err_msg += ". to overwrite this user, add --yes-i-really-mean-it";
}
cerr << "could not rename user: " << err_msg << std::endl;
return -ret;
}
break;
case OPT::USER_ENABLE:
case OPT::USER_SUSPEND:
case OPT::USER_MODIFY:
ret = ruser.modify(dpp(), user_op, null_yield, &err_msg);
if (ret < 0) {
cerr << "could not modify user: " << err_msg << std::endl;
return -ret;
}
break;
case OPT::SUBUSER_CREATE:
ret = ruser.subusers.add(dpp(), user_op, null_yield, &err_msg);
if (ret < 0) {
cerr << "could not create subuser: " << err_msg << std::endl;
return -ret;
}
break;
case OPT::SUBUSER_MODIFY:
ret = ruser.subusers.modify(dpp(), user_op, null_yield, &err_msg);
if (ret < 0) {
cerr << "could not modify subuser: " << err_msg << std::endl;
return -ret;
}
break;
case OPT::SUBUSER_RM:
ret = ruser.subusers.remove(dpp(), user_op, null_yield, &err_msg);
if (ret < 0) {
cerr << "could not remove subuser: " << err_msg << std::endl;
return -ret;
}
break;
case OPT::CAPS_ADD:
ret = ruser.caps.add(dpp(), user_op, null_yield, &err_msg);
if (ret < 0) {
cerr << "could not add caps: " << err_msg << std::endl;
return -ret;
}
break;
case OPT::CAPS_RM:
ret = ruser.caps.remove(dpp(), user_op, null_yield, &err_msg);
if (ret < 0) {
cerr << "could not remove caps: " << err_msg << std::endl;
return -ret;
}
break;
case OPT::KEY_CREATE:
ret = ruser.keys.add(dpp(), user_op, null_yield, &err_msg);
if (ret < 0) {
cerr << "could not create key: " << err_msg << std::endl;
return -ret;
}
break;
case OPT::KEY_RM:
ret = ruser.keys.remove(dpp(), user_op, null_yield, &err_msg);
if (ret < 0) {
cerr << "could not remove key: " << err_msg << std::endl;
return -ret;
}
break;
case OPT::PERIOD_PUSH:
{
RGWEnv env;
req_info info(g_ceph_context, &env);
info.method = "POST";
info.request_uri = "/admin/realm/period";
map<string, string> ¶ms = info.args.get_params();
if (!realm_id.empty())
params["realm_id"] = realm_id;
if (!realm_name.empty())
params["realm_name"] = realm_name;
if (!period_id.empty())
params["period_id"] = period_id;
if (!period_epoch.empty())
params["epoch"] = period_epoch;
// load the period
RGWPeriod period;
int ret = cfgstore->read_period(dpp(), null_yield, period_id,
std::nullopt, period);
if (ret < 0) {
cerr << "failed to load period: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
// json format into a bufferlist
JSONFormatter jf(false);
encode_json("period", period, &jf);
bufferlist bl;
jf.flush(bl);
JSONParser p;
ret = send_to_remote_or_url(nullptr, url, opt_region,
access_key, secret_key,
info, bl, p);
if (ret < 0) {
cerr << "request failed: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
}
return 0;
case OPT::PERIOD_UPDATE:
{
int ret = update_period(cfgstore.get(), realm_id, realm_name,
period_epoch, commit, remote, url,
opt_region, access_key, secret_key,
formatter.get(), yes_i_really_mean_it);
if (ret < 0) {
return -ret;
}
}
return 0;
case OPT::PERIOD_COMMIT:
{
// read realm and staging period
RGWRealm realm;
std::unique_ptr<rgw::sal::RealmWriter> realm_writer;
int ret = rgw::read_realm(dpp(), null_yield, cfgstore.get(),
realm_id, realm_name,
realm, &realm_writer);
if (ret < 0) {
cerr << "Error initializing realm: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
period_id = rgw::get_staging_period_id(realm.id);
epoch_t epoch = 1;
RGWPeriod period;
ret = cfgstore->read_period(dpp(), null_yield, period_id, epoch, period);
if (ret < 0) {
cerr << "failed to load period: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
ret = commit_period(cfgstore.get(), realm, *realm_writer, period,
remote, url, opt_region, access_key, secret_key,
yes_i_really_mean_it);
if (ret < 0) {
cerr << "failed to commit period: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
encode_json("period", period, formatter.get());
formatter->flush(cout);
}
return 0;
case OPT::ROLE_CREATE:
{
if (role_name.empty()) {
cerr << "ERROR: role name is empty" << std::endl;
return -EINVAL;
}
if (assume_role_doc.empty()) {
cerr << "ERROR: assume role policy document is empty" << std::endl;
return -EINVAL;
}
bufferlist bl = bufferlist::static_from_string(assume_role_doc);
try {
const rgw::IAM::Policy p(
g_ceph_context, tenant, bl,
g_ceph_context->_conf.get_val<bool>(
"rgw_policy_reject_invalid_principals"));
} catch (rgw::IAM::PolicyParseException& e) {
cerr << "failed to parse policy: " << e.what() << std::endl;
return -EINVAL;
}
std::unique_ptr<rgw::sal::RGWRole> role = driver->get_role(role_name, tenant, path, assume_role_doc);
ret = role->create(dpp(), true, "", null_yield);
if (ret < 0) {
return -ret;
}
show_role_info(role.get(), formatter.get());
return 0;
}
case OPT::ROLE_DELETE:
{
if (role_name.empty()) {
cerr << "ERROR: empty role name" << std::endl;
return -EINVAL;
}
std::unique_ptr<rgw::sal::RGWRole> role = driver->get_role(role_name, tenant);
ret = role->delete_obj(dpp(), null_yield);
if (ret < 0) {
return -ret;
}
cout << "role: " << role_name << " successfully deleted" << std::endl;
return 0;
}
case OPT::ROLE_GET:
{
if (role_name.empty()) {
cerr << "ERROR: empty role name" << std::endl;
return -EINVAL;
}
std::unique_ptr<rgw::sal::RGWRole> role = driver->get_role(role_name, tenant);
ret = role->get(dpp(), null_yield);
if (ret < 0) {
return -ret;
}
show_role_info(role.get(), formatter.get());
return 0;
}
case OPT::ROLE_TRUST_POLICY_MODIFY:
{
if (role_name.empty()) {
cerr << "ERROR: role name is empty" << std::endl;
return -EINVAL;
}
if (assume_role_doc.empty()) {
cerr << "ERROR: assume role policy document is empty" << std::endl;
return -EINVAL;
}
bufferlist bl = bufferlist::static_from_string(assume_role_doc);
try {
const rgw::IAM::Policy p(g_ceph_context, tenant, bl,
g_ceph_context->_conf.get_val<bool>(
"rgw_policy_reject_invalid_principals"));
} catch (rgw::IAM::PolicyParseException& e) {
cerr << "failed to parse policy: " << e.what() << std::endl;
return -EINVAL;
}
std::unique_ptr<rgw::sal::RGWRole> role = driver->get_role(role_name, tenant);
ret = role->get(dpp(), null_yield);
if (ret < 0) {
return -ret;
}
role->update_trust_policy(assume_role_doc);
ret = role->update(dpp(), null_yield);
if (ret < 0) {
return -ret;
}
cout << "Assume role policy document updated successfully for role: " << role_name << std::endl;
return 0;
}
case OPT::ROLE_LIST:
{
vector<std::unique_ptr<rgw::sal::RGWRole>> result;
ret = driver->get_roles(dpp(), null_yield, path_prefix, tenant, result);
if (ret < 0) {
return -ret;
}
show_roles_info(result, formatter.get());
return 0;
}
case OPT::ROLE_POLICY_PUT:
{
if (role_name.empty()) {
cerr << "role name is empty" << std::endl;
return -EINVAL;
}
if (policy_name.empty()) {
cerr << "policy name is empty" << std::endl;
return -EINVAL;
}
if (perm_policy_doc.empty() && infile.empty()) {
cerr << "permission policy document is empty" << std::endl;
return -EINVAL;
}
bufferlist bl;
if (!infile.empty()) {
int ret = read_input(infile, bl);
if (ret < 0) {
cerr << "ERROR: failed to read input policy document: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
perm_policy_doc = bl.to_str();
} else {
bl = bufferlist::static_from_string(perm_policy_doc);
}
try {
const rgw::IAM::Policy p(g_ceph_context, tenant, bl,
g_ceph_context->_conf.get_val<bool>(
"rgw_policy_reject_invalid_principals"));
} catch (rgw::IAM::PolicyParseException& e) {
cerr << "failed to parse perm policy: " << e.what() << std::endl;
return -EINVAL;
}
std::unique_ptr<rgw::sal::RGWRole> role = driver->get_role(role_name, tenant);
ret = role->get(dpp(), null_yield);
if (ret < 0) {
return -ret;
}
role->set_perm_policy(policy_name, perm_policy_doc);
ret = role->update(dpp(), null_yield);
if (ret < 0) {
return -ret;
}
cout << "Permission policy attached successfully" << std::endl;
return 0;
}
case OPT::ROLE_POLICY_LIST:
{
if (role_name.empty()) {
cerr << "ERROR: Role name is empty" << std::endl;
return -EINVAL;
}
std::unique_ptr<rgw::sal::RGWRole> role = driver->get_role(role_name, tenant);
ret = role->get(dpp(), null_yield);
if (ret < 0) {
return -ret;
}
std::vector<string> policy_names = role->get_role_policy_names();
show_policy_names(policy_names, formatter.get());
return 0;
}
case OPT::ROLE_POLICY_GET:
{
if (role_name.empty()) {
cerr << "ERROR: role name is empty" << std::endl;
return -EINVAL;
}
if (policy_name.empty()) {
cerr << "ERROR: policy name is empty" << std::endl;
return -EINVAL;
}
std::unique_ptr<rgw::sal::RGWRole> role = driver->get_role(role_name, tenant);
int ret = role->get(dpp(), null_yield);
if (ret < 0) {
return -ret;
}
string perm_policy;
ret = role->get_role_policy(dpp(), policy_name, perm_policy);
if (ret < 0) {
return -ret;
}
show_perm_policy(perm_policy, formatter.get());
return 0;
}
case OPT::ROLE_POLICY_DELETE:
{
if (role_name.empty()) {
cerr << "ERROR: role name is empty" << std::endl;
return -EINVAL;
}
if (policy_name.empty()) {
cerr << "ERROR: policy name is empty" << std::endl;
return -EINVAL;
}
std::unique_ptr<rgw::sal::RGWRole> role = driver->get_role(role_name, tenant);
ret = role->get(dpp(), null_yield);
if (ret < 0) {
return -ret;
}
ret = role->delete_policy(dpp(), policy_name);
if (ret < 0) {
return -ret;
}
ret = role->update(dpp(), null_yield);
if (ret < 0) {
return -ret;
}
cout << "Policy: " << policy_name << " successfully deleted for role: "
<< role_name << std::endl;
return 0;
}
case OPT::ROLE_UPDATE:
{
if (role_name.empty()) {
cerr << "ERROR: role name is empty" << std::endl;
return -EINVAL;
}
std::unique_ptr<rgw::sal::RGWRole> role = driver->get_role(role_name, tenant);
ret = role->get(dpp(), null_yield);
if (ret < 0) {
return -ret;
}
if (!role->validate_max_session_duration(dpp())) {
ret = -EINVAL;
return ret;
}
role->update_max_session_duration(max_session_duration);
ret = role->update(dpp(), null_yield);
if (ret < 0) {
return -ret;
}
cout << "Max session duration updated successfully for role: " << role_name << std::endl;
return 0;
}
default:
output_user_info = false;
}
// output the result of a user operation
if (output_user_info) {
ret = ruser.info(info, &err_msg);
if (ret < 0) {
cerr << "could not fetch user info: " << err_msg << std::endl;
return -ret;
}
show_user_info(info, formatter.get());
}
if (opt_cmd == OPT::POLICY) {
if (format == "xml") {
int ret = RGWBucketAdminOp::dump_s3_policy(driver, bucket_op, cout, dpp(), null_yield);
if (ret < 0) {
cerr << "ERROR: failed to get policy: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
} else {
int ret = RGWBucketAdminOp::get_policy(driver, bucket_op, stream_flusher, dpp(), null_yield);
if (ret < 0) {
cerr << "ERROR: failed to get policy: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
}
}
if (opt_cmd == OPT::BUCKET_LIMIT_CHECK) {
void *handle;
std::list<std::string> user_ids;
metadata_key = "user";
int max = 1000;
bool truncated;
if (!rgw::sal::User::empty(user)) {
user_ids.push_back(user->get_id().id);
ret =
RGWBucketAdminOp::limit_check(driver, bucket_op, user_ids, stream_flusher,
null_yield, dpp(), warnings_only);
} else {
/* list users in groups of max-keys, then perform user-bucket
* limit-check on each group */
ret = driver->meta_list_keys_init(dpp(), metadata_key, string(), &handle);
if (ret < 0) {
cerr << "ERROR: buckets limit check can't get user metadata_key: "
<< cpp_strerror(-ret) << std::endl;
return -ret;
}
do {
ret = driver->meta_list_keys_next(dpp(), handle, max, user_ids,
&truncated);
if (ret < 0 && ret != -ENOENT) {
cerr << "ERROR: buckets limit check lists_keys_next(): "
<< cpp_strerror(-ret) << std::endl;
break;
} else {
/* ok, do the limit checks for this group */
ret =
RGWBucketAdminOp::limit_check(driver, bucket_op, user_ids, stream_flusher,
null_yield, dpp(), warnings_only);
if (ret < 0)
break;
}
user_ids.clear();
} while (truncated);
driver->meta_list_keys_complete(handle);
}
return -ret;
} /* OPT::BUCKET_LIMIT_CHECK */
if (opt_cmd == OPT::BUCKETS_LIST) {
if (bucket_name.empty()) {
if (!rgw::sal::User::empty(user)) {
if (!user_op.has_existing_user()) {
cerr << "ERROR: could not find user: " << user << std::endl;
return -ENOENT;
}
}
RGWBucketAdminOp::info(driver, bucket_op, stream_flusher, null_yield, dpp());
} else {
int ret = init_bucket(user.get(), tenant, bucket_name, bucket_id, &bucket);
if (ret < 0) {
cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
formatter->open_array_section("entries");
int count = 0;
static constexpr int MAX_PAGINATE_SIZE = 10000;
static constexpr int DEFAULT_MAX_ENTRIES = 1000;
if (max_entries < 0) {
max_entries = DEFAULT_MAX_ENTRIES;
}
const int paginate_size = std::min(max_entries, MAX_PAGINATE_SIZE);
string prefix;
string delim;
string ns;
rgw::sal::Bucket::ListParams params;
rgw::sal::Bucket::ListResults results;
params.prefix = prefix;
params.delim = delim;
params.marker = rgw_obj_key(marker);
params.ns = ns;
params.enforce_ns = false;
params.list_versions = true;
params.allow_unordered = bool(allow_unordered);
do {
const int remaining = max_entries - count;
ret = bucket->list(dpp(), params, std::min(remaining, paginate_size), results,
null_yield);
if (ret < 0) {
cerr << "ERROR: driver->list_objects(): " << cpp_strerror(-ret) << std::endl;
return -ret;
}
ldpp_dout(dpp(), 20) << "INFO: " << __func__ <<
": list() returned without error; results.objs.sizie()=" <<
results.objs.size() << "results.is_truncated=" << results.is_truncated << ", marker=" <<
params.marker << dendl;
count += results.objs.size();
for (const auto& entry : results.objs) {
encode_json("entry", entry, formatter.get());
}
formatter->flush(cout);
} while (results.is_truncated && count < max_entries);
ldpp_dout(dpp(), 20) << "INFO: " << __func__ << ": done" << dendl;
formatter->close_section();
formatter->flush(cout);
} /* have bucket_name */
} /* OPT::BUCKETS_LIST */
if (opt_cmd == OPT::BUCKET_RADOS_LIST) {
RGWRadosList lister(static_cast<rgw::sal::RadosStore*>(driver),
max_concurrent_ios, orphan_stale_secs, tenant);
if (rgw_obj_fs) {
lister.set_field_separator(*rgw_obj_fs);
}
if (bucket_name.empty()) {
// yes_i_really_mean_it means continue with listing even if
// there are indexless buckets
ret = lister.run(dpp(), yes_i_really_mean_it);
} else {
ret = lister.run(dpp(), bucket_name);
}
if (ret < 0) {
std::cerr <<
"ERROR: bucket radoslist failed to finish before " <<
"encountering error: " << cpp_strerror(-ret) << std::endl;
std::cerr << "************************************"
"************************************" << std::endl;
std::cerr << "WARNING: THE RESULTS ARE NOT RELIABLE AND SHOULD NOT " <<
"BE USED IN DELETING ORPHANS" << std::endl;
std::cerr << "************************************"
"************************************" << std::endl;
return -ret;
}
}
if (opt_cmd == OPT::BUCKET_LAYOUT) {
if (bucket_name.empty()) {
cerr << "ERROR: bucket not specified" << std::endl;
return EINVAL;
}
int ret = init_bucket(user.get(), tenant, bucket_name, bucket_id, &bucket);
if (ret < 0) {
return -ret;
}
const auto& bucket_info = bucket->get_info();
formatter->open_object_section("layout");
encode_json("layout", bucket_info.layout, formatter.get());
formatter->close_section();
formatter->flush(cout);
}
if (opt_cmd == OPT::BUCKET_STATS) {
if (bucket_name.empty() && !bucket_id.empty()) {
rgw_bucket bucket;
if (!rgw_find_bucket_by_id(dpp(), driver->ctx(), driver, marker, bucket_id, &bucket)) {
cerr << "failure: no such bucket id" << std::endl;
return -ENOENT;
}
bucket_op.set_tenant(bucket.tenant);
bucket_op.set_bucket_name(bucket.name);
}
bucket_op.set_fetch_stats(true);
int r = RGWBucketAdminOp::info(driver, bucket_op, stream_flusher, null_yield, dpp());
if (r < 0) {
cerr << "failure: " << cpp_strerror(-r) << ": " << err << std::endl;
return posix_errortrans(-r);
}
}
if (opt_cmd == OPT::BUCKET_LINK) {
bucket_op.set_bucket_id(bucket_id);
bucket_op.set_new_bucket_name(new_bucket_name);
string err;
int r = RGWBucketAdminOp::link(driver, bucket_op, dpp(), null_yield, &err);
if (r < 0) {
cerr << "failure: " << cpp_strerror(-r) << ": " << err << std::endl;
return -r;
}
}
if (opt_cmd == OPT::BUCKET_UNLINK) {
int r = RGWBucketAdminOp::unlink(driver, bucket_op, dpp(), null_yield);
if (r < 0) {
cerr << "failure: " << cpp_strerror(-r) << std::endl;
return -r;
}
}
if (opt_cmd == OPT::BUCKET_SHARD_OBJECTS) {
const auto prefix = opt_prefix ? *opt_prefix : "obj"s;
if (!num_shards_specified) {
cerr << "ERROR: num-shards must be specified."
<< std::endl;
return EINVAL;
}
if (specified_shard_id) {
if (shard_id >= num_shards) {
cerr << "ERROR: shard-id must be less than num-shards."
<< std::endl;
return EINVAL;
}
std::string obj;
uint64_t ctr = 0;
int shard;
do {
obj = fmt::format("{}{:0>20}", prefix, ctr);
shard = RGWSI_BucketIndex_RADOS::bucket_shard_index(obj, num_shards);
++ctr;
} while (shard != shard_id);
formatter->open_object_section("shard_obj");
encode_json("obj", obj, formatter.get());
formatter->close_section();
formatter->flush(cout);
} else {
std::vector<std::string> objs(num_shards);
for (uint64_t ctr = 0, shardsleft = num_shards; shardsleft > 0; ++ctr) {
auto key = fmt::format("{}{:0>20}", prefix, ctr);
auto shard = RGWSI_BucketIndex_RADOS::bucket_shard_index(key, num_shards);
if (objs[shard].empty()) {
objs[shard] = std::move(key);
--shardsleft;
}
}
formatter->open_object_section("shard_objs");
encode_json("objs", objs, formatter.get());
formatter->close_section();
formatter->flush(cout);
}
}
if (opt_cmd == OPT::BUCKET_OBJECT_SHARD) {
if (!num_shards_specified || object.empty()) {
cerr << "ERROR: num-shards and object must be specified."
<< std::endl;
return EINVAL;
}
auto shard = RGWSI_BucketIndex_RADOS::bucket_shard_index(object, num_shards);
formatter->open_object_section("obj_shard");
encode_json("shard", shard, formatter.get());
formatter->close_section();
formatter->flush(cout);
}
if (opt_cmd == OPT::BUCKET_CHOWN) {
if (bucket_name.empty()) {
cerr << "ERROR: bucket name not specified" << std::endl;
return EINVAL;
}
bucket_op.set_bucket_name(bucket_name);
bucket_op.set_new_bucket_name(new_bucket_name);
string err;
int r = RGWBucketAdminOp::chown(driver, bucket_op, marker, dpp(), null_yield, &err);
if (r < 0) {
cerr << "failure: " << cpp_strerror(-r) << ": " << err << std::endl;
return -r;
}
}
if (opt_cmd == OPT::LOG_LIST) {
// filter by date?
if (date.size() && date.size() != 10) {
cerr << "bad date format for '" << date << "', expect YYYY-MM-DD" << std::endl;
return EINVAL;
}
formatter->reset();
formatter->open_array_section("logs");
RGWAccessHandle h;
int r = static_cast<rgw::sal::RadosStore*>(driver)->getRados()->log_list_init(dpp(), date, &h);
if (r == -ENOENT) {
// no logs.
} else {
if (r < 0) {
cerr << "log list: error " << r << std::endl;
return -r;
}
while (true) {
string name;
int r = static_cast<rgw::sal::RadosStore*>(driver)->getRados()->log_list_next(h, &name);
if (r == -ENOENT)
break;
if (r < 0) {
cerr << "log list: error " << r << std::endl;
return -r;
}
formatter->dump_string("object", name);
}
}
formatter->close_section();
formatter->flush(cout);
cout << std::endl;
}
if (opt_cmd == OPT::LOG_SHOW || opt_cmd == OPT::LOG_RM) {
if (object.empty() && (date.empty() || bucket_name.empty() || bucket_id.empty())) {
cerr << "specify an object or a date, bucket and bucket-id" << std::endl;
exit(1);
}
string oid;
if (!object.empty()) {
oid = object;
} else {
oid = date;
oid += "-";
oid += bucket_id;
oid += "-";
oid += bucket_name;
}
if (opt_cmd == OPT::LOG_SHOW) {
RGWAccessHandle h;
int r = static_cast<rgw::sal::RadosStore*>(driver)->getRados()->log_show_init(dpp(), oid, &h);
if (r < 0) {
cerr << "error opening log " << oid << ": " << cpp_strerror(-r) << std::endl;
return -r;
}
formatter->reset();
formatter->open_object_section("log");
struct rgw_log_entry entry;
// peek at first entry to get bucket metadata
r = static_cast<rgw::sal::RadosStore*>(driver)->getRados()->log_show_next(dpp(), h, &entry);
if (r < 0) {
cerr << "error reading log " << oid << ": " << cpp_strerror(-r) << std::endl;
return -r;
}
formatter->dump_string("bucket_id", entry.bucket_id);
formatter->dump_string("bucket_owner", entry.bucket_owner.to_str());
formatter->dump_string("bucket", entry.bucket);
uint64_t agg_time = 0;
uint64_t agg_bytes_sent = 0;
uint64_t agg_bytes_received = 0;
uint64_t total_entries = 0;
if (show_log_entries)
formatter->open_array_section("log_entries");
do {
using namespace std::chrono;
uint64_t total_time = duration_cast<milliseconds>(entry.total_time).count();
agg_time += total_time;
agg_bytes_sent += entry.bytes_sent;
agg_bytes_received += entry.bytes_received;
total_entries++;
if (skip_zero_entries && entry.bytes_sent == 0 &&
entry.bytes_received == 0)
goto next;
if (show_log_entries) {
rgw_format_ops_log_entry(entry, formatter.get());
formatter->flush(cout);
}
next:
r = static_cast<rgw::sal::RadosStore*>(driver)->getRados()->log_show_next(dpp(), h, &entry);
} while (r > 0);
if (r < 0) {
cerr << "error reading log " << oid << ": " << cpp_strerror(-r) << std::endl;
return -r;
}
if (show_log_entries)
formatter->close_section();
if (show_log_sum) {
formatter->open_object_section("log_sum");
formatter->dump_int("bytes_sent", agg_bytes_sent);
formatter->dump_int("bytes_received", agg_bytes_received);
formatter->dump_int("total_time", agg_time);
formatter->dump_int("total_entries", total_entries);
formatter->close_section();
}
formatter->close_section();
formatter->flush(cout);
cout << std::endl;
}
if (opt_cmd == OPT::LOG_RM) {
int r = static_cast<rgw::sal::RadosStore*>(driver)->getRados()->log_remove(dpp(), oid);
if (r < 0) {
cerr << "error removing log " << oid << ": " << cpp_strerror(-r) << std::endl;
return -r;
}
}
}
if (opt_cmd == OPT::POOL_ADD) {
if (pool_name.empty()) {
cerr << "need to specify pool to add!" << std::endl;
exit(1);
}
int ret = static_cast<rgw::sal::RadosStore*>(driver)->svc()->zone->add_bucket_placement(dpp(), pool, null_yield);
if (ret < 0)
cerr << "failed to add bucket placement: " << cpp_strerror(-ret) << std::endl;
}
if (opt_cmd == OPT::POOL_RM) {
if (pool_name.empty()) {
cerr << "need to specify pool to remove!" << std::endl;
exit(1);
}
int ret = static_cast<rgw::sal::RadosStore*>(driver)->svc()->zone->remove_bucket_placement(dpp(), pool, null_yield);
if (ret < 0)
cerr << "failed to remove bucket placement: " << cpp_strerror(-ret) << std::endl;
}
if (opt_cmd == OPT::POOLS_LIST) {
set<rgw_pool> pools;
int ret = static_cast<rgw::sal::RadosStore*>(driver)->svc()->zone->list_placement_set(dpp(), pools, null_yield);
if (ret < 0) {
cerr << "could not list placement set: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
formatter->reset();
formatter->open_array_section("pools");
for (auto siter = pools.begin(); siter != pools.end(); ++siter) {
formatter->open_object_section("pool");
formatter->dump_string("name", siter->to_str());
formatter->close_section();
}
formatter->close_section();
formatter->flush(cout);
cout << std::endl;
}
if (opt_cmd == OPT::USAGE_SHOW) {
uint64_t start_epoch = 0;
uint64_t end_epoch = (uint64_t)-1;
int ret;
if (!start_date.empty()) {
ret = utime_t::parse_date(start_date, &start_epoch, NULL);
if (ret < 0) {
cerr << "ERROR: failed to parse start date" << std::endl;
return 1;
}
}
if (!end_date.empty()) {
ret = utime_t::parse_date(end_date, &end_epoch, NULL);
if (ret < 0) {
cerr << "ERROR: failed to parse end date" << std::endl;
return 1;
}
}
if (!bucket_name.empty()) {
int ret = init_bucket(user.get(), tenant, bucket_name, bucket_id, &bucket);
if (ret < 0) {
cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
}
ret = RGWUsage::show(dpp(), driver, user.get(), bucket.get(), start_epoch,
end_epoch, show_log_entries, show_log_sum, &categories,
stream_flusher);
if (ret < 0) {
cerr << "ERROR: failed to show usage" << std::endl;
return 1;
}
}
if (opt_cmd == OPT::USAGE_TRIM) {
if (rgw::sal::User::empty(user) && bucket_name.empty() &&
start_date.empty() && end_date.empty() && !yes_i_really_mean_it) {
cerr << "usage trim without user/date/bucket specified will remove *all* users data" << std::endl;
cerr << "do you really mean it? (requires --yes-i-really-mean-it)" << std::endl;
return 1;
}
int ret;
uint64_t start_epoch = 0;
uint64_t end_epoch = (uint64_t)-1;
if (!start_date.empty()) {
ret = utime_t::parse_date(start_date, &start_epoch, NULL);
if (ret < 0) {
cerr << "ERROR: failed to parse start date" << std::endl;
return 1;
}
}
if (!end_date.empty()) {
ret = utime_t::parse_date(end_date, &end_epoch, NULL);
if (ret < 0) {
cerr << "ERROR: failed to parse end date" << std::endl;
return 1;
}
}
if (!bucket_name.empty()) {
int ret = init_bucket(user.get(), tenant, bucket_name, bucket_id, &bucket);
if (ret < 0) {
cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
}
ret = RGWUsage::trim(dpp(), driver, user.get(), bucket.get(), start_epoch, end_epoch, null_yield);
if (ret < 0) {
cerr << "ERROR: read_usage() returned ret=" << ret << std::endl;
return 1;
}
}
if (opt_cmd == OPT::USAGE_CLEAR) {
if (!yes_i_really_mean_it) {
cerr << "usage clear would remove *all* users usage data for all time" << std::endl;
cerr << "do you really mean it? (requires --yes-i-really-mean-it)" << std::endl;
return 1;
}
ret = RGWUsage::clear(dpp(), driver, null_yield);
if (ret < 0) {
return ret;
}
}
if (opt_cmd == OPT::OLH_GET || opt_cmd == OPT::OLH_READLOG) {
if (bucket_name.empty()) {
cerr << "ERROR: bucket not specified" << std::endl;
return EINVAL;
}
if (object.empty()) {
cerr << "ERROR: object not specified" << std::endl;
return EINVAL;
}
}
if (opt_cmd == OPT::OLH_GET) {
int ret = init_bucket(user.get(), tenant, bucket_name, bucket_id, &bucket);
if (ret < 0) {
cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
RGWOLHInfo olh;
rgw_obj obj(bucket->get_key(), object);
ret = static_cast<rgw::sal::RadosStore*>(driver)->getRados()->get_olh(dpp(), bucket->get_info(), obj, &olh, null_yield);
if (ret < 0) {
cerr << "ERROR: failed reading olh: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
encode_json("olh", olh, formatter.get());
formatter->flush(cout);
}
if (opt_cmd == OPT::OLH_READLOG) {
int ret = init_bucket(user.get(), tenant, bucket_name, bucket_id, &bucket);
if (ret < 0) {
cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
map<uint64_t, vector<rgw_bucket_olh_log_entry> > log;
bool is_truncated;
std::unique_ptr<rgw::sal::Object> obj = bucket->get_object(object);
RGWObjState *state;
ret = obj->get_obj_state(dpp(), &state, null_yield);
if (ret < 0) {
return -ret;
}
ret = static_cast<rgw::sal::RadosStore*>(driver)->getRados()->bucket_index_read_olh_log(dpp(), bucket->get_info(), *state, obj->get_obj(), 0, &log, &is_truncated, null_yield);
if (ret < 0) {
cerr << "ERROR: failed reading olh: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
formatter->open_object_section("result");
encode_json("is_truncated", is_truncated, formatter.get());
encode_json("log", log, formatter.get());
formatter->close_section();
formatter->flush(cout);
}
if (opt_cmd == OPT::BI_GET) {
if (bucket_name.empty()) {
cerr << "ERROR: bucket name not specified" << std::endl;
return EINVAL;
}
if (object.empty()) {
cerr << "ERROR: object not specified" << std::endl;
return EINVAL;
}
int ret = init_bucket(user.get(), tenant, bucket_name, bucket_id, &bucket);
if (ret < 0) {
cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
rgw_obj obj(bucket->get_key(), object);
if (!object_version.empty()) {
obj.key.set_instance(object_version);
}
rgw_cls_bi_entry entry;
ret = static_cast<rgw::sal::RadosStore*>(driver)->getRados()->bi_get(dpp(), bucket->get_info(), obj, bi_index_type, &entry, null_yield);
if (ret < 0) {
cerr << "ERROR: bi_get(): " << cpp_strerror(-ret) << std::endl;
return -ret;
}
encode_json("entry", entry, formatter.get());
formatter->flush(cout);
}
if (opt_cmd == OPT::BI_PUT) {
if (bucket_name.empty()) {
cerr << "ERROR: bucket name not specified" << std::endl;
return EINVAL;
}
int ret = init_bucket(user.get(), tenant, bucket_name, bucket_id, &bucket);
if (ret < 0) {
cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
rgw_cls_bi_entry entry;
cls_rgw_obj_key key;
ret = read_decode_json(infile, entry, &key);
if (ret < 0) {
return 1;
}
rgw_obj obj(bucket->get_key(), key);
ret = static_cast<rgw::sal::RadosStore*>(driver)->getRados()->bi_put(dpp(), bucket->get_key(), obj, entry, null_yield);
if (ret < 0) {
cerr << "ERROR: bi_put(): " << cpp_strerror(-ret) << std::endl;
return -ret;
}
}
if (opt_cmd == OPT::BI_LIST) {
if (bucket_name.empty()) {
cerr << "ERROR: bucket name not specified" << std::endl;
return EINVAL;
}
int ret = init_bucket(user.get(), tenant, bucket_name, bucket_id, &bucket);
if (ret < 0) {
cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
std::list<rgw_cls_bi_entry> entries;
bool is_truncated;
const auto& index = bucket->get_info().layout.current_index;
const int max_shards = rgw::num_shards(index);
if (max_entries < 0) {
max_entries = 1000;
}
ldpp_dout(dpp(), 20) << "INFO: " << __func__ << ": max_entries=" << max_entries <<
", index=" << index << ", max_shards=" << max_shards << dendl;
formatter->open_array_section("entries");
int i = (specified_shard_id ? shard_id : 0);
for (; i < max_shards; i++) {
ldpp_dout(dpp(), 20) << "INFO: " << __func__ << ": starting shard=" << i << dendl;
RGWRados::BucketShard bs(static_cast<rgw::sal::RadosStore*>(driver)->getRados());
int ret = bs.init(dpp(), bucket->get_info(), index, i, null_yield);
marker.clear();
if (ret < 0) {
cerr << "ERROR: bs.init(bucket=" << bucket << ", shard=" << i << "): " << cpp_strerror(-ret) << std::endl;
return -ret;
}
do {
entries.clear();
// if object is specified, we use that as a filter to only retrieve some some entries
ret = static_cast<rgw::sal::RadosStore*>(driver)->getRados()->bi_list(bs, object, marker, max_entries, &entries, &is_truncated, null_yield);
if (ret < 0) {
cerr << "ERROR: bi_list(): " << cpp_strerror(-ret) << std::endl;
return -ret;
}
ldpp_dout(dpp(), 20) << "INFO: " << __func__ <<
": bi_list() returned without error; entries.size()=" <<
entries.size() << ", is_truncated=" << is_truncated <<
", marker=" << marker << dendl;
for (const auto& entry : entries) {
encode_json("entry", entry, formatter.get());
marker = entry.idx;
}
formatter->flush(cout);
} while (is_truncated);
formatter->flush(cout);
if (specified_shard_id) {
break;
}
}
ldpp_dout(dpp(), 20) << "INFO: " << __func__ << ": done" << dendl;
formatter->close_section();
formatter->flush(cout);
}
if (opt_cmd == OPT::BI_PURGE) {
if (bucket_name.empty()) {
cerr << "ERROR: bucket name not specified" << std::endl;
return EINVAL;
}
int ret = init_bucket(user.get(), tenant, bucket_name, bucket_id, &bucket);
if (ret < 0) {
cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
std::unique_ptr<rgw::sal::Bucket> cur_bucket;
ret = init_bucket(user.get(), tenant, bucket_name, string(), &cur_bucket);
if (ret == -ENOENT) {
// no bucket entrypoint
} else if (ret < 0) {
cerr << "ERROR: could not init current bucket info for bucket_name=" << bucket_name << ": " << cpp_strerror(-ret) << std::endl;
return -ret;
} else if (cur_bucket->get_bucket_id() == bucket->get_bucket_id() &&
!yes_i_really_mean_it) {
cerr << "specified bucket instance points to a current bucket instance" << std::endl;
cerr << "do you really mean it? (requires --yes-i-really-mean-it)" << std::endl;
return EINVAL;
}
const auto& index = bucket->get_info().layout.current_index;
if (index.layout.type == rgw::BucketIndexType::Indexless) {
cerr << "ERROR: indexless bucket has no index to purge" << std::endl;
return EINVAL;
}
const int max_shards = rgw::num_shards(index);
for (int i = 0; i < max_shards; i++) {
RGWRados::BucketShard bs(static_cast<rgw::sal::RadosStore*>(driver)->getRados());
int ret = bs.init(dpp(), bucket->get_info(), index, i, null_yield);
if (ret < 0) {
cerr << "ERROR: bs.init(bucket=" << bucket << ", shard=" << i << "): " << cpp_strerror(-ret) << std::endl;
return -ret;
}
ret = static_cast<rgw::sal::RadosStore*>(driver)->getRados()->bi_remove(dpp(), bs);
if (ret < 0) {
cerr << "ERROR: failed to remove bucket index object: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
}
}
if (opt_cmd == OPT::OBJECT_PUT) {
if (bucket_name.empty()) {
cerr << "ERROR: bucket not specified" << std::endl;
return EINVAL;
}
if (object.empty()) {
cerr << "ERROR: object not specified" << std::endl;
return EINVAL;
}
RGWDataAccess data_access(driver);
rgw_obj_key key(object, object_version);
RGWDataAccess::BucketRef b;
RGWDataAccess::ObjectRef obj;
int ret = data_access.get_bucket(dpp(), tenant, bucket_name, bucket_id, &b, null_yield);
if (ret < 0) {
cerr << "ERROR: failed to init bucket: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
ret = b->get_object(key, &obj);
if (ret < 0) {
cerr << "ERROR: failed to get object: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
bufferlist bl;
ret = read_input(infile, bl);
if (ret < 0) {
cerr << "ERROR: failed to read input: " << cpp_strerror(-ret) << std::endl;
}
map<string, bufferlist> attrs;
ret = obj->put(bl, attrs, dpp(), null_yield);
if (ret < 0) {
cerr << "ERROR: put object returned error: " << cpp_strerror(-ret) << std::endl;
}
}
if (opt_cmd == OPT::OBJECT_RM) {
int ret = init_bucket(user.get(), tenant, bucket_name, bucket_id, &bucket);
if (ret < 0) {
cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
rgw_obj_key key(object, object_version);
ret = rgw_remove_object(dpp(), driver, bucket.get(), key, null_yield);
if (ret < 0) {
cerr << "ERROR: object remove returned: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
}
if (opt_cmd == OPT::OBJECT_REWRITE) {
if (bucket_name.empty()) {
cerr << "ERROR: bucket not specified" << std::endl;
return EINVAL;
}
if (object.empty()) {
cerr << "ERROR: object not specified" << std::endl;
return EINVAL;
}
int ret = init_bucket(user.get(), tenant, bucket_name, bucket_id, &bucket);
if (ret < 0) {
cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
std::unique_ptr<rgw::sal::Object> obj = bucket->get_object(object);
obj->set_instance(object_version);
bool need_rewrite = true;
if (min_rewrite_stripe_size > 0) {
ret = check_min_obj_stripe_size(driver, obj.get(), min_rewrite_stripe_size, &need_rewrite);
if (ret < 0) {
ldpp_dout(dpp(), 0) << "WARNING: check_min_obj_stripe_size failed, r=" << ret << dendl;
}
}
if (need_rewrite) {
RGWRados* store = static_cast<rgw::sal::RadosStore*>(driver)->getRados();
ret = store->rewrite_obj(bucket->get_info(), obj->get_obj(), dpp(), null_yield);
if (ret < 0) {
cerr << "ERROR: object rewrite returned: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
} else {
ldpp_dout(dpp(), 20) << "skipped object" << dendl;
}
} // OPT::OBJECT_REWRITE
if (opt_cmd == OPT::OBJECT_REINDEX) {
if (bucket_name.empty()) {
cerr << "ERROR: --bucket not specified." << std::endl;
return EINVAL;
}
if (object.empty() && objects_file.empty()) {
cerr << "ERROR: neither --object nor --objects-file specified." << std::endl;
return EINVAL;
} else if (!object.empty() && !objects_file.empty()) {
cerr << "ERROR: both --object and --objects-file specified and only one is allowed." << std::endl;
return EINVAL;
} else if (!objects_file.empty() && !object_version.empty()) {
cerr << "ERROR: cannot specify --object_version when --objects-file specified." << std::endl;
return EINVAL;
}
int ret = init_bucket(user.get(), tenant, bucket_name, bucket_id, &bucket);
if (ret < 0) {
cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) <<
"." << std::endl;
return -ret;
}
rgw::sal::RadosStore* rados_store = dynamic_cast<rgw::sal::RadosStore*>(driver);
if (!rados_store) {
cerr <<
"ERROR: this command can only work when the cluster has a RADOS backing store." <<
std::endl;
return EPERM;
}
RGWRados* store = rados_store->getRados();
auto process = [&](const std::string& p_object, const std::string& p_object_version) -> int {
std::unique_ptr<rgw::sal::Object> obj = bucket->get_object(p_object);
obj->set_instance(p_object_version);
ret = store->reindex_obj(bucket->get_info(), obj->get_obj(), dpp(), null_yield);
if (ret < 0) {
return ret;
}
return 0;
};
if (!object.empty()) {
ret = process(object, object_version);
if (ret < 0) {
return -ret;
}
} else {
std::ifstream file;
file.open(objects_file);
if (!file.is_open()) {
std::cerr << "ERROR: unable to open objects-file \"" <<
objects_file << "\"." << std::endl;
return ENOENT;
}
std::string obj_name;
const std::string empty_version;
while (std::getline(file, obj_name)) {
ret = process(obj_name, empty_version);
if (ret < 0) {
std::cerr << "ERROR: while processing \"" << obj_name <<
"\", received " << cpp_strerror(-ret) << "." << std::endl;
if (!yes_i_really_mean_it) {
std::cerr <<
"NOTE: with *caution* you can use --yes-i-really-mean-it to push through errors and continue processing." <<
std::endl;
return -ret;
}
}
} // while
}
} // OPT::OBJECT_REINDEX
if (opt_cmd == OPT::OBJECTS_EXPIRE) {
if (!static_cast<rgw::sal::RadosStore*>(driver)->getRados()->process_expire_objects(dpp(), null_yield)) {
cerr << "ERROR: process_expire_objects() processing returned error." << std::endl;
return 1;
}
}
if (opt_cmd == OPT::OBJECTS_EXPIRE_STALE_LIST) {
ret = RGWBucketAdminOp::fix_obj_expiry(driver, bucket_op, stream_flusher, dpp(), null_yield, true);
if (ret < 0) {
cerr << "ERROR: listing returned " << cpp_strerror(-ret) << std::endl;
return -ret;
}
}
if (opt_cmd == OPT::OBJECTS_EXPIRE_STALE_RM) {
ret = RGWBucketAdminOp::fix_obj_expiry(driver, bucket_op, stream_flusher, dpp(), null_yield, false);
if (ret < 0) {
cerr << "ERROR: removing returned " << cpp_strerror(-ret) << std::endl;
return -ret;
}
}
if (opt_cmd == OPT::BUCKET_REWRITE) {
if (bucket_name.empty()) {
cerr << "ERROR: bucket not specified" << std::endl;
return EINVAL;
}
int ret = init_bucket(user.get(), tenant, bucket_name, bucket_id, &bucket);
if (ret < 0) {
cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
uint64_t start_epoch = 0;
uint64_t end_epoch = 0;
if (!end_date.empty()) {
int ret = utime_t::parse_date(end_date, &end_epoch, NULL);
if (ret < 0) {
cerr << "ERROR: failed to parse end date" << std::endl;
return EINVAL;
}
}
if (!start_date.empty()) {
int ret = utime_t::parse_date(start_date, &start_epoch, NULL);
if (ret < 0) {
cerr << "ERROR: failed to parse start date" << std::endl;
return EINVAL;
}
}
bool is_truncated = true;
bool cls_filtered = true;
rgw_obj_index_key marker;
string empty_prefix;
string empty_delimiter;
formatter->open_object_section("result");
formatter->dump_string("bucket", bucket_name);
formatter->open_array_section("objects");
constexpr uint32_t NUM_ENTRIES = 1000;
uint16_t expansion_factor = 1;
while (is_truncated) {
RGWRados::ent_map_t result;
result.reserve(NUM_ENTRIES);
const auto& current_index = bucket->get_info().layout.current_index;
int r = static_cast<rgw::sal::RadosStore*>(driver)->getRados()->cls_bucket_list_ordered(
dpp(), bucket->get_info(), current_index, RGW_NO_SHARD,
marker, empty_prefix, empty_delimiter,
NUM_ENTRIES, true, expansion_factor,
result, &is_truncated, &cls_filtered, &marker,
null_yield,
rgw_bucket_object_check_filter);
if (r < 0 && r != -ENOENT) {
cerr << "ERROR: failed operation r=" << r << std::endl;
} else if (r == -ENOENT) {
break;
}
if (result.size() < NUM_ENTRIES / 8) {
++expansion_factor;
} else if (result.size() > NUM_ENTRIES * 7 / 8 &&
expansion_factor > 1) {
--expansion_factor;
}
for (auto iter = result.begin(); iter != result.end(); ++iter) {
rgw_obj_key key = iter->second.key;
rgw_bucket_dir_entry& entry = iter->second;
formatter->open_object_section("object");
formatter->dump_string("name", key.name);
formatter->dump_string("instance", key.instance);
formatter->dump_int("size", entry.meta.size);
utime_t ut(entry.meta.mtime);
ut.gmtime(formatter->dump_stream("mtime"));
if ((entry.meta.size < min_rewrite_size) ||
(entry.meta.size > max_rewrite_size) ||
(start_epoch > 0 && start_epoch > (uint64_t)ut.sec()) ||
(end_epoch > 0 && end_epoch < (uint64_t)ut.sec())) {
formatter->dump_string("status", "Skipped");
} else {
std::unique_ptr<rgw::sal::Object> obj = bucket->get_object(key);
bool need_rewrite = true;
if (min_rewrite_stripe_size > 0) {
r = check_min_obj_stripe_size(driver, obj.get(), min_rewrite_stripe_size, &need_rewrite);
if (r < 0) {
ldpp_dout(dpp(), 0) << "WARNING: check_min_obj_stripe_size failed, r=" << r << dendl;
}
}
if (!need_rewrite) {
formatter->dump_string("status", "Skipped");
} else {
RGWRados* store = static_cast<rgw::sal::RadosStore*>(driver)->getRados();
r = store->rewrite_obj(bucket->get_info(), obj->get_obj(), dpp(), null_yield);
if (r == 0) {
formatter->dump_string("status", "Success");
} else {
formatter->dump_string("status", cpp_strerror(-r));
}
}
}
formatter->dump_int("flags", entry.flags);
formatter->close_section();
formatter->flush(cout);
}
}
formatter->close_section();
formatter->close_section();
formatter->flush(cout);
}
if (opt_cmd == OPT::BUCKET_RESHARD) {
int ret = check_reshard_bucket_params(driver,
bucket_name,
tenant,
bucket_id,
num_shards_specified,
num_shards,
yes_i_really_mean_it,
&bucket);
if (ret < 0) {
return ret;
}
auto zone_svc = static_cast<rgw::sal::RadosStore*>(driver)->svc()->zone;
if (!zone_svc->can_reshard()) {
const auto& zonegroup = zone_svc->get_zonegroup();
std::cerr << "The zonegroup '" << zonegroup.get_name() << "' does not "
"have the resharding feature enabled." << std::endl;
return ENOTSUP;
}
if (!RGWBucketReshard::can_reshard(bucket->get_info(), zone_svc) &&
!yes_i_really_mean_it) {
std::cerr << "Bucket '" << bucket->get_name() << "' already has too many "
"log generations (" << bucket->get_info().layout.logs.size() << ") "
"from previous reshards that peer zones haven't finished syncing. "
"Resharding is not recommended until the old generations sync, but "
"you can force a reshard with --yes-i-really-mean-it." << std::endl;
return EINVAL;
}
RGWBucketReshard br(static_cast<rgw::sal::RadosStore*>(driver),
bucket->get_info(), bucket->get_attrs(),
nullptr /* no callback */);
#define DEFAULT_RESHARD_MAX_ENTRIES 1000
if (max_entries < 1) {
max_entries = DEFAULT_RESHARD_MAX_ENTRIES;
}
ReshardFaultInjector fault;
if (inject_error_at) {
const int code = -inject_error_code.value_or(EIO);
fault.inject(*inject_error_at, InjectError{code, dpp()});
} else if (inject_abort_at) {
fault.inject(*inject_abort_at, InjectAbort{});
}
ret = br.execute(num_shards, fault, max_entries, dpp(), null_yield,
verbose, &cout, formatter.get());
return -ret;
}
if (opt_cmd == OPT::RESHARD_ADD) {
int ret = check_reshard_bucket_params(driver,
bucket_name,
tenant,
bucket_id,
num_shards_specified,
num_shards,
yes_i_really_mean_it,
&bucket);
if (ret < 0) {
return ret;
}
int num_source_shards = rgw::current_num_shards(bucket->get_info().layout);
RGWReshard reshard(static_cast<rgw::sal::RadosStore*>(driver), dpp());
cls_rgw_reshard_entry entry;
entry.time = real_clock::now();
entry.tenant = tenant;
entry.bucket_name = bucket_name;
entry.bucket_id = bucket->get_info().bucket.bucket_id;
entry.old_num_shards = num_source_shards;
entry.new_num_shards = num_shards;
return reshard.add(dpp(), entry, null_yield);
}
if (opt_cmd == OPT::RESHARD_LIST) {
int ret;
int count = 0;
if (max_entries < 0) {
max_entries = 1000;
}
int num_logshards =
driver->ctx()->_conf.get_val<uint64_t>("rgw_reshard_num_logs");
RGWReshard reshard(static_cast<rgw::sal::RadosStore*>(driver), dpp());
formatter->open_array_section("reshard");
for (int i = 0; i < num_logshards; i++) {
bool is_truncated = true;
std::string marker;
do {
std::list<cls_rgw_reshard_entry> entries;
ret = reshard.list(dpp(), i, marker, max_entries - count, entries, &is_truncated);
if (ret < 0) {
cerr << "Error listing resharding buckets: " << cpp_strerror(-ret) << std::endl;
return ret;
}
for (const auto& entry : entries) {
encode_json("entry", entry, formatter.get());
}
if (is_truncated) {
entries.crbegin()->get_key(&marker); // last entry's key becomes marker
}
count += entries.size();
formatter->flush(cout);
} while (is_truncated && count < max_entries);
if (count >= max_entries) {
break;
}
}
formatter->close_section();
formatter->flush(cout);
return 0;
}
if (opt_cmd == OPT::RESHARD_STATUS) {
if (bucket_name.empty()) {
cerr << "ERROR: bucket not specified" << std::endl;
return EINVAL;
}
ret = init_bucket(user.get(), tenant, bucket_name, bucket_id, &bucket);
if (ret < 0) {
cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
RGWBucketReshard br(static_cast<rgw::sal::RadosStore*>(driver),
bucket->get_info(), bucket->get_attrs(),
nullptr /* no callback */);
list<cls_rgw_bucket_instance_entry> status;
int r = br.get_status(dpp(), &status);
if (r < 0) {
cerr << "ERROR: could not get resharding status for bucket " <<
bucket_name << std::endl;
return -r;
}
show_reshard_status(status, formatter.get());
}
if (opt_cmd == OPT::RESHARD_PROCESS) {
RGWReshard reshard(static_cast<rgw::sal::RadosStore*>(driver), true, &cout);
int ret = reshard.process_all_logshards(dpp(), null_yield);
if (ret < 0) {
cerr << "ERROR: failed to process reshard logs, error=" << cpp_strerror(-ret) << std::endl;
return -ret;
}
}
if (opt_cmd == OPT::RESHARD_CANCEL) {
if (bucket_name.empty()) {
cerr << "ERROR: bucket not specified" << std::endl;
return EINVAL;
}
bool bucket_initable = true;
ret = init_bucket(user.get(), tenant, bucket_name, bucket_id, &bucket);
if (ret < 0) {
if (yes_i_really_mean_it) {
bucket_initable = false;
} else {
cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) <<
"; if you want to cancel the reshard request nonetheless, please "
"use the --yes-i-really-mean-it option" << std::endl;
return -ret;
}
}
bool resharding_underway = true;
if (bucket_initable) {
// we did not encounter an error, so let's work with the bucket
RGWBucketReshard br(static_cast<rgw::sal::RadosStore*>(driver),
bucket->get_info(), bucket->get_attrs(),
nullptr /* no callback */);
int ret = br.cancel(dpp(), null_yield);
if (ret < 0) {
if (ret == -EBUSY) {
cerr << "There is ongoing resharding, please retry after " <<
driver->ctx()->_conf.get_val<uint64_t>("rgw_reshard_bucket_lock_duration") <<
" seconds." << std::endl;
return -ret;
} else if (ret == -EINVAL) {
resharding_underway = false;
// we can continue and try to unschedule
} else {
cerr << "Error cancelling bucket \"" << bucket_name <<
"\" resharding: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
}
}
RGWReshard reshard(static_cast<rgw::sal::RadosStore*>(driver), dpp());
cls_rgw_reshard_entry entry;
entry.tenant = tenant;
entry.bucket_name = bucket_name;
ret = reshard.remove(dpp(), entry, null_yield);
if (ret == -ENOENT) {
if (!resharding_underway) {
cerr << "Error, bucket \"" << bucket_name <<
"\" is neither undergoing resharding nor scheduled to undergo "
"resharding." << std::endl;
return EINVAL;
} else {
// we cancelled underway resharding above, so we're good
return 0;
}
} else if (ret < 0) {
cerr << "Error in updating reshard log with bucket \"" <<
bucket_name << "\": " << cpp_strerror(-ret) << std::endl;
return -ret;
}
} // OPT_RESHARD_CANCEL
if (opt_cmd == OPT::OBJECT_UNLINK) {
int ret = init_bucket(user.get(), tenant, bucket_name, bucket_id, &bucket);
if (ret < 0) {
cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
list<rgw_obj_index_key> oid_list;
rgw_obj_key key(object, object_version);
rgw_obj_index_key index_key;
key.get_index_key(&index_key);
oid_list.push_back(index_key);
// note: under rados this removes directly from rados index objects
ret = bucket->remove_objs_from_index(dpp(), oid_list);
if (ret < 0) {
cerr << "ERROR: remove_obj_from_index() returned error: " << cpp_strerror(-ret) << std::endl;
return 1;
}
}
if (opt_cmd == OPT::OBJECT_STAT) {
int ret = init_bucket(user.get(), tenant, bucket_name, bucket_id, &bucket);
if (ret < 0) {
cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
std::unique_ptr<rgw::sal::Object> obj = bucket->get_object(object);
obj->set_instance(object_version);
ret = obj->get_obj_attrs(null_yield, dpp());
if (ret < 0) {
cerr << "ERROR: failed to stat object, returned error: " << cpp_strerror(-ret) << std::endl;
return 1;
}
formatter->open_object_section("object_metadata");
formatter->dump_string("name", object);
formatter->dump_unsigned("size", obj->get_obj_size());
map<string, bufferlist>::iterator iter;
map<string, bufferlist> other_attrs;
for (iter = obj->get_attrs().begin(); iter != obj->get_attrs().end(); ++iter) {
bufferlist& bl = iter->second;
bool handled = false;
if (iter->first == RGW_ATTR_MANIFEST) {
handled = decode_dump<RGWObjManifest>("manifest", bl, formatter.get());
} else if (iter->first == RGW_ATTR_ACL) {
handled = decode_dump<RGWAccessControlPolicy>("policy", bl, formatter.get());
} else if (iter->first == RGW_ATTR_ID_TAG) {
handled = dump_string("tag", bl, formatter.get());
} else if (iter->first == RGW_ATTR_ETAG) {
handled = dump_string("etag", bl, formatter.get());
} else if (iter->first == RGW_ATTR_COMPRESSION) {
handled = decode_dump<RGWCompressionInfo>("compression", bl, formatter.get());
} else if (iter->first == RGW_ATTR_DELETE_AT) {
handled = decode_dump<utime_t>("delete_at", bl, formatter.get());
} else if (iter->first == RGW_ATTR_TORRENT) {
// contains bencoded binary data which shouldn't be output directly
// TODO: decode torrent info for display as json?
formatter->dump_string("torrent", "<contains binary data>");
handled = true;
}
if (!handled)
other_attrs[iter->first] = bl;
}
formatter->open_object_section("attrs");
for (iter = other_attrs.begin(); iter != other_attrs.end(); ++iter) {
dump_string(iter->first.c_str(), iter->second, formatter.get());
}
formatter->close_section();
formatter->close_section();
formatter->flush(cout);
}
if (opt_cmd == OPT::BUCKET_CHECK) {
if (check_head_obj_locator) {
if (bucket_name.empty()) {
cerr << "ERROR: need to specify bucket name" << std::endl;
return EINVAL;
}
do_check_object_locator(tenant, bucket_name, fix, remove_bad, formatter.get());
} else {
RGWBucketAdminOp::check_index(driver, bucket_op, stream_flusher, null_yield, dpp());
}
}
if (opt_cmd == OPT::BUCKET_RM) {
if (!inconsistent_index) {
RGWBucketAdminOp::remove_bucket(driver, bucket_op, null_yield, dpp(), bypass_gc, true);
} else {
if (!yes_i_really_mean_it) {
cerr << "using --inconsistent_index can corrupt the bucket index " << std::endl
<< "do you really mean it? (requires --yes-i-really-mean-it)" << std::endl;
return 1;
}
RGWBucketAdminOp::remove_bucket(driver, bucket_op, null_yield, dpp(), bypass_gc, false);
}
}
if (opt_cmd == OPT::GC_LIST) {
int index = 0;
bool truncated;
bool processing_queue = false;
formatter->open_array_section("entries");
do {
list<cls_rgw_gc_obj_info> result;
int ret = static_cast<rgw::sal::RadosStore*>(driver)->getRados()->list_gc_objs(&index, marker, 1000, !include_all, result, &truncated, processing_queue);
if (ret < 0) {
cerr << "ERROR: failed to list objs: " << cpp_strerror(-ret) << std::endl;
return 1;
}
list<cls_rgw_gc_obj_info>::iterator iter;
for (iter = result.begin(); iter != result.end(); ++iter) {
cls_rgw_gc_obj_info& info = *iter;
formatter->open_object_section("chain_info");
formatter->dump_string("tag", info.tag);
formatter->dump_stream("time") << info.time;
formatter->open_array_section("objs");
list<cls_rgw_obj>::iterator liter;
cls_rgw_obj_chain& chain = info.chain;
for (liter = chain.objs.begin(); liter != chain.objs.end(); ++liter) {
cls_rgw_obj& obj = *liter;
encode_json("obj", obj, formatter.get());
}
formatter->close_section(); // objs
formatter->close_section(); // obj_chain
formatter->flush(cout);
}
} while (truncated);
formatter->close_section();
formatter->flush(cout);
}
if (opt_cmd == OPT::GC_PROCESS) {
rgw::sal::RadosStore* rados_store = dynamic_cast<rgw::sal::RadosStore*>(driver);
if (!rados_store) {
cerr <<
"WARNING: this command can only work when the cluster has a RADOS backing store." <<
std::endl;
return 0;
}
RGWRados* store = rados_store->getRados();
int ret = store->process_gc(!include_all, null_yield);
if (ret < 0) {
cerr << "ERROR: gc processing returned error: " << cpp_strerror(-ret) << std::endl;
return 1;
}
}
if (opt_cmd == OPT::LC_LIST) {
formatter->open_array_section("lifecycle_list");
vector<std::unique_ptr<rgw::sal::Lifecycle::LCEntry>> bucket_lc_map;
string marker;
int index{0};
#define MAX_LC_LIST_ENTRIES 100
if (max_entries < 0) {
max_entries = MAX_LC_LIST_ENTRIES;
}
do {
int ret = static_cast<rgw::sal::RadosStore*>(driver)->getRados()->list_lc_progress(marker, max_entries,
bucket_lc_map, index);
if (ret < 0) {
cerr << "ERROR: failed to list objs: " << cpp_strerror(-ret)
<< std::endl;
return 1;
}
for (const auto& entry : bucket_lc_map) {
formatter->open_object_section("bucket_lc_info");
formatter->dump_string("bucket", entry->get_bucket());
formatter->dump_string("shard", entry->get_oid());
char exp_buf[100];
time_t t{time_t(entry->get_start_time())};
if (std::strftime(
exp_buf, sizeof(exp_buf),
"%a, %d %b %Y %T %Z", std::gmtime(&t))) {
formatter->dump_string("started", exp_buf);
}
string lc_status = LC_STATUS[entry->get_status()];
formatter->dump_string("status", lc_status);
formatter->close_section(); // objs
formatter->flush(cout);
}
} while (!bucket_lc_map.empty());
formatter->close_section(); //lifecycle list
formatter->flush(cout);
}
if (opt_cmd == OPT::LC_GET) {
if (bucket_name.empty()) {
cerr << "ERROR: bucket not specified" << std::endl;
return EINVAL;
}
RGWLifecycleConfiguration config;
ret = init_bucket(user.get(), tenant, bucket_name, bucket_id, &bucket);
if (ret < 0) {
cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
auto aiter = bucket->get_attrs().find(RGW_ATTR_LC);
if (aiter == bucket->get_attrs().end()) {
return -ENOENT;
}
bufferlist::const_iterator iter{&aiter->second};
try {
config.decode(iter);
} catch (const buffer::error& e) {
cerr << "ERROR: decode life cycle config failed" << std::endl;
return -EIO;
}
encode_json("result", config, formatter.get());
formatter->flush(cout);
}
if (opt_cmd == OPT::LC_PROCESS) {
if ((! bucket_name.empty()) ||
(! bucket_id.empty())) {
int ret = init_bucket(nullptr, tenant, bucket_name, bucket_id, &bucket);
if (ret < 0) {
cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret)
<< std::endl;
return ret;
}
}
int ret =
static_cast<rgw::sal::RadosStore*>(driver)->getRados()->process_lc(bucket);
if (ret < 0) {
cerr << "ERROR: lc processing returned error: " << cpp_strerror(-ret) << std::endl;
return 1;
}
}
if (opt_cmd == OPT::LC_RESHARD_FIX) {
ret = RGWBucketAdminOp::fix_lc_shards(driver, bucket_op, stream_flusher, dpp(), null_yield);
if (ret < 0) {
cerr << "ERROR: fixing lc shards: " << cpp_strerror(-ret) << std::endl;
}
}
if (opt_cmd == OPT::ORPHANS_FIND) {
if (!yes_i_really_mean_it) {
cerr << "this command is now deprecated; please consider using the rgw-orphan-list tool; "
<< "accidental removal of active objects cannot be reversed; "
<< "do you really mean it? (requires --yes-i-really-mean-it)"
<< std::endl;
return EINVAL;
} else {
cerr << "IMPORTANT: this command is now deprecated; please consider using the rgw-orphan-list tool"
<< std::endl;
}
RGWOrphanSearch search(static_cast<rgw::sal::RadosStore*>(driver), max_concurrent_ios, orphan_stale_secs);
if (job_id.empty()) {
cerr << "ERROR: --job-id not specified" << std::endl;
return EINVAL;
}
if (pool_name.empty()) {
cerr << "ERROR: --pool not specified" << std::endl;
return EINVAL;
}
RGWOrphanSearchInfo info;
info.pool = pool;
info.job_name = job_id;
info.num_shards = num_shards;
int ret = search.init(dpp(), job_id, &info, detail);
if (ret < 0) {
cerr << "could not init search, ret=" << ret << std::endl;
return -ret;
}
ret = search.run(dpp());
if (ret < 0) {
return -ret;
}
}
if (opt_cmd == OPT::ORPHANS_FINISH) {
if (!yes_i_really_mean_it) {
cerr << "this command is now deprecated; please consider using the rgw-orphan-list tool; "
<< "accidental removal of active objects cannot be reversed; "
<< "do you really mean it? (requires --yes-i-really-mean-it)"
<< std::endl;
return EINVAL;
} else {
cerr << "IMPORTANT: this command is now deprecated; please consider using the rgw-orphan-list tool"
<< std::endl;
}
RGWOrphanSearch search(static_cast<rgw::sal::RadosStore*>(driver), max_concurrent_ios, orphan_stale_secs);
if (job_id.empty()) {
cerr << "ERROR: --job-id not specified" << std::endl;
return EINVAL;
}
int ret = search.init(dpp(), job_id, NULL);
if (ret < 0) {
if (ret == -ENOENT) {
cerr << "job not found" << std::endl;
}
return -ret;
}
ret = search.finish();
if (ret < 0) {
return -ret;
}
}
if (opt_cmd == OPT::ORPHANS_LIST_JOBS){
if (!yes_i_really_mean_it) {
cerr << "this command is now deprecated; please consider using the rgw-orphan-list tool; "
<< "do you really mean it? (requires --yes-i-really-mean-it)"
<< std::endl;
return EINVAL;
} else {
cerr << "IMPORTANT: this command is now deprecated; please consider using the rgw-orphan-list tool"
<< std::endl;
}
RGWOrphanStore orphan_store(static_cast<rgw::sal::RadosStore*>(driver));
int ret = orphan_store.init(dpp());
if (ret < 0){
cerr << "connection to cluster failed!" << std::endl;
return -ret;
}
map <string,RGWOrphanSearchState> m;
ret = orphan_store.list_jobs(m);
if (ret < 0) {
cerr << "job list failed" << std::endl;
return -ret;
}
formatter->open_array_section("entries");
for (const auto &it: m){
if (!extra_info){
formatter->dump_string("job-id",it.first);
} else {
encode_json("orphan_search_state", it.second, formatter.get());
}
}
formatter->close_section();
formatter->flush(cout);
}
if (opt_cmd == OPT::USER_CHECK) {
check_bad_user_bucket_mapping(driver, *user.get(), fix, null_yield, dpp());
}
if (opt_cmd == OPT::USER_STATS) {
if (rgw::sal::User::empty(user)) {
cerr << "ERROR: uid not specified" << std::endl;
return EINVAL;
}
if (reset_stats) {
if (!bucket_name.empty()) {
cerr << "ERROR: --reset-stats does not work on buckets and "
"bucket specified" << std::endl;
return EINVAL;
}
if (sync_stats) {
cerr << "ERROR: sync-stats includes the reset-stats functionality, "
"so at most one of the two should be specified" << std::endl;
return EINVAL;
}
ret = static_cast<rgw::sal::RadosStore*>(driver)->svc()->user->reset_bucket_stats(dpp(), user->get_id(), null_yield);
if (ret < 0) {
cerr << "ERROR: could not reset user stats: " << cpp_strerror(-ret) <<
std::endl;
return -ret;
}
}
if (sync_stats) {
if (!bucket_name.empty()) {
int ret = init_bucket(user.get(), tenant, bucket_name, bucket_id, &bucket);
if (ret < 0) {
cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
ret = bucket->sync_user_stats(dpp(), null_yield);
if (ret < 0) {
cerr << "ERROR: could not sync bucket stats: " <<
cpp_strerror(-ret) << std::endl;
return -ret;
}
} else {
int ret = rgw_user_sync_all_stats(dpp(), driver, user.get(), null_yield);
if (ret < 0) {
cerr << "ERROR: could not sync user stats: " <<
cpp_strerror(-ret) << std::endl;
return -ret;
}
}
}
constexpr bool omit_utilized_stats = false;
RGWStorageStats stats(omit_utilized_stats);
ceph::real_time last_stats_sync;
ceph::real_time last_stats_update;
int ret = user->read_stats(dpp(), null_yield, &stats, &last_stats_sync, &last_stats_update);
if (ret < 0) {
if (ret == -ENOENT) { /* in case of ENOENT */
cerr << "User has not been initialized or user does not exist" << std::endl;
} else {
cerr << "ERROR: can't read user: " << cpp_strerror(ret) << std::endl;
}
return -ret;
}
{
Formatter::ObjectSection os(*formatter, "result");
encode_json("stats", stats, formatter.get());
utime_t last_sync_ut(last_stats_sync);
encode_json("last_stats_sync", last_sync_ut, formatter.get());
utime_t last_update_ut(last_stats_update);
encode_json("last_stats_update", last_update_ut, formatter.get());
}
formatter->flush(cout);
}
if (opt_cmd == OPT::METADATA_GET) {
int ret = static_cast<rgw::sal::RadosStore*>(driver)->ctl()->meta.mgr->get(metadata_key, formatter.get(), null_yield, dpp());
if (ret < 0) {
cerr << "ERROR: can't get key: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
formatter->flush(cout);
}
if (opt_cmd == OPT::METADATA_PUT) {
bufferlist bl;
int ret = read_input(infile, bl);
if (ret < 0) {
cerr << "ERROR: failed to read input: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
ret = static_cast<rgw::sal::RadosStore*>(driver)->ctl()->meta.mgr->put(metadata_key, bl, null_yield, dpp(), RGWMDLogSyncType::APPLY_ALWAYS, false);
if (ret < 0) {
cerr << "ERROR: can't put key: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
}
if (opt_cmd == OPT::METADATA_RM) {
int ret = static_cast<rgw::sal::RadosStore*>(driver)->ctl()->meta.mgr->remove(metadata_key, null_yield, dpp());
if (ret < 0) {
cerr << "ERROR: can't remove key: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
}
if (opt_cmd == OPT::METADATA_LIST || opt_cmd == OPT::USER_LIST) {
if (opt_cmd == OPT::USER_LIST) {
metadata_key = "user";
}
void *handle;
int max = 1000;
int ret = driver->meta_list_keys_init(dpp(), metadata_key, marker, &handle);
if (ret < 0) {
cerr << "ERROR: can't get key: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
bool truncated;
uint64_t count = 0;
if (max_entries_specified) {
formatter->open_object_section("result");
}
formatter->open_array_section("keys");
uint64_t left;
do {
list<string> keys;
left = (max_entries_specified ? max_entries - count : max);
ret = driver->meta_list_keys_next(dpp(), handle, left, keys, &truncated);
if (ret < 0 && ret != -ENOENT) {
cerr << "ERROR: lists_keys_next(): " << cpp_strerror(-ret) << std::endl;
return -ret;
} if (ret != -ENOENT) {
for (list<string>::iterator iter = keys.begin(); iter != keys.end(); ++iter) {
formatter->dump_string("key", *iter);
++count;
}
formatter->flush(cout);
}
} while (truncated && left > 0);
formatter->close_section();
if (max_entries_specified) {
encode_json("truncated", truncated, formatter.get());
encode_json("count", count, formatter.get());
if (truncated) {
encode_json("marker", driver->meta_get_marker(handle), formatter.get());
}
formatter->close_section();
}
formatter->flush(cout);
driver->meta_list_keys_complete(handle);
}
if (opt_cmd == OPT::MDLOG_LIST) {
if (!start_date.empty()) {
std::cerr << "start-date not allowed." << std::endl;
return -EINVAL;
}
if (!end_date.empty()) {
std::cerr << "end-date not allowed." << std::endl;
return -EINVAL;
}
if (!end_marker.empty()) {
std::cerr << "end-marker not allowed." << std::endl;
return -EINVAL;
}
if (!start_marker.empty()) {
if (marker.empty()) {
marker = start_marker;
} else {
std::cerr << "start-marker and marker not both allowed." << std::endl;
return -EINVAL;
}
}
int i = (specified_shard_id ? shard_id : 0);
if (period_id.empty()) {
// use realm's current period
RGWRealm realm;
int ret = rgw::read_realm(dpp(), null_yield, cfgstore.get(),
realm_id, realm_name, realm);
if (ret < 0 ) {
cerr << "failed to load realm: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
period_id = realm.current_period;
std::cerr << "No --period given, using current period="
<< period_id << std::endl;
}
RGWMetadataLog *meta_log = static_cast<rgw::sal::RadosStore*>(driver)->svc()->mdlog->get_log(period_id);
formatter->open_array_section("entries");
for (; i < g_ceph_context->_conf->rgw_md_log_max_shards; i++) {
void *handle;
list<cls_log_entry> entries;
meta_log->init_list_entries(i, {}, {}, marker, &handle);
bool truncated;
do {
int ret = meta_log->list_entries(dpp(), handle, 1000, entries, NULL, &truncated);
if (ret < 0) {
cerr << "ERROR: meta_log->list_entries(): " << cpp_strerror(-ret) << std::endl;
return -ret;
}
for (list<cls_log_entry>::iterator iter = entries.begin(); iter != entries.end(); ++iter) {
cls_log_entry& entry = *iter;
static_cast<rgw::sal::RadosStore*>(driver)->ctl()->meta.mgr->dump_log_entry(entry, formatter.get());
}
formatter->flush(cout);
} while (truncated);
meta_log->complete_list_entries(handle);
if (specified_shard_id)
break;
}
formatter->close_section();
formatter->flush(cout);
}
if (opt_cmd == OPT::MDLOG_STATUS) {
int i = (specified_shard_id ? shard_id : 0);
if (period_id.empty()) {
// use realm's current period
RGWRealm realm;
int ret = rgw::read_realm(dpp(), null_yield, cfgstore.get(),
realm_id, realm_name, realm);
if (ret < 0 ) {
cerr << "failed to load realm: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
period_id = realm.current_period;
std::cerr << "No --period given, using current period="
<< period_id << std::endl;
}
RGWMetadataLog *meta_log = static_cast<rgw::sal::RadosStore*>(driver)->svc()->mdlog->get_log(period_id);
formatter->open_array_section("entries");
for (; i < g_ceph_context->_conf->rgw_md_log_max_shards; i++) {
RGWMetadataLogInfo info;
meta_log->get_info(dpp(), i, &info);
::encode_json("info", info, formatter.get());
if (specified_shard_id)
break;
}
formatter->close_section();
formatter->flush(cout);
}
if (opt_cmd == OPT::MDLOG_AUTOTRIM) {
// need a full history for purging old mdlog periods
static_cast<rgw::sal::RadosStore*>(driver)->svc()->mdlog->init_oldest_log_period(null_yield, dpp());
RGWCoroutinesManager crs(driver->ctx(), driver->get_cr_registry());
RGWHTTPManager http(driver->ctx(), crs.get_completion_mgr());
int ret = http.start();
if (ret < 0) {
cerr << "failed to initialize http client with " << cpp_strerror(ret) << std::endl;
return -ret;
}
auto num_shards = g_conf()->rgw_md_log_max_shards;
auto mltcr = create_admin_meta_log_trim_cr(
dpp(), static_cast<rgw::sal::RadosStore*>(driver), &http, num_shards);
if (!mltcr) {
cerr << "Cluster misconfigured! Unable to trim." << std::endl;
return -EIO;
}
ret = crs.run(dpp(), mltcr);
if (ret < 0) {
cerr << "automated mdlog trim failed with " << cpp_strerror(ret) << std::endl;
return -ret;
}
}
if (opt_cmd == OPT::MDLOG_TRIM) {
if (!start_date.empty()) {
std::cerr << "start-date not allowed." << std::endl;
return -EINVAL;
}
if (!end_date.empty()) {
std::cerr << "end-date not allowed." << std::endl;
return -EINVAL;
}
if (!start_marker.empty()) {
std::cerr << "start-marker not allowed." << std::endl;
return -EINVAL;
}
if (!end_marker.empty()) {
if (marker.empty()) {
marker = end_marker;
} else {
std::cerr << "end-marker and marker not both allowed." << std::endl;
return -EINVAL;
}
}
if (!specified_shard_id) {
cerr << "ERROR: shard-id must be specified for trim operation" << std::endl;
return EINVAL;
}
if (marker.empty()) {
cerr << "ERROR: marker must be specified for trim operation" << std::endl;
return EINVAL;
}
if (period_id.empty()) {
std::cerr << "missing --period argument" << std::endl;
return EINVAL;
}
RGWMetadataLog *meta_log = static_cast<rgw::sal::RadosStore*>(driver)->svc()->mdlog->get_log(period_id);
// trim until -ENODATA
do {
ret = meta_log->trim(dpp(), shard_id, {}, {}, {}, marker);
} while (ret == 0);
if (ret < 0 && ret != -ENODATA) {
cerr << "ERROR: meta_log->trim(): " << cpp_strerror(-ret) << std::endl;
return -ret;
}
}
if (opt_cmd == OPT::SYNC_INFO) {
sync_info(opt_effective_zone_id, opt_bucket, zone_formatter.get());
}
if (opt_cmd == OPT::SYNC_STATUS) {
sync_status(formatter.get());
}
if (opt_cmd == OPT::METADATA_SYNC_STATUS) {
RGWMetaSyncStatusManager sync(static_cast<rgw::sal::RadosStore*>(driver), static_cast<rgw::sal::RadosStore*>(driver)->svc()->rados->get_async_processor());
int ret = sync.init(dpp());
if (ret < 0) {
cerr << "ERROR: sync.init() returned ret=" << ret << std::endl;
return -ret;
}
rgw_meta_sync_status sync_status;
ret = sync.read_sync_status(dpp(), &sync_status);
if (ret < 0) {
cerr << "ERROR: sync.read_sync_status() returned ret=" << ret << std::endl;
return -ret;
}
formatter->open_object_section("summary");
encode_json("sync_status", sync_status, formatter.get());
uint64_t full_total = 0;
uint64_t full_complete = 0;
for (auto marker_iter : sync_status.sync_markers) {
full_total += marker_iter.second.total_entries;
if (marker_iter.second.state == rgw_meta_sync_marker::SyncState::FullSync) {
full_complete += marker_iter.second.pos;
} else {
full_complete += marker_iter.second.total_entries;
}
}
formatter->open_object_section("full_sync");
encode_json("total", full_total, formatter.get());
encode_json("complete", full_complete, formatter.get());
formatter->close_section();
formatter->dump_string("current_time",
to_iso_8601(ceph::real_clock::now(),
iso_8601_format::YMDhms));
formatter->close_section();
formatter->flush(cout);
}
if (opt_cmd == OPT::METADATA_SYNC_INIT) {
RGWMetaSyncStatusManager sync(static_cast<rgw::sal::RadosStore*>(driver), static_cast<rgw::sal::RadosStore*>(driver)->svc()->rados->get_async_processor());
int ret = sync.init(dpp());
if (ret < 0) {
cerr << "ERROR: sync.init() returned ret=" << ret << std::endl;
return -ret;
}
ret = sync.init_sync_status(dpp());
if (ret < 0) {
cerr << "ERROR: sync.init_sync_status() returned ret=" << ret << std::endl;
return -ret;
}
}
if (opt_cmd == OPT::METADATA_SYNC_RUN) {
RGWMetaSyncStatusManager sync(static_cast<rgw::sal::RadosStore*>(driver), static_cast<rgw::sal::RadosStore*>(driver)->svc()->rados->get_async_processor());
int ret = sync.init(dpp());
if (ret < 0) {
cerr << "ERROR: sync.init() returned ret=" << ret << std::endl;
return -ret;
}
ret = sync.run(dpp(), null_yield);
if (ret < 0) {
cerr << "ERROR: sync.run() returned ret=" << ret << std::endl;
return -ret;
}
}
if (opt_cmd == OPT::DATA_SYNC_STATUS) {
if (source_zone.empty()) {
cerr << "ERROR: source zone not specified" << std::endl;
return EINVAL;
}
RGWDataSyncStatusManager sync(static_cast<rgw::sal::RadosStore*>(driver), static_cast<rgw::sal::RadosStore*>(driver)->svc()->rados->get_async_processor(), source_zone, nullptr);
int ret = sync.init(dpp());
if (ret < 0) {
cerr << "ERROR: sync.init() returned ret=" << ret << std::endl;
return -ret;
}
rgw_data_sync_status sync_status;
if (specified_shard_id) {
set<string> pending_buckets;
set<string> recovering_buckets;
rgw_data_sync_marker sync_marker;
ret = sync.read_shard_status(dpp(), shard_id, pending_buckets, recovering_buckets, &sync_marker,
max_entries_specified ? max_entries : 20);
if (ret < 0 && ret != -ENOENT) {
cerr << "ERROR: sync.read_shard_status() returned ret=" << ret << std::endl;
return -ret;
}
formatter->open_object_section("summary");
encode_json("shard_id", shard_id, formatter.get());
encode_json("marker", sync_marker, formatter.get());
encode_json("pending_buckets", pending_buckets, formatter.get());
encode_json("recovering_buckets", recovering_buckets, formatter.get());
formatter->dump_string("current_time",
to_iso_8601(ceph::real_clock::now(),
iso_8601_format::YMDhms));
formatter->close_section();
formatter->flush(cout);
} else {
ret = sync.read_sync_status(dpp(), &sync_status);
if (ret < 0 && ret != -ENOENT) {
cerr << "ERROR: sync.read_sync_status() returned ret=" << ret << std::endl;
return -ret;
}
formatter->open_object_section("summary");
encode_json("sync_status", sync_status, formatter.get());
uint64_t full_total = 0;
uint64_t full_complete = 0;
for (auto marker_iter : sync_status.sync_markers) {
full_total += marker_iter.second.total_entries;
if (marker_iter.second.state == rgw_meta_sync_marker::SyncState::FullSync) {
full_complete += marker_iter.second.pos;
} else {
full_complete += marker_iter.second.total_entries;
}
}
formatter->open_object_section("full_sync");
encode_json("total", full_total, formatter.get());
encode_json("complete", full_complete, formatter.get());
formatter->close_section();
formatter->dump_string("current_time",
to_iso_8601(ceph::real_clock::now(),
iso_8601_format::YMDhms));
formatter->close_section();
formatter->flush(cout);
}
}
if (opt_cmd == OPT::DATA_SYNC_INIT) {
if (source_zone.empty()) {
cerr << "ERROR: source zone not specified" << std::endl;
return EINVAL;
}
RGWDataSyncStatusManager sync(static_cast<rgw::sal::RadosStore*>(driver), static_cast<rgw::sal::RadosStore*>(driver)->svc()->rados->get_async_processor(), source_zone, nullptr);
int ret = sync.init(dpp());
if (ret < 0) {
cerr << "ERROR: sync.init() returned ret=" << ret << std::endl;
return -ret;
}
ret = sync.init_sync_status(dpp());
if (ret < 0) {
cerr << "ERROR: sync.init_sync_status() returned ret=" << ret << std::endl;
return -ret;
}
}
if (opt_cmd == OPT::DATA_SYNC_RUN) {
if (source_zone.empty()) {
cerr << "ERROR: source zone not specified" << std::endl;
return EINVAL;
}
RGWSyncModuleInstanceRef sync_module;
int ret = static_cast<rgw::sal::RadosStore*>(driver)->svc()->sync_modules->get_manager()->create_instance(dpp(), g_ceph_context, static_cast<rgw::sal::RadosStore*>(driver)->svc()->zone->get_zone().tier_type,
static_cast<rgw::sal::RadosStore*>(driver)->svc()->zone->get_zone_params().tier_config, &sync_module);
if (ret < 0) {
ldpp_dout(dpp(), -1) << "ERROR: failed to init sync module instance, ret=" << ret << dendl;
return ret;
}
RGWDataSyncStatusManager sync(static_cast<rgw::sal::RadosStore*>(driver), static_cast<rgw::sal::RadosStore*>(driver)->svc()->rados->get_async_processor(), source_zone, nullptr, sync_module);
ret = sync.init(dpp());
if (ret < 0) {
cerr << "ERROR: sync.init() returned ret=" << ret << std::endl;
return -ret;
}
ret = sync.run(dpp());
if (ret < 0) {
cerr << "ERROR: sync.run() returned ret=" << ret << std::endl;
return -ret;
}
}
if (opt_cmd == OPT::BUCKET_SYNC_INIT) {
if (source_zone.empty()) {
cerr << "ERROR: source zone not specified" << std::endl;
return EINVAL;
}
if (bucket_name.empty()) {
cerr << "ERROR: bucket not specified" << std::endl;
return EINVAL;
}
int ret = init_bucket_for_sync(user.get(), tenant, bucket_name, bucket_id, &bucket);
if (ret < 0) {
return -ret;
}
auto opt_sb = opt_source_bucket;
if (opt_sb && opt_sb->bucket_id.empty()) {
string sbid;
std::unique_ptr<rgw::sal::Bucket> sbuck;
int ret = init_bucket_for_sync(user.get(), opt_sb->tenant, opt_sb->name, sbid, &sbuck);
if (ret < 0) {
return -ret;
}
opt_sb = sbuck->get_key();
}
auto sync = RGWBucketPipeSyncStatusManager::construct(
dpp(), static_cast<rgw::sal::RadosStore*>(driver), source_zone, opt_sb,
bucket->get_key(), extra_info ? &std::cout : nullptr);
if (!sync) {
cerr << "ERROR: sync.init() returned error=" << sync.error() << std::endl;
return -sync.error();
}
ret = (*sync)->init_sync_status(dpp());
if (ret < 0) {
cerr << "ERROR: sync.init_sync_status() returned ret=" << ret << std::endl;
return -ret;
}
}
if (opt_cmd == OPT::BUCKET_SYNC_CHECKPOINT) {
std::optional<rgw_zone_id> opt_source_zone;
if (!source_zone.empty()) {
opt_source_zone = source_zone;
}
if (bucket_name.empty()) {
cerr << "ERROR: bucket not specified" << std::endl;
return EINVAL;
}
int ret = init_bucket(user.get(), tenant, bucket_name, bucket_id, &bucket);
if (ret < 0) {
return -ret;
}
if (!static_cast<rgw::sal::RadosStore*>(driver)->ctl()->bucket->bucket_imports_data(bucket->get_key(), null_yield, dpp())) {
std::cout << "Sync is disabled for bucket " << bucket_name << std::endl;
return 0;
}
RGWBucketSyncPolicyHandlerRef handler;
ret = driver->get_sync_policy_handler(dpp(), std::nullopt, bucket->get_key(), &handler, null_yield);
if (ret < 0) {
std::cerr << "ERROR: failed to get policy handler for bucket ("
<< bucket << "): r=" << ret << ": " << cpp_strerror(-ret) << std::endl;
return -ret;
}
auto timeout_at = ceph::coarse_mono_clock::now() + opt_timeout_sec;
ret = rgw_bucket_sync_checkpoint(dpp(), static_cast<rgw::sal::RadosStore*>(driver), *handler, bucket->get_info(),
opt_source_zone, opt_source_bucket,
opt_retry_delay_ms, timeout_at);
if (ret < 0) {
ldpp_dout(dpp(), -1) << "bucket sync checkpoint failed: " << cpp_strerror(ret) << dendl;
return -ret;
}
}
if ((opt_cmd == OPT::BUCKET_SYNC_DISABLE) || (opt_cmd == OPT::BUCKET_SYNC_ENABLE)) {
if (bucket_name.empty()) {
cerr << "ERROR: bucket not specified" << std::endl;
return EINVAL;
}
if (opt_cmd == OPT::BUCKET_SYNC_DISABLE) {
bucket_op.set_sync_bucket(false);
} else {
bucket_op.set_sync_bucket(true);
}
bucket_op.set_tenant(tenant);
string err_msg;
ret = RGWBucketAdminOp::sync_bucket(driver, bucket_op, dpp(), null_yield, &err_msg);
if (ret < 0) {
cerr << err_msg << std::endl;
return -ret;
}
}
if (opt_cmd == OPT::BUCKET_SYNC_INFO) {
if (bucket_name.empty()) {
cerr << "ERROR: bucket not specified" << std::endl;
return EINVAL;
}
int ret = init_bucket(user.get(), tenant, bucket_name, bucket_id, &bucket);
if (ret < 0) {
return -ret;
}
bucket_sync_info(driver, bucket->get_info(), std::cout);
}
if (opt_cmd == OPT::BUCKET_SYNC_STATUS) {
if (bucket_name.empty()) {
cerr << "ERROR: bucket not specified" << std::endl;
return EINVAL;
}
int ret = init_bucket(user.get(), tenant, bucket_name, bucket_id, &bucket);
if (ret < 0) {
return -ret;
}
bucket_sync_status(driver, bucket->get_info(), source_zone, opt_source_bucket, std::cout);
}
if (opt_cmd == OPT::BUCKET_SYNC_MARKERS) {
if (source_zone.empty()) {
cerr << "ERROR: source zone not specified" << std::endl;
return EINVAL;
}
if (bucket_name.empty()) {
cerr << "ERROR: bucket not specified" << std::endl;
return EINVAL;
}
int ret = init_bucket_for_sync(user.get(), tenant, bucket_name, bucket_id, &bucket);
if (ret < 0) {
return -ret;
}
auto sync = RGWBucketPipeSyncStatusManager::construct(
dpp(), static_cast<rgw::sal::RadosStore*>(driver), source_zone,
opt_source_bucket, bucket->get_key(), nullptr);
if (!sync) {
cerr << "ERROR: sync.init() returned error=" << sync.error() << std::endl;
return -sync.error();
}
auto sync_status = (*sync)->read_sync_status(dpp());
if (!sync_status) {
cerr << "ERROR: sync.read_sync_status() returned error="
<< sync_status.error() << std::endl;
return -sync_status.error();
}
encode_json("sync_status", *sync_status, formatter.get());
formatter->flush(cout);
}
if (opt_cmd == OPT::BUCKET_SYNC_RUN) {
if (source_zone.empty()) {
cerr << "ERROR: source zone not specified" << std::endl;
return EINVAL;
}
if (bucket_name.empty()) {
cerr << "ERROR: bucket not specified" << std::endl;
return EINVAL;
}
int ret = init_bucket_for_sync(user.get(), tenant, bucket_name, bucket_id, &bucket);
if (ret < 0) {
return -ret;
}
auto sync = RGWBucketPipeSyncStatusManager::construct(
dpp(), static_cast<rgw::sal::RadosStore*>(driver), source_zone,
opt_source_bucket, bucket->get_key(), extra_info ? &std::cout : nullptr);
if (!sync) {
cerr << "ERROR: sync.init() returned error=" << sync.error() << std::endl;
return -sync.error();
}
ret = (*sync)->run(dpp());
if (ret < 0) {
cerr << "ERROR: sync.run() returned ret=" << ret << std::endl;
return -ret;
}
}
if (opt_cmd == OPT::BILOG_LIST) {
if (bucket_name.empty()) {
cerr << "ERROR: bucket not specified" << std::endl;
return EINVAL;
}
int ret = init_bucket(user.get(), tenant, bucket_name, bucket_id, &bucket);
if (ret < 0) {
cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
formatter->open_array_section("entries");
bool truncated;
int count = 0;
if (max_entries < 0)
max_entries = 1000;
const auto& logs = bucket->get_info().layout.logs;
auto log_layout = std::reference_wrapper{logs.back()};
if (gen) {
auto i = std::find_if(logs.begin(), logs.end(), rgw::matches_gen(*gen));
if (i == logs.end()) {
cerr << "ERROR: no log layout with gen=" << *gen << std::endl;
return ENOENT;
}
log_layout = *i;
}
do {
list<rgw_bi_log_entry> entries;
ret = static_cast<rgw::sal::RadosStore*>(driver)->svc()->bilog_rados->log_list(dpp(), bucket->get_info(), log_layout, shard_id, marker, max_entries - count, entries, &truncated);
if (ret < 0) {
cerr << "ERROR: list_bi_log_entries(): " << cpp_strerror(-ret) << std::endl;
return -ret;
}
count += entries.size();
for (list<rgw_bi_log_entry>::iterator iter = entries.begin(); iter != entries.end(); ++iter) {
rgw_bi_log_entry& entry = *iter;
encode_json("entry", entry, formatter.get());
marker = entry.id;
}
formatter->flush(cout);
} while (truncated && count < max_entries);
formatter->close_section();
formatter->flush(cout);
}
if (opt_cmd == OPT::SYNC_ERROR_LIST) {
if (max_entries < 0) {
max_entries = 1000;
}
if (!start_date.empty()) {
std::cerr << "start-date not allowed." << std::endl;
return -EINVAL;
}
if (!end_date.empty()) {
std::cerr << "end-date not allowed." << std::endl;
return -EINVAL;
}
if (!end_marker.empty()) {
std::cerr << "end-marker not allowed." << std::endl;
return -EINVAL;
}
if (!start_marker.empty()) {
if (marker.empty()) {
marker = start_marker;
} else {
std::cerr << "start-marker and marker not both allowed." << std::endl;
return -EINVAL;
}
}
bool truncated;
if (shard_id < 0) {
shard_id = 0;
}
formatter->open_array_section("entries");
for (; shard_id < ERROR_LOGGER_SHARDS; ++shard_id) {
formatter->open_object_section("shard");
encode_json("shard_id", shard_id, formatter.get());
formatter->open_array_section("entries");
int count = 0;
string oid = RGWSyncErrorLogger::get_shard_oid(RGW_SYNC_ERROR_LOG_SHARD_PREFIX, shard_id);
do {
list<cls_log_entry> entries;
ret = static_cast<rgw::sal::RadosStore*>(driver)->svc()->cls->timelog.list(dpp(), oid, {}, {}, max_entries - count, entries, marker, &marker, &truncated,
null_yield);
if (ret == -ENOENT) {
break;
}
if (ret < 0) {
cerr << "ERROR: svc.cls->timelog.list(): " << cpp_strerror(-ret) << std::endl;
return -ret;
}
count += entries.size();
for (auto& cls_entry : entries) {
rgw_sync_error_info log_entry;
auto iter = cls_entry.data.cbegin();
try {
decode(log_entry, iter);
} catch (buffer::error& err) {
cerr << "ERROR: failed to decode log entry" << std::endl;
continue;
}
formatter->open_object_section("entry");
encode_json("id", cls_entry.id, formatter.get());
encode_json("section", cls_entry.section, formatter.get());
encode_json("name", cls_entry.name, formatter.get());
encode_json("timestamp", cls_entry.timestamp, formatter.get());
encode_json("info", log_entry, formatter.get());
formatter->close_section();
formatter->flush(cout);
}
} while (truncated && count < max_entries);
formatter->close_section();
formatter->close_section();
if (specified_shard_id) {
break;
}
}
formatter->close_section();
formatter->flush(cout);
}
if (opt_cmd == OPT::SYNC_ERROR_TRIM) {
if (!start_date.empty()) {
std::cerr << "start-date not allowed." << std::endl;
return -EINVAL;
}
if (!end_date.empty()) {
std::cerr << "end-date not allowed." << std::endl;
return -EINVAL;
}
if (!start_marker.empty()) {
std::cerr << "end-date not allowed." << std::endl;
return -EINVAL;
}
if (!end_marker.empty()) {
std::cerr << "end-date not allowed." << std::endl;
return -EINVAL;
}
if (shard_id < 0) {
shard_id = 0;
}
for (; shard_id < ERROR_LOGGER_SHARDS; ++shard_id) {
ret = trim_sync_error_log(shard_id, marker, trim_delay_ms);
if (ret < 0) {
cerr << "ERROR: sync error trim: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
if (specified_shard_id) {
break;
}
}
}
if (opt_cmd == OPT::SYNC_GROUP_CREATE ||
opt_cmd == OPT::SYNC_GROUP_MODIFY) {
CHECK_TRUE(require_opt(opt_group_id), "ERROR: --group-id not specified", EINVAL);
CHECK_TRUE(require_opt(opt_status), "ERROR: --status is not specified (options: forbidden, allowed, enabled)", EINVAL);
SyncPolicyContext sync_policy_ctx(cfgstore.get(), opt_bucket);
ret = sync_policy_ctx.init(zonegroup_id, zonegroup_name);
if (ret < 0) {
return -ret;
}
auto& sync_policy = sync_policy_ctx.get_policy();
if (opt_cmd == OPT::SYNC_GROUP_MODIFY) {
auto iter = sync_policy.groups.find(*opt_group_id);
if (iter == sync_policy.groups.end()) {
cerr << "ERROR: could not find group '" << *opt_group_id << "'" << std::endl;
return ENOENT;
}
}
auto& group = sync_policy.groups[*opt_group_id];
group.id = *opt_group_id;
if (opt_status) {
if (!group.set_status(*opt_status)) {
cerr << "ERROR: unrecognized status (options: forbidden, allowed, enabled)" << std::endl;
return EINVAL;
}
}
ret = sync_policy_ctx.write_policy();
if (ret < 0) {
return -ret;
}
show_result(sync_policy, zone_formatter.get(), cout);
}
if (opt_cmd == OPT::SYNC_GROUP_GET) {
SyncPolicyContext sync_policy_ctx(cfgstore.get(), opt_bucket);
ret = sync_policy_ctx.init(zonegroup_id, zonegroup_name);
if (ret < 0) {
return -ret;
}
auto& sync_policy = sync_policy_ctx.get_policy();
auto& groups = sync_policy.groups;
if (!opt_group_id) {
show_result(groups, zone_formatter.get(), cout);
} else {
auto iter = sync_policy.groups.find(*opt_group_id);
if (iter == sync_policy.groups.end()) {
cerr << "ERROR: could not find group '" << *opt_group_id << "'" << std::endl;
return ENOENT;
}
show_result(iter->second, zone_formatter.get(), cout);
}
}
if (opt_cmd == OPT::SYNC_GROUP_REMOVE) {
CHECK_TRUE(require_opt(opt_group_id), "ERROR: --group-id not specified", EINVAL);
SyncPolicyContext sync_policy_ctx(cfgstore.get(), opt_bucket);
ret = sync_policy_ctx.init(zonegroup_id, zonegroup_name);
if (ret < 0) {
return -ret;
}
auto& sync_policy = sync_policy_ctx.get_policy();
sync_policy.groups.erase(*opt_group_id);
ret = sync_policy_ctx.write_policy();
if (ret < 0) {
return -ret;
}
{
Formatter::ObjectSection os(*zone_formatter.get(), "result");
encode_json("sync_policy", sync_policy, zone_formatter.get());
}
zone_formatter->flush(cout);
}
if (opt_cmd == OPT::SYNC_GROUP_FLOW_CREATE) {
CHECK_TRUE(require_opt(opt_group_id), "ERROR: --group-id not specified", EINVAL);
CHECK_TRUE(require_opt(opt_flow_id), "ERROR: --flow-id not specified", EINVAL);
CHECK_TRUE(require_opt(opt_flow_type),
"ERROR: --flow-type not specified (options: symmetrical, directional)", EINVAL);
CHECK_TRUE((symmetrical_flow_opt(*opt_flow_type) ||
directional_flow_opt(*opt_flow_type)),
"ERROR: --flow-type invalid (options: symmetrical, directional)", EINVAL);
SyncPolicyContext sync_policy_ctx(cfgstore.get(), opt_bucket);
ret = sync_policy_ctx.init(zonegroup_id, zonegroup_name);
if (ret < 0) {
return -ret;
}
auto& sync_policy = sync_policy_ctx.get_policy();
auto iter = sync_policy.groups.find(*opt_group_id);
if (iter == sync_policy.groups.end()) {
cerr << "ERROR: could not find group '" << *opt_group_id << "'" << std::endl;
return ENOENT;
}
auto& group = iter->second;
if (symmetrical_flow_opt(*opt_flow_type)) {
CHECK_TRUE(require_non_empty_opt(opt_zone_ids), "ERROR: --zones not provided for symmetrical flow, or is empty", EINVAL);
rgw_sync_symmetric_group *flow_group;
group.data_flow.find_or_create_symmetrical(*opt_flow_id, &flow_group);
for (auto& z : *opt_zone_ids) {
flow_group->zones.insert(z);
}
} else { /* directional */
CHECK_TRUE(require_non_empty_opt(opt_source_zone_id), "ERROR: --source-zone not provided for directional flow rule, or is empty", EINVAL);
CHECK_TRUE(require_non_empty_opt(opt_dest_zone_id), "ERROR: --dest-zone not provided for directional flow rule, or is empty", EINVAL);
rgw_sync_directional_rule *flow_rule;
group.data_flow.find_or_create_directional(*opt_source_zone_id, *opt_dest_zone_id, &flow_rule);
}
ret = sync_policy_ctx.write_policy();
if (ret < 0) {
return -ret;
}
show_result(sync_policy, zone_formatter.get(), cout);
}
if (opt_cmd == OPT::SYNC_GROUP_FLOW_REMOVE) {
CHECK_TRUE(require_opt(opt_group_id), "ERROR: --group-id not specified", EINVAL);
CHECK_TRUE(require_opt(opt_flow_id), "ERROR: --flow-id not specified", EINVAL);
CHECK_TRUE(require_opt(opt_flow_type),
"ERROR: --flow-type not specified (options: symmetrical, directional)", EINVAL);
CHECK_TRUE((symmetrical_flow_opt(*opt_flow_type) ||
directional_flow_opt(*opt_flow_type)),
"ERROR: --flow-type invalid (options: symmetrical, directional)", EINVAL);
SyncPolicyContext sync_policy_ctx(cfgstore.get(), opt_bucket);
ret = sync_policy_ctx.init(zonegroup_id, zonegroup_name);
if (ret < 0) {
return -ret;
}
auto& sync_policy = sync_policy_ctx.get_policy();
auto iter = sync_policy.groups.find(*opt_group_id);
if (iter == sync_policy.groups.end()) {
cerr << "ERROR: could not find group '" << *opt_group_id << "'" << std::endl;
return ENOENT;
}
auto& group = iter->second;
if (symmetrical_flow_opt(*opt_flow_type)) {
group.data_flow.remove_symmetrical(*opt_flow_id, opt_zone_ids);
} else { /* directional */
CHECK_TRUE(require_non_empty_opt(opt_source_zone_id), "ERROR: --source-zone not provided for directional flow rule, or is empty", EINVAL);
CHECK_TRUE(require_non_empty_opt(opt_dest_zone_id), "ERROR: --dest-zone not provided for directional flow rule, or is empty", EINVAL);
group.data_flow.remove_directional(*opt_source_zone_id, *opt_dest_zone_id);
}
ret = sync_policy_ctx.write_policy();
if (ret < 0) {
return -ret;
}
show_result(sync_policy, zone_formatter.get(), cout);
}
if (opt_cmd == OPT::SYNC_GROUP_PIPE_CREATE ||
opt_cmd == OPT::SYNC_GROUP_PIPE_MODIFY) {
CHECK_TRUE(require_opt(opt_group_id), "ERROR: --group-id not specified", EINVAL);
CHECK_TRUE(require_opt(opt_pipe_id), "ERROR: --pipe-id not specified", EINVAL);
if (opt_cmd == OPT::SYNC_GROUP_PIPE_CREATE) {
CHECK_TRUE(require_non_empty_opt(opt_source_zone_ids), "ERROR: --source-zones not provided or is empty; should be list of zones or '*'", EINVAL);
CHECK_TRUE(require_non_empty_opt(opt_dest_zone_ids), "ERROR: --dest-zones not provided or is empty; should be list of zones or '*'", EINVAL);
}
SyncPolicyContext sync_policy_ctx(cfgstore.get(), opt_bucket);
ret = sync_policy_ctx.init(zonegroup_id, zonegroup_name);
if (ret < 0) {
return -ret;
}
auto& sync_policy = sync_policy_ctx.get_policy();
auto iter = sync_policy.groups.find(*opt_group_id);
if (iter == sync_policy.groups.end()) {
cerr << "ERROR: could not find group '" << *opt_group_id << "'" << std::endl;
return ENOENT;
}
auto& group = iter->second;
rgw_sync_bucket_pipes *pipe;
if (opt_cmd == OPT::SYNC_GROUP_PIPE_CREATE) {
group.find_pipe(*opt_pipe_id, true, &pipe);
} else {
if (!group.find_pipe(*opt_pipe_id, false, &pipe)) {
cerr << "ERROR: could not find pipe '" << *opt_pipe_id << "'" << std::endl;
return ENOENT;
}
}
if (opt_source_zone_ids) {
pipe->source.add_zones(*opt_source_zone_ids);
}
pipe->source.set_bucket(opt_source_tenant,
opt_source_bucket_name,
opt_source_bucket_id);
if (opt_dest_zone_ids) {
pipe->dest.add_zones(*opt_dest_zone_ids);
}
pipe->dest.set_bucket(opt_dest_tenant,
opt_dest_bucket_name,
opt_dest_bucket_id);
pipe->params.source.filter.set_prefix(opt_prefix, !!opt_prefix_rm);
pipe->params.source.filter.set_tags(tags_add, tags_rm);
if (opt_dest_owner) {
pipe->params.dest.set_owner(*opt_dest_owner);
}
if (opt_storage_class) {
pipe->params.dest.set_storage_class(*opt_storage_class);
}
if (opt_priority) {
pipe->params.priority = *opt_priority;
}
if (opt_mode) {
if (*opt_mode == "system") {
pipe->params.mode = rgw_sync_pipe_params::MODE_SYSTEM;
} else if (*opt_mode == "user") {
pipe->params.mode = rgw_sync_pipe_params::MODE_USER;
} else {
cerr << "ERROR: bad mode value: should be one of the following: system, user" << std::endl;
return EINVAL;
}
}
if (!rgw::sal::User::empty(user)) {
pipe->params.user = user->get_id();
} else if (pipe->params.user.empty()) {
auto owner = sync_policy_ctx.get_owner();
if (owner) {
pipe->params.user = *owner;
}
}
ret = sync_policy_ctx.write_policy();
if (ret < 0) {
return -ret;
}
show_result(sync_policy, zone_formatter.get(), cout);
}
if (opt_cmd == OPT::SYNC_GROUP_PIPE_REMOVE) {
CHECK_TRUE(require_opt(opt_group_id), "ERROR: --group-id not specified", EINVAL);
CHECK_TRUE(require_opt(opt_pipe_id), "ERROR: --pipe-id not specified", EINVAL);
SyncPolicyContext sync_policy_ctx(cfgstore.get(), opt_bucket);
ret = sync_policy_ctx.init(zonegroup_id, zonegroup_name);
if (ret < 0) {
return -ret;
}
auto& sync_policy = sync_policy_ctx.get_policy();
auto iter = sync_policy.groups.find(*opt_group_id);
if (iter == sync_policy.groups.end()) {
cerr << "ERROR: could not find group '" << *opt_group_id << "'" << std::endl;
return ENOENT;
}
auto& group = iter->second;
rgw_sync_bucket_pipes *pipe;
if (!group.find_pipe(*opt_pipe_id, false, &pipe)) {
cerr << "ERROR: could not find pipe '" << *opt_pipe_id << "'" << std::endl;
return ENOENT;
}
if (opt_source_zone_ids) {
pipe->source.remove_zones(*opt_source_zone_ids);
}
pipe->source.remove_bucket(opt_source_tenant,
opt_source_bucket_name,
opt_source_bucket_id);
if (opt_dest_zone_ids) {
pipe->dest.remove_zones(*opt_dest_zone_ids);
}
pipe->dest.remove_bucket(opt_dest_tenant,
opt_dest_bucket_name,
opt_dest_bucket_id);
if (!(opt_source_zone_ids ||
opt_source_tenant ||
opt_source_bucket ||
opt_source_bucket_id ||
opt_dest_zone_ids ||
opt_dest_tenant ||
opt_dest_bucket ||
opt_dest_bucket_id)) {
group.remove_pipe(*opt_pipe_id);
}
ret = sync_policy_ctx.write_policy();
if (ret < 0) {
return -ret;
}
show_result(sync_policy, zone_formatter.get(), cout);
}
if (opt_cmd == OPT::SYNC_POLICY_GET) {
SyncPolicyContext sync_policy_ctx(cfgstore.get(), opt_bucket);
ret = sync_policy_ctx.init(zonegroup_id, zonegroup_name);
if (ret < 0) {
return -ret;
}
auto& sync_policy = sync_policy_ctx.get_policy();
show_result(sync_policy, zone_formatter.get(), cout);
}
if (opt_cmd == OPT::BILOG_TRIM) {
if (bucket_name.empty()) {
cerr << "ERROR: bucket not specified" << std::endl;
return EINVAL;
}
int ret = init_bucket(user.get(), tenant, bucket_name, bucket_id, &bucket);
if (ret < 0) {
cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
if (!gen) {
gen = 0;
}
ret = bilog_trim(dpp(), static_cast<rgw::sal::RadosStore*>(driver),
bucket->get_info(), *gen,
shard_id, start_marker, end_marker);
if (ret < 0) {
cerr << "ERROR: trim_bi_log_entries(): " << cpp_strerror(-ret) << std::endl;
return -ret;
}
}
if (opt_cmd == OPT::BILOG_STATUS) {
if (bucket_name.empty()) {
cerr << "ERROR: bucket not specified" << std::endl;
return EINVAL;
}
int ret = init_bucket(user.get(), tenant, bucket_name, bucket_id, &bucket);
if (ret < 0) {
cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
map<int, string> markers;
const auto& logs = bucket->get_info().layout.logs;
auto log_layout = std::reference_wrapper{logs.back()};
if (gen) {
auto i = std::find_if(logs.begin(), logs.end(), rgw::matches_gen(*gen));
if (i == logs.end()) {
cerr << "ERROR: no log layout with gen=" << *gen << std::endl;
return ENOENT;
}
log_layout = *i;
}
ret = static_cast<rgw::sal::RadosStore*>(driver)->svc()->bilog_rados->get_log_status(dpp(), bucket->get_info(), log_layout, shard_id,
&markers, null_yield);
if (ret < 0) {
cerr << "ERROR: get_bi_log_status(): " << cpp_strerror(-ret) << std::endl;
return -ret;
}
formatter->open_object_section("entries");
encode_json("markers", markers, formatter.get());
formatter->dump_string("current_time",
to_iso_8601(ceph::real_clock::now(),
iso_8601_format::YMDhms));
formatter->close_section();
formatter->flush(cout);
}
if (opt_cmd == OPT::BILOG_AUTOTRIM) {
RGWCoroutinesManager crs(driver->ctx(), driver->get_cr_registry());
RGWHTTPManager http(driver->ctx(), crs.get_completion_mgr());
int ret = http.start();
if (ret < 0) {
cerr << "failed to initialize http client with " << cpp_strerror(ret) << std::endl;
return -ret;
}
rgw::BucketTrimConfig config;
configure_bucket_trim(driver->ctx(), config);
rgw::BucketTrimManager trim(static_cast<rgw::sal::RadosStore*>(driver), config);
ret = trim.init();
if (ret < 0) {
cerr << "trim manager init failed with " << cpp_strerror(ret) << std::endl;
return -ret;
}
ret = crs.run(dpp(), trim.create_admin_bucket_trim_cr(&http));
if (ret < 0) {
cerr << "automated bilog trim failed with " << cpp_strerror(ret) << std::endl;
return -ret;
}
}
if (opt_cmd == OPT::DATALOG_LIST) {
formatter->open_array_section("entries");
bool truncated;
int count = 0;
if (max_entries < 0)
max_entries = 1000;
if (!start_date.empty()) {
std::cerr << "start-date not allowed." << std::endl;
return -EINVAL;
}
if (!end_date.empty()) {
std::cerr << "end-date not allowed." << std::endl;
return -EINVAL;
}
if (!end_marker.empty()) {
std::cerr << "end-marker not allowed." << std::endl;
return -EINVAL;
}
if (!start_marker.empty()) {
if (marker.empty()) {
marker = start_marker;
} else {
std::cerr << "start-marker and marker not both allowed." << std::endl;
return -EINVAL;
}
}
auto datalog_svc = static_cast<rgw::sal::RadosStore*>(driver)->svc()->datalog_rados;
RGWDataChangesLog::LogMarker log_marker;
do {
std::vector<rgw_data_change_log_entry> entries;
if (specified_shard_id) {
ret = datalog_svc->list_entries(dpp(), shard_id, max_entries - count,
entries, marker,
&marker, &truncated,
null_yield);
} else {
ret = datalog_svc->list_entries(dpp(), max_entries - count, entries,
log_marker, &truncated, null_yield);
}
if (ret < 0) {
cerr << "ERROR: datalog_svc->list_entries(): " << cpp_strerror(-ret) << std::endl;
return -ret;
}
count += entries.size();
for (const auto& entry : entries) {
if (!extra_info) {
encode_json("entry", entry.entry, formatter.get());
} else {
encode_json("entry", entry, formatter.get());
}
}
formatter.get()->flush(cout);
} while (truncated && count < max_entries);
formatter->close_section();
formatter->flush(cout);
}
if (opt_cmd == OPT::DATALOG_STATUS) {
int i = (specified_shard_id ? shard_id : 0);
formatter->open_array_section("entries");
for (; i < g_ceph_context->_conf->rgw_data_log_num_shards; i++) {
list<cls_log_entry> entries;
RGWDataChangesLogInfo info;
static_cast<rgw::sal::RadosStore*>(driver)->svc()->
datalog_rados->get_info(dpp(), i, &info, null_yield);
::encode_json("info", info, formatter.get());
if (specified_shard_id)
break;
}
formatter->close_section();
formatter->flush(cout);
}
if (opt_cmd == OPT::DATALOG_AUTOTRIM) {
RGWCoroutinesManager crs(driver->ctx(), driver->get_cr_registry());
RGWHTTPManager http(driver->ctx(), crs.get_completion_mgr());
int ret = http.start();
if (ret < 0) {
cerr << "failed to initialize http client with " << cpp_strerror(ret) << std::endl;
return -ret;
}
auto num_shards = g_conf()->rgw_data_log_num_shards;
std::vector<std::string> markers(num_shards);
ret = crs.run(dpp(), create_admin_data_log_trim_cr(dpp(), static_cast<rgw::sal::RadosStore*>(driver), &http, num_shards, markers));
if (ret < 0) {
cerr << "automated datalog trim failed with " << cpp_strerror(ret) << std::endl;
return -ret;
}
}
if (opt_cmd == OPT::DATALOG_TRIM) {
if (!start_date.empty()) {
std::cerr << "start-date not allowed." << std::endl;
return -EINVAL;
}
if (!end_date.empty()) {
std::cerr << "end-date not allowed." << std::endl;
return -EINVAL;
}
if (!start_marker.empty()) {
std::cerr << "start-marker not allowed." << std::endl;
return -EINVAL;
}
if (!end_marker.empty()) {
if (marker.empty()) {
marker = end_marker;
} else {
std::cerr << "end-marker and marker not both allowed." << std::endl;
return -EINVAL;
}
}
if (!specified_shard_id) {
cerr << "ERROR: requires a --shard-id" << std::endl;
return EINVAL;
}
if (marker.empty()) {
cerr << "ERROR: requires a --marker" << std::endl;
return EINVAL;
}
auto datalog = static_cast<rgw::sal::RadosStore*>(driver)->svc()->datalog_rados;
ret = datalog->trim_entries(dpp(), shard_id, marker, null_yield);
if (ret < 0 && ret != -ENODATA) {
cerr << "ERROR: trim_entries(): " << cpp_strerror(-ret) << std::endl;
return -ret;
}
}
if (opt_cmd == OPT::DATALOG_TYPE) {
if (!opt_log_type) {
std::cerr << "log-type not specified." << std::endl;
return -EINVAL;
}
auto datalog = static_cast<rgw::sal::RadosStore*>(driver)->svc()->datalog_rados;
ret = datalog->change_format(dpp(), *opt_log_type, null_yield);
if (ret < 0) {
cerr << "ERROR: change_format(): " << cpp_strerror(-ret) << std::endl;
return -ret;
}
}
if (opt_cmd == OPT::DATALOG_PRUNE) {
auto datalog = static_cast<rgw::sal::RadosStore*>(driver)->svc()->datalog_rados;
std::optional<uint64_t> through;
ret = datalog->trim_generations(dpp(), through, null_yield);
if (ret < 0) {
cerr << "ERROR: trim_generations(): " << cpp_strerror(-ret) << std::endl;
return -ret;
}
if (through) {
std::cout << "Pruned " << *through << " empty generations." << std::endl;
} else {
std::cout << "No empty generations." << std::endl;
}
}
bool quota_op = (opt_cmd == OPT::QUOTA_SET || opt_cmd == OPT::QUOTA_ENABLE || opt_cmd == OPT::QUOTA_DISABLE);
if (quota_op) {
if (bucket_name.empty() && rgw::sal::User::empty(user)) {
cerr << "ERROR: bucket name or uid is required for quota operation" << std::endl;
return EINVAL;
}
if (!bucket_name.empty()) {
if (!quota_scope.empty() && quota_scope != "bucket") {
cerr << "ERROR: invalid quota scope specification." << std::endl;
return EINVAL;
}
set_bucket_quota(driver, opt_cmd, tenant, bucket_name,
max_size, max_objects, have_max_size, have_max_objects);
} else if (!rgw::sal::User::empty(user)) {
if (quota_scope == "bucket") {
return set_user_bucket_quota(opt_cmd, ruser, user_op, max_size, max_objects, have_max_size, have_max_objects);
} else if (quota_scope == "user") {
return set_user_quota(opt_cmd, ruser, user_op, max_size, max_objects, have_max_size, have_max_objects);
} else {
cerr << "ERROR: invalid quota scope specification. Please specify either --quota-scope=bucket, or --quota-scope=user" << std::endl;
return EINVAL;
}
}
}
bool ratelimit_op_set = (opt_cmd == OPT::RATELIMIT_SET || opt_cmd == OPT::RATELIMIT_ENABLE || opt_cmd == OPT::RATELIMIT_DISABLE);
bool ratelimit_op_get = opt_cmd == OPT::RATELIMIT_GET;
if (ratelimit_op_set) {
if (bucket_name.empty() && rgw::sal::User::empty(user)) {
cerr << "ERROR: bucket name or uid is required for ratelimit operation" << std::endl;
return EINVAL;
}
if (!bucket_name.empty()) {
if (!ratelimit_scope.empty() && ratelimit_scope != "bucket") {
cerr << "ERROR: invalid ratelimit scope specification. (bucket scope is not bucket but bucket has been specified)" << std::endl;
return EINVAL;
}
return set_bucket_ratelimit(driver, opt_cmd, tenant, bucket_name,
max_read_ops, max_write_ops,
max_read_bytes, max_write_bytes,
have_max_read_ops, have_max_write_ops,
have_max_read_bytes, have_max_write_bytes);
} else if (!rgw::sal::User::empty(user)) {
if (ratelimit_scope == "user") {
return set_user_ratelimit(opt_cmd, user, max_read_ops, max_write_ops,
max_read_bytes, max_write_bytes,
have_max_read_ops, have_max_write_ops,
have_max_read_bytes, have_max_write_bytes);
} else {
cerr << "ERROR: invalid ratelimit scope specification. Please specify either --ratelimit-scope=bucket, or --ratelimit-scope=user" << std::endl;
return EINVAL;
}
}
}
if (ratelimit_op_get) {
if (bucket_name.empty() && rgw::sal::User::empty(user)) {
cerr << "ERROR: bucket name or uid is required for ratelimit operation" << std::endl;
return EINVAL;
}
if (!bucket_name.empty()) {
if (!ratelimit_scope.empty() && ratelimit_scope != "bucket") {
cerr << "ERROR: invalid ratelimit scope specification. (bucket scope is not bucket but bucket has been specified)" << std::endl;
return EINVAL;
}
return show_bucket_ratelimit(driver, tenant, bucket_name, formatter.get());
} else if (!rgw::sal::User::empty(user)) {
if (ratelimit_scope == "user") {
return show_user_ratelimit(user, formatter.get());
} else {
cerr << "ERROR: invalid ratelimit scope specification. Please specify either --ratelimit-scope=bucket, or --ratelimit-scope=user" << std::endl;
return EINVAL;
}
}
}
if (opt_cmd == OPT::MFA_CREATE) {
rados::cls::otp::otp_info_t config;
if (rgw::sal::User::empty(user)) {
cerr << "ERROR: user id was not provided (via --uid)" << std::endl;
return EINVAL;
}
if (totp_serial.empty()) {
cerr << "ERROR: TOTP device serial number was not provided (via --totp-serial)" << std::endl;
return EINVAL;
}
if (totp_seed.empty()) {
cerr << "ERROR: TOTP device seed was not provided (via --totp-seed)" << std::endl;
return EINVAL;
}
rados::cls::otp::SeedType seed_type;
if (totp_seed_type == "hex") {
seed_type = rados::cls::otp::OTP_SEED_HEX;
} else if (totp_seed_type == "base32") {
seed_type = rados::cls::otp::OTP_SEED_BASE32;
} else {
cerr << "ERROR: invalid seed type: " << totp_seed_type << std::endl;
return EINVAL;
}
config.id = totp_serial;
config.seed = totp_seed;
config.seed_type = seed_type;
if (totp_seconds > 0) {
config.step_size = totp_seconds;
}
if (totp_window > 0) {
config.window = totp_window;
}
real_time mtime = real_clock::now();
string oid = static_cast<rgw::sal::RadosStore*>(driver)->svc()->cls->mfa.get_mfa_oid(user->get_id());
int ret = static_cast<rgw::sal::RadosStore*>(driver)->ctl()->meta.mgr->mutate(RGWSI_MetaBackend_OTP::get_meta_key(user->get_id()),
mtime, &objv_tracker,
null_yield, dpp(),
MDLOG_STATUS_WRITE,
[&] {
return static_cast<rgw::sal::RadosStore*>(driver)->svc()->cls->mfa.create_mfa(dpp(), user->get_id(), config, &objv_tracker, mtime, null_yield);
});
if (ret < 0) {
cerr << "MFA creation failed, error: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
RGWUserInfo& user_info = user_op.get_user_info();
user_info.mfa_ids.insert(totp_serial);
user_op.set_mfa_ids(user_info.mfa_ids);
string err;
ret = ruser.modify(dpp(), user_op, null_yield, &err);
if (ret < 0) {
cerr << "ERROR: failed storing user info, error: " << err << std::endl;
return -ret;
}
}
if (opt_cmd == OPT::MFA_REMOVE) {
if (rgw::sal::User::empty(user)) {
cerr << "ERROR: user id was not provided (via --uid)" << std::endl;
return EINVAL;
}
if (totp_serial.empty()) {
cerr << "ERROR: TOTP device serial number was not provided (via --totp-serial)" << std::endl;
return EINVAL;
}
real_time mtime = real_clock::now();
int ret = static_cast<rgw::sal::RadosStore*>(driver)->ctl()->meta.mgr->mutate(RGWSI_MetaBackend_OTP::get_meta_key(user->get_id()),
mtime, &objv_tracker,
null_yield, dpp(),
MDLOG_STATUS_WRITE,
[&] {
return static_cast<rgw::sal::RadosStore*>(driver)->svc()->cls->mfa.remove_mfa(dpp(), user->get_id(), totp_serial, &objv_tracker, mtime, null_yield);
});
if (ret < 0) {
cerr << "MFA removal failed, error: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
RGWUserInfo& user_info = user_op.get_user_info();
user_info.mfa_ids.erase(totp_serial);
user_op.set_mfa_ids(user_info.mfa_ids);
string err;
ret = ruser.modify(dpp(), user_op, null_yield, &err);
if (ret < 0) {
cerr << "ERROR: failed storing user info, error: " << err << std::endl;
return -ret;
}
}
if (opt_cmd == OPT::MFA_GET) {
if (rgw::sal::User::empty(user)) {
cerr << "ERROR: user id was not provided (via --uid)" << std::endl;
return EINVAL;
}
if (totp_serial.empty()) {
cerr << "ERROR: TOTP device serial number was not provided (via --totp-serial)" << std::endl;
return EINVAL;
}
rados::cls::otp::otp_info_t result;
int ret = static_cast<rgw::sal::RadosStore*>(driver)->svc()->cls->mfa.get_mfa(dpp(), user->get_id(), totp_serial, &result, null_yield);
if (ret < 0) {
if (ret == -ENOENT || ret == -ENODATA) {
cerr << "MFA serial id not found" << std::endl;
} else {
cerr << "MFA retrieval failed, error: " << cpp_strerror(-ret) << std::endl;
}
return -ret;
}
formatter->open_object_section("result");
encode_json("entry", result, formatter.get());
formatter->close_section();
formatter->flush(cout);
}
if (opt_cmd == OPT::MFA_LIST) {
if (rgw::sal::User::empty(user)) {
cerr << "ERROR: user id was not provided (via --uid)" << std::endl;
return EINVAL;
}
list<rados::cls::otp::otp_info_t> result;
int ret = static_cast<rgw::sal::RadosStore*>(driver)->svc()->cls->mfa.list_mfa(dpp(), user->get_id(), &result, null_yield);
if (ret < 0 && ret != -ENOENT) {
cerr << "MFA listing failed, error: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
formatter->open_object_section("result");
encode_json("entries", result, formatter.get());
formatter->close_section();
formatter->flush(cout);
}
if (opt_cmd == OPT::MFA_CHECK) {
if (rgw::sal::User::empty(user)) {
cerr << "ERROR: user id was not provided (via --uid)" << std::endl;
return EINVAL;
}
if (totp_serial.empty()) {
cerr << "ERROR: TOTP device serial number was not provided (via --totp-serial)" << std::endl;
return EINVAL;
}
if (totp_pin.empty()) {
cerr << "ERROR: TOTP device serial number was not provided (via --totp-pin)" << std::endl;
return EINVAL;
}
list<rados::cls::otp::otp_info_t> result;
int ret = static_cast<rgw::sal::RadosStore*>(driver)->svc()->cls->mfa.check_mfa(dpp(), user->get_id(), totp_serial, totp_pin.front(), null_yield);
if (ret < 0) {
cerr << "MFA check failed, error: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
cout << "ok" << std::endl;
}
if (opt_cmd == OPT::MFA_RESYNC) {
if (rgw::sal::User::empty(user)) {
cerr << "ERROR: user id was not provided (via --uid)" << std::endl;
return EINVAL;
}
if (totp_serial.empty()) {
cerr << "ERROR: TOTP device serial number was not provided (via --totp-serial)" << std::endl;
return EINVAL;
}
if (totp_pin.size() != 2) {
cerr << "ERROR: missing two --totp-pin params (--totp-pin=<first> --totp-pin=<second>)" << std::endl;
return EINVAL;
}
rados::cls::otp::otp_info_t config;
int ret = static_cast<rgw::sal::RadosStore*>(driver)->svc()->cls->mfa.get_mfa(dpp(), user->get_id(), totp_serial, &config, null_yield);
if (ret < 0) {
if (ret == -ENOENT || ret == -ENODATA) {
cerr << "MFA serial id not found" << std::endl;
} else {
cerr << "MFA retrieval failed, error: " << cpp_strerror(-ret) << std::endl;
}
return -ret;
}
ceph::real_time now;
ret = static_cast<rgw::sal::RadosStore*>(driver)->svc()->cls->mfa.otp_get_current_time(dpp(), user->get_id(), &now, null_yield);
if (ret < 0) {
cerr << "ERROR: failed to fetch current time from osd: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
time_t time_ofs;
ret = scan_totp(driver->ctx(), now, config, totp_pin, &time_ofs);
if (ret < 0) {
if (ret == -ENOENT) {
cerr << "failed to resync, TOTP values not found in range" << std::endl;
} else {
cerr << "ERROR: failed to scan for TOTP values: " << cpp_strerror(-ret) << std::endl;
}
return -ret;
}
// time offset is a small number and unlikely to overflow
// coverity[store_truncates_time_t:SUPPRESS]
config.time_ofs = time_ofs;
/* now update the backend */
real_time mtime = real_clock::now();
ret = static_cast<rgw::sal::RadosStore*>(driver)->ctl()->meta.mgr->mutate(RGWSI_MetaBackend_OTP::get_meta_key(user->get_id()),
mtime, &objv_tracker,
null_yield, dpp(),
MDLOG_STATUS_WRITE,
[&] {
return static_cast<rgw::sal::RadosStore*>(driver)->svc()->cls->mfa.create_mfa(dpp(), user->get_id(), config, &objv_tracker, mtime, null_yield);
});
if (ret < 0) {
cerr << "MFA update failed, error: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
}
if (opt_cmd == OPT::RESHARD_STALE_INSTANCES_LIST) {
if (!static_cast<rgw::sal::RadosStore*>(driver)->svc()->zone->can_reshard() && !yes_i_really_mean_it) {
cerr << "Resharding disabled in a multisite env, stale instances unlikely from resharding" << std::endl;
cerr << "These instances may not be safe to delete." << std::endl;
cerr << "Use --yes-i-really-mean-it to force displaying these instances." << std::endl;
return EINVAL;
}
ret = RGWBucketAdminOp::list_stale_instances(driver, bucket_op, stream_flusher, dpp(), null_yield);
if (ret < 0) {
cerr << "ERROR: listing stale instances" << cpp_strerror(-ret) << std::endl;
}
}
if (opt_cmd == OPT::RESHARD_STALE_INSTANCES_DELETE) {
if (!static_cast<rgw::sal::RadosStore*>(driver)->svc()->zone->can_reshard()) {
cerr << "Resharding disabled in a multisite env. Stale instances are not safe to be deleted." << std::endl;
return EINVAL;
}
ret = RGWBucketAdminOp::clear_stale_instances(driver, bucket_op, stream_flusher, dpp(), null_yield);
if (ret < 0) {
cerr << "ERROR: deleting stale instances" << cpp_strerror(-ret) << std::endl;
}
}
if (opt_cmd == OPT::PUBSUB_NOTIFICATION_LIST) {
if (bucket_name.empty()) {
cerr << "ERROR: bucket name was not provided (via --bucket)" << std::endl;
return EINVAL;
}
RGWPubSub ps(driver, tenant);
rgw_pubsub_bucket_topics result;
int ret = init_bucket(user.get(), tenant, bucket_name, bucket_id, &bucket);
if (ret < 0) {
cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
const RGWPubSub::Bucket b(ps, bucket.get());
ret = b.get_topics(dpp(), result, null_yield);
if (ret < 0 && ret != -ENOENT) {
cerr << "ERROR: could not get topics: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
encode_json("result", result, formatter.get());
formatter->flush(cout);
}
if (opt_cmd == OPT::PUBSUB_TOPIC_LIST) {
RGWPubSub ps(driver, tenant);
rgw_pubsub_topics result;
int ret = ps.get_topics(dpp(), result, null_yield);
if (ret < 0 && ret != -ENOENT) {
cerr << "ERROR: could not get topics: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
encode_json("result", result, formatter.get());
formatter->flush(cout);
}
if (opt_cmd == OPT::PUBSUB_TOPIC_GET) {
if (topic_name.empty()) {
cerr << "ERROR: topic name was not provided (via --topic)" << std::endl;
return EINVAL;
}
RGWPubSub ps(driver, tenant);
rgw_pubsub_topic topic;
ret = ps.get_topic(dpp(), topic_name, topic, null_yield);
if (ret < 0) {
cerr << "ERROR: could not get topic: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
encode_json("topic", topic, formatter.get());
formatter->flush(cout);
}
if (opt_cmd == OPT::PUBSUB_NOTIFICATION_GET) {
if (notification_id.empty()) {
cerr << "ERROR: notification-id was not provided (via --notification-id)" << std::endl;
return EINVAL;
}
if (bucket_name.empty()) {
cerr << "ERROR: bucket name was not provided (via --bucket)" << std::endl;
return EINVAL;
}
int ret = init_bucket(user.get(), tenant, bucket_name, bucket_id, &bucket);
if (ret < 0) {
cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
RGWPubSub ps(driver, tenant);
rgw_pubsub_bucket_topics bucket_topics;
const RGWPubSub::Bucket b(ps, bucket.get());
ret = b.get_topics(dpp(), bucket_topics, null_yield);
if (ret < 0 && ret != -ENOENT) {
cerr << "ERROR: could not get bucket notifications: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
rgw_pubsub_topic_filter bucket_topic;
ret = b.get_notification_by_id(dpp(), notification_id, bucket_topic, null_yield);
if (ret < 0) {
cerr << "ERROR: could not get notification: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
encode_json("notification", bucket_topic, formatter.get());
formatter->flush(cout);
}
if (opt_cmd == OPT::PUBSUB_TOPIC_RM) {
if (topic_name.empty()) {
cerr << "ERROR: topic name was not provided (via --topic)" << std::endl;
return EINVAL;
}
ret = rgw::notify::remove_persistent_topic(
dpp(), static_cast<rgw::sal::RadosStore*>(driver)->getRados()->get_notif_pool_ctx(), topic_name, null_yield);
if (ret < 0) {
cerr << "ERROR: could not remove persistent topic: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
RGWPubSub ps(driver, tenant);
ret = ps.remove_topic(dpp(), topic_name, null_yield);
if (ret < 0) {
cerr << "ERROR: could not remove topic: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
}
if (opt_cmd == OPT::PUBSUB_NOTIFICATION_RM) {
if (bucket_name.empty()) {
cerr << "ERROR: bucket name was not provided (via --bucket)" << std::endl;
return EINVAL;
}
int ret = init_bucket(user.get(), tenant, bucket_name, bucket_id, &bucket);
if (ret < 0) {
cerr << "ERROR: could not init bucket: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
RGWPubSub ps(driver, tenant);
rgw_pubsub_bucket_topics bucket_topics;
const RGWPubSub::Bucket b(ps, bucket.get());
ret = b.get_topics(dpp(), bucket_topics, null_yield);
if (ret < 0 && ret != -ENOENT) {
cerr << "ERROR: could not get bucket notifications: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
rgw_pubsub_topic_filter bucket_topic;
if(notification_id.empty()) {
ret = b.remove_notifications(dpp(), null_yield);
} else {
ret = b.remove_notification_by_id(dpp(), notification_id, null_yield);
}
}
if (opt_cmd == OPT::PUBSUB_TOPIC_STATS) {
if (topic_name.empty()) {
cerr << "ERROR: topic name was not provided (via --topic)" << std::endl;
return EINVAL;
}
rgw::notify::rgw_topic_stats stats;
ret = rgw::notify::get_persistent_queue_stats_by_topic_name(
dpp(), static_cast<rgw::sal::RadosStore *>(driver)->getRados()->get_notif_pool_ctx(), topic_name,
stats, null_yield);
if (ret < 0) {
cerr << "ERROR: could not get persistent queue: " << cpp_strerror(-ret) << std::endl;
return -ret;
}
encode_json("", stats, formatter.get());
formatter->flush(cout);
}
if (opt_cmd == OPT::SCRIPT_PUT) {
if (!str_script_ctx) {
cerr << "ERROR: context was not provided (via --context)" << std::endl;
return EINVAL;
}
if (infile.empty()) {
cerr << "ERROR: infile was not provided (via --infile)" << std::endl;
return EINVAL;
}
bufferlist bl;
auto rc = read_input(infile, bl);
if (rc < 0) {
cerr << "ERROR: failed to read script: '" << infile << "'. error: " << rc << std::endl;
return -rc;
}
const std::string script = bl.to_str();
std::string err_msg;
if (!rgw::lua::verify(script, err_msg)) {
cerr << "ERROR: script: '" << infile << "' has error: " << std::endl << err_msg << std::endl;
return EINVAL;
}
const rgw::lua::context script_ctx = rgw::lua::to_context(*str_script_ctx);
if (script_ctx == rgw::lua::context::none) {
cerr << "ERROR: invalid script context: " << *str_script_ctx << ". must be one of: " << LUA_CONTEXT_LIST << std::endl;
return EINVAL;
}
if (script_ctx == rgw::lua::context::background && !tenant.empty()) {
cerr << "ERROR: cannot specify tenant in background context" << std::endl;
return EINVAL;
}
auto lua_manager = driver->get_lua_manager();
rc = rgw::lua::write_script(dpp(), lua_manager.get(), tenant, null_yield, script_ctx, script);
if (rc < 0) {
cerr << "ERROR: failed to put script. error: " << rc << std::endl;
return -rc;
}
}
if (opt_cmd == OPT::SCRIPT_GET) {
if (!str_script_ctx) {
cerr << "ERROR: context was not provided (via --context)" << std::endl;
return EINVAL;
}
const rgw::lua::context script_ctx = rgw::lua::to_context(*str_script_ctx);
if (script_ctx == rgw::lua::context::none) {
cerr << "ERROR: invalid script context: " << *str_script_ctx << ". must be one of: " << LUA_CONTEXT_LIST << std::endl;
return EINVAL;
}
auto lua_manager = driver->get_lua_manager();
std::string script;
const auto rc = rgw::lua::read_script(dpp(), lua_manager.get(), tenant, null_yield, script_ctx, script);
if (rc == -ENOENT) {
std::cout << "no script exists for context: " << *str_script_ctx <<
(tenant.empty() ? "" : (" in tenant: " + tenant)) << std::endl;
} else if (rc < 0) {
cerr << "ERROR: failed to read script. error: " << rc << std::endl;
return -rc;
} else {
std::cout << script << std::endl;
}
}
if (opt_cmd == OPT::SCRIPT_RM) {
if (!str_script_ctx) {
cerr << "ERROR: context was not provided (via --context)" << std::endl;
return EINVAL;
}
const rgw::lua::context script_ctx = rgw::lua::to_context(*str_script_ctx);
if (script_ctx == rgw::lua::context::none) {
cerr << "ERROR: invalid script context: " << *str_script_ctx << ". must be one of: " << LUA_CONTEXT_LIST << std::endl;
return EINVAL;
}
auto lua_manager = driver->get_lua_manager();
const auto rc = rgw::lua::delete_script(dpp(), lua_manager.get(), tenant, null_yield, script_ctx);
if (rc < 0) {
cerr << "ERROR: failed to remove script. error: " << rc << std::endl;
return -rc;
}
}
if (opt_cmd == OPT::SCRIPT_PACKAGE_ADD) {
#ifdef WITH_RADOSGW_LUA_PACKAGES
if (!script_package) {
cerr << "ERROR: lua package name was not provided (via --package)" << std::endl;
return EINVAL;
}
const auto rc = rgw::lua::add_package(dpp(), driver, null_yield, *script_package, bool(allow_compilation));
if (rc < 0) {
cerr << "ERROR: failed to add lua package: " << script_package << " .error: " << rc << std::endl;
return -rc;
}
#else
cerr << "ERROR: adding lua packages is not permitted" << std::endl;
return EPERM;
#endif
}
if (opt_cmd == OPT::SCRIPT_PACKAGE_RM) {
#ifdef WITH_RADOSGW_LUA_PACKAGES
if (!script_package) {
cerr << "ERROR: lua package name was not provided (via --package)" << std::endl;
return EINVAL;
}
const auto rc = rgw::lua::remove_package(dpp(), driver, null_yield, *script_package);
if (rc == -ENOENT) {
cerr << "WARNING: package " << script_package << " did not exists or already removed" << std::endl;
return 0;
}
if (rc < 0) {
cerr << "ERROR: failed to remove lua package: " << script_package << " .error: " << rc << std::endl;
return -rc;
}
#else
cerr << "ERROR: removing lua packages in not permitted" << std::endl;
return EPERM;
#endif
}
if (opt_cmd == OPT::SCRIPT_PACKAGE_LIST) {
#ifdef WITH_RADOSGW_LUA_PACKAGES
rgw::lua::packages_t packages;
const auto rc = rgw::lua::list_packages(dpp(), driver, null_yield, packages);
if (rc == -ENOENT) {
std::cout << "no lua packages in allowlist" << std::endl;
} else if (rc < 0) {
cerr << "ERROR: failed to read lua packages allowlist. error: " << rc << std::endl;
return rc;
} else {
for (const auto& package : packages) {
std::cout << package << std::endl;
}
}
#else
cerr << "ERROR: listing lua packages in not permitted" << std::endl;
return EPERM;
#endif
}
return 0;
}
| 379,777 | 34.410536 | 211 |
cc
|
null |
ceph-main/src/rgw/rgw_aio.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2018 Red Hat, Inc.
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#include <type_traits>
#include "include/rados/librados.hpp"
#include "librados/librados_asio.h"
#include "rgw_aio.h"
#include "rgw_d3n_cacherequest.h"
namespace rgw {
namespace {
void cb(librados::completion_t, void* arg);
struct state {
Aio* aio;
librados::IoCtx ctx;
librados::AioCompletion* c;
state(Aio* aio, librados::IoCtx ctx, AioResult& r)
: aio(aio), ctx(std::move(ctx)),
c(librados::Rados::aio_create_completion(&r, &cb)) {}
};
void cb(librados::completion_t, void* arg) {
static_assert(sizeof(AioResult::user_data) >= sizeof(state));
auto& r = *(static_cast<AioResult*>(arg));
auto s = reinterpret_cast<state*>(&r.user_data);
r.result = s->c->get_return_value();
s->c->release();
Aio* aio = s->aio;
// manually destroy the state that was constructed with placement new
s->~state();
aio->put(r);
}
template <typename Op>
Aio::OpFunc aio_abstract(librados::IoCtx ctx, Op&& op) {
return [ctx = std::move(ctx), op = std::move(op)] (Aio* aio, AioResult& r) mutable {
constexpr bool read = std::is_same_v<std::decay_t<Op>, librados::ObjectReadOperation>;
// use placement new to construct the rados state inside of user_data
auto s = new (&r.user_data) state(aio, ctx, r);
if constexpr (read) {
r.result = ctx.aio_operate(r.obj.oid, s->c, &op, &r.data);
} else {
r.result = ctx.aio_operate(r.obj.oid, s->c, &op);
}
if (r.result < 0) {
// cb() won't be called, so release everything here
s->c->release();
aio->put(r);
s->~state();
}
};
}
struct Handler {
Aio* throttle = nullptr;
librados::IoCtx ctx;
AioResult& r;
// write callback
void operator()(boost::system::error_code ec) const {
r.result = -ec.value();
throttle->put(r);
}
// read callback
void operator()(boost::system::error_code ec, bufferlist bl) const {
r.result = -ec.value();
r.data = std::move(bl);
throttle->put(r);
}
};
template <typename Op>
Aio::OpFunc aio_abstract(librados::IoCtx ctx, Op&& op,
boost::asio::io_context& context,
yield_context yield) {
return [ctx = std::move(ctx), op = std::move(op), &context, yield] (Aio* aio, AioResult& r) mutable {
// arrange for the completion Handler to run on the yield_context's strand
// executor so it can safely call back into Aio without locking
using namespace boost::asio;
async_completion<yield_context, void()> init(yield);
auto ex = get_associated_executor(init.completion_handler);
librados::async_operate(context, ctx, r.obj.oid, &op, 0,
bind_executor(ex, Handler{aio, ctx, r}));
};
}
Aio::OpFunc d3n_cache_aio_abstract(const DoutPrefixProvider *dpp, optional_yield y, off_t read_ofs, off_t read_len, std::string& cache_location) {
return [dpp, y, read_ofs, read_len, cache_location] (Aio* aio, AioResult& r) mutable {
// d3n data cache requires yield context (rgw_beast_enable_async=true)
ceph_assert(y);
auto c = std::make_unique<D3nL1CacheRequest>();
lsubdout(g_ceph_context, rgw_datacache, 20) << "D3nDataCache: d3n_cache_aio_abstract(): libaio Read From Cache, oid=" << r.obj.oid << dendl;
c->file_aio_read_abstract(dpp, y.get_io_context(), y.get_yield_context(), cache_location, read_ofs, read_len, aio, r);
};
}
template <typename Op>
Aio::OpFunc aio_abstract(librados::IoCtx ctx, Op&& op, optional_yield y) {
static_assert(std::is_base_of_v<librados::ObjectOperation, std::decay_t<Op>>);
static_assert(!std::is_lvalue_reference_v<Op>);
static_assert(!std::is_const_v<Op>);
if (y) {
return aio_abstract(std::move(ctx), std::forward<Op>(op),
y.get_io_context(), y.get_yield_context());
}
return aio_abstract(std::move(ctx), std::forward<Op>(op));
}
} // anonymous namespace
Aio::OpFunc Aio::librados_op(librados::IoCtx ctx,
librados::ObjectReadOperation&& op,
optional_yield y) {
return aio_abstract(std::move(ctx), std::move(op), y);
}
Aio::OpFunc Aio::librados_op(librados::IoCtx ctx,
librados::ObjectWriteOperation&& op,
optional_yield y) {
return aio_abstract(std::move(ctx), std::move(op), y);
}
Aio::OpFunc Aio::d3n_cache_op(const DoutPrefixProvider *dpp, optional_yield y,
off_t read_ofs, off_t read_len, std::string& cache_location) {
return d3n_cache_aio_abstract(dpp, y, read_ofs, read_len, cache_location);
}
} // namespace rgw
| 5,020 | 33.156463 | 146 |
cc
|
null |
ceph-main/src/rgw/rgw_aio.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2018 Red Hat, Inc.
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#pragma once
#include <cstdint>
#include <memory>
#include <type_traits>
#include <boost/intrusive/list.hpp>
#include "include/rados/librados_fwd.hpp"
#include "common/async/yield_context.h"
#include "rgw_common.h"
#include "include/function2.hpp"
struct D3nGetObjData;
namespace rgw {
struct AioResult {
rgw_raw_obj obj;
uint64_t id = 0; // id allows caller to associate a result with its request
bufferlist data; // result buffer for reads
int result = 0;
std::aligned_storage_t<3 * sizeof(void*)> user_data;
AioResult() = default;
AioResult(const AioResult&) = delete;
AioResult& operator =(const AioResult&) = delete;
AioResult(AioResult&&) = delete;
AioResult& operator =(AioResult&&) = delete;
};
struct AioResultEntry : AioResult, boost::intrusive::list_base_hook<> {
virtual ~AioResultEntry() {}
};
// a list of polymorphic entries that frees them on destruction
template <typename T, typename ...Args>
struct OwningList : boost::intrusive::list<T, Args...> {
OwningList() = default;
~OwningList() { this->clear_and_dispose(std::default_delete<T>{}); }
OwningList(OwningList&&) = default;
OwningList& operator=(OwningList&&) = default;
OwningList(const OwningList&) = delete;
OwningList& operator=(const OwningList&) = delete;
};
using AioResultList = OwningList<AioResultEntry>;
// returns the first error code or 0 if all succeeded
inline int check_for_errors(const AioResultList& results) {
for (auto& e : results) {
if (e.result < 0) {
return e.result;
}
}
return 0;
}
// interface to submit async librados operations and wait on their completions.
// each call returns a list of results from prior completions
class Aio {
public:
using OpFunc = fu2::unique_function<void(Aio*, AioResult&) &&>;
virtual ~Aio() {}
virtual AioResultList get(rgw_raw_obj obj,
OpFunc&& f,
uint64_t cost, uint64_t id) = 0;
virtual void put(AioResult& r) = 0;
// poll for any ready completions without waiting
virtual AioResultList poll() = 0;
// return any ready completions. if there are none, wait for the next
virtual AioResultList wait() = 0;
// wait for all outstanding completions and return their results
virtual AioResultList drain() = 0;
static OpFunc librados_op(librados::IoCtx ctx,
librados::ObjectReadOperation&& op,
optional_yield y);
static OpFunc librados_op(librados::IoCtx ctx,
librados::ObjectWriteOperation&& op,
optional_yield y);
static OpFunc d3n_cache_op(const DoutPrefixProvider *dpp, optional_yield y,
off_t read_ofs, off_t read_len, std::string& location);
};
} // namespace rgw
| 3,161 | 29.114286 | 84 |
h
|
null |
ceph-main/src/rgw/rgw_aio_throttle.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2018 Red Hat, Inc.
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#include "rgw_aio_throttle.h"
namespace rgw {
bool Throttle::waiter_ready() const
{
switch (waiter) {
case Wait::Available: return is_available();
case Wait::Completion: return has_completion();
case Wait::Drained: return is_drained();
default: return false;
}
}
AioResultList BlockingAioThrottle::get(rgw_raw_obj obj,
OpFunc&& f,
uint64_t cost, uint64_t id)
{
auto p = std::make_unique<Pending>();
p->obj = std::move(obj);
p->id = id;
p->cost = cost;
std::unique_lock lock{mutex};
if (cost > window) {
p->result = -EDEADLK; // would never succeed
completed.push_back(*p);
} else {
// wait for the write size to become available
pending_size += p->cost;
if (!is_available()) {
ceph_assert(waiter == Wait::None);
waiter = Wait::Available;
cond.wait(lock, [this] { return is_available(); });
waiter = Wait::None;
}
// register the pending write and attach a completion
p->parent = this;
pending.push_back(*p);
lock.unlock();
std::move(f)(this, *static_cast<AioResult*>(p.get()));
lock.lock();
}
// coverity[leaked_storage:SUPPRESS]
p.release();
return std::move(completed);
}
void BlockingAioThrottle::put(AioResult& r)
{
auto& p = static_cast<Pending&>(r);
std::scoped_lock lock{mutex};
// move from pending to completed
pending.erase(pending.iterator_to(p));
completed.push_back(p);
pending_size -= p.cost;
if (waiter_ready()) {
cond.notify_one();
}
}
AioResultList BlockingAioThrottle::poll()
{
std::unique_lock lock{mutex};
return std::move(completed);
}
AioResultList BlockingAioThrottle::wait()
{
std::unique_lock lock{mutex};
if (completed.empty() && !pending.empty()) {
ceph_assert(waiter == Wait::None);
waiter = Wait::Completion;
cond.wait(lock, [this] { return has_completion(); });
waiter = Wait::None;
}
return std::move(completed);
}
AioResultList BlockingAioThrottle::drain()
{
std::unique_lock lock{mutex};
if (!pending.empty()) {
ceph_assert(waiter == Wait::None);
waiter = Wait::Drained;
cond.wait(lock, [this] { return is_drained(); });
waiter = Wait::None;
}
return std::move(completed);
}
template <typename CompletionToken>
auto YieldingAioThrottle::async_wait(CompletionToken&& token)
{
using boost::asio::async_completion;
using Signature = void(boost::system::error_code);
async_completion<CompletionToken, Signature> init(token);
completion = Completion::create(context.get_executor(),
std::move(init.completion_handler));
return init.result.get();
}
AioResultList YieldingAioThrottle::get(rgw_raw_obj obj,
OpFunc&& f,
uint64_t cost, uint64_t id)
{
auto p = std::make_unique<Pending>();
p->obj = std::move(obj);
p->id = id;
p->cost = cost;
if (cost > window) {
p->result = -EDEADLK; // would never succeed
completed.push_back(*p);
} else {
// wait for the write size to become available
pending_size += p->cost;
if (!is_available()) {
ceph_assert(waiter == Wait::None);
ceph_assert(!completion);
boost::system::error_code ec;
waiter = Wait::Available;
async_wait(yield[ec]);
}
// register the pending write and initiate the operation
pending.push_back(*p);
std::move(f)(this, *static_cast<AioResult*>(p.get()));
}
// coverity[leaked_storage:SUPPRESS]
p.release();
return std::move(completed);
}
void YieldingAioThrottle::put(AioResult& r)
{
auto& p = static_cast<Pending&>(r);
// move from pending to completed
pending.erase(pending.iterator_to(p));
completed.push_back(p);
pending_size -= p.cost;
if (waiter_ready()) {
ceph_assert(completion);
ceph::async::post(std::move(completion), boost::system::error_code{});
waiter = Wait::None;
}
}
AioResultList YieldingAioThrottle::poll()
{
return std::move(completed);
}
AioResultList YieldingAioThrottle::wait()
{
if (!has_completion() && !pending.empty()) {
ceph_assert(waiter == Wait::None);
ceph_assert(!completion);
boost::system::error_code ec;
waiter = Wait::Completion;
async_wait(yield[ec]);
}
return std::move(completed);
}
AioResultList YieldingAioThrottle::drain()
{
if (!is_drained()) {
ceph_assert(waiter == Wait::None);
ceph_assert(!completion);
boost::system::error_code ec;
waiter = Wait::Drained;
async_wait(yield[ec]);
}
return std::move(completed);
}
} // namespace rgw
| 5,041 | 23.837438 | 74 |
cc
|
null |
ceph-main/src/rgw/rgw_aio_throttle.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2018 Red Hat, Inc.
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#pragma once
#include <memory>
#include "common/ceph_mutex.h"
#include "common/async/completion.h"
#include "common/async/yield_context.h"
#include "rgw_aio.h"
namespace rgw {
class Throttle {
protected:
const uint64_t window;
uint64_t pending_size = 0;
AioResultList pending;
AioResultList completed;
bool is_available() const { return pending_size <= window; }
bool has_completion() const { return !completed.empty(); }
bool is_drained() const { return pending.empty(); }
enum class Wait { None, Available, Completion, Drained };
Wait waiter = Wait::None;
bool waiter_ready() const;
public:
Throttle(uint64_t window) : window(window) {}
virtual ~Throttle() {
// must drain before destructing
ceph_assert(pending.empty());
ceph_assert(completed.empty());
}
};
// a throttle for aio operations. all public functions must be called from
// the same thread
class BlockingAioThrottle final : public Aio, private Throttle {
ceph::mutex mutex = ceph::make_mutex("AioThrottle");
ceph::condition_variable cond;
struct Pending : AioResultEntry {
BlockingAioThrottle *parent = nullptr;
uint64_t cost = 0;
};
public:
BlockingAioThrottle(uint64_t window) : Throttle(window) {}
virtual ~BlockingAioThrottle() override {};
AioResultList get(rgw_raw_obj obj, OpFunc&& f,
uint64_t cost, uint64_t id) override final;
void put(AioResult& r) override final;
AioResultList poll() override final;
AioResultList wait() override final;
AioResultList drain() override final;
};
// a throttle that yields the coroutine instead of blocking. all public
// functions must be called within the coroutine strand
class YieldingAioThrottle final : public Aio, private Throttle {
boost::asio::io_context& context;
yield_context yield;
struct Handler;
// completion callback associated with the waiter
using Completion = ceph::async::Completion<void(boost::system::error_code)>;
std::unique_ptr<Completion> completion;
template <typename CompletionToken>
auto async_wait(CompletionToken&& token);
struct Pending : AioResultEntry { uint64_t cost = 0; };
public:
YieldingAioThrottle(uint64_t window, boost::asio::io_context& context,
yield_context yield)
: Throttle(window), context(context), yield(yield)
{}
virtual ~YieldingAioThrottle() override {};
AioResultList get(rgw_raw_obj obj, OpFunc&& f,
uint64_t cost, uint64_t id) override final;
void put(AioResult& r) override final;
AioResultList poll() override final;
AioResultList wait() override final;
AioResultList drain() override final;
};
// return a smart pointer to Aio
inline auto make_throttle(uint64_t window_size, optional_yield y)
{
std::unique_ptr<Aio> aio;
if (y) {
aio = std::make_unique<YieldingAioThrottle>(window_size,
y.get_io_context(),
y.get_yield_context());
} else {
aio = std::make_unique<BlockingAioThrottle>(window_size);
}
return aio;
}
} // namespace rgw
| 3,530 | 25.954198 | 78 |
h
|
null |
ceph-main/src/rgw/rgw_amqp.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include "rgw_amqp.h"
#include <amqp.h>
#include <amqp_ssl_socket.h>
#include <amqp_tcp_socket.h>
#include <amqp_framing.h>
#include "include/ceph_assert.h"
#include <sstream>
#include <cstring>
#include <unordered_map>
#include <string>
#include <vector>
#include <thread>
#include <atomic>
#include <mutex>
#include <boost/lockfree/queue.hpp>
#include <boost/functional/hash.hpp>
#include "common/dout.h"
#include <openssl/ssl.h>
#define dout_subsys ceph_subsys_rgw
// TODO investigation, not necessarily issues:
// (1) in case of single threaded writer context use spsc_queue
// (2) support multiple channels
// (3) check performance of emptying queue to local list, and go over the list and publish
// (4) use std::shared_mutex (c++17) or equivalent for the connections lock
namespace rgw::amqp {
// RGW AMQP status codes for publishing
static const int RGW_AMQP_STATUS_BROKER_NACK = -0x1001;
static const int RGW_AMQP_STATUS_CONNECTION_CLOSED = -0x1002;
static const int RGW_AMQP_STATUS_QUEUE_FULL = -0x1003;
static const int RGW_AMQP_STATUS_MAX_INFLIGHT = -0x1004;
static const int RGW_AMQP_STATUS_MANAGER_STOPPED = -0x1005;
// RGW AMQP status code for connection opening
static const int RGW_AMQP_STATUS_CONN_ALLOC_FAILED = -0x2001;
static const int RGW_AMQP_STATUS_SOCKET_ALLOC_FAILED = -0x2002;
static const int RGW_AMQP_STATUS_SOCKET_OPEN_FAILED = -0x2003;
static const int RGW_AMQP_STATUS_LOGIN_FAILED = -0x2004;
static const int RGW_AMQP_STATUS_CHANNEL_OPEN_FAILED = -0x2005;
static const int RGW_AMQP_STATUS_VERIFY_EXCHANGE_FAILED = -0x2006;
static const int RGW_AMQP_STATUS_Q_DECLARE_FAILED = -0x2007;
static const int RGW_AMQP_STATUS_CONFIRM_DECLARE_FAILED = -0x2008;
static const int RGW_AMQP_STATUS_CONSUME_DECLARE_FAILED = -0x2009;
static const int RGW_AMQP_STATUS_SOCKET_CACERT_FAILED = -0x2010;
static const int RGW_AMQP_RESPONSE_SOCKET_ERROR = -0x3008;
static const int RGW_AMQP_NO_REPLY_CODE = 0x0;
// the amqp_connection_info struct does not hold any memory and just points to the URL string
// so, strings are copied into connection_id_t
connection_id_t::connection_id_t(const amqp_connection_info& info, const std::string& _exchange)
: host(info.host), port(info.port), vhost(info.vhost), exchange(_exchange), ssl(info.ssl) {}
// equality operator and hasher functor are needed
// so that connection_id_t could be used as key in unordered_map
bool operator==(const connection_id_t& lhs, const connection_id_t& rhs) {
return lhs.host == rhs.host && lhs.port == rhs.port &&
lhs.vhost == rhs.vhost && lhs.exchange == rhs.exchange;
}
struct connection_id_hasher {
std::size_t operator()(const connection_id_t& k) const {
std::size_t h = 0;
boost::hash_combine(h, k.host);
boost::hash_combine(h, k.port);
boost::hash_combine(h, k.vhost);
boost::hash_combine(h, k.exchange);
return h;
}
};
std::string to_string(const connection_id_t& id) {
return fmt::format("{}://{}:{}{}?exchange={}",
id.ssl ? "amqps" : "amqp",
id.host, id.port, id.vhost, id.exchange);
}
// automatically cleans amqp state when gets out of scope
class ConnectionCleaner {
private:
amqp_connection_state_t state;
public:
ConnectionCleaner(amqp_connection_state_t _state) : state(_state) {}
~ConnectionCleaner() {
if (state) {
amqp_destroy_connection(state);
}
}
// call reset() if cleanup is not needed anymore
void reset() {
state = nullptr;
}
};
// struct for holding the callback and its tag in the callback list
struct reply_callback_with_tag_t {
uint64_t tag;
reply_callback_t cb;
reply_callback_with_tag_t(uint64_t _tag, reply_callback_t _cb) : tag(_tag), cb(_cb) {}
bool operator==(uint64_t rhs) {
return tag == rhs;
}
};
typedef std::vector<reply_callback_with_tag_t> CallbackList;
// struct for holding the connection state object as well as the exchange
struct connection_t {
CephContext* cct = nullptr;
amqp_connection_state_t state = nullptr;
amqp_bytes_t reply_to_queue = amqp_empty_bytes;
uint64_t delivery_tag = 1;
int status = AMQP_STATUS_OK;
int reply_type = AMQP_RESPONSE_NORMAL;
int reply_code = RGW_AMQP_NO_REPLY_CODE;
CallbackList callbacks;
ceph::coarse_real_clock::time_point next_reconnect = ceph::coarse_real_clock::now();
bool mandatory = false;
const bool use_ssl = false;
std::string user;
std::string password;
bool verify_ssl = true;
boost::optional<std::string> ca_location;
utime_t timestamp = ceph_clock_now();
connection_t(CephContext* _cct, const amqp_connection_info& info, bool _verify_ssl, boost::optional<const std::string&> _ca_location) :
cct(_cct), use_ssl(info.ssl), user(info.user), password(info.password), verify_ssl(_verify_ssl), ca_location(_ca_location) {}
// cleanup of all internal connection resource
// the object can still remain, and internal connection
// resources created again on successful reconnection
void destroy(int s) {
status = s;
ConnectionCleaner clean_state(state);
state = nullptr;
amqp_bytes_free(reply_to_queue);
reply_to_queue = amqp_empty_bytes;
// fire all remaining callbacks
std::for_each(callbacks.begin(), callbacks.end(), [this](auto& cb_tag) {
cb_tag.cb(status);
ldout(cct, 20) << "AMQP destroy: invoking callback with tag=" << cb_tag.tag << dendl;
});
callbacks.clear();
delivery_tag = 1;
}
bool is_ok() const {
return (state != nullptr);
}
// dtor also destroys the internals
~connection_t() {
destroy(RGW_AMQP_STATUS_CONNECTION_CLOSED);
}
};
// convert connection info to string
std::string to_string(const amqp_connection_info& info) {
std::stringstream ss;
ss << "connection info:" <<
"\nHost: " << info.host <<
"\nPort: " << info.port <<
"\nUser: " << info.user <<
"\nPassword: " << info.password <<
"\nvhost: " << info.vhost <<
"\nSSL support: " << info.ssl << std::endl;
return ss.str();
}
// convert reply to error code
int reply_to_code(const amqp_rpc_reply_t& reply) {
switch (reply.reply_type) {
case AMQP_RESPONSE_NONE:
case AMQP_RESPONSE_NORMAL:
return RGW_AMQP_NO_REPLY_CODE;
case AMQP_RESPONSE_LIBRARY_EXCEPTION:
return reply.library_error;
case AMQP_RESPONSE_SERVER_EXCEPTION:
if (reply.reply.decoded) {
const amqp_connection_close_t* m = (amqp_connection_close_t*)reply.reply.decoded;
return m->reply_code;
}
return reply.reply.id;
}
return RGW_AMQP_NO_REPLY_CODE;
}
// convert reply to string
std::string to_string(const amqp_rpc_reply_t& reply) {
std::stringstream ss;
switch (reply.reply_type) {
case AMQP_RESPONSE_NORMAL:
return "";
case AMQP_RESPONSE_NONE:
return "missing RPC reply type";
case AMQP_RESPONSE_LIBRARY_EXCEPTION:
return amqp_error_string2(reply.library_error);
case AMQP_RESPONSE_SERVER_EXCEPTION:
{
switch (reply.reply.id) {
case AMQP_CONNECTION_CLOSE_METHOD:
ss << "server connection error: ";
break;
case AMQP_CHANNEL_CLOSE_METHOD:
ss << "server channel error: ";
break;
default:
ss << "server unknown error: ";
break;
}
if (reply.reply.decoded) {
amqp_connection_close_t* m = (amqp_connection_close_t*)reply.reply.decoded;
ss << m->reply_code << " text: " << std::string((char*)m->reply_text.bytes, m->reply_text.len);
}
return ss.str();
}
default:
ss << "unknown error, method id: " << reply.reply.id;
return ss.str();
}
}
// convert status enum to string
std::string to_string(amqp_status_enum s) {
switch (s) {
case AMQP_STATUS_OK:
return "AMQP_STATUS_OK";
case AMQP_STATUS_NO_MEMORY:
return "AMQP_STATUS_NO_MEMORY";
case AMQP_STATUS_BAD_AMQP_DATA:
return "AMQP_STATUS_BAD_AMQP_DATA";
case AMQP_STATUS_UNKNOWN_CLASS:
return "AMQP_STATUS_UNKNOWN_CLASS";
case AMQP_STATUS_UNKNOWN_METHOD:
return "AMQP_STATUS_UNKNOWN_METHOD";
case AMQP_STATUS_HOSTNAME_RESOLUTION_FAILED:
return "AMQP_STATUS_HOSTNAME_RESOLUTION_FAILED";
case AMQP_STATUS_INCOMPATIBLE_AMQP_VERSION:
return "AMQP_STATUS_INCOMPATIBLE_AMQP_VERSION";
case AMQP_STATUS_CONNECTION_CLOSED:
return "AMQP_STATUS_CONNECTION_CLOSED";
case AMQP_STATUS_BAD_URL:
return "AMQP_STATUS_BAD_URL";
case AMQP_STATUS_SOCKET_ERROR:
return "AMQP_STATUS_SOCKET_ERROR";
case AMQP_STATUS_INVALID_PARAMETER:
return "AMQP_STATUS_INVALID_PARAMETER";
case AMQP_STATUS_TABLE_TOO_BIG:
return "AMQP_STATUS_TABLE_TOO_BIG";
case AMQP_STATUS_WRONG_METHOD:
return "AMQP_STATUS_WRONG_METHOD";
case AMQP_STATUS_TIMEOUT:
return "AMQP_STATUS_TIMEOUT";
case AMQP_STATUS_TIMER_FAILURE:
return "AMQP_STATUS_TIMER_FAILURE";
case AMQP_STATUS_HEARTBEAT_TIMEOUT:
return "AMQP_STATUS_HEARTBEAT_TIMEOUT";
case AMQP_STATUS_UNEXPECTED_STATE:
return "AMQP_STATUS_UNEXPECTED_STATE";
case AMQP_STATUS_SOCKET_CLOSED:
return "AMQP_STATUS_SOCKET_CLOSED";
case AMQP_STATUS_SOCKET_INUSE:
return "AMQP_STATUS_SOCKET_INUSE";
case AMQP_STATUS_BROKER_UNSUPPORTED_SASL_METHOD:
return "AMQP_STATUS_BROKER_UNSUPPORTED_SASL_METHOD";
#if AMQP_VERSION >= AMQP_VERSION_CODE(0, 8, 0, 0)
case AMQP_STATUS_UNSUPPORTED:
return "AMQP_STATUS_UNSUPPORTED";
#endif
case _AMQP_STATUS_NEXT_VALUE:
return "AMQP_STATUS_INTERNAL";
case AMQP_STATUS_TCP_ERROR:
return "AMQP_STATUS_TCP_ERROR";
case AMQP_STATUS_TCP_SOCKETLIB_INIT_ERROR:
return "AMQP_STATUS_TCP_SOCKETLIB_INIT_ERROR";
case _AMQP_STATUS_TCP_NEXT_VALUE:
return "AMQP_STATUS_INTERNAL";
case AMQP_STATUS_SSL_ERROR:
return "AMQP_STATUS_SSL_ERROR";
case AMQP_STATUS_SSL_HOSTNAME_VERIFY_FAILED:
return "AMQP_STATUS_SSL_HOSTNAME_VERIFY_FAILED";
case AMQP_STATUS_SSL_PEER_VERIFY_FAILED:
return "AMQP_STATUS_SSL_PEER_VERIFY_FAILED";
case AMQP_STATUS_SSL_CONNECTION_FAILED:
return "AMQP_STATUS_SSL_CONNECTION_FAILED";
case _AMQP_STATUS_SSL_NEXT_VALUE:
return "AMQP_STATUS_INTERNAL";
#if AMQP_VERSION >= AMQP_VERSION_CODE(0, 11, 0, 0)
case AMQP_STATUS_SSL_SET_ENGINE_FAILED:
return "AMQP_STATUS_SSL_SET_ENGINE_FAILED";
#endif
default:
return "AMQP_STATUS_UNKNOWN";
}
}
// TODO: add status_to_string on the connection object to prinf full status
// convert int status to string - including RGW specific values
std::string status_to_string(int s) {
switch (s) {
case RGW_AMQP_STATUS_BROKER_NACK:
return "RGW_AMQP_STATUS_BROKER_NACK";
case RGW_AMQP_STATUS_CONNECTION_CLOSED:
return "RGW_AMQP_STATUS_CONNECTION_CLOSED";
case RGW_AMQP_STATUS_QUEUE_FULL:
return "RGW_AMQP_STATUS_QUEUE_FULL";
case RGW_AMQP_STATUS_MAX_INFLIGHT:
return "RGW_AMQP_STATUS_MAX_INFLIGHT";
case RGW_AMQP_STATUS_MANAGER_STOPPED:
return "RGW_AMQP_STATUS_MANAGER_STOPPED";
case RGW_AMQP_STATUS_CONN_ALLOC_FAILED:
return "RGW_AMQP_STATUS_CONN_ALLOC_FAILED";
case RGW_AMQP_STATUS_SOCKET_ALLOC_FAILED:
return "RGW_AMQP_STATUS_SOCKET_ALLOC_FAILED";
case RGW_AMQP_STATUS_SOCKET_OPEN_FAILED:
return "RGW_AMQP_STATUS_SOCKET_OPEN_FAILED";
case RGW_AMQP_STATUS_LOGIN_FAILED:
return "RGW_AMQP_STATUS_LOGIN_FAILED";
case RGW_AMQP_STATUS_CHANNEL_OPEN_FAILED:
return "RGW_AMQP_STATUS_CHANNEL_OPEN_FAILED";
case RGW_AMQP_STATUS_VERIFY_EXCHANGE_FAILED:
return "RGW_AMQP_STATUS_VERIFY_EXCHANGE_FAILED";
case RGW_AMQP_STATUS_Q_DECLARE_FAILED:
return "RGW_AMQP_STATUS_Q_DECLARE_FAILED";
case RGW_AMQP_STATUS_CONFIRM_DECLARE_FAILED:
return "RGW_AMQP_STATUS_CONFIRM_DECLARE_FAILED";
case RGW_AMQP_STATUS_CONSUME_DECLARE_FAILED:
return "RGW_AMQP_STATUS_CONSUME_DECLARE_FAILED";
case RGW_AMQP_STATUS_SOCKET_CACERT_FAILED:
return "RGW_AMQP_STATUS_SOCKET_CACERT_FAILED";
}
return to_string((amqp_status_enum)s);
}
// check the result from calls and return if error (=null)
#define RETURN_ON_ERROR(C, S, OK) \
if (!OK) { \
C->status = S; \
return false; \
}
// in case of RPC calls, getting the RPC reply and return if an error is detected
#define RETURN_ON_REPLY_ERROR(C, ST, S) { \
const auto reply = amqp_get_rpc_reply(ST); \
if (reply.reply_type != AMQP_RESPONSE_NORMAL) { \
C->status = S; \
C->reply_type = reply.reply_type; \
C->reply_code = reply_to_code(reply); \
return false; \
} \
}
static const amqp_channel_t CHANNEL_ID = 1;
static const amqp_channel_t CONFIRMING_CHANNEL_ID = 2;
// utility function to create a connection, when the connection object already exists
bool new_state(connection_t* conn, const connection_id_t& conn_id) {
// state must be null at this point
ceph_assert(!conn->state);
// reset all status codes
conn->status = AMQP_STATUS_OK;
conn->reply_type = AMQP_RESPONSE_NORMAL;
conn->reply_code = RGW_AMQP_NO_REPLY_CODE;
auto state = amqp_new_connection();
if (!state) {
conn->status = RGW_AMQP_STATUS_CONN_ALLOC_FAILED;
return false;
}
// make sure that the connection state is cleaned up in case of error
ConnectionCleaner state_guard(state);
// create and open socket
amqp_socket_t *socket = nullptr;
if (conn->use_ssl) {
socket = amqp_ssl_socket_new(state);
#if AMQP_VERSION >= AMQP_VERSION_CODE(0, 10, 0, 1)
SSL_CTX* ssl_ctx = reinterpret_cast<SSL_CTX*>(amqp_ssl_socket_get_context(socket));
#else
// taken from https://github.com/alanxz/rabbitmq-c/pull/560
struct hack {
const struct amqp_socket_class_t *klass;
SSL_CTX *ctx;
};
struct hack *h = reinterpret_cast<struct hack*>(socket);
SSL_CTX* ssl_ctx = h->ctx;
#endif
// ensure system CA certificates get loaded
SSL_CTX_set_default_verify_paths(ssl_ctx);
}
else {
socket = amqp_tcp_socket_new(state);
}
if (!socket) {
conn->status = RGW_AMQP_STATUS_SOCKET_ALLOC_FAILED;
return false;
}
if (conn->use_ssl) {
if (!conn->verify_ssl) {
amqp_ssl_socket_set_verify_peer(socket, 0);
amqp_ssl_socket_set_verify_hostname(socket, 0);
}
if (conn->ca_location.has_value()) {
const auto s = amqp_ssl_socket_set_cacert(socket, conn->ca_location.get().c_str());
if (s != AMQP_STATUS_OK) {
conn->status = RGW_AMQP_STATUS_SOCKET_CACERT_FAILED;
conn->reply_code = s;
return false;
}
}
}
const auto s = amqp_socket_open(socket, conn_id.host.c_str(), conn_id.port);
if (s < 0) {
conn->status = RGW_AMQP_STATUS_SOCKET_OPEN_FAILED;
conn->reply_type = RGW_AMQP_RESPONSE_SOCKET_ERROR;
conn->reply_code = s;
return false;
}
// login to broker
const auto reply = amqp_login(state,
conn_id.vhost.c_str(),
AMQP_DEFAULT_MAX_CHANNELS,
AMQP_DEFAULT_FRAME_SIZE,
0, // no heartbeat TODO: add conf
AMQP_SASL_METHOD_PLAIN, // TODO: add other types of security
conn->user.c_str(),
conn->password.c_str());
if (reply.reply_type != AMQP_RESPONSE_NORMAL) {
conn->status = RGW_AMQP_STATUS_LOGIN_FAILED;
conn->reply_type = reply.reply_type;
conn->reply_code = reply_to_code(reply);
return false;
}
// open channels
{
const auto ok = amqp_channel_open(state, CHANNEL_ID);
RETURN_ON_ERROR(conn, RGW_AMQP_STATUS_CHANNEL_OPEN_FAILED, ok);
RETURN_ON_REPLY_ERROR(conn, state, RGW_AMQP_STATUS_CHANNEL_OPEN_FAILED);
}
{
const auto ok = amqp_channel_open(state, CONFIRMING_CHANNEL_ID);
RETURN_ON_ERROR(conn, RGW_AMQP_STATUS_CHANNEL_OPEN_FAILED, ok);
RETURN_ON_REPLY_ERROR(conn, state, RGW_AMQP_STATUS_CHANNEL_OPEN_FAILED);
}
{
const auto ok = amqp_confirm_select(state, CONFIRMING_CHANNEL_ID);
RETURN_ON_ERROR(conn, RGW_AMQP_STATUS_CONFIRM_DECLARE_FAILED, ok);
RETURN_ON_REPLY_ERROR(conn, state, RGW_AMQP_STATUS_CONFIRM_DECLARE_FAILED);
}
// verify that the topic exchange is there
// TODO: make this step optional
{
const auto ok = amqp_exchange_declare(state,
CHANNEL_ID,
amqp_cstring_bytes(conn_id.exchange.c_str()),
amqp_cstring_bytes("topic"),
1, // passive - exchange must already exist on broker
1, // durable
0, // dont auto-delete
0, // not internal
amqp_empty_table);
RETURN_ON_ERROR(conn, RGW_AMQP_STATUS_VERIFY_EXCHANGE_FAILED, ok);
RETURN_ON_REPLY_ERROR(conn, state, RGW_AMQP_STATUS_VERIFY_EXCHANGE_FAILED);
}
{
// create queue for confirmations
const auto queue_ok = amqp_queue_declare(state,
CHANNEL_ID, // use the regular channel for this call
amqp_empty_bytes, // let broker allocate queue name
0, // not passive - create the queue
0, // not durable
1, // exclusive
1, // auto-delete
amqp_empty_table // not args TODO add args from conf: TTL, max length etc.
);
RETURN_ON_ERROR(conn, RGW_AMQP_STATUS_Q_DECLARE_FAILED, queue_ok);
RETURN_ON_REPLY_ERROR(conn, state, RGW_AMQP_STATUS_Q_DECLARE_FAILED);
// define consumption for connection
const auto consume_ok = amqp_basic_consume(state,
CONFIRMING_CHANNEL_ID,
queue_ok->queue,
amqp_empty_bytes, // broker will generate consumer tag
1, // messages sent from client are never routed back
1, // client does not ack thr acks
1, // exclusive access to queue
amqp_empty_table // no parameters
);
RETURN_ON_ERROR(conn, RGW_AMQP_STATUS_CONSUME_DECLARE_FAILED, consume_ok);
RETURN_ON_REPLY_ERROR(conn, state, RGW_AMQP_STATUS_CONSUME_DECLARE_FAILED);
// broker generated consumer_tag could be used to cancel sending of n/acks from broker - not needed
state_guard.reset();
conn->state = state;
conn->reply_to_queue = amqp_bytes_malloc_dup(queue_ok->queue);
}
return true;
}
/// struct used for holding messages in the message queue
struct message_wrapper_t {
connection_id_t conn_id;
std::string topic;
std::string message;
reply_callback_t cb;
message_wrapper_t(const connection_id_t& _conn_id,
const std::string& _topic,
const std::string& _message,
reply_callback_t _cb) : conn_id(_conn_id), topic(_topic), message(_message), cb(_cb) {}
};
using connection_t_ptr = std::unique_ptr<connection_t>;
typedef std::unordered_map<connection_id_t, connection_t_ptr, connection_id_hasher> ConnectionList;
typedef boost::lockfree::queue<message_wrapper_t*, boost::lockfree::fixed_sized<true>> MessageQueue;
// macros used inside a loop where an iterator is either incremented or erased
#define INCREMENT_AND_CONTINUE(IT) \
++IT; \
continue;
#define ERASE_AND_CONTINUE(IT,CONTAINER) \
IT=CONTAINER.erase(IT); \
--connection_count; \
continue;
class Manager {
public:
const size_t max_connections;
const size_t max_inflight;
const size_t max_queue;
const size_t max_idle_time;
private:
std::atomic<size_t> connection_count;
std::atomic<bool> stopped;
struct timeval read_timeout;
ConnectionList connections;
MessageQueue messages;
std::atomic<size_t> queued;
std::atomic<size_t> dequeued;
CephContext* const cct;
mutable std::mutex connections_lock;
const ceph::coarse_real_clock::duration idle_time;
const ceph::coarse_real_clock::duration reconnect_time;
std::thread runner;
void publish_internal(message_wrapper_t* message) {
const std::unique_ptr<message_wrapper_t> msg_owner(message);
const auto& conn_id = message->conn_id;
auto conn_it = connections.find(conn_id);
if (conn_it == connections.end()) {
ldout(cct, 1) << "AMQP publish: connection '" << to_string(conn_id) << "' not found" << dendl;
if (message->cb) {
message->cb(RGW_AMQP_STATUS_CONNECTION_CLOSED);
}
return;
}
auto& conn = conn_it->second;
conn->timestamp = ceph_clock_now();
if (!conn->is_ok()) {
// connection had an issue while message was in the queue
ldout(cct, 1) << "AMQP publish: connection '" << to_string(conn_id) << "' is closed" << dendl;
if (message->cb) {
message->cb(RGW_AMQP_STATUS_CONNECTION_CLOSED);
}
return;
}
if (message->cb == nullptr) {
const auto rc = amqp_basic_publish(conn->state,
CHANNEL_ID,
amqp_cstring_bytes(conn_id.exchange.c_str()),
amqp_cstring_bytes(message->topic.c_str()),
0, // does not have to be routable
0, // not immediate
nullptr, // no properties needed
amqp_cstring_bytes(message->message.c_str()));
if (rc == AMQP_STATUS_OK) {
ldout(cct, 20) << "AMQP publish (no callback): OK" << dendl;
return;
}
ldout(cct, 1) << "AMQP publish (no callback): failed with error " << status_to_string(rc) << dendl;
// an error occurred, close connection
// it will be retied by the main loop
conn->destroy(rc);
return;
}
amqp_basic_properties_t props;
props._flags =
AMQP_BASIC_DELIVERY_MODE_FLAG |
AMQP_BASIC_REPLY_TO_FLAG;
props.delivery_mode = 2; // persistent delivery TODO take from conf
props.reply_to = conn->reply_to_queue;
const auto rc = amqp_basic_publish(conn->state,
CONFIRMING_CHANNEL_ID,
amqp_cstring_bytes(conn_id.exchange.c_str()),
amqp_cstring_bytes(message->topic.c_str()),
conn->mandatory,
0, // not immediate
&props,
amqp_cstring_bytes(message->message.c_str()));
if (rc == AMQP_STATUS_OK) {
auto const q_len = conn->callbacks.size();
if (q_len < max_inflight) {
ldout(cct, 20) << "AMQP publish (with callback, tag=" << conn->delivery_tag << "): OK. Queue has: " << q_len << " callbacks" << dendl;
conn->callbacks.emplace_back(conn->delivery_tag++, message->cb);
} else {
// immediately invoke callback with error
ldout(cct, 1) << "AMQP publish (with callback): failed with error: callback queue full" << dendl;
message->cb(RGW_AMQP_STATUS_MAX_INFLIGHT);
}
} else {
// an error occurred, close connection
// it will be retied by the main loop
ldout(cct, 1) << "AMQP publish (with callback): failed with error: " << status_to_string(rc) << dendl;
conn->destroy(rc);
// immediately invoke callback with error
message->cb(rc);
}
}
// the managers thread:
// (1) empty the queue of messages to be published
// (2) loop over all connections and read acks
// (3) manages deleted connections
// (4) TODO reconnect on connection errors
// (5) TODO cleanup timedout callbacks
void run() noexcept {
amqp_frame_t frame;
while (!stopped) {
// publish all messages in the queue
const auto count = messages.consume_all(std::bind(&Manager::publish_internal, this, std::placeholders::_1));
dequeued += count;
ConnectionList::iterator conn_it;
ConnectionList::const_iterator end_it;
{
// thread safe access to the connection list
// once the iterators are fetched they are guaranteed to remain valid
std::lock_guard lock(connections_lock);
conn_it = connections.begin();
end_it = connections.end();
}
auto incoming_message = false;
// loop over all connections to read acks
for (;conn_it != end_it;) {
const auto& conn_id = conn_it->first;
auto& conn = conn_it->second;
if(conn->timestamp.sec() + max_idle_time < ceph_clock_now()) {
ldout(cct, 20) << "AMQP run: Time for deleting a connection due to idle behaviour: " << ceph_clock_now() << dendl;
ERASE_AND_CONTINUE(conn_it, connections);
}
// try to reconnect the connection if it has an error
if (!conn->is_ok()) {
const auto now = ceph::coarse_real_clock::now();
if (now >= conn->next_reconnect) {
// pointers are used temporarily inside the amqp_connection_info object
// as read-only values, hence the assignment, and const_cast are safe here
ldout(cct, 20) << "AMQP run: retry connection" << dendl;
if (!new_state(conn.get(), conn_id)) {
ldout(cct, 10) << "AMQP run: connection '" << to_string(conn_id) << "' retry failed. error: " <<
status_to_string(conn->status) << " (" << conn->reply_code << ")" << dendl;
// TODO: add error counter for failed retries
// TODO: add exponential backoff for retries
conn->next_reconnect = now + reconnect_time;
} else {
ldout(cct, 10) << "AMQP run: connection '" << to_string(conn_id) << "' retry successfull" << dendl;
}
}
INCREMENT_AND_CONTINUE(conn_it);
}
const auto rc = amqp_simple_wait_frame_noblock(conn->state, &frame, &read_timeout);
if (rc == AMQP_STATUS_TIMEOUT) {
// TODO mark connection as idle
INCREMENT_AND_CONTINUE(conn_it);
}
// this is just to prevent spinning idle, does not indicate that a message
// was successfully processed or not
incoming_message = true;
// check if error occurred that require reopening the connection
if (rc != AMQP_STATUS_OK) {
// an error occurred, close connection
// it will be retied by the main loop
ldout(cct, 1) << "AMQP run: connection read error: " << status_to_string(rc) << dendl;
conn->destroy(rc);
INCREMENT_AND_CONTINUE(conn_it);
}
if (frame.frame_type != AMQP_FRAME_METHOD) {
ldout(cct, 10) << "AMQP run: ignoring non n/ack messages. frame type: "
<< unsigned(frame.frame_type) << dendl;
// handler is for publish confirmation only - handle only method frames
INCREMENT_AND_CONTINUE(conn_it);
}
uint64_t tag;
bool multiple;
int result;
switch (frame.payload.method.id) {
case AMQP_BASIC_ACK_METHOD:
{
result = AMQP_STATUS_OK;
const auto ack = (amqp_basic_ack_t*)frame.payload.method.decoded;
ceph_assert(ack);
tag = ack->delivery_tag;
multiple = ack->multiple;
break;
}
case AMQP_BASIC_NACK_METHOD:
{
result = RGW_AMQP_STATUS_BROKER_NACK;
const auto nack = (amqp_basic_nack_t*)frame.payload.method.decoded;
ceph_assert(nack);
tag = nack->delivery_tag;
multiple = nack->multiple;
break;
}
case AMQP_BASIC_REJECT_METHOD:
{
result = RGW_AMQP_STATUS_BROKER_NACK;
const auto reject = (amqp_basic_reject_t*)frame.payload.method.decoded;
tag = reject->delivery_tag;
multiple = false;
break;
}
case AMQP_CONNECTION_CLOSE_METHOD:
// TODO on channel close, no need to reopen the connection
case AMQP_CHANNEL_CLOSE_METHOD:
{
// other side closed the connection, no need to continue
ldout(cct, 10) << "AMQP run: connection was closed by broker" << dendl;
conn->destroy(rc);
INCREMENT_AND_CONTINUE(conn_it);
}
case AMQP_BASIC_RETURN_METHOD:
// message was not delivered, returned to sender
ldout(cct, 10) << "AMQP run: message was not routable" << dendl;
INCREMENT_AND_CONTINUE(conn_it);
break;
default:
// unexpected method
ldout(cct, 10) << "AMQP run: unexpected message" << dendl;
INCREMENT_AND_CONTINUE(conn_it);
}
const auto tag_it = std::find(conn->callbacks.begin(), conn->callbacks.end(), tag);
if (tag_it != conn->callbacks.end()) {
if (multiple) {
// n/ack all up to (and including) the tag
ldout(cct, 20) << "AMQP run: multiple n/acks received with tag=" << tag << " and result=" << result << dendl;
auto it = conn->callbacks.begin();
while (it->tag <= tag && it != conn->callbacks.end()) {
ldout(cct, 20) << "AMQP run: invoking callback with tag=" << it->tag << dendl;
it->cb(result);
it = conn->callbacks.erase(it);
}
} else {
// n/ack a specific tag
ldout(cct, 20) << "AMQP run: n/ack received, invoking callback with tag=" << tag << " and result=" << result << dendl;
tag_it->cb(result);
conn->callbacks.erase(tag_it);
}
} else {
ldout(cct, 10) << "AMQP run: unsolicited n/ack received with tag=" << tag << dendl;
}
// just increment the iterator
++conn_it;
}
// if no messages were received or published, sleep for 100ms
if (count == 0 && !incoming_message) {
std::this_thread::sleep_for(idle_time);
}
}
}
// used in the dtor for message cleanup
static void delete_message(const message_wrapper_t* message) {
delete message;
}
public:
Manager(size_t _max_connections,
size_t _max_inflight,
size_t _max_queue,
long _usec_timeout,
unsigned reconnect_time_ms,
unsigned idle_time_ms,
CephContext* _cct) :
max_connections(_max_connections),
max_inflight(_max_inflight),
max_queue(_max_queue),
max_idle_time(30),
connection_count(0),
stopped(false),
read_timeout{0, _usec_timeout},
connections(_max_connections),
messages(max_queue),
queued(0),
dequeued(0),
cct(_cct),
idle_time(std::chrono::milliseconds(idle_time_ms)),
reconnect_time(std::chrono::milliseconds(reconnect_time_ms)),
runner(&Manager::run, this) {
// The hashmap has "max connections" as the initial number of buckets,
// and allows for 10 collisions per bucket before rehash.
// This is to prevent rehashing so that iterators are not invalidated
// when a new connection is added.
connections.max_load_factor(10.0);
// give the runner thread a name for easier debugging
const auto rc = ceph_pthread_setname(runner.native_handle(), "amqp_manager");
ceph_assert(rc==0);
}
// non copyable
Manager(const Manager&) = delete;
const Manager& operator=(const Manager&) = delete;
// stop the main thread
void stop() {
stopped = true;
}
// connect to a broker, or reuse an existing connection if already connected
bool connect(connection_id_t& id, const std::string& url, const std::string& exchange, bool mandatory_delivery, bool verify_ssl,
boost::optional<const std::string&> ca_location) {
if (stopped) {
ldout(cct, 1) << "AMQP connect: manager is stopped" << dendl;
return false;
}
amqp_connection_info info;
// cache the URL so that parsing could happen in-place
std::vector<char> url_cache(url.c_str(), url.c_str()+url.size()+1);
const auto retcode = amqp_parse_url(url_cache.data(), &info);
if (AMQP_STATUS_OK != retcode) {
ldout(cct, 1) << "AMQP connect: URL parsing failed. error: " << retcode << dendl;
return false;
}
connection_id_t tmp_id(info, exchange);
std::lock_guard lock(connections_lock);
const auto it = connections.find(tmp_id);
if (it != connections.end()) {
// connection found - return even if non-ok
ldout(cct, 20) << "AMQP connect: connection found" << dendl;
id = it->first;
return true;
}
// connection not found, creating a new one
if (connection_count >= max_connections) {
ldout(cct, 1) << "AMQP connect: max connections exceeded" << dendl;
return false;
}
// if error occurred during creation the creation will be retried in the main thread
++connection_count;
auto conn = connections.emplace(tmp_id, std::make_unique<connection_t>(cct, info, verify_ssl, ca_location)).first->second.get();
ldout(cct, 10) << "AMQP connect: new connection is created. Total connections: " << connection_count << dendl;
if (!new_state(conn, tmp_id)) {
ldout(cct, 1) << "AMQP connect: new connection '" << to_string(tmp_id) << "' is created. but state creation failed (will retry). error: " <<
status_to_string(conn->status) << " (" << conn->reply_code << ")" << dendl;
}
id = std::move(tmp_id);
return true;
}
// TODO publish with confirm is needed in "none" case as well, cb should be invoked publish is ok (no ack)
int publish(const connection_id_t& conn_id,
const std::string& topic,
const std::string& message) {
if (stopped) {
ldout(cct, 1) << "AMQP publish: manager is not running" << dendl;
return RGW_AMQP_STATUS_MANAGER_STOPPED;
}
auto wrapper = std::make_unique<message_wrapper_t>(conn_id, topic, message, nullptr);
if (messages.push(wrapper.get())) {
std::ignore = wrapper.release();
++queued;
return AMQP_STATUS_OK;
}
ldout(cct, 1) << "AMQP publish: queue is full" << dendl;
return RGW_AMQP_STATUS_QUEUE_FULL;
}
int publish_with_confirm(const connection_id_t& conn_id,
const std::string& topic,
const std::string& message,
reply_callback_t cb) {
if (stopped) {
ldout(cct, 1) << "AMQP publish_with_confirm: manager is not running" << dendl;
return RGW_AMQP_STATUS_MANAGER_STOPPED;
}
auto wrapper = std::make_unique<message_wrapper_t>(conn_id, topic, message, cb);
if (messages.push(wrapper.get())) {
std::ignore = wrapper.release();
++queued;
return AMQP_STATUS_OK;
}
ldout(cct, 1) << "AMQP publish_with_confirm: queue is full" << dendl;
return RGW_AMQP_STATUS_QUEUE_FULL;
}
// dtor wait for thread to stop
// then connection are cleaned-up
~Manager() {
stopped = true;
runner.join();
messages.consume_all(delete_message);
}
// get the number of connections
size_t get_connection_count() const {
return connection_count;
}
// get the number of in-flight messages
size_t get_inflight() const {
size_t sum = 0;
std::lock_guard lock(connections_lock);
std::for_each(connections.begin(), connections.end(), [&sum](auto& conn_pair) {
// concurrent access to the callback vector is safe without locking
sum += conn_pair.second->callbacks.size();
});
return sum;
}
// running counter of the queued messages
size_t get_queued() const {
return queued;
}
// running counter of the dequeued messages
size_t get_dequeued() const {
return dequeued;
}
};
// singleton manager
// note that the manager itself is not a singleton, and multiple instances may co-exist
// TODO make the pointer atomic in allocation and deallocation to avoid race conditions
static Manager* s_manager = nullptr;
static const size_t MAX_CONNECTIONS_DEFAULT = 256;
static const size_t MAX_INFLIGHT_DEFAULT = 8192;
static const size_t MAX_QUEUE_DEFAULT = 8192;
static const long READ_TIMEOUT_USEC = 100;
static const unsigned IDLE_TIME_MS = 100;
static const unsigned RECONNECT_TIME_MS = 100;
bool init(CephContext* cct) {
if (s_manager) {
return false;
}
// TODO: take conf from CephContext
s_manager = new Manager(MAX_CONNECTIONS_DEFAULT, MAX_INFLIGHT_DEFAULT, MAX_QUEUE_DEFAULT,
READ_TIMEOUT_USEC, IDLE_TIME_MS, RECONNECT_TIME_MS, cct);
return true;
}
void shutdown() {
delete s_manager;
s_manager = nullptr;
}
bool connect(connection_id_t& conn_id, const std::string& url, const std::string& exchange, bool mandatory_delivery, bool verify_ssl,
boost::optional<const std::string&> ca_location) {
if (!s_manager) return false;
return s_manager->connect(conn_id, url, exchange, mandatory_delivery, verify_ssl, ca_location);
}
int publish(const connection_id_t& conn_id,
const std::string& topic,
const std::string& message) {
if (!s_manager) return RGW_AMQP_STATUS_MANAGER_STOPPED;
return s_manager->publish(conn_id, topic, message);
}
int publish_with_confirm(const connection_id_t& conn_id,
const std::string& topic,
const std::string& message,
reply_callback_t cb) {
if (!s_manager) return RGW_AMQP_STATUS_MANAGER_STOPPED;
return s_manager->publish_with_confirm(conn_id, topic, message, cb);
}
size_t get_connection_count() {
if (!s_manager) return 0;
return s_manager->get_connection_count();
}
size_t get_inflight() {
if (!s_manager) return 0;
return s_manager->get_inflight();
}
size_t get_queued() {
if (!s_manager) return 0;
return s_manager->get_queued();
}
size_t get_dequeued() {
if (!s_manager) return 0;
return s_manager->get_dequeued();
}
size_t get_max_connections() {
if (!s_manager) return MAX_CONNECTIONS_DEFAULT;
return s_manager->max_connections;
}
size_t get_max_inflight() {
if (!s_manager) return MAX_INFLIGHT_DEFAULT;
return s_manager->max_inflight;
}
size_t get_max_queue() {
if (!s_manager) return MAX_QUEUE_DEFAULT;
return s_manager->max_queue;
}
} // namespace amqp
| 37,625 | 34.76616 | 146 |
cc
|
null |
ceph-main/src/rgw/rgw_amqp.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#pragma once
#include <string>
#include <functional>
#include <boost/optional.hpp>
#include "include/common_fwd.h"
struct amqp_connection_info;
namespace rgw::amqp {
// the reply callback is expected to get an integer parameter
// indicating the result, and not to return anything
typedef std::function<void(int)> reply_callback_t;
// initialize the amqp manager
bool init(CephContext* cct);
// shutdown the amqp manager
void shutdown();
// key class for the connection list
struct connection_id_t {
std::string host;
int port;
std::string vhost;
std::string exchange;
bool ssl;
connection_id_t() = default;
connection_id_t(const amqp_connection_info& info, const std::string& _exchange);
};
std::string to_string(const connection_id_t& id);
// connect to an amqp endpoint
bool connect(connection_id_t& conn_id, const std::string& url, const std::string& exchange, bool mandatory_delivery, bool verify_ssl,
boost::optional<const std::string&> ca_location);
// publish a message over a connection that was already created
int publish(const connection_id_t& conn_id,
const std::string& topic,
const std::string& message);
// publish a message over a connection that was already created
// and pass a callback that will be invoked (async) when broker confirms
// receiving the message
int publish_with_confirm(const connection_id_t& conn_id,
const std::string& topic,
const std::string& message,
reply_callback_t cb);
// convert the integer status returned from the "publish" function to a string
std::string status_to_string(int s);
// number of connections
size_t get_connection_count();
// return the number of messages that were sent
// to broker, but were not yet acked/nacked/timedout
size_t get_inflight();
// running counter of successfully queued messages
size_t get_queued();
// running counter of dequeued messages
size_t get_dequeued();
// number of maximum allowed connections
size_t get_max_connections();
// number of maximum allowed inflight messages
size_t get_max_inflight();
// maximum number of messages in the queue
size_t get_max_queue();
}
| 2,234 | 25.927711 | 133 |
h
|
null |
ceph-main/src/rgw/rgw_appmain.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2022 Red Hat, Inc
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#include <boost/intrusive/list.hpp>
#include "global/global_init.h"
#include "global/signal_handler.h"
#include "common/config.h"
#include "common/errno.h"
#include "common/Timer.h"
#include "common/TracepointProvider.h"
#include "common/openssl_opts_handler.h"
#include "common/numa.h"
#include "include/compat.h"
#include "include/str_list.h"
#include "include/stringify.h"
#include "rgw_main.h"
#include "rgw_common.h"
#include "rgw_sal.h"
#include "rgw_sal_config.h"
#include "rgw_period_pusher.h"
#include "rgw_realm_reloader.h"
#include "rgw_rest.h"
#include "rgw_rest_s3.h"
#include "rgw_rest_swift.h"
#include "rgw_rest_admin.h"
#include "rgw_rest_info.h"
#include "rgw_rest_usage.h"
#include "rgw_rest_bucket.h"
#include "rgw_rest_metadata.h"
#include "rgw_rest_log.h"
#include "rgw_rest_config.h"
#include "rgw_rest_realm.h"
#include "rgw_rest_ratelimit.h"
#include "rgw_rest_zero.h"
#include "rgw_swift_auth.h"
#include "rgw_log.h"
#include "rgw_lib.h"
#include "rgw_frontend.h"
#include "rgw_lib_frontend.h"
#include "rgw_tools.h"
#include "rgw_resolve.h"
#include "rgw_process.h"
#include "rgw_frontend.h"
#include "rgw_http_client_curl.h"
#include "rgw_kmip_client.h"
#include "rgw_kmip_client_impl.h"
#include "rgw_perf_counters.h"
#include "rgw_signal.h"
#ifdef WITH_RADOSGW_AMQP_ENDPOINT
#include "rgw_amqp.h"
#endif
#ifdef WITH_RADOSGW_KAFKA_ENDPOINT
#include "rgw_kafka.h"
#endif
#ifdef WITH_ARROW_FLIGHT
#include "rgw_flight_frontend.h"
#endif
#include "rgw_asio_frontend.h"
#include "rgw_dmclock_scheduler_ctx.h"
#include "rgw_lua.h"
#ifdef WITH_RADOSGW_DBSTORE
#include "rgw_sal_dbstore.h"
#endif
#include "rgw_lua_background.h"
#include "services/svc_zone.h"
#ifdef HAVE_SYS_PRCTL_H
#include <sys/prctl.h>
#endif
#define dout_subsys ceph_subsys_rgw
using namespace std;
namespace {
TracepointProvider::Traits rgw_op_tracepoint_traits(
"librgw_op_tp.so", "rgw_op_tracing");
TracepointProvider::Traits rgw_rados_tracepoint_traits(
"librgw_rados_tp.so", "rgw_rados_tracing");
}
OpsLogFile* rgw::AppMain::ops_log_file;
rgw::AppMain::AppMain(const DoutPrefixProvider* dpp) : dpp(dpp)
{
}
rgw::AppMain::~AppMain() = default;
void rgw::AppMain::init_frontends1(bool nfs)
{
this->nfs = nfs;
std::string fe_key = (nfs) ? "rgw_nfs_frontends" : "rgw_frontends";
std::vector<std::string> frontends;
std::string rgw_frontends_str = g_conf().get_val<string>(fe_key);
g_conf().early_expand_meta(rgw_frontends_str, &cerr);
get_str_vec(rgw_frontends_str, ",", frontends);
/* default frontends */
if (nfs) {
const auto is_rgw_nfs = [](const auto& s){return s == "rgw-nfs";};
if (std::find_if(frontends.begin(), frontends.end(), is_rgw_nfs) == frontends.end()) {
frontends.push_back("rgw-nfs");
}
} else {
if (frontends.empty()) {
frontends.push_back("beast");
}
}
for (auto &f : frontends) {
if (f.find("beast") != string::npos) {
have_http_frontend = true;
if (f.find("port") != string::npos) {
// check for the most common ws problems
if ((f.find("port=") == string::npos) ||
(f.find("port= ") != string::npos)) {
derr <<
R"(WARNING: radosgw frontend config found unexpected spacing around 'port'
(ensure frontend port parameter has the form 'port=80' with no spaces
before or after '='))"
<< dendl;
}
}
} else {
if (f.find("civetweb") != string::npos) {
have_http_frontend = true;
}
} /* fe !beast */
RGWFrontendConfig *config = new RGWFrontendConfig(f);
int r = config->init();
if (r < 0) {
delete config;
cerr << "ERROR: failed to init config: " << f << std::endl;
continue;
}
fe_configs.push_back(config);
fe_map.insert(
pair<string, RGWFrontendConfig *>(config->get_framework(), config));
} /* for each frontend */
// maintain existing region root pool for new multisite objects
if (!g_conf()->rgw_region_root_pool.empty()) {
const char *root_pool = g_conf()->rgw_region_root_pool.c_str();
if (g_conf()->rgw_zonegroup_root_pool.empty()) {
g_conf().set_val_or_die("rgw_zonegroup_root_pool", root_pool);
}
if (g_conf()->rgw_period_root_pool.empty()) {
g_conf().set_val_or_die("rgw_period_root_pool", root_pool);
}
if (g_conf()->rgw_realm_root_pool.empty()) {
g_conf().set_val_or_die("rgw_realm_root_pool", root_pool);
}
}
// for region -> zonegroup conversion (must happen before
// common_init_finish())
if (!g_conf()->rgw_region.empty() && g_conf()->rgw_zonegroup.empty()) {
g_conf().set_val_or_die("rgw_zonegroup", g_conf()->rgw_region.c_str());
}
ceph::crypto::init_openssl_engine_once();
} /* init_frontends1 */
void rgw::AppMain::init_numa()
{
if (nfs) {
return;
}
int numa_node = g_conf().get_val<int64_t>("rgw_numa_node");
size_t numa_cpu_set_size = 0;
cpu_set_t numa_cpu_set;
if (numa_node >= 0) {
int r = get_numa_node_cpu_set(numa_node, &numa_cpu_set_size, &numa_cpu_set);
if (r < 0) {
dout(1) << __func__ << " unable to determine rgw numa node " << numa_node
<< " CPUs" << dendl;
numa_node = -1;
} else {
r = set_cpu_affinity_all_threads(numa_cpu_set_size, &numa_cpu_set);
if (r < 0) {
derr << __func__ << " failed to set numa affinity: " << cpp_strerror(r)
<< dendl;
}
}
} else {
dout(1) << __func__ << " not setting numa affinity" << dendl;
}
} /* init_numa */
int rgw::AppMain::init_storage()
{
auto config_store_type = g_conf().get_val<std::string>("rgw_config_store");
cfgstore = DriverManager::create_config_store(dpp, config_store_type);
if (!cfgstore) {
return -EIO;
}
env.cfgstore = cfgstore.get();
int r = site.load(dpp, null_yield, cfgstore.get());
if (r < 0) {
return r;
}
env.site = &site;
auto run_gc =
(g_conf()->rgw_enable_gc_threads &&
((!nfs) || (nfs && g_conf()->rgw_nfs_run_gc_threads)));
auto run_lc =
(g_conf()->rgw_enable_lc_threads &&
((!nfs) || (nfs && g_conf()->rgw_nfs_run_lc_threads)));
auto run_quota =
(g_conf()->rgw_enable_quota_threads &&
((!nfs) || (nfs && g_conf()->rgw_nfs_run_quota_threads)));
auto run_sync =
(g_conf()->rgw_run_sync_thread &&
((!nfs) || (nfs && g_conf()->rgw_nfs_run_sync_thread)));
DriverManager::Config cfg = DriverManager::get_config(false, g_ceph_context);
env.driver = DriverManager::get_storage(dpp, dpp->get_cct(),
cfg,
run_gc,
run_lc,
run_quota,
run_sync,
g_conf().get_val<bool>("rgw_dynamic_resharding"),
true, null_yield, // run notification thread
g_conf()->rgw_cache_enabled);
if (!env.driver) {
return -EIO;
}
return 0;
} /* init_storage */
void rgw::AppMain::init_perfcounters()
{
(void) rgw_perf_start(dpp->get_cct());
} /* init_perfcounters */
void rgw::AppMain::init_http_clients()
{
rgw_init_resolver();
rgw::curl::setup_curl(fe_map);
rgw_http_client_init(dpp->get_cct());
rgw_kmip_client_init(*new RGWKMIPManagerImpl(dpp->get_cct()));
} /* init_http_clients */
void rgw::AppMain::cond_init_apis()
{
rgw_rest_init(g_ceph_context, env.driver->get_zone()->get_zonegroup());
if (have_http_frontend) {
std::vector<std::string> apis;
get_str_vec(g_conf()->rgw_enable_apis, apis);
std::map<std::string, bool> apis_map;
for (auto &api : apis) {
apis_map[api] = true;
}
/* warn about insecure keystone secret config options */
if (!(g_ceph_context->_conf->rgw_keystone_admin_token.empty() ||
g_ceph_context->_conf->rgw_keystone_admin_password.empty())) {
dout(0)
<< "WARNING: rgw_keystone_admin_token and "
"rgw_keystone_admin_password should be avoided as they can "
"expose secrets. Prefer the new rgw_keystone_admin_token_path "
"and rgw_keystone_admin_password_path options, which read their "
"secrets from files."
<< dendl;
}
// S3 website mode is a specialization of S3
const bool s3website_enabled = apis_map.count("s3website") > 0;
const bool sts_enabled = apis_map.count("sts") > 0;
const bool iam_enabled = apis_map.count("iam") > 0;
const bool pubsub_enabled =
apis_map.count("pubsub") > 0 || apis_map.count("notifications") > 0;
// Swift API entrypoint could placed in the root instead of S3
const bool swift_at_root = g_conf()->rgw_swift_url_prefix == "/";
if (apis_map.count("s3") > 0 || s3website_enabled) {
if (!swift_at_root) {
rest.register_default_mgr(set_logging(
rest_filter(env.driver, RGW_REST_S3,
new RGWRESTMgr_S3(s3website_enabled, sts_enabled,
iam_enabled, pubsub_enabled))));
} else {
derr << "Cannot have the S3 or S3 Website enabled together with "
<< "Swift API placed in the root of hierarchy" << dendl;
}
}
if (apis_map.count("swift") > 0) {
RGWRESTMgr_SWIFT* const swift_resource = new RGWRESTMgr_SWIFT;
if (! g_conf()->rgw_cross_domain_policy.empty()) {
swift_resource->register_resource("crossdomain.xml",
set_logging(new RGWRESTMgr_SWIFT_CrossDomain));
}
swift_resource->register_resource("healthcheck",
set_logging(new RGWRESTMgr_SWIFT_HealthCheck));
swift_resource->register_resource("info",
set_logging(new RGWRESTMgr_SWIFT_Info));
if (! swift_at_root) {
rest.register_resource(g_conf()->rgw_swift_url_prefix,
set_logging(rest_filter(env.driver, RGW_REST_SWIFT,
swift_resource)));
} else {
if (env.driver->get_zone()->get_zonegroup().get_zone_count() > 1) {
derr << "Placing Swift API in the root of URL hierarchy while running"
<< " multi-site configuration requires another instance of RadosGW"
<< " with S3 API enabled!" << dendl;
}
rest.register_default_mgr(set_logging(swift_resource));
}
}
if (apis_map.count("swift_auth") > 0) {
rest.register_resource(g_conf()->rgw_swift_auth_entry,
set_logging(new RGWRESTMgr_SWIFT_Auth));
}
if (apis_map.count("admin") > 0) {
RGWRESTMgr_Admin *admin_resource = new RGWRESTMgr_Admin;
admin_resource->register_resource("info", new RGWRESTMgr_Info);
admin_resource->register_resource("usage", new RGWRESTMgr_Usage);
/* Register driver-specific admin APIs */
env.driver->register_admin_apis(admin_resource);
rest.register_resource(g_conf()->rgw_admin_entry, admin_resource);
}
if (apis_map.count("zero")) {
rest.register_resource("zero", new rgw::RESTMgr_Zero());
}
} /* have_http_frontend */
} /* init_apis */
void rgw::AppMain::init_ldap()
{
CephContext* cct = env.driver->ctx();
const string &ldap_uri = cct->_conf->rgw_ldap_uri;
const string &ldap_binddn = cct->_conf->rgw_ldap_binddn;
const string &ldap_searchdn = cct->_conf->rgw_ldap_searchdn;
const string &ldap_searchfilter = cct->_conf->rgw_ldap_searchfilter;
const string &ldap_dnattr = cct->_conf->rgw_ldap_dnattr;
std::string ldap_bindpw = parse_rgw_ldap_bindpw(cct);
ldh.reset(new rgw::LDAPHelper(ldap_uri, ldap_binddn,
ldap_bindpw.c_str(), ldap_searchdn, ldap_searchfilter, ldap_dnattr));
ldh->init();
ldh->bind();
} /* init_ldap */
void rgw::AppMain::init_opslog()
{
rgw_log_usage_init(dpp->get_cct(), env.driver);
OpsLogManifold *olog_manifold = new OpsLogManifold();
if (!g_conf()->rgw_ops_log_socket_path.empty()) {
OpsLogSocket *olog_socket =
new OpsLogSocket(g_ceph_context, g_conf()->rgw_ops_log_data_backlog);
olog_socket->init(g_conf()->rgw_ops_log_socket_path);
olog_manifold->add_sink(olog_socket);
}
if (!g_conf()->rgw_ops_log_file_path.empty()) {
ops_log_file =
new OpsLogFile(g_ceph_context, g_conf()->rgw_ops_log_file_path,
g_conf()->rgw_ops_log_data_backlog);
ops_log_file->start();
olog_manifold->add_sink(ops_log_file);
}
olog_manifold->add_sink(new OpsLogRados(env.driver));
olog = olog_manifold;
} /* init_opslog */
int rgw::AppMain::init_frontends2(RGWLib* rgwlib)
{
int r{0};
vector<string> frontends_def;
std::string frontend_defs_str =
g_conf().get_val<string>("rgw_frontend_defaults");
get_str_vec(frontend_defs_str, ",", frontends_def);
service_map_meta["pid"] = stringify(getpid());
std::map<std::string, std::unique_ptr<RGWFrontendConfig> > fe_def_map;
for (auto& f : frontends_def) {
RGWFrontendConfig *config = new RGWFrontendConfig(f);
int r = config->init();
if (r < 0) {
delete config;
cerr << "ERROR: failed to init default config: " << f << std::endl;
continue;
}
fe_def_map[config->get_framework()].reset(config);
}
/* Initialize the registry of auth strategies which will coordinate
* the dynamic reconfiguration. */
implicit_tenant_context.reset(new rgw::auth::ImplicitTenants{g_conf()});
g_conf().add_observer(implicit_tenant_context.get());
/* allocate a mime table (you'd never guess that from the name) */
rgw_tools_init(dpp, dpp->get_cct());
/* Header custom behavior */
rest.register_x_headers(g_conf()->rgw_log_http_headers);
sched_ctx.reset(new rgw::dmclock::SchedulerCtx{dpp->get_cct()});
ratelimiter.reset(new ActiveRateLimiter{dpp->get_cct()});
ratelimiter->start();
// initialize RGWProcessEnv
env.rest = &rest;
env.olog = olog;
env.auth_registry = rgw::auth::StrategyRegistry::create(
dpp->get_cct(), *implicit_tenant_context, env.driver);
env.ratelimiting = ratelimiter.get();
int fe_count = 0;
for (multimap<string, RGWFrontendConfig *>::iterator fiter = fe_map.begin();
fiter != fe_map.end(); ++fiter, ++fe_count) {
RGWFrontendConfig *config = fiter->second;
string framework = config->get_framework();
auto def_iter = fe_def_map.find(framework);
if (def_iter != fe_def_map.end()) {
config->set_default_config(*def_iter->second);
}
RGWFrontend* fe = nullptr;
if (framework == "loadgen") {
fe = new RGWLoadGenFrontend(env, config);
}
else if (framework == "beast") {
fe = new RGWAsioFrontend(env, config, *sched_ctx);
}
else if (framework == "rgw-nfs") {
fe = new RGWLibFrontend(env, config);
if (rgwlib) {
rgwlib->set_fe(static_cast<RGWLibFrontend*>(fe));
}
}
else if (framework == "arrow_flight") {
#ifdef WITH_ARROW_FLIGHT
int port;
config->get_val("port", 8077, &port);
fe = new rgw::flight::FlightFrontend(env, config, port);
#else
derr << "WARNING: arrow_flight frontend requested, but not included in build; skipping" << dendl;
continue;
#endif
}
service_map_meta["frontend_type#" + stringify(fe_count)] = framework;
service_map_meta["frontend_config#" + stringify(fe_count)] = config->get_config();
if (! fe) {
dout(0) << "WARNING: skipping unknown framework: " << framework << dendl;
continue;
}
dout(0) << "starting handler: " << fiter->first << dendl;
int r = fe->init();
if (r < 0) {
derr << "ERROR: failed initializing frontend" << dendl;
return -r;
}
r = fe->run();
if (r < 0) {
derr << "ERROR: failed run" << dendl;
return -r;
}
fes.push_back(fe);
}
std::string daemon_type = (nfs) ? "rgw-nfs" : "rgw";
r = env.driver->register_to_service_map(dpp, daemon_type, service_map_meta);
if (r < 0) {
derr << "ERROR: failed to register to service map: " << cpp_strerror(-r) << dendl;
/* ignore error */
}
if (env.driver->get_name() == "rados") {
// add a watcher to respond to realm configuration changes
pusher = std::make_unique<RGWPeriodPusher>(dpp, env.driver, null_yield);
fe_pauser = std::make_unique<RGWFrontendPauser>(fes, pusher.get());
rgw_pauser = std::make_unique<RGWPauser>();
rgw_pauser->add_pauser(fe_pauser.get());
if (env.lua.background) {
rgw_pauser->add_pauser(env.lua.background);
}
reloader = std::make_unique<RGWRealmReloader>(
env, *implicit_tenant_context, service_map_meta, rgw_pauser.get());
realm_watcher = std::make_unique<RGWRealmWatcher>(dpp, g_ceph_context,
static_cast<rgw::sal::RadosStore*>(env.driver)->svc()->zone->get_realm());
realm_watcher->add_watcher(RGWRealmNotify::Reload, *reloader);
realm_watcher->add_watcher(RGWRealmNotify::ZonesNeedPeriod, *pusher.get());
}
return r;
} /* init_frontends2 */
void rgw::AppMain::init_tracepoints()
{
TracepointProvider::initialize<rgw_rados_tracepoint_traits>(dpp->get_cct());
TracepointProvider::initialize<rgw_op_tracepoint_traits>(dpp->get_cct());
tracing::rgw::tracer.init("rgw");
} /* init_tracepoints() */
void rgw::AppMain::init_notification_endpoints()
{
#ifdef WITH_RADOSGW_AMQP_ENDPOINT
if (!rgw::amqp::init(dpp->get_cct())) {
derr << "ERROR: failed to initialize AMQP manager" << dendl;
}
#endif
#ifdef WITH_RADOSGW_KAFKA_ENDPOINT
if (!rgw::kafka::init(dpp->get_cct())) {
derr << "ERROR: failed to initialize Kafka manager" << dendl;
}
#endif
} /* init_notification_endpoints */
void rgw::AppMain::init_lua()
{
rgw::sal::Driver* driver = env.driver;
int r{0};
std::string path = g_conf().get_val<std::string>("rgw_luarocks_location");
if (!path.empty()) {
path += "/" + g_conf()->name.to_str();
}
env.lua.luarocks_path = path;
#ifdef WITH_RADOSGW_LUA_PACKAGES
rgw::lua::packages_t failed_packages;
std::string output;
r = rgw::lua::install_packages(dpp, driver, null_yield, path,
failed_packages, output);
if (r < 0) {
dout(1) << "WARNING: failed to install lua packages from allowlist. error: " << r
<< dendl;
}
if (!output.empty()) {
dout(10) << "INFO: lua packages installation output: \n" << output << dendl;
}
for (const auto &p : failed_packages) {
dout(5) << "WARNING: failed to install lua package: " << p
<< " from allowlist" << dendl;
}
#endif
env.lua.manager = env.driver->get_lua_manager();
if (driver->get_name() == "rados") { /* Supported for only RadosStore */
lua_background = std::make_unique<
rgw::lua::Background>(driver, dpp->get_cct(), path);
lua_background->start();
env.lua.background = lua_background.get();
}
} /* init_lua */
void rgw::AppMain::shutdown(std::function<void(void)> finalize_async_signals)
{
if (env.driver->get_name() == "rados") {
reloader.reset(); // stop the realm reloader
}
for (auto& fe : fes) {
fe->stop();
}
for (auto& fe : fes) {
fe->join();
delete fe;
}
for (auto& fec : fe_configs) {
delete fec;
}
ldh.reset(nullptr); // deletes
finalize_async_signals(); // callback
rgw_log_usage_finalize();
delete olog;
if (lua_background) {
lua_background->shutdown();
}
cfgstore.reset(); // deletes
DriverManager::close_storage(env.driver);
rgw_tools_cleanup();
rgw_shutdown_resolver();
rgw_http_client_cleanup();
rgw_kmip_client_cleanup();
rgw::curl::cleanup_curl();
g_conf().remove_observer(implicit_tenant_context.get());
implicit_tenant_context.reset(); // deletes
#ifdef WITH_RADOSGW_AMQP_ENDPOINT
rgw::amqp::shutdown();
#endif
#ifdef WITH_RADOSGW_KAFKA_ENDPOINT
rgw::kafka::shutdown();
#endif
rgw_perf_stop(g_ceph_context);
ratelimiter.reset(); // deletes--ensure this happens before we destruct
} /* AppMain::shutdown */
| 20,164 | 30.755906 | 103 |
cc
|
null |
ceph-main/src/rgw/rgw_arn.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include "rgw_arn.h"
#include "rgw_common.h"
#include <regex>
using namespace std;
namespace rgw {
namespace {
boost::optional<Partition> to_partition(const smatch::value_type& p,
bool wildcards) {
if (p == "aws") {
return Partition::aws;
} else if (p == "aws-cn") {
return Partition::aws_cn;
} else if (p == "aws-us-gov") {
return Partition::aws_us_gov;
} else if (p == "*" && wildcards) {
return Partition::wildcard;
} else {
return boost::none;
}
ceph_abort();
}
boost::optional<Service> to_service(const smatch::value_type& s,
bool wildcards) {
static const unordered_map<string, Service> services = {
{ "acm", Service::acm },
{ "apigateway", Service::apigateway },
{ "appstream", Service::appstream },
{ "artifact", Service::artifact },
{ "autoscaling", Service::autoscaling },
{ "aws-marketplace", Service::aws_marketplace },
{ "aws-marketplace-management",
Service::aws_marketplace_management },
{ "aws-portal", Service::aws_portal },
{ "cloudformation", Service::cloudformation },
{ "cloudfront", Service::cloudfront },
{ "cloudhsm", Service::cloudhsm },
{ "cloudsearch", Service::cloudsearch },
{ "cloudtrail", Service::cloudtrail },
{ "cloudwatch", Service::cloudwatch },
{ "codebuild", Service::codebuild },
{ "codecommit", Service::codecommit },
{ "codedeploy", Service::codedeploy },
{ "codepipeline", Service::codepipeline },
{ "cognito-identity", Service::cognito_identity },
{ "cognito-idp", Service::cognito_idp },
{ "cognito-sync", Service::cognito_sync },
{ "config", Service::config },
{ "datapipeline", Service::datapipeline },
{ "devicefarm", Service::devicefarm },
{ "directconnect", Service::directconnect },
{ "dms", Service::dms },
{ "ds", Service::ds },
{ "dynamodb", Service::dynamodb },
{ "ec2", Service::ec2 },
{ "ecr", Service::ecr },
{ "ecs", Service::ecs },
{ "elasticache", Service::elasticache },
{ "elasticbeanstalk", Service::elasticbeanstalk },
{ "elasticfilesystem", Service::elasticfilesystem },
{ "elasticloadbalancing", Service::elasticloadbalancing },
{ "elasticmapreduce", Service::elasticmapreduce },
{ "elastictranscoder", Service::elastictranscoder },
{ "es", Service::es },
{ "events", Service::events },
{ "firehose", Service::firehose },
{ "gamelift", Service::gamelift },
{ "glacier", Service::glacier },
{ "health", Service::health },
{ "iam", Service::iam },
{ "importexport", Service::importexport },
{ "inspector", Service::inspector },
{ "iot", Service::iot },
{ "kinesis", Service::kinesis },
{ "kinesisanalytics", Service::kinesisanalytics },
{ "kms", Service::kms },
{ "lambda", Service::lambda },
{ "lightsail", Service::lightsail },
{ "logs", Service::logs },
{ "machinelearning", Service::machinelearning },
{ "mobileanalytics", Service::mobileanalytics },
{ "mobilehub", Service::mobilehub },
{ "opsworks", Service::opsworks },
{ "opsworks-cm", Service::opsworks_cm },
{ "polly", Service::polly },
{ "rds", Service::rds },
{ "redshift", Service::redshift },
{ "route53", Service::route53 },
{ "route53domains", Service::route53domains },
{ "s3", Service::s3 },
{ "sdb", Service::sdb },
{ "servicecatalog", Service::servicecatalog },
{ "ses", Service::ses },
{ "sns", Service::sns },
{ "sqs", Service::sqs },
{ "ssm", Service::ssm },
{ "states", Service::states },
{ "storagegateway", Service::storagegateway },
{ "sts", Service::sts },
{ "support", Service::support },
{ "swf", Service::swf },
{ "trustedadvisor", Service::trustedadvisor },
{ "waf", Service::waf },
{ "workmail", Service::workmail },
{ "workspaces", Service::workspaces }};
if (wildcards && s == "*") {
return Service::wildcard;
}
auto i = services.find(s);
if (i == services.end()) {
return boost::none;
} else {
return i->second;
}
}
}
ARN::ARN(const rgw_obj& o)
: partition(Partition::aws),
service(Service::s3),
region(),
account(o.bucket.tenant),
resource(o.bucket.name)
{
resource.push_back('/');
resource.append(o.key.name);
}
ARN::ARN(const rgw_bucket& b)
: partition(Partition::aws),
service(Service::s3),
region(),
account(b.tenant),
resource(b.name) { }
ARN::ARN(const rgw_bucket& b, const std::string& o)
: partition(Partition::aws),
service(Service::s3),
region(),
account(b.tenant),
resource(b.name) {
resource.push_back('/');
resource.append(o);
}
ARN::ARN(const std::string& resource_name, const std::string& type, const std::string& tenant, bool has_path)
: partition(Partition::aws),
service(Service::iam),
region(),
account(tenant),
resource(type) {
if (! has_path)
resource.push_back('/');
resource.append(resource_name);
}
boost::optional<ARN> ARN::parse(const std::string& s, bool wildcards) {
static const std::regex rx_wild("arn:([^:]*):([^:]*):([^:]*):([^:]*):([^:]*)",
std::regex_constants::ECMAScript |
std::regex_constants::optimize);
static const std::regex rx_no_wild(
"arn:([^:*]*):([^:*]*):([^:*]*):([^:*]*):(.*)",
std::regex_constants::ECMAScript |
std::regex_constants::optimize);
smatch match;
if ((s == "*") && wildcards) {
return ARN(Partition::wildcard, Service::wildcard, "*", "*", "*");
} else if (regex_match(s, match, wildcards ? rx_wild : rx_no_wild) &&
match.size() == 6) {
if (auto p = to_partition(match[1], wildcards)) {
if (auto s = to_service(match[2], wildcards)) {
return ARN(*p, *s, match[3], match[4], match[5]);
}
}
}
return boost::none;
}
std::string ARN::to_string() const {
std::string s{"arn:"};
if (partition == Partition::aws) {
s.append("aws:");
} else if (partition == Partition::aws_cn) {
s.append("aws-cn:");
} else if (partition == Partition::aws_us_gov) {
s.append("aws-us-gov:");
} else {
s.append("*:");
}
static const std::unordered_map<Service, string> services = {
{ Service::acm, "acm" },
{ Service::apigateway, "apigateway" },
{ Service::appstream, "appstream" },
{ Service::artifact, "artifact" },
{ Service::autoscaling, "autoscaling" },
{ Service::aws_marketplace, "aws-marketplace" },
{ Service::aws_marketplace_management, "aws-marketplace-management" },
{ Service::aws_portal, "aws-portal" },
{ Service::cloudformation, "cloudformation" },
{ Service::cloudfront, "cloudfront" },
{ Service::cloudhsm, "cloudhsm" },
{ Service::cloudsearch, "cloudsearch" },
{ Service::cloudtrail, "cloudtrail" },
{ Service::cloudwatch, "cloudwatch" },
{ Service::codebuild, "codebuild" },
{ Service::codecommit, "codecommit" },
{ Service::codedeploy, "codedeploy" },
{ Service::codepipeline, "codepipeline" },
{ Service::cognito_identity, "cognito-identity" },
{ Service::cognito_idp, "cognito-idp" },
{ Service::cognito_sync, "cognito-sync" },
{ Service::config, "config" },
{ Service::datapipeline, "datapipeline" },
{ Service::devicefarm, "devicefarm" },
{ Service::directconnect, "directconnect" },
{ Service::dms, "dms" },
{ Service::ds, "ds" },
{ Service::dynamodb, "dynamodb" },
{ Service::ec2, "ec2" },
{ Service::ecr, "ecr" },
{ Service::ecs, "ecs" },
{ Service::elasticache, "elasticache" },
{ Service::elasticbeanstalk, "elasticbeanstalk" },
{ Service::elasticfilesystem, "elasticfilesystem" },
{ Service::elasticloadbalancing, "elasticloadbalancing" },
{ Service::elasticmapreduce, "elasticmapreduce" },
{ Service::elastictranscoder, "elastictranscoder" },
{ Service::es, "es" },
{ Service::events, "events" },
{ Service::firehose, "firehose" },
{ Service::gamelift, "gamelift" },
{ Service::glacier, "glacier" },
{ Service::health, "health" },
{ Service::iam, "iam" },
{ Service::importexport, "importexport" },
{ Service::inspector, "inspector" },
{ Service::iot, "iot" },
{ Service::kinesis, "kinesis" },
{ Service::kinesisanalytics, "kinesisanalytics" },
{ Service::kms, "kms" },
{ Service::lambda, "lambda" },
{ Service::lightsail, "lightsail" },
{ Service::logs, "logs" },
{ Service::machinelearning, "machinelearning" },
{ Service::mobileanalytics, "mobileanalytics" },
{ Service::mobilehub, "mobilehub" },
{ Service::opsworks, "opsworks" },
{ Service::opsworks_cm, "opsworks-cm" },
{ Service::polly, "polly" },
{ Service::rds, "rds" },
{ Service::redshift, "redshift" },
{ Service::route53, "route53" },
{ Service::route53domains, "route53domains" },
{ Service::s3, "s3" },
{ Service::sdb, "sdb" },
{ Service::servicecatalog, "servicecatalog" },
{ Service::ses, "ses" },
{ Service::sns, "sns" },
{ Service::sqs, "sqs" },
{ Service::ssm, "ssm" },
{ Service::states, "states" },
{ Service::storagegateway, "storagegateway" },
{ Service::sts, "sts" },
{ Service::support, "support" },
{ Service::swf, "swf" },
{ Service::trustedadvisor, "trustedadvisor" },
{ Service::waf, "waf" },
{ Service::workmail, "workmail" },
{ Service::workspaces, "workspaces" }};
auto i = services.find(service);
if (i != services.end()) {
s.append(i->second);
} else {
s.push_back('*');
}
s.push_back(':');
s.append(region);
s.push_back(':');
s.append(account);
s.push_back(':');
s.append(resource);
return s;
}
bool operator ==(const ARN& l, const ARN& r) {
return ((l.partition == r.partition) &&
(l.service == r.service) &&
(l.region == r.region) &&
(l.account == r.account) &&
(l.resource == r.resource));
}
bool operator <(const ARN& l, const ARN& r) {
return ((l.partition < r.partition) ||
(l.service < r.service) ||
(l.region < r.region) ||
(l.account < r.account) ||
(l.resource < r.resource));
}
// The candidate is not allowed to have wildcards. The only way to
// do that sanely would be to use unification rather than matching.
bool ARN::match(const ARN& candidate) const {
if ((candidate.partition == Partition::wildcard) ||
(partition != candidate.partition && partition
!= Partition::wildcard)) {
return false;
}
if ((candidate.service == Service::wildcard) ||
(service != candidate.service && service != Service::wildcard)) {
return false;
}
if (!match_policy(region, candidate.region, MATCH_POLICY_ARN)) {
return false;
}
if (!match_policy(account, candidate.account, MATCH_POLICY_ARN)) {
return false;
}
if (!match_policy(resource, candidate.resource, MATCH_POLICY_RESOURCE)) {
return false;
}
return true;
}
boost::optional<ARNResource> ARNResource::parse(const std::string& s) {
static const std::regex rx("^([^:/]*)[:/]?([^:/]*)?[:/]?(.*)$",
std::regex_constants::ECMAScript |
std::regex_constants::optimize);
std::smatch match;
if (!regex_match(s, match, rx)) {
return boost::none;
}
if (match[2].str().empty() && match[3].str().empty()) {
// only resource exist
return rgw::ARNResource("", match[1], "");
}
// resource type also exist, and cannot be wildcard
if (match[1] != std::string(wildcard)) {
// resource type cannot be wildcard
return rgw::ARNResource(match[1], match[2], match[3]);
}
return boost::none;
}
std::string ARNResource::to_string() const {
std::string s;
if (!resource_type.empty()) {
s.append(resource_type);
s.push_back(':');
s.append(resource);
s.push_back(':');
s.append(qualifier);
} else {
s.append(resource);
}
return s;
}
}
| 11,916 | 29.713918 | 109 |
cc
|
null |
ceph-main/src/rgw/rgw_arn.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#pragma once
#include <string>
#include <boost/optional.hpp>
class rgw_obj;
class rgw_bucket;
namespace rgw {
enum struct Partition {
aws, aws_cn, aws_us_gov, wildcard
// If we wanted our own ARNs for principal type unique to us
// (maybe to integrate better with Swift) or for anything else we
// provide that doesn't map onto S3, we could add an 'rgw'
// partition type.
};
enum struct Service {
apigateway, appstream, artifact, autoscaling, aws_portal, acm,
cloudformation, cloudfront, cloudhsm, cloudsearch, cloudtrail,
cloudwatch, events, logs, codebuild, codecommit, codedeploy,
codepipeline, cognito_idp, cognito_identity, cognito_sync,
config, datapipeline, dms, devicefarm, directconnect,
ds, dynamodb, ec2, ecr, ecs, ssm, elasticbeanstalk, elasticfilesystem,
elasticloadbalancing, elasticmapreduce, elastictranscoder, elasticache,
es, gamelift, glacier, health, iam, importexport, inspector, iot,
kms, kinesisanalytics, firehose, kinesis, lambda, lightsail,
machinelearning, aws_marketplace, aws_marketplace_management,
mobileanalytics, mobilehub, opsworks, opsworks_cm, polly,
redshift, rds, route53, route53domains, sts, servicecatalog,
ses, sns, sqs, s3, swf, sdb, states, storagegateway, support,
trustedadvisor, waf, workmail, workspaces, wildcard
};
/* valid format:
* 'arn:partition:service:region:account-id:resource'
* The 'resource' part can be further broken down via ARNResource
*/
struct ARN {
Partition partition;
Service service;
std::string region;
// Once we refit tenant, we should probably use that instead of a
// string.
std::string account;
std::string resource;
ARN()
: partition(Partition::wildcard), service(Service::wildcard) {}
ARN(Partition partition, Service service, std::string region,
std::string account, std::string resource)
: partition(partition), service(service), region(std::move(region)),
account(std::move(account)), resource(std::move(resource)) {}
ARN(const rgw_obj& o);
ARN(const rgw_bucket& b);
ARN(const rgw_bucket& b, const std::string& o);
ARN(const std::string& resource_name, const std::string& type, const std::string& tenant, bool has_path=false);
static boost::optional<ARN> parse(const std::string& s,
bool wildcard = false);
std::string to_string() const;
// `this` is the pattern
bool match(const ARN& candidate) const;
};
inline std::string to_string(const ARN& a) {
return a.to_string();
}
inline std::ostream& operator <<(std::ostream& m, const ARN& a) {
return m << to_string(a);
}
bool operator ==(const ARN& l, const ARN& r);
bool operator <(const ARN& l, const ARN& r);
/* valid formats (only resource part):
* 'resource'
* 'resourcetype/resource'
* 'resourcetype/resource/qualifier'
* 'resourcetype/resource:qualifier'
* 'resourcetype:resource'
* 'resourcetype:resource:qualifier'
* Note that 'resourceType' cannot be wildcard
*/
struct ARNResource {
constexpr static const char* const wildcard = "*";
std::string resource_type;
std::string resource;
std::string qualifier;
ARNResource() : resource_type(""), resource(wildcard), qualifier("") {}
ARNResource(const std::string& _resource_type, const std::string& _resource, const std::string& _qualifier) :
resource_type(std::move(_resource_type)), resource(std::move(_resource)), qualifier(std::move(_qualifier)) {}
static boost::optional<ARNResource> parse(const std::string& s);
std::string to_string() const;
};
inline std::string to_string(const ARNResource& r) {
return r.to_string();
}
} // namespace rgw
namespace std {
template<>
struct hash<::rgw::Service> {
size_t operator()(const ::rgw::Service& s) const noexcept {
// Invoke a default-constructed hash object for int.
return hash<int>()(static_cast<int>(s));
}
};
} // namespace std
| 3,948 | 31.368852 | 113 |
h
|
null |
ceph-main/src/rgw/rgw_asio_client.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include <boost/algorithm/string/predicate.hpp>
#include <boost/asio/write.hpp>
#include "rgw_asio_client.h"
#include "rgw_perf_counters.h"
#define dout_context g_ceph_context
#define dout_subsys ceph_subsys_rgw
using namespace rgw::asio;
ClientIO::ClientIO(parser_type& parser, bool is_ssl,
const endpoint_type& local_endpoint,
const endpoint_type& remote_endpoint)
: parser(parser), is_ssl(is_ssl),
local_endpoint(local_endpoint),
remote_endpoint(remote_endpoint),
txbuf(*this)
{
}
ClientIO::~ClientIO() = default;
int ClientIO::init_env(CephContext *cct)
{
env.init(cct);
perfcounter->inc(l_rgw_qlen);
perfcounter->inc(l_rgw_qactive);
const auto& request = parser.get();
const auto& headers = request;
for (auto header = headers.begin(); header != headers.end(); ++header) {
const auto& field = header->name(); // enum type for known headers
const auto& name = header->name_string();
const auto& value = header->value();
if (field == beast::http::field::content_length) {
env.set("CONTENT_LENGTH", std::string(value));
continue;
}
if (field == beast::http::field::content_type) {
env.set("CONTENT_TYPE", std::string(value));
continue;
}
static const std::string_view HTTP_{"HTTP_"};
char buf[name.size() + HTTP_.size() + 1];
auto dest = std::copy(std::begin(HTTP_), std::end(HTTP_), buf);
for (auto src = name.begin(); src != name.end(); ++src, ++dest) {
if (*src == '-') {
*dest = '_';
} else if (*src == '_') {
*dest = '-';
} else {
*dest = std::toupper(*src);
}
}
*dest = '\0';
env.set(buf, std::string(value));
}
int major = request.version() / 10;
int minor = request.version() % 10;
env.set("HTTP_VERSION", std::to_string(major) + '.' + std::to_string(minor));
env.set("REQUEST_METHOD", std::string(request.method_string()));
// split uri from query
auto uri = request.target();
auto pos = uri.find('?');
if (pos != uri.npos) {
auto query = uri.substr(pos + 1);
env.set("QUERY_STRING", std::string(query));
uri = uri.substr(0, pos);
}
env.set("SCRIPT_URI", std::string(uri));
env.set("REQUEST_URI", std::string(request.target()));
char port_buf[16];
snprintf(port_buf, sizeof(port_buf), "%d", local_endpoint.port());
env.set("SERVER_PORT", port_buf);
if (is_ssl) {
env.set("SERVER_PORT_SECURE", port_buf);
}
env.set("REMOTE_ADDR", remote_endpoint.address().to_string());
// TODO: set REMOTE_USER if authenticated
return 0;
}
size_t ClientIO::complete_request()
{
perfcounter->inc(l_rgw_qlen, -1);
perfcounter->inc(l_rgw_qactive, -1);
return 0;
}
void ClientIO::flush()
{
txbuf.pubsync();
}
size_t ClientIO::send_status(int status, const char* status_name)
{
static constexpr size_t STATUS_BUF_SIZE = 128;
char statusbuf[STATUS_BUF_SIZE];
const auto statuslen = snprintf(statusbuf, sizeof(statusbuf),
"HTTP/1.1 %d %s\r\n", status, status_name);
return txbuf.sputn(statusbuf, statuslen);
}
size_t ClientIO::send_100_continue()
{
const char HTTTP_100_CONTINUE[] = "HTTP/1.1 100 CONTINUE\r\n\r\n";
const size_t sent = txbuf.sputn(HTTTP_100_CONTINUE,
sizeof(HTTTP_100_CONTINUE) - 1);
flush();
sent100continue = true;
return sent;
}
static constexpr size_t TIME_BUF_SIZE = 128;
static size_t dump_date_header(char (×tr)[TIME_BUF_SIZE])
{
const time_t gtime = time(nullptr);
struct tm result;
struct tm const * const tmp = gmtime_r(>ime, &result);
if (tmp == nullptr) {
return 0;
}
return strftime(timestr, sizeof(timestr),
"Date: %a, %d %b %Y %H:%M:%S %Z\r\n", tmp);
}
size_t ClientIO::complete_header()
{
size_t sent = 0;
char timestr[TIME_BUF_SIZE];
if (dump_date_header(timestr)) {
sent += txbuf.sputn(timestr, strlen(timestr));
}
if (parser.keep_alive()) {
constexpr char CONN_KEEP_ALIVE[] = "Connection: Keep-Alive\r\n";
sent += txbuf.sputn(CONN_KEEP_ALIVE, sizeof(CONN_KEEP_ALIVE) - 1);
} else {
constexpr char CONN_KEEP_CLOSE[] = "Connection: close\r\n";
sent += txbuf.sputn(CONN_KEEP_CLOSE, sizeof(CONN_KEEP_CLOSE) - 1);
}
constexpr char HEADER_END[] = "\r\n";
sent += txbuf.sputn(HEADER_END, sizeof(HEADER_END) - 1);
flush();
return sent;
}
size_t ClientIO::send_header(const std::string_view& name,
const std::string_view& value)
{
static constexpr char HEADER_SEP[] = ": ";
static constexpr char HEADER_END[] = "\r\n";
size_t sent = 0;
sent += txbuf.sputn(name.data(), name.length());
sent += txbuf.sputn(HEADER_SEP, sizeof(HEADER_SEP) - 1);
sent += txbuf.sputn(value.data(), value.length());
sent += txbuf.sputn(HEADER_END, sizeof(HEADER_END) - 1);
return sent;
}
size_t ClientIO::send_content_length(uint64_t len)
{
static constexpr size_t CONLEN_BUF_SIZE = 128;
char sizebuf[CONLEN_BUF_SIZE];
const auto sizelen = snprintf(sizebuf, sizeof(sizebuf),
"Content-Length: %" PRIu64 "\r\n", len);
return txbuf.sputn(sizebuf, sizelen);
}
| 5,299 | 26.46114 | 79 |
cc
|
null |
ceph-main/src/rgw/rgw_asio_client.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#pragma once
#include <boost/asio/ip/tcp.hpp>
#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include "include/ceph_assert.h"
#include "rgw_client_io.h"
namespace rgw {
namespace asio {
namespace beast = boost::beast;
using parser_type = beast::http::request_parser<beast::http::buffer_body>;
class ClientIO : public io::RestfulClient,
public io::BuffererSink {
protected:
parser_type& parser;
private:
const bool is_ssl;
using endpoint_type = boost::asio::ip::tcp::endpoint;
endpoint_type local_endpoint;
endpoint_type remote_endpoint;
RGWEnv env;
rgw::io::StaticOutputBufferer<> txbuf;
bool sent100continue = false;
public:
ClientIO(parser_type& parser, bool is_ssl,
const endpoint_type& local_endpoint,
const endpoint_type& remote_endpoint);
~ClientIO() override;
int init_env(CephContext *cct) override;
size_t complete_request() override;
void flush() override;
size_t send_status(int status, const char *status_name) override;
size_t send_100_continue() override;
size_t send_header(const std::string_view& name,
const std::string_view& value) override;
size_t send_content_length(uint64_t len) override;
size_t complete_header() override;
size_t send_body(const char* buf, size_t len) override {
return write_data(buf, len);
}
RGWEnv& get_env() noexcept override {
return env;
}
bool sent_100_continue() const { return sent100continue; }
};
} // namespace asio
} // namespace rgw
| 1,640 | 25.047619 | 74 |
h
|
null |
ceph-main/src/rgw/rgw_asio_frontend.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include <atomic>
#include <ctime>
#include <thread>
#include <vector>
#include <boost/asio.hpp>
#include <boost/intrusive/list.hpp>
#include <boost/smart_ptr/intrusive_ref_counter.hpp>
#include <boost/context/protected_fixedsize_stack.hpp>
#include <spawn/spawn.hpp>
#include "common/async/shared_mutex.h"
#include "common/errno.h"
#include "common/strtol.h"
#include "rgw_asio_client.h"
#include "rgw_asio_frontend.h"
#ifdef WITH_RADOSGW_BEAST_OPENSSL
#include <boost/asio/ssl.hpp>
#endif
#include "common/split.h"
#include "services/svc_config_key.h"
#include "services/svc_zone.h"
#include "rgw_zone.h"
#include "rgw_asio_frontend_timer.h"
#include "rgw_dmclock_async_scheduler.h"
#define dout_subsys ceph_subsys_rgw
namespace {
using tcp = boost::asio::ip::tcp;
namespace http = boost::beast::http;
#ifdef WITH_RADOSGW_BEAST_OPENSSL
namespace ssl = boost::asio::ssl;
#endif
struct Connection;
// use explicit executor types instead of the type-erased boost::asio::executor
using executor_type = boost::asio::io_context::executor_type;
using tcp_socket = boost::asio::basic_stream_socket<tcp, executor_type>;
using tcp_stream = boost::beast::basic_stream<tcp, executor_type>;
using timeout_timer = rgw::basic_timeout_timer<ceph::coarse_mono_clock,
executor_type, Connection>;
static constexpr size_t parse_buffer_size = 65536;
using parse_buffer = boost::beast::flat_static_buffer<parse_buffer_size>;
// use mmap/mprotect to allocate 512k coroutine stacks
auto make_stack_allocator() {
return boost::context::protected_fixedsize_stack{512*1024};
}
using namespace std;
template <typename Stream>
class StreamIO : public rgw::asio::ClientIO {
CephContext* const cct;
Stream& stream;
timeout_timer& timeout;
yield_context yield;
parse_buffer& buffer;
boost::system::error_code fatal_ec;
public:
StreamIO(CephContext *cct, Stream& stream, timeout_timer& timeout,
rgw::asio::parser_type& parser, yield_context yield,
parse_buffer& buffer, bool is_ssl,
const tcp::endpoint& local_endpoint,
const tcp::endpoint& remote_endpoint)
: ClientIO(parser, is_ssl, local_endpoint, remote_endpoint),
cct(cct), stream(stream), timeout(timeout), yield(yield),
buffer(buffer)
{}
boost::system::error_code get_fatal_error_code() const { return fatal_ec; }
size_t write_data(const char* buf, size_t len) override {
boost::system::error_code ec;
timeout.start();
auto bytes = boost::asio::async_write(stream, boost::asio::buffer(buf, len),
yield[ec]);
timeout.cancel();
if (ec) {
ldout(cct, 4) << "write_data failed: " << ec.message() << dendl;
if (ec == boost::asio::error::broken_pipe) {
boost::system::error_code ec_ignored;
stream.lowest_layer().shutdown(tcp_socket::shutdown_both, ec_ignored);
}
if (!fatal_ec) {
fatal_ec = ec;
}
throw rgw::io::Exception(ec.value(), std::system_category());
}
return bytes;
}
size_t recv_body(char* buf, size_t max) override {
auto& message = parser.get();
auto& body_remaining = message.body();
body_remaining.data = buf;
body_remaining.size = max;
while (body_remaining.size && !parser.is_done()) {
boost::system::error_code ec;
timeout.start();
http::async_read_some(stream, buffer, parser, yield[ec]);
timeout.cancel();
if (ec == http::error::need_buffer) {
break;
}
if (ec) {
ldout(cct, 4) << "failed to read body: " << ec.message() << dendl;
if (!fatal_ec) {
fatal_ec = ec;
}
throw rgw::io::Exception(ec.value(), std::system_category());
}
}
return max - body_remaining.size;
}
};
// output the http version as a string, ie 'HTTP/1.1'
struct http_version {
unsigned major_ver;
unsigned minor_ver;
explicit http_version(unsigned version)
: major_ver(version / 10), minor_ver(version % 10) {}
};
std::ostream& operator<<(std::ostream& out, const http_version& v) {
return out << "HTTP/" << v.major_ver << '.' << v.minor_ver;
}
// log an http header value or '-' if it's missing
struct log_header {
const http::fields& fields;
http::field field;
std::string_view quote;
log_header(const http::fields& fields, http::field field,
std::string_view quote = "")
: fields(fields), field(field), quote(quote) {}
};
std::ostream& operator<<(std::ostream& out, const log_header& h) {
auto p = h.fields.find(h.field);
if (p == h.fields.end()) {
return out << '-';
}
return out << h.quote << p->value() << h.quote;
}
// log fractional seconds in milliseconds
struct log_ms_remainder {
ceph::coarse_real_time t;
log_ms_remainder(ceph::coarse_real_time t) : t(t) {}
};
std::ostream& operator<<(std::ostream& out, const log_ms_remainder& m) {
using namespace std::chrono;
return out << std::setfill('0') << std::setw(3)
<< duration_cast<milliseconds>(m.t.time_since_epoch()).count() % 1000;
}
// log time in apache format: day/month/year:hour:minute:second zone
struct log_apache_time {
ceph::coarse_real_time t;
log_apache_time(ceph::coarse_real_time t) : t(t) {}
};
std::ostream& operator<<(std::ostream& out, const log_apache_time& a) {
const auto t = ceph::coarse_real_clock::to_time_t(a.t);
const auto local = std::localtime(&t);
return out << std::put_time(local, "%d/%b/%Y:%T.") << log_ms_remainder{a.t}
<< std::put_time(local, " %z");
};
using SharedMutex = ceph::async::SharedMutex<boost::asio::io_context::executor_type>;
template <typename Stream>
void handle_connection(boost::asio::io_context& context,
RGWProcessEnv& env, Stream& stream,
timeout_timer& timeout, size_t header_limit,
parse_buffer& buffer, bool is_ssl,
SharedMutex& pause_mutex,
rgw::dmclock::Scheduler *scheduler,
const std::string& uri_prefix,
boost::system::error_code& ec,
yield_context yield)
{
// don't impose a limit on the body, since we read it in pieces
static constexpr size_t body_limit = std::numeric_limits<size_t>::max();
auto cct = env.driver->ctx();
// read messages from the stream until eof
for (;;) {
// configure the parser
rgw::asio::parser_type parser;
parser.header_limit(header_limit);
parser.body_limit(body_limit);
timeout.start();
// parse the header
http::async_read_header(stream, buffer, parser, yield[ec]);
timeout.cancel();
if (ec == boost::asio::error::connection_reset ||
ec == boost::asio::error::bad_descriptor ||
ec == boost::asio::error::operation_aborted ||
#ifdef WITH_RADOSGW_BEAST_OPENSSL
ec == ssl::error::stream_truncated ||
#endif
ec == http::error::end_of_stream) {
ldout(cct, 20) << "failed to read header: " << ec.message() << dendl;
return;
}
auto& message = parser.get();
if (ec) {
ldout(cct, 1) << "failed to read header: " << ec.message() << dendl;
http::response<http::empty_body> response;
response.result(http::status::bad_request);
response.version(message.version() == 10 ? 10 : 11);
response.prepare_payload();
timeout.start();
http::async_write(stream, response, yield[ec]);
timeout.cancel();
if (ec) {
ldout(cct, 5) << "failed to write response: " << ec.message() << dendl;
}
ldout(cct, 1) << "====== req done http_status=400 ======" << dendl;
return;
}
bool expect_continue = (message[http::field::expect] == "100-continue");
{
auto lock = pause_mutex.async_lock_shared(yield[ec]);
if (ec == boost::asio::error::operation_aborted) {
return;
} else if (ec) {
ldout(cct, 1) << "failed to lock: " << ec.message() << dendl;
return;
}
// process the request
RGWRequest req{env.driver->get_new_req_id()};
auto& socket = stream.lowest_layer();
const auto& remote_endpoint = socket.remote_endpoint(ec);
if (ec) {
ldout(cct, 1) << "failed to connect client: " << ec.message() << dendl;
return;
}
const auto& local_endpoint = socket.local_endpoint(ec);
if (ec) {
ldout(cct, 1) << "failed to connect client: " << ec.message() << dendl;
return;
}
StreamIO real_client{cct, stream, timeout, parser, yield, buffer,
is_ssl, local_endpoint, remote_endpoint};
auto real_client_io = rgw::io::add_reordering(
rgw::io::add_buffering(cct,
rgw::io::add_chunking(
rgw::io::add_conlen_controlling(
&real_client))));
RGWRestfulIO client(cct, &real_client_io);
optional_yield y = null_yield;
if (cct->_conf->rgw_beast_enable_async) {
y = optional_yield{context, yield};
}
int http_ret = 0;
string user = "-";
const auto started = ceph::coarse_real_clock::now();
ceph::coarse_real_clock::duration latency{};
process_request(env, &req, uri_prefix, &client, y,
scheduler, &user, &latency, &http_ret);
if (cct->_conf->subsys.should_gather(ceph_subsys_rgw_access, 1)) {
// access log line elements begin per Apache Combined Log Format with additions following
lsubdout(cct, rgw_access, 1) << "beast: " << std::hex << &req << std::dec << ": "
<< remote_endpoint.address() << " - " << user << " [" << log_apache_time{started} << "] \""
<< message.method_string() << ' ' << message.target() << ' '
<< http_version{message.version()} << "\" " << http_ret << ' '
<< client.get_bytes_sent() + client.get_bytes_received() << ' '
<< log_header{message, http::field::referer, "\""} << ' '
<< log_header{message, http::field::user_agent, "\""} << ' '
<< log_header{message, http::field::range} << " latency="
<< latency << dendl;
}
// process_request() can't distinguish between connection errors and
// http/s3 errors, so check StreamIO for fatal connection errors
ec = real_client.get_fatal_error_code();
if (ec) {
return;
}
if (real_client.sent_100_continue()) {
expect_continue = false;
}
}
if (!parser.keep_alive()) {
return;
}
// if we failed before reading the entire message, discard any remaining
// bytes before reading the next
while (!expect_continue && !parser.is_done()) {
static std::array<char, 1024> discard_buffer;
auto& body = parser.get().body();
body.size = discard_buffer.size();
body.data = discard_buffer.data();
timeout.start();
http::async_read_some(stream, buffer, parser, yield[ec]);
timeout.cancel();
if (ec == http::error::need_buffer) {
continue;
}
if (ec == boost::asio::error::connection_reset) {
return;
}
if (ec) {
ldout(cct, 5) << "failed to discard unread message: "
<< ec.message() << dendl;
return;
}
}
}
}
// timeout support requires that connections are reference-counted, because the
// timeout_handler can outlive the coroutine
struct Connection : boost::intrusive::list_base_hook<>,
boost::intrusive_ref_counter<Connection>
{
tcp_socket socket;
parse_buffer buffer;
explicit Connection(tcp_socket&& socket) noexcept
: socket(std::move(socket)) {}
void close(boost::system::error_code& ec) {
socket.close(ec);
}
tcp_socket& get_socket() { return socket; }
};
class ConnectionList {
using List = boost::intrusive::list<Connection>;
List connections;
std::mutex mutex;
void remove(Connection& c) {
std::lock_guard lock{mutex};
if (c.is_linked()) {
connections.erase(List::s_iterator_to(c));
}
}
public:
class Guard {
ConnectionList *list;
Connection *conn;
public:
Guard(ConnectionList *list, Connection *conn) : list(list), conn(conn) {}
~Guard() { list->remove(*conn); }
};
[[nodiscard]] Guard add(Connection& conn) {
std::lock_guard lock{mutex};
connections.push_back(conn);
return Guard{this, &conn};
}
void close(boost::system::error_code& ec) {
std::lock_guard lock{mutex};
for (auto& conn : connections) {
conn.socket.close(ec);
}
connections.clear();
}
};
namespace dmc = rgw::dmclock;
class AsioFrontend {
RGWProcessEnv& env;
RGWFrontendConfig* conf;
boost::asio::io_context context;
std::string uri_prefix;
ceph::timespan request_timeout = std::chrono::milliseconds(REQUEST_TIMEOUT);
size_t header_limit = 16384;
#ifdef WITH_RADOSGW_BEAST_OPENSSL
boost::optional<ssl::context> ssl_context;
int get_config_key_val(string name,
const string& type,
bufferlist *pbl);
int ssl_set_private_key(const string& name, bool is_ssl_cert);
int ssl_set_certificate_chain(const string& name);
int init_ssl();
#endif
SharedMutex pause_mutex;
std::unique_ptr<rgw::dmclock::Scheduler> scheduler;
struct Listener {
tcp::endpoint endpoint;
tcp::acceptor acceptor;
tcp_socket socket;
bool use_ssl = false;
bool use_nodelay = false;
explicit Listener(boost::asio::io_context& context)
: acceptor(context), socket(context) {}
};
std::vector<Listener> listeners;
ConnectionList connections;
// work guard to keep run() threads busy while listeners are paused
using Executor = boost::asio::io_context::executor_type;
std::optional<boost::asio::executor_work_guard<Executor>> work;
std::vector<std::thread> threads;
std::atomic<bool> going_down{false};
CephContext* ctx() const { return env.driver->ctx(); }
std::optional<dmc::ClientCounters> client_counters;
std::unique_ptr<dmc::ClientConfig> client_config;
void accept(Listener& listener, boost::system::error_code ec);
public:
AsioFrontend(RGWProcessEnv& env, RGWFrontendConfig* conf,
dmc::SchedulerCtx& sched_ctx)
: env(env), conf(conf), pause_mutex(context.get_executor())
{
auto sched_t = dmc::get_scheduler_t(ctx());
switch(sched_t){
case dmc::scheduler_t::dmclock:
scheduler.reset(new dmc::AsyncScheduler(ctx(),
context,
std::ref(sched_ctx.get_dmc_client_counters()),
sched_ctx.get_dmc_client_config(),
*sched_ctx.get_dmc_client_config(),
dmc::AtLimit::Reject));
break;
case dmc::scheduler_t::none:
lderr(ctx()) << "Got invalid scheduler type for beast, defaulting to throttler" << dendl;
[[fallthrough]];
case dmc::scheduler_t::throttler:
scheduler.reset(new dmc::SimpleThrottler(ctx()));
}
}
int init();
int run();
void stop();
void join();
void pause();
void unpause();
};
unsigned short parse_port(const char *input, boost::system::error_code& ec)
{
char *end = nullptr;
auto port = std::strtoul(input, &end, 10);
if (port > std::numeric_limits<unsigned short>::max()) {
ec.assign(ERANGE, boost::system::system_category());
} else if (port == 0 && end == input) {
ec.assign(EINVAL, boost::system::system_category());
}
return port;
}
tcp::endpoint parse_endpoint(boost::asio::string_view input,
unsigned short default_port,
boost::system::error_code& ec)
{
tcp::endpoint endpoint;
if (input.empty()) {
ec = boost::asio::error::invalid_argument;
return endpoint;
}
if (input[0] == '[') { // ipv6
const size_t addr_begin = 1;
const size_t addr_end = input.find(']');
if (addr_end == input.npos) { // no matching ]
ec = boost::asio::error::invalid_argument;
return endpoint;
}
if (addr_end + 1 < input.size()) {
// :port must must follow [ipv6]
if (input[addr_end + 1] != ':') {
ec = boost::asio::error::invalid_argument;
return endpoint;
} else {
auto port_str = input.substr(addr_end + 2);
endpoint.port(parse_port(port_str.data(), ec));
}
} else {
endpoint.port(default_port);
}
auto addr = input.substr(addr_begin, addr_end - addr_begin);
endpoint.address(boost::asio::ip::make_address_v6(addr, ec));
} else { // ipv4
auto colon = input.find(':');
if (colon != input.npos) {
auto port_str = input.substr(colon + 1);
endpoint.port(parse_port(port_str.data(), ec));
if (ec) {
return endpoint;
}
} else {
endpoint.port(default_port);
}
auto addr = input.substr(0, colon);
endpoint.address(boost::asio::ip::make_address_v4(addr, ec));
}
return endpoint;
}
static int drop_privileges(CephContext *ctx)
{
uid_t uid = ctx->get_set_uid();
gid_t gid = ctx->get_set_gid();
std::string uid_string = ctx->get_set_uid_string();
std::string gid_string = ctx->get_set_gid_string();
if (gid && setgid(gid) != 0) {
int err = errno;
ldout(ctx, -1) << "unable to setgid " << gid << ": " << cpp_strerror(err) << dendl;
return -err;
}
if (uid && setuid(uid) != 0) {
int err = errno;
ldout(ctx, -1) << "unable to setuid " << uid << ": " << cpp_strerror(err) << dendl;
return -err;
}
if (uid && gid) {
ldout(ctx, 0) << "set uid:gid to " << uid << ":" << gid
<< " (" << uid_string << ":" << gid_string << ")" << dendl;
}
return 0;
}
int AsioFrontend::init()
{
boost::system::error_code ec;
auto& config = conf->get_config_map();
if (auto i = config.find("prefix"); i != config.end()) {
uri_prefix = i->second;
}
// Setting global timeout
auto timeout = config.find("request_timeout_ms");
if (timeout != config.end()) {
auto timeout_number = ceph::parse<uint64_t>(timeout->second);
if (timeout_number) {
request_timeout = std::chrono::milliseconds(*timeout_number);
} else {
lderr(ctx()) << "WARNING: invalid value for request_timeout_ms: "
<< timeout->second << " setting it to the default value: "
<< REQUEST_TIMEOUT << dendl;
}
}
auto max_header_size = config.find("max_header_size");
if (max_header_size != config.end()) {
auto limit = ceph::parse<uint64_t>(max_header_size->second);
if (!limit) {
lderr(ctx()) << "WARNING: invalid value for max_header_size: "
<< max_header_size->second << ", using the default value: "
<< header_limit << dendl;
} else if (*limit > parse_buffer_size) { // can't exceed parse buffer size
header_limit = parse_buffer_size;
lderr(ctx()) << "WARNING: max_header_size " << max_header_size->second
<< " capped at maximum value " << header_limit << dendl;
} else {
header_limit = *limit;
}
}
#ifdef WITH_RADOSGW_BEAST_OPENSSL
int r = init_ssl();
if (r < 0) {
return r;
}
#endif
// parse endpoints
auto ports = config.equal_range("port");
for (auto i = ports.first; i != ports.second; ++i) {
auto port = parse_port(i->second.c_str(), ec);
if (ec) {
lderr(ctx()) << "failed to parse port=" << i->second << dendl;
return -ec.value();
}
listeners.emplace_back(context);
listeners.back().endpoint.port(port);
listeners.emplace_back(context);
listeners.back().endpoint = tcp::endpoint(tcp::v6(), port);
}
auto endpoints = config.equal_range("endpoint");
for (auto i = endpoints.first; i != endpoints.second; ++i) {
auto endpoint = parse_endpoint(i->second, 80, ec);
if (ec) {
lderr(ctx()) << "failed to parse endpoint=" << i->second << dendl;
return -ec.value();
}
listeners.emplace_back(context);
listeners.back().endpoint = endpoint;
}
// parse tcp nodelay
auto nodelay = config.find("tcp_nodelay");
if (nodelay != config.end()) {
for (auto& l : listeners) {
l.use_nodelay = (nodelay->second == "1");
}
}
bool socket_bound = false;
// start listeners
for (auto& l : listeners) {
l.acceptor.open(l.endpoint.protocol(), ec);
if (ec) {
if (ec == boost::asio::error::address_family_not_supported) {
ldout(ctx(), 0) << "WARNING: cannot open socket for endpoint=" << l.endpoint
<< ", " << ec.message() << dendl;
continue;
}
lderr(ctx()) << "failed to open socket: " << ec.message() << dendl;
return -ec.value();
}
if (l.endpoint.protocol() == tcp::v6()) {
l.acceptor.set_option(boost::asio::ip::v6_only(true), ec);
if (ec) {
lderr(ctx()) << "failed to set v6_only socket option: "
<< ec.message() << dendl;
return -ec.value();
}
}
l.acceptor.set_option(tcp::acceptor::reuse_address(true));
l.acceptor.bind(l.endpoint, ec);
if (ec) {
lderr(ctx()) << "failed to bind address " << l.endpoint
<< ": " << ec.message() << dendl;
return -ec.value();
}
auto it = config.find("max_connection_backlog");
auto max_connection_backlog = boost::asio::socket_base::max_listen_connections;
if (it != config.end()) {
string err;
max_connection_backlog = strict_strtol(it->second.c_str(), 10, &err);
if (!err.empty()) {
ldout(ctx(), 0) << "WARNING: invalid value for max_connection_backlog=" << it->second << dendl;
max_connection_backlog = boost::asio::socket_base::max_listen_connections;
}
}
l.acceptor.listen(max_connection_backlog);
l.acceptor.async_accept(l.socket,
[this, &l] (boost::system::error_code ec) {
accept(l, ec);
});
ldout(ctx(), 4) << "frontend listening on " << l.endpoint << dendl;
socket_bound = true;
}
if (!socket_bound) {
lderr(ctx()) << "Unable to listen at any endpoints" << dendl;
return -EINVAL;
}
return drop_privileges(ctx());
}
#ifdef WITH_RADOSGW_BEAST_OPENSSL
static string config_val_prefix = "config://";
namespace {
class ExpandMetaVar {
map<string, string> meta_map;
public:
ExpandMetaVar(rgw::sal::Zone* zone_svc) {
meta_map["realm"] = zone_svc->get_realm_name();
meta_map["realm_id"] = zone_svc->get_realm_id();
meta_map["zonegroup"] = zone_svc->get_zonegroup().get_name();
meta_map["zonegroup_id"] = zone_svc->get_zonegroup().get_id();
meta_map["zone"] = zone_svc->get_name();
meta_map["zone_id"] = zone_svc->get_id();
}
string process_str(const string& in);
};
string ExpandMetaVar::process_str(const string& in)
{
if (meta_map.empty()) {
return in;
}
auto pos = in.find('$');
if (pos == std::string::npos) {
return in;
}
string out;
decltype(pos) last_pos = 0;
while (pos != std::string::npos) {
if (pos > last_pos) {
out += in.substr(last_pos, pos - last_pos);
}
string var;
const char *valid_chars = "abcdefghijklmnopqrstuvwxyz_";
size_t endpos = 0;
if (in[pos+1] == '{') {
// ...${foo_bar}...
endpos = in.find_first_not_of(valid_chars, pos + 2);
if (endpos != std::string::npos &&
in[endpos] == '}') {
var = in.substr(pos + 2, endpos - pos - 2);
endpos++;
}
} else {
// ...$foo...
endpos = in.find_first_not_of(valid_chars, pos + 1);
if (endpos != std::string::npos)
var = in.substr(pos + 1, endpos - pos - 1);
else
var = in.substr(pos + 1);
}
string var_source = in.substr(pos, endpos - pos);
last_pos = endpos;
auto iter = meta_map.find(var);
if (iter != meta_map.end()) {
out += iter->second;
} else {
out += var_source;
}
pos = in.find('$', last_pos);
}
if (last_pos != std::string::npos) {
out += in.substr(last_pos);
}
return out;
}
} /* anonymous namespace */
int AsioFrontend::get_config_key_val(string name,
const string& type,
bufferlist *pbl)
{
if (name.empty()) {
lderr(ctx()) << "bad " << type << " config value" << dendl;
return -EINVAL;
}
int r = env.driver->get_config_key_val(name, pbl);
if (r < 0) {
lderr(ctx()) << type << " was not found: " << name << dendl;
return r;
}
return 0;
}
int AsioFrontend::ssl_set_private_key(const string& name, bool is_ssl_certificate)
{
boost::system::error_code ec;
if (!boost::algorithm::starts_with(name, config_val_prefix)) {
ssl_context->use_private_key_file(name, ssl::context::pem, ec);
} else {
bufferlist bl;
int r = get_config_key_val(name.substr(config_val_prefix.size()),
"ssl_private_key",
&bl);
if (r < 0) {
return r;
}
ssl_context->use_private_key(boost::asio::buffer(bl.c_str(), bl.length()),
ssl::context::pem, ec);
}
if (ec) {
if (!is_ssl_certificate) {
lderr(ctx()) << "failed to add ssl_private_key=" << name
<< ": " << ec.message() << dendl;
} else {
lderr(ctx()) << "failed to use ssl_certificate=" << name
<< " as a private key: " << ec.message() << dendl;
}
return -ec.value();
}
return 0;
}
int AsioFrontend::ssl_set_certificate_chain(const string& name)
{
boost::system::error_code ec;
if (!boost::algorithm::starts_with(name, config_val_prefix)) {
ssl_context->use_certificate_chain_file(name, ec);
} else {
bufferlist bl;
int r = get_config_key_val(name.substr(config_val_prefix.size()),
"ssl_certificate",
&bl);
if (r < 0) {
return r;
}
ssl_context->use_certificate_chain(boost::asio::buffer(bl.c_str(), bl.length()),
ec);
}
if (ec) {
lderr(ctx()) << "failed to use ssl_certificate=" << name
<< ": " << ec.message() << dendl;
return -ec.value();
}
return 0;
}
int AsioFrontend::init_ssl()
{
boost::system::error_code ec;
auto& config = conf->get_config_map();
// ssl configuration
std::optional<string> cert = conf->get_val("ssl_certificate");
if (cert) {
// only initialize the ssl context if it's going to be used
ssl_context = boost::in_place(ssl::context::tls);
}
std::optional<string> key = conf->get_val("ssl_private_key");
bool have_cert = false;
if (key && !cert) {
lderr(ctx()) << "no ssl_certificate configured for ssl_private_key" << dendl;
return -EINVAL;
}
std::optional<string> options = conf->get_val("ssl_options");
if (options) {
if (!cert) {
lderr(ctx()) << "no ssl_certificate configured for ssl_options" << dendl;
return -EINVAL;
}
} else if (cert) {
options = "no_sslv2:no_sslv3:no_tlsv1:no_tlsv1_1";
}
if (options) {
for (auto &option : ceph::split(*options, ":")) {
if (option == "default_workarounds") {
ssl_context->set_options(ssl::context::default_workarounds);
} else if (option == "no_compression") {
ssl_context->set_options(ssl::context::no_compression);
} else if (option == "no_sslv2") {
ssl_context->set_options(ssl::context::no_sslv2);
} else if (option == "no_sslv3") {
ssl_context->set_options(ssl::context::no_sslv3);
} else if (option == "no_tlsv1") {
ssl_context->set_options(ssl::context::no_tlsv1);
} else if (option == "no_tlsv1_1") {
ssl_context->set_options(ssl::context::no_tlsv1_1);
} else if (option == "no_tlsv1_2") {
ssl_context->set_options(ssl::context::no_tlsv1_2);
} else if (option == "single_dh_use") {
ssl_context->set_options(ssl::context::single_dh_use);
} else {
lderr(ctx()) << "ignoring unknown ssl option '" << option << "'" << dendl;
}
}
}
std::optional<string> ciphers = conf->get_val("ssl_ciphers");
if (ciphers) {
if (!cert) {
lderr(ctx()) << "no ssl_certificate configured for ssl_ciphers" << dendl;
return -EINVAL;
}
int r = SSL_CTX_set_cipher_list(ssl_context->native_handle(),
ciphers->c_str());
if (r == 0) {
lderr(ctx()) << "no cipher could be selected from ssl_ciphers: "
<< *ciphers << dendl;
return -EINVAL;
}
}
auto ports = config.equal_range("ssl_port");
auto endpoints = config.equal_range("ssl_endpoint");
/*
* don't try to config certificate if frontend isn't configured for ssl
*/
if (ports.first == ports.second &&
endpoints.first == endpoints.second) {
return 0;
}
bool key_is_cert = false;
if (cert) {
if (!key) {
key = cert;
key_is_cert = true;
}
ExpandMetaVar emv(env.driver->get_zone());
cert = emv.process_str(*cert);
key = emv.process_str(*key);
int r = ssl_set_private_key(*key, key_is_cert);
bool have_private_key = (r >= 0);
if (r < 0) {
if (!key_is_cert) {
r = ssl_set_private_key(*cert, true);
have_private_key = (r >= 0);
}
}
if (have_private_key) {
int r = ssl_set_certificate_chain(*cert);
have_cert = (r >= 0);
}
}
// parse ssl endpoints
for (auto i = ports.first; i != ports.second; ++i) {
if (!have_cert) {
lderr(ctx()) << "no ssl_certificate configured for ssl_port" << dendl;
return -EINVAL;
}
auto port = parse_port(i->second.c_str(), ec);
if (ec) {
lderr(ctx()) << "failed to parse ssl_port=" << i->second << dendl;
return -ec.value();
}
listeners.emplace_back(context);
listeners.back().endpoint.port(port);
listeners.back().use_ssl = true;
listeners.emplace_back(context);
listeners.back().endpoint = tcp::endpoint(tcp::v6(), port);
listeners.back().use_ssl = true;
}
for (auto i = endpoints.first; i != endpoints.second; ++i) {
if (!have_cert) {
lderr(ctx()) << "no ssl_certificate configured for ssl_endpoint" << dendl;
return -EINVAL;
}
auto endpoint = parse_endpoint(i->second, 443, ec);
if (ec) {
lderr(ctx()) << "failed to parse ssl_endpoint=" << i->second << dendl;
return -ec.value();
}
listeners.emplace_back(context);
listeners.back().endpoint = endpoint;
listeners.back().use_ssl = true;
}
return 0;
}
#endif // WITH_RADOSGW_BEAST_OPENSSL
void AsioFrontend::accept(Listener& l, boost::system::error_code ec)
{
if (!l.acceptor.is_open()) {
return;
} else if (ec == boost::asio::error::operation_aborted) {
return;
} else if (ec) {
ldout(ctx(), 1) << "accept failed: " << ec.message() << dendl;
return;
}
auto stream = std::move(l.socket);
stream.set_option(tcp::no_delay(l.use_nodelay), ec);
l.acceptor.async_accept(l.socket,
[this, &l] (boost::system::error_code ec) {
accept(l, ec);
});
// spawn a coroutine to handle the connection
#ifdef WITH_RADOSGW_BEAST_OPENSSL
if (l.use_ssl) {
spawn::spawn(context,
[this, s=std::move(stream)] (yield_context yield) mutable {
auto conn = boost::intrusive_ptr{new Connection(std::move(s))};
auto c = connections.add(*conn);
// wrap the tcp stream in an ssl stream
boost::asio::ssl::stream<tcp_socket&> stream{conn->socket, *ssl_context};
auto timeout = timeout_timer{context.get_executor(), request_timeout, conn};
// do ssl handshake
boost::system::error_code ec;
timeout.start();
auto bytes = stream.async_handshake(ssl::stream_base::server,
conn->buffer.data(), yield[ec]);
timeout.cancel();
if (ec) {
ldout(ctx(), 1) << "ssl handshake failed: " << ec.message() << dendl;
return;
}
conn->buffer.consume(bytes);
handle_connection(context, env, stream, timeout, header_limit,
conn->buffer, true, pause_mutex, scheduler.get(),
uri_prefix, ec, yield);
if (!ec) {
// ssl shutdown (ignoring errors)
stream.async_shutdown(yield[ec]);
}
conn->socket.shutdown(tcp::socket::shutdown_both, ec);
}, make_stack_allocator());
} else {
#else
{
#endif // WITH_RADOSGW_BEAST_OPENSSL
spawn::spawn(context,
[this, s=std::move(stream)] (yield_context yield) mutable {
auto conn = boost::intrusive_ptr{new Connection(std::move(s))};
auto c = connections.add(*conn);
auto timeout = timeout_timer{context.get_executor(), request_timeout, conn};
boost::system::error_code ec;
handle_connection(context, env, conn->socket, timeout, header_limit,
conn->buffer, false, pause_mutex, scheduler.get(),
uri_prefix, ec, yield);
conn->socket.shutdown(tcp_socket::shutdown_both, ec);
}, make_stack_allocator());
}
}
int AsioFrontend::run()
{
auto cct = ctx();
const int thread_count = cct->_conf->rgw_thread_pool_size;
threads.reserve(thread_count);
ldout(cct, 4) << "frontend spawning " << thread_count << " threads" << dendl;
// the worker threads call io_context::run(), which will return when there's
// no work left. hold a work guard to keep these threads going until join()
work.emplace(boost::asio::make_work_guard(context));
for (int i = 0; i < thread_count; i++) {
threads.emplace_back([this]() noexcept {
// request warnings on synchronous librados calls in this thread
is_asio_thread = true;
// Have uncaught exceptions kill the process and give a
// stacktrace, not be swallowed.
context.run();
});
}
return 0;
}
void AsioFrontend::stop()
{
ldout(ctx(), 4) << "frontend initiating shutdown..." << dendl;
going_down = true;
boost::system::error_code ec;
// close all listeners
for (auto& listener : listeners) {
listener.acceptor.close(ec);
}
// close all connections
connections.close(ec);
pause_mutex.cancel();
}
void AsioFrontend::join()
{
if (!going_down) {
stop();
}
work.reset();
ldout(ctx(), 4) << "frontend joining threads..." << dendl;
for (auto& thread : threads) {
thread.join();
}
ldout(ctx(), 4) << "frontend done" << dendl;
}
void AsioFrontend::pause()
{
ldout(ctx(), 4) << "frontend pausing connections..." << dendl;
// cancel pending calls to accept(), but don't close the sockets
boost::system::error_code ec;
for (auto& l : listeners) {
l.acceptor.cancel(ec);
}
// pause and wait for outstanding requests to complete
pause_mutex.lock(ec);
if (ec) {
ldout(ctx(), 1) << "frontend failed to pause: " << ec.message() << dendl;
} else {
ldout(ctx(), 4) << "frontend paused" << dendl;
}
}
void AsioFrontend::unpause()
{
// unpause to unblock connections
pause_mutex.unlock();
// start accepting connections again
for (auto& l : listeners) {
l.acceptor.async_accept(l.socket,
[this, &l] (boost::system::error_code ec) {
accept(l, ec);
});
}
ldout(ctx(), 4) << "frontend unpaused" << dendl;
}
} // anonymous namespace
class RGWAsioFrontend::Impl : public AsioFrontend {
public:
Impl(RGWProcessEnv& env, RGWFrontendConfig* conf,
rgw::dmclock::SchedulerCtx& sched_ctx)
: AsioFrontend(env, conf, sched_ctx) {}
};
RGWAsioFrontend::RGWAsioFrontend(RGWProcessEnv& env,
RGWFrontendConfig* conf,
rgw::dmclock::SchedulerCtx& sched_ctx)
: impl(new Impl(env, conf, sched_ctx))
{
}
RGWAsioFrontend::~RGWAsioFrontend() = default;
int RGWAsioFrontend::init()
{
return impl->init();
}
int RGWAsioFrontend::run()
{
return impl->run();
}
void RGWAsioFrontend::stop()
{
impl->stop();
}
void RGWAsioFrontend::join()
{
impl->join();
}
void RGWAsioFrontend::pause_for_new_config()
{
impl->pause();
}
void RGWAsioFrontend::unpause_with_new_config()
{
impl->unpause();
}
| 36,436 | 29.364167 | 103 |
cc
|
null |
ceph-main/src/rgw/rgw_asio_frontend.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#pragma once
#include <memory>
#include "rgw_frontend.h"
#define REQUEST_TIMEOUT 65000
class RGWAsioFrontend : public RGWFrontend {
class Impl;
std::unique_ptr<Impl> impl;
public:
RGWAsioFrontend(RGWProcessEnv& env, RGWFrontendConfig* conf,
rgw::dmclock::SchedulerCtx& sched_ctx);
~RGWAsioFrontend() override;
int init() override;
int run() override;
void stop() override;
void join() override;
void pause_for_new_config() override;
void unpause_with_new_config() override;
};
| 611 | 22.538462 | 70 |
h
|
null |
ceph-main/src/rgw/rgw_asio_frontend_timer.h
|
#pragma once
#include <boost/asio/basic_waitable_timer.hpp>
#include <boost/intrusive_ptr.hpp>
#include "common/ceph_time.h"
namespace rgw {
// a WaitHandler that closes a stream if the timeout expires
template <typename Stream>
struct timeout_handler {
// this handler may outlive the timer/stream, so we need to hold a reference
// to keep the stream alive
boost::intrusive_ptr<Stream> stream;
explicit timeout_handler(boost::intrusive_ptr<Stream> stream) noexcept
: stream(std::move(stream)) {}
void operator()(boost::system::error_code ec) {
if (!ec) { // wait was not canceled
boost::system::error_code ec_ignored;
stream->get_socket().cancel();
stream->get_socket().shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec_ignored);
}
}
};
// a timeout timer for stream operations
template <typename Clock, typename Executor, typename Stream>
class basic_timeout_timer {
public:
using clock_type = Clock;
using duration = typename clock_type::duration;
using executor_type = Executor;
explicit basic_timeout_timer(const executor_type& ex, duration dur,
boost::intrusive_ptr<Stream> stream)
: timer(ex), dur(dur), stream(std::move(stream))
{}
basic_timeout_timer(const basic_timeout_timer&) = delete;
basic_timeout_timer& operator=(const basic_timeout_timer&) = delete;
void start() {
if (dur.count() > 0) {
timer.expires_after(dur);
timer.async_wait(timeout_handler{stream});
}
}
void cancel() {
if (dur.count() > 0) {
timer.cancel();
}
}
private:
using Timer = boost::asio::basic_waitable_timer<clock_type,
boost::asio::wait_traits<clock_type>, executor_type>;
Timer timer;
duration dur;
boost::intrusive_ptr<Stream> stream;
};
} // namespace rgw
| 1,822 | 26.208955 | 93 |
h
|
null |
ceph-main/src/rgw/rgw_auth.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include <array>
#include <string>
#include "rgw_common.h"
#include "rgw_auth.h"
#include "rgw_quota.h"
#include "rgw_user.h"
#include "rgw_http_client.h"
#include "rgw_keystone.h"
#include "rgw_sal.h"
#include "rgw_log.h"
#include "include/str_list.h"
#define dout_context g_ceph_context
#define dout_subsys ceph_subsys_rgw
using namespace std;
namespace rgw {
namespace auth {
std::unique_ptr<rgw::auth::Identity>
transform_old_authinfo(CephContext* const cct,
const rgw_user& auth_id,
const int perm_mask,
const bool is_admin,
const uint32_t type)
{
/* This class is not intended for public use. Should be removed altogether
* with this function after moving all our APIs to the new authentication
* infrastructure. */
class DummyIdentityApplier : public rgw::auth::Identity {
CephContext* const cct;
/* For this particular case it's OK to use rgw_user structure to convey
* the identity info as this was the policy for doing that before the
* new auth. */
const rgw_user id;
const int perm_mask;
const bool is_admin;
const uint32_t type;
public:
DummyIdentityApplier(CephContext* const cct,
const rgw_user& auth_id,
const int perm_mask,
const bool is_admin,
const uint32_t type)
: cct(cct),
id(auth_id),
perm_mask(perm_mask),
is_admin(is_admin),
type(type) {
}
uint32_t get_perms_from_aclspec(const DoutPrefixProvider* dpp, const aclspec_t& aclspec) const override {
return rgw_perms_from_aclspec_default_strategy(id, aclspec, dpp);
}
bool is_admin_of(const rgw_user& acct_id) const override {
return is_admin;
}
bool is_owner_of(const rgw_user& acct_id) const override {
return id == acct_id;
}
bool is_identity(const idset_t& ids) const override {
for (auto& p : ids) {
if (p.is_wildcard()) {
return true;
} else if (p.is_tenant() && p.get_tenant() == id.tenant) {
return true;
} else if (p.is_user() &&
(p.get_tenant() == id.tenant) &&
(p.get_id() == id.id)) {
return true;
}
}
return false;
}
uint32_t get_perm_mask() const override {
return perm_mask;
}
uint32_t get_identity_type() const override {
return type;
}
string get_acct_name() const override {
return {};
}
string get_subuser() const override {
return {};
}
void to_str(std::ostream& out) const override {
out << "RGWDummyIdentityApplier(auth_id=" << id
<< ", perm_mask=" << perm_mask
<< ", is_admin=" << is_admin << ")";
}
};
return std::unique_ptr<rgw::auth::Identity>(
new DummyIdentityApplier(cct,
auth_id,
perm_mask,
is_admin,
type));
}
std::unique_ptr<rgw::auth::Identity>
transform_old_authinfo(const req_state* const s)
{
return transform_old_authinfo(s->cct,
s->user->get_id(),
s->perm_mask,
/* System user has admin permissions by default - it's supposed to pass
* through any security check. */
s->system_request,
s->user->get_type());
}
} /* namespace auth */
} /* namespace rgw */
uint32_t rgw_perms_from_aclspec_default_strategy(
const rgw_user& uid,
const rgw::auth::Identity::aclspec_t& aclspec,
const DoutPrefixProvider *dpp)
{
ldpp_dout(dpp, 5) << "Searching permissions for uid=" << uid << dendl;
const auto iter = aclspec.find(uid.to_str());
if (std::end(aclspec) != iter) {
ldpp_dout(dpp, 5) << "Found permission: " << iter->second << dendl;
return iter->second;
}
ldpp_dout(dpp, 5) << "Permissions for user not found" << dendl;
return 0;
}
static inline const std::string make_spec_item(const std::string& tenant,
const std::string& id)
{
return tenant + ":" + id;
}
static inline std::pair<bool, rgw::auth::Engine::result_t>
strategy_handle_rejected(rgw::auth::Engine::result_t&& engine_result,
const rgw::auth::Strategy::Control policy,
rgw::auth::Engine::result_t&& strategy_result)
{
using Control = rgw::auth::Strategy::Control;
switch (policy) {
case Control::REQUISITE:
/* Don't try next. */
return std::make_pair(false, std::move(engine_result));
case Control::SUFFICIENT:
/* Don't try next. */
return std::make_pair(false, std::move(engine_result));
case Control::FALLBACK:
/* Don't try next. */
return std::make_pair(false, std::move(strategy_result));
default:
/* Huh, memory corruption? */
ceph_abort();
}
}
static inline std::pair<bool, rgw::auth::Engine::result_t>
strategy_handle_denied(rgw::auth::Engine::result_t&& engine_result,
const rgw::auth::Strategy::Control policy,
rgw::auth::Engine::result_t&& strategy_result)
{
using Control = rgw::auth::Strategy::Control;
switch (policy) {
case Control::REQUISITE:
/* Don't try next. */
return std::make_pair(false, std::move(engine_result));
case Control::SUFFICIENT:
/* Just try next. */
return std::make_pair(true, std::move(engine_result));
case Control::FALLBACK:
return std::make_pair(true, std::move(strategy_result));
default:
/* Huh, memory corruption? */
ceph_abort();
}
}
static inline std::pair<bool, rgw::auth::Engine::result_t>
strategy_handle_granted(rgw::auth::Engine::result_t&& engine_result,
const rgw::auth::Strategy::Control policy,
rgw::auth::Engine::result_t&& strategy_result)
{
using Control = rgw::auth::Strategy::Control;
switch (policy) {
case Control::REQUISITE:
/* Try next. */
return std::make_pair(true, std::move(engine_result));
case Control::SUFFICIENT:
/* Don't try next. */
return std::make_pair(false, std::move(engine_result));
case Control::FALLBACK:
/* Don't try next. */
return std::make_pair(false, std::move(engine_result));
default:
/* Huh, memory corruption? */
ceph_abort();
}
}
rgw::auth::Engine::result_t
rgw::auth::Strategy::authenticate(const DoutPrefixProvider* dpp, const req_state* const s, optional_yield y) const
{
result_t strategy_result = result_t::deny();
for (const stack_item_t& kv : auth_stack) {
const rgw::auth::Engine& engine = kv.first;
const auto& policy = kv.second;
ldpp_dout(dpp, 20) << get_name() << ": trying " << engine.get_name() << dendl;
result_t engine_result = result_t::deny();
try {
engine_result = engine.authenticate(dpp, s, y);
} catch (const int err) {
engine_result = result_t::deny(err);
}
bool try_next = true;
switch (engine_result.get_status()) {
case result_t::Status::REJECTED: {
ldpp_dout(dpp, 20) << engine.get_name() << " rejected with reason="
<< engine_result.get_reason() << dendl;
std::tie(try_next, strategy_result) = \
strategy_handle_rejected(std::move(engine_result), policy,
std::move(strategy_result));
break;
}
case result_t::Status::DENIED: {
ldpp_dout(dpp, 20) << engine.get_name() << " denied with reason="
<< engine_result.get_reason() << dendl;
std::tie(try_next, strategy_result) = \
strategy_handle_denied(std::move(engine_result), policy,
std::move(strategy_result));
break;
}
case result_t::Status::GRANTED: {
ldpp_dout(dpp, 20) << engine.get_name() << " granted access" << dendl;
std::tie(try_next, strategy_result) = \
strategy_handle_granted(std::move(engine_result), policy,
std::move(strategy_result));
break;
}
default: {
ceph_abort();
}
}
if (! try_next) {
break;
}
}
return strategy_result;
}
int
rgw::auth::Strategy::apply(const DoutPrefixProvider *dpp, const rgw::auth::Strategy& auth_strategy,
req_state* const s, optional_yield y) noexcept
{
try {
auto result = auth_strategy.authenticate(dpp, s, y);
if (result.get_status() != decltype(result)::Status::GRANTED) {
/* Access denied is acknowledged by returning a std::unique_ptr with
* nullptr inside. */
ldpp_dout(dpp, 5) << "Failed the auth strategy, reason="
<< result.get_reason() << dendl;
return result.get_reason();
}
try {
rgw::auth::IdentityApplier::aplptr_t applier = result.get_applier();
rgw::auth::Completer::cmplptr_t completer = result.get_completer();
/* Account used by a given RGWOp is decoupled from identity employed
* in the authorization phase (RGWOp::verify_permissions). */
applier->load_acct_info(dpp, s->user->get_info());
s->perm_mask = applier->get_perm_mask();
/* This is the single place where we pass req_state as a pointer
* to non-const and thus its modification is allowed. In the time
* of writing only RGWTempURLEngine needed that feature. */
applier->modify_request_state(dpp, s);
if (completer) {
completer->modify_request_state(dpp, s);
}
s->auth.identity = std::move(applier);
s->auth.completer = std::move(completer);
return 0;
} catch (const int err) {
ldpp_dout(dpp, 5) << "applier throwed err=" << err << dendl;
return err;
} catch (const std::exception& e) {
ldpp_dout(dpp, 5) << "applier throwed unexpected err: " << e.what()
<< dendl;
return -EPERM;
}
} catch (const int err) {
ldpp_dout(dpp, 5) << "auth engine throwed err=" << err << dendl;
return err;
} catch (const std::exception& e) {
ldpp_dout(dpp, 5) << "auth engine throwed unexpected err: " << e.what()
<< dendl;
}
/* We never should be here. */
return -EPERM;
}
void
rgw::auth::Strategy::add_engine(const Control ctrl_flag,
const Engine& engine) noexcept
{
auth_stack.push_back(std::make_pair(std::cref(engine), ctrl_flag));
}
void rgw::auth::WebIdentityApplier::to_str(std::ostream& out) const
{
out << "rgw::auth::WebIdentityApplier(sub =" << sub
<< ", user_name=" << user_name
<< ", provider_id =" << iss << ")";
}
string rgw::auth::WebIdentityApplier::get_idp_url() const
{
string idp_url = this->iss;
idp_url = url_remove_prefix(idp_url);
return idp_url;
}
void rgw::auth::WebIdentityApplier::create_account(const DoutPrefixProvider* dpp,
const rgw_user& acct_user,
const string& display_name,
RGWUserInfo& user_info) const /* out */
{
std::unique_ptr<rgw::sal::User> user = driver->get_user(acct_user);
user->get_info().display_name = display_name;
user->get_info().type = TYPE_WEB;
user->get_info().max_buckets =
cct->_conf.get_val<int64_t>("rgw_user_max_buckets");
rgw_apply_default_bucket_quota(user->get_info().quota.bucket_quota, cct->_conf);
rgw_apply_default_user_quota(user->get_info().quota.user_quota, cct->_conf);
int ret = user->store_user(dpp, null_yield, true);
if (ret < 0) {
ldpp_dout(dpp, 0) << "ERROR: failed to store new user info: user="
<< user << " ret=" << ret << dendl;
throw ret;
}
user_info = user->get_info();
}
void rgw::auth::WebIdentityApplier::load_acct_info(const DoutPrefixProvider* dpp, RGWUserInfo& user_info) const {
rgw_user federated_user;
federated_user.id = this->sub;
federated_user.tenant = role_tenant;
federated_user.ns = "oidc";
std::unique_ptr<rgw::sal::User> user = driver->get_user(federated_user);
//Check in oidc namespace
if (user->load_user(dpp, null_yield) >= 0) {
/* Succeeded. */
user_info = user->get_info();
return;
}
user->clear_ns();
//Check for old users which wouldn't have been created in oidc namespace
if (user->load_user(dpp, null_yield) >= 0) {
/* Succeeded. */
user_info = user->get_info();
return;
}
//Check if user_id.buckets already exists, may have been from the time, when shadow users didnt exist
RGWStorageStats stats;
int ret = user->read_stats(dpp, null_yield, &stats);
if (ret < 0 && ret != -ENOENT) {
ldpp_dout(dpp, 0) << "ERROR: reading stats for the user returned error " << ret << dendl;
return;
}
if (ret == -ENOENT) { /* in case of ENOENT, which means user doesnt have buckets */
//In this case user will be created in oidc namespace
ldpp_dout(dpp, 5) << "NOTICE: incoming user has no buckets " << federated_user << dendl;
federated_user.ns = "oidc";
} else {
//User already has buckets associated, hence wont be created in oidc namespace.
ldpp_dout(dpp, 5) << "NOTICE: incoming user already has buckets associated " << federated_user << ", won't be created in oidc namespace"<< dendl;
federated_user.ns = "";
}
ldpp_dout(dpp, 0) << "NOTICE: couldn't map oidc federated user " << federated_user << dendl;
create_account(dpp, federated_user, this->user_name, user_info);
}
void rgw::auth::WebIdentityApplier::modify_request_state(const DoutPrefixProvider *dpp, req_state* s) const
{
s->info.args.append("sub", this->sub);
s->info.args.append("aud", this->aud);
s->info.args.append("provider_id", this->iss);
s->info.args.append("client_id", this->client_id);
string condition;
string idp_url = get_idp_url();
for (auto& claim : token_claims) {
if (claim.first == "aud") {
condition.clear();
condition = idp_url + ":app_id";
s->env.emplace(condition, claim.second);
}
condition.clear();
condition = idp_url + ":" + claim.first;
s->env.emplace(condition, claim.second);
}
if (principal_tags) {
constexpr size_t KEY_SIZE = 128, VAL_SIZE = 256;
std::set<std::pair<string, string>> p_tags = principal_tags.get();
for (auto& it : p_tags) {
string key = it.first;
string val = it.second;
if (key.find("aws:") == 0 || val.find("aws:") == 0) {
ldpp_dout(dpp, 0) << "ERROR: Tag/Value can't start with aws:, hence skipping it" << dendl;
continue;
}
if (key.size() > KEY_SIZE || val.size() > VAL_SIZE) {
ldpp_dout(dpp, 0) << "ERROR: Invalid tag/value size, hence skipping it" << dendl;
continue;
}
std::string p_key = "aws:PrincipalTag/";
p_key.append(key);
s->principal_tags.emplace_back(std::make_pair(p_key, val));
ldpp_dout(dpp, 10) << "Principal Tag Key: " << p_key << " Value: " << val << dendl;
std::string e_key = "aws:RequestTag/";
e_key.append(key);
s->env.emplace(e_key, val);
ldpp_dout(dpp, 10) << "RGW Env Tag Key: " << e_key << " Value: " << val << dendl;
s->env.emplace("aws:TagKeys", key);
ldpp_dout(dpp, 10) << "aws:TagKeys: " << key << dendl;
if (s->principal_tags.size() == 50) {
ldpp_dout(dpp, 0) << "ERROR: Number of tag/value pairs exceeding 50, hence skipping the rest" << dendl;
break;
}
}
}
if (role_tags) {
for (auto& it : role_tags.get()) {
std::string p_key = "aws:PrincipalTag/";
p_key.append(it.first);
s->principal_tags.emplace_back(std::make_pair(p_key, it.second));
ldpp_dout(dpp, 10) << "Principal Tag Key: " << p_key << " Value: " << it.second << dendl;
std::string e_key = "iam:ResourceTag/";
e_key.append(it.first);
s->env.emplace(e_key, it.second);
ldpp_dout(dpp, 10) << "RGW Env Tag Key: " << e_key << " Value: " << it.second << dendl;
}
}
}
bool rgw::auth::WebIdentityApplier::is_identity(const idset_t& ids) const
{
if (ids.size() > 1) {
return false;
}
for (auto id : ids) {
string idp_url = get_idp_url();
if (id.is_oidc_provider() && id.get_idp_url() == idp_url) {
return true;
}
}
return false;
}
const std::string rgw::auth::RemoteApplier::AuthInfo::NO_SUBUSER;
const std::string rgw::auth::RemoteApplier::AuthInfo::NO_ACCESS_KEY;
/* rgw::auth::RemoteAuthApplier */
uint32_t rgw::auth::RemoteApplier::get_perms_from_aclspec(const DoutPrefixProvider* dpp, const aclspec_t& aclspec) const
{
uint32_t perm = 0;
/* For backward compatibility with ACLOwner. */
perm |= rgw_perms_from_aclspec_default_strategy(info.acct_user,
aclspec, dpp);
/* We also need to cover cases where rgw_keystone_implicit_tenants
* was enabled. */
if (info.acct_user.tenant.empty()) {
const rgw_user tenanted_acct_user(info.acct_user.id, info.acct_user.id);
perm |= rgw_perms_from_aclspec_default_strategy(tenanted_acct_user,
aclspec, dpp);
}
/* Now it's a time for invoking additional strategy that was supplied by
* a specific auth engine. */
if (extra_acl_strategy) {
perm |= extra_acl_strategy(aclspec);
}
ldpp_dout(dpp, 20) << "from ACL got perm=" << perm << dendl;
return perm;
}
bool rgw::auth::RemoteApplier::is_admin_of(const rgw_user& uid) const
{
return info.is_admin;
}
bool rgw::auth::RemoteApplier::is_owner_of(const rgw_user& uid) const
{
if (info.acct_user.tenant.empty()) {
const rgw_user tenanted_acct_user(info.acct_user.id, info.acct_user.id);
if (tenanted_acct_user == uid) {
return true;
}
}
return info.acct_user == uid;
}
bool rgw::auth::RemoteApplier::is_identity(const idset_t& ids) const {
for (auto& id : ids) {
if (id.is_wildcard()) {
return true;
// We also need to cover cases where rgw_keystone_implicit_tenants
// was enabled. */
} else if (id.is_tenant() &&
(info.acct_user.tenant.empty() ?
info.acct_user.id :
info.acct_user.tenant) == id.get_tenant()) {
return true;
} else if (id.is_user() &&
info.acct_user.id == id.get_id() &&
(info.acct_user.tenant.empty() ?
info.acct_user.id :
info.acct_user.tenant) == id.get_tenant()) {
return true;
}
}
return false;
}
void rgw::auth::RemoteApplier::to_str(std::ostream& out) const
{
out << "rgw::auth::RemoteApplier(acct_user=" << info.acct_user
<< ", acct_name=" << info.acct_name
<< ", perm_mask=" << info.perm_mask
<< ", is_admin=" << info.is_admin << ")";
}
void rgw::auth::ImplicitTenants::recompute_value(const ConfigProxy& c)
{
std::string s = c.get_val<std::string>("rgw_keystone_implicit_tenants");
int v = 0;
if (boost::iequals(s, "both")
|| boost::iequals(s, "true")
|| boost::iequals(s, "1")) {
v = IMPLICIT_TENANTS_S3|IMPLICIT_TENANTS_SWIFT;
} else if (boost::iequals(s, "0")
|| boost::iequals(s, "none")
|| boost::iequals(s, "false")) {
v = 0;
} else if (boost::iequals(s, "s3")) {
v = IMPLICIT_TENANTS_S3;
} else if (boost::iequals(s, "swift")) {
v = IMPLICIT_TENANTS_SWIFT;
} else { /* "" (and anything else) */
v = IMPLICIT_TENANTS_BAD;
// assert(0);
}
saved = v;
}
const char **rgw::auth::ImplicitTenants::get_tracked_conf_keys() const
{
static const char *keys[] = {
"rgw_keystone_implicit_tenants",
nullptr };
return keys;
}
void rgw::auth::ImplicitTenants::handle_conf_change(const ConfigProxy& c,
const std::set <std::string> &changed)
{
if (changed.count("rgw_keystone_implicit_tenants")) {
recompute_value(c);
}
}
void rgw::auth::RemoteApplier::create_account(const DoutPrefixProvider* dpp,
const rgw_user& acct_user,
bool implicit_tenant,
RGWUserInfo& user_info) const /* out */
{
rgw_user new_acct_user = acct_user;
/* An upper layer may enforce creating new accounts within their own
* tenants. */
if (new_acct_user.tenant.empty() && implicit_tenant) {
new_acct_user.tenant = new_acct_user.id;
}
std::unique_ptr<rgw::sal::User> user = driver->get_user(new_acct_user);
user->get_info().display_name = info.acct_name;
if (info.acct_type) {
//ldap/keystone for s3 users
user->get_info().type = info.acct_type;
}
user->get_info().max_buckets =
cct->_conf.get_val<int64_t>("rgw_user_max_buckets");
rgw_apply_default_bucket_quota(user->get_info().quota.bucket_quota, cct->_conf);
rgw_apply_default_user_quota(user->get_info().quota.user_quota, cct->_conf);
user_info = user->get_info();
int ret = user->store_user(dpp, null_yield, true);
if (ret < 0) {
ldpp_dout(dpp, 0) << "ERROR: failed to store new user info: user="
<< user << " ret=" << ret << dendl;
throw ret;
}
}
void rgw::auth::RemoteApplier::write_ops_log_entry(rgw_log_entry& entry) const
{
entry.access_key_id = info.access_key_id;
entry.subuser = info.subuser;
}
/* TODO(rzarzynski): we need to handle display_name changes. */
void rgw::auth::RemoteApplier::load_acct_info(const DoutPrefixProvider* dpp, RGWUserInfo& user_info) const /* out */
{
/* It's supposed that RGWRemoteAuthApplier tries to load account info
* that belongs to the authenticated identity. Another policy may be
* applied by using a RGWThirdPartyAccountAuthApplier decorator. */
const rgw_user& acct_user = info.acct_user;
auto implicit_value = implicit_tenant_context.get_value();
bool implicit_tenant = implicit_value.implicit_tenants_for_(implicit_tenant_bit);
bool split_mode = implicit_value.is_split_mode();
std::unique_ptr<rgw::sal::User> user;
/* Normally, empty "tenant" field of acct_user means the authenticated
* identity has the legacy, global tenant. However, due to inclusion
* of multi-tenancy, we got some special compatibility kludge for remote
* backends like Keystone.
* If the global tenant is the requested one, we try the same tenant as
* the user name first. If that RGWUserInfo exists, we use it. This way,
* migrated OpenStack users can get their namespaced containers and nobody's
* the wiser.
* If that fails, we look up in the requested (possibly empty) tenant.
* If that fails too, we create the account within the global or separated
* namespace depending on rgw_keystone_implicit_tenants.
* For compatibility with previous versions of ceph, it is possible
* to enable implicit_tenants for only s3 or only swift.
* in this mode ("split_mode"), we must constrain the id lookups to
* only use the identifier space that would be used if the id were
* to be created. */
if (split_mode && !implicit_tenant)
; /* suppress lookup for id used by "other" protocol */
else if (acct_user.tenant.empty()) {
const rgw_user tenanted_uid(acct_user.id, acct_user.id);
user = driver->get_user(tenanted_uid);
if (user->load_user(dpp, null_yield) >= 0) {
/* Succeeded. */
user_info = user->get_info();
return;
}
}
user = driver->get_user(acct_user);
if (split_mode && implicit_tenant)
; /* suppress lookup for id used by "other" protocol */
else if (user->load_user(dpp, null_yield) >= 0) {
/* Succeeded. */
user_info = user->get_info();
return;
}
ldpp_dout(dpp, 0) << "NOTICE: couldn't map swift user " << acct_user << dendl;
create_account(dpp, acct_user, implicit_tenant, user_info);
/* Succeeded if we are here (create_account() hasn't throwed). */
}
/* rgw::auth::LocalApplier */
/* static declaration */
const std::string rgw::auth::LocalApplier::NO_SUBUSER;
const std::string rgw::auth::LocalApplier::NO_ACCESS_KEY;
uint32_t rgw::auth::LocalApplier::get_perms_from_aclspec(const DoutPrefixProvider* dpp, const aclspec_t& aclspec) const
{
return rgw_perms_from_aclspec_default_strategy(user_info.user_id, aclspec, dpp);
}
bool rgw::auth::LocalApplier::is_admin_of(const rgw_user& uid) const
{
return user_info.admin || user_info.system;
}
bool rgw::auth::LocalApplier::is_owner_of(const rgw_user& uid) const
{
return uid == user_info.user_id;
}
bool rgw::auth::LocalApplier::is_identity(const idset_t& ids) const {
for (auto& id : ids) {
if (id.is_wildcard()) {
return true;
} else if (id.is_tenant() &&
id.get_tenant() == user_info.user_id.tenant) {
return true;
} else if (id.is_user() &&
(id.get_tenant() == user_info.user_id.tenant)) {
if (id.get_id() == user_info.user_id.id) {
return true;
}
std::string wildcard_subuser = user_info.user_id.id;
wildcard_subuser.append(":*");
if (wildcard_subuser == id.get_id()) {
return true;
} else if (subuser != NO_SUBUSER) {
std::string user = user_info.user_id.id;
user.append(":");
user.append(subuser);
if (user == id.get_id()) {
return true;
}
}
}
}
return false;
}
void rgw::auth::LocalApplier::to_str(std::ostream& out) const {
out << "rgw::auth::LocalApplier(acct_user=" << user_info.user_id
<< ", acct_name=" << user_info.display_name
<< ", subuser=" << subuser
<< ", perm_mask=" << get_perm_mask()
<< ", is_admin=" << static_cast<bool>(user_info.admin) << ")";
}
uint32_t rgw::auth::LocalApplier::get_perm_mask(const std::string& subuser_name,
const RGWUserInfo &uinfo) const
{
if (! subuser_name.empty() && subuser_name != NO_SUBUSER) {
const auto iter = uinfo.subusers.find(subuser_name);
if (iter != std::end(uinfo.subusers)) {
return iter->second.perm_mask;
} else {
/* Subuser specified but not found. */
return RGW_PERM_NONE;
}
} else {
/* Due to backward compatibility. */
return RGW_PERM_FULL_CONTROL;
}
}
void rgw::auth::LocalApplier::load_acct_info(const DoutPrefixProvider* dpp, RGWUserInfo& user_info) const /* out */
{
/* Load the account that belongs to the authenticated identity. An extra call
* to RADOS may be safely skipped in this case. */
user_info = this->user_info;
}
void rgw::auth::LocalApplier::write_ops_log_entry(rgw_log_entry& entry) const
{
entry.access_key_id = access_key_id;
entry.subuser = subuser;
}
void rgw::auth::RoleApplier::to_str(std::ostream& out) const {
out << "rgw::auth::RoleApplier(role name =" << role.name;
for (auto& policy: role.role_policies) {
out << ", role policy =" << policy;
}
out << ", token policy =" << token_attrs.token_policy;
out << ")";
}
bool rgw::auth::RoleApplier::is_identity(const idset_t& ids) const {
for (auto& p : ids) {
if (p.is_wildcard()) {
return true;
} else if (p.is_role()) {
string name = p.get_id();
string tenant = p.get_tenant();
if (name == role.name && tenant == role.tenant) {
return true;
}
} else if (p.is_assumed_role()) {
string tenant = p.get_tenant();
string role_session = role.name + "/" + token_attrs.role_session_name; //role/role-session
if (role.tenant == tenant && role_session == p.get_role_session()) {
return true;
}
} else {
string id = p.get_id();
string tenant = p.get_tenant();
string oidc_id;
if (token_attrs.user_id.ns.empty()) {
oidc_id = token_attrs.user_id.id;
} else {
oidc_id = token_attrs.user_id.ns + "$" + token_attrs.user_id.id;
}
if (oidc_id == id && token_attrs.user_id.tenant == tenant) {
return true;
}
}
}
return false;
}
void rgw::auth::RoleApplier::load_acct_info(const DoutPrefixProvider* dpp, RGWUserInfo& user_info) const /* out */
{
/* Load the user id */
user_info.user_id = this->token_attrs.user_id;
}
void rgw::auth::RoleApplier::modify_request_state(const DoutPrefixProvider *dpp, req_state* s) const
{
for (auto it: role.role_policies) {
try {
bufferlist bl = bufferlist::static_from_string(it);
const rgw::IAM::Policy p(s->cct, role.tenant, bl, false);
s->iam_user_policies.push_back(std::move(p));
} catch (rgw::IAM::PolicyParseException& e) {
//Control shouldn't reach here as the policy has already been
//verified earlier
ldpp_dout(dpp, 20) << "failed to parse role policy: " << e.what() << dendl;
}
}
if (!this->token_attrs.token_policy.empty()) {
try {
string policy = this->token_attrs.token_policy;
bufferlist bl = bufferlist::static_from_string(policy);
const rgw::IAM::Policy p(s->cct, role.tenant, bl, false);
s->session_policies.push_back(std::move(p));
} catch (rgw::IAM::PolicyParseException& e) {
//Control shouldn't reach here as the policy has already been
//verified earlier
ldpp_dout(dpp, 20) << "failed to parse token policy: " << e.what() << dendl;
}
}
string condition = "aws:userid";
string value = role.id + ":" + token_attrs.role_session_name;
s->env.emplace(condition, value);
s->env.emplace("aws:TokenIssueTime", token_attrs.token_issued_at);
for (auto& m : token_attrs.principal_tags) {
s->env.emplace(m.first, m.second);
ldpp_dout(dpp, 10) << "Principal Tag Key: " << m.first << " Value: " << m.second << dendl;
std::size_t pos = m.first.find('/');
string key = m.first.substr(pos + 1);
s->env.emplace("aws:TagKeys", key);
ldpp_dout(dpp, 10) << "aws:TagKeys: " << key << dendl;
}
s->token_claims.emplace_back("sts");
s->token_claims.emplace_back("role_name:" + role.tenant + "$" + role.name);
s->token_claims.emplace_back("role_session:" + token_attrs.role_session_name);
for (auto& it : token_attrs.token_claims) {
s->token_claims.emplace_back(it);
}
}
rgw::auth::Engine::result_t
rgw::auth::AnonymousEngine::authenticate(const DoutPrefixProvider* dpp, const req_state* const s, optional_yield y) const
{
if (! is_applicable(s)) {
return result_t::deny(-EPERM);
} else {
RGWUserInfo user_info;
rgw_get_anon_user(user_info);
auto apl = \
apl_factory->create_apl_local(cct, s, user_info,
rgw::auth::LocalApplier::NO_SUBUSER,
std::nullopt, rgw::auth::LocalApplier::NO_ACCESS_KEY);
return result_t::grant(std::move(apl));
}
}
| 30,728 | 31.865241 | 149 |
cc
|
null |
ceph-main/src/rgw/rgw_auth.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#pragma once
#include <functional>
#include <optional>
#include <ostream>
#include <type_traits>
#include <system_error>
#include <utility>
#include "rgw_common.h"
#include "rgw_web_idp.h"
#define RGW_USER_ANON_ID "anonymous"
class RGWCtl;
struct rgw_log_entry;
struct req_state;
namespace rgw {
namespace auth {
using Exception = std::system_error;
/* Load information about identity that will be used by RGWOp to authorize
* any operation that comes from an authenticated user. */
class Identity {
public:
typedef std::map<std::string, int> aclspec_t;
using idset_t = boost::container::flat_set<Principal>;
virtual ~Identity() = default;
/* Translate the ACL provided in @aclspec into concrete permission set that
* can be used during the authorization phase (RGWOp::verify_permission).
* On error throws rgw::auth::Exception storing the reason.
*
* NOTE: an implementation is responsible for giving the real semantic to
* the items in @aclspec. That is, their meaning may depend on particular
* applier that is being used. */
virtual uint32_t get_perms_from_aclspec(const DoutPrefixProvider* dpp, const aclspec_t& aclspec) const = 0;
/* Verify whether a given identity *can be treated as* an admin of rgw_user
* (account in Swift's terminology) specified in @uid. On error throws
* rgw::auth::Exception storing the reason. */
virtual bool is_admin_of(const rgw_user& uid) const = 0;
/* Verify whether a given identity *is* the owner of the rgw_user (account
* in the Swift's terminology) specified in @uid. On internal error throws
* rgw::auth::Exception storing the reason. */
virtual bool is_owner_of(const rgw_user& uid) const = 0;
/* Return the permission mask that is used to narrow down the set of
* operations allowed for a given identity. This method reflects the idea
* of subuser tied to RGWUserInfo. On error throws rgw::auth::Exception
* with the reason. */
virtual uint32_t get_perm_mask() const = 0;
virtual bool is_anonymous() const {
/* If the identity owns the anonymous account (rgw_user), it's considered
* the anonymous identity. On error throws rgw::auth::Exception storing
* the reason. */
return is_owner_of(rgw_user(RGW_USER_ANON_ID));
}
virtual void to_str(std::ostream& out) const = 0;
/* Verify whether a given identity corresponds to an identity in the
provided set */
virtual bool is_identity(const idset_t& ids) const = 0;
/* Identity Type: RGW/ LDAP/ Keystone */
virtual uint32_t get_identity_type() const = 0;
/* Name of Account */
virtual std::string get_acct_name() const = 0;
/* Subuser of Account */
virtual std::string get_subuser() const = 0;
virtual std::string get_role_tenant() const { return ""; }
/* write any auth-specific fields that are safe to expose in the ops log */
virtual void write_ops_log_entry(rgw_log_entry& entry) const {};
};
inline std::ostream& operator<<(std::ostream& out,
const rgw::auth::Identity& id) {
id.to_str(out);
return out;
}
std::unique_ptr<rgw::auth::Identity>
transform_old_authinfo(CephContext* const cct,
const rgw_user& auth_id,
const int perm_mask,
const bool is_admin,
const uint32_t type);
std::unique_ptr<Identity> transform_old_authinfo(const req_state* const s);
/* Interface for classes applying changes to request state/RADOS store
* imposed by a particular rgw::auth::Engine.
*
* In contrast to rgw::auth::Engine, implementations of this interface
* are allowed to handle req_state or RGWUserCtl in the read-write manner.
*
* It's expected that most (if not all) of implementations will also
* conform to rgw::auth::Identity interface to provide authorization
* policy (ACLs, account's ownership and entitlement). */
class IdentityApplier : public Identity {
public:
typedef std::unique_ptr<IdentityApplier> aplptr_t;
virtual ~IdentityApplier() {};
/* Fill provided RGWUserInfo with information about the account that
* RGWOp will operate on. Errors are handled solely through exceptions.
*
* XXX: be aware that the "account" term refers to rgw_user. The naming
* is legacy. */
virtual void load_acct_info(const DoutPrefixProvider* dpp, RGWUserInfo& user_info) const = 0; /* out */
/* Apply any changes to request state. This method will be most useful for
* TempURL of Swift API. */
virtual void modify_request_state(const DoutPrefixProvider* dpp, req_state* s) const {} /* in/out */
};
/* Interface class for completing the two-step authentication process.
* Completer provides the second step - the complete() method that should
* be called after Engine::authenticate() but before *committing* results
* of an RGWOp (or sending a response in the case of non-mutating ops).
*
* The motivation driving the interface is to address those authentication
* schemas that require message integrity verification *without* in-memory
* data buffering. Typical examples are AWS Auth v4 and the auth mechanism
* of browser uploads facilities both in S3 and Swift APIs (see RGWPostObj).
* The workflow of request from the authentication point-of-view does look
* like following one:
* A. authenticate (Engine::authenticate),
* B. authorize (see RGWOp::verify_permissions),
* C. execute-prepare (init potential data modifications),
* D. authenticate-complete - (Completer::complete),
* E. execute-commit - commit the modifications from point C. */
class Completer {
public:
/* It's expected that Completers would tend to implement many interfaces
* and be used not only in req_state::auth::completer. Ref counting their
* instances would be helpful. */
typedef std::shared_ptr<Completer> cmplptr_t;
virtual ~Completer() = default;
/* Complete the authentication process. Return boolean indicating whether
* the completion succeeded. On error throws rgw::auth::Exception storing
* the reason. */
virtual bool complete() = 0;
/* Apply any changes to request state. The initial use case was injecting
* the AWSv4 filter over rgw::io::RestfulClient in req_state. */
virtual void modify_request_state(const DoutPrefixProvider* dpp, req_state* s) = 0; /* in/out */
};
/* Interface class for authentication backends (auth engines) in RadosGW.
*
* An engine is supposed only to authenticate (not authorize!) requests
* basing on their req_state and - if access has been granted - provide
* an upper layer with:
* - rgw::auth::IdentityApplier to commit all changes to the request state as
* well as to the RADOS store (creating an account, synchronizing
* user-related information with external databases and so on).
* - rgw::auth::Completer (optionally) to finish the authentication
* of the request. Typical use case is verifying message integrity
* in AWS Auth v4 and browser uploads (RGWPostObj).
*
* Both of them are supposed to be wrapped in Engine::AuthResult.
*
* The authentication process consists of two steps:
* - Engine::authenticate() which should be called before *initiating*
* any modifications to RADOS store that are related to an operation
* a client wants to perform (RGWOp::execute).
* - Completer::complete() supposed to be called, if completer has been
* returned, after the authenticate() step but before *committing*
* those modifications or sending a response (RGWOp::complete).
*
* An engine outlives both Applier and Completer. It's intended to live
* since RadosGW's initialization and handle multiple requests till
* a reconfiguration.
*
* Auth engine MUST NOT make any changes to req_state nor RADOS store.
* This is solely an Applier's responsibility!
*
* Separation between authentication and global state modification has
* been introduced because many auth engines are orthogonal to appliers
* and thus they can be decoupled. Additional motivation is to clearly
* distinguish all portions of code modifying data structures. */
class Engine {
public:
virtual ~Engine() = default;
class AuthResult {
struct rejection_mark_t {};
bool is_rejected = false;
int reason = 0;
std::pair<IdentityApplier::aplptr_t, Completer::cmplptr_t> result_pair;
explicit AuthResult(const int reason)
: reason(reason) {
}
AuthResult(rejection_mark_t&&, const int reason)
: is_rejected(true),
reason(reason) {
}
/* Allow only the reasonable combintations - returning just Completer
* without accompanying IdentityApplier is strictly prohibited! */
explicit AuthResult(IdentityApplier::aplptr_t&& applier)
: result_pair(std::move(applier), nullptr) {
}
AuthResult(IdentityApplier::aplptr_t&& applier,
Completer::cmplptr_t&& completer)
: result_pair(std::move(applier), std::move(completer)) {
}
public:
enum class Status {
/* Engine doesn't grant the access but also doesn't reject it. */
DENIED,
/* Engine successfully authenicated requester. */
GRANTED,
/* Engine strictly indicates that a request should be rejected
* without trying any further engine. */
REJECTED
};
Status get_status() const {
if (is_rejected) {
return Status::REJECTED;
} else if (! result_pair.first) {
return Status::DENIED;
} else {
return Status::GRANTED;
}
}
int get_reason() const {
return reason;
}
IdentityApplier::aplptr_t get_applier() {
return std::move(result_pair.first);
}
Completer::cmplptr_t&& get_completer() {
return std::move(result_pair.second);
}
static AuthResult reject(const int reason = -EACCES) {
return AuthResult(rejection_mark_t(), reason);
}
static AuthResult deny(const int reason = -EACCES) {
return AuthResult(reason);
}
static AuthResult grant(IdentityApplier::aplptr_t&& applier) {
return AuthResult(std::move(applier));
}
static AuthResult grant(IdentityApplier::aplptr_t&& applier,
Completer::cmplptr_t&& completer) {
return AuthResult(std::move(applier), std::move(completer));
}
};
using result_t = AuthResult;
/* Get name of the auth engine. */
virtual const char* get_name() const noexcept = 0;
/* Throwing method for identity verification. When the check is positive
* an implementation should return Engine::result_t containing:
* - a non-null pointer to an object conforming the Applier interface.
* Otherwise, the authentication is treated as failed.
* - a (potentially null) pointer to an object conforming the Completer
* interface.
*
* On error throws rgw::auth::Exception containing the reason. */
virtual result_t authenticate(const DoutPrefixProvider* dpp, const req_state* s, optional_yield y) const = 0;
};
/* Interface for extracting a token basing from data carried by req_state. */
class TokenExtractor {
public:
virtual ~TokenExtractor() = default;
virtual std::string get_token(const req_state* s) const = 0;
};
/* Abstract class for stacking sub-engines to expose them as a single
* Engine. It is responsible for ordering its sub-engines and managing
* fall-backs between them. Derivatee is supposed to encapsulate engine
* instances and add them using the add_engine() method in the order it
* wants to be tried during the call to authenticate().
*
* Each new Strategy should be exposed to StrategyRegistry for handling
* the dynamic reconfiguration. */
class Strategy : public Engine {
public:
/* Specifiers controlling what happens when an associated engine fails.
* The names and semantic has been borrowed mostly from libpam. */
enum class Control {
/* Failure of an engine injected with the REQUISITE specifier aborts
* the strategy's authentication process immediately. No other engine
* will be tried. */
REQUISITE,
/* Success of an engine injected with the SUFFICIENT specifier ends
* strategy's authentication process successfully. However, denying
* doesn't abort it -- there will be fall-back to following engine
* if the one that failed wasn't the last one. */
SUFFICIENT,
/* Like SUFFICIENT with the exception that on failure the reason code
* is not overridden. Instead, it's taken directly from the last tried
* non-FALLBACK engine. If there was no previous non-FALLBACK engine
* in a Strategy, then the result_t::deny(reason = -EACCES) is used. */
FALLBACK,
};
Engine::result_t authenticate(const DoutPrefixProvider* dpp, const req_state* s, optional_yield y) const override final;
bool is_empty() const {
return auth_stack.empty();
}
static int apply(const DoutPrefixProvider* dpp, const Strategy& auth_strategy, req_state* s, optional_yield y) noexcept;
private:
/* Using the reference wrapper here to explicitly point out we are not
* interested in storing nulls while preserving the dynamic polymorphism. */
using stack_item_t = std::pair<std::reference_wrapper<const Engine>,
Control>;
std::vector<stack_item_t> auth_stack;
protected:
void add_engine(Control ctrl_flag, const Engine& engine) noexcept;
};
/* A class aggregating the knowledge about all Strategies in RadosGW. It is
* responsible for handling the dynamic reconfiguration on e.g. realm update.
* The definition is in rgw/rgw_auth_registry.h,
*
* Each new Strategy should be exposed to it. */
class StrategyRegistry;
class WebIdentityApplier : public IdentityApplier {
std::string sub;
std::string iss;
std::string aud;
std::string client_id;
std::string user_name;
protected:
CephContext* const cct;
rgw::sal::Driver* driver;
std::string role_session;
std::string role_tenant;
std::unordered_multimap<std::string, std::string> token_claims;
boost::optional<std::multimap<std::string,std::string>> role_tags;
boost::optional<std::set<std::pair<std::string, std::string>>> principal_tags;
std::string get_idp_url() const;
void create_account(const DoutPrefixProvider* dpp,
const rgw_user& acct_user,
const std::string& display_name,
RGWUserInfo& user_info) const; /* out */
public:
WebIdentityApplier( CephContext* const cct,
rgw::sal::Driver* driver,
const std::string& role_session,
const std::string& role_tenant,
const std::unordered_multimap<std::string, std::string>& token_claims,
boost::optional<std::multimap<std::string,std::string>> role_tags,
boost::optional<std::set<std::pair<std::string, std::string>>> principal_tags)
: cct(cct),
driver(driver),
role_session(role_session),
role_tenant(role_tenant),
token_claims(token_claims),
role_tags(role_tags),
principal_tags(principal_tags) {
const auto& sub = token_claims.find("sub");
if(sub != token_claims.end()) {
this->sub = sub->second;
}
const auto& iss = token_claims.find("iss");
if(iss != token_claims.end()) {
this->iss = iss->second;
}
const auto& aud = token_claims.find("aud");
if(aud != token_claims.end()) {
this->aud = aud->second;
}
const auto& client_id = token_claims.find("client_id");
if(client_id != token_claims.end()) {
this->client_id = client_id->second;
} else {
const auto& azp = token_claims.find("azp");
if (azp != token_claims.end()) {
this->client_id = azp->second;
}
}
const auto& user_name = token_claims.find("username");
if(user_name != token_claims.end()) {
this->user_name = user_name->second;
} else {
const auto& given_username = token_claims.find("given_username");
if (given_username != token_claims.end()) {
this->user_name = given_username->second;
}
}
}
void modify_request_state(const DoutPrefixProvider *dpp, req_state* s) const override;
uint32_t get_perms_from_aclspec(const DoutPrefixProvider* dpp, const aclspec_t& aclspec) const override {
return RGW_PERM_NONE;
}
bool is_admin_of(const rgw_user& uid) const override {
return false;
}
bool is_owner_of(const rgw_user& uid) const override {
if (uid.id == this->sub && uid.tenant == role_tenant && uid.ns == "oidc") {
return true;
}
return false;
}
uint32_t get_perm_mask() const override {
return RGW_PERM_NONE;
}
void to_str(std::ostream& out) const override;
bool is_identity(const idset_t& ids) const override;
void load_acct_info(const DoutPrefixProvider* dpp, RGWUserInfo& user_info) const override;
uint32_t get_identity_type() const override {
return TYPE_WEB;
}
std::string get_acct_name() const override {
return this->user_name;
}
std::string get_subuser() const override {
return {};
}
struct Factory {
virtual ~Factory() {}
virtual aplptr_t create_apl_web_identity( CephContext* cct,
const req_state* s,
const std::string& role_session,
const std::string& role_tenant,
const std::unordered_multimap<std::string, std::string>& token,
boost::optional<std::multimap<std::string, std::string>>,
boost::optional<std::set<std::pair<std::string, std::string>>> principal_tags) const = 0;
};
};
class ImplicitTenants: public md_config_obs_t {
public:
enum implicit_tenant_flag_bits {IMPLICIT_TENANTS_SWIFT=1,
IMPLICIT_TENANTS_S3=2, IMPLICIT_TENANTS_BAD = -1, };
private:
int saved;
void recompute_value(const ConfigProxy& );
class ImplicitTenantValue {
friend class ImplicitTenants;
int v;
ImplicitTenantValue(int v) : v(v) {};
public:
bool inline is_split_mode()
{
assert(v != IMPLICIT_TENANTS_BAD);
return v == IMPLICIT_TENANTS_SWIFT || v == IMPLICIT_TENANTS_S3;
}
bool inline implicit_tenants_for_(const implicit_tenant_flag_bits bit)
{
assert(v != IMPLICIT_TENANTS_BAD);
return static_cast<bool>(v&bit);
}
};
public:
ImplicitTenants(const ConfigProxy& c) { recompute_value(c);}
ImplicitTenantValue get_value() const {
return ImplicitTenantValue(saved);
}
private:
const char** get_tracked_conf_keys() const override;
void handle_conf_change(const ConfigProxy& conf,
const std::set <std::string> &changed) override;
};
std::tuple<bool,bool> implicit_tenants_enabled_for_swift(CephContext * const cct);
std::tuple<bool,bool> implicit_tenants_enabled_for_s3(CephContext * const cct);
/* rgw::auth::RemoteApplier targets those authentication engines which don't
* need to ask the RADOS store while performing the auth process. Instead,
* they obtain credentials from an external source like Keystone or LDAP.
*
* As the authenticated user may not have an account yet, RGWRemoteAuthApplier
* must be able to create it basing on data passed by an auth engine. Those
* data will be used to fill RGWUserInfo structure. */
class RemoteApplier : public IdentityApplier {
public:
class AuthInfo {
friend class RemoteApplier;
protected:
const rgw_user acct_user;
const std::string acct_name;
const uint32_t perm_mask;
const bool is_admin;
const uint32_t acct_type;
const std::string access_key_id;
const std::string subuser;
public:
enum class acct_privilege_t {
IS_ADMIN_ACCT,
IS_PLAIN_ACCT
};
static const std::string NO_SUBUSER;
static const std::string NO_ACCESS_KEY;
AuthInfo(const rgw_user& acct_user,
const std::string& acct_name,
const uint32_t perm_mask,
const acct_privilege_t level,
const std::string access_key_id,
const std::string subuser,
const uint32_t acct_type=TYPE_NONE)
: acct_user(acct_user),
acct_name(acct_name),
perm_mask(perm_mask),
is_admin(acct_privilege_t::IS_ADMIN_ACCT == level),
acct_type(acct_type),
access_key_id(access_key_id),
subuser(subuser) {
}
};
using aclspec_t = rgw::auth::Identity::aclspec_t;
typedef std::function<uint32_t(const aclspec_t&)> acl_strategy_t;
protected:
CephContext* const cct;
/* Read-write is intensional here due to RGWUserInfo creation process. */
rgw::sal::Driver* driver;
/* Supplemental strategy for extracting permissions from ACLs. Its results
* will be combined (ORed) with a default strategy that is responsible for
* handling backward compatibility. */
const acl_strategy_t extra_acl_strategy;
const AuthInfo info;
const rgw::auth::ImplicitTenants& implicit_tenant_context;
const rgw::auth::ImplicitTenants::implicit_tenant_flag_bits implicit_tenant_bit;
virtual void create_account(const DoutPrefixProvider* dpp,
const rgw_user& acct_user,
bool implicit_tenant,
RGWUserInfo& user_info) const; /* out */
public:
RemoteApplier(CephContext* const cct,
rgw::sal::Driver* driver,
acl_strategy_t&& extra_acl_strategy,
const AuthInfo& info,
const rgw::auth::ImplicitTenants& implicit_tenant_context,
rgw::auth::ImplicitTenants::implicit_tenant_flag_bits implicit_tenant_bit)
: cct(cct),
driver(driver),
extra_acl_strategy(std::move(extra_acl_strategy)),
info(info),
implicit_tenant_context(implicit_tenant_context),
implicit_tenant_bit(implicit_tenant_bit) {
}
uint32_t get_perms_from_aclspec(const DoutPrefixProvider* dpp, const aclspec_t& aclspec) const override;
bool is_admin_of(const rgw_user& uid) const override;
bool is_owner_of(const rgw_user& uid) const override;
bool is_identity(const idset_t& ids) const override;
uint32_t get_perm_mask() const override { return info.perm_mask; }
void to_str(std::ostream& out) const override;
void load_acct_info(const DoutPrefixProvider* dpp, RGWUserInfo& user_info) const override; /* out */
void write_ops_log_entry(rgw_log_entry& entry) const override;
uint32_t get_identity_type() const override { return info.acct_type; }
std::string get_acct_name() const override { return info.acct_name; }
std::string get_subuser() const override { return {}; }
struct Factory {
virtual ~Factory() {}
/* Providing r-value reference here is required intensionally. Callee is
* thus disallowed to handle std::function in a way that could inhibit
* the move behaviour (like forgetting about std::moving a l-value). */
virtual aplptr_t create_apl_remote(CephContext* cct,
const req_state* s,
acl_strategy_t&& extra_acl_strategy,
const AuthInfo &info) const = 0;
};
};
/* rgw::auth::LocalApplier targets those auth engines that base on the data
* enclosed in the RGWUserInfo control structure. As a side effect of doing
* the authentication process, they must have it loaded. Leveraging this is
* a way to avoid unnecessary calls to underlying RADOS store. */
class LocalApplier : public IdentityApplier {
using aclspec_t = rgw::auth::Identity::aclspec_t;
protected:
const RGWUserInfo user_info;
const std::string subuser;
uint32_t perm_mask;
const std::string access_key_id;
uint32_t get_perm_mask(const std::string& subuser_name,
const RGWUserInfo &uinfo) const;
public:
static const std::string NO_SUBUSER;
static const std::string NO_ACCESS_KEY;
LocalApplier(CephContext* const cct,
const RGWUserInfo& user_info,
std::string subuser,
const std::optional<uint32_t>& perm_mask,
const std::string access_key_id)
: user_info(user_info),
subuser(std::move(subuser)),
perm_mask(perm_mask.value_or(RGW_PERM_INVALID)),
access_key_id(access_key_id) {
}
uint32_t get_perms_from_aclspec(const DoutPrefixProvider* dpp, const aclspec_t& aclspec) const override;
bool is_admin_of(const rgw_user& uid) const override;
bool is_owner_of(const rgw_user& uid) const override;
bool is_identity(const idset_t& ids) const override;
uint32_t get_perm_mask() const override {
if (this->perm_mask == RGW_PERM_INVALID) {
return get_perm_mask(subuser, user_info);
} else {
return this->perm_mask;
}
}
void to_str(std::ostream& out) const override;
void load_acct_info(const DoutPrefixProvider* dpp, RGWUserInfo& user_info) const override; /* out */
uint32_t get_identity_type() const override { return TYPE_RGW; }
std::string get_acct_name() const override { return {}; }
std::string get_subuser() const override { return subuser; }
void write_ops_log_entry(rgw_log_entry& entry) const override;
struct Factory {
virtual ~Factory() {}
virtual aplptr_t create_apl_local(CephContext* cct,
const req_state* s,
const RGWUserInfo& user_info,
const std::string& subuser,
const std::optional<uint32_t>& perm_mask,
const std::string& access_key_id) const = 0;
};
};
class RoleApplier : public IdentityApplier {
public:
struct Role {
std::string id;
std::string name;
std::string tenant;
std::vector<std::string> role_policies;
};
struct TokenAttrs {
rgw_user user_id;
std::string token_policy;
std::string role_session_name;
std::vector<std::string> token_claims;
std::string token_issued_at;
std::vector<std::pair<std::string, std::string>> principal_tags;
};
protected:
Role role;
TokenAttrs token_attrs;
public:
RoleApplier(CephContext* const cct,
const Role& role,
const TokenAttrs& token_attrs)
: role(role),
token_attrs(token_attrs) {}
uint32_t get_perms_from_aclspec(const DoutPrefixProvider* dpp, const aclspec_t& aclspec) const override {
return 0;
}
bool is_admin_of(const rgw_user& uid) const override {
return false;
}
bool is_owner_of(const rgw_user& uid) const override {
return (this->token_attrs.user_id.id == uid.id && this->token_attrs.user_id.tenant == uid.tenant && this->token_attrs.user_id.ns == uid.ns);
}
bool is_identity(const idset_t& ids) const override;
uint32_t get_perm_mask() const override {
return RGW_PERM_NONE;
}
void to_str(std::ostream& out) const override;
void load_acct_info(const DoutPrefixProvider* dpp, RGWUserInfo& user_info) const override; /* out */
uint32_t get_identity_type() const override { return TYPE_ROLE; }
std::string get_acct_name() const override { return {}; }
std::string get_subuser() const override { return {}; }
void modify_request_state(const DoutPrefixProvider* dpp, req_state* s) const override;
std::string get_role_tenant() const override { return role.tenant; }
struct Factory {
virtual ~Factory() {}
virtual aplptr_t create_apl_role( CephContext* cct,
const req_state* s,
const rgw::auth::RoleApplier::Role& role,
const rgw::auth::RoleApplier::TokenAttrs& token_attrs) const = 0;
};
};
/* The anonymous abstract engine. */
class AnonymousEngine : public Engine {
CephContext* const cct;
const rgw::auth::LocalApplier::Factory* const apl_factory;
public:
AnonymousEngine(CephContext* const cct,
const rgw::auth::LocalApplier::Factory* const apl_factory)
: cct(cct),
apl_factory(apl_factory) {
}
const char* get_name() const noexcept override {
return "rgw::auth::AnonymousEngine";
}
Engine::result_t authenticate(const DoutPrefixProvider* dpp, const req_state* s, optional_yield y) const override final;
protected:
virtual bool is_applicable(const req_state*) const noexcept {
return true;
}
};
} /* namespace auth */
} /* namespace rgw */
uint32_t rgw_perms_from_aclspec_default_strategy(
const rgw_user& uid,
const rgw::auth::Identity::aclspec_t& aclspec,
const DoutPrefixProvider *dpp);
| 28,787 | 35.348485 | 144 |
h
|
null |
ceph-main/src/rgw/rgw_auth_filters.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#pragma once
#include <type_traits>
#include <boost/logic/tribool.hpp>
#include <boost/optional.hpp>
#include "rgw_service.h"
#include "rgw_common.h"
#include "rgw_auth.h"
#include "rgw_user.h"
namespace rgw {
namespace auth {
/* Abstract decorator over any implementation of rgw::auth::IdentityApplier
* which could be provided both as a pointer-to-object or the object itself. */
template <typename DecorateeT>
class DecoratedApplier : public rgw::auth::IdentityApplier {
typedef typename std::remove_pointer<DecorateeT>::type DerefedDecorateeT;
static_assert(std::is_base_of<rgw::auth::IdentityApplier,
DerefedDecorateeT>::value,
"DecorateeT must be a subclass of rgw::auth::IdentityApplier");
DecorateeT decoratee;
/* There is an indirection layer over accessing decoratee to share the same
* code base between dynamic and static decorators. The difference is about
* what we store internally: pointer to a decorated object versus the whole
* object itself. Googling for "SFINAE" can help to understand the code. */
template <typename T = void,
typename std::enable_if<
std::is_pointer<DecorateeT>::value, T>::type* = nullptr>
DerefedDecorateeT& get_decoratee() {
return *decoratee;
}
template <typename T = void,
typename std::enable_if<
! std::is_pointer<DecorateeT>::value, T>::type* = nullptr>
DerefedDecorateeT& get_decoratee() {
return decoratee;
}
template <typename T = void,
typename std::enable_if<
std::is_pointer<DecorateeT>::value, T>::type* = nullptr>
const DerefedDecorateeT& get_decoratee() const {
return *decoratee;
}
template <typename T = void,
typename std::enable_if<
! std::is_pointer<DecorateeT>::value, T>::type* = nullptr>
const DerefedDecorateeT& get_decoratee() const {
return decoratee;
}
public:
explicit DecoratedApplier(DecorateeT&& decoratee)
: decoratee(std::forward<DecorateeT>(decoratee)) {
}
uint32_t get_perms_from_aclspec(const DoutPrefixProvider* dpp, const aclspec_t& aclspec) const override {
return get_decoratee().get_perms_from_aclspec(dpp, aclspec);
}
bool is_admin_of(const rgw_user& uid) const override {
return get_decoratee().is_admin_of(uid);
}
bool is_owner_of(const rgw_user& uid) const override {
return get_decoratee().is_owner_of(uid);
}
bool is_anonymous() const override {
return get_decoratee().is_anonymous();
}
uint32_t get_perm_mask() const override {
return get_decoratee().get_perm_mask();
}
uint32_t get_identity_type() const override {
return get_decoratee().get_identity_type();
}
std::string get_acct_name() const override {
return get_decoratee().get_acct_name();
}
std::string get_subuser() const override {
return get_decoratee().get_subuser();
}
bool is_identity(
const boost::container::flat_set<Principal>& ids) const override {
return get_decoratee().is_identity(ids);
}
void to_str(std::ostream& out) const override {
get_decoratee().to_str(out);
}
std::string get_role_tenant() const override { /* in/out */
return get_decoratee().get_role_tenant();
}
void load_acct_info(const DoutPrefixProvider* dpp, RGWUserInfo& user_info) const override { /* out */
return get_decoratee().load_acct_info(dpp, user_info);
}
void modify_request_state(const DoutPrefixProvider* dpp, req_state * s) const override { /* in/out */
return get_decoratee().modify_request_state(dpp, s);
}
void write_ops_log_entry(rgw_log_entry& entry) const override {
return get_decoratee().write_ops_log_entry(entry);
}
};
template <typename T>
class ThirdPartyAccountApplier : public DecoratedApplier<T> {
rgw::sal::Driver* driver;
const rgw_user acct_user_override;
public:
/* A value representing situations where there is no requested account
* override. In other words, acct_user_override will be equal to this
* constant where the request isn't a cross-tenant one. */
static const rgw_user UNKNOWN_ACCT;
template <typename U>
ThirdPartyAccountApplier(rgw::sal::Driver* driver,
const rgw_user &acct_user_override,
U&& decoratee)
: DecoratedApplier<T>(std::move(decoratee)),
driver(driver),
acct_user_override(acct_user_override) {
}
void to_str(std::ostream& out) const override;
void load_acct_info(const DoutPrefixProvider* dpp, RGWUserInfo& user_info) const override; /* out */
};
/* static declaration: UNKNOWN_ACCT will be an empty rgw_user that is a result
* of the default construction. */
template <typename T>
const rgw_user ThirdPartyAccountApplier<T>::UNKNOWN_ACCT;
template <typename T>
void ThirdPartyAccountApplier<T>::to_str(std::ostream& out) const
{
out << "rgw::auth::ThirdPartyAccountApplier(" + acct_user_override.to_str() + ")"
<< " -> ";
DecoratedApplier<T>::to_str(out);
}
template <typename T>
void ThirdPartyAccountApplier<T>::load_acct_info(const DoutPrefixProvider* dpp, RGWUserInfo& user_info) const
{
if (UNKNOWN_ACCT == acct_user_override) {
/* There is no override specified by the upper layer. This means that we'll
* load the account owned by the authenticated identity (aka auth_user). */
DecoratedApplier<T>::load_acct_info(dpp, user_info);
} else if (DecoratedApplier<T>::is_owner_of(acct_user_override)) {
/* The override has been specified but the account belongs to the authenticated
* identity. We may safely forward the call to a next stage. */
DecoratedApplier<T>::load_acct_info(dpp, user_info);
} else if (this->is_anonymous()) {
/* If the user was authed by the anonymous engine then scope the ANON user
* to the correct tenant */
if (acct_user_override.tenant.empty())
user_info.user_id = rgw_user(acct_user_override.id, RGW_USER_ANON_ID);
else
user_info.user_id = rgw_user(acct_user_override.tenant, RGW_USER_ANON_ID);
} else {
/* Compatibility mechanism for multi-tenancy. For more details refer to
* load_acct_info method of rgw::auth::RemoteApplier. */
std::unique_ptr<rgw::sal::User> user;
if (acct_user_override.tenant.empty()) {
const rgw_user tenanted_uid(acct_user_override.id, acct_user_override.id);
user = driver->get_user(tenanted_uid);
if (user->load_user(dpp, null_yield) >= 0) {
user_info = user->get_info();
/* Succeeded. */
return;
}
}
user = driver->get_user(acct_user_override);
const int ret = user->load_user(dpp, null_yield);
if (ret < 0) {
/* We aren't trying to recover from ENOENT here. It's supposed that creating
* someone else's account isn't a thing we want to support in this filter. */
if (ret == -ENOENT) {
throw -EACCES;
} else {
throw ret;
}
}
user_info = user->get_info();
}
}
template <typename T> static inline
ThirdPartyAccountApplier<T> add_3rdparty(rgw::sal::Driver* driver,
const rgw_user &acct_user_override,
T&& t) {
return ThirdPartyAccountApplier<T>(driver, acct_user_override,
std::forward<T>(t));
}
template <typename T>
class SysReqApplier : public DecoratedApplier<T> {
CephContext* const cct;
rgw::sal::Driver* driver;
const RGWHTTPArgs& args;
mutable boost::tribool is_system;
public:
template <typename U>
SysReqApplier(CephContext* const cct,
rgw::sal::Driver* driver,
const req_state* const s,
U&& decoratee)
: DecoratedApplier<T>(std::forward<T>(decoratee)),
cct(cct),
driver(driver),
args(s->info.args),
is_system(boost::logic::indeterminate) {
}
void to_str(std::ostream& out) const override;
void load_acct_info(const DoutPrefixProvider* dpp, RGWUserInfo& user_info) const override; /* out */
void modify_request_state(const DoutPrefixProvider* dpp, req_state* s) const override; /* in/out */
};
template <typename T>
void SysReqApplier<T>::to_str(std::ostream& out) const
{
out << "rgw::auth::SysReqApplier" << " -> ";
DecoratedApplier<T>::to_str(out);
}
template <typename T>
void SysReqApplier<T>::load_acct_info(const DoutPrefixProvider* dpp, RGWUserInfo& user_info) const
{
DecoratedApplier<T>::load_acct_info(dpp, user_info);
is_system = user_info.system;
if (is_system) {
//ldpp_dout(dpp, 20) << "system request" << dendl;
rgw_user effective_uid(args.sys_get(RGW_SYS_PARAM_PREFIX "uid"));
if (! effective_uid.empty()) {
/* We aren't writing directly to user_info for consistency and security
* reasons. rgw_get_user_info_by_uid doesn't trigger the operator=() but
* calls ::decode instead. */
std::unique_ptr<rgw::sal::User> user = driver->get_user(effective_uid);
if (user->load_user(dpp, null_yield) < 0) {
//ldpp_dout(dpp, 0) << "User lookup failed!" << dendl;
throw -EACCES;
}
user_info = user->get_info();
}
}
}
template <typename T>
void SysReqApplier<T>::modify_request_state(const DoutPrefixProvider* dpp, req_state* const s) const
{
if (boost::logic::indeterminate(is_system)) {
RGWUserInfo unused_info;
load_acct_info(dpp, unused_info);
}
if (is_system) {
s->info.args.set_system();
s->system_request = true;
}
DecoratedApplier<T>::modify_request_state(dpp, s);
}
template <typename T> static inline
SysReqApplier<T> add_sysreq(CephContext* const cct,
rgw::sal::Driver* driver,
const req_state* const s,
T&& t) {
return SysReqApplier<T>(cct, driver, s, std::forward<T>(t));
}
} /* namespace auth */
} /* namespace rgw */
| 9,946 | 31.828383 | 109 |
h
|
null |
ceph-main/src/rgw/rgw_auth_keystone.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include <string>
#include <vector>
#include <errno.h>
#include <fnmatch.h>
#include "rgw_b64.h"
#include "common/errno.h"
#include "common/ceph_json.h"
#include "include/types.h"
#include "include/str_list.h"
#include "rgw_common.h"
#include "rgw_keystone.h"
#include "rgw_auth_keystone.h"
#include "rgw_rest_s3.h"
#include "rgw_auth_s3.h"
#include "common/ceph_crypto.h"
#include "common/Cond.h"
#define dout_subsys ceph_subsys_rgw
using namespace std;
namespace rgw {
namespace auth {
namespace keystone {
bool
TokenEngine::is_applicable(const std::string& token) const noexcept
{
return ! token.empty() && ! cct->_conf->rgw_keystone_url.empty();
}
boost::optional<TokenEngine::token_envelope_t>
TokenEngine::get_from_keystone(const DoutPrefixProvider* dpp, const std::string& token, bool allow_expired) const
{
/* Unfortunately, we can't use the short form of "using" here. It's because
* we're aliasing a class' member, not namespace. */
using RGWValidateKeystoneToken = \
rgw::keystone::Service::RGWValidateKeystoneToken;
/* The container for plain response obtained from Keystone. It will be
* parsed token_envelope_t::parse method. */
ceph::bufferlist token_body_bl;
RGWValidateKeystoneToken validate(cct, "GET", "", &token_body_bl);
std::string url = config.get_endpoint_url();
if (url.empty()) {
throw -EINVAL;
}
const auto keystone_version = config.get_api_version();
if (keystone_version == rgw::keystone::ApiVersion::VER_2) {
url.append("v2.0/tokens/" + token);
} else if (keystone_version == rgw::keystone::ApiVersion::VER_3) {
url.append("v3/auth/tokens");
if (allow_expired) {
url.append("?allow_expired=1");
}
validate.append_header("X-Subject-Token", token);
}
std::string admin_token;
if (rgw::keystone::Service::get_admin_token(dpp, cct, token_cache, config,
admin_token) < 0) {
throw -EINVAL;
}
validate.append_header("X-Auth-Token", admin_token);
validate.set_send_length(0);
validate.set_url(url);
int ret = validate.process(null_yield);
if (ret < 0) {
throw ret;
}
/* NULL terminate for debug output. */
token_body_bl.append(static_cast<char>(0));
/* Detect Keystone rejection earlier than during the token parsing.
* Although failure at the parsing phase doesn't impose a threat,
* this allows to return proper error code (EACCESS instead of EINVAL
* or similar) and thus improves logging. */
if (validate.get_http_status() ==
/* Most likely: wrong admin credentials or admin token. */
RGWValidateKeystoneToken::HTTP_STATUS_UNAUTHORIZED ||
validate.get_http_status() ==
/* Most likely: non-existent token supplied by the client. */
RGWValidateKeystoneToken::HTTP_STATUS_NOTFOUND) {
ldpp_dout(dpp, 5) << "Failed keystone auth from " << url << " with "
<< validate.get_http_status() << dendl;
return boost::none;
}
ldpp_dout(dpp, 20) << "received response status=" << validate.get_http_status()
<< ", body=" << token_body_bl.c_str() << dendl;
TokenEngine::token_envelope_t token_body;
ret = token_body.parse(dpp, cct, token, token_body_bl, config.get_api_version());
if (ret < 0) {
throw ret;
}
return token_body;
}
TokenEngine::auth_info_t
TokenEngine::get_creds_info(const TokenEngine::token_envelope_t& token
) const noexcept
{
using acct_privilege_t = rgw::auth::RemoteApplier::AuthInfo::acct_privilege_t;
/* Check whether the user has an admin status. */
acct_privilege_t level = acct_privilege_t::IS_PLAIN_ACCT;
for (const auto& role : token.roles) {
if (role.is_admin && !role.is_reader) {
level = acct_privilege_t::IS_ADMIN_ACCT;
break;
}
}
return auth_info_t {
/* Suggested account name for the authenticated user. */
rgw_user(token.get_project_id()),
/* User's display name (aka real name). */
token.get_project_name(),
/* Keystone doesn't support RGW's subuser concept, so we cannot cut down
* the access rights through the perm_mask. At least at this layer. */
RGW_PERM_FULL_CONTROL,
level,
rgw::auth::RemoteApplier::AuthInfo::NO_ACCESS_KEY,
rgw::auth::RemoteApplier::AuthInfo::NO_SUBUSER,
TYPE_KEYSTONE
};
}
static inline const std::string
make_spec_item(const std::string& tenant, const std::string& id)
{
return tenant + ":" + id;
}
TokenEngine::acl_strategy_t
TokenEngine::get_acl_strategy(const TokenEngine::token_envelope_t& token) const
{
/* The primary identity is constructed upon UUIDs. */
const auto& tenant_uuid = token.get_project_id();
const auto& user_uuid = token.get_user_id();
/* For Keystone v2 an alias may be also used. */
const auto& tenant_name = token.get_project_name();
const auto& user_name = token.get_user_name();
/* Construct all possible combinations including Swift's wildcards. */
const std::array<std::string, 6> allowed_items = {
make_spec_item(tenant_uuid, user_uuid),
make_spec_item(tenant_name, user_name),
/* Wildcards. */
make_spec_item(tenant_uuid, "*"),
make_spec_item(tenant_name, "*"),
make_spec_item("*", user_uuid),
make_spec_item("*", user_name),
};
/* Lambda will obtain a copy of (not a reference to!) allowed_items. */
return [allowed_items, token_roles=token.roles](const rgw::auth::Identity::aclspec_t& aclspec) {
uint32_t perm = 0;
for (const auto& allowed_item : allowed_items) {
const auto iter = aclspec.find(allowed_item);
if (std::end(aclspec) != iter) {
perm |= iter->second;
}
}
for (const auto& r : token_roles) {
if (r.is_reader) {
if (r.is_admin) { /* system scope reader persona */
/*
* Because system reader defeats permissions,
* we don't even look at the aclspec.
*/
perm |= RGW_OP_TYPE_READ;
}
}
}
return perm;
};
}
TokenEngine::result_t
TokenEngine::authenticate(const DoutPrefixProvider* dpp,
const std::string& token,
const std::string& service_token,
const req_state* const s) const
{
bool allow_expired = false;
boost::optional<TokenEngine::token_envelope_t> t;
/* This will be initialized on the first call to this method. In C++11 it's
* also thread-safe. */
static const struct RolesCacher {
explicit RolesCacher(CephContext* const cct) {
get_str_vec(cct->_conf->rgw_keystone_accepted_roles, plain);
get_str_vec(cct->_conf->rgw_keystone_accepted_admin_roles, admin);
get_str_vec(cct->_conf->rgw_keystone_accepted_reader_roles, reader);
/* Let's suppose that having an admin role implies also a regular one. */
plain.insert(std::end(plain), std::begin(admin), std::end(admin));
}
std::vector<std::string> plain;
std::vector<std::string> admin;
std::vector<std::string> reader;
} roles(cct);
static const struct ServiceTokenRolesCacher {
explicit ServiceTokenRolesCacher(CephContext* const cct) {
get_str_vec(cct->_conf->rgw_keystone_service_token_accepted_roles, plain);
}
std::vector<std::string> plain;
} service_token_roles(cct);
if (! is_applicable(token)) {
return result_t::deny();
}
/* Token ID is a legacy of supporting the service-side validation
* of PKI/PKIz token type which are already-removed-in-OpenStack.
* The idea was to bury in cache only a short hash instead of few
* kilobytes. RadosGW doesn't do the local validation anymore. */
const auto& token_id = rgw_get_token_id(token);
ldpp_dout(dpp, 20) << "token_id=" << token_id << dendl;
/* Check cache first. */
t = token_cache.find(token_id);
if (t) {
ldpp_dout(dpp, 20) << "cached token.project.id=" << t->get_project_id()
<< dendl;
auto apl = apl_factory->create_apl_remote(cct, s, get_acl_strategy(*t),
get_creds_info(*t));
return result_t::grant(std::move(apl));
}
/* We have a service token and a token so we verify the service
* token and if it's invalid the request is invalid. If it's valid
* we allow an expired token to be used when doing lookup in Keystone.
* We never get to this if the token is in the cache. */
if (g_conf()->rgw_keystone_service_token_enabled && ! service_token.empty()) {
boost::optional<TokenEngine::token_envelope_t> st;
const auto& service_token_id = rgw_get_token_id(service_token);
ldpp_dout(dpp, 20) << "service_token_id=" << service_token_id << dendl;
/* Check cache for service token first. */
st = token_cache.find_service(service_token_id);
if (st) {
ldpp_dout(dpp, 20) << "cached service_token.project.id=" << st->get_project_id()
<< dendl;
/* We found the service token in the cache so we allow using an expired
* token for this request. */
allow_expired = true;
ldpp_dout(dpp, 20) << "allowing expired tokens because service_token_id="
<< service_token_id
<< " was found in cache" << dendl;
} else {
/* Service token was not found in cache. Go to Keystone for validating
* the token. The allow_expired here must always be false. */
ceph_assert(allow_expired == false);
st = get_from_keystone(dpp, service_token, allow_expired);
if (! st) {
return result_t::deny(-EACCES);
}
/* Verify expiration of service token. */
if (st->expired()) {
ldpp_dout(dpp, 0) << "got expired service token: " << st->get_project_name()
<< ":" << st->get_user_name()
<< " expired " << st->get_expires() << dendl;
return result_t::deny(-EPERM);
}
/* Check for necessary roles for service token. */
for (const auto& role : service_token_roles.plain) {
if (st->has_role(role) == true) {
/* Service token is valid so we allow using an expired token for
* this request. */
ldpp_dout(dpp, 20) << "allowing expired tokens because service_token_id="
<< service_token_id
<< " is valid, role: "
<< role << dendl;
allow_expired = true;
token_cache.add_service(service_token_id, *st);
break;
}
}
if (!allow_expired) {
ldpp_dout(dpp, 0) << "service token user does not hold a matching role; required roles: "
<< g_conf()->rgw_keystone_service_token_accepted_roles << dendl;
return result_t::deny(-EPERM);
}
}
}
/* Token not in cache. Go to the Keystone for validation. This happens even
* for the legacy PKI/PKIz token types. That's it, after the PKI/PKIz
* RadosGW-side validation has been removed, we always ask Keystone. */
t = get_from_keystone(dpp, token, allow_expired);
if (! t) {
return result_t::deny(-EACCES);
}
t->update_roles(roles.admin, roles.reader);
/* Verify expiration. */
if (t->expired()) {
if (allow_expired) {
ldpp_dout(dpp, 20) << "allowing expired token: " << t->get_project_name()
<< ":" << t->get_user_name()
<< " expired: " << t->get_expires()
<< " because of valid service token" << dendl;
} else {
ldpp_dout(dpp, 0) << "got expired token: " << t->get_project_name()
<< ":" << t->get_user_name()
<< " expired: " << t->get_expires() << dendl;
return result_t::deny(-EPERM);
}
}
/* Check for necessary roles. */
for (const auto& role : roles.plain) {
if (t->has_role(role) == true) {
/* If this token was an allowed expired token because we got a
* service token we need to update the expiration before we cache it. */
if (allow_expired) {
time_t now = ceph_clock_now().sec();
time_t new_expires = now + g_conf()->rgw_keystone_expired_token_cache_expiration;
ldpp_dout(dpp, 20) << "updating expiration of allowed expired token"
<< " from old " << t->get_expires() << " to now " << now << " + "
<< g_conf()->rgw_keystone_expired_token_cache_expiration
<< " secs = "
<< new_expires << dendl;
t->set_expires(new_expires);
}
ldpp_dout(dpp, 0) << "validated token: " << t->get_project_name()
<< ":" << t->get_user_name()
<< " expires: " << t->get_expires() << dendl;
token_cache.add(token_id, *t);
auto apl = apl_factory->create_apl_remote(cct, s, get_acl_strategy(*t),
get_creds_info(*t));
return result_t::grant(std::move(apl));
}
}
ldpp_dout(dpp, 0) << "user does not hold a matching role; required roles: "
<< g_conf()->rgw_keystone_accepted_roles << dendl;
return result_t::deny(-EPERM);
}
/*
* Try to validate S3 auth against keystone s3token interface
*/
std::pair<boost::optional<rgw::keystone::TokenEnvelope>, int>
EC2Engine::get_from_keystone(const DoutPrefixProvider* dpp, const std::string_view& access_key_id,
const std::string& string_to_sign,
const std::string_view& signature) const
{
/* prepare keystone url */
std::string keystone_url = config.get_endpoint_url();
if (keystone_url.empty()) {
throw -EINVAL;
}
const auto api_version = config.get_api_version();
if (api_version == rgw::keystone::ApiVersion::VER_3) {
keystone_url.append("v3/s3tokens");
} else {
keystone_url.append("v2.0/s3tokens");
}
/* get authentication token for Keystone. */
std::string admin_token;
int ret = rgw::keystone::Service::get_admin_token(dpp, cct, token_cache, config,
admin_token);
if (ret < 0) {
ldpp_dout(dpp, 2) << "s3 keystone: cannot get token for keystone access"
<< dendl;
throw ret;
}
using RGWValidateKeystoneToken
= rgw::keystone::Service::RGWValidateKeystoneToken;
/* The container for plain response obtained from Keystone. It will be
* parsed token_envelope_t::parse method. */
ceph::bufferlist token_body_bl;
RGWValidateKeystoneToken validate(cct, "POST", keystone_url, &token_body_bl);
/* set required headers for keystone request */
validate.append_header("X-Auth-Token", admin_token);
validate.append_header("Content-Type", "application/json");
/* check if we want to verify keystone's ssl certs */
validate.set_verify_ssl(cct->_conf->rgw_keystone_verify_ssl);
/* create json credentials request body */
JSONFormatter credentials(false);
credentials.open_object_section("");
credentials.open_object_section("credentials");
credentials.dump_string("access", sview2cstr(access_key_id).data());
credentials.dump_string("token", rgw::to_base64(string_to_sign));
credentials.dump_string("signature", sview2cstr(signature).data());
credentials.close_section();
credentials.close_section();
std::stringstream os;
credentials.flush(os);
validate.set_post_data(os.str());
validate.set_send_length(os.str().length());
/* send request */
ret = validate.process(null_yield);
if (ret < 0) {
ldpp_dout(dpp, 2) << "s3 keystone: token validation ERROR: "
<< token_body_bl.c_str() << dendl;
throw ret;
}
/* if the supplied signature is wrong, we will get 401 from Keystone */
if (validate.get_http_status() ==
decltype(validate)::HTTP_STATUS_UNAUTHORIZED) {
return std::make_pair(boost::none, -ERR_SIGNATURE_NO_MATCH);
} else if (validate.get_http_status() ==
decltype(validate)::HTTP_STATUS_NOTFOUND) {
return std::make_pair(boost::none, -ERR_INVALID_ACCESS_KEY);
}
/* now parse response */
rgw::keystone::TokenEnvelope token_envelope;
ret = token_envelope.parse(dpp, cct, std::string(), token_body_bl, api_version);
if (ret < 0) {
ldpp_dout(dpp, 2) << "s3 keystone: token parsing failed, ret=0" << ret
<< dendl;
throw ret;
}
return std::make_pair(std::move(token_envelope), 0);
}
std::pair<boost::optional<std::string>, int> EC2Engine::get_secret_from_keystone(const DoutPrefixProvider* dpp,
const std::string& user_id,
const std::string_view& access_key_id) const
{
/* Fetch from /users/{USER_ID}/credentials/OS-EC2/{ACCESS_KEY_ID} */
/* Should return json with response key "credential" which contains entry "secret"*/
/* prepare keystone url */
std::string keystone_url = config.get_endpoint_url();
if (keystone_url.empty()) {
return make_pair(boost::none, -EINVAL);
}
const auto api_version = config.get_api_version();
if (api_version == rgw::keystone::ApiVersion::VER_3) {
keystone_url.append("v3/");
} else {
keystone_url.append("v2.0/");
}
keystone_url.append("users/");
keystone_url.append(user_id);
keystone_url.append("/credentials/OS-EC2/");
keystone_url.append(std::string(access_key_id));
/* get authentication token for Keystone. */
std::string admin_token;
int ret = rgw::keystone::Service::get_admin_token(dpp, cct, token_cache, config,
admin_token);
if (ret < 0) {
ldpp_dout(dpp, 2) << "s3 keystone: cannot get token for keystone access"
<< dendl;
return make_pair(boost::none, ret);
}
using RGWGetAccessSecret
= rgw::keystone::Service::RGWKeystoneHTTPTransceiver;
/* The container for plain response obtained from Keystone.*/
ceph::bufferlist token_body_bl;
RGWGetAccessSecret secret(cct, "GET", keystone_url, &token_body_bl);
/* set required headers for keystone request */
secret.append_header("X-Auth-Token", admin_token);
/* check if we want to verify keystone's ssl certs */
secret.set_verify_ssl(cct->_conf->rgw_keystone_verify_ssl);
/* send request */
ret = secret.process(null_yield);
if (ret < 0) {
ldpp_dout(dpp, 2) << "s3 keystone: secret fetching error: "
<< token_body_bl.c_str() << dendl;
return make_pair(boost::none, ret);
}
/* if the supplied signature is wrong, we will get 401 from Keystone */
if (secret.get_http_status() ==
decltype(secret)::HTTP_STATUS_NOTFOUND) {
return make_pair(boost::none, -EINVAL);
}
/* now parse response */
JSONParser parser;
if (! parser.parse(token_body_bl.c_str(), token_body_bl.length())) {
ldpp_dout(dpp, 0) << "Keystone credential parse error: malformed json" << dendl;
return make_pair(boost::none, -EINVAL);
}
JSONObjIter credential_iter = parser.find_first("credential");
std::string secret_string;
try {
if (!credential_iter.end()) {
JSONDecoder::decode_json("secret", secret_string, *credential_iter, true);
} else {
ldpp_dout(dpp, 0) << "Keystone credential not present in return from server" << dendl;
return make_pair(boost::none, -EINVAL);
}
} catch (const JSONDecoder::err& err) {
ldpp_dout(dpp, 0) << "Keystone credential parse error: " << err.what() << dendl;
return make_pair(boost::none, -EINVAL);
}
return make_pair(secret_string, 0);
}
/*
* Try to get a token for S3 authentication, using a secret cache if available
*/
auto EC2Engine::get_access_token(const DoutPrefixProvider* dpp,
const std::string_view& access_key_id,
const std::string& string_to_sign,
const std::string_view& signature,
const signature_factory_t& signature_factory) const
-> access_token_result
{
using server_signature_t = VersionAbstractor::server_signature_t;
boost::optional<rgw::keystone::TokenEnvelope> token;
boost::optional<std::string> secret;
int failure_reason;
/* Get a token from the cache if one has already been stored */
boost::optional<boost::tuple<rgw::keystone::TokenEnvelope, std::string>>
t = secret_cache.find(std::string(access_key_id));
/* Check that credentials can correctly be used to sign data */
if (t) {
std::string sig(signature);
server_signature_t server_signature = signature_factory(cct, t->get<1>(), string_to_sign);
if (sig.compare(server_signature) == 0) {
return {t->get<0>(), t->get<1>(), 0};
} else {
ldpp_dout(dpp, 0) << "Secret string does not correctly sign payload, cache miss" << dendl;
}
} else {
ldpp_dout(dpp, 0) << "No stored secret string, cache miss" << dendl;
}
/* No cached token, token expired, or secret invalid: fall back to keystone */
std::tie(token, failure_reason) = get_from_keystone(dpp, access_key_id, string_to_sign, signature);
if (token) {
/* Fetch secret from keystone for the access_key_id */
std::tie(secret, failure_reason) =
get_secret_from_keystone(dpp, token->get_user_id(), access_key_id);
if (secret) {
/* Add token, secret pair to cache, and set timeout */
secret_cache.add(std::string(access_key_id), *token, *secret);
}
}
return {token, secret, failure_reason};
}
EC2Engine::acl_strategy_t
EC2Engine::get_acl_strategy(const EC2Engine::token_envelope_t&) const
{
/* This is based on the assumption that the default acl strategy in
* get_perms_from_aclspec, will take care. Extra acl spec is not required. */
return nullptr;
}
EC2Engine::auth_info_t
EC2Engine::get_creds_info(const EC2Engine::token_envelope_t& token,
const std::vector<std::string>& admin_roles,
const std::string& access_key_id
) const noexcept
{
using acct_privilege_t = \
rgw::auth::RemoteApplier::AuthInfo::acct_privilege_t;
/* Check whether the user has an admin status. */
acct_privilege_t level = acct_privilege_t::IS_PLAIN_ACCT;
for (const auto& admin_role : admin_roles) {
if (token.has_role(admin_role)) {
level = acct_privilege_t::IS_ADMIN_ACCT;
break;
}
}
return auth_info_t {
/* Suggested account name for the authenticated user. */
rgw_user(token.get_project_id()),
/* User's display name (aka real name). */
token.get_project_name(),
/* Keystone doesn't support RGW's subuser concept, so we cannot cut down
* the access rights through the perm_mask. At least at this layer. */
RGW_PERM_FULL_CONTROL,
level,
access_key_id,
rgw::auth::RemoteApplier::AuthInfo::NO_SUBUSER,
TYPE_KEYSTONE
};
}
rgw::auth::Engine::result_t EC2Engine::authenticate(
const DoutPrefixProvider* dpp,
const std::string_view& access_key_id,
const std::string_view& signature,
const std::string_view& session_token,
const string_to_sign_t& string_to_sign,
const signature_factory_t& signature_factory,
const completer_factory_t& completer_factory,
/* Passthorugh only! */
const req_state* s,
optional_yield y) const
{
/* This will be initialized on the first call to this method. In C++11 it's
* also thread-safe. */
static const struct RolesCacher {
explicit RolesCacher(CephContext* const cct) {
get_str_vec(cct->_conf->rgw_keystone_accepted_roles, plain);
get_str_vec(cct->_conf->rgw_keystone_accepted_admin_roles, admin);
/* Let's suppose that having an admin role implies also a regular one. */
plain.insert(std::end(plain), std::begin(admin), std::end(admin));
}
std::vector<std::string> plain;
std::vector<std::string> admin;
} accepted_roles(cct);
auto [t, secret_key, failure_reason] =
get_access_token(dpp, access_key_id, string_to_sign, signature, signature_factory);
if (! t) {
return result_t::deny(failure_reason);
}
/* Verify expiration. */
if (t->expired()) {
ldpp_dout(dpp, 0) << "got expired token: " << t->get_project_name()
<< ":" << t->get_user_name()
<< " expired: " << t->get_expires() << dendl;
return result_t::deny();
}
/* check if we have a valid role */
bool found = false;
for (const auto& role : accepted_roles.plain) {
if (t->has_role(role) == true) {
found = true;
break;
}
}
if (! found) {
ldpp_dout(dpp, 5) << "s3 keystone: user does not hold a matching role;"
" required roles: "
<< cct->_conf->rgw_keystone_accepted_roles << dendl;
return result_t::deny();
} else {
/* everything seems fine, continue with this user */
ldpp_dout(dpp, 5) << "s3 keystone: validated token: " << t->get_project_name()
<< ":" << t->get_user_name()
<< " expires: " << t->get_expires() << dendl;
auto apl = apl_factory->create_apl_remote(cct, s, get_acl_strategy(*t),
get_creds_info(*t, accepted_roles.admin, std::string(access_key_id)));
return result_t::grant(std::move(apl), completer_factory(secret_key));
}
}
bool SecretCache::find(const std::string& token_id,
SecretCache::token_envelope_t& token,
std::string &secret)
{
std::lock_guard<std::mutex> l(lock);
map<std::string, secret_entry>::iterator iter = secrets.find(token_id);
if (iter == secrets.end()) {
return false;
}
secret_entry& entry = iter->second;
secrets_lru.erase(entry.lru_iter);
const utime_t now = ceph_clock_now();
if (entry.token.expired() || now > entry.expires) {
secrets.erase(iter);
return false;
}
token = entry.token;
secret = entry.secret;
secrets_lru.push_front(token_id);
entry.lru_iter = secrets_lru.begin();
return true;
}
void SecretCache::add(const std::string& token_id,
const SecretCache::token_envelope_t& token,
const std::string& secret)
{
std::lock_guard<std::mutex> l(lock);
map<string, secret_entry>::iterator iter = secrets.find(token_id);
if (iter != secrets.end()) {
secret_entry& e = iter->second;
secrets_lru.erase(e.lru_iter);
}
const utime_t now = ceph_clock_now();
secrets_lru.push_front(token_id);
secret_entry& entry = secrets[token_id];
entry.token = token;
entry.secret = secret;
entry.expires = now + s3_token_expiry_length;
entry.lru_iter = secrets_lru.begin();
while (secrets_lru.size() > max) {
list<string>::reverse_iterator riter = secrets_lru.rbegin();
iter = secrets.find(*riter);
assert(iter != secrets.end());
secrets.erase(iter);
secrets_lru.pop_back();
}
}
}; /* namespace keystone */
}; /* namespace auth */
}; /* namespace rgw */
| 27,011 | 33.944373 | 125 |
cc
|
null |
ceph-main/src/rgw/rgw_auth_keystone.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#pragma once
#include <string_view>
#include <utility>
#include <boost/optional.hpp>
#include "rgw_auth.h"
#include "rgw_rest_s3.h"
#include "rgw_common.h"
#include "rgw_keystone.h"
namespace rgw {
namespace auth {
namespace keystone {
/* Dedicated namespace for Keystone-related auth engines. We need it because
* Keystone offers three different authentication mechanisms (token, EC2 and
* regular user/pass). RadosGW actually does support the first two. */
class TokenEngine : public rgw::auth::Engine {
CephContext* const cct;
using acl_strategy_t = rgw::auth::RemoteApplier::acl_strategy_t;
using auth_info_t = rgw::auth::RemoteApplier::AuthInfo;
using result_t = rgw::auth::Engine::result_t;
using token_envelope_t = rgw::keystone::TokenEnvelope;
const rgw::auth::TokenExtractor* const auth_token_extractor;
const rgw::auth::TokenExtractor* const service_token_extractor;
const rgw::auth::RemoteApplier::Factory* const apl_factory;
rgw::keystone::Config& config;
rgw::keystone::TokenCache& token_cache;
/* Helper methods. */
bool is_applicable(const std::string& token) const noexcept;
boost::optional<token_envelope_t>
get_from_keystone(const DoutPrefixProvider* dpp, const std::string& token, bool allow_expired) const;
acl_strategy_t get_acl_strategy(const token_envelope_t& token) const;
auth_info_t get_creds_info(const token_envelope_t& token) const noexcept;
result_t authenticate(const DoutPrefixProvider* dpp,
const std::string& token,
const std::string& service_token,
const req_state* s) const;
public:
TokenEngine(CephContext* const cct,
const rgw::auth::TokenExtractor* const auth_token_extractor,
const rgw::auth::TokenExtractor* const service_token_extractor,
const rgw::auth::RemoteApplier::Factory* const apl_factory,
rgw::keystone::Config& config,
rgw::keystone::TokenCache& token_cache)
: cct(cct),
auth_token_extractor(auth_token_extractor),
service_token_extractor(service_token_extractor),
apl_factory(apl_factory),
config(config),
token_cache(token_cache) {
}
const char* get_name() const noexcept override {
return "rgw::auth::keystone::TokenEngine";
}
result_t authenticate(const DoutPrefixProvider* dpp, const req_state* const s,
optional_yield y) const override {
return authenticate(dpp, auth_token_extractor->get_token(s), service_token_extractor->get_token(s), s);
}
}; /* class TokenEngine */
class SecretCache {
using token_envelope_t = rgw::keystone::TokenEnvelope;
struct secret_entry {
token_envelope_t token;
std::string secret;
utime_t expires;
std::list<std::string>::iterator lru_iter;
};
const boost::intrusive_ptr<CephContext> cct;
std::map<std::string, secret_entry> secrets;
std::list<std::string> secrets_lru;
std::mutex lock;
const size_t max;
const utime_t s3_token_expiry_length;
SecretCache()
: cct(g_ceph_context),
lock(),
max(cct->_conf->rgw_keystone_token_cache_size),
s3_token_expiry_length(300, 0) {
}
~SecretCache() {}
public:
SecretCache(const SecretCache&) = delete;
void operator=(const SecretCache&) = delete;
static SecretCache& get_instance() {
/* In C++11 this is thread safe. */
static SecretCache instance;
return instance;
}
bool find(const std::string& token_id, token_envelope_t& token, std::string& secret);
boost::optional<boost::tuple<token_envelope_t, std::string>> find(const std::string& token_id) {
token_envelope_t token_envlp;
std::string secret;
if (find(token_id, token_envlp, secret)) {
return boost::make_tuple(token_envlp, secret);
}
return boost::none;
}
void add(const std::string& token_id, const token_envelope_t& token, const std::string& secret);
}; /* class SecretCache */
class EC2Engine : public rgw::auth::s3::AWSEngine {
using acl_strategy_t = rgw::auth::RemoteApplier::acl_strategy_t;
using auth_info_t = rgw::auth::RemoteApplier::AuthInfo;
using result_t = rgw::auth::Engine::result_t;
using token_envelope_t = rgw::keystone::TokenEnvelope;
const rgw::auth::RemoteApplier::Factory* const apl_factory;
rgw::keystone::Config& config;
rgw::keystone::TokenCache& token_cache;
rgw::auth::keystone::SecretCache& secret_cache;
/* Helper methods. */
acl_strategy_t get_acl_strategy(const token_envelope_t& token) const;
auth_info_t get_creds_info(const token_envelope_t& token,
const std::vector<std::string>& admin_roles,
const std::string& access_key_id
) const noexcept;
std::pair<boost::optional<token_envelope_t>, int>
get_from_keystone(const DoutPrefixProvider* dpp,
const std::string_view& access_key_id,
const std::string& string_to_sign,
const std::string_view& signature) const;
struct access_token_result {
boost::optional<token_envelope_t> token;
boost::optional<std::string> secret_key;
int failure_reason = 0;
};
access_token_result
get_access_token(const DoutPrefixProvider* dpp,
const std::string_view& access_key_id,
const std::string& string_to_sign,
const std::string_view& signature,
const signature_factory_t& signature_factory) const;
result_t authenticate(const DoutPrefixProvider* dpp,
const std::string_view& access_key_id,
const std::string_view& signature,
const std::string_view& session_token,
const string_to_sign_t& string_to_sign,
const signature_factory_t& signature_factory,
const completer_factory_t& completer_factory,
const req_state* s,
optional_yield y) const override;
std::pair<boost::optional<std::string>, int> get_secret_from_keystone(const DoutPrefixProvider* dpp,
const std::string& user_id,
const std::string_view& access_key_id) const;
public:
EC2Engine(CephContext* const cct,
const rgw::auth::s3::AWSEngine::VersionAbstractor* const ver_abstractor,
const rgw::auth::RemoteApplier::Factory* const apl_factory,
rgw::keystone::Config& config,
/* The token cache is used ONLY for the retrieving admin token.
* Due to the architecture of AWS Auth S3 credentials cannot be
* cached at all. */
rgw::keystone::TokenCache& token_cache,
rgw::auth::keystone::SecretCache& secret_cache)
: AWSEngine(cct, *ver_abstractor),
apl_factory(apl_factory),
config(config),
token_cache(token_cache),
secret_cache(secret_cache) {
}
using AWSEngine::authenticate;
const char* get_name() const noexcept override {
return "rgw::auth::keystone::EC2Engine";
}
}; /* class EC2Engine */
}; /* namespace keystone */
}; /* namespace auth */
}; /* namespace rgw */
| 7,368 | 35.661692 | 117 |
h
|
null |
ceph-main/src/rgw/rgw_auth_registry.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#pragma once
#include <functional>
#include <memory>
#include <ostream>
#include <type_traits>
#include <utility>
#include "rgw_auth.h"
#include "rgw_auth_s3.h"
#include "rgw_swift_auth.h"
#include "rgw_rest_sts.h"
namespace rgw {
namespace auth {
/* A class aggregating the knowledge about all Strategies in RadosGW. It is
* responsible for handling the dynamic reconfiguration on e.g. realm update. */
class StrategyRegistry {
template <class AbstractorT,
bool AllowAnonAccessT = false>
using s3_strategy_t = \
rgw::auth::s3::AWSAuthStrategy<AbstractorT, AllowAnonAccessT>;
struct s3_main_strategy_t : public Strategy {
using s3_main_strategy_plain_t = \
s3_strategy_t<rgw::auth::s3::AWSGeneralAbstractor, true>;
using s3_main_strategy_boto2_t = \
s3_strategy_t<rgw::auth::s3::AWSGeneralBoto2Abstractor>;
s3_main_strategy_plain_t s3_main_strategy_plain;
s3_main_strategy_boto2_t s3_main_strategy_boto2;
s3_main_strategy_t(CephContext* const cct,
const ImplicitTenants& implicit_tenant_context,
rgw::sal::Driver* driver)
: s3_main_strategy_plain(cct, implicit_tenant_context, driver),
s3_main_strategy_boto2(cct, implicit_tenant_context, driver) {
add_engine(Strategy::Control::SUFFICIENT, s3_main_strategy_plain);
add_engine(Strategy::Control::FALLBACK, s3_main_strategy_boto2);
}
const char* get_name() const noexcept override {
return "rgw::auth::StrategyRegistry::s3_main_strategy_t";
}
} s3_main_strategy;
using s3_post_strategy_t = \
s3_strategy_t<rgw::auth::s3::AWSBrowserUploadAbstractor>;
s3_post_strategy_t s3_post_strategy;
rgw::auth::swift::DefaultStrategy swift_strategy;
rgw::auth::sts::DefaultStrategy sts_strategy;
public:
StrategyRegistry(CephContext* const cct,
const ImplicitTenants& implicit_tenant_context,
rgw::sal::Driver* driver)
: s3_main_strategy(cct, implicit_tenant_context, driver),
s3_post_strategy(cct, implicit_tenant_context, driver),
swift_strategy(cct, implicit_tenant_context, driver),
sts_strategy(cct, implicit_tenant_context, driver) {
}
const s3_main_strategy_t& get_s3_main() const {
return s3_main_strategy;
}
const s3_post_strategy_t& get_s3_post() const {
return s3_post_strategy;
}
const rgw::auth::swift::DefaultStrategy& get_swift() const {
return swift_strategy;
}
const rgw::auth::sts::DefaultStrategy& get_sts() const {
return sts_strategy;
}
static std::unique_ptr<StrategyRegistry>
create(CephContext* const cct,
const ImplicitTenants& implicit_tenant_context,
rgw::sal::Driver* driver) {
return std::make_unique<StrategyRegistry>(cct, implicit_tenant_context, driver);
}
};
} /* namespace auth */
} /* namespace rgw */
using rgw_auth_registry_t = rgw::auth::StrategyRegistry;
using rgw_auth_registry_ptr_t = std::unique_ptr<rgw_auth_registry_t>;
| 3,080 | 30.438776 | 84 |
h
|
null |
ceph-main/src/rgw/rgw_auth_s3.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include <algorithm>
#include <map>
#include <iterator>
#include <string>
#include <string_view>
#include <vector>
#include "common/armor.h"
#include "common/utf8.h"
#include "rgw_rest_s3.h"
#include "rgw_auth_s3.h"
#include "rgw_common.h"
#include "rgw_client_io.h"
#include "rgw_rest.h"
#include "rgw_crypt_sanitize.h"
#include <boost/container/small_vector.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/trim_all.hpp>
#define dout_context g_ceph_context
#define dout_subsys ceph_subsys_rgw
using namespace std;
static const auto signed_subresources = {
"acl",
"cors",
"delete",
"encryption",
"lifecycle",
"location",
"logging",
"notification",
"partNumber",
"policy",
"policyStatus",
"publicAccessBlock",
"requestPayment",
"response-cache-control",
"response-content-disposition",
"response-content-encoding",
"response-content-language",
"response-content-type",
"response-expires",
"tagging",
"torrent",
"uploadId",
"uploads",
"versionId",
"versioning",
"versions",
"website",
"object-lock"
};
/*
* ?get the canonical amazon-style header for something?
*/
static std::string
get_canon_amz_hdr(const meta_map_t& meta_map)
{
std::string dest;
for (const auto& kv : meta_map) {
dest.append(kv.first);
dest.append(":");
dest.append(kv.second);
dest.append("\n");
}
return dest;
}
/*
* ?get the canonical representation of the object's location
*/
static std::string
get_canon_resource(const DoutPrefixProvider *dpp, const char* const request_uri,
const std::map<std::string, std::string>& sub_resources)
{
std::string dest;
if (request_uri) {
dest.append(request_uri);
}
bool initial = true;
for (const auto& subresource : signed_subresources) {
const auto iter = sub_resources.find(subresource);
if (iter == std::end(sub_resources)) {
continue;
}
if (initial) {
dest.append("?");
initial = false;
} else {
dest.append("&");
}
dest.append(iter->first);
if (! iter->second.empty()) {
dest.append("=");
dest.append(iter->second);
}
}
ldpp_dout(dpp, 10) << "get_canon_resource(): dest=" << dest << dendl;
return dest;
}
/*
* get the header authentication information required to
* compute a request's signature
*/
void rgw_create_s3_canonical_header(
const DoutPrefixProvider *dpp,
const char* const method,
const char* const content_md5,
const char* const content_type,
const char* const date,
const meta_map_t& meta_map,
const meta_map_t& qs_map,
const char* const request_uri,
const std::map<std::string, std::string>& sub_resources,
std::string& dest_str)
{
std::string dest;
if (method) {
dest = method;
}
dest.append("\n");
if (content_md5) {
dest.append(content_md5);
}
dest.append("\n");
if (content_type) {
dest.append(content_type);
}
dest.append("\n");
if (date) {
dest.append(date);
}
dest.append("\n");
dest.append(get_canon_amz_hdr(meta_map));
dest.append(get_canon_amz_hdr(qs_map));
dest.append(get_canon_resource(dpp, request_uri, sub_resources));
dest_str = dest;
}
static inline bool is_base64_for_content_md5(unsigned char c) {
return (isalnum(c) || isspace(c) || (c == '+') || (c == '/') || (c == '='));
}
static inline void get_v2_qs_map(const req_info& info,
meta_map_t& qs_map) {
const auto& params = const_cast<RGWHTTPArgs&>(info.args).get_params();
for (const auto& elt : params) {
std::string k = boost::algorithm::to_lower_copy(elt.first);
if (k.find("x-amz-meta-") == /* offset */ 0) {
rgw_add_amz_meta_header(qs_map, k, elt.second);
}
if (k == "x-amz-security-token") {
qs_map[k] = elt.second;
}
}
}
/*
* get the header authentication information required to
* compute a request's signature
*/
bool rgw_create_s3_canonical_header(const DoutPrefixProvider *dpp,
const req_info& info,
utime_t* const header_time,
std::string& dest,
const bool qsr)
{
const char* const content_md5 = info.env->get("HTTP_CONTENT_MD5");
if (content_md5) {
for (const char *p = content_md5; *p; p++) {
if (!is_base64_for_content_md5(*p)) {
ldpp_dout(dpp, 0) << "NOTICE: bad content-md5 provided (not base64),"
<< " aborting request p=" << *p << " " << (int)*p << dendl;
return false;
}
}
}
const char *content_type = info.env->get("CONTENT_TYPE");
std::string date;
meta_map_t qs_map;
if (qsr) {
get_v2_qs_map(info, qs_map); // handle qs metadata
date = info.args.get("Expires");
} else {
const char *str = info.env->get("HTTP_X_AMZ_DATE");
const char *req_date = str;
if (str == NULL) {
req_date = info.env->get("HTTP_DATE");
if (!req_date) {
ldpp_dout(dpp, 0) << "NOTICE: missing date for auth header" << dendl;
return false;
}
date = req_date;
}
if (header_time) {
struct tm t;
uint32_t ns = 0;
if (!parse_rfc2616(req_date, &t) && !parse_iso8601(req_date, &t, &ns, false)) {
ldpp_dout(dpp, 0) << "NOTICE: failed to parse date <" << req_date << "> for auth header" << dendl;
return false;
}
if (t.tm_year < 70) {
ldpp_dout(dpp, 0) << "NOTICE: bad date (predates epoch): " << req_date << dendl;
return false;
}
*header_time = utime_t(internal_timegm(&t), 0);
*header_time -= t.tm_gmtoff;
}
}
const auto& meta_map = info.x_meta_map;
const auto& sub_resources = info.args.get_sub_resources();
std::string request_uri;
if (info.effective_uri.empty()) {
request_uri = info.request_uri;
} else {
request_uri = info.effective_uri;
}
rgw_create_s3_canonical_header(dpp, info.method, content_md5, content_type,
date.c_str(), meta_map, qs_map,
request_uri.c_str(), sub_resources, dest);
return true;
}
namespace rgw::auth::s3 {
bool is_time_skew_ok(time_t t)
{
auto req_tp = ceph::coarse_real_clock::from_time_t(t);
auto cur_tp = ceph::coarse_real_clock::now();
if (std::chrono::abs(cur_tp - req_tp) > RGW_AUTH_GRACE) {
dout(10) << "NOTICE: request time skew too big." << dendl;
using ceph::operator<<;
dout(10) << "req_tp=" << req_tp << ", cur_tp=" << cur_tp << dendl;
return false;
}
return true;
}
static inline int parse_v4_query_string(const req_info& info, /* in */
std::string_view& credential, /* out */
std::string_view& signedheaders, /* out */
std::string_view& signature, /* out */
std::string_view& date, /* out */
std::string_view& sessiontoken) /* out */
{
/* auth ships with req params ... */
/* look for required params */
credential = info.args.get("x-amz-credential");
if (credential.size() == 0) {
return -EPERM;
}
date = info.args.get("x-amz-date");
struct tm date_t;
if (!parse_iso8601(sview2cstr(date).data(), &date_t, nullptr, false)) {
return -EPERM;
}
std::string_view expires = info.args.get("x-amz-expires");
if (expires.empty()) {
return -EPERM;
}
/* X-Amz-Expires provides the time period, in seconds, for which
the generated presigned URL is valid. The minimum value
you can set is 1, and the maximum is 604800 (seven days) */
time_t exp = atoll(expires.data());
if ((exp < 1) || (exp > 7*24*60*60)) {
dout(10) << "NOTICE: exp out of range, exp = " << exp << dendl;
return -EPERM;
}
/* handle expiration in epoch time */
uint64_t req_sec = (uint64_t)internal_timegm(&date_t);
uint64_t now = ceph_clock_now();
if (now >= req_sec + exp) {
dout(10) << "NOTICE: now = " << now << ", req_sec = " << req_sec << ", exp = " << exp << dendl;
return -EPERM;
}
signedheaders = info.args.get("x-amz-signedheaders");
if (signedheaders.size() == 0) {
return -EPERM;
}
signature = info.args.get("x-amz-signature");
if (signature.size() == 0) {
return -EPERM;
}
if (info.args.exists("x-amz-security-token")) {
sessiontoken = info.args.get("x-amz-security-token");
if (sessiontoken.size() == 0) {
return -EPERM;
}
}
return 0;
}
static bool get_next_token(const std::string_view& s,
size_t& pos,
const char* const delims,
std::string_view& token)
{
const size_t start = s.find_first_not_of(delims, pos);
if (start == std::string_view::npos) {
pos = s.size();
return false;
}
size_t end = s.find_first_of(delims, start);
if (end != std::string_view::npos)
pos = end + 1;
else {
pos = end = s.size();
}
token = s.substr(start, end - start);
return true;
}
template<std::size_t ExpectedStrNum>
boost::container::small_vector<std::string_view, ExpectedStrNum>
get_str_vec(const std::string_view& str, const char* const delims)
{
boost::container::small_vector<std::string_view, ExpectedStrNum> str_vec;
size_t pos = 0;
std::string_view token;
while (pos < str.size()) {
if (get_next_token(str, pos, delims, token)) {
if (token.size() > 0) {
str_vec.push_back(token);
}
}
}
return str_vec;
}
template<std::size_t ExpectedStrNum>
boost::container::small_vector<std::string_view, ExpectedStrNum>
get_str_vec(const std::string_view& str)
{
const char delims[] = ";,= \t";
return get_str_vec<ExpectedStrNum>(str, delims);
}
static inline int parse_v4_auth_header(const req_info& info, /* in */
std::string_view& credential, /* out */
std::string_view& signedheaders, /* out */
std::string_view& signature, /* out */
std::string_view& date, /* out */
std::string_view& sessiontoken, /* out */
const DoutPrefixProvider *dpp)
{
std::string_view input(info.env->get("HTTP_AUTHORIZATION", ""));
try {
input = input.substr(::strlen(AWS4_HMAC_SHA256_STR) + 1);
} catch (std::out_of_range&) {
/* We should never ever run into this situation as the presence of
* AWS4_HMAC_SHA256_STR had been verified earlier. */
ldpp_dout(dpp, 10) << "credentials string is too short" << dendl;
return -EINVAL;
}
std::map<std::string_view, std::string_view> kv;
for (const auto& s : get_str_vec<4>(input, ",")) {
const auto parsed_pair = parse_key_value(s);
if (parsed_pair) {
kv[parsed_pair->first] = parsed_pair->second;
} else {
ldpp_dout(dpp, 10) << "NOTICE: failed to parse auth header (s=" << s << ")"
<< dendl;
return -EINVAL;
}
}
static const std::array<std::string_view, 3> required_keys = {
"Credential",
"SignedHeaders",
"Signature"
};
/* Ensure that the presigned required keys are really there. */
for (const auto& k : required_keys) {
if (kv.find(k) == std::end(kv)) {
ldpp_dout(dpp, 10) << "NOTICE: auth header missing key: " << k << dendl;
return -EINVAL;
}
}
credential = kv["Credential"];
signedheaders = kv["SignedHeaders"];
signature = kv["Signature"];
/* sig hex str */
ldpp_dout(dpp, 10) << "v4 signature format = " << signature << dendl;
/* ------------------------- handle x-amz-date header */
/* grab date */
const char *d = info.env->get("HTTP_X_AMZ_DATE");
struct tm t;
if (unlikely(d == NULL)) {
d = info.env->get("HTTP_DATE");
}
if (!d || !parse_iso8601(d, &t, NULL, false)) {
ldpp_dout(dpp, 10) << "error reading date via http_x_amz_date and http_date" << dendl;
return -EACCES;
}
date = d;
if (!is_time_skew_ok(internal_timegm(&t))) {
return -ERR_REQUEST_TIME_SKEWED;
}
auto token = info.env->get_optional("HTTP_X_AMZ_SECURITY_TOKEN");
if (token) {
sessiontoken = *token;
}
return 0;
}
bool is_non_s3_op(RGWOpType op_type)
{
if (op_type == RGW_STS_GET_SESSION_TOKEN ||
op_type == RGW_STS_ASSUME_ROLE ||
op_type == RGW_STS_ASSUME_ROLE_WEB_IDENTITY ||
op_type == RGW_OP_CREATE_ROLE ||
op_type == RGW_OP_DELETE_ROLE ||
op_type == RGW_OP_GET_ROLE ||
op_type == RGW_OP_MODIFY_ROLE_TRUST_POLICY ||
op_type == RGW_OP_LIST_ROLES ||
op_type == RGW_OP_PUT_ROLE_POLICY ||
op_type == RGW_OP_GET_ROLE_POLICY ||
op_type == RGW_OP_LIST_ROLE_POLICIES ||
op_type == RGW_OP_DELETE_ROLE_POLICY ||
op_type == RGW_OP_PUT_USER_POLICY ||
op_type == RGW_OP_GET_USER_POLICY ||
op_type == RGW_OP_LIST_USER_POLICIES ||
op_type == RGW_OP_DELETE_USER_POLICY ||
op_type == RGW_OP_CREATE_OIDC_PROVIDER ||
op_type == RGW_OP_DELETE_OIDC_PROVIDER ||
op_type == RGW_OP_GET_OIDC_PROVIDER ||
op_type == RGW_OP_LIST_OIDC_PROVIDERS ||
op_type == RGW_OP_PUBSUB_TOPIC_CREATE ||
op_type == RGW_OP_PUBSUB_TOPICS_LIST ||
op_type == RGW_OP_PUBSUB_TOPIC_GET ||
op_type == RGW_OP_PUBSUB_TOPIC_DELETE ||
op_type == RGW_OP_TAG_ROLE ||
op_type == RGW_OP_LIST_ROLE_TAGS ||
op_type == RGW_OP_UNTAG_ROLE ||
op_type == RGW_OP_UPDATE_ROLE) {
return true;
}
return false;
}
int parse_v4_credentials(const req_info& info, /* in */
std::string_view& access_key_id, /* out */
std::string_view& credential_scope, /* out */
std::string_view& signedheaders, /* out */
std::string_view& signature, /* out */
std::string_view& date, /* out */
std::string_view& session_token, /* out */
const bool using_qs, /* in */
const DoutPrefixProvider *dpp)
{
std::string_view credential;
int ret;
if (using_qs) {
ret = parse_v4_query_string(info, credential, signedheaders,
signature, date, session_token);
} else {
ret = parse_v4_auth_header(info, credential, signedheaders,
signature, date, session_token, dpp);
}
if (ret < 0) {
return ret;
}
/* access_key/YYYYMMDD/region/service/aws4_request */
ldpp_dout(dpp, 10) << "v4 credential format = " << credential << dendl;
if (std::count(credential.begin(), credential.end(), '/') != 4) {
return -EINVAL;
}
/* credential must end with 'aws4_request' */
if (credential.find("aws4_request") == std::string::npos) {
return -EINVAL;
}
/* grab access key id */
const size_t pos = credential.find("/");
access_key_id = credential.substr(0, pos);
ldpp_dout(dpp, 10) << "access key id = " << access_key_id << dendl;
/* grab credential scope */
credential_scope = credential.substr(pos + 1);
ldpp_dout(dpp, 10) << "credential scope = " << credential_scope << dendl;
return 0;
}
string gen_v4_scope(const ceph::real_time& timestamp,
const string& region,
const string& service)
{
auto sec = real_clock::to_time_t(timestamp);
struct tm bt;
gmtime_r(&sec, &bt);
auto year = 1900 + bt.tm_year;
auto mon = bt.tm_mon + 1;
auto day = bt.tm_mday;
return fmt::format(FMT_STRING("{:d}{:02d}{:02d}/{:s}/{:s}/aws4_request"),
year, mon, day, region, service);
}
std::string get_v4_canonical_qs(const req_info& info, const bool using_qs)
{
const std::string *params = &info.request_params;
std::string copy_params;
if (params->empty()) {
/* Optimize the typical flow. */
return std::string();
}
if (params->find_first_of('+') != std::string::npos) {
copy_params = *params;
boost::replace_all(copy_params, "+", "%20");
params = ©_params;
}
/* Handle case when query string exists. Step 3 described in: http://docs.
* aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html */
std::map<std::string, std::string> canonical_qs_map;
for (const auto& s : get_str_vec<5>(*params, "&")) {
std::string_view key, val;
const auto parsed_pair = parse_key_value(s);
if (parsed_pair) {
std::tie(key, val) = *parsed_pair;
} else {
/* Handling a parameter without any value (even the empty one). That's
* it, we've encountered something like "this_param&other_param=val"
* which is used by S3 for subresources. */
key = s;
}
if (using_qs && boost::iequals(key, "X-Amz-Signature")) {
/* Preserving the original behaviour of get_v4_canonical_qs() here. */
continue;
}
// while awsv4 specs ask for all slashes to be encoded, s3 itself is relaxed
// in its implementation allowing non-url-encoded slashes to be present in
// presigned urls for instance
canonical_qs_map[aws4_uri_recode(key, true)] = aws4_uri_recode(val, true);
}
/* Thanks to the early exist we have the guarantee that canonical_qs_map has
* at least one element. */
auto iter = std::begin(canonical_qs_map);
std::string canonical_qs;
canonical_qs.append(iter->first)
.append("=", ::strlen("="))
.append(iter->second);
for (iter++; iter != std::end(canonical_qs_map); iter++) {
canonical_qs.append("&", ::strlen("&"))
.append(iter->first)
.append("=", ::strlen("="))
.append(iter->second);
}
return canonical_qs;
}
static void add_v4_canonical_params_from_map(const map<string, string>& m,
std::map<string, string> *result,
bool is_non_s3_op)
{
for (auto& entry : m) {
const auto& key = entry.first;
if (key.empty() || (is_non_s3_op && key == "PayloadHash")) {
continue;
}
(*result)[aws4_uri_recode(key, true)] = aws4_uri_recode(entry.second, true);
}
}
std::string gen_v4_canonical_qs(const req_info& info, bool is_non_s3_op)
{
std::map<std::string, std::string> canonical_qs_map;
add_v4_canonical_params_from_map(info.args.get_params(), &canonical_qs_map, is_non_s3_op);
add_v4_canonical_params_from_map(info.args.get_sys_params(), &canonical_qs_map, false);
if (canonical_qs_map.empty()) {
return string();
}
/* Thanks to the early exit we have the guarantee that canonical_qs_map has
* at least one element. */
auto iter = std::begin(canonical_qs_map);
std::string canonical_qs;
canonical_qs.append(iter->first)
.append("=", ::strlen("="))
.append(iter->second);
for (iter++; iter != std::end(canonical_qs_map); iter++) {
canonical_qs.append("&", ::strlen("&"))
.append(iter->first)
.append("=", ::strlen("="))
.append(iter->second);
}
return canonical_qs;
}
boost::optional<std::string>
get_v4_canonical_headers(const req_info& info,
const std::string_view& signedheaders,
const bool using_qs,
const bool force_boto2_compat)
{
std::map<std::string_view, std::string> canonical_hdrs_map;
for (const auto& token : get_str_vec<5>(signedheaders, ";")) {
/* TODO(rzarzynski): we'd like to switch to sstring here but it should
* get push_back() and reserve() first. */
std::string token_env = "HTTP_";
token_env.reserve(token.length() + std::strlen("HTTP_") + 1);
std::transform(std::begin(token), std::end(token),
std::back_inserter(token_env), [](const int c) {
return c == '-' ? '_' : c == '_' ? '-' : std::toupper(c);
});
if (token_env == "HTTP_CONTENT_LENGTH") {
token_env = "CONTENT_LENGTH";
} else if (token_env == "HTTP_CONTENT_TYPE") {
token_env = "CONTENT_TYPE";
}
const char* const t = info.env->get(token_env.c_str());
if (!t) {
dout(10) << "warning env var not available " << token_env.c_str() << dendl;
continue;
}
std::string token_value(t);
if (token_env == "HTTP_CONTENT_MD5" &&
!std::all_of(std::begin(token_value), std::end(token_value),
is_base64_for_content_md5)) {
dout(0) << "NOTICE: bad content-md5 provided (not base64)"
<< ", aborting request" << dendl;
return boost::none;
}
if (force_boto2_compat && using_qs && token == "host") {
std::string_view port = info.env->get("SERVER_PORT", "");
std::string_view secure_port = info.env->get("SERVER_PORT_SECURE", "");
if (!secure_port.empty()) {
if (secure_port != "443")
token_value.append(":", std::strlen(":"))
.append(secure_port.data(), secure_port.length());
} else if (!port.empty()) {
if (port != "80")
token_value.append(":", std::strlen(":"))
.append(port.data(), port.length());
}
}
canonical_hdrs_map[token] = rgw_trim_whitespace(token_value);
}
std::string canonical_hdrs;
for (const auto& header : canonical_hdrs_map) {
const std::string_view& name = header.first;
std::string value = header.second;
boost::trim_all<std::string>(value);
canonical_hdrs.append(name.data(), name.length())
.append(":", std::strlen(":"))
.append(value)
.append("\n", std::strlen("\n"));
}
return canonical_hdrs;
}
static void handle_header(const string& header, const string& val,
std::map<std::string, std::string> *canonical_hdrs_map)
{
/* TODO(rzarzynski): we'd like to switch to sstring here but it should
* get push_back() and reserve() first. */
std::string token;
token.reserve(header.length());
if (header == "HTTP_CONTENT_LENGTH") {
token = "content-length";
} else if (header == "HTTP_CONTENT_TYPE") {
token = "content-type";
} else {
auto start = std::begin(header);
if (boost::algorithm::starts_with(header, "HTTP_")) {
start += 5; /* len("HTTP_") */
}
std::transform(start, std::end(header),
std::back_inserter(token), [](const int c) {
return c == '_' ? '-' : std::tolower(c);
});
}
(*canonical_hdrs_map)[token] = rgw_trim_whitespace(val);
}
std::string gen_v4_canonical_headers(const req_info& info,
const map<string, string>& extra_headers,
string *signed_hdrs)
{
std::map<std::string, std::string> canonical_hdrs_map;
for (auto& entry : info.env->get_map()) {
handle_header(entry.first, entry.second, &canonical_hdrs_map);
}
for (auto& entry : extra_headers) {
handle_header(entry.first, entry.second, &canonical_hdrs_map);
}
std::string canonical_hdrs;
signed_hdrs->clear();
for (const auto& header : canonical_hdrs_map) {
const auto& name = header.first;
std::string value = header.second;
boost::trim_all<std::string>(value);
if (!signed_hdrs->empty()) {
signed_hdrs->append(";");
}
signed_hdrs->append(name);
canonical_hdrs.append(name.data(), name.length())
.append(":", std::strlen(":"))
.append(value)
.append("\n", std::strlen("\n"));
}
return canonical_hdrs;
}
/*
* create canonical request for signature version 4
*
* http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html
*/
sha256_digest_t
get_v4_canon_req_hash(CephContext* cct,
const std::string_view& http_verb,
const std::string& canonical_uri,
const std::string& canonical_qs,
const std::string& canonical_hdrs,
const std::string_view& signed_hdrs,
const std::string_view& request_payload_hash,
const DoutPrefixProvider *dpp)
{
ldpp_dout(dpp, 10) << "payload request hash = " << request_payload_hash << dendl;
const auto canonical_req = string_join_reserve("\n",
http_verb,
canonical_uri,
canonical_qs,
canonical_hdrs,
signed_hdrs,
request_payload_hash);
const auto canonical_req_hash = calc_hash_sha256(canonical_req);
using sanitize = rgw::crypt_sanitize::log_content;
ldpp_dout(dpp, 10) << "canonical request = " << sanitize{canonical_req} << dendl;
ldpp_dout(dpp, 10) << "canonical request hash = "
<< canonical_req_hash << dendl;
return canonical_req_hash;
}
/*
* create string to sign for signature version 4
*
* http://docs.aws.amazon.com/general/latest/gr/sigv4-create-string-to-sign.html
*/
AWSEngine::VersionAbstractor::string_to_sign_t
get_v4_string_to_sign(CephContext* const cct,
const std::string_view& algorithm,
const std::string_view& request_date,
const std::string_view& credential_scope,
const sha256_digest_t& canonreq_hash,
const DoutPrefixProvider *dpp)
{
const auto hexed_cr_hash = canonreq_hash.to_str();
const std::string_view hexed_cr_hash_str(hexed_cr_hash);
const auto string_to_sign = string_join_reserve("\n",
algorithm,
request_date,
credential_scope,
hexed_cr_hash_str);
ldpp_dout(dpp, 10) << "string to sign = "
<< rgw::crypt_sanitize::log_content{string_to_sign}
<< dendl;
return string_to_sign;
}
static inline std::tuple<std::string_view, /* date */
std::string_view, /* region */
std::string_view> /* service */
parse_cred_scope(std::string_view credential_scope)
{
/* date cred */
size_t pos = credential_scope.find("/");
const auto date_cs = credential_scope.substr(0, pos);
credential_scope = credential_scope.substr(pos + 1);
/* region cred */
pos = credential_scope.find("/");
const auto region_cs = credential_scope.substr(0, pos);
credential_scope = credential_scope.substr(pos + 1);
/* service cred */
pos = credential_scope.find("/");
const auto service_cs = credential_scope.substr(0, pos);
return std::make_tuple(date_cs, region_cs, service_cs);
}
static inline std::vector<unsigned char>
transform_secret_key(const std::string_view& secret_access_key)
{
/* TODO(rzarzynski): switch to constexpr when C++14 becomes available. */
static const std::initializer_list<unsigned char> AWS4 { 'A', 'W', 'S', '4' };
/* boost::container::small_vector might be used here if someone wants to
* optimize out even more dynamic allocations. */
std::vector<unsigned char> secret_key_utf8;
secret_key_utf8.reserve(AWS4.size() + secret_access_key.size());
secret_key_utf8.assign(AWS4);
for (const auto c : secret_access_key) {
std::array<unsigned char, MAX_UTF8_SZ> buf;
const size_t n = encode_utf8(c, buf.data());
secret_key_utf8.insert(std::end(secret_key_utf8),
std::begin(buf), std::begin(buf) + n);
}
return secret_key_utf8;
}
/*
* calculate the SigningKey of AWS auth version 4
*/
static sha256_digest_t
get_v4_signing_key(CephContext* const cct,
const std::string_view& credential_scope,
const std::string_view& secret_access_key,
const DoutPrefixProvider *dpp)
{
std::string_view date, region, service;
std::tie(date, region, service) = parse_cred_scope(credential_scope);
const auto utfed_sec_key = transform_secret_key(secret_access_key);
const auto date_k = calc_hmac_sha256(utfed_sec_key, date);
const auto region_k = calc_hmac_sha256(date_k, region);
const auto service_k = calc_hmac_sha256(region_k, service);
/* aws4_request */
const auto signing_key = calc_hmac_sha256(service_k,
std::string_view("aws4_request"));
ldpp_dout(dpp, 10) << "date_k = " << date_k << dendl;
ldpp_dout(dpp, 10) << "region_k = " << region_k << dendl;
ldpp_dout(dpp, 10) << "service_k = " << service_k << dendl;
ldpp_dout(dpp, 10) << "signing_k = " << signing_key << dendl;
return signing_key;
}
/*
* calculate the AWS signature version 4
*
* http://docs.aws.amazon.com/general/latest/gr/sigv4-calculate-signature.html
*
* srv_signature_t is an alias over Ceph's basic_sstring. We're using
* it to keep everything within the stack boundaries instead of doing
* dynamic allocations.
*/
AWSEngine::VersionAbstractor::server_signature_t
get_v4_signature(const std::string_view& credential_scope,
CephContext* const cct,
const std::string_view& secret_key,
const AWSEngine::VersionAbstractor::string_to_sign_t& string_to_sign,
const DoutPrefixProvider *dpp)
{
auto signing_key = get_v4_signing_key(cct, credential_scope, secret_key, dpp);
/* The server-side generated digest for comparison. */
const auto digest = calc_hmac_sha256(signing_key, string_to_sign);
/* TODO(rzarzynski): I would love to see our sstring having reserve() and
* the non-const data() variant like C++17's std::string. */
using srv_signature_t = AWSEngine::VersionAbstractor::server_signature_t;
srv_signature_t signature(srv_signature_t::initialized_later(),
digest.SIZE * 2);
buf_to_hex(digest.v, digest.SIZE, signature.begin());
ldpp_dout(dpp, 10) << "generated signature = " << signature << dendl;
return signature;
}
AWSEngine::VersionAbstractor::server_signature_t
get_v2_signature(CephContext* const cct,
const std::string& secret_key,
const AWSEngine::VersionAbstractor::string_to_sign_t& string_to_sign)
{
if (secret_key.empty()) {
throw -EINVAL;
}
const auto digest = calc_hmac_sha1(secret_key, string_to_sign);
/* 64 is really enough */;
char buf[64];
const int ret = ceph_armor(std::begin(buf),
std::begin(buf) + 64,
reinterpret_cast<const char *>(digest.v),
reinterpret_cast<const char *>(digest.v + digest.SIZE));
if (ret < 0) {
ldout(cct, 10) << "ceph_armor failed" << dendl;
throw ret;
} else {
buf[ret] = '\0';
using srv_signature_t = AWSEngine::VersionAbstractor::server_signature_t;
return srv_signature_t(buf, ret);
}
}
bool AWSv4ComplMulti::ChunkMeta::is_new_chunk_in_stream(size_t stream_pos) const
{
return stream_pos >= (data_offset_in_stream + data_length);
}
size_t AWSv4ComplMulti::ChunkMeta::get_data_size(size_t stream_pos) const
{
if (stream_pos > (data_offset_in_stream + data_length)) {
/* Data in parsing_buf. */
return data_length;
} else {
return data_offset_in_stream + data_length - stream_pos;
}
}
/* AWSv4 completers begin. */
std::pair<AWSv4ComplMulti::ChunkMeta, size_t /* consumed */>
AWSv4ComplMulti::ChunkMeta::create_next(CephContext* const cct,
ChunkMeta&& old,
const char* const metabuf,
const size_t metabuf_len)
{
std::string_view metastr(metabuf, metabuf_len);
const size_t semicolon_pos = metastr.find(";");
if (semicolon_pos == std::string_view::npos) {
ldout(cct, 20) << "AWSv4ComplMulti cannot find the ';' separator"
<< dendl;
throw rgw::io::Exception(EINVAL, std::system_category());
}
char* data_field_end;
/* strtoull ignores the "\r\n" sequence after each non-first chunk. */
const size_t data_length = std::strtoull(metabuf, &data_field_end, 16);
if (data_length == 0 && data_field_end == metabuf) {
ldout(cct, 20) << "AWSv4ComplMulti: cannot parse the data size"
<< dendl;
throw rgw::io::Exception(EINVAL, std::system_category());
}
/* Parse the chunk_signature=... part. */
const auto signature_part = metastr.substr(semicolon_pos + 1);
const size_t eq_sign_pos = signature_part.find("=");
if (eq_sign_pos == std::string_view::npos) {
ldout(cct, 20) << "AWSv4ComplMulti: cannot find the '=' separator"
<< dendl;
throw rgw::io::Exception(EINVAL, std::system_category());
}
/* OK, we have at least the beginning of a signature. */
const size_t data_sep_pos = signature_part.find("\r\n");
if (data_sep_pos == std::string_view::npos) {
ldout(cct, 20) << "AWSv4ComplMulti: no new line at signature end"
<< dendl;
throw rgw::io::Exception(EINVAL, std::system_category());
}
const auto signature = \
signature_part.substr(eq_sign_pos + 1, data_sep_pos - 1 - eq_sign_pos);
if (signature.length() != SIG_SIZE) {
ldout(cct, 20) << "AWSv4ComplMulti: signature.length() != 64"
<< dendl;
throw rgw::io::Exception(EINVAL, std::system_category());
}
const size_t data_starts_in_stream = \
+ semicolon_pos + strlen(";") + data_sep_pos + strlen("\r\n")
+ old.data_offset_in_stream + old.data_length;
ldout(cct, 20) << "parsed new chunk; signature=" << signature
<< ", data_length=" << data_length
<< ", data_starts_in_stream=" << data_starts_in_stream
<< dendl;
return std::make_pair(ChunkMeta(data_starts_in_stream,
data_length,
signature),
semicolon_pos + 83);
}
std::string
AWSv4ComplMulti::calc_chunk_signature(const std::string& payload_hash) const
{
const auto string_to_sign = string_join_reserve("\n",
AWS4_HMAC_SHA256_PAYLOAD_STR,
date,
credential_scope,
prev_chunk_signature,
AWS4_EMPTY_PAYLOAD_HASH,
payload_hash);
ldout(cct, 20) << "AWSv4ComplMulti: string_to_sign=\n" << string_to_sign
<< dendl;
/* new chunk signature */
const auto sig = calc_hmac_sha256(signing_key, string_to_sign);
/* FIXME(rzarzynski): std::string here is really unnecessary. */
return sig.to_str();
}
bool AWSv4ComplMulti::is_signature_mismatched()
{
/* The validity of previous chunk can be verified only after getting meta-
* data of the next one. */
const auto payload_hash = calc_hash_sha256_restart_stream(&sha256_hash);
const auto calc_signature = calc_chunk_signature(payload_hash);
if (chunk_meta.get_signature() != calc_signature) {
ldout(cct, 20) << "AWSv4ComplMulti: ERROR: chunk signature mismatch"
<< dendl;
ldout(cct, 20) << "AWSv4ComplMulti: declared signature="
<< chunk_meta.get_signature() << dendl;
ldout(cct, 20) << "AWSv4ComplMulti: calculated signature="
<< calc_signature << dendl;
return true;
} else {
prev_chunk_signature = chunk_meta.get_signature();
return false;
}
}
size_t AWSv4ComplMulti::recv_body(char* const buf, const size_t buf_max)
{
/* Buffer stores only parsed stream. Raw values reflect the stream
* we're getting from a client. */
size_t buf_pos = 0;
if (chunk_meta.is_new_chunk_in_stream(stream_pos)) {
/* Verify signature of the previous chunk. We aren't doing that for new
* one as the procedure requires calculation of payload hash. This code
* won't be triggered for the last, zero-length chunk. Instead, is will
* be checked in the complete() method. */
if (stream_pos >= ChunkMeta::META_MAX_SIZE && is_signature_mismatched()) {
throw rgw::io::Exception(ERR_SIGNATURE_NO_MATCH, std::system_category());
}
/* We don't have metadata for this range. This means a new chunk, so we
* need to parse a fresh portion of the stream. Let's start. */
size_t to_extract = parsing_buf.capacity() - parsing_buf.size();
do {
const size_t orig_size = parsing_buf.size();
parsing_buf.resize(parsing_buf.size() + to_extract);
const size_t received = io_base_t::recv_body(parsing_buf.data() + orig_size,
to_extract);
parsing_buf.resize(parsing_buf.size() - (to_extract - received));
if (received == 0) {
break;
}
stream_pos += received;
to_extract -= received;
} while (to_extract > 0);
size_t consumed;
std::tie(chunk_meta, consumed) = \
ChunkMeta::create_next(cct, std::move(chunk_meta),
parsing_buf.data(), parsing_buf.size());
/* We can drop the bytes consumed during metadata parsing. The remainder
* can be chunk's data plus possibly beginning of next chunks' metadata. */
parsing_buf.erase(std::begin(parsing_buf),
std::begin(parsing_buf) + consumed);
}
size_t stream_pos_was = stream_pos - parsing_buf.size();
size_t to_extract = \
std::min(chunk_meta.get_data_size(stream_pos_was), buf_max);
dout(30) << "AWSv4ComplMulti: stream_pos_was=" << stream_pos_was << ", to_extract=" << to_extract << dendl;
/* It's quite probable we have a couple of real data bytes stored together
* with meta-data in the parsing_buf. We need to extract them and move to
* the final buffer. This is a trade-off between frontend's read overhead
* and memcpy. */
if (to_extract > 0 && parsing_buf.size() > 0) {
const auto data_len = std::min(to_extract, parsing_buf.size());
const auto data_end_iter = std::begin(parsing_buf) + data_len;
dout(30) << "AWSv4ComplMulti: to_extract=" << to_extract << ", data_len=" << data_len << dendl;
std::copy(std::begin(parsing_buf), data_end_iter, buf);
parsing_buf.erase(std::begin(parsing_buf), data_end_iter);
calc_hash_sha256_update_stream(sha256_hash, buf, data_len);
to_extract -= data_len;
buf_pos += data_len;
}
/* Now we can do the bulk read directly from RestfulClient without any extra
* buffering. */
while (to_extract > 0) {
const size_t received = io_base_t::recv_body(buf + buf_pos, to_extract);
dout(30) << "AWSv4ComplMulti: to_extract=" << to_extract << ", received=" << received << dendl;
if (received == 0) {
break;
}
calc_hash_sha256_update_stream(sha256_hash, buf + buf_pos, received);
buf_pos += received;
stream_pos += received;
to_extract -= received;
}
dout(20) << "AWSv4ComplMulti: filled=" << buf_pos << dendl;
return buf_pos;
}
void AWSv4ComplMulti::modify_request_state(const DoutPrefixProvider* dpp, req_state* const s_rw)
{
const char* const decoded_length = \
s_rw->info.env->get("HTTP_X_AMZ_DECODED_CONTENT_LENGTH");
if (!decoded_length) {
throw -EINVAL;
} else {
s_rw->length = decoded_length;
s_rw->content_length = parse_content_length(decoded_length);
if (s_rw->content_length < 0) {
ldpp_dout(dpp, 10) << "negative AWSv4's content length, aborting" << dendl;
throw -EINVAL;
}
}
/* Install the filter over rgw::io::RestfulClient. */
AWS_AUTHv4_IO(s_rw)->add_filter(
std::static_pointer_cast<io_base_t>(shared_from_this()));
}
bool AWSv4ComplMulti::complete()
{
/* Now it's time to verify the signature of the last, zero-length chunk. */
if (is_signature_mismatched()) {
ldout(cct, 10) << "ERROR: signature of last chunk does not match"
<< dendl;
return false;
} else {
return true;
}
}
rgw::auth::Completer::cmplptr_t
AWSv4ComplMulti::create(const req_state* const s,
std::string_view date,
std::string_view credential_scope,
std::string_view seed_signature,
const boost::optional<std::string>& secret_key)
{
if (!secret_key) {
/* Some external authorizers (like Keystone) aren't fully compliant with
* AWSv4. They do not provide the secret_key which is necessary to handle
* the streamed upload. */
throw -ERR_NOT_IMPLEMENTED;
}
const auto signing_key = \
rgw::auth::s3::get_v4_signing_key(s->cct, credential_scope, *secret_key, s);
return std::make_shared<AWSv4ComplMulti>(s,
std::move(date),
std::move(credential_scope),
std::move(seed_signature),
signing_key);
}
size_t AWSv4ComplSingle::recv_body(char* const buf, const size_t max)
{
const auto received = io_base_t::recv_body(buf, max);
calc_hash_sha256_update_stream(sha256_hash, buf, received);
return received;
}
void AWSv4ComplSingle::modify_request_state(const DoutPrefixProvider* dpp, req_state* const s_rw)
{
/* Install the filter over rgw::io::RestfulClient. */
AWS_AUTHv4_IO(s_rw)->add_filter(
std::static_pointer_cast<io_base_t>(shared_from_this()));
}
bool AWSv4ComplSingle::complete()
{
/* The completer is only for the cases where signed payload has been
* requested. It won't be used, for instance, during the query string-based
* authentication. */
const auto payload_hash = calc_hash_sha256_close_stream(&sha256_hash);
/* Validate x-amz-sha256 */
if (payload_hash.compare(expected_request_payload_hash) == 0) {
return true;
} else {
ldout(cct, 10) << "ERROR: x-amz-content-sha256 does not match"
<< dendl;
ldout(cct, 10) << "ERROR: grab_aws4_sha256_hash()="
<< payload_hash << dendl;
ldout(cct, 10) << "ERROR: expected_request_payload_hash="
<< expected_request_payload_hash << dendl;
return false;
}
}
AWSv4ComplSingle::AWSv4ComplSingle(const req_state* const s)
: io_base_t(nullptr),
cct(s->cct),
expected_request_payload_hash(get_v4_exp_payload_hash(s->info)),
sha256_hash(calc_hash_sha256_open_stream()) {
}
rgw::auth::Completer::cmplptr_t
AWSv4ComplSingle::create(const req_state* const s,
const boost::optional<std::string>&)
{
return std::make_shared<AWSv4ComplSingle>(s);
}
} // namespace rgw::auth::s3
| 42,302 | 31.24314 | 109 |
cc
|
null |
ceph-main/src/rgw/rgw_auth_s3.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#pragma once
#include <array>
#include <memory>
#include <string>
#include <string_view>
#include <tuple>
#include <boost/algorithm/string.hpp>
#include <boost/container/static_vector.hpp>
#include "common/sstring.hh"
#include "rgw_common.h"
#include "rgw_rest_s3.h"
#include "rgw_auth.h"
#include "rgw_auth_filters.h"
#include "rgw_auth_keystone.h"
namespace rgw {
namespace auth {
namespace s3 {
static constexpr auto RGW_AUTH_GRACE = std::chrono::minutes{15};
// returns true if the request time is within RGW_AUTH_GRACE of the current time
bool is_time_skew_ok(time_t t);
class STSAuthStrategy : public rgw::auth::Strategy,
public rgw::auth::RemoteApplier::Factory,
public rgw::auth::LocalApplier::Factory,
public rgw::auth::RoleApplier::Factory {
typedef rgw::auth::IdentityApplier::aplptr_t aplptr_t;
rgw::sal::Driver* driver;
const rgw::auth::ImplicitTenants& implicit_tenant_context;
STSEngine sts_engine;
aplptr_t create_apl_remote(CephContext* const cct,
const req_state* const s,
rgw::auth::RemoteApplier::acl_strategy_t&& acl_alg,
const rgw::auth::RemoteApplier::AuthInfo &info) const override {
auto apl = rgw::auth::add_sysreq(cct, driver, s,
rgw::auth::RemoteApplier(cct, driver, std::move(acl_alg), info,
implicit_tenant_context,
rgw::auth::ImplicitTenants::IMPLICIT_TENANTS_S3));
return aplptr_t(new decltype(apl)(std::move(apl)));
}
aplptr_t create_apl_local(CephContext* const cct,
const req_state* const s,
const RGWUserInfo& user_info,
const std::string& subuser,
const std::optional<uint32_t>& perm_mask,
const std::string& access_key_id) const override {
auto apl = rgw::auth::add_sysreq(cct, driver, s,
rgw::auth::LocalApplier(cct, user_info, subuser, perm_mask, access_key_id));
return aplptr_t(new decltype(apl)(std::move(apl)));
}
aplptr_t create_apl_role(CephContext* const cct,
const req_state* const s,
const rgw::auth::RoleApplier::Role& role,
const rgw::auth::RoleApplier::TokenAttrs& token_attrs) const override {
auto apl = rgw::auth::add_sysreq(cct, driver, s,
rgw::auth::RoleApplier(cct, role, token_attrs));
return aplptr_t(new decltype(apl)(std::move(apl)));
}
public:
STSAuthStrategy(CephContext* const cct,
rgw::sal::Driver* driver,
const rgw::auth::ImplicitTenants& implicit_tenant_context,
AWSEngine::VersionAbstractor* const ver_abstractor)
: driver(driver),
implicit_tenant_context(implicit_tenant_context),
sts_engine(cct, driver, *ver_abstractor,
static_cast<rgw::auth::LocalApplier::Factory*>(this),
static_cast<rgw::auth::RemoteApplier::Factory*>(this),
static_cast<rgw::auth::RoleApplier::Factory*>(this)) {
if (cct->_conf->rgw_s3_auth_use_sts) {
add_engine(Control::SUFFICIENT, sts_engine);
}
}
const char* get_name() const noexcept override {
return "rgw::auth::s3::STSAuthStrategy";
}
};
class ExternalAuthStrategy : public rgw::auth::Strategy,
public rgw::auth::RemoteApplier::Factory {
typedef rgw::auth::IdentityApplier::aplptr_t aplptr_t;
rgw::sal::Driver* driver;
const rgw::auth::ImplicitTenants& implicit_tenant_context;
using keystone_config_t = rgw::keystone::CephCtxConfig;
using keystone_cache_t = rgw::keystone::TokenCache;
using secret_cache_t = rgw::auth::keystone::SecretCache;
using EC2Engine = rgw::auth::keystone::EC2Engine;
boost::optional <EC2Engine> keystone_engine;
LDAPEngine ldap_engine;
aplptr_t create_apl_remote(CephContext* const cct,
const req_state* const s,
rgw::auth::RemoteApplier::acl_strategy_t&& acl_alg,
const rgw::auth::RemoteApplier::AuthInfo &info) const override {
auto apl = rgw::auth::add_sysreq(cct, driver, s,
rgw::auth::RemoteApplier(cct, driver, std::move(acl_alg), info,
implicit_tenant_context,
rgw::auth::ImplicitTenants::IMPLICIT_TENANTS_S3));
/* TODO(rzarzynski): replace with static_ptr. */
return aplptr_t(new decltype(apl)(std::move(apl)));
}
public:
ExternalAuthStrategy(CephContext* const cct,
rgw::sal::Driver* driver,
const rgw::auth::ImplicitTenants& implicit_tenant_context,
AWSEngine::VersionAbstractor* const ver_abstractor)
: driver(driver),
implicit_tenant_context(implicit_tenant_context),
ldap_engine(cct, driver, *ver_abstractor,
static_cast<rgw::auth::RemoteApplier::Factory*>(this)) {
if (cct->_conf->rgw_s3_auth_use_keystone &&
! cct->_conf->rgw_keystone_url.empty()) {
keystone_engine.emplace(cct, ver_abstractor,
static_cast<rgw::auth::RemoteApplier::Factory*>(this),
keystone_config_t::get_instance(),
keystone_cache_t::get_instance<keystone_config_t>(),
secret_cache_t::get_instance());
add_engine(Control::SUFFICIENT, *keystone_engine);
}
if (ldap_engine.valid()) {
add_engine(Control::SUFFICIENT, ldap_engine);
}
}
const char* get_name() const noexcept override {
return "rgw::auth::s3::AWSv2ExternalAuthStrategy";
}
};
template <class AbstractorT,
bool AllowAnonAccessT = false>
class AWSAuthStrategy : public rgw::auth::Strategy,
public rgw::auth::LocalApplier::Factory {
typedef rgw::auth::IdentityApplier::aplptr_t aplptr_t;
static_assert(std::is_base_of<rgw::auth::s3::AWSEngine::VersionAbstractor,
AbstractorT>::value,
"AbstractorT must be a subclass of rgw::auth::s3::VersionAbstractor");
rgw::sal::Driver* driver;
AbstractorT ver_abstractor;
S3AnonymousEngine anonymous_engine;
ExternalAuthStrategy external_engines;
STSAuthStrategy sts_engine;
LocalEngine local_engine;
aplptr_t create_apl_local(CephContext* const cct,
const req_state* const s,
const RGWUserInfo& user_info,
const std::string& subuser,
const std::optional<uint32_t>& perm_mask,
const std::string& access_key_id) const override {
auto apl = rgw::auth::add_sysreq(cct, driver, s,
rgw::auth::LocalApplier(cct, user_info, subuser, perm_mask, access_key_id));
/* TODO(rzarzynski): replace with static_ptr. */
return aplptr_t(new decltype(apl)(std::move(apl)));
}
public:
using engine_map_t = std::map <std::string, std::reference_wrapper<const Engine>>;
void add_engines(const std::vector <std::string>& auth_order,
engine_map_t eng_map)
{
auto ctrl_flag = Control::SUFFICIENT;
for (const auto &eng : auth_order) {
// fallback to the last engine, in case of multiple engines, since ctrl
// flag is sufficient for others, error from earlier engine is returned
if (&eng == &auth_order.back() && eng_map.size() > 1) {
ctrl_flag = Control::FALLBACK;
}
if (const auto kv = eng_map.find(eng);
kv != eng_map.end()) {
add_engine(ctrl_flag, kv->second);
}
}
}
auto parse_auth_order(CephContext* const cct)
{
std::vector <std::string> result;
const std::set <std::string_view> allowed_auth = { "sts", "external", "local" };
std::vector <std::string> default_order = { "sts", "external", "local" };
// supplied strings may contain a space, so let's bypass that
boost::split(result, cct->_conf->rgw_s3_auth_order,
boost::is_any_of(", "), boost::token_compress_on);
if (std::any_of(result.begin(), result.end(),
[allowed_auth](std::string_view s)
{ return allowed_auth.find(s) == allowed_auth.end();})){
return default_order;
}
return result;
}
AWSAuthStrategy(CephContext* const cct,
const rgw::auth::ImplicitTenants& implicit_tenant_context,
rgw::sal::Driver* driver)
: driver(driver),
ver_abstractor(cct),
anonymous_engine(cct,
static_cast<rgw::auth::LocalApplier::Factory*>(this)),
external_engines(cct, driver, implicit_tenant_context, &ver_abstractor),
sts_engine(cct, driver, implicit_tenant_context, &ver_abstractor),
local_engine(cct, driver, ver_abstractor,
static_cast<rgw::auth::LocalApplier::Factory*>(this)) {
/* The anonymous auth. */
if (AllowAnonAccessT) {
add_engine(Control::SUFFICIENT, anonymous_engine);
}
auto auth_order = parse_auth_order(cct);
engine_map_t engine_map;
/* STS Auth*/
if (! sts_engine.is_empty()) {
engine_map.insert(std::make_pair("sts", std::cref(sts_engine)));
}
/* The external auth. */
if (! external_engines.is_empty()) {
engine_map.insert(std::make_pair("external", std::cref(external_engines)));
}
/* The local auth. */
if (cct->_conf->rgw_s3_auth_use_rados) {
engine_map.insert(std::make_pair("local", std::cref(local_engine)));
}
add_engines(auth_order, engine_map);
}
const char* get_name() const noexcept override {
return "rgw::auth::s3::AWSAuthStrategy";
}
};
class AWSv4ComplMulti : public rgw::auth::Completer,
public rgw::io::DecoratedRestfulClient<rgw::io::RestfulClient*>,
public std::enable_shared_from_this<AWSv4ComplMulti> {
using io_base_t = rgw::io::DecoratedRestfulClient<rgw::io::RestfulClient*>;
using signing_key_t = sha256_digest_t;
CephContext* const cct;
const std::string_view date;
const std::string_view credential_scope;
const signing_key_t signing_key;
class ChunkMeta {
size_t data_offset_in_stream = 0;
size_t data_length = 0;
std::string signature;
ChunkMeta(const size_t data_starts_in_stream,
const size_t data_length,
const std::string_view signature)
: data_offset_in_stream(data_starts_in_stream),
data_length(data_length),
signature(std::string(signature)) {
}
explicit ChunkMeta(const std::string_view& signature)
: signature(std::string(signature)) {
}
public:
static constexpr size_t SIG_SIZE = 64;
/* Let's suppose the data length fields can't exceed uint64_t. */
static constexpr size_t META_MAX_SIZE = \
sarrlen("\r\nffffffffffffffff;chunk-signature=") + SIG_SIZE + sarrlen("\r\n");
/* The metadata size of for the last, empty chunk. */
static constexpr size_t META_MIN_SIZE = \
sarrlen("0;chunk-signature=") + SIG_SIZE + sarrlen("\r\n");
/* Detect whether a given stream_pos fits in boundaries of a chunk. */
bool is_new_chunk_in_stream(size_t stream_pos) const;
/* Get the remaining data size. */
size_t get_data_size(size_t stream_pos) const;
const std::string& get_signature() const {
return signature;
}
/* Factory: create an object representing metadata of first, initial chunk
* in a stream. */
static ChunkMeta create_first(const std::string_view& seed_signature) {
return ChunkMeta(seed_signature);
}
/* Factory: parse a block of META_MAX_SIZE bytes and creates an object
* representing non-first chunk in a stream. As the process is sequential
* and depends on the previous chunk, caller must pass it. */
static std::pair<ChunkMeta, size_t> create_next(CephContext* cct,
ChunkMeta&& prev,
const char* metabuf,
size_t metabuf_len);
} chunk_meta;
size_t stream_pos;
boost::container::static_vector<char, ChunkMeta::META_MAX_SIZE> parsing_buf;
ceph::crypto::SHA256* sha256_hash;
std::string prev_chunk_signature;
bool is_signature_mismatched();
std::string calc_chunk_signature(const std::string& payload_hash) const;
public:
/* We need the constructor to be public because of the std::make_shared that
* is employed by the create() method. */
AWSv4ComplMulti(const req_state* const s,
std::string_view date,
std::string_view credential_scope,
std::string_view seed_signature,
const signing_key_t& signing_key)
: io_base_t(nullptr),
cct(s->cct),
date(std::move(date)),
credential_scope(std::move(credential_scope)),
signing_key(signing_key),
/* The evolving state. */
chunk_meta(ChunkMeta::create_first(seed_signature)),
stream_pos(0),
sha256_hash(calc_hash_sha256_open_stream()),
prev_chunk_signature(std::move(seed_signature)) {
}
~AWSv4ComplMulti() {
if (sha256_hash) {
calc_hash_sha256_close_stream(&sha256_hash);
}
}
/* rgw::io::DecoratedRestfulClient. */
size_t recv_body(char* buf, size_t max) override;
/* rgw::auth::Completer. */
void modify_request_state(const DoutPrefixProvider* dpp, req_state* s_rw) override;
bool complete() override;
/* Factories. */
static cmplptr_t create(const req_state* s,
std::string_view date,
std::string_view credential_scope,
std::string_view seed_signature,
const boost::optional<std::string>& secret_key);
};
class AWSv4ComplSingle : public rgw::auth::Completer,
public rgw::io::DecoratedRestfulClient<rgw::io::RestfulClient*>,
public std::enable_shared_from_this<AWSv4ComplSingle> {
using io_base_t = rgw::io::DecoratedRestfulClient<rgw::io::RestfulClient*>;
CephContext* const cct;
const char* const expected_request_payload_hash;
ceph::crypto::SHA256* sha256_hash = nullptr;
public:
/* Defined in rgw_auth_s3.cc because of get_v4_exp_payload_hash(). We need
* the constructor to be public because of the std::make_shared employed by
* the create() method. */
explicit AWSv4ComplSingle(const req_state* const s);
~AWSv4ComplSingle() {
if (sha256_hash) {
calc_hash_sha256_close_stream(&sha256_hash);
}
}
/* rgw::io::DecoratedRestfulClient. */
size_t recv_body(char* buf, size_t max) override;
/* rgw::auth::Completer. */
void modify_request_state(const DoutPrefixProvider* dpp, req_state* s_rw) override;
bool complete() override;
/* Factories. */
static cmplptr_t create(const req_state* s,
const boost::optional<std::string>&);
};
} /* namespace s3 */
} /* namespace auth */
} /* namespace rgw */
void rgw_create_s3_canonical_header(
const DoutPrefixProvider *dpp,
const char *method,
const char *content_md5,
const char *content_type,
const char *date,
const meta_map_t& meta_map,
const meta_map_t& qs_map,
const char *request_uri,
const std::map<std::string, std::string>& sub_resources,
std::string& dest_str);
bool rgw_create_s3_canonical_header(const DoutPrefixProvider *dpp,
const req_info& info,
utime_t *header_time, /* out */
std::string& dest, /* out */
bool qsr);
static inline std::tuple<bool, std::string, utime_t>
rgw_create_s3_canonical_header(const DoutPrefixProvider *dpp, const req_info& info, const bool qsr) {
std::string dest;
utime_t header_time;
const bool ok = rgw_create_s3_canonical_header(dpp, info, &header_time, dest, qsr);
return std::make_tuple(ok, dest, header_time);
}
namespace rgw {
namespace auth {
namespace s3 {
static constexpr char AWS4_HMAC_SHA256_STR[] = "AWS4-HMAC-SHA256";
static constexpr char AWS4_HMAC_SHA256_PAYLOAD_STR[] = "AWS4-HMAC-SHA256-PAYLOAD";
static constexpr char AWS4_EMPTY_PAYLOAD_HASH[] = \
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
static constexpr char AWS4_UNSIGNED_PAYLOAD_HASH[] = "UNSIGNED-PAYLOAD";
static constexpr char AWS4_STREAMING_PAYLOAD_HASH[] = \
"STREAMING-AWS4-HMAC-SHA256-PAYLOAD";
bool is_non_s3_op(RGWOpType op_type);
int parse_v4_credentials(const req_info& info, /* in */
std::string_view& access_key_id, /* out */
std::string_view& credential_scope, /* out */
std::string_view& signedheaders, /* out */
std::string_view& signature, /* out */
std::string_view& date, /* out */
std::string_view& session_token, /* out */
const bool using_qs, /* in */
const DoutPrefixProvider *dpp); /* in */
string gen_v4_scope(const ceph::real_time& timestamp,
const string& region,
const string& service);
static inline bool char_needs_aws4_escaping(const char c, bool encode_slash)
{
if ((c >= 'a' && c <= 'z') ||
(c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9')) {
return false;
}
switch (c) {
case '-':
case '_':
case '.':
case '~':
return false;
}
if (c == '/' && !encode_slash)
return false;
return true;
}
static inline std::string aws4_uri_encode(const std::string& src, bool encode_slash)
{
std::string result;
for (const std::string::value_type c : src) {
if (char_needs_aws4_escaping(c, encode_slash)) {
rgw_uri_escape_char(c, result);
} else {
result.push_back(c);
}
}
return result;
}
static inline std::string aws4_uri_recode(const std::string_view& src, bool encode_slash)
{
std::string decoded = url_decode(src);
return aws4_uri_encode(decoded, encode_slash);
}
static inline std::string get_v4_canonical_uri(const req_info& info) {
/* The code should normalize according to RFC 3986 but S3 does NOT do path
* normalization that SigV4 typically does. This code follows the same
* approach that boto library. See auth.py:canonical_uri(...). */
std::string canonical_uri = aws4_uri_recode(info.request_uri_aws4, false);
if (canonical_uri.empty()) {
canonical_uri = "/";
} else {
boost::replace_all(canonical_uri, "+", "%20");
}
return canonical_uri;
}
static inline std::string gen_v4_canonical_uri(const req_info& info) {
/* The code should normalize according to RFC 3986 but S3 does NOT do path
* normalization that SigV4 typically does. This code follows the same
* approach that boto library. See auth.py:canonical_uri(...). */
std::string canonical_uri = aws4_uri_recode(info.request_uri, false);
if (canonical_uri.empty()) {
canonical_uri = "/";
} else {
boost::replace_all(canonical_uri, "+", "%20");
}
return canonical_uri;
}
static inline const string calc_v4_payload_hash(const string& payload)
{
ceph::crypto::SHA256* sha256_hash = calc_hash_sha256_open_stream();
calc_hash_sha256_update_stream(sha256_hash, payload.c_str(), payload.length());
const auto payload_hash = calc_hash_sha256_close_stream(&sha256_hash);
return payload_hash;
}
static inline const char* get_v4_exp_payload_hash(const req_info& info)
{
/* In AWSv4 the hash of real, transferred payload IS NOT necessary to form
* a Canonical Request, and thus verify a Signature. x-amz-content-sha256
* header lets get the information very early -- before seeing first byte
* of HTTP body. As a consequence, we can decouple Signature verification
* from payload's fingerprint check. */
const char *expected_request_payload_hash = \
info.env->get("HTTP_X_AMZ_CONTENT_SHA256");
if (!expected_request_payload_hash) {
/* An HTTP client MUST send x-amz-content-sha256. The single exception
* is the case of using the Query Parameters where "UNSIGNED-PAYLOAD"
* literals are used for crafting Canonical Request:
*
* You don't include a payload hash in the Canonical Request, because
* when you create a presigned URL, you don't know the payload content
* because the URL is used to upload an arbitrary payload. Instead, you
* use a constant string UNSIGNED-PAYLOAD. */
expected_request_payload_hash = AWS4_UNSIGNED_PAYLOAD_HASH;
}
return expected_request_payload_hash;
}
static inline bool is_v4_payload_unsigned(const char* const exp_payload_hash)
{
return boost::equals(exp_payload_hash, AWS4_UNSIGNED_PAYLOAD_HASH);
}
static inline bool is_v4_payload_empty(const req_state* const s)
{
/* from rfc2616 - 4.3 Message Body
*
* "The presence of a message-body in a request is signaled by the inclusion
* of a Content-Length or Transfer-Encoding header field in the request's
* message-headers." */
return s->content_length == 0 &&
s->info.env->get("HTTP_TRANSFER_ENCODING") == nullptr;
}
static inline bool is_v4_payload_streamed(const char* const exp_payload_hash)
{
return boost::equals(exp_payload_hash, AWS4_STREAMING_PAYLOAD_HASH);
}
std::string get_v4_canonical_qs(const req_info& info, bool using_qs);
std::string gen_v4_canonical_qs(const req_info& info, bool is_non_s3_op);
boost::optional<std::string>
get_v4_canonical_headers(const req_info& info,
const std::string_view& signedheaders,
bool using_qs,
bool force_boto2_compat);
std::string gen_v4_canonical_headers(const req_info& info,
const std::map<std::string, std::string>& extra_headers,
string *signed_hdrs);
extern sha256_digest_t
get_v4_canon_req_hash(CephContext* cct,
const std::string_view& http_verb,
const std::string& canonical_uri,
const std::string& canonical_qs,
const std::string& canonical_hdrs,
const std::string_view& signed_hdrs,
const std::string_view& request_payload_hash,
const DoutPrefixProvider *dpp);
AWSEngine::VersionAbstractor::string_to_sign_t
get_v4_string_to_sign(CephContext* cct,
const std::string_view& algorithm,
const std::string_view& request_date,
const std::string_view& credential_scope,
const sha256_digest_t& canonreq_hash,
const DoutPrefixProvider *dpp);
extern AWSEngine::VersionAbstractor::server_signature_t
get_v4_signature(const std::string_view& credential_scope,
CephContext* const cct,
const std::string_view& secret_key,
const AWSEngine::VersionAbstractor::string_to_sign_t& string_to_sign,
const DoutPrefixProvider *dpp);
extern AWSEngine::VersionAbstractor::server_signature_t
get_v2_signature(CephContext*,
const std::string& secret_key,
const AWSEngine::VersionAbstractor::string_to_sign_t& string_to_sign);
} /* namespace s3 */
} /* namespace auth */
} /* namespace rgw */
| 23,640 | 35.539413 | 101 |
h
|
null |
ceph-main/src/rgw/rgw_b64.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#pragma once
#include <boost/archive/iterators/base64_from_binary.hpp>
#include <boost/archive/iterators/binary_from_base64.hpp>
#include <boost/archive/iterators/insert_linebreaks.hpp>
#include <boost/archive/iterators/transform_width.hpp>
#include <boost/archive/iterators/remove_whitespace.hpp>
#include <limits>
#include <string>
#include <string_view>
namespace rgw {
/*
* A header-only Base64 encoder built on boost::archive. The
* formula is based on a class poposed for inclusion in boost in
* 2011 by Denis Shevchenko (abandoned), updated slightly
* (e.g., uses std::string_view).
*
* Also, wrap_width added as template argument, based on
* feedback from Marcus.
*/
template<int wrap_width = std::numeric_limits<int>::max()>
inline std::string to_base64(std::string_view sview)
{
using namespace boost::archive::iterators;
// output must be =padded modulo 3
auto psize = sview.size();
while ((psize % 3) != 0) {
++psize;
}
/* RFC 2045 requires linebreaks to be present in the output
* sequence every at-most 76 characters (MIME-compliance),
* but we could likely omit it. */
typedef
insert_linebreaks<
base64_from_binary<
transform_width<
std::string_view::const_iterator
,6,8>
>
,wrap_width
> b64_iter;
std::string outstr(b64_iter(sview.data()),
b64_iter(sview.data() + sview.size()));
// pad outstr with '=' to a length that is a multiple of 3
for (size_t ix = 0; ix < (psize-sview.size()); ++ix)
outstr.push_back('=');
return outstr;
}
inline std::string from_base64(std::string_view sview)
{
using namespace boost::archive::iterators;
if (sview.empty())
return std::string();
/* MIME-compliant input will have line-breaks, so we have to
* filter WS */
typedef
transform_width<
binary_from_base64<
remove_whitespace<
std::string_view::const_iterator>>
,8,6
> b64_iter;
while (sview.back() == '=')
sview.remove_suffix(1);
std::string outstr(b64_iter(sview.data()),
b64_iter(sview.data() + sview.size()));
return outstr;
}
} /* namespace */
| 2,336 | 26.494118 | 70 |
h
|
null |
ceph-main/src/rgw/rgw_basic_types.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include <iostream>
#include <sstream>
#include <string>
#include "cls/user/cls_user_types.h"
#include "rgw_basic_types.h"
#include "rgw_bucket.h"
#include "rgw_xml.h"
#include "common/ceph_json.h"
#include "common/Formatter.h"
#include "cls/user/cls_user_types.h"
#include "cls/rgw/cls_rgw_types.h"
using std::ostream;
using std::string;
using std::stringstream;
using namespace std;
void decode_json_obj(rgw_user& val, JSONObj *obj)
{
val.from_str(obj->get_data());
}
void encode_json(const char *name, const rgw_user& val, Formatter *f)
{
f->dump_string(name, val.to_str());
}
void encode_xml(const char *name, const rgw_user& val, Formatter *f)
{
encode_xml(name, val.to_str(), f);
}
rgw_bucket::rgw_bucket(const rgw_user& u, const cls_user_bucket& b) :
tenant(u.tenant),
name(b.name),
marker(b.marker),
bucket_id(b.bucket_id),
explicit_placement(b.explicit_placement.data_pool,
b.explicit_placement.data_extra_pool,
b.explicit_placement.index_pool)
{
}
void rgw_bucket::convert(cls_user_bucket *b) const
{
b->name = name;
b->marker = marker;
b->bucket_id = bucket_id;
b->explicit_placement.data_pool = explicit_placement.data_pool.to_str();
b->explicit_placement.data_extra_pool = explicit_placement.data_extra_pool.to_str();
b->explicit_placement.index_pool = explicit_placement.index_pool.to_str();
}
std::string rgw_bucket::get_key(char tenant_delim, char id_delim, size_t reserve) const
{
const size_t max_len = tenant.size() + sizeof(tenant_delim) +
name.size() + sizeof(id_delim) + bucket_id.size() + reserve;
std::string key;
key.reserve(max_len);
if (!tenant.empty() && tenant_delim) {
key.append(tenant);
key.append(1, tenant_delim);
}
key.append(name);
if (!bucket_id.empty() && id_delim) {
key.append(1, id_delim);
key.append(bucket_id);
}
return key;
}
void rgw_bucket::generate_test_instances(list<rgw_bucket*>& o)
{
rgw_bucket *b = new rgw_bucket;
init_bucket(b, "tenant", "name", "pool", ".index_pool", "marker", "123");
o.push_back(b);
o.push_back(new rgw_bucket);
}
std::string rgw_bucket_shard::get_key(char tenant_delim, char id_delim,
char shard_delim, size_t reserve) const
{
static constexpr size_t shard_len{12}; // ":4294967295\0"
auto key = bucket.get_key(tenant_delim, id_delim, reserve + shard_len);
if (shard_id >= 0 && shard_delim) {
key.append(1, shard_delim);
key.append(std::to_string(shard_id));
}
return key;
}
void encode(const rgw_bucket_shard& b, bufferlist& bl, uint64_t f)
{
encode(b.bucket, bl, f);
encode(b.shard_id, bl, f);
}
void decode(rgw_bucket_shard& b, bufferlist::const_iterator& bl)
{
decode(b.bucket, bl);
decode(b.shard_id, bl);
}
void encode_json_impl(const char *name, const rgw_zone_id& zid, Formatter *f)
{
encode_json(name, zid.id, f);
}
void decode_json_obj(rgw_zone_id& zid, JSONObj *obj)
{
decode_json_obj(zid.id, obj);
}
void rgw_user::generate_test_instances(list<rgw_user*>& o)
{
rgw_user *u = new rgw_user("tenant", "user");
o.push_back(u);
o.push_back(new rgw_user);
}
void rgw_data_placement_target::dump(Formatter *f) const
{
encode_json("data_pool", data_pool, f);
encode_json("data_extra_pool", data_extra_pool, f);
encode_json("index_pool", index_pool, f);
}
void rgw_data_placement_target::decode_json(JSONObj *obj) {
JSONDecoder::decode_json("data_pool", data_pool, obj);
JSONDecoder::decode_json("data_extra_pool", data_extra_pool, obj);
JSONDecoder::decode_json("index_pool", index_pool, obj);
}
void rgw_bucket::dump(Formatter *f) const
{
encode_json("name", name, f);
encode_json("marker", marker, f);
encode_json("bucket_id", bucket_id, f);
encode_json("tenant", tenant, f);
encode_json("explicit_placement", explicit_placement, f);
}
void rgw_bucket::decode_json(JSONObj *obj) {
JSONDecoder::decode_json("name", name, obj);
JSONDecoder::decode_json("marker", marker, obj);
JSONDecoder::decode_json("bucket_id", bucket_id, obj);
JSONDecoder::decode_json("tenant", tenant, obj);
JSONDecoder::decode_json("explicit_placement", explicit_placement, obj);
if (explicit_placement.data_pool.empty()) {
/* decoding old format */
JSONDecoder::decode_json("pool", explicit_placement.data_pool, obj);
JSONDecoder::decode_json("data_extra_pool", explicit_placement.data_extra_pool, obj);
JSONDecoder::decode_json("index_pool", explicit_placement.index_pool, obj);
}
}
namespace rgw {
namespace auth {
ostream& operator <<(ostream& m, const Principal& p) {
if (p.is_wildcard()) {
return m << "*";
}
m << "arn:aws:iam:" << p.get_tenant() << ":";
if (p.is_tenant()) {
return m << "root";
}
return m << (p.is_user() ? "user/" : "role/") << p.get_id();
}
}
}
| 4,934 | 26.265193 | 89 |
cc
|
null |
ceph-main/src/rgw/rgw_basic_types.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2019 Red Hat, Inc.
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
/* N.B., this header defines fundamental serialized types. Do not
* introduce changes or include files which can only be compiled in
* radosgw or OSD contexts (e.g., rgw_sal.h, rgw_common.h)
*/
#pragma once
#include <string>
#include <fmt/format.h>
#include "include/types.h"
#include "rgw_compression_types.h"
#include "rgw_pool_types.h"
#include "rgw_acl_types.h"
#include "rgw_zone_types.h"
#include "rgw_user_types.h"
#include "rgw_bucket_types.h"
#include "rgw_obj_types.h"
#include "rgw_obj_manifest.h"
#include "common/Formatter.h"
class JSONObj;
class cls_user_bucket;
enum RGWIntentEvent {
DEL_OBJ = 0,
DEL_DIR = 1,
};
/** Store error returns for output at a different point in the program */
struct rgw_err {
rgw_err();
void clear();
bool is_clear() const;
bool is_err() const;
friend std::ostream& operator<<(std::ostream& oss, const rgw_err &err);
int http_ret;
int ret;
std::string err_code;
std::string message;
}; /* rgw_err */
struct rgw_zone_id {
std::string id;
rgw_zone_id() {}
rgw_zone_id(const std::string& _id) : id(_id) {}
rgw_zone_id(std::string&& _id) : id(std::move(_id)) {}
void encode(ceph::buffer::list& bl) const {
/* backward compatiblity, not using ENCODE_{START,END} macros */
ceph::encode(id, bl);
}
void decode(ceph::buffer::list::const_iterator& bl) {
/* backward compatiblity, not using DECODE_{START,END} macros */
ceph::decode(id, bl);
}
void clear() {
id.clear();
}
bool operator==(const std::string& _id) const {
return (id == _id);
}
bool operator==(const rgw_zone_id& zid) const {
return (id == zid.id);
}
bool operator!=(const rgw_zone_id& zid) const {
return (id != zid.id);
}
bool operator<(const rgw_zone_id& zid) const {
return (id < zid.id);
}
bool operator>(const rgw_zone_id& zid) const {
return (id > zid.id);
}
bool empty() const {
return id.empty();
}
};
WRITE_CLASS_ENCODER(rgw_zone_id)
inline std::ostream& operator<<(std::ostream& os, const rgw_zone_id& zid) {
os << zid.id;
return os;
}
struct obj_version;
struct rgw_placement_rule;
struct RGWAccessKey;
class RGWUserCaps;
extern void encode_json(const char *name, const obj_version& v, Formatter *f);
extern void encode_json(const char *name, const RGWUserCaps& val, Formatter *f);
extern void encode_json(const char *name, const rgw_pool& pool, Formatter *f);
extern void encode_json(const char *name, const rgw_placement_rule& r, Formatter *f);
extern void encode_json_impl(const char *name, const rgw_zone_id& zid, ceph::Formatter *f);
extern void encode_json_plain(const char *name, const RGWAccessKey& val, Formatter *f);
extern void decode_json_obj(obj_version& v, JSONObj *obj);
extern void decode_json_obj(rgw_zone_id& zid, JSONObj *obj);
extern void decode_json_obj(rgw_pool& pool, JSONObj *obj);
extern void decode_json_obj(rgw_placement_rule& v, JSONObj *obj);
// Represents an identity. This is more wide-ranging than a
// 'User'. Its purposes is to be matched against by an
// IdentityApplier. The internal representation will doubtless change as
// more types are added. We may want to expose the type enum and make
// the member public so people can switch/case on it.
namespace rgw {
namespace auth {
class Principal {
enum types { User, Role, Tenant, Wildcard, OidcProvider, AssumedRole };
types t;
rgw_user u;
std::string idp_url;
explicit Principal(types t)
: t(t) {}
Principal(types t, std::string&& n, std::string i)
: t(t), u(std::move(n), std::move(i)) {}
Principal(std::string&& idp_url)
: t(OidcProvider), idp_url(std::move(idp_url)) {}
public:
static Principal wildcard() {
return Principal(Wildcard);
}
static Principal user(std::string&& t, std::string&& u) {
return Principal(User, std::move(t), std::move(u));
}
static Principal role(std::string&& t, std::string&& u) {
return Principal(Role, std::move(t), std::move(u));
}
static Principal tenant(std::string&& t) {
return Principal(Tenant, std::move(t), {});
}
static Principal oidc_provider(std::string&& idp_url) {
return Principal(std::move(idp_url));
}
static Principal assumed_role(std::string&& t, std::string&& u) {
return Principal(AssumedRole, std::move(t), std::move(u));
}
bool is_wildcard() const {
return t == Wildcard;
}
bool is_user() const {
return t == User;
}
bool is_role() const {
return t == Role;
}
bool is_tenant() const {
return t == Tenant;
}
bool is_oidc_provider() const {
return t == OidcProvider;
}
bool is_assumed_role() const {
return t == AssumedRole;
}
const std::string& get_tenant() const {
return u.tenant;
}
const std::string& get_id() const {
return u.id;
}
const std::string& get_idp_url() const {
return idp_url;
}
const std::string& get_role_session() const {
return u.id;
}
const std::string& get_role() const {
return u.id;
}
bool operator ==(const Principal& o) const {
return (t == o.t) && (u == o.u);
}
bool operator <(const Principal& o) const {
return (t < o.t) || ((t == o.t) && (u < o.u));
}
};
std::ostream& operator <<(std::ostream& m, const Principal& p);
}
}
class JSONObj;
void decode_json_obj(rgw_user& val, JSONObj *obj);
void encode_json(const char *name, const rgw_user& val, ceph::Formatter *f);
void encode_xml(const char *name, const rgw_user& val, ceph::Formatter *f);
inline std::ostream& operator<<(std::ostream& out, const rgw_user &u) {
std::string s;
u.to_str(s);
return out << s;
}
struct RGWUploadPartInfo {
uint32_t num;
uint64_t size;
uint64_t accounted_size{0};
std::string etag;
ceph::real_time modified;
RGWObjManifest manifest;
RGWCompressionInfo cs_info;
// Previous part obj prefixes. Recorded here for later cleanup.
std::set<std::string> past_prefixes;
RGWUploadPartInfo() : num(0), size(0) {}
void encode(bufferlist& bl) const {
ENCODE_START(5, 2, bl);
encode(num, bl);
encode(size, bl);
encode(etag, bl);
encode(modified, bl);
encode(manifest, bl);
encode(cs_info, bl);
encode(accounted_size, bl);
encode(past_prefixes, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& bl) {
DECODE_START_LEGACY_COMPAT_LEN(5, 2, 2, bl);
decode(num, bl);
decode(size, bl);
decode(etag, bl);
decode(modified, bl);
if (struct_v >= 3)
decode(manifest, bl);
if (struct_v >= 4) {
decode(cs_info, bl);
decode(accounted_size, bl);
} else {
accounted_size = size;
}
if (struct_v >= 5) {
decode(past_prefixes, bl);
}
DECODE_FINISH(bl);
}
void dump(Formatter *f) const;
static void generate_test_instances(std::list<RGWUploadPartInfo*>& o);
};
WRITE_CLASS_ENCODER(RGWUploadPartInfo)
| 7,263 | 23.876712 | 91 |
h
|
null |
ceph-main/src/rgw/rgw_bucket.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include "rgw_bucket.h"
#include "common/errno.h"
#define dout_subsys ceph_subsys_rgw
// stolen from src/cls/version/cls_version.cc
#define VERSION_ATTR "ceph.objclass.version"
using namespace std;
static void set_err_msg(std::string *sink, std::string msg)
{
if (sink && !msg.empty())
*sink = msg;
}
void init_bucket(rgw_bucket *b, const char *t, const char *n, const char *dp, const char *ip, const char *m, const char *id)
{
b->tenant = t;
b->name = n;
b->marker = m;
b->bucket_id = id;
b->explicit_placement.data_pool = rgw_pool(dp);
b->explicit_placement.index_pool = rgw_pool(ip);
}
// parse key in format: [tenant/]name:instance[:shard_id]
int rgw_bucket_parse_bucket_key(CephContext *cct, const string& key,
rgw_bucket *bucket, int *shard_id)
{
std::string_view name{key};
std::string_view instance;
// split tenant/name
auto pos = name.find('/');
if (pos != string::npos) {
auto tenant = name.substr(0, pos);
bucket->tenant.assign(tenant.begin(), tenant.end());
name = name.substr(pos + 1);
} else {
bucket->tenant.clear();
}
// split name:instance
pos = name.find(':');
if (pos != string::npos) {
instance = name.substr(pos + 1);
name = name.substr(0, pos);
}
bucket->name.assign(name.begin(), name.end());
// split instance:shard
pos = instance.find(':');
if (pos == string::npos) {
bucket->bucket_id.assign(instance.begin(), instance.end());
if (shard_id) {
*shard_id = -1;
}
return 0;
}
// parse shard id
auto shard = instance.substr(pos + 1);
string err;
auto id = strict_strtol(shard.data(), 10, &err);
if (!err.empty()) {
if (cct) {
ldout(cct, 0) << "ERROR: failed to parse bucket shard '"
<< instance.data() << "': " << err << dendl;
}
return -EINVAL;
}
if (shard_id) {
*shard_id = id;
}
instance = instance.substr(0, pos);
bucket->bucket_id.assign(instance.begin(), instance.end());
return 0;
}
/*
* Note that this is not a reversal of parse_bucket(). That one deals
* with the syntax we need in metadata and such. This one deals with
* the representation in RADOS pools. We chose '/' because it's not
* acceptable in bucket names and thus qualified buckets cannot conflict
* with the legacy or S3 buckets.
*/
std::string rgw_make_bucket_entry_name(const std::string& tenant_name,
const std::string& bucket_name) {
std::string bucket_entry;
if (bucket_name.empty()) {
bucket_entry.clear();
} else if (tenant_name.empty()) {
bucket_entry = bucket_name;
} else {
bucket_entry = tenant_name + "/" + bucket_name;
}
return bucket_entry;
}
/*
* Tenants are separated from buckets in URLs by a colon in S3.
* This function is not to be used on Swift URLs, not even for COPY arguments.
*/
int rgw_parse_url_bucket(const string &bucket, const string& auth_tenant,
string &tenant_name, string &bucket_name) {
int pos = bucket.find(':');
if (pos >= 0) {
/*
* N.B.: We allow ":bucket" syntax with explicit empty tenant in order
* to refer to the legacy tenant, in case users in new named tenants
* want to access old global buckets.
*/
tenant_name = bucket.substr(0, pos);
bucket_name = bucket.substr(pos + 1);
if (bucket_name.empty()) {
return -ERR_INVALID_BUCKET_NAME;
}
} else {
tenant_name = auth_tenant;
bucket_name = bucket;
}
return 0;
}
int rgw_chown_bucket_and_objects(rgw::sal::Driver* driver, rgw::sal::Bucket* bucket,
rgw::sal::User* new_user,
const std::string& marker, std::string *err_msg,
const DoutPrefixProvider *dpp, optional_yield y)
{
/* Chown on the bucket */
int ret = bucket->chown(dpp, *new_user, y);
if (ret < 0) {
set_err_msg(err_msg, "Failed to change object ownership: " + cpp_strerror(-ret));
}
/* Now chown on all the objects in the bucket */
map<string, bool> common_prefixes;
rgw::sal::Bucket::ListParams params;
rgw::sal::Bucket::ListResults results;
params.list_versions = true;
params.allow_unordered = true;
params.marker = marker;
int count = 0;
int max_entries = 1000;
//Loop through objects and update object acls to point to bucket owner
do {
results.objs.clear();
ret = bucket->list(dpp, params, max_entries, results, y);
if (ret < 0) {
ldpp_dout(dpp, 0) << "ERROR: list objects failed: " << cpp_strerror(-ret) << dendl;
return ret;
}
params.marker = results.next_marker;
count += results.objs.size();
for (const auto& obj : results.objs) {
std::unique_ptr<rgw::sal::Object> r_obj = bucket->get_object(obj.key);
ret = r_obj->chown(*new_user, dpp, y);
if (ret < 0) {
ldpp_dout(dpp, 0) << "ERROR: chown failed on " << r_obj << " :" << cpp_strerror(-ret) << dendl;
return ret;
}
}
cerr << count << " objects processed in " << bucket
<< ". Next marker " << params.marker.name << std::endl;
} while(results.is_truncated);
return ret;
}
| 5,216 | 26.898396 | 124 |
cc
|
null |
ceph-main/src/rgw/rgw_bucket.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#pragma once
#include <string>
#include <memory>
#include <variant>
#include <boost/container/flat_map.hpp>
#include <boost/container/flat_set.hpp>
#include "include/types.h"
#include "rgw_common.h"
#include "rgw_sal.h"
extern void init_bucket(rgw_bucket *b, const char *t, const char *n, const char *dp, const char *ip, const char *m, const char *id);
extern int rgw_bucket_parse_bucket_key(CephContext *cct, const std::string& key,
rgw_bucket* bucket, int *shard_id);
extern std::string rgw_make_bucket_entry_name(const std::string& tenant_name,
const std::string& bucket_name);
[[nodiscard]] int rgw_parse_url_bucket(const std::string& bucket,
const std::string& auth_tenant,
std::string &tenant_name,
std::string &bucket_name);
extern int rgw_chown_bucket_and_objects(rgw::sal::Driver* driver,
rgw::sal::Bucket* bucket,
rgw::sal::User* new_user,
const std::string& marker,
std::string *err_msg,
const DoutPrefixProvider *dpp,
optional_yield y);
| 1,295 | 34.027027 | 132 |
h
|
null |
ceph-main/src/rgw/rgw_bucket_encryption.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
//
#include "rgw_bucket_encryption.h"
#include "rgw_xml.h"
#include "common/ceph_json.h"
void ApplyServerSideEncryptionByDefault::decode_xml(XMLObj *obj) {
RGWXMLDecoder::decode_xml("KMSMasterKeyID", kmsMasterKeyID, obj, false);
RGWXMLDecoder::decode_xml("SSEAlgorithm", sseAlgorithm, obj, false);
}
void ApplyServerSideEncryptionByDefault::dump_xml(Formatter *f) const {
encode_xml("SSEAlgorithm", sseAlgorithm, f);
if (kmsMasterKeyID != "") {
encode_xml("KMSMasterKeyID", kmsMasterKeyID, f);
}
}
void ServerSideEncryptionConfiguration::decode_xml(XMLObj *obj) {
RGWXMLDecoder::decode_xml("ApplyServerSideEncryptionByDefault", applyServerSideEncryptionByDefault, obj, false);
RGWXMLDecoder::decode_xml("BucketKeyEnabled", bucketKeyEnabled, obj, false);
}
void ServerSideEncryptionConfiguration::dump_xml(Formatter *f) const {
encode_xml("ApplyServerSideEncryptionByDefault", applyServerSideEncryptionByDefault, f);
if (bucketKeyEnabled) {
encode_xml("BucketKeyEnabled", true, f);
}
}
void RGWBucketEncryptionConfig::decode_xml(XMLObj *obj) {
rule_exist = RGWXMLDecoder::decode_xml("Rule", rule, obj);
}
void RGWBucketEncryptionConfig::dump_xml(Formatter *f) const {
if (rule_exist) {
encode_xml("Rule", rule, f);
}
}
void RGWBucketEncryptionConfig::dump(Formatter *f) const {
encode_json("rule_exist", has_rule(), f);
if (has_rule()) {
encode_json("sse_algorithm", sse_algorithm(), f);
encode_json("kms_master_key_id", kms_master_key_id(), f);
encode_json("bucket_key_enabled", bucket_key_enabled(), f);
}
}
| 1,677 | 32.56 | 114 |
cc
|
null |
ceph-main/src/rgw/rgw_bucket_encryption.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#pragma once
#include <include/types.h>
class XMLObj;
class ApplyServerSideEncryptionByDefault
{
std::string kmsMasterKeyID;
std::string sseAlgorithm;
public:
ApplyServerSideEncryptionByDefault() {};
ApplyServerSideEncryptionByDefault(const std::string &algorithm,
const std::string &key_id)
: kmsMasterKeyID(key_id), sseAlgorithm(algorithm) {};
const std::string& kms_master_key_id() const {
return kmsMasterKeyID;
}
const std::string& sse_algorithm() const {
return sseAlgorithm;
}
void encode(bufferlist& bl) const {
ENCODE_START(1, 1, bl);
encode(kmsMasterKeyID, bl);
encode(sseAlgorithm, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& bl) {
DECODE_START(1, bl);
decode(kmsMasterKeyID, bl);
decode(sseAlgorithm, bl);
DECODE_FINISH(bl);
}
void decode_xml(XMLObj *obj);
void dump_xml(Formatter *f) const;
};
WRITE_CLASS_ENCODER(ApplyServerSideEncryptionByDefault)
class ServerSideEncryptionConfiguration
{
protected:
ApplyServerSideEncryptionByDefault applyServerSideEncryptionByDefault;
bool bucketKeyEnabled;
public:
ServerSideEncryptionConfiguration(): bucketKeyEnabled(false) {};
ServerSideEncryptionConfiguration(const std::string &algorithm,
const std::string &keyid="", bool enabled = false)
: applyServerSideEncryptionByDefault(algorithm, keyid),
bucketKeyEnabled(enabled) {}
const std::string& kms_master_key_id() const {
return applyServerSideEncryptionByDefault.kms_master_key_id();
}
const std::string& sse_algorithm() const {
return applyServerSideEncryptionByDefault.sse_algorithm();
}
bool bucket_key_enabled() const {
return bucketKeyEnabled;
}
void encode(bufferlist& bl) const {
ENCODE_START(1, 1, bl);
encode(applyServerSideEncryptionByDefault, bl);
encode(bucketKeyEnabled, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& bl) {
DECODE_START(1, bl);
decode(applyServerSideEncryptionByDefault, bl);
decode(bucketKeyEnabled, bl);
DECODE_FINISH(bl);
}
void decode_xml(XMLObj *obj);
void dump_xml(Formatter *f) const;
};
WRITE_CLASS_ENCODER(ServerSideEncryptionConfiguration)
class RGWBucketEncryptionConfig
{
protected:
bool rule_exist;
ServerSideEncryptionConfiguration rule;
public:
RGWBucketEncryptionConfig(): rule_exist(false) {}
RGWBucketEncryptionConfig(const std::string &algorithm,
const std::string &keyid = "", bool enabled = false)
: rule_exist(true), rule(algorithm, keyid, enabled) {}
const std::string& kms_master_key_id() const {
return rule.kms_master_key_id();
}
const std::string& sse_algorithm() const {
return rule.sse_algorithm();
}
bool bucket_key_enabled() const {
return rule.bucket_key_enabled();
}
bool has_rule() const {
return rule_exist;
}
void encode(bufferlist& bl) const {
ENCODE_START(1, 1, bl);
encode(rule_exist, bl);
if (rule_exist) {
encode(rule, bl);
}
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& bl) {
DECODE_START(1, bl);
decode(rule_exist, bl);
if (rule_exist) {
decode(rule, bl);
}
DECODE_FINISH(bl);
}
void decode_xml(XMLObj *obj);
void dump_xml(Formatter *f) const;
void dump(Formatter *f) const;
static void generate_test_instances(std::list<RGWBucketEncryptionConfig*>& o);
};
WRITE_CLASS_ENCODER(RGWBucketEncryptionConfig)
| 3,562 | 23.916084 | 80 |
h
|
null |
ceph-main/src/rgw/rgw_bucket_layout.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2020 Red Hat, Inc.
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#include <boost/algorithm/string.hpp>
#include "rgw_bucket_layout.h"
namespace rgw {
// BucketIndexType
std::string_view to_string(const BucketIndexType& t)
{
switch (t) {
case BucketIndexType::Normal: return "Normal";
case BucketIndexType::Indexless: return "Indexless";
default: return "Unknown";
}
}
bool parse(std::string_view str, BucketIndexType& t)
{
if (boost::iequals(str, "Normal")) {
t = BucketIndexType::Normal;
return true;
}
if (boost::iequals(str, "Indexless")) {
t = BucketIndexType::Indexless;
return true;
}
return false;
}
void encode_json_impl(const char *name, const BucketIndexType& t, ceph::Formatter *f)
{
encode_json(name, to_string(t), f);
}
void decode_json_obj(BucketIndexType& t, JSONObj *obj)
{
std::string str;
decode_json_obj(str, obj);
parse(str, t);
}
// BucketHashType
std::string_view to_string(const BucketHashType& t)
{
switch (t) {
case BucketHashType::Mod: return "Mod";
default: return "Unknown";
}
}
bool parse(std::string_view str, BucketHashType& t)
{
if (boost::iequals(str, "Mod")) {
t = BucketHashType::Mod;
return true;
}
return false;
}
void encode_json_impl(const char *name, const BucketHashType& t, ceph::Formatter *f)
{
encode_json(name, to_string(t), f);
}
void decode_json_obj(BucketHashType& t, JSONObj *obj)
{
std::string str;
decode_json_obj(str, obj);
parse(str, t);
}
// bucket_index_normal_layout
void encode(const bucket_index_normal_layout& l, bufferlist& bl, uint64_t f)
{
ENCODE_START(1, 1, bl);
encode(l.num_shards, bl);
encode(l.hash_type, bl);
ENCODE_FINISH(bl);
}
void decode(bucket_index_normal_layout& l, bufferlist::const_iterator& bl)
{
DECODE_START(1, bl);
decode(l.num_shards, bl);
decode(l.hash_type, bl);
DECODE_FINISH(bl);
}
void encode_json_impl(const char *name, const bucket_index_normal_layout& l, ceph::Formatter *f)
{
f->open_object_section(name);
encode_json("num_shards", l.num_shards, f);
encode_json("hash_type", l.hash_type, f);
f->close_section();
}
void decode_json_obj(bucket_index_normal_layout& l, JSONObj *obj)
{
JSONDecoder::decode_json("num_shards", l.num_shards, obj);
JSONDecoder::decode_json("hash_type", l.hash_type, obj);
}
// bucket_index_layout
void encode(const bucket_index_layout& l, bufferlist& bl, uint64_t f)
{
ENCODE_START(1, 1, bl);
encode(l.type, bl);
switch (l.type) {
case BucketIndexType::Normal:
encode(l.normal, bl);
break;
case BucketIndexType::Indexless:
break;
}
ENCODE_FINISH(bl);
}
void decode(bucket_index_layout& l, bufferlist::const_iterator& bl)
{
DECODE_START(1, bl);
decode(l.type, bl);
switch (l.type) {
case BucketIndexType::Normal:
decode(l.normal, bl);
break;
case BucketIndexType::Indexless:
break;
}
DECODE_FINISH(bl);
}
void encode_json_impl(const char *name, const bucket_index_layout& l, ceph::Formatter *f)
{
f->open_object_section(name);
encode_json("type", l.type, f);
encode_json("normal", l.normal, f);
f->close_section();
}
void decode_json_obj(bucket_index_layout& l, JSONObj *obj)
{
JSONDecoder::decode_json("type", l.type, obj);
JSONDecoder::decode_json("normal", l.normal, obj);
}
// bucket_index_layout_generation
void encode(const bucket_index_layout_generation& l, bufferlist& bl, uint64_t f)
{
ENCODE_START(1, 1, bl);
encode(l.gen, bl);
encode(l.layout, bl);
ENCODE_FINISH(bl);
}
void decode(bucket_index_layout_generation& l, bufferlist::const_iterator& bl)
{
DECODE_START(1, bl);
decode(l.gen, bl);
decode(l.layout, bl);
DECODE_FINISH(bl);
}
void encode_json_impl(const char *name, const bucket_index_layout_generation& l, ceph::Formatter *f)
{
f->open_object_section(name);
encode_json("gen", l.gen, f);
encode_json("layout", l.layout, f);
f->close_section();
}
void decode_json_obj(bucket_index_layout_generation& l, JSONObj *obj)
{
JSONDecoder::decode_json("gen", l.gen, obj);
JSONDecoder::decode_json("layout", l.layout, obj);
}
// BucketLogType
std::string_view to_string(const BucketLogType& t)
{
switch (t) {
case BucketLogType::InIndex: return "InIndex";
default: return "Unknown";
}
}
bool parse(std::string_view str, BucketLogType& t)
{
if (boost::iequals(str, "InIndex")) {
t = BucketLogType::InIndex;
return true;
}
return false;
}
void encode_json_impl(const char *name, const BucketLogType& t, ceph::Formatter *f)
{
encode_json(name, to_string(t), f);
}
void decode_json_obj(BucketLogType& t, JSONObj *obj)
{
std::string str;
decode_json_obj(str, obj);
parse(str, t);
}
// bucket_index_log_layout
void encode(const bucket_index_log_layout& l, bufferlist& bl, uint64_t f)
{
ENCODE_START(1, 1, bl);
encode(l.gen, bl);
encode(l.layout, bl);
ENCODE_FINISH(bl);
}
void decode(bucket_index_log_layout& l, bufferlist::const_iterator& bl)
{
DECODE_START(1, bl);
decode(l.gen, bl);
decode(l.layout, bl);
DECODE_FINISH(bl);
}
void encode_json_impl(const char *name, const bucket_index_log_layout& l, ceph::Formatter *f)
{
f->open_object_section(name);
encode_json("gen", l.gen, f);
encode_json("layout", l.layout, f);
f->close_section();
}
void decode_json_obj(bucket_index_log_layout& l, JSONObj *obj)
{
JSONDecoder::decode_json("gen", l.gen, obj);
JSONDecoder::decode_json("layout", l.layout, obj);
}
// bucket_log_layout
void encode(const bucket_log_layout& l, bufferlist& bl, uint64_t f)
{
ENCODE_START(1, 1, bl);
encode(l.type, bl);
switch (l.type) {
case BucketLogType::InIndex:
encode(l.in_index, bl);
break;
}
ENCODE_FINISH(bl);
}
void decode(bucket_log_layout& l, bufferlist::const_iterator& bl)
{
DECODE_START(1, bl);
decode(l.type, bl);
switch (l.type) {
case BucketLogType::InIndex:
decode(l.in_index, bl);
break;
}
DECODE_FINISH(bl);
}
void encode_json_impl(const char *name, const bucket_log_layout& l, ceph::Formatter *f)
{
f->open_object_section(name);
encode_json("type", l.type, f);
if (l.type == BucketLogType::InIndex) {
encode_json("in_index", l.in_index, f);
}
f->close_section();
}
void decode_json_obj(bucket_log_layout& l, JSONObj *obj)
{
JSONDecoder::decode_json("type", l.type, obj);
JSONDecoder::decode_json("in_index", l.in_index, obj);
}
// bucket_log_layout_generation
void encode(const bucket_log_layout_generation& l, bufferlist& bl, uint64_t f)
{
ENCODE_START(1, 1, bl);
encode(l.gen, bl);
encode(l.layout, bl);
ENCODE_FINISH(bl);
}
void decode(bucket_log_layout_generation& l, bufferlist::const_iterator& bl)
{
DECODE_START(1, bl);
decode(l.gen, bl);
decode(l.layout, bl);
DECODE_FINISH(bl);
}
void encode_json_impl(const char *name, const bucket_log_layout_generation& l, ceph::Formatter *f)
{
f->open_object_section(name);
encode_json("gen", l.gen, f);
encode_json("layout", l.layout, f);
f->close_section();
}
void decode_json_obj(bucket_log_layout_generation& l, JSONObj *obj)
{
JSONDecoder::decode_json("gen", l.gen, obj);
JSONDecoder::decode_json("layout", l.layout, obj);
}
// BucketReshardState
std::string_view to_string(const BucketReshardState& s)
{
switch (s) {
case BucketReshardState::None: return "None";
case BucketReshardState::InProgress: return "InProgress";
default: return "Unknown";
}
}
bool parse(std::string_view str, BucketReshardState& s)
{
if (boost::iequals(str, "None")) {
s = BucketReshardState::None;
return true;
}
if (boost::iequals(str, "InProgress")) {
s = BucketReshardState::InProgress;
return true;
}
return false;
}
void encode_json_impl(const char *name, const BucketReshardState& s, ceph::Formatter *f)
{
encode_json(name, to_string(s), f);
}
void decode_json_obj(BucketReshardState& s, JSONObj *obj)
{
std::string str;
decode_json_obj(str, obj);
parse(str, s);
}
// BucketLayout
void encode(const BucketLayout& l, bufferlist& bl, uint64_t f)
{
ENCODE_START(2, 1, bl);
encode(l.resharding, bl);
encode(l.current_index, bl);
encode(l.target_index, bl);
encode(l.logs, bl);
ENCODE_FINISH(bl);
}
void decode(BucketLayout& l, bufferlist::const_iterator& bl)
{
DECODE_START(2, bl);
decode(l.resharding, bl);
decode(l.current_index, bl);
decode(l.target_index, bl);
if (struct_v < 2) {
l.logs.clear();
// initialize the log layout to match the current index layout
if (l.current_index.layout.type == BucketIndexType::Normal) {
l.logs.push_back(log_layout_from_index(0, l.current_index));
}
} else {
decode(l.logs, bl);
}
DECODE_FINISH(bl);
}
void encode_json_impl(const char *name, const BucketLayout& l, ceph::Formatter *f)
{
f->open_object_section(name);
encode_json("resharding", l.resharding, f);
encode_json("current_index", l.current_index, f);
if (l.target_index) {
encode_json("target_index", *l.target_index, f);
}
f->open_array_section("logs");
for (const auto& log : l.logs) {
encode_json("log", log, f);
}
f->close_section(); // logs[]
f->close_section();
}
void decode_json_obj(BucketLayout& l, JSONObj *obj)
{
JSONDecoder::decode_json("resharding", l.resharding, obj);
JSONDecoder::decode_json("current_index", l.current_index, obj);
JSONDecoder::decode_json("target_index", l.target_index, obj);
JSONDecoder::decode_json("logs", l.logs, obj);
}
} // namespace rgw
| 9,706 | 24.47769 | 100 |
cc
|
null |
ceph-main/src/rgw/rgw_bucket_layout.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2020 Red Hat, Inc.
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
/* N.B., this header defines fundamental serialized types. Do not
* introduce changes or include files which can only be compiled in
* radosgw or OSD contexts (e.g., rgw_sal.h, rgw_common.h)
*/
#pragma once
#include <optional>
#include <string>
#include "include/encoding.h"
#include "common/ceph_json.h"
namespace rgw {
enum class BucketIndexType : uint8_t {
Normal, // normal hash-based sharded index layout
Indexless, // no bucket index, so listing is unsupported
};
std::string_view to_string(const BucketIndexType& t);
bool parse(std::string_view str, BucketIndexType& t);
void encode_json_impl(const char *name, const BucketIndexType& t, ceph::Formatter *f);
void decode_json_obj(BucketIndexType& t, JSONObj *obj);
inline std::ostream& operator<<(std::ostream& out, const BucketIndexType& t)
{
return out << to_string(t);
}
enum class BucketHashType : uint8_t {
Mod, // rjenkins hash of object name, modulo num_shards
};
std::string_view to_string(const BucketHashType& t);
bool parse(std::string_view str, BucketHashType& t);
void encode_json_impl(const char *name, const BucketHashType& t, ceph::Formatter *f);
void decode_json_obj(BucketHashType& t, JSONObj *obj);
struct bucket_index_normal_layout {
uint32_t num_shards = 1;
BucketHashType hash_type = BucketHashType::Mod;
friend std::ostream& operator<<(std::ostream& out, const bucket_index_normal_layout& l) {
out << "num_shards=" << l.num_shards << ", hash_type=" << to_string(l.hash_type);
return out;
}
};
inline bool operator==(const bucket_index_normal_layout& l,
const bucket_index_normal_layout& r) {
return l.num_shards == r.num_shards
&& l.hash_type == r.hash_type;
}
inline bool operator!=(const bucket_index_normal_layout& l,
const bucket_index_normal_layout& r) {
return !(l == r);
}
void encode(const bucket_index_normal_layout& l, bufferlist& bl, uint64_t f=0);
void decode(bucket_index_normal_layout& l, bufferlist::const_iterator& bl);
void encode_json_impl(const char *name, const bucket_index_normal_layout& l, ceph::Formatter *f);
void decode_json_obj(bucket_index_normal_layout& l, JSONObj *obj);
struct bucket_index_layout {
BucketIndexType type = BucketIndexType::Normal;
// TODO: variant of layout types?
bucket_index_normal_layout normal;
friend std::ostream& operator<<(std::ostream& out, const bucket_index_layout& l) {
out << "type=" << to_string(l.type) << ", normal=" << l.normal;
return out;
}
};
inline bool operator==(const bucket_index_layout& l,
const bucket_index_layout& r) {
return l.type == r.type && l.normal == r.normal;
}
inline bool operator!=(const bucket_index_layout& l,
const bucket_index_layout& r) {
return !(l == r);
}
void encode(const bucket_index_layout& l, bufferlist& bl, uint64_t f=0);
void decode(bucket_index_layout& l, bufferlist::const_iterator& bl);
void encode_json_impl(const char *name, const bucket_index_layout& l, ceph::Formatter *f);
void decode_json_obj(bucket_index_layout& l, JSONObj *obj);
struct bucket_index_layout_generation {
uint64_t gen = 0;
bucket_index_layout layout;
friend std::ostream& operator<<(std::ostream& out, const bucket_index_layout_generation& g) {
out << "gen=" << g.gen;
return out;
}
};
inline bool operator==(const bucket_index_layout_generation& l,
const bucket_index_layout_generation& r) {
return l.gen == r.gen && l.layout == r.layout;
}
inline bool operator!=(const bucket_index_layout_generation& l,
const bucket_index_layout_generation& r) {
return !(l == r);
}
void encode(const bucket_index_layout_generation& l, bufferlist& bl, uint64_t f=0);
void decode(bucket_index_layout_generation& l, bufferlist::const_iterator& bl);
void encode_json_impl(const char *name, const bucket_index_layout_generation& l, ceph::Formatter *f);
void decode_json_obj(bucket_index_layout_generation& l, JSONObj *obj);
enum class BucketLogType : uint8_t {
// colocated with bucket index, so the log layout matches the index layout
InIndex,
};
std::string_view to_string(const BucketLogType& t);
bool parse(std::string_view str, BucketLogType& t);
void encode_json_impl(const char *name, const BucketLogType& t, ceph::Formatter *f);
void decode_json_obj(BucketLogType& t, JSONObj *obj);
inline std::ostream& operator<<(std::ostream& out, const BucketLogType &log_type)
{
switch (log_type) {
case BucketLogType::InIndex:
return out << "InIndex";
default:
return out << "Unknown";
}
}
struct bucket_index_log_layout {
uint64_t gen = 0;
bucket_index_normal_layout layout;
operator bucket_index_layout_generation() const {
bucket_index_layout_generation bilg;
bilg.gen = gen;
bilg.layout.type = BucketIndexType::Normal;
bilg.layout.normal = layout;
return bilg;
}
};
void encode(const bucket_index_log_layout& l, bufferlist& bl, uint64_t f=0);
void decode(bucket_index_log_layout& l, bufferlist::const_iterator& bl);
void encode_json_impl(const char *name, const bucket_index_log_layout& l, ceph::Formatter *f);
void decode_json_obj(bucket_index_log_layout& l, JSONObj *obj);
struct bucket_log_layout {
BucketLogType type = BucketLogType::InIndex;
bucket_index_log_layout in_index;
friend std::ostream& operator<<(std::ostream& out, const bucket_log_layout& l) {
out << "type=" << to_string(l.type);
return out;
}
};
void encode(const bucket_log_layout& l, bufferlist& bl, uint64_t f=0);
void decode(bucket_log_layout& l, bufferlist::const_iterator& bl);
void encode_json_impl(const char *name, const bucket_log_layout& l, ceph::Formatter *f);
void decode_json_obj(bucket_log_layout& l, JSONObj *obj);
struct bucket_log_layout_generation {
uint64_t gen = 0;
bucket_log_layout layout;
friend std::ostream& operator<<(std::ostream& out, const bucket_log_layout_generation& g) {
out << "gen=" << g.gen << ", layout=[ " << g.layout << " ]";
return out;
}
};
void encode(const bucket_log_layout_generation& l, bufferlist& bl, uint64_t f=0);
void decode(bucket_log_layout_generation& l, bufferlist::const_iterator& bl);
void encode_json_impl(const char *name, const bucket_log_layout_generation& l, ceph::Formatter *f);
void decode_json_obj(bucket_log_layout_generation& l, JSONObj *obj);
// return a log layout that shares its layout with the index
inline bucket_log_layout_generation log_layout_from_index(
uint64_t gen, const bucket_index_layout_generation& index)
{
return {gen, {BucketLogType::InIndex, {index.gen, index.layout.normal}}};
}
inline auto matches_gen(uint64_t gen)
{
return [gen] (const bucket_log_layout_generation& l) { return l.gen == gen; };
}
inline bucket_index_layout_generation log_to_index_layout(const bucket_log_layout_generation& log_layout)
{
ceph_assert(log_layout.layout.type == BucketLogType::InIndex);
bucket_index_layout_generation index;
index.gen = log_layout.layout.in_index.gen;
index.layout.normal = log_layout.layout.in_index.layout;
return index;
}
enum class BucketReshardState : uint8_t {
None,
InProgress,
};
std::string_view to_string(const BucketReshardState& s);
bool parse(std::string_view str, BucketReshardState& s);
void encode_json_impl(const char *name, const BucketReshardState& s, ceph::Formatter *f);
void decode_json_obj(BucketReshardState& s, JSONObj *obj);
// describes the layout of bucket index objects
struct BucketLayout {
BucketReshardState resharding = BucketReshardState::None;
// current bucket index layout
bucket_index_layout_generation current_index;
// target index layout of a resharding operation
std::optional<bucket_index_layout_generation> target_index;
// history of untrimmed bucket log layout generations, with the current
// generation at the back()
std::vector<bucket_log_layout_generation> logs;
friend std::ostream& operator<<(std::ostream& out, const BucketLayout& l) {
std::stringstream ss;
if (l.target_index) {
ss << *l.target_index;
} else {
ss << "none";
}
out << "resharding=" << to_string(l.resharding) <<
", current_index=[" << l.current_index << "], target_index=[" <<
ss.str() << "], logs.size()=" << l.logs.size();
return out;
}
};
void encode(const BucketLayout& l, bufferlist& bl, uint64_t f=0);
void decode(BucketLayout& l, bufferlist::const_iterator& bl);
void encode_json_impl(const char *name, const BucketLayout& l, ceph::Formatter *f);
void decode_json_obj(BucketLayout& l, JSONObj *obj);
inline uint32_t num_shards(const bucket_index_normal_layout& index) {
// old buckets used num_shards=0 to mean 1
return index.num_shards > 0 ? index.num_shards : 1;
}
inline uint32_t num_shards(const bucket_index_layout& index) {
ceph_assert(index.type == BucketIndexType::Normal);
return num_shards(index.normal);
}
inline uint32_t num_shards(const bucket_index_layout_generation& index) {
return num_shards(index.layout);
}
inline uint32_t current_num_shards(const BucketLayout& layout) {
return num_shards(layout.current_index);
}
inline bool is_layout_indexless(const bucket_index_layout_generation& layout) {
return layout.layout.type == BucketIndexType::Indexless;
}
} // namespace rgw
| 9,694 | 33.257951 | 105 |
h
|
null |
ceph-main/src/rgw/rgw_bucket_sync_cache.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2020 Red Hat, Inc
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*/
#pragma once
#include <boost/smart_ptr/intrusive_ref_counter.hpp>
#include "common/intrusive_lru.h"
#include "rgw_data_sync.h"
namespace rgw::bucket_sync {
// per bucket-shard state cached by DataSyncShardCR
struct State {
// the source bucket shard to sync
std::pair<rgw_bucket_shard, std::optional<uint64_t>> key;
// current sync obligation being processed by DataSyncSingleEntry
std::optional<rgw_data_sync_obligation> obligation;
// incremented with each new obligation
uint32_t counter = 0;
// highest timestamp applied by all sources
ceph::real_time progress_timestamp;
State(const std::pair<rgw_bucket_shard, std::optional<uint64_t>>& key ) noexcept
: key(key) {}
State(const rgw_bucket_shard& shard, std::optional<uint64_t> gen) noexcept
: key(shard, gen) {}
};
struct Entry;
struct EntryToKey;
class Handle;
using lru_config = ceph::common::intrusive_lru_config<
std::pair<rgw_bucket_shard, std::optional<uint64_t>>, Entry, EntryToKey>;
// a recyclable cache entry
struct Entry : State, ceph::common::intrusive_lru_base<lru_config> {
using State::State;
};
struct EntryToKey {
using type = std::pair<rgw_bucket_shard, std::optional<uint64_t>>;
const type& operator()(const Entry& e) { return e.key; }
};
// use a non-atomic reference count since these aren't shared across threads
template <typename T>
using thread_unsafe_ref_counter = boost::intrusive_ref_counter<
T, boost::thread_unsafe_counter>;
// a state cache for entries within a single datalog shard
class Cache : public thread_unsafe_ref_counter<Cache> {
ceph::common::intrusive_lru<lru_config> cache;
protected:
// protected ctor to enforce the use of factory function create()
explicit Cache(size_t target_size) {
cache.set_target_size(target_size);
}
public:
static boost::intrusive_ptr<Cache> create(size_t target_size) {
return new Cache(target_size);
}
// find or create a cache entry for the given key, and return a Handle that
// keeps it lru-pinned until destruction
Handle get(const rgw_bucket_shard& shard, std::optional<uint64_t> gen);
};
// a State handle that keeps the Cache referenced
class Handle {
boost::intrusive_ptr<Cache> cache;
boost::intrusive_ptr<Entry> entry;
public:
Handle() noexcept = default;
~Handle() = default;
Handle(boost::intrusive_ptr<Cache> cache,
boost::intrusive_ptr<Entry> entry) noexcept
: cache(std::move(cache)), entry(std::move(entry)) {}
Handle(Handle&&) = default;
Handle(const Handle&) = default;
Handle& operator=(Handle&& o) noexcept {
// move the entry first so that its cache stays referenced over destruction
entry = std::move(o.entry);
cache = std::move(o.cache);
return *this;
}
Handle& operator=(const Handle& o) noexcept {
// copy the entry first so that its cache stays referenced over destruction
entry = o.entry;
cache = o.cache;
return *this;
}
explicit operator bool() const noexcept { return static_cast<bool>(entry); }
State& operator*() const noexcept { return *entry; }
State* operator->() const noexcept { return entry.get(); }
};
inline Handle Cache::get(const rgw_bucket_shard& shard, std::optional<uint64_t> gen)
{
auto result = cache.get_or_create({ shard, gen });
return {this, std::move(result.first)};
}
} // namespace rgw::bucket_sync
| 3,750 | 31.059829 | 84 |
h
|
null |
ceph-main/src/rgw/rgw_bucket_types.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2019 Red Hat, Inc.
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
/* N.B., this header defines fundamental serialized types. Do not
* include files which can only be compiled in radosgw or OSD
* contexts (e.g., rgw_sal.h, rgw_common.h) */
#pragma once
#include <fmt/format.h>
#include "rgw_pool_types.h"
#include "rgw_user_types.h"
#include "rgw_placement_types.h"
#include "common/dout.h"
#include "common/Formatter.h"
struct cls_user_bucket;
struct rgw_bucket_key {
std::string tenant;
std::string name;
std::string bucket_id;
rgw_bucket_key(const std::string& _tenant,
const std::string& _name,
const std::string& _bucket_id) : tenant(_tenant),
name(_name),
bucket_id(_bucket_id) {}
rgw_bucket_key(const std::string& _tenant,
const std::string& _name) : tenant(_tenant),
name(_name) {}
};
struct rgw_bucket {
std::string tenant;
std::string name;
std::string marker;
std::string bucket_id;
rgw_data_placement_target explicit_placement;
rgw_bucket() { }
// cppcheck-suppress noExplicitConstructor
explicit rgw_bucket(const rgw_user& u, const cls_user_bucket& b);
rgw_bucket(const std::string& _tenant,
const std::string& _name,
const std::string& _bucket_id) : tenant(_tenant),
name(_name),
bucket_id(_bucket_id) {}
rgw_bucket(const rgw_bucket_key& bk) : tenant(bk.tenant),
name(bk.name),
bucket_id(bk.bucket_id) {}
rgw_bucket(const rgw_bucket&) = default;
rgw_bucket(rgw_bucket&&) = default;
bool match(const rgw_bucket& b) const {
return (tenant == b.tenant &&
name == b.name &&
(bucket_id == b.bucket_id ||
bucket_id.empty() ||
b.bucket_id.empty()));
}
void convert(cls_user_bucket *b) const;
void encode(ceph::buffer::list& bl) const {
ENCODE_START(10, 10, bl);
encode(name, bl);
encode(marker, bl);
encode(bucket_id, bl);
encode(tenant, bl);
bool encode_explicit = !explicit_placement.data_pool.empty();
encode(encode_explicit, bl);
if (encode_explicit) {
encode(explicit_placement.data_pool, bl);
encode(explicit_placement.data_extra_pool, bl);
encode(explicit_placement.index_pool, bl);
}
ENCODE_FINISH(bl);
}
void decode(ceph::buffer::list::const_iterator& bl) {
DECODE_START_LEGACY_COMPAT_LEN(10, 3, 3, bl);
decode(name, bl);
if (struct_v < 10) {
decode(explicit_placement.data_pool.name, bl);
}
if (struct_v >= 2) {
decode(marker, bl);
if (struct_v <= 3) {
uint64_t id;
decode(id, bl);
char buf[16];
snprintf(buf, sizeof(buf), "%" PRIu64, id);
bucket_id = buf;
} else {
decode(bucket_id, bl);
}
}
if (struct_v < 10) {
if (struct_v >= 5) {
decode(explicit_placement.index_pool.name, bl);
} else {
explicit_placement.index_pool = explicit_placement.data_pool;
}
if (struct_v >= 7) {
decode(explicit_placement.data_extra_pool.name, bl);
}
}
if (struct_v >= 8) {
decode(tenant, bl);
}
if (struct_v >= 10) {
bool decode_explicit = !explicit_placement.data_pool.empty();
decode(decode_explicit, bl);
if (decode_explicit) {
decode(explicit_placement.data_pool, bl);
decode(explicit_placement.data_extra_pool, bl);
decode(explicit_placement.index_pool, bl);
}
}
DECODE_FINISH(bl);
}
void update_bucket_id(const std::string& new_bucket_id) {
bucket_id = new_bucket_id;
}
// format a key for the bucket/instance. pass delim=0 to skip a field
std::string get_key(char tenant_delim = '/',
char id_delim = ':',
size_t reserve = 0) const;
const rgw_pool& get_data_extra_pool() const {
return explicit_placement.get_data_extra_pool();
}
void dump(ceph::Formatter *f) const;
void decode_json(JSONObj *obj);
static void generate_test_instances(std::list<rgw_bucket*>& o);
rgw_bucket& operator=(const rgw_bucket&) = default;
bool operator<(const rgw_bucket& b) const {
if (tenant < b.tenant) {
return true;
} else if (tenant > b.tenant) {
return false;
}
if (name < b.name) {
return true;
} else if (name > b.name) {
return false;
}
return (bucket_id < b.bucket_id);
}
bool operator==(const rgw_bucket& b) const {
return (tenant == b.tenant) && (name == b.name) && \
(bucket_id == b.bucket_id);
}
bool operator!=(const rgw_bucket& b) const {
return (tenant != b.tenant) || (name != b.name) ||
(bucket_id != b.bucket_id);
}
};
WRITE_CLASS_ENCODER(rgw_bucket)
inline std::ostream& operator<<(std::ostream& out, const rgw_bucket &b) {
out << b.tenant << ":" << b.name << "[" << b.bucket_id << "])";
return out;
}
struct rgw_bucket_placement {
rgw_placement_rule placement_rule;
rgw_bucket bucket;
void dump(Formatter *f) const;
}; /* rgw_bucket_placement */
struct rgw_bucket_shard {
rgw_bucket bucket;
int shard_id;
rgw_bucket_shard() : shard_id(-1) {}
rgw_bucket_shard(const rgw_bucket& _b, int _sid) : bucket(_b), shard_id(_sid) {}
std::string get_key(char tenant_delim = '/', char id_delim = ':',
char shard_delim = ':',
size_t reserve = 0) const;
bool operator<(const rgw_bucket_shard& b) const {
if (bucket < b.bucket) {
return true;
}
if (b.bucket < bucket) {
return false;
}
return shard_id < b.shard_id;
}
bool operator==(const rgw_bucket_shard& b) const {
return (bucket == b.bucket &&
shard_id == b.shard_id);
}
}; /* rgw_bucket_shard */
void encode(const rgw_bucket_shard& b, bufferlist& bl, uint64_t f=0);
void decode(rgw_bucket_shard& b, bufferlist::const_iterator& bl);
inline std::ostream& operator<<(std::ostream& out, const rgw_bucket_shard& bs) {
if (bs.shard_id <= 0) {
return out << bs.bucket;
}
return out << bs.bucket << ":" << bs.shard_id;
}
| 6,688 | 27.58547 | 82 |
h
|
null |
ceph-main/src/rgw/rgw_cache.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include "rgw_cache.h"
#include "rgw_perf_counters.h"
#include <errno.h>
#define dout_subsys ceph_subsys_rgw
using namespace std;
int ObjectCache::get(const DoutPrefixProvider *dpp, const string& name, ObjectCacheInfo& info, uint32_t mask, rgw_cache_entry_info *cache_info)
{
std::shared_lock rl{lock};
std::unique_lock wl{lock, std::defer_lock}; // may be promoted to write lock
if (!enabled) {
return -ENOENT;
}
auto iter = cache_map.find(name);
if (iter == cache_map.end()) {
ldpp_dout(dpp, 10) << "cache get: name=" << name << " : miss" << dendl;
if (perfcounter) {
perfcounter->inc(l_rgw_cache_miss);
}
return -ENOENT;
}
if (expiry.count() &&
(ceph::coarse_mono_clock::now() - iter->second.info.time_added) > expiry) {
ldpp_dout(dpp, 10) << "cache get: name=" << name << " : expiry miss" << dendl;
rl.unlock();
wl.lock(); // write lock for expiration
// check that wasn't already removed by other thread
iter = cache_map.find(name);
if (iter != cache_map.end()) {
for (auto &kv : iter->second.chained_entries)
kv.first->invalidate(kv.second);
remove_lru(name, iter->second.lru_iter);
cache_map.erase(iter);
}
if (perfcounter) {
perfcounter->inc(l_rgw_cache_miss);
}
return -ENOENT;
}
ObjectCacheEntry *entry = &iter->second;
if (lru_counter - entry->lru_promotion_ts > lru_window) {
ldpp_dout(dpp, 20) << "cache get: touching lru, lru_counter=" << lru_counter
<< " promotion_ts=" << entry->lru_promotion_ts << dendl;
rl.unlock();
wl.lock(); // write lock for touch_lru()
/* need to redo this because entry might have dropped off the cache */
iter = cache_map.find(name);
if (iter == cache_map.end()) {
ldpp_dout(dpp, 10) << "lost race! cache get: name=" << name << " : miss" << dendl;
if(perfcounter) perfcounter->inc(l_rgw_cache_miss);
return -ENOENT;
}
entry = &iter->second;
/* check again, we might have lost a race here */
if (lru_counter - entry->lru_promotion_ts > lru_window) {
touch_lru(dpp, name, *entry, iter->second.lru_iter);
}
}
ObjectCacheInfo& src = iter->second.info;
if(src.status == -ENOENT) {
ldpp_dout(dpp, 10) << "cache get: name=" << name << " : hit (negative entry)" << dendl;
if (perfcounter) perfcounter->inc(l_rgw_cache_hit);
return -ENODATA;
}
if ((src.flags & mask) != mask) {
ldpp_dout(dpp, 10) << "cache get: name=" << name << " : type miss (requested=0x"
<< std::hex << mask << ", cached=0x" << src.flags
<< std::dec << ")" << dendl;
if(perfcounter) perfcounter->inc(l_rgw_cache_miss);
return -ENOENT;
}
ldpp_dout(dpp, 10) << "cache get: name=" << name << " : hit (requested=0x"
<< std::hex << mask << ", cached=0x" << src.flags
<< std::dec << ")" << dendl;
info = src;
if (cache_info) {
cache_info->cache_locator = name;
cache_info->gen = entry->gen;
}
if(perfcounter) perfcounter->inc(l_rgw_cache_hit);
return 0;
}
bool ObjectCache::chain_cache_entry(const DoutPrefixProvider *dpp,
std::initializer_list<rgw_cache_entry_info*> cache_info_entries,
RGWChainedCache::Entry *chained_entry)
{
std::unique_lock l{lock};
if (!enabled) {
return false;
}
std::vector<ObjectCacheEntry*> entries;
entries.reserve(cache_info_entries.size());
/* first verify that all entries are still valid */
for (auto cache_info : cache_info_entries) {
ldpp_dout(dpp, 10) << "chain_cache_entry: cache_locator="
<< cache_info->cache_locator << dendl;
auto iter = cache_map.find(cache_info->cache_locator);
if (iter == cache_map.end()) {
ldpp_dout(dpp, 20) << "chain_cache_entry: couldn't find cache locator" << dendl;
return false;
}
auto entry = &iter->second;
if (entry->gen != cache_info->gen) {
ldpp_dout(dpp, 20) << "chain_cache_entry: entry.gen (" << entry->gen
<< ") != cache_info.gen (" << cache_info->gen << ")"
<< dendl;
return false;
}
entries.push_back(entry);
}
chained_entry->cache->chain_cb(chained_entry->key, chained_entry->data);
for (auto entry : entries) {
entry->chained_entries.push_back(make_pair(chained_entry->cache,
chained_entry->key));
}
return true;
}
void ObjectCache::put(const DoutPrefixProvider *dpp, const string& name, ObjectCacheInfo& info, rgw_cache_entry_info *cache_info)
{
std::unique_lock l{lock};
if (!enabled) {
return;
}
ldpp_dout(dpp, 10) << "cache put: name=" << name << " info.flags=0x"
<< std::hex << info.flags << std::dec << dendl;
auto [iter, inserted] = cache_map.emplace(name, ObjectCacheEntry{});
ObjectCacheEntry& entry = iter->second;
entry.info.time_added = ceph::coarse_mono_clock::now();
if (inserted) {
entry.lru_iter = lru.end();
}
ObjectCacheInfo& target = entry.info;
invalidate_lru(entry);
entry.chained_entries.clear();
entry.gen++;
touch_lru(dpp, name, entry, entry.lru_iter);
target.status = info.status;
if (info.status < 0) {
target.flags = 0;
target.xattrs.clear();
target.data.clear();
return;
}
if (cache_info) {
cache_info->cache_locator = name;
cache_info->gen = entry.gen;
}
// put() must include the latest version if we're going to keep caching it
target.flags &= ~CACHE_FLAG_OBJV;
target.flags |= info.flags;
if (info.flags & CACHE_FLAG_META)
target.meta = info.meta;
else if (!(info.flags & CACHE_FLAG_MODIFY_XATTRS))
target.flags &= ~CACHE_FLAG_META; // non-meta change should reset meta
if (info.flags & CACHE_FLAG_XATTRS) {
target.xattrs = info.xattrs;
map<string, bufferlist>::iterator iter;
for (iter = target.xattrs.begin(); iter != target.xattrs.end(); ++iter) {
ldpp_dout(dpp, 10) << "updating xattr: name=" << iter->first << " bl.length()=" << iter->second.length() << dendl;
}
} else if (info.flags & CACHE_FLAG_MODIFY_XATTRS) {
map<string, bufferlist>::iterator iter;
for (iter = info.rm_xattrs.begin(); iter != info.rm_xattrs.end(); ++iter) {
ldpp_dout(dpp, 10) << "removing xattr: name=" << iter->first << dendl;
target.xattrs.erase(iter->first);
}
for (iter = info.xattrs.begin(); iter != info.xattrs.end(); ++iter) {
ldpp_dout(dpp, 10) << "appending xattr: name=" << iter->first << " bl.length()=" << iter->second.length() << dendl;
target.xattrs[iter->first] = iter->second;
}
}
if (info.flags & CACHE_FLAG_DATA)
target.data = info.data;
if (info.flags & CACHE_FLAG_OBJV)
target.version = info.version;
}
// WARNING: This function /must not/ be modified to cache a
// negative lookup. It must only invalidate.
bool ObjectCache::invalidate_remove(const DoutPrefixProvider *dpp, const string& name)
{
std::unique_lock l{lock};
if (!enabled) {
return false;
}
auto iter = cache_map.find(name);
if (iter == cache_map.end())
return false;
ldpp_dout(dpp, 10) << "removing " << name << " from cache" << dendl;
ObjectCacheEntry& entry = iter->second;
for (auto& kv : entry.chained_entries) {
kv.first->invalidate(kv.second);
}
remove_lru(name, iter->second.lru_iter);
cache_map.erase(iter);
return true;
}
void ObjectCache::touch_lru(const DoutPrefixProvider *dpp, const string& name, ObjectCacheEntry& entry,
std::list<string>::iterator& lru_iter)
{
while (lru_size > (size_t)cct->_conf->rgw_cache_lru_size) {
auto iter = lru.begin();
if ((*iter).compare(name) == 0) {
/*
* if the entry we're touching happens to be at the lru end, don't remove it,
* lru shrinking can wait for next time
*/
break;
}
auto map_iter = cache_map.find(*iter);
ldout(cct, 10) << "removing entry: name=" << *iter << " from cache LRU" << dendl;
if (map_iter != cache_map.end()) {
ObjectCacheEntry& entry = map_iter->second;
invalidate_lru(entry);
cache_map.erase(map_iter);
}
lru.pop_front();
lru_size--;
}
if (lru_iter == lru.end()) {
lru.push_back(name);
lru_size++;
lru_iter--;
ldpp_dout(dpp, 10) << "adding " << name << " to cache LRU end" << dendl;
} else {
ldpp_dout(dpp, 10) << "moving " << name << " to cache LRU end" << dendl;
lru.erase(lru_iter);
lru.push_back(name);
lru_iter = lru.end();
--lru_iter;
}
lru_counter++;
entry.lru_promotion_ts = lru_counter;
}
void ObjectCache::remove_lru(const string& name,
std::list<string>::iterator& lru_iter)
{
if (lru_iter == lru.end())
return;
lru.erase(lru_iter);
lru_size--;
lru_iter = lru.end();
}
void ObjectCache::invalidate_lru(ObjectCacheEntry& entry)
{
for (auto iter = entry.chained_entries.begin();
iter != entry.chained_entries.end(); ++iter) {
RGWChainedCache *chained_cache = iter->first;
chained_cache->invalidate(iter->second);
}
}
void ObjectCache::set_enabled(bool status)
{
std::unique_lock l{lock};
enabled = status;
if (!enabled) {
do_invalidate_all();
}
}
void ObjectCache::invalidate_all()
{
std::unique_lock l{lock};
do_invalidate_all();
}
void ObjectCache::do_invalidate_all()
{
cache_map.clear();
lru.clear();
lru_size = 0;
lru_counter = 0;
lru_window = 0;
for (auto& cache : chained_cache) {
cache->invalidate_all();
}
}
void ObjectCache::chain_cache(RGWChainedCache *cache) {
std::unique_lock l{lock};
chained_cache.push_back(cache);
}
void ObjectCache::unchain_cache(RGWChainedCache *cache) {
std::unique_lock l{lock};
auto iter = chained_cache.begin();
for (; iter != chained_cache.end(); ++iter) {
if (cache == *iter) {
chained_cache.erase(iter);
cache->unregistered();
return;
}
}
}
ObjectCache::~ObjectCache()
{
for (auto cache : chained_cache) {
cache->unregistered();
}
}
void ObjectMetaInfo::generate_test_instances(list<ObjectMetaInfo*>& o)
{
ObjectMetaInfo *m = new ObjectMetaInfo;
m->size = 1024 * 1024;
o.push_back(m);
o.push_back(new ObjectMetaInfo);
}
void ObjectMetaInfo::dump(Formatter *f) const
{
encode_json("size", size, f);
encode_json("mtime", utime_t(mtime), f);
}
void ObjectCacheInfo::generate_test_instances(list<ObjectCacheInfo*>& o)
{
using ceph::encode;
ObjectCacheInfo *i = new ObjectCacheInfo;
i->status = 0;
i->flags = CACHE_FLAG_MODIFY_XATTRS;
string s = "this is a string";
string s2 = "this is a another string";
bufferlist data, data2;
encode(s, data);
encode(s2, data2);
i->data = data;
i->xattrs["x1"] = data;
i->xattrs["x2"] = data2;
i->rm_xattrs["r2"] = data2;
i->rm_xattrs["r3"] = data;
i->meta.size = 512 * 1024;
o.push_back(i);
o.push_back(new ObjectCacheInfo);
}
void ObjectCacheInfo::dump(Formatter *f) const
{
encode_json("status", status, f);
encode_json("flags", flags, f);
encode_json("data", data, f);
encode_json_map("xattrs", "name", "value", "length", xattrs, f);
encode_json_map("rm_xattrs", "name", "value", "length", rm_xattrs, f);
encode_json("meta", meta, f);
}
void RGWCacheNotifyInfo::generate_test_instances(list<RGWCacheNotifyInfo*>& o)
{
o.push_back(new RGWCacheNotifyInfo);
}
void RGWCacheNotifyInfo::dump(Formatter *f) const
{
encode_json("op", op, f);
encode_json("obj", obj, f);
encode_json("obj_info", obj_info, f);
encode_json("ofs", ofs, f);
encode_json("ns", ns, f);
}
| 11,630 | 26.692857 | 143 |
cc
|
null |
ceph-main/src/rgw/rgw_cache.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#pragma once
#include <string>
#include <map>
#include <unordered_map>
#include "include/types.h"
#include "include/utime.h"
#include "include/ceph_assert.h"
#include "common/ceph_mutex.h"
#include "cls/version/cls_version_types.h"
#include "rgw_common.h"
enum {
UPDATE_OBJ,
INVALIDATE_OBJ,
};
#define CACHE_FLAG_DATA 0x01
#define CACHE_FLAG_XATTRS 0x02
#define CACHE_FLAG_META 0x04
#define CACHE_FLAG_MODIFY_XATTRS 0x08
#define CACHE_FLAG_OBJV 0x10
struct ObjectMetaInfo {
uint64_t size;
real_time mtime;
ObjectMetaInfo() : size(0) {}
void encode(bufferlist& bl) const {
ENCODE_START(2, 2, bl);
encode(size, bl);
encode(mtime, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& bl) {
DECODE_START_LEGACY_COMPAT_LEN(2, 2, 2, bl);
decode(size, bl);
decode(mtime, bl);
DECODE_FINISH(bl);
}
void dump(Formatter *f) const;
static void generate_test_instances(std::list<ObjectMetaInfo*>& o);
};
WRITE_CLASS_ENCODER(ObjectMetaInfo)
struct ObjectCacheInfo {
int status = 0;
uint32_t flags = 0;
uint64_t epoch = 0;
bufferlist data;
std::map<std::string, bufferlist> xattrs;
std::map<std::string, bufferlist> rm_xattrs;
ObjectMetaInfo meta;
obj_version version = {};
ceph::coarse_mono_time time_added;
ObjectCacheInfo() = default;
void encode(bufferlist& bl) const {
ENCODE_START(5, 3, bl);
encode(status, bl);
encode(flags, bl);
encode(data, bl);
encode(xattrs, bl);
encode(meta, bl);
encode(rm_xattrs, bl);
encode(epoch, bl);
encode(version, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& bl) {
DECODE_START_LEGACY_COMPAT_LEN(5, 3, 3, bl);
decode(status, bl);
decode(flags, bl);
decode(data, bl);
decode(xattrs, bl);
decode(meta, bl);
if (struct_v >= 2)
decode(rm_xattrs, bl);
if (struct_v >= 4)
decode(epoch, bl);
if (struct_v >= 5)
decode(version, bl);
DECODE_FINISH(bl);
}
void dump(Formatter *f) const;
static void generate_test_instances(std::list<ObjectCacheInfo*>& o);
};
WRITE_CLASS_ENCODER(ObjectCacheInfo)
struct RGWCacheNotifyInfo {
uint32_t op;
rgw_raw_obj obj;
ObjectCacheInfo obj_info;
off_t ofs;
std::string ns;
RGWCacheNotifyInfo() : op(0), ofs(0) {}
void encode(bufferlist& obl) const {
ENCODE_START(2, 2, obl);
encode(op, obl);
encode(obj, obl);
encode(obj_info, obl);
encode(ofs, obl);
encode(ns, obl);
ENCODE_FINISH(obl);
}
void decode(bufferlist::const_iterator& ibl) {
DECODE_START_LEGACY_COMPAT_LEN(2, 2, 2, ibl);
decode(op, ibl);
decode(obj, ibl);
decode(obj_info, ibl);
decode(ofs, ibl);
decode(ns, ibl);
DECODE_FINISH(ibl);
}
void dump(Formatter *f) const;
static void generate_test_instances(std::list<RGWCacheNotifyInfo*>& o);
};
WRITE_CLASS_ENCODER(RGWCacheNotifyInfo)
inline std::ostream& operator <<(std::ostream& m, const RGWCacheNotifyInfo& cni) {
return m << "[op: " << cni.op << ", obj: " << cni.obj
<< ", ofs" << cni.ofs << ", ns" << cni.ns << "]";
}
class RGWChainedCache {
public:
virtual ~RGWChainedCache() {}
virtual void chain_cb(const std::string& key, void *data) = 0;
virtual void invalidate(const std::string& key) = 0;
virtual void invalidate_all() = 0;
virtual void unregistered() {}
struct Entry {
RGWChainedCache *cache;
const std::string& key;
void *data;
Entry(RGWChainedCache *_c, const std::string& _k, void *_d) : cache(_c), key(_k), data(_d) {}
};
};
struct ObjectCacheEntry {
ObjectCacheInfo info;
std::list<std::string>::iterator lru_iter;
uint64_t lru_promotion_ts;
uint64_t gen;
std::vector<std::pair<RGWChainedCache *, std::string> > chained_entries;
ObjectCacheEntry() : lru_promotion_ts(0), gen(0) {}
};
class ObjectCache {
std::unordered_map<std::string, ObjectCacheEntry> cache_map;
std::list<std::string> lru;
unsigned long lru_size;
unsigned long lru_counter;
unsigned long lru_window;
ceph::shared_mutex lock = ceph::make_shared_mutex("ObjectCache");
CephContext *cct;
std::vector<RGWChainedCache *> chained_cache;
bool enabled;
ceph::timespan expiry;
void touch_lru(const DoutPrefixProvider *dpp, const std::string& name, ObjectCacheEntry& entry,
std::list<std::string>::iterator& lru_iter);
void remove_lru(const std::string& name, std::list<std::string>::iterator& lru_iter);
void invalidate_lru(ObjectCacheEntry& entry);
void do_invalidate_all();
public:
ObjectCache() : lru_size(0), lru_counter(0), lru_window(0), cct(NULL), enabled(false) { }
~ObjectCache();
int get(const DoutPrefixProvider *dpp, const std::string& name, ObjectCacheInfo& bl, uint32_t mask, rgw_cache_entry_info *cache_info);
std::optional<ObjectCacheInfo> get(const DoutPrefixProvider *dpp, const std::string& name) {
std::optional<ObjectCacheInfo> info{std::in_place};
auto r = get(dpp, name, *info, 0, nullptr);
return r < 0 ? std::nullopt : info;
}
template<typename F>
void for_each(const F& f) {
std::shared_lock l{lock};
if (enabled) {
auto now = ceph::coarse_mono_clock::now();
for (const auto& [name, entry] : cache_map) {
if (expiry.count() && (now - entry.info.time_added) < expiry) {
f(name, entry);
}
}
}
}
void put(const DoutPrefixProvider *dpp, const std::string& name, ObjectCacheInfo& bl, rgw_cache_entry_info *cache_info);
bool invalidate_remove(const DoutPrefixProvider *dpp, const std::string& name);
void set_ctx(CephContext *_cct) {
cct = _cct;
lru_window = cct->_conf->rgw_cache_lru_size / 2;
expiry = std::chrono::seconds(cct->_conf.get_val<uint64_t>(
"rgw_cache_expiry_interval"));
}
bool chain_cache_entry(const DoutPrefixProvider *dpp,
std::initializer_list<rgw_cache_entry_info*> cache_info_entries,
RGWChainedCache::Entry *chained_entry);
void set_enabled(bool status);
void chain_cache(RGWChainedCache *cache);
void unchain_cache(RGWChainedCache *cache);
void invalidate_all();
};
| 6,247 | 27.017937 | 136 |
h
|
null |
ceph-main/src/rgw/rgw_client_io.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include "rgw_client_io.h"
#include "rgw_crypt.h"
#include "rgw_crypt_sanitize.h"
#define dout_subsys ceph_subsys_rgw
namespace rgw {
namespace io {
[[nodiscard]] int BasicClient::init(CephContext *cct) {
int init_error = init_env(cct);
if (init_error != 0)
return init_error;
if (cct->_conf->subsys.should_gather<ceph_subsys_rgw, 20>()) {
const auto& env_map = get_env().get_map();
for (const auto& iter: env_map) {
rgw::crypt_sanitize::env x{iter.first, iter.second};
ldout(cct, 20) << iter.first << "=" << (x) << dendl;
}
}
return init_error;
}
} /* namespace io */
} /* namespace rgw */
| 801 | 21.914286 | 70 |
cc
|
null |
ceph-main/src/rgw/rgw_client_io.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#pragma once
#include <exception>
#include <string>
#include <string_view>
#include <streambuf>
#include <istream>
#include <stdlib.h>
#include <system_error>
#include "include/types.h"
#include "rgw_common.h"
class RGWRestfulIO;
namespace rgw {
namespace io {
using Exception = std::system_error;
/* The minimal and simplest subset of methods that a client of RadosGW can be
* interacted with. */
class BasicClient {
protected:
virtual int init_env(CephContext *cct) = 0;
public:
virtual ~BasicClient() = default;
/* Initialize the BasicClient and inject CephContext. */
int init(CephContext *cct);
/* Return the RGWEnv describing the environment that a given request lives in.
* The method does not throw exceptions. */
virtual RGWEnv& get_env() noexcept = 0;
/* Complete request.
* On success returns number of bytes generated for a direct client of RadosGW.
* On failure throws rgw::io::Exception containing errno. */
virtual size_t complete_request() = 0;
}; /* rgw::io::Client */
class Accounter {
public:
virtual ~Accounter() = default;
/* Enable or disable the accounting of both sent and received data. Changing
* the state does not affect the counters. */
virtual void set_account(bool enabled) = 0;
/* Return number of bytes sent to a direct client of RadosGW (direct means
* eg. a web server instance in the case of using FastCGI front-end) when
* the accounting was enabled. */
virtual uint64_t get_bytes_sent() const = 0;
/* Return number of bytes received from a direct client of RadosGW (direct
* means eg. a web server instance in the case of using FastCGI front-end)
* when the accounting was enabled. */
virtual uint64_t get_bytes_received() const = 0;
}; /* rgw::io::Accounter */
/* Interface abstracting restful interactions with clients, usually through
* the HTTP protocol. The methods participating in the response generation
* process should be called in the specific order:
* 1. send_100_continue() - at most once,
* 2. send_status() - exactly once,
* 3. Any of:
* a. send_header(),
* b. send_content_length() XOR send_chunked_transfer_encoding()
* Please note that only one of those two methods must be called
at most once.
* 4. complete_header() - exactly once,
* 5. send_body()
* 6. complete_request() - exactly once.
* There are no restrictions on flush() - it may be called in any moment.
*
* Receiving data from a client isn't a subject to any further call order
* restrictions besides those imposed by BasicClient. That is, get_env()
* and recv_body can be mixed. */
class RestfulClient : public BasicClient {
template<typename T> friend class DecoratedRestfulClient;
public:
/* Generate the 100 Continue message.
* On success returns number of bytes generated for a direct client of RadosGW.
* On failure throws rgw::io::Exception containing errno. */
virtual size_t send_100_continue() = 0;
/* Generate the response's status part taking the HTTP status code as @status
* and its name pointed in @status_name.
* On success returns number of bytes generated for a direct client of RadosGW.
* On failure throws rgw::io::Exception containing errno. */
virtual size_t send_status(int status, const char *status_name) = 0;
/* Generate header. On success returns number of bytes generated for a direct
* client of RadosGW. On failure throws rgw::io::Exception containing errno.
*
* std::string_view is being used because of length it internally carries. */
virtual size_t send_header(const std::string_view& name,
const std::string_view& value) = 0;
/* Inform a client about a content length. Takes number of bytes as @len.
* On success returns number of bytes generated for a direct client of RadosGW.
* On failure throws rgw::io::Exception containing errno.
*
* CALL LIMITATIONS:
* - The method must be called EXACTLY ONCE.
* - The method is interchangeable with send_chunked_transfer_encoding(). */
virtual size_t send_content_length(uint64_t len) = 0;
/* Inform a client that the chunked transfer encoding will be used.
* On success returns number of bytes generated for a direct client of RadosGW.
* On failure throws rgw::io::Exception containing errno.
*
* CALL LIMITATIONS:
* - The method must be called EXACTLY ONCE.
* - The method is interchangeable with send_content_length(). */
virtual size_t send_chunked_transfer_encoding() {
/* This is a null implementation. We don't send anything here, even the HTTP
* header. The intended behaviour should be provided through a decorator or
* directly by a given front-end. */
return 0;
}
/* Generate completion (the CRLF sequence separating headers and body in
* the case of HTTP) of headers. On success returns number of generated bytes
* for a direct client of RadosGW. On failure throws rgw::io::Exception with
* errno. */
virtual size_t complete_header() = 0;
/* Receive no more than @max bytes from a request's body and store it in
* buffer pointed by @buf. On success returns number of bytes received from
* a direct client of RadosGW that has been stored in @buf. On failure throws
* rgw::io::Exception containing errno. */
virtual size_t recv_body(char* buf, size_t max) = 0;
/* Generate a part of response's body by taking exactly @len bytes from
* the buffer pointed by @buf. On success returns number of generated bytes
* of response's body. On failure throws rgw::io::Exception. */
virtual size_t send_body(const char* buf, size_t len) = 0;
/* Flushes all already generated data to a direct client of RadosGW.
* On failure throws rgw::io::Exception containing errno. */
virtual void flush() = 0;
} /* rgw::io::RestfulClient */;
/* Abstract decorator over any implementation of rgw::io::RestfulClient
* which could be provided both as a pointer-to-object or the object itself. */
template <typename DecorateeT>
class DecoratedRestfulClient : public RestfulClient {
template<typename T> friend class DecoratedRestfulClient;
friend RGWRestfulIO;
typedef typename std::remove_pointer<DecorateeT>::type DerefedDecorateeT;
static_assert(std::is_base_of<RestfulClient, DerefedDecorateeT>::value,
"DecorateeT must be a subclass of rgw::io::RestfulClient");
DecorateeT decoratee;
/* There is an indirection layer over accessing decoratee to share the same
* code base between dynamic and static decorators. The difference is about
* what we store internally: pointer to a decorated object versus the whole
* object itself. */
template <typename T = void,
typename std::enable_if<
! std::is_pointer<DecorateeT>::value, T>::type* = nullptr>
DerefedDecorateeT& get_decoratee() {
return decoratee;
}
protected:
template <typename T = void,
typename std::enable_if<
std::is_pointer<DecorateeT>::value, T>::type* = nullptr>
DerefedDecorateeT& get_decoratee() {
return *decoratee;
}
/* Dynamic decorators (those storing a pointer instead of the decorated
* object itself) can be reconfigured on-the-fly. HOWEVER: there are no
* facilities for orchestrating such changes. Callers must take care of
* atomicity and thread-safety. */
template <typename T = void,
typename std::enable_if<
std::is_pointer<DecorateeT>::value, T>::type* = nullptr>
void set_decoratee(DerefedDecorateeT& new_dec) {
decoratee = &new_dec;
}
int init_env(CephContext *cct) override {
return get_decoratee().init_env(cct);
}
public:
explicit DecoratedRestfulClient(DecorateeT&& decoratee)
: decoratee(std::forward<DecorateeT>(decoratee)) {
}
size_t send_status(const int status,
const char* const status_name) override {
return get_decoratee().send_status(status, status_name);
}
size_t send_100_continue() override {
return get_decoratee().send_100_continue();
}
size_t send_header(const std::string_view& name,
const std::string_view& value) override {
return get_decoratee().send_header(name, value);
}
size_t send_content_length(const uint64_t len) override {
return get_decoratee().send_content_length(len);
}
size_t send_chunked_transfer_encoding() override {
return get_decoratee().send_chunked_transfer_encoding();
}
size_t complete_header() override {
return get_decoratee().complete_header();
}
size_t recv_body(char* const buf, const size_t max) override {
return get_decoratee().recv_body(buf, max);
}
size_t send_body(const char* const buf,
const size_t len) override {
return get_decoratee().send_body(buf, len);
}
void flush() override {
return get_decoratee().flush();
}
RGWEnv& get_env() noexcept override {
return get_decoratee().get_env();
}
size_t complete_request() override {
return get_decoratee().complete_request();
}
} /* rgw::io::DecoratedRestfulClient */;
/* Interface that should be provided by a front-end class wanting to use
* the low-level buffering offered by i.e. StaticOutputBufferer. */
class BuffererSink {
public:
virtual ~BuffererSink() = default;
/* Send exactly @len bytes from the memory location pointed by @buf.
* On success returns @len. On failure throws rgw::io::Exception. */
virtual size_t write_data(const char *buf, size_t len) = 0;
};
/* Utility class providing RestfulClient's implementations with facilities
* for low-level buffering without relying on dynamic memory allocations.
* The buffer is carried entirely on stack. This narrows down applicability
* to these situations where buffers are relatively small. This perfectly
* fits the needs of composing an HTTP header. Without that a front-end
* might need to issue a lot of small IO operations leading to increased
* overhead on syscalls and fragmentation of a message if the Nagle's
* algorithm won't be able to form a single TCP segment (usually when
* running on extremely fast network interfaces like the loopback). */
template <size_t BufferSizeV = 4096>
class StaticOutputBufferer : public std::streambuf {
static_assert(BufferSizeV >= sizeof(std::streambuf::char_type),
"Buffer size must be bigger than a single char_type.");
using std::streambuf::int_type;
int_type overflow(const int_type c) override {
*pptr() = c;
pbump(sizeof(std::streambuf::char_type));
if (! sync()) {
/* No error, the buffer has been successfully synchronized. */
return c;
} else {
return std::streambuf::traits_type::eof();
}
}
int sync() override {
const auto len = static_cast<size_t>(std::streambuf::pptr() -
std::streambuf::pbase());
std::streambuf::pbump(-len);
sink.write_data(std::streambuf::pbase(), len);
/* Always return success here. In case of failure write_data() will throw
* rgw::io::Exception. */
return 0;
}
BuffererSink& sink;
std::streambuf::char_type buffer[BufferSizeV];
public:
explicit StaticOutputBufferer(BuffererSink& sink)
: sink(sink) {
constexpr size_t len = sizeof(buffer) - sizeof(std::streambuf::char_type);
std::streambuf::setp(buffer, buffer + len);
}
};
} /* namespace io */
} /* namespace rgw */
/* We're doing this nasty thing only because of extensive usage of templates
* to implement the static decorator pattern. C++ templates de facto enforce
* mixing interfaces with implementation. Additionally, those classes derive
* from RGWRestfulIO defined here. I believe that including in the middle of
* file is still better than polluting it directly. */
#include "rgw_client_io_filters.h"
/* RGWRestfulIO: high level interface to interact with RESTful clients. What
* differentiates it from rgw::io::RestfulClient is providing more specific APIs
* like rgw::io::Accounter or the AWS Auth v4 stuff implemented by filters
* while hiding the pipelined architecture from clients.
*
* rgw::io::Accounter came in as a part of rgw::io::AccountingFilter. */
class RGWRestfulIO : public rgw::io::AccountingFilter<rgw::io::RestfulClient*> {
std::vector<std::shared_ptr<DecoratedRestfulClient>> filters;
public:
~RGWRestfulIO() override = default;
RGWRestfulIO(CephContext *_cx, rgw::io::RestfulClient* engine)
: AccountingFilter<rgw::io::RestfulClient*>(_cx, std::move(engine)) {
}
void add_filter(std::shared_ptr<DecoratedRestfulClient> new_filter) {
new_filter->set_decoratee(this->get_decoratee());
this->set_decoratee(*new_filter);
filters.emplace_back(std::move(new_filter));
}
}; /* RGWRestfulIO */
/* Type conversions to work around lack of req_state type hierarchy matching
* (e.g.) REST backends (may be replaced w/dynamic typed req_state). */
static inline rgw::io::RestfulClient* RESTFUL_IO(req_state* s) {
ceph_assert(dynamic_cast<rgw::io::RestfulClient*>(s->cio) != nullptr);
return static_cast<rgw::io::RestfulClient*>(s->cio);
}
static inline rgw::io::Accounter* ACCOUNTING_IO(req_state* s) {
auto ptr = dynamic_cast<rgw::io::Accounter*>(s->cio);
ceph_assert(ptr != nullptr);
return ptr;
}
static inline RGWRestfulIO* AWS_AUTHv4_IO(const req_state* const s) {
ceph_assert(dynamic_cast<RGWRestfulIO*>(s->cio) != nullptr);
return static_cast<RGWRestfulIO*>(s->cio);
}
class RGWClientIOStreamBuf : public std::streambuf {
protected:
RGWRestfulIO &rio;
size_t const window_size;
size_t const putback_size;
std::vector<char> buffer;
public:
RGWClientIOStreamBuf(RGWRestfulIO &rio, size_t ws, size_t ps = 1)
: rio(rio),
window_size(ws),
putback_size(ps),
buffer(ws + ps)
{
setg(nullptr, nullptr, nullptr);
}
std::streambuf::int_type underflow() override {
if (gptr() < egptr()) {
return traits_type::to_int_type(*gptr());
}
char * const base = buffer.data();
char * start;
if (nullptr != eback()) {
/* We need to skip moving bytes on first underflow. In such case
* there is simply no previous data we should preserve for unget()
* or something similar. */
std::memmove(base, egptr() - putback_size, putback_size);
start = base + putback_size;
} else {
start = base;
}
size_t read_len = 0;
try {
read_len = rio.recv_body(base, window_size);
} catch (rgw::io::Exception&) {
return traits_type::eof();
}
if (0 == read_len) {
return traits_type::eof();
}
setg(base, start, start + read_len);
return traits_type::to_int_type(*gptr());
}
};
class RGWClientIOStream : private RGWClientIOStreamBuf, public std::istream {
/* Inheritance from RGWClientIOStreamBuf is a kind of shadow, undirect
* form of composition here. We cannot do that explicitly because istream
* ctor is being called prior to construction of any member of this class. */
public:
explicit RGWClientIOStream(RGWRestfulIO &s)
: RGWClientIOStreamBuf(s, 1, 2),
std::istream(static_cast<RGWClientIOStreamBuf *>(this)) {
}
};
| 15,240 | 33.956422 | 81 |
h
|
null |
ceph-main/src/rgw/rgw_client_io_filters.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#pragma once
#include <type_traits>
#include <boost/optional.hpp>
#include "rgw_common.h"
#include "rgw_client_io.h"
namespace rgw {
namespace io {
template <typename T>
class AccountingFilter : public DecoratedRestfulClient<T>,
public Accounter {
bool enabled;
uint64_t total_sent;
uint64_t total_received;
CephContext *cct;
public:
template <typename U>
AccountingFilter(CephContext *cct, U&& decoratee)
: DecoratedRestfulClient<T>(std::forward<U>(decoratee)),
enabled(false),
total_sent(0),
total_received(0), cct(cct) {
}
size_t send_status(const int status,
const char* const status_name) override {
const auto sent = DecoratedRestfulClient<T>::send_status(status,
status_name);
lsubdout(cct, rgw, 30) << "AccountingFilter::send_status: e="
<< (enabled ? "1" : "0") << ", sent=" << sent << ", total="
<< total_sent << dendl;
if (enabled) {
total_sent += sent;
}
return sent;
}
size_t send_100_continue() override {
const auto sent = DecoratedRestfulClient<T>::send_100_continue();
lsubdout(cct, rgw, 30) << "AccountingFilter::send_100_continue: e="
<< (enabled ? "1" : "0") << ", sent=" << sent << ", total="
<< total_sent << dendl;
if (enabled) {
total_sent += sent;
}
return sent;
}
size_t send_header(const std::string_view& name,
const std::string_view& value) override {
const auto sent = DecoratedRestfulClient<T>::send_header(name, value);
lsubdout(cct, rgw, 30) << "AccountingFilter::send_header: e="
<< (enabled ? "1" : "0") << ", sent=" << sent << ", total="
<< total_sent << dendl;
if (enabled) {
total_sent += sent;
}
return sent;
}
size_t send_content_length(const uint64_t len) override {
const auto sent = DecoratedRestfulClient<T>::send_content_length(len);
lsubdout(cct, rgw, 30) << "AccountingFilter::send_content_length: e="
<< (enabled ? "1" : "0") << ", sent=" << sent << ", total="
<< total_sent << dendl;
if (enabled) {
total_sent += sent;
}
return sent;
}
size_t send_chunked_transfer_encoding() override {
const auto sent = DecoratedRestfulClient<T>::send_chunked_transfer_encoding();
lsubdout(cct, rgw, 30) << "AccountingFilter::send_chunked_transfer_encoding: e="
<< (enabled ? "1" : "0") << ", sent=" << sent << ", total="
<< total_sent << dendl;
if (enabled) {
total_sent += sent;
}
return sent;
}
size_t complete_header() override {
const auto sent = DecoratedRestfulClient<T>::complete_header();
lsubdout(cct, rgw, 30) << "AccountingFilter::complete_header: e="
<< (enabled ? "1" : "0") << ", sent=" << sent << ", total="
<< total_sent << dendl;
if (enabled) {
total_sent += sent;
}
return sent;
}
size_t recv_body(char* buf, size_t max) override {
const auto received = DecoratedRestfulClient<T>::recv_body(buf, max);
lsubdout(cct, rgw, 30) << "AccountingFilter::recv_body: e="
<< (enabled ? "1" : "0") << ", received=" << received << dendl;
if (enabled) {
total_received += received;
}
return received;
}
size_t send_body(const char* const buf,
const size_t len) override {
const auto sent = DecoratedRestfulClient<T>::send_body(buf, len);
lsubdout(cct, rgw, 30) << "AccountingFilter::send_body: e="
<< (enabled ? "1" : "0") << ", sent=" << sent << ", total="
<< total_sent << dendl;
if (enabled) {
total_sent += sent;
}
return sent;
}
size_t complete_request() override {
const auto sent = DecoratedRestfulClient<T>::complete_request();
lsubdout(cct, rgw, 30) << "AccountingFilter::complete_request: e="
<< (enabled ? "1" : "0") << ", sent=" << sent << ", total="
<< total_sent << dendl;
if (enabled) {
total_sent += sent;
}
return sent;
}
uint64_t get_bytes_sent() const override {
return total_sent;
}
uint64_t get_bytes_received() const override {
return total_received;
}
void set_account(bool enabled) override {
this->enabled = enabled;
lsubdout(cct, rgw, 30) << "AccountingFilter::set_account: e="
<< (enabled ? "1" : "0") << dendl;
}
};
/* Filter for in-memory buffering incoming data and calculating the content
* length header if it isn't present. */
template <typename T>
class BufferingFilter : public DecoratedRestfulClient<T> {
template<typename Td> friend class DecoratedRestfulClient;
protected:
ceph::bufferlist data;
bool has_content_length;
bool buffer_data;
CephContext *cct;
public:
template <typename U>
BufferingFilter(CephContext *cct, U&& decoratee)
: DecoratedRestfulClient<T>(std::forward<U>(decoratee)),
has_content_length(false),
buffer_data(false), cct(cct) {
}
size_t send_content_length(const uint64_t len) override;
size_t send_chunked_transfer_encoding() override;
size_t complete_header() override;
size_t send_body(const char* buf, size_t len) override;
size_t complete_request() override;
};
template <typename T>
size_t BufferingFilter<T>::send_body(const char* const buf,
const size_t len)
{
if (buffer_data) {
data.append(buf, len);
lsubdout(cct, rgw, 30) << "BufferingFilter<T>::send_body: defer count = "
<< len << dendl;
return 0;
}
return DecoratedRestfulClient<T>::send_body(buf, len);
}
template <typename T>
size_t BufferingFilter<T>::send_content_length(const uint64_t len)
{
has_content_length = true;
return DecoratedRestfulClient<T>::send_content_length(len);
}
template <typename T>
size_t BufferingFilter<T>::send_chunked_transfer_encoding()
{
has_content_length = true;
return DecoratedRestfulClient<T>::send_chunked_transfer_encoding();
}
template <typename T>
size_t BufferingFilter<T>::complete_header()
{
if (! has_content_length) {
/* We will dump everything in complete_request(). */
buffer_data = true;
lsubdout(cct, rgw, 30) << "BufferingFilter<T>::complete_header: has_content_length="
<< (has_content_length ? "1" : "0") << dendl;
return 0;
}
return DecoratedRestfulClient<T>::complete_header();
}
template <typename T>
size_t BufferingFilter<T>::complete_request()
{
size_t sent = 0;
if (! has_content_length) {
/* It is not correct to count these bytes here,
* because they can only be part of the header.
* Therefore force count to 0.
*/
sent += DecoratedRestfulClient<T>::send_content_length(data.length());
sent += DecoratedRestfulClient<T>::complete_header();
lsubdout(cct, rgw, 30) <<
"BufferingFilter::complete_request: !has_content_length: IGNORE: sent="
<< sent << dendl;
sent = 0;
}
if (buffer_data) {
/* We are sending each buffer separately to avoid extra memory shuffling
* that would occur on data.c_str() to provide a continuous memory area. */
for (const auto& ptr : data.buffers()) {
sent += DecoratedRestfulClient<T>::send_body(ptr.c_str(),
ptr.length());
}
data.clear();
buffer_data = false;
lsubdout(cct, rgw, 30) << "BufferingFilter::complete_request: buffer_data: sent="
<< sent << dendl;
}
return sent + DecoratedRestfulClient<T>::complete_request();
}
template <typename T> static inline
BufferingFilter<T> add_buffering(
CephContext *cct,
T&& t) {
return BufferingFilter<T>(cct, std::forward<T>(t));
}
template <typename T>
class ChunkingFilter : public DecoratedRestfulClient<T> {
template<typename Td> friend class DecoratedRestfulClient;
protected:
bool chunking_enabled;
public:
template <typename U>
explicit ChunkingFilter(U&& decoratee)
: DecoratedRestfulClient<T>(std::forward<U>(decoratee)),
chunking_enabled(false) {
}
size_t send_chunked_transfer_encoding() override {
chunking_enabled = true;
return DecoratedRestfulClient<T>::send_header("Transfer-Encoding",
"chunked");
}
size_t send_body(const char* buf,
const size_t len) override {
if (! chunking_enabled) {
return DecoratedRestfulClient<T>::send_body(buf, len);
} else {
static constexpr char HEADER_END[] = "\r\n";
/* https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.6.1 */
// TODO: we have no support for sending chunked-encoding
// extensions/trailing headers.
char chunk_size[32];
const auto chunk_size_len = snprintf(chunk_size, sizeof(chunk_size),
"%zx\r\n", len);
size_t sent = 0;
sent += DecoratedRestfulClient<T>::send_body(chunk_size, chunk_size_len);
sent += DecoratedRestfulClient<T>::send_body(buf, len);
sent += DecoratedRestfulClient<T>::send_body(HEADER_END,
sizeof(HEADER_END) - 1);
return sent;
}
}
size_t complete_request() override {
size_t sent = 0;
if (chunking_enabled) {
static constexpr char CHUNKED_RESP_END[] = "0\r\n\r\n";
sent += DecoratedRestfulClient<T>::send_body(CHUNKED_RESP_END,
sizeof(CHUNKED_RESP_END) - 1);
}
return sent + DecoratedRestfulClient<T>::complete_request();
}
};
template <typename T> static inline
ChunkingFilter<T> add_chunking(T&& t) {
return ChunkingFilter<T>(std::forward<T>(t));
}
/* Class that controls and inhibits the process of sending Content-Length HTTP
* header where RFC 7230 requests so. The cases worth our attention are 204 No
* Content as well as 304 Not Modified. */
template <typename T>
class ConLenControllingFilter : public DecoratedRestfulClient<T> {
protected:
enum class ContentLengthAction {
FORWARD,
INHIBIT,
UNKNOWN
} action;
public:
template <typename U>
explicit ConLenControllingFilter(U&& decoratee)
: DecoratedRestfulClient<T>(std::forward<U>(decoratee)),
action(ContentLengthAction::UNKNOWN) {
}
size_t send_status(const int status,
const char* const status_name) override {
if ((204 == status || 304 == status) &&
! g_conf()->rgw_print_prohibited_content_length) {
action = ContentLengthAction::INHIBIT;
} else {
action = ContentLengthAction::FORWARD;
}
return DecoratedRestfulClient<T>::send_status(status, status_name);
}
size_t send_content_length(const uint64_t len) override {
switch(action) {
case ContentLengthAction::FORWARD:
return DecoratedRestfulClient<T>::send_content_length(len);
case ContentLengthAction::INHIBIT:
return 0;
case ContentLengthAction::UNKNOWN:
default:
return -EINVAL;
}
}
};
template <typename T> static inline
ConLenControllingFilter<T> add_conlen_controlling(T&& t) {
return ConLenControllingFilter<T>(std::forward<T>(t));
}
/* Filter that rectifies the wrong behaviour of some clients of the RGWRestfulIO
* interface. Should be removed after fixing those clients. */
template <typename T>
class ReorderingFilter : public DecoratedRestfulClient<T> {
protected:
enum class ReorderState {
RGW_EARLY_HEADERS, /* Got headers sent before calling send_status. */
RGW_STATUS_SEEN, /* Status has been seen. */
RGW_DATA /* Header has been completed. */
} phase;
boost::optional<uint64_t> content_length;
std::vector<std::pair<std::string, std::string>> headers;
size_t send_header(const std::string_view& name,
const std::string_view& value) override {
switch (phase) {
case ReorderState::RGW_EARLY_HEADERS:
case ReorderState::RGW_STATUS_SEEN:
headers.emplace_back(std::make_pair(std::string(name.data(), name.size()),
std::string(value.data(), value.size())));
return 0;
case ReorderState::RGW_DATA:
return DecoratedRestfulClient<T>::send_header(name, value);
}
return -EIO;
}
public:
template <typename U>
explicit ReorderingFilter(U&& decoratee)
: DecoratedRestfulClient<T>(std::forward<U>(decoratee)),
phase(ReorderState::RGW_EARLY_HEADERS) {
}
size_t send_status(const int status,
const char* const status_name) override {
phase = ReorderState::RGW_STATUS_SEEN;
return DecoratedRestfulClient<T>::send_status(status, status_name);
}
size_t send_content_length(const uint64_t len) override {
if (ReorderState::RGW_EARLY_HEADERS == phase) {
/* Oh great, someone tries to send content length before status. */
content_length = len;
return 0;
} else {
return DecoratedRestfulClient<T>::send_content_length(len);
}
}
size_t complete_header() override {
size_t sent = 0;
/* Change state in order to immediately send everything we get. */
phase = ReorderState::RGW_DATA;
/* Sent content length if necessary. */
if (content_length) {
sent += DecoratedRestfulClient<T>::send_content_length(*content_length);
}
/* Header data in buffers are already counted. */
for (const auto& kv : headers) {
sent += DecoratedRestfulClient<T>::send_header(kv.first, kv.second);
}
headers.clear();
return sent + DecoratedRestfulClient<T>::complete_header();
}
};
template <typename T> static inline
ReorderingFilter<T> add_reordering(T&& t) {
return ReorderingFilter<T>(std::forward<T>(t));
}
} /* namespace io */
} /* namespace rgw */
| 13,842 | 29.424176 | 88 |
h
|
null |
ceph-main/src/rgw/rgw_common.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include <errno.h>
#include <vector>
#include <algorithm>
#include <string>
#include <boost/tokenizer.hpp>
#include "json_spirit/json_spirit.h"
#include "common/ceph_json.h"
#include "common/Formatter.h"
#include "rgw_op.h"
#include "rgw_common.h"
#include "rgw_acl.h"
#include "rgw_string.h"
#include "rgw_http_errors.h"
#include "rgw_arn.h"
#include "rgw_data_sync.h"
#include "global/global_init.h"
#include "common/ceph_crypto.h"
#include "common/armor.h"
#include "common/errno.h"
#include "common/Clock.h"
#include "common/convenience.h"
#include "common/strtol.h"
#include "include/str_list.h"
#include "rgw_crypt_sanitize.h"
#include "rgw_bucket_sync.h"
#include "rgw_sync_policy.h"
#include "services/svc_zone.h"
#include <sstream>
#define dout_context g_ceph_context
static constexpr auto dout_subsys = ceph_subsys_rgw;
using rgw::ARN;
using rgw::IAM::Effect;
using rgw::IAM::op_to_perm;
using rgw::IAM::Policy;
const uint32_t RGWBucketInfo::NUM_SHARDS_BLIND_BUCKET(UINT32_MAX);
rgw_http_errors rgw_http_s3_errors({
{ 0, {200, "" }},
{ STATUS_CREATED, {201, "Created" }},
{ STATUS_ACCEPTED, {202, "Accepted" }},
{ STATUS_NO_CONTENT, {204, "NoContent" }},
{ STATUS_PARTIAL_CONTENT, {206, "" }},
{ ERR_PERMANENT_REDIRECT, {301, "PermanentRedirect" }},
{ ERR_WEBSITE_REDIRECT, {301, "WebsiteRedirect" }},
{ STATUS_REDIRECT, {303, "" }},
{ ERR_NOT_MODIFIED, {304, "NotModified" }},
{ EINVAL, {400, "InvalidArgument" }},
{ ERR_INVALID_REQUEST, {400, "InvalidRequest" }},
{ ERR_INVALID_DIGEST, {400, "InvalidDigest" }},
{ ERR_BAD_DIGEST, {400, "BadDigest" }},
{ ERR_INVALID_LOCATION_CONSTRAINT, {400, "InvalidLocationConstraint" }},
{ ERR_ZONEGROUP_DEFAULT_PLACEMENT_MISCONFIGURATION, {400, "ZonegroupDefaultPlacementMisconfiguration" }},
{ ERR_INVALID_BUCKET_NAME, {400, "InvalidBucketName" }},
{ ERR_INVALID_OBJECT_NAME, {400, "InvalidObjectName" }},
{ ERR_UNRESOLVABLE_EMAIL, {400, "UnresolvableGrantByEmailAddress" }},
{ ERR_INVALID_PART, {400, "InvalidPart" }},
{ ERR_INVALID_PART_ORDER, {400, "InvalidPartOrder" }},
{ ERR_REQUEST_TIMEOUT, {400, "RequestTimeout" }},
{ ERR_TOO_LARGE, {400, "EntityTooLarge" }},
{ ERR_TOO_SMALL, {400, "EntityTooSmall" }},
{ ERR_TOO_MANY_BUCKETS, {400, "TooManyBuckets" }},
{ ERR_MALFORMED_XML, {400, "MalformedXML" }},
{ ERR_AMZ_CONTENT_SHA256_MISMATCH, {400, "XAmzContentSHA256Mismatch" }},
{ ERR_MALFORMED_DOC, {400, "MalformedPolicyDocument"}},
{ ERR_INVALID_TAG, {400, "InvalidTag"}},
{ ERR_MALFORMED_ACL_ERROR, {400, "MalformedACLError" }},
{ ERR_INVALID_CORS_RULES_ERROR, {400, "InvalidRequest" }},
{ ERR_INVALID_WEBSITE_ROUTING_RULES_ERROR, {400, "InvalidRequest" }},
{ ERR_INVALID_ENCRYPTION_ALGORITHM, {400, "InvalidEncryptionAlgorithmError" }},
{ ERR_INVALID_RETENTION_PERIOD,{400, "InvalidRetentionPeriod"}},
{ ERR_LIMIT_EXCEEDED, {400, "LimitExceeded" }},
{ ERR_LENGTH_REQUIRED, {411, "MissingContentLength" }},
{ EACCES, {403, "AccessDenied" }},
{ EPERM, {403, "AccessDenied" }},
{ ERR_SIGNATURE_NO_MATCH, {403, "SignatureDoesNotMatch" }},
{ ERR_INVALID_ACCESS_KEY, {403, "InvalidAccessKeyId" }},
{ ERR_USER_SUSPENDED, {403, "UserSuspended" }},
{ ERR_REQUEST_TIME_SKEWED, {403, "RequestTimeTooSkewed" }},
{ ERR_QUOTA_EXCEEDED, {403, "QuotaExceeded" }},
{ ERR_MFA_REQUIRED, {403, "AccessDenied" }},
{ ENOENT, {404, "NoSuchKey" }},
{ ERR_NO_SUCH_BUCKET, {404, "NoSuchBucket" }},
{ ERR_NO_SUCH_WEBSITE_CONFIGURATION, {404, "NoSuchWebsiteConfiguration" }},
{ ERR_NO_SUCH_UPLOAD, {404, "NoSuchUpload" }},
{ ERR_NOT_FOUND, {404, "Not Found"}},
{ ERR_NO_SUCH_LC, {404, "NoSuchLifecycleConfiguration"}},
{ ERR_NO_SUCH_BUCKET_POLICY, {404, "NoSuchBucketPolicy"}},
{ ERR_NO_SUCH_USER, {404, "NoSuchUser"}},
{ ERR_NO_ROLE_FOUND, {404, "NoSuchEntity"}},
{ ERR_NO_CORS_FOUND, {404, "NoSuchCORSConfiguration"}},
{ ERR_NO_SUCH_SUBUSER, {404, "NoSuchSubUser"}},
{ ERR_NO_SUCH_ENTITY, {404, "NoSuchEntity"}},
{ ERR_NO_SUCH_CORS_CONFIGURATION, {404, "NoSuchCORSConfiguration"}},
{ ERR_NO_SUCH_OBJECT_LOCK_CONFIGURATION, {404, "ObjectLockConfigurationNotFoundError"}},
{ ERR_METHOD_NOT_ALLOWED, {405, "MethodNotAllowed" }},
{ ETIMEDOUT, {408, "RequestTimeout" }},
{ EEXIST, {409, "BucketAlreadyExists" }},
{ ERR_USER_EXIST, {409, "UserAlreadyExists" }},
{ ERR_EMAIL_EXIST, {409, "EmailExists" }},
{ ERR_KEY_EXIST, {409, "KeyExists"}},
{ ERR_TAG_CONFLICT, {409, "OperationAborted"}},
{ ERR_POSITION_NOT_EQUAL_TO_LENGTH, {409, "PositionNotEqualToLength"}},
{ ERR_OBJECT_NOT_APPENDABLE, {409, "ObjectNotAppendable"}},
{ ERR_INVALID_BUCKET_STATE, {409, "InvalidBucketState"}},
{ ERR_INVALID_OBJECT_STATE, {403, "InvalidObjectState"}},
{ ERR_INVALID_SECRET_KEY, {400, "InvalidSecretKey"}},
{ ERR_INVALID_KEY_TYPE, {400, "InvalidKeyType"}},
{ ERR_INVALID_CAP, {400, "InvalidCapability"}},
{ ERR_INVALID_TENANT_NAME, {400, "InvalidTenantName" }},
{ ENOTEMPTY, {409, "BucketNotEmpty" }},
{ ERR_PRECONDITION_FAILED, {412, "PreconditionFailed" }},
{ ERANGE, {416, "InvalidRange" }},
{ ERR_UNPROCESSABLE_ENTITY, {422, "UnprocessableEntity" }},
{ ERR_LOCKED, {423, "Locked" }},
{ ERR_INTERNAL_ERROR, {500, "InternalError" }},
{ ERR_NOT_IMPLEMENTED, {501, "NotImplemented" }},
{ ERR_SERVICE_UNAVAILABLE, {503, "ServiceUnavailable"}},
{ ERR_RATE_LIMITED, {503, "SlowDown"}},
{ ERR_ZERO_IN_URL, {400, "InvalidRequest" }},
{ ERR_NO_SUCH_TAG_SET, {404, "NoSuchTagSet"}},
{ ERR_NO_SUCH_BUCKET_ENCRYPTION_CONFIGURATION, {404, "ServerSideEncryptionConfigurationNotFoundError"}},
});
rgw_http_errors rgw_http_swift_errors({
{ EACCES, {403, "AccessDenied" }},
{ EPERM, {401, "AccessDenied" }},
{ ENAMETOOLONG, {400, "Metadata name too long" }},
{ ERR_USER_SUSPENDED, {401, "UserSuspended" }},
{ ERR_INVALID_UTF8, {412, "Invalid UTF8" }},
{ ERR_BAD_URL, {412, "Bad URL" }},
{ ERR_NOT_SLO_MANIFEST, {400, "Not an SLO manifest" }},
{ ERR_QUOTA_EXCEEDED, {413, "QuotaExceeded" }},
{ ENOTEMPTY, {409, "There was a conflict when trying "
"to complete your request." }},
/* FIXME(rzarzynski): we need to find a way to apply Swift's error handling
* procedures also for ERR_ZERO_IN_URL. This make a problem as the validation
* is performed very early, even before setting the req_state::proto_flags. */
{ ERR_ZERO_IN_URL, {412, "Invalid UTF8 or contains NULL"}},
{ ERR_RATE_LIMITED, {498, "Rate Limited"}},
});
rgw_http_errors rgw_http_sts_errors({
{ ERR_PACKED_POLICY_TOO_LARGE, {400, "PackedPolicyTooLarge" }},
{ ERR_INVALID_IDENTITY_TOKEN, {400, "InvalidIdentityToken" }},
});
rgw_http_errors rgw_http_iam_errors({
{ EINVAL, {400, "InvalidInput" }},
{ ENOENT, {404, "NoSuchEntity"}},
{ ERR_ROLE_EXISTS, {409, "EntityAlreadyExists"}},
{ ERR_DELETE_CONFLICT, {409, "DeleteConflict"}},
{ EEXIST, {409, "EntityAlreadyExists"}},
{ ERR_INTERNAL_ERROR, {500, "ServiceFailure" }},
});
using namespace std;
using namespace ceph::crypto;
thread_local bool is_asio_thread = false;
rgw_err::
rgw_err()
{
clear();
}
void rgw_err::
clear()
{
http_ret = 200;
ret = 0;
err_code.clear();
}
bool rgw_err::
is_clear() const
{
return (http_ret == 200);
}
bool rgw_err::
is_err() const
{
return !(http_ret >= 200 && http_ret <= 399);
}
// The requestURI transferred from the frontend can be abs_path or absoluteURI
// If it is absoluteURI, we should adjust it to abs_path for the following
// S3 authorization and some other processes depending on the requestURI
// The absoluteURI can start with "http://", "https://", "ws://" or "wss://"
static string get_abs_path(const string& request_uri) {
const static string ABS_PREFIXS[] = {"http://", "https://", "ws://", "wss://"};
bool isAbs = false;
for (int i = 0; i < 4; ++i) {
if (boost::algorithm::starts_with(request_uri, ABS_PREFIXS[i])) {
isAbs = true;
break;
}
}
if (!isAbs) { // it is not a valid absolute uri
return request_uri;
}
size_t beg_pos = request_uri.find("://") + 3;
size_t len = request_uri.size();
beg_pos = request_uri.find('/', beg_pos);
if (beg_pos == string::npos) return request_uri;
return request_uri.substr(beg_pos, len - beg_pos);
}
req_info::req_info(CephContext *cct, const class RGWEnv *env) : env(env) {
method = env->get("REQUEST_METHOD", "");
script_uri = env->get("SCRIPT_URI", cct->_conf->rgw_script_uri.c_str());
request_uri = env->get("REQUEST_URI", cct->_conf->rgw_request_uri.c_str());
if (request_uri[0] != '/') {
request_uri = get_abs_path(request_uri);
}
auto pos = request_uri.find('?');
if (pos != string::npos) {
request_params = request_uri.substr(pos + 1);
request_uri = request_uri.substr(0, pos);
} else {
request_params = env->get("QUERY_STRING", "");
}
host = env->get("HTTP_HOST", "");
// strip off any trailing :port from host (added by CrossFTP and maybe others)
size_t colon_offset = host.find_last_of(':');
if (colon_offset != string::npos) {
bool all_digits = true;
for (unsigned i = colon_offset + 1; i < host.size(); ++i) {
if (!isdigit(host[i])) {
all_digits = false;
break;
}
}
if (all_digits) {
host.resize(colon_offset);
}
}
}
void req_info::rebuild_from(req_info& src)
{
method = src.method;
script_uri = src.script_uri;
args = src.args;
if (src.effective_uri.empty()) {
request_uri = src.request_uri;
} else {
request_uri = src.effective_uri;
}
effective_uri.clear();
host = src.host;
x_meta_map = src.x_meta_map;
x_meta_map.erase("x-amz-date");
}
req_state::req_state(CephContext* _cct, const RGWProcessEnv& penv,
RGWEnv* e, uint64_t id)
: cct(_cct), penv(penv), info(_cct, e), id(id)
{
enable_ops_log = e->get_enable_ops_log();
enable_usage_log = e->get_enable_usage_log();
defer_to_bucket_acls = e->get_defer_to_bucket_acls();
time = Clock::now();
}
req_state::~req_state() {
delete formatter;
}
std::ostream& req_state::gen_prefix(std::ostream& out) const
{
auto p = out.precision();
return out << "req " << id << ' '
<< std::setprecision(3) << std::fixed << time_elapsed() // '0.123s'
<< std::setprecision(p) << std::defaultfloat << ' ';
}
bool search_err(rgw_http_errors& errs, int err_no, int& http_ret, string& code)
{
auto r = errs.find(err_no);
if (r != errs.end()) {
http_ret = r->second.first;
code = r->second.second;
return true;
}
return false;
}
void set_req_state_err(struct rgw_err& err, /* out */
int err_no, /* in */
const int prot_flags) /* in */
{
if (err_no < 0)
err_no = -err_no;
err.ret = -err_no;
if (prot_flags & RGW_REST_SWIFT) {
if (search_err(rgw_http_swift_errors, err_no, err.http_ret, err.err_code))
return;
}
if (prot_flags & RGW_REST_STS) {
if (search_err(rgw_http_sts_errors, err_no, err.http_ret, err.err_code))
return;
}
if (prot_flags & RGW_REST_IAM) {
if (search_err(rgw_http_iam_errors, err_no, err.http_ret, err.err_code))
return;
}
//Default to searching in s3 errors
if (search_err(rgw_http_s3_errors, err_no, err.http_ret, err.err_code))
return;
dout(0) << "WARNING: set_req_state_err err_no=" << err_no
<< " resorting to 500" << dendl;
err.http_ret = 500;
err.err_code = "UnknownError";
}
void set_req_state_err(req_state* s, int err_no, const string& err_msg)
{
if (s) {
set_req_state_err(s, err_no);
if (s->prot_flags & RGW_REST_SWIFT && !err_msg.empty()) {
/* TODO(rzarzynski): there never ever should be a check like this one.
* It's here only for the sake of the patch's backportability. Further
* commits will move the logic to a per-RGWHandler replacement of
* the end_header() function. Alternativaly, we might consider making
* that just for the dump(). Please take a look on @cbodley's comments
* in PR #10690 (https://github.com/ceph/ceph/pull/10690). */
s->err.err_code = err_msg;
} else {
s->err.message = err_msg;
}
}
}
void set_req_state_err(req_state* s, int err_no)
{
if (s) {
set_req_state_err(s->err, err_no, s->prot_flags);
}
}
void dump(req_state* s)
{
if (s->format != RGWFormat::HTML)
s->formatter->open_object_section("Error");
if (!s->err.err_code.empty())
s->formatter->dump_string("Code", s->err.err_code);
s->formatter->dump_string("Message", s->err.message);
if (!s->bucket_name.empty()) // TODO: connect to expose_bucket
s->formatter->dump_string("BucketName", s->bucket_name);
if (!s->trans_id.empty()) // TODO: connect to expose_bucket or another toggle
s->formatter->dump_string("RequestId", s->trans_id);
s->formatter->dump_string("HostId", s->host_id);
if (s->format != RGWFormat::HTML)
s->formatter->close_section();
}
struct str_len {
const char *str;
int len;
};
#define STR_LEN_ENTRY(s) { s, sizeof(s) - 1 }
struct str_len meta_prefixes[] = { STR_LEN_ENTRY("HTTP_X_AMZ"),
STR_LEN_ENTRY("HTTP_X_GOOG"),
STR_LEN_ENTRY("HTTP_X_DHO"),
STR_LEN_ENTRY("HTTP_X_RGW"),
STR_LEN_ENTRY("HTTP_X_OBJECT"),
STR_LEN_ENTRY("HTTP_X_CONTAINER"),
STR_LEN_ENTRY("HTTP_X_ACCOUNT"),
{NULL, 0} };
void req_info::init_meta_info(const DoutPrefixProvider *dpp, bool *found_bad_meta)
{
x_meta_map.clear();
crypt_attribute_map.clear();
for (const auto& kv: env->get_map()) {
const char *prefix;
const string& header_name = kv.first;
const string& val = kv.second;
for (int prefix_num = 0; (prefix = meta_prefixes[prefix_num].str) != NULL; prefix_num++) {
int len = meta_prefixes[prefix_num].len;
const char *p = header_name.c_str();
if (strncmp(p, prefix, len) == 0) {
ldpp_dout(dpp, 10) << "meta>> " << p << dendl;
const char *name = p+len; /* skip the prefix */
int name_len = header_name.size() - len;
if (found_bad_meta && strncmp(name, "_META_", name_len) == 0)
*found_bad_meta = true;
char name_low[meta_prefixes[0].len + name_len + 1];
snprintf(name_low, meta_prefixes[0].len - 5 + name_len + 1, "%s%s", meta_prefixes[0].str + 5 /* skip HTTP_ */, name); // normalize meta prefix
int j;
for (j = 0; name_low[j]; j++) {
if (name_low[j] == '_')
name_low[j] = '-';
else if (name_low[j] == '-')
name_low[j] = '_';
else
name_low[j] = tolower(name_low[j]);
}
name_low[j] = 0;
auto it = x_meta_map.find(name_low);
if (it != x_meta_map.end()) {
string old = it->second;
boost::algorithm::trim_right(old);
old.append(",");
old.append(val);
x_meta_map[name_low] = old;
} else {
x_meta_map[name_low] = val;
}
if (strncmp(name_low, "x-amz-server-side-encryption", 20) == 0) {
crypt_attribute_map[name_low] = val;
}
}
}
}
for (const auto& kv: x_meta_map) {
ldpp_dout(dpp, 10) << "x>> " << kv.first << ":" << rgw::crypt_sanitize::x_meta_map{kv.first, kv.second} << dendl;
}
}
std::ostream& operator<<(std::ostream& oss, const rgw_err &err)
{
oss << "rgw_err(http_ret=" << err.http_ret << ", err_code='" << err.err_code << "') ";
return oss;
}
void rgw_add_amz_meta_header(
meta_map_t& x_meta_map,
const std::string& k,
const std::string& v)
{
auto it = x_meta_map.find(k);
if (it != x_meta_map.end()) {
std::string old = it->second;
boost::algorithm::trim_right(old);
old.append(",");
old.append(v);
x_meta_map[k] = old;
} else {
x_meta_map[k] = v;
}
}
bool rgw_set_amz_meta_header(
meta_map_t& x_meta_map,
const std::string& k,
const std::string& v,
rgw_set_action_if_set a)
{
auto it { x_meta_map.find(k) };
bool r { it != x_meta_map.end() };
switch(a) {
default:
ceph_assert(a == 0);
case DISCARD:
break;
case APPEND:
if (r) {
std::string old { it->second };
boost::algorithm::trim_right(old);
old.append(",");
old.append(v);
x_meta_map[k] = old;
break;
}
/* fall through */
case OVERWRITE:
x_meta_map[k] = v;
}
return r;
}
string rgw_string_unquote(const string& s)
{
if (s[0] != '"' || s.size() < 2)
return s;
int len;
for (len = s.size(); len > 2; --len) {
if (s[len - 1] != ' ')
break;
}
if (s[len-1] != '"')
return s;
return s.substr(1, len - 2);
}
static bool check_str_end(const char *s)
{
if (!s)
return false;
while (*s) {
if (!isspace(*s))
return false;
s++;
}
return true;
}
static bool check_gmt_end(const char *s)
{
if (!s || !*s)
return false;
while (isspace(*s)) {
++s;
}
/* check for correct timezone */
if ((strncmp(s, "GMT", 3) != 0) &&
(strncmp(s, "UTC", 3) != 0)) {
return false;
}
return true;
}
static bool parse_rfc850(const char *s, struct tm *t)
{
// FIPS zeroization audit 20191115: this memset is not security related.
memset(t, 0, sizeof(*t));
return check_gmt_end(strptime(s, "%A, %d-%b-%y %H:%M:%S ", t));
}
static bool parse_asctime(const char *s, struct tm *t)
{
// FIPS zeroization audit 20191115: this memset is not security related.
memset(t, 0, sizeof(*t));
return check_str_end(strptime(s, "%a %b %d %H:%M:%S %Y", t));
}
static bool parse_rfc1123(const char *s, struct tm *t)
{
// FIPS zeroization audit 20191115: this memset is not security related.
memset(t, 0, sizeof(*t));
return check_gmt_end(strptime(s, "%a, %d %b %Y %H:%M:%S ", t));
}
static bool parse_rfc1123_alt(const char *s, struct tm *t)
{
// FIPS zeroization audit 20191115: this memset is not security related.
memset(t, 0, sizeof(*t));
return check_str_end(strptime(s, "%a, %d %b %Y %H:%M:%S %z", t));
}
bool parse_rfc2616(const char *s, struct tm *t)
{
return parse_rfc850(s, t) || parse_asctime(s, t) || parse_rfc1123(s, t) || parse_rfc1123_alt(s,t);
}
bool parse_iso8601(const char *s, struct tm *t, uint32_t *pns, bool extended_format)
{
// FIPS zeroization audit 20191115: this memset is not security related.
memset(t, 0, sizeof(*t));
const char *p;
if (!s)
s = "";
if (extended_format) {
p = strptime(s, "%Y-%m-%dT%T", t);
if (!p) {
p = strptime(s, "%Y-%m-%d %T", t);
}
} else {
p = strptime(s, "%Y%m%dT%H%M%S", t);
}
if (!p) {
dout(0) << "parse_iso8601 failed" << dendl;
return false;
}
const std::string_view str = rgw_trim_whitespace(std::string_view(p));
int len = str.size();
if (len == 0 || (len == 1 && str[0] == 'Z'))
return true;
if (str[0] != '.' ||
str[len - 1] != 'Z')
return false;
uint32_t ms;
std::string_view nsstr = str.substr(1, len - 2);
int r = stringtoul(std::string(nsstr), &ms);
if (r < 0)
return false;
if (!pns) {
return true;
}
if (nsstr.size() > 9) {
nsstr = nsstr.substr(0, 9);
}
uint64_t mul_table[] = { 0,
100000000LL,
10000000LL,
1000000LL,
100000LL,
10000LL,
1000LL,
100LL,
10LL,
1 };
*pns = ms * mul_table[nsstr.size()];
return true;
}
int parse_key_value(string& in_str, const char *delim, string& key, string& val)
{
if (delim == NULL)
return -EINVAL;
auto pos = in_str.find(delim);
if (pos == string::npos)
return -EINVAL;
key = rgw_trim_whitespace(in_str.substr(0, pos));
val = rgw_trim_whitespace(in_str.substr(pos + 1));
return 0;
}
int parse_key_value(string& in_str, string& key, string& val)
{
return parse_key_value(in_str, "=", key,val);
}
boost::optional<std::pair<std::string_view, std::string_view>>
parse_key_value(const std::string_view& in_str,
const std::string_view& delim)
{
const size_t pos = in_str.find(delim);
if (pos == std::string_view::npos) {
return boost::none;
}
const auto key = rgw_trim_whitespace(in_str.substr(0, pos));
const auto val = rgw_trim_whitespace(in_str.substr(pos + 1));
return std::make_pair(key, val);
}
boost::optional<std::pair<std::string_view, std::string_view>>
parse_key_value(const std::string_view& in_str)
{
return parse_key_value(in_str, "=");
}
int parse_time(const char *time_str, real_time *time)
{
struct tm tm;
uint32_t ns = 0;
if (!parse_rfc2616(time_str, &tm) && !parse_iso8601(time_str, &tm, &ns)) {
return -EINVAL;
}
time_t sec = internal_timegm(&tm);
*time = utime_t(sec, ns).to_real_time();
return 0;
}
#define TIME_BUF_SIZE 128
void rgw_to_iso8601(const real_time& t, char *dest, int buf_size)
{
utime_t ut(t);
char buf[TIME_BUF_SIZE];
struct tm result;
time_t epoch = ut.sec();
struct tm *tmp = gmtime_r(&epoch, &result);
if (tmp == NULL)
return;
if (strftime(buf, sizeof(buf), "%Y-%m-%dT%T", tmp) == 0)
return;
snprintf(dest, buf_size, "%s.%03dZ", buf, (int)(ut.usec() / 1000));
}
void rgw_to_iso8601(const real_time& t, string *dest)
{
char buf[TIME_BUF_SIZE];
rgw_to_iso8601(t, buf, sizeof(buf));
*dest = buf;
}
string rgw_to_asctime(const utime_t& t)
{
stringstream s;
t.asctime(s);
return s.str();
}
/*
* calculate the sha1 value of a given msg and key
*/
void calc_hmac_sha1(const char *key, int key_len,
const char *msg, int msg_len, char *dest)
/* destination should be CEPH_CRYPTO_HMACSHA1_DIGESTSIZE bytes long */
{
HMACSHA1 hmac((const unsigned char *)key, key_len);
hmac.Update((const unsigned char *)msg, msg_len);
hmac.Final((unsigned char *)dest);
}
/*
* calculate the sha256 value of a given msg and key
*/
void calc_hmac_sha256(const char *key, int key_len,
const char *msg, int msg_len, char *dest)
{
char hash_sha256[CEPH_CRYPTO_HMACSHA256_DIGESTSIZE];
HMACSHA256 hmac((const unsigned char *)key, key_len);
hmac.Update((const unsigned char *)msg, msg_len);
hmac.Final((unsigned char *)hash_sha256);
memcpy(dest, hash_sha256, CEPH_CRYPTO_HMACSHA256_DIGESTSIZE);
}
using ceph::crypto::SHA256;
/*
* calculate the sha256 hash value of a given msg
*/
sha256_digest_t calc_hash_sha256(const std::string_view& msg)
{
sha256_digest_t hash;
SHA256 hasher;
hasher.Update(reinterpret_cast<const unsigned char*>(msg.data()), msg.size());
hasher.Final(hash.v);
return hash;
}
SHA256* calc_hash_sha256_open_stream()
{
return new SHA256;
}
void calc_hash_sha256_update_stream(SHA256 *hash, const char *msg, int len)
{
hash->Update((const unsigned char *)msg, len);
}
string calc_hash_sha256_close_stream(SHA256 **phash)
{
SHA256 *hash = *phash;
if (!hash) {
hash = calc_hash_sha256_open_stream();
}
char hash_sha256[CEPH_CRYPTO_HMACSHA256_DIGESTSIZE];
hash->Final((unsigned char *)hash_sha256);
char hex_str[(CEPH_CRYPTO_SHA256_DIGESTSIZE * 2) + 1];
buf_to_hex((unsigned char *)hash_sha256, CEPH_CRYPTO_SHA256_DIGESTSIZE, hex_str);
delete hash;
*phash = NULL;
return std::string(hex_str);
}
std::string calc_hash_sha256_restart_stream(SHA256 **phash)
{
const auto hash = calc_hash_sha256_close_stream(phash);
*phash = calc_hash_sha256_open_stream();
return hash;
}
int NameVal::parse()
{
auto delim_pos = str.find('=');
int ret = 0;
if (delim_pos == string::npos) {
name = str;
val = "";
ret = 1;
} else {
name = str.substr(0, delim_pos);
val = str.substr(delim_pos + 1);
}
return ret;
}
int RGWHTTPArgs::parse(const DoutPrefixProvider *dpp)
{
int pos = 0;
bool end = false;
if (str.empty())
return 0;
if (str[pos] == '?')
pos++;
while (!end) {
int fpos = str.find('&', pos);
if (fpos < pos) {
end = true;
fpos = str.size();
}
std::string nameval = url_decode(str.substr(pos, fpos - pos), true);
NameVal nv(std::move(nameval));
int ret = nv.parse();
if (ret >= 0) {
string& name = nv.get_name();
if (name.find("X-Amz-") != string::npos) {
std::for_each(name.begin(),
name.end(),
[](char &c){
if (c != '-') {
c = ::tolower(static_cast<unsigned char>(c));
}
});
}
string& val = nv.get_val();
ldpp_dout(dpp, 10) << "name: " << name << " val: " << val << dendl;
append(name, val);
}
pos = fpos + 1;
}
return 0;
}
void RGWHTTPArgs::remove(const string& name)
{
auto val_iter = val_map.find(name);
if (val_iter != std::end(val_map)) {
val_map.erase(val_iter);
}
auto sys_val_iter = sys_val_map.find(name);
if (sys_val_iter != std::end(sys_val_map)) {
sys_val_map.erase(sys_val_iter);
}
auto subres_iter = sub_resources.find(name);
if (subres_iter != std::end(sub_resources)) {
sub_resources.erase(subres_iter);
}
}
void RGWHTTPArgs::append(const string& name, const string& val)
{
if (name.compare(0, sizeof(RGW_SYS_PARAM_PREFIX) - 1, RGW_SYS_PARAM_PREFIX) == 0) {
sys_val_map[name] = val;
} else {
val_map[name] = val;
}
// when sub_resources exclusive by object are added, please remember to update obj_sub_resource in RGWHTTPArgs::exist_obj_excl_sub_resource().
if ((name.compare("acl") == 0) ||
(name.compare("cors") == 0) ||
(name.compare("notification") == 0) ||
(name.compare("location") == 0) ||
(name.compare("logging") == 0) ||
(name.compare("usage") == 0) ||
(name.compare("lifecycle") == 0) ||
(name.compare("delete") == 0) ||
(name.compare("uploads") == 0) ||
(name.compare("partNumber") == 0) ||
(name.compare("uploadId") == 0) ||
(name.compare("versionId") == 0) ||
(name.compare("start-date") == 0) ||
(name.compare("end-date") == 0) ||
(name.compare("versions") == 0) ||
(name.compare("versioning") == 0) ||
(name.compare("website") == 0) ||
(name.compare("requestPayment") == 0) ||
(name.compare("torrent") == 0) ||
(name.compare("tagging") == 0) ||
(name.compare("append") == 0) ||
(name.compare("position") == 0) ||
(name.compare("policyStatus") == 0) ||
(name.compare("publicAccessBlock") == 0)) {
sub_resources[name] = val;
} else if (name[0] == 'r') { // root of all evil
if ((name.compare("response-content-type") == 0) ||
(name.compare("response-content-language") == 0) ||
(name.compare("response-expires") == 0) ||
(name.compare("response-cache-control") == 0) ||
(name.compare("response-content-disposition") == 0) ||
(name.compare("response-content-encoding") == 0)) {
sub_resources[name] = val;
has_resp_modifier = true;
}
} else if ((name.compare("subuser") == 0) ||
(name.compare("key") == 0) ||
(name.compare("caps") == 0) ||
(name.compare("index") == 0) ||
(name.compare("policy") == 0) ||
(name.compare("quota") == 0) ||
(name.compare("list") == 0) ||
(name.compare("object") == 0) ||
(name.compare("sync") == 0)) {
if (!admin_subresource_added) {
sub_resources[name] = "";
admin_subresource_added = true;
}
}
}
const string& RGWHTTPArgs::get(const string& name, bool *exists) const
{
auto iter = val_map.find(name);
bool e = (iter != std::end(val_map));
if (exists)
*exists = e;
if (e)
return iter->second;
return empty_str;
}
boost::optional<const std::string&>
RGWHTTPArgs::get_optional(const std::string& name) const
{
bool exists;
const std::string& value = get(name, &exists);
if (exists) {
return value;
} else {
return boost::none;
}
}
int RGWHTTPArgs::get_bool(const string& name, bool *val, bool *exists) const
{
map<string, string>::const_iterator iter;
iter = val_map.find(name);
bool e = (iter != val_map.end());
if (exists)
*exists = e;
if (e) {
const char *s = iter->second.c_str();
if (strcasecmp(s, "false") == 0) {
*val = false;
} else if (strcasecmp(s, "true") == 0) {
*val = true;
} else {
return -EINVAL;
}
}
return 0;
}
int RGWHTTPArgs::get_bool(const char *name, bool *val, bool *exists) const
{
string s(name);
return get_bool(s, val, exists);
}
void RGWHTTPArgs::get_bool(const char *name, bool *val, bool def_val) const
{
bool exists = false;
if ((get_bool(name, val, &exists) < 0) ||
!exists) {
*val = def_val;
}
}
int RGWHTTPArgs::get_int(const char *name, int *val, int def_val) const
{
bool exists = false;
string val_str;
val_str = get(name, &exists);
if (!exists) {
*val = def_val;
return 0;
}
string err;
*val = (int)strict_strtol(val_str.c_str(), 10, &err);
if (!err.empty()) {
*val = def_val;
return -EINVAL;
}
return 0;
}
string RGWHTTPArgs::sys_get(const string& name, bool * const exists) const
{
const auto iter = sys_val_map.find(name);
const bool e = (iter != sys_val_map.end());
if (exists) {
*exists = e;
}
return e ? iter->second : string();
}
bool rgw_transport_is_secure(CephContext *cct, const RGWEnv& env)
{
const auto& m = env.get_map();
// frontend connected with ssl
if (m.count("SERVER_PORT_SECURE")) {
return true;
}
// ignore proxy headers unless explicitly enabled
if (!cct->_conf->rgw_trust_forwarded_https) {
return false;
}
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Forwarded
// Forwarded: by=<identifier>; for=<identifier>; host=<host>; proto=<http|https>
auto i = m.find("HTTP_FORWARDED");
if (i != m.end() && i->second.find("proto=https") != std::string::npos) {
return true;
}
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-Proto
i = m.find("HTTP_X_FORWARDED_PROTO");
if (i != m.end() && i->second == "https") {
return true;
}
return false;
}
namespace {
struct perm_state_from_req_state : public perm_state_base {
req_state * const s;
perm_state_from_req_state(req_state * const _s)
: perm_state_base(_s->cct,
_s->env,
_s->auth.identity.get(),
_s->bucket.get() ? _s->bucket->get_info() : RGWBucketInfo(),
_s->perm_mask,
_s->defer_to_bucket_acls,
_s->bucket_access_conf),
s(_s) {}
std::optional<bool> get_request_payer() const override {
const char *request_payer = s->info.env->get("HTTP_X_AMZ_REQUEST_PAYER");
if (!request_payer) {
bool exists;
request_payer = s->info.args.get("x-amz-request-payer", &exists).c_str();
if (!exists) {
return false;
}
}
if (strcasecmp(request_payer, "requester") == 0) {
return true;
}
return std::nullopt;
}
const char *get_referer() const override {
return s->info.env->get("HTTP_REFERER");
}
};
Effect eval_or_pass(const DoutPrefixProvider* dpp,
const boost::optional<Policy>& policy,
const rgw::IAM::Environment& env,
boost::optional<const rgw::auth::Identity&> id,
const uint64_t op,
const ARN& resource,
boost::optional<rgw::IAM::PolicyPrincipal&> princ_type=boost::none) {
if (!policy)
return Effect::Pass;
else
return policy->eval(env, id, op, resource, princ_type);
}
}
Effect eval_identity_or_session_policies(const DoutPrefixProvider* dpp,
const vector<Policy>& policies,
const rgw::IAM::Environment& env,
const uint64_t op,
const ARN& arn) {
auto policy_res = Effect::Pass, prev_res = Effect::Pass;
for (auto& policy : policies) {
if (policy_res = eval_or_pass(dpp, policy, env, boost::none, op, arn); policy_res == Effect::Deny)
return policy_res;
else if (policy_res == Effect::Allow)
prev_res = Effect::Allow;
else if (policy_res == Effect::Pass && prev_res == Effect::Allow)
policy_res = Effect::Allow;
}
return policy_res;
}
bool verify_user_permission(const DoutPrefixProvider* dpp,
perm_state_base * const s,
RGWAccessControlPolicy * const user_acl,
const vector<rgw::IAM::Policy>& user_policies,
const vector<rgw::IAM::Policy>& session_policies,
const rgw::ARN& res,
const uint64_t op,
bool mandatory_policy)
{
auto identity_policy_res = eval_identity_or_session_policies(dpp, user_policies, s->env, op, res);
if (identity_policy_res == Effect::Deny) {
return false;
}
if (! session_policies.empty()) {
auto session_policy_res = eval_identity_or_session_policies(dpp, session_policies, s->env, op, res);
if (session_policy_res == Effect::Deny) {
return false;
}
//Intersection of identity policies and session policies
if (identity_policy_res == Effect::Allow && session_policy_res == Effect::Allow) {
return true;
}
return false;
}
if (identity_policy_res == Effect::Allow) {
return true;
}
if (mandatory_policy) {
// no policies, and policy is mandatory
ldpp_dout(dpp, 20) << "no policies for a policy mandatory op " << op << dendl;
return false;
}
auto perm = op_to_perm(op);
return verify_user_permission_no_policy(dpp, s, user_acl, perm);
}
bool verify_user_permission_no_policy(const DoutPrefixProvider* dpp,
struct perm_state_base * const s,
RGWAccessControlPolicy * const user_acl,
const int perm)
{
if (s->identity->get_identity_type() == TYPE_ROLE)
return false;
/* S3 doesn't support account ACLs. */
if (!user_acl)
return true;
if ((perm & (int)s->perm_mask) != perm)
return false;
return user_acl->verify_permission(dpp, *s->identity, perm, perm);
}
bool verify_user_permission(const DoutPrefixProvider* dpp,
req_state * const s,
const rgw::ARN& res,
const uint64_t op,
bool mandatory_policy)
{
perm_state_from_req_state ps(s);
return verify_user_permission(dpp, &ps, s->user_acl.get(), s->iam_user_policies, s->session_policies, res, op, mandatory_policy);
}
bool verify_user_permission_no_policy(const DoutPrefixProvider* dpp,
req_state * const s,
const int perm)
{
perm_state_from_req_state ps(s);
return verify_user_permission_no_policy(dpp, &ps, s->user_acl.get(), perm);
}
bool verify_requester_payer_permission(struct perm_state_base *s)
{
if (!s->bucket_info.requester_pays)
return true;
if (s->identity->is_owner_of(s->bucket_info.owner))
return true;
if (s->identity->is_anonymous()) {
return false;
}
auto request_payer = s->get_request_payer();
if (request_payer) {
return *request_payer;
}
return false;
}
bool verify_bucket_permission(const DoutPrefixProvider* dpp,
struct perm_state_base * const s,
const rgw_bucket& bucket,
RGWAccessControlPolicy * const user_acl,
RGWAccessControlPolicy * const bucket_acl,
const boost::optional<Policy>& bucket_policy,
const vector<Policy>& identity_policies,
const vector<Policy>& session_policies,
const uint64_t op)
{
if (!verify_requester_payer_permission(s))
return false;
auto identity_policy_res = eval_identity_or_session_policies(dpp, identity_policies, s->env, op, ARN(bucket));
if (identity_policy_res == Effect::Deny)
return false;
rgw::IAM::PolicyPrincipal princ_type = rgw::IAM::PolicyPrincipal::Other;
if (bucket_policy) {
ldpp_dout(dpp, 16) << __func__ << ": policy: " << bucket_policy.get()
<< "resource: " << ARN(bucket) << dendl;
}
auto r = eval_or_pass(dpp, bucket_policy, s->env, *s->identity,
op, ARN(bucket), princ_type);
if (r == Effect::Deny)
return false;
//Take into account session policies, if the identity making a request is a role
if (!session_policies.empty()) {
auto session_policy_res = eval_identity_or_session_policies(dpp, session_policies, s->env, op, ARN(bucket));
if (session_policy_res == Effect::Deny) {
return false;
}
if (princ_type == rgw::IAM::PolicyPrincipal::Role) {
//Intersection of session policy and identity policy plus intersection of session policy and bucket policy
if ((session_policy_res == Effect::Allow && identity_policy_res == Effect::Allow) ||
(session_policy_res == Effect::Allow && r == Effect::Allow))
return true;
} else if (princ_type == rgw::IAM::PolicyPrincipal::Session) {
//Intersection of session policy and identity policy plus bucket policy
if ((session_policy_res == Effect::Allow && identity_policy_res == Effect::Allow) || r == Effect::Allow)
return true;
} else if (princ_type == rgw::IAM::PolicyPrincipal::Other) {// there was no match in the bucket policy
if (session_policy_res == Effect::Allow && identity_policy_res == Effect::Allow)
return true;
}
return false;
}
if (r == Effect::Allow || identity_policy_res == Effect::Allow)
// It looks like S3 ACLs only GRANT permissions rather than
// denying them, so this should be safe.
return true;
const auto perm = op_to_perm(op);
return verify_bucket_permission_no_policy(dpp, s, user_acl, bucket_acl, perm);
}
bool verify_bucket_permission(const DoutPrefixProvider* dpp,
req_state * const s,
const rgw_bucket& bucket,
RGWAccessControlPolicy * const user_acl,
RGWAccessControlPolicy * const bucket_acl,
const boost::optional<Policy>& bucket_policy,
const vector<Policy>& user_policies,
const vector<Policy>& session_policies,
const uint64_t op)
{
perm_state_from_req_state ps(s);
return verify_bucket_permission(dpp, &ps, bucket,
user_acl, bucket_acl,
bucket_policy, user_policies,
session_policies, op);
}
bool verify_bucket_permission_no_policy(const DoutPrefixProvider* dpp, struct perm_state_base * const s,
RGWAccessControlPolicy * const user_acl,
RGWAccessControlPolicy * const bucket_acl,
const int perm)
{
if (!bucket_acl)
return false;
if ((perm & (int)s->perm_mask) != perm)
return false;
if (bucket_acl->verify_permission(dpp, *s->identity, perm, perm,
s->get_referer(),
s->bucket_access_conf &&
s->bucket_access_conf->ignore_public_acls()))
return true;
if (!user_acl)
return false;
return user_acl->verify_permission(dpp, *s->identity, perm, perm);
}
bool verify_bucket_permission_no_policy(const DoutPrefixProvider* dpp, req_state * const s,
RGWAccessControlPolicy * const user_acl,
RGWAccessControlPolicy * const bucket_acl,
const int perm)
{
perm_state_from_req_state ps(s);
return verify_bucket_permission_no_policy(dpp,
&ps,
user_acl,
bucket_acl,
perm);
}
bool verify_bucket_permission_no_policy(const DoutPrefixProvider* dpp, req_state * const s, const int perm)
{
perm_state_from_req_state ps(s);
if (!verify_requester_payer_permission(&ps))
return false;
return verify_bucket_permission_no_policy(dpp,
&ps,
s->user_acl.get(),
s->bucket_acl.get(),
perm);
}
bool verify_bucket_permission(const DoutPrefixProvider* dpp, req_state * const s, const uint64_t op)
{
if (rgw::sal::Bucket::empty(s->bucket)) {
// request is missing a bucket name
return false;
}
perm_state_from_req_state ps(s);
return verify_bucket_permission(dpp,
&ps,
s->bucket->get_key(),
s->user_acl.get(),
s->bucket_acl.get(),
s->iam_policy,
s->iam_user_policies,
s->session_policies,
op);
}
// Authorize anyone permitted by the bucket policy, identity policies, session policies and the bucket owner
// unless explicitly denied by the policy.
int verify_bucket_owner_or_policy(req_state* const s,
const uint64_t op)
{
auto identity_policy_res = eval_identity_or_session_policies(s, s->iam_user_policies, s->env, op, ARN(s->bucket->get_key()));
if (identity_policy_res == Effect::Deny) {
return -EACCES;
}
rgw::IAM::PolicyPrincipal princ_type = rgw::IAM::PolicyPrincipal::Other;
auto e = eval_or_pass(s, s->iam_policy,
s->env, *s->auth.identity,
op, ARN(s->bucket->get_key()), princ_type);
if (e == Effect::Deny) {
return -EACCES;
}
if (!s->session_policies.empty()) {
auto session_policy_res = eval_identity_or_session_policies(s, s->session_policies, s->env, op,
ARN(s->bucket->get_key()));
if (session_policy_res == Effect::Deny) {
return -EACCES;
}
if (princ_type == rgw::IAM::PolicyPrincipal::Role) {
//Intersection of session policy and identity policy plus intersection of session policy and bucket policy
if ((session_policy_res == Effect::Allow && identity_policy_res == Effect::Allow) ||
(session_policy_res == Effect::Allow && e == Effect::Allow))
return 0;
} else if (princ_type == rgw::IAM::PolicyPrincipal::Session) {
//Intersection of session policy and identity policy plus bucket policy
if ((session_policy_res == Effect::Allow && identity_policy_res == Effect::Allow) || e == Effect::Allow)
return 0;
} else if (princ_type == rgw::IAM::PolicyPrincipal::Other) {// there was no match in the bucket policy
if (session_policy_res == Effect::Allow && identity_policy_res == Effect::Allow)
return 0;
}
return -EACCES;
}
if (e == Effect::Allow ||
identity_policy_res == Effect::Allow ||
(e == Effect::Pass &&
identity_policy_res == Effect::Pass &&
s->auth.identity->is_owner_of(s->bucket_owner.get_id()))) {
return 0;
} else {
return -EACCES;
}
}
static inline bool check_deferred_bucket_perms(const DoutPrefixProvider* dpp,
struct perm_state_base * const s,
const rgw_bucket& bucket,
RGWAccessControlPolicy * const user_acl,
RGWAccessControlPolicy * const bucket_acl,
const boost::optional<Policy>& bucket_policy,
const vector<Policy>& identity_policies,
const vector<Policy>& session_policies,
const uint8_t deferred_check,
const uint64_t op)
{
return (s->defer_to_bucket_acls == deferred_check \
&& verify_bucket_permission(dpp, s, bucket, user_acl, bucket_acl, bucket_policy, identity_policies, session_policies,op));
}
static inline bool check_deferred_bucket_only_acl(const DoutPrefixProvider* dpp,
struct perm_state_base * const s,
RGWAccessControlPolicy * const user_acl,
RGWAccessControlPolicy * const bucket_acl,
const uint8_t deferred_check,
const int perm)
{
return (s->defer_to_bucket_acls == deferred_check \
&& verify_bucket_permission_no_policy(dpp, s, user_acl, bucket_acl, perm));
}
bool verify_object_permission(const DoutPrefixProvider* dpp, struct perm_state_base * const s,
const rgw_obj& obj,
RGWAccessControlPolicy * const user_acl,
RGWAccessControlPolicy * const bucket_acl,
RGWAccessControlPolicy * const object_acl,
const boost::optional<Policy>& bucket_policy,
const vector<Policy>& identity_policies,
const vector<Policy>& session_policies,
const uint64_t op)
{
if (!verify_requester_payer_permission(s))
return false;
auto identity_policy_res = eval_identity_or_session_policies(dpp, identity_policies, s->env, op, ARN(obj));
if (identity_policy_res == Effect::Deny)
return false;
rgw::IAM::PolicyPrincipal princ_type = rgw::IAM::PolicyPrincipal::Other;
auto r = eval_or_pass(dpp, bucket_policy, s->env, *s->identity, op, ARN(obj), princ_type);
if (r == Effect::Deny)
return false;
if (!session_policies.empty()) {
auto session_policy_res = eval_identity_or_session_policies(dpp, session_policies, s->env, op, ARN(obj));
if (session_policy_res == Effect::Deny) {
return false;
}
if (princ_type == rgw::IAM::PolicyPrincipal::Role) {
//Intersection of session policy and identity policy plus intersection of session policy and bucket policy
if ((session_policy_res == Effect::Allow && identity_policy_res == Effect::Allow) ||
(session_policy_res == Effect::Allow && r == Effect::Allow))
return true;
} else if (princ_type == rgw::IAM::PolicyPrincipal::Session) {
//Intersection of session policy and identity policy plus bucket policy
if ((session_policy_res == Effect::Allow && identity_policy_res == Effect::Allow) || r == Effect::Allow)
return true;
} else if (princ_type == rgw::IAM::PolicyPrincipal::Other) {// there was no match in the bucket policy
if (session_policy_res == Effect::Allow && identity_policy_res == Effect::Allow)
return true;
}
return false;
}
if (r == Effect::Allow || identity_policy_res == Effect::Allow)
// It looks like S3 ACLs only GRANT permissions rather than
// denying them, so this should be safe.
return true;
const auto perm = op_to_perm(op);
if (check_deferred_bucket_perms(dpp, s, obj.bucket, user_acl, bucket_acl, bucket_policy,
identity_policies, session_policies, RGW_DEFER_TO_BUCKET_ACLS_RECURSE, op) ||
check_deferred_bucket_perms(dpp, s, obj.bucket, user_acl, bucket_acl, bucket_policy,
identity_policies, session_policies, RGW_DEFER_TO_BUCKET_ACLS_FULL_CONTROL, rgw::IAM::s3All)) {
return true;
}
if (!object_acl) {
return false;
}
bool ret = object_acl->verify_permission(dpp, *s->identity, s->perm_mask, perm,
nullptr, /* http_referrer */
s->bucket_access_conf &&
s->bucket_access_conf->ignore_public_acls());
if (ret) {
return true;
}
if (!s->cct->_conf->rgw_enforce_swift_acls)
return ret;
if ((perm & (int)s->perm_mask) != perm)
return false;
int swift_perm = 0;
if (perm & (RGW_PERM_READ | RGW_PERM_READ_ACP))
swift_perm |= RGW_PERM_READ_OBJS;
if (perm & RGW_PERM_WRITE)
swift_perm |= RGW_PERM_WRITE_OBJS;
if (!swift_perm)
return false;
/* we already verified the user mask above, so we pass swift_perm as the mask here,
otherwise the mask might not cover the swift permissions bits */
if (bucket_acl->verify_permission(dpp, *s->identity, swift_perm, swift_perm,
s->get_referer()))
return true;
if (!user_acl)
return false;
return user_acl->verify_permission(dpp, *s->identity, swift_perm, swift_perm);
}
bool verify_object_permission(const DoutPrefixProvider* dpp, req_state * const s,
const rgw_obj& obj,
RGWAccessControlPolicy * const user_acl,
RGWAccessControlPolicy * const bucket_acl,
RGWAccessControlPolicy * const object_acl,
const boost::optional<Policy>& bucket_policy,
const vector<Policy>& identity_policies,
const vector<Policy>& session_policies,
const uint64_t op)
{
perm_state_from_req_state ps(s);
return verify_object_permission(dpp, &ps, obj,
user_acl, bucket_acl,
object_acl, bucket_policy,
identity_policies, session_policies, op);
}
bool verify_object_permission_no_policy(const DoutPrefixProvider* dpp,
struct perm_state_base * const s,
RGWAccessControlPolicy * const user_acl,
RGWAccessControlPolicy * const bucket_acl,
RGWAccessControlPolicy * const object_acl,
const int perm)
{
if (check_deferred_bucket_only_acl(dpp, s, user_acl, bucket_acl, RGW_DEFER_TO_BUCKET_ACLS_RECURSE, perm) ||
check_deferred_bucket_only_acl(dpp, s, user_acl, bucket_acl, RGW_DEFER_TO_BUCKET_ACLS_FULL_CONTROL, RGW_PERM_FULL_CONTROL)) {
return true;
}
if (!object_acl) {
return false;
}
bool ret = object_acl->verify_permission(dpp, *s->identity, s->perm_mask, perm,
nullptr, /* http referrer */
s->bucket_access_conf &&
s->bucket_access_conf->ignore_public_acls());
if (ret) {
return true;
}
if (!s->cct->_conf->rgw_enforce_swift_acls)
return ret;
if ((perm & (int)s->perm_mask) != perm)
return false;
int swift_perm = 0;
if (perm & (RGW_PERM_READ | RGW_PERM_READ_ACP))
swift_perm |= RGW_PERM_READ_OBJS;
if (perm & RGW_PERM_WRITE)
swift_perm |= RGW_PERM_WRITE_OBJS;
if (!swift_perm)
return false;
/* we already verified the user mask above, so we pass swift_perm as the mask here,
otherwise the mask might not cover the swift permissions bits */
if (bucket_acl->verify_permission(dpp, *s->identity, swift_perm, swift_perm,
s->get_referer()))
return true;
if (!user_acl)
return false;
return user_acl->verify_permission(dpp, *s->identity, swift_perm, swift_perm);
}
bool verify_object_permission_no_policy(const DoutPrefixProvider* dpp, req_state *s, int perm)
{
perm_state_from_req_state ps(s);
if (!verify_requester_payer_permission(&ps))
return false;
return verify_object_permission_no_policy(dpp,
&ps,
s->user_acl.get(),
s->bucket_acl.get(),
s->object_acl.get(),
perm);
}
bool verify_object_permission(const DoutPrefixProvider* dpp, req_state *s, uint64_t op)
{
perm_state_from_req_state ps(s);
return verify_object_permission(dpp,
&ps,
rgw_obj(s->bucket->get_key(), s->object->get_key()),
s->user_acl.get(),
s->bucket_acl.get(),
s->object_acl.get(),
s->iam_policy,
s->iam_user_policies,
s->session_policies,
op);
}
int verify_object_lock(const DoutPrefixProvider* dpp, const rgw::sal::Attrs& attrs, const bool bypass_perm, const bool bypass_governance_mode) {
auto aiter = attrs.find(RGW_ATTR_OBJECT_RETENTION);
if (aiter != attrs.end()) {
RGWObjectRetention obj_retention;
try {
decode(obj_retention, aiter->second);
} catch (buffer::error& err) {
ldpp_dout(dpp, 0) << "ERROR: failed to decode RGWObjectRetention" << dendl;
return -EIO;
}
if (ceph::real_clock::to_time_t(obj_retention.get_retain_until_date()) > ceph_clock_now()) {
if (obj_retention.get_mode().compare("GOVERNANCE") != 0 || !bypass_perm || !bypass_governance_mode) {
return -EACCES;
}
}
}
aiter = attrs.find(RGW_ATTR_OBJECT_LEGAL_HOLD);
if (aiter != attrs.end()) {
RGWObjectLegalHold obj_legal_hold;
try {
decode(obj_legal_hold, aiter->second);
} catch (buffer::error& err) {
ldpp_dout(dpp, 0) << "ERROR: failed to decode RGWObjectLegalHold" << dendl;
return -EIO;
}
if (obj_legal_hold.is_enabled()) {
return -EACCES;
}
}
return 0;
}
class HexTable
{
char table[256];
public:
HexTable() {
// FIPS zeroization audit 20191115: this memset is not security related.
memset(table, -1, sizeof(table));
int i;
for (i = '0'; i<='9'; i++)
table[i] = i - '0';
for (i = 'A'; i<='F'; i++)
table[i] = i - 'A' + 0xa;
for (i = 'a'; i<='f'; i++)
table[i] = i - 'a' + 0xa;
}
char to_num(char c) {
return table[(int)c];
}
};
static char hex_to_num(char c)
{
static HexTable hex_table;
return hex_table.to_num(c);
}
std::string url_decode(const std::string_view& src_str, bool in_query)
{
std::string dest_str;
dest_str.reserve(src_str.length() + 1);
for (auto src = std::begin(src_str); src != std::end(src_str); ++src) {
if (*src != '%') {
if (!in_query || *src != '+') {
if (*src == '?') {
in_query = true;
}
dest_str.push_back(*src);
} else {
dest_str.push_back(' ');
}
} else {
/* 3 == strlen("%%XX") */
if (std::distance(src, std::end(src_str)) < 3) {
break;
}
src++;
const char c1 = hex_to_num(*src++);
const char c2 = hex_to_num(*src);
if (c1 < 0 || c2 < 0) {
return std::string();
} else {
dest_str.push_back(c1 << 4 | c2);
}
}
}
return dest_str;
}
void rgw_uri_escape_char(char c, string& dst)
{
char buf[16];
snprintf(buf, sizeof(buf), "%%%.2X", (int)(unsigned char)c);
dst.append(buf);
}
static bool char_needs_url_encoding(char c)
{
if (c <= 0x20 || c >= 0x7f)
return true;
switch (c) {
case 0x22:
case 0x23:
case 0x25:
case 0x26:
case 0x2B:
case 0x2C:
case 0x2F:
case 0x3A:
case 0x3B:
case 0x3C:
case 0x3E:
case 0x3D:
case 0x3F:
case 0x40:
case 0x5B:
case 0x5D:
case 0x5C:
case 0x5E:
case 0x60:
case 0x7B:
case 0x7D:
return true;
}
return false;
}
void url_encode(const string& src, string& dst, bool encode_slash)
{
const char *p = src.c_str();
for (unsigned i = 0; i < src.size(); i++, p++) {
if ((!encode_slash && *p == 0x2F) || !char_needs_url_encoding(*p)) {
dst.append(p, 1);
}else {
rgw_uri_escape_char(*p, dst);
}
}
}
std::string url_encode(const std::string& src, bool encode_slash)
{
std::string dst;
url_encode(src, dst, encode_slash);
return dst;
}
std::string url_remove_prefix(const std::string& url)
{
std::string dst = url;
auto pos = dst.find("http://");
if (pos == std::string::npos) {
pos = dst.find("https://");
if (pos != std::string::npos) {
dst.erase(pos, 8);
} else {
pos = dst.find("www.");
if (pos != std::string::npos) {
dst.erase(pos, 4);
}
}
} else {
dst.erase(pos, 7);
}
return dst;
}
string rgw_trim_whitespace(const string& src)
{
if (src.empty()) {
return string();
}
int start = 0;
for (; start != (int)src.size(); start++) {
if (!isspace(src[start]))
break;
}
int end = src.size() - 1;
if (end < start) {
return string();
}
for (; end > start; end--) {
if (!isspace(src[end]))
break;
}
return src.substr(start, end - start + 1);
}
std::string_view rgw_trim_whitespace(const std::string_view& src)
{
std::string_view res = src;
while (res.size() > 0 && std::isspace(res.front())) {
res.remove_prefix(1);
}
while (res.size() > 0 && std::isspace(res.back())) {
res.remove_suffix(1);
}
return res;
}
string rgw_trim_quotes(const string& val)
{
string s = rgw_trim_whitespace(val);
if (s.size() < 2)
return s;
int start = 0;
int end = s.size() - 1;
int quotes_count = 0;
if (s[start] == '"') {
start++;
quotes_count++;
}
if (s[end] == '"') {
end--;
quotes_count++;
}
if (quotes_count == 2) {
return s.substr(start, end - start + 1);
}
return s;
}
static struct rgw_name_to_flag cap_names[] = { {"*", RGW_CAP_ALL},
{"read", RGW_CAP_READ},
{"write", RGW_CAP_WRITE},
{NULL, 0} };
static int rgw_parse_list_of_flags(struct rgw_name_to_flag *mapping,
const string& str, uint32_t *perm)
{
list<string> strs;
get_str_list(str, strs);
list<string>::iterator iter;
uint32_t v = 0;
for (iter = strs.begin(); iter != strs.end(); ++iter) {
string& s = *iter;
for (int i = 0; mapping[i].type_name; i++) {
if (s.compare(mapping[i].type_name) == 0)
v |= mapping[i].flag;
}
}
*perm = v;
return 0;
}
int RGWUserCaps::parse_cap_perm(const string& str, uint32_t *perm)
{
return rgw_parse_list_of_flags(cap_names, str, perm);
}
int RGWUserCaps::get_cap(const string& cap, string& type, uint32_t *pperm)
{
int pos = cap.find('=');
if (pos >= 0) {
type = rgw_trim_whitespace(cap.substr(0, pos));
}
if (!is_valid_cap_type(type))
return -ERR_INVALID_CAP;
string cap_perm;
uint32_t perm = 0;
if (pos < (int)cap.size() - 1) {
cap_perm = cap.substr(pos + 1);
int r = RGWUserCaps::parse_cap_perm(cap_perm, &perm);
if (r < 0)
return r;
}
*pperm = perm;
return 0;
}
int RGWUserCaps::add_cap(const string& cap)
{
uint32_t perm;
string type;
int r = get_cap(cap, type, &perm);
if (r < 0)
return r;
caps[type] |= perm;
return 0;
}
int RGWUserCaps::remove_cap(const string& cap)
{
uint32_t perm;
string type;
int r = get_cap(cap, type, &perm);
if (r < 0)
return r;
map<string, uint32_t>::iterator iter = caps.find(type);
if (iter == caps.end())
return 0;
uint32_t& old_perm = iter->second;
old_perm &= ~perm;
if (!old_perm)
caps.erase(iter);
return 0;
}
int RGWUserCaps::add_from_string(const string& str)
{
int start = 0;
do {
auto end = str.find(';', start);
if (end == string::npos)
end = str.size();
int r = add_cap(str.substr(start, end - start));
if (r < 0)
return r;
start = end + 1;
} while (start < (int)str.size());
return 0;
}
int RGWUserCaps::remove_from_string(const string& str)
{
int start = 0;
do {
auto end = str.find(';', start);
if (end == string::npos)
end = str.size();
int r = remove_cap(str.substr(start, end - start));
if (r < 0)
return r;
start = end + 1;
} while (start < (int)str.size());
return 0;
}
void RGWUserCaps::dump(Formatter *f) const
{
dump(f, "caps");
}
void RGWUserCaps::dump(Formatter *f, const char *name) const
{
f->open_array_section(name);
map<string, uint32_t>::const_iterator iter;
for (iter = caps.begin(); iter != caps.end(); ++iter)
{
f->open_object_section("cap");
f->dump_string("type", iter->first);
uint32_t perm = iter->second;
string perm_str;
for (int i=0; cap_names[i].type_name; i++) {
if ((perm & cap_names[i].flag) == cap_names[i].flag) {
if (perm_str.size())
perm_str.append(", ");
perm_str.append(cap_names[i].type_name);
perm &= ~cap_names[i].flag;
}
}
if (perm_str.empty())
perm_str = "<none>";
f->dump_string("perm", perm_str);
f->close_section();
}
f->close_section();
}
struct RGWUserCap {
string type;
uint32_t perm;
void decode_json(JSONObj *obj) {
JSONDecoder::decode_json("type", type, obj);
string perm_str;
JSONDecoder::decode_json("perm", perm_str, obj);
if (RGWUserCaps::parse_cap_perm(perm_str, &perm) < 0) {
throw JSONDecoder::err("failed to parse permissions");
}
}
};
void RGWUserCaps::decode_json(JSONObj *obj)
{
list<RGWUserCap> caps_list;
decode_json_obj(caps_list, obj);
list<RGWUserCap>::iterator iter;
for (iter = caps_list.begin(); iter != caps_list.end(); ++iter) {
RGWUserCap& cap = *iter;
caps[cap.type] = cap.perm;
}
}
int RGWUserCaps::check_cap(const string& cap, uint32_t perm) const
{
auto iter = caps.find(cap);
if ((iter == caps.end()) ||
(iter->second & perm) != perm) {
return -EPERM;
}
return 0;
}
bool RGWUserCaps::is_valid_cap_type(const string& tp)
{
static const char *cap_type[] = { "user",
"users",
"buckets",
"metadata",
"info",
"usage",
"zone",
"bilog",
"mdlog",
"datalog",
"roles",
"user-policy",
"amz-cache",
"oidc-provider",
"ratelimit"};
for (unsigned int i = 0; i < sizeof(cap_type) / sizeof(char *); ++i) {
if (tp.compare(cap_type[i]) == 0) {
return true;
}
}
return false;
}
void rgw_pool::from_str(const string& s)
{
size_t pos = rgw_unescape_str(s, 0, '\\', ':', &name);
if (pos != string::npos) {
pos = rgw_unescape_str(s, pos, '\\', ':', &ns);
/* ignore return; if pos != string::npos it means that we had a colon
* in the middle of ns that wasn't escaped, we're going to stop there
*/
}
}
string rgw_pool::to_str() const
{
string esc_name;
rgw_escape_str(name, '\\', ':', &esc_name);
if (ns.empty()) {
return esc_name;
}
string esc_ns;
rgw_escape_str(ns, '\\', ':', &esc_ns);
return esc_name + ":" + esc_ns;
}
void rgw_raw_obj::decode_from_rgw_obj(bufferlist::const_iterator& bl)
{
using ceph::decode;
rgw_obj old_obj;
decode(old_obj, bl);
get_obj_bucket_and_oid_loc(old_obj, oid, loc);
pool = old_obj.get_explicit_data_pool();
}
static struct rgw_name_to_flag op_type_mapping[] = { {"*", RGW_OP_TYPE_ALL},
{"read", RGW_OP_TYPE_READ},
{"write", RGW_OP_TYPE_WRITE},
{"delete", RGW_OP_TYPE_DELETE},
{NULL, 0} };
int rgw_parse_op_type_list(const string& str, uint32_t *perm)
{
return rgw_parse_list_of_flags(op_type_mapping, str, perm);
}
bool match_policy(std::string_view pattern, std::string_view input,
uint32_t flag)
{
const uint32_t flag2 = flag & (MATCH_POLICY_ACTION|MATCH_POLICY_ARN) ?
MATCH_CASE_INSENSITIVE : 0;
const bool colonblocks = !(flag & (MATCH_POLICY_RESOURCE |
MATCH_POLICY_STRING));
const auto npos = std::string_view::npos;
std::string_view::size_type last_pos_input = 0, last_pos_pattern = 0;
while (true) {
auto cur_pos_input = colonblocks ? input.find(":", last_pos_input) : npos;
auto cur_pos_pattern =
colonblocks ? pattern.find(":", last_pos_pattern) : npos;
auto substr_input = input.substr(last_pos_input, cur_pos_input);
auto substr_pattern = pattern.substr(last_pos_pattern, cur_pos_pattern);
if (!match_wildcards(substr_pattern, substr_input, flag2))
return false;
if (cur_pos_pattern == npos)
return cur_pos_input == npos;
if (cur_pos_input == npos)
return false;
last_pos_pattern = cur_pos_pattern + 1;
last_pos_input = cur_pos_input + 1;
}
}
/*
* make attrs look-like-this
* converts underscores to dashes
*/
string lowercase_dash_http_attr(const string& orig)
{
const char *s = orig.c_str();
char buf[orig.size() + 1];
buf[orig.size()] = '\0';
for (size_t i = 0; i < orig.size(); ++i, ++s) {
switch (*s) {
case '_':
buf[i] = '-';
break;
default:
buf[i] = tolower(*s);
}
}
return string(buf);
}
/*
* make attrs Look-Like-This
* converts underscores to dashes
*/
string camelcase_dash_http_attr(const string& orig)
{
const char *s = orig.c_str();
char buf[orig.size() + 1];
buf[orig.size()] = '\0';
bool last_sep = true;
for (size_t i = 0; i < orig.size(); ++i, ++s) {
switch (*s) {
case '_':
case '-':
buf[i] = '-';
last_sep = true;
break;
default:
if (last_sep) {
buf[i] = toupper(*s);
} else {
buf[i] = tolower(*s);
}
last_sep = false;
}
}
return string(buf);
}
RGWBucketInfo::RGWBucketInfo()
{
}
RGWBucketInfo::~RGWBucketInfo()
{
}
void RGWBucketInfo::encode(bufferlist& bl) const {
ENCODE_START(23, 4, bl);
encode(bucket, bl);
encode(owner.id, bl);
encode(flags, bl);
encode(zonegroup, bl);
uint64_t ct = real_clock::to_time_t(creation_time);
encode(ct, bl);
encode(placement_rule, bl);
encode(has_instance_obj, bl);
encode(quota, bl);
encode(requester_pays, bl);
encode(owner.tenant, bl);
encode(has_website, bl);
if (has_website) {
encode(website_conf, bl);
}
encode(swift_versioning, bl);
if (swift_versioning) {
encode(swift_ver_location, bl);
}
encode(creation_time, bl);
encode(mdsearch_config, bl);
encode(reshard_status, bl);
encode(new_bucket_instance_id, bl);
if (obj_lock_enabled()) {
encode(obj_lock, bl);
}
bool has_sync_policy = !empty_sync_policy();
encode(has_sync_policy, bl);
if (has_sync_policy) {
encode(*sync_policy, bl);
}
encode(layout, bl);
encode(owner.ns, bl);
ENCODE_FINISH(bl);
}
void RGWBucketInfo::decode(bufferlist::const_iterator& bl) {
DECODE_START_LEGACY_COMPAT_LEN_32(23, 4, 4, bl);
decode(bucket, bl);
if (struct_v >= 2) {
string s;
decode(s, bl);
owner.from_str(s);
}
if (struct_v >= 3)
decode(flags, bl);
if (struct_v >= 5)
decode(zonegroup, bl);
if (struct_v >= 6) {
uint64_t ct;
decode(ct, bl);
if (struct_v < 17)
creation_time = ceph::real_clock::from_time_t((time_t)ct);
}
if (struct_v >= 7)
decode(placement_rule, bl);
if (struct_v >= 8)
decode(has_instance_obj, bl);
if (struct_v >= 9)
decode(quota, bl);
static constexpr uint8_t new_layout_v = 22;
if (struct_v >= 10 && struct_v < new_layout_v)
decode(layout.current_index.layout.normal.num_shards, bl);
if (struct_v >= 11 && struct_v < new_layout_v)
decode(layout.current_index.layout.normal.hash_type, bl);
if (struct_v >= 12)
decode(requester_pays, bl);
if (struct_v >= 13)
decode(owner.tenant, bl);
if (struct_v >= 14) {
decode(has_website, bl);
if (has_website) {
decode(website_conf, bl);
} else {
website_conf = RGWBucketWebsiteConf();
}
}
if (struct_v >= 15 && struct_v < new_layout_v) {
uint32_t it;
decode(it, bl);
layout.current_index.layout.type = (rgw::BucketIndexType)it;
} else {
layout.current_index.layout.type = rgw::BucketIndexType::Normal;
}
swift_versioning = false;
swift_ver_location.clear();
if (struct_v >= 16) {
decode(swift_versioning, bl);
if (swift_versioning) {
decode(swift_ver_location, bl);
}
}
if (struct_v >= 17) {
decode(creation_time, bl);
}
if (struct_v >= 18) {
decode(mdsearch_config, bl);
}
if (struct_v >= 19) {
decode(reshard_status, bl);
decode(new_bucket_instance_id, bl);
}
if (struct_v >= 20 && obj_lock_enabled()) {
decode(obj_lock, bl);
}
if (struct_v >= 21) {
decode(sync_policy, bl);
}
if (struct_v >= 22) {
decode(layout, bl);
}
if (struct_v >= 23) {
decode(owner.ns, bl);
}
if (layout.logs.empty() &&
layout.current_index.layout.type == rgw::BucketIndexType::Normal) {
layout.logs.push_back(rgw::log_layout_from_index(0, layout.current_index));
}
DECODE_FINISH(bl);
}
void RGWBucketInfo::set_sync_policy(rgw_sync_policy_info&& policy)
{
sync_policy = std::move(policy);
}
bool RGWBucketInfo::empty_sync_policy() const
{
if (!sync_policy) {
return true;
}
return sync_policy->empty();
}
struct rgw_pool;
struct rgw_placement_rule;
class RGWUserCaps;
void decode_json_obj(rgw_pool& pool, JSONObj *obj)
{
string s;
decode_json_obj(s, obj);
pool = rgw_pool(s);
}
void encode_json(const char *name, const rgw_placement_rule& r, Formatter *f)
{
encode_json(name, r.to_str(), f);
}
void encode_json(const char *name, const rgw_pool& pool, Formatter *f)
{
f->dump_string(name, pool.to_str());
}
void encode_json(const char *name, const RGWUserCaps& val, Formatter *f)
{
val.dump(f, name);
}
void RGWBucketEnt::generate_test_instances(list<RGWBucketEnt*>& o)
{
RGWBucketEnt *e = new RGWBucketEnt;
init_bucket(&e->bucket, "tenant", "bucket", "pool", ".index_pool", "marker", "10");
e->size = 1024;
e->size_rounded = 4096;
e->count = 1;
o.push_back(e);
o.push_back(new RGWBucketEnt);
}
void RGWBucketEnt::dump(Formatter *f) const
{
encode_json("bucket", bucket, f);
encode_json("size", size, f);
encode_json("size_rounded", size_rounded, f);
utime_t ut(creation_time);
encode_json("mtime", ut, f); /* mtime / creation time discrepency needed for backward compatibility */
encode_json("count", count, f);
encode_json("placement_rule", placement_rule.to_str(), f);
}
void rgw_obj::generate_test_instances(list<rgw_obj*>& o)
{
rgw_bucket b;
init_bucket(&b, "tenant", "bucket", "pool", ".index_pool", "marker", "10");
rgw_obj *obj = new rgw_obj(b, "object");
o.push_back(obj);
o.push_back(new rgw_obj);
}
void rgw_bucket_placement::dump(Formatter *f) const
{
encode_json("bucket", bucket, f);
encode_json("placement_rule", placement_rule, f);
}
void RGWBucketInfo::generate_test_instances(list<RGWBucketInfo*>& o)
{
// Since things without a log will have one synthesized on decode,
// ensure the things we attempt to encode will have one added so we
// round-trip properly.
auto gen_layout = [](rgw::BucketLayout& l) {
l.current_index.gen = 0;
l.current_index.layout.normal.hash_type = rgw::BucketHashType::Mod;
l.current_index.layout.type = rgw::BucketIndexType::Normal;
l.current_index.layout.normal.num_shards = 11;
l.logs.push_back(log_layout_from_index(
l.current_index.gen,
l.current_index));
};
RGWBucketInfo *i = new RGWBucketInfo;
init_bucket(&i->bucket, "tenant", "bucket", "pool", ".index_pool", "marker", "10");
i->owner = "owner";
i->flags = BUCKET_SUSPENDED;
gen_layout(i->layout);
o.push_back(i);
i = new RGWBucketInfo;
gen_layout(i->layout);
o.push_back(i);
}
void RGWBucketInfo::dump(Formatter *f) const
{
encode_json("bucket", bucket, f);
utime_t ut(creation_time);
encode_json("creation_time", ut, f);
encode_json("owner", owner.to_str(), f);
encode_json("flags", flags, f);
encode_json("zonegroup", zonegroup, f);
encode_json("placement_rule", placement_rule, f);
encode_json("has_instance_obj", has_instance_obj, f);
encode_json("quota", quota, f);
encode_json("num_shards", layout.current_index.layout.normal.num_shards, f);
encode_json("bi_shard_hash_type", (uint32_t)layout.current_index.layout.normal.hash_type, f);
encode_json("requester_pays", requester_pays, f);
encode_json("has_website", has_website, f);
if (has_website) {
encode_json("website_conf", website_conf, f);
}
encode_json("swift_versioning", swift_versioning, f);
encode_json("swift_ver_location", swift_ver_location, f);
encode_json("index_type", (uint32_t)layout.current_index.layout.type, f);
encode_json("mdsearch_config", mdsearch_config, f);
encode_json("reshard_status", (int)reshard_status, f);
encode_json("new_bucket_instance_id", new_bucket_instance_id, f);
if (!empty_sync_policy()) {
encode_json("sync_policy", *sync_policy, f);
}
}
void RGWBucketInfo::decode_json(JSONObj *obj) {
JSONDecoder::decode_json("bucket", bucket, obj);
utime_t ut;
JSONDecoder::decode_json("creation_time", ut, obj);
creation_time = ut.to_real_time();
JSONDecoder::decode_json("owner", owner, obj);
JSONDecoder::decode_json("flags", flags, obj);
JSONDecoder::decode_json("zonegroup", zonegroup, obj);
/* backward compatability with region */
if (zonegroup.empty()) {
JSONDecoder::decode_json("region", zonegroup, obj);
}
string pr;
JSONDecoder::decode_json("placement_rule", pr, obj);
placement_rule.from_str(pr);
JSONDecoder::decode_json("has_instance_obj", has_instance_obj, obj);
JSONDecoder::decode_json("quota", quota, obj);
JSONDecoder::decode_json("num_shards", layout.current_index.layout.normal.num_shards, obj);
uint32_t hash_type;
JSONDecoder::decode_json("bi_shard_hash_type", hash_type, obj);
layout.current_index.layout.normal.hash_type = static_cast<rgw::BucketHashType>(hash_type);
JSONDecoder::decode_json("requester_pays", requester_pays, obj);
JSONDecoder::decode_json("has_website", has_website, obj);
if (has_website) {
JSONDecoder::decode_json("website_conf", website_conf, obj);
}
JSONDecoder::decode_json("swift_versioning", swift_versioning, obj);
JSONDecoder::decode_json("swift_ver_location", swift_ver_location, obj);
uint32_t it;
JSONDecoder::decode_json("index_type", it, obj);
layout.current_index.layout.type = (rgw::BucketIndexType)it;
JSONDecoder::decode_json("mdsearch_config", mdsearch_config, obj);
int rs;
JSONDecoder::decode_json("reshard_status", rs, obj);
reshard_status = (cls_rgw_reshard_status)rs;
rgw_sync_policy_info sp;
JSONDecoder::decode_json("sync_policy", sp, obj);
if (!sp.empty()) {
set_sync_policy(std::move(sp));
}
}
void RGWUserInfo::generate_test_instances(list<RGWUserInfo*>& o)
{
RGWUserInfo *i = new RGWUserInfo;
i->user_id = "user_id";
i->display_name = "display_name";
i->user_email = "user@email";
RGWAccessKey k1, k2;
k1.id = "id1";
k1.key = "key1";
k2.id = "id2";
k2.subuser = "subuser";
RGWSubUser u;
u.name = "id2";
u.perm_mask = 0x1;
i->access_keys[k1.id] = k1;
i->swift_keys[k2.id] = k2;
i->subusers[u.name] = u;
o.push_back(i);
o.push_back(new RGWUserInfo);
}
static void user_info_dump_subuser(const char *name, const RGWSubUser& subuser, Formatter *f, void *parent)
{
RGWUserInfo *info = static_cast<RGWUserInfo *>(parent);
subuser.dump(f, info->user_id.to_str());
}
static void user_info_dump_key(const char *name, const RGWAccessKey& key, Formatter *f, void *parent)
{
RGWUserInfo *info = static_cast<RGWUserInfo *>(parent);
key.dump(f, info->user_id.to_str(), false);
}
static void user_info_dump_swift_key(const char *name, const RGWAccessKey& key, Formatter *f, void *parent)
{
RGWUserInfo *info = static_cast<RGWUserInfo *>(parent);
key.dump(f, info->user_id.to_str(), true);
}
static void decode_access_keys(map<string, RGWAccessKey>& m, JSONObj *o)
{
RGWAccessKey k;
k.decode_json(o);
m[k.id] = k;
}
static void decode_swift_keys(map<string, RGWAccessKey>& m, JSONObj *o)
{
RGWAccessKey k;
k.decode_json(o, true);
m[k.id] = k;
}
static void decode_subusers(map<string, RGWSubUser>& m, JSONObj *o)
{
RGWSubUser u;
u.decode_json(o);
m[u.name] = u;
}
struct rgw_flags_desc {
uint32_t mask;
const char *str;
};
static struct rgw_flags_desc rgw_perms[] = {
{ RGW_PERM_FULL_CONTROL, "full-control" },
{ RGW_PERM_READ | RGW_PERM_WRITE, "read-write" },
{ RGW_PERM_READ, "read" },
{ RGW_PERM_WRITE, "write" },
{ RGW_PERM_READ_ACP, "read-acp" },
{ RGW_PERM_WRITE_ACP, "write-acp" },
{ 0, NULL }
};
void rgw_perm_to_str(uint32_t mask, char *buf, int len)
{
const char *sep = "";
int pos = 0;
if (!mask) {
snprintf(buf, len, "<none>");
return;
}
while (mask) {
uint32_t orig_mask = mask;
for (int i = 0; rgw_perms[i].mask; i++) {
struct rgw_flags_desc *desc = &rgw_perms[i];
if ((mask & desc->mask) == desc->mask) {
pos += snprintf(buf + pos, len - pos, "%s%s", sep, desc->str);
if (pos == len)
return;
sep = ", ";
mask &= ~desc->mask;
if (!mask)
return;
}
}
if (mask == orig_mask) // no change
break;
}
}
uint32_t rgw_str_to_perm(const char *str)
{
if (strcasecmp(str, "") == 0)
return RGW_PERM_NONE;
else if (strcasecmp(str, "read") == 0)
return RGW_PERM_READ;
else if (strcasecmp(str, "write") == 0)
return RGW_PERM_WRITE;
else if (strcasecmp(str, "readwrite") == 0)
return RGW_PERM_READ | RGW_PERM_WRITE;
else if (strcasecmp(str, "full") == 0)
return RGW_PERM_FULL_CONTROL;
return RGW_PERM_INVALID;
}
template <class T>
static void mask_to_str(T *mask_list, uint32_t mask, char *buf, int len)
{
const char *sep = "";
int pos = 0;
if (!mask) {
snprintf(buf, len, "<none>");
return;
}
while (mask) {
uint32_t orig_mask = mask;
for (int i = 0; mask_list[i].mask; i++) {
T *desc = &mask_list[i];
if ((mask & desc->mask) == desc->mask) {
pos += snprintf(buf + pos, len - pos, "%s%s", sep, desc->str);
if (pos == len)
return;
sep = ", ";
mask &= ~desc->mask;
if (!mask)
return;
}
}
if (mask == orig_mask) // no change
break;
}
}
static void perm_to_str(uint32_t mask, char *buf, int len)
{
return mask_to_str(rgw_perms, mask, buf, len);
}
static struct rgw_flags_desc op_type_flags[] = {
{ RGW_OP_TYPE_READ, "read" },
{ RGW_OP_TYPE_WRITE, "write" },
{ RGW_OP_TYPE_DELETE, "delete" },
{ 0, NULL }
};
void op_type_to_str(uint32_t mask, char *buf, int len)
{
return mask_to_str(op_type_flags, mask, buf, len);
}
void RGWRateLimitInfo::decode_json(JSONObj *obj)
{
JSONDecoder::decode_json("max_read_ops", max_read_ops, obj);
JSONDecoder::decode_json("max_write_ops", max_write_ops, obj);
JSONDecoder::decode_json("max_read_bytes", max_read_ops, obj);
JSONDecoder::decode_json("max_write_bytes", max_write_ops, obj);
JSONDecoder::decode_json("enabled", enabled, obj);
}
void RGWRateLimitInfo::dump(Formatter *f) const
{
f->dump_int("max_read_ops", max_read_ops);
f->dump_int("max_write_ops", max_write_ops);
f->dump_int("max_read_bytes", max_read_bytes);
f->dump_int("max_write_bytes", max_write_bytes);
f->dump_bool("enabled", enabled);
}
void RGWUserInfo::dump(Formatter *f) const
{
encode_json("user_id", user_id.to_str(), f);
encode_json("display_name", display_name, f);
encode_json("email", user_email, f);
encode_json("suspended", (int)suspended, f);
encode_json("max_buckets", (int)max_buckets, f);
encode_json_map("subusers", NULL, "subuser", NULL, user_info_dump_subuser,(void *)this, subusers, f);
encode_json_map("keys", NULL, "key", NULL, user_info_dump_key,(void *)this, access_keys, f);
encode_json_map("swift_keys", NULL, "key", NULL, user_info_dump_swift_key,(void *)this, swift_keys, f);
encode_json("caps", caps, f);
char buf[256];
op_type_to_str(op_mask, buf, sizeof(buf));
encode_json("op_mask", (const char *)buf, f);
if (system) { /* no need to show it for every user */
encode_json("system", (bool)system, f);
}
if (admin) {
encode_json("admin", (bool)admin, f);
}
encode_json("default_placement", default_placement.name, f);
encode_json("default_storage_class", default_placement.storage_class, f);
encode_json("placement_tags", placement_tags, f);
encode_json("bucket_quota", quota.bucket_quota, f);
encode_json("user_quota", quota.user_quota, f);
encode_json("temp_url_keys", temp_url_keys, f);
string user_source_type;
switch ((RGWIdentityType)type) {
case TYPE_RGW:
user_source_type = "rgw";
break;
case TYPE_KEYSTONE:
user_source_type = "keystone";
break;
case TYPE_LDAP:
user_source_type = "ldap";
break;
case TYPE_NONE:
user_source_type = "none";
break;
default:
user_source_type = "none";
break;
}
encode_json("type", user_source_type, f);
encode_json("mfa_ids", mfa_ids, f);
}
void RGWUserInfo::decode_json(JSONObj *obj)
{
string uid;
JSONDecoder::decode_json("user_id", uid, obj, true);
user_id.from_str(uid);
JSONDecoder::decode_json("display_name", display_name, obj);
JSONDecoder::decode_json("email", user_email, obj);
bool susp = false;
JSONDecoder::decode_json("suspended", susp, obj);
suspended = (__u8)susp;
JSONDecoder::decode_json("max_buckets", max_buckets, obj);
JSONDecoder::decode_json("keys", access_keys, decode_access_keys, obj);
JSONDecoder::decode_json("swift_keys", swift_keys, decode_swift_keys, obj);
JSONDecoder::decode_json("subusers", subusers, decode_subusers, obj);
JSONDecoder::decode_json("caps", caps, obj);
string mask_str;
JSONDecoder::decode_json("op_mask", mask_str, obj);
rgw_parse_op_type_list(mask_str, &op_mask);
bool sys = false;
JSONDecoder::decode_json("system", sys, obj);
system = (__u8)sys;
bool ad = false;
JSONDecoder::decode_json("admin", ad, obj);
admin = (__u8)ad;
JSONDecoder::decode_json("default_placement", default_placement.name, obj);
JSONDecoder::decode_json("default_storage_class", default_placement.storage_class, obj);
JSONDecoder::decode_json("placement_tags", placement_tags, obj);
JSONDecoder::decode_json("bucket_quota", quota.bucket_quota, obj);
JSONDecoder::decode_json("user_quota", quota.user_quota, obj);
JSONDecoder::decode_json("temp_url_keys", temp_url_keys, obj);
string user_source_type;
JSONDecoder::decode_json("type", user_source_type, obj);
if (user_source_type == "rgw") {
type = TYPE_RGW;
} else if (user_source_type == "keystone") {
type = TYPE_KEYSTONE;
} else if (user_source_type == "ldap") {
type = TYPE_LDAP;
} else if (user_source_type == "none") {
type = TYPE_NONE;
}
JSONDecoder::decode_json("mfa_ids", mfa_ids, obj);
}
void RGWSubUser::generate_test_instances(list<RGWSubUser*>& o)
{
RGWSubUser *u = new RGWSubUser;
u->name = "name";
u->perm_mask = 0xf;
o.push_back(u);
o.push_back(new RGWSubUser);
}
void RGWSubUser::dump(Formatter *f) const
{
encode_json("id", name, f);
char buf[256];
perm_to_str(perm_mask, buf, sizeof(buf));
encode_json("permissions", (const char *)buf, f);
}
void RGWSubUser::dump(Formatter *f, const string& user) const
{
string s = user;
s.append(":");
s.append(name);
encode_json("id", s, f);
char buf[256];
perm_to_str(perm_mask, buf, sizeof(buf));
encode_json("permissions", (const char *)buf, f);
}
uint32_t str_to_perm(const string& s)
{
if (s.compare("read") == 0)
return RGW_PERM_READ;
else if (s.compare("write") == 0)
return RGW_PERM_WRITE;
else if (s.compare("read-write") == 0)
return RGW_PERM_READ | RGW_PERM_WRITE;
else if (s.compare("full-control") == 0)
return RGW_PERM_FULL_CONTROL;
return 0;
}
void RGWSubUser::decode_json(JSONObj *obj)
{
string uid;
JSONDecoder::decode_json("id", uid, obj);
int pos = uid.find(':');
if (pos >= 0)
name = uid.substr(pos + 1);
string perm_str;
JSONDecoder::decode_json("permissions", perm_str, obj);
perm_mask = str_to_perm(perm_str);
}
void RGWAccessKey::generate_test_instances(list<RGWAccessKey*>& o)
{
RGWAccessKey *k = new RGWAccessKey;
k->id = "id";
k->key = "key";
k->subuser = "subuser";
o.push_back(k);
o.push_back(new RGWAccessKey);
}
void RGWAccessKey::dump(Formatter *f) const
{
encode_json("access_key", id, f);
encode_json("secret_key", key, f);
encode_json("subuser", subuser, f);
}
void RGWAccessKey::dump_plain(Formatter *f) const
{
encode_json("access_key", id, f);
encode_json("secret_key", key, f);
}
void RGWAccessKey::dump(Formatter *f, const string& user, bool swift) const
{
string u = user;
if (!subuser.empty()) {
u.append(":");
u.append(subuser);
}
encode_json("user", u, f);
if (!swift) {
encode_json("access_key", id, f);
}
encode_json("secret_key", key, f);
}
void RGWAccessKey::decode_json(JSONObj *obj) {
JSONDecoder::decode_json("access_key", id, obj, true);
JSONDecoder::decode_json("secret_key", key, obj, true);
if (!JSONDecoder::decode_json("subuser", subuser, obj)) {
string user;
JSONDecoder::decode_json("user", user, obj);
int pos = user.find(':');
if (pos >= 0) {
subuser = user.substr(pos + 1);
}
}
}
void RGWAccessKey::decode_json(JSONObj *obj, bool swift) {
if (!swift) {
decode_json(obj);
return;
}
if (!JSONDecoder::decode_json("subuser", subuser, obj)) {
JSONDecoder::decode_json("user", id, obj, true);
int pos = id.find(':');
if (pos >= 0) {
subuser = id.substr(pos + 1);
}
}
JSONDecoder::decode_json("secret_key", key, obj, true);
}
void RGWStorageStats::dump(Formatter *f) const
{
encode_json("size", size, f);
encode_json("size_actual", size_rounded, f);
if (dump_utilized) {
encode_json("size_utilized", size_utilized, f);
}
encode_json("size_kb", rgw_rounded_kb(size), f);
encode_json("size_kb_actual", rgw_rounded_kb(size_rounded), f);
if (dump_utilized) {
encode_json("size_kb_utilized", rgw_rounded_kb(size_utilized), f);
}
encode_json("num_objects", num_objects, f);
}
void rgw_obj_key::dump(Formatter *f) const
{
encode_json("name", name, f);
encode_json("instance", instance, f);
encode_json("ns", ns, f);
}
void rgw_obj_key::decode_json(JSONObj *obj)
{
JSONDecoder::decode_json("name", name, obj);
JSONDecoder::decode_json("instance", instance, obj);
JSONDecoder::decode_json("ns", ns, obj);
}
void rgw_raw_obj::dump(Formatter *f) const
{
encode_json("pool", pool, f);
encode_json("oid", oid, f);
encode_json("loc", loc, f);
}
void rgw_raw_obj::decode_json(JSONObj *obj) {
JSONDecoder::decode_json("pool", pool, obj);
JSONDecoder::decode_json("oid", oid, obj);
JSONDecoder::decode_json("loc", loc, obj);
}
void rgw_obj::dump(Formatter *f) const
{
encode_json("bucket", bucket, f);
encode_json("key", key, f);
}
int rgw_bucket_parse_bucket_instance(const string& bucket_instance, string *bucket_name, string *bucket_id, int *shard_id)
{
auto pos = bucket_instance.rfind(':');
if (pos == string::npos) {
return -EINVAL;
}
string first = bucket_instance.substr(0, pos);
string second = bucket_instance.substr(pos + 1);
pos = first.find(':');
if (pos == string::npos) {
*shard_id = -1;
*bucket_name = first;
*bucket_id = second;
return 0;
}
*bucket_name = first.substr(0, pos);
*bucket_id = first.substr(pos + 1);
string err;
*shard_id = strict_strtol(second.c_str(), 10, &err);
if (!err.empty()) {
return -EINVAL;
}
return 0;
}
boost::intrusive_ptr<CephContext>
rgw_global_init(const std::map<std::string,std::string> *defaults,
std::vector < const char* >& args,
uint32_t module_type, code_environment_t code_env,
int flags)
{
// Load the config from the files, but not the mon
global_pre_init(defaults, args, module_type, code_env, flags);
// Get the store backend
const auto& config_store = g_conf().get_val<std::string>("rgw_backend_store");
if ((config_store == "dbstore") ||
(config_store == "motr") ||
(config_store == "daos")) {
// These stores don't use the mon
flags |= CINIT_FLAG_NO_MON_CONFIG;
}
// Finish global init, indicating we already ran pre-init
return global_init(defaults, args, module_type, code_env, flags, false);
}
void RGWObjVersionTracker::generate_new_write_ver(CephContext *cct)
{
write_version.ver = 1;
#define TAG_LEN 24
write_version.tag.clear();
append_rand_alpha(cct, write_version.tag, write_version.tag, TAG_LEN);
}
| 88,229 | 27.683355 | 150 |
cc
|
null |
ceph-main/src/rgw/rgw_common.h
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2004-2009 Sage Weil <[email protected]>
* Copyright (C) 2015 Yehuda Sadeh <[email protected]>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#pragma once
#include <array>
#include <string_view>
#include <atomic>
#include <unordered_map>
#include <fmt/format.h>
#include "common/ceph_crypto.h"
#include "common/random_string.h"
#include "rgw_acl.h"
#include "rgw_bucket_layout.h"
#include "rgw_cors.h"
#include "rgw_basic_types.h"
#include "rgw_iam_policy.h"
#include "rgw_quota_types.h"
#include "rgw_string.h"
#include "common/async/yield_context.h"
#include "rgw_website.h"
#include "rgw_object_lock.h"
#include "rgw_tag.h"
#include "rgw_op_type.h"
#include "rgw_sync_policy.h"
#include "cls/version/cls_version_types.h"
#include "cls/user/cls_user_types.h"
#include "cls/rgw/cls_rgw_types.h"
#include "include/rados/librados.hpp"
#include "rgw_public_access.h"
#include "common/tracer.h"
#include "rgw_sal_fwd.h"
namespace ceph {
class Formatter;
}
namespace rgw::sal {
using Attrs = std::map<std::string, ceph::buffer::list>;
}
namespace rgw::lua {
class Background;
}
struct RGWProcessEnv;
using ceph::crypto::MD5;
#define RGW_ATTR_PREFIX "user.rgw."
#define RGW_HTTP_RGWX_ATTR_PREFIX "RGWX_ATTR_"
#define RGW_HTTP_RGWX_ATTR_PREFIX_OUT "Rgwx-Attr-"
#define RGW_AMZ_PREFIX "x-amz-"
#define RGW_AMZ_META_PREFIX RGW_AMZ_PREFIX "meta-"
#define RGW_AMZ_WEBSITE_REDIRECT_LOCATION RGW_AMZ_PREFIX "website-redirect-location"
#define RGW_AMZ_TAG_COUNT RGW_AMZ_PREFIX "tagging-count"
#define RGW_SYS_PARAM_PREFIX "rgwx-"
#define RGW_ATTR_ACL RGW_ATTR_PREFIX "acl"
#define RGW_ATTR_RATELIMIT RGW_ATTR_PREFIX "ratelimit"
#define RGW_ATTR_LC RGW_ATTR_PREFIX "lc"
#define RGW_ATTR_CORS RGW_ATTR_PREFIX "cors"
#define RGW_ATTR_ETAG RGW_ATTR_PREFIX "etag"
#define RGW_ATTR_BUCKETS RGW_ATTR_PREFIX "buckets"
#define RGW_ATTR_META_PREFIX RGW_ATTR_PREFIX RGW_AMZ_META_PREFIX
#define RGW_ATTR_CONTENT_TYPE RGW_ATTR_PREFIX "content_type"
#define RGW_ATTR_CACHE_CONTROL RGW_ATTR_PREFIX "cache_control"
#define RGW_ATTR_CONTENT_DISP RGW_ATTR_PREFIX "content_disposition"
#define RGW_ATTR_CONTENT_ENC RGW_ATTR_PREFIX "content_encoding"
#define RGW_ATTR_CONTENT_LANG RGW_ATTR_PREFIX "content_language"
#define RGW_ATTR_EXPIRES RGW_ATTR_PREFIX "expires"
#define RGW_ATTR_DELETE_AT RGW_ATTR_PREFIX "delete_at"
#define RGW_ATTR_ID_TAG RGW_ATTR_PREFIX "idtag"
#define RGW_ATTR_TAIL_TAG RGW_ATTR_PREFIX "tail_tag"
#define RGW_ATTR_SHADOW_OBJ RGW_ATTR_PREFIX "shadow_name"
#define RGW_ATTR_MANIFEST RGW_ATTR_PREFIX "manifest"
#define RGW_ATTR_USER_MANIFEST RGW_ATTR_PREFIX "user_manifest"
#define RGW_ATTR_AMZ_WEBSITE_REDIRECT_LOCATION RGW_ATTR_PREFIX RGW_AMZ_WEBSITE_REDIRECT_LOCATION
#define RGW_ATTR_SLO_MANIFEST RGW_ATTR_PREFIX "slo_manifest"
/* Information whether an object is SLO or not must be exposed to
* user through custom HTTP header named X-Static-Large-Object. */
#define RGW_ATTR_SLO_UINDICATOR RGW_ATTR_META_PREFIX "static-large-object"
#define RGW_ATTR_X_ROBOTS_TAG RGW_ATTR_PREFIX "x-robots-tag"
#define RGW_ATTR_STORAGE_CLASS RGW_ATTR_PREFIX "storage_class"
/* S3 Object Lock*/
#define RGW_ATTR_OBJECT_LOCK RGW_ATTR_PREFIX "object-lock"
#define RGW_ATTR_OBJECT_RETENTION RGW_ATTR_PREFIX "object-retention"
#define RGW_ATTR_OBJECT_LEGAL_HOLD RGW_ATTR_PREFIX "object-legal-hold"
#define RGW_ATTR_PG_VER RGW_ATTR_PREFIX "pg_ver"
#define RGW_ATTR_SOURCE_ZONE RGW_ATTR_PREFIX "source_zone"
#define RGW_ATTR_TAGS RGW_ATTR_PREFIX RGW_AMZ_PREFIX "tagging"
#define RGW_ATTR_TEMPURL_KEY1 RGW_ATTR_META_PREFIX "temp-url-key"
#define RGW_ATTR_TEMPURL_KEY2 RGW_ATTR_META_PREFIX "temp-url-key-2"
/* Account/container quota of the Swift API. */
#define RGW_ATTR_QUOTA_NOBJS RGW_ATTR_META_PREFIX "quota-count"
#define RGW_ATTR_QUOTA_MSIZE RGW_ATTR_META_PREFIX "quota-bytes"
/* Static Web Site of Swift API. */
#define RGW_ATTR_WEB_INDEX RGW_ATTR_META_PREFIX "web-index"
#define RGW_ATTR_WEB_ERROR RGW_ATTR_META_PREFIX "web-error"
#define RGW_ATTR_WEB_LISTINGS RGW_ATTR_META_PREFIX "web-listings"
#define RGW_ATTR_WEB_LIST_CSS RGW_ATTR_META_PREFIX "web-listings-css"
#define RGW_ATTR_SUBDIR_MARKER RGW_ATTR_META_PREFIX "web-directory-type"
#define RGW_ATTR_OLH_PREFIX RGW_ATTR_PREFIX "olh."
#define RGW_ATTR_OLH_INFO RGW_ATTR_OLH_PREFIX "info"
#define RGW_ATTR_OLH_VER RGW_ATTR_OLH_PREFIX "ver"
#define RGW_ATTR_OLH_ID_TAG RGW_ATTR_OLH_PREFIX "idtag"
#define RGW_ATTR_OLH_PENDING_PREFIX RGW_ATTR_OLH_PREFIX "pending."
#define RGW_ATTR_COMPRESSION RGW_ATTR_PREFIX "compression"
#define RGW_ATTR_TORRENT RGW_ATTR_PREFIX "torrent"
#define RGW_ATTR_APPEND_PART_NUM RGW_ATTR_PREFIX "append_part_num"
/* Attrs to store cloudtier config information. These are used internally
* for the replication of cloudtiered objects but not stored as xattrs in
* the head object. */
#define RGW_ATTR_CLOUD_TIER_TYPE RGW_ATTR_PREFIX "cloud_tier_type"
#define RGW_ATTR_CLOUD_TIER_CONFIG RGW_ATTR_PREFIX "cloud_tier_config"
#define RGW_ATTR_OBJ_REPLICATION_STATUS RGW_ATTR_PREFIX "amz-replication-status"
#define RGW_ATTR_OBJ_REPLICATION_TRACE RGW_ATTR_PREFIX "replication-trace"
/* IAM Policy */
#define RGW_ATTR_IAM_POLICY RGW_ATTR_PREFIX "iam-policy"
#define RGW_ATTR_USER_POLICY RGW_ATTR_PREFIX "user-policy"
#define RGW_ATTR_PUBLIC_ACCESS RGW_ATTR_PREFIX "public-access"
/* RGW File Attributes */
#define RGW_ATTR_UNIX_KEY1 RGW_ATTR_PREFIX "unix-key1"
#define RGW_ATTR_UNIX1 RGW_ATTR_PREFIX "unix1"
#define RGW_ATTR_CRYPT_PREFIX RGW_ATTR_PREFIX "crypt."
#define RGW_ATTR_CRYPT_MODE RGW_ATTR_CRYPT_PREFIX "mode"
#define RGW_ATTR_CRYPT_KEYMD5 RGW_ATTR_CRYPT_PREFIX "keymd5"
#define RGW_ATTR_CRYPT_KEYID RGW_ATTR_CRYPT_PREFIX "keyid"
#define RGW_ATTR_CRYPT_KEYSEL RGW_ATTR_CRYPT_PREFIX "keysel"
#define RGW_ATTR_CRYPT_CONTEXT RGW_ATTR_CRYPT_PREFIX "context"
#define RGW_ATTR_CRYPT_DATAKEY RGW_ATTR_CRYPT_PREFIX "datakey"
/* SSE-S3 Encryption Attributes */
#define RGW_ATTR_BUCKET_ENCRYPTION_PREFIX RGW_ATTR_PREFIX "sse-s3."
#define RGW_ATTR_BUCKET_ENCRYPTION_POLICY RGW_ATTR_BUCKET_ENCRYPTION_PREFIX "policy"
#define RGW_ATTR_BUCKET_ENCRYPTION_KEY_ID RGW_ATTR_BUCKET_ENCRYPTION_PREFIX "key-id"
#define RGW_ATTR_TRACE RGW_ATTR_PREFIX "trace"
enum class RGWFormat : int8_t {
BAD_FORMAT = -1,
PLAIN = 0,
XML,
JSON,
HTML,
};
static inline const char* to_mime_type(const RGWFormat f)
{
switch (f) {
case RGWFormat::XML:
return "application/xml";
break;
case RGWFormat::JSON:
return "application/json";
break;
case RGWFormat::HTML:
return "text/html";
break;
case RGWFormat::PLAIN:
return "text/plain";
break;
default:
return "invalid format";
}
}
#define RGW_CAP_READ 0x1
#define RGW_CAP_WRITE 0x2
#define RGW_CAP_ALL (RGW_CAP_READ | RGW_CAP_WRITE)
#define RGW_REST_SWIFT 0x1
#define RGW_REST_SWIFT_AUTH 0x2
#define RGW_REST_S3 0x4
#define RGW_REST_WEBSITE 0x8
#define RGW_REST_STS 0x10
#define RGW_REST_IAM 0x20
#define RGW_REST_SNS 0x30
#define RGW_SUSPENDED_USER_AUID (uint64_t)-2
#define RGW_OP_TYPE_READ 0x01
#define RGW_OP_TYPE_WRITE 0x02
#define RGW_OP_TYPE_DELETE 0x04
#define RGW_OP_TYPE_MODIFY (RGW_OP_TYPE_WRITE | RGW_OP_TYPE_DELETE)
#define RGW_OP_TYPE_ALL (RGW_OP_TYPE_READ | RGW_OP_TYPE_WRITE | RGW_OP_TYPE_DELETE)
#define RGW_DEFAULT_MAX_BUCKETS 1000
#define RGW_DEFER_TO_BUCKET_ACLS_RECURSE 1
#define RGW_DEFER_TO_BUCKET_ACLS_FULL_CONTROL 2
#define STATUS_CREATED 1900
#define STATUS_ACCEPTED 1901
#define STATUS_NO_CONTENT 1902
#define STATUS_PARTIAL_CONTENT 1903
#define STATUS_REDIRECT 1904
#define STATUS_NO_APPLY 1905
#define STATUS_APPLIED 1906
#define ERR_INVALID_BUCKET_NAME 2000
#define ERR_INVALID_OBJECT_NAME 2001
#define ERR_NO_SUCH_BUCKET 2002
#define ERR_METHOD_NOT_ALLOWED 2003
#define ERR_INVALID_DIGEST 2004
#define ERR_BAD_DIGEST 2005
#define ERR_UNRESOLVABLE_EMAIL 2006
#define ERR_INVALID_PART 2007
#define ERR_INVALID_PART_ORDER 2008
#define ERR_NO_SUCH_UPLOAD 2009
#define ERR_REQUEST_TIMEOUT 2010
#define ERR_LENGTH_REQUIRED 2011
#define ERR_REQUEST_TIME_SKEWED 2012
#define ERR_BUCKET_EXISTS 2013
#define ERR_BAD_URL 2014
#define ERR_PRECONDITION_FAILED 2015
#define ERR_NOT_MODIFIED 2016
#define ERR_INVALID_UTF8 2017
#define ERR_UNPROCESSABLE_ENTITY 2018
#define ERR_TOO_LARGE 2019
#define ERR_TOO_MANY_BUCKETS 2020
#define ERR_INVALID_REQUEST 2021
#define ERR_TOO_SMALL 2022
#define ERR_NOT_FOUND 2023
#define ERR_PERMANENT_REDIRECT 2024
#define ERR_LOCKED 2025
#define ERR_QUOTA_EXCEEDED 2026
#define ERR_SIGNATURE_NO_MATCH 2027
#define ERR_INVALID_ACCESS_KEY 2028
#define ERR_MALFORMED_XML 2029
#define ERR_USER_EXIST 2030
#define ERR_NOT_SLO_MANIFEST 2031
#define ERR_EMAIL_EXIST 2032
#define ERR_KEY_EXIST 2033
#define ERR_INVALID_SECRET_KEY 2034
#define ERR_INVALID_KEY_TYPE 2035
#define ERR_INVALID_CAP 2036
#define ERR_INVALID_TENANT_NAME 2037
#define ERR_WEBSITE_REDIRECT 2038
#define ERR_NO_SUCH_WEBSITE_CONFIGURATION 2039
#define ERR_AMZ_CONTENT_SHA256_MISMATCH 2040
#define ERR_NO_SUCH_LC 2041
#define ERR_NO_SUCH_USER 2042
#define ERR_NO_SUCH_SUBUSER 2043
#define ERR_MFA_REQUIRED 2044
#define ERR_NO_SUCH_CORS_CONFIGURATION 2045
#define ERR_NO_SUCH_OBJECT_LOCK_CONFIGURATION 2046
#define ERR_INVALID_RETENTION_PERIOD 2047
#define ERR_NO_SUCH_BUCKET_ENCRYPTION_CONFIGURATION 2048
#define ERR_USER_SUSPENDED 2100
#define ERR_INTERNAL_ERROR 2200
#define ERR_NOT_IMPLEMENTED 2201
#define ERR_SERVICE_UNAVAILABLE 2202
#define ERR_ROLE_EXISTS 2203
#define ERR_MALFORMED_DOC 2204
#define ERR_NO_ROLE_FOUND 2205
#define ERR_DELETE_CONFLICT 2206
#define ERR_NO_SUCH_BUCKET_POLICY 2207
#define ERR_INVALID_LOCATION_CONSTRAINT 2208
#define ERR_TAG_CONFLICT 2209
#define ERR_INVALID_TAG 2210
#define ERR_ZERO_IN_URL 2211
#define ERR_MALFORMED_ACL_ERROR 2212
#define ERR_ZONEGROUP_DEFAULT_PLACEMENT_MISCONFIGURATION 2213
#define ERR_INVALID_ENCRYPTION_ALGORITHM 2214
#define ERR_INVALID_CORS_RULES_ERROR 2215
#define ERR_NO_CORS_FOUND 2216
#define ERR_INVALID_WEBSITE_ROUTING_RULES_ERROR 2217
#define ERR_RATE_LIMITED 2218
#define ERR_POSITION_NOT_EQUAL_TO_LENGTH 2219
#define ERR_OBJECT_NOT_APPENDABLE 2220
#define ERR_INVALID_BUCKET_STATE 2221
#define ERR_INVALID_OBJECT_STATE 2222
#define ERR_BUSY_RESHARDING 2300
#define ERR_NO_SUCH_ENTITY 2301
#define ERR_LIMIT_EXCEEDED 2302
// STS Errors
#define ERR_PACKED_POLICY_TOO_LARGE 2400
#define ERR_INVALID_IDENTITY_TOKEN 2401
#define ERR_NO_SUCH_TAG_SET 2402
#ifndef UINT32_MAX
#define UINT32_MAX (0xffffffffu)
#endif
typedef void *RGWAccessHandle;
/* Helper class used for RGWHTTPArgs parsing */
class NameVal
{
const std::string str;
std::string name;
std::string val;
public:
explicit NameVal(const std::string& nv) : str(nv) {}
int parse();
std::string& get_name() { return name; }
std::string& get_val() { return val; }
};
/** Stores the XML arguments associated with the HTTP request in req_state*/
class RGWHTTPArgs {
std::string str, empty_str;
std::map<std::string, std::string> val_map;
std::map<std::string, std::string> sys_val_map;
std::map<std::string, std::string> sub_resources;
bool has_resp_modifier = false;
bool admin_subresource_added = false;
public:
RGWHTTPArgs() = default;
explicit RGWHTTPArgs(const std::string& s, const DoutPrefixProvider *dpp) {
set(s);
parse(dpp);
}
/** Set the arguments; as received */
void set(const std::string& s) {
has_resp_modifier = false;
val_map.clear();
sub_resources.clear();
str = s;
}
/** parse the received arguments */
int parse(const DoutPrefixProvider *dpp);
void append(const std::string& name, const std::string& val);
void remove(const std::string& name);
/** Get the value for a specific argument parameter */
const std::string& get(const std::string& name, bool *exists = NULL) const;
boost::optional<const std::string&>
get_optional(const std::string& name) const;
int get_bool(const std::string& name, bool *val, bool *exists) const;
int get_bool(const char *name, bool *val, bool *exists) const;
void get_bool(const char *name, bool *val, bool def_val) const;
int get_int(const char *name, int *val, int def_val) const;
/** Get the value for specific system argument parameter */
std::string sys_get(const std::string& name, bool *exists = nullptr) const;
/** see if a parameter is contained in this RGWHTTPArgs */
bool exists(const char *name) const {
return (val_map.find(name) != std::end(val_map));
}
bool sub_resource_exists(const char *name) const {
return (sub_resources.find(name) != std::end(sub_resources));
}
bool exist_obj_excl_sub_resource() const {
const char* const obj_sub_resource[] = {"append", "torrent", "uploadId",
"partNumber", "versionId"};
for (unsigned i = 0; i != std::size(obj_sub_resource); i++) {
if (sub_resource_exists(obj_sub_resource[i])) return true;
}
return false;
}
std::map<std::string, std::string>& get_params() {
return val_map;
}
const std::map<std::string, std::string>& get_params() const {
return val_map;
}
std::map<std::string, std::string>& get_sys_params() {
return sys_val_map;
}
const std::map<std::string, std::string>& get_sys_params() const {
return sys_val_map;
}
const std::map<std::string, std::string>& get_sub_resources() const {
return sub_resources;
}
unsigned get_num_params() const {
return val_map.size();
}
bool has_response_modifier() const {
return has_resp_modifier;
}
void set_system() { /* make all system params visible */
std::map<std::string, std::string>::iterator iter;
for (iter = sys_val_map.begin(); iter != sys_val_map.end(); ++iter) {
val_map[iter->first] = iter->second;
}
}
const std::string& get_str() {
return str;
}
}; // RGWHTTPArgs
const char *rgw_conf_get(const std::map<std::string, std::string, ltstr_nocase>& conf_map, const char *name, const char *def_val);
boost::optional<const std::string&> rgw_conf_get_optional(const std::map<std::string, std::string, ltstr_nocase>& conf_map, const std::string& name);
int rgw_conf_get_int(const std::map<std::string, std::string, ltstr_nocase>& conf_map, const char *name, int def_val);
bool rgw_conf_get_bool(const std::map<std::string, std::string, ltstr_nocase>& conf_map, const char *name, bool def_val);
class RGWEnv;
class RGWConf {
friend class RGWEnv;
int enable_ops_log;
int enable_usage_log;
uint8_t defer_to_bucket_acls;
void init(CephContext *cct);
public:
RGWConf()
: enable_ops_log(1),
enable_usage_log(1),
defer_to_bucket_acls(0) {
}
};
class RGWEnv {
std::map<std::string, std::string, ltstr_nocase> env_map;
RGWConf conf;
public:
void init(CephContext *cct);
void init(CephContext *cct, char **envp);
void set(std::string name, std::string val);
const char *get(const char *name, const char *def_val = nullptr) const;
boost::optional<const std::string&>
get_optional(const std::string& name) const;
int get_int(const char *name, int def_val = 0) const;
bool get_bool(const char *name, bool def_val = 0);
size_t get_size(const char *name, size_t def_val = 0) const;
bool exists(const char *name) const;
bool exists_prefix(const char *prefix) const;
void remove(const char *name);
const std::map<std::string, std::string, ltstr_nocase>& get_map() const { return env_map; }
int get_enable_ops_log() const {
return conf.enable_ops_log;
}
int get_enable_usage_log() const {
return conf.enable_usage_log;
}
int get_defer_to_bucket_acls() const {
return conf.defer_to_bucket_acls;
}
};
// return true if the connection is secure. this either means that the
// connection arrived via ssl, or was forwarded as https by a trusted proxy
bool rgw_transport_is_secure(CephContext *cct, const RGWEnv& env);
enum http_op {
OP_GET,
OP_PUT,
OP_DELETE,
OP_HEAD,
OP_POST,
OP_COPY,
OP_OPTIONS,
OP_UNKNOWN,
};
class RGWAccessControlPolicy;
class JSONObj;
void encode_json(const char *name, const obj_version& v, Formatter *f);
void encode_json(const char *name, const RGWUserCaps& val, Formatter *f);
void decode_json_obj(obj_version& v, JSONObj *obj);
enum RGWIdentityType
{
TYPE_NONE=0,
TYPE_RGW=1,
TYPE_KEYSTONE=2,
TYPE_LDAP=3,
TYPE_ROLE=4,
TYPE_WEB=5,
};
void encode_json(const char *name, const rgw_placement_rule& val, ceph::Formatter *f);
void decode_json_obj(rgw_placement_rule& v, JSONObj *obj);
inline std::ostream& operator<<(std::ostream& out, const rgw_placement_rule& rule) {
return out << rule.to_str();
}
class RateLimiter;
struct RGWRateLimitInfo {
int64_t max_write_ops;
int64_t max_read_ops;
int64_t max_write_bytes;
int64_t max_read_bytes;
bool enabled = false;
RGWRateLimitInfo()
: max_write_ops(0), max_read_ops(0), max_write_bytes(0), max_read_bytes(0) {}
void encode(bufferlist& bl) const {
ENCODE_START(1, 1, bl);
encode(max_write_ops, bl);
encode(max_read_ops, bl);
encode(max_write_bytes, bl);
encode(max_read_bytes, bl);
encode(enabled, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& bl) {
DECODE_START(1, bl);
decode(max_write_ops,bl);
decode(max_read_ops, bl);
decode(max_write_bytes,bl);
decode(max_read_bytes, bl);
decode(enabled, bl);
DECODE_FINISH(bl);
}
void dump(Formatter *f) const;
void decode_json(JSONObj *obj);
};
WRITE_CLASS_ENCODER(RGWRateLimitInfo)
struct RGWUserInfo
{
rgw_user user_id;
std::string display_name;
std::string user_email;
std::map<std::string, RGWAccessKey> access_keys;
std::map<std::string, RGWAccessKey> swift_keys;
std::map<std::string, RGWSubUser> subusers;
__u8 suspended;
int32_t max_buckets;
uint32_t op_mask;
RGWUserCaps caps;
__u8 admin;
__u8 system;
rgw_placement_rule default_placement;
std::list<std::string> placement_tags;
std::map<int, std::string> temp_url_keys;
RGWQuota quota;
uint32_t type;
std::set<std::string> mfa_ids;
RGWUserInfo()
: suspended(0),
max_buckets(RGW_DEFAULT_MAX_BUCKETS),
op_mask(RGW_OP_TYPE_ALL),
admin(0),
system(0),
type(TYPE_NONE) {
}
RGWAccessKey* get_key(const std::string& access_key) {
if (access_keys.empty())
return nullptr;
auto k = access_keys.find(access_key);
if (k == access_keys.end())
return nullptr;
else
return &(k->second);
}
void encode(bufferlist& bl) const {
ENCODE_START(22, 9, bl);
encode((uint64_t)0, bl); // old auid
std::string access_key;
std::string secret_key;
if (!access_keys.empty()) {
std::map<std::string, RGWAccessKey>::const_iterator iter = access_keys.begin();
const RGWAccessKey& k = iter->second;
access_key = k.id;
secret_key = k.key;
}
encode(access_key, bl);
encode(secret_key, bl);
encode(display_name, bl);
encode(user_email, bl);
std::string swift_name;
std::string swift_key;
if (!swift_keys.empty()) {
std::map<std::string, RGWAccessKey>::const_iterator iter = swift_keys.begin();
const RGWAccessKey& k = iter->second;
swift_name = k.id;
swift_key = k.key;
}
encode(swift_name, bl);
encode(swift_key, bl);
encode(user_id.id, bl);
encode(access_keys, bl);
encode(subusers, bl);
encode(suspended, bl);
encode(swift_keys, bl);
encode(max_buckets, bl);
encode(caps, bl);
encode(op_mask, bl);
encode(system, bl);
encode(default_placement, bl);
encode(placement_tags, bl);
encode(quota.bucket_quota, bl);
encode(temp_url_keys, bl);
encode(quota.user_quota, bl);
encode(user_id.tenant, bl);
encode(admin, bl);
encode(type, bl);
encode(mfa_ids, bl);
{
std::string assumed_role_arn; // removed
encode(assumed_role_arn, bl);
}
encode(user_id.ns, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& bl) {
DECODE_START_LEGACY_COMPAT_LEN_32(22, 9, 9, bl);
if (struct_v >= 2) {
uint64_t old_auid;
decode(old_auid, bl);
}
std::string access_key;
std::string secret_key;
decode(access_key, bl);
decode(secret_key, bl);
if (struct_v < 6) {
RGWAccessKey k;
k.id = access_key;
k.key = secret_key;
access_keys[access_key] = k;
}
decode(display_name, bl);
decode(user_email, bl);
/* We populate swift_keys map later nowadays, but we have to decode. */
std::string swift_name;
std::string swift_key;
if (struct_v >= 3) decode(swift_name, bl);
if (struct_v >= 4) decode(swift_key, bl);
if (struct_v >= 5)
decode(user_id.id, bl);
else
user_id.id = access_key;
if (struct_v >= 6) {
decode(access_keys, bl);
decode(subusers, bl);
}
suspended = 0;
if (struct_v >= 7) {
decode(suspended, bl);
}
if (struct_v >= 8) {
decode(swift_keys, bl);
}
if (struct_v >= 10) {
decode(max_buckets, bl);
} else {
max_buckets = RGW_DEFAULT_MAX_BUCKETS;
}
if (struct_v >= 11) {
decode(caps, bl);
}
if (struct_v >= 12) {
decode(op_mask, bl);
} else {
op_mask = RGW_OP_TYPE_ALL;
}
if (struct_v >= 13) {
decode(system, bl);
decode(default_placement, bl);
decode(placement_tags, bl); /* tags of allowed placement rules */
}
if (struct_v >= 14) {
decode(quota.bucket_quota, bl);
}
if (struct_v >= 15) {
decode(temp_url_keys, bl);
}
if (struct_v >= 16) {
decode(quota.user_quota, bl);
}
if (struct_v >= 17) {
decode(user_id.tenant, bl);
} else {
user_id.tenant.clear();
}
if (struct_v >= 18) {
decode(admin, bl);
}
if (struct_v >= 19) {
decode(type, bl);
}
if (struct_v >= 20) {
decode(mfa_ids, bl);
}
if (struct_v >= 21) {
std::string assumed_role_arn; // removed
decode(assumed_role_arn, bl);
}
if (struct_v >= 22) {
decode(user_id.ns, bl);
} else {
user_id.ns.clear();
}
DECODE_FINISH(bl);
}
void dump(Formatter *f) const;
static void generate_test_instances(std::list<RGWUserInfo*>& o);
void decode_json(JSONObj *obj);
};
WRITE_CLASS_ENCODER(RGWUserInfo)
/// `RGWObjVersionTracker`
/// ======================
///
/// What and why is this?
/// ---------------------
///
/// This is a wrapper around `cls_version` functionality. If two RGWs
/// (or two non-synchronized threads in the same RGW) are accessing
/// the same object, they may race and overwrite each other's work.
///
/// This class solves this issue by tracking and recording an object's
/// version in the extended attributes. Operations are failed with
/// ECANCELED if the version is not what we expect.
///
/// How to Use It
/// -------------
///
/// When preparing a read operation, call `prepare_op_for_read`.
/// For a write, call `prepare_op_for_write` when preparing the
/// operation, and `apply_write` after it succeeds.
///
/// Adhere to the following guidelines:
///
/// - Each RGWObjVersionTracker should be used with only one object.
///
/// - If you receive `ECANCELED`, throw away whatever you were doing
/// based on the content of the versioned object, re-read, and
/// restart as appropriate.
///
/// - If one code path uses RGWObjVersionTracker, then they all
/// should. In a situation where a writer should unconditionally
/// overwrite an object, call `generate_new_write_ver` on a default
/// constructed `RGWObjVersionTracker`.
///
/// - If we have a version from a previous read, we will check against
/// it and fail the read if it doesn't match. Thus, if we want to
/// re-read a new version of the object, call `clear()` on the
/// `RGWObjVersionTracker`.
///
/// - This type is not thread-safe. Every thread must have its own
/// instance.
///
struct RGWObjVersionTracker {
obj_version read_version; //< The version read from an object. If
// set, this value is used to check the
// stored version.
obj_version write_version; //< Set the object to this version on
// write, if set.
/// Pointer to the read version.
obj_version* version_for_read() {
return &read_version;
}
/// If we have a write version, return a pointer to it. Otherwise
/// return null. This is used in `prepare_op_for_write` to treat the
/// `write_version` as effectively an `option` type.
obj_version* version_for_write() {
if (write_version.ver == 0)
return nullptr;
return &write_version;
}
/// If read_version is non-empty, return a pointer to it, otherwise
/// null. This is used internally by `prepare_op_for_read` and
/// `prepare_op_for_write` to treat the `read_version` as
/// effectively an `option` type.
obj_version* version_for_check() {
if (read_version.ver == 0)
return nullptr;
return &read_version;
}
/// This function is to be called on any read operation. If we have
/// a non-empty `read_version`, assert on the OSD that the object
/// has the same version. Also reads the version into `read_version`.
///
/// This function is defined in `rgw_rados.cc` rather than `rgw_common.cc`.
void prepare_op_for_read(librados::ObjectReadOperation* op);
/// This function is to be called on any write operation. If we have
/// a non-empty read operation, assert on the OSD that the object
/// has the same version. If we have a non-empty `write_version`,
/// set the object to it. Otherwise increment the version on the OSD.
///
/// This function is defined in `rgw_rados.cc` rather than
/// `rgw_common.cc`.
void prepare_op_for_write(librados::ObjectWriteOperation* op);
/// This function is to be called after the completion of any write
/// operation on which `prepare_op_for_write` was called. If we did
/// not set the write version explicitly, it increments
/// `read_version`. If we did, it sets `read_version` to
/// `write_version`. In either case, it clears `write_version`.
///
/// RADOS write operations, at least those not using the relatively
/// new RETURNVEC flag, cannot return more information than an error
/// code. Thus, write operations can't simply fill in the read
/// version the way read operations can, so prepare_op_for_write`
/// instructs the OSD to increment the object as stored in RADOS and
/// `apply_write` increments our `read_version` in RAM.
///
/// This function is defined in `rgw_rados.cc` rather than
/// `rgw_common.cc`.
void apply_write();
/// Clear `read_version` and `write_version`, making the instance
/// identical to a default-constructed instance.
void clear() {
read_version = obj_version();
write_version = obj_version();
}
/// Set `write_version` to a new, unique version.
///
/// An `obj_version` contains an opaque, random tag and a
/// sequence. If the tags of two `obj_version`s don't match, the
/// versions are unordered and unequal. This function creates a
/// version with a new tag, ensuring that any other process
/// operating on the object will receive `ECANCELED` and will know
/// to re-read the object and restart whatever it was doing.
void generate_new_write_ver(CephContext* cct);
};
inline std::ostream& operator<<(std::ostream& out, const obj_version &v)
{
out << v.tag << ":" << v.ver;
return out;
}
inline std::ostream& operator<<(std::ostream& out, const RGWObjVersionTracker &ot)
{
out << "{r=" << ot.read_version << ",w=" << ot.write_version << "}";
return out;
}
enum RGWBucketFlags {
BUCKET_SUSPENDED = 0x1,
BUCKET_VERSIONED = 0x2,
BUCKET_VERSIONS_SUSPENDED = 0x4,
BUCKET_DATASYNC_DISABLED = 0X8,
BUCKET_MFA_ENABLED = 0X10,
BUCKET_OBJ_LOCK_ENABLED = 0X20,
};
class RGWSI_Zone;
struct RGWBucketInfo {
rgw_bucket bucket;
rgw_user owner;
uint32_t flags{0};
std::string zonegroup;
ceph::real_time creation_time;
rgw_placement_rule placement_rule;
bool has_instance_obj{false};
RGWObjVersionTracker objv_tracker; /* we don't need to serialize this, for runtime tracking */
RGWQuotaInfo quota;
// layout of bucket index objects
rgw::BucketLayout layout;
// Represents the shard number for blind bucket.
const static uint32_t NUM_SHARDS_BLIND_BUCKET;
bool requester_pays{false};
bool has_website{false};
RGWBucketWebsiteConf website_conf;
bool swift_versioning{false};
std::string swift_ver_location;
std::map<std::string, uint32_t> mdsearch_config;
// resharding
cls_rgw_reshard_status reshard_status{cls_rgw_reshard_status::NOT_RESHARDING};
std::string new_bucket_instance_id;
RGWObjectLock obj_lock;
std::optional<rgw_sync_policy_info> sync_policy;
void encode(bufferlist& bl) const;
void decode(bufferlist::const_iterator& bl);
void dump(Formatter *f) const;
static void generate_test_instances(std::list<RGWBucketInfo*>& o);
void decode_json(JSONObj *obj);
bool versioned() const { return (flags & BUCKET_VERSIONED) != 0; }
int versioning_status() const { return flags & (BUCKET_VERSIONED | BUCKET_VERSIONS_SUSPENDED | BUCKET_MFA_ENABLED); }
bool versioning_enabled() const { return (versioning_status() & (BUCKET_VERSIONED | BUCKET_VERSIONS_SUSPENDED)) == BUCKET_VERSIONED; }
bool mfa_enabled() const { return (versioning_status() & BUCKET_MFA_ENABLED) != 0; }
bool datasync_flag_enabled() const { return (flags & BUCKET_DATASYNC_DISABLED) == 0; }
bool obj_lock_enabled() const { return (flags & BUCKET_OBJ_LOCK_ENABLED) != 0; }
bool has_swift_versioning() const {
/* A bucket may be versioned through one mechanism only. */
return swift_versioning && !versioned();
}
void set_sync_policy(rgw_sync_policy_info&& policy);
bool empty_sync_policy() const;
bool is_indexless() const {
return rgw::is_layout_indexless(layout.current_index);
}
const rgw::bucket_index_layout_generation& get_current_index() const {
return layout.current_index;
}
rgw::bucket_index_layout_generation& get_current_index() {
return layout.current_index;
}
RGWBucketInfo();
~RGWBucketInfo();
};
WRITE_CLASS_ENCODER(RGWBucketInfo)
struct RGWBucketEntryPoint
{
rgw_bucket bucket;
rgw_user owner;
ceph::real_time creation_time;
bool linked;
bool has_bucket_info;
RGWBucketInfo old_bucket_info;
RGWBucketEntryPoint() : linked(false), has_bucket_info(false) {}
void encode(bufferlist& bl) const {
ENCODE_START(10, 8, bl);
encode(bucket, bl);
encode(owner.id, bl);
encode(linked, bl);
uint64_t ctime = (uint64_t)real_clock::to_time_t(creation_time);
encode(ctime, bl);
encode(owner, bl);
encode(creation_time, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& bl) {
auto orig_iter = bl;
DECODE_START_LEGACY_COMPAT_LEN_32(10, 4, 4, bl);
if (struct_v < 8) {
/* ouch, old entry, contains the bucket info itself */
old_bucket_info.decode(orig_iter);
has_bucket_info = true;
return;
}
has_bucket_info = false;
decode(bucket, bl);
decode(owner.id, bl);
decode(linked, bl);
uint64_t ctime;
decode(ctime, bl);
if (struct_v < 10) {
creation_time = real_clock::from_time_t((time_t)ctime);
}
if (struct_v >= 9) {
decode(owner, bl);
}
if (struct_v >= 10) {
decode(creation_time, bl);
}
DECODE_FINISH(bl);
}
void dump(Formatter *f) const;
void decode_json(JSONObj *obj);
static void generate_test_instances(std::list<RGWBucketEntryPoint*>& o);
};
WRITE_CLASS_ENCODER(RGWBucketEntryPoint)
struct RGWStorageStats
{
RGWObjCategory category;
uint64_t size;
uint64_t size_rounded;
uint64_t num_objects;
uint64_t size_utilized{0}; //< size after compression, encryption
bool dump_utilized; // whether dump should include utilized values
RGWStorageStats(bool _dump_utilized=true)
: category(RGWObjCategory::None),
size(0),
size_rounded(0),
num_objects(0),
dump_utilized(_dump_utilized)
{}
void dump(Formatter *f) const;
}; // RGWStorageStats
class RGWEnv;
/* Namespaced forward declarations. */
namespace rgw {
namespace auth {
namespace s3 {
class AWSBrowserUploadAbstractor;
class STSEngine;
}
class Completer;
}
namespace io {
class BasicClient;
}
}
using meta_map_t = boost::container::flat_map <std::string, std::string>;
struct req_info {
const RGWEnv *env;
RGWHTTPArgs args;
meta_map_t x_meta_map;
meta_map_t crypt_attribute_map;
std::string host;
const char *method;
std::string script_uri;
std::string request_uri;
std::string request_uri_aws4;
std::string effective_uri;
std::string request_params;
std::string domain;
std::string storage_class;
req_info(CephContext *cct, const RGWEnv *env);
void rebuild_from(req_info& src);
void init_meta_info(const DoutPrefixProvider *dpp, bool *found_bad_meta);
};
struct req_init_state {
/* Keeps [[tenant]:]bucket until we parse the token. */
std::string url_bucket;
std::string src_bucket;
};
#include "rgw_auth.h"
class RGWObjectCtx;
/** Store all the state necessary to complete and respond to an HTTP request*/
struct req_state : DoutPrefixProvider {
CephContext *cct;
const RGWProcessEnv& penv;
rgw::io::BasicClient *cio{nullptr};
http_op op{OP_UNKNOWN};
RGWOpType op_type{};
std::shared_ptr<RateLimiter> ratelimit_data;
RGWRateLimitInfo user_ratelimit;
RGWRateLimitInfo bucket_ratelimit;
std::string ratelimit_bucket_marker;
std::string ratelimit_user_name;
bool content_started{false};
RGWFormat format{RGWFormat::PLAIN};
ceph::Formatter *formatter{nullptr};
std::string decoded_uri;
std::string relative_uri;
const char *length{nullptr};
int64_t content_length{0};
std::map<std::string, std::string> generic_attrs;
rgw_err err;
bool expect_cont{false};
uint64_t obj_size{0};
bool enable_ops_log;
bool enable_usage_log;
uint8_t defer_to_bucket_acls;
uint32_t perm_mask{0};
/* Set once when url_bucket is parsed and not violated thereafter. */
std::string account_name;
std::string bucket_tenant;
std::string bucket_name;
/* bucket is only created in rgw_build_bucket_policies() and should never be
* overwritten */
std::unique_ptr<rgw::sal::Bucket> bucket;
std::unique_ptr<rgw::sal::Object> object;
std::string src_tenant_name;
std::string src_bucket_name;
std::unique_ptr<rgw::sal::Object> src_object;
ACLOwner bucket_owner;
ACLOwner owner;
std::string zonegroup_name;
std::string zonegroup_endpoint;
std::string bucket_instance_id;
int bucket_instance_shard_id{-1};
std::string redirect_zone_endpoint;
std::string redirect;
real_time bucket_mtime;
std::map<std::string, ceph::bufferlist> bucket_attrs;
bool bucket_exists{false};
rgw_placement_rule dest_placement;
bool has_bad_meta{false};
std::unique_ptr<rgw::sal::User> user;
struct {
/* TODO(rzarzynski): switch out to the static_ptr for both members. */
/* Object having the knowledge about an authenticated identity and allowing
* to apply it during the authorization phase (verify_permission() methods
* of a given RGWOp). Thus, it bounds authentication and authorization steps
* through a well-defined interface. For more details, see rgw_auth.h. */
std::unique_ptr<rgw::auth::Identity> identity;
std::shared_ptr<rgw::auth::Completer> completer;
/* A container for credentials of the S3's browser upload. It's necessary
* because: 1) the ::authenticate() method of auth engines and strategies
* take req_state only; 2) auth strategies live much longer than RGWOps -
* there is no way to pass additional data dependencies through ctors. */
class {
/* Writer. */
friend class RGWPostObj_ObjStore_S3;
/* Reader. */
friend class rgw::auth::s3::AWSBrowserUploadAbstractor;
friend class rgw::auth::s3::STSEngine;
std::string access_key;
std::string signature;
std::string x_amz_algorithm;
std::string x_amz_credential;
std::string x_amz_date;
std::string x_amz_security_token;
ceph::bufferlist encoded_policy;
} s3_postobj_creds;
} auth;
std::unique_ptr<RGWAccessControlPolicy> user_acl;
std::unique_ptr<RGWAccessControlPolicy> bucket_acl;
std::unique_ptr<RGWAccessControlPolicy> object_acl;
rgw::IAM::Environment env;
boost::optional<rgw::IAM::Policy> iam_policy;
boost::optional<PublicAccessBlockConfiguration> bucket_access_conf;
std::vector<rgw::IAM::Policy> iam_user_policies;
/* Is the request made by an user marked as a system one?
* Being system user means we also have the admin status. */
bool system_request{false};
std::string canned_acl;
bool has_acl_header{false};
bool local_source{false}; /* source is local */
int prot_flags{0};
/* Content-Disposition override for TempURL of Swift API. */
struct {
std::string override;
std::string fallback;
} content_disp;
std::string host_id;
req_info info;
req_init_state init_state;
using Clock = ceph::coarse_real_clock;
Clock::time_point time;
Clock::duration time_elapsed() const { return Clock::now() - time; }
std::string dialect;
std::string req_id;
std::string trans_id;
uint64_t id;
RGWObjTags tagset;
bool mfa_verified{false};
/// optional coroutine context
optional_yield yield{null_yield};
//token claims from STS token for ops log (can be used for Keystone token also)
std::vector<std::string> token_claims;
std::vector<rgw::IAM::Policy> session_policies;
jspan trace;
bool trace_enabled = false;
//Principal tags that come in as part of AssumeRoleWithWebIdentity
std::vector<std::pair<std::string, std::string>> principal_tags;
req_state(CephContext* _cct, const RGWProcessEnv& penv, RGWEnv* e, uint64_t id);
~req_state();
void set_user(std::unique_ptr<rgw::sal::User>& u) { user.swap(u); }
bool is_err() const { return err.is_err(); }
// implements DoutPrefixProvider
std::ostream& gen_prefix(std::ostream& out) const override;
CephContext* get_cct() const override { return cct; }
unsigned get_subsys() const override { return ceph_subsys_rgw; }
};
void set_req_state_err(req_state*, int);
void set_req_state_err(req_state*, int, const std::string&);
void set_req_state_err(struct rgw_err&, int, const int);
void dump(req_state*);
/** Store basic data on bucket */
struct RGWBucketEnt {
rgw_bucket bucket;
size_t size;
size_t size_rounded;
ceph::real_time creation_time;
uint64_t count;
/* The placement_rule is necessary to calculate per-storage-policy statics
* of the Swift API. Although the info available in RGWBucketInfo, we need
* to duplicate it here to not affect the performance of buckets listing. */
rgw_placement_rule placement_rule;
RGWBucketEnt()
: size(0),
size_rounded(0),
count(0) {
}
RGWBucketEnt(const RGWBucketEnt&) = default;
RGWBucketEnt(RGWBucketEnt&&) = default;
explicit RGWBucketEnt(const rgw_user& u, cls_user_bucket_entry&& e)
: bucket(u, std::move(e.bucket)),
size(e.size),
size_rounded(e.size_rounded),
creation_time(e.creation_time),
count(e.count) {
}
RGWBucketEnt& operator=(const RGWBucketEnt&) = default;
void convert(cls_user_bucket_entry *b) const {
bucket.convert(&b->bucket);
b->size = size;
b->size_rounded = size_rounded;
b->creation_time = creation_time;
b->count = count;
}
void encode(bufferlist& bl) const {
ENCODE_START(7, 5, bl);
uint64_t s = size;
// issue tracked here: https://tracker.ceph.com/issues/61160
// coverity[store_truncates_time_t:SUPPRESS]
__u32 mt = ceph::real_clock::to_time_t(creation_time);
std::string empty_str; // originally had the bucket name here, but we encode bucket later
encode(empty_str, bl);
encode(s, bl);
encode(mt, bl);
encode(count, bl);
encode(bucket, bl);
s = size_rounded;
encode(s, bl);
encode(creation_time, bl);
encode(placement_rule, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& bl) {
DECODE_START_LEGACY_COMPAT_LEN(7, 5, 5, bl);
__u32 mt;
uint64_t s;
std::string empty_str; // backward compatibility
decode(empty_str, bl);
decode(s, bl);
decode(mt, bl);
size = s;
if (struct_v < 6) {
creation_time = ceph::real_clock::from_time_t(mt);
}
if (struct_v >= 2)
decode(count, bl);
if (struct_v >= 3)
decode(bucket, bl);
if (struct_v >= 4)
decode(s, bl);
size_rounded = s;
if (struct_v >= 6)
decode(creation_time, bl);
if (struct_v >= 7)
decode(placement_rule, bl);
DECODE_FINISH(bl);
}
void dump(Formatter *f) const;
static void generate_test_instances(std::list<RGWBucketEnt*>& o);
};
WRITE_CLASS_ENCODER(RGWBucketEnt)
struct rgw_cache_entry_info {
std::string cache_locator;
uint64_t gen;
rgw_cache_entry_info() : gen(0) {}
};
inline std::ostream& operator<<(std::ostream& out, const rgw_obj &o) {
return out << o.bucket.name << ":" << o.get_oid();
}
struct multipart_upload_info
{
rgw_placement_rule dest_placement;
void encode(bufferlist& bl) const {
ENCODE_START(1, 1, bl);
encode(dest_placement, bl);
ENCODE_FINISH(bl);
}
void decode(bufferlist::const_iterator& bl) {
DECODE_START(1, bl);
decode(dest_placement, bl);
DECODE_FINISH(bl);
}
};
WRITE_CLASS_ENCODER(multipart_upload_info)
static inline void buf_to_hex(const unsigned char* const buf,
const size_t len,
char* const str)
{
str[0] = '\0';
for (size_t i = 0; i < len; i++) {
::sprintf(&str[i*2], "%02x", static_cast<int>(buf[i]));
}
}
template<size_t N> static inline std::array<char, N * 2 + 1>
buf_to_hex(const std::array<unsigned char, N>& buf)
{
static_assert(N > 0, "The input array must be at least one element long");
std::array<char, N * 2 + 1> hex_dest;
buf_to_hex(buf.data(), N, hex_dest.data());
return hex_dest;
}
static inline int hexdigit(char c)
{
if (c >= '0' && c <= '9')
return (c - '0');
c = toupper(c);
if (c >= 'A' && c <= 'F')
return c - 'A' + 0xa;
return -EINVAL;
}
static inline int hex_to_buf(const char *hex, char *buf, int len)
{
int i = 0;
const char *p = hex;
while (*p) {
if (i >= len)
return -EINVAL;
buf[i] = 0;
int d = hexdigit(*p);
if (d < 0)
return d;
buf[i] = d << 4;
p++;
if (!*p)
return -EINVAL;
d = hexdigit(*p);
if (d < 0)
return d;
buf[i] += d;
i++;
p++;
}
return i;
}
static inline int rgw_str_to_bool(const char *s, int def_val)
{
if (!s)
return def_val;
return (strcasecmp(s, "true") == 0 ||
strcasecmp(s, "on") == 0 ||
strcasecmp(s, "yes") == 0 ||
strcasecmp(s, "1") == 0);
}
static inline void append_rand_alpha(CephContext *cct, const std::string& src, std::string& dest, int len)
{
dest = src;
char buf[len + 1];
gen_rand_alphanumeric(cct, buf, len);
dest.append("_");
dest.append(buf);
}
static inline uint64_t rgw_rounded_kb(uint64_t bytes)
{
return (bytes + 1023) / 1024;
}
static inline uint64_t rgw_rounded_objsize(uint64_t bytes)
{
return ((bytes + 4095) & ~4095);
}
static inline uint64_t rgw_rounded_objsize_kb(uint64_t bytes)
{
return ((bytes + 4095) & ~4095) / 1024;
}
/* implement combining step, S3 header canonicalization; k is a
* valid header and in lc form */
void rgw_add_amz_meta_header(
meta_map_t& x_meta_map,
const std::string& k,
const std::string& v);
enum rgw_set_action_if_set {
DISCARD=0, OVERWRITE, APPEND
};
bool rgw_set_amz_meta_header(
meta_map_t& x_meta_map,
const std::string& k,
const std::string& v, rgw_set_action_if_set f);
extern std::string rgw_string_unquote(const std::string& s);
extern void parse_csv_string(const std::string& ival, std::vector<std::string>& ovals);
extern int parse_key_value(std::string& in_str, std::string& key, std::string& val);
extern int parse_key_value(std::string& in_str, const char *delim, std::string& key, std::string& val);
extern boost::optional<std::pair<std::string_view,std::string_view>>
parse_key_value(const std::string_view& in_str,
const std::string_view& delim);
extern boost::optional<std::pair<std::string_view,std::string_view>>
parse_key_value(const std::string_view& in_str);
struct rgw_name_to_flag {
const char *type_name;
uint32_t flag;
};
/** time parsing */
extern int parse_time(const char *time_str, real_time *time);
extern bool parse_rfc2616(const char *s, struct tm *t);
extern bool parse_iso8601(const char *s, struct tm *t, uint32_t *pns = NULL, bool extended_format = true);
extern std::string rgw_trim_whitespace(const std::string& src);
extern std::string_view rgw_trim_whitespace(const std::string_view& src);
extern std::string rgw_trim_quotes(const std::string& val);
extern void rgw_to_iso8601(const real_time& t, char *dest, int buf_size);
extern void rgw_to_iso8601(const real_time& t, std::string *dest);
extern std::string rgw_to_asctime(const utime_t& t);
struct perm_state_base {
CephContext *cct;
const rgw::IAM::Environment& env;
rgw::auth::Identity *identity;
const RGWBucketInfo bucket_info;
int perm_mask;
bool defer_to_bucket_acls;
boost::optional<PublicAccessBlockConfiguration> bucket_access_conf;
perm_state_base(CephContext *_cct,
const rgw::IAM::Environment& _env,
rgw::auth::Identity *_identity,
const RGWBucketInfo& _bucket_info,
int _perm_mask,
bool _defer_to_bucket_acls,
boost::optional<PublicAccessBlockConfiguration> _bucket_acess_conf = boost::none) :
cct(_cct),
env(_env),
identity(_identity),
bucket_info(_bucket_info),
perm_mask(_perm_mask),
defer_to_bucket_acls(_defer_to_bucket_acls),
bucket_access_conf(_bucket_acess_conf)
{}
virtual ~perm_state_base() {}
virtual const char *get_referer() const = 0;
virtual std::optional<bool> get_request_payer() const = 0; /*
* empty state means that request_payer param was not passed in
*/
};
struct perm_state : public perm_state_base {
const char *referer;
bool request_payer;
perm_state(CephContext *_cct,
const rgw::IAM::Environment& _env,
rgw::auth::Identity *_identity,
const RGWBucketInfo& _bucket_info,
int _perm_mask,
bool _defer_to_bucket_acls,
const char *_referer,
bool _request_payer) : perm_state_base(_cct,
_env,
_identity,
_bucket_info,
_perm_mask,
_defer_to_bucket_acls),
referer(_referer),
request_payer(_request_payer) {}
const char *get_referer() const override {
return referer;
}
std::optional<bool> get_request_payer() const override {
return request_payer;
}
};
/** Check if the req_state's user has the necessary permissions
* to do the requested action */
bool verify_bucket_permission_no_policy(
const DoutPrefixProvider* dpp,
struct perm_state_base * const s,
RGWAccessControlPolicy * const user_acl,
RGWAccessControlPolicy * const bucket_acl,
const int perm);
bool verify_user_permission_no_policy(const DoutPrefixProvider* dpp,
struct perm_state_base * const s,
RGWAccessControlPolicy * const user_acl,
const int perm);
bool verify_object_permission_no_policy(const DoutPrefixProvider* dpp,
struct perm_state_base * const s,
RGWAccessControlPolicy * const user_acl,
RGWAccessControlPolicy * const bucket_acl,
RGWAccessControlPolicy * const object_acl,
const int perm);
/** Check if the req_state's user has the necessary permissions
* to do the requested action */
rgw::IAM::Effect eval_identity_or_session_policies(const DoutPrefixProvider* dpp,
const std::vector<rgw::IAM::Policy>& user_policies,
const rgw::IAM::Environment& env,
const uint64_t op,
const rgw::ARN& arn);
bool verify_user_permission(const DoutPrefixProvider* dpp,
req_state * const s,
RGWAccessControlPolicy * const user_acl,
const std::vector<rgw::IAM::Policy>& user_policies,
const std::vector<rgw::IAM::Policy>& session_policies,
const rgw::ARN& res,
const uint64_t op,
bool mandatory_policy=true);
bool verify_user_permission_no_policy(const DoutPrefixProvider* dpp,
req_state * const s,
RGWAccessControlPolicy * const user_acl,
const int perm);
bool verify_user_permission(const DoutPrefixProvider* dpp,
req_state * const s,
const rgw::ARN& res,
const uint64_t op,
bool mandatory_policy=true);
bool verify_user_permission_no_policy(const DoutPrefixProvider* dpp,
req_state * const s,
int perm);
bool verify_bucket_permission(
const DoutPrefixProvider* dpp,
req_state * const s,
const rgw_bucket& bucket,
RGWAccessControlPolicy * const user_acl,
RGWAccessControlPolicy * const bucket_acl,
const boost::optional<rgw::IAM::Policy>& bucket_policy,
const std::vector<rgw::IAM::Policy>& identity_policies,
const std::vector<rgw::IAM::Policy>& session_policies,
const uint64_t op);
bool verify_bucket_permission(const DoutPrefixProvider* dpp, req_state * const s, const uint64_t op);
bool verify_bucket_permission_no_policy(
const DoutPrefixProvider* dpp,
req_state * const s,
RGWAccessControlPolicy * const user_acl,
RGWAccessControlPolicy * const bucket_acl,
const int perm);
bool verify_bucket_permission_no_policy(const DoutPrefixProvider* dpp,
req_state * const s,
const int perm);
int verify_bucket_owner_or_policy(req_state* const s,
const uint64_t op);
extern bool verify_object_permission(
const DoutPrefixProvider* dpp,
req_state * const s,
const rgw_obj& obj,
RGWAccessControlPolicy * const user_acl,
RGWAccessControlPolicy * const bucket_acl,
RGWAccessControlPolicy * const object_acl,
const boost::optional<rgw::IAM::Policy>& bucket_policy,
const std::vector<rgw::IAM::Policy>& identity_policies,
const std::vector<rgw::IAM::Policy>& session_policies,
const uint64_t op);
extern bool verify_object_permission(const DoutPrefixProvider* dpp, req_state *s, uint64_t op);
extern bool verify_object_permission_no_policy(
const DoutPrefixProvider* dpp,
req_state * const s,
RGWAccessControlPolicy * const user_acl,
RGWAccessControlPolicy * const bucket_acl,
RGWAccessControlPolicy * const object_acl,
int perm);
extern bool verify_object_permission_no_policy(const DoutPrefixProvider* dpp, req_state *s,
int perm);
extern int verify_object_lock(
const DoutPrefixProvider* dpp,
const rgw::sal::Attrs& attrs,
const bool bypass_perm,
const bool bypass_governance_mode);
/** Convert an input URL into a sane object name
* by converting %-escaped std::strings into characters, etc*/
extern void rgw_uri_escape_char(char c, std::string& dst);
extern std::string url_decode(const std::string_view& src_str,
bool in_query = false);
extern void url_encode(const std::string& src, std::string& dst,
bool encode_slash = true);
extern std::string url_encode(const std::string& src, bool encode_slash = true);
extern std::string url_remove_prefix(const std::string& url); // Removes hhtp, https and www from url
/* destination should be CEPH_CRYPTO_HMACSHA1_DIGESTSIZE bytes long */
extern void calc_hmac_sha1(const char *key, int key_len,
const char *msg, int msg_len, char *dest);
static inline sha1_digest_t
calc_hmac_sha1(const std::string_view& key, const std::string_view& msg) {
sha1_digest_t dest;
calc_hmac_sha1(key.data(), key.size(), msg.data(), msg.size(),
reinterpret_cast<char*>(dest.v));
return dest;
}
/* destination should be CEPH_CRYPTO_HMACSHA256_DIGESTSIZE bytes long */
extern void calc_hmac_sha256(const char *key, int key_len,
const char *msg, int msg_len,
char *dest);
static inline sha256_digest_t
calc_hmac_sha256(const char *key, const int key_len,
const char *msg, const int msg_len) {
sha256_digest_t dest;
calc_hmac_sha256(key, key_len, msg, msg_len,
reinterpret_cast<char*>(dest.v));
return dest;
}
static inline sha256_digest_t
calc_hmac_sha256(const std::string_view& key, const std::string_view& msg) {
sha256_digest_t dest;
calc_hmac_sha256(key.data(), key.size(),
msg.data(), msg.size(),
reinterpret_cast<char*>(dest.v));
return dest;
}
static inline sha256_digest_t
calc_hmac_sha256(const sha256_digest_t &key,
const std::string_view& msg) {
sha256_digest_t dest;
calc_hmac_sha256(reinterpret_cast<const char*>(key.v), sha256_digest_t::SIZE,
msg.data(), msg.size(),
reinterpret_cast<char*>(dest.v));
return dest;
}
static inline sha256_digest_t
calc_hmac_sha256(const std::vector<unsigned char>& key,
const std::string_view& msg) {
sha256_digest_t dest;
calc_hmac_sha256(reinterpret_cast<const char*>(key.data()), key.size(),
msg.data(), msg.size(),
reinterpret_cast<char*>(dest.v));
return dest;
}
template<size_t KeyLenN>
static inline sha256_digest_t
calc_hmac_sha256(const std::array<unsigned char, KeyLenN>& key,
const std::string_view& msg) {
sha256_digest_t dest;
calc_hmac_sha256(reinterpret_cast<const char*>(key.data()), key.size(),
msg.data(), msg.size(),
reinterpret_cast<char*>(dest.v));
return dest;
}
extern sha256_digest_t calc_hash_sha256(const std::string_view& msg);
extern ceph::crypto::SHA256* calc_hash_sha256_open_stream();
extern void calc_hash_sha256_update_stream(ceph::crypto::SHA256* hash,
const char* msg,
int len);
extern std::string calc_hash_sha256_close_stream(ceph::crypto::SHA256** phash);
extern std::string calc_hash_sha256_restart_stream(ceph::crypto::SHA256** phash);
extern int rgw_parse_op_type_list(const std::string& str, uint32_t *perm);
static constexpr uint32_t MATCH_POLICY_ACTION = 0x01;
static constexpr uint32_t MATCH_POLICY_RESOURCE = 0x02;
static constexpr uint32_t MATCH_POLICY_ARN = 0x04;
static constexpr uint32_t MATCH_POLICY_STRING = 0x08;
extern bool match_policy(std::string_view pattern, std::string_view input,
uint32_t flag);
extern std::string camelcase_dash_http_attr(const std::string& orig);
extern std::string lowercase_dash_http_attr(const std::string& orig);
void rgw_setup_saved_curl_handles();
void rgw_release_all_curl_handles();
static inline void rgw_escape_str(const std::string& s, char esc_char,
char special_char, std::string *dest)
{
const char *src = s.c_str();
char dest_buf[s.size() * 2 + 1];
char *destp = dest_buf;
for (size_t i = 0; i < s.size(); i++) {
char c = src[i];
if (c == esc_char || c == special_char) {
*destp++ = esc_char;
}
*destp++ = c;
}
*destp++ = '\0';
*dest = dest_buf;
}
static inline ssize_t rgw_unescape_str(const std::string& s, ssize_t ofs,
char esc_char, char special_char,
std::string *dest)
{
const char *src = s.c_str();
char dest_buf[s.size() + 1];
char *destp = dest_buf;
bool esc = false;
dest_buf[0] = '\0';
for (size_t i = ofs; i < s.size(); i++) {
char c = src[i];
if (!esc && c == esc_char) {
esc = true;
continue;
}
if (!esc && c == special_char) {
*destp = '\0';
*dest = dest_buf;
return (ssize_t)i + 1;
}
*destp++ = c;
esc = false;
}
*destp = '\0';
*dest = dest_buf;
return std::string::npos;
}
static inline std::string rgw_bl_str(ceph::buffer::list& raw)
{
size_t len = raw.length();
std::string s(raw.c_str(), len);
while (len && !s[len - 1]) {
--len;
s.resize(len);
}
return s;
}
template <typename T>
int decode_bl(bufferlist& bl, T& t)
{
auto iter = bl.cbegin();
try {
decode(t, iter);
} catch (buffer::error& err) {
return -EIO;
}
return 0;
}
extern int rgw_bucket_parse_bucket_instance(const std::string& bucket_instance, std::string *bucket_name, std::string *bucket_id, int *shard_id);
boost::intrusive_ptr<CephContext>
rgw_global_init(const std::map<std::string,std::string> *defaults,
std::vector < const char* >& args,
uint32_t module_type, code_environment_t code_env,
int flags);
| 59,215 | 31.095393 | 149 |
h
|
null |
ceph-main/src/rgw/rgw_compression.cc
|
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab ft=cpp
#include "rgw_compression.h"
#define dout_subsys ceph_subsys_rgw
using namespace std;
int rgw_compression_info_from_attr(const bufferlist& attr,
bool& need_decompress,
RGWCompressionInfo& cs_info)
{
auto bliter = attr.cbegin();
try {
decode(cs_info, bliter);
} catch (buffer::error& err) {
return -EIO;
}
if (cs_info.blocks.size() == 0) {
return -EIO;
}
if (cs_info.compression_type != "none")
need_decompress = true;
else
need_decompress = false;
return 0;
}
int rgw_compression_info_from_attrset(const map<string, bufferlist>& attrs,
bool& need_decompress,
RGWCompressionInfo& cs_info)
{
auto value = attrs.find(RGW_ATTR_COMPRESSION);
if (value == attrs.end()) {
need_decompress = false;
return 0;
}
return rgw_compression_info_from_attr(value->second, need_decompress, cs_info);
}
//------------RGWPutObj_Compress---------------
int RGWPutObj_Compress::process(bufferlist&& in, uint64_t logical_offset)
{
bufferlist out;
compressed_ofs = logical_offset;
if (in.length() > 0) {
// compression stuff
if ((logical_offset > 0 && compressed) || // if previous part was compressed
(logical_offset == 0)) { // or it's the first part
ldout(cct, 10) << "Compression for rgw is enabled, compress part " << in.length() << dendl;
int cr = compressor->compress(in, out, compressor_message);
if (cr < 0) {
if (logical_offset > 0) {
lderr(cct) << "Compression failed with exit code " << cr
<< " for next part, compression process failed" << dendl;
return -EIO;
}
compressed = false;
ldout(cct, 5) << "Compression failed with exit code " << cr
<< " for first part, storing uncompressed" << dendl;
out = std::move(in);
} else {
compressed = true;
compression_block newbl;
size_t bs = blocks.size();
newbl.old_ofs = logical_offset;
newbl.new_ofs = bs > 0 ? blocks[bs-1].len + blocks[bs-1].new_ofs : 0;
newbl.len = out.length();
blocks.push_back(newbl);
compressed_ofs = newbl.new_ofs;
}
} else {
compressed = false;
out = std::move(in);
}
// end of compression stuff
} else {
size_t bs = blocks.size();
compressed_ofs = bs > 0 ? blocks[bs-1].len + blocks[bs-1].new_ofs : logical_offset;
}
return Pipe::process(std::move(out), compressed_ofs);
}
//----------------RGWGetObj_Decompress---------------------
RGWGetObj_Decompress::RGWGetObj_Decompress(CephContext* cct_,
RGWCompressionInfo* cs_info_,
bool partial_content_,
RGWGetObj_Filter* next): RGWGetObj_Filter(next),
cct(cct_),
cs_info(cs_info_),
partial_content(partial_content_),
q_ofs(0),
q_len(0),
cur_ofs(0)
{
compressor = Compressor::create(cct, cs_info->compression_type);
if (!compressor.get())
lderr(cct) << "Cannot load compressor of type " << cs_info->compression_type << dendl;
}
int RGWGetObj_Decompress::handle_data(bufferlist& bl, off_t bl_ofs, off_t bl_len)
{
ldout(cct, 10) << "Compression for rgw is enabled, decompress part "
<< "bl_ofs=" << bl_ofs << ", bl_len=" << bl_len << dendl;
if (!compressor.get()) {
// if compressor isn't available - error, because cannot return decompressed data?
lderr(cct) << "Cannot load compressor of type " << cs_info->compression_type << dendl;
return -EIO;
}
bufferlist out_bl, in_bl, temp_in_bl;
bl.begin(bl_ofs).copy(bl_len, temp_in_bl);
bl_ofs = 0;
int r = 0;
if (waiting.length() != 0) {
in_bl.append(waiting);
in_bl.append(temp_in_bl);
waiting.clear();
} else {
in_bl = std::move(temp_in_bl);
}
bl_len = in_bl.length();
auto iter_in_bl = in_bl.cbegin();
while (first_block <= last_block) {
bufferlist tmp;
off_t ofs_in_bl = first_block->new_ofs - cur_ofs;
if (ofs_in_bl + (off_t)first_block->len > bl_len) {
// not complete block, put it to waiting
unsigned tail = bl_len - ofs_in_bl;
if (iter_in_bl.get_off() != ofs_in_bl) {
iter_in_bl.seek(ofs_in_bl);
}
iter_in_bl.copy(tail, waiting);
cur_ofs -= tail;
break;
}
if (iter_in_bl.get_off() != ofs_in_bl) {
iter_in_bl.seek(ofs_in_bl);
}
iter_in_bl.copy(first_block->len, tmp);
int cr = compressor->decompress(tmp, out_bl, cs_info->compressor_message);
if (cr < 0) {
lderr(cct) << "Decompression failed with exit code " << cr << dendl;
return cr;
}
++first_block;
while (out_bl.length() - q_ofs >=
static_cast<off_t>(cct->_conf->rgw_max_chunk_size)) {
off_t ch_len = std::min<off_t>(cct->_conf->rgw_max_chunk_size, q_len);
q_len -= ch_len;
r = next->handle_data(out_bl, q_ofs, ch_len);
if (r < 0) {
lsubdout(cct, rgw, 0) << "handle_data failed with exit code " << r << dendl;
return r;
}
out_bl.splice(0, q_ofs + ch_len);
q_ofs = 0;
}
}
cur_ofs += bl_len;
off_t ch_len = std::min<off_t>(out_bl.length() - q_ofs, q_len);
if (ch_len > 0) {
r = next->handle_data(out_bl, q_ofs, ch_len);
if (r < 0) {
lsubdout(cct, rgw, 0) << "handle_data failed with exit code " << r << dendl;
return r;
}
out_bl.splice(0, q_ofs + ch_len);
q_len -= ch_len;
q_ofs = 0;
}
return r;
}
int RGWGetObj_Decompress::fixup_range(off_t& ofs, off_t& end)
{
if (partial_content) {
// if user set range, we need to calculate it in decompressed data
first_block = cs_info->blocks.begin(); last_block = cs_info->blocks.begin();
if (cs_info->blocks.size() > 1) {
vector<compression_block>::iterator fb, lb;
// not bad to use auto for lambda, I think
auto cmp_u = [] (off_t ofs, const compression_block& e) { return (uint64_t)ofs < e.old_ofs; };
auto cmp_l = [] (const compression_block& e, off_t ofs) { return e.old_ofs <= (uint64_t)ofs; };
fb = upper_bound(cs_info->blocks.begin()+1,
cs_info->blocks.end(),
ofs,
cmp_u);
first_block = fb - 1;
lb = lower_bound(fb,
cs_info->blocks.end(),
end,
cmp_l);
last_block = lb - 1;
}
} else {
first_block = cs_info->blocks.begin(); last_block = cs_info->blocks.end() - 1;
}
q_ofs = ofs - first_block->old_ofs;
q_len = end + 1 - ofs;
ofs = first_block->new_ofs;
end = last_block->new_ofs + last_block->len - 1;
cur_ofs = ofs;
waiting.clear();
return next->fixup_range(ofs, end);
}
void compression_block::dump(Formatter *f) const
{
f->dump_unsigned("old_ofs", old_ofs);
f->dump_unsigned("new_ofs", new_ofs);
f->dump_unsigned("len", len);
}
void RGWCompressionInfo::dump(Formatter *f) const
{
f->dump_string("compression_type", compression_type);
f->dump_unsigned("orig_size", orig_size);
if (compressor_message) {
f->dump_int("compressor_message", *compressor_message);
}
::encode_json("blocks", blocks, f);
}
| 7,803 | 31.92827 | 101 |
cc
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.