patch
stringlengths
17
31.2k
y
int64
1
1
oldf
stringlengths
0
2.21M
idx
int64
1
1
id
int64
4.29k
68.4k
msg
stringlengths
8
843
proj
stringclasses
212 values
lang
stringclasses
9 values
@@ -853,6 +853,11 @@ class DynamicMap(HoloMap): unbounded_dims.append(str(kdim)) return unbounded_dims + @property + def current_key(self): + """Returns the current key value.""" + return getattr(self, '_current_key', None) + def _stream_parameters(self): return util.stream_parameters( self.streams, no_duplicates=not self.positional_stream_args
1
import itertools import types import inspect from numbers import Number from itertools import groupby from functools import partial from collections import defaultdict from contextlib import contextmanager from types import FunctionType import numpy as np import param from . import traversal, util from .accessors import Opts, Redim from .dimension import OrderedDict, Dimension, ViewableElement from .layout import Layout, AdjointLayout, NdLayout, Empty from .ndmapping import UniformNdMapping, NdMapping, item_check from .overlay import Overlay, CompositeOverlay, NdOverlay, Overlayable from .options import Store, StoreOptions from ..streams import Stream, Params, streams_list_from_dict class HoloMap(UniformNdMapping, Overlayable): """ A HoloMap is an n-dimensional mapping of viewable elements or overlays. Each item in a HoloMap has an tuple key defining the values along each of the declared key dimensions, defining the discretely sampled space of values. The visual representation of a HoloMap consists of the viewable objects inside the HoloMap which can be explored by varying one or more widgets mapping onto the key dimensions of the HoloMap. """ data_type = (ViewableElement, NdMapping, Layout) def __init__(self, initial_items=None, kdims=None, group=None, label=None, **params): super().__init__(initial_items, kdims, group, label, **params) @property def opts(self): return Opts(self, mode='holomap') def overlay(self, dimensions=None, **kwargs): """Group by supplied dimension(s) and overlay each group Groups data by supplied dimension(s) overlaying the groups along the dimension(s). Args: dimensions: Dimension(s) of dimensions to group by Returns: NdOverlay object(s) with supplied dimensions """ dimensions = self._valid_dimensions(dimensions) if len(dimensions) == self.ndims: with item_check(False): return NdOverlay(self, **kwargs).reindex(dimensions) else: dims = [d for d in self.kdims if d not in dimensions] return self.groupby(dims, group_type=NdOverlay, **kwargs) def grid(self, dimensions=None, **kwargs): """Group by supplied dimension(s) and lay out groups in grid Groups data by supplied dimension(s) laying the groups along the dimension(s) out in a GridSpace. Args: dimensions: Dimension/str or list Dimension or list of dimensions to group by Returns: GridSpace with supplied dimensions """ dimensions = self._valid_dimensions(dimensions) if len(dimensions) == self.ndims: with item_check(False): return GridSpace(self, **kwargs).reindex(dimensions) return self.groupby(dimensions, container_type=GridSpace, **kwargs) def layout(self, dimensions=None, **kwargs): """Group by supplied dimension(s) and lay out groups Groups data by supplied dimension(s) laying the groups along the dimension(s) out in a NdLayout. Args: dimensions: Dimension(s) to group by Returns: NdLayout with supplied dimensions """ dimensions = self._valid_dimensions(dimensions) if len(dimensions) == self.ndims: with item_check(False): return NdLayout(self, **kwargs).reindex(dimensions) return self.groupby(dimensions, container_type=NdLayout, **kwargs) def options(self, *args, **kwargs): """Applies simplified option definition returning a new object Applies options defined in a flat format to the objects returned by the DynamicMap. If the options are to be set directly on the objects in the HoloMap a simple format may be used, e.g.: obj.options(cmap='viridis', show_title=False) If the object is nested the options must be qualified using a type[.group][.label] specification, e.g.: obj.options('Image', cmap='viridis', show_title=False) or using: obj.options({'Image': dict(cmap='viridis', show_title=False)}) Args: *args: Sets of options to apply to object Supports a number of formats including lists of Options objects, a type[.group][.label] followed by a set of keyword options to apply and a dictionary indexed by type[.group][.label] specs. backend (optional): Backend to apply options to Defaults to current selected backend clone (bool, optional): Whether to clone object Options can be applied inplace with clone=False **kwargs: Keywords of options Set of options to apply to the object Returns: Returns the cloned object with the options applied """ data = OrderedDict([(k, v.options(*args, **kwargs)) for k, v in self.data.items()]) return self.clone(data) def _split_overlays(self): "Splits overlays inside the HoloMap into list of HoloMaps" if not issubclass(self.type, CompositeOverlay): return None, self.clone() item_maps = OrderedDict() for k, overlay in self.data.items(): for key, el in overlay.items(): if key not in item_maps: item_maps[key] = [(k, el)] else: item_maps[key].append((k, el)) maps, keys = [], [] for k, layermap in item_maps.items(): maps.append(self.clone(layermap)) keys.append(k) return keys, maps def _dimension_keys(self): """ Helper for __mul__ that returns the list of keys together with the dimension labels. """ return [tuple(zip([d.name for d in self.kdims], [k] if self.ndims == 1 else k)) for k in self.keys()] def _dynamic_mul(self, dimensions, other, keys): """ Implements dynamic version of overlaying operation overlaying DynamicMaps and HoloMaps where the key dimensions of one is a strict superset of the other. """ # If either is a HoloMap compute Dimension values if not isinstance(self, DynamicMap) or not isinstance(other, DynamicMap): keys = sorted((d, v) for k in keys for d, v in k) grouped = dict([(g, [v for _, v in group]) for g, group in groupby(keys, lambda x: x[0])]) dimensions = [d.clone(values=grouped[d.name]) for d in dimensions] map_obj = None # Combine streams map_obj = self if isinstance(self, DynamicMap) else other if isinstance(self, DynamicMap) and isinstance(other, DynamicMap): self_streams = util.dimensioned_streams(self) other_streams = util.dimensioned_streams(other) streams = list(util.unique_iterator(self_streams+other_streams)) else: streams = map_obj.streams def dynamic_mul(*key, **kwargs): key_map = {d.name: k for d, k in zip(dimensions, key)} layers = [] try: self_el = self.select(HoloMap, **key_map) if self.kdims else self[()] layers.append(self_el) except KeyError: pass try: other_el = other.select(HoloMap, **key_map) if other.kdims else other[()] layers.append(other_el) except KeyError: pass return Overlay(layers) callback = Callable(dynamic_mul, inputs=[self, other]) callback._is_overlay = True if map_obj: return map_obj.clone(callback=callback, shared_data=False, kdims=dimensions, streams=streams) else: return DynamicMap(callback=callback, kdims=dimensions, streams=streams) def __mul__(self, other, reverse=False): """Overlays items in the object with another object The mul (*) operator implements overlaying of different objects. This method tries to intelligently overlay mappings with differing keys. If the UniformNdMapping is mulled with a simple ViewableElement each element in the UniformNdMapping is overlaid with the ViewableElement. If the element the UniformNdMapping is mulled with is another UniformNdMapping it will try to match up the dimensions, making sure that items with completely different dimensions aren't overlaid. """ if isinstance(other, HoloMap): self_set = {d.name for d in self.kdims} other_set = {d.name for d in other.kdims} # Determine which is the subset, to generate list of keys and # dimension labels for the new view self_in_other = self_set.issubset(other_set) other_in_self = other_set.issubset(self_set) dims = [other.kdims, self.kdims] if self_in_other else [self.kdims, other.kdims] dimensions = util.merge_dimensions(dims) if self_in_other and other_in_self: # superset of each other keys = self._dimension_keys() + other._dimension_keys() super_keys = util.unique_iterator(keys) elif self_in_other: # self is superset dimensions = other.kdims super_keys = other._dimension_keys() elif other_in_self: # self is superset super_keys = self._dimension_keys() else: # neither is superset raise Exception('One set of keys needs to be a strict subset of the other.') if isinstance(self, DynamicMap) or isinstance(other, DynamicMap): return self._dynamic_mul(dimensions, other, super_keys) items = [] for dim_keys in super_keys: # Generate keys for both subset and superset and sort them by the dimension index. self_key = tuple(k for p, k in sorted( [(self.get_dimension_index(dim), v) for dim, v in dim_keys if dim in self.kdims])) other_key = tuple(k for p, k in sorted( [(other.get_dimension_index(dim), v) for dim, v in dim_keys if dim in other.kdims])) new_key = self_key if other_in_self else other_key # Append SheetOverlay of combined items if (self_key in self) and (other_key in other): if reverse: value = other[other_key] * self[self_key] else: value = self[self_key] * other[other_key] items.append((new_key, value)) elif self_key in self: items.append((new_key, Overlay([self[self_key]]))) else: items.append((new_key, Overlay([other[other_key]]))) return self.clone(items, kdims=dimensions, label=self._label, group=self._group) elif isinstance(other, self.data_type) and not isinstance(other, Layout): if isinstance(self, DynamicMap): def dynamic_mul(*args, **kwargs): element = self[args] if reverse: return other * element else: return element * other callback = Callable(dynamic_mul, inputs=[self, other]) callback._is_overlay = True return self.clone(shared_data=False, callback=callback, streams=util.dimensioned_streams(self)) items = [(k, other * v) if reverse else (k, v * other) for (k, v) in self.data.items()] return self.clone(items, label=self._label, group=self._group) else: return NotImplemented def __add__(self, obj): "Composes HoloMap with other object into a Layout" return Layout([self, obj]) def __lshift__(self, other): "Adjoin another object to this one returning an AdjointLayout" if isinstance(other, (ViewableElement, UniformNdMapping, Empty)): return AdjointLayout([self, other]) elif isinstance(other, AdjointLayout): return AdjointLayout(other.data+[self]) else: raise TypeError('Cannot append {0} to a AdjointLayout'.format(type(other).__name__)) def collate(self, merge_type=None, drop=[], drop_constant=False): """Collate allows reordering nested containers Collation allows collapsing nested mapping types by merging their dimensions. In simple terms in merges nested containers into a single merged type. In the simple case a HoloMap containing other HoloMaps can easily be joined in this way. However collation is particularly useful when the objects being joined are deeply nested, e.g. you want to join multiple Layouts recorded at different times, collation will return one Layout containing HoloMaps indexed by Time. Changing the merge_type will allow merging the outer Dimension into any other UniformNdMapping type. Args: merge_type: Type of the object to merge with drop: List of dimensions to drop drop_constant: Drop constant dimensions automatically Returns: Collated Layout or HoloMap """ from .element import Collator merge_type=merge_type if merge_type else self.__class__ return Collator(self, merge_type=merge_type, drop=drop, drop_constant=drop_constant)() def decollate(self): """Packs HoloMap of DynamicMaps into a single DynamicMap that returns an HoloMap Decollation allows packing a HoloMap of DynamicMaps into a single DynamicMap that returns an HoloMap of simple (non-dynamic) elements. All nested streams are lifted to the resulting DynamicMap, and are available in the `streams` property. The `callback` property of the resulting DynamicMap is a pure, stateless function of the stream values. To avoid stream parameter name conflicts, the resulting DynamicMap is configured with positional_stream_args=True, and the callback function accepts stream values as positional dict arguments. Returns: DynamicMap that returns an HoloMap """ from .decollate import decollate return decollate(self) def relabel(self, label=None, group=None, depth=1): """Clone object and apply new group and/or label. Applies relabeling to children up to the supplied depth. Args: label (str, optional): New label to apply to returned object group (str, optional): New group to apply to returned object depth (int, optional): Depth to which relabel will be applied If applied to container allows applying relabeling to contained objects up to the specified depth Returns: Returns relabelled object """ return super().relabel(label=label, group=group, depth=depth) def hist(self, dimension=None, num_bins=20, bin_range=None, adjoin=True, individually=True, **kwargs): """Computes and adjoins histogram along specified dimension(s). Defaults to first value dimension if present otherwise falls back to first key dimension. Args: dimension: Dimension(s) to compute histogram on num_bins (int, optional): Number of bins bin_range (tuple optional): Lower and upper bounds of bins adjoin (bool, optional): Whether to adjoin histogram Returns: AdjointLayout of HoloMap and histograms or just the histograms """ if dimension is not None and not isinstance(dimension, list): dimension = [dimension] histmaps = [self.clone(shared_data=False) for _ in (dimension or [None])] if individually: map_range = None else: if dimension is None: raise Exception("Please supply the dimension to compute a histogram for.") map_range = self.range(kwargs['dimension']) bin_range = map_range if bin_range is None else bin_range style_prefix = 'Custom[<' + self.name + '>]_' if issubclass(self.type, (NdOverlay, Overlay)) and 'index' not in kwargs: kwargs['index'] = 0 for k, v in self.data.items(): hists = v.hist(adjoin=False, dimension=dimension, bin_range=bin_range, num_bins=num_bins, style_prefix=style_prefix, **kwargs) if isinstance(hists, Layout): for i, hist in enumerate(hists): histmaps[i][k] = hist else: histmaps[0][k] = hists if adjoin: layout = self for hist in histmaps: layout = (layout << hist) if issubclass(self.type, (NdOverlay, Overlay)): layout.main_layer = kwargs['index'] return layout else: if len(histmaps) > 1: return Layout(histmaps) else: return histmaps[0] class Callable(param.Parameterized): """ Callable allows wrapping callbacks on one or more DynamicMaps allowing their inputs (and in future outputs) to be defined. This makes it possible to wrap DynamicMaps with streams and makes it possible to traverse the graph of operations applied to a DynamicMap. Additionally, if the memoize attribute is True, a Callable will memoize the last returned value based on the arguments to the function and the state of all streams on its inputs, to avoid calling the function unnecessarily. Note that because memoization includes the streams found on the inputs it may be disabled if the stream requires it and is triggering. A Callable may also specify a stream_mapping which specifies the objects that are associated with interactive (i.e. linked) streams when composite objects such as Layouts are returned from the callback. This is required for building interactive, linked visualizations (for the backends that support them) when returning Layouts, NdLayouts or GridSpace objects. When chaining multiple DynamicMaps into a pipeline, the link_inputs parameter declares whether the visualization generated using this Callable will inherit the linked streams. This parameter is used as a hint by the applicable backend. The mapping should map from an appropriate key to a list of streams associated with the selected object. The appropriate key may be a type[.group][.label] specification for Layouts, an integer index or a suitable NdLayout/GridSpace key. For more information see the DynamicMap tutorial at holoviews.org. """ callable = param.Callable(default=None, constant=True, doc=""" The callable function being wrapped.""") inputs = param.List(default=[], constant=True, doc=""" The list of inputs the callable function is wrapping. Used to allow deep access to streams in chained Callables.""") operation_kwargs = param.Dict(default={}, constant=True, doc=""" Potential dynamic keyword arguments associated with the operation.""") link_inputs = param.Boolean(default=True, doc=""" If the Callable wraps around other DynamicMaps in its inputs, determines whether linked streams attached to the inputs are transferred to the objects returned by the Callable. For example the Callable wraps a DynamicMap with an RangeXY stream, this switch determines whether the corresponding visualization should update this stream with range changes originating from the newly generated axes.""") memoize = param.Boolean(default=True, doc=""" Whether the return value of the callable should be memoized based on the call arguments and any streams attached to the inputs.""") operation = param.Callable(default=None, doc=""" The function being applied by the Callable. May be used to record the transform(s) being applied inside the callback function.""") stream_mapping = param.Dict(default={}, constant=True, doc=""" Defines how streams should be mapped to objects returned by the Callable, e.g. when it returns a Layout.""") def __init__(self, callable, **params): super().__init__(callable=callable, **dict(params, name=util.callable_name(callable))) self._memoized = {} self._is_overlay = False self.args = None self.kwargs = None self._stream_memoization = self.memoize @property def argspec(self): return util.argspec(self.callable) @property def noargs(self): "Returns True if the callable takes no arguments" noargs = inspect.ArgSpec(args=[], varargs=None, keywords=None, defaults=None) return self.argspec == noargs def clone(self, callable=None, **overrides): """Clones the Callable optionally with new settings Args: callable: New callable function to wrap **overrides: Parameter overrides to apply Returns: Cloned Callable object """ old = {k: v for k, v in self.param.get_param_values() if k not in ['callable', 'name']} params = dict(old, **overrides) callable = self.callable if callable is None else callable return self.__class__(callable, **params) def __call__(self, *args, **kwargs): """Calls the callable function with supplied args and kwargs. If enabled uses memoization to avoid calling function unneccessarily. Args: *args: Arguments passed to the callable function **kwargs: Keyword arguments passed to the callable function Returns: Return value of the wrapped callable function """ # Nothing to do for callbacks that accept no arguments kwarg_hash = kwargs.pop('_memoization_hash_', ()) (self.args, self.kwargs) = (args, kwargs) if not args and not kwargs and not any(kwarg_hash): return self.callable() inputs = [i for i in self.inputs if isinstance(i, DynamicMap)] streams = [] for stream in [s for i in inputs for s in get_nested_streams(i)]: if stream not in streams: streams.append(stream) memoize = self._stream_memoization and not any(s.transient and s._triggering for s in streams) values = tuple(tuple(sorted(s.hashkey.items())) for s in streams) key = args + kwarg_hash + values hashed_key = util.deephash(key) if self.memoize else None if hashed_key is not None and memoize and hashed_key in self._memoized: return self._memoized[hashed_key] if self.argspec.varargs is not None: # Missing information on positional argument names, cannot promote to keywords pass elif len(args) != 0: # Turn positional arguments into keyword arguments pos_kwargs = {k:v for k,v in zip(self.argspec.args, args)} ignored = range(len(self.argspec.args),len(args)) if len(ignored): self.param.warning('Ignoring extra positional argument %s' % ', '.join('%s' % i for i in ignored)) clashes = set(pos_kwargs.keys()) & set(kwargs.keys()) if clashes: self.param.warning( 'Positional arguments %r overriden by keywords' % list(clashes)) args, kwargs = (), dict(pos_kwargs, **kwargs) try: ret = self.callable(*args, **kwargs) except KeyError: # KeyError is caught separately because it is used to signal # invalid keys on DynamicMap and should not warn raise except Exception as e: posstr = ', '.join(['%r' % el for el in self.args]) if self.args else '' kwstr = ', '.join('%s=%r' % (k,v) for k,v in self.kwargs.items()) argstr = ', '.join([el for el in [posstr, kwstr] if el]) message = ("Callable raised \"{e}\".\n" "Invoked as {name}({argstr})") self.param.warning(message.format(name=self.name, argstr=argstr, e=repr(e))) raise if hashed_key is not None: self._memoized = {hashed_key : ret} return ret class Generator(Callable): """ Generators are considered a special case of Callable that accept no arguments and never memoize. """ callable = param.ClassSelector(default=None, class_ = types.GeneratorType, constant=True, doc=""" The generator that is wrapped by this Generator.""") @property def argspec(self): return inspect.ArgSpec(args=[], varargs=None, keywords=None, defaults=None) def __call__(self): try: return next(self.callable) except StopIteration: raise except Exception: msg = 'Generator {name} raised the following exception:' self.param.warning(msg.format(name=self.name)) raise def get_nested_dmaps(dmap): """Recurses DynamicMap to find DynamicMaps inputs Args: dmap: DynamicMap to recurse to look for DynamicMap inputs Returns: List of DynamicMap instances that were found """ if not isinstance(dmap, DynamicMap): return [] dmaps = [dmap] for o in dmap.callback.inputs: dmaps.extend(get_nested_dmaps(o)) return list(set(dmaps)) def get_nested_streams(dmap): """Recurses supplied DynamicMap to find all streams Args: dmap: DynamicMap to recurse to look for streams Returns: List of streams that were found """ return list({s for dmap in get_nested_dmaps(dmap) for s in dmap.streams}) @contextmanager def dynamicmap_memoization(callable_obj, streams): """ Determine whether the Callable should have memoization enabled based on the supplied streams (typically by a DynamicMap). Memoization is disabled if any of the streams require it it and are currently in a triggered state. """ memoization_state = bool(callable_obj._stream_memoization) callable_obj._stream_memoization &= not any(s.transient and s._triggering for s in streams) try: yield finally: callable_obj._stream_memoization = memoization_state class periodic(object): """ Implements the utility of the same name on DynamicMap. Used to defined periodic event updates that can be started and stopped. """ _periodic_util = util.periodic def __init__(self, dmap): self.dmap = dmap self.instance = None def __call__(self, period, count=None, param_fn=None, timeout=None, block=True): """Periodically trigger the streams on the DynamicMap. Run a non-blocking loop that updates the stream parameters using the event method. Runs count times with the specified period. If count is None, runs indefinitely. Args: period: Timeout between events in seconds count: Number of events to trigger param_fn: Function returning stream updates given count Stream parameter values should be returned as dictionary timeout: Overall timeout in seconds block: Whether the periodic callbacks should be blocking """ if self.instance is not None and not self.instance.completed: raise RuntimeError('Periodic process already running. ' 'Wait until it completes or call ' 'stop() before running a new periodic process') def inner(i): kwargs = {} if param_fn is None else param_fn(i) if kwargs: self.dmap.event(**kwargs) else: Stream.trigger(self.dmap.streams) instance = self._periodic_util(period, count, inner, timeout=timeout, block=block) instance.start() self.instance = instance def stop(self): "Stop the periodic process." self.instance.stop() def __str__(self): return "<holoviews.core.spaces.periodic method>" class DynamicMap(HoloMap): """ A DynamicMap is a type of HoloMap where the elements are dynamically generated by a callable. The callable is invoked with values associated with the key dimensions or with values supplied by stream parameters. """ # Declare that callback is a positional parameter (used in clone) __pos_params = ['callback'] kdims = param.List(default=[], constant=True, doc=""" The key dimensions of a DynamicMap map to the arguments of the callback. This mapping can be by position or by name.""") callback = param.ClassSelector(class_=Callable, constant=True, doc=""" The callable used to generate the elements. The arguments to the callable includes any number of declared key dimensions as well as any number of stream parameters defined on the input streams. If the callable is an instance of Callable it will be used directly, otherwise it will be automatically wrapped in one.""") streams = param.List(default=[], constant=True, doc=""" List of Stream instances to associate with the DynamicMap. The set of parameter values across these streams will be supplied as keyword arguments to the callback when the events are received, updating the streams. Can also be supplied as a dictionary that maps parameters or panel widgets to callback argument names that will then be automatically converted to the equivalent list format.""") cache_size = param.Integer(default=500, doc=""" The number of entries to cache for fast access. This is an LRU cache where the least recently used item is overwritten once the cache is full.""") positional_stream_args = param.Boolean(default=False, constant=True, doc=""" If False, stream parameters are passed to the callback as keyword arguments. If True, stream parameters are passed to callback as positional arguments. Each positional argument is a dict containing the contents of a stream. The positional stream arguments follow the positional arguments for each kdim, and they are ordered to match the order of the DynamicMap's streams list. """) def __init__(self, callback, initial_items=None, streams=None, **params): streams = (streams or []) if isinstance(streams, dict): streams = streams_list_from_dict(streams) # If callback is a parameterized method and watch is disabled add as stream if (params.get('watch', True) and (util.is_param_method(callback, has_deps=True) or (isinstance(callback, FunctionType) and hasattr(callback, '_dinfo')))): streams.append(callback) if isinstance(callback, types.GeneratorType): callback = Generator(callback) elif not isinstance(callback, Callable): callback = Callable(callback) valid, invalid = Stream._process_streams(streams) if invalid: msg = ('The supplied streams list contains objects that ' 'are not Stream instances: {objs}') raise TypeError(msg.format(objs = ', '.join('%r' % el for el in invalid))) super().__init__(initial_items, callback=callback, streams=valid, **params) if self.callback.noargs: prefix = 'DynamicMaps using generators (or callables without arguments)' if self.kdims: raise Exception(prefix + ' must be declared without key dimensions') if len(self.streams)> 1: raise Exception(prefix + ' must have either streams=[] or a single, ' + 'stream instance without any stream parameters') if self._stream_parameters() != []: raise Exception(prefix + ' cannot accept any stream parameters') if self.positional_stream_args: self._posarg_keys = None else: self._posarg_keys = util.validate_dynamic_argspec( self.callback, self.kdims, self.streams ) # Set source to self if not already specified for stream in self.streams: if stream.source is None: stream.source = self if isinstance(stream, Params): for p in stream.parameters: if isinstance(p.owner, Stream) and p.owner.source is None: p.owner.source = self self.periodic = periodic(self) @property def opts(self): return Opts(self, mode='dynamicmap') @property def redim(self): return Redim(self, mode='dynamic') @property def unbounded(self): """ Returns a list of key dimensions that are unbounded, excluding stream parameters. If any of theses key dimensions are unbounded, the DynamicMap as a whole is also unbounded. """ unbounded_dims = [] # Dimensioned streams do not need to be bounded stream_params = set(self._stream_parameters()) for kdim in self.kdims: if str(kdim) in stream_params: continue if kdim.values: continue if None in kdim.range: unbounded_dims.append(str(kdim)) return unbounded_dims def _stream_parameters(self): return util.stream_parameters( self.streams, no_duplicates=not self.positional_stream_args ) def _initial_key(self): """ Construct an initial key for based on the lower range bounds or values on the key dimensions. """ key = [] undefined = [] stream_params = set(self._stream_parameters()) for kdim in self.kdims: if str(kdim) in stream_params: key.append(None) elif kdim.default is not None: key.append(kdim.default) elif kdim.values: if all(util.isnumeric(v) for v in kdim.values): key.append(sorted(kdim.values)[0]) else: key.append(kdim.values[0]) elif kdim.range[0] is not None: key.append(kdim.range[0]) else: undefined.append(kdim) if undefined: msg = ('Dimension(s) {undefined_dims} do not specify range or values needed ' 'to generate initial key') undefined_dims = ', '.join(['%r' % str(dim) for dim in undefined]) raise KeyError(msg.format(undefined_dims=undefined_dims)) return tuple(key) def _validate_key(self, key): """ Make sure the supplied key values are within the bounds specified by the corresponding dimension range and soft_range. """ if key == () and len(self.kdims) == 0: return () key = util.wrap_tuple(key) assert len(key) == len(self.kdims) for ind, val in enumerate(key): kdim = self.kdims[ind] low, high = util.max_range([kdim.range, kdim.soft_range]) if util.is_number(low) and util.isfinite(low): if val < low: raise KeyError("Key value %s below lower bound %s" % (val, low)) if util.is_number(high) and util.isfinite(high): if val > high: raise KeyError("Key value %s above upper bound %s" % (val, high)) def event(self, **kwargs): """Updates attached streams and triggers events Automatically find streams matching the supplied kwargs to update and trigger events on them. Args: **kwargs: Events to update streams with """ if self.callback.noargs and self.streams == []: self.param.warning( 'No streams declared. To update a DynamicMaps using ' 'generators (or callables without arguments) use streams=[Next()]') return if self.streams == []: self.param.warning('No streams on DynamicMap, calling event ' 'will have no effect') return stream_params = set(self._stream_parameters()) invalid = [k for k in kwargs.keys() if k not in stream_params] if invalid: msg = 'Key(s) {invalid} do not correspond to stream parameters' raise KeyError(msg.format(invalid = ', '.join('%r' % i for i in invalid))) streams = [] for stream in self.streams: contents = stream.contents applicable_kws = {k:v for k,v in kwargs.items() if k in set(contents.keys())} if not applicable_kws and contents: continue streams.append(stream) rkwargs = util.rename_stream_kwargs(stream, applicable_kws, reverse=True) stream.update(**rkwargs) Stream.trigger(streams) def _style(self, retval): "Applies custom option tree to values return by the callback." if self.id not in Store.custom_options(): return retval spec = StoreOptions.tree_to_dict(Store.custom_options()[self.id]) return retval.opts(spec) def _execute_callback(self, *args): "Executes the callback with the appropriate args and kwargs" self._validate_key(args) # Validate input key # Additional validation needed to ensure kwargs don't clash kdims = [kdim.name for kdim in self.kdims] kwarg_items = [s.contents.items() for s in self.streams] hash_items = tuple(tuple(sorted(s.hashkey.items())) for s in self.streams)+args flattened = [(k,v) for kws in kwarg_items for (k,v) in kws if k not in kdims] if self.positional_stream_args: kwargs = {} args = args + tuple([s.contents for s in self.streams]) elif self._posarg_keys: kwargs = dict(flattened, **dict(zip(self._posarg_keys, args))) args = () else: kwargs = dict(flattened) if not isinstance(self.callback, Generator): kwargs['_memoization_hash_'] = hash_items with dynamicmap_memoization(self.callback, self.streams): retval = self.callback(*args, **kwargs) return self._style(retval) def options(self, *args, **kwargs): """Applies simplified option definition returning a new object. Applies options defined in a flat format to the objects returned by the DynamicMap. If the options are to be set directly on the objects returned by the DynamicMap a simple format may be used, e.g.: obj.options(cmap='viridis', show_title=False) If the object is nested the options must be qualified using a type[.group][.label] specification, e.g.: obj.options('Image', cmap='viridis', show_title=False) or using: obj.options({'Image': dict(cmap='viridis', show_title=False)}) Args: *args: Sets of options to apply to object Supports a number of formats including lists of Options objects, a type[.group][.label] followed by a set of keyword options to apply and a dictionary indexed by type[.group][.label] specs. backend (optional): Backend to apply options to Defaults to current selected backend clone (bool, optional): Whether to clone object Options can be applied inplace with clone=False **kwargs: Keywords of options Set of options to apply to the object Returns: Returns the cloned object with the options applied """ if 'clone' not in kwargs: kwargs['clone'] = True return self.opts(*args, **kwargs) def clone(self, data=None, shared_data=True, new_type=None, link=True, *args, **overrides): """Clones the object, overriding data and parameters. Args: data: New data replacing the existing data shared_data (bool, optional): Whether to use existing data new_type (optional): Type to cast object to link (bool, optional): Whether clone should be linked Determines whether Streams and Links attached to original object will be inherited. *args: Additional arguments to pass to constructor **overrides: New keyword arguments to pass to constructor Returns: Cloned object """ callback = overrides.pop('callback', self.callback) if data is None and shared_data: data = self.data if link and callback is self.callback: overrides['plot_id'] = self._plot_id clone = super(UniformNdMapping, self).clone( callback, shared_data, new_type, link, *(data,) + args, **overrides) # Ensure the clone references this object to ensure # stream sources are inherited if clone.callback is self.callback: from ..operation import function with util.disable_constant(clone): op = function.instance(fn=lambda x, **kwargs: x) clone.callback = clone.callback.clone( inputs=[self], link_inputs=link, operation=op, operation_kwargs={} ) return clone def reset(self): "Clear the DynamicMap cache" self.data = OrderedDict() return self def _cross_product(self, tuple_key, cache, data_slice): """ Returns a new DynamicMap if the key (tuple form) expresses a cross product, otherwise returns None. The cache argument is a dictionary (key:element pairs) of all the data found in the cache for this key. Each key inside the cross product is looked up in the cache (self.data) to check if the appropriate element is available. Otherwise the element is computed accordingly. The data_slice may specify slices into each value in the the cross-product. """ if not any(isinstance(el, (list, set)) for el in tuple_key): return None if len(tuple_key)==1: product = tuple_key[0] else: args = [set(el) if isinstance(el, (list,set)) else set([el]) for el in tuple_key] product = itertools.product(*args) data = [] for inner_key in product: key = util.wrap_tuple(inner_key) if key in cache: val = cache[key] else: val = self._execute_callback(*key) if data_slice: val = self._dataslice(val, data_slice) data.append((key, val)) product = self.clone(data) if data_slice: from ..util import Dynamic dmap = Dynamic(self, operation=lambda obj, **dynkwargs: obj[data_slice], streams=self.streams) dmap.data = product.data return dmap return product def _slice_bounded(self, tuple_key, data_slice): """ Slices bounded DynamicMaps by setting the soft_ranges on key dimensions and applies data slice to cached and dynamic values. """ slices = [el for el in tuple_key if isinstance(el, slice)] if any(el.step for el in slices): raise Exception("DynamicMap slices cannot have a step argument") elif len(slices) not in [0, len(tuple_key)]: raise Exception("Slices must be used exclusively or not at all") elif not slices: return None sliced = self.clone(self) for i, slc in enumerate(tuple_key): (start, stop) = slc.start, slc.stop if start is not None and start < sliced.kdims[i].range[0]: raise Exception("Requested slice below defined dimension range.") if stop is not None and stop > sliced.kdims[i].range[1]: raise Exception("Requested slice above defined dimension range.") sliced.kdims[i].soft_range = (start, stop) if data_slice: if not isinstance(sliced, DynamicMap): return self._dataslice(sliced, data_slice) else: from ..util import Dynamic if len(self): slices = [slice(None) for _ in range(self.ndims)] + list(data_slice) sliced = super(DynamicMap, sliced).__getitem__(tuple(slices)) dmap = Dynamic(self, operation=lambda obj, **dynkwargs: obj[data_slice], streams=self.streams) dmap.data = sliced.data return dmap return sliced def __getitem__(self, key): """Evaluates DynamicMap with specified key. Indexing into a DynamicMap evaluates the dynamic function with the specified key unless the key and corresponding value are already in the cache. This may also be used to evaluate multiple keys or even a cross-product of keys if a list of values per Dimension are defined. Once values are in the cache the DynamicMap can be cast to a HoloMap. Args: key: n-dimensional key corresponding to the key dimensions Scalar values will be evaluated as normal while lists of values will be combined to form the cross-product, making it possible to evaluate many keys at once. Returns: Returns evaluated callback return value for scalar key otherwise returns cloned DynamicMap containing the cross- product of evaluated items. """ # Split key dimensions and data slices sample = False if key is Ellipsis: return self elif isinstance(key, (list, set)) and all(isinstance(v, tuple) for v in key): map_slice, data_slice = key, () sample = True elif self.positional_stream_args: # First positional args are dynamic map kdim indices, remaining args # are stream values, not data_slice values map_slice, _ = self._split_index(key) data_slice = () else: map_slice, data_slice = self._split_index(key) tuple_key = util.wrap_tuple_streams(map_slice, self.kdims, self.streams) # Validation if not sample: sliced = self._slice_bounded(tuple_key, data_slice) if sliced is not None: return sliced # Cache lookup try: dimensionless = util.dimensionless_contents(get_nested_streams(self), self.kdims, no_duplicates=False) empty = self._stream_parameters() == [] and self.kdims==[] if dimensionless or empty: raise KeyError('Using dimensionless streams disables DynamicMap cache') cache = super().__getitem__(key) except KeyError: cache = None # If the key expresses a cross product, compute the elements and return product = self._cross_product(tuple_key, cache.data if cache else {}, data_slice) if product is not None: return product # Not a cross product and nothing cached so compute element. if cache is not None: return cache val = self._execute_callback(*tuple_key) if data_slice: val = self._dataslice(val, data_slice) self._cache(tuple_key, val) return val def select(self, selection_specs=None, **kwargs): """Applies selection by dimension name Applies a selection along the dimensions of the object using keyword arguments. The selection may be narrowed to certain objects using selection_specs. For container objects the selection will be applied to all children as well. Selections may select a specific value, slice or set of values: * value: Scalar values will select rows along with an exact match, e.g.: ds.select(x=3) * slice: Slices may be declared as tuples of the upper and lower bound, e.g.: ds.select(x=(0, 3)) * values: A list of values may be selected using a list or set, e.g.: ds.select(x=[0, 1, 2]) Args: selection_specs: List of specs to match on A list of types, functions, or type[.group][.label] strings specifying which objects to apply the selection on. **selection: Dictionary declaring selections by dimension Selections can be scalar values, tuple ranges, lists of discrete values and boolean arrays Returns: Returns an Dimensioned object containing the selected data or a scalar if a single value was selected """ if selection_specs is not None and not isinstance(selection_specs, (list, tuple)): selection_specs = [selection_specs] selection = super().select(selection_specs=selection_specs, **kwargs) def dynamic_select(obj, **dynkwargs): if selection_specs is not None: matches = any(obj.matches(spec) for spec in selection_specs) else: matches = True if matches: return obj.select(**kwargs) return obj if not isinstance(selection, DynamicMap): return dynamic_select(selection) else: from ..util import Dynamic dmap = Dynamic(self, operation=dynamic_select, streams=self.streams) dmap.data = selection.data return dmap def _cache(self, key, val): """ Request that a key/value pair be considered for caching. """ cache_size = (1 if util.dimensionless_contents( self.streams, self.kdims, no_duplicates=not self.positional_stream_args) else self.cache_size) if len(self) >= cache_size: first_key = next(k for k in self.data) self.data.pop(first_key) self[key] = val def map(self, map_fn, specs=None, clone=True, link_inputs=True): """Map a function to all objects matching the specs Recursively replaces elements using a map function when the specs apply, by default applies to all objects, e.g. to apply the function to all contained Curve objects: dmap.map(fn, hv.Curve) Args: map_fn: Function to apply to each object specs: List of specs to match List of types, functions or type[.group][.label] specs to select objects to return, by default applies to all objects. clone: Whether to clone the object or transform inplace Returns: Returns the object after the map_fn has been applied """ deep_mapped = super().map(map_fn, specs, clone) if isinstance(deep_mapped, type(self)): from ..util import Dynamic def apply_map(obj, **dynkwargs): return obj.map(map_fn, specs, clone) dmap = Dynamic(self, operation=apply_map, streams=self.streams, link_inputs=link_inputs) dmap.data = deep_mapped.data return dmap return deep_mapped def relabel(self, label=None, group=None, depth=1): """Clone object and apply new group and/or label. Applies relabeling to children up to the supplied depth. Args: label (str, optional): New label to apply to returned object group (str, optional): New group to apply to returned object depth (int, optional): Depth to which relabel will be applied If applied to container allows applying relabeling to contained objects up to the specified depth Returns: Returns relabelled object """ relabelled = super().relabel(label, group, depth) if depth > 0: from ..util import Dynamic def dynamic_relabel(obj, **dynkwargs): return obj.relabel(group=group, label=label, depth=depth-1) dmap = Dynamic(self, streams=self.streams, operation=dynamic_relabel) dmap.data = relabelled.data with util.disable_constant(dmap): dmap.group = relabelled.group dmap.label = relabelled.label return dmap return relabelled def _split_overlays(self): """ Splits a DynamicMap into its components. Only well defined for DynamicMap with consistent number and order of layers. """ if not len(self): raise ValueError('Cannot split DynamicMap before it has been initialized') elif not issubclass(self.type, CompositeOverlay): return None, self from ..util import Dynamic keys = list(self.last.data.keys()) dmaps = [] for key in keys: el = self.last.data[key] def split_overlay_callback(obj, overlay_key=key, overlay_el=el, **kwargs): spec = util.get_overlay_spec(obj, overlay_key, overlay_el) items = list(obj.data.items()) specs = [(i, util.get_overlay_spec(obj, k, v)) for i, (k, v) in enumerate(items)] match = util.closest_match(spec, specs) if match is None: raise KeyError('{spec} spec not found in {otype}. The split_overlays method ' 'only works consistently for a DynamicMap where the ' 'layers of the {otype} do not change.'.format( spec=spec, otype=type(obj).__name__)) return items[match][1] dmap = Dynamic(self, streams=self.streams, operation=split_overlay_callback) dmap.data = OrderedDict([(list(self.data.keys())[-1], self.last.data[key])]) dmaps.append(dmap) return keys, dmaps def decollate(self): """Packs DynamicMap of nested DynamicMaps into a single DynamicMap that returns a non-dynamic element Decollation allows packing a DynamicMap of nested DynamicMaps into a single DynamicMap that returns a simple (non-dynamic) element. All nested streams are lifted to the resulting DynamicMap, and are available in the `streams` property. The `callback` property of the resulting DynamicMap is a pure, stateless function of the stream values. To avoid stream parameter name conflicts, the resulting DynamicMap is configured with positional_stream_args=True, and the callback function accepts stream values as positional dict arguments. Returns: DynamicMap that returns a non-dynamic element """ from .decollate import decollate return decollate(self) def collate(self): """Unpacks DynamicMap into container of DynamicMaps Collation allows unpacking DynamicMaps which return Layout, NdLayout or GridSpace objects into a single such object containing DynamicMaps. Assumes that the items in the layout or grid that is returned do not change. Returns: Collated container containing DynamicMaps """ # Initialize if self.last is not None: initialized = self else: initialized = self.clone() initialized[initialized._initial_key()] if not isinstance(initialized.last, (Layout, NdLayout, GridSpace)): return self container = initialized.last.clone(shared_data=False) type_counter = defaultdict(int) # Get stream mapping from callback remapped_streams = [] self_dstreams = util.dimensioned_streams(self) streams = self.callback.stream_mapping for i, (k, v) in enumerate(initialized.last.data.items()): vstreams = streams.get(i, []) if not vstreams: if isinstance(initialized.last, Layout): for l in range(len(k)): path = '.'.join(k[:l]) if path in streams: vstreams = streams[path] break else: vstreams = streams.get(k, []) if any(s in remapped_streams for s in vstreams): raise ValueError( "The stream_mapping supplied on the Callable " "is ambiguous please supply more specific Layout " "path specs.") remapped_streams += vstreams # Define collation callback def collation_cb(*args, **kwargs): layout = self[args] layout_type = type(layout).__name__ if len(container.keys()) != len(layout.keys()): raise ValueError('Collated DynamicMaps must return ' '%s with consistent number of items.' % layout_type) key = kwargs['selection_key'] index = kwargs['selection_index'] obj_type = kwargs['selection_type'] dyn_type_map = defaultdict(list) for k, v in layout.data.items(): if k == key: return layout[k] dyn_type_map[type(v)].append(v) dyn_type_counter = {t: len(vals) for t, vals in dyn_type_map.items()} if dyn_type_counter != type_counter: raise ValueError('The objects in a %s returned by a ' 'DynamicMap must consistently return ' 'the same number of items of the ' 'same type.' % layout_type) return dyn_type_map[obj_type][index] callback = Callable(partial(collation_cb, selection_key=k, selection_index=type_counter[type(v)], selection_type=type(v)), inputs=[self]) vstreams = list(util.unique_iterator(self_dstreams + vstreams)) vdmap = self.clone(callback=callback, shared_data=False, streams=vstreams) type_counter[type(v)] += 1 # Remap source of streams for stream in vstreams: if stream.source is self: stream.source = vdmap container[k] = vdmap unmapped_streams = [repr(stream) for stream in self.streams if (stream.source is self) and (stream not in remapped_streams) and stream.linked] if unmapped_streams: raise ValueError( 'The following streams are set to be automatically ' 'linked to a plot, but no stream_mapping specifying ' 'which item in the (Nd)Layout to link it to was found:\n%s' % ', '.join(unmapped_streams) ) return container def groupby(self, dimensions=None, container_type=None, group_type=None, **kwargs): """Groups DynamicMap by one or more dimensions Applies groupby operation over the specified dimensions returning an object of type container_type (expected to be dictionary-like) containing the groups. Args: dimensions: Dimension(s) to group by container_type: Type to cast group container to group_type: Type to cast each group to dynamic: Whether to return a DynamicMap **kwargs: Keyword arguments to pass to each group Returns: Returns object of supplied container_type containing the groups. If dynamic=True returns a DynamicMap instead. """ if dimensions is None: dimensions = self.kdims if not isinstance(dimensions, (list, tuple)): dimensions = [dimensions] container_type = container_type if container_type else type(self) group_type = group_type if group_type else type(self) outer_kdims = [self.get_dimension(d) for d in dimensions] inner_kdims = [d for d in self.kdims if not d in outer_kdims] outer_dynamic = issubclass(container_type, DynamicMap) inner_dynamic = issubclass(group_type, DynamicMap) if ((not outer_dynamic and any(not d.values for d in outer_kdims)) or (not inner_dynamic and any(not d.values for d in inner_kdims))): raise Exception('Dimensions must specify sampling via ' 'values to apply a groupby') if outer_dynamic: def outer_fn(*outer_key, **dynkwargs): if inner_dynamic: def inner_fn(*inner_key, **dynkwargs): outer_vals = zip(outer_kdims, util.wrap_tuple(outer_key)) inner_vals = zip(inner_kdims, util.wrap_tuple(inner_key)) inner_sel = [(k.name, v) for k, v in inner_vals] outer_sel = [(k.name, v) for k, v in outer_vals] return self.select(**dict(inner_sel+outer_sel)) return self.clone([], callback=inner_fn, kdims=inner_kdims) else: dim_vals = [(d.name, d.values) for d in inner_kdims] dim_vals += [(d.name, [v]) for d, v in zip(outer_kdims, util.wrap_tuple(outer_key))] with item_check(False): selected = HoloMap(self.select(**dict(dim_vals))) return group_type(selected.reindex(inner_kdims)) if outer_kdims: return self.clone([], callback=outer_fn, kdims=outer_kdims) else: return outer_fn(()) else: outer_product = itertools.product(*[self.get_dimension(d).values for d in dimensions]) groups = [] for outer in outer_product: outer_vals = [(d.name, [o]) for d, o in zip(outer_kdims, outer)] if inner_dynamic or not inner_kdims: def inner_fn(outer_vals, *key, **dynkwargs): inner_dims = zip(inner_kdims, util.wrap_tuple(key)) inner_vals = [(d.name, k) for d, k in inner_dims] return self.select(**dict(outer_vals+inner_vals)).last if inner_kdims or self.streams: callback = Callable(partial(inner_fn, outer_vals), inputs=[self]) group = self.clone( callback=callback, kdims=inner_kdims ) else: group = inner_fn(outer_vals, ()) groups.append((outer, group)) else: inner_vals = [(d.name, self.get_dimension(d).values) for d in inner_kdims] with item_check(False): selected = HoloMap(self.select(**dict(outer_vals+inner_vals))) group = group_type(selected.reindex(inner_kdims)) groups.append((outer, group)) return container_type(groups, kdims=outer_kdims) def grid(self, dimensions=None, **kwargs): """ Groups data by supplied dimension(s) laying the groups along the dimension(s) out in a GridSpace. Args: dimensions: Dimension/str or list Dimension or list of dimensions to group by Returns: grid: GridSpace GridSpace with supplied dimensions """ return self.groupby(dimensions, container_type=GridSpace, **kwargs) def layout(self, dimensions=None, **kwargs): """ Groups data by supplied dimension(s) laying the groups along the dimension(s) out in a NdLayout. Args: dimensions: Dimension/str or list Dimension or list of dimensions to group by Returns: layout: NdLayout NdLayout with supplied dimensions """ return self.groupby(dimensions, container_type=NdLayout, **kwargs) def overlay(self, dimensions=None, **kwargs): """Group by supplied dimension(s) and overlay each group Groups data by supplied dimension(s) overlaying the groups along the dimension(s). Args: dimensions: Dimension(s) of dimensions to group by Returns: NdOverlay object(s) with supplied dimensions """ if dimensions is None: dimensions = self.kdims else: if not isinstance(dimensions, (list, tuple)): dimensions = [dimensions] dimensions = [self.get_dimension(d, strict=True) for d in dimensions] dims = [d for d in self.kdims if d not in dimensions] return self.groupby(dims, group_type=NdOverlay) def hist(self, dimension=None, num_bins=20, bin_range=None, adjoin=True, **kwargs): """Computes and adjoins histogram along specified dimension(s). Defaults to first value dimension if present otherwise falls back to first key dimension. Args: dimension: Dimension(s) to compute histogram on num_bins (int, optional): Number of bins bin_range (tuple optional): Lower and upper bounds of bins adjoin (bool, optional): Whether to adjoin histogram Returns: AdjointLayout of DynamicMap and adjoined histogram if adjoin=True, otherwise just the histogram """ def dynamic_hist(obj, **dynkwargs): if isinstance(obj, (NdOverlay, Overlay)): index = kwargs.get('index', 0) obj = obj.get(index) return obj.hist( dimension=dimension, num_bins=num_bins, bin_range=bin_range, adjoin=False, **kwargs ) from ..util import Dynamic hist = Dynamic(self, streams=self.streams, link_inputs=False, operation=dynamic_hist) if adjoin: return self << hist else: return hist def reindex(self, kdims=[], force=False): """Reorders key dimensions on DynamicMap Create a new object with a reordered set of key dimensions. Dropping dimensions is not allowed on a DynamicMap. Args: kdims: List of dimensions to reindex the mapping with force: Not applicable to a DynamicMap Returns: Reindexed DynamicMap """ if not isinstance(kdims, list): kdims = [kdims] kdims = [self.get_dimension(kd, strict=True) for kd in kdims] dropped = [kd for kd in self.kdims if kd not in kdims] if dropped: raise ValueError("DynamicMap does not allow dropping dimensions, " "reindex may only be used to reorder dimensions.") return super().reindex(kdims, force) def drop_dimension(self, dimensions): raise NotImplementedError('Cannot drop dimensions from a DynamicMap, ' 'cast to a HoloMap first.') def add_dimension(self, dimension, dim_pos, dim_val, vdim=False, **kwargs): raise NotImplementedError('Cannot add dimensions to a DynamicMap, ' 'cast to a HoloMap first.') def next(self): if self.callback.noargs: return self[()] else: raise Exception('The next method can only be used for DynamicMaps using' 'generators (or callables without arguments)') # For Python 2 and 3 compatibility __next__ = next class GridSpace(UniformNdMapping): """ Grids are distinct from Layouts as they ensure all contained elements to be of the same type. Unlike Layouts, which have integer keys, Grids usually have floating point keys, which correspond to a grid sampling in some two-dimensional space. This two-dimensional space may have to arbitrary dimensions, e.g. for 2D parameter spaces. """ kdims = param.List(default=[Dimension("X"), Dimension("Y")], bounds=(1,2)) def __init__(self, initial_items=None, kdims=None, **params): super().__init__(initial_items, kdims=kdims, **params) if self.ndims > 2: raise Exception('Grids can have no more than two dimensions.') def __lshift__(self, other): "Adjoins another object to the GridSpace" if isinstance(other, (ViewableElement, UniformNdMapping)): return AdjointLayout([self, other]) elif isinstance(other, AdjointLayout): return AdjointLayout(other.data+[self]) else: raise TypeError('Cannot append {0} to a AdjointLayout'.format(type(other).__name__)) def _transform_indices(self, key): """Snaps indices into the GridSpace to the closest coordinate. Args: key: Tuple index into the GridSpace Returns: Transformed key snapped to closest numeric coordinates """ ndims = self.ndims if all(not (isinstance(el, slice) or callable(el)) for el in key): dim_inds = [] for dim in self.kdims: dim_type = self.get_dimension_type(dim) if isinstance(dim_type, type) and issubclass(dim_type, Number): dim_inds.append(self.get_dimension_index(dim)) str_keys = iter(key[i] for i in range(self.ndims) if i not in dim_inds) num_keys = [] if len(dim_inds): keys = list({tuple(k[i] if ndims > 1 else k for i in dim_inds) for k in self.keys()}) q = np.array([tuple(key[i] if ndims > 1 else key for i in dim_inds)]) idx = np.argmin([np.inner(q - np.array(x), q - np.array(x)) if len(dim_inds) == 2 else np.abs(q-x) for x in keys]) num_keys = iter(keys[idx]) key = tuple(next(num_keys) if i in dim_inds else next(str_keys) for i in range(self.ndims)) elif any(not (isinstance(el, slice) or callable(el)) for el in key): keys = self.keys() for i, k in enumerate(key): if isinstance(k, slice): continue dim_keys = np.array([ke[i] for ke in keys]) if dim_keys.dtype.kind in 'OSU': continue snapped_val = dim_keys[np.argmin(np.abs(dim_keys-k))] key = list(key) key[i] = snapped_val key = tuple(key) return key def keys(self, full_grid=False): """Returns the keys of the GridSpace Args: full_grid (bool, optional): Return full cross-product of keys Returns: List of keys """ keys = super().keys() if self.ndims == 1 or not full_grid: return keys dim1_keys = list(OrderedDict.fromkeys(k[0] for k in keys)) dim2_keys = list(OrderedDict.fromkeys(k[1] for k in keys)) return [(d1, d2) for d1 in dim1_keys for d2 in dim2_keys] @property def last(self): """ The last of a GridSpace is another GridSpace constituted of the last of the individual elements. To access the elements by their X,Y position, either index the position directly or use the items() method. """ if self.type == HoloMap: last_items = [(k, v.last if isinstance(v, HoloMap) else v) for (k, v) in self.data.items()] else: last_items = self.data return self.clone(last_items) def __len__(self): """ The maximum depth of all the elements. Matches the semantics of __len__ used by Maps. For the total number of elements, count the full set of keys. """ return max([(len(v) if hasattr(v, '__len__') else 1) for v in self.values()] + [0]) def __add__(self, obj): "Composes the GridSpace with another object into a Layout." return Layout([self, obj]) @property def shape(self): "Returns the 2D shape of the GridSpace as (rows, cols)." keys = self.keys() if self.ndims == 1: return (len(keys), 1) return len(set(k[0] for k in keys)), len(set(k[1] for k in keys)) def decollate(self): """Packs GridSpace of DynamicMaps into a single DynamicMap that returns a GridSpace Decollation allows packing a GridSpace of DynamicMaps into a single DynamicMap that returns a GridSpace of simple (non-dynamic) elements. All nested streams are lifted to the resulting DynamicMap, and are available in the `streams` property. The `callback` property of the resulting DynamicMap is a pure, stateless function of the stream values. To avoid stream parameter name conflicts, the resulting DynamicMap is configured with positional_stream_args=True, and the callback function accepts stream values as positional dict arguments. Returns: DynamicMap that returns a GridSpace """ from .decollate import decollate return decollate(self) class GridMatrix(GridSpace): """ GridMatrix is container type for heterogeneous Element types laid out in a grid. Unlike a GridSpace the axes of the Grid must not represent an actual coordinate space, but may be used to plot various dimensions against each other. The GridMatrix is usually constructed using the gridmatrix operation, which will generate a GridMatrix plotting each dimension in an Element against each other. """ def _item_check(self, dim_vals, data): if not traversal.uniform(NdMapping([(0, self), (1, data)])): raise ValueError("HoloMaps dimensions must be consistent in %s." % type(self).__name__) NdMapping._item_check(self, dim_vals, data)
1
24,655
I think I would prefer you declare `self._current_key=None` in the constructor and just return `self._current_key`. That way you can prevent anyone from overwriting `current_key` without needing to use `getattr` here.
holoviz-holoviews
py
@@ -22,8 +22,14 @@ const FromCSVKind = "fromCSV" type FromCSVOpSpec struct { CSV string `json:"csv"` File string `json:"file"` + Mode string `json:"mode"` } +const ( + annotationMode = "annotations" + rawMode = "raw" +) + func init() { fromCSVSignature := runtime.MustLookupBuiltinType("csv", "from") runtime.RegisterPackageValue("csv", "from", flux.MustValue(flux.FunctionValue(FromCSVKind, createFromCSVOpSpec, fromCSVSignature)))
1
package csv import ( "context" "io" "io/ioutil" "strings" "github.com/influxdata/flux" "github.com/influxdata/flux/codes" "github.com/influxdata/flux/csv" "github.com/influxdata/flux/dependencies/filesystem" "github.com/influxdata/flux/execute" "github.com/influxdata/flux/internal/errors" "github.com/influxdata/flux/memory" "github.com/influxdata/flux/plan" "github.com/influxdata/flux/runtime" ) const FromCSVKind = "fromCSV" type FromCSVOpSpec struct { CSV string `json:"csv"` File string `json:"file"` } func init() { fromCSVSignature := runtime.MustLookupBuiltinType("csv", "from") runtime.RegisterPackageValue("csv", "from", flux.MustValue(flux.FunctionValue(FromCSVKind, createFromCSVOpSpec, fromCSVSignature))) flux.RegisterOpSpec(FromCSVKind, newFromCSVOp) plan.RegisterProcedureSpec(FromCSVKind, newFromCSVProcedure, FromCSVKind) execute.RegisterSource(FromCSVKind, createFromCSVSource) } func createFromCSVOpSpec(args flux.Arguments, a *flux.Administration) (flux.OperationSpec, error) { spec := new(FromCSVOpSpec) if csv, ok, err := args.GetString("csv"); err != nil { return nil, err } else if ok { spec.CSV = csv } if file, ok, err := args.GetString("file"); err != nil { return nil, err } else if ok { spec.File = file } if spec.CSV == "" && spec.File == "" { return nil, errors.New(codes.Invalid, "must provide csv raw text or filename") } if spec.CSV != "" && spec.File != "" { return nil, errors.New(codes.Invalid, "must provide exactly one of the parameters csv or file") } return spec, nil } func newFromCSVOp() flux.OperationSpec { return new(FromCSVOpSpec) } func (s *FromCSVOpSpec) Kind() flux.OperationKind { return FromCSVKind } type FromCSVProcedureSpec struct { plan.DefaultCost CSV string File string } func newFromCSVProcedure(qs flux.OperationSpec, pa plan.Administration) (plan.ProcedureSpec, error) { spec, ok := qs.(*FromCSVOpSpec) if !ok { return nil, errors.Newf(codes.Internal, "invalid spec type %T", qs) } return &FromCSVProcedureSpec{ CSV: spec.CSV, File: spec.File, }, nil } func (s *FromCSVProcedureSpec) Kind() plan.ProcedureKind { return FromCSVKind } func (s *FromCSVProcedureSpec) Copy() plan.ProcedureSpec { ns := new(FromCSVProcedureSpec) ns.CSV = s.CSV ns.File = s.File return ns } func createFromCSVSource(prSpec plan.ProcedureSpec, dsid execute.DatasetID, a execute.Administration) (execute.Source, error) { spec, ok := prSpec.(*FromCSVProcedureSpec) if !ok { return nil, errors.Newf(codes.Internal, "invalid spec type %T", prSpec) } return CreateSource(spec, dsid, a) } func CreateSource(spec *FromCSVProcedureSpec, dsid execute.DatasetID, a execute.Administration) (execute.Source, error) { var getDataStream func() (io.ReadCloser, error) if spec.File != "" { getDataStream = func() (io.ReadCloser, error) { f, err := filesystem.OpenFile(a.Context(), spec.File) if err != nil { return nil, errors.Wrap(err, codes.Inherit, "csv.from() failed to read file") } return f, nil } } else { // if spec.File is empty then spec.CSV is not empty getDataStream = func() (io.ReadCloser, error) { return ioutil.NopCloser(strings.NewReader(spec.CSV)), nil } } csvSource := CSVSource{ id: dsid, getDataStream: getDataStream, alloc: a.Allocator(), } return &csvSource, nil } type CSVSource struct { execute.ExecutionNode id execute.DatasetID getDataStream func() (io.ReadCloser, error) ts []execute.Transformation alloc *memory.Allocator } func (c *CSVSource) AddTransformation(t execute.Transformation) { c.ts = append(c.ts, t) } func (c *CSVSource) Run(ctx context.Context) { var err error var max execute.Time maxSet := false for _, t := range c.ts { // For each downstream transformation, instantiate a new result // decoder. This way a table instance goes to one and only one // transformation. Unlike other sources, tables from csv sources // are not read-only. They contain mutable state and therefore // cannot be shared among goroutines. decoder := csv.NewMultiResultDecoder(csv.ResultDecoderConfig{ Allocator: c.alloc, Context: ctx, }) var data io.ReadCloser data, err = c.getDataStream() if err != nil { goto FINISH } results, decodeErr := decoder.Decode(data) defer results.Release() if decodeErr != nil { err = decodeErr goto FINISH } if !results.More() { err = results.Err() goto FINISH } result := results.Next() err = result.Tables().Do(func(tbl flux.Table) error { err := t.Process(c.id, tbl) if err != nil { return err } if idx := execute.ColIdx(execute.DefaultStopColLabel, tbl.Key().Cols()); idx >= 0 { if stop := tbl.Key().ValueTime(idx); !maxSet || stop > max { max = stop maxSet = true } } return nil }) if err != nil { goto FINISH } if results.More() { err = errors.New( codes.FailedPrecondition, "csv.from() can only parse 1 result", ) goto FINISH } } if maxSet { for _, t := range c.ts { if err = t.UpdateWatermark(c.id, max); err != nil { goto FINISH } } } FINISH: if err != nil { err = errors.Wrap(err, codes.Inherit, "error in csv.from()") } for _, t := range c.ts { t.Finish(c.id, err) } }
1
15,731
I guess I like the name `mode` okay. I can't think of anything better.
influxdata-flux
go
@@ -69,8 +69,12 @@ type Step struct { testType stepImpl } -// NewStep creates a Step with given name and timeout with the specified workflow +// NewStep creates a Step with given name and timeout with the specified workflow. +// If timeout is less or equal to zero, defaultTimeout from the workflow will be used func NewStep(name string, w *Workflow, timeout time.Duration) *Step { + if timeout <= 0 { + return &Step{name: name, w: w, Timeout: w.DefaultTimeout} + } return &Step{name: name, w: w, timeout: timeout} }
1
// Copyright 2017 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package daisy import ( "context" "fmt" "reflect" "strings" "time" ) type stepImpl interface { // populate modifies the step type field values. // populate should set defaults, extend GCE partial URLs to full partial // URLs (partial URLs including the "projects/<project>" prefix), etc. // This should not perform value validation. // Returns any parsing errors. populate(ctx context.Context, s *Step) DError validate(ctx context.Context, s *Step) DError run(ctx context.Context, s *Step) DError } // Step is a single daisy workflow step. type Step struct { name string w *Workflow //Timeout description TimeoutDescription string `json:",omitempty"` // Time to wait for this step to complete (default 10m). // Must be parsable by https://golang.org/pkg/time/#ParseDuration. Timeout string `json:",omitempty"` timeout time.Duration // Only one of the below fields should exist for each instance of Step. AttachDisks *AttachDisks `json:",omitempty"` DetachDisks *DetachDisks `json:",omitempty"` CreateDisks *CreateDisks `json:",omitempty"` CreateForwardingRules *CreateForwardingRules `json:",omitempty"` CreateFirewallRules *CreateFirewallRules `json:",omitempty"` CreateImages *CreateImages `json:",omitempty"` CreateInstances *CreateInstances `json:",omitempty"` CreateNetworks *CreateNetworks `json:",omitempty"` CreateSubnetworks *CreateSubnetworks `json:",omitempty"` CreateTargetInstances *CreateTargetInstances `json:",omitempty"` CopyGCSObjects *CopyGCSObjects `json:",omitempty"` ResizeDisks *ResizeDisks `json:",omitempty"` StartInstances *StartInstances `json:",omitempty"` StopInstances *StopInstances `json:",omitempty"` DeleteResources *DeleteResources `json:",omitempty"` DeprecateImages *DeprecateImages `json:",omitempty"` IncludeWorkflow *IncludeWorkflow `json:",omitempty"` SubWorkflow *SubWorkflow `json:",omitempty"` WaitForInstancesSignal *WaitForInstancesSignal `json:",omitempty"` UpdateInstancesMetadata *UpdateInstancesMetadata `json:",omitempty"` // Used for unit tests. testType stepImpl } // NewStep creates a Step with given name and timeout with the specified workflow func NewStep(name string, w *Workflow, timeout time.Duration) *Step { return &Step{name: name, w: w, timeout: timeout} } func (s *Step) stepImpl() (stepImpl, DError) { var result stepImpl matchCount := 0 if s.AttachDisks != nil { matchCount++ result = s.AttachDisks } if s.DetachDisks != nil { matchCount++ result = s.DetachDisks } if s.CreateDisks != nil { matchCount++ result = s.CreateDisks } if s.CreateForwardingRules != nil { matchCount++ result = s.CreateForwardingRules } if s.CreateFirewallRules != nil { matchCount++ result = s.CreateFirewallRules } if s.CreateImages != nil { matchCount++ result = s.CreateImages } if s.CreateInstances != nil { matchCount++ result = s.CreateInstances } if s.CreateNetworks != nil { matchCount++ result = s.CreateNetworks } if s.CreateSubnetworks != nil { matchCount++ result = s.CreateSubnetworks } if s.CreateTargetInstances != nil { matchCount++ result = s.CreateTargetInstances } if s.CopyGCSObjects != nil { matchCount++ result = s.CopyGCSObjects } if s.ResizeDisks != nil { matchCount++ result = s.ResizeDisks } if s.StartInstances != nil { matchCount++ result = s.StartInstances } if s.StopInstances != nil { matchCount++ result = s.StopInstances } if s.DeleteResources != nil { matchCount++ result = s.DeleteResources } if s.DeprecateImages != nil { matchCount++ result = s.DeprecateImages } if s.IncludeWorkflow != nil { matchCount++ result = s.IncludeWorkflow } if s.SubWorkflow != nil { matchCount++ result = s.SubWorkflow } if s.WaitForInstancesSignal != nil { matchCount++ result = s.WaitForInstancesSignal } if s.UpdateInstancesMetadata != nil { matchCount++ result = s.UpdateInstancesMetadata } if s.testType != nil { matchCount++ result = s.testType } if matchCount == 0 { return nil, Errf("no step type defined") } if matchCount > 1 { return nil, Errf("multiple step types defined") } return result, nil } func (s *Step) depends(other *Step) bool { if s == nil || other == nil || s.w == nil || s.w != other.w { return false } deps := s.w.Dependencies steps := s.w.Steps q := deps[s.name] seen := map[string]bool{} // Do a BFS search on s's dependencies, looking for the target dependency. Don't revisit visited dependencies. for i := 0; i < len(q); i++ { name := q[i] if seen[name] { continue } seen[name] = true if steps[name] == other { return true } for _, dep := range deps[name] { q = append(q, dep) } } return false } // nestedDepends determines if s depends on other, taking into account the recursive, nested nature of // workflows, i.e. workflows in IncludeWorkflow and SubWorkflow. // Example: if s depends on an IncludeWorkflow whose workflow contains other, then s depends on other. func (s *Step) nestedDepends(other *Step) bool { sChain := s.getChain() oChain := other.getChain() // If sChain and oChain don't share the same root workflow, then there is no dependency relationship. if len(sChain) == 0 || len(oChain) == 0 || sChain[0].w != oChain[0].w { return false } // Find where the step chains diverge. // A divergence in the chains indicates sibling steps, where we can check dependency. // We want to see if s's branch depends on other's branch. var sStep, oStep *Step for i := 0; i < minInt(len(sChain), len(oChain)); i++ { sStep = sChain[i] oStep = oChain[i] if sStep != oStep { break } } return sStep.depends(oStep) } // getChain returns the step chain getting to a step. A link in the chain represents an IncludeWorkflow step, a // SubWorkflow step, or the step itself. // For example, workflow A has a step s1 which includes workflow B. B has a step s2 which subworkflows C. Finally, // C has a step s3. s3.getChain() will return []*Step{s1, s2, s3} func (s *Step) getChain() []*Step { if s == nil || s.w == nil { return nil } if s.w.parent == nil { return []*Step{s} } for _, st := range s.w.parent.Steps { if st.IncludeWorkflow != nil && st.IncludeWorkflow.Workflow == s.w { return append(st.getChain(), s) } if st.SubWorkflow != nil && st.SubWorkflow.Workflow == s.w { return append(st.getChain(), s) } } // We shouldn't get here. return nil } func (s *Step) populate(ctx context.Context) DError { s.w.LogWorkflowInfo("Populating step %q", s.name) impl, err := s.stepImpl() if err != nil { return s.wrapPopulateError(err) } if err = impl.populate(ctx, s); err != nil { err = s.wrapPopulateError(err) } return err } func (s *Step) recordStepTime(startTime time.Time) { endTime := time.Now() s.w.recordStepTime(s.name, startTime, endTime) } func (s *Step) run(ctx context.Context) DError { startTime := time.Now() defer s.recordStepTime(startTime) impl, err := s.stepImpl() if err != nil { return s.wrapRunError(err) } var st string if t := reflect.TypeOf(impl); t.Kind() == reflect.Ptr { st = t.Elem().Name() } else { st = t.Name() } s.w.LogWorkflowInfo("Running step %q (%s)", s.name, st) if err = impl.run(ctx, s); err != nil { return s.wrapRunError(err) } select { case <-s.w.Cancel: default: s.w.LogWorkflowInfo("Step %q (%s) successfully finished.", s.name, st) } return nil } func (s *Step) validate(ctx context.Context) DError { s.w.LogWorkflowInfo("Validating step %q", s.name) if !rfc1035Rgx.MatchString(strings.ToLower(s.name)) { return s.wrapValidateError(Errf("step name must start with a letter and only contain letters, numbers, and hyphens")) } impl, err := s.stepImpl() if err != nil { return s.wrapValidateError(err) } if err = impl.validate(ctx, s); err != nil { return s.wrapValidateError(err) } return nil } func (s *Step) wrapPopulateError(e DError) DError { return Errf("step %q populate error: %s", s.name, e) } func (s *Step) wrapRunError(e DError) DError { return Errf("step %q run error: %s", s.name, e) } func (s *Step) wrapValidateError(e DError) DError { return Errf("step %q validation error: %s", s.name, e) } func (s *Step) getTimeoutError() DError { var timeoutDescription string if s.TimeoutDescription != "" { timeoutDescription = fmt.Sprintf(". %s", s.TimeoutDescription) } return Errf("step %q did not complete within the specified timeout of %s%s", s.name, s.timeout, timeoutDescription) }
1
9,845
I would create a new method (NewStepWithDefaultTimeout?) for this purpose because timeout<=0 looks like a hidden logic
GoogleCloudPlatform-compute-image-tools
go
@@ -71,6 +71,7 @@ func Register(r *gin.RouterGroup, s *Service) { // @Param experimentNamespace query string false "The namespace of the experiment" // @Param uid query string false "The UID of the experiment" // @Param kind query string false "kind" Enums(PodChaos, IoChaos, NetworkChaos, TimeChaos, KernelChaos, StressChaos) +// @Param limit query string false "The max length of events list" // @Success 200 {array} core.Event // @Router /api/events [get] // @Failure 500 {object} utils.APIError
1
// Copyright 2020 Chaos Mesh Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // See the License for the specific language governing permissions and // limitations under the License. package event import ( "context" "fmt" "net/http" "github.com/gin-gonic/gin" "github.com/chaos-mesh/chaos-mesh/pkg/apiserver/utils" "github.com/chaos-mesh/chaos-mesh/pkg/config" "github.com/chaos-mesh/chaos-mesh/pkg/core" "sigs.k8s.io/controller-runtime/pkg/client" ) // Service defines a handler service for events. type Service struct { conf *config.ChaosDashboardConfig kubeCli client.Client archive core.ExperimentStore event core.EventStore } // NewService return an event service instance. func NewService( conf *config.ChaosDashboardConfig, cli client.Client, archive core.ExperimentStore, event core.EventStore, ) *Service { return &Service{ conf: conf, kubeCli: cli, archive: archive, event: event, } } // Register mounts our HTTP handler on the mux. func Register(r *gin.RouterGroup, s *Service) { endpoint := r.Group("/events") // TODO: add more api handlers endpoint.GET("", s.listEvents) endpoint.GET("/dry", s.listDryEvents) } // @Summary Get the list of events from db. // @Description Get the list of events from db. // @Tags events // @Produce json // @Param podName query string false "The pod's name" // @Param podNamespace query string false "The pod's namespace" // @Param startTime query string false "The start time of events" // @Param endTime query string false "The end time of events" // @Param experimentName query string false "The name of the experiment" // @Param experimentNamespace query string false "The namespace of the experiment" // @Param uid query string false "The UID of the experiment" // @Param kind query string false "kind" Enums(PodChaos, IoChaos, NetworkChaos, TimeChaos, KernelChaos, StressChaos) // @Success 200 {array} core.Event // @Router /api/events [get] // @Failure 500 {object} utils.APIError func (s *Service) listEvents(c *gin.Context) { filter := core.Filter{ PodName: c.Query("podName"), PodNamespace: c.Query("podNamespace"), StartTimeStr: c.Query("startTime"), FinishTimeStr: c.Query("finishTime"), ExperimentName: c.Query("experimentName"), ExperimentNamespace: c.Query("experimentNamespace"), UID: c.Query("uid"), Kind: c.Query("kind"), } if filter.PodName != "" && filter.PodNamespace == "" { c.Status(http.StatusInternalServerError) _ = c.Error(utils.ErrInternalServer.WrapWithNoMessage(fmt.Errorf("when podName is not empty, podNamespace cannot be empty"))) return } eventList, err := s.event.ListByFilter(context.Background(), filter) if err != nil { c.Status(http.StatusInternalServerError) _ = c.Error(utils.ErrInternalServer.WrapWithNoMessage(err)) return } c.JSON(http.StatusOK, eventList) } // @Summary Get the list of events without pod records from db. // @Description Get the list of events without pod records from db. // @Tags events // @Produce json // @Param startTime query string false "The start time of events" // @Param endTime query string false "The end time of events" // @Param experimentName query string false "The name of the experiment" // @Param experimentNamespace query string false "The namespace of the experiment" // @Param kind query string false "kind" Enums(PodChaos, IoChaos, NetworkChaos, TimeChaos, KernelChaos, StressChaos) // @Success 200 {array} core.Event // @Router /api/events/dry [get] // @Failure 500 {object} utils.APIError func (s *Service) listDryEvents(c *gin.Context) { filter := core.Filter{ StartTimeStr: c.Query("startTime"), FinishTimeStr: c.Query("finishTime"), ExperimentName: c.Query("experimentName"), ExperimentNamespace: c.Query("experimentNamespace"), Kind: c.Query("kind"), } eventList, err := s.event.DryListByFilter(context.Background(), filter) if err != nil { c.Status(http.StatusInternalServerError) _ = c.Error(utils.ErrInternalServer.WrapWithNoMessage(err)) return } c.JSON(http.StatusOK, eventList) }
1
16,329
Are these limit changes related?
chaos-mesh-chaos-mesh
go
@@ -18,12 +18,12 @@ Routing and network interface handling for IPv6. from __future__ import absolute_import import socket +import scapy.consts from scapy.config import conf from scapy.utils6 import * from scapy.arch import * from scapy.pton_ntop import * from scapy.error import warning, log_loading -from scapy.consts import LOOPBACK_INTERFACE import scapy.modules.six as six
1
## This file is part of Scapy ## See http://www.secdev.org/projects/scapy for more informations ## Copyright (C) Philippe Biondi <[email protected]> ## This program is published under a GPLv2 license ## Copyright (C) 2005 Guillaume Valadon <[email protected]> ## Arnaud Ebalard <[email protected]> """ Routing and network interface handling for IPv6. """ ############################################################################# ############################################################################# ### Routing/Interfaces stuff ### ############################################################################# ############################################################################# from __future__ import absolute_import import socket from scapy.config import conf from scapy.utils6 import * from scapy.arch import * from scapy.pton_ntop import * from scapy.error import warning, log_loading from scapy.consts import LOOPBACK_INTERFACE import scapy.modules.six as six class Route6: def __init__(self): self.invalidate_cache() self.resync() def invalidate_cache(self): self.cache = {} def flush(self): self.invalidate_cache() self.routes = [] def resync(self): # TODO : At the moment, resync will drop existing Teredo routes # if any. Change that ... self.invalidate_cache() self.routes = read_routes6() if self.routes == []: log_loading.info("No IPv6 support in kernel") def __repr__(self): rtlst = [] for net,msk,gw,iface,cset in self.routes: rtlst.append(('%s/%i'% (net,msk), gw, (iface if isinstance(iface, six.string_types) else iface.name), ", ".join(cset) if len(cset) > 0 else "")) return pretty_routes(rtlst, [('Destination', 'Next Hop', "Iface", "Src candidates")], sortBy = 1) # Unlike Scapy's Route.make_route() function, we do not have 'host' and 'net' # parameters. We only have a 'dst' parameter that accepts 'prefix' and # 'prefix/prefixlen' values. # WARNING: Providing a specific device will at the moment not work correctly. def make_route(self, dst, gw=None, dev=None): """Internal function : create a route for 'dst' via 'gw'. """ prefix, plen = (dst.split("/")+["128"])[:2] plen = int(plen) if gw is None: gw = "::" if dev is None: dev, ifaddr, x = self.route(gw) else: # TODO: do better than that # replace that unique address by the list of all addresses lifaddr = in6_getifaddr() devaddrs = [x for x in lifaddr if x[2] == dev] ifaddr = construct_source_candidate_set(prefix, plen, devaddrs) return (prefix, plen, gw, dev, ifaddr) def add(self, *args, **kargs): """Ex: add(dst="2001:db8:cafe:f000::/56") add(dst="2001:db8:cafe:f000::/56", gw="2001:db8:cafe::1") add(dst="2001:db8:cafe:f000::/64", gw="2001:db8:cafe::1", dev="eth0") """ self.invalidate_cache() self.routes.append(self.make_route(*args, **kargs)) def delt(self, dst, gw=None): """ Ex: delt(dst="::/0") delt(dst="2001:db8:cafe:f000::/56") delt(dst="2001:db8:cafe:f000::/56", gw="2001:db8:deca::1") """ tmp = dst+"/128" dst, plen = tmp.split('/')[:2] dst = in6_ptop(dst) plen = int(plen) l = [x for x in self.routes if in6_ptop(x[0]) == dst and x[1] == plen] if gw: gw = in6_ptop(gw) l = [x for x in self.routes if in6_ptop(x[2]) == gw] if len(l) == 0: warning("No matching route found") elif len(l) > 1: warning("Found more than one match. Aborting.") else: i=self.routes.index(l[0]) self.invalidate_cache() del(self.routes[i]) def ifchange(self, iff, addr): the_addr, the_plen = (addr.split("/")+["128"])[:2] the_plen = int(the_plen) naddr = inet_pton(socket.AF_INET6, the_addr) nmask = in6_cidr2mask(the_plen) the_net = inet_ntop(socket.AF_INET6, in6_and(nmask,naddr)) for i, route in enumerate(self.routes): net,plen,gw,iface,addr = route if iface != iff: continue if gw == '::': self.routes[i] = (the_net,the_plen,gw,iface,[the_addr]) else: self.routes[i] = (net,plen,gw,iface,[the_addr]) self.invalidate_cache() conf.netcache.in6_neighbor.flush() def ifdel(self, iff): """ removes all route entries that uses 'iff' interface. """ new_routes=[] for rt in self.routes: if rt[3] != iff: new_routes.append(rt) self.invalidate_cache() self.routes = new_routes def ifadd(self, iff, addr): """ Add an interface 'iff' with provided address into routing table. Ex: ifadd('eth0', '2001:bd8:cafe:1::1/64') will add following entry into Scapy6 internal routing table: Destination Next Hop iface Def src @ 2001:bd8:cafe:1::/64 :: eth0 2001:bd8:cafe:1::1 prefix length value can be omitted. In that case, a value of 128 will be used. """ addr, plen = (addr.split("/")+["128"])[:2] addr = in6_ptop(addr) plen = int(plen) naddr = inet_pton(socket.AF_INET6, addr) nmask = in6_cidr2mask(plen) prefix = inet_ntop(socket.AF_INET6, in6_and(nmask,naddr)) self.invalidate_cache() self.routes.append((prefix,plen,'::',iff,[addr])) def route(self, dst, dev=None): """ Provide best route to IPv6 destination address, based on Scapy6 internal routing table content. When a set of address is passed (e.g. 2001:db8:cafe:*::1-5) an address of the set is used. Be aware of that behavior when using wildcards in upper parts of addresses ! If 'dst' parameter is a FQDN, name resolution is performed and result is used. if optional 'dev' parameter is provided a specific interface, filtering is performed to limit search to route associated to that interface. """ # Transform "2001:db8:cafe:*::1-5:0/120" to one IPv6 address of the set dst = dst.split("/")[0] savedst = dst # In case following inet_pton() fails dst = dst.replace("*","0") l = dst.find("-") while l >= 0: m = (dst[l:]+":").find(":") dst = dst[:l]+dst[l+m:] l = dst.find("-") try: inet_pton(socket.AF_INET6, dst) except socket.error: dst = socket.getaddrinfo(savedst, None, socket.AF_INET6)[0][-1][0] # TODO : Check if name resolution went well # Deal with dev-specific request for cache search k = dst if dev is not None: k = dst + "%%" + (dev if isinstance(dev, six.string_types) else dev.pcap_name) if k in self.cache: return self.cache[k] pathes = [] # TODO : review all kinds of addresses (scope and *cast) to see # if we are able to cope with everything possible. I'm convinced # it's not the case. # -- arnaud for p, plen, gw, iface, cset in self.routes: if dev is not None and iface != dev: continue if in6_isincluded(dst, p, plen): pathes.append((plen, (iface, cset, gw))) elif (in6_ismlladdr(dst) and in6_islladdr(p) and in6_islladdr(cset[0])): pathes.append((plen, (iface, cset, gw))) if not pathes: warning("No route found for IPv6 destination %s (no default route?)" % dst) return (LOOPBACK_INTERFACE, "::", "::") # Sort with longest prefix first pathes.sort(reverse=True) best_plen = pathes[0][0] pathes = [x for x in pathes if x[0] == best_plen] res = [] for p in pathes: # Here we select best source address for every route tmp = p[1] srcaddr = get_source_addr_from_candidate_set(dst, p[1][1]) if srcaddr is not None: res.append((p[0], (tmp[0], srcaddr, tmp[2]))) if res == []: warning("Found a route for IPv6 destination '%s', but no possible source address." % dst) return (LOOPBACK_INTERFACE, "::", "::") # Symptom : 2 routes with same weight (our weight is plen) # Solution : # - dst is unicast global. Check if it is 6to4 and we have a source # 6to4 address in those available # - dst is link local (unicast or multicast) and multiple output # interfaces are available. Take main one (conf.iface6) # - if none of the previous or ambiguity persists, be lazy and keep # first one # XXX TODO : in a _near_ future, include metric in the game if len(res) > 1: tmp = [] if in6_isgladdr(dst) and in6_isaddr6to4(dst): # TODO : see if taking the longest match between dst and # every source addresses would provide better results tmp = [x for x in res if in6_isaddr6to4(x[1][1])] elif in6_ismaddr(dst) or in6_islladdr(dst): # TODO : I'm sure we are not covering all addresses. Check that tmp = [x for x in res if x[1][0] == conf.iface6] if tmp: res = tmp # Fill the cache (including dev-specific request) k = dst if dev is not None: k = dst + "%%" + (dev if isinstance(dev, six.string_types) else dev.pcap_name) self.cache[k] = res[0][1] return res[0][1] conf.route6 = Route6() try: conf.iface6 = conf.route6.route("::/0")[0] except: pass
1
10,307
Don't you mean `import scapy.consts`?
secdev-scapy
py
@@ -62,3 +62,7 @@ func (e *Executor) ensurePrimaryUpdate(ctx context.Context) model.StageStatus { e.LogPersister.AppendSuccess(fmt.Sprintf("Successfully applied %d primary resources", len(manifests))) return model.StageStatus_STAGE_SUCCESS } + +func (e *Executor) rollbackPrimary(ctx context.Context) model.StageStatus { + return model.StageStatus_STAGE_SUCCESS +}
1
// Copyright 2020 The PipeCD Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package kubernetes import ( "context" "fmt" provider "github.com/pipe-cd/pipe/pkg/app/piped/cloudprovider/kubernetes" "github.com/pipe-cd/pipe/pkg/model" ) const ( primaryVariant = "primary" ) func (e *Executor) ensurePrimaryUpdate(ctx context.Context) model.StageStatus { manifests, err := e.loadManifests(ctx) if err != nil { e.LogPersister.AppendError(fmt.Sprintf("Failed while loading manifests (%v)", err)) return model.StageStatus_STAGE_FAILURE } if len(manifests) == 0 { e.LogPersister.AppendError("There are no kubernetes manifests to handle") return model.StageStatus_STAGE_FAILURE } for _, m := range manifests { m.AddAnnotations(map[string]string{ provider.LabelManagedBy: provider.ManagedByPiped, provider.LabelPiped: e.PipedConfig.PipedID, provider.LabelApplication: e.Deployment.ApplicationId, provider.LabelVariant: primaryVariant, provider.LabelOriginalAPIVersion: m.Key.APIVersion, provider.LabelResourceKey: m.Key.String(), provider.LabelCommitHash: e.Deployment.Trigger.Commit.Hash, }) } e.LogPersister.AppendInfo(fmt.Sprintf("Applying %d primary resources", len(manifests))) for _, m := range manifests { if err = e.provider.ApplyManifest(ctx, m); err != nil { e.LogPersister.AppendError(fmt.Sprintf("Failed to apply manfiest: %s (%v)", m.Key.ReadableString(), err)) return model.StageStatus_STAGE_FAILURE } e.LogPersister.AppendSuccess(fmt.Sprintf("- applied manfiest: %s", m.Key.ReadableString())) } e.LogPersister.AppendSuccess(fmt.Sprintf("Successfully applied %d primary resources", len(manifests))) return model.StageStatus_STAGE_SUCCESS }
1
7,343
`ctx` is unused in rollbackPrimary
pipe-cd-pipe
go
@@ -40,7 +40,7 @@ const ( // BufferedEventID is the id of the buffered event BufferedEventID int64 = -123 // EmptyEventTaskID is uninitialized id of the task id within event - EmptyEventTaskID int64 = -1234 + EmptyEventTaskID int64 = 0 // TransientEventID is the id of the transient event TransientEventID int64 = -124 // FirstBlobPageToken is the page token identifying the first blob for each history archival
1
// The MIT License // // Copyright (c) 2020 Temporal Technologies Inc. All rights reserved. // // Copyright (c) 2020 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. package common import ( "time" ) const ( // FirstEventID is the id of the first event in the history FirstEventID int64 = 1 // EmptyEventID is the id of the empty event EmptyEventID int64 = -23 // EmptyVersion is used as the default value for failover version when no value is provided EmptyVersion int64 = -24 // EndEventID is the id of the end event, here we use the int64 max EndEventID int64 = 1<<63 - 1 // BufferedEventID is the id of the buffered event BufferedEventID int64 = -123 // EmptyEventTaskID is uninitialized id of the task id within event EmptyEventTaskID int64 = -1234 // TransientEventID is the id of the transient event TransientEventID int64 = -124 // FirstBlobPageToken is the page token identifying the first blob for each history archival FirstBlobPageToken = 1 // LastBlobNextPageToken is the next page token on the last blob for each history archival LastBlobNextPageToken = -1 // EndMessageID is the id of the end message, here we use the int64 max EndMessageID int64 = 1<<63 - 1 ) const ( // FrontendServiceName is the name of the frontend service FrontendServiceName = "frontend" // HistoryServiceName is the name of the history service HistoryServiceName = "history" // MatchingServiceName is the name of the matching service MatchingServiceName = "matching" // WorkerServiceName is the name of the worker service WorkerServiceName = "worker" ) // MaxTaskTimeout is maximum task timeout allowed. 366 days in seconds const MaxTaskTimeout = MaxTaskTimeoutSeconds * time.Second const MaxTaskTimeoutSeconds = 31622400 const ( // GetHistoryMaxPageSize is the max page size for get history GetHistoryMaxPageSize = 1000 // ReadDLQMessagesPageSize is the max page size for read DLQ messages ReadDLQMessagesPageSize = 1000 ) const ( // VisibilityAppName is used to find kafka topics and ES indexName for visibility VisibilityAppName = "visibility" ) // This was flagged by salus as potentially hardcoded credentials. This is a false positive by the scanner and should be // disregarded. // #nosec const ( // SystemGlobalNamespace is global namespace name for temporal system workflows running globally SystemGlobalNamespace = "temporal-system-global" // SystemLocalNamespace is namespace name for temporal system workflows running in local cluster SystemLocalNamespace = "temporal-system" // SystemNamespaceID is namespace id for all temporal system workflows SystemNamespaceID = "32049b68-7872-4094-8e63-d0dd59896a83" // SystemNamespaceRetentionDays is retention config for all temporal system workflows SystemNamespaceRetentionDays = time.Hour * 24 * 7 // DefaultAdminOperationToken is the default dynamic config value for AdminOperationToken DefaultAdminOperationToken = "TemporalTeamONLY" ) const ( // MinLongPollTimeout is the minimum context timeout for long poll API, below which // the request won't be processed MinLongPollTimeout = time.Second * 2 // CriticalLongPollTimeout is a threshold for the context timeout passed into long poll API, // below which a warning will be logged CriticalLongPollTimeout = time.Second * 20 // MaxWorkflowRetentionPeriod is the maximum of workflow retention when registering namespace // !!! Do NOT simply decrease this number, because it is being used by history scavenger to avoid race condition against history archival. // Check more details in history scanner(scavenger) MaxWorkflowRetentionPeriod = 30 * time.Hour * 24 ) const ( // DefaultTransactionSizeLimit is the largest allowed transaction size to persistence DefaultTransactionSizeLimit = 14 * 1024 * 1024 ) const ( // ArchivalEnabled is the state for enabling archival ArchivalEnabled = "enabled" // ArchivalDisabled is the state for disabling archival ArchivalDisabled = "disabled" // ArchivalPaused is the state for pausing archival ArchivalPaused = "paused" ) // enum for dynamic config AdvancedVisibilityWritingMode const ( // AdvancedVisibilityWritingModeOff means do not write to advanced visibility store AdvancedVisibilityWritingModeOff = "off" // AdvancedVisibilityWritingModeOn means only write to advanced visibility store AdvancedVisibilityWritingModeOn = "on" // AdvancedVisibilityWritingModeDual means write to both normal visibility and advanced visibility store AdvancedVisibilityWritingModeDual = "dual" )
1
10,002
This is not what title says.
temporalio-temporal
go
@@ -0,0 +1,19 @@ +/** + * BSD-style license; for more info see http://pmd.sourceforge.net/license.html + */ + +package net.sourceforge.pmd.autofix; + +import net.sourceforge.pmd.lang.ast.Node; + +/** + * Classes of this interface must be used when it is desired to make one or more operations to the AST. + */ +public interface RuleViolationFix { + + /** + * Apply one or more operations to a node. + * @param node the node in the AST on which to apply operations + */ + void applyFixesToNode(Node node); +}
1
1
13,445
a fix applies several fixes? maybe this should simply be `applyToNode`
pmd-pmd
java
@@ -25,11 +25,12 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) +// fakeGetClientset gets the cvr clientset func fakeGetClientset() (clientset *clientset.Clientset, err error) { return &client.Clientset{}, nil } -func fakeListfn(cli *clientset.Clientset, namespace string, opts metav1.ListOptions) (*apis.CStorVolumeReplicaList, error) { +func fakeListOk(cli *clientset.Clientset, namespace string, opts metav1.ListOptions) (*apis.CStorVolumeReplicaList, error) { return &apis.CStorVolumeReplicaList{}, nil }
1
// Copyright © 2018-2019 The OpenEBS Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package v1alpha1 import ( "errors" "reflect" "testing" apis "github.com/openebs/maya/pkg/apis/openebs.io/v1alpha1" client "github.com/openebs/maya/pkg/client/generated/clientset/versioned" clientset "github.com/openebs/maya/pkg/client/generated/clientset/versioned" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) func fakeGetClientset() (clientset *clientset.Clientset, err error) { return &client.Clientset{}, nil } func fakeListfn(cli *clientset.Clientset, namespace string, opts metav1.ListOptions) (*apis.CStorVolumeReplicaList, error) { return &apis.CStorVolumeReplicaList{}, nil } func fakeListErrfn(cli *clientset.Clientset, namespace string, opts metav1.ListOptions) (*apis.CStorVolumeReplicaList, error) { return &apis.CStorVolumeReplicaList{}, errors.New("some error") } func fakeSetClientset(k *kubeclient) { k.clientset = &client.Clientset{} } func fakeSetNilClientset(k *kubeclient) { k.clientset = nil } func fakeGetNilErrClientSet() (clientset *clientset.Clientset, err error) { return nil, nil } func fakeGetErrClientSet() (clientset *clientset.Clientset, err error) { return nil, errors.New("Some error") } func fakeClientSet(k *kubeclient) {} func TestKubernetesWithDefaults(t *testing.T) { tests := map[string]struct { expectListFn, expectGetClientset bool }{ "When mockclient is empty": {true, true}, "When mockclient contains getClientsetFn": {false, true}, "When mockclient contains ListFn": {true, false}, "When mockclient contains both": {true, true}, } for name, mock := range tests { t.Run(name, func(t *testing.T) { fc := &kubeclient{} if !mock.expectListFn { fc.list = fakeListfn } if !mock.expectGetClientset { fc.getClientset = fakeGetClientset } fc.withDefaults() if mock.expectListFn && fc.list == nil { t.Fatalf("test %q failed: expected fc.list not to be empty", name) } if mock.expectGetClientset && fc.getClientset == nil { t.Fatalf("test %q failed: expected fc.getClientset not to be empty", name) } }) } } func TestKubernetesWithKubeClient(t *testing.T) { tests := map[string]struct { Clientset *client.Clientset expectKubeClientEmpty bool }{ "Clientset is empty": {nil, true}, "Clientset is not empty": {&client.Clientset{}, false}, } for name, mock := range tests { t.Run(name, func(t *testing.T) { h := WithKubeClient(mock.Clientset) fake := &kubeclient{} h(fake) if mock.expectKubeClientEmpty && fake.clientset != nil { t.Fatalf("test %q failed expected fake.clientset to be empty", name) } if !mock.expectKubeClientEmpty && fake.clientset == nil { t.Fatalf("test %q failed expected fake.clientset not to be empty", name) } }) } } func TestKubernetesKubeClient(t *testing.T) { tests := map[string]struct { expectClientSet bool opts []kubeclientBuildOption }{ "Positive 1": {true, []kubeclientBuildOption{fakeSetClientset}}, "Positive 2": {true, []kubeclientBuildOption{fakeSetClientset, fakeClientSet}}, "Positive 3": {true, []kubeclientBuildOption{fakeSetClientset, fakeClientSet, fakeClientSet}}, "Negative 1": {false, []kubeclientBuildOption{fakeSetNilClientset}}, "Negative 2": {false, []kubeclientBuildOption{fakeSetNilClientset, fakeClientSet}}, "Negative 3": {false, []kubeclientBuildOption{fakeSetNilClientset, fakeClientSet, fakeClientSet}}, } for name, mock := range tests { t.Run(name, func(t *testing.T) { c := KubeClient(mock.opts...) if !mock.expectClientSet && c.clientset != nil { t.Fatalf("test %q failed expected fake.clientset to be empty", name) } if mock.expectClientSet && c.clientset == nil { t.Fatalf("test %q failed expected fake.clientset not to be empty", name) } }) } } func TesKubernetestGetClientOrCached(t *testing.T) { tests := map[string]struct { expectErr bool KubeClient *kubeclient }{ // Positive tests "Positive 1": {false, &kubeclient{nil, "", fakeGetNilErrClientSet, fakeListfn}}, "Positive 2": {false, &kubeclient{&client.Clientset{}, "", fakeGetNilErrClientSet, fakeListfn}}, // Negative tests "Negative 1": {true, &kubeclient{nil, "", fakeGetErrClientSet, fakeListfn}}, } for name, mock := range tests { t.Run(name, func(t *testing.T) { c, err := mock.KubeClient.getClientOrCached() if mock.expectErr && err == nil { t.Fatalf("test %q failed : expected error not to be nil but got %v", name, err) } if !reflect.DeepEqual(c, mock.KubeClient.clientset) { t.Fatalf("test %q failed : expected clientset %v but got %v", name, mock.KubeClient.clientset, c) } }) } } func TestKubenetesList(t *testing.T) { tests := map[string]struct { getClientset getClientsetFn list listFn expectErr bool }{ "Test 1": {fakeGetErrClientSet, fakeListfn, true}, "Test 2": {fakeGetClientset, fakeListfn, false}, "Test 3": {fakeGetClientset, fakeListErrfn, true}, } for name, mock := range tests { t.Run(name, func(t *testing.T) { k := kubeclient{getClientset: mock.getClientset, list: mock.list} _, err := k.List(metav1.ListOptions{}) if mock.expectErr && err == nil { t.Fatalf("Test %q failed: expected error not to be nil", name) } if !mock.expectErr && err != nil { t.Fatalf("Test %q failed: expected error to be nil", name) } }) } }
1
16,162
U1000: func `fakeGetOk` is unused (from `unused`)
openebs-maya
go
@@ -18,6 +18,8 @@ import ( "errors" "fmt" + "k8s.io/client-go/util/retry" + "github.com/hashicorp/go-multierror" "golang.org/x/sync/errgroup" v1 "k8s.io/api/core/v1"
1
// Copyright 2019 Chaos Mesh Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // See the License for the specific language governing permissions and // limitations under the License. package podfailure import ( "context" "errors" "fmt" "github.com/hashicorp/go-multierror" "golang.org/x/sync/errgroup" v1 "k8s.io/api/core/v1" k8serror "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" "k8s.io/client-go/tools/cache" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" "github.com/chaos-mesh/chaos-mesh/api/v1alpha1" "github.com/chaos-mesh/chaos-mesh/controllers/common" "github.com/chaos-mesh/chaos-mesh/controllers/config" "github.com/chaos-mesh/chaos-mesh/pkg/router" ctx "github.com/chaos-mesh/chaos-mesh/pkg/router/context" end "github.com/chaos-mesh/chaos-mesh/pkg/router/endpoint" "github.com/chaos-mesh/chaos-mesh/pkg/utils" ) const ( // Always fails a container pauseImage = "gcr.io/google-containers/pause:latest" podFailureActionMsg = "pod failure duration %s" ) type endpoint struct { ctx.Context } // Object implements the reconciler.InnerReconciler.Object func (r *endpoint) Object() v1alpha1.InnerObject { return &v1alpha1.PodChaos{} } // Apply implements the reconciler.InnerReconciler.Apply func (r *endpoint) Apply(ctx context.Context, req ctrl.Request, chaos v1alpha1.InnerObject) error { podchaos, ok := chaos.(*v1alpha1.PodChaos) if !ok { err := errors.New("chaos is not PodChaos") r.Log.Error(err, "chaos is not PodChaos", "chaos", chaos) return err } pods, err := utils.SelectAndFilterPods(ctx, r.Client, r.Reader, &podchaos.Spec, config.ControllerCfg.ClusterScoped, config.ControllerCfg.TargetNamespace, config.ControllerCfg.AllowedNamespaces, config.ControllerCfg.IgnoredNamespaces) if err != nil { r.Log.Error(err, "failed to select and filter pods") return err } err = r.failAllPods(ctx, pods, podchaos) if err != nil { return err } podchaos.Status.Experiment.PodRecords = make([]v1alpha1.PodStatus, 0, len(pods)) for _, pod := range pods { ps := v1alpha1.PodStatus{ Namespace: pod.Namespace, Name: pod.Name, HostIP: pod.Status.HostIP, PodIP: pod.Status.PodIP, Action: string(podchaos.Spec.Action), } if podchaos.Spec.Duration != nil { ps.Message = fmt.Sprintf(podFailureActionMsg, *podchaos.Spec.Duration) } podchaos.Status.Experiment.PodRecords = append(podchaos.Status.Experiment.PodRecords, ps) } r.Event(podchaos, v1.EventTypeNormal, utils.EventChaosInjected, "") return nil } // Recover implements the reconciler.InnerReconciler.Recover func (r *endpoint) Recover(ctx context.Context, req ctrl.Request, obj v1alpha1.InnerObject) error { podchaos, ok := obj.(*v1alpha1.PodChaos) if !ok { err := errors.New("chaos is not PodChaos") r.Log.Error(err, "chaos is not PodChaos", "chaos", obj) return err } if err := r.cleanFinalizersAndRecover(ctx, podchaos); err != nil { return err } r.Event(podchaos, v1.EventTypeNormal, utils.EventChaosRecovered, "") return nil } func (r *endpoint) cleanFinalizersAndRecover(ctx context.Context, podchaos *v1alpha1.PodChaos) error { var result error for _, key := range podchaos.Finalizers { ns, name, err := cache.SplitMetaNamespaceKey(key) if err != nil { result = multierror.Append(result, err) continue } var pod v1.Pod err = r.Client.Get(ctx, types.NamespacedName{ Namespace: ns, Name: name, }, &pod) if err != nil { if !k8serror.IsNotFound(err) { result = multierror.Append(result, err) continue } r.Log.Info("Pod not found", "namespace", ns, "name", name) podchaos.Finalizers = utils.RemoveFromFinalizer(podchaos.Finalizers, key) continue } err = r.recoverPod(ctx, &pod, podchaos) if err != nil { result = multierror.Append(result, err) continue } podchaos.Finalizers = utils.RemoveFromFinalizer(podchaos.Finalizers, key) } if podchaos.Annotations[common.AnnotationCleanFinalizer] == common.AnnotationCleanFinalizerForced { r.Log.Info("Force cleanup all finalizers", "chaos", podchaos) podchaos.Finalizers = podchaos.Finalizers[:0] return nil } return result } func (r *endpoint) failAllPods(ctx context.Context, pods []v1.Pod, podchaos *v1alpha1.PodChaos) error { g := errgroup.Group{} for index := range pods { pod := &pods[index] key, err := cache.MetaNamespaceKeyFunc(pod) if err != nil { return err } podchaos.Finalizers = utils.InsertFinalizer(podchaos.Finalizers, key) g.Go(func() error { return r.failPod(ctx, pod, podchaos) }) } return g.Wait() } func (r *endpoint) failPod(ctx context.Context, pod *v1.Pod, podchaos *v1alpha1.PodChaos) error { r.Log.Info("Try to inject pod-failure", "namespace", pod.Namespace, "name", pod.Name) // TODO: check the annotations or others in case that this pod is used by other chaos for index := range pod.Spec.InitContainers { originImage := pod.Spec.InitContainers[index].Image name := pod.Spec.InitContainers[index].Name key := utils.GenAnnotationKeyForImage(podchaos, name) if pod.Annotations == nil { pod.Annotations = make(map[string]string) } // If the annotation is already existed, we could skip the reconcile for this container if _, ok := pod.Annotations[key]; ok { continue } pod.Annotations[key] = originImage pod.Spec.InitContainers[index].Image = pauseImage } for index := range pod.Spec.Containers { originImage := pod.Spec.Containers[index].Image name := pod.Spec.Containers[index].Name key := utils.GenAnnotationKeyForImage(podchaos, name) if pod.Annotations == nil { pod.Annotations = make(map[string]string) } // If the annotation is already existed, we could skip the reconcile for this container if _, ok := pod.Annotations[key]; ok { continue } pod.Annotations[key] = originImage pod.Spec.Containers[index].Image = pauseImage } if err := r.Update(ctx, pod); err != nil { r.Log.Error(err, "unable to use fake image on pod") return err } ps := v1alpha1.PodStatus{ Namespace: pod.Namespace, Name: pod.Name, HostIP: pod.Status.HostIP, PodIP: pod.Status.PodIP, Action: string(podchaos.Spec.Action), } if podchaos.Spec.Duration != nil { ps.Message = fmt.Sprintf(podFailureActionMsg, *podchaos.Spec.Duration) } podchaos.Status.Experiment.PodRecords = append(podchaos.Status.Experiment.PodRecords, ps) return nil } func (r *endpoint) recoverPod(ctx context.Context, pod *v1.Pod, podchaos *v1alpha1.PodChaos) error { r.Log.Info("Recovering", "namespace", pod.Namespace, "name", pod.Name) for index := range pod.Spec.Containers { name := pod.Spec.Containers[index].Name _ = utils.GenAnnotationKeyForImage(podchaos, name) if pod.Annotations == nil { pod.Annotations = make(map[string]string) } // FIXME: Check annotations and return error. } // chaos-mesh don't support return r.Delete(ctx, pod, &client.DeleteOptions{ GracePeriodSeconds: new(int64), // PeriodSeconds has to be set specifically }) } func init() { router.Register("podchaos", &v1alpha1.PodChaos{}, func(obj runtime.Object) bool { chaos, ok := obj.(*v1alpha1.PodChaos) if !ok { return false } return chaos.Spec.Action == v1alpha1.PodFailureAction }, func(ctx ctx.Context) end.Endpoint { return &endpoint{ Context: ctx, } }) }
1
19,137
Because there is a "k8s.io/client-go/tools/cache" below, we can sort out all the "imports" here.
chaos-mesh-chaos-mesh
go
@@ -3,7 +3,9 @@ package api import ( + "github.com/aws/aws-sdk-go/aws" "fmt" + "encoding/json" "reflect" "sort" "strings"
1
// +build codegen package api import ( "fmt" "reflect" "sort" "strings" ) // ShapeValueBuilder provides the logic to build the nested values for a shape. type ShapeValueBuilder struct{} // BuildShape will recursively build the referenced shape based on the json // object provided. isMap will dictate how the field name is specified. If // isMap is true, we will expect the member name to be quotes like "Foo". func (b ShapeValueBuilder) BuildShape(ref *ShapeRef, shapes map[string]interface{}, isMap bool) string { order := make([]string, len(shapes)) for k := range shapes { order = append(order, k) } sort.Strings(order) ret := "" for _, name := range order { if name == "" { continue } shape := shapes[name] // If the shape isn't a map, we want to export the value, since every field // defined in our shapes are exported. if len(name) > 0 && !isMap && strings.ToLower(name[0:1]) == name[0:1] { name = strings.Title(name) } memName := name passRef := ref.Shape.MemberRefs[name] if isMap { memName = fmt.Sprintf("%q", memName) passRef = &ref.Shape.ValueRef } switch v := shape.(type) { case map[string]interface{}: ret += b.BuildComplex(name, memName, passRef, v) case []interface{}: ret += b.BuildList(name, memName, passRef, v) default: ret += b.BuildScalar(name, memName, passRef, v, ref.Shape.Payload == name) } } return ret } // BuildList will construct a list shape based off the service's definition of // that list. func (b ShapeValueBuilder) BuildList(name, memName string, ref *ShapeRef, v []interface{}) string { ret := "" if len(v) == 0 || ref == nil { return "" } passRef := &ref.Shape.MemberRef ret += fmt.Sprintf("%s: %s {\n", memName, b.GoType(ref, false)) ret += b.buildListElements(passRef, v) ret += "},\n" return ret } func (b ShapeValueBuilder) buildListElements(ref *ShapeRef, v []interface{}) string { if len(v) == 0 || ref == nil { return "" } ret := "" format := "" isComplex := false isList := false // get format for atomic type. If it is not an atomic type, // get the element. switch v[0].(type) { case string: format = "%s" case bool: format = "%t" case float64: switch ref.Shape.Type { case "integer", "int64", "long": format = "%d" default: format = "%f" } case []interface{}: isList = true case map[string]interface{}: isComplex = true } for _, elem := range v { if isComplex { ret += fmt.Sprintf("{\n%s\n},\n", b.BuildShape(ref, elem.(map[string]interface{}), ref.Shape.Type == "map")) } else if isList { ret += fmt.Sprintf("{\n%s\n},\n", b.buildListElements(&ref.Shape.MemberRef, elem.([]interface{}))) } else { switch ref.Shape.Type { case "integer", "int64", "long": elem = int(elem.(float64)) } ret += fmt.Sprintf("%s,\n", getValue(ref.Shape.Type, fmt.Sprintf(format, elem))) } } return ret } // BuildScalar will build atomic Go types. func (b ShapeValueBuilder) BuildScalar(name, memName string, ref *ShapeRef, shape interface{}, isPayload bool) string { if ref == nil || ref.Shape == nil { return "" } switch v := shape.(type) { case bool: return convertToCorrectType(memName, ref.Shape.Type, fmt.Sprintf("%t", v)) case int: if ref.Shape.Type == "timestamp" { return parseTimeString(ref, memName, fmt.Sprintf("%d", v)) } return convertToCorrectType(memName, ref.Shape.Type, fmt.Sprintf("%d", v)) case float64: dataType := ref.Shape.Type if dataType == "integer" || dataType == "int64" || dataType == "long" { return convertToCorrectType(memName, ref.Shape.Type, fmt.Sprintf("%d", int(shape.(float64)))) } return convertToCorrectType(memName, ref.Shape.Type, fmt.Sprintf("%f", v)) case string: t := ref.Shape.Type switch t { case "timestamp": return parseTimeString(ref, memName, fmt.Sprintf("%s", v)) case "blob": if (ref.Streaming || ref.Shape.Streaming) && isPayload { return fmt.Sprintf("%s: aws.ReadSeekCloser(strings.NewReader(%q)),\n", memName, v) } return fmt.Sprintf("%s: []byte(%q),\n", memName, v) default: return convertToCorrectType(memName, t, v) } default: panic(fmt.Errorf("Unsupported scalar type: %v", reflect.TypeOf(v))) } } // BuildComplex will build the shape's value for complex types such as structs, // and maps. func (b ShapeValueBuilder) BuildComplex(name, memName string, ref *ShapeRef, v map[string]interface{}) string { switch ref.Shape.Type { case "structure": return fmt.Sprintf(`%s: &%s{ %s }, `, memName, b.GoType(ref, true), b.BuildShape(ref, v, false)) case "map": return fmt.Sprintf(`%s: %s{ %s }, `, name, b.GoType(ref, false), b.BuildShape(ref, v, true)) default: panic(fmt.Sprintf("Expected complex type but received %q", ref.Shape.Type)) } } // GoType returns the string of the shape's Go type identifier. func (b ShapeValueBuilder) GoType(ref *ShapeRef, elem bool) string { if ref.Shape.Type != "structure" && ref.Shape.Type != "list" && ref.Shape.Type != "map" { // Scalars are always pointers. return ref.GoTypeWithPkgName() } prefix := "" if ref.Shape.Type == "list" { ref = &ref.Shape.MemberRef prefix = "[]" } if elem { return prefix + ref.Shape.GoTypeWithPkgNameElem() } return prefix + ref.GoTypeWithPkgName() }
1
9,800
Nit should be using `goimports` to format the import statements with standard libary imports first, new line, followed by non-standard library imports.
aws-aws-sdk-go
go
@@ -118,8 +118,10 @@ func (o *deletePipelineOpts) Ask() error { // Execute deletes the secret and pipeline stack. func (o *deletePipelineOpts) Execute() error { - if err := o.deleteSecret(); err != nil { - return err + if o.PipelineSecret != "" { + if err := o.deleteSecret(); err != nil { + return err + } } if err := o.deleteStack(); err != nil {
1
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package cli import ( "errors" "fmt" "github.com/aws/copilot-cli/internal/pkg/aws/secretsmanager" "github.com/aws/copilot-cli/internal/pkg/aws/sessions" "github.com/aws/copilot-cli/internal/pkg/deploy/cloudformation" "github.com/aws/copilot-cli/internal/pkg/manifest" "github.com/aws/copilot-cli/internal/pkg/term/log" termprogress "github.com/aws/copilot-cli/internal/pkg/term/progress" "github.com/aws/copilot-cli/internal/pkg/term/prompt" "github.com/aws/copilot-cli/internal/pkg/workspace" "github.com/spf13/cobra" ) const ( pipelineDeleteConfirmPrompt = "Are you sure you want to delete pipeline %s from application %s?" pipelineDeleteConfirmHelp = "This will delete the deployment pipeline for the services in the workspace." pipelineSecretDeleteConfirmPrompt = "Are you sure you want to delete the source secret %s associated with pipeline %s?" pipelineDeleteSecretConfirmHelp = "This will delete the token associated with the source of your pipeline." fmtDeletePipelineStart = "Deleting pipeline %s from application %s." fmtDeletePipelineFailed = "Failed to delete pipeline %s from application %s: %v.\n" fmtDeletePipelineComplete = "Deleted pipeline %s from application %s.\n" ) var ( errPipelineDeleteCancelled = errors.New("pipeline delete cancelled - no changes made") ) type deletePipelineVars struct { appName string skipConfirmation bool shouldDeleteSecret bool } type deletePipelineOpts struct { deletePipelineVars PipelineName string PipelineSecret string // Interfaces to dependencies pipelineDeployer pipelineDeployer prog progress prompt prompter secretsmanager secretsManager ws wsPipelineReader } func newDeletePipelineOpts(vars deletePipelineVars) (*deletePipelineOpts, error) { ws, err := workspace.New() if err != nil { return nil, fmt.Errorf("new workspace client: %w", err) } secretsmanager, err := secretsmanager.New() if err != nil { return nil, fmt.Errorf("new secrets manager client: %w", err) } defaultSess, err := sessions.NewProvider().Default() if err != nil { return nil, fmt.Errorf("default session: %w", err) } opts := &deletePipelineOpts{ deletePipelineVars: vars, prog: termprogress.NewSpinner(log.DiagnosticWriter), prompt: prompt.New(), secretsmanager: secretsmanager, pipelineDeployer: cloudformation.New(defaultSess), ws: ws, } return opts, nil } // Validate returns an error if the flag values passed by the user are invalid. func (o *deletePipelineOpts) Validate() error { if o.appName == "" { return errNoAppInWorkspace } if err := o.readPipelineManifest(); err != nil { return err } return nil } // Ask prompts for fields that are required but not passed in. func (o *deletePipelineOpts) Ask() error { if o.skipConfirmation { return nil } deleteConfirmed, err := o.prompt.Confirm( fmt.Sprintf(pipelineDeleteConfirmPrompt, o.PipelineName, o.appName), pipelineDeleteConfirmHelp) if err != nil { return fmt.Errorf("pipeline delete confirmation prompt: %w", err) } if !deleteConfirmed { return errPipelineDeleteCancelled } return nil } // Execute deletes the secret and pipeline stack. func (o *deletePipelineOpts) Execute() error { if err := o.deleteSecret(); err != nil { return err } if err := o.deleteStack(); err != nil { return err } return nil } func (o *deletePipelineOpts) readPipelineManifest() error { data, err := o.ws.ReadPipelineManifest() if err != nil { if err == workspace.ErrNoPipelineInWorkspace { return err } return fmt.Errorf("read pipeline manifest: %w", err) } pipeline, err := manifest.UnmarshalPipeline(data) if err != nil { return fmt.Errorf("unmarshal pipeline manifest: %w", err) } o.PipelineName = pipeline.Name if secret, ok := (pipeline.Source.Properties["access_token_secret"]).(string); ok { o.PipelineSecret = secret } return nil } func (o *deletePipelineOpts) deleteSecret() error { if !o.shouldDeleteSecret { confirmDeletion, err := o.prompt.Confirm( fmt.Sprintf(pipelineSecretDeleteConfirmPrompt, o.PipelineSecret, o.PipelineName), pipelineDeleteSecretConfirmHelp, ) if err != nil { return fmt.Errorf("pipeline delete secret confirmation prompt: %w", err) } if !confirmDeletion { log.Infof("Skipping deletion of secret %s.\n", o.PipelineSecret) return nil } } if err := o.secretsmanager.DeleteSecret(o.PipelineSecret); err != nil { return err } log.Successf("Deleted secret %s.\n", o.PipelineSecret) return nil } func (o *deletePipelineOpts) deleteStack() error { o.prog.Start(fmt.Sprintf(fmtDeletePipelineStart, o.PipelineName, o.appName)) if err := o.pipelineDeployer.DeletePipeline(o.PipelineName); err != nil { o.prog.Stop(log.Serrorf(fmtDeletePipelineFailed, o.PipelineName, o.appName, err)) return err } o.prog.Stop(log.Ssuccessf(fmtDeletePipelineComplete, o.PipelineName, o.appName)) return nil } // RecommendedActions is a no-op for this command. func (o *deletePipelineOpts) RecommendedActions() []string { return nil } // Run validates user input, asks for any missing flags, and then executes the command. func (o *deletePipelineOpts) Run() error { if err := o.Validate(); err != nil { return err } if err := o.Ask(); err != nil { return err } if err := o.Execute(); err != nil { return err } return nil } // buildPipelineDeleteCmd build the command for deleting an existing pipeline. func buildPipelineDeleteCmd() *cobra.Command { vars := deletePipelineVars{} cmd := &cobra.Command{ Use: "delete", Short: "Deletes the pipeline associated with your workspace.", Example: ` Delete the pipeline associated with your workspace. /code $ copilot pipeline delete`, RunE: runCmdE(func(cmd *cobra.Command, args []string) error { opts, err := newDeletePipelineOpts(vars) if err != nil { return err } return opts.Run() }), } cmd.Flags().StringVarP(&vars.appName, appFlag, appFlagShort, tryReadingAppName(), appFlagDescription) cmd.Flags().BoolVar(&vars.skipConfirmation, yesFlag, false, yesFlagDescription) cmd.Flags().BoolVar(&vars.shouldDeleteSecret, deleteSecretFlag, false, deleteSecretFlagDescription) return cmd }
1
16,268
Do we not have tests for pipeline delete
aws-copilot-cli
go
@@ -146,6 +146,12 @@ class HdfsClient(hdfs_abstract_client.HdfsFileSystem): def put(self, local_path, destination): self.call_check(load_hadoop_cmd() + ['fs', '-put', local_path, destination]) + def append(self, local_path, destination): + """ + Requires Hadoop >= 2.3.0 + """ + call_check(load_hadoop_cmd() + ['fs', '-appendToFile', local_path, destination]) + def get(self, path, local_destination): self.call_check(load_hadoop_cmd() + ['fs', '-get', path, local_destination])
1
# -*- coding: utf-8 -*- # # Copyright 2012-2015 Spotify AB # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # """ The implementations of the hdfs clients. The hadoop cli client and the snakebite client. """ from luigi.target import FileAlreadyExists from luigi.contrib.hdfs.config import load_hadoop_cmd from luigi.contrib.hdfs import abstract_client as hdfs_abstract_client from luigi.contrib.hdfs import config as hdfs_config from luigi.contrib.hdfs import error as hdfs_error import logging import subprocess import datetime import os import re import warnings logger = logging.getLogger('luigi-interface') def create_hadoopcli_client(): """ Given that we want one of the hadoop cli clients (unlike snakebite), this one will return the right one. """ version = hdfs_config.get_configured_hadoop_version() if version == "cdh4": return HdfsClient() elif version == "cdh3": return HdfsClientCdh3() elif version == "apache1": return HdfsClientApache1() else: raise ValueError("Error: Unknown version specified in Hadoop version" "configuration parameter") class HdfsClient(hdfs_abstract_client.HdfsFileSystem): """ This client uses Apache 2.x syntax for file system commands, which also matched CDH4. """ recursive_listdir_cmd = ['-ls', '-R'] @staticmethod def call_check(command): p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True, universal_newlines=True) stdout, stderr = p.communicate() if p.returncode != 0: raise hdfs_error.HDFSCliError(command, p.returncode, stdout, stderr) return stdout def exists(self, path): """ Use ``hadoop fs -stat`` to check file existence. """ cmd = load_hadoop_cmd() + ['fs', '-stat', path] logger.debug('Running file existence check: %s', u' '.join(cmd)) p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True, universal_newlines=True) stdout, stderr = p.communicate() if p.returncode == 0: return True else: not_found_pattern = "^.*No such file or directory$" not_found_re = re.compile(not_found_pattern) for line in stderr.split('\n'): if not_found_re.match(line): return False raise hdfs_error.HDFSCliError(cmd, p.returncode, stdout, stderr) def rename(self, path, dest): parent_dir = os.path.dirname(dest) if parent_dir != '' and not self.exists(parent_dir): self.mkdir(parent_dir) if not isinstance(path, (list, tuple)): path = [path] else: warnings.warn("Renaming multiple files at once is not atomic.", stacklevel=2) self.call_check(load_hadoop_cmd() + ['fs', '-mv'] + path + [dest]) def remove(self, path, recursive=True, skip_trash=False): if recursive: cmd = load_hadoop_cmd() + ['fs', '-rm', '-r'] else: cmd = load_hadoop_cmd() + ['fs', '-rm'] if skip_trash: cmd = cmd + ['-skipTrash'] cmd = cmd + [path] self.call_check(cmd) def chmod(self, path, permissions, recursive=False): if recursive: cmd = load_hadoop_cmd() + ['fs', '-chmod', '-R', permissions, path] else: cmd = load_hadoop_cmd() + ['fs', '-chmod', permissions, path] self.call_check(cmd) def chown(self, path, owner, group, recursive=False): if owner is None: owner = '' if group is None: group = '' ownership = "%s:%s" % (owner, group) if recursive: cmd = load_hadoop_cmd() + ['fs', '-chown', '-R', ownership, path] else: cmd = load_hadoop_cmd() + ['fs', '-chown', ownership, path] self.call_check(cmd) def count(self, path): cmd = load_hadoop_cmd() + ['fs', '-count', path] stdout = self.call_check(cmd) lines = stdout.split('\n') for line in stdout.split('\n'): if line.startswith("OpenJDK 64-Bit Server VM warning") or line.startswith("It's highly recommended") or not line: lines.pop(lines.index(line)) else: (dir_count, file_count, content_size, ppath) = stdout.split() results = {'content_size': content_size, 'dir_count': dir_count, 'file_count': file_count} return results def copy(self, path, destination): self.call_check(load_hadoop_cmd() + ['fs', '-cp', path, destination]) def put(self, local_path, destination): self.call_check(load_hadoop_cmd() + ['fs', '-put', local_path, destination]) def get(self, path, local_destination): self.call_check(load_hadoop_cmd() + ['fs', '-get', path, local_destination]) def getmerge(self, path, local_destination, new_line=False): if new_line: cmd = load_hadoop_cmd() + ['fs', '-getmerge', '-nl', path, local_destination] else: cmd = load_hadoop_cmd() + ['fs', '-getmerge', path, local_destination] self.call_check(cmd) def mkdir(self, path, parents=True, raise_if_exists=False): if parents and raise_if_exists: raise NotImplementedError("HdfsClient.mkdir can't raise with -p") try: cmd = (load_hadoop_cmd() + ['fs', '-mkdir'] + (['-p'] if parents else []) + [path]) self.call_check(cmd) except hdfs_error.HDFSCliError as ex: if "File exists" in ex.stderr: if raise_if_exists: raise FileAlreadyExists(ex.stderr) else: raise def listdir(self, path, ignore_directories=False, ignore_files=False, include_size=False, include_type=False, include_time=False, recursive=False): if not path: path = "." # default to current/home catalog if recursive: cmd = load_hadoop_cmd() + ['fs'] + self.recursive_listdir_cmd + [path] else: cmd = load_hadoop_cmd() + ['fs', '-ls', path] lines = self.call_check(cmd).split('\n') for line in lines: if not line: continue elif line.startswith('OpenJDK 64-Bit Server VM warning') or line.startswith('It\'s highly recommended') or line.startswith('Found'): continue # "hadoop fs -ls" outputs "Found %d items" as its first line elif ignore_directories and line[0] == 'd': continue elif ignore_files and line[0] == '-': continue data = line.split(' ') file = data[-1] size = int(data[-4]) line_type = line[0] extra_data = () if include_size: extra_data += (size,) if include_type: extra_data += (line_type,) if include_time: time_str = '%sT%s' % (data[-3], data[-2]) modification_time = datetime.datetime.strptime(time_str, '%Y-%m-%dT%H:%M') extra_data += (modification_time,) if len(extra_data) > 0: yield (file,) + extra_data else: yield file def touchz(self, path): self.call_check(load_hadoop_cmd() + ['fs', '-touchz', path]) class HdfsClientCdh3(HdfsClient): """ This client uses CDH3 syntax for file system commands. """ def mkdir(self, path): """ No -p switch, so this will fail creating ancestors. """ try: self.call_check(load_hadoop_cmd() + ['fs', '-mkdir', path]) except hdfs_error.HDFSCliError as ex: if "File exists" in ex.stderr: raise FileAlreadyExists(ex.stderr) else: raise def remove(self, path, recursive=True, skip_trash=False): if recursive: cmd = load_hadoop_cmd() + ['fs', '-rmr'] else: cmd = load_hadoop_cmd() + ['fs', '-rm'] if skip_trash: cmd = cmd + ['-skipTrash'] cmd = cmd + [path] self.call_check(cmd) class HdfsClientApache1(HdfsClientCdh3): """ This client uses Apache 1.x syntax for file system commands, which are similar to CDH3 except for the file existence check. """ recursive_listdir_cmd = ['-lsr'] def exists(self, path): cmd = load_hadoop_cmd() + ['fs', '-test', '-e', path] p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) stdout, stderr = p.communicate() if p.returncode == 0: return True elif p.returncode == 1: return False else: raise hdfs_error.HDFSCliError(cmd, p.returncode, stdout, stderr)
1
11,932
Good that you mention this constraint in the docstring :)
spotify-luigi
py
@@ -15,8 +15,13 @@ package workflow import ( "encoding/json" + "fmt" "net/http" + ctrl "sigs.k8s.io/controller-runtime" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + "github.com/gin-gonic/gin" "github.com/chaos-mesh/chaos-mesh/api/v1alpha1"
1
// Copyright 2021 Chaos Mesh Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // See the License for the specific language governing permissions and // limitations under the License. package workflow import ( "encoding/json" "net/http" "github.com/gin-gonic/gin" "github.com/chaos-mesh/chaos-mesh/api/v1alpha1" "github.com/chaos-mesh/chaos-mesh/pkg/apiserver/utils" "github.com/chaos-mesh/chaos-mesh/pkg/clientpool" config "github.com/chaos-mesh/chaos-mesh/pkg/config/dashboard" "github.com/chaos-mesh/chaos-mesh/pkg/core" ) // StatusResponse defines a common status struct. type StatusResponse struct { Status string `json:"status"` } func Register(r *gin.RouterGroup, s *Service) { endpoint := r.Group("/workflows") endpoint.GET("", s.listWorkflows) endpoint.POST("", s.createWorkflow) endpoint.GET("/:namespace/:name", s.getWorkflowDetail) endpoint.DELETE("/:namespace/:name", s.deleteWorkflow) endpoint.PUT("/:namespace/:name", s.updateWorkflow) } // Service defines a handler service for workflows. type Service struct { conf *config.ChaosDashboardConfig } func NewService(conf *config.ChaosDashboardConfig) *Service { return &Service{ conf: conf, } } func NewServiceWithKubeRepo(conf *config.ChaosDashboardConfig) *Service { return NewService(conf) } // @Summary List workflows from Kubernetes cluster. // @Description List workflows from Kubernetes cluster. // @Tags workflows // @Produce json // @Param namespace query string false "namespace, given empty string means list from all namespace" // @Param status query string false "status" Enums(Initializing, Running, Errored, Finished) // @Success 200 {array} core.Workflow // @Router /workflows [get] // @Failure 500 {object} utils.APIError func (it *Service) listWorkflows(c *gin.Context) { namespace := c.Query("namespace") if len(namespace) == 0 && !it.conf.ClusterScoped && len(it.conf.TargetNamespace) != 0 { namespace = it.conf.TargetNamespace } result := make([]core.Workflow, 0) kubeClient, err := clientpool.ExtractTokenAndGetClient(c.Request.Header) if err != nil { _ = c.Error(utils.ErrInvalidRequest.WrapWithNoMessage(err)) return } repo := core.NewKubeWorkflowRepository(kubeClient) if namespace != "" { workflowFromNs, err := repo.ListByNamespace(c.Request.Context(), namespace) if err != nil { utils.SetErrorForGinCtx(c, err) return } result = append(result, workflowFromNs...) } else { allWorkflow, err := repo.List(c.Request.Context()) if err != nil { utils.SetErrorForGinCtx(c, err) return } result = append(result, allWorkflow...) } c.JSON(http.StatusOK, result) } // @Summary Get detailed information about the specified workflow. // @Description Get detailed information about the specified workflow. // @Tags workflows // @Produce json // @Param namespace path string true "namespace" // @Param name path string true "name" // @Router /workflows/{namespace}/{name} [GET] // @Success 200 {object} core.WorkflowDetail // @Failure 400 {object} utils.APIError // @Failure 500 {object} utils.APIError func (it *Service) getWorkflowDetail(c *gin.Context) { namespace := c.Param("namespace") name := c.Param("name") kubeClient, err := clientpool.ExtractTokenAndGetClient(c.Request.Header) if err != nil { _ = c.Error(utils.ErrInvalidRequest.WrapWithNoMessage(err)) return } repo := core.NewKubeWorkflowRepository(kubeClient) result, err := repo.Get(c.Request.Context(), namespace, name) if err != nil { utils.SetErrorForGinCtx(c, err) return } c.JSON(http.StatusOK, result) } // @Summary Create a new workflow. // @Description Create a new workflow. // @Tags workflows // @Produce json // @Param request body v1alpha1.Workflow true "Request body" // @Success 200 {object} core.WorkflowDetail // @Failure 400 {object} utils.APIError // @Failure 500 {object} utils.APIError // @Router /workflows/new [post] func (it *Service) createWorkflow(c *gin.Context) { payload := v1alpha1.Workflow{} err := json.NewDecoder(c.Request.Body).Decode(&payload) if err != nil { _ = c.Error(utils.ErrInternalServer.Wrap(err, "failed to parse request body")) return } kubeClient, err := clientpool.ExtractTokenAndGetClient(c.Request.Header) if err != nil { _ = c.Error(utils.ErrInvalidRequest.WrapWithNoMessage(err)) return } repo := core.NewKubeWorkflowRepository(kubeClient) result, err := repo.Create(c.Request.Context(), payload) if err != nil { _ = c.Error(utils.ErrInternalServer.WrapWithNoMessage(err)) return } c.JSON(http.StatusOK, result) } // @Summary Delete the specified workflow. // @Description Delete the specified workflow. // @Tags workflows // @Produce json // @Param namespace path string true "namespace" // @Param name path string true "name" // @Success 200 {object} StatusResponse // @Failure 400 {object} utils.APIError // @Failure 404 {object} utils.APIError // @Failure 500 {object} utils.APIError // @Router /workflows/{namespace}/{name} [delete] func (it *Service) deleteWorkflow(c *gin.Context) { namespace := c.Param("namespace") name := c.Param("name") kubeClient, err := clientpool.ExtractTokenAndGetClient(c.Request.Header) if err != nil { _ = c.Error(utils.ErrInvalidRequest.WrapWithNoMessage(err)) return } repo := core.NewKubeWorkflowRepository(kubeClient) err = repo.Delete(c.Request.Context(), namespace, name) if err != nil { utils.SetErrorForGinCtx(c, err) return } c.JSON(http.StatusOK, StatusResponse{Status: "success"}) } // @Summary Update a workflow. // @Description Update a workflow. // @Tags workflows // @Produce json // @Param request body v1alpha1.Workflow true "Request body" // @Success 200 {object} core.WorkflowDetail // @Failure 400 {object} utils.APIError // @Failure 500 {object} utils.APIError // @Router /workflows/update [put] func (it *Service) updateWorkflow(c *gin.Context) { payload := v1alpha1.Workflow{} err := json.NewDecoder(c.Request.Body).Decode(&payload) if err != nil { _ = c.Error(utils.ErrInternalServer.Wrap(err, "failed to parse request body")) return } // validate the consistent with path parameter and request body of namespace and name namespace := c.Param("namespace") name := c.Param("name") if namespace != payload.Namespace { _ = c.Error(utils.ErrInvalidRequest.Wrap(err, "namespace is not consistent, pathParameter: %s, metaInRaw: %s", namespace, payload.Namespace), ) return } if name != payload.Name { _ = c.Error(utils.ErrInvalidRequest.Wrap(err, "name is not consistent, pathParameter: %s, metaInRaw: %s", name, payload.Name), ) return } kubeClient, err := clientpool.ExtractTokenAndGetClient(c.Request.Header) if err != nil { _ = c.Error(utils.ErrInvalidRequest.WrapWithNoMessage(err)) return } repo := core.NewKubeWorkflowRepository(kubeClient) result, err := repo.Update(c.Request.Context(), namespace, name, payload) if err != nil { _ = c.Error(utils.ErrInternalServer.WrapWithNoMessage(err)) return } c.JSON(http.StatusOK, result) }
1
22,634
remove this blank?
chaos-mesh-chaos-mesh
go
@@ -9515,7 +9515,8 @@ FileScan::FileScan(const CorrName& tableName, estRowsAccessed_ (0), mdamFlag_(UNDECIDED), skipRowsToPreventHalloween_(FALSE), - doUseSearchKey_(TRUE) + doUseSearchKey_(TRUE), + computedNumOfActivePartiions_(-1) { // Set the filescan properties:
1
/*********************************************************************** // @@@ START COPYRIGHT @@@ // // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // // @@@ END COPYRIGHT @@@ **********************************************************************/ /* -*-C++-*- ****************************************************************************** * * File: RelExpr.C * Description: Relational expressions (both physical and logical operators) * Created: 5/17/94 * Language: C++ * * ****************************************************************************** */ #define SQLPARSERGLOBALS_FLAGS // must precede all #include's #define SQLPARSERGLOBALS_NADEFAULTS #include "Debug.h" #include "Sqlcomp.h" #include "AllRelExpr.h" #include "AllItemExpr.h" #include "GroupAttr.h" #include "opt.h" #include "PhyProp.h" #include "mdam.h" #include "ControlDB.h" #include "disjuncts.h" #include "ScanOptimizer.h" #include "CmpContext.h" #include "StmtDDLCreateTrigger.h" #include "ExpError.h" #include "ComTransInfo.h" #include "BindWA.h" #include "Refresh.h" #include "CmpMain.h" #include "ControlDB.h" #include "ElemDDLColDef.h" #include "Analyzer.h" #include "OptHints.h" #include "ComTdbSendTop.h" #include "DatetimeType.h" #include "SequenceGeneratorAttributes.h" #include "SqlParserGlobals.h" #include "AppliedStatMan.h" #include "Generator.h" #include "CmpStatement.h" #define TEXT_DISPLAY_LENGTH 1001 // ---------------------------------------------------------------------- // forward declarations // ---------------------------------------------------------------------- // ----------------------------------------------------------------------- // methods for class ExprGroupId // ----------------------------------------------------------------------- ExprGroupId::ExprGroupId() { groupIdMode_ = STANDALONE; node_ = NULL; groupId_ = INVALID_GROUP_ID; } ExprGroupId::ExprGroupId(const ExprGroupId & other) { groupIdMode_ = other.groupIdMode_; node_ = other.node_; groupId_ = other.groupId_; } ExprGroupId::ExprGroupId(RelExpr *node) { groupIdMode_ = STANDALONE; node_ = node; groupId_ = INVALID_GROUP_ID; } ExprGroupId::ExprGroupId(CascadesGroupId groupId) { groupIdMode_ = MEMOIZED; node_ = NULL; groupId_ = groupId; } ExprGroupId & ExprGroupId::operator = (const ExprGroupId & other) { groupIdMode_ = other.groupIdMode_; node_ = other.node_; groupId_ = other.groupId_; return *this; } ExprGroupId & ExprGroupId::operator = (RelExpr * other) { if (groupIdMode_ == MEMOIZED) { // Trying to assign an actual pointer to an ExprGroupId that // is in CascadesMemo. This is materialization of a binding. groupIdMode_ = BINDING; } else if (groupIdMode_ == BINDING) // sanity check, can't directly overwrite another binding ABORT("Didn't call BINDING::release_expr()"); node_ = other; return *this; } ExprGroupId & ExprGroupId::operator = (CascadesGroupId other) { // The expression is now (again) in CascadesMemo without participating in // a binding. This may happen when an expression is copied into CascadesMemo // (groupIdMode_ was STANDALONE) or when a binding is released (groupIdMode_ // was BINDING). The node_ member is no longer a valid pointer. if (groupIdMode_ == BINDING && groupId_ != other) ABORT("can't change group of an expression during release of binding"); groupIdMode_ = MEMOIZED; groupId_ = other; node_ = NULL; return *this; } NABoolean ExprGroupId::operator == (const ExprGroupId &other) const { // if the two operands have mode ... then do this: // ---------------------------------------- ------------------ // STANDALONE-STANDALONE: ptrs must match // STANDALONE-MEMOIZED: (x) return FALSE // STANDALONE-BINDING: ptrs must match // MEMOIZED-MEMOIZED: (x) groups must match // MEMOIZED-BINDING: (x) groups must match // BINDING-BINDING: ptrs must match if (node_ == NULL OR other.getPtr() == NULL) return (groupId_ == other.getGroupId()); // cases with (x) else return (node_ == other.getPtr()); // ptrs must match } NABoolean ExprGroupId::operator == (const RelExpr *other) const { CMPASSERT(groupIdMode_ != MEMOIZED); return node_ == other; } CascadesGroupId ExprGroupId::getGroupId() const { return ((groupIdMode_ != STANDALONE)? groupId_ : INVALID_GROUP_ID); } void ExprGroupId::releaseBinding() { if (groupIdMode_ != BINDING) ABORT("binding to release was not established"); groupIdMode_ = MEMOIZED; node_ = NULL; } void ExprGroupId::convertBindingToStandalone() { groupIdMode_ = STANDALONE; } void ExprGroupId::setGroupAttr(GroupAttributes *gaPtr) { // If the expression is either in the standalone mode or is // a part of a binding, then store the Group Attributes // in the node. Group attributes in Cascades can not be set through // an individual expression and an attempt to do this results in an abort. CMPASSERT(groupIdMode_ == STANDALONE); node_->setGroupAttr(gaPtr); } // ExprGroupId::setGroupAttr() GroupAttributes * ExprGroupId::getGroupAttr() const { CMPASSERT(node_ != NULL OR groupIdMode_ == MEMOIZED); // If the expression is either in the standalone mode or is // a part of a binding, then use the Group Attributes that // are stored in the node. if (node_ != NULL) return node_->getGroupAttr(); else // otherwise, use the Cascades group's group attributes return (*CURRSTMT_OPTGLOBALS->memo)[groupId_]->getGroupAttr(); } // ExprGroupId::getGroupAttr() // shortcut to get the output estimated log props out of the group // attributes EstLogPropSharedPtr ExprGroupId::outputLogProp(const EstLogPropSharedPtr& inputLogProp) { return getGroupAttr()->outputLogProp(inputLogProp); } // a shortcut to get the bound expression, if it exists ... // or the first logical expression inserted in the Cascades Group or NULL. // Note: The last log expr in the list is the first one inserted. RelExpr * ExprGroupId::getLogExpr() const { if (node_ != NULL) return node_; else if (groupId_ != INVALID_GROUP_ID) return ((*CURRSTMT_OPTGLOBALS->memo)[groupId_]->getLastLogExpr()); return 0; } RelExpr * ExprGroupId::getFirstLogExpr() const { if (node_ != NULL) return node_; else if (groupId_ != INVALID_GROUP_ID) return ((*CURRSTMT_OPTGLOBALS->memo)[groupId_]->getFirstLogExpr()); return 0; } // ----------------------------------------------------------------------- // member functions for class RelExpr // ----------------------------------------------------------------------- THREAD_P ObjectCounter (*RelExpr::counter_)(0); RelExpr::RelExpr(OperatorTypeEnum otype, RelExpr *leftChild, RelExpr *rightChild, CollHeap *outHeap) : ExprNode(otype) ,selection_(NULL) ,RETDesc_(NULL) ,groupAttr_(NULL) ,groupId_(INVALID_GROUP_ID) ,groupNext_(NULL) ,bucketNext_(NULL) ,operatorCost_(NULL) ,rollUpCost_(NULL) ,physProp_(NULL) ,estRowsUsed_((Cardinality)-1) ,inputCardinality_((Cardinality)-1) ,maxCardEst_((Cardinality)-1) ,contextInsensRules_(outHeap) ,contextSensRules_(outHeap) ,accessSet0_(NULL) // Triggers -- ,accessSet1_(NULL) ,uniqueColumnsTree_(NULL) //++MV ,cardConstraint_(NULL) //++MV ,isinBlockStmt_(FALSE) ,firstNRows_(-1) ,flags_(0) ,rowsetIterator_(FALSE) ,tolerateNonFatalError_(UNSPECIFIED_) ,hint_(NULL) ,markedForElimination_(FALSE) ,isExtraHub_(FALSE) ,potential_(-1) ,seenIUD_(FALSE) ,parentTaskId_(0) ,stride_(0) ,birthId_(0) ,memoExprId_(0) ,sourceMemoExprId_(0) ,sourceGroupId_(0) ,costLimit_(-1) ,cachedTupleFormat_(ExpTupleDesc::UNINITIALIZED_FORMAT) ,cachedResizeCIFRecord_(FALSE) ,dopReduced_(FALSE) { child_[0] = leftChild; child_[1] = rightChild; (*counter_).incrementCounter(); // QSTUFF setGroupAttr(new (outHeap) GroupAttributes); // QSTUFF } RelExpr::~RelExpr() { // the group attributes maintain a reference count if (groupAttr_ != NULL) groupAttr_->decrementReferenceCount(); // these data structures are always owned by the tree delete selection_; // delete all children, if this is a standalone query // (NOTE: can't use the virtual function getArity() in a destructor!!!) for (Lng32 i = 0; i < MAX_REL_ARITY; i++) { if (child(i).getMode() == ExprGroupId::STANDALONE) { // the input was not obtained from CascadesMemo, so delete it if (child(i).getPtr() != NULL) delete child(i).getPtr(); } } (*counter_).decrementCounter(); delete cardConstraint_; //++MV if (hint_) delete hint_; } // RelExpr::~RelExpr() Int32 RelExpr::getArity() const { switch (getOperatorType()) { case REL_SCAN: return 0; case REL_EXCHANGE: return 1; case REL_JOIN: case REL_TSJ: case REL_ROUTINE_JOIN: case REL_SEMIJOIN: case REL_SEMITSJ: case REL_ANTI_SEMIJOIN: case REL_ANTI_SEMITSJ: case REL_LEFT_JOIN: case REL_FULL_JOIN: case REL_LEFT_TSJ: case REL_NESTED_JOIN: case REL_MERGE_JOIN: return 2; default: ABORT("RelExpr with unknown arity encountered"); return 0; } } void RelExpr::deleteInstance() { Int32 nc = getArity(); // avoid deleting the children by resetting all child pointers first for (Lng32 i = 0; i < nc; i++) { child(i) = (RelExpr *) NULL; } delete this; } // RelExpr::deleteInstance() TableMappingUDF *RelExpr::castToTableMappingUDF() { return NULL; } ExprNode * RelExpr::getChild(Lng32 index) { return child(index); } // RelExpr::getChild() void RelExpr::setChild(Lng32 index, ExprNode * newChild) { if (newChild) { CMPASSERT(newChild->castToRelExpr()); child(index) = newChild->castToRelExpr(); } else child(index) = (RelExpr *)NULL; } // RelExpr::setChild() // get TableDesc from the expression. It could be directly // attached to the expression, as in Scan, or could be a // part of GroupAnalysis, as in cut-opp. For expressions // which do not have a tableDesc attached to them, like Join // it would be NULL TableDesc* RelExpr::getTableDescForExpr() { TableDesc * tableDesc = NULL; if (getOperatorType() == REL_SCAN) { tableDesc = ((Scan *)this)->getTableDesc(); } else { if(getGroupAttr()->getGroupAnalysis() && getGroupAttr()->getGroupAnalysis()->getNodeAnalysis() ) { TableAnalysis * tableAnalysis = getGroupAttr()->getGroupAnalysis()->getNodeAnalysis()->getTableAnalysis(); if (tableAnalysis) tableDesc = tableAnalysis->getTableDesc(); } } return tableDesc; } // This method clears all logical expressions uptill the leaf node // for multi-join. The methid should be called only before optimization phases // Reason for that is (1)it is very expensive to synthLogProp and should be avoided // (2) we are resetting number of joined tables, which should not be done once it is // set during optimization phases void RelExpr::clearLogExprForSynthDuringAnalysis() { Int32 numChildren = getArity(); if (numChildren >= 1) { GroupAttributes * grp = getGroupAttr(); grp->setLogExprForSynthesis(NULL); grp->resetNumJoinedTables(1); } // clear the log expr for all children for (Lng32 i = 0; i < numChildren; i++) { // only if the child is not a CascadesGroup or NULL if (child(i).getPtr() != NULL) { child(i)->clearLogExprForSynthDuringAnalysis(); } } } void RelExpr::releaseBindingTree(NABoolean memoIsMoribund) { Int32 nc = getArity(); for (Lng32 i = 0; i < nc; i++) { if (memoIsMoribund || child(i).getMode() == ExprGroupId::BINDING) { // recursively release the bindings of the children's children if (child(i).getPtr() != NULL) child(i)->releaseBindingTree(memoIsMoribund); // release the bindings to the children child(i).convertBindingToStandalone(); } } // for each child // indicate that this expression is no longer part of CascadesMemo, // (although its groupNext_ and bucketNext_ pointers are still valid) groupId_ = INVALID_GROUP_ID; if (memoIsMoribund) { groupAttr_ = NULL; groupNext_ = bucketNext_ = NULL; } } void RelExpr::addSelPredTree(ItemExpr *selpred) { ExprValueId sel = selection_; ItemExprTreeAsList(&sel, ITM_AND).insert(selpred); selection_ = sel.getPtr(); } // RelExpr::addSelPredTree() ItemExpr * RelExpr::removeSelPredTree() { ItemExpr * result = selection_; selection_ = NULL; return result; } // RelExpr::removeSelPredTree() //++ MV - void RelExpr::addUniqueColumnsTree(ItemExpr *uniqueColumnsTree) { ExprValueId t = uniqueColumnsTree_; ItemExprTreeAsList(&t, ITM_ITEM_LIST).insert(uniqueColumnsTree); uniqueColumnsTree_ = t.getPtr(); } ItemExpr *RelExpr::removeUniqueColumnsTree() { ItemExpr *result = uniqueColumnsTree_; uniqueColumnsTree_ = NULL; return result; } // MV-- void RelExpr::setGroupAttr(GroupAttributes *gaPtr) { // the new group attributes are now used in one more place if (gaPtr != NULL) gaPtr->incrementReferenceCount(); // the old group attributes are now used in one place less than before // NOTE: old and new group attribute pointers may be the same if (groupAttr_ != NULL) groupAttr_->decrementReferenceCount(); // now assign the new group attribute pointer to the local data member groupAttr_ = gaPtr; } NABoolean RelExpr::reconcileGroupAttr(GroupAttributes *newGroupAttr) { // make sure the new group attributes have all the information needed // and are not inconsistent newGroupAttr->reconcile(*groupAttr_); // unlink from the current group attributes and adopt the new (compatible) // ones setGroupAttr(newGroupAttr); return FALSE; // no re-optimization for now } RelExpr * RelExpr::castToRelExpr() { return this; } const RelExpr * RelExpr::castToRelExpr() const { return this; } NABoolean RelExpr::isLogical() const { return TRUE; } NABoolean RelExpr::isPhysical() const { return FALSE; } NABoolean RelExpr::isCutOp() const { return FALSE; } NABoolean RelExpr::isSubtreeOp() const { return FALSE; } NABoolean RelExpr::isWildcard() const { return FALSE; } ItemExpr * RelExpr::selectList() { // RelRoot redefines this virtual method (see BindRelExpr.cpp); // Tuple and Union use this standard method. RETDesc *rd = getRETDesc(); if (rd) { ValueIdList vids; const ColumnDescList &cols = *rd->getColumnList(); for (CollIndex i = 0; i < cols.entries(); i++) vids.insert(cols[i]->getValueId()); return vids.rebuildExprTree(ITM_ITEM_LIST); } return NULL; } SimpleHashValue RelExpr::hash() { // this method is just defined to have a hash method in ExprNode // without referencing class HashValue (which is too complicated // for the common code directory) return treeHash().getValue(); } HashValue RelExpr::topHash() { HashValue result = (Int32) getOperatorType(); // hash the required input and output values from the GroupAttributes if (groupAttr_ != NULL) result ^= groupAttr_->hash(); // hash the ValueIdSet of the selection predicates result ^= predicates_; // the other data members are not significant for the hash function CMPASSERT(selection_ == NULL); // this method doesn't work in the parser return result; } // this method is not virtual, since combining the hash values of the // top node and its children should be independent of the actual node HashValue RelExpr::treeHash() { HashValue result = topHash(); Int32 maxc = getArity(); for (Lng32 i = 0; i < maxc; i++) { if (child(i).getMode() == ExprGroupId::MEMOIZED) // use the numbers of the input CascadesGroup result ^= child(i).getGroupId(); else // call this method recursively for the children result ^= child(i)->treeHash(); } return result; } NABoolean RelExpr::patternMatch(const RelExpr & other) const { return getOperator().match(other.getOperator()); } // Checks if the selection preds at this join node are of the // form FKtable.col1 = UKTable.col1 and FKtable.col1 = UKTable.col1 // and ..., where FKTable.col1 is the FK column that points to // UKTable.col1. // The third arguments matchingPreds is an output parameter. // It is used to send the a list of FKtable.col1 = UKTable.col1 // type predicates back to the caller, so that it can be used // to adjust the selection preds and equiJoinPreds in the join // node. NABoolean Join::hasRIMatchingPredicates(const ValueIdList& fkCols, const ValueIdList& ucCols, const TableDesc * compRefTabId, ValueIdSet & matchingPreds) const { // if the size of the fkCols does not match with ucCols then something is wrong. // We also assume below that corresponding cols have identical positions // in the two valueidlists and that all entries here are in terms of VEG. CMPASSERT(fkCols.entries() == ucCols.entries()); // There is not possibility of finding a full match // if number ofselection preds is smaller than the fkCols. // number of selection preds can be larger than fkCols.entries, // for example there may be a predicate on the fktable and some // other table which is being joined up above. Since the fktable // is below this join, this join will have that predicate. if ((getSelectionPredicates().entries() < fkCols.entries())) return FALSE; ValueIdList localFKCols(fkCols); ValueIdList localUCCols(ucCols); ValueIdSet compRefTabNonUCCols(compRefTabId->getColumnVEGList()); ValueIdSet localUCColsSet(localUCCols); compRefTabNonUCCols -= localUCColsSet; NABoolean matchFound = FALSE; const ValueIdSet& selPreds = getSelectionPredicates(); matchingPreds.clear(); for (ValueId x = selPreds.init(); selPreds.next(x); selPreds.advance(x)) { ItemExpr *ie = x.getItemExpr(); matchFound = FALSE; if (ie->getOperatorType() == ITM_VEG_PREDICATE) { ValueId vegRef = ((VEGPredicate *)ie)->getVEG()->getVEGReference()->getValueId(); CollIndex fkidx = localFKCols.index(vegRef); if ((fkidx != NULL_COLL_INDEX)&&(localUCCols[fkidx] == vegRef)) { localFKCols.removeAt(fkidx); localUCCols.removeAt(fkidx); matchingPreds.insert(x); } if (compRefTabNonUCCols.contains(vegRef)) { // return false on a predicate // of the form fktable.x = uniquetable.x where x is a nonkey column. matchingPreds.clear(); return FALSE; } } else if ((ie->getOperatorType() == ITM_EQUAL)&& (ie->child(0)->getOperatorType() == ITM_VEG_REFERENCE)&& (ie->child(1)->getOperatorType() == ITM_VEG_REFERENCE)) { ValueId vegRef0 = ((VEGReference *)ie->child(0).getPtr())->getValueId(); ValueId vegRef1 = ((VEGReference *)ie->child(1).getPtr())->getValueId(); ValueId ukVid = NULL_COLL_INDEX; CollIndex fkidx = localFKCols.index(vegRef0); if (fkidx == NULL_COLL_INDEX) { CollIndex fkidx = localFKCols.index(vegRef1); if (fkidx != NULL_COLL_INDEX) ukVid = vegRef0; } else ukVid = vegRef1; if ((fkidx != NULL_COLL_INDEX)&&(localUCCols[fkidx] == ukVid)) { localFKCols.removeAt(fkidx); localUCCols.removeAt(fkidx); matchingPreds.insert(x); } } else { matchingPreds.clear(); return FALSE; // not a VEG Pred (revisit for char-varchar) } } if (localFKCols.isEmpty()) return TRUE ; // all preds have a match with a FK-UC column pair. else { matchingPreds.clear(); return FALSE; } } // Special method added to check for ordered cross product called by // RequiredPhysicalProperty::satisfied() to ensure that if a CQS has // requested an ordered cross product, then one is being produced. NABoolean HashJoin::patternMatch(const RelExpr &other) const { if (other.getOperator() == REL_FORCE_ORDERED_CROSS_PRODUCT) return ((HashJoin *) this)->isOrderedCrossProduct(); else return RelExpr::patternMatch(other); } // Two trees match, if their top nodes and their children are duplicates // (are the same logical or physical expression). This method provides // the generic part for determining a match. It can be called by // redefined virtual methods of derived classes. NABoolean RelExpr::duplicateMatch(const RelExpr & other) const { if (getOperatorType() != other.getOperatorType()) return FALSE; CMPASSERT(selection_ == NULL); // this method doesn't work in the parser if (predicates_ != other.predicates_) return FALSE; if (rowsetIterator_ != other.rowsetIterator_) return FALSE; if (tolerateNonFatalError_ != other.tolerateNonFatalError_) return FALSE; Int32 maxc = getArity(); // determine whether the children match for (Lng32 i = 0; i < maxc; i++) { // different situations, depending on whether the child // and the other node's child is in state MEMOIZED, // BINDING, or STANDALONE. See ExprGroupId::operator == // for an explanation for each of the cases if (child(i).getMode() == ExprGroupId::MEMOIZED OR other.child(i).getMode() == ExprGroupId::MEMOIZED) { // cases marked (x) in ExprGroupId::operator == // (groups must match) if (NOT (child(i) == other.child(i))) return FALSE; } else { // outside of CascadesMemo or in a CascadesBinding, then // call this method recursively for the children if (NOT child(i)->duplicateMatch(*other.child(i).getPtr())) return FALSE; } } return TRUE; } const CorrName RelExpr::invalid = CorrName("~X~invalid"); RelExpr * RelExpr::copyTopNode(RelExpr *derivedNode,CollHeap* outHeap) { RelExpr *result; if (derivedNode == NULL) result = new (outHeap) RelExpr(getOperatorType(), NULL, NULL, outHeap); else result = derivedNode; // don't copy pointers to required input/output values, since we don't // allow duplicate expressions the new node is likely to get new group // attributes // copy selection predicates result->predicates_ = predicates_; // copy pointer to the selection expression tree (Parser only) if (selection_ != NULL) result->selection_ = selection_->copyTree(outHeap)->castToItemExpr(); // -- Triggers // Copy the inlining information and access sets. result->getInliningInfo().merge(&getInliningInfo()); result->setAccessSet0(getAccessSet0()); result->setAccessSet0(getAccessSet0()); //++MV - result->setUniqueColumns(getUniqueColumns()); if (uniqueColumnsTree_ != NULL) result->uniqueColumnsTree_ = uniqueColumnsTree_->copyTree(outHeap)->castToItemExpr(); //--MV - // leave any physical properties or CascadesMemo-related data // off the returned result ??? (see RelExpr::save) result->setBlockStmt(isinBlockStmt()); result->setFirstNRows(getFirstNRows()); result->oltOptInfo() = oltOptInfo(); result->setHint(getHint()); result->setRowsetIterator(isRowsetIterator()); result->setTolerateNonFatalError(getTolerateNonFatalError()); result->setIsExtraHub(isExtraHub()); result->setMarkedForElimination(markedForElimination()); result->seenIUD_ = seenIUD_; // set the expression's potential result->potential_ = potential_; // copy cascades trace info result->parentTaskId_ = parentTaskId_; result->stride_ = stride_; result->birthId_ = birthId_; result->memoExprId_ = memoExprId_; result->sourceMemoExprId_ = sourceMemoExprId_; result->sourceGroupId_ = sourceGroupId_; result->costLimit_ = costLimit_; return result; } // this method is not virtual, since combining the copies of the // top node and its children should be independent of the actual node RelExpr * RelExpr::copyTree(CollHeap* outHeap) { RelExpr * result = copyTopNode(0,outHeap); Int32 arity = getArity(); for (Lng32 i = 0; i < arity; i++) result->child(i) = child(i)->copyTree(outHeap); return result; } // this method is also not virtual, It does same thing as copyTree // except that it copies the RETDesc and groupAttr pointers too // this is method is used to get a copy of the original tree before // inserting it to Cascades. RelExpr * RelExpr::copyRelExprTree(CollHeap* outHeap) { RelExpr * result = copyTopNode(0,outHeap); result->setGroupAttr(new (outHeap) GroupAttributes(*(getGroupAttr()))); result->setRETDesc(getRETDesc()); result->getGroupAttr()->setLogExprForSynthesis(result); Int32 arity = getArity(); for (Lng32 i = 0; i < arity; i++) result->child(i) = child(i)->copyRelExprTree(outHeap); return result; } void RelExpr::setBlockStmtRecursively(NABoolean x) { setBlockStmt(x); Int32 arity = getArity(); for (Lng32 i = 0; i < arity; i++) child(i)->setBlockStmtRecursively(x); } // ----------------------------------------------------------------------- // create or share an optimization goal for a child group // ----------------------------------------------------------------------- Context * RelExpr::shareContext(Lng32 childIndex, const ReqdPhysicalProperty* const reqdPhys, const InputPhysicalProperty* const inputPhys, CostLimit* costLimit, Context * parentContext, const EstLogPropSharedPtr& inputLogProp, RelExpr *explicitlyRequiredShape) const { // no need to do the job if costLimit id already negative if ( costLimit AND CURRSTMT_OPTDEFAULTS->OPHpruneWhenCLExceeded() AND costLimit->getValue(reqdPhys) < 0 ) return NULL; const ReqdPhysicalProperty* searchForRPP; // if the required physical properties are empty, don't use them if (reqdPhys != NULL AND reqdPhys->isEmpty()) searchForRPP = NULL; else searchForRPP = reqdPhys; // handle force plan directives: if the parent node must match a // certain tree, make sure the child node gets the appropriate // requirement to match a child node of the mustMatch pattern RelExpr *childMustMatch = explicitlyRequiredShape; if (parentContext->getReqdPhysicalProperty() != NULL AND parentContext->getReqdPhysicalProperty()->getMustMatch() != NULL AND explicitlyRequiredShape == NULL) { const RelExpr *parentMustMatch = parentContext->getReqdPhysicalProperty()->getMustMatch(); // Reuse the parent's pattern if this node is a map value ids // node and the required pattern isn't. This is because a map value // ids node, PACK node and UNPACK node is essentially a no-op and // does not need to be specified in CONTROL QUERY SHAPE. // Sorry for putting this DBI code into // places where particular operator types shouldn't be known. // It's the summer of 1997 and we have a deadline for FCS. // Its (almost) summer of 2003 and I am adding the same thingy // for FIRST_N operator. if (((getOperatorType() == REL_MAP_VALUEIDS) && (parentMustMatch->getOperatorType() != REL_MAP_VALUEIDS)) || ((getOperatorType() == REL_PACK) AND (parentMustMatch->getOperatorType() != REL_PACK)) || ((getOperatorType() == REL_UNPACKROWS) AND (parentMustMatch->getOperatorType() != REL_UNPACKROWS)) || ((getOperatorType() == REL_FIRST_N) AND (parentMustMatch->getOperatorType() != REL_FIRST_N)) || (CURRSTMT_OPTDEFAULTS->ignoreExchangesInCQS() AND (getOperatorType() == REL_EXCHANGE) AND (parentMustMatch->getOperatorType() != REL_FORCE_EXCHANGE)) || (CURRSTMT_OPTDEFAULTS->ignoreSortsInCQS() AND (getOperatorType() == REL_SORT) AND (parentMustMatch->getOperatorType() != REL_SORT))) { childMustMatch = (RelExpr *) parentMustMatch; } else { // If the "must match" pattern specifies something other than // a cut op for child "childIndex" then this is our new "must match". if (childIndex < parentMustMatch->getArity() AND NOT parentMustMatch->child(childIndex)->isCutOp()) childMustMatch = parentMustMatch->child(childIndex); } } if (childMustMatch != NULL OR searchForRPP AND searchForRPP->getMustMatch() != NULL) { // we have to change the "must match" attribute of searchForRPP // add the "mustMatch" requirement if (searchForRPP != NULL) { searchForRPP = new (CmpCommon::statementHeap()) ReqdPhysicalProperty(*searchForRPP, childMustMatch); } else searchForRPP = new (CmpCommon::statementHeap()) ReqdPhysicalProperty(childMustMatch); } return (*CURRSTMT_OPTGLOBALS->memo)[child(childIndex).getGroupId()]->shareContext(searchForRPP, inputPhys, costLimit, parentContext, inputLogProp); } // RelExpr::shareContext() ULng32 RelExpr::getDefault(DefaultConstants id) { return ActiveSchemaDB()->getDefaults().getAsULong(id); } void RelExpr::addLocalExpr(LIST(ExprNode *) &xlist, LIST(NAString) &llist) const { if (selection_ != NULL OR NOT predicates_.isEmpty()) { if (predicates_.isEmpty()) xlist.insert(selection_); else xlist.insert(predicates_.rebuildExprTree()); llist.insert("selection_predicates"); } if(NOT uniqueColumns_.isEmpty()) { xlist.insert(uniqueColumns_.rebuildExprTree()); llist.insert("uniqueColumns_"); } } //QSTUFF // we must pushdown the outputs of a genericupdate root to its // descendants to ensure that only those required output values are // tested against indexes when selecting an index for a stream scan // followed by an embedded update. Since we may allow for unions and // for inner updates we just follow the isEmbeddedUpdate() thread once // we reach a generic update root. void RelExpr::pushDownGenericUpdateRootOutputs( const ValueIdSet &outputs) { ValueIdSet rootOutputs = getGroupAttr()->isGenericUpdateRoot() ? getGroupAttr()->getCharacteristicOutputs() : outputs; for (Int32 i=0; i < getArity(); i++) { if (child(i)->castToRelExpr()->getGroupAttr()->isEmbeddedUpdateOrDelete()){ child(i)->castToRelExpr()-> pushDownGenericUpdateRootOutputs(rootOutputs); } } if (NOT rootOutputs.isEmpty()){ getGroupAttr()->setGenericUpdateRootOutputs(rootOutputs); } } //QSTUFF void RelExpr::needSortedNRows(NABoolean val) { for (Int32 i=0; i < getArity(); i++) { if (child(i)) child(i)->castToRelExpr()->needSortedNRows(val); } } // ----------------------------------------------------------------------- // computeValuesReqdForPredicates() // // There has been some problems with this function (as to how it should // behave). The issue has been whether we should allow an operator to // have the boolean value of a predicate as its output. That is to say, // whether (SCAN T1), for example, could evaluate a predicate such as // (T1.a > 3) and output a value of true or false to its parent. // // In most cases, this wouldn't be an issue since the predicate is used // to filter out all the non-qualified rows. However, such is not the // case when a CASE statement is involved. Part of the CASE statement, // (e.g. the WHEN clause) can be evaluated at the SCAN, while the rest // of the statement could reference some other tables and therefore must // be evaluated at an ancestor node of the tree. // // A complete example is SELECT CASE WHEN T1.A > 3 THEN T2.A ELSE 0 END // FROM T1 JOIN T2 ON T1.C = T2.C. In this case, if we allow a boolean // value to be our output, the (T1.A > 3) could be evaluated at SCAN T1, // and the CASE statement itself at the JOIN. The alternative would be // for SCAN T1 to output T1.A and the CASE statement evaluated wholly at // the JOIN. // // Now, how do all these relate to this function? The purpose of this // function is to turn a predicate into values required to evaluate the // predicate. Thus, the question is: should we allow the boolean value // of (T1.A > 3) be the value required to evaluate the predicate (T1.A > // 3). Or, should the values be T1.A and 3 instead? More generally, // should we go for the leaf values of a non-VEG predicate (there is a // separate story for VEG predicates, see later) or just the bool value // of that predicate? // // This function has been implemented to gather the leaf values. However, // there is no reason why we could // not just require the boolean value. The logic of predicate pushdown // mandates that if the child of the operator is unable to produce that // boolean value, it will figure out what sub-expressions it could produce // in its outputs in order for the boolean value to be evaluated at its // parent. // // On the other hand, since this function has not been changed for quite // a while, we are worried the change might trigger problematic spots in // other places which rely on this function behaving the way it has been. // Through extensive testing, we didn't seem to identify any problems and // therefore, we decided to commit this fix. // // Now for VEGPred's. A VEGPred is considered "evaluable" at an operator // if any *one* of its VEG members is "evaluable". For example, VEGPred( // VEG{T1.a,T2.a}) in the query SELECT T2.B FROM (T1 JOIN T2 ON T1.A = // T2.A) is "evaluable" at SCAN T1 and will be pushed down. Clearly, only // evaluating the predicate there is not enough. We have to keep the // VEGPred at the JOIN as well. The logic in Join::pushdownCoveredExpr() // correctly handle that now. That is, it keeps the predicate even if // it has been pushed down. However, doing so means that in the example // given, SCAN T1 has to return T1.A as an output rather than just the // boolean value of VEGPred(VEG{T1.A,T2.A}). That boolean value is sort // of only local to SCAN T1. This function, therefore, declares that the // value required to evaluate a VEGPred is not the boolean value of the // VEGPred itself but the VEGRef of its VEG. In our example, the required // value is VEGRef(VEG{T1.A,T2.A}). The semantics of this is that SCAN T1 // is asked to return as an output one of the VEG members available to // it. The pre-code generator will thus change this VEGRef into T1.A. // // 8/14/1998 // // ----------------------------------------------------------------------- void RelExpr::computeValuesReqdForPredicates(const ValueIdSet& setOfExpr, ValueIdSet& reqdValues, NABoolean addInstNull) { for (ValueId exprId = setOfExpr.init(); setOfExpr.next(exprId); setOfExpr.advance(exprId)) { if (exprId.getItemExpr()->getOperatorType() == ITM_VEG_PREDICATE) { VEG * vegPtr = ((VEGPredicate *)(exprId.getItemExpr()))->getVEG(); reqdValues += vegPtr->getVEGReference()->getValueId(); // If the VEG for this VEGPredicate contains a member that is // another VEGReference, add it to reqdValues in order to ensure // that it gets retrieved. // for (ValueId x = vegPtr->getAllValues().init(); vegPtr->getAllValues().next(x); vegPtr->getAllValues().advance(x)) { OperatorTypeEnum optype = x.getItemExpr()->getOperatorType(); if ( optype == ITM_VEG_REFERENCE ) // ********************************************************** // Note: this "if" used to have the following cases as well. // We feel that they might not be necessary any more. // || optype == ITM_INSTANTIATE_NULL || // optype == ITM_UNPACKCOL ) // ********************************************************** reqdValues += x; else if ( addInstNull && optype == ITM_INSTANTIATE_NULL ) { // part of fix to soln 10-090618-2434: a full outer join // select ... from t1 inner join t2 on ... // full outer join t3 on ... where t2.RGN = 'EMEA' // whose selection predicate "t2.RGN = <constant>" must have // its null-instantiated "t.RGN" column added to reqdValues. reqdValues += x; } } // end inner for } // endif is a VEGPredicate else { // Not a VEGPred (either a "normal" pred or a "real" value). In // any case, just add the value to the required values set. (For // a "normal" pred, it means the boolean value for the predicate // is required. // reqdValues += exprId; } } // end outer for } // computeValuesReqdForPredicates() void RelExpr::computeValuesReqdForOutput(const ValueIdSet& setOfExpr, const ValueIdSet& newExternalInputs, ValueIdSet& reqdValues) { // if VEGPreds are in the output, get the underlying VEGRefs computeValuesReqdForPredicates(setOfExpr, reqdValues); const GroupAttributes emptyGA; for (ValueId exprId = setOfExpr.init(); setOfExpr.next(exprId); setOfExpr.advance(exprId)) { if ((exprId.getType().getTypeQualifier() == NA_CHARACTER_TYPE) && (exprId.getType().getNominalSize() > CONST_32K)) { exprId.getItemExpr()->getLeafValuesForCoverTest(reqdValues, emptyGA, newExternalInputs); } } } // ----------------------------------------------------------------------- // RelExpr::pushdownCoveredExpr() // ----------------------------------------------------------------------- void RelExpr::pushdownCoveredExpr(const ValueIdSet & outputExpr, const ValueIdSet & newExternalInputs, ValueIdSet & predicatesOnParent, const ValueIdSet * setOfValuesReqdByParent, Lng32 childIndex ) { ValueIdSet exprToEvalOnParent, outputSet, extraHubNonEssOutputs; Int32 firstChild, lastChild; // loop bounds Int32 iter; // loop index variable NABoolean optimizeOutputs; if (getArity() == 0 ) return; // we don't do anything for leaf nodes.. if ((getOperator().match(REL_ANY_TSJ) ) || (getOperator().match(REL_ANY_GEN_UPDATE) ) ) optimizeOutputs = FALSE; else optimizeOutputs = TRUE; if (getOperator().match(REL_ANY_JOIN) && isExtraHub()) extraHubNonEssOutputs = ((Join *)this)->getExtraHubNonEssentialOutputs(); // ----------------------------------------------------------------- // Should the pushdown be attempted on a specific child? // ----------------------------------------------------------------- if ( (childIndex >= 0) AND (childIndex < getArity()) ) { // yes, a child index is given firstChild = (Int32)childIndex; lastChild = firstChild + 1; } else // no, perform pushdown on all { firstChild = 0; lastChild = getArity(); } // --------------------------------------------------------------------- // Examine the set of values required by the parent. Replace each // VEGPredicate with a VEGReferences for its VEG; if its VEG // contains other VEGReferences, add them to exprToEvalOnParent. // --------------------------------------------------------------------- if (setOfValuesReqdByParent) computeValuesReqdForPredicates(*setOfValuesReqdByParent, exprToEvalOnParent); computeValuesReqdForOutput(outputExpr,newExternalInputs,outputSet); // --------------------------------------------------------------------- // Are there any predicates that can be pushed down? // --------------------------------------------------------------------- if ( (getArity() > 0) AND (NOT predicatesOnParent.isEmpty()) ) { // ----------------------------------------------------------------- // 1) Figure out which predicates could be push to which child. // Try to give all predicates to all children. // 2) Modify predOnParent to be those predicates that no could // could take. // 3) Add to the selectionPred() of each child those predicates // it could take (if it is not a cut operator) // 4) Add to exprToEvalOnParent the predicates that could not // be push down to any child (predOnParent) // 5) Recompute the input and outputs for each child given this // set of exprOnParent. // ----------------------------------------------------------------- // Allocate an array to contain the ValueIds of external inputs // that are referenced in the given expressions. // ----------------------------------------------------------------- ValueIdSet referencedInputs[MAX_REL_ARITY]; // ----------------------------------------------------------------- // Allocate a ValueIdSet to contain the ValueIds of the roots of // sub-expressions that are covered by // a) the Group Attributes of a child and // b) the new external inputs. // Note that the containing expression is not covered for each // such sub-expression. // ----------------------------------------------------------------- ValueIdSet coveredSubExprNotUsed; // ----------------------------------------------------------------- // Allocate an array to contain the ValueIds of predicates that // can be pushed down to a specific child. // ----------------------------------------------------------------- ValueIdSet predPushSet[MAX_REL_ARITY]; // ----------------------------------------------------------------- // Check which predicate factors are fully covered by a certain // child. Gather their ValueIds in predPushSet. // ----------------------------------------------------------------- const ValueIdSet emptySet; // ----------------------------------------------------------------- // Join predicates can be pushed below a GU root as the comment a // few lines below does applies only to selection predicates // and not join predicates. The comment below indicates that in // some cases we do not wish to push a user provided predicate on // select below the GU root. These user provided predicates are // stored as selection predicates. // For MTS deletes, an anti-semi-join is used to glue the // inlined tree. For such joins all predicates that are pulled // are stored as join predicates. The change below facilitates // a push down of those predicates. The firstChild condition below // ensures that we are considering join predicates here (see // Join::pushDownCoveredExpr) // ----------------------------------------------------------------- NABoolean pushPredicateBelowGURoot = FALSE; if ((getGroupAttr()->isGenericUpdateRoot() AND getOperator() == REL_ANTI_SEMITSJ AND firstChild == 1 ) OR (NOT (getGroupAttr()->isGenericUpdateRoot()))) { pushPredicateBelowGURoot = TRUE; } for (iter = firstChild; iter < lastChild; iter++) { if (NOT child(iter).getPtr()->isCutOp()){ // QSTUFF // we don't push predicates beyond the root of a generic // update tree. This is done by pretending that those // predicates are not covered by any child. This is // required to allows us to distinguish between the // following two types of expressions: // select * from (delete from x) y where y.x > 3; // select * from (delete from x where x.x > 3) y; if (pushPredicateBelowGURoot ) { // QSTUFF child(iter).getGroupAttr()->coverTest(predicatesOnParent, newExternalInputs, predPushSet[iter], referencedInputs[iter], &coveredSubExprNotUsed); // QSTUFF } // QSTUFF } else // ---------------------------------------------------------- // If this is a cutop these predicates were already pushed // down to the child during predicate pushdown. Compute // which predicates were pushable so that we can remove them // from predOnParent and avoid creating a new group that will // later be merged // ---------------------------------------------------------- // QSTUFF // for more explanation please see comment above if ( pushPredicateBelowGURoot ) { // QSTUFF child(iter).getGroupAttr()->coverTest(predicatesOnParent, emptySet, predPushSet[iter], referencedInputs[iter], &coveredSubExprNotUsed); // QSTUFF } // QSTUFF } // for loop to perform coverTest() // ----------------------------------------------------------------- // From the original set of predicates, delete all those predicates // that will be pushed down. The remaining predicates will be // evaluated on the parent (this node). // ----------------------------------------------------------------- for (iter = firstChild; iter < lastChild; iter++) predicatesOnParent -= predPushSet[iter]; // ----------------------------------------------------------------- // Add the predicates that could not be pushed to any child to the // set of expressions to evaluate on the parent. // ----------------------------------------------------------------- computeValuesReqdForPredicates(predicatesOnParent, exprToEvalOnParent); // ----------------------------------------------------------------- // Perform predicate pushdown // ----------------------------------------------------------------- for (iter = firstChild; iter < lastChild; iter++) { if (NOT child(iter).getPtr()->isCutOp()) { // --------------------------------------------------------- // Reassign predicate factors to the appropriate children // --------------------------------------------------------- child(iter).getPtr()->selectionPred().insert(predPushSet[iter]); // --------------------------------------------------------- // Add the input values that are referenced by the predicates // that were pushed down in the above step, to the Group // Attributes of the child. // We need to call coverTest again to figure out which inputs // are needed for the predicates that will be pushdown. // --------------------------------------------------------- ValueIdSet inputsNeededByPredicates; child(iter).getGroupAttr()->coverTest(predPushSet[iter], referencedInputs[iter], predPushSet[iter], inputsNeededByPredicates, &coveredSubExprNotUsed); child(iter).getPtr()->getGroupAttr()->addCharacteristicInputs (inputsNeededByPredicates); ValueIdSet essChildOutputs; child(iter).getPtr()->getEssentialOutputsFromChildren (essChildOutputs); // ---------------------------------------------------------- // Have the child compute what output it can provide for // the expressions that remain on the parent // ---------------------------------------------------------- // TBD: Fix the hack described in // GroupAttributes::resolveCharacteristicOutputs() if(iter==1 AND getOperator().match(REL_ANY_LEFT_JOIN)) child(iter).getPtr()->getGroupAttr()->computeCharacteristicIO (newExternalInputs, exprToEvalOnParent, outputSet, essChildOutputs, &(getSelectionPred()), TRUE, optimizeOutputs, &extraHubNonEssOutputs ); else child(iter).getPtr()->getGroupAttr()->computeCharacteristicIO (newExternalInputs, exprToEvalOnParent, outputSet, essChildOutputs, NULL, FALSE, optimizeOutputs, &extraHubNonEssOutputs ); }; } // for loop to pushdown predicates } // endif (NOT predicatesOnParent.isEmpty()) else { // --------------------------------------------------------------------- // Compute the characteristic inputs and outputs of each child // --------------------------------------------------------------------- for (iter = firstChild; iter < lastChild; iter++) { // ----------------------------------------------------------------- // Ignore CutOps because they exist simply to facilitate // pattern matching. Their Group Attributes are actually those // of the CascadesGroup. So, don't mess with them! // ----------------------------------------------------------------- if (NOT child(iter).getPtr()->isCutOp()) { ValueIdSet essChildOutputs; child(iter).getPtr()->getEssentialOutputsFromChildren (essChildOutputs); // TBD: Fix the hack described in // GroupAttributes::resolveCharacteristicOutputs() child(iter).getPtr()->getGroupAttr()->computeCharacteristicIO (newExternalInputs, exprToEvalOnParent, outputSet, essChildOutputs, NULL, FALSE, optimizeOutputs, &extraHubNonEssOutputs ); } } // for loop to compute characteristic inputs and outputs } // endelse predicatesOnParent is empty } // RelExpr::pushdownCoveredExpr() // ----------------------------------------------------------------------- // A virtual method for computing output values that an operator can // produce potentially. // ----------------------------------------------------------------------- void RelExpr::getPotentialOutputValues(ValueIdSet & outputValues) const { outputValues.clear(); Int32 nc = getArity(); // For operators that are not leaves, clear the potential outputs // and rebuild them. if (nc > 0) for (Lng32 i = 0; i < nc; i++) outputValues += child(i).getGroupAttr()->getCharacteristicOutputs(); else outputValues += getGroupAttr()->getCharacteristicOutputs(); } // RelExpr::getPotentialOutputValues() void RelExpr::getPotentialOutputValuesAsVEGs(ValueIdSet& outputs) const { getPotentialOutputValues(outputs); } // ----------------------------------------------------------------------- // primeGroupAttributes() // Initialize the Characteristic Inputs And Outputs of this operator. // ----------------------------------------------------------------------- void RelExpr::primeGroupAttributes() { // Ignore CutOps because they exist simply to facilitate // pattern matching. Their Group Attributes are actually those // of the CascadesGroup. So, don't mess with them. if (isCutOp()) return; // The method sets the characteristic outputs of a node to its // potential outputs and sets the required input to the values // it needs. It does this by calling two virtual functions // on RelExpr. ValueIdSet outputValues; getPotentialOutputValues(outputValues); getGroupAttr()->setCharacteristicOutputs(outputValues); recomputeOuterReferences(); } // RelExpr::primeGroupAttributes() // ----------------------------------------------------------------------- // allocateAndPrimeGroupAttributes() // This method is for allocating new Group Attributes for the children // of this operator that were introduced in the dataflow by a rule- // based transformation. Each new child, or set of children, intervene // between this operator and another operator that was originally a // direct child of the latter. The Group Attributes of each newly // introduced child are recursively primed with the Characteristic // Inputs and Outputs of the operators of which it is the parent. // ----------------------------------------------------------------------- void RelExpr::allocateAndPrimeGroupAttributes() { Int32 nc = getArity(); for (Lng32 i = 0; i < nc; i++) { CMPASSERT(child(i).getMode() == ExprGroupId::STANDALONE); // Terminate the recursive descent upon reaching a CutOp. // Ignore CutOps because they exist simply to facilitate // pattern matching. Their Group Attributes are actually // those for the CascadesGroup that they belong to and // must not change. if (NOT child(i)->isCutOp()) { if (child(i).getGroupAttr() == NULL) { // A CutOp must have Group Attributes. child(i)->setGroupAttr(new (CmpCommon::statementHeap()) GroupAttributes()); } // Assign my Characteristic Inputs to my child. // This is done in order to ensure that they are propagated // recursively to all my children who are not CutOps. child(i).getPtr()->getGroupAttr() ->addCharacteristicInputs (getGroupAttr()->getCharacteristicInputs()); // Recompute the potential inputs/outputs for each real child // recursively. // Terminate the recursive descent upon encountering an // operator whose arity == 0 child(i).getPtr()->allocateAndPrimeGroupAttributes(); // Prime the Group Attributes of the child. // The following call primes the child's Characteristic Outputs. // It ensures that the inputs are minimal and outputs are maximal. child(i).getPtr()->primeGroupAttributes(); // Now compute the GroupAnalysis fields child(i).getPtr()->primeGroupAnalysis(); } // endif child is not a CutOp } // for loop } // RelExpr::allocateAndPrimeGroupAttributes() void RelExpr::getEssentialOutputsFromChildren(ValueIdSet & essOutputs) { Int32 nc = getArity(); for (Lng32 i = 0; i < nc; i++) { essOutputs += child(i).getGroupAttr()-> getEssentialCharacteristicOutputs(); } } void RelExpr::fixEssentialCharacteristicOutputs() { ValueIdSet essChildOutputs,nonEssOutputs; getEssentialOutputsFromChildren(essChildOutputs); getGroupAttr()->getNonEssentialCharacteristicOutputs(nonEssOutputs); nonEssOutputs.intersectSet(essChildOutputs); getGroupAttr()->addEssentialCharacteristicOutputs(nonEssOutputs); } // do some analysis on the initial plan // this is called at the end of the analysis phase void RelExpr::analyzeInitialPlan() { Int32 nc = getArity(); for (Lng32 i = 0; i < nc; i++) { child(i)->analyzeInitialPlan(); } } double RelExpr::calculateNoOfLogPlans(Lng32& numOfMergedExprs) { double result = 1; Int32 nc = getArity(); CascadesGroup* group; for (Lng32 i = 0; i < nc; i++) { if (getGroupId() == child(i).getGroupId()) { // This is a recursive reference of an expression to itself // due to a group merge. We cannot call this method on the // child, as we would end up calling this method on ourselves // again! So, we skip the recursive call on our child and // instead return an indication to our caller // (CascadesGroup::calculateNoOfLogPlans) that we encountered // a merged expression. Our caller will then know what to do // to calculate the correct number of logical expressions. numOfMergedExprs++; } else { group = (*CURRSTMT_OPTGLOBALS->memo)[child(i).getGroupId()]; result *= group->calculateNoOfLogPlans(); } } // for each child return result; } // This function is called before any optimization starts // i.e. applied to the normalizer output (reorderJoinTree OK) double RelExpr::calculateSubTreeComplexity (NABoolean& enableJoinToTSJRuleOnPass1) { double result = 0; Int32 freeLeaves = 1; // # of subtree legs that can permutate RelExpr* expr = this; while (expr) { if (expr->getGroupAttr()->isEmbeddedUpdateOrDelete() OR expr->getGroupAttr()->isStream()) { enableJoinToTSJRuleOnPass1 = TRUE; } Int32 nc = expr->getArity(); // The multi-join case if (expr->getOperatorType() == REL_MULTI_JOIN) { for (Int32 i = 0; i < nc; i++) { CascadesGroup* groupi = (*CURRSTMT_OPTGLOBALS->memo)[expr->child(i).getGroupId()]; RelExpr * expri = groupi->getFirstLogExpr(); result += expri-> calculateSubTreeComplexity(enableJoinToTSJRuleOnPass1); } freeLeaves = nc; // end the while loop expr = NULL; } // Not multi-join, and not leaf else if (nc > 0) { if (nc == 1) { // no permutation can take place across groupbys if (expr->getOperator().match(REL_ANY_GROUP)) { if (freeLeaves > 1) { // compute the last permuatation set contribution // to the complexity and start a new one result += freeLeaves * pow(2,freeLeaves-1); freeLeaves = 1; // start again } } } if (nc == 2) { double child1Complexity; CascadesGroup* group1 = (*CURRSTMT_OPTGLOBALS->memo)[expr->child(1).getGroupId()]; if (group1->getGroupAttr()->getNumBaseTables() > 1) { // Only one log expr exist in the group at this point RelExpr * expr1 = group1->getFirstLogExpr(); child1Complexity = expr1->calculateSubTreeComplexity(enableJoinToTSJRuleOnPass1); // adding this comp_bool guard in case this fix causes regressions // and we need to disable this fix. Should be taken out in a subsequent // release. (say 2.2) if (CmpCommon::getDefault(COMP_BOOL_123) == DF_OFF) { // The factor 2 accounts for the fact that the join could be a // join or a TSJ i.e. two possible logical choices. if (expr->getOperator().match(REL_ANY_NON_TSJ_JOIN)) child1Complexity = 2*child1Complexity ; } // add the right child subtree contribution to complexity result += child1Complexity; } // only REL_ANY_NON_TSJ_JOINs can permutate if (expr->getOperator().match(REL_ANY_NON_TSJ_JOIN)) freeLeaves++; // still in same permutation set else { // compute the last permuatation set contribution // to the complexity and start a new one result += freeLeaves * pow(2,freeLeaves-1); freeLeaves = 1; // start again } } // we do not handle VPJoin yet (nc==3) CascadesGroup* group0 = (*CURRSTMT_OPTGLOBALS->memo)[expr->child(0).getGroupId()]; // Only one log expr exist in the group at this point expr = group0->getFirstLogExpr(); } // leaf operators else expr = NULL; } // add last permutation set contribution result += freeLeaves * pow(2,freeLeaves-1); return result; } // calculate a query's MJ complexity, // shoud be called after MJ rewrite double RelExpr::calculateQueryMJComplexity(double &n,double &n2,double &n3,double &n4) { double result = 0; Int32 nc = getArity(); Int32 freeLeaves = nc; // # of subtree legs that can permutate RelExpr * expr = this; if (getOperatorType() == REL_MULTI_JOIN) { for (Int32 i = 0; i < nc; i++) { RelExpr * expri = expr->child(i); NABoolean childIsFullOuterJoinOrTSJ = child(i)->getGroupAnalysis()->getNodeAnalysis()-> getJBBC()->isFullOuterJoinOrTSJJBBC(); if (childIsFullOuterJoinOrTSJ) { NABoolean childIsOuterMost = !(child(i)->getGroupAnalysis()->getNodeAnalysis()-> getJBBC()->getOriginalParentJoin()); if(childIsOuterMost) freeLeaves--; } result += expri-> calculateQueryMJComplexity(n, n2, n3, n4); } //only do this for multijoins since only the children //of the multijoin will be permuted. //Note: This assumes the query tree to be the multijoinized //tree produced after multijoin rewrite in the Analyzer n += freeLeaves; n2 += pow(freeLeaves,2); n3 += pow(freeLeaves,3); n4 += pow(freeLeaves,4); result += freeLeaves * pow(2,freeLeaves-1); } else if(nc > 0) { if (nc == 1) { RelExpr * expr0 = expr->child(0); result += expr0-> calculateQueryMJComplexity(n, n2, n3, n4); } else if (nc == 2) { // only for joins, not for union // these will only be TSJ or Full Outer Joins // other joins become part of JBB if (expr->getOperator().match(REL_ANY_JOIN)) { RelExpr * expr0 = expr->child(0); result += expr0->calculateQueryMJComplexity(n, n2, n3, n4); RelExpr * expr1 = expr->child(1); result += expr1->calculateQueryMJComplexity(n, n2, n3, n4); } } } return result; } // ----------------------------------------------------------------------- // the following method is used to created a list of all scan operators // in order by size. // ----------------------------------------------------------------------- void RelExpr::makeListBySize(LIST(CostScalar) & orderedList, // order list of size NABoolean recompute) // recompute memory // limit -not used { Int32 nc = getArity(); RelExpr * expr = this; CostScalar size = 0; if (recompute) { // this needs to be filled in if this ever is redriven by costing CMPASSERT(NOT recompute); } else { if (expr->getOperatorType() == REL_SCAN OR expr->getOperatorType() == REL_GROUPBY) { //++MV, use the global empty input logical properties instead of //initializing a new one size = expr->getGroupAttr()->outputLogProp((*GLOBAL_EMPTY_INPUT_LOGPROP))->getResultCardinality() * expr->getGroupAttr()->getRecordLength() / 1024; } } if (size > 1) // don't include anything 1KB or less { CollIndex idx = 0; for (idx = 0; idx < orderedList.entries(); idx++) { // list should be ordered by increasing estimated rowcount. if (orderedList[idx] >= size) { orderedList.insertAt (idx, size); break; } } // insert at end of list if (idx >= orderedList.entries()) { orderedList.insertAt (orderedList.entries(), size); } } for (Lng32 i = 0; i < nc; i++) { CascadesGroup* group1 = (*CURRSTMT_OPTGLOBALS->memo)[expr->child(i).getGroupId()]; // Only one log expr exist in the group at this point // if onlyMemoryOps is ever set true, we will have to traverse // the tree differently RelExpr * expr1 = group1->getFirstLogExpr(); expr1->makeListBySize(orderedList, recompute); } } // Default implementation every RelExpr returns normal priority PlanPriority RelExpr::computeOperatorPriority (const Context* context, PlanWorkSpace *pws, Lng32 planNumber) { PlanPriority result; // This will create normal plan priority return result; } // ----------------------------------------------------------------------- // Method for debugging // ----------------------------------------------------------------------- void RelExpr::print(FILE * f, const char * prefix, const char * suffix) const { #ifndef NDEBUG ExprNode::print(f,prefix,suffix); fprintf(f,"%sRelational Expression:\n",prefix); if (selection_ != NULL) selection_->print(f,prefix,suffix); else predicates_.print(f,prefix,suffix); // print children or input equivalence classes Int32 nc = getArity(); for (Lng32 i = 0; i < nc; i++) { fprintf(f,"%sExpression input %d:\n",prefix,i); if (child(i).getMode() == ExprGroupId::MEMOIZED) { fprintf(f, "%s input eq. class #%d\n", prefix, child(i).getGroupId()); } else { if (child(i).getPtr() != NULL) child(i)->print(f,CONCAT(prefix," ")); else fprintf(f,"%snonexistent child\n",prefix); } } #endif } Int32 RelExpr::nodeCount() const { Int32 result = 1; // start from me. Int32 nc = getArity(); for (Lng32 i = 0; i < nc; i++) if (child(i).getPtr() != NULL) result += child(i)->nodeCount(); return result; } NABoolean RelExpr::containsNode(OperatorTypeEnum nodeType) { if (getOperatorType() == nodeType) return TRUE; Int32 nc = getArity(); for (Int32 i = 0; i < nc; i++) { if (child(i).getPtr() != NULL && child(i)->containsNode(nodeType)) return TRUE; } return FALSE; } double RelExpr::computeMemoryQuota(NABoolean inMaster, NABoolean perCPU, double BMOsMemoryLimit, // in bytes UInt16 totalNumBMOs, // per CPU double totalBMOsMemoryUsage, // per CPU, in bytes UInt16 numBMOsPerFragment, // per fragment double BMOsMemoryUsagePerFragment // per fragment, in bytes ) { if ( perCPU == TRUE ) { Lng32 exeMem = Lng32(BMOsMemoryLimit/(1024*1024)); if ( inMaster && CmpCommon::getDefault(ODBC_PROCESS) == DF_ON ) { // Limiting the total memory in the master process when in both // the per-CPU estimation and the ODBC mode. NADefaults &defs = ActiveSchemaDB()->getDefaults(); Lng32 inCpuLimitDelta = defs.getAsLong(EXE_MEMORY_AVAILABLE_IN_MB) - defs.getAsLong(EXE_MEMORY_RESERVED_FOR_MXOSRVR_IN_MB); if ( inCpuLimitDelta < 0 ) inCpuLimitDelta = 50; if (exeMem > inCpuLimitDelta) exeMem = inCpuLimitDelta; } // the quota is propotional to both the # of BMOs and the estimated memory // usage in the fragment, and evenly distrbuted among BMOs in the fragment. return ((exeMem/2) * (BMOsMemoryUsagePerFragment/totalBMOsMemoryUsage + double(numBMOsPerFragment)/totalNumBMOs) ) / numBMOsPerFragment; } else { // the old way to compute quota Lng32 exeMem = getExeMemoryAvailable(inMaster); return exeMem / numBMOsPerFragment; } } Lng32 RelExpr::getExeMemoryAvailable(NABoolean inMaster, Lng32 BMOsMemoryLimit) const { Lng32 exeMemAvailMB = BMOsMemoryLimit; if ((CmpCommon::getDefault(ODBC_PROCESS) == DF_ON) && inMaster && (exeMemAvailMB != 0)) // if the cqd is zero, then we do not do BMO quota { // Adjustment because MXOSRVR has QIO segments in competition with // executor. exeMemAvailMB -= ActiveSchemaDB()->getDefaults().getAsLong( EXE_MEMORY_RESERVED_FOR_MXOSRVR_IN_MB); if (exeMemAvailMB < 50) exeMemAvailMB = 50; } return exeMemAvailMB; } // RelExpr::getExeMemoryAvailable() Lng32 RelExpr::getExeMemoryAvailable(NABoolean inMaster) const { Lng32 exeMemAvailMB = ActiveSchemaDB()->getDefaults().getAsLong(EXE_MEMORY_AVAILABLE_IN_MB); return getExeMemoryAvailable(inMaster, exeMemAvailMB); } // ----------------------------------------------------------------------- // methods for class RelExprList // ----------------------------------------------------------------------- void RelExprList::insertOrderByRowcount (RelExpr * expr) { Int32 i = 0; NABoolean done = FALSE; // QSTUFF // insert stream expression as the left most expression // by articially forcing it to have lowest cost // assumes that only one stream and one embedded update clause // is in the statement if (expr->getGroupAttr()->isStream() || expr->getGroupAttr()->isEmbeddedUpdateOrDelete()) { insertAt(0,expr); done = TRUE; } // QSTUFF while (!done && i < (Int32)entries()) { CostScalar thisCard = (*this)[i]-> getGroupAttr()-> getResultCardinalityForEmptyInput(); CostScalar exprCard = expr-> getGroupAttr()-> getResultCardinalityForEmptyInput(); NABoolean increasing = ((ActiveSchemaDB()->getDefaults()).getAsULong(COMP_INT_90)==1); // list should be ordered by increasing estimated rowcount. if (((thisCard >= exprCard ) && increasing) || ((thisCard < exprCard ) && !increasing)) { // QSTUFF // stream and nested updates or deletes expressions should always be // left most, i.e of lowest cost if ( (*this)[i]->getGroupAttr()->isStream() || (*this)[i]->getGroupAttr()->isEmbeddedUpdateOrDelete()) i++; // QSTUFF insertAt (i, expr); done = TRUE; } else i++; } // insert at end of list if (!done) insertAt (entries(), expr); } NABoolean RelExprList::operator== (const RelExprList &other) const { if (entries() != other.entries()) return FALSE; for (Lng32 i = 0; i < (Lng32)entries(); i++) { if ((*this)[i] != other[i]) return FALSE; } return TRUE; } NABoolean RelExprList::operator!= (const RelExprList &other) const { if ((*this) == other) return FALSE; else return TRUE; } // ----------------------------------------------------------------------- // methods for class CutOp // ----------------------------------------------------------------------- CutOp::~CutOp() {} void CutOp::print(FILE * f, const char * prefix, const char *) const { #ifndef NDEBUG if (getGroupId() == INVALID_GROUP_ID) fprintf(f, "%sLeaf (%d)\n", prefix, index_); else fprintf(f, "%sLeaf (%d, bound to group #%d)\n", prefix, index_, getGroupId()); return; #endif } Int32 CutOp::getArity () const { return 0; } NABoolean CutOp::isCutOp() const { return TRUE; } const NAString CutOp::getText() const { char theText[TEXT_DISPLAY_LENGTH]; if (getGroupId() == INVALID_GROUP_ID) sprintf(theText, "Cut (%d)", index_); else if (index_ < 99) sprintf(theText, "Cut (%d, #%d)", index_, getGroupId()); else // don't display funny indexes (>= 99) sprintf(theText, "Cut (#%d)", getGroupId()); return NAString(theText); } RelExpr * CutOp::copyTopNode(RelExpr * derivedNode, CollHeap* outHeap) { if (getGroupId() == INVALID_GROUP_ID) { // this is a standalone cut operator (e.g. in the tree of a // CONTROL QUERY SHAPE directive), return a copy of it CMPASSERT(derivedNode == NULL); CutOp* result = new (outHeap)CutOp(index_, outHeap); return RelExpr::copyTopNode(result,outHeap); } else { // CutOps are shared among the pattern and the substitute of // a rule. Often the substitute is produced by calling the copyTree() // method on the "before" expression or a part of it. This implementation // of copyTopNode() makes it possible to do that. return this; } } void CutOp::setGroupIdAndAttr(CascadesGroupId groupId) { setGroupId(groupId); // set the group attributes of the leaf node to match the group if (groupId == INVALID_GROUP_ID) setGroupAttr(NULL); else setGroupAttr((*CURRSTMT_OPTGLOBALS->memo)[groupId]->getGroupAttr()); } void CutOp::setExpr(RelExpr *e) { expr_ = e; if (expr_ == NULL) { setGroupIdAndAttr(INVALID_GROUP_ID); } else { setGroupAttr(expr_->getGroupAttr()); // ##shouldn't this line.. // setGroupIdAndAttr(expr_->getGroupId()); // ##..be replaced by this? } } // ----------------------------------------------------------------------- // methods for class SubtreeOp // ----------------------------------------------------------------------- SubtreeOp::~SubtreeOp() {} Int32 SubtreeOp::getArity() const { return 0; } NABoolean SubtreeOp::isSubtreeOp() const { return TRUE; } const NAString SubtreeOp::getText() const { return NAString("Tree Op"); } RelExpr * SubtreeOp::copyTopNode(RelExpr *, CollHeap*) { return this; } // ----------------------------------------------------------------------- // methods for class WildCardOp // ----------------------------------------------------------------------- WildCardOp::~WildCardOp() {} Int32 WildCardOp::getArity() const { switch (getOperatorType()) { case REL_ANY_LEAF_OP: case REL_FORCE_ANY_SCAN: case REL_ANY_ROUTINE: case REL_FORCE_ANY_SCALAR_UDF: case REL_ANY_SCALAR_UDF_ROUTINE: case REL_ANY_LEAF_GEN_UPDATE: return 0; case REL_ANY_UNARY_GEN_UPDATE: case REL_ANY_UNARY_OP: case REL_ANY_GROUP: case REL_FORCE_EXCHANGE: return 1; case REL_ANY_BINARY_OP: case REL_ANY_JOIN: case REL_ANY_TSJ: case REL_ANY_SEMIJOIN: case REL_ANY_SEMITSJ: case REL_ANY_ANTI_SEMIJOIN: case REL_ANY_ANTI_SEMITSJ: case REL_ANY_INNER_JOIN: case REL_ANY_NON_TS_INNER_JOIN: case REL_ANY_NON_TSJ_JOIN: case REL_ANY_LEFT_JOIN: case REL_ANY_LEFT_TSJ: case REL_ANY_NESTED_JOIN: case REL_ANY_HASH_JOIN: case REL_ANY_MERGE_JOIN: case REL_FORCE_JOIN: case REL_FORCE_NESTED_JOIN: case REL_FORCE_HASH_JOIN: case REL_FORCE_ORDERED_HASH_JOIN: case REL_FORCE_HYBRID_HASH_JOIN: case REL_FORCE_MERGE_JOIN: case REL_FORCE_ORDERED_CROSS_PRODUCT: return 2; default: ABORT("WildCardOp with unknown arity encountered"); return 0; } } NABoolean WildCardOp::isWildcard() const { return TRUE; } const NAString WildCardOp::getText() const { switch (getOperatorType()) { case ANY_REL_OR_ITM_OP: return "ANY_REL_OR_ITM_OP"; case REL_ANY_LEAF_OP: return "REL_ANY_LEAF_OP"; case REL_ANY_UNARY_OP: return "REL_ANY_UNARY_OP"; case REL_ANY_ROUTINE: return "REL_ANY_ROUTINE"; case REL_ANY_GEN_UPDATE: return "REL_ANY_GEN_UPDATE"; case REL_ANY_UNARY_GEN_UPDATE: return "REL_ANY_UNARY_GEN_UPDATE"; case REL_ANY_LEAF_GEN_UPDATE: return "REL_ANY_LEAF_GEN_UPDATE"; case REL_ANY_GROUP: return "REL_ANY_GROUP"; case REL_ANY_BINARY_OP: return "REL_ANY_BINARY_OP"; case REL_ANY_JOIN: return "REL_ANY_JOIN"; case REL_ANY_TSJ: return "REL_ANY_TSJ"; case REL_ANY_SEMIJOIN: return "REL_ANY_SEMIJOIN"; case REL_ANY_SEMITSJ: return "REL_ANY_SEMITSJ"; case REL_ANY_INNER_JOIN: return "REL_ANY_INNER_JOIN"; case REL_ANY_LEFT_JOIN: return "REL_ANY_LEFT_JOIN"; case REL_ANY_LEFT_TSJ: return "REL_ANY_LEFT_TSJ"; case REL_ANY_NESTED_JOIN: return "REL_ANY_NESTED_JOIN"; case REL_ANY_HASH_JOIN: return "REL_ANY_HASH_JOIN"; case REL_ANY_MERGE_JOIN: return "REL_ANY_MERGE_JOIN"; case REL_FORCE_ANY_SCAN: return "REL_FORCE_ANY_SCAN"; case REL_FORCE_EXCHANGE: return "REL_FORCE_EXCHANGE"; case REL_FORCE_JOIN: return "REL_FORCE_JOIN"; case REL_FORCE_NESTED_JOIN: return "REL_FORCE_NESTED_JOIN"; case REL_FORCE_HASH_JOIN: return "REL_FORCE_HASH_JOIN"; case REL_FORCE_HYBRID_HASH_JOIN: return "REL_FORCE_HYBRID_HASH_JOIN"; case REL_FORCE_ORDERED_HASH_JOIN: return "REL_FORCE_ORDERED_HASH_JOIN"; case REL_FORCE_MERGE_JOIN: return "REL_FORCE_MERGE_JOIN"; default: return "unknown??"; } } RelExpr * WildCardOp::copyTopNode(RelExpr * derivedNode, CollHeap* outHeap) { if (corrNode_ != NULL) return corrNode_->copyTopNode(0, outHeap); else { if (derivedNode != NULL) return derivedNode; else { WildCardOp* result; result = new (outHeap) WildCardOp(getOperatorType(), 0, NULL, NULL, outHeap); return RelExpr::copyTopNode(result,outHeap); } } #pragma nowarn(203) // warning elimination return NULL; // shouldn't really reach here #pragma warn(203) // warning elimination } // ----------------------------------------------------------------------- // member functions for class ScanForceWildCard // ----------------------------------------------------------------------- ScanForceWildCard::ScanForceWildCard(CollHeap * outHeap) : WildCardOp(REL_FORCE_ANY_SCAN), exposedName_(outHeap), indexName_(outHeap) {initializeScanOptions();} ScanForceWildCard::ScanForceWildCard(const NAString& exposedName, CollHeap *outHeap) : WildCardOp(REL_FORCE_ANY_SCAN,0,NULL,NULL,outHeap), exposedName_(exposedName, outHeap), indexName_(outHeap) {initializeScanOptions();} ScanForceWildCard::ScanForceWildCard(const NAString& exposedName, const NAString& indexName, CollHeap *outHeap) : WildCardOp(REL_FORCE_ANY_SCAN,0,NULL,NULL,outHeap), exposedName_(exposedName, outHeap), indexName_(indexName, outHeap) {initializeScanOptions();} ScanForceWildCard::~ScanForceWildCard() { collHeap()->deallocateMemory((void*)enumAlgorithms_); // delete enumAlgorithms_ from the same heap were the // ScanForceWildCard object belong } //---------------------------------------------------------- // initialize class members //---------------------------------------------------------- void ScanForceWildCard::initializeScanOptions() { mdamStatus_ = UNDEFINED; direction_ = UNDEFINED; indexStatus_ = UNDEFINED; numMdamColumns_ = 0; mdamColumnsStatus_ = UNDEFINED; enumAlgorithms_ = NULL; numberOfBlocksToReadPerAccess_ = -1; } //---------------------------------------------------------- // get the enumeration algorithm (density) for column // if beyound specified columns return COLUMN_SYSTEM //---------------------------------------------------------- ScanForceWildCard::scanOptionEnum ScanForceWildCard::getEnumAlgorithmForColumn(CollIndex column) const { if (column >= numMdamColumns_) return ScanForceWildCard::COLUMN_SYSTEM; else return enumAlgorithms_[column]; } //---------------------------------------------------------- // set the following scan option. return FALSE only if // such option does not exist. //---------------------------------------------------------- NABoolean ScanForceWildCard::setScanOptions(ScanForceWildCard::scanOptionEnum option) { if (option == INDEX_SYSTEM) { indexStatus_ = INDEX_SYSTEM; return TRUE; } else if (option == MDAM_SYSTEM) { mdamStatus_ = MDAM_SYSTEM; return TRUE; } else if (option == MDAM_OFF) { mdamStatus_ = MDAM_OFF; return TRUE; } else if (option == MDAM_FORCED) { mdamStatus_ = MDAM_FORCED; return TRUE; } else if (option == DIRECTION_FORWARD) { direction_ = DIRECTION_FORWARD; return TRUE; } else if (option == DIRECTION_REVERSED) { direction_ = DIRECTION_REVERSED; return TRUE; } else if (option == DIRECTION_SYSTEM) { direction_ = DIRECTION_SYSTEM; return TRUE; } else return FALSE; } NABoolean ScanForceWildCard::setIndexName(const NAString& value) { if (value != "") { indexName_ = value; return TRUE; } else return FALSE; // Error should be nonempty string } //---------------------------------------------------------- // set the columns options based on passed values //---------------------------------------------------------- NABoolean ScanForceWildCard:: setColumnOptions(CollIndex numColumns, ScanForceWildCard::scanOptionEnum* columnAlgorithms, ScanForceWildCard::scanOptionEnum mdamColumnsStatus) { mdamStatus_ = MDAM_FORCED; mdamColumnsStatus_ = mdamColumnsStatus; numMdamColumns_ = numColumns; // delete enumAlgorithms_ from the same heap were the // ScanForceWildCard object belong collHeap()->deallocateMemory((void*)enumAlgorithms_); // allocate enumAlgorithms_[numMdamColumns] in the same heap // were the ScanForceWildCard object belong enumAlgorithms_ = (ScanForceWildCard::scanOptionEnum*) collHeap()->allocateMemory(sizeof(ScanForceWildCard::scanOptionEnum)*numMdamColumns_); for (CollIndex i=0; i<numMdamColumns_; i++) enumAlgorithms_[i] = columnAlgorithms[i]; return TRUE; } //---------------------------------------------------------- // set the columns options based on passed values // here options for particular columns are not passed // and hence COLUMN_SYSTEM is assigned //---------------------------------------------------------- NABoolean ScanForceWildCard:: setColumnOptions(CollIndex numColumns, ScanForceWildCard::scanOptionEnum mdamColumnsStatus) { mdamStatus_ = MDAM_FORCED; mdamColumnsStatus_ = mdamColumnsStatus; numMdamColumns_ = numColumns; // delete enumAlgorithms_ from the same heap were the // ScanForceWildCard object belong collHeap()->deallocateMemory((void*)enumAlgorithms_); // allocate enumAlgorithms_[numMdamColumns] in the same heap // were the ScanForceWildCard object belong enumAlgorithms_ = (ScanForceWildCard::scanOptionEnum*) collHeap()->allocateMemory(sizeof(ScanForceWildCard::scanOptionEnum)*numMdamColumns_); //enumAlgorithms_ = new scanOptionEnum[numMdamColumns_]; for (CollIndex i=0; i<numMdamColumns_; i++) enumAlgorithms_[i] = COLUMN_SYSTEM; return TRUE; } //---------------------------------------------------------- // check if the forced scan options conflict with the Mdam // Master switch status //---------------------------------------------------------- NABoolean ScanForceWildCard::doesThisCoflictMasterSwitch() const { char* globalMdamStatus = getenv("MDAM"); if (globalMdamStatus != NULL) { if (strcmp(globalMdamStatus,"OFF")==0 ) { if ((mdamStatus_ == MDAM_FORCED)||(mdamStatus_ == MDAM_SYSTEM)) return TRUE; } } return FALSE; } //---------------------------------------------------------- // merge with another ScanForceWildCard object. // return FALSE if a conflict between the options of // the two objects exists. //---------------------------------------------------------- NABoolean ScanForceWildCard::mergeScanOptions(const ScanForceWildCard &other) { if ((other.exposedName_ != "") &&(other.exposedName_ != exposedName_)) { if (exposedName_ == "") { exposedName_ = other.exposedName_; } else return FALSE; // conflict } if ((other.indexName_ != "") &&(other.indexName_ != indexName_)) { if (indexName_ == "") { indexName_ = other.indexName_; } else return FALSE; // conflict } if (other.indexStatus_ == INDEX_SYSTEM) { indexStatus_ = INDEX_SYSTEM; } if (indexStatus_ == INDEX_SYSTEM) { if (indexName_ != "") return FALSE; // conflict } if ((other.mdamStatus_ == MDAM_OFF) &&(mdamStatus_ != MDAM_OFF)) { if (mdamStatus_ == UNDEFINED) { mdamStatus_ = other.mdamStatus_; } else return FALSE; // conflict } if ((other.mdamStatus_ == MDAM_SYSTEM) &&(mdamStatus_ != MDAM_SYSTEM)) { if (mdamStatus_ == UNDEFINED) { mdamStatus_ = other.mdamStatus_; } else return FALSE; // conflict } if ((other.mdamStatus_ == MDAM_FORCED) &&(mdamStatus_ != MDAM_FORCED)) { if (mdamStatus_ == UNDEFINED) { mdamStatus_ = other.mdamStatus_; } else return FALSE; // conflict } if (other.numMdamColumns_ > 0) { if ((mdamStatus_ == UNDEFINED)||(mdamStatus_ == MDAM_FORCED)) { if (numMdamColumns_ == other.numMdamColumns_) { for (CollIndex i=0; i<numMdamColumns_; i++) { if (enumAlgorithms_[i] != other.enumAlgorithms_[i]) return FALSE; // conflict } if (other.mdamColumnsStatus_ != mdamColumnsStatus_) return FALSE; // conflict } else if (numMdamColumns_ == 0) // i.e. enumAlgorithm is NULL { numMdamColumns_ = other.numMdamColumns_; collHeap()->deallocateMemory((void*)enumAlgorithms_); //delete enumAlgorithms_; enumAlgorithms_ = (ScanForceWildCard::scanOptionEnum*) collHeap()->allocateMemory(sizeof(ScanForceWildCard::scanOptionEnum)*numMdamColumns_); //enumAlgorithms_ = new scanOptionEnum[numMdamColumns_]; for (CollIndex i=0; i<numMdamColumns_; i++) { enumAlgorithms_[i] = other.enumAlgorithms_[i]; } } else return FALSE; // coflict } else return FALSE; // conflict } if (other.mdamColumnsStatus_ != UNDEFINED) { if (mdamColumnsStatus_ == UNDEFINED) { mdamColumnsStatus_ = other.mdamColumnsStatus_; } if (mdamColumnsStatus_ != other.mdamColumnsStatus_) { return FALSE; // conflict } } if ((other.direction_ == DIRECTION_FORWARD) &&(direction_ != DIRECTION_FORWARD)) { if (direction_ == UNDEFINED) { direction_ = other.direction_; } else return FALSE; // conflict } if ((other.direction_ == DIRECTION_REVERSED) &&(direction_ != DIRECTION_REVERSED)) { if (direction_ == UNDEFINED) { direction_ = other.direction_; } else return FALSE; // conflict } if ((other.direction_ == DIRECTION_SYSTEM) &&(direction_ != DIRECTION_SYSTEM)) { if (direction_ == UNDEFINED) { direction_ = other.direction_; } else return FALSE; // conflict } if (other.numberOfBlocksToReadPerAccess_ > 0) { numberOfBlocksToReadPerAccess_ = other.numberOfBlocksToReadPerAccess_; } return TRUE; } //---------------------------------------------------------- // if access path is not given then the default is ANY i.e // system choice unless MDAM is forced then the default is // the base table. //---------------------------------------------------------- void ScanForceWildCard::prepare() { if (mdamStatus_ != ScanForceWildCard::MDAM_FORCED) { if (indexName_ == "") { indexStatus_ = ScanForceWildCard::INDEX_SYSTEM; } } else // mdam is forced { if ((indexName_ == "") && (indexStatus_ != ScanForceWildCard::INDEX_SYSTEM)) { indexName_ = exposedName_; } } if (mdamColumnsStatus_ == ScanForceWildCard::UNDEFINED) { mdamColumnsStatus_ = ScanForceWildCard::MDAM_COLUMNS_REST_BY_SYSTEM; } return; } RelExpr * ScanForceWildCard::copyTopNode(RelExpr *derivedNode, CollHeap* outHeap) { ScanForceWildCard *temp; if (derivedNode != NULL) ABORT("No support for classes derived from ScanForceWildcard"); temp = new (outHeap) ScanForceWildCard(exposedName_,indexName_,outHeap); temp->direction_ = direction_; temp->indexStatus_ = indexStatus_; temp->mdamStatus_ = mdamStatus_; temp->mdamColumnsStatus_ = mdamColumnsStatus_; temp->numMdamColumns_ = numMdamColumns_; temp->numberOfBlocksToReadPerAccess_ = numberOfBlocksToReadPerAccess_; temp->enumAlgorithms_ = new (outHeap) scanOptionEnum[numMdamColumns_]; for (CollIndex i=0; i<numMdamColumns_; i++) { temp->enumAlgorithms_[i]=enumAlgorithms_[i]; } RelExpr *result = temp; WildCardOp::copyTopNode(result,outHeap); return result; } const NAString ScanForceWildCard::getText() const { NAString result("forced scan", CmpCommon::statementHeap()); if (exposedName_ != "") { result += "("; result += exposedName_; if (indexName_ != "") { result += ", index "; result += indexName_; } result += ")"; } return result; } // ----------------------------------------------------------------------- // member functions for class JoinForceWildCard // ----------------------------------------------------------------------- JoinForceWildCard::JoinForceWildCard(OperatorTypeEnum type, RelExpr *child0, RelExpr *child1, forcedPlanEnum plan, Int32 numOfEsps, CollHeap *outHeap) : WildCardOp(type, 0, child0, child1,outHeap) { plan_ = plan; numOfEsps_ = numOfEsps; } JoinForceWildCard::~JoinForceWildCard() {} RelExpr * JoinForceWildCard::copyTopNode(RelExpr *derivedNode, CollHeap* outHeap) { RelExpr *result; if (derivedNode != NULL) ABORT("No support for classes derived from JoinForceWildcard"); result = new(outHeap) JoinForceWildCard(getOperatorType(), NULL, NULL, plan_, numOfEsps_, outHeap); WildCardOp::copyTopNode(result,outHeap); return result; } const NAString JoinForceWildCard::getText() const { NAString result("forced", CmpCommon::statementHeap()); if (plan_ == FORCED_PLAN0) result += " plan0"; else if (plan_ == FORCED_PLAN1) result += " plan1"; else if (plan_ == FORCED_PLAN2) result += " plan2"; else if (plan_ == FORCED_TYPE1) result += " type1"; else if (plan_ == FORCED_TYPE2) result += " type2"; else if (plan_ == FORCED_INDEXJOIN) result += " indexjoin"; switch (getOperatorType()) { case REL_FORCE_NESTED_JOIN: result += " nested join"; break; case REL_FORCE_MERGE_JOIN: result += " merge join"; break; case REL_FORCE_HASH_JOIN: result += " hash join"; break; case REL_FORCE_HYBRID_HASH_JOIN: result += " hybrid hash join"; break; case REL_FORCE_ORDERED_HASH_JOIN: result += " ordered hash join"; break; default: result += " join"; break; } return result; } // ----------------------------------------------------------------------- // member functions for class ExchangeForceWildCard // ----------------------------------------------------------------------- ExchangeForceWildCard::ExchangeForceWildCard(RelExpr *child0, forcedExchEnum which, forcedLogPartEnum whatLogPart, Lng32 numBottomEsps, CollHeap *outHeap) : WildCardOp(REL_FORCE_EXCHANGE, 0, child0, NULL, outHeap), which_(which), whatLogPart_(whatLogPart), howMany_(numBottomEsps) { } ExchangeForceWildCard::~ExchangeForceWildCard() {} RelExpr * ExchangeForceWildCard::copyTopNode(RelExpr *derivedNode, CollHeap* outHeap) { RelExpr *result; if (derivedNode != NULL) ABORT("No support for classes derived from ExchangeForceWildcard"); result = new(outHeap) ExchangeForceWildCard(NULL, which_, whatLogPart_, howMany_, outHeap); WildCardOp::copyTopNode(result,outHeap); return result; } const NAString ExchangeForceWildCard::getText() const { NAString result("forced",CmpCommon::statementHeap()); if (which_ == FORCED_PA) result += " PA"; else if (which_ == FORCED_PAPA) result += " PAPA"; else if (which_ == FORCED_ESP_EXCHANGE) result += " ESP"; result += " exchange"; return result; } // ----------------------------------------------------------------------- // member functions for class UDFForceWildCard // ----------------------------------------------------------------------- UDFForceWildCard::UDFForceWildCard(OperatorTypeEnum op, CollHeap *outHeap) : WildCardOp(op, 0, NULL, NULL, outHeap), functionName_(outHeap), actionName_(outHeap) {} UDFForceWildCard::UDFForceWildCard(const NAString& functionName, const NAString& actionName, CollHeap *outHeap) : WildCardOp(REL_FORCE_ANY_SCALAR_UDF, 0, NULL, NULL, outHeap), functionName_(functionName, outHeap), actionName_(actionName, outHeap) {} UDFForceWildCard::~UDFForceWildCard() { } //---------------------------------------------------------- // merge with another UDFForceWildCard object. // return FALSE if a conflict between the options of // the two objects exists. //---------------------------------------------------------- NABoolean UDFForceWildCard::mergeUDFOptions(const UDFForceWildCard &other) { if ((other.functionName_ != "") &&(other.functionName_ != functionName_)) { if (functionName_ == "") { functionName_ = other.functionName_; } else return FALSE; // conflict } if ((other.actionName_ != "") &&(other.actionName_ != actionName_)) { if (actionName_ == "") { actionName_ = other.actionName_; } else return FALSE; // conflict } return TRUE; } RelExpr * UDFForceWildCard::copyTopNode(RelExpr *derivedNode, CollHeap* outHeap) { UDFForceWildCard *temp; if (derivedNode != NULL) ABORT("No support for classes derived from UDFForceWildCard"); temp = new (outHeap) UDFForceWildCard(functionName_,actionName_,outHeap); RelExpr *result = temp; WildCardOp::copyTopNode(result,outHeap); return result; } const NAString UDFForceWildCard::getText() const { NAString result("forced UDF", CmpCommon::statementHeap()); if (functionName_ != "") { result += "("; result += functionName_; if (actionName_ != "") { result += ", "; result += actionName_; } result += ")"; } return result; } // ----------------------------------------------------------------------- // member functions for Control* base class // ----------------------------------------------------------------------- ControlAbstractClass::~ControlAbstractClass() {} NABoolean ControlAbstractClass::duplicateMatch(const RelExpr & other) const { if (NOT RelExpr::duplicateMatch(other)) return FALSE; ControlAbstractClass &o = (ControlAbstractClass &) other; // We do NOT need to compare sqlText's here return (token_ == o.token_ AND value_ == o.value_ AND dynamic_ == o.dynamic_ AND reset_ == o.reset_); } RelExpr *ControlAbstractClass::copyTopNode(RelExpr *derivedNode, CollHeap *h) { CMPASSERT(derivedNode); ((ControlAbstractClass *)derivedNode)->reset_ = reset_; return derivedNode; } NABoolean ControlAbstractClass::alterArkcmpEnvNow() const { return NOT (dynamic() || CmpCommon::context()->GetMode() == STMT_DYNAMIC); } StaticOnly ControlAbstractClass::isAStaticOnlyStatement() const { if (dynamic_) return NOT_STATIC_ONLY; return (getOperatorType() == REL_CONTROL_QUERY_DEFAULT) ? STATIC_ONLY_WITH_WORK_FOR_PREPROCESSOR : STATIC_ONLY_VANILLA; } static void removeLeadingSpace(NAString &sqlText) { if (!sqlText.isNull() && isspace((unsigned char)sqlText[size_t(0)])) sqlText.remove(0, 1); // For VS2003 } static NABoolean beginsWithKeyword(NAString &sqlText, const char *kwd, NABoolean thenRemoveIt = TRUE) { // Assumes Prettify has been called, so only one space (at most) btw tokens. // If this is called more than once, the second time in the text might begin // with a delimiting space. removeLeadingSpace(sqlText); size_t len = strlen(kwd) + 1; // +1 for delimiter (space) if (sqlText.length() > len) { NAString tmp(sqlText,CmpCommon::statementHeap()); tmp.remove(len); char c = tmp[--len]; // delimiter if (!isalnum(c) && c != '_') { tmp.remove(len); // remove the delimiter 'c' from tmp if (tmp == kwd) { if (thenRemoveIt) sqlText.remove(0, len); // leave delimiter, now at beginning return TRUE; } } } return FALSE; } // Convert "PROCEDURE xyz () CONTROL..." to just the "CONTROL..." part. // Convert a dynamic stmt's text of "SET SCHEMA 'x.y';" // into the static "CONTROL QUERY DEFAULT SCHEMA 'x.y';" // for its round-trip to executor and back here as a SQLTEXT_STATIC_COMPILE. void ControlAbstractClass::rewriteControlText( NAString &sqlText, CharInfo::CharSet sqlTextCharSet, ControlAbstractClass *ctrl) { PrettifySqlText(sqlText); // trim, upcase where okay, cvt tabs to spaces if (beginsWithKeyword(sqlText, "PROCEDURE")) { size_t rp = sqlText.index(')'); CMPASSERT(rp != NA_NPOS); sqlText.remove(0, ++rp); removeLeadingSpace(sqlText); } // if SHOWSHAPE or SHOWPLAN, remove them from the beginning. // beginsWithKeyword will remove the keyword, if found. if ((beginsWithKeyword(sqlText, "SHOWSHAPE")) || (beginsWithKeyword(sqlText, "SHOWPLAN"))) { removeLeadingSpace(sqlText); } if (ctrl->dynamic()) { if ((beginsWithKeyword(sqlText, "SET")) && (ctrl->getOperatorType() != REL_SET_SESSION_DEFAULT)) sqlText.prepend(getControlTextPrefix(ctrl)); } else { if (beginsWithKeyword(sqlText, "DECLARE")) sqlText.prepend(getControlTextPrefix(ctrl)); } //## We'll have to fix SqlParser.y, I think, if this stmt appears in //## a compound stmt (IF ... THEN SET SCHEMA 'x' ... ELSE SET SCHEMA 'y' ...) if (ctrl->getOperatorType() != REL_SET_SESSION_DEFAULT) { if ((NOT beginsWithKeyword(sqlText, "CONTROL", FALSE)) && (NOT beginsWithKeyword(sqlText, "CQD", FALSE))) CMPASSERT(0); } } NAString ControlAbstractClass::getControlTextPrefix( const ControlAbstractClass *ctrl) { switch (ctrl->getOperatorType()) { case REL_CONTROL_QUERY_SHAPE: return "CONTROL QUERY SHAPE"; case REL_CONTROL_QUERY_DEFAULT: return "CONTROL QUERY DEFAULT"; case REL_CONTROL_TABLE: return "CONTROL TABLE"; case REL_CONTROL_SESSION: return "CONTROL SESSION"; case REL_SET_SESSION_DEFAULT: return "SET SESSION DEFAULT"; default: return "CONTROL ??"; } } // ----------------------------------------------------------------------- // member functions for class ControlQueryShape // ----------------------------------------------------------------------- RelExpr * ControlQueryShape::copyTopNode(RelExpr *derivedNode, CollHeap *h) { ControlQueryShape *result; if (derivedNode == NULL) result = new (h) ControlQueryShape(NULL, getSqlText(), getSqlTextCharSet(), holdShape_, dynamic_, ignoreExchange_, ignoreSort_, h); else result = (ControlQueryShape *) derivedNode; return ControlAbstractClass::copyTopNode(result,h); } const NAString ControlQueryShape::getText() const { NAString result(getControlTextPrefix(this)); if (ignoreExchange_) { if (ignoreSort_) result += " WITHOUT ENFORCERS"; else result += " WITHOUT EXCHANGE"; } else if (ignoreSort_) result += " WITHOUT SORT"; return result; } // ----------------------------------------------------------------------- // member functions for class ControlQueryDefault // ----------------------------------------------------------------------- ControlQueryDefault::ControlQueryDefault( const NAString &sqlText, CharInfo::CharSet sqlTextCharSet, const NAString &token, const NAString &value, NABoolean dyn, Lng32 holdOrRestoreCQD, CollHeap *h, Int32 reset): ControlAbstractClass(REL_CONTROL_QUERY_DEFAULT, sqlText, sqlTextCharSet, token, value, dyn, h, reset), holdOrRestoreCQD_(holdOrRestoreCQD), attrEnum_(__INVALID_DEFAULT_ATTRIBUTE) {} RelExpr * ControlQueryDefault::copyTopNode(RelExpr *derivedNode, CollHeap *h) { RelExpr *result; if (derivedNode == NULL) { result = new (h) ControlQueryDefault(sqlText_, sqlTextCharSet_, token_, value_, dynamic_, holdOrRestoreCQD_, h); ((ControlQueryDefault *)result)->attrEnum_ = attrEnum_; } else result = derivedNode; return ControlAbstractClass::copyTopNode(result,h); } const NAString ControlQueryDefault::getText() const { return getControlTextPrefix(this); } // ----------------------------------------------------------------------- // member functions for class ControlTable // ----------------------------------------------------------------------- ControlTable::ControlTable( CorrName *tableName, const NAString &sqlText, CharInfo::CharSet sqlTextCharSet, const NAString &token, const NAString &value, NABoolean dyn, CollHeap *h): ControlAbstractClass(REL_CONTROL_TABLE, sqlText, sqlTextCharSet, token, value, dyn, h), tableName_(tableName) {} RelExpr * ControlTable::copyTopNode(RelExpr *derivedNode, CollHeap *h) { RelExpr *result; if (derivedNode == NULL) result = new (h) ControlTable(tableName_, sqlText_, sqlTextCharSet_, token_, value_, dynamic_, h); else result = derivedNode; return ControlAbstractClass::copyTopNode(result,h); } const NAString ControlTable::getText() const { return getControlTextPrefix(this); } // ----------------------------------------------------------------------- // member functions for class ControlSession // ----------------------------------------------------------------------- ControlSession::ControlSession( const NAString &sqlText, CharInfo::CharSet sqlTextCharSet, const NAString &token, const NAString &value, NABoolean dyn, CollHeap *h): ControlAbstractClass(REL_CONTROL_SESSION, sqlText, sqlTextCharSet, token, value, dyn, h) {} RelExpr * ControlSession::copyTopNode(RelExpr *derivedNode, CollHeap *h) { RelExpr *result; if (derivedNode == NULL) result = new (h) ControlSession(sqlText_, sqlTextCharSet_, token_, value_, dynamic_, h); else result = derivedNode; return ControlAbstractClass::copyTopNode(result,h); } const NAString ControlSession::getText() const { return getControlTextPrefix(this); } // ----------------------------------------------------------------------- // member functions for class SetSessionDefault // ----------------------------------------------------------------------- SetSessionDefault::SetSessionDefault( const NAString &sqlText, CharInfo::CharSet sqlTextCharSet, const NAString &token, const NAString &value, CollHeap *h): ControlAbstractClass(REL_SET_SESSION_DEFAULT, sqlText, sqlTextCharSet, token, value, TRUE, h) {} RelExpr * SetSessionDefault::copyTopNode(RelExpr *derivedNode, CollHeap *h) { RelExpr *result; if (derivedNode == NULL) result = new (h) SetSessionDefault(sqlText_, sqlTextCharSet_, token_, value_, h); else result = derivedNode; return ControlAbstractClass::copyTopNode(result,h); } const NAString SetSessionDefault::getText() const { return getControlTextPrefix(this); } // ----------------------------------------------------------------------- // member functions for class OSIMControl // ----------------------------------------------------------------------- OSIMControl::OSIMControl(OptimizerSimulator::osimMode mode, NAString & localDir, NABoolean force, CollHeap * oHeap) //the real work is done in OSIMControl::bindNode() to control OSIM. //We set operator type to REL_SET_SESSION_DEFAULT, //so as not to define dummy OSIMControl::codeGen() and OSIMControl::work(), //which will do nothing there, : ControlAbstractClass(REL_SET_SESSION_DEFAULT, NAString("DUMMYSQLTEXT", oHeap), CharInfo::ISO88591, NAString("OSIM", oHeap), NAString("DUMMYVALUE", oHeap), TRUE, oHeap) , targetMode_(mode), osimLocalDir_(localDir, oHeap), forceLoad_(force) {} RelExpr * OSIMControl::copyTopNode(RelExpr *derivedNode, CollHeap *h ) { RelExpr *result; if (derivedNode == NULL) result = new (h) OSIMControl(targetMode_, osimLocalDir_, forceLoad_, h); else result = derivedNode; return ControlAbstractClass::copyTopNode(result,h); } // ----------------------------------------------------------------------- // member functions for class Sort // ----------------------------------------------------------------------- Sort::~Sort() { } Int32 Sort::getArity() const { return 1;} HashValue Sort::topHash() { HashValue result = RelExpr::topHash(); result ^= sortKey_; result ^= arrangedCols_; return result; } NABoolean Sort::duplicateMatch(const RelExpr & other) const { if (NOT RelExpr::duplicateMatch(other)) return FALSE; Sort &o = (Sort &) other; if (NOT (sortKey_ == o.sortKey_) OR NOT(arrangedCols_ == o.arrangedCols_)) return FALSE; return TRUE; } RelExpr * Sort::copyTopNode(RelExpr *derivedNode, CollHeap* outHeap) { Sort *result; if (derivedNode == NULL) result = new (outHeap) Sort(NULL, sortKey_, outHeap); else result = (Sort *) derivedNode; // copy arranged columns result->arrangedCols_ = arrangedCols_; return RelExpr::copyTopNode(result, outHeap); } NABoolean Sort::isLogical() const { return FALSE; } NABoolean Sort::isPhysical() const { return TRUE; } const NAString Sort::getText() const { return "sort"; } PlanPriority Sort::computeOperatorPriority (const Context* context, PlanWorkSpace *pws, Lng32 planNumber) { const PhysicalProperty* spp = context->getPlan()->getPhysicalProperty(); Lng32 degreeOfParallelism = spp->getCountOfPartitions(); double val = 1; if (degreeOfParallelism <= 1) { // serial plans are risky. exact an insurance premium from serial plans. val = CURRSTMT_OPTDEFAULTS->riskPremiumSerial(); } CostScalar premium(val); PlanPriority result(0, 0, premium); if (QueryAnalysis::Instance() AND QueryAnalysis::Instance()->optimizeForFirstNRows()) result.incrementLevels(SORT_FIRST_N_PRIORITY,0); // For the option of Max Degree of Parallelism we can either use the // value set in comp_int_9 (if positive) or we use the number of CPUs // if the CQD is set to -1, or feature is disabled if CQD is 0 (default). Lng32 maxDegree = ActiveSchemaDB()->getDefaults().getAsLong(COMP_INT_9); if (CURRSTMT_OPTDEFAULTS->maxParallelismIsFeasible() OR ( maxDegree == -1) ) { // if CQD is set to -1 this mean use the number of CPUs maxDegree = spp->getCurrentCountOfCPUs(); } if (maxDegree > 1) // CQD set to 0 means feature is OFF { if (degreeOfParallelism < maxDegree) result.incrementLevels(0,-10); // need to replace with constant } return result; } void Sort::addLocalExpr(LIST(ExprNode *) &xlist, LIST(NAString) &llist) const { if (sortKey_.entries() > 0) { xlist.insert(sortKey_.rebuildExprTree(ITM_ITEM_LIST)); llist.insert("sort_key"); } if (PartialSortKeyFromChild_.entries() > 0) { xlist.insert(PartialSortKeyFromChild_.rebuildExprTree(ITM_ITEM_LIST)); llist.insert("PartialSort_FromChild"); } // if (NOT arrangedCols_.isEmpty()) // { // xlist.insert(arrangedCols_.rebuildExprTree(ITM_ITEM_LIST)); // llist.insert("arranged_cols"); // } RelExpr::addLocalExpr(xlist,llist); } void Sort::needSortedNRows(NABoolean val) { sortNRows_ = val; RelExpr::needSortedNRows(val); } // ----------------------------------------------------------------------- // member functions for class SortFromTop // ----------------------------------------------------------------------- RelExpr * SortFromTop::copyTopNode(RelExpr *derivedNode, CollHeap* outHeap) { SortFromTop *result; if (derivedNode == NULL) result = new (outHeap) SortFromTop(NULL, outHeap); else result = (SortFromTop *) derivedNode; result->getSortRecExpr() = getSortRecExpr(); return Sort::copyTopNode(result, outHeap); } const NAString SortFromTop::getText() const { return "sort_from_top"; } // ----------------------------------------------------------------------- // member functions for class Exchange // ----------------------------------------------------------------------- Exchange::~Exchange() { } Int32 Exchange::getArity() const { return 1;} RelExpr * Exchange::copyTopNode(RelExpr *derivedNode, CollHeap* outHeap) { Exchange *result; if (derivedNode == NULL) { result = new (outHeap) Exchange(NULL, outHeap); } else result = (Exchange *) derivedNode; result->upMessageBufferLength_=upMessageBufferLength_; result->downMessageBufferLength_=downMessageBufferLength_; result->hash2RepartitioningWithSameKey_ = hash2RepartitioningWithSameKey_; if (halloweenSortIsMyChild_) result->markHalloweenSortIsMyChild(); return RelExpr::copyTopNode(result, outHeap); } NABoolean Exchange::isLogical() const { return FALSE; } NABoolean Exchange::isPhysical() const { return TRUE; } NABoolean Exchange::isAPA() const { if (NOT isDP2Exchange() OR bottomPartFunc_ == NULL) return FALSE; const LogPhysPartitioningFunction *lpf = bottomPartFunc_-> castToLogPhysPartitioningFunction(); return (lpf == NULL OR NOT lpf->getUsePapa()); } NABoolean Exchange::isAPAPA() const { return (isDP2Exchange() AND bottomPartFunc_ AND NOT isAPA()); } const NAString Exchange::getText() const { NAString result("exchange",CmpCommon::statementHeap()); if (isAPA()) result = "pa_exchange"; else if (isAPAPA()) result = "split_top"; else if (isAnESPAccess()) result = "esp_access"; else if (isEspExchange()) result = "esp_exchange"; const PartitioningFunction *topPartFunc = getTopPartitioningFunction(); const PartitioningFunction *bottomPartFunc = getBottomPartitioningFunction(); Lng32 topNumParts = ANY_NUMBER_OF_PARTITIONS; Lng32 bottomNumParts = ANY_NUMBER_OF_PARTITIONS; if (topPartFunc) topNumParts = topPartFunc->getCountOfPartitions(); if (bottomPartFunc) bottomNumParts = bottomPartFunc->getCountOfPartitions(); if (topNumParts != ANY_NUMBER_OF_PARTITIONS OR bottomNumParts != ANY_NUMBER_OF_PARTITIONS) { char str[TEXT_DISPLAY_LENGTH]; sprintf(str," %d:%d",topNumParts,bottomNumParts); result += str; } if (bottomPartFunc AND isDP2Exchange()) { const LogPhysPartitioningFunction *lpf = bottomPartFunc->castToLogPhysPartitioningFunction(); if (lpf) { if (lpf->getUsePapa()) { char str[TEXT_DISPLAY_LENGTH]; sprintf(str," with %d PA(s)",lpf->getNumOfClients()); result += str; } switch (lpf->getLogPartType()) { case LogPhysPartitioningFunction::LOGICAL_SUBPARTITIONING: result += ", log. subpart."; break; case LogPhysPartitioningFunction::HORIZONTAL_PARTITION_SLICING: result += ", slicing"; break; case LogPhysPartitioningFunction::PA_GROUPED_REPARTITIONING: result += ", repartitioned"; break; default: break; } } } return result; } PlanPriority Exchange::computeOperatorPriority (const Context* context, PlanWorkSpace *pws, Lng32 planNumber) { PlanPriority result; OperatorTypeEnum parOperType = context->getCurrentAncestor()->getPlan()-> getPhysicalExpr()->getOperatorType(); Lng32 cqdValue = ActiveSchemaDB()->getDefaults().getAsLong(COMP_INT_9); if ((cqdValue == -2) AND ((parOperType == REL_ROOT) OR (parOperType == REL_FIRST_N))) result.incrementLevels(10,0); return result; } void Exchange::addLocalExpr(LIST(ExprNode *) &xlist, LIST(NAString) &llist) const { const PartitioningFunction *topPartFunc = getTopPartitioningFunction(); if (topPartFunc AND topPartFunc->getCountOfPartitions() > 1 AND topPartFunc->getPartitioningExpression()) { xlist.insert(topPartFunc->getPartitioningExpression()); llist.insert("partitioning_expression"); } if (NOT sortKeyForMyOutput_.isEmpty()) { xlist.insert(sortKeyForMyOutput_.rebuildExprTree(ITM_ITEM_LIST)); llist.insert("merged_order"); } RelExpr::addLocalExpr(xlist,llist); } // ----------------------------------------------------------------------- // member functions for class Join // ----------------------------------------------------------------------- Int32 Join::getArity() const { return 2;} // helper function used in // HashJoinRule::topMatch() and // JoinToTSJRule::topMatch() // to make sure that only one of them is turned off. // Otherwise, error 2235 "pass one skipped, but cannot produce a plan // in pass two, originated from file ../optimizer/opt.cpp" NABoolean Join::allowHashJoin() { // HJ is only implementation for full outer join NABoolean fullOuterJoin = (CmpCommon::getDefault(COMP_BOOL_196) != DF_ON) AND isFullOuterJoin(); if (fullOuterJoin) return TRUE; // HJ is only join implementation allowed when avoiding halloween update if (avoidHalloweenR2()) return TRUE; // favor NJ when only one row from outer for sure Cardinality minrows, outerLimit; GroupAttributes *oGrpAttr = child(0).getGroupAttr(); NABoolean hasConstraint = oGrpAttr->hasCardConstraint(minrows, outerLimit); // outerLimit was set to INFINITE_CARDINALITY if no constraint CostScalar outerRows(outerLimit); // if it has no constraint and outer is 1 table if (!hasConstraint && oGrpAttr->getNumBaseTables() == 1) { // use max cardinality estimate outerRows = oGrpAttr->getResultMaxCardinalityForEmptyInput(); } NABoolean favorNJ = CURRSTMT_OPTDEFAULTS->isNestedJoinConsidered() AND (outerRows <= 1) AND GlobalRuleSet->getCurrentPassNumber() > GlobalRuleSet->getFirstPassNumber(); if (favorNJ) return FALSE; // disallow HJ return TRUE; // allow HJ } OperatorTypeEnum Join::getTSJJoinOpType() { switch (getOperatorType()) { case REL_JOIN: case REL_ROUTINE_JOIN: return REL_TSJ; case REL_LEFT_JOIN: return REL_LEFT_TSJ; case REL_SEMIJOIN: return REL_SEMITSJ; case REL_ANTI_SEMIJOIN: return REL_ANTI_SEMITSJ; default: ABORT("Unsupported join type in Join::getTSJJoinOpType()"); return REL_NESTED_JOIN; // Return makes MSVC happy. } // switch } // Join::getNestedJoinOpType() OperatorTypeEnum Join::getNestedJoinOpType() { switch (getOperatorType()) { case REL_JOIN: case REL_ROUTINE_JOIN: case REL_TSJ: return REL_NESTED_JOIN; case REL_LEFT_JOIN: case REL_LEFT_TSJ: return REL_LEFT_NESTED_JOIN; case REL_SEMIJOIN: case REL_SEMITSJ: return REL_NESTED_SEMIJOIN; case REL_ANTI_SEMIJOIN: case REL_ANTI_SEMITSJ: return REL_NESTED_ANTI_SEMIJOIN; default: ABORT("Unsupported join type in Join::getNestedJoinOpType()"); return REL_NESTED_JOIN; // Return makes MSVC happy. } // switch } // Join::getNestedJoinOpType() OperatorTypeEnum Join::getHashJoinOpType(NABoolean isNoOverflow) { if(isNoOverflow) { switch (getOperatorType()) { case REL_JOIN: return REL_ORDERED_HASH_JOIN; case REL_LEFT_JOIN: return REL_LEFT_ORDERED_HASH_JOIN; case REL_SEMIJOIN: return REL_ORDERED_HASH_SEMIJOIN; case REL_ANTI_SEMIJOIN: return REL_ORDERED_HASH_ANTI_SEMIJOIN; default: ABORT("Unsupported join type in Join::getHashJoinOpType()"); return REL_ORDERED_HASH_JOIN; // return makes MSVC happy. } // switch } else { switch (getOperatorType()) { case REL_JOIN: return REL_HYBRID_HASH_JOIN; case REL_LEFT_JOIN: return REL_LEFT_HYBRID_HASH_JOIN; case REL_FULL_JOIN: return REL_FULL_HYBRID_HASH_JOIN; case REL_SEMIJOIN: return REL_HYBRID_HASH_SEMIJOIN; case REL_ANTI_SEMIJOIN: return REL_HYBRID_HASH_ANTI_SEMIJOIN; default: ABORT("Unsupported join type in Join::getHashJoinOpType()"); return REL_HYBRID_HASH_JOIN; // return makes MSVC happy. } // switch }//else } // Join::getHashJoinOpType() NABoolean Join::isCrossProduct() const { // only for our beloved inner non semi joins (for now) if (NOT isInnerNonSemiJoin()) return FALSE; ValueIdSet VEGEqPreds; ValueIdSet newJoinPreds = getSelectionPred(); newJoinPreds += getJoinPred(); // ----------------------------------------------------------------- // Find all the VEGPreds in the newJoinPreds. // Remove all the ones that are not true join predicates // (i.e. they are covered by the inputs, or one of the // children cannot produce it) // ----------------------------------------------------------------- newJoinPreds.lookForVEGPredicates(VEGEqPreds); // remove those VEGPredicates that are covered by the input values VEGEqPreds.removeCoveredExprs(getGroupAttr()-> getCharacteristicInputs()); VEGEqPreds.removeUnCoveredExprs(child(0).getGroupAttr()-> getCharacteristicOutputs()); VEGEqPreds.removeUnCoveredExprs(child(1).getGroupAttr()-> getCharacteristicOutputs()); if (VEGEqPreds.isEmpty()) return TRUE; // is a cross product else return FALSE; } NABoolean Join::isOuterJoin() const { if(isLeftJoin() || isRightJoin() || isFullOuterJoin()) return TRUE; return FALSE; } NABoolean RelExpr::isAnyJoin() const { switch (getOperatorType()) { case REL_JOIN: case REL_ROUTINE_JOIN: case REL_LEFT_JOIN: case REL_ANY_JOIN: case REL_ANY_TSJ: case REL_ANY_INNER_JOIN: case REL_ANY_NON_TS_INNER_JOIN: case REL_ANY_NON_TSJ_JOIN: case REL_ANY_LEFT_JOIN: case REL_ANY_LEFT_TSJ: case REL_ANY_NESTED_JOIN: case REL_ANY_HASH_JOIN: case REL_ANY_MERGE_JOIN: case REL_FORCE_JOIN: case REL_FORCE_NESTED_JOIN: case REL_FORCE_HASH_JOIN: case REL_FORCE_ORDERED_HASH_JOIN: case REL_FORCE_HYBRID_HASH_JOIN: case REL_FORCE_MERGE_JOIN: return TRUE; default: return FALSE; } } NABoolean Join::isInnerNonSemiJoinWithNoPredicates() const { if (isInnerNonSemiJoin() AND getSelectionPred().isEmpty() AND getJoinPred().isEmpty()) return TRUE; else return FALSE; } NABoolean Join:: isInnerJoin() const { return getOperator().match(REL_ANY_INNER_JOIN); } NABoolean Join::isInnerNonSemiJoin() const { return getOperator().match(REL_ANY_INNER_JOIN) AND NOT getOperator().match(REL_ANY_SEMIJOIN); } NABoolean Join::isInnerNonSemiNonTSJJoin() const { return (getOperator().match(REL_ANY_INNER_JOIN) AND NOT getOperator().match(REL_ANY_SEMIJOIN)) AND NOT getOperator().match(REL_ANY_TSJ); } NABoolean Join::isLeftJoin() const { return getOperator().match(REL_ANY_LEFT_JOIN); } NABoolean Join::isRightJoin() const { return getOperator().match(REL_ANY_RIGHT_JOIN); } NABoolean Join::isFullOuterJoin() const { return (getOperator().match(REL_ANY_FULL_JOIN)); } NABoolean Join::isSemiJoin() const { return getOperator().match(REL_ANY_SEMIJOIN); } NABoolean Join::isAntiSemiJoin() const { return getOperator().match(REL_ANY_ANTI_SEMIJOIN); } NABoolean Join::isTSJ() const { return getOperator().match(REL_ANY_TSJ); } NABoolean Join::isRoutineJoin() const { return (getOperator() == REL_ROUTINE_JOIN); } NABoolean Join::isNonRoutineTSJ() const { return ( getOperator().match(REL_ANY_TSJ) && ( getOperator() != REL_ROUTINE_JOIN)); } NABoolean Join::isNestedJoin() const { return getOperator().match(REL_ANY_NESTED_JOIN); } NABoolean Join::isHashJoin() const { return getOperator().match(REL_ANY_HASH_JOIN); } OperatorTypeEnum Join::getBaseHashType() const { switch (getOperatorType()) { case REL_HASH_JOIN: case REL_LEFT_HASH_JOIN: case REL_HASH_SEMIJOIN: case REL_HASH_ANTI_SEMIJOIN: case REL_ANY_HASH_JOIN: return REL_HASH_JOIN; case REL_HYBRID_HASH_JOIN: case REL_LEFT_HYBRID_HASH_JOIN: case REL_FULL_HYBRID_HASH_JOIN: case REL_HYBRID_HASH_SEMIJOIN: case REL_HYBRID_HASH_ANTI_SEMIJOIN: return REL_HYBRID_HASH_JOIN; case REL_ORDERED_HASH_JOIN: case REL_LEFT_ORDERED_HASH_JOIN: case REL_ORDERED_HASH_SEMIJOIN: case REL_ORDERED_HASH_ANTI_SEMIJOIN: return REL_ORDERED_HASH_JOIN; default: return INVALID_OPERATOR_TYPE; } // switch } // Join::getBaseHashType NABoolean Join::isMergeJoin() const { return getOperator().match(REL_ANY_MERGE_JOIN); } OperatorTypeEnum Join::getMergeJoinOpType() { switch (getOperatorType()) { case REL_JOIN: return REL_MERGE_JOIN; case REL_LEFT_JOIN: return REL_LEFT_MERGE_JOIN; case REL_SEMIJOIN: return REL_MERGE_SEMIJOIN; case REL_ANTI_SEMIJOIN: return REL_MERGE_ANTI_SEMIJOIN; default: ABORT("Unsupported join type in Join::getMergeJoinOpType()"); return REL_MERGE_JOIN; // return makes MSVC happy. } // switch } // Join::getMergeJoinOpType() void Join::pushdownCoveredExpr(const ValueIdSet & outputExpr, const ValueIdSet & newExternalInputs, ValueIdSet & predicatesOnParent, const ValueIdSet * setOfValuesReqdByParent, Lng32 childIndex ) { #ifdef NDEBUG NAString pushdownDebugStr(CmpCommon::statementHeap()); #define PUSHDOWN_DEBUG_SAVE(str) #else Int32 PUSHDOWN_DEBUG = !!getenv("PUSHDOWN_DEBUG"); NAString pushdownDebugStr, pushdownDebugTmp; #define PUSHDOWN_DEBUG_SAVE(str) \ { if (PUSHDOWN_DEBUG) \ { pushdownDebugTmp = ""; \ predicatesOnParent.unparse(pushdownDebugTmp); \ pushdownDebugStr += NAString("\n") + str + ": " + pushdownDebugTmp; \ if (PUSHDOWN_DEBUG == 99) cerr << pushdownDebugStr << endl; \ } \ } PUSHDOWN_DEBUG_SAVE("J1"); #endif // ---------------------------------------------------------------------- // Note: Normally, predicatesOnParent is the set of predicates to be // considered for pushing down. For most of the other nodes, this set // is usually just the set (or maybe a subset) of selection predicates // the node has. However, a Join node distinguishes between selection // predicates (which are specified in the WHERE clause of a SQL query) // and join predicates (which are specified in the ON clause). The two // types of predicates have different criteria (as we will see later) // to satisfy in order to be pushed down. The predicatesOnParent supplied // are treated as selection predicates for the purpose of consideration // for pushing down. Note also that this procedure also considers the // pushing down of join predicates (as in joinPred_ of Join). // ---------------------------------------------------------------------- // This method only supports pushing predicates down to both children, // but not only to one specified. // CMPASSERT(childIndex < 0); NABoolean isATSJFlag = isTSJ(); ValueIdSet exprOnParent ; if (setOfValuesReqdByParent) exprOnParent = *setOfValuesReqdByParent; if (isFullOuterJoin()) { // For Full Outer Join, we cannot push down the selctionPred() // or the joinPred() to either child0 or child1. // Note that for FOJ, predicates are not pulled up. // --------------------------------------------------------------------- // STEP 1: We cannot pushdown join predicates to either child, // so compute values required to evaluate the joinPred() // here at the parent (the Join) and add // it to exprOnParent. // // --------------------------------------------------------------------- computeValuesReqdForPredicates(joinPred(), exprOnParent, TRUE); // --------------------------------------------------------------------- // STEP 2: We cannot pushdown selectionPred() to either child, // so compute values required to evaluate the selectionPred() // here at the parent (the Join) and add // it to exprOnParent. // // --------------------------------------------------------------------- computeValuesReqdForPredicates(selectionPred(), exprOnParent, TRUE); // --------------------------------------------------------------------- // STEP 3: Calling pushdownCoveredExpr on an empty set, so that the child // inputs and outputs are set properly. // --------------------------------------------------------------------- ValueIdSet emptySet; RelExpr::pushdownCoveredExpr(outputExpr, newExternalInputs, emptySet, &exprOnParent, 0); // --------------------------------------------------------------------- // STEP 4: Calling pushdownCoveredExpr on an empty set, so that the child // inputs and outputs are set properly. // --------------------------------------------------------------------- RelExpr::pushdownCoveredExpr(outputExpr, newExternalInputs, emptySet, &exprOnParent, 1); } // if (isFullOuterJoin()) // ----------------------------------------------------------------------- // It might not be obvious, but it turns out that pushing down of // predicates in a Left Join is quite similar to that in an Anti-Semi // Join. One striking similarity is that the join predicates cannot be // pushed down to the left child. In both cases, pushing down join preds // filters out rows from the left child which shouldn't be filtered out. // In the case of Left Join, those rows should be null-instantiated while // in the case of Anti-Semi Join, they are exactly the set of rows which // we *should* return. (An Anti-Semi Join returns rows from the left // which do *not* join with rows from the right). // ----------------------------------------------------------------------- else if ((isLeftJoin() || isAntiSemiJoin()) && (!isFullOuterJoin())) { // --------------------------------------------------------------------- // STEP 1: Try to push down the given predicatesOnParent to first child. // --------------------------------------------------------------------- // --------------------------------------------------------------------- // STEP 1A: Gather all values the left child must still produce even if // predicates are pushed down. // // Selection predicates can only be pushed to the first child of an // outer join. Join predicates can only be pushed to the second. Make // sure the first child produces what we need for the join predicates. // --------------------------------------------------------------------- computeValuesReqdForPredicates(joinPred(), exprOnParent); // --------------------------------------------------------------------- // If this is a TSJ, the left child should also produce those values // that the parent needs to give as inputs to the second child. // --------------------------------------------------------------------- if (isATSJFlag) exprOnParent += child(1).getGroupAttr()->getCharacteristicInputs(); // --------------------------------------------------------------------- // This seems to be the only difference between the case of a Left Join // and the case of a Anti-Semi Join. For an Anti-Semi Join, selection // predicates should be in terms of columns on the left child only (by // definition). Therefore, we don't have to worry about retaining things // like VEGPred(VEG{T1.a,T2.a}). // --------------------------------------------------------------------- ValueIdSet VEGEqPreds1; if (isLeftJoin()) { // --------------------------------------------------------------------- // Find all the VEGPreds in predicatesOnParent. VEGPred(VEG{T1.a,T2.a}) // will be pushed down to Scan T1 even if T2.a is not available there. // Therefore, we still need to keep a copy of this type of predicates // here at this Join node where both T1.a and T2.a will be available. // --------------------------------------------------------------------- predicatesOnParent.lookForVEGPredicates(VEGEqPreds1); // --------------------------------------------------------------------- // Remove those VEGPreds that are covered by the input values, since // VEGPred(VEG{T1.a,3}) needn't be retained at this Join node after it's // pushed down to Scan T1. // --------------------------------------------------------------------- VEGEqPreds1.removeCoveredExprs(newExternalInputs); // --------------------------------------------------------------------- // Remove those VEGPreds which are not covered at second child. For // example VEGPred(VEG{T1.a,T2.a}) in JOIN2 of ((T1 JOIN1 T2) JOIN2 T3) // is not covered at the second child. The predicate should be pushed // down to the first child without being retained at JOIN2. Note that // since predicatesOnParent are selection predicates evaluated after // a Left Join, they are in terms of the null-instantiated outputs from // the Join rather than direct outputs from the second child. // --------------------------------------------------------------------- VEGEqPreds1.removeUnCoveredExprs(nullInstantiatedOutput()); PUSHDOWN_DEBUG_SAVE("J2"); // --------------------------------------------------------------------- // ??? First child not needed ??? since we are trying to push down to // child0, if it's uncovered, it wouldn't be pushed down anyway. //VEGEqPreds1.removeUnCoveredExprs( // child(0).getGroupAttr()->getCharacteristicOutputs()); // --------------------------------------------------------------------- // --------------------------------------------------------------------- // Since these VEGEqPreds1 will be added back to predicatesOnParent // after the attempt to push down to first child, make sure the first // child produces the required values to evaluate them. // --------------------------------------------------------------------- computeValuesReqdForPredicates(VEGEqPreds1, exprOnParent); } // endif (isLeftJoin()) // --------------------------------------------------------------------- // STEP 1B: Perform pushdown to the first child, and add VEGEqPreds // back to predicatesOnParent after the push down. // --------------------------------------------------------------------- RelExpr::pushdownCoveredExpr(outputExpr, newExternalInputs, predicatesOnParent, &exprOnParent, 0); // --------------------------------------------------------------------- // All selection predicates could be pushed to the first child for an // Anti-Semi Join should those predicates should involve columns from // the second child by definition. // --------------------------------------------------------------------- if (isAntiSemiJoin()) { CMPASSERT(predicatesOnParent.isEmpty() // QSTUFF OR getGroupAttr()->isGenericUpdateRoot() // QSTUFF ); } else predicatesOnParent += VEGEqPreds1; PUSHDOWN_DEBUG_SAVE("J3"); // --------------------------------------------------------------------- // STEP 2: Try to push down the join predicates to second child. // --------------------------------------------------------------------- // --------------------------------------------------------------------- // STEP 2A: Gather all values the second child must still produce even // if predicates are pushed down. Start with all the required // values specified by the caller of this method. // --------------------------------------------------------------------- if (setOfValuesReqdByParent) exprOnParent = *setOfValuesReqdByParent; else exprOnParent.clear(); // --------------------------------------------------------------------- // Since the remaining predicatesOnParent could not be pushed down to // the second child and must be evaluated on the Left Join, values reqd // for their evaluation must be included to make sure the second child // produces them. For Anti-Semi Join, predicatesOnParent is empty. // --------------------------------------------------------------------- ValueIdSet inputs = newExternalInputs; ValueIdSet inputsTakenOut; if (isLeftJoin()) { computeValuesReqdForPredicates(predicatesOnParent, exprOnParent); // ------------------------------------------------------------------- // Special case: If this left join is the right child of a Nested // Join, it could happen that the inputs we get from above already // contains a value which our push down logic considers to have // covered the predicatesOnParent which we don't attempt to push // down. This is a very peculiar failure of our cover logic, where // the predicates should have been pushed down but held back cos of // the semantics of an operator (case in point, the left join). To // deal with this, we remove from the available inputs to my child // those values so that the child will produce this as an output. // ------------------------------------------------------------------- // inputTakenOut = inputs; // predicatesOnParent.weedOutUnreferenced(inputsTakenOut); // inputs -= inputsTakenOut; } // --------------------------------------------------------------------- // Also, if this is NOT a TSJ, there are some join predicates which need // to be retained even if they are pushed down to the second child. All // Join predicates are pushable to the second child of a TSJ without // being retained at the TSJ. (See later for an exception) // --------------------------------------------------------------------- ValueIdSet VEGEqPreds2; ValueIdSet availableInputs = inputs; if (isATSJFlag) { availableInputs += child(0).getGroupAttr()->getCharacteristicOutputs(); } else { // ------------------------------------------------------------------- // First, find all the VEGPreds in join predicates. This is similar to // what we did above with predicatesOnParent. VEGPred(VEG{T1.a,T2.a}) // will be pushed down to Scan T2 even if T1.a is not available there. // Therefore, we still need to keep a copy of this type of predicates // here at this Join node where both T1.a and T2.a will be available. // ------------------------------------------------------------------- joinPred().lookForVEGPredicates(VEGEqPreds2); // ------------------------------------------------------------------- // Remove those VEGPreds that are covered by the input values, since // VEGPred(VEG{T2.a,3}) needn't be retained at this Join node after // pushed down to Scan T2. (There is an exception to this. See later.) // ------------------------------------------------------------------- VEGEqPreds2.removeCoveredExprs(availableInputs); //newExternalInputs // ------------------------------------------------------------------- // Remove those VEGPreds which are not covered at first child. For // example VEGPred(VEG{T2.a,T3.a}) in JOIN1 of (T1 JOIN1 (T2 JOIN2 T3)) // is not covered at the first child. The predicate could be pushed // down to the second child without being retained at JOIN2. // ------------------------------------------------------------------- VEGEqPreds2.removeUnCoveredExprs( child(0).getGroupAttr()->getCharacteristicOutputs()); // ------------------------------------------------------------------- // Since these predicates will be added back to the join predicates // after the attempt to push down to second child, make sure the second // child produces the required values to evaluate them. // ------------------------------------------------------------------- computeValuesReqdForPredicates(VEGEqPreds2, exprOnParent); } // --------------------------------------------------------------------- // Now, there are additional join predicates that must be retained // even if they are pushable to the second child. An example would be // VEGPred(VEG{T1.a,T2.a,10}). For an inner join, this predicate can // be pushed to Scan T1 and Scan T2 and evaluated as (T1.a=10) and // (T2.a=10) respectively. However, for a Left Join or Anti-Semi Join, // this predicate (if it's a join predicate) cannot be pushed down to // the first child. The (T1.a=10) part must then be retained at this // Join node. These types of VEGPreds are those covered by T1 and the // external inputs. // --------------------------------------------------------------------- ValueIdSet joinPredsThatStay; joinPredsThatStay = joinPred(); ValueIdSet availableValues = availableInputs; //newExternalInputs availableValues += child(0).getGroupAttr()->getCharacteristicOutputs(); joinPredsThatStay.removeUnCoveredExprs(availableValues); // --------------------------------------------------------------------- // However, we don't want VEGPred like VEGPred(VEG{T2.a,10}) which // actually does not reference an output of T1. // --------------------------------------------------------------------- joinPredsThatStay.removeUnReferencedVEGPreds( child(0).getGroupAttr()->getCharacteristicOutputs()); // --------------------------------------------------------------------- // Also, if some inputs have been taken out deliberately, we want to // make sure other predicates which references the inputs taken out // are going to stay. Otherwise, we will have the issue that not // sufficient values are available at the child to ensure correctness // in evaluating the predicates pushed down to it. The same predicate // must be re-evaluated at this JOIN node. // --------------------------------------------------------------------- if (NOT inputsTakenOut.isEmpty()) { ValueIdSet moreJoinPredsThatStay; joinPred().lookForVEGPredicates(moreJoinPredsThatStay); moreJoinPredsThatStay.removeUnReferencedVEGPreds(inputsTakenOut); joinPredsThatStay += moreJoinPredsThatStay; } // --------------------------------------------------------------------- // Since these predicates will be added back to the join predicates // after the attempt to push down to second child, make sure the second // child produces the required values to evaluate them. // --------------------------------------------------------------------- computeValuesReqdForPredicates(joinPredsThatStay, exprOnParent); //---------------------------------------------------------------------- // Solution 10-030728-8252: check if the second child could produce // expressions of type Instnull(CAST(aggregate)). // See if the CAST could be pushed // up. The Groupby node does not manufacture expressions of the type // cast(aggregate) as outputs in the generator. So do not ask for them //---------------------------------------------------------------------- exprOnParent.replaceInstnullCastAggregateWithAggregateInLeftJoins(this); // --------------------------------------------------------------------- // STEP 2B: Perform pushdown to the second child, and add reqd preds // back to the join predicates after the push down. // --------------------------------------------------------------------- RelExpr::pushdownCoveredExpr(outputExpr, availableInputs, joinPred(), &exprOnParent, 1); // --------------------------------------------------------------------- // Add back those predicates which must stay with the JOIN even after // they are pushed to the second child. // --------------------------------------------------------------------- joinPred() += VEGEqPreds2; joinPred() += joinPredsThatStay; PUSHDOWN_DEBUG_SAVE("J4"); } else // ----------------------------------------------------------------------- // For other types of Join's: Semi and Inner (either TSJ or non-TSJ), // processing is quite similar. Inner Joins has no join prediciates. For // Semi-Join, although we distinguish between join predicates and // selection predicates, both types of predicates are equally pushable. // The only thing is "true join VEGPreds" like VEGPred(VEG{T1.a,T2.a}) // should be retained as join predicates in a Semi-Join but as selection // predicates in an Inner Join after being pushed down. // ----------------------------------------------------------------------- { ValueIdSet predicates1 = predicatesOnParent; ValueIdSet predicates2 = predicatesOnParent; if (isSemiJoin()) { // Join predicates in a Semi-Join are "as pushable as" its selection // predicates. // predicates1 += joinPred(); predicates2 += joinPred(); } else { // Inner Join should have no join predicates. CMPASSERT(joinPred().isEmpty() // QSTUFF OR getGroupAttr()->isGenericUpdateRoot() // QSTUFF ); } // --------------------------------------------------------------------- // STEP 1: Gather all values the children must still produce even if // predicates are pushed down. // // Find all the "true join VEGPreds" in predicates. E.g, VEGPred(VEG{ // T1.a,T2.a}) will be pushed down to Scan T1 and to Scan T2 even if // not both values are availble at either node. Therefore, we still // need to keep a copy of this type of predicates here at this Join node // where both T1.a and T2.a will be available. That means the children // need to provide these values to the Join node. The only exception is // when we are doing a TSJ. The predicates are then all pushed to the // right child, and the right child could then *not* provide the value // to the Join node if it's not a required output from the Join. // --------------------------------------------------------------------- ValueIdSet VEGEqPreds; predicates1.lookForVEGPredicates(VEGEqPreds); // --------------------------------------------------------------------- // Remove those VEGPreds that are covered by the input values, since // VEGPred(VEG{T1.a,3}) needn't be retained at this Join node after // it's pushed down to Scan T1. // --------------------------------------------------------------------- VEGEqPreds.removeCoveredExprs(newExternalInputs); // --------------------------------------------------------------------- // Remove those VEGPreds which are not covered at first child. For // example VEGPred(VEG{T2.a,T3.a}) in JOIN1 of (T1 JOIN1 (T2 JOIN2 T3)) // is not covered at the first child. The predicate could be pushed // down to the second child without being retained at JOIN2. // --------------------------------------------------------------------- VEGEqPreds.removeUnCoveredExprs( child(0).getGroupAttr()->getCharacteristicOutputs()); // --------------------------------------------------------------------- // Remove those VEGPreds which are not covered at second child. For // example VEGPred(VEG{T1.a,T2.a}) in JOIN2 of ((T1 JOIN1 T2) JOIN2 T3) // is not covered at the second child. The predicate could be pushed // down to the first child without being retained at JOIN2. // --------------------------------------------------------------------- VEGEqPreds.removeUnCoveredExprs( child(1).getGroupAttr()->getCharacteristicOutputs()); // --------------------------------------------------------------------- // Since these predicates will be retained at the Join (or pushed down // to the second child in the case of a TSJ), make sure the first // child produces the required values to evaluate them. // --------------------------------------------------------------------- computeValuesReqdForPredicates(VEGEqPreds, exprOnParent); // --------------------------------------------------------------------- // First child of a TSJ should produce inputs required from the second // child as well. // --------------------------------------------------------------------- if (isATSJFlag) exprOnParent += child(1).getGroupAttr()->getCharacteristicInputs(); // --------------------------------------------------------------------- // STEP 2: Try pushing down to the first child. // --------------------------------------------------------------------- RelExpr::pushdownCoveredExpr(outputExpr, newExternalInputs, predicates1, &exprOnParent, 0); PUSHDOWN_DEBUG_SAVE("J5"); // --------------------------------------------------------------------- // Find subset of predicatesOnParent which have *not* been pushed down // to first child. // --------------------------------------------------------------------- predicatesOnParent.intersectSet(predicates1); PUSHDOWN_DEBUG_SAVE("J6"); // --------------------------------------------------------------------- // For a Semi-Join, all selection predicates (which should not involve // columns from the second child) should be pushed down to the first // child by now. Also get rid of the join predicates which have been // pushed down. // --------------------------------------------------------------------- if (isSemiJoin()) { joinPred().intersectSet(predicates1); CMPASSERT(predicatesOnParent.isEmpty() // QSTUFF OR getGroupAttr()->isGenericUpdateRoot() // QSTUFF ); } // --------------------------------------------------------------------- // If this is a TSJ, we do not even need to retain VEGEqPreds at the // Join. Everything remaining should be pushable to the right child. // Therefore, we don't need the right child to output values required // for evaluating VEGEqPreds, unless it's an required output from the // // We do not want to push the predicate down to the right child now for // the RoutineJoin. That will happen later when the RoutineJoin gets // transfered back to a TSJ/nested join by the optimizer impl rules. // // The reason we don't want it pushed here is so that the analyzer does // not have to differentiate what imputs are required for predicates and // which is required for a UDF. By knowing what inputs are required for // the UDF, the analyzer can determine if there is a different join order // that might be cheaper. We will attempt to push the predicate during // the optimizer phase.. // --------------------------------------------------------------------- if (!isRoutineJoin()) { ValueIdSet availableInputs = newExternalInputs; if (isATSJFlag) { if (setOfValuesReqdByParent) exprOnParent = *setOfValuesReqdByParent; else exprOnParent.clear(); availableInputs += child(0).getGroupAttr()->getCharacteristicOutputs(); } // --------------------------------------------------------------------- // STEP 3: Try pushing to second child now. // --------------------------------------------------------------------- RelExpr::pushdownCoveredExpr(outputExpr, availableInputs, predicates2, &exprOnParent, 1); } // --------------------------------------------------------------------- // Find subset of predicatesOnParent which have *not* been pushed down // to second child. // --------------------------------------------------------------------- predicatesOnParent.intersectSet(predicates2); PUSHDOWN_DEBUG_SAVE("J7"); if (isSemiJoin()) { // ------------------------------------------------------------------- // set joinPred to have those predicates that were not pushed down to // the second child. // ------------------------------------------------------------------- joinPred().intersectSet(predicates2); // ------------------------------------------------------------------- // If this is a semi-join that is not a TSJ we need to add all the // true join VEGPreds back to joinPred(). // ------------------------------------------------------------------- if (NOT isATSJFlag) joinPred() += VEGEqPreds; else // ----------------------------------------------------------------- // If it is a TSJ all join predicates should be pushable, no preds // should be remaining in joinPred(). // ----------------------------------------------------------------- CMPASSERT(joinPred().isEmpty() // QSTUFF OR getGroupAttr()->isGenericUpdateRoot() // QSTUFF ); } else { // ------------------------------------------------------------------- // If this is a inner-join that is not a TSJ we need to add all the // true join VEGPreds back to selection predicates. // ------------------------------------------------------------------- if (NOT isATSJFlag OR isRoutineJoin()) { predicatesOnParent += VEGEqPreds; PUSHDOWN_DEBUG_SAVE("J9"); } else // ----------------------------------------------------------------- // If it is a TSJ all selection predicates should be pushable, no // preds should remain. // ----------------------------------------------------------------- CMPASSERT(predicatesOnParent.isEmpty() // QSTUFF OR getGroupAttr()->isGenericUpdateRoot() // QSTUFF ); } } } // Join::pushdownCoveredExpr // -------------------------------------------------------------------------- // Join::pushdownCoveredExprSQO // Rules for pushdown from Join during the SemanticQueryOptimize(SQO) // subphase are different in two ways from the usual. // 1) If left child does not cover any part of a // VEGPred it will still be retained in the Join, so that it can be pulled // further up the query tree as we apply this transformation at other levels // In the usual rules, the VEGPred will be pushed down to the right child // without being retained at the Join. This behaviour is controlled by the // boolean input parameter keepPredsNotCoveredByChild0. Similarly preds not // covered by the right child can also be retained at the Join. This is // controlled by keepPredsNotCoveredByChild1. // 2) If left child is a semiJoin or a TSJ we do not push any predicates // down that side as those selection predicates are supposed to be empty // at this phase of compilation. // --------------------------------------------------------------------------- void Join::pushdownCoveredExprSQO(const ValueIdSet & outputExpr, const ValueIdSet & newExternalInputs, ValueIdSet & predicatesOnParent, ValueIdSet & setOfValuesReqdByParent, NABoolean keepPredsNotCoveredByChild0, NABoolean keepPredsNotCoveredByChild1 ) { ValueIdSet exprOnParent1 = setOfValuesReqdByParent; ValueIdSet exprOnParent = setOfValuesReqdByParent; ValueIdSet exprOnParent2 = setOfValuesReqdByParent; ValueIdSet predicates1 = predicatesOnParent; ValueIdSet predicates2 = predicatesOnParent; if (isLeftJoin()) { // --------------------------------------------------------------------- // STEP 1: Try to push down the given predicatesOnParent to first child. // --------------------------------------------------------------------- // --------------------------------------------------------------------- // STEP 1A: Gather all values the left child must still produce even if // predicates are pushed down. // // Selection predicates can only be pushed to the first child of an // outer join. Join predicates can only be pushed to the second. Make // sure the first child produces what we need for the join predicates. // --------------------------------------------------------------------- computeValuesReqdForPredicates(joinPred(), exprOnParent); ValueIdSet VEGEqPreds1; // --------------------------------------------------------------------- // Find all the VEGPreds in predicatesOnParent. VEGPred(VEG{T1.a,T2.a}) // will be pushed down to Scan T1 even if T2.a is not available there. // Therefore, we still need to keep a copy of this type of predicates // here at this Join node where both T1.a and T2.a will be available. // --------------------------------------------------------------------- predicatesOnParent.lookForVEGPredicates(VEGEqPreds1); // --------------------------------------------------------------------- // Remove those VEGPreds that are covered by the input values, since // VEGPred(VEG{T1.a,3}) needn't be retained at this Join node after it's // pushed down to Scan T1. // --------------------------------------------------------------------- VEGEqPreds1.removeCoveredExprs(newExternalInputs); // --------------------------------------------------------------------- // Remove those VEGPreds which are not covered at second child. For // example VEGPred(VEG{T1.a,T2.a}) in JOIN2 of ((T1 JOIN1 T2) JOIN2 T3) // is not covered at the second child. The predicate should be pushed // down to the first child without being retained at JOIN2. Note that // since predicatesOnParent are selection predicates evaluated after // a Left Join, they are in terms of the null-instantiated outputs from // the Join rather than direct outputs from the second child. // --------------------------------------------------------------------- if (NOT keepPredsNotCoveredByChild1) VEGEqPreds1.removeUnCoveredExprs(nullInstantiatedOutput()); // --------------------------------------------------------------------- // Since these VEGEqPreds1 will be added back to predicatesOnParent // after the attempt to push down to first child, make sure the first // child produces the required values to evaluate them. // --------------------------------------------------------------------- computeValuesReqdForPredicates(VEGEqPreds1, exprOnParent); // --------------------------------------------------------------------- // STEP 1B: Perform pushdown to the first child, and add VEGEqPreds // back to predicatesOnParent after the push down. // --------------------------------------------------------------------- RelExpr::pushdownCoveredExpr(outputExpr, newExternalInputs, predicatesOnParent, &exprOnParent, 0); // --------------------------------------------------------------------- // All selection predicates could be pushed to the first child for an // Anti-Semi Join should those predicates should involve columns from // the second child by definition. // --------------------------------------------------------------------- predicatesOnParent += VEGEqPreds1; // --------------------------------------------------------------------- // STEP 2: Try to push down the join predicates to second child. // --------------------------------------------------------------------- // --------------------------------------------------------------------- // STEP 2A: Gather all values the second child must still produce even // if predicates are pushed down. Start with all the required // values specified by the caller of this method. // --------------------------------------------------------------------- exprOnParent = outputExpr; // --------------------------------------------------------------------- // Since the remaining predicatesOnParent could not be pushed down to // the second child and must be evaluated on the Left Join, values reqd // for their evaluation must be included to make sure the second child // produces them. For Anti-Semi Join, predicatesOnParent is empty. // --------------------------------------------------------------------- ValueIdSet inputs = newExternalInputs; ValueIdSet inputsTakenOut; computeValuesReqdForPredicates(predicatesOnParent, exprOnParent); // --------------------------------------------------------------------- // Also, if this is NOT a TSJ, there are some join predicates which need // to be retained even if they are pushed down to the second child. All // Join predicates are pushable to the second child of a TSJ without // being retained at the TSJ. (See later for an exception) // --------------------------------------------------------------------- ValueIdSet VEGEqPreds2; ValueIdSet availableInputs = inputs; // ------------------------------------------------------------------- // First, find all the VEGPreds in join predicates. This is similar to // what we did above with predicatesOnParent. VEGPred(VEG{T1.a,T2.a}) // will be pushed down to Scan T2 even if T1.a is not available there. // Therefore, we still need to keep a copy of this type of predicates // here at this Join node where both T1.a and T2.a will be available. // ------------------------------------------------------------------- joinPred().lookForVEGPredicates(VEGEqPreds2); // ------------------------------------------------------------------- // Remove those VEGPreds that are covered by the input values, since // VEGPred(VEG{T2.a,3}) needn't be retained at this Join node after // pushed down to Scan T2. (There is an exception to this. See later.) // ------------------------------------------------------------------- VEGEqPreds2.removeCoveredExprs(availableInputs); //newExternalInputs // ------------------------------------------------------------------- // Remove those VEGPreds which are not covered at first child. For // example VEGPred(VEG{T2.a,T3.a}) in JOIN1 of (T1 JOIN1 (T2 JOIN2 T3)) // is not covered at the first child. The predicate could be pushed // down to the second child without being retained at JOIN2. // ------------------------------------------------------------------- if (NOT keepPredsNotCoveredByChild0) VEGEqPreds2.removeUnCoveredExprs( child(0).getGroupAttr()->getCharacteristicOutputs()); // ------------------------------------------------------------------- // Since these predicates will be added back to the join predicates // after the attempt to push down to second child, make sure the second // child produces the required values to evaluate them. // ------------------------------------------------------------------- computeValuesReqdForPredicates(VEGEqPreds2, exprOnParent); // --------------------------------------------------------------------- // Now, there are additional join predicates that must be retained // even if they are pushable to the second child. An example would be // VEGPred(VEG{T1.a,T2.a,10}). For an inner join, this predicate can // be pushed to Scan T1 and Scan T2 and evaluated as (T1.a=10) and // (T2.a=10) respectively. However, for a Left Join or Anti-Semi Join, // this predicate (if it's a join predicate) cannot be pushed down to // the first child. The (T1.a=10) part must then be retained at this // Join node. These types of VEGPreds are those covered by T1 and the // external inputs. // --------------------------------------------------------------------- ValueIdSet joinPredsThatStay; joinPredsThatStay = joinPred(); ValueIdSet availableValues = availableInputs; //newExternalInputs availableValues += child(0).getGroupAttr()->getCharacteristicOutputs(); joinPredsThatStay.removeUnCoveredExprs(availableValues); // --------------------------------------------------------------------- // However, we don't want VEGPred like VEGPred(VEG{T2.a,10}) which // actually does not reference an output of T1. // --------------------------------------------------------------------- if (NOT keepPredsNotCoveredByChild0) joinPredsThatStay.removeUnReferencedVEGPreds( child(0).getGroupAttr()->getCharacteristicOutputs()); // --------------------------------------------------------------------- // Also, if some inputs have been taken out deliberately, we want to // make sure other predicates which references the inputs taken out // are going to stay. Otherwise, we will have the issue that not // sufficient values are available at the child to ensure correctness // in evaluating the predicates pushed down to it. The same predicate // must be re-evaluated at this JOIN node. // --------------------------------------------------------------------- if (NOT inputsTakenOut.isEmpty()) { ValueIdSet moreJoinPredsThatStay; joinPred().lookForVEGPredicates(moreJoinPredsThatStay); moreJoinPredsThatStay.removeUnReferencedVEGPreds(inputsTakenOut); joinPredsThatStay += moreJoinPredsThatStay; } // --------------------------------------------------------------------- // Since these predicates will be added back to the join predicates // after the attempt to push down to second child, make sure the second // child produces the required values to evaluate them. // --------------------------------------------------------------------- computeValuesReqdForPredicates(joinPredsThatStay, exprOnParent); //---------------------------------------------------------------------- // Solution 10-030728-8252: check if the second child could produce // expressions of type Instnull(CAST(aggregate)). // See if the CAST could be pushed // up. The Groupby node does not manufacture expressions of the type // cast(aggregate) as outputs in the generator. So do not ask for them //---------------------------------------------------------------------- exprOnParent.replaceInstnullCastAggregateWithAggregateInLeftJoins(this); // --------------------------------------------------------------------- // STEP 2B: Perform pushdown to the second child, and add reqd preds // back to the join predicates after the push down. // --------------------------------------------------------------------- RelExpr::pushdownCoveredExpr(outputExpr, availableInputs, joinPred(), &exprOnParent, 1); // --------------------------------------------------------------------- // Add back those predicates which must stay with the JOIN even after // they are pushed to the second child. // --------------------------------------------------------------------- joinPred() += VEGEqPreds2; joinPred() += joinPredsThatStay; } else { // STEP 1: Gather all values the children must still produce even if // predicates are pushed down. // // Find all the "true join VEGPreds" in predicates. E.g, VEGPred(VEG{ // T1.a,T2.a}) will be pushed down to Scan T1 and to Scan T2 even if // not both values are availble at either node. Therefore, we still // need to keep a copy of this type of predicates here at this Join node // where both T1.a and T2.a will be available. That means the children // need to provide these values to the Join node. The only exception is // when we are doing a TSJ. The predicates are then all pushed to the // right child, and the right child could then *not* provide the value // to the Join node if it's not a required output from the Join. // --------------------------------------------------------------------- ValueIdSet VEGEqPreds; predicates1.lookForVEGPredicates(VEGEqPreds); // --------------------------------------------------------------------- // Remove those VEGPreds that are covered by the input values, since // VEGPred(VEG{T1.a,3}) needn't be retained at this Join node after // it's pushed down to Scan T1. // --------------------------------------------------------------------- VEGEqPreds.removeCoveredExprs(newExternalInputs); // --------------------------------------------------------------------- // Remove those VEGPreds which are not covered at first child. For // example VEGPred(VEG{T2.a,T3.a}) in JOIN1 of (T1 JOIN1 (T2 JOIN2 T3)) // is not covered at the first child. The predicate could be pushed // down to the second child without being retained at JOIN2. // --------------------------------------------------------------------- if (NOT keepPredsNotCoveredByChild0) VEGEqPreds.removeUnCoveredExprs( child(0).getGroupAttr()->getCharacteristicOutputs()); // --------------------------------------------------------------------- // Remove those VEGPreds which are not covered at second child. For // example VEGPred(VEG{T1.a,T2.a}) in JOIN2 of ((T1 JOIN1 T2) JOIN2 T3) // is not covered at the second child. The predicate could be pushed // down to the first child without being retained at JOIN2. // --------------------------------------------------------------------- if (NOT keepPredsNotCoveredByChild1) VEGEqPreds.removeUnCoveredExprs( child(1).getGroupAttr()->getCharacteristicOutputs()); // --------------------------------------------------------------------- // Since these predicates will be retained at the Join (or pushed down // to the second child in the case of a TSJ), make sure the first // child produces the required values to evaluate them. // --------------------------------------------------------------------- computeValuesReqdForPredicates(VEGEqPreds, exprOnParent); // --------------------------------------------------------------------- // STEP 2: Try pushing down to the first child. // --------------------------------------------------------------------- if (child(0).getPtr()->getOperator().match(REL_ANY_SEMIJOIN) || child(0).getPtr()->getOperator().match(REL_ANY_TSJ)) { computeValuesReqdForPredicates(predicates1, exprOnParent1); ValueIdSet emptySet; RelExpr::pushdownCoveredExpr(outputExpr, newExternalInputs, emptySet, &exprOnParent1, 0); } else { RelExpr::pushdownCoveredExpr(outputExpr, newExternalInputs, predicates1, &exprOnParent, 0); } // --------------------------------------------------------------------- // Find subset of predicatesOnParent which have *not* been pushed down // to first child. // --------------------------------------------------------------------- predicatesOnParent.intersectSet(predicates1); // --------------------------------------------------------------------- // STEP 3: Try pushing to second child now. // --------------------------------------------------------------------- if (child(1).getPtr()->getOperator().match(REL_ANY_SEMIJOIN) || (child(1).getPtr()->getOperator().match(REL_ANY_TSJ) && (child(1).getPtr()->getOperator() != REL_ROUTINE_JOIN))) { computeValuesReqdForPredicates(predicates2, exprOnParent2); ValueIdSet emptySet; RelExpr::pushdownCoveredExpr(outputExpr, newExternalInputs, emptySet, &exprOnParent2, 1); } else { // We do not want to push predicates to the right child of a // routineJoin. if (!isRoutineJoin()) { RelExpr::pushdownCoveredExpr(outputExpr, newExternalInputs, predicates2, &exprOnParent, 1); } } // --------------------------------------------------------------------- // Find subset of predicatesOnParent which have *not* been pushed down // to second child. // --------------------------------------------------------------------- predicatesOnParent.intersectSet(predicates2); // ------------------------------------------------------------------- // If this is a inner-join that is not a TSJ we need to add all the // true join VEGPreds back to selection predicates. // ------------------------------------------------------------------- predicatesOnParent += VEGEqPreds; } } // Join::pushdownCoveredExprSQO void Join::getPotentialOutputValues(ValueIdSet & outputValues) const { outputValues.clear(); switch (getOperatorType()) { case REL_JOIN: case REL_MERGE_JOIN: case REL_NESTED_JOIN: case REL_HASH_JOIN: case REL_HYBRID_HASH_JOIN: case REL_ORDERED_HASH_JOIN: case REL_INDEX_JOIN: case REL_ROUTINE_JOIN: case REL_TSJ: { // Potentially, all the values that are produced by // my left child as well as my right child. outputValues += child(0).getGroupAttr()->getCharacteristicOutputs(); outputValues += child(1).getGroupAttr()->getCharacteristicOutputs(); break; } case REL_LEFT_JOIN: case REL_LEFT_NESTED_JOIN: case REL_LEFT_MERGE_JOIN: case REL_LEFT_ORDERED_HASH_JOIN: case REL_LEFT_HYBRID_HASH_JOIN: case REL_LEFT_TSJ: { // Potentially, all the values that are produced by // my left child and all null instantiated values from // my right child. outputValues += child(0).getGroupAttr()->getCharacteristicOutputs(); outputValues.insertList(nullInstantiatedOutput()); break; } case REL_FULL_JOIN: case REL_UNION_JOIN: case REL_FULL_HYBRID_HASH_JOIN: { // Potentially, all the values that are produced by // my left child and the right child. Since it's a FULL_OUTER_JOIN // all null instantiated values from my right and left child. outputValues.insertList(nullInstantiatedOutput()); outputValues.insertList(nullInstantiatedForRightJoinOutput()); break; } case REL_SEMIJOIN: case REL_ANTI_SEMIJOIN: case REL_SEMITSJ: case REL_ANTI_SEMITSJ: case REL_HASH_SEMIJOIN: case REL_HASH_ANTI_SEMIJOIN: case REL_MERGE_SEMIJOIN: case REL_MERGE_ANTI_SEMIJOIN: case REL_HYBRID_HASH_SEMIJOIN: case REL_HYBRID_HASH_ANTI_SEMIJOIN: case REL_ORDERED_HASH_SEMIJOIN: case REL_ORDERED_HASH_ANTI_SEMIJOIN: case REL_NESTED_SEMIJOIN: case REL_NESTED_ANTI_SEMIJOIN: { // No value from my right child can appear in my output. outputValues += child(0).getGroupAttr()->getCharacteristicOutputs(); break; } case REL_TSJ_FLOW: case REL_NESTED_JOIN_FLOW: { // No value from my left child can appear in my output. outputValues += child(1).getGroupAttr()->getCharacteristicOutputs(); break; } default: { ABORT("Unsupported join type in Join::getPotentialOutputValues()"); break; } } // switch } // Join::getPotentialOutputValues() CostScalar Join::computeMinEstRCForGroup() { CostScalar minCard = csOne; GroupAttributes * ga = getGroupAttr(); RelExpr * logExpr = ga->getLogExprForSynthesis(); if (logExpr != NULL) { logExpr->finishSynthEstLogProp(); minCard = ga->getMinChildEstRowCount(); } return minCard; } // get the highest reduction from local predicates for cols of this join CostScalar Join::highestReductionForCols(ValueIdSet colSet) { // if the child is anything other than scan, then we assume the reduction to be 1 // but before that we still need to see if the column set that we are looking for // belongs to this child or not. // since we don't know to which child tableOne belongs, we shall look at both left // and right histograms for the columns. Start with the left child ColStatDescList completeList = child(0).outputLogProp((*GLOBAL_EMPTY_INPUT_LOGPROP))->colStats(); ColStatDescList rightColStatList = child(1).outputLogProp((*GLOBAL_EMPTY_INPUT_LOGPROP))->colStats(); // form a complete list of histograms from both sides completeList.makeDeepCopy(rightColStatList); // Compute reduction for this column set CostScalar highestUecRedByLocalPreds = highestUecRedByLocalPreds = completeList.getHighestUecReductionByLocalPreds(colSet); return highestUecRedByLocalPreds; } const NAString Join::getText() const { NAString result; switch (getOperatorType()) { case REL_JOIN: result += "join"; break; case REL_LEFT_JOIN: result += "left_join"; break; case REL_RIGHT_JOIN: result += "right_join"; break; case REL_FULL_JOIN: result += "full_join"; break; case REL_UNION_JOIN: result += "union_join"; break; case REL_ROUTINE_JOIN: result += "routine_join"; break; case REL_TSJ: result += "tsj"; break; case REL_TSJ_FLOW: result += "tsj_flow"; break; case REL_LEFT_TSJ: result += "left_tsj"; break; case REL_SEMIJOIN: result += "semi_join"; break; case REL_ANTI_SEMIJOIN: result += "anti_semi_join"; break; case REL_SEMITSJ: result += "semi_tsj"; break; case REL_ANTI_SEMITSJ: result += "anti_semi_tsj"; break; case REL_INDEX_JOIN: result += "index_join"; break; default: result += "UNKNOWN??"; break; } // switch if(CmpCommon::getDefault(COMP_BOOL_183) == DF_ON) { Int32 potential = getPotential(); if(potential < 0) { result += "_-"+ istring(-1*potential); } else result += "_" + istring(potential); } return result; } // Join::getText() HashValue Join::topHash() { HashValue result = RelExpr::topHash(); result ^= joinPred_; return result; } NABoolean Join::duplicateMatch(const RelExpr & other) const { if (!RelExpr::duplicateMatch(other)) return FALSE; Join &o = (Join &) other; if (joinPred_ != o.joinPred_) return FALSE; // Temp member to seperate joins PTRule from others in cascades memo if (joinFromPTRule_ != o.joinFromPTRule_) return FALSE; if (joinForZigZag_ != o.joinForZigZag_) return FALSE; if (avoidHalloweenR2_ != o.avoidHalloweenR2_) return FALSE; if (halloweenForceSort_ != o.halloweenForceSort_) return FALSE; return TRUE; } RelExpr * Join::copyTopNode(RelExpr *derivedNode, CollHeap* outHeap) { Join *result; if (derivedNode == NULL) result = new (outHeap) Join(NULL, NULL, getOperatorType(), NULL, FALSE, FALSE, outHeap); else result = (Join *) derivedNode; // copy join predicate parse tree (parser only) if (joinPredTree_ != NULL) result->joinPredTree_ = joinPredTree_->copyTree(outHeap)->castToItemExpr(); result->joinPred_ = joinPred_; // Copy the uniqueness flags result->leftHasUniqueMatches_ = leftHasUniqueMatches_; result->rightHasUniqueMatches_ = rightHasUniqueMatches_; // Copy the equijoin predicates result->equiJoinPredicates_ = equiJoinPredicates_; result->equiJoinExpressions_ = equiJoinExpressions_; result->nullInstantiatedOutput() = nullInstantiatedOutput(); result->nullInstantiatedForRightJoinOutput() = nullInstantiatedForRightJoinOutput(); result->transformComplete_ = transformComplete_; // Copy the required order, if any, that originated from an insert node result->reqdOrder_ = reqdOrder_; // copy flag that marks a mandatory TSJ which could not be unnested result->tsjAfterSQO_ = tsjAfterSQO_; // Copy the flag that indicates if this is a TSJ for a write operation result->tsjForWrite_ = tsjForWrite_; result->tsjForUndo_ = tsjForUndo_; result->tsjForSetNFError_ = tsjForSetNFError_; result->tsjForMerge_ = tsjForMerge_; result->tsjForMergeWithInsert_ = tsjForMergeWithInsert_; result->tsjForSideTreeInsert_ = tsjForSideTreeInsert_; result->enableTransformToSTI_ = enableTransformToSTI_; result->forcePhysicalJoinType_ = forcePhysicalJoinType_; result->derivedFromRoutineJoin_ = derivedFromRoutineJoin_; // Temp member to seperate joins PTRule from others in cascades memo result->joinFromPTRule_ = joinFromPTRule_; result->joinForZigZag_ = joinForZigZag_; result->sourceType_ = sourceType_; result->rowsetRowCountArraySize_ = rowsetRowCountArraySize_; result->avoidHalloweenR2_ = avoidHalloweenR2_; result->halloweenForceSort_ = halloweenForceSort_; result->candidateForSubqueryUnnest_ = candidateForSubqueryUnnest_; result->candidateForSubqueryLeftJoinConversion_ = candidateForSubqueryLeftJoinConversion_; result->candidateForSemiJoinTransform_ = candidateForSemiJoinTransform_; result->predicatesToBeRemoved_ = predicatesToBeRemoved_; //++MV result->rightChildMapForLeftJoin_ = rightChildMapForLeftJoin_; //--MV result->isIndexJoin_ = isIndexJoin_; if(!result->isInnerNonSemiJoin()) result->floatingJoin_ = floatingJoin_; result->allowPushDown_ = allowPushDown_; result->extraHubNonEssentialOutputs_ = extraHubNonEssentialOutputs_; result->isForTrafLoadPrep_ = isForTrafLoadPrep_; return RelExpr::copyTopNode(result, outHeap); } void Join::addJoinPredTree(ItemExpr *joinPred) { ExprValueId j = joinPredTree_; ItemExprTreeAsList(&j, ITM_AND).insert(joinPred); joinPredTree_ = j.getPtr(); } ItemExpr * Join::removeJoinPredTree() { ItemExpr * result = joinPredTree_; joinPredTree_ = NULL; return result; } void Join::addLocalExpr(LIST(ExprNode *) &xlist, LIST(NAString) &llist) const { if (joinPredTree_ != NULL OR NOT joinPred_.isEmpty()) { if (joinPred_.isEmpty()) xlist.insert(joinPredTree_); else xlist.insert(joinPred_.rebuildExprTree()); llist.insert("other_join_predicates"); } RelExpr::addLocalExpr(xlist,llist); } void Join::convertToTsj() { switch (getOperatorType()) { case REL_JOIN: setOperatorType(REL_TSJ); break; case REL_LEFT_JOIN: setOperatorType(REL_LEFT_TSJ); break; case REL_SEMIJOIN: setOperatorType(REL_SEMITSJ); break; case REL_ANTI_SEMIJOIN: setOperatorType(REL_ANTI_SEMITSJ); break; default: ABORT("Internal error: Join::convertTsj()"); break; } } // Join::convertToTsj() void Join::convertToNotTsj() { switch (getOperatorType()) { case REL_TSJ: case REL_TSJ_FLOW: case REL_ROUTINE_JOIN: setOperatorType(REL_JOIN); break; case REL_LEFT_TSJ: setOperatorType(REL_LEFT_JOIN); break; case REL_SEMITSJ: setOperatorType(REL_SEMIJOIN); break; case REL_ANTI_SEMITSJ: setOperatorType(REL_ANTI_SEMIJOIN); break; default: ABORT("Internal error: Join::convertTsj()"); break; } } // Join::convertToNotTsj() void Join::convertToNotOuterJoin() { switch (getOperatorType()) { case REL_LEFT_JOIN: setOperatorType(REL_JOIN); break; case REL_LEFT_TSJ: setOperatorType(REL_TSJ); break; default: ABORT("Internal error: Join::convertOuterJoin()"); break; } // end switch } // Join::convertToNotOuterJoin() // ---------------------------------------------------------------------------- // This procedure gets called when synthesising logical properties. // It finds all the equijoin predicates and saves them in equiJoinPredicates_ // But leaves them in the originating selectionPred()/joinPred() // --------------------------------------------------------------------------- void Join::findEquiJoinPredicates() { ValueIdSet allJoinPredicates; ValueId leftExprId, rightExprId; NABoolean predicateIsOrderPreserving; ItemExpr* expr; equiJoinPredicates_.clear(); equiJoinExpressions_.clear(); // If this is a TSJ there is nothing to analyze. All join predicates // have been pushed down to the second child. if(isTSJ()) return; if (isInnerNonSemiJoin()) { allJoinPredicates = selectionPred(); CMPASSERT(joinPred().isEmpty()); } else { // for an outer or semi join, the ON clause is stored in "joinPred" // while the WHERE clause is stored in "selectionPred". allJoinPredicates = joinPred(); } // remove any predicates covered by the inputs allJoinPredicates.removeCoveredExprs(getGroupAttr()-> getCharacteristicInputs()); for (ValueId exprId = allJoinPredicates.init(); allJoinPredicates.next(exprId); allJoinPredicates.advance(exprId)) { expr = exprId.getItemExpr(); if (expr->isAnEquiJoinPredicate(child(0).getGroupAttr(), child(1).getGroupAttr(), getGroupAttr(), leftExprId, rightExprId, predicateIsOrderPreserving)) { equiJoinPredicates_ += exprId; equiJoinExpressions_.addMapEntry(leftExprId, rightExprId); } } } // Join::findEquiJoinPredicates() // --------------------------------------------------------------------------- // separateEquiAndNonEquiJoinPredicates is called from the Join // implementation rules to weed out of equiJoinPredicates_ all // the predicates that can be used by the join. The equiJoin // predicates for the physical operator will be remove from // the selectioPred() or joinPred() where they came from. // --------------------------------------------------------------------------- void Join::separateEquiAndNonEquiJoinPredicates (const NABoolean joinStrategyIsOrderSensitive) { ValueId leftExprId, rightExprId; NABoolean predicateIsOrderPreserving; ItemExpr* expr; // equiJoinPredicates_ has all the equijoin predicates found // when synthesing logical properties. It is a subset of // either selectionPred() or joinPred() ValueIdSet foundEquiJoinPredicates = equiJoinPredicates_; equiJoinPredicates_.clear(); equiJoinExpressions_.clear(); // remove any predicates covered by the inputs foundEquiJoinPredicates.removeCoveredExprs(getGroupAttr()-> getCharacteristicInputs()); for (ValueId exprId = foundEquiJoinPredicates.init(); foundEquiJoinPredicates.next(exprId); foundEquiJoinPredicates.advance(exprId)) { expr = exprId.getItemExpr(); if (expr->isAnEquiJoinPredicate(child(0).getGroupAttr(), child(1).getGroupAttr(), getGroupAttr(), leftExprId, rightExprId, predicateIsOrderPreserving)) { if ( (NOT joinStrategyIsOrderSensitive) OR (joinStrategyIsOrderSensitive AND predicateIsOrderPreserving) ) { equiJoinPredicates_ += exprId; equiJoinExpressions_.addMapEntry(leftExprId, rightExprId); } } else { CMPASSERT(0); // We knew it was an equijoin predicate already } } if (isInnerNonSemiJoin()) { selectionPred() -= equiJoinPredicates_; CMPASSERT(joinPred().isEmpty()); } else { // for an outer or semi join, the ON clause is stored in "joinPred" // while the WHERE clause is stored in "selectionPred". joinPred() -= equiJoinPredicates_; } // Since we have changed the set of equijoin predicates we will consider // we should resyhtnesize the left/rightHasUnqiueMatches_ flags synthConstraints(NULL); } // Join::separateEquiAndNonEquiJoinPredicates() void Join::flipChildren() { NABoolean flipUnique; flipUnique = leftHasUniqueMatches_; leftHasUniqueMatches_ = rightHasUniqueMatches_; rightHasUniqueMatches_ = flipUnique; equiJoinExpressions_.flipSides(); } // Join::flipChildren() // --------------------------------------------------------------------------- // get the parallel join type and return additional info (optional) // // 0: serial join // 1: TYPE1 join (matching partitions on both sides, including SkewBuster) // 2: TYPE2 join (join one partition on one side with the // entire table on the other side) // --------------------------------------------------------------------------- Int32 Join::getParallelJoinType(ParallelJoinTypeDetail *optionalDetail) const { Int32 result = 0; ParallelJoinTypeDetail detailedType = Join::PAR_NONE; const PartitioningFunction *mpf = NULL; const PartitioningFunction *cpf = NULL; if (getPhysicalProperty()) mpf = getPhysicalProperty()->getPartitioningFunction(); if (mpf == NULL OR mpf->getCountOfPartitions() <= 1) { // no parallelism or unknown parallelism, not a parallel join if (optionalDetail) *optionalDetail = detailedType; return 0; } if (child(1)->getPhysicalProperty()) cpf = child(1)->getPhysicalProperty()->getPartitioningFunction(); CMPASSERT( cpf ); if (cpf->castToLogPhysPartitioningFunction()) { // only the child of a join in DP2 can have a logphys part func DCMPASSERT(getPhysicalProperty()->executeInDP2()); cpf = cpf->castToLogPhysPartitioningFunction()-> getPhysPartitioningFunction(); } if (cpf->isAReplicateViaBroadcastPartitioningFunction() OR cpf->isAReplicateNoBroadcastPartitioningFunction()) { // Right child replicates, now check my own partitioning // function to see whether this node just passes on the // replication function. if (mpf->castToLogPhysPartitioningFunction()) { // only a join in DP2 can have a logphys part func DCMPASSERT(getPhysicalProperty()->executeInDP2()); // check the physical part. func of the join in DP2 mpf = mpf->castToLogPhysPartitioningFunction()-> getPhysPartitioningFunction(); } if (NOT mpf->isAReplicateViaBroadcastPartitioningFunction() AND NOT mpf->isAReplicateNoBroadcastPartitioningFunction()) { // See if the right child REALLY replicates data. If this is // a nested join and the chosen plan was a "preferred probing // order" plan, then this is really a type 1 join, because a // ppo plan always demands the two tables be logically // partitioned the same way. if (isNestedJoin() && ((NestedJoin*)this)->probesInOrder()) { result = 1; detailedType = PAR_OCR; } else { // right child replicates data, and the node itself doesn't, // this is a type 2 join result = 2; if (isNestedJoin()) detailedType = PAR_N2J; } } else { // Both the right child and the parent replicate data. // This is not a parallel join, it is a join that simply // passes its replication requirement down to both of its // children. The join will be executed in multiple ESPs, // but it will not employ one of the two parallel algorithms // (TYPE1 or TYPE2). result = 0; } } else { // right child is partitioned, but does not replicate, parallel type 1 join or SkewBuster or OCB PartitioningFunction *opf = NULL; if (child(0)->getPhysicalProperty()) opf = child(0)->getPhysicalProperty()->getPartitioningFunction(); if (opf->isAReplicateViaBroadcastPartitioningFunction()) { // this is an OCB join, which is considered type2 result = 2; detailedType = PAR_OCB; } else { // the regular TYPE1 join (including SkewBuster) result = 1; if (opf->isASkewedDataPartitioningFunction()) detailedType = PAR_SB; } } if (optionalDetail) *optionalDetail = detailedType; return result; } // --------------------------------------------------------------------- // Method to split the order req between the two join children. // return FALSE if not possible // --------------------------------------------------------------------- NABoolean Join::splitOrderReq( const ValueIdList& myOrderReq, /*IN*/ ValueIdList& orderReqOfChild0, /*OUT*/ ValueIdList& orderReqOfChild1 /*OUT*/) const { NABoolean partOfChild0List = TRUE; ValueId exprId; GroupAttributes* child0GA = child(0).getGroupAttr(); GroupAttributes* child1GA = child(1).getGroupAttr(); orderReqOfChild0.clear(); orderReqOfChild1.clear(); for (CollIndex ix = 0; ix < myOrderReq.entries(); ix++) { exprId = myOrderReq.at(ix); // dummy variables for the cover test ValueIdSet newInputs,referencedInputs, coveredSubExpr,uncoveredExpr; NABoolean coveredByChild0 = child0GA->covers(exprId, newInputs, referencedInputs, &coveredSubExpr, &uncoveredExpr); if (NOT coveredByChild0) partOfChild0List = FALSE; if (partOfChild0List) orderReqOfChild0.insertAt(orderReqOfChild0.entries(),exprId); else // i.e. NOT partOfChild0List { //++MV // For left join we need to translate the required sort key to // the right child outputs because there is an InstantiateNull function // on all of the right child outputs. The InstantiateNull function will // cause the cover test to fail and therefore the optimization that merge // the left child sort key with the right child sort key will fail // For more information see NestedJoin::synthPhysicalProperty() if (isLeftJoin()) { const ValueIdMap &map = rightChildMapForLeftJoin(); ValueId tempExprId = exprId; map.mapValueIdDown(tempExprId, exprId); } //--MV coveredSubExpr.clear(); uncoveredExpr.clear(); NABoolean coveredByChild1 = child1GA->covers(exprId, newInputs, referencedInputs, &coveredSubExpr, &uncoveredExpr); if (coveredByChild1) { orderReqOfChild1.insertAt(orderReqOfChild1.entries(),exprId); } else // i.e NOT (partOfChild0List || coveredByChild1) { orderReqOfChild0.clear(); orderReqOfChild1.clear(); return FALSE; } } } // end for all expressions in the required order // Check to see if it is possible to split the order if (child0GA->isUnique(orderReqOfChild0) OR (child0GA->getMaxNumOfRows() <= 1) OR (orderReqOfChild1.entries() == 0)) { return TRUE; } else { orderReqOfChild0.clear(); orderReqOfChild1.clear(); return FALSE; } } // end splitOrderReq() // --------------------------------------------------------------------- // method to split the arrangement req between the two join childs. // return FALSE if not possible // --------------------------------------------------------------------- NABoolean Join::splitArrangementReq( const ValueIdSet& myArrangReq, /*IN*/ ValueIdSet& ArrangReqOfChild0, /*OUT*/ ValueIdSet& ArrangReqOfChild1 /*OUT*/) const { ArrangReqOfChild0.clear(); ArrangReqOfChild1.clear(); ValueId exprId; GroupAttributes* child0GA = child(0).getGroupAttr(); GroupAttributes* child1GA = child(1).getGroupAttr(); for (exprId = myArrangReq.init(); myArrangReq.next(exprId); myArrangReq.advance(exprId)) { // dummy variables for the cover test ValueIdSet newInputs,referencedInputs, coveredSubExpr,uncoveredExpr; // First we see if this element is covered by child 0 if (child0GA->covers(exprId, newInputs, referencedInputs, &coveredSubExpr, &uncoveredExpr)) { ArrangReqOfChild0.insert(exprId); } // Only if an element is not covered by Child0 then we check // Child1. i.e. if it is covered by both we bill it to Child0. else { coveredSubExpr.clear(); uncoveredExpr.clear(); if (child1GA->covers(exprId, newInputs, referencedInputs, &coveredSubExpr, &uncoveredExpr)) { ArrangReqOfChild1.insert(exprId); } else { // If the expression was not covered soley by one of the children, then // we must give up. For example, "T1.a * T2.a" needs both children. ArrangReqOfChild0.clear(); ArrangReqOfChild1.clear(); return FALSE; } } // end if not covered by child0 } // end for all expressions in the required arrangement // Check to see if it is possible to split the arrangement if (child0GA->isUnique(ArrangReqOfChild0) OR (child0GA->getMaxNumOfRows() <= 1) OR (ArrangReqOfChild1.entries() == 0)) { return TRUE; } else { ArrangReqOfChild0.clear(); ArrangReqOfChild1.clear(); return FALSE; } } // end splitArrangementReq() NABoolean Join::ownsVEGRegions() const { return isLeftJoin() OR isAntiSemiJoin() OR isFullOuterJoin(); } PlanPriority NestedJoin::computeOperatorPriority (const Context* context, PlanWorkSpace *pws, Lng32 planNumber) { const PhysicalProperty* spp = context->getPlan()->getPhysicalProperty(); Lng32 degreeOfParallelism = spp->getCountOfPartitions(); NABoolean applySerialPremium = TRUE; double val; Cardinality minrows, maxrows; CostScalar expectedrows = child(0).getGroupAttr()->getResultCardinalityForEmptyInput(); if (child(0).getGroupAttr()->hasCardConstraint(minrows, maxrows) && (maxrows <= ActiveSchemaDB()->getDefaults().getAsLong(COMP_INT_99) OR CostScalar(maxrows) < CostScalar(1.2) * expectedrows)) { // a nested join with at most N outer rows is NOT risky val = 1.0; // In this case premium for serial plan can be waived because cost of // starting ESPs over weighs any benefit we get from parallel plan. // Fix is controlled by COMP_BOOL_75, default value is ON. if (CmpCommon::getDefault(COMP_BOOL_75) == DF_ON) applySerialPremium = FALSE; } else if (context->getInputLogProp() && context->getInputLogProp()->getResultCardinality().value() > 1) { // temporary workaround until we cost HJ under NJ correctly val = 1.0; } else { // a nested join with more than N outer rows is considered risky val = CURRSTMT_OPTDEFAULTS->riskPremiumNJ(); // nested join cache should have a lower risk premium GroupAttributes &rightGA = *child(1).getGroupAttr(); NABoolean probeIsUnique = rightGA.isUnique(rightGA.getCharacteristicInputs()); NABoolean isTypeOfSemiJoin = isSemiJoin() || isAntiSemiJoin(); if ((probeIsUnique || isTypeOfSemiJoin) && (rowsFromRightHaveUniqueMatch() == FALSE) && (getOperatorType() != REL_NESTED_JOIN_FLOW) && (isTSJForWrite() == FALSE ) && (getGroupAttr()-> isEmbeddedUpdateOrDelete() == FALSE ) && (!spp->executeInDP2()) && (CmpCommon::getDefault(NESTED_JOIN_CACHE) != DF_OFF)) { double red=ActiveSchemaDB()->getDefaults().getAsDouble(COMP_INT_89); if (red > 1) { // reduce risk premium because it's a nested join cache operator val = 1 + (val - 1) / red; } } } if (degreeOfParallelism <= 1 && applySerialPremium) { // serial plans are risky. exact an insurance premium from serial plans. val *= CURRSTMT_OPTDEFAULTS->riskPremiumSerial(); } CostScalar premium(val); PlanPriority result(0, 0, premium); // esp parallelism priority logic below does not apply to operators in dp2 if(spp->executeInDP2()) return result; // For the option of Max Degree of Parallelism we can either use the // value set in comp_int_9 (if positive) or we use the number of CPUs // if the CQD is set to -1, or feature is disabled if CQD is 0 (default). Lng32 maxDegree = ActiveSchemaDB()->getDefaults().getAsLong(COMP_INT_9); if (CURRSTMT_OPTDEFAULTS->maxParallelismIsFeasible() OR (maxDegree == -1) ) { // if CQD is set to -1 this mean use the number of CPUs maxDegree = spp->getCurrentCountOfCPUs(); } if (maxDegree > 1) // CQD set to 0 means feature is OFF { if (degreeOfParallelism < maxDegree) result.incrementLevels(0,-10); // need to replace with constant } // fix for SAP case 10-100602-2913, soln 10-100602-0803 // long-running select for DSO activation, query plan for empty table // if nested join has // 1) a tuple list (something with 0 base tables) on left, and // 2) a table on right, and // 3) prefer_key_nested_join is set, and // 4) table's predicate (including pushed join pred) forms begin/end // key on table, and // 5) tuple list is of reasonable size (<= tuplelist_size_threshold), // and // 6) table is small or has no stats // then give nested join plan higher priority // push it by 1 if it has a key range predicate // push it by 2 if it has a unique key predicate // is prefer_key_nested_join active? NABoolean prefer_key_nested_join = (CmpCommon::getDefault(SAP_PREFER_KEY_NESTED_JOIN) == DF_ON); if (prefer_key_nested_join) { GroupAttributes *grpAttr0 = child(0).getGroupAttr(); GroupAttributes *grpAttr1 = child(1).getGroupAttr(); GroupAnalysis *grpA0 = grpAttr0->getGroupAnalysis(); GroupAnalysis *grpA1 = grpAttr1->getGroupAnalysis(); // is left child guaranteed small? NABoolean leftIsSmall = FALSE; Cardinality minLeft, maxLeft; if (grpAttr0->hasCardConstraint(minLeft,maxLeft) AND maxLeft <= ActiveSchemaDB()->getDefaults().getAsLong (SAP_TUPLELIST_SIZE_THRESHOLD)) { leftIsSmall = TRUE; } // is right a single table? FileScan *rScan = NULL; NABoolean rightIsTable = pws->getRightLeaf(planNumber, &rScan); // is right table small? NABoolean isSmallTable = grpAttr1->getResultCardinalityForEmptyInput() <= ActiveSchemaDB()->getDefaults().getAsLong (SAP_KEY_NJ_TABLE_SIZE_THRESHOLD); // prefer this nested_join iff all above conditions are met if (leftIsSmall && rightIsTable && isSmallTable && rScan) { // is predicate on unique key or prefix key? NABoolean hasUniqKeyPred = FALSE; NABoolean hasPrefixKeyPred = FALSE; const SearchKey *sKey = rScan->getSearchKey(); if (sKey) { hasUniqKeyPred = sKey->isUnique(); // TBD: check if key prefix selects few or many rows hasPrefixKeyPred = sKey->getKeyPredicates().entries() > 0; } // TBD: take care of MDAM case // push priority by 2 if it has a unique key predicate if (hasUniqKeyPred) result.incrementLevels(2,0); // push priority by 1 if it has a prefix key predicate else if (hasPrefixKeyPred) result.incrementLevels(1,0); } } return result; } // ----------------------------------------------------------------------- // member functions for class NestedJoinFlow // ----------------------------------------------------------------------- RelExpr * NestedJoinFlow::copyTopNode(RelExpr *derivedNode, CollHeap* outHeap) { NestedJoinFlow *result; if (derivedNode == NULL) { result = new (outHeap) NestedJoinFlow(NULL, NULL, NULL, NULL, outHeap); } else result = (NestedJoinFlow*)derivedNode; result->sendEODtoTgt_ = sendEODtoTgt_; return NestedJoin::copyTopNode(result, outHeap); } // ----------------------------------------------------------------------- // member functions for class NestedJoin // ----------------------------------------------------------------------- NABoolean NestedJoin::isLogical() const {return FALSE;} NABoolean NestedJoin::isPhysical() const {return TRUE;} const NAString NestedJoin::getText() const { switch (getOperatorType()) { case REL_NESTED_JOIN: return "nested_join"; case REL_LEFT_NESTED_JOIN: return "left_nested_join"; case REL_NESTED_SEMIJOIN: return "nested_semi_join"; case REL_NESTED_ANTI_SEMIJOIN: return "nested_anti_semi_join"; case REL_NESTED_JOIN_FLOW: return "tuple_flow"; default: return "UNKNOWN??"; } // switch } // NestedJoin::getText() RelExpr * NestedJoin::copyTopNode(RelExpr *derivedNode, CollHeap* outHeap) { RelExpr *result; if (derivedNode == NULL) { result = new (outHeap) NestedJoin(NULL, NULL, getOperatorType(), outHeap); } else result = derivedNode; return Join::copyTopNode(result, outHeap); } NABoolean NestedJoin::allPartitionsProbed() { return TRUE;//all partitions probed } // Conditions to check before applying the nested join probing cache: // 1. The right child has a cardinality constraint of at most one row, // or else the join is a semi-join or anti-semi-join. // 2. The right child's characteristic inputs are not unique for every // request (with exceptions, see below). // 3. The nested join is not a NestedJoinFlow. // 4. The right child does not contain any IUD operations. // 5. The nested join's GroupAttributes do not include embedded IUD. // 6. The execution location is not in DP2. // 7. The nested join cache feature is not suppressed by a default. // 8. The right child does not contain non-deterministic UDRs NABoolean NestedJoin::isProbeCacheApplicable(PlanExecutionEnum loc) const { NABoolean result = FALSE; GroupAttributes &rightGA = *child(1).getGroupAttr(); NABoolean probeIsUnique = rightGA.isUnique(rightGA.getCharacteristicInputs()); if ( !probeIsUnique ) { // dig deep into the right child to see if the searchKey associated with the // only Scan node is unique. If it is unique, we also declare the probe is // unique (i.e., for each probe, there is at most one row returned). The // probe uniqueness property check is for the current implementation in executor // where only one entry per probe in the hash table in probe cache is allocated. RelExpr *childExpr = child(1); // skip over Exchange nodes while (childExpr && (childExpr->getOperator() == REL_EXCHANGE)) childExpr = childExpr->child(0); if (childExpr) { OperatorTypeEnum x = childExpr->getOperator(); if (x == REL_HBASE_ACCESS || x == REL_HBASE_COPROC_AGGR) { HbaseAccess *hbscan = (HbaseAccess*)childExpr; const SearchKey *skey = hbscan->getSearchKey(); if (skey && skey->isUnique()) probeIsUnique = TRUE; } } } NABoolean isTypeOfSemiJoin = isSemiJoin() || isAntiSemiJoin(); if ((probeIsUnique || isTypeOfSemiJoin) && (getOperatorType() != REL_NESTED_JOIN_FLOW) && (isTSJForWrite() == FALSE ) && (getGroupAttr()-> isEmbeddedUpdateOrDelete() == FALSE ) && loc != EXECUTE_IN_DP2 && (CmpCommon::getDefault(NESTED_JOIN_CACHE) != DF_OFF) && (rightGA.getHasNonDeterministicUDRs() == FALSE)) { if (! rowsFromRightHaveUniqueMatch()) { // big if passed and we have a chance of duplicate probes from the left result = TRUE; } else { // If left probes are unique, there isn't a reason for a probe // cache. However, we might be able to pull up some predicate from // the right into the ProbeCache, which might give us non-unique // probes. The code below targets a specific case (ALM 4783): // // NestedJoin // / \ // Aggregate (one equi-join pred is a HAVING pred) // // We can't detect this in the optimizer (where the nested join // may point to a filter or a MEMO group), but that's fine, since // we don't really want to give this unusual case a cost advantage. RelExpr *childExpr = child(1); // skip over Exchange and MapValueIds nodes while (childExpr && (childExpr->getOperator() == REL_EXCHANGE || childExpr->getOperator() == REL_MAP_VALUEIDS)) childExpr = childExpr->child(0); if (childExpr && childExpr->getOperator().match(REL_ANY_GROUP) && CmpCommon::getDefault(NESTED_JOIN_CACHE_PREDS) != DF_OFF) { GroupByAgg *childGB = (GroupByAgg *) childExpr; if (childGB->groupExpr().isEmpty() && ! childGB->selectionPred().isEmpty()) // This is a scalar aggregate with a HAVING predicate, // at least we know that there is a reasonable chance that // we can pull up a HAVING predicate into the probe cache // in method GroupByAgg::tryToPullUpPredicatesInPreCodeGen() result = TRUE; } } } return result; } // ----------------------------------------------------------------------- // member functions for class MergeJoin // ----------------------------------------------------------------------- NABoolean MergeJoin::isLogical() const {return FALSE;} NABoolean MergeJoin::isPhysical() const {return TRUE;} const NAString MergeJoin::getText() const { switch (getOperatorType()) { case REL_MERGE_JOIN: return "merge_join"; case REL_LEFT_MERGE_JOIN: return "left_merge_join"; case REL_MERGE_SEMIJOIN: return "merge_semi_join"; case REL_MERGE_ANTI_SEMIJOIN: return "merge_anti_semi_join"; default: return "UNKNOWN merge join??"; } // switch } // MergeJoin::getText() RelExpr * MergeJoin::copyTopNode(RelExpr *derivedNode, CollHeap* outHeap) { RelExpr *result; if (derivedNode == NULL) result = new (outHeap) MergeJoin(NULL, NULL, getOperatorType(), NULL, outHeap); else result = derivedNode; return Join::copyTopNode(result, outHeap); } void MergeJoin::addLocalExpr(LIST(ExprNode *) &xlist, LIST(NAString) &llist) const { xlist.insert(orderedMJPreds_.rebuildExprTree()); llist.insert("merge_join_predicate"); Join::addLocalExpr(xlist,llist); } PlanPriority MergeJoin::computeOperatorPriority (const Context* context, PlanWorkSpace *pws, Lng32 planNumber) { const PhysicalProperty* spp = context->getPlan()->getPhysicalProperty(); Lng32 degreeOfParallelism = spp->getCountOfPartitions(); double val = CURRSTMT_OPTDEFAULTS->riskPremiumMJ(); if (degreeOfParallelism <= 1) { // serial plans are risky. exact an insurance premium from serial plans. val *= CURRSTMT_OPTDEFAULTS->riskPremiumSerial(); } CostScalar premium(val); PlanPriority result(0, 0, premium); // For the option of Max Degree of Parallelism we can either use the // value set in comp_int_9 (if positive) or we use the number of CPUs // if the CQD is set to -1, or feature is disabled if CQD is 0 (default). Lng32 maxDegree = ActiveSchemaDB()->getDefaults().getAsLong(COMP_INT_9); if (CURRSTMT_OPTDEFAULTS->maxParallelismIsFeasible() OR (maxDegree == -1) ) { // if CQD is set to -1 this mean use the number of CPUs maxDegree = spp->getCurrentCountOfCPUs(); } if (maxDegree > 1) // CQD set to 0 means feature is OFF { if (degreeOfParallelism < maxDegree) result.incrementLevels(0,-10); // need to replace with constant } return result; } // ----------------------------------------------------------------------- // member functions for class HashJoin // ----------------------------------------------------------------------- NABoolean HashJoin::isLogical() const { return FALSE; } NABoolean HashJoin::isPhysical() const { return TRUE; } const NAString HashJoin::getText() const { switch (getOperatorType()) { case REL_HASH_JOIN: return "hash_join"; case REL_LEFT_HASH_JOIN: return "left_hash_join"; case REL_HASH_SEMIJOIN: return "semi_join"; case REL_HASH_ANTI_SEMIJOIN: return "hash_anti_semi_join"; case REL_HYBRID_HASH_JOIN: { if(((HashJoin *)this)->isOrderedCrossProduct()) return "ordered_cross_product"; else return "hybrid_hash_join"; } case REL_LEFT_HYBRID_HASH_JOIN: return "left_hybrid_hash_join"; case REL_FULL_HYBRID_HASH_JOIN: return "full_hybrid_hash_join"; case REL_HYBRID_HASH_SEMIJOIN: return "hybrid_hash_semi_join"; case REL_HYBRID_HASH_ANTI_SEMIJOIN: return "hybrid_hash_anti_semi_join"; case REL_ORDERED_HASH_JOIN: { if (getEquiJoinPredicates().isEmpty()) return "ordered_cross_product"; else return "ordered_hash_join"; } case REL_LEFT_ORDERED_HASH_JOIN: return "left_ordered_hash_join"; case REL_ORDERED_HASH_SEMIJOIN: return "ordered_hash_semi_join"; case REL_ORDERED_HASH_ANTI_SEMIJOIN: return "ordered_hash_anti_semi_join"; default: return "UNKNOWN hash join??"; } // switch } // HashJoin::getText() RelExpr * HashJoin::copyTopNode(RelExpr *derivedNode, CollHeap* outHeap) { RelExpr *result; if (derivedNode == NULL) { result = new (outHeap) HashJoin(NULL, NULL, getOperatorType(), NULL, outHeap); ((HashJoin *)result)->setIsOrderedCrossProduct(isOrderedCrossProduct()); ((HashJoin *)result)->setReuse(isReuse()); ((HashJoin *)result)->setNoOverflow(isNoOverflow()); } else result = derivedNode; ((HashJoin*)result)->isNotInSubqTransform_ = isNotInSubqTransform_; ((HashJoin*)result)->requireOneBroadcast_ = requireOneBroadcast_; ((HashJoin*)result)->innerAccessOnePartition_ = innerAccessOnePartition_; return Join::copyTopNode(result, outHeap); } PlanPriority HashJoin::computeOperatorPriority (const Context* context, PlanWorkSpace *pws, Lng32 planNumber) { const PhysicalProperty* spp = context->getPlan()->getPhysicalProperty(); Lng32 degreeOfParallelism = spp->getCountOfPartitions(); double val = 1; if (degreeOfParallelism <= 1 && getInnerAccessOnePartition() == FALSE ) { // serial plans are risky. exact an insurance premium from serial plans. // The exception is when only one partition is accessed. val = CURRSTMT_OPTDEFAULTS->riskPremiumSerial(); } CostScalar premium(val); PlanPriority result(0, 0, premium); if (QueryAnalysis::Instance() AND QueryAnalysis::Instance()->optimizeForFirstNRows()) result.incrementLevels(HASH_JOIN_FIRST_N_PRIORITY,0); // For the option of Max Degree of Parallelism we can either use the // value set in comp_int_9 (if positive) or we use the number of CPUs // if the CQD is set to -1, or feature is disabled if CQD is 0 (default). Lng32 maxDegree = ActiveSchemaDB()->getDefaults().getAsLong(COMP_INT_9); if (CURRSTMT_OPTDEFAULTS->maxParallelismIsFeasible() OR (maxDegree == -1) ) { // if CQD is set to -1 this mean use the number of CPUs maxDegree = spp->getCurrentCountOfCPUs(); } if (maxDegree > 1) // CQD set to 0 means feature is OFF { if (degreeOfParallelism < maxDegree) result.incrementLevels(0,-10); // need to replace with constant } return result; } void HashJoin::addLocalExpr(LIST(ExprNode *) &xlist, LIST(NAString) &llist) const { if (NOT getEquiJoinPredicates().isEmpty()) { xlist.insert(getEquiJoinPredicates().rebuildExprTree()); llist.insert("hash_join_predicates"); } if (NOT valuesGivenToChild_.isEmpty()) { xlist.insert(valuesGivenToChild_.rebuildExprTree(ITM_ITEM_LIST)); llist.insert("reuse_comparison_values"); } if (NOT checkInnerNullExpr_.isEmpty()) { xlist.insert(checkInnerNullExpr_.rebuildExprTree()); llist.insert("check_inner_null_expr"); } if (NOT checkOuterNullExpr_.isEmpty()) { xlist.insert(checkOuterNullExpr_.rebuildExprTree()); llist.insert("check_outer_null_expr"); } Join::addLocalExpr(xlist,llist); } void HashJoin::resolveSingleColNotInPredicate() { if (!isAntiSemiJoin() || !isHashJoin()) { return; } ValueIdSet jPred = joinPred(); short notinCount=0; for ( ValueId valId = jPred.init(); jPred.next(valId); jPred.advance(valId)) { ItemExpr * itmExpr = valId.getItemExpr(); if (itmExpr->getOperatorType() == ITM_NOT_IN) { if (((NotIn*)itmExpr)->getEquivEquiPredicate() == NULL_VALUE_ID) { ((NotIn*)itmExpr)->cacheEquivEquiPredicate(); } // use cached value ids equiJoinPredicates() += ((NotIn*)itmExpr)->getEquivEquiPredicate(); joinPred() -=valId; joinPred() += ((NotIn*)itmExpr)->getEquivEquiPredicate(); notinCount++; setIsNotInSubqTransform(TRUE); setRequireOneBroadcast(((NotIn*)itmExpr)->getIsOneInnerBroadcastRequired()); } } DCMPASSERT(notinCount <=1); }//void HashJoin::resolveSingleColNotInPredicate() void Join::resolveSingleColNotInPredicate() { // applies only to anti_semi_joins if (!isAntiSemiJoin()) { return; } short notinCount = 0; ValueIdSet jPred = joinPred(); for ( ValueId valId = jPred.init(); jPred.next(valId); jPred.advance(valId)) { ItemExpr * itmExpr = valId.getItemExpr(); if (itmExpr->getOperatorType() == ITM_NOT_IN) { if (((NotIn*)itmExpr)->getEquivNonEquiPredicate() == NULL_VALUE_ID ) { ((NotIn*)itmExpr)->cacheEquivNonEquiPredicate(); } //use cached valueids joinPred() -= valId; joinPred() += ((NotIn*)itmExpr)->getEquivNonEquiPredicate(); notinCount++; } } DCMPASSERT(notinCount <=1); }//void Join::resolveSingleColNotInPredicate() // Join::rewriteNotInPredicate() // is method is called right after the predicates are pushed down and // the goal is to make sure that only the NotIn predicate is present. // in any other preduicate exist besides the NotIn Predicate than we can not // optimize the hash anti semi join when the outer column is nullable and may // have null values void Join::rewriteNotInPredicate() { // applies only to anti_semi_joins if (!isAntiSemiJoin()) { return; } ValueIdSet jPred = joinPred(); ItemExpr * notinExpr=NULL; NABoolean otherPredicatesExist = FALSE; for ( ValueId valId = jPred.init(); jPred.next(valId); jPred.advance(valId)) { ItemExpr * itmExpr = valId.getItemExpr(); if (itmExpr->getOperatorType() != ITM_NOT_IN) { otherPredicatesExist = TRUE; } else { // assert if we already encoutered a not in DCMPASSERT(notinExpr == NULL); notinExpr = itmExpr; } } if (notinExpr) { //single column DCMPASSERT (notinExpr->child(0)->getOperatorType() != ITM_ITEM_LIST); const NAType &outerType = notinExpr->child(0)->getValueId().getType(); GroupAttributes * leftChildGrpAttr = child(0).getGroupAttr(); GroupAttributes * rightChildGrpAttr = child(1).getGroupAttr(); const ValueIdSet &inputs = getGroupAttr()->getCharacteristicInputs(); ValueIdSet refs; ValueId valId = notinExpr->getValueId(); if ((outerType.supportsSQLnull() && !((NotIn*)notinExpr)->getOuterNullFilteringDetected() && otherPredicatesExist) || //fix for solution Id:10-100331-9194 //select count(*) from h2_data_1k_37 where col_lar2 <> all (select col_id from //h2_data_1k_37 where col_id=100) ; //NotIn(VEGRef(col_lar2),VEGRef(col_id=100)) is in the join prdicate and in t he characteristc //outputs of the child. changing it to euipredicate may lead to wrong results //the below code will change the NotIn(a,b) predicate to NOT(a<>B is true) when the predicate is covered //by one of of children leftChildGrpAttr->covers(valId, inputs, refs) || rightChildGrpAttr->covers(valId, inputs, refs)) { ValueId tmpId = ((NotIn *)notinExpr)->createEquivNonEquiPredicate(); ItemExpr * tmpItemExpr = tmpId.getItemExpr(); valId.replaceItemExpr(tmpItemExpr); } } }//Join::rewriteNotInPredicate() // Join::rewriteNotInPredicate( ValueIdSet & origVidSet, ValueIdSet & newVidSet) // if both the outer and the inner columns are not nullable or are nullable but // have no NULL values then the NotIn Predicate is changed to an equi-predicate. // otherwise the NotIn predicate is not changed and the optimizer will decide what // to do with it // this method is called right after the pull up of the predicates in join::transformNode() // in the case of anti semi join the inner predicates are pulled and added to join pred // and the outer predicates are pulled and added to selectionPredicates // When we look for outer NUll filetering predicates we look in the selection predocates // and when we look inner NULL filtering predicates we look in the join predicates void Join::rewriteNotInPredicate( ValueIdSet & origVidSet, ValueIdSet & newVidSet) { // applies only to anti_semi_joins if (!isAntiSemiJoin()) { return; } ValueIdSet jPred = joinPred(); ValueIdSet selPred = selectionPred(); short notinCount = 0; for ( ValueId valId = joinPred().init(); joinPred().next(valId); joinPred().advance(valId)) { ItemExpr * itmExpr = valId.getItemExpr(); if (itmExpr->getOperatorType() == ITM_NOT_IN) { //single column if (itmExpr->child(0)->getOperatorType() != ITM_ITEM_LIST) { const NAType &innerType = itmExpr->child(1)->getValueId().getType(); const NAType &outerType = itmExpr->child(0)->getValueId().getType(); selPred -= valId; jPred -= valId; NABoolean child0IsNotNullable = selPred.isNotNullable(itmExpr->child(0)) ; NABoolean child1IsNotNullable = jPred.isNotNullable(itmExpr->child(1)) ; if ((!innerType.supportsSQLnull() || child1IsNotNullable) && (!outerType.supportsSQLnull() || child0IsNotNullable) ) { origVidSet += valId; // we can change the not in predicate to an equi-predicate in this case newVidSet += ((NotIn *)itmExpr)->createEquivEquiPredicate(); } else { // outer refrences case are not handled by optimization ValueIdSet rightSideofPred; ValueIdSet tempSet; rightSideofPred.insert(itmExpr->child(1)->getValueId()); rightSideofPred.getReferencedPredicates(child(0)->getGroupAttr()->getCharacteristicOutputs(), tempSet) ; if (!tempSet.isEmpty()) { origVidSet += valId; // we can change the not in predicate to an equi-predicate in this case newVidSet += ((NotIn *)itmExpr)->createEquivNonEquiPredicate(); } else { if (CmpCommon::getDefault(NOT_IN_OUTER_OPTIMIZATION) == DF_OFF) { //NOT_IN_OUTER_OPTIMIZATION == OFF ==> if outer is nullable and may have NULL values // change to Non equi-predicate here if ( outerType.supportsSQLnull() && !child0IsNotNullable) { origVidSet += valId; // we can change the not in predicate to an equi-predicate in this case newVidSet += ((NotIn *)itmExpr)->createEquivNonEquiPredicate(); } } else { // case where outer or inner columns (or both) is nullable and may have NULL values // optimizer will decide depending on the type of join // hash join ==> equi-predicate with cancel expression when inner is nullbale // ==> filter to filter out NULL values coming from outer side // ==> when inner is not empty // ==> NUILL values coming from outer side are not filtered out when // ==> inner is empty // non hash join ==> Non equi-predicate if (child0IsNotNullable) { ((NotIn*)itmExpr)->setOuterNullFilteringDetected(TRUE); } if (child1IsNotNullable) { ((NotIn*)itmExpr)->setInnerNullFilteringDetected(TRUE); } } } } } else { ValueIdSet predSet ; //ValueIdSet jPreds; //ValueIdSet selPred; //jPreds = joinPred(); //selPred = selectionPred(); predSet = NotIn::rewriteMultiColNotInPredicate( valId, joinPred(), selectionPred()); DCMPASSERT(predSet.entries() >0); origVidSet += valId; newVidSet += predSet; } notinCount++; }//if (itmExpr->getOperatorType() == ITM_NOT_IN) } DCMPASSERT(notinCount <=1); }//void Join::rewriteNotInPredicate() // ----------------------------------------------------------------------- // member functions for class Intersect // ----------------------------------------------------------------------- Intersect::Intersect(RelExpr *leftChild, RelExpr *rightChild) : RelExpr(REL_INTERSECT, leftChild, rightChild) { setNonCacheable(); } Intersect::~Intersect() {} Int32 Intersect::getArity() const { return 2; } const NAString Intersect::getText() const { return "intersect"; } // ----------------------------------------------------------------------- // member functions for class Union // ----------------------------------------------------------------------- Union::Union(RelExpr *leftChild, RelExpr *rightChild, UnionMap *unionMap, ItemExpr *condExpr, OperatorTypeEnum otype, CollHeap *oHeap, NABoolean sysGenerated, NABoolean mayBeCacheable ) : RelExpr(otype, leftChild, rightChild, oHeap), condExprTree_(condExpr) ,trigExceptExprTree_(NULL) ,previousIF_(NULL) ,flags_(0) ,leftList_(NULL) ,rightList_(NULL) ,currentChild_(-1) ,alternateRightChildOrderExprTree_(NULL) //++MV ,isSystemGenerated_(sysGenerated), isSerialUnion_(FALSE) { if ( NOT mayBeCacheable ) setNonCacheable(); if (unionMap != NULL) { unionMap_ = unionMap; unionMap_->count_++; } else unionMap_ = new (oHeap) UnionMap; condExpr_.clear(); trigExceptExpr_.clear(); alternateRightChildOrderExpr_.clear(); //++MV variablesSet_.clear(); controlFlags_ = 0; //++ Triggers - } Union::~Union() { if (unionMap_->count_ == 0) delete unionMap_;} Int32 Union::getArity() const { return 2; } void Union::rewriteUnionExpr(const ValueIdSet &unionExpr, ValueIdSet &leftExpr, ValueIdSet &rightExpr) const { // walk the original selection predicates and rewrite them in terms // of the mapped value ids of the union's inputs for (ValueId x = unionExpr.init(); unionExpr.next(x); unionExpr.advance(x)) { ValueId newLeftExpr = x.getItemExpr()->mapAndRewrite(getLeftMap(),TRUE); ValueId newRightExpr = x.getItemExpr()->mapAndRewrite(getRightMap(),TRUE); leftExpr += newLeftExpr; rightExpr += newRightExpr; } } // Union::rewriteExprs() void Union::pushdownCoveredExpr(const ValueIdSet & outputExpr, const ValueIdSet & newExternalInputs, ValueIdSet & predicatesOnParent, const ValueIdSet * setOfValuesReqdByParent, Lng32 // childIndex ignored ) { ValueIdSet resultSet = outputExpr; if (setOfValuesReqdByParent) resultSet += *setOfValuesReqdByParent; resultSet += getGroupAttr()->getCharacteristicInputs(); // alternateRightChildOrderExpr expressions should not be pushed down resultSet.insertList(alternateRightChildOrderExpr()); // ++MV // --------------------------------------------------------------------- // Not all the output columns from the union may be needed. // Map the required input list to the corresponding left // and right required outputs list // --------------------------------------------------------------------- ValueIdSet valuesRequiredFromLeft, valuesRequiredFromRight; rewriteUnionExpr(resultSet, valuesRequiredFromLeft, valuesRequiredFromRight); // --------------------------------------------------------------------- // Rewrite selectionPred() // --------------------------------------------------------------------- ValueIdSet leftPred, rightPred, emptySet; rewriteUnionExpr(predicatesOnParent, leftPred, rightPred); // push the left predicates to the left subtree // empty set for the first argument indicates that there are no // non-essential outputs, (in other words, outputs that are // simply passed through) RelExpr::pushdownCoveredExpr(emptySet, newExternalInputs, leftPred, &valuesRequiredFromLeft, 0 ); // push the right predicates to the right subtree RelExpr::pushdownCoveredExpr(emptySet, newExternalInputs, rightPred, &valuesRequiredFromRight, 1 ); // Verify that all the predicates were pushed leftPred -= child(0)->selectionPred(); CMPASSERT( leftPred.isEmpty() ); rightPred -= child(1)->selectionPred(); CMPASSERT( rightPred.isEmpty() ); // All the predicates have been pushed down to the children. predicatesOnParent.clear(); } // Union::pushdownCoveredExpr void Union::getPotentialOutputValues(ValueIdSet & outputValues) const { outputValues.clear(); // // The output of the union is defined by the ValueIdUnion // expressions that are maintained in the colMapTable_. // #pragma nowarn(1506) // warning elimination Lng32 ne = unionMap_->colMapTable_.entries(); #pragma warn(1506) // warning elimination for (Lng32 index = 0; index < ne; index++) { // Accumulate the ValueIds of the result of the union // in the set provided by the caller. outputValues += ((ValueIdUnion *) (unionMap_->colMapTable_[index].getItemExpr()))->getResult(); } } // Union::getPotentialOutputValues() HashValue Union::topHash() { HashValue result = RelExpr::topHash(); // result ^= colMapTable_; return result; } NABoolean Union::duplicateMatch(const RelExpr & other) const { if (NOT RelExpr::duplicateMatch(other)) return FALSE; Union &o = (Union &) other; if (NOT ((unionMap_ == o.unionMap_) AND (condExpr_ == o.condExpr_) AND (trigExceptExpr_ == o.trigExceptExpr_) AND (alternateRightChildOrderExpr_ == o.alternateRightChildOrderExpr_))) //++MV return FALSE; return TRUE; } RelExpr * Union::copyTopNode(RelExpr *derivedNode, CollHeap* outHeap) { Union *result; if (derivedNode == NULL) result = new (outHeap) Union(NULL, NULL, unionMap_, NULL, getOperatorType(), outHeap); else result = (Union *) derivedNode; if (condExprTree_ != NULL) result->condExprTree_ = condExprTree_->copyTree(outHeap)->castToItemExpr(); if (trigExceptExprTree_ != NULL) result->trigExceptExprTree_ = trigExceptExprTree_->copyTree(outHeap)->castToItemExpr(); //++MV - if (alternateRightChildOrderExprTree_ != NULL) result->alternateRightChildOrderExprTree_ = alternateRightChildOrderExprTree_->copyTree(outHeap)->castToItemExpr(); //--MV - result->condExpr_ = condExpr_; result->trigExceptExpr_ = trigExceptExpr_; result->alternateRightChildOrderExpr_ = alternateRightChildOrderExpr_; result->setUnionFlags(getUnionFlags()); //++Triggers - result->controlFlags_ = controlFlags_; result->isSystemGenerated_ = isSystemGenerated_; if (getSerialUnion()) { result->setSerialUnion(); } return RelExpr::copyTopNode(result, outHeap); } void Union::addValueIdUnion(ValueId vidUnion, CollHeap* heap) { ValueIdUnion *xvid = (ValueIdUnion *) vidUnion.getItemExpr(); CMPASSERT(vidUnion.getItemExpr()->getOperatorType() == ITM_VALUEIDUNION); // This method is only called by the binder when it is first // building the unionMap if(unionMap_->count_ > 1) { unionMap_->count_--; unionMap_ = new (heap) UnionMap; } CMPASSERT(unionMap_->count_ == 1); // add the value id to the list of value ids for ValueIdUnion expressions // and also add entries to the two maps that describe the same information unionMap_->colMapTable_.insert(vidUnion); unionMap_->leftColMap_.addMapEntry(vidUnion,xvid->getLeftSource()); unionMap_->rightColMap_.addMapEntry(vidUnion,xvid->getRightSource()); } //++ Triggers - void Union::setNoOutputs() { CMPASSERT(flags_ == UNION_BLOCKED || flags_ == UNION_ORDERED); controlFlags_ |= NO_OUTPUTS; } void Union::addLocalExpr(LIST(ExprNode *) &xlist, LIST(NAString) &llist) const { if (condExprTree_ != NULL) { xlist.insert(condExprTree_); llist.insert("condExprTree"); } if (NOT condExpr_.isEmpty()) { xlist.insert(condExpr_.rebuildExprTree()); llist.insert("condExpr"); } if (trigExceptExprTree_ != NULL) { xlist.insert(trigExceptExprTree_); llist.insert("trigExceptExprTree"); } if (NOT trigExceptExpr_.isEmpty()) { xlist.insert(trigExceptExpr_.rebuildExprTree()); llist.insert("trigExceptExpr"); } if (alternateRightChildOrderExprTree_ != NULL) { xlist.insert(alternateRightChildOrderExprTree_); llist.insert("alternateRightChildOrderExprTree"); } if (NOT alternateRightChildOrderExpr_.isEmpty()) { xlist.insert(alternateRightChildOrderExpr_.rebuildExprTree()); llist.insert("alternateRightChildOrderExpr"); } RelExpr::addLocalExpr(xlist,llist); } const NAString Union::getText() const { NAString text; switch (getUnionFlags()) { case UNION_ORDERED : text += "ordered_union"; break; case UNION_BLOCKED : text += "blocked_union"; break; case UNION_COND_UNARY : text += "unary_union"; break; default : text += "merge_union"; break; } if (getOperatorType() == REL_MERGE_UNION) text += " (phys.)"; return text; } ItemExpr *Union::getCondExprTree() { return condExprTree_; } void Union::addCondExprTree(ItemExpr *condExpr) { ExprValueId t = condExprTree_; ItemExprTreeAsList(&t, ITM_ITEM_LIST).insert(condExpr); condExprTree_ = t.getPtr(); } ItemExpr *Union::removeCondExprTree() { ItemExpr *result = condExprTree_; condExprTree_ = NULL; return result; } ItemExpr *Union::getTrigExceptExprTree() { return trigExceptExprTree_; } void Union::addTrigExceptExprTree(ItemExpr *trigExceptExpr) { ExprValueId t = trigExceptExprTree_; ItemExprTreeAsList(&t, ITM_ITEM_LIST).insert(trigExceptExpr); trigExceptExprTree_ = t.getPtr(); } ItemExpr *Union::removeTrigExceptExprTree() { ItemExpr *result = trigExceptExprTree_; trigExceptExprTree_ = NULL; return result; } // If this Union node is an IF node of a compound statement, this function // returns either the left or right list of value ids associated with the node. // It returns the left one if we are currently visiting the left child. // Otherwise we return the right one. AssignmentStHostVars *Union::getCurrentList(BindWA *bindWA) { if (currentChild_ == 0) { if (!leftList_) { leftList_ = new (bindWA->wHeap()) AssignmentStHostVars(bindWA); } return leftList_; } else { if (!rightList_) { rightList_ = new (bindWA->wHeap()) AssignmentStHostVars(bindWA); } return rightList_; } } // When we are in a CompoundStatement and we have IF statements in it, // we must create a RETDesc for this Union node (which is // actually an IF node). In this function, we create a list of // ValueIdUnion nodes. We figure out which valueids // of the left child must be matched with those of the right child // (for instance, if SET :a appears in both children) and which must // be matched with previously existing valueids (for instance, if // SET :a = ... only appears in one branch, then the ValueIdUnion associated // with that SET statement must reference the value id of :a that existed before // this IF statement). RETDesc * Union::createReturnTable(AssignmentStArea *assignArea, BindWA *bindWA) { AssignmentStHostVars * leftList = leftList_; AssignmentStHostVars * rightList = rightList_; NABoolean foundAMatch = FALSE; AssignmentStHostVars *globalList = assignArea->getAssignmentStHostVars(); NAString const *nameOfLeftVar; RETDesc *resultTable = new (bindWA->wHeap()) RETDesc(bindWA); ColRefName *refName = new (bindWA->wHeap()) ColRefName(); AssignmentStHostVars *listOfPreviousIF = NULL; // We find the list of variables of the previous IF node. We will // need to update it since some of its variables may get new value ids // within the IF statement if (previousIF_) { short currentChild = previousIF_->currentChild(); if (currentChild == 0) { listOfPreviousIF = previousIF_->leftList(); } else { listOfPreviousIF = previousIF_->rightList(); } } // Scan the left list and look for matches in the right List while (leftList && (leftList->var())) { foundAMatch = FALSE; nameOfLeftVar = &(leftList->var()->getName()); rightList = rightList_; while (rightList && rightList->var()) { NAString const *nameOfRightVar = &(rightList->var()->getName()); if (*nameOfLeftVar == *nameOfRightVar) { foundAMatch = TRUE; break; } rightList = rightList->next(); } AssignmentStHostVars *ptrLeftVar = globalList->findVar(*nameOfLeftVar); CMPASSERT(ptrLeftVar); // If we found a match, we create a ValueIdUnion node of the paired match; otherwise // we pair the current value id of the variable in question with the value id it // had before the IF statement. If the variable does not have a value id, we bind it. ValueId value ; if (foundAMatch) { value = rightList->currentValueId(); } else { ValueIdList list = ptrLeftVar->valueIds(); if (list.entries() > 0) { value = ptrLeftVar->currentValueId(); } else { // Get a value id for this variable. ItemExpr *expr = ptrLeftVar->var()->bindNode(bindWA); if (bindWA->errStatus()) { return NULL; } value = expr->getValueId(); } } ValueIdUnion *vidUnion = new (bindWA->wHeap()) ValueIdUnion(leftList->currentValueId(), value, NULL_VALUE_ID); vidUnion->bindNode(bindWA); if (bindWA->errStatus()) { delete vidUnion; return NULL; } ValueId valId = vidUnion->getValueId(); addValueIdUnion(valId,bindWA->wHeap()); resultTable->addColumn(bindWA, *refName, valId); // The variable inside the IF gets the value id of the ValueIdUnion just // generated. ptrLeftVar->setCurrentValueId(valId); // Also update the variable list in the previous IF node if (listOfPreviousIF) { listOfPreviousIF->addToListInIF(leftList->var(), valId); } leftList = leftList->next(); } // while // We now search the right list and do a similar processing for the variables on // the right side that are not on the left rightList = rightList_; while (rightList && (rightList->var())) { foundAMatch = FALSE; NAString const *nameOfRightVar = &(rightList->var()->getName()); AssignmentStHostVars *ptrRightVar = globalList->findVar(*nameOfRightVar); CMPASSERT(ptrRightVar); leftList = leftList_; while (leftList && (leftList->var())) { nameOfLeftVar = &(leftList->var()->getName()); if (*nameOfLeftVar == *nameOfRightVar) { foundAMatch = TRUE; break; } leftList = leftList->next(); } // Create the ValueIdUnion of the two value ids if (!foundAMatch) { ValueId value; ValueIdList list = ptrRightVar->valueIds(); if (list.entries() > 0) { value = ptrRightVar->currentValueId(); } else { // Get a value id for this variable. ItemExpr *expr = ptrRightVar->var()->bindNode(bindWA); value = expr->getValueId(); } ValueIdUnion *vidUnion = new (bindWA->wHeap()) ValueIdUnion(value, rightList->currentValueId(), NULL_VALUE_ID); vidUnion->bindNode(bindWA); if (bindWA->errStatus()) { delete vidUnion; return NULL; } ValueId valId = vidUnion->getValueId(); addValueIdUnion(valId, bindWA->wHeap()); resultTable->addColumn(bindWA, *refName, valId); // The variable inside the IF gets the value id of the ValueIdUnion just // generated. ptrRightVar->setCurrentValueId(valId); // Also update the variable list in the previous IF node if (listOfPreviousIF) { listOfPreviousIF->addToListInIF(rightList->var(), valId); } } // if (!foundAMatch) rightList = rightList->next(); } // while return resultTable; } //++ MV - void Union::addAlternateRightChildOrderExprTree(ItemExpr *alternateRightChildOrderExprTree) { ExprValueId t = alternateRightChildOrderExprTree_; ItemExprTreeAsList(&t, ITM_ITEM_LIST).insert(alternateRightChildOrderExprTree); alternateRightChildOrderExprTree_ = t.getPtr(); } ItemExpr *Union::removeAlternateRightChildOrderExprTree() { ItemExpr *result = alternateRightChildOrderExprTree_; alternateRightChildOrderExprTree_ = NULL; return result; } // MV-- // ----------------------------------------------------------------------- // member functions for class MergeUnion // ----------------------------------------------------------------------- MergeUnion::~MergeUnion() {} NABoolean MergeUnion::isLogical() const { return FALSE; } NABoolean MergeUnion::isPhysical() const { return TRUE; } HashValue MergeUnion::topHash() { HashValue result = Union::topHash(); // result ^= mergeExpr_; return result; } #pragma nowarn(262) // warning elimination NABoolean MergeUnion::duplicateMatch(const RelExpr & other) const { if (!RelExpr::duplicateMatch(other)) return FALSE; MergeUnion &o = (MergeUnion &) other; // if (mergeExpr_ != o.mergeExpr_) ABORT("duplicateMatch shouldn't be called for physical nodes"); return FALSE; } #pragma warn(262) // warning elimination RelExpr * MergeUnion::copyTopNode(RelExpr *derivedNode, CollHeap* outHeap) { MergeUnion *result; if (derivedNode == NULL) result = new (outHeap) MergeUnion(NULL, NULL, new (outHeap)UnionMap(*getUnionMap()), getOperatorType(), outHeap); else result = (MergeUnion *) derivedNode; result->mergeExpr_ = mergeExpr_; return Union::copyTopNode(result, outHeap); } void MergeUnion::setSortOrder(const ValueIdList &newSortOrder) { sortOrder_ = newSortOrder; buildMergeExpr(); } void MergeUnion::addLocalExpr(LIST(ExprNode *) &xlist, LIST(NAString) &llist) const { if (sortOrder_.entries() > 0) { xlist.insert(sortOrder_.rebuildExprTree(ITM_ITEM_LIST)); llist.insert("sort_order"); } if (mergeExpr_ != NULL) { xlist.insert(mergeExpr_); llist.insert("merge_expr"); } Union::addLocalExpr(xlist,llist); } void MergeUnion::buildMergeExpr() { // --------------------------------------------------------------------- // build the merge expression (an expression that tells which of the // two input rows, left or right, should be returned next) by creating // an expression "left <= right" from the sort order. // --------------------------------------------------------------------- ItemExpr *leftList = NULL; ItemExpr *rightList = NULL; BiRelat *result = NULL; if (sortOrder_.entries() > 0) { for (Lng32 i = 0; i < (Lng32)sortOrder_.entries(); i++) { ItemExpr *leftItem; ItemExpr *rightItem; leftItem = sortOrder_[i].getItemExpr()-> mapAndRewrite(getLeftMap(),TRUE).getItemExpr(); rightItem = sortOrder_[i].getItemExpr()-> mapAndRewrite(getRightMap(),TRUE).getItemExpr(); // swap left and right if DESC is specified. if(leftItem->getOperatorType() == ITM_INVERSE) { // both streams must be sorted according to the same order. CMPASSERT(rightItem->getOperatorType() == ITM_INVERSE); ItemExpr *temp = leftItem; leftItem = rightItem; rightItem = temp; } // add the newly formed fields of the sort key to the // left and right lists of sort keys if (leftList != NULL) { leftList = new (CmpCommon::statementHeap()) ItemList(leftList,leftItem); rightList = new (CmpCommon::statementHeap()) ItemList(rightList,rightItem); } else { // both left and right list must be NULL leftList = leftItem; rightList = rightItem; } } result = new (CmpCommon::statementHeap()) BiRelat(ITM_LESS_EQ,leftList,rightList); // make the comparison such that NULLs compare greater than instead // of making the expression result NULL result->setSpecialNulls(TRUE); result->synthTypeAndValueId(); } // store the result in the merge expression mergeExpr_ = result; } // ----------------------------------------------------------------------- // member functions for class GroupByAgg // ----------------------------------------------------------------------- GroupByAgg::~GroupByAgg() {} Int32 GroupByAgg::getArity() const { return 1; } void GroupByAgg::pushdownCoveredExpr(const ValueIdSet & outputExpr, const ValueIdSet & newExternalInputs, ValueIdSet & predicatesOnParent, const ValueIdSet * setOfValuesReqdByParent, Lng32 childIndex ) { // --------------------------------------------------------------------- // predicates can only be pushed down if the group by did contain // a group by clause or if this is a scalar groupby for a subquery that // contains null rejecting predicates. If the subquery contains null-rej. // preds then it does not need to do null instantiation for the empty // result set and therefore we do not create a separate VEGRegion for this // subquery. This means that preds can be freely pushed down in this case. // See GroupByAgg::pullUpPreds for a symmetric condition. // --------------------------------------------------------------------- ValueIdSet pushablePredicates; ValueIdSet exprOnParent; ValueIdSet emptySet; if (NOT groupExpr().isEmpty() || containsNullRejectingPredicates()) pushablePredicates = predicatesOnParent; #if 0 else computeValuesReqdForPredicates(predicatesOnParent, exprOnParent); #endif // --------------------------------------------------------------------- // Cause the retrieval of all those values that are needed for // computing the aggregate functions and the group by list. // --------------------------------------------------------------------- getValuesRequiredForEvaluatingAggregate(exprOnParent); exprOnParent += groupExpr(); // --------------------------------------------------------------------- RelExpr::pushdownCoveredExpr(emptySet, newExternalInputs, pushablePredicates, &exprOnParent, childIndex ); // --------------------------------------------------------------------- // Set the value of predicatesOnParent appropriately. // --------------------------------------------------------------------- if (NOT groupExpr().isEmpty() || containsNullRejectingPredicates()) predicatesOnParent.intersectSet(pushablePredicates); } // GroupByAgg::pushdownCoveredExpr void GroupByAgg::getPotentialOutputValues(ValueIdSet & outputValues) const { outputValues.clear(); // Assign the grouping expressions and the aggregate functions // that are computed here as the outputs. // outputValues += groupExpr(); outputValues += aggregateExpr(); // If we're enforcing an ITM_ONE_ROW on (x,y), then we can produce not // merely the ITM_ONE_ROW, but also x and y, so add them to our outputs. // For example, if the aggregate is, say, // ITM_ONE_ROW(VEGRef_10(T.A,ixT.A), VEGRef_15(T.B,ixT.B)) // { example query: select * from S where (select A,B from T) < (100,200) } // then add value ids 10 and 11 to our characteristic outputs. // for (ValueId aggid = aggregateExpr().init(); aggregateExpr().next(aggid); aggregateExpr().advance(aggid)) { ItemExpr *aggie = aggid.getItemExpr(); if (aggie->getOperatorType() == ITM_ONE_ROW) { ValueIdSet moreAvailableOutputs; aggie->child(0)->convertToValueIdSet(moreAvailableOutputs, NULL, ITM_ITEM_LIST, FALSE); outputValues += moreAvailableOutputs; } } } // GroupByAgg::getPotentialOutputValues() const NAString GroupByAgg::getText() const { if (NOT groupExpr().isEmpty()) { if (isNotAPartialGroupBy()) return "groupby"; else if (isAPartialGroupByRoot()) return "partial_groupby_root"; else if (isAPartialGroupByNonLeaf()) return "partial_groupby_non_leaf"; else return "partial_groupby_leaf"; } else { if (isNotAPartialGroupBy()) return "scalar_aggr"; else if (isAPartialGroupByRoot()) return "partial_aggr_root"; else if (isAPartialGroupByNonLeaf()) return "partial_aggr_non_leaf"; else return "partial_aggr_leaf"; } } // GroupByAgg::getText() HashValue GroupByAgg::topHash() { HashValue result = RelExpr::topHash(); result ^= groupExpr_; result ^= aggregateExpr_; result ^= (Int32) formEnum_; // MSVC requires cast. return result; } NABoolean GroupByAgg::duplicateMatch(const RelExpr & other) const { if (!RelExpr::duplicateMatch(other)) return FALSE; GroupByAgg &o = (GroupByAgg &) other; if (groupExpr_ != o.groupExpr_ OR aggregateExpr_ != o.aggregateExpr_ OR formEnum_ != o.formEnum_ ) return FALSE; return TRUE; } RelExpr * GroupByAgg::copyTopNode(RelExpr *derivedNode, CollHeap* outHeap) { GroupByAgg *result; if (derivedNode == NULL) result = new (outHeap) GroupByAgg(NULL, getOperatorType(), NULL, NULL, outHeap); else result = (GroupByAgg *) derivedNode; // copy parse tree nodes (parser only) if (groupExprTree_ != NULL) result->groupExprTree_ = groupExprTree_->copyTree(outHeap); if (aggregateExprTree_ != NULL) result->aggregateExprTree_ = aggregateExprTree_->copyTree(outHeap); result->groupExpr_ = groupExpr_; result->aggregateExpr_ = aggregateExpr_; result->formEnum_ = formEnum_; result->gbAggPushedBelowTSJ_ = gbAggPushedBelowTSJ_; result->gbAnalysis_ = gbAnalysis_; result->requiresMoveUp_ = requiresMoveUp_ ; result->leftUniqueExpr_ = leftUniqueExpr_; result->containsNullRejectingPredicates_ = containsNullRejectingPredicates_ ; result->parentRootSelectList_ = parentRootSelectList_; result->isMarkedForElimination_ = isMarkedForElimination_; result->selIndexInHaving_ = selIndexInHaving_; result->aggrExprsToBeDeleted_ = aggrExprsToBeDeleted_; return RelExpr::copyTopNode(result, outHeap); } void GroupByAgg::addGroupExprTree(ItemExpr *groupExpr) { ExprValueId g = groupExprTree_; ItemExprTreeAsList(&g, ITM_ITEM_LIST).insert(groupExpr); groupExprTree_ = g.getPtr(); } ItemExpr * GroupByAgg::removeGroupExprTree() { ItemExpr * result = groupExprTree_; groupExprTree_ = NULL; return result; } void GroupByAgg::addAggregateExprTree(ItemExpr *aggrExpr) { ExprValueId g = groupExprTree_; ItemExprTreeAsList(&g, ITM_ITEM_LIST).insert(aggrExpr); groupExprTree_ = g.getPtr(); } ItemExpr * GroupByAgg::removeAggregateExprTree() { ItemExpr * result = aggregateExprTree_; aggregateExprTree_ = NULL; return result; } void GroupByAgg::getValuesRequiredForEvaluatingAggregate(ValueIdSet& relevantValues) { // Find the values that are needed to evaluate aggregate functions. // NOTE: this should normally just be the direct children of the // aggregate functions. However, some aggregate functions such as // anyTrue sometimes refer to values further down the tree (and // if it's only by using such values as required sort orders). // Handle this special case here (or maybe we should have changed // the anyTrue aggregate function such that it takes separate arguments: // anyTrueGreater(a,b), anyTrueLess(a,b), anyTrueGreaterEq(a,b), ... // for each aggregate expression in the groupby node for (ValueId x = aggregateExpr_.init(); aggregateExpr_.next(x); aggregateExpr_.advance(x)) { Aggregate *agg = (Aggregate *) x.getItemExpr(); Lng32 nc = agg->getArity(); // handle special cases for special aggregate functions switch (agg->getOperatorType()) { case ITM_ANY_TRUE: case ITM_ANY_TRUE_MAX: { ItemExpr *boolInput = agg->child(0); // if the child is a binary comparison operator, then // require both of the children instead of the comparison op. switch (boolInput->getOperatorType()) { case ITM_EQUAL: case ITM_NOT_EQUAL: case ITM_LESS: case ITM_LESS_EQ: case ITM_GREATER: case ITM_GREATER_EQ: relevantValues += boolInput->child(0)->getValueId(); relevantValues += boolInput->child(1)->getValueId(); break; case ITM_VEG_PREDICATE: { VEG * vegPtr = ((VEGPredicate *)boolInput)->getVEG(); relevantValues += vegPtr->getVEGReference()->getValueId(); } break; default: // might not happen right now: an anyTrue with something // other than a binary comparison operator relevantValues += boolInput->getValueId(); break; } } break; case ITM_ONE_ROW: { // collect leaf values into relevant Values ValueIdSet AvailableOutputs_; agg->child(0)->convertToValueIdSet(AvailableOutputs_, NULL, ITM_ITEM_LIST, FALSE); relevantValues += AvailableOutputs_; break; } default: { // all other aggregate functions are handled here // // If we are doing a distinct aggregate we need the // distinct value id. E.g. sum(distinct x*x) with distinct // valueId x, means we eliminate // distinct x's first, then compute sum(x*x) if(agg->isDistinct()) relevantValues += agg->getDistinctValueId(); else relevantValues += agg->child(0)->getValueId(); // for each child of this particular aggregate expression for (Lng32 i = 1; i < nc; i++) { // add the value id of that child to "relevantValues" relevantValues += agg->child(i)->getValueId(); } } break; } } } void GroupByAgg::addLocalExpr(LIST(ExprNode *) &xlist, LIST(NAString) &llist) const { if (groupExprTree_ != NULL OR NOT groupExpr_.isEmpty()) { if (groupExpr_.isEmpty()) xlist.insert(groupExprTree_); else xlist.insert(groupExpr_.rebuildExprTree(ITM_ITEM_LIST)); llist.insert("grouping_columns"); } if (aggregateExprTree_ != NULL OR NOT aggregateExpr_.isEmpty()) { if (aggregateExpr_.isEmpty()) xlist.insert(aggregateExprTree_); else xlist.insert(aggregateExpr_.rebuildExprTree(ITM_ITEM_LIST)); llist.insert("aggregates"); } RelExpr::addLocalExpr(xlist,llist); } // ----------------------------------------------------------------------- // Examine the aggregate functions. If any one of them cannot be // evaluated in stages, for example, a partial aggregation followed // by finalization, then do not split this GroupByAgg. // ----------------------------------------------------------------------- NABoolean GroupByAgg::aggregateEvaluationCanBeStaged() const { for (ValueId aggrId = aggregateExpr().init(); aggregateExpr().next(aggrId); aggregateExpr().advance(aggrId)) { CMPASSERT(aggrId.getItemExpr()->isAnAggregate()); if (groupExpr().isEmpty() && (aggrId.getItemExpr()->getOperatorType() == ITM_ONEROW)) return FALSE; if (NOT ((Aggregate *)aggrId.getItemExpr())->evaluationCanBeStaged()) return FALSE; } return TRUE; } // GroupByAgg::aggregateEvaluationCanBeStaged() NABoolean GroupByAgg::executeInDP2() const { CMPASSERT(getPhysicalProperty()); return getPhysicalProperty()->executeInDP2(); } // Try to pull up predicates in preCodeGen, to reduce char. inputs of the // child. Don't actually do this unless "modify" parameter is set to TRUE, // (we want to test this condition in the optimizer for costing). // Return TRUE if we could move some predicates. // Could make this a virtual method on RelExpr if we want to support // this for other operators as well. NABoolean GroupByAgg::tryToPullUpPredicatesInPreCodeGen( const ValueIdSet &valuesAvailableInParent, // pull preds that are covered by these ValueIdSet &pulledPredicates, // return the pulled-up preds ValueIdMap *optionalMap) // optional map to rewrite preds { // other item expressions needed by the child (excluding // selection preds), this is where we make use of the knowledge // that we are dealing with a groupby. ValueIdSet myLocalExpr; ValueIdSet myNewInputs(getGroupAttr()->getCharacteristicInputs()); ValueIdSet mappedValuesAvailableInParent; ValueIdSet tempPulledPreds(selectionPred()); // be optimistic myLocalExpr += child(0).getGroupAttr()->getCharacteristicInputs(); myLocalExpr += groupExpr(); myLocalExpr += aggregateExpr(); // consider only preds that we can evaluate in the parent if (optionalMap) optionalMap->mapValueIdSetDown(valuesAvailableInParent, mappedValuesAvailableInParent); else mappedValuesAvailableInParent = valuesAvailableInParent; tempPulledPreds.removeUnCoveredExprs(mappedValuesAvailableInParent); // add the rest to myLocalExpr myLocalExpr += selectionPred(); myLocalExpr -= tempPulledPreds; // see which of the char. inputs are needed by my local expressions myLocalExpr.weedOutUnreferenced(myNewInputs); // pull up predicates only if that reduces my char. inputs if (NOT (myNewInputs == getGroupAttr()->getCharacteristicInputs())) { ValueIdSet selPredOnlyInputs(getGroupAttr()->getCharacteristicInputs()); // inputs only used by selection predicates selPredOnlyInputs -= myNewInputs; // loop through the selection predicates and pull // those up that reference myNewInputs for (ValueId x=tempPulledPreds.init(); tempPulledPreds.next(x); tempPulledPreds.advance(x)) { if (x.getItemExpr()->referencesOneValueFrom(selPredOnlyInputs)) { // keep this predicate in tempPulledPreds and // remove it from the selection predicates selectionPred() -= x; } else { // this predicate stays on the local node, // remove it from tempPulledPreds tempPulledPreds -= x; } } } else { // no predicates get pulled up tempPulledPreds.clear(); } if (!tempPulledPreds.isEmpty()) { // return pulled predicates if (optionalMap) { ValueIdSet rewrittenPulledPreds; optionalMap->rewriteValueIdSetUp(rewrittenPulledPreds, tempPulledPreds); pulledPredicates += rewrittenPulledPreds; } else pulledPredicates += tempPulledPreds; // adjust char. inputs - this is not exactly // good style, just overwriting the char. inputs, but // hopefully we'll get away with it at this stage in // the processing getGroupAttr()->setCharacteristicInputs(myNewInputs); } // note that we removed these predicates from our node, it's the // caller's responsibility to take them return (NOT tempPulledPreds.isEmpty()); } // ----------------------------------------------------------------------- // member functions for class SortGroupBy // ----------------------------------------------------------------------- SortGroupBy::~SortGroupBy() {} NABoolean SortGroupBy::isLogical() const {return FALSE;} NABoolean SortGroupBy::isPhysical() const {return TRUE;} const NAString SortGroupBy::getText() const { return "sort_" + GroupByAgg::getText(); } RelExpr * SortGroupBy::copyTopNode(RelExpr *derivedNode, CollHeap* outHeap) { RelExpr *result; if (derivedNode == NULL) result = new (outHeap) SortGroupBy(NULL, getOperatorType(), NULL, NULL, outHeap); else result = derivedNode; return GroupByAgg::copyTopNode(result, outHeap); } PlanPriority ShortCutGroupBy::computeOperatorPriority (const Context* context, PlanWorkSpace *pws, Lng32 planNumber) { // For min(X) or max(X) where X is the first clustering key column, // allow shortcutgroupby plan to compete with other plans based on cost. // Specifically, match the priority of the wave fix so that a // shortcutgroupby plan can cost compete with the parallel // partialgroupby plan. PlanPriority result; if (QueryAnalysis::Instance() && QueryAnalysis::Instance()->dontSurfTheWave()) { // do this only if the wave fix is a competing plan result.incrementLevels(10, 0); } return result; } PlanPriority SortGroupBy::computeOperatorPriority (const Context* context, PlanWorkSpace *pws, Lng32 planNumber) { const PhysicalProperty* spp = context->getPlan()->getPhysicalProperty(); Lng32 degreeOfParallelism = spp->getCountOfPartitions(); double val = 1; if (degreeOfParallelism <= 1) { // serial plans are risky. exact an insurance premium from serial plans. val = CURRSTMT_OPTDEFAULTS->riskPremiumSerial(); // when dontSurfTheWave is ON, // consider serial sort_partial_aggr_nonleaf risky if (QueryAnalysis::Instance() && QueryAnalysis::Instance()->dontSurfTheWave() && isAPartialGroupByNonLeaf() && val <= 1) { val = 1.1; } } CostScalar premium(val); PlanPriority result(0, 0, premium); // WaveFix Begin // This is part of the fix for the count(*) wave // if there is a scalar aggregate query on a single partitioned table, // something like Select count(*) from fact; // In such a case we would like to get a layer of esps, // doing so causes the plan to fixup in parallel avoiding the serial // fixup if the plan is just the master executor on top of dp2. The // serial fixup causes the query to execute in wave pattern, since // each dp2 is fixed up and then starts execution. Due to serial // fixup a dp2 is fixed up, and then we move to the next dp2 causing // the wave pattern. if (QueryAnalysis::Instance() && QueryAnalysis::Instance()->dontSurfTheWave()) { if (isAPartialGroupByLeaf2() && spp->executeInDP2()) result.incrementLevels(10, 0); else if (isAPartialGroupByLeaf1() && (degreeOfParallelism>1) && (!spp->executeInDP2())) result.incrementLevels(5, 0); } // WaveFix End // The remaining part of the code in this function relates to parallelism // priority and not applicable to scalar aggregates if (groupExpr().isEmpty()) return result; if(spp->executeInDP2()) return result; // For the option of Max Degree of Parallelism we can either use the // value set in comp_int_9 (if positive) or we use the number of CPUs // if the CQD is set to -1, or feature is disabled if CQD is 0 (default). Lng32 maxDegree = ActiveSchemaDB()->getDefaults().getAsLong(COMP_INT_9); if (CURRSTMT_OPTDEFAULTS->maxParallelismIsFeasible() OR (maxDegree == -1) ) { // if CQD is set to -1 this mean use the number of CPUs maxDegree = spp->getCurrentCountOfCPUs(); } if (maxDegree > 1) // CQD set to 0 means feature is OFF { if (degreeOfParallelism < maxDegree) result.incrementLevels(0,-10); // need to replace with constant } return result; } // ----------------------------------------------------------------------- // member functions for class ShortCutGroupBy // ----------------------------------------------------------------------- const NAString ShortCutGroupBy::getText() const { return "shortcut_" + GroupByAgg::getText(); } RelExpr * ShortCutGroupBy::copyTopNode(RelExpr *derivedNode, CollHeap* outHeap) { ShortCutGroupBy *result; if (derivedNode == NULL) // This is the top of the derivation chain // Create an empty ShortCutGroupBy node. // result = new (outHeap) ShortCutGroupBy(NULL, getOperatorType(), NULL, NULL, outHeap); else // A node has already been constructed as a derived class. // result = (ShortCutGroupBy *) derivedNode; // Copy the relevant fields. result->opt_for_max_ = opt_for_max_; result->opt_for_min_ = opt_for_min_; result->isnullable_ = isnullable_; result->lhs_anytrue_ = lhs_anytrue_; result->rhs_anytrue_ = rhs_anytrue_; // Copy any data members from the classes lower in the derivation chain. // return GroupByAgg::copyTopNode(result, outHeap); } // ----------------------------------------------------------------------- // member functions for class PhysShortCutGroupBy // ----------------------------------------------------------------------- RelExpr * PhysShortCutGroupBy::copyTopNode(RelExpr *derivedNode, CollHeap* outHeap) { RelExpr *result; if (derivedNode == NULL) // This is the top of the derivation chain // Create an empty ShortCutGroupBy node. // result = new (outHeap) PhysShortCutGroupBy(NULL, getOperatorType(), NULL, NULL, outHeap); else // A node has already been constructed as a derived class. // result = (PhysShortCutGroupBy *) derivedNode; // PhysShortCutGroupBy has no data members. // Copy any data members from the classes lower in the derivation chain. // return ShortCutGroupBy::copyTopNode(result, outHeap); } // ----------------------------------------------------------------------- // member functions for class HashGroupBy // ----------------------------------------------------------------------- HashGroupBy::~HashGroupBy() {} NABoolean HashGroupBy::isLogical() const {return FALSE;} NABoolean HashGroupBy::isPhysical() const {return TRUE;} const NAString HashGroupBy::getText() const { return "hash_" + GroupByAgg::getText(); } RelExpr * HashGroupBy::copyTopNode(RelExpr *derivedNode, CollHeap* outHeap) { RelExpr *result; if (derivedNode == NULL) result = new (outHeap) HashGroupBy(NULL, getOperatorType(), NULL, NULL, outHeap); else result = derivedNode; return GroupByAgg::copyTopNode(result, outHeap); } PlanPriority HashGroupBy::computeOperatorPriority (const Context* context, PlanWorkSpace *pws, Lng32 planNumber) { const PhysicalProperty* spp = context->getPlan()->getPhysicalProperty(); Lng32 degreeOfParallelism = spp->getCountOfPartitions(); double val = 1; if (degreeOfParallelism <= 1) { // Don't command premium for serial hash partial groupby plan if : // 1. Operator is partial group by root // 2. process < 5K rows // This is to prevent optimizer choosing parallel plans for small queries. // The idea is either premium has been already applied for groupby leaf level // or leaf is running in parallel, we don't need to run root also in parallel if ( isAPartialGroupByRoot() && CostScalar((ActiveSchemaDB()->getDefaults()). getAsULong(GROUP_BY_PARTIAL_ROOT_THRESHOLD)) >= this->getChild0Cardinality(context) ) val = 1; else // serial plans are risky. extract an insurance premium from serial plans. val = CURRSTMT_OPTDEFAULTS->riskPremiumSerial(); } CostScalar premium(val); PlanPriority result(0, 0, premium); if (QueryAnalysis::Instance() AND QueryAnalysis::Instance()->optimizeForFirstNRows()) result.incrementLevels(HASH_GROUP_BY_FIRST_N_PRIORITY,0); // The remaining part of the code in this funtion relates to parallelism // priority and not applicable to scalar aggregates if (groupExpr().isEmpty()) return result; // esp parallelism priority logic does not apply to operators in dp2 if(spp->executeInDP2()) return result; // For the option of Max Degree of Parallelism we can either use the // value set in comp_int_9 (if positive) or we use the number of CPUs // if the CQD is set to -1, or feature is disabled if CQD is 0 (default). Lng32 maxDegree = ActiveSchemaDB()->getDefaults().getAsLong(COMP_INT_9); if (CURRSTMT_OPTDEFAULTS->maxParallelismIsFeasible() OR (maxDegree == -1) ) { // if CQD is set to -1 this mean use the number of CPUs maxDegree = spp->getCurrentCountOfCPUs(); } if (maxDegree > 1) // CQD set to 0 means feature is OFF { if (degreeOfParallelism < maxDegree) result.incrementLevels(0,-10); // need to replace with constant } //cout<<maxDegree<<"-------"<<spp->getCountOfPartitions()<<endl; return result; } // ----------------------------------------------------------------------- // member functions for class Scan // ----------------------------------------------------------------------- void Scan::getPotentialOutputValues(ValueIdSet & outputValues) const { outputValues.clear(); // // Assign the set of columns that belong to the table to be scanned // as the output values that can be produced by this scan. // if (potentialOutputs_.isEmpty()) { outputValues.insertList( getTableDesc()->getColumnList() ); outputValues.insertList( getTableDesc()->hbaseTSList() ); outputValues.insertList( getTableDesc()->hbaseVersionList() ); } else outputValues = potentialOutputs_; outputValues += getExtraOutputColumns(); } // Scan::getPotentialOutputValues() void Scan::getPotentialOutputValuesAsVEGs(ValueIdSet& outputs) const { outputs.clear(); ValueIdSet tempSet ; ValueIdList tempList ; getPotentialOutputValues(tempSet); getTableDesc()->getEquivVEGCols(tempSet, tempList); outputs = tempList ; } Int32 Scan::getArity() const { return 0;} NABoolean Scan::isHiveTable() const { return (getTableDesc() && getTableDesc()->getNATable() ? getTableDesc()->getNATable()->isHiveTable() : FALSE); } NABoolean Scan::isHbaseTable() const { return (getTableDesc() && getTableDesc()->getNATable() ? getTableDesc()->getNATable()->isHbaseTable() : FALSE); } NABoolean Scan::isSeabaseTable() const { return (getTableDesc() && getTableDesc()->getNATable() ? getTableDesc()->getNATable()->isSeabaseTable() : FALSE); } const NAString Scan::getText() const { NAString op(CmpCommon::statementHeap()); if (isSampleScan() == TRUE) op = "sample_scan "; else op = "scan "; return op + userTableName_.getTextWithSpecialType(); } HashValue Scan::topHash() { HashValue result = RelExpr::topHash(); result ^= getTableDesc(); result ^= potentialOutputs_; result ^= numIndexJoins_; return result; } NABoolean Scan::duplicateMatch(const RelExpr & other) const { if (NOT RelExpr::duplicateMatch(other)) return FALSE; Scan &o = (Scan &) other; if (NOT (userTableName_ == o.userTableName_) OR NOT (getTableDesc() == o.getTableDesc()) OR NOT (potentialOutputs_ == o.potentialOutputs_) OR ((forcedIndexInfo_ OR o.forcedIndexInfo_) AND ( //just comparing the entries is probably not enough???? NOT (indexOnlyIndexes_.entries() == o.indexOnlyIndexes_.entries()) OR NOT (possibleIndexJoins_ == o.possibleIndexJoins_) OR NOT (numIndexJoins_ == o.numIndexJoins_))) OR NOT (isSingleVPScan_ == o.isSingleVPScan_) OR NOT (getExtraOutputColumns() == o.getExtraOutputColumns()) OR NOT (samplePercent() == o.samplePercent()) OR NOT (clusterSize() == o.clusterSize())) return FALSE; return TRUE; } RelExpr * Scan::copyTopNode(RelExpr *derivedNode, CollHeap* outHeap) { Scan *result; if (derivedNode == NULL) result = new (outHeap) Scan(userTableName_, getTableDesc(), REL_SCAN, outHeap); else result = (Scan *) derivedNode; result->baseCardinality_ = baseCardinality_; result->potentialOutputs_ = potentialOutputs_; result->numIndexJoins_ = numIndexJoins_; result->accessOptions_ = accessOptions_; result->pkeyHvarList_ = pkeyHvarList_; result->setOptStoi(stoi_); result->samplePercent(samplePercent()); result->setScanSelectivityFactor(getScanSelectivityFactor() ); result->setScanCardinalityHint(getScanCardinalityHint() ); result->clusterSize(clusterSize()); result->scanFlags_ = scanFlags_; result->setExtraOutputColumns(getExtraOutputColumns()); result->isRewrittenMV_ = isRewrittenMV_; result->matchingMVs_ = matchingMVs_; result->hbaseAccessOptions_ = hbaseAccessOptions_; // don't copy values that can be calculated by addIndexInfo() // (could be done, but we are lazy and just call addIndexInfo() again) return RelExpr::copyTopNode(result, outHeap); } void Scan::copyIndexInfo(RelExpr *derivedNode) { CMPASSERT (derivedNode != NULL AND derivedNode->getOperatorType() == REL_SCAN); Scan * scan = (Scan *)derivedNode; forcedIndexInfo_ = scan->forcedIndexInfo_; // set the selectivity factor if defined by the user if (scan->cardinalityHint_ >= 1.0) cardinalityHint_ = scan->cardinalityHint_; else cardinalityHint_ = -1.0; if (scan->selectivityFactor_ >= 0.0) { if (scan->selectivityFactor_ <= 1.0) selectivityFactor_ = scan->selectivityFactor_; else selectivityFactor_ = csOne; } else selectivityFactor_ = -1.0; if (NOT scan->getIndexOnlyIndexes().isEmpty() OR scan->getPossibleIndexJoins().entries() > 0) { // first copy the possible index join info const LIST(ScanIndexInfo *) & ixJoins = scan->getPossibleIndexJoins(); for (CollIndex i = 0; i < ixJoins.entries(); i++) { ScanIndexInfo * ix = new (CmpCommon::statementHeap()) ScanIndexInfo(*(ixJoins[i])); possibleIndexJoins_.insert(ix); } // now, copy the index descriptors const SET(IndexProperty *) & ixDescs = scan->getIndexOnlyIndexes(); for (CollIndex j = 0; j <ixDescs.entries(); j++) { indexOnlyIndexes_.insert(ixDescs[j]); } } } void Scan::removeIndexInfo() { possibleIndexJoins_.clear(); indexOnlyIndexes_.clear(); indexJoinScans_.clear(); forcedIndexInfo_ = FALSE; } /******************************************************* * Generates set of IndexDesc from the set of IndexProperty ********************************************************/ const SET(IndexDesc *) & Scan::deriveIndexOnlyIndexDesc() { indexOnlyScans_.clear(); CollIndex ixCount = indexOnlyIndexes_.entries(); for(CollIndex i=0; i< ixCount; i++) { indexOnlyScans_.insert(indexOnlyIndexes_[i]->getIndexDesc()); } return indexOnlyScans_; } /******************************************************* * Generates set of IndexDesc from the set of ScanIndexInfo ********************************************************/ const SET(IndexDesc *) & Scan::deriveIndexJoinIndexDesc() { indexJoinScans_.clear(); CollIndex ijCount = possibleIndexJoins_.entries(); for(CollIndex i=0; i< ijCount; i++) { ScanIndexInfo *ixi = possibleIndexJoins_[i]; CollIndex uixCount = ixi->usableIndexes_.entries(); for(CollIndex j=0; j < uixCount; j++) { if (ixi->usableIndexes_[j]->getIndexDesc()) indexJoinScans_.insert(ixi->usableIndexes_[j]->getIndexDesc()); } } return indexJoinScans_; } void Scan::addIndexInfo() { // don't do this twice, return if already set if (NOT indexOnlyIndexes_.isEmpty() OR possibleIndexJoins_.entries() > 0) return; forcedIndexInfo_ = FALSE; const TableDesc * tableDesc = getTableDesc(); const LIST(IndexDesc *) & ixlist = tableDesc->getIndexes(); ValueIdSet preds = selectionPred(); // changing back to old predicate tree: if ((CmpCommon::getDefault(RANGESPEC_TRANSFORMATION) == DF_ON ) && (preds.entries())) { ValueIdList selectionPredList(preds); ItemExpr *inputItemExprTree = selectionPredList.rebuildExprTree(ITM_AND,FALSE,FALSE); ItemExpr * resultOld = revertBackToOldTree(CmpCommon::statementHeap(), inputItemExprTree); preds.clear(); resultOld->convertToValueIdSet(preds, NULL, ITM_AND); doNotReplaceAnItemExpressionForLikePredicates(resultOld,preds,resultOld); // ValueIdSet resultSet; // revertBackToOldTreeUsingValueIdSet(preds, resultSet); // ItemExpr* resultOld = resultSet.rebuildExprTree(ITM_AND,FALSE,FALSE); // preds.clear(); // preds += resultSet; // doNotReplaceAnItemExpressionForLikePredicates(resultOld,preds,resultOld); } if (CmpCommon::getDefault(MTD_GENERATE_CC_PREDS) == DF_ON) { // compute predicates on computed columns from regular predicates, based // on the definition of the computed column. Example: // - regular predicate: a = 99 // - computed column definition: "_SALT_" = HASH2PARTFUNC(a,2) // - computed predicate: "_SALT_" = HASH2PARTFUNC(99,2); ValueIdSet clusteringKeyCols( getTableDesc()->getClusteringIndex()->getClusteringKeyCols()); ValueIdSet selectionPreds(preds); ScanKey::createComputedColumnPredicates( selectionPreds, clusteringKeyCols, getGroupAttr()->getCharacteristicInputs(), generatedCCPreds_); } // a shortcut for tables with no indexes if ((ixlist.entries() == 1)|| (tableDesc->isPartitionNameSpecified())) { // that's easy, there is only one index (the base table) // and that index better have everything we need IndexJoinSelectivityEnum junk; MdamFlags flag=ixlist[0]->pruneMdam(preds,TRUE,junk);; IndexProperty * ixProp = new(CmpCommon::statementHeap()) IndexProperty(ixlist[0], flag); indexOnlyIndexes_.insert(ixProp); return; } // all the value ids that are required by the scan and its parents ValueIdSet requiredValueIds(getGroupAttr()->getCharacteristicOutputs()); // VEGPreds can have two forms, an A IS NOT NULL form and an A=B form // when expanded in the generator. If an index does not provide a // VEG member that the base table provides, a VEGPredicate could be // covered by the index in its IS NOT NULL form (checking a char. input // whether it is not null). To avoid this bug, add all the base cols // that contribute to VEGPredicates as explicitly required values. addBaseColsFromVEGPreds(requiredValueIds); // for debugging in ObjectCenter if (tableDesc == NULL) { requiredValueIds.display(); } // using old predicate tree: if ((CmpCommon::getDefault(RANGESPEC_TRANSFORMATION) == DF_ON ) && (preds.entries())) { requiredValueIds += preds; } else // selection predicates are also required, add them to requiredValueIds requiredValueIds += selectionPred(); // a list of VEGReferences to the clustering key column(s) ValueIdSet clusteringKeyColumns; // some helper variables ValueIdList clusteringKeyColList; // a set of join predicates between indexes (same for all indexes) ValueIdSet indexJoinPreds; // --------------------------------------------------------------------- // find out the subset of values that are always covered // --------------------------------------------------------------------- // get the clustering key columns and transform them into VEGies CMPASSERT(tableDesc); tableDesc->getEquivVEGCols( tableDesc->getClusteringIndex()->getIndexKey(), clusteringKeyColList); clusteringKeyColumns = clusteringKeyColList; // get the VEGPredicates from the list of VEGReferences; they are // the join predicates between indexes (who all contain the clustering key) for (ValueId x = clusteringKeyColumns.init(); clusteringKeyColumns.next(x); clusteringKeyColumns.advance(x)) { // clustering key columns must be VEGReferences CMPASSERT(x.getItemExpr()->getOperatorType() == ITM_VEG_REFERENCE); if (((VEGReference *) x.getItemExpr())->getVEG()->getSpecialNulls()) ((VEGReference *) x.getItemExpr()) ->getVEG()->getVEGPredicate()->setSpecialNulls(TRUE); // find the corresponding VEGPredicate and add it to the join preds indexJoinPreds += ((VEGReference *) x.getItemExpr())-> getVEG()->getVEGPredicate()->getValueId(); } const NABoolean updatingCol = tableDesc->getColUpdated().entries() > 0; const NABoolean unlimitedIndexJoinsAllowed = ((ActiveControlDB()->getRequiredShape() AND ActiveControlDB()->getRequiredShape()->getShape() AND NOT ActiveControlDB()->getRequiredShape()->getShape()->isCutOp()) OR (getGroupAttr()->isEmbeddedUpdateOrDelete()) OR (getGroupAttr()->isStream()) OR (tableDesc->hasHintIndexes()) // xxx this could be done better ); const TableAnalysis * tAnalysis = getTableDesc()->getTableAnalysis(); // with this CQD value set, try to consider minimum indexes possible // if ixProp is no better than any of indexOnlyIndexes_ - don't add // it. If ixProp is better than some of this set - remove them. NABoolean tryToEliminateIndex = CURRSTMT_OPTDEFAULTS->indexEliminationLevel() == OptDefaults::AGGRESSIVE AND NOT unlimitedIndexJoinsAllowed AND tAnalysis; CostScalar indexEliminationThreshold = ActiveSchemaDB()->getDefaults().getAsLong(INDEX_ELIMINATION_THRESHOLD); NABoolean printIndexElimination = CmpCommon::getDefault(NSK_DBG_PRINT_INDEX_ELIMINATION) == DF_ON && CmpCommon::getDefault(NSK_DBG) == DF_ON; ostream &out = CURRCONTEXT_OPTDEBUG->stream(); if ( printIndexElimination ) { out << endl << "call addIndexInfo()" << endl; out << "tryToEliminateIndex=" << (Lng32)tryToEliminateIndex << endl; } // --------------------------------------------------------------------- // For each index, check whether it provides any useful values // --------------------------------------------------------------------- for (CollIndex indexNo = 0; indexNo < ixlist.entries(); indexNo++) { IndexDesc *idesc = ixlist[indexNo]; // Determine if this index can be used for a scan during an update. if (updatingCol AND NOT updateableIndex(idesc)) continue; ValueIdSet indexColumns(idesc->getIndexColumns()); ValueIdSet referencedInputs; ValueIdSet coveredSubexpr; ValueIdSet unCoveredExpr; GroupAttributes indexOnlyGA; NABoolean indexOnlyScan; // make group attributes for an index scan indexOnlyGA.addCharacteristicOutputs(idesc->getIndexColumns()); indexOnlyGA.addCharacteristicOutputs(extraOutputColumns_); // does the index cover all required values, and if not, which // ones does it cover and which ones are not covered indexOnlyScan = requiredValueIds.isCovered( getGroupAttr()->getCharacteristicInputs(), indexOnlyGA, referencedInputs, coveredSubexpr, unCoveredExpr); // if this is a sample scan (currently these are only CLUSTER // sampling scans) then do not choose index only scan. Also, // due to an artifact of sampling, the 'isCovered' test above // will not return TRUE even for the ClusteringIndex, so force // it to be true for the ClusteringIndex. Note that // ClusterIndex means that this is the basetable access path. // if (isSampleScan()) { if (idesc->isClusteringIndex()) { // Force it to be TRUE for the basetable access path. // This overrides the value of 'indexOnlyScan' produced // above since for sample scans, the isCovered test will // always fail, even for the basetable. // indexOnlyScan = TRUE; } else { indexOnlyScan = FALSE; } } // if the user specified IN EXCLUSIVE MODE option for this select, // then do not choose index only scan. This is needed so the base // table row could be locked in exclusive mode. if ((indexOnlyScan) && (! idesc->isClusteringIndex()) && (accessOptions().lockMode() == EXCLUSIVE_)) indexOnlyScan = FALSE; //pruneMdam() returns a flag indicating if the index would have //has good enough key access for MDAM access to be viable. For index //join indexes it also returns a IndexJoinSelectivityEnum that //indicates if the index join is going to exceed the cost of just //scanning the base table. if (indexOnlyScan) { // this index supplies all the info we need, consider // it for an index only scan later IndexJoinSelectivityEnum junk; MdamFlags flag=idesc->pruneMdam(preds,TRUE,junk); IndexProperty * ixProp = new(CmpCommon::statementHeap()) IndexProperty(idesc, flag); if (tryToEliminateIndex) { // with this CQD value set, try to consider minimum indexes possible // if ixProp is no better than any of indexOnlyIndexes_ - don't add // it. If ixProp is better than some of this set - remove them. ixProp->updatePossibleIndexes(indexOnlyIndexes_, this); } else indexOnlyIndexes_.insert(ixProp); } else { GroupAttributes indexGA; ValueIdSet ijCoveredPredicates; if(numIndexJoins_ < MAX_NUM_INDEX_JOINS AND NOT unlimitedIndexJoinsAllowed) { //Is any of the predicates covered by key columns of the //alternate index? ValueIdList userKeyColumns(idesc->getIndexKey()); CollIndex numSecondaryIndexKey = idesc->getNAFileSet()->getCountOfColumns( TRUE, // key columns only TRUE, // user-specified key columns only FALSE, // don't exclude system columns FALSE); // don't exclude salt/divisioning columns CollIndex numClusteringKey = userKeyColumns.entries() - numSecondaryIndexKey; if(NOT idesc->isUniqueIndex()) { CollIndex entry = userKeyColumns.entries() -1; for(CollIndex i=0;i<numClusteringKey;i++) { userKeyColumns.removeAt(entry); entry--; } } indexGA.addCharacteristicOutputs(userKeyColumns); ValueIdSet ijReferencedInputs; ValueIdSet ijUnCoveredExpr; ValueId vid; ValueIdSet disjuncts; // Multi-Index OR optimization requires that the index information // is maintained for disjuncts as well. So here we check if the // predicate is of the form A OR B OR C. If it is, then the top // operator is the OR operator. The optimization is considered only // in this case. So if the predicate has an OR on top of the item // expression, then we check if the disjuncts are covered by the // index. if (preds.entries() == 1) { preds.getFirst(vid); if (vid.getItemExpr()->getOperatorType() == ITM_OR) { vid.getItemExpr()->convertToValueIdSet(disjuncts, NULL, ITM_OR, FALSE); } else disjuncts=preds; } else disjuncts=preds; disjuncts.isCovered( getGroupAttr()->getCharacteristicInputs(), indexGA, ijReferencedInputs, ijCoveredPredicates, ijUnCoveredExpr); // we only care about predicates that are entirely covered, // parts of predicates (like constants) that are covered // don't help in this context ijCoveredPredicates.intersectSet(disjuncts); } // This index does not provide all required values. // However, it might be useful to join this index with another // one (most likely the clustering index) to get the rest // of the required values. If this is promising at all, then // add this index to a list of possible index joins. // In that list of possible index joins, group all indexes // that provide the same set of output values (but different // orders) together. if (numIndexJoins_ < MAX_NUM_INDEX_JOINS AND (unlimitedIndexJoinsAllowed OR NOT ijCoveredPredicates.isEmpty())) { // changing back to old predicate tree: ValueIdSet selectionpreds; if((CmpCommon::getDefault(RANGESPEC_TRANSFORMATION) == DF_ON ) && (selectionPred().entries())) { ValueIdList selectionPredList(selectionPred()); ItemExpr *inputItemExprTree = selectionPredList.rebuildExprTree(ITM_AND,FALSE,FALSE); ItemExpr * resultOld = revertBackToOldTree(CmpCommon::statementHeap(), inputItemExprTree); resultOld->convertToValueIdSet(selectionpreds, NULL, ITM_AND); doNotReplaceAnItemExpressionForLikePredicates(resultOld,selectionpreds,resultOld); // revertBackToOldTreeUsingValueIdSet(selectionPred(), selectionpreds); // ItemExpr* resultOld = selectionpreds.rebuildExprTree(ITM_AND,FALSE,FALSE); // doNotReplaceAnItemExpressionForLikePredicates(resultOld,selectionpreds,resultOld); } // For now, only consider indexes that covers one of the selection // predicates unless control query shape is in effect. // NOTE: we should also consider indexes that potentially // could provide an interesting order or partitioning. To do // that, we would have to check whether their first key column // or any of their partitioning key columns is used. // For exclusive mode, any index can be called a usable index of // of another, only if it produces the same characteristic // outputs as the main index, and also both indexes have the same // uncovered expressions. This is because, in exclusive mode the // base (clustering key) index must always be read even if the // alternate index is index only, because the locks on the // base index are required for exclusive mode. // We can test the index only case with exclusive mode by // requiring the uncovered expressions to be the same // (both would be NULL for index only). // we now have the following information ready: // - coveredSubexpr are the values that the index can deliver // (+ clustering key columns) // - unCoveredExpr are the values that the right child of the // index join should deliver (+ clustering key values) // - we know the clustering key VEGies, whose VEGPredicates // serve as join predicates between the indexes // - we can find out the selection predicates covered // by the index by intersecting them with coveredSubexpr ValueIdSet newOutputsFromIndex(coveredSubexpr); ValueIdSet newIndexPredicates(coveredSubexpr); ValueIdSet newOutputsFromRightScan(unCoveredExpr); newOutputsFromIndex += clusteringKeyColumns; if(CmpCommon::getDefault(RANGESPEC_TRANSFORMATION) == DF_ON ) { newOutputsFromIndex -= selectionpreds; } else newOutputsFromIndex -= selectionPred(); newOutputsFromIndex -= getGroupAttr()-> getCharacteristicInputs(); if(CmpCommon::getDefault(RANGESPEC_TRANSFORMATION) == DF_ON ) { newIndexPredicates.intersectSet(selectionpreds); newOutputsFromRightScan -= selectionpreds; } else { newIndexPredicates.intersectSet(selectionPred()); newOutputsFromRightScan -= selectionPred(); } newOutputsFromRightScan += clusteringKeyColumns; NABoolean idescAbsorbed = FALSE; // does another index have the same covered values? for (CollIndex i = 0; i < possibleIndexJoins_.entries(); i++) { NABoolean isASupersetIndex = possibleIndexJoins_[i]->outputsFromIndex_.contains(newOutputsFromIndex); NABoolean isASubsetIndex = newOutputsFromIndex.contains(possibleIndexJoins_[i]->outputsFromIndex_) ; NABoolean isASuperOrSubsetIndex = isASupersetIndex || isASubsetIndex; NABoolean produceSameIndexOutputs = isASupersetIndex && isASubsetIndex; if ((possibleIndexJoins_[i]->inputsToIndex_ == referencedInputs) && ((accessOptions().lockMode() != EXCLUSIVE_) || possibleIndexJoins_[i]->outputsFromRightScan_ == newOutputsFromRightScan)) { ScanIndexInfo *ixi = possibleIndexJoins_[i]; IndexJoinSelectivityEnum isGoodIndexJoin = INDEX_JOIN_VIABLE; MdamFlags mdamFlag = idesc->pruneMdam(ixi->indexPredicates_,FALSE, isGoodIndexJoin, getGroupAttr(),&(ixi->inputsToIndex_)); IndexProperty * ixProp; if(getGroupAttr()->getInputLogPropList().entries() >0) ixProp = new(CmpCommon::statementHeap()) IndexProperty(idesc, mdamFlag, isGoodIndexJoin, (getGroupAttr()->getInputLogPropList())[0]); else ixProp = new(CmpCommon::statementHeap()) IndexProperty(idesc, mdamFlag, isGoodIndexJoin); if ( !tryToEliminateIndex ) { if ( produceSameIndexOutputs && ixi->indexPredicates_ == newIndexPredicates ) { ixi->usableIndexes_.insert(ixProp); idescAbsorbed = TRUE; break; } } else { CANodeId tableId = tAnalysis->getNodeAnalysis()->getId(); // keep the index that provides the maximal coverage of the // predicate. Do this only when the output from one index is // the super set of the other. For example (a,b) in I1 // (CREATE INDEX T1 on T(a, b)) is a superset of (a) in I2 // (CREATE INDEX T2 on T(a)). if ( isASuperOrSubsetIndex && !produceSameIndexOutputs ) { // Score the index's coverage by computing the remaining length of the // key columns not covering the index predicates. The one with remaining // length of 0 is the best. ValueIdSet indexCols; newIndexPredicates.findAllReferencedIndexCols(indexCols); Lng32 currentPrefixLen = idesc->getIndexKey().findPrefixLength(indexCols); Lng32 currentSuffixLen = idesc->getIndexKey().entries() - currentPrefixLen; Lng32 previousPrefixLen = ixi->usableIndexes_[0]->getIndexDesc() ->getIndexKey().findPrefixLength(indexCols); Lng32 previousSuffixLen = ixi->usableIndexes_[0]->getIndexDesc() ->getIndexKey().entries() - previousPrefixLen; if ( currentSuffixLen < previousSuffixLen ) { if ( printIndexElimination ) out << "Eliminate index join heuristics 1: remove " << ixi->usableIndexes_[0]->getIndexDesc()->getExtIndexName().data() << endl; ixi = new (CmpCommon::statementHeap()) ScanIndexInfo(referencedInputs, newOutputsFromIndex, newIndexPredicates, indexJoinPreds, newOutputsFromRightScan, idesc->getIndexKey(), ixProp); possibleIndexJoins_[i] = ixi; } else { // do nothing. The current index is less useful. if ( printIndexElimination ) out << "Eliminate index join heuristics 1: remove " << idesc->getExtIndexName().data() << endl; } idescAbsorbed = TRUE; } else // if no index is a prefix of the other and the two do not produce // same output, pick one with high selectivity. if ( !isASuperOrSubsetIndex && !produceSameIndexOutputs ) { // two indexes do not produce the same outputs. Select // one with the most selectivity. CostScalar rowsToScan; CostScalar currentDataAccess = computeCpuResourceForIndexJoin(tableId, idesc, newIndexPredicates, rowsToScan); if ( rowsToScan > indexEliminationThreshold ) break; CostScalar previousDataAccess = computeCpuResourceForIndexJoin(tableId, ixi->usableIndexes_[0]->getIndexDesc(), ixi->indexPredicates_, rowsToScan); if ( currentDataAccess < previousDataAccess ) { if ( printIndexElimination ) out << "Eliminate index join heuristics 2: remove " << ixi->usableIndexes_[0]->getIndexDesc()->getExtIndexName().data() << endl; ixi = new (CmpCommon::statementHeap()) ScanIndexInfo(referencedInputs, newOutputsFromIndex, newIndexPredicates, indexJoinPreds, newOutputsFromRightScan, idesc->getIndexKey(), ixProp); possibleIndexJoins_[i] = ixi; } else { // do nothing. The current index is less useful. if ( printIndexElimination ) out << "Eliminate index join heuristics 2: remove " << idesc->getExtIndexName().data() << endl; } idescAbsorbed = TRUE; } else { // must be produceSameIndexOutputs when reach here. CMPASSERT(produceSameIndexOutputs); // Another index produces the same characteristic // outputs. Combine the two indexes in a single // scan. Add this index to the list of indexes, // everything else should be set already if ( possibleIndexJoins_[i]->indexPredicates_ == newIndexPredicates && ixProp->compareIndexPromise(ixi->usableIndexes_[0]) == MORE ) { if ( printIndexElimination ) out << "Eliminate index join heuristics 0: remove " << ixi->usableIndexes_[0]->getIndexDesc()->getExtIndexName().data() << endl; ixi = new (CmpCommon::statementHeap()) ScanIndexInfo(referencedInputs, newOutputsFromIndex, newIndexPredicates, indexJoinPreds, newOutputsFromRightScan, idesc->getIndexKey(), ixProp); possibleIndexJoins_[i] = ixi; idescAbsorbed = TRUE; } } break; } } } if (!idescAbsorbed) { // create a new index info struct and add this into the // possible index joins list IndexJoinSelectivityEnum isGoodIndexJoin = INDEX_JOIN_VIABLE; MdamFlags mdamFlag = idesc->pruneMdam(newIndexPredicates,FALSE, isGoodIndexJoin, getGroupAttr(),&referencedInputs); IndexProperty * ixProp = (getGroupAttr()->getInputLogPropList().entries() >0) ? new(CmpCommon::statementHeap()) IndexProperty(idesc, mdamFlag, isGoodIndexJoin, (getGroupAttr()->getInputLogPropList())[0]) : new(CmpCommon::statementHeap()) IndexProperty(idesc, mdamFlag, isGoodIndexJoin); ScanIndexInfo *ixi = new (CmpCommon::statementHeap()) ScanIndexInfo(referencedInputs, newOutputsFromIndex, newIndexPredicates, indexJoinPreds, newOutputsFromRightScan, idesc->getIndexKey(), ixProp); possibleIndexJoins_.insert(ixi); } // !idescAbsorbed } // index delivers new values } // not indexOnly access } // for each index if ( printIndexElimination ) { out << "# of index join scans=" << possibleIndexJoins_.entries() << endl; out << "# of index only scans=" << indexOnlyIndexes_.entries() << endl; out << "==================" << endl; } CMPASSERT(indexOnlyIndexes_.entries() > 0); } // Scan::addIndexInfo void Scan::setTableAttributes(CANodeId nodeId) { NodeAnalysis * nodeAnalysis = nodeId.getNodeAnalysis(); if (nodeAnalysis == NULL) return; TableAnalysis * tableAnalysis = nodeAnalysis->getTableAnalysis(); if (tableAnalysis == NULL) return; TableDesc * tableDesc = tableAnalysis->getTableDesc(); const CorrName& name = tableDesc->getNATable()->getTableName(); setTableName((CorrName &)name); setTableDesc(tableDesc); setBaseCardinality(MIN_ONE (tableDesc->getNATable()->getEstRowCount())) ; } NABoolean Scan::equalityPredOnCol(ItemExpr *col) { // // Returns TRUE if the column (col) has an equality predicate // associated with it the scan's predicate list. // ValueIdSet pred = getSelectionPredicates(); for (ValueId vid=pred.init(); pred.next(vid); pred.advance(vid)) { if ( vid.getItemExpr()->getOperatorType() != ITM_VEG_PREDICATE ) continue; ItemExpr *expr = vid.getItemExpr(); ValueId id; VEG *veg = ((VEGPredicate*)expr)->getVEG(); if (veg->getAllValues().referencesTheGivenValue(col->getValueId(), id)) return TRUE; } return FALSE; } // Scan::equalityPredOnCol NABoolean Scan::updateableIndex(IndexDesc *idx) { // // Returns TRUE if the index (idx) can be used for a scan during an UPDATE. // Otherwise, returns FALSE to prevent the "Halloween Update Problem". // ValueIdSet pred = getSelectionPredicates(), dummySet; SearchKey searchKey(idx->getIndexKey(), idx->getOrderOfKeyValues(), getGroupAttr()->getCharacteristicInputs(), TRUE, pred, dummySet, // needed by the interface but not used here idx ); // Unique index is OK to use. if (searchKey.isUnique()) return TRUE; const ValueIdList colUpdated = getTableDesc()->getColUpdated(); const ValueIdList indexKey = idx->getIndexKey(); // Determine if the columns being updated are key columns. Each key // column being updated must have an associated equality clause in // the WHERE clause of the UPDATE for it to be used. for (CollIndex i = 0; i < colUpdated.entries(); i++) { ItemExpr *updateCol = colUpdated[i].getItemExpr(); CMPASSERT(updateCol->getOperatorType() == ITM_BASECOLUMN); for (CollIndex j = 0; j < indexKey.entries(); j++) { ItemExpr *keyCol = indexKey[j].getItemExpr(); ItemExpr *baseCol = ((IndexColumn*)keyCol)->getDefinition().getItemExpr(); CMPASSERT(baseCol->getOperatorType() == ITM_BASECOLUMN); // QSTUFF if (getGroupAttr()->isEmbeddedUpdate()){ if (((BaseColumn*)updateCol)->getColNumber() == ((BaseColumn*)baseCol)->getColNumber()) return FALSE; } // QSTUFF if ((NOT(idx->isUniqueIndex() || idx->isClusteringIndex())) || (CmpCommon::getDefault(UPDATE_CLUSTERING_OR_UNIQUE_INDEX_KEY) == DF_OFF)) { if (((BaseColumn*)updateCol)->getColNumber() == ((BaseColumn*)baseCol)->getColNumber() AND NOT equalityPredOnCol(baseCol)) return FALSE; } } } return TRUE; } // Scan::updateableIndex // how many index descriptors can be used with this scan node? CollIndex Scan::numUsableIndexes() { // start with the index-only indexes CollIndex result = indexOnlyIndexes_.entries(); // for each index join, count all the indexes that result in equivalent // characteristics inputs and outputs for (CollIndex i=0; i < possibleIndexJoins_.entries(); i++) result += possibleIndexJoins_[i]->usableIndexes_.entries(); return result; } // this method works like an operator[], with values for indexNum // between 0 and numUsableIndexes()-1. It returns the associated IndexDesc // and - depending on whether it is an index-only scan or an index join - // the appropriate information class (optional). IndexDesc * Scan::getUsableIndex(CollIndex indexNum, IndexProperty **indexOnlyInfo, ScanIndexInfo **indexJoinInfo) { IndexDesc *result = NULL; IndexProperty *locIndexOnlyInfo = NULL; ScanIndexInfo *locIndexJoinInfo = NULL; if (indexNum < indexOnlyIndexes_.entries()) { // indexNum corresponds to an index-only scan locIndexOnlyInfo = indexOnlyIndexes_[indexNum]; result = locIndexOnlyInfo->getIndexDesc(); } else { // search for index desc "indexNum" in the index joins // (which is a list of sets of index descs, making this // method somewhat complex) indexNum -= indexOnlyIndexes_.entries(); CollIndex ixJoinIx = 0; CollIndex numIndexJoins = possibleIndexJoins_.entries(); if (numIndexJoins > 0) { // loop over the list of index joins, counting index descs until // we find the right index join while (ixJoinIx < numIndexJoins) { ScanIndexInfo *si = possibleIndexJoins_[ixJoinIx]; if (indexNum >= si->usableIndexes_.entries()) { // not there yet, go on to the next index join indexNum -= si->usableIndexes_.entries(); ixJoinIx++; } else { // now we have reached the right index join (if // any), select an index locIndexJoinInfo = si; result = si->usableIndexes_[indexNum]->getIndexDesc(); break; } } } } // return information or NULL for not found if (indexOnlyInfo) *indexOnlyInfo = locIndexOnlyInfo; if (indexJoinInfo) *indexJoinInfo = locIndexJoinInfo; return result; } void Scan::getRequiredVerticalPartitions (SET(IndexDesc *) & requiredVPs, SET(ValueIdSet *) & columnsProvidedByVP) const { // We get requiredVPs and columnsProvidedByVP passed to us that have // no entries. We have to populate them with the vertical partitions // required to service the query and the columns that each of those // VPs will provide. Each entry in columnsProvidedByVP is related to // the corresponding entry in requiredVPs CMPASSERT(requiredVPs.entries() == 0 && columnsProvidedByVP.entries() == 0); const TableDesc * tableDesc = getTableDesc(); const LIST(IndexDesc *) & allVPs = tableDesc->getVerticalPartitions(); #ifdef OLD // Get all the value ids that are required by the scan and its parents ValueIdSet requiredValueIds(getGroupAttr()->getCharacteristicOutputs()); // VEGPreds can have two forms, an A IS NOT NULL form and an A=B form // when expanded in the generator. If an index does not provide a // VEG member that the base table provides, a VEGPredicate could be // covered by the index in its IS NOT NULL form (checking a char. input // whether it is not null). To avoid this bug, add all the base cols // that contribute to VEGPredicates as explicitly required values. addBaseColsFromVEGPreds(requiredValueIds); // selection predicates are also required, add them to requiredValueIds requiredValueIds += getSelectionPred(); // Remove any VEGPreds from required Values ValueIdSet VEGEqPreds; getSelectionPred().lookForVEGPredicates(VEGEqPreds); requiredValueIds -= VEGEqPreds; // The following code gets all the leaf node value ids. It deletes the // characteristic input list of value ids from the leaf value ids. It // does this since predicates are not pushed down to the VPs and the VPs // only provide outputs and do not take any inputs. It reassigns the // remaining leaf value ids as those actually required from the VPs. // This code e.g. will only keep the b from a predicate such as b > 3 // and the c from an expression c + 1 in the select list. ValueIdSet leafValues, emptySet; GroupAttributes emptyGA; requiredValueIds.getLeafValuesForCoverTest(leafValues, emptyGA, emptySet); leafValues -= getGroupAttr()->getCharacteristicInputs(); requiredValueIds = leafValues; #endif // ----------------------------------------------------------------- // Accumulate the ValueIds of all VEGPredicates. // ----------------------------------------------------------------- ValueIdSet VEGEqPreds; getSelectionPred().lookForVEGPredicates(VEGEqPreds); // ----------------------------------------------------------------- // Compute the set of expressions that will be evaluated on the // parent. Add a VEGReference for every VEGPredicate in this set. // ----------------------------------------------------------------- // remaining expressions on parent ValueIdSet requiredValueIdsMembers; RelExpr::computeValuesReqdForPredicates(VEGEqPreds, requiredValueIdsMembers); ValueIdSet requiredValueIds; requiredValueIds.replaceVEGExpressionsAndCopy(requiredValueIdsMembers); // --------------------------------------------------------------------- // Examine the set of values required by the parent (VPJoin node). // Replace each VEGPredicate with a VEGReferences for its VEG; if its // VEG contains other VEGReferences, add them to requiredValueIds. // --------------------------------------------------------------------- RelExpr::computeValuesReqdForPredicates(getGroupAttr()->getCharacteristicOutputs(), requiredValueIds); requiredValueIds += getSelectionPred(); requiredValueIds -= VEGEqPreds; // delete all VEGPredicates // The following code gets all the leaf node value ids. It deletes the // characteristic input list of value ids from the leaf value ids. It // does this since predicates are not pushed down to the VPs and the VPs // only provide outputs and do not take any inputs. It reassigns the // remaining leaf value ids as those actually required from the VPs. // This code e.g. will only keep the b from a predicate such as b > 3 // and the c from an expression c + 1 in the select list. ValueIdSet leafValues, emptySet; GroupAttributes emptyGA; requiredValueIds.getLeafValuesForCoverTest(leafValues, emptyGA, emptySet); leafValues -= getGroupAttr()->getCharacteristicInputs(); requiredValueIds = leafValues; // Remove all basecolumns (logical columns) // for(ValueId expr = requiredValueIds.init(); requiredValueIds.next(expr); requiredValueIds.advance(expr)) { ItemExpr *ie = expr.getItemExpr(); if(ie->getOperatorType() == ITM_BASECOLUMN) requiredValueIds -= expr; } // the values that are covered by every vertical partition (such as // clustering key) ValueIdSet alwaysCovered; // a list of VEGReferences to the clustering key column(s) ValueIdSet clusteringKeyColumns; // some helper variables ValueIdList clusteringKeyColList; GroupAttributes alwaysCoveredGA; ValueIdSet dummyReferencedInputs; ValueIdSet dummyUnCoveredExpr; // --------------------------------------------------------------------- // find out the subset of values that are always covered // --------------------------------------------------------------------- // get the clustering key columns and transform them into VEGies tableDesc->getEquivVEGCols(tableDesc->getClusteringIndex()->getIndexKey(), clusteringKeyColList); clusteringKeyColumns = clusteringKeyColList; // make group attributes that get the original scan node's char. // inputs and the clustering key columns as outputs (every VP // should have the clustering key), to represent the least common // denominator of all VP attributes alwaysCoveredGA.addCharacteristicOutputs(clusteringKeyColumns); requiredValueIds.isCovered( getGroupAttr()->getCharacteristicInputs(), alwaysCoveredGA, dummyReferencedInputs, alwaysCovered, dummyUnCoveredExpr); // alwaysCovered now contains a set of values that should be covered // by every vertical partition ValueIdSet remainingValueIds = requiredValueIds; // --------------------------------------------------------------------- // For each vertical partition, check whether it provides any useful // values // --------------------------------------------------------------------- for (CollIndex indexNo = 0; indexNo < allVPs.entries(); indexNo++) { IndexDesc *idesc = allVPs[indexNo]; ValueIdSet indexColumns(idesc->getIndexColumns()); ValueIdSet *coveredSubexpr = new (CmpCommon::statementHeap()) ValueIdSet(); ValueIdSet noCharacteristicInputs; GroupAttributes vpGroupAttributes; NABoolean onlyOneVPRequired; // make group attributes for a vertical partition scan vpGroupAttributes.addCharacteristicOutputs(idesc->getIndexColumns()); // does the index cover all required values, and if not, which // ones does it cover onlyOneVPRequired = requiredValueIds.isCovered(noCharacteristicInputs, vpGroupAttributes, dummyReferencedInputs, *coveredSubexpr, dummyUnCoveredExpr); if (onlyOneVPRequired) { // This vertical partition supplies all the required values. // That means we have all the required vertical partitions // and we are done. In fact, if we had selected other VPs // before we need to clear them out along with the columns // they provide. // There should not be any selection predicates in this list // since they should have been eliminated from // requiredValueIdsby the leaf value id code earlier. requiredVPs.clear(); columnsProvidedByVP.clear(); requiredVPs.insert(idesc); columnsProvidedByVP.insert(coveredSubexpr); return; } else { if(remainingValueIds.entries() > 0) { coveredSubexpr->clear(); requiredValueIds.isCovered(noCharacteristicInputs, vpGroupAttributes, dummyReferencedInputs, *coveredSubexpr, dummyUnCoveredExpr); // This vertical partition does not provide all required values. // Normally we wouldn't expect it to. But does it provide a // column value other than the clustering key? If it does, it's in! // We should take out the selection predicates since we will // not be evaluating any predicates in the VP scan. if ( (*coveredSubexpr != alwaysCovered) && ((*coveredSubexpr).entries() > 0) ) { requiredVPs.insert(idesc); *coveredSubexpr -= getSelectionPred(); columnsProvidedByVP.insert(coveredSubexpr); } // VP delivers column values remainingValueIds -= *coveredSubexpr; } } // not onlyOneVPRequired } // for each VP return; } // Scan::getRequiredVerticalPartitions void Scan::addBaseColsFromVEGPreds(ValueIdSet &vs) const { // get all the base columns of the table (no VEGies) ValueIdSet baseCols(tabId_->getColumnList()); for (ValueId x = getSelectionPred().init(); getSelectionPred().next(x); getSelectionPred().advance(x)) { ItemExpr *ie = x.getItemExpr(); if (ie->getOperatorType() == ITM_VEG_PREDICATE) { // get the VEG members ValueIdSet vegMembers( ((VEGPredicate *)ie)->getVEG()->getAllValues()); // filter out the base columns of this table that are VEG members // and add them to the output parameter vegMembers.intersectSet(baseCols); vs += vegMembers; } } } void Scan::addLocalExpr(LIST(ExprNode *) &xlist, LIST(NAString) &llist) const { RelExpr::addLocalExpr(xlist,llist); } NABoolean Scan::reconcileGroupAttr(GroupAttributes *newGroupAttr) { addIndexInfo(); const SET(IndexDesc *) & indexOnlyScans = deriveIndexOnlyIndexDesc(); const SET(IndexDesc *) & indexJoinScans = deriveIndexJoinIndexDesc(); // we add the available indexes on this scan node to the // new GroupAttrs availableBtreeIndexes newGroupAttr->addToAvailableBtreeIndexes(indexOnlyScans); newGroupAttr->addToAvailableBtreeIndexes(indexJoinScans); // This one is not actually necessary getGroupAttr()->addToAvailableBtreeIndexes(indexOnlyScans); getGroupAttr()->addToAvailableBtreeIndexes(indexJoinScans); // Now as usual return RelExpr::reconcileGroupAttr(newGroupAttr); } // -------------------------------------------------------------------- // 10-040128-2749 -begin // This will compute based on the context,Current Control table setting // and defaults. // Input : Context // -------------------------------------------------------------------- NABoolean Scan::isMdamEnabled(const Context *context) { NABoolean mdamIsEnabled = TRUE; // ----------------------------------------------------------------------- // Check the status of the enabled/disabled flag in // the defaults: // ----------------------------------------------------------------------- if (CmpCommon::getDefault(MDAM_SCAN_METHOD) == DF_OFF) mdamIsEnabled = FALSE; // ----------------------------------------------------------------------- // Mdam can also be disabled for a particular scan via Control // Query Shape. The information is passed by the context. // ----------------------------------------------------------------------- if (mdamIsEnabled) { const ReqdPhysicalProperty* propertyPtr = context->getReqdPhysicalProperty(); if ( propertyPtr && propertyPtr->getMustMatch() && (propertyPtr->getMustMatch()->getOperatorType() == REL_FORCE_ANY_SCAN)) { ScanForceWildCard* scanForcePtr = (ScanForceWildCard*)propertyPtr->getMustMatch(); if (scanForcePtr->getMdamStatus() == ScanForceWildCard::MDAM_OFF) mdamIsEnabled = FALSE; } } // ----------------------------------------------------------------------- // Mdam can also be disabled for a particular table via a Control // Table command. // ----------------------------------------------------------------------- if (mdamIsEnabled) { const NAString * val = ActiveControlDB()->getControlTableValue(getTableName().getUgivenName(), "MDAM"); if ((val) && (*val == "OFF")) // CT in effect { mdamIsEnabled = FALSE; } } return mdamIsEnabled; } // 10-040128-2749 -end // ----------------------------------------------------------------------- // methods for class ScanIndexInfo // ----------------------------------------------------------------------- ScanIndexInfo::ScanIndexInfo(const ScanIndexInfo & other) : outputsFromIndex_ (other.outputsFromIndex_), indexPredicates_ (other.indexPredicates_), joinPredicates_ (other.joinPredicates_), outputsFromRightScan_ (other.outputsFromRightScan_), transformationDone_ (other.transformationDone_), indexColumns_ (other.indexColumns_), usableIndexes_ (other.usableIndexes_) {} ScanIndexInfo::ScanIndexInfo( const ValueIdSet& inputsToIndex, const ValueIdSet& outputsFromIndex, const ValueIdSet& indexPredicates, const ValueIdSet& joinPredicates, const ValueIdSet& outputsFromRightScan, const ValueIdSet& indexColumns, IndexProperty* ixProp ) : inputsToIndex_(inputsToIndex), outputsFromIndex_(outputsFromIndex), indexPredicates_(indexPredicates), joinPredicates_(joinPredicates), outputsFromRightScan_(outputsFromRightScan), indexColumns_(indexColumns), transformationDone_(FALSE), usableIndexes_(CmpCommon::statementHeap()) { usableIndexes_.insert(ixProp); } // ----------------------------------------------------------------------- // methods for class FileScan // ----------------------------------------------------------------------- FileScan::FileScan(const CorrName& tableName, TableDesc * tableDescPtr, const IndexDesc *indexDescPtr, const NABoolean isReverseScan, const Cardinality& baseCardinality, StmtLevelAccessOptions& accessOpts, GroupAttributes * groupAttributesPtr, const ValueIdSet& selectionPredicates, const Disjuncts& disjuncts, const ValueIdSet& generatedCCPreds, OperatorTypeEnum otype) : Scan (tableName, tableDescPtr, otype), indexDesc_(indexDescPtr), reverseScan_(isReverseScan), executorPredTree_(NULL), mdamKeyPtr_(NULL), disjunctsPtr_(&disjuncts), pathKeys_(NULL), partKeys_(NULL), hiveSearchKey_(NULL), estRowsAccessed_ (0), mdamFlag_(UNDECIDED), skipRowsToPreventHalloween_(FALSE), doUseSearchKey_(TRUE) { // Set the filescan properties: // Set the base cardinality to that for the logical scan setBaseCardinality(baseCardinality); // move the statement level access options accessOptions() = accessOpts; // the top node keeps the original group attributes setGroupAttr(groupAttributesPtr); // Initialize selection predicates: // (they are needed to set the executor predicates later in // pre-code gen) selectionPred().insert(selectionPredicates); // Get the predicates on the partitioning key: if (getIndexDesc() && getIndexDesc()->isPartitioned()) { ValueIdSet externalInputs = getGroupAttr()->getCharacteristicInputs(); ValueIdSet dummySet; ValueIdSet selPreds(selectionPredicates); // Create and set the Searchkey for the partitioning key: partKeys_ = new (CmpCommon::statementHeap()) SearchKey(indexDesc_->getPartitioningKey(), indexDesc_->getOrderOfPartitioningKeyValues(), externalInputs, NOT getReverseScan(), selPreds, disjuncts, dummySet, // needed by interface but not used here indexDesc_ ); } setComputedPredicates(generatedCCPreds); } // FileScan() void FileScan::getPotentialOutputValues(ValueIdSet & outputValues) const { outputValues.clear(); // // Assign the set of columns that belong to the index to be scanned // as the output values that can be produced by this scan. // outputValues.insertList( getIndexDesc()->getIndexColumns() ); // MV -- // Add the CurrentEpoch column as well. outputValues.insert(getExtraOutputColumns()); } // FileScan::getPotentialOutputValues() NABoolean FileScan::patternMatch(const RelExpr & other) const { // handle the special case of a pattern to force a // specific table or index if (other.getOperatorType() == REL_FORCE_ANY_SCAN) { ScanForceWildCard &w = (ScanForceWildCard &) other; if (w.getExposedName() != "") { QualifiedName wName(w.getExposedName(), 1 /* minimal 1 part name */); if (getTableName().getCorrNameAsString() != "") { // query uses a correlation name, compare that with the wildcard // as a string if (wName.getQualifiedNameAsAnsiString() != ToAnsiIdentifier(getTableName().getCorrNameAsString())) return FALSE; } else { // no correlation name used in the query, compare catalog, schema // and table parts separately, if they exist in the wildcard const NAString& catName = wName.getCatalogName(); const NAString& schName = wName.getSchemaName(); const QualifiedName& x = getTableName(). getExtendedQualNameObj().getQualifiedNameObj(); if ((catName.length() > 0 && x.getCatalogName() != catName) || (schName.length() > 0 && x.getSchemaName() != schName) || x.getObjectName() != wName.getObjectName()) return FALSE; } } // if an index name was specified in the wildcard, check for it if (w.getIndexName() != "") { NAString forcedIndexName(w.getIndexName(), CmpCommon::statementHeap()); // The user can specify the index to be the base table in the // Control Query Shape statement by using the table name (object // name or correlation) as the index name. Ex: scan('t1','t1',..) // since t1 might be a correlation name, its necessary to check // for the corresponding object name and not the table correlation // name when searching for the index match. if (forcedIndexName == w.getExposedName()) forcedIndexName = ToAnsiIdentifier( getTableName().getQualifiedNameObj().getObjectName() ); // get the three-part name of the index const NAString &ixName = indexDesc_->getNAFileSet()->getExtFileSetName(); // Declare a match if either the index name in w is equal to // indexName or if it is equal to the last part of indexName. //if (w.getIndexName() != ixName) if (forcedIndexName != ixName) { QualifiedName ixNameQ(ixName, 1); if ( ToAnsiIdentifier(ixNameQ.getObjectName()) != forcedIndexName ) return FALSE; } } return TRUE; } else return RelExpr::patternMatch(other); } NABoolean FileScan::duplicateMatch(const RelExpr & other) const { if (!Scan::duplicateMatch(other)) return FALSE; FileScan &o = (FileScan &) other; if (//beginKeyPred_ != o.beginKeyPred_ OR //endKeyPred_ != o.endKeyPred_ OR retrievedCols_ != o.retrievedCols_ OR getExecutorPredicates() != o.getExecutorPredicates()) return FALSE; return TRUE; } RelExpr * FileScan::copyTopNode(RelExpr *derivedNode, CollHeap* outHeap) { // $$$ Function needs to be updated with new fields // added to the filescan. // If you need to use this function please update it // with those new fields (i.e. SearchKey *, etc's) // then remove the following abort // CMPABORT; FileScan *result; if (derivedNode == NULL) result = new(outHeap) FileScan(getTableName(), getTableDesc(), getIndexDesc(), REL_FILE_SCAN, outHeap); else result = (FileScan *) derivedNode; result->setBaseCardinality(getBaseCardinality()); result->setEstRowsAccessed(getEstRowsAccessed()); result->beginKeyPred_ = beginKeyPred_; result->endKeyPred_ = endKeyPred_; result->setExecutorPredicates(getExecutorPredicates()); result->retrievedCols_ = retrievedCols_; return Scan::copyTopNode(result, outHeap); } NABoolean FileScan::isLogical() const { return FALSE; } NABoolean FileScan::isPhysical() const { return TRUE; } PlanPriority FileScan::computeOperatorPriority (const Context* context, PlanWorkSpace *pws, Lng32 planNumber) { PlanPriority result; // --------------------------------------------------------------------- // If under interactive_access mode, then give preference to plans that // avoid full table scans // Similarly if under firstN optimization mode then give preference to // plans that avoid full table scans // --------------------------------------------------------------------- NABoolean interactiveAccess = (CmpCommon::getDefault(INTERACTIVE_ACCESS) == DF_ON) OR ( QueryAnalysis::Instance() AND QueryAnalysis::Instance()->optimizeForFirstNRows()); if (interactiveAccess) { if(getMdamKeyPtr()) { // We have MDAM. Give this a preference result.incrementLevels(INTERACTIVE_ACCESS_MDAM_PRIORITY,0); } else if(getSearchKeyPtr() AND getSearchKeyPtr()->getKeyPredicates().entries()) { // We have direct index access. Give this a preference result.incrementLevels(INTERACTIVE_ACCESS_PRIORITY,0); } } if (isRecommendedByHints()) result.incrementLevels(INDEX_HINT_PRIORITY,0); return result; } // currently only used by MV query rewrite PlanPriority PhysicalMapValueIds::computeOperatorPriority (const Context* context, PlanWorkSpace *pws, Lng32 planNumber) { PlanPriority result; // is this MVI wraps one of the favorite MVs // (included in the MVQR_REWRITE_CANDIDATES default) if (includesFavoriteMV()) { result.incrementLevels(MVQR_FAVORITE_PRIORITY,0); } return result; } // Is this fileScan recommended by the user via the optimizer hints? NABoolean FileScan::isRecommendedByHints() { return getIndexDesc()->isHintIndex(); } const NAString FileScan::getText() const { // --------------------------------------------------------------------- // returns: // // file scan t c for a primary index scan on table // t with correlation name c // index scan ix(t c) for an index scan on index ix of // table t // rev. index scan ix(t c) if the scan goes backwards // --------------------------------------------------------------------- NAString op(CmpCommon::statementHeap()); NAString tname(getTableName().getText(),CmpCommon::statementHeap()); if (isSampleScan() == TRUE) op = "sample_"; if (indexDesc_ == NULL OR indexDesc_->isClusteringIndex()) { if (isHiveTable()) op += "hive_scan "; else op += "file_scan "; } else { op += "index_scan "; tname = indexDesc_->getIndexName().getQualifiedNameAsString() + "(" + tname + ")"; } if (reverseScan_) op += NAString("rev "); return op + tname; } const NAString FileScan::getTypeText() const { NAString descr(CmpCommon::statementHeap()); NAString tname(getTableName().getText(),CmpCommon::statementHeap()); if (isSampleScan() == TRUE) descr = "sample "; if (reverseScan_) descr += NAString("reverse "); if (isFullScanPresent() && !getMdamKeyPtr()) { descr += "full scan "; if (getMdamKeyPtr()) descr += "limited by mdam "; } else { descr += "subset scan "; if (getMdamKeyPtr()) descr += "limited by mdam "; } descr += "of "; if (indexDesc_ == NULL OR indexDesc_->isClusteringIndex()) descr += "table "; else { descr += "index "; tname = indexDesc_->getIndexName().getQualifiedNameAsString() + "(" + tname + ")"; } descr += tname; return descr; } #pragma nowarn(262) // warning elimination void FileScan::addLocalExpr(LIST(ExprNode *) &xlist, LIST(NAString) &llist) const { if (getIndexDesc() != NULL) { const ValueIdList& keyColumns = getIndexDesc()->getIndexKey(); xlist.insert(keyColumns.rebuildExprTree()); llist.insert("key_columns"); } if (executorPredTree_ != NULL OR NOT getExecutorPredicates().isEmpty()) { if (getExecutorPredicates().isEmpty()) xlist.insert(executorPredTree_); else xlist.insert(getExecutorPredicates().rebuildExprTree()); llist.insert("executor_predicates"); } // ----------------------------------------------------------------------- // Display key information // ----------------------------------------------------------------------- if (getMdamKeyPtr() != NULL) { // Mdam access! const CollIndex columns = getIndexDesc()->getIndexKey().entries(); const CollIndex disjEntries = getMdamKeyPtr()->getKeyDisjunctEntries(); // If we are in the optimizer, obtain key preds from // the disjuncts, // else obtain them from the column order list array: if (NOT nodeIsPreCodeGenned()) { // We are in the optimizer... // For every disjunct for (CollIndex i=0; i < disjEntries; i++) { ColumnOrderList kpbc(getIndexDesc()->getIndexKey()); getMdamKeyPtr()->getKeyPredicatesByColumn(kpbc,i); // gather the key predicates: ValueIdSet keyPreds; for (CollIndex j=0; j < columns; j++) { if (kpbc[j]) { keyPreds.insert(*(kpbc[j])); } } // display this disjunct key preds. into the GUI: xlist.insert(keyPreds.rebuildExprTree()); llist.insert("mdam_disjunct"); } // for every disjunct } else { // we are after the generator... const ColumnOrderListPtrArray &columnOrderListPtrArray = getMdamKeyPtr()->getColumnOrderListPtrArray(); // we are in the generator, obtain the key preds // from thr column order list: ValueIdSet *predsPtr = NULL; for (CollIndex n = 0; n < columnOrderListPtrArray.entries(); n++) { // get the list of key predicates associated with the n disjunct: const ColumnOrderList &columnOrderList = *columnOrderListPtrArray[n]; // get predicates for column order i: // gather the key predicates: ValueIdSet keyPreds; const ValueIdSet *predsPtr = NULL; for (CollIndex i = 0; i < columnOrderList.entries(); i++) { predsPtr = columnOrderList[i]; if (predsPtr) { keyPreds.insert(*predsPtr); } } // display this disjunct key preds. into the GUI: xlist.insert(keyPreds.rebuildExprTree()); llist.insert("mdam_disjunct"); } } // mdam after the generator } // mdam access else if (getSearchKeyPtr() != NULL) // Is Single subset access? { // yes! // display preds from search key only if begin/end keys are // not generated yet (e.g. during optimization) if (getBeginKeyPred().isEmpty() AND getEndKeyPred().isEmpty() AND pathKeys_ AND NOT pathKeys_->getKeyPredicates().isEmpty()) { xlist.insert(pathKeys_->getKeyPredicates().rebuildExprTree()); if (pathKeys_ == partKeys_) llist.insert("key_and_part_key_preds"); else llist.insert("key_predicates"); } } // display part key preds only if different from clustering key preds if (partKeys_ AND pathKeys_ != partKeys_ AND NOT partKeys_->getKeyPredicates().isEmpty()) { xlist.insert(partKeys_->getKeyPredicates().rebuildExprTree()); llist.insert("part_key_predicates"); } if (NOT getBeginKeyPred().isEmpty()) { xlist.insert(getBeginKeyPred().rebuildExprTree()); llist.insert("begin_key"); } if (NOT getEndKeyPred().isEmpty()) { xlist.insert(getEndKeyPred().rebuildExprTree()); llist.insert("end_key"); } // xlist.insert(retrievedCols_.rebuildExprTree(ITM_ITEM_LIST)); // llist.insert("retrieved_cols"); RelExpr::addLocalExpr(xlist,llist); } #pragma warn(262) // warning elimination const Disjuncts& FileScan::getDisjuncts() const { CMPASSERT(disjunctsPtr_ != NULL); return *disjunctsPtr_; } // ----------------------------------------------------------------------- // methods for class HbaseAccess // ----------------------------------------------------------------------- HbaseAccess::HbaseAccess(CorrName &corrName, OperatorTypeEnum otype, CollHeap *oHeap) : FileScan(corrName, NULL, NULL, otype, oHeap), listOfSearchKeys_(oHeap) { accessType_ = SELECT_; uniqueHbaseOper_ = FALSE; uniqueRowsetHbaseOper_ = FALSE; } HbaseAccess::HbaseAccess(CorrName &corrName, TableDesc *tableDesc, IndexDesc *idx, const NABoolean isReverseScan, const Cardinality& baseCardinality, StmtLevelAccessOptions& accessOptions, GroupAttributes * groupAttributesPtr, const ValueIdSet& selectionPredicates, const Disjuncts& disjuncts, const ValueIdSet& generatedCCPreds, OperatorTypeEnum otype, CollHeap *oHeap) : FileScan(corrName, tableDesc, idx, isReverseScan, baseCardinality, accessOptions, groupAttributesPtr, selectionPredicates, disjuncts, generatedCCPreds, otype), listOfSearchKeys_(oHeap), snpType_(SNP_NONE) { accessType_ = SELECT_; //setTableDesc(tableDesc); uniqueHbaseOper_ = FALSE; uniqueRowsetHbaseOper_ = FALSE; } HbaseAccess::HbaseAccess(CorrName &corrName, NABoolean isRW, NABoolean isCW, CollHeap *oHeap) : FileScan(corrName, NULL, NULL, REL_HBASE_ACCESS, oHeap), isRW_(isRW), isCW_(isCW), listOfSearchKeys_(oHeap), snpType_(SNP_NONE) { accessType_ = SELECT_; uniqueHbaseOper_ = FALSE; uniqueRowsetHbaseOper_ = FALSE; } HbaseAccess::HbaseAccess( OperatorTypeEnum otype, CollHeap *oHeap) : FileScan(CorrName(), NULL, NULL, otype, oHeap), listOfSearchKeys_(oHeap), snpType_(SNP_NONE) { accessType_ = SELECT_; uniqueHbaseOper_ = FALSE; uniqueRowsetHbaseOper_ = FALSE; } //! HbaseAccess::~HbaseAccess Destructor HbaseAccess::~HbaseAccess() { } //! HbaseAccess::copyTopNode method RelExpr * HbaseAccess::copyTopNode(RelExpr *derivedNode, CollHeap* outHeap) { HbaseAccess *result; if (derivedNode == NULL) result = new (outHeap) HbaseAccess(REL_HBASE_ACCESS, outHeap); else result = (HbaseAccess *) derivedNode; //result->corrName_ = corrName_; result->accessType_ = accessType_; result->isRW_ = isRW_; result->isCW_ = isCW_; result->setTableDesc(getTableDesc()); result->setIndexDesc(getIndexDesc()); //result->setTableDesc(getTableDesc()); result->listOfSearchKeys_ = listOfSearchKeys_; result->retColRefSet_ = retColRefSet_; result->uniqueHbaseOper_ = uniqueHbaseOper_; result->uniqueRowsetHbaseOper_ = uniqueRowsetHbaseOper_; return Scan::copyTopNode(result, outHeap); // return BuiltinTableValuedFunction::copyTopNode(result, outHeap); } const NAString HbaseAccess::getText() const { NAString op(CmpCommon::statementHeap()); NAString tname(getTableName().getText(),CmpCommon::statementHeap()); NAString sampleOpt(CmpCommon::statementHeap()); if (isSampleScan()) sampleOpt = "sample_"; if (getIndexDesc() == NULL OR getIndexDesc()->isClusteringIndex()) { if (isSeabaseTable()) { if (uniqueRowsetHbaseOper()) (op += "trafodion_vsbb_") += sampleOpt += "scan "; else (op += "trafodion_") += sampleOpt += "scan "; } else (op += "hbase_") += sampleOpt += "scan "; } else { if (isSeabaseTable()) (op += "trafodion_index_") += sampleOpt += "scan "; else (op += "hbase_index_") += sampleOpt += "scan "; tname = getIndexDesc()->getIndexName().getQualifiedNameAsString() + "(" + tname + ")"; } if (getReverseScan()) op += NAString("rev "); return op + tname; } RelExpr *HbaseAccess::bindNode(BindWA *bindWA) { if (nodeIsBound()) { bindWA->getCurrentScope()->setRETDesc(getRETDesc()); return this; } // CorrName &corrName = (CorrName&)getCorrName(); CorrName &corrName = getTableName(); NATable * naTable = NULL; naTable = bindWA->getSchemaDB()->getNATableDB()-> get(&corrName.getExtendedQualNameObj()); if ( !naTable || bindWA->errStatus()) { *CmpCommon::diags() << DgSqlCode(-1388) << DgTableName(corrName.getExposedNameAsAnsiString()); bindWA->setErrStatus(); return this; } // Allocate a TableDesc and attach it to this. // TableDesc * td = bindWA->createTableDesc(naTable, corrName); if (! td || bindWA->errStatus()) return this; setTableDesc(td); setIndexDesc(td->getClusteringIndex()); if (bindWA->errStatus()) return this; RelExpr * re = NULL; // re = BuiltinTableValuedFunction::bindNode(bindWA); re = Scan::bindNode(bindWA); if (bindWA->errStatus()) return this; return re; } void HbaseAccess::getPotentialOutputValues( ValueIdSet & outputValues) const { outputValues.clear(); // since this is a physical operator, it only generates the index columns outputValues.insertList( getIndexDesc()->getIndexColumns() ); outputValues.insertList( getTableDesc()->hbaseTSList() ); outputValues.insertList( getTableDesc()->hbaseVersionList() ); } // HbaseAccess::getPotentialOutputValues() void HbaseAccess::synthEstLogProp(const EstLogPropSharedPtr& inputEstLogProp) { if (getGroupAttr()->isPropSynthesized(inputEstLogProp)) return; // Create a new Output Log Property with cardinality of 10 for now. EstLogPropSharedPtr myEstProps(new (HISTHEAP) EstLogProp(10)); getGroupAttr()->addInputOutputLogProp(inputEstLogProp, myEstProps); } // HbaseAccess::synthEstLogProp void HbaseAccess::synthLogProp(NormWA * normWAPtr) { // Check to see whether this GA has already been associated // with a logExpr for synthesis. If so, no need to resynthesize // for this equivalent log. expression. if (getGroupAttr()->existsLogExprForSynthesis()) return; RelExpr::synthLogProp(normWAPtr); } // HbaseAccess::synthLogProp() // ----------------------------------------------------------------------- // methods for class HBaseAccessCoProcAggr // ----------------------------------------------------------------------- HbaseAccessCoProcAggr::HbaseAccessCoProcAggr(CorrName &corrName, ValueIdSet &aggregateExpr, TableDesc *tableDesc, IndexDesc *idx, const NABoolean isReverseScan, const Cardinality& baseCardinality, StmtLevelAccessOptions& accessOptions, GroupAttributes * groupAttributesPtr, const ValueIdSet& selectionPredicates, const Disjuncts& disjuncts, CollHeap *oHeap) : HbaseAccess(corrName, tableDesc, idx, isReverseScan, baseCardinality, accessOptions, groupAttributesPtr, selectionPredicates, disjuncts, ValueIdSet(), REL_HBASE_COPROC_AGGR), aggregateExpr_(aggregateExpr) { accessType_ = COPROC_AGGR_; } HbaseAccessCoProcAggr::HbaseAccessCoProcAggr(CorrName &corrName, ValueIdSet &aggregateExpr, CollHeap *oHeap) : HbaseAccess(corrName, REL_HBASE_COPROC_AGGR, oHeap), aggregateExpr_(aggregateExpr) { accessType_ = COPROC_AGGR_; } HbaseAccessCoProcAggr::HbaseAccessCoProcAggr( CollHeap *oHeap) : HbaseAccess(REL_HBASE_COPROC_AGGR, oHeap) { accessType_ = SELECT_; uniqueHbaseOper_ = FALSE; uniqueRowsetHbaseOper_ = FALSE; } //! HbaseAccessCoProcAggr::~HbaseAccessCoProcAggr Destructor HbaseAccessCoProcAggr::~HbaseAccessCoProcAggr() { } //! HbaseAccessCoProcAggr::copyTopNode method RelExpr * HbaseAccessCoProcAggr::copyTopNode(RelExpr *derivedNode, CollHeap* outHeap) { HbaseAccessCoProcAggr *result; if (derivedNode == NULL) result = new (outHeap) HbaseAccessCoProcAggr(outHeap); else result = (HbaseAccessCoProcAggr *) derivedNode; result->aggregateExpr_ = aggregateExpr_; return HbaseAccess::copyTopNode(result, outHeap); } const NAString HbaseAccessCoProcAggr::getText() const { NAString op(CmpCommon::statementHeap()); NAString tname(getTableName().getText(),CmpCommon::statementHeap()); op += "hbase_coproc_aggr "; return op + tname; } RelExpr *HbaseAccessCoProcAggr::bindNode(BindWA *bindWA) { if (nodeIsBound()) { bindWA->getCurrentScope()->setRETDesc(getRETDesc()); return this; } RelExpr * re = NULL; re = HbaseAccess::bindNode(bindWA); if (bindWA->errStatus()) return this; return re; } void HbaseAccessCoProcAggr::getPotentialOutputValues( ValueIdSet & outputValues) const { outputValues.clear(); outputValues += aggregateExpr(); } // HbaseAccessCoProcAggr::getPotentialOutputValues() PhysicalProperty* HbaseAccessCoProcAggr::synthPhysicalProperty(const Context* myContext, const Lng32 planNumber, PlanWorkSpace *pws) { //---------------------------------------------------------- // Create a node map with a single, active, wild-card entry. //---------------------------------------------------------- NodeMap* myNodeMap = new(CmpCommon::statementHeap()) NodeMap(CmpCommon::statementHeap(), 1, NodeMapEntry::ACTIVE); //------------------------------------------------------------ // Synthesize a partitioning function with a single partition. //------------------------------------------------------------ PartitioningFunction* myPartFunc = new(CmpCommon::statementHeap()) SinglePartitionPartitioningFunction(myNodeMap); PhysicalProperty * sppForMe = new(CmpCommon::statementHeap()) PhysicalProperty(myPartFunc, EXECUTE_IN_MASTER, SOURCE_VIRTUAL_TABLE); // remove anything that's not covered by the group attributes sppForMe->enforceCoverageByGroupAttributes (getGroupAttr()) ; return sppForMe; } // HbaseAccessCoProcAggr::synthPhysicalProperty() // ----------------------------------------------------------------------- // methods for class HbaseDelete // ----------------------------------------------------------------------- HbaseDelete::HbaseDelete(CorrName &corrName, RelExpr *scan, CollHeap *oHeap) : Delete(corrName, NULL, REL_HBASE_DELETE, scan, NULL, NULL, NULL, oHeap), corrName_(corrName), listOfSearchKeys_(oHeap) { hbaseOper() = TRUE; } HbaseDelete::HbaseDelete(CorrName &corrName, TableDesc *tableDesc, CollHeap *oHeap) : Delete(corrName, tableDesc, REL_HBASE_DELETE, NULL, NULL, NULL, NULL,oHeap), corrName_(corrName), listOfSearchKeys_(oHeap) { hbaseOper() = TRUE; } HbaseDelete::HbaseDelete( CollHeap *oHeap) : Delete(CorrName(""), NULL, REL_HBASE_DELETE, NULL, NULL, NULL, NULL, oHeap), listOfSearchKeys_(oHeap) { hbaseOper() = TRUE; } //! HbaseDelete::~HbaseDelete Destructor HbaseDelete::~HbaseDelete() { } //! HbaseDelete::copyTopNode method RelExpr * HbaseDelete::copyTopNode(RelExpr *derivedNode, CollHeap* outHeap) { HbaseDelete *result; if (derivedNode == NULL) result = new (outHeap) HbaseDelete(corrName_, getTableDesc(), outHeap); else result = (HbaseDelete *) derivedNode; result->corrName_ = corrName_; result->setTableDesc(getTableDesc()); result->listOfSearchKeys_ = listOfSearchKeys_; result->retColRefSet_ = retColRefSet_; return Delete::copyTopNode(result, outHeap); } RelExpr *HbaseDelete::bindNode(BindWA *bindWA) { if (nodeIsBound()) { bindWA->getCurrentScope()->setRETDesc(getRETDesc()); return this; } RelExpr * re = NULL; re = Delete::bindNode(bindWA); if (bindWA->errStatus()) return this; return re; } //! HbaseDelete::getText method const NAString HbaseDelete::getText() const { NABoolean isSeabase = (getTableDesc() && getTableDesc()->getNATable() ? getTableDesc()->getNATable()->isSeabaseTable() : FALSE); NAString text; if (NOT isSeabase) text = "hbase_"; else text = "trafodion_"; if (uniqueRowsetHbaseOper()) text += "vsbb_"; text += "delete"; return text; } Int32 HbaseDelete::getArity() const { return 0; } void HbaseDelete::getPotentialOutputValues( ValueIdSet & outputValues) const { outputValues.clear(); // since this is a physical operator, it only generates the index columns if (getScanIndexDesc()) outputValues.insertList(getScanIndexDesc()->getIndexColumns()); } // HbaseDelete::getPotentialOutputValues() // ----------------------------------------------------------------------- // methods for class HbaseUpdate // ----------------------------------------------------------------------- HbaseUpdate::HbaseUpdate(CorrName &corrName, RelExpr *scan, CollHeap *oHeap) : UpdateCursor(corrName, NULL, REL_HBASE_UPDATE, scan, oHeap), corrName_(corrName), listOfSearchKeys_(oHeap) { hbaseOper() = TRUE; } HbaseUpdate::HbaseUpdate(CorrName &corrName, TableDesc *tableDesc, CollHeap *oHeap) : UpdateCursor(corrName, tableDesc, REL_HBASE_UPDATE, NULL, oHeap), corrName_(corrName), listOfSearchKeys_(oHeap) { hbaseOper() = TRUE; } HbaseUpdate::HbaseUpdate( CollHeap *oHeap) : UpdateCursor(CorrName(""), NULL, REL_HBASE_UPDATE, NULL, oHeap), listOfSearchKeys_(oHeap) { hbaseOper() = TRUE; } //! HbaseUpdate::~HbaseUpdate Destructor HbaseUpdate::~HbaseUpdate() { } //! HbaseUpdate::copyTopNode method RelExpr * HbaseUpdate::copyTopNode(RelExpr *derivedNode, CollHeap* outHeap) { HbaseUpdate *result; if (derivedNode == NULL) result = new (outHeap) HbaseUpdate(corrName_, getTableDesc(), outHeap); else result = (HbaseUpdate *) derivedNode; result->corrName_ = corrName_; result->setTableDesc(getTableDesc()); result->listOfSearchKeys_ = listOfSearchKeys_; result->retColRefSet_ = retColRefSet_; return Update::copyTopNode(result, outHeap); } RelExpr *HbaseUpdate::bindNode(BindWA *bindWA) { if (nodeIsBound()) { bindWA->getCurrentScope()->setRETDesc(getRETDesc()); return this; } RelExpr * re = NULL; re = Update::bindNode(bindWA); if (bindWA->errStatus()) return this; return re; } //! HbaseUpdate::getText method const NAString HbaseUpdate::getText() const { NABoolean isSeabase = (getTableDesc() ? getTableDesc()->getNATable()->isSeabaseTable() : FALSE); NAString text; if (isMerge()) { text = (isSeabase ? "trafodion_merge" : "hbase_merge"); } else { if (NOT isSeabase) text = "hbase_"; else text = "trafodion_"; if (uniqueRowsetHbaseOper()) text += "vsbb_"; text += "update"; } return text; } Int32 HbaseUpdate::getArity() const { return 0; } void HbaseUpdate::getPotentialOutputValues( ValueIdSet & outputValues) const { outputValues.clear(); // Include the index columns from the original Scan, if any if (getScanIndexDesc()) outputValues.insertList(getScanIndexDesc()->getIndexColumns()); // Include the index columns from the updated table, if any if (getIndexDesc()) outputValues.insertList (getIndexDesc()->getIndexColumns()); } // HbaseUpdate::getPotentialOutputValues() // ----------------------------------------------------------------------- // Member functions for DP2 Scan // ----------------------------------------------------------------------- DP2Scan::DP2Scan(const CorrName& tableName, TableDesc * tableDescPtr, const IndexDesc *indexDescPtr, const NABoolean isReverseScan, const Cardinality& baseCardinality, StmtLevelAccessOptions& accessOpts, GroupAttributes * groupAttributesPtr, const ValueIdSet& selectionPredicates, const Disjuncts& disjuncts) : FileScan(tableName, tableDescPtr, indexDescPtr, isReverseScan, baseCardinality, accessOpts, groupAttributesPtr, selectionPredicates, disjuncts, ValueIdSet()) { } // -------------------------------------------------- // methods for class Describe // -------------------------------------------------- void Describe::getPotentialOutputValues(ValueIdSet & outputValues) const { outputValues.clear(); // // Assign the set of columns that belong to the index to be scanned // as the output values that can be produced by this scan. // outputValues.insertList( getTableDesc()->getClusteringIndex()->getIndexColumns() ); } // Describe::getPotentialOutputValues() // ----------------------------------------------------------------------- // methods for class RelRoot // ----------------------------------------------------------------------- RelRoot::RelRoot(RelExpr *input, OperatorTypeEnum otype, ItemExpr *compExpr, ItemExpr *orderBy, ItemExpr *updateCol, RelExpr *reqdShape, CollHeap *oHeap) : RelExpr(otype, input, NULL, oHeap), compExprTree_(compExpr), orderByTree_(orderBy), updateColTree_(updateCol), reqdShape_(reqdShape), viewStoiList_(CmpCommon::statementHeap()), ddlStoiList_(CmpCommon::statementHeap()), stoiUdrList_(CmpCommon::statementHeap()), udfList_(CmpCommon::statementHeap()), securityKeySet_(CmpCommon::statementHeap()), trueRoot_(FALSE), subRoot_(FALSE), displayTree_(FALSE), outputVarCnt_(-1), inputVarTree_(NULL), outputVarTree_(NULL), updatableSelect_(TRUE), updateCurrentOf_(FALSE), currOfCursorName_(NULL), rollbackOnError_(FALSE), readOnlyTransIsOK_(FALSE), needFirstSortedRows_(FALSE), numSimpleVar_(0), numHostVar_(0), childOperType_(NO_OPERATOR_TYPE), hostArraysArea_(NULL), assignmentStTree_(NULL), assignList_(NULL), isRootOfInternalRefresh_(FALSE), isQueryNonCacheable_(FALSE), pMvBindContextForScope_(NULL), parentForRowsetReqdOrder_(NULL), isEmptySelectList_(FALSE), isDontOpenNewScope_(FALSE), triggersList_(NULL), spOutParams_(NULL), downrevCompileMXV_(COM_VERS_CURR_PLAN), numExtractStreams_(0), numBMOs_(0), BMOsMemoryUsage_(0), nBMOsMemoryUsage_(0), uninitializedMvList_(NULL), allOrderByRefsInGby_(FALSE), avoidHalloween_(FALSE), containsOnStatementMV_(FALSE), containsLRU_(FALSE), mustUseESPs_(FALSE), disableESPParallelism_(FALSE), hasOlapFunctions_(FALSE), hasTDFunctions_(FALSE), isAnalyzeOnly_(FALSE), hasMandatoryXP_(FALSE), partReqType_(ANY_PARTITIONING), partitionByTree_(NULL), predExprTree_(NULL), firstNRowsParam_(NULL), flags_(0) { accessOptions().accessType() = ACCESS_TYPE_NOT_SPECIFIED_; accessOptions().lockMode() = LOCK_MODE_NOT_SPECIFIED_; isCIFOn_ = FALSE; } RelRoot::RelRoot(RelExpr *input, AccessType at, LockMode lm, OperatorTypeEnum otype, ItemExpr *compExpr, ItemExpr *orderBy, ItemExpr *updateCol, RelExpr *reqdShape, CollHeap *oHeap) : RelExpr(otype, input, NULL, oHeap), compExprTree_(compExpr), orderByTree_(orderBy), updateColTree_(updateCol), reqdShape_(reqdShape), viewStoiList_(CmpCommon::statementHeap()), ddlStoiList_(CmpCommon::statementHeap()), stoiUdrList_(CmpCommon::statementHeap()), udfList_(CmpCommon::statementHeap()), securityKeySet_(CmpCommon::statementHeap()), trueRoot_(FALSE), subRoot_(FALSE), displayTree_(FALSE), outputVarCnt_(-1), inputVarTree_(NULL), outputVarTree_(NULL), updatableSelect_(TRUE), updateCurrentOf_(FALSE), currOfCursorName_(NULL), rollbackOnError_(FALSE), readOnlyTransIsOK_(FALSE), needFirstSortedRows_(FALSE), numSimpleVar_(0), numHostVar_(0), childOperType_(NO_OPERATOR_TYPE), hostArraysArea_(NULL), assignmentStTree_(NULL), assignList_(NULL), isRootOfInternalRefresh_(FALSE), isQueryNonCacheable_(FALSE), pMvBindContextForScope_(NULL), parentForRowsetReqdOrder_(NULL), isEmptySelectList_(FALSE), isDontOpenNewScope_(FALSE), triggersList_(NULL), spOutParams_(NULL), downrevCompileMXV_(COM_VERS_CURR_PLAN), numExtractStreams_(0), numBMOs_(0), BMOsMemoryUsage_(0), nBMOsMemoryUsage_(0), uninitializedMvList_(NULL), allOrderByRefsInGby_(FALSE), avoidHalloween_(FALSE), containsOnStatementMV_(FALSE), containsLRU_(FALSE), mustUseESPs_(FALSE), disableESPParallelism_(FALSE), hasOlapFunctions_(FALSE), hasTDFunctions_(FALSE), isAnalyzeOnly_(FALSE), hasMandatoryXP_(FALSE), partReqType_(ANY_PARTITIONING), partitionByTree_(NULL), predExprTree_(NULL), firstNRowsParam_(NULL), flags_(0) { accessOptions().accessType() = at; accessOptions().lockMode() = lm; isCIFOn_ = FALSE; } // Why not just use the default copy ctor that C++ provides automatically, ## // rather than having to maintain this??? ## // Is it because of the "numXXXVar_(0)" lines below, ## // or should those be "numXXXVar_(other.numXXXVar_)" ? ## RelRoot::RelRoot(const RelRoot & other) : RelExpr(REL_ROOT, other.child(0)), compExprTree_(other.compExprTree_), orderByTree_(other.orderByTree_), updateColTree_(other.updateColTree_), reqdShape_(other.reqdShape_), viewStoiList_(other.viewStoiList_), ddlStoiList_(other.ddlStoiList_), stoiUdrList_(other.stoiUdrList_), udfList_(other.udfList_), securityKeySet_(other.securityKeySet_), trueRoot_(other.trueRoot_), subRoot_(other.subRoot_), displayTree_(other.displayTree_), outputVarCnt_(other.outputVarCnt_), inputVarTree_(other.inputVarTree_), outputVarTree_(other.outputVarTree_), updatableSelect_(other.updatableSelect_), updateCurrentOf_(other.updateCurrentOf_), currOfCursorName_(other.currOfCursorName_), rollbackOnError_(other.rollbackOnError_), readOnlyTransIsOK_(other.readOnlyTransIsOK_), needFirstSortedRows_(other.needFirstSortedRows_), isRootOfInternalRefresh_(other.isRootOfInternalRefresh_), isQueryNonCacheable_(other.isQueryNonCacheable_), pMvBindContextForScope_(other.pMvBindContextForScope_), isEmptySelectList_(other.isEmptySelectList_), isDontOpenNewScope_(other.isDontOpenNewScope_), // oltOptInfo_(other.oltOptInfo_), numSimpleVar_(0), //## bug? numHostVar_(0), //## bug? childOperType_(other.childOperType_), hostArraysArea_(other.hostArraysArea_), assignmentStTree_(other.assignmentStTree_), assignList_(other.assignList_), triggersList_(other.triggersList_), compExpr_(other.compExpr_), reqdOrder_(other.reqdOrder_), partArrangement_(other.partArrangement_), updateCol_(other.updateCol_), inputVars_(other.inputVars_), accessOptions_(other.accessOptions_), pkeyList_(other.pkeyList_), rowsetReqdOrder_(other.rowsetReqdOrder_), parentForRowsetReqdOrder_(other.parentForRowsetReqdOrder_), spOutParams_ (NULL), // Raj P - 12/2000 - stored procedures (for java) downrevCompileMXV_(COM_VERS_CURR_PLAN), uninitializedMvList_(other.uninitializedMvList_), allOrderByRefsInGby_(other.allOrderByRefsInGby_), numExtractStreams_(other.numExtractStreams_), numBMOs_(other.numBMOs_), BMOsMemoryUsage_(other.BMOsMemoryUsage_), nBMOsMemoryUsage_(other.nBMOsMemoryUsage_), avoidHalloween_(other.avoidHalloween_), disableESPParallelism_(other.disableESPParallelism_), containsOnStatementMV_(other.containsOnStatementMV_), containsLRU_(other.containsLRU_), mustUseESPs_(other.mustUseESPs_), hasOlapFunctions_(other.hasOlapFunctions_), hasTDFunctions_(other.hasTDFunctions_ ), isAnalyzeOnly_(FALSE), hasMandatoryXP_(other.hasMandatoryXP_), partReqType_(other.partReqType_), partitionByTree_(other.partitionByTree_), isCIFOn_(other.isCIFOn_), predExprTree_(other.predExprTree_), firstNRowsParam_(other.firstNRowsParam_), flags_(other.flags_) { oltOptInfo() = ((RelRoot&)other).oltOptInfo(); setRETDesc(other.getRETDesc()); } RelRoot::~RelRoot() { // Explicitly deleting our members is deliberately not being done -- // we should allocate all RelExpr's on the appropriate heap // (as a NABasicObject) and free the (stmt) heap all in one blow. // delete compExprTree_; // delete orderByTree_; // delete reqdShape_; // delete inputVarTree_; } Int32 RelRoot::getArity() const { return 1; } void RelRoot::getPotentialOutputValues(ValueIdSet & outputValues) const { outputValues.clear(); // // Assign the select list as the outputs // outputValues.insertList(compExpr()); } // RelRoot::getPotentialOutputValues() void RelRoot::pushdownCoveredExpr(const ValueIdSet & outputExpr, const ValueIdSet & newExternalInputs, ValueIdSet & predicatesOnParent, const ValueIdSet * setOfValuesReqdByParent, Lng32 //childIndex ignored ) { //--------------------------------------------------------------------- // case 10-030708-7671: In the case of a cast, the RelRoot operator // needs to ask for original expression it is casting; if it asks for // the cast expression, the child may be incapable of producing it. For // example, a nested join operator can't produce the cast expression, // unless produced by its children //--------------------------------------------------------------------- ValueIdSet originalOutputs = getGroupAttr()->getCharacteristicOutputs(); ValueIdSet updateOutputs(originalOutputs); updateOutputs.replaceCastExprWithOriginal(originalOutputs, this); ValueIdSet myCharInput = getGroupAttr()->getCharacteristicInputs(); // since the orderby list is not a subset of the select list include it. ValueIdSet allMyExpr; ValueIdList orderByList = reqdOrder(); allMyExpr.insertList(orderByList); // add the primary key columns, if they are to be returned. if (updatableSelect() == TRUE) { allMyExpr.insertList(pkeyList()); } // --------------------------------------------------------------------- RelExpr::pushdownCoveredExpr(updateOutputs, myCharInput, predicatesOnParent, &allMyExpr ); // All expressions should have been pushed CMPASSERT(predicatesOnParent.isEmpty()); } // RelRoot::pushdownCoveredExpr const NAString RelRoot::getText() const { NAString result("root"); #ifdef DEBUG_TRIGGERS char totalNodes[20]; sprintf(totalNodes, "(total %d nodes)", nodeCount()); result += totalNodes; if (isDontOpenNewScope()) result += "(no_scope)"; if (isEmptySelectList()) result += "(empty_select_list)"; #endif return result; } HashValue RelRoot::topHash() { HashValue result = RelExpr::topHash(); // it's not (yet) needed to produce a really good hash value for this node result ^= compExpr_.entries(); result ^= inputVars_.entries(); // result ^= compExpr_; // result ^= inputVars_; return result; } NABoolean RelRoot::duplicateMatch(const RelExpr & other) const { if (!RelExpr::duplicateMatch(other)) return FALSE; RelRoot &o = (RelRoot &) other; if (NOT (compExpr_ == o.compExpr_) OR NOT (inputVars_ == o.inputVars_)) return FALSE; if (avoidHalloween_ != o.avoidHalloween_) return FALSE; if (disableESPParallelism_ != o.disableESPParallelism_) return FALSE; if (isAnalyzeOnly_ != o.isAnalyzeOnly_) return FALSE; return TRUE; } RelExpr * RelRoot::copyTopNode(RelExpr *derivedNode, CollHeap* outHeap) { RelRoot *result; if (derivedNode == NULL) result = new (outHeap) RelRoot(NULL, getOperatorType(), NULL, NULL, NULL, NULL, outHeap); else result = (RelRoot *) derivedNode; if (compExprTree_ != NULL) result->compExprTree_ = compExprTree_->copyTree(outHeap)->castToItemExpr(); if (inputVarTree_ != NULL) result->inputVarTree_ = inputVarTree_->copyTree(outHeap)->castToItemExpr(); if (outputVarTree_ != NULL) result->outputVarTree_ = outputVarTree_->copyTree(outHeap)->castToItemExpr(); if (predExprTree_ != NULL) result->predExprTree_ = predExprTree_->copyTree(outHeap)->castToItemExpr(); result->compExpr_ = compExpr_; result->inputVars_ = inputVars_; result->accessOptions_ = accessOptions_; result->updatableSelect_ = updatableSelect_; result->updateCurrentOf_ = updateCurrentOf_; if (currOfCursorName()) result->currOfCursorName_ = currOfCursorName()->copyTree(outHeap)->castToItemExpr(); result->rollbackOnError_ = rollbackOnError_; result->isEmptySelectList_ = isEmptySelectList_; result->isDontOpenNewScope_ = isDontOpenNewScope_; result->oltOptInfo() = oltOptInfo(); result->childOperType_ = childOperType_; result->rowsetReqdOrder_ = rowsetReqdOrder_; result->parentForRowsetReqdOrder_ = parentForRowsetReqdOrder_; // Raj P - 12/2000 stored procedures (for java) if ( spOutParams_ ) { result->spOutParams_ = new ItemExprList (outHeap); (*result->spOutParams_) = *spOutParams_; } if( uninitializedMvList_ ) { result->uninitializedMvList_ = new UninitializedMvNameList (outHeap); result->uninitializedMvList_->insert( *uninitializedMvList_ ); } result->setDownrevCompileMXV(getDownrevCompileMXV()); result->numExtractStreams_ = numExtractStreams_; result->allOrderByRefsInGby_ = allOrderByRefsInGby_; result->avoidHalloween_ = avoidHalloween_; result->disableESPParallelism_ = disableESPParallelism_; result->containsOnStatementMV_ = containsOnStatementMV_; result->hasOlapFunctions_ = hasOlapFunctions_; result->containsLRU_ = containsLRU_; result->mustUseESPs_ = mustUseESPs_; result->isAnalyzeOnly_ = isAnalyzeOnly_; result->hasMandatoryXP_ = hasMandatoryXP_ ; if (partitionByTree_ != NULL) result->partitionByTree_ = partitionByTree_->copyTree(outHeap)->castToItemExpr(); result->partReqType_ = partReqType_ ; result->isQueryNonCacheable_ = isQueryNonCacheable_; result->firstNRowsParam_ = firstNRowsParam_; result->flags_ = flags_; return RelExpr::copyTopNode(result, outHeap); } void RelRoot::addCompExprTree(ItemExpr *compExpr) { ExprValueId c = compExprTree_; ItemExprTreeAsList(&c, ITM_ITEM_LIST).insert(compExpr); compExprTree_ = c.getPtr(); } ItemExpr * RelRoot::removeCompExprTree() { ItemExpr * result = compExprTree_; compExprTree_ = NULL; return result; } void RelRoot::addPredExprTree(ItemExpr *predExpr) { ExprValueId c = predExprTree_; ItemExprTreeAsList(&c, ITM_ITEM_LIST).insert(predExpr); predExprTree_ = c.getPtr(); } ItemExpr * RelRoot::removePredExprTree() { ItemExpr * result = predExprTree_; predExprTree_ = NULL; return result; } void RelRoot::addInputVarTree(ItemExpr *inputVar) { ExprValueId c = inputVarTree_; ItemExprTreeAsList(&c, ITM_ITEM_LIST).insert(inputVar); inputVarTree_ = c.getPtr(); } void RelRoot::addAtTopOfInputVarTree(ItemExpr *inputVar) { ExprValueId c = inputVarTree_; ItemExprTreeAsList(&c, ITM_ITEM_LIST).insertAtTop(inputVar); inputVarTree_ = c.getPtr(); } ItemExpr * RelRoot::removeInputVarTree() { ItemExpr * result = inputVarTree_; inputVarTree_ = NULL; return result; } void RelRoot::addOutputVarTree(ItemExpr *outputVar) { if (!outputVarTree_) { outputVarTree_ = new(CmpCommon::statementHeap()) ItemList(outputVar, NULL); } else { ItemExpr *start = outputVarTree_; while (start->child(1)) { start = start->child(1); } start->child(1) = new(CmpCommon::statementHeap()) ItemList(outputVar, NULL); } } // Used by Assignment Statement in a Compound Statement. It adds a host variable // to assignmentStTree_ void RelRoot::addAssignmentStTree(ItemExpr *inputOutputVar) { if (!assignmentStTree_) { assignmentStTree_ = new(CmpCommon::statementHeap()) ItemList(inputOutputVar, NULL); } else { ItemExpr *start = assignmentStTree_; while (start->child(1)) { start = start->child(1); } start->child(1) = new(CmpCommon::statementHeap()) ItemList(inputOutputVar, NULL); } } ItemExpr * RelRoot::removeOutputVarTree() { ItemExpr * result = outputVarTree_; outputVarTree_ = NULL; return result; } void RelRoot::addOrderByTree(ItemExpr *orderBy) { ExprValueId c = orderByTree_; ItemExprTreeAsList(&c, ITM_ITEM_LIST).insert(orderBy); orderByTree_ = c.getPtr(); } ItemExpr * RelRoot::removeOrderByTree() { ItemExpr * result = orderByTree_; orderByTree_ = NULL; return result; } void RelRoot::addPartitionByTree(ItemExpr *partBy) { ExprValueId c = partitionByTree_; ItemExprTreeAsList(&c, ITM_ITEM_LIST).insert(partBy); partitionByTree_ = c.getPtr(); } ItemExpr * RelRoot::removePartitionByTree() { ItemExpr * result = partitionByTree_; partitionByTree_ = NULL; return result; } void RelRoot::addUpdateColTree(ItemExpr *updateCol) { ExprValueId c = updateColTree_; ItemExprTreeAsList(&c, ITM_ITEM_LIST).insert(updateCol); updateColTree_ = c.getPtr(); } ItemExpr * RelRoot::removeUpdateColTree() { ItemExpr * result = updateColTree_; updateColTree_ = NULL; return result; } void RelRoot::addLocalExpr(LIST(ExprNode *) &xlist, LIST(NAString) &llist) const { if (compExprTree_ != NULL OR compExpr_.entries() == 0) xlist.insert(compExprTree_); else xlist.insert(compExpr_.rebuildExprTree(ITM_ITEM_LIST)); llist.insert("select_list"); if (inputVarTree_ != NULL OR inputVars_.entries() > 0) { if (inputVars_.entries() == 0) xlist.insert(inputVarTree_); else xlist.insert(inputVars_.rebuildExprTree(ITM_ITEM_LIST)); llist.insert("input_variables"); } if (orderByTree_ != NULL OR reqdOrder_.entries() > 0) { if (reqdOrder_.entries() == 0) xlist.insert(orderByTree_); else xlist.insert(reqdOrder_.rebuildExprTree(ITM_ITEM_LIST)); llist.insert("order_by"); } if ((partitionByTree_ != NULL) OR (partArrangement_.entries() > 0)) { if (partArrangement_.entries() == 0) xlist.insert(partitionByTree_); else xlist.insert(partArrangement_.rebuildExprTree(ITM_ITEM_LIST)); llist.insert("partition_by"); } if (updateColTree_ != NULL OR updateCol_.entries() > 0) { if (updateCol_.entries() == 0) xlist.insert(updateColTree_); else xlist.insert(updateCol_.rebuildExprTree(ITM_ITEM_LIST)); llist.insert("update_col"); } if (reqdShape_ != NULL) { xlist.insert(reqdShape_); llist.insert("must_match"); } RelExpr::addLocalExpr(xlist,llist); } //---------------------------------------------------------------------------- //++ MV OZ NABoolean RelRoot::hasMvBindContext() const { return (NULL != pMvBindContextForScope_) ? TRUE : FALSE; } MvBindContext * RelRoot::getMvBindContext() const { return pMvBindContextForScope_; } void RelRoot::setMvBindContext(MvBindContext * pMvBindContext) { pMvBindContextForScope_ = pMvBindContext; } void RelRoot::addOneRowAggregates(BindWA* bindWA) { RelExpr * childOfRoot = child(0); GroupByAgg *aggNode = NULL; // If the One Row Subquery is already enforced by a scalar aggregate // then we do not need to add an additional one row aggregate. The exceptions to // this rule is if we have count(t1.a) where t1 itself is a one row subquery. // Note that the count is needed in order to have a groupby below the root node. // See soln. 10-071105-8680 // Another exception is when the select list has say max(a) + select a from t1 // In this case there is a onerowsubquery in the select list but it is a child // of BiArith. Due to all these exceptions we are simply going to scan the select // list. As soon as we find something other than an aggregate we take the safe // way out and add a one row aggregate. // Also if the groupby is non scalar then we need to add a one row aggregate. // Also if we have select max(a) + select b from t1 from t2; if (childOfRoot->getOperatorType() == REL_GROUPBY) { aggNode = (GroupByAgg *)childOfRoot; if (!aggNode->groupExpr().isEmpty()) aggNode = NULL; // Check to see if the compExpr contains a subquery. for (CollIndex i=0; i < compExpr().entries(); i++) if (compExpr()[i].getItemExpr()->containsOpType(ITM_ROW_SUBQUERY)) { aggNode = NULL ; break; } } if (aggNode) return ; const RETDesc *oldTable = getRETDesc(); RETDesc *resultTable = new(bindWA->wHeap()) RETDesc(bindWA); // Transform select list such that that each item has a oneRow parent. for (CollIndex selectListIndex=0; selectListIndex < compExpr().entries(); selectListIndex++) { ItemExpr *colExpr = compExpr()[selectListIndex].getItemExpr(); // Build a new OneRow aggregate on top of the existing expression. ItemExpr *newColExpr = new(bindWA->wHeap()) Aggregate(ITM_ONEROW, colExpr); newColExpr->bindNode(bindWA); ColumnNameMap *xcnmEntry = oldTable->findColumn(compExpr()[selectListIndex]); if (xcnmEntry) // ## I don't recall when this case occurs... resultTable->addColumn(bindWA, xcnmEntry->getColRefNameObj(), newColExpr->getValueId(), USER_COLUMN, xcnmEntry->getColumnDesc()->getHeading()); else { ColRefName colRefName; resultTable->addColumn(bindWA, colRefName, newColExpr->getValueId()); } // Replace the select list expression with the new one. compExpr()[selectListIndex] = newColExpr->getValueId(); } ValueIdSet aggregateExpr(compExpr()) ; GroupByAgg *newGrby = NULL; newGrby = new(bindWA->wHeap()) GroupByAgg(childOfRoot, aggregateExpr); newGrby->bindNode(bindWA) ; child(0) = newGrby ; // Set the return descriptor // setRETDesc(resultTable); } // ----------------------------------------------------------------------- // member functions for class PhysicalRelRoot // ----------------------------------------------------------------------- NABoolean PhysicalRelRoot::isLogical() const { return FALSE; } NABoolean PhysicalRelRoot::isPhysical() const { return TRUE; } // ----------------------------------------------------------------------- // methods for class Tuple // ----------------------------------------------------------------------- THREAD_P Lng32 Tuple::idCounter_(0); Tuple::Tuple(const Tuple & other) : RelExpr(other.getOperatorType()) { selectionPred() = other.getSelectionPred(); tupleExprTree_ = other.tupleExprTree_; tupleExpr_ = other.tupleExpr_; rejectPredicates_ = other.rejectPredicates_; id_ = other.id_; } Tuple::~Tuple() {} #pragma nowarn(1026) // warning elimination Int32 Tuple::getArity() const { return 0; } #pragma warn(1026) // warning elimination // ----------------------------------------------------------------------- // A virtual method for computing output values that an operator can // produce potentially. // ----------------------------------------------------------------------- void Tuple::getPotentialOutputValues(ValueIdSet & outputValues) const { outputValues.clear(); outputValues.insertList( tupleExpr() ); } // Tuple::getPotentialOutputValues() HashValue Tuple::topHash() { HashValue result = RelExpr::topHash(); result ^= tupleExpr_.entries(); return result; } NABoolean Tuple::duplicateMatch(const RelExpr & other) const { if (!RelExpr::duplicateMatch(other)) return FALSE; Tuple &o = (Tuple &) other; if (NOT (tupleExpr_ == o.tupleExpr_)) return FALSE; if (NOT (id_ == o.id_)) return FALSE; return TRUE; } RelExpr * Tuple::copyTopNode(RelExpr *derivedNode, CollHeap* outHeap) { Tuple *result; if (derivedNode == NULL) result = new (outHeap) Tuple(NULL,outHeap); else result = (Tuple *) derivedNode; if (tupleExprTree_ != NULL) result->tupleExprTree_ = tupleExprTree_->copyTree(outHeap)->castToItemExpr(); result->tupleExpr_ = tupleExpr_; result->id_ = id_; return RelExpr::copyTopNode(result, outHeap); } void Tuple::addTupleExprTree(ItemExpr *tupleExpr) { ExprValueId t = tupleExprTree_; ItemExprTreeAsList(&t, ITM_ITEM_LIST).insert(tupleExpr); tupleExprTree_ = t.getPtr(); } ItemExpr * Tuple::removeTupleExprTree() { ItemExpr * result = tupleExprTree_; tupleExprTree_ = NULL; return result; } void Tuple::addLocalExpr(LIST(ExprNode *) &xlist, LIST(NAString) &llist) const { if (tupleExprTree_ != NULL OR NOT tupleExpr_.isEmpty()) { if(tupleExpr_.isEmpty()) xlist.insert(tupleExprTree_); else xlist.insert(tupleExpr_.rebuildExprTree(ITM_ITEM_LIST)); llist.insert("tuple_expr"); } RelExpr::addLocalExpr(xlist,llist); } const NAString Tuple::getText() const { NAString tmp("values ", CmpCommon::statementHeap()); if (tupleExprTree()) tupleExprTree()->unparse(tmp); else ((ValueIdList &)tupleExpr()).unparse(tmp); return tmp; } // ----------------------------------------------------------------------- // methods for class TupleList // ----------------------------------------------------------------------- TupleList::TupleList(const TupleList & other) : Tuple(other) { castToList_ = other.castToList_; createdForInList_ = other.createdForInList_; } RelExpr * TupleList::copyTopNode(RelExpr *derivedNode, CollHeap* outHeap) { TupleList *result; if (derivedNode == NULL) result = new (outHeap) TupleList(NULL,outHeap); else result = (TupleList *) derivedNode; result->castToList() = castToList(); return Tuple::copyTopNode(result, outHeap); } void TupleList::addLocalExpr(LIST(ExprNode *) &xlist, LIST(NAString) &llist) const { Tuple::addLocalExpr(xlist,llist); } const NAString TupleList::getText() const { NAString tmp("TupleList",CmpCommon::statementHeap()); return tmp; } // ----------------------------------------------------------------------- // member functions for class PhysicalTuple // ----------------------------------------------------------------------- NABoolean PhysicalTuple::isLogical() const { return FALSE; } NABoolean PhysicalTuple::isPhysical() const { return TRUE; } // ----------------------------------------------------------------------- // Member functions for class FirstN // ----------------------------------------------------------------------- RelExpr * FirstN::copyTopNode(RelExpr *derivedNode, CollHeap* outHeap) { FirstN *result; if (derivedNode == NULL) { result = new (outHeap) FirstN(NULL, getFirstNRows(), getFirstNRowsParam(), outHeap); result->setCanExecuteInDp2(canExecuteInDp2()); } else result = (FirstN *) derivedNode; return RelExpr::copyTopNode(result, outHeap); } const NAString FirstN::getText() const { NAString result(CmpCommon::statementHeap()); result = "FirstN"; return result; } // helper method to determine if we have a child Fisrt N node that can execute in Dp2. // This method will only search nodes with one child. We do not expect the child First N // to occur below a join or union type node. This method will unwind as soon as the first // FirstN child is found. static NABoolean haveChildFirstNInDp2 (RelExpr * node) { if (node->getArity() != 1) return FALSE; if (node->child(0)) { if (node->child(0)->getOperatorType() == REL_FIRST_N) { // child is FirstN FirstN * innerFirstN = (FirstN *) node->child(0)->castToRelExpr(); if (innerFirstN->canExecuteInDp2()) return TRUE; else return FALSE; } else { // have child but it is not FirstN return (haveChildFirstNInDp2(node->child(0))); } } else return FALSE; // no child even though arity is 1! } RelExpr * FirstN::bindNode(BindWA *bindWA) { if (nodeIsBound()) { bindWA->getCurrentScope()->setRETDesc(getRETDesc()); return this; } if (bindWA->isEmbeddedIUDStatement() && haveChildFirstNInDp2(this)) { setCanExecuteInDp2(TRUE); } return RelExpr::bindNode(bindWA); } NABoolean FirstN::computeRowsAffected() const { if (child(0)) { return child(0)->castToRelExpr()->computeRowsAffected(); } return FALSE; } // member functions for class Filter // ----------------------------------------------------------------------- Filter::~Filter() {} Int32 Filter::getArity() const { return 1; } HashValue Filter::topHash() { HashValue result = RelExpr::topHash(); return result; } NABoolean Filter::duplicateMatch(const RelExpr & other) const { return RelExpr::duplicateMatch(other); } RelExpr * Filter::copyTopNode(RelExpr *derivedNode, CollHeap* outHeap) { Filter *result; if (derivedNode == NULL) result = new (outHeap) Filter(NULL, outHeap); else result = (Filter *) derivedNode; return RelExpr::copyTopNode(result, outHeap); } void Filter::getPotentialOutputValues(ValueIdSet & outputValues) const { outputValues.clear(); outputValues += child(0)->getGroupAttr()->getCharacteristicOutputs(); } // Filter::getPotentialOutputValues() const NAString Filter::getText() const { return "filter"; } // ----------------------------------------------------------------------- // member functions for class Rename // ----------------------------------------------------------------------- Rename::~Rename() {} Int32 Rename::getArity() const { return 1; } HashValue Rename::topHash() { ABORT("Hash functions can't be called in the parser"); return 0x0; } NABoolean Rename::duplicateMatch(const RelExpr & /* other */) const { ABORT("Duplicate match doesn't work in the parser"); return FALSE; } // ----------------------------------------------------------------------- // member functions for class RenameTable // ----------------------------------------------------------------------- RenameTable::~RenameTable() {} const NAString RenameTable::getText() const { return ("rename_as " + newTableName_.getCorrNameAsString()); } RelExpr * RenameTable::copyTopNode(RelExpr *derivedNode, CollHeap* outHeap) { RenameTable *result; if (derivedNode == NULL) result = new (outHeap) RenameTable(TRUE, NULL, newTableName_, NULL, outHeap); else result = (RenameTable *) derivedNode; if (newColNamesTree_ != NULL) result->newColNamesTree_ = newColNamesTree_->copyTree(outHeap)->castToItemExpr(); if (viewNATable_ != NULL) result->viewNATable_ = viewNATable_; return RelExpr::copyTopNode(result, outHeap); } ItemExpr * RenameTable::removeColNameTree() { ItemExpr * result = newColNamesTree_; newColNamesTree_ = NULL; return result; } void RenameTable::addLocalExpr(LIST(ExprNode *) &xlist, LIST(NAString) &llist) const { xlist.insert(newColNamesTree_); llist.insert("new_col_names"); RelExpr::addLocalExpr(xlist,llist); } // ----------------------------------------------------------------------- // member functions for class RenameReference // ----------------------------------------------------------------------- RenameReference::~RenameReference() {} const NAString RenameReference::getText() const { NAString text("rename_ref"); for (CollIndex i=0; i<tableReferences_.entries(); i++) text += " " + tableReferences_[i].getRefName(); return text; } RelExpr * RenameReference::copyTopNode(RelExpr *derivedNode, CollHeap* outHeap) { RenameReference *result; if (derivedNode == NULL) { TableRefList *tableRef = new(outHeap) TableRefList(tableReferences_); result = new (outHeap) RenameReference(NULL, *tableRef, outHeap); } else result = (RenameReference *) derivedNode; return RelExpr::copyTopNode(result, outHeap); } void RenameReference::addLocalExpr(LIST(ExprNode *) &xlist, LIST(NAString) &llist) const { RelExpr::addLocalExpr(xlist,llist); } // ----------------------------------------------------------------------- // member functions for class BeforeTrigger // ----------------------------------------------------------------------- BeforeTrigger::~BeforeTrigger() {} Int32 BeforeTrigger::getArity() const { if (child(0) == NULL) return 0; else return 1; } const NAString BeforeTrigger::getText() const { NAString text("before_trigger: "); if (signal_) text += "Signal"; else text += "Set"; return text; } RelExpr * BeforeTrigger::copyTopNode(RelExpr *derivedNode, CollHeap* outHeap) { BeforeTrigger *result; if (derivedNode == NULL) { TableRefList *tableRef = new(outHeap) TableRefList(tableReferences_); ItemExpr *whenClause = NULL; if (whenClause_ != NULL) whenClause = whenClause_->copyTree(outHeap); if (isSignal_) { RaiseError *signalClause = (RaiseError *)signal_->copyTree(outHeap); result = new (outHeap) BeforeTrigger(*tableRef, whenClause, signalClause, outHeap); } else { CMPASSERT(setList_ != NULL); // Must have either SET or SIGNAL clause. #pragma nowarn(1506) // warning elimination ItemExprList *setList = new(outHeap) ItemExprList(setList_->entries(), outHeap); #pragma warn(1506) // warning elimination for (CollIndex i=0; i<setList_->entries(); i++) setList->insert(setList_->at(i)->copyTree(outHeap)); result = new (outHeap) BeforeTrigger(*tableRef, whenClause, setList, outHeap); } } else result = (BeforeTrigger *) derivedNode; return RelExpr::copyTopNode(result, outHeap); } void BeforeTrigger::addLocalExpr(LIST(ExprNode *) &xlist, LIST(NAString) &llist) const { if (whenClause_ != NULL) { llist.insert("WHEN clause"); xlist.insert(whenClause_); } if (signal_) { llist.insert("SIGNAL clause"); xlist.insert(signal_); } else { for (CollIndex i=0; i<setList_->entries(); i++) { llist.insert("SET clause"); xlist.insert(setList_->at(i)); } } RelExpr::addLocalExpr(xlist,llist); } // ----------------------------------------------------------------------- // member functions for class MapValueIds // ----------------------------------------------------------------------- MapValueIds::~MapValueIds() { } Int32 MapValueIds::getArity() const { return 1; } void MapValueIds::pushdownCoveredExpr( const ValueIdSet & outputExpr, const ValueIdSet & newExternalInputs, ValueIdSet & predicatesOnParent, const ValueIdSet * setOfValuesReqdByParent, Lng32 childIndex) { // --------------------------------------------------------------------- // Since the MapValueIds node rewrites predicates, the characteristic // outputs of the node usually make no sense to the child node. For // this reason, translate the characteristic outputs of this node before // passing them down to the children. // --------------------------------------------------------------------- ValueIdSet requiredValues; if (setOfValuesReqdByParent) requiredValues = *setOfValuesReqdByParent; ValueIdSet translatedOutputs; ValueIdSet predsRewrittenForChild; ValueIdSet outputValues(outputExpr); // first subtract the outputs from the required values, then add back // the translated outputs outputValues -= getGroupAttr()->getCharacteristicOutputs(); getMap().rewriteValueIdSetDown(getGroupAttr()->getCharacteristicOutputs(), translatedOutputs); outputValues += translatedOutputs; translatedOutputs.clear(); requiredValues -= getGroupAttr()->getCharacteristicOutputs(); getMap().rewriteValueIdSetDown(getGroupAttr()->getCharacteristicOutputs(), translatedOutputs); requiredValues += translatedOutputs; // rewrite the predicates so they can be applied in the child node getMap().rewriteValueIdSetDown(predicatesOnParent,predsRewrittenForChild); // use the standard method with the new required values RelExpr::pushdownCoveredExpr(outputValues, newExternalInputs, predsRewrittenForChild, &requiredValues, childIndex); // eliminate any VEGPredicates that got duplicated in the parent if (NOT child(0)->isCutOp()) predsRewrittenForChild -= child(0)->selectionPred(); // all predicates must have been pushed down!! CMPASSERT(predsRewrittenForChild.isEmpty()); predicatesOnParent.clear(); // Remove entries from the map that are no longer required since // they no longer appear in the outputs. NABoolean matchWithTopValues = FALSE; if (child(0)->isCutOp() || child(0)->getOperatorType() == REL_FILTER || child(0)->getOperatorType() == REL_MAP_VALUEIDS ) { matchWithTopValues = TRUE; getMap().removeUnusedEntries(getGroupAttr()->getCharacteristicOutputs(), matchWithTopValues); } else { getMap().removeUnusedEntries(child(0)->getGroupAttr()->getCharacteristicOutputs(), matchWithTopValues); } } // MapValueIds::pushdownCoveredExpr void MapValueIds::getPotentialOutputValues(ValueIdSet & outputValues) const { outputValues.clear(); // // The output of the MapValueId is given by the ValueIds // contained in the "upper" portion of a two-tiered mapping // table. // outputValues.insertList((getMap2()).getTopValues()); } // MapValueIds::getPotentialOutputValues() void MapValueIds::addLocalExpr(LIST(ExprNode *) &xlist, LIST(NAString) &llist) const { xlist.insert(map_.getTopValues().rebuildExprTree(ITM_ITEM_LIST)); llist.insert("upper_values"); xlist.insert(map_.getBottomValues().rebuildExprTree(ITM_ITEM_LIST)); llist.insert("lower_values"); RelExpr::addLocalExpr(xlist,llist); } HashValue MapValueIds::topHash() { HashValue result = RelExpr::topHash(); result ^= map_.getTopValues(); result ^= map_.getBottomValues(); return result; } NABoolean MapValueIds::duplicateMatch(const RelExpr & other) const { if (NOT RelExpr::duplicateMatch(other)) return FALSE; MapValueIds &o = (MapValueIds &) other; if (includesFavoriteMV_ != o.includesFavoriteMV_) return FALSE; if (usedByMvqr_ != o.usedByMvqr_) return FALSE; if (map_ != o.map_) return FALSE; return TRUE; } RelExpr * MapValueIds::copyTopNode(RelExpr *derivedNode, CollHeap* outHeap) { MapValueIds *result; if (derivedNode == NULL) result = new (outHeap) MapValueIds(NULL,map_,outHeap); else result = static_cast<MapValueIds*>(derivedNode); result->includesFavoriteMV_ = includesFavoriteMV_; result->usedByMvqr_ = usedByMvqr_; return RelExpr::copyTopNode(result, outHeap); } const NAString MapValueIds::getText() const { return "map_value_ids"; // return "expr"; } // ----------------------------------------------------------------------- // Member functions for class PhysicalMapValueIds // ----------------------------------------------------------------------- NABoolean PhysicalMapValueIds::isLogical() const { return FALSE; } NABoolean PhysicalMapValueIds::isPhysical() const { return TRUE; } // ----------------------------------------------------------------------- // Member functions for class Describe // ----------------------------------------------------------------------- RelExpr * Describe::copyTopNode(RelExpr *derivedNode, CollHeap* outHeap) { Describe *result; if (derivedNode == NULL) result = new (outHeap) Describe(originalQuery_, getDescribedTableName(), format_, labelAnsiNameSpace_); else result = (Describe *) derivedNode; return RelExpr::copyTopNode(result, outHeap); } const NAString Describe::getText() const { return "describe"; } // ----------------------------------------------------------------------- // Member functions for class ProbeCache // ----------------------------------------------------------------------- NABoolean ProbeCache::isLogical() const { return FALSE; } NABoolean ProbeCache::isPhysical() const { return TRUE; } Int32 ProbeCache::getArity() const { return 1; } RelExpr * ProbeCache::copyTopNode(RelExpr *derivedNode, CollHeap* outHeap) { ProbeCache *result; if (derivedNode == NULL) result = new (outHeap) ProbeCache(NULL, numCachedProbes_, outHeap); else result = (ProbeCache *) derivedNode; result->numCachedProbes_ = numCachedProbes_; result->numInnerTuples_ = numInnerTuples_; return RelExpr::copyTopNode(result, outHeap); } const NAString ProbeCache::getText() const { return "probe_cache"; } // ----------------------------------------------------------------------- // Member functions for class ControlRunningQuery // ----------------------------------------------------------------------- NABoolean ControlRunningQuery::isLogical() const { return TRUE; } NABoolean ControlRunningQuery::isPhysical() const { return TRUE; } Int32 ControlRunningQuery::getArity() const { return 0; } RelExpr * ControlRunningQuery::copyTopNode(RelExpr *derivedNode, CollHeap* outHeap) { ControlRunningQuery *result = NULL; if (derivedNode == NULL) { switch (qs_) { case ControlNidPid: result = new (outHeap) ControlRunningQuery(nid_, pid_, ControlNidPid, action_, forced_, outHeap); break; case ControlPname: result = new (outHeap) ControlRunningQuery(pname_, ControlPname, action_, forced_, outHeap); break; case ControlQid: result = new (outHeap) ControlRunningQuery(queryId_, ControlQid, action_, forced_, outHeap); break; default: CMPASSERT(0); } result->setComment(comment_); } else result = (ControlRunningQuery *) derivedNode; return RelExpr::copyTopNode(result, outHeap); } const NAString ControlRunningQuery::getText() const { return "control_running_query"; } void ControlRunningQuery::setComment(NAString &comment) { NAString cancelComment (comment, CmpCommon::statementHeap()); comment_ = cancelComment; } // ----------------------------------------------------------------------- // member functions for class GenericUpdate // ----------------------------------------------------------------------- GenericUpdate::~GenericUpdate() {} Int32 GenericUpdate::getArity() const { if (getOperator().match(REL_ANY_LEAF_GEN_UPDATE)) return 0; else if (getOperator().match(REL_ANY_UNARY_GEN_UPDATE)) return 1; else ABORT("Don't know opcode in GenericUpdate::getArity()"); return 0; // return makes MSVC happy. } void GenericUpdate::getPotentialOutputValues(ValueIdSet & outputValues) const { outputValues = potentialOutputs_; } const NAString GenericUpdate::getUpdTableNameText() const { return updatedTableName_.getTextWithSpecialType(); } void GenericUpdate::computeUsedCols() { ValueIdSet requiredValueIds(newRecExpr_); ValueIdSet coveredExprs; // --------------------------------------------------------------------- // Call the "coverTest" method, offering it all the index columns // as additional inputs. "coverTest" will mark those index columns that // it actually needs to satisfy the required value ids, and that is // what we actually want. The actual cover test should always succeed, // otherwise the update node would have been inconsistent. // --------------------------------------------------------------------- // use the clustering index, unless set otherwise if (indexDesc_ == NULL) indexDesc_ = getTableDesc()->getClusteringIndex(); if (isMerge()) { requiredValueIds.insertList(mergeInsertRecExpr_); } requiredValueIds.insertList(beginKeyPred_); requiredValueIds.insertList(endKeyPred_); requiredValueIds.insertList(getCheckConstraints()); // QSTUFF requiredValueIds.insertList(newRecBeforeExpr_); // QSTUFF getGroupAttr()->coverTest(requiredValueIds, indexDesc_->getIndexColumns(), // all index columns coveredExprs, // dummy parameter usedColumns_); // needed index cols // usedColumns_ is now set correctly } // GenericUpdate::computeUsedCols const NAString GenericUpdate::getText() const { return ("GenericUpdate " + getUpdTableNameText()); } HashValue GenericUpdate::topHash() { HashValue result = RelExpr::topHash(); result ^= newRecExpr_; if (isMerge()) result ^= mergeInsertRecExpr_; // result ^= keyExpr_; return result; } NABoolean GenericUpdate::duplicateMatch(const RelExpr & other) const { if (NOT RelExpr::duplicateMatch(other)) return FALSE; GenericUpdate &o = (GenericUpdate &) other; if (newRecExpr_ != o.newRecExpr_ OR (isMerge() && ((mergeInsertRecExpr_ != o.mergeInsertRecExpr_) OR (mergeUpdatePred_ != o.mergeUpdatePred_)) ) OR NOT (beginKeyPred_ == o.beginKeyPred_) OR NOT (endKeyPred_ == o.endKeyPred_)) return FALSE; // later, replace this with the getTableDesc() ??? if (NOT (updatedTableName_ == o.updatedTableName_)) return FALSE; if (mtsStatement_ != o.mtsStatement_) return FALSE; if (noRollback_ != o.noRollback_) return FALSE; if (avoidHalloweenR2_ != o.avoidHalloweenR2_) return FALSE; if (avoidHalloween_ != o.avoidHalloween_) return FALSE; if (halloweenCannotUseDP2Locks_ != o.halloweenCannotUseDP2Locks_) return FALSE; return TRUE; } RelExpr * GenericUpdate::copyTopNode(RelExpr *derivedNode, CollHeap* outHeap) { GenericUpdate *result; if (derivedNode == NULL) result = new (outHeap) GenericUpdate(updatedTableName_, getTableDesc(), getOperatorType(), NULL, NULL, NULL, outHeap); else result = (GenericUpdate *) derivedNode; result->setIndexDesc((IndexDesc *)getIndexDesc()); if (newRecExprTree_) result->newRecExprTree_ = newRecExprTree_->copyTree(outHeap)->castToItemExpr(); // ## Should usedColumns_ be copied here? Is it missing deliberately or only by mistake? result->updateToSelectMap_ = updateToSelectMap_; result->newRecExpr_ = newRecExpr_; result->newRecExprArray_ = newRecExprArray_; // QSTUFF result->newRecBeforeExpr_ = newRecBeforeExpr_; result->newRecBeforeExprArray_ = newRecBeforeExprArray_; // QSTUFF result->mergeInsertRecExpr_ = mergeInsertRecExpr_; result->mergeInsertRecExprArray_ = mergeInsertRecExprArray_; result->mergeUpdatePred_ = mergeUpdatePred_; result->beginKeyPred_ = beginKeyPred_; result->endKeyPred_ = endKeyPred_; result->executorPred_ = executorPred_; result->potentialOutputs_ = potentialOutputs_; result->indexNewRecExprArrays_ = indexNewRecExprArrays_; result->indexBeginKeyPredArray_ = indexBeginKeyPredArray_; result->indexEndKeyPredArray_ = indexEndKeyPredArray_; result->indexNumberArray_ = indexNumberArray_; result->scanIndexDesc_ = scanIndexDesc_; result->accessOptions_ = accessOptions_; result->checkConstraints_ = checkConstraints_; result->rowsAffected_ = rowsAffected_; result->setOptStoi(stoi_); result->setNoFlow(noFlow_); result->setMtsStatement(mtsStatement_); result->setNoRollbackOperation(noRollback_); result->setAvoidHalloweenR2(avoidHalloweenR2_); result->avoidHalloween_ = avoidHalloween_; result->halloweenCannotUseDP2Locks_ = halloweenCannotUseDP2Locks_; result->setIsMergeUpdate(isMergeUpdate_); result->setIsMergeDelete(isMergeDelete_); result->subqInUpdateAssign_ = subqInUpdateAssign_; result->setUpdateCKorUniqueIndexKey(updateCKorUniqueIndexKey_); result->hbaseOper() = hbaseOper(); result->uniqueHbaseOper() = uniqueHbaseOper(); result->cursorHbaseOper() = cursorHbaseOper(); result->uniqueRowsetHbaseOper() = uniqueRowsetHbaseOper(); result->canDoCheckAndUpdel() = canDoCheckAndUpdel(); result->setNoCheck(noCheck()); result->noDTMxn() = noDTMxn(); result->useMVCC() = useMVCC(); result->useSSCC() = useSSCC(); if (currOfCursorName()) result->currOfCursorName_ = currOfCursorName()->copyTree(outHeap)->castToItemExpr(); if (preconditionTree_) result->preconditionTree_ = preconditionTree_->copyTree(outHeap)->castToItemExpr(); result->setPrecondition(precondition_); result->exprsInDerivedClasses_ = exprsInDerivedClasses_; return RelExpr::copyTopNode(result, outHeap); } PlanPriority GenericUpdate::computeOperatorPriority (const Context* context, PlanWorkSpace *pws, Lng32 planNumber) { PlanPriority result; NABoolean interactiveAccess = (CmpCommon::getDefault(INTERACTIVE_ACCESS) == DF_ON) OR ( QueryAnalysis::Instance() AND QueryAnalysis::Instance()->optimizeForFirstNRows()); return result; } void GenericUpdate::addNewRecExprTree(ItemExpr *expr) { ExprValueId newRec = newRecExprTree_; ItemExprTreeAsList(&newRec, ITM_AND).insert(expr); newRecExprTree_ = newRec.getPtr(); } ItemExpr * GenericUpdate::removeNewRecExprTree() { ItemExpr * result = newRecExprTree_; newRecExprTree_ = NULL; return result; } void GenericUpdate::addLocalExpr(LIST(ExprNode *) &xlist, LIST(NAString) &llist) const { if (newRecExprTree_ != NULL OR NOT newRecExpr_.isEmpty()) { if (newRecExpr_.isEmpty()) xlist.insert(newRecExprTree_); else xlist.insert(newRecExpr_.rebuildExprTree(ITM_ITEM_LIST)); llist.insert("new_rec_expr"); } if ((isMerge()) && (NOT mergeInsertRecExpr_.isEmpty())) { xlist.insert(mergeInsertRecExpr_.rebuildExprTree(ITM_ITEM_LIST)); llist.insert("merge_insert_rec_expr"); } if ((isMerge()) && (NOT mergeUpdatePred_.isEmpty())) { xlist.insert(mergeUpdatePred_.rebuildExprTree(ITM_ITEM_LIST)); llist.insert("merge_update_where_pred"); } Int32 indexNo = 0; for(; indexNo < (Int32)indexNewRecExprArrays_.entries(); indexNo++) { ValueIdArray array = indexNewRecExprArrays_[indexNo]; ValueIdList list; for(Int32 i = 0; i < (Int32)array.entries(); i++) list.insert(array[i]); xlist.insert(list.rebuildExprTree(ITM_ITEM_LIST)); llist.insert("new idx rec expr"); } if (executorPredTree_ != NULL OR NOT executorPred_.isEmpty()) { if (executorPred_.isEmpty()) xlist.insert(executorPredTree_); else xlist.insert(executorPred_.rebuildExprTree()); llist.insert("predicate"); } // display preds from search key only if begin/end keys are // not generated yet (e.g. during optimization) if (beginKeyPred_.isEmpty() AND endKeyPred_.isEmpty() AND pathKeys_ AND NOT pathKeys_->getKeyPredicates().isEmpty()) { xlist.insert(pathKeys_->getKeyPredicates().rebuildExprTree()); if (pathKeys_ == partKeys_) llist.insert("key_and_part_key_preds"); else llist.insert("key_predicates"); } // display part key preds only if different from clustering key preds if (partKeys_ AND pathKeys_ != partKeys_ AND NOT partKeys_->getKeyPredicates().isEmpty()) { xlist.insert(partKeys_->getKeyPredicates().rebuildExprTree()); llist.insert("part_key_predicates"); } if (NOT beginKeyPred_.isEmpty()) { xlist.insert(beginKeyPred_.rebuildExprTree(ITM_AND)); llist.insert("begin_key"); } for(indexNo = 0; indexNo < (Int32)indexBeginKeyPredArray_.entries(); indexNo++){ if(NOT indexBeginKeyPredArray_[indexNo].isEmpty()) { xlist.insert(indexBeginKeyPredArray_[indexNo] .rebuildExprTree(ITM_ITEM_LIST)); llist.insert("index_begin_key"); } } if (NOT endKeyPred_.isEmpty()) { xlist.insert(endKeyPred_.rebuildExprTree(ITM_AND)); llist.insert("end_key"); } for(indexNo = 0; indexNo < (Int32)indexEndKeyPredArray_.entries(); indexNo++) { if(NOT indexEndKeyPredArray_[indexNo].isEmpty()) { xlist.insert(indexEndKeyPredArray_[indexNo] .rebuildExprTree(ITM_ITEM_LIST)); llist.insert("index_end_key"); } } if (NOT getCheckConstraints().isEmpty()) { xlist.insert(getCheckConstraints().rebuildExprTree(ITM_AND)); llist.insert("check_constraint"); } if (preconditionTree_ != NULL OR precondition_.entries() > 0) { if (preconditionTree_ != NULL) xlist.insert(preconditionTree_); else xlist.insert(precondition_.rebuildExprTree(ITM_AND)); llist.insert("precondition"); } RelExpr::addLocalExpr(xlist,llist); } NABoolean GenericUpdate::updateCurrentOf() { return currOfCursorName() != NULL #ifndef NDEBUG || getenv("FORCE_UPD_CURR_OF") #endif ; } //++MV - returns the GenericUpdateOutputFunction's that are in the // potential outputs NABoolean GenericUpdate::getOutputFunctionsForMV(ValueId &valueId, OperatorTypeEnum opType) const { const ValueIdSet& outputs = getGroupAttr()->getCharacteristicOutputs(); for (ValueId vid= outputs.init(); outputs.next(vid); outputs.advance(vid) ) { ItemExpr *expr = vid.getItemExpr(); if (expr->getOperatorType() == ITM_CAST) expr = expr->child(0); if (expr->getOperator().match(opType) && expr->isAGenericUpdateOutputFunction() ) { valueId = vid; return TRUE; } } return FALSE; } NABoolean GenericUpdate::computeRowsAffected() const { if (rowsAffected_ == GenericUpdate::COMPUTE_ROWSAFFECTED) return TRUE; else return FALSE; }; void GenericUpdate::configTSJforHalloween( Join* tsj, OperatorTypeEnum opType, CostScalar inputCardinality) { if (avoidHalloween()) { // If we use DP2's FELOCKSELF (i.e., DP2Locks) method to // protect against Halloween, then lock escalation will // be disabled in the Generator. So DP2 wants us to use // no more than 25000 locks per volume. // Also, notice that // by design, we are relying on good cardinality estimates. // If the estimates are too low, then there may be // runtime errors. const PartitioningFunction *partFunc = getTableDesc()-> getClusteringIndex()->getPartitioningFunction(); const Lng32 numParts = partFunc ? partFunc->getCountOfPartitions() : 1; const Lng32 maxLocksAllParts = 25000 * numParts; if ((opType == REL_LEAF_INSERT) && (inputCardinality < maxLocksAllParts) && ! getHalloweenCannotUseDP2Locks() && (CmpCommon::getDefault(BLOCK_TO_PREVENT_HALLOWEEN) != DF_ON) ) tsj->setHalloweenForceSort(Join::NOT_FORCED); else tsj->setHalloweenForceSort(Join::FORCED); } } void GenericUpdate::pushdownCoveredExpr(const ValueIdSet &outputExpr, const ValueIdSet &newExternalInputs, ValueIdSet &predicatesOnParent, const ValueIdSet *setOfValuesReqdByParent, Lng32 childIndex ) { // --------------------------------------------------------------------- // determine the set of local expressions that need to be evaluated // - assign expressions (reference source & target cols) // - source cols alone (in case order is required) // - characteristic outputs for this node // --------------------------------------------------------------------- // QSTUFF ?? again need to understand details ValueIdSet localExprs(newRecExpr()); if (setOfValuesReqdByParent) localExprs += *setOfValuesReqdByParent; // QSTUFF localExprs.insertList(newRecBeforeExpr()); // QSTUFF if (isMerge()) { localExprs.insertList(mergeInsertRecExpr()); } localExprs.insertList(beginKeyPred()); localExprs.insertList(updateToSelectMap().getBottomValues()); if (setOfValuesReqdByParent) localExprs += *setOfValuesReqdByParent ; localExprs += exprsInDerivedClasses_; // --------------------------------------------------------------------- // Check which expressions can be evaluated by my child. // Modify the Group Attributes of those children who inherit some of // these expressions. // Since an GenericUpdate has no predicates, supply an empty set. // --------------------------------------------------------------------- RelExpr::pushdownCoveredExpr( outputExpr, newExternalInputs, predicatesOnParent, &localExprs); } /* NABoolean Insert::reconcileGroupAttr(GroupAttributes *newGroupAttr) { SET(IndexDesc *) x; const IndexDesc* y = getTableDesc()->getClusteringIndex(); x.insert((IndexDesc*)y); newGroupAttr->addToAvailableBtreeIndexes(x); // Now as usual return RelExpr::reconcileGroupAttr(newGroupAttr); } */ // ----------------------------------------------------------------------- // member functions for class Insert // ----------------------------------------------------------------------- Insert::Insert(const CorrName &name, TableDesc *tabId, OperatorTypeEnum otype, RelExpr *child , ItemExpr *insertCols , ItemExpr *orderBy , CollHeap *oHeap , InsertType insertType, NABoolean createUstatSample) : GenericUpdate(name,tabId,otype,child,NULL,NULL,oHeap), insertColTree_(insertCols), orderByTree_(orderBy), targetUserColPosList_(NULL), bufferedInsertsAllowed_(FALSE), insertType_(insertType), noBeginSTInsert_(FALSE), noCommitSTInsert_(FALSE), enableTransformToSTI_(FALSE), enableAqrWnrEmpty_(FALSE), systemGeneratesIdentityValue_(FALSE), insertSelectQuery_(FALSE), boundView_(NULL), overwriteHiveTable_(FALSE), isSequenceFile_(FALSE), isUpsert_(FALSE), isTrafLoadPrep_(FALSE), createUstatSample_(createUstatSample), baseColRefs_(NULL) { insert_a_tuple_ = FALSE; if ( child ) { if ( child->getOperatorType() == REL_TUPLE ) { insert_a_tuple_ = TRUE; if (!name.isLocationNameSpecified()) { setCacheableNode(CmpMain::PARSE); } } else if ( child->getOperatorType() == REL_TUPLE_LIST && !name.isLocationNameSpecified() ) { setCacheableNode(CmpMain::PARSE); } } else // this is a patch to pass regression for maximum parallelism project, // if we insert a default values not a real tuple the child is NULL // but we'd like to identify is as a tuple insert. March,2006 if (CmpCommon::getDefault(COMP_BOOL_66) == DF_OFF) { insert_a_tuple_ = TRUE; } } Insert::~Insert() {} void Insert::addInsertColTree(ItemExpr *expr) { ExprValueId newCol = insertColTree_; ItemExprTreeAsList(&newCol, ITM_AND).insert(expr); insertColTree_ = newCol.getPtr(); } ItemExpr * Insert::removeInsertColTree() { ItemExpr * result = insertColTree_; insertColTree_ = NULL; return result; } ItemExpr * Insert::getInsertColTree() { return insertColTree_; } const NAString Insert::getText() const { NAString text("insert",CmpCommon::statementHeap()); return (text + " " + getUpdTableNameText()); } RelExpr * Insert::copyTopNode(RelExpr *derivedNode, CollHeap* outHeap) { Insert *result; if (derivedNode == NULL) result = new (outHeap) Insert(getTableName(), getTableDesc(), getOperatorType(), NULL, NULL, NULL, outHeap, getInsertType()); else result = (Insert *) derivedNode; result->rrKeyExpr() = rrKeyExpr(); result->partNumInput() = partNumInput(); result->rowPosInput() = rowPosInput(); result->totalNumPartsInput() = totalNumPartsInput(); result->reqdOrder() = reqdOrder(); result->noBeginSTInsert_ = noBeginSTInsert_; result->noCommitSTInsert_ = noCommitSTInsert_; result->enableTransformToSTI() = enableTransformToSTI(); result->enableAqrWnrEmpty() = enableAqrWnrEmpty(); if (insertColTree_ != NULL) result->insertColTree_ = insertColTree_->copyTree(outHeap)->castToItemExpr(); result->insertATuple() = insertATuple(); result->setInsertSelectQuery(isInsertSelectQuery()); result->setOverwriteHiveTable(getOverwriteHiveTable()); result->setSequenceFile(isSequenceFile()); result->isUpsert_ = isUpsert_; result->isTrafLoadPrep_ = isTrafLoadPrep_; result->createUstatSample_ = createUstatSample_; return GenericUpdate::copyTopNode(result, outHeap); } void Insert::setNoBeginCommitSTInsert(NABoolean noBeginSTI, NABoolean noCommitSTI) { noBeginSTInsert_ = noBeginSTI; noCommitSTInsert_ = noCommitSTI; } // ----------------------------------------------------------------------- // member functions for class Update // ----------------------------------------------------------------------- Update::Update(const CorrName &name, TableDesc *tabId, OperatorTypeEnum otype, RelExpr *child, ItemExpr *newRecExpr, ItemExpr *currOfCursorName, CollHeap *oHeap) : GenericUpdate(name,tabId,otype,child,newRecExpr,currOfCursorName,oHeap), estRowsAccessed_(0) { setCacheableNode(CmpMain::BIND); } Update::~Update() {} const NAString Update::getText() const { NAString text("update",CmpCommon::statementHeap()); return (text + " " + getUpdTableNameText()); } RelExpr * Update::copyTopNode(RelExpr *derivedNode, CollHeap* outHeap) { Update *result; if (derivedNode == NULL) result = new (outHeap) Update(getTableName(), getTableDesc(), getOperatorType(), NULL, NULL, NULL, outHeap); else result = (Update *) derivedNode; result->setEstRowsAccessed(getEstRowsAccessed()); return GenericUpdate::copyTopNode(result, outHeap); } // ----------------------------------------------------------------------- // member functions for class MergeUpdate // ----------------------------------------------------------------------- MergeUpdate::MergeUpdate(const CorrName &name, TableDesc *tabId, OperatorTypeEnum otype, RelExpr *child, ItemExpr *setExpr, ItemExpr *insertCols, ItemExpr *insertValues, CollHeap *oHeap, ItemExpr *where) : Update(name,tabId,otype,child,setExpr,NULL,oHeap), insertCols_(insertCols), insertValues_(insertValues), where_(where),xformedUpsert_(FALSE) { setCacheableNode(CmpMain::BIND); setIsMergeUpdate(TRUE); } MergeUpdate::~MergeUpdate() {} const NAString MergeUpdate::getText() const { NAString text("merge_update",CmpCommon::statementHeap()); return (text + " " + getUpdTableNameText()); } RelExpr * MergeUpdate::copyTopNode(RelExpr *derivedNode, CollHeap* outHeap) { MergeUpdate *result; if (derivedNode == NULL) result = new (outHeap) MergeUpdate(getTableName(), getTableDesc(), getOperatorType(), child(0), NULL, insertCols(), insertValues(), outHeap, where_); else result = (MergeUpdate *) derivedNode; if (xformedUpsert()) result->setXformedUpsert(); return Update::copyTopNode(result, outHeap); } // ----------------------------------------------------------------------- // member functions for class Delete // ----------------------------------------------------------------------- Delete::Delete(const CorrName &name, TableDesc *tabId, OperatorTypeEnum otype, RelExpr *child, ItemExpr *newRecExpr, ItemExpr *currOfCursorName, ConstStringList * csl, CollHeap *oHeap) : GenericUpdate(name,tabId,otype,child,newRecExpr,currOfCursorName,oHeap), isFastDelete_(FALSE), csl_(csl),estRowsAccessed_(0) { setCacheableNode(CmpMain::BIND); } Delete::~Delete() {} const NAString Delete::getText() const { NAString text("delete",CmpCommon::statementHeap()); return (text + " " + getUpdTableNameText()); } RelExpr * Delete::copyTopNode(RelExpr *derivedNode, CollHeap* outHeap) { Delete *result; if (derivedNode == NULL) result = new (outHeap) Delete(getTableName(), getTableDesc(), getOperatorType(), NULL, NULL, NULL, csl_, outHeap); else result = (Delete *) derivedNode; result->isFastDelete_ = isFastDelete_; result->csl() = csl(); result->setEstRowsAccessed(getEstRowsAccessed()); return GenericUpdate::copyTopNode(result, outHeap); } // ----------------------------------------------------------------------- // member functions for class MergeDelete // ----------------------------------------------------------------------- MergeDelete::MergeDelete(const CorrName &name, TableDesc *tabId, OperatorTypeEnum otype, RelExpr *child, ItemExpr *insertCols, ItemExpr *insertValues, CollHeap *oHeap) : Delete(name,tabId,otype,child,NULL,NULL,NULL,oHeap), insertCols_(insertCols), insertValues_(insertValues) { setCacheableNode(CmpMain::BIND); setIsMergeDelete(TRUE); } MergeDelete::~MergeDelete() {} const NAString MergeDelete::getText() const { NAString text("merge_delete",CmpCommon::statementHeap()); return (text + " " + getUpdTableNameText()); } RelExpr * MergeDelete::copyTopNode(RelExpr *derivedNode, CollHeap* outHeap) { MergeDelete *result; if (derivedNode == NULL) result = new (outHeap) MergeDelete(getTableName(), getTableDesc(), getOperatorType(), child(0), insertCols(), insertValues(), outHeap); else result = (MergeDelete *) derivedNode; return Delete::copyTopNode(result, outHeap); } // ----------------------------------------------------------------------- // member functions for class InsertCursor // ----------------------------------------------------------------------- InsertCursor::~InsertCursor() {} NABoolean InsertCursor::isLogical() const { return FALSE; } NABoolean InsertCursor::isPhysical() const { return TRUE; } const NAString InsertCursor::getText() const { NAString text("insert", CmpCommon::statementHeap()); if ((insertType_ == VSBB_INSERT_SYSTEM) || (insertType_ == VSBB_INSERT_USER)) text = text + "_vsbb"; else if ((insertType_ == VSBB_LOAD) || (insertType_ == VSBB_LOAD_APPEND) || (insertType_ == VSBB_LOAD_NO_DUP_KEY_CHECK) || (insertType_ == VSBB_LOAD_APPEND_NO_DUP_KEY_CHECK)) text = text + "_sidetree"; else if (insertType_ == VSBB_LOAD_AUDITED) text = text + "_sidetree_audited"; text = text + " (physical)"; return (text + " " + getUpdTableNameText()); } RelExpr * InsertCursor::copyTopNode(RelExpr *derivedNode, CollHeap* outHeap) { RelExpr *result; if (derivedNode == NULL) result = new (outHeap) InsertCursor(getTableName(), getTableDesc(), getOperatorType(), NULL, outHeap); else result = derivedNode; return Insert::copyTopNode(result, outHeap); } // ----------------------------------------------------------------------- // member functions for class HiveInsert // ----------------------------------------------------------------------- const NAString HiveInsert::getText() const { NAString text("hive_insert", CmpCommon::statementHeap()); text += " (physical)"; return (text + " " + getUpdTableNameText()); } RelExpr * HiveInsert::copyTopNode(RelExpr *derivedNode, CollHeap* outHeap) { RelExpr *result; if (derivedNode == NULL) result = new (outHeap) HiveInsert(getTableName(), getTableDesc(), getOperatorType(), NULL, outHeap); else result = derivedNode; return Insert::copyTopNode(result, outHeap); } // ----------------------------------------------------------------------- // member functions for class HbaseInsert // ----------------------------------------------------------------------- const NAString HbaseInsert::getText() const { NABoolean isSeabase = (getTableDesc() && getTableDesc()->getNATable() ? getTableDesc()->getNATable()->isSeabaseTable() : FALSE); NAString text; if (NOT isSeabase) text = "hbase_"; else text = "trafodion_"; if (isUpsert()) { if (getInsertType() == Insert::UPSERT_LOAD) { if (getIsTrafLoadPrep()) text += "load_preparation"; else text += "load"; } else if (vsbbInsert()) text += "vsbb_upsert"; else text += "upsert"; } else { if (vsbbInsert()) text += "vsbb_upsert"; else text += "insert"; } return (text + " " + getUpdTableNameText()); } RelExpr * HbaseInsert::copyTopNode(RelExpr *derivedNode, CollHeap* outHeap) { HbaseInsert *result; if (derivedNode == NULL) result = new (outHeap) HbaseInsert(getTableName(), getTableDesc(), getOperatorType(), NULL, outHeap); else result = (HbaseInsert *) derivedNode; result->returnRow_ = returnRow_; return Insert::copyTopNode(result, outHeap); } RelExpr * HBaseBulkLoadPrep::copyTopNode(RelExpr *derivedNode, CollHeap* outHeap) { RelExpr *result; if (derivedNode == NULL) result = new (outHeap) HbaseInsert(getTableName(), getTableDesc(), getOperatorType(), NULL, outHeap); else result = derivedNode; return Insert::copyTopNode(result, outHeap); } // ----------------------------------------------------------------------- // member functions for class UpdateCursor // ----------------------------------------------------------------------- UpdateCursor::~UpdateCursor() {} NABoolean UpdateCursor::isLogical() const { return FALSE; } NABoolean UpdateCursor::isPhysical() const { return TRUE; } const NAString UpdateCursor::getText() const { NAString text("cursor_update",CmpCommon::statementHeap()); return (text + " " + getUpdTableNameText()); } RelExpr * UpdateCursor::copyTopNode(RelExpr *derivedNode, CollHeap* outHeap) { RelExpr *result; if (derivedNode == NULL) result = new (outHeap) UpdateCursor(getTableName(), getTableDesc(), getOperatorType(), NULL, outHeap); else result = derivedNode; return Update::copyTopNode(result, outHeap); } // ----------------------------------------------------------------------- // member functions for class DeleteCursor // ----------------------------------------------------------------------- DeleteCursor::~DeleteCursor() {} NABoolean DeleteCursor::isLogical() const { return FALSE; } NABoolean DeleteCursor::isPhysical() const { return TRUE; } const NAString DeleteCursor::getText() const { NAString text("cursor_delete",CmpCommon::statementHeap()); return (text + " " + getUpdTableNameText()); } RelExpr * DeleteCursor::copyTopNode(RelExpr *derivedNode, CollHeap* outHeap) { RelExpr *result; if (derivedNode == NULL) result = new (outHeap) DeleteCursor(getTableName(), getTableDesc(), getOperatorType(), NULL, outHeap); else result = derivedNode; return Delete::copyTopNode(result, outHeap); } ///////////////////////////////////////////////////////////////////// void RelExpr::unparse(NAString &result, PhaseEnum /* phase */, UnparseFormatEnum /* form */, TableDesc * tabId) const { result += getText(); #ifndef NDEBUG if (getenv("UNPARSE_FULL")) { if (selection_) { result += "["; selection_->unparse(result /*, phase, form */); result += "]"; } if (predicates_.entries()) { result += "{"; predicates_.unparse(result /*, phase, form */); result += "}"; } } #endif Int32 maxi = getArity(); if (maxi) { result += "("; for (Lng32 i = 0; i < maxi; i++) { if (i > 0) result += ", "; if ( child(i).getPtr() == NULL ) continue; child(i)->unparse(result); } result += ")"; } } // ----------------------------------------------------------------------- // methods for class Transpose // ----------------------------------------------------------------------- // Transpose::~Transpose() ----------------------------------------------- // The destructor // Transpose::~Transpose() { } // Transpose::topHash() -------------------------------------------------- // Compute a hash value for a chain of derived RelExpr nodes. // Used by the Cascade engine as a quick way to determine if // two nodes are identical. // Can produce false positives (nodes appear to be identical), // but should not produce false negatives (nodes are definitely different) // // Inputs: none (other than 'this') // // Outputs: A HashValue of this node and all nodes in the // derivation chain below (towards the base class) this node. // HashValue Transpose::topHash() { // Compute a hash value of the derivation chain below this node. // HashValue result = RelExpr::topHash(); // transUnionVector is the only relevant // data members at this point. The other data members do not // live past the binder. // for(CollIndex i = 0; i < transUnionVectorSize(); i++) { result ^= transUnionVector()[i]; } return result; } // Transpose::duplicateMatch() // A more thorough method to compare two RelExpr nodes. // Used by the Cascades engine when the topHash() of two // nodes returns the same hash values. // // Inputs: other - a reference to another node of the same type. // // Outputs: NABoolean - TRUE if this node is 'identical' to the // 'other' node. FALSE otherwise. // // In order to match, this node must match all the way down the // derivation chain to the RelExpr class. // // For the Transpose node, the only relevant data member which // needs to be compared is transUnionVals_. The other data members // do not exist passed the binder. // NABoolean Transpose::duplicateMatch(const RelExpr & other) const { // Compare this node with 'other' down the derivation chain. // if (!RelExpr::duplicateMatch(other)) return FALSE; // Cast the RelExpr to a Transpose node. (This must be a Transpose node) // Transpose &o = (Transpose &) other; // If the transUnionVectors are the same size and have the same entries, // then the nodes are identical // if(transUnionVectorSize() != o.transUnionVectorSize()) return FALSE; for(CollIndex i = 0; i < transUnionVectorSize(); i++) { if (!(transUnionVector()[i] == o.transUnionVector()[i])) return FALSE; } return TRUE; } // Transpose::copyTopNode ---------------------------------------------- // Copy a chain of derived nodes (Calls RelExpr::copyTopNode). // Needs to copy all relevant fields. // Used by the Cascades engine. // // Inputs: derivedNode - If Non-NULL this should point to a node // which is derived from this node. If NULL, then this // node is the top of the derivation chain and a node must // be constructed. // // Outputs: RelExpr * - A Copy of this node. // // If the 'derivedNode is non-NULL, then this method is being called // from a copyTopNode method on a class derived from this one. If it // is NULL, then this is the top of the derivation chain and a transpose // node must be constructed. // // In either case, the relevant data members must be copied to 'derivedNode' // and 'derivedNode' is passed to the copyTopNode method of the class // below this one in the derivation chain (RelExpr::copyTopNode() in this // case). // RelExpr * Transpose::copyTopNode(RelExpr *derivedNode, CollHeap *outHeap) { Transpose *result; if (derivedNode == NULL) // This is the top of the derivation chain // Create an empty Transpose node. // result = new (outHeap) Transpose(NULL,NULL,NULL,outHeap); else // A node has already been constructed as a derived class. // result = (Transpose *) derivedNode; // Copy the relavant fields. result->transUnionVectorSize_ = transUnionVectorSize(); result->transUnionVector() = new (outHeap) ValueIdList[transUnionVectorSize()]; for(CollIndex i = 0; i < transUnionVectorSize(); i++) { result->transUnionVector()[i] = transUnionVector()[i]; } // copy pointer to expressions // These are not available after bindNode() // if (transValsTree_ != NULL) result->transValsTree_ = transValsTree_->copyTree(outHeap)->castToItemExpr(); if (keyCol_ != NULL) result->keyCol_ = keyCol_->copyTree(outHeap)->castToItemExpr(); // Copy any data members from the classes lower in the derivation chain. // return RelExpr::copyTopNode(result, outHeap); } // Transpose::addLocalExpr() ----------------------------------------------- // Insert into a list of expressions all the expressions of this node and // all nodes below this node in the derivation chain. Insert into a list of // names, all the names of the expressions of this node and all nodes below // this node in the derivation chain. This method is used by the GUI tool // and by the Explain Function to have a common method to get all the // expressions associated with a node. // // Inputs/Outputs: xlist - a list of expressions. // llist - a list of names of expressions. // // The xlist contains a list of all the expressions associated with this // node. The llist contains the names of these expressions. (This lists // must be kept in the same order). // Transpose::addLocalExpr potentially adds the transUnionVals_ expression // ("transpose_union_values"), the transValsTree_ expression // ("transpose_values"), and the keyCol_ expression ("key_column"). // // It then calls RelExpr::addLocalExpr() which will add any RelExpr // expressions to the list. // void Transpose::addLocalExpr(LIST(ExprNode *) &xlist, LIST(NAString) &llist) const { for(CollIndex i = 0; i < transUnionVectorSize(); i++) { if (NOT transUnionVector()[i].isEmpty()) { xlist.insert(transUnionVector()[i].rebuildExprTree()); llist.insert("transpose_union_vector"); } } // This is only available as an ItemExpr tree. It is never // stored as a ValueIdSet. This is not available after bindNode(). // if(transValsTree_) { xlist.insert(transValsTree_); llist.insert("transpose_values"); } // This is only available as an ItemExpr tree. It is never // stored as a ValueIdSet. This is not available after bindNode(). // if(keyCol_) { xlist.insert(keyCol_); llist.insert("key_column"); } RelExpr::addLocalExpr(xlist,llist); } // Transpose::getPotentialOutputValues() --------------------------------- // Construct a Set of the potential outputs of this node. // // Inputs: none (other than 'this') // // Outputs: outputValues - a ValueIdSet representing the potential outputs // of this node. // // The potential outputs for the transpose node are the new columns // generated by the transpose node, plus the outputs produced by the // child node. The new columns generated by transpose are the key // column and the value colunms (one for each transpose group). // void Transpose::getPotentialOutputValues(ValueIdSet & outputValues) const { // Make sure the ValueIdSet is empty. // outputValues.clear(); // Add the values generated by the transpose node. // for(CollIndex i = 0; i < transUnionVectorSize(); i++) { outputValues.insertList( transUnionVector()[i] ); } // Add the values produced by the child. // outputValues += child(0).getGroupAttr()->getCharacteristicOutputs(); } // Transpose::getPotentialOutputValues() // Transpose::pushdownCoveredExpr() ------------------------------------ // // In order to compute the Group Attributes for a relational operator // an analysis of all the scalar expressions associated with it is // performed. The purpose of this analysis is to identify the sources // of the values that each expression requires. As a result of this // analysis values are categorized as external dataflow inputs or // those that can be produced completely by a certain child of the // relational operator. // // This method is invoked on each relational operator. It causes // a) the pushdown of predicates and // b) the recomputation of the Group Attributes of each child. // The recomputation is required either because the child is // assigned new predicates or is expected to compute some of the // expressions that are required by its parent. // // Parameters: // // const ValueIdSet &setOfValuesReqdByParent // IN: a read-only reference to a set of expressions that are // associated with this operator. Typically, they do not // include the predicates. // // ValueIdSet & newExternalInputs // IN : a reference to a set of new external inputs (ValueIds) // that are provided by this operator for evaluating the // the above expressions. // // ValueIdSet & predicatesOnParent // IN : the set of predicates existing on the operator // OUT: a subset of the original predicates. Some of the // predicate factors may have been pushed down to // the operator's children. // // long childIndex // IN : This is an optional parameter. // If supplied, it is a zero-based index for a specific child // on which the predicate pushdown should be attempted. // If not supplied, or a null pointer is supplied, then // the pushdown is attempted on all the children. // // --------------------------------------------------------------------- void Transpose::pushdownCoveredExpr(const ValueIdSet &outputExpr, const ValueIdSet &newExternalInputs, ValueIdSet &predicatesOnParent, const ValueIdSet *setOfValuesReqdByParent, Lng32 childIndex ) { ValueIdSet exprOnParent; if (setOfValuesReqdByParent) exprOnParent = *setOfValuesReqdByParent; // Add all the values required for the transpose expressions // to the values required by the parent. // Don't add the valueIds of the ValueIdUnion nodes, but the // valueIds of the contents of the ValueIdUnion nodes. // for(CollIndex v = 0; v < transUnionVectorSize(); v++) { ValueIdList &valIdList = transUnionVector()[v]; for(CollIndex i = 0; i < valIdList.entries(); i++) { ValueIdUnion *valIdu = ((ValueIdUnion *)valIdList[i]. getValueDesc()->getItemExpr()); exprOnParent.insertList(valIdu->getSources()); } } ValueIdSet pushablePredicates(predicatesOnParent); RelExpr::pushdownCoveredExpr(outputExpr, newExternalInputs, pushablePredicates, &exprOnParent, childIndex); predicatesOnParent.intersectSet(pushablePredicates); } // Transpose::pushdownCoveredExpr // Transpose::removeTransValsTree() ------------------------------------- // Return the transValsTree_ ItemExpr tree and set to NULL, // // Inputs: none (Other than 'this') // // Outputs: ItemExpr * - the value of transValsTree_ // // Side Effects: Sets the value of transValsTree_ to NULL. // // Called by Transpose::bindNode(). The value of transValsTree_ is not // needed after the binder. // const ItemExpr * Transpose::removeTransValsTree() { ItemExpr *result = transValsTree_; transValsTree_ = (ItemExpr *)NULL; return result; } // Transpose::removeKeyCol() ------------------------------------- // Return the keyCol_ ItemExpr tree and set it to NULL, // // Inputs: none (Other than 'this') // // Outputs: ItemExpr * - the value of keyCol_ // // Side Effects: Sets the value of keyCol_ to NULL. // // Call by Transpose::bindNode(). The value of keyCol_ is not // needed after the binder. // const ItemExpr * Transpose::removeKeyCol() { ItemExpr *result = keyCol_; keyCol_ = (ItemExpr *)NULL; return result; } // This method is used in case there are expressions in the Transpose column // list. It traverses through the expression to get the column under them // If it is a unary expression, it gets the column directly below the expression. // If the expression has two children, it goes through both the children // to see which one of them has a higher UEC. It returns the ValueId of that // column. This column is later used to determine the UEC of the final // transpose column. ValueId Transpose::getSourceColFromExprForUec(ValueId sourceValId, const ColStatDescList & childColStatsList) { if (sourceValId.getItemExpr()->getOperatorType() == ITM_VEG_REFERENCE) return sourceValId; ValueIdSet vegCols; sourceValId.getItemExpr()-> findAll(ITM_VEG_REFERENCE, vegCols, TRUE, TRUE); // case 1 : expression with a constant, return sourceValId // case 2 :(only one expr) concentrates on simple expressions only // case 3 :(Multiple exprs) Expression of type EXPR1 OP EXPR2 // where EXPR1 , EXPR2 is VEGREF or EXPR we will assume the max UEC // admist the list of base columns found will be used. // This is an approximation but better that the worst case. if (vegCols.entries() == 0) { // case 1 return sourceValId; } if(vegCols.entries() == 1) { // case 2 // There is only one get that. vegCols.getFirst(sourceValId); } else { //case 3 //Initialize for safety. vegCols.getFirst(sourceValId); //CostScalars are initialized by their constructor to zero. CostScalar currentMaxUEC,currentUEC; CollIndex index = NULL_COLL_INDEX; for(ValueId currentValId = vegCols.init() ;vegCols.next(currentValId) ;vegCols.advance(currentValId)) { index = NULL_COLL_INDEX; childColStatsList.getColStatDescIndex(index, currentValId); if (index == NULL_COLL_INDEX) continue; currentUEC = childColStatsList[index]->getColStats() ->getTotalUec(); //get the UEC and find the max and corresponding valueID //and assign it ti sourceValId. if(currentUEC > currentMaxUEC) { currentMaxUEC = currentUEC; sourceValId = currentValId; } }// end of for }//end of elsif return sourceValId; } // The destructor // PhysTranspose::~PhysTranspose() { } // PhysTranspose::copyTopNode ---------------------------------------------- // Copy a chain of derived nodes (Calls Transpose::copyTopNode). // Needs to copy all relevant fields. // Used by the Cascades engine. // // Inputs: derivedNode - If Non-NULL this should point to a node // which is derived from this node. If NULL, then this // node is the top of the derivation chain and a node must // be constructed. // // Outputs: RelExpr * - A Copy of this node. // // If the 'derivedNode is non-NULL, then this method is being called // from a copyTopNode method on a class derived from this one. If it // is NULL, then this is the top of the derivation chain and a transpose // node must be constructed. // // In either case, the relevant data members must be copied to 'derivedNode' // and 'derivedNode' is passed to the copyTopNode method of the class // below this one in the derivation chain (Transpose::copyTopNode() in this // case). // RelExpr * PhysTranspose::copyTopNode(RelExpr *derivedNode, CollHeap *outHeap) { PhysTranspose *result; if (derivedNode == NULL) // This is the top of the derivation chain // Generate an empty PhysTranspose node. // result = new (outHeap) PhysTranspose(NULL,outHeap); else // A node has already been constructed as a derived class. // result = (PhysTranspose *) derivedNode; // PhysTranspose has no data members. // Copy any data members from the classes lower in the derivation chain. // return Transpose::copyTopNode(result, outHeap); } // ----------------------------------------------------------------------- // methods for class Pack // ----------------------------------------------------------------------- // Constructor Pack::Pack(ULng32 pf, RelExpr* child, ItemExpr* packingExprTree, CollHeap* oHeap) : RelExpr(REL_PACK,child,NULL,oHeap), packingFactorLong_(pf), packingFactorTree_(NULL), packingExprTree_(packingExprTree) { setNonCacheable(); packingFactor().clear(); packingExpr().clear(); requiredOrder_.clear(); } // Destructor. Pack::~Pack() { } // ----------------------------------------------------------------------- // Pack:: some Accessors/Mutators. // ----------------------------------------------------------------------- ItemExpr* Pack::removePackingFactorTree() { ItemExpr* pf = packingFactorTree_; packingFactorTree_ = NULL; return pf; } ItemExpr* Pack::removePackingExprTree() { ItemExpr* pe = packingExprTree_; packingExprTree_ = NULL; return pe; } // ----------------------------------------------------------------------- // Pack::getText() // ----------------------------------------------------------------------- const NAString Pack::getText() const { return "PACK"; } // ----------------------------------------------------------------------- // Pack::topHash() // ----------------------------------------------------------------------- HashValue Pack::topHash() { // The base class's topHash deals with inputs/outputs and operator type. HashValue result = RelExpr::topHash(); // Packing factor and packing expression are the differentiating factors. result ^= packingFactor(); result ^= packingExpr(); result ^= requiredOrder(); return result; } // ----------------------------------------------------------------------- // Pack::duplicateMatch() // ----------------------------------------------------------------------- NABoolean Pack::duplicateMatch(const RelExpr& other) const { // Assume optimizer already matches inputs/outputs in Group Attributes. // Base class checks for operator type, predicates and children. if(NOT RelExpr::duplicateMatch(other)) return FALSE; // Base class implementation already makes sure other is a Pack node. Pack& otherPack = (Pack &) other; // If the required order keys are not the same // then the nodes are not identical // if (!(requiredOrder() == otherPack.requiredOrder())) return FALSE; // Packing factor is the only remaining thing to check. return (packingFactor_ == otherPack.packingFactor() AND packingExpr_ == otherPack.packingExpr()); } // ----------------------------------------------------------------------- // Pack::copyTopNode() // ----------------------------------------------------------------------- RelExpr* Pack::copyTopNode(RelExpr* derivedNode, CollHeap* outHeap) { Pack* result; // This the real node we want to copy. Construct a new Pack node. if(derivedNode == NULL) { result = new (outHeap) Pack (packingFactorLong(),NULL,NULL,outHeap); result->packingFactor() = packingFactor(); result->packingExpr() = packingExpr(); //result->setRequiredOrder(requiredOrder()); result->requiredOrder() = requiredOrder(); result->setFirstNRows(getFirstNRows()); } else // --------------------------------------------------------------------- // The real node we want to copy is of a derived class. The duplicate // has already been made and store in derived node. All I need to do is // to copy the members stored with this base class. // --------------------------------------------------------------------- { result = (Pack *) derivedNode; result->packingFactorLong() = packingFactorLong(); result->packingFactor() = packingFactor(); result->packingExpr() = packingExpr(); result->requiredOrder() = requiredOrder(); result->setFirstNRows(getFirstNRows()); } // Call base class to make copies of its own data members. return RelExpr::copyTopNode(result,outHeap); } // ----------------------------------------------------------------------- // Pack::getPotentialOutputValues() // ----------------------------------------------------------------------- void Pack::getPotentialOutputValues(ValueIdSet& outputValues) const { // Just the outputs of the packing expression. outputValues.clear(); outputValues.insertList(packingExpr_); } // ----------------------------------------------------------------------- // Pack::getNonPackedExpr() returns the non-packed sub-expressions of the // packing expression. // ----------------------------------------------------------------------- void Pack::getNonPackedExpr(ValueIdSet& vidset) { for(CollIndex i = 0; i < packingExpr().entries(); i++) { ItemExpr* packItem = packingExpr().at(i).getItemExpr(); vidset.insert(packItem->child(0)->getValueId()); } } // ----------------------------------------------------------------------- // Pack::pushdownCoveredExpr() needs to add the sub-expressions of the // packing expression to nonPredExprOnOperator and then make use of the // default implementation. It is expected in the first phase, nothing // can be pushed down though. // ----------------------------------------------------------------------- void Pack::pushdownCoveredExpr(const ValueIdSet& outputExpr, const ValueIdSet& newExternalInputs, ValueIdSet& predOnOperator, const ValueIdSet* nonPredExprOnOperator, Lng32 childId) { ValueIdSet exprNeededByOperator; getNonPackedExpr(exprNeededByOperator); if (nonPredExprOnOperator) exprNeededByOperator += *nonPredExprOnOperator; exprNeededByOperator.insertList(requiredOrder()); RelExpr::pushdownCoveredExpr(outputExpr, newExternalInputs, predOnOperator, &exprNeededByOperator, childId); } // ----------------------------------------------------------------------- // Pack::addLocalExpr() adds the packing expressions to be displayed by // the GUI debugger. // ----------------------------------------------------------------------- void Pack::addLocalExpr(LIST(ExprNode*)& xlist, LIST(NAString)& llist) const { if(packingExprTree_ != NULL) { xlist.insert(packingExprTree_); llist.insert("pack_expr_tree"); } if (requiredOrder().entries() > 0) { xlist.insert(requiredOrder().rebuildExprTree(ITM_ITEM_LIST)); llist.insert("required_order"); } if(NOT packingExpr_.isEmpty()) { xlist.insert(packingExpr_.rebuildExprTree()); llist.insert("pack_expr"); } RelExpr::addLocalExpr(xlist,llist); } // ----------------------------------------------------------------------- // methods for class PhyPack // ----------------------------------------------------------------------- // Destructor. PhyPack::~PhyPack() { } // ----------------------------------------------------------------------- // PhyPack::copyTopNode() // ----------------------------------------------------------------------- RelExpr* PhyPack::copyTopNode(RelExpr* derivedNode, CollHeap* outHeap) { PhyPack* result; // This the real node we want to copy. Construct a new PhyPack node. if(derivedNode == NULL) { result = new (outHeap) PhyPack (0,NULL,outHeap); } else // --------------------------------------------------------------------- // The real node we want to copy is of a derived class. The duplicate // has already been made and store in derived node. All I need to do is // to copy the members stored with this base class. // --------------------------------------------------------------------- { result = (PhyPack *) derivedNode; } // Tell base class to copy its members. PhyPack has no added members. return Pack::copyTopNode(result,outHeap); } // ----------------------------------------------------------------------- // methods for class Rowset // ----------------------------------------------------------------------- // Constructor Rowset::Rowset(ItemExpr *inputHostvars, ItemExpr *indexExpr, ItemExpr *sizeExpr, RelExpr * childExpr, CollHeap* oHeap) : RelExpr(REL_ROWSET,childExpr,NULL,oHeap), inputHostvars_(inputHostvars), indexExpr_(indexExpr), sizeExpr_(sizeExpr) { setNonCacheable(); } // Rowset::Rowset() // Destructor. Rowset::~Rowset() { } // Rowset::~Rowset() RelExpr * Rowset::copyTopNode(RelExpr *derivedNode, CollHeap* oHeap) { Rowset *result; if (derivedNode == NULL) result = new (oHeap) Rowset(inputHostvars_, indexExpr_, sizeExpr_, NULL, oHeap); else { result = (Rowset *) derivedNode; } return RelExpr::copyTopNode(result,oHeap); } // Rowset::copyTopNode() Int32 Rowset::getArity() const { return 0; // This is a leaf node } // Rowset::getArity() const NAString Rowset::getText() const { NAString result("RowSet",CmpCommon::statementHeap()); if (sizeExpr_) { if (sizeExpr_->getOperatorType() == ITM_CONSTANT) { char str[TEXT_DISPLAY_LENGTH]; sprintf(str, " " PF64, ((ConstValue *)sizeExpr_)->getExactNumericValue()); result += str; } else if (sizeExpr_->getOperatorType() == ITM_HOSTVAR) result += " " + ((HostVar *)sizeExpr_)->getName(); else result += " ??"; } result += " ("; for (ItemExpr *hostVarTree = inputHostvars_; hostVarTree != NULL; hostVarTree = hostVarTree->child(1)) { if (inputHostvars_ != hostVarTree) result += ", "; HostVar *hostVar = (HostVar *)hostVarTree->getChild(0); result += hostVar->getName(); } result += ")"; if (indexExpr_) result += ("KEY BY " + ((ColReference *)indexExpr_)->getColRefNameObj().getColName()); return result; } // returns the name of the exposed index of the Rowset const NAString Rowset::getIndexName() const { // A hack to check if the Rowset has an index expression NAString result("",CmpCommon::statementHeap()); if (indexExpr_) result += ((ColReference *)indexExpr_)->getColRefNameObj().getColName(); return(result); } // ----------------------------------------------------------------------- // methods for class Rowset // ----------------------------------------------------------------------- // Constructor RowsetRowwise::RowsetRowwise(RelExpr * childExpr, CollHeap* oHeap) : Rowset(NULL, NULL, NULL, childExpr, oHeap) { } // RowsetRowwise::RowsetRowwise() RelExpr * RowsetRowwise::copyTopNode(RelExpr *derivedNode, CollHeap* oHeap) { Rowset *result; if (derivedNode == NULL) result = new (oHeap) RowsetRowwise(NULL, oHeap); else { result = (RowsetRowwise *) derivedNode; } return Rowset::copyTopNode(result,oHeap); } // RowsetRowwise::copyTopNode() const NAString RowsetRowwise::getText() const { NAString result("RowSet Rowwise",CmpCommon::statementHeap()); return result; } Int32 RowsetRowwise::getArity() const { return 1; } // Rowset::getArity() RowsetFor::RowsetFor(RelExpr *child, ItemExpr *inputSizeExpr, ItemExpr *outputSizeExpr, ItemExpr *indexExpr, ItemExpr *maxSizeExpr, ItemExpr *maxInputRowlen, ItemExpr *rwrsBuffer, ItemExpr *partnNum, CollHeap *oHeap) : RelExpr(REL_ROWSETFOR,child,NULL,oHeap), inputSizeExpr_(inputSizeExpr), outputSizeExpr_(outputSizeExpr), indexExpr_(indexExpr), maxSizeExpr_(maxSizeExpr), maxInputRowlen_(maxInputRowlen), rwrsBuffer_(rwrsBuffer), partnNum_(partnNum), rowwiseRowset_(FALSE), packedFormat_(FALSE), compressed_(FALSE), dcompressInMaster_(FALSE), compressInMaster_(FALSE), partnNumInBuffer_(FALSE) { setNonCacheable(); } // Destructor. RowsetFor::~RowsetFor() { } RelExpr * RowsetFor::copyTopNode(RelExpr *derivedNode, CollHeap* oHeap) { RowsetFor *result; if (derivedNode == NULL) result = new (oHeap) RowsetFor(NULL, inputSizeExpr_, outputSizeExpr_, indexExpr_, maxSizeExpr_, maxInputRowlen_, rwrsBuffer_, partnNum_, oHeap); else result = (RowsetFor *) derivedNode; result->rowwiseRowset_ = rowwiseRowset_; result->setBufferAttributes(packedFormat_, compressed_, dcompressInMaster_, compressInMaster_, partnNumInBuffer_); return RelExpr::copyTopNode(result,oHeap); } Int32 RowsetFor::getArity() const { return 1; } // RowsetFor::getArity() const NAString RowsetFor::getText() const { NAString result("RowSetFor ", CmpCommon::statementHeap()); if (inputSizeExpr_) { if (inputSizeExpr_->getOperatorType() == ITM_CONSTANT) { char str[TEXT_DISPLAY_LENGTH]; sprintf(str, PF64, ((ConstValue *)inputSizeExpr_)->getExactNumericValue()); result += "INPUT SIZE "; result += str; } else if (inputSizeExpr_->getOperatorType() == ITM_HOSTVAR) result += "INPUT SIZE " + ((HostVar *)inputSizeExpr_)->getName(); else result += "INPUT SIZE ??"; if (outputSizeExpr_ || indexExpr_) result += ","; } if (outputSizeExpr_) { if (outputSizeExpr_->getOperatorType() == ITM_CONSTANT) { char str[TEXT_DISPLAY_LENGTH]; sprintf(str, PF64, ((ConstValue *)outputSizeExpr_)->getExactNumericValue()); result += "OUTPUT SIZE "; result += str; } else if (outputSizeExpr_->getOperatorType() == ITM_HOSTVAR) result += "OUTPUT SIZE " + ((HostVar *)outputSizeExpr_)->getName(); else result += "OUTPUT SIZE ??"; if (indexExpr_) result += ","; } if (indexExpr_) result += ("KEY BY " + ((ColReference *)indexExpr_)->getColRefNameObj().getColName()); return result; } // ----------------------------------------------------------------------- // methods for class RowsetInto // ----------------------------------------------------------------------- // Constructor RowsetInto::RowsetInto(RelExpr *child, ItemExpr *outputHostvars, ItemExpr *sizeExpr, CollHeap* oHeap) : RelExpr(REL_ROWSET_INTO,child,NULL,oHeap), outputHostvars_(outputHostvars), sizeExpr_(sizeExpr), requiredOrderTree_(NULL) { setNonCacheable(); requiredOrder_.clear(); } // RowsetInto::RowsetInto() // Destructor. RowsetInto::~RowsetInto() { } // RowsetInto::~RowsetInto() RelExpr * RowsetInto::copyTopNode(RelExpr *derivedNode, CollHeap* oHeap) { RowsetInto *result; if (derivedNode == NULL) result = new (oHeap) RowsetInto(NULL, outputHostvars_, sizeExpr_, oHeap); else result = (RowsetInto *) derivedNode; return RelExpr::copyTopNode(result,oHeap); } // RowsetInto::copyTopNode() Int32 RowsetInto::getArity() const { return 1; // This select-list root node } // RowsetInto::getArity() const NAString RowsetInto::getText() const { NAString result("RowsetINTO",CmpCommon::statementHeap()); if (sizeExpr_) { if (sizeExpr_->getOperatorType() == ITM_CONSTANT) { char str[TEXT_DISPLAY_LENGTH]; sprintf(str, " " PF64 , ((ConstValue *)sizeExpr_)->getExactNumericValue()); result += str; } else if (sizeExpr_->getOperatorType() == ITM_HOSTVAR) result += " " + ((HostVar *)sizeExpr_)->getName(); else result += " ??"; } result += " ("; for (ItemExpr *hostVarTree = outputHostvars_; hostVarTree != NULL; hostVarTree = hostVarTree->child(1)) { if (outputHostvars_ != hostVarTree) result += ", "; HostVar *hostVar = (HostVar *)hostVarTree->getChild(0); result += hostVar->getName(); } result += ")"; return result; } NABoolean RelExpr::treeContainsEspExchange() { Lng32 nc = getArity(); if (nc > 0) { if ((getOperatorType() == REL_EXCHANGE) && (child(0)->castToRelExpr()->getPhysicalProperty()->getPlanExecutionLocation() != EXECUTE_IN_DP2)) { return TRUE; } for (Lng32 i = 0; i < nc; i++) { if (child(i)->treeContainsEspExchange()) return TRUE; } } return FALSE; } NABoolean Exchange::areProbesHashed(const ValueIdSet pkey) { return getGroupAttr()->getCharacteristicInputs().contains(pkey); } void Exchange::computeBufferLength(const Context *myContext, const CostScalar &numConsumers, const CostScalar &numProducers, CostScalar &upMessageBufferLength, CostScalar &downMessageBufferLength) { CostScalar numDownBuffers = (Int32) ActiveSchemaDB()->getDefaults().getAsULong (GEN_SNDT_NUM_BUFFERS); CostScalar numUpBuffers = (Int32) ActiveSchemaDB()->getDefaults().getAsULong (GEN_SNDB_NUM_BUFFERS); CostScalar maxOutDegree = MAXOF(numConsumers, numProducers); CostScalar upSizeOverride = ActiveSchemaDB()->getDefaults().getAsLong (GEN_SNDT_BUFFER_SIZE_UP); // The adjustment is a fudge factor to improve scalability by // reducing the buffer size // "penalty" when the number of connections is high due //to a high degree of parallelism. // The net result is to increase the memory "floor" and "ceiling" // (that are base d on the // number of connections) by up to fourfold. //Too high a ceiling can cause memory pressure, // a high level of paging activity, etc., //while too low a ceiling can cause a large // number of IPC messages and dispatches, and a // resultant increase in path lengt h. // The adjustment attempts to strike a balance between // the two opposing clusters of performance factors. CostScalar adjMaxNumConnections = maxOutDegree < 32 || upSizeOverride == 1 || upSizeOverride > 2 ? maxOutDegree : maxOutDegree < 64 ? 32 : maxOutDegree < 128 ? 40 : maxOutDegree < 256 ? 50 : maxOutDegree < 512 ? 64 : 70; CostScalar overhead = CostScalar(50); // compute numProbes, probeSize, cardinality, outputSize CostScalar downRecordLength = getGroupAttr()-> getCharacteristicInputs().getRowLength(); CostScalar upRecordLength = getGroupAttr()-> getCharacteristicOutputs().getRowLength(); const CostScalar & numOfProbes = ( myContext->getInputLogProp()->getResultCardinality() ).minCsOne(); // use no more than 50 KB and try to send all rows down in a single message CostScalar reasonableBufferSpace1 = CostScalar(50000) / (maxOutDegree * numDownBuffers); reasonableBufferSpace1 = MINOF(reasonableBufferSpace1, (downRecordLength + overhead) * numOfProbes); const EstLogPropSharedPtr inputLP = myContext->getInputLogProp(); CostScalar numRowsUp = child(0).outputLogProp(inputLP)-> getResultCardinality(); const PartitioningFunction* const parentPartFunc = myContext->getPlan()->getPhysicalProperty()->getPartitioningFunction(); if (parentPartFunc->isAReplicateViaBroadcastPartitioningFunction()) numRowsUp = numRowsUp * numConsumers; // check for an overriding define for the buffer size CostScalar downSizeOverride = ActiveSchemaDB()->getDefaults().getAsLong (GEN_SNDT_BUFFER_SIZE_DOWN); if (downSizeOverride.isGreaterThanZero()) reasonableBufferSpace1 = downSizeOverride; // we MUST be able to fit at least one row into a buffer CostScalar controlAppendedLength= ComTdbSendTop::minSendBufferSize( (Lng32)downRecordLength.getValue()); downMessageBufferLength = MAXOF(controlAppendedLength, reasonableBufferSpace1); // Total size of output buffer that needs to be sent to the parent. CostScalar totalBufferSize = upRecordLength * numRowsUp; // Divide this by number of connections to get total buffer per connection. CostScalar bufferSizePerConnection = totalBufferSize / adjMaxNumConnections; // Aim for a situation where atleast 80 messages are sent per connection. CostScalar reasonableBufferSpace2 = bufferSizePerConnection / ActiveSchemaDB() ->getDefaults().getAsLong(GEN_EXCHANGE_MSG_COUNT); // Now Esp has numUpBuffers of size reasonableBufferSpace2 per // each stream (connection), so total memory to be allocated // in this Esp would be: // reasonableBufferSpace2 * numUpBuffers * maxOutDegree. // We need to apply ceiling and floor to this memory i.e.: // 4MB > reasonableBufferSpace2 * numUpBuffers * maxOutDegree > 50KB. // OR divide both ceiling and floor by numUpBuffers * maxOutDegree. Int32 maxMemKB = ActiveSchemaDB() ->getDefaults().getAsLong(GEN_EXCHANGE_MAX_MEM_IN_KB); if (maxMemKB <= 0) maxMemKB = 4000; // 4MB if not set or negative CostScalar maxMem1 = maxMemKB * 1000; CostScalar maxMem2 = maxMemKB * 4000; CostScalar ceiling = MINOF(maxMem1 / (numUpBuffers * adjMaxNumConnections), maxMem2 / (numUpBuffers * maxOutDegree)); CostScalar floor = MINOF(CostScalar(50000) / (numUpBuffers * adjMaxNumConnections), CostScalar(200000) / (numUpBuffers * maxOutDegree)); // Apply the floor. reasonableBufferSpace2 = MAXOF(floor, reasonableBufferSpace2); // Apply the ceiling. reasonableBufferSpace2 = MINOF(ceiling, reasonableBufferSpace2); // Make sure the floor is at least 5K to avoid performance problem. reasonableBufferSpace2 = MAXOF(CostScalar(5000), reasonableBufferSpace2); // Make sure that it is at most 31k-1356 reasonableBufferSpace2 = MINOF( reasonableBufferSpace2, 31 * 1024 - 1356); if (upSizeOverride.isGreaterThanZero()) reasonableBufferSpace2 = upSizeOverride; // we MUST be able to fit at least one row into a buffer controlAppendedLength = ComTdbSendTop::minReceiveBufferSize( (Lng32) (upRecordLength.getValue()) ); upMessageBufferLength = MAXOF( controlAppendedLength, reasonableBufferSpace2); // convert Buffers to kilo bytes upMessageBufferLength_= upMessageBufferLength = upMessageBufferLength/CostScalar(1024); downMessageBufferLength_ = downMessageBufferLength = downMessageBufferLength/ CostScalar(1024); } // Exchange::computeBufferLength() ////////////////////////////////////////////////////////////////////// // Class pcgEspFragment related methods ////////////////////////////////////////////////////////////////////// void pcgEspFragment::addChild(Exchange* esp) { CollIndex newIndex = childEsps_.entries(); childEsps_.insertAt(newIndex, esp); } // Verify that the newly added exchange node at the end of childEsps_[] // is compatible with others. // Note that preCodeGen traversal the query tree via a depth-first // search. Each time the leave exchange node in this fragment is encountered, // this method is called, The order of visit to the child exchanges // is from left to right. // NABoolean pcgEspFragment::tryToReduceDoP() { float threshold; ActiveSchemaDB()-> getDefaults().getFloat(DOP_REDUCTION_ROWCOUNT_THRESHOLD, threshold); if ( threshold == 0.0 || getTotaleRows() >= threshold ) { return FALSE; } // Defensive programming. Nothing to verify when there is no child esp. if ( childEsps_.entries() == 0 ) return FALSE; // Get the ptr to last exchange CollIndex lastIdx = childEsps_.entries()-1; Exchange* xch = childEsps_[lastIdx]; // // No dop reduction for Parallel Extract // if ( xch->getExtractProducerFlag() || xch->getExtractConsumerFlag() ) return FALSE; PartitioningFunction* partFunc = xch->getPhysicalProperty()->getPartitioningFunction(); // // If xch's count of partitions is less than newDoP, bail out // Lng32 newDoP = CURRSTMT_OPTDEFAULTS->getDefaultDegreeOfParallelism(); if ( partFunc->getCountOfPartitions() < newDoP ) return FALSE; // Do not reduce dop if this exchange is a PA, except if it is // the right child of a TYPE2 join, using replicate-no-broadcast. // An extra exchange is needed otherwise to bridge the // new DoP and all original partitions, unless the newDoP is a factor // of #part of the hash2 partfunc for the PA node. // if ( xch->child(0)->getPhysicalProperty() ->getPlanExecutionLocation() == EXECUTE_IN_DP2) { if ( partFunc->isAHash2PartitioningFunction() ) { if ( partFunc->getCountOfPartitions() % newDoP != 0 ) return FALSE; } else if (!partFunc->isAReplicateNoBroadcastPartitioningFunction()) return FALSE; } Lng32 suggestedNewDoP = newDoP; // // Make a copy of the part func as the scaling method can side effect. // PartitioningFunction* partFuncCopy = xch->getPhysicalProperty()->getPartitioningFunction()->copy(); PartitioningFunction* newPF = partFuncCopy->scaleNumberOfPartitions(suggestedNewDoP); // // If the part func can not scale to newDoP, bail out. // if ( suggestedNewDoP != newDoP ) return FALSE; // // Find a common dop for all child esps in the fragment first. // A common dop is one associated with 1st esp that has non- // broadcasting part func. All other child esps with non-broadcasting // partFunc should be use the "common dop". This is true prior to // the dop reduction attempt. If it is already found (commonDoP_ > 0), // just use it. // if ( commonDoP_ == 0 && partFuncCopy->isAReplicationPartitioningFunction() == FALSE ) commonDoP_ = partFuncCopy->getCountOfPartitions(); // If the dop at child exchange A can be reduced but not at // child exchange B, we may end up with in an inconsistent state. // The following code detects it. if ( commonDoP_ > 0 ) { if ( partFuncCopy->isAReplicationPartitioningFunction() == FALSE && partFuncCopy->getCountOfPartitions() != commonDoP_ ) return FALSE; } // // The new dop is acceptable. // newDoP_ = newDoP; setValid(TRUE); return TRUE; } void pcgEspFragment::invalidate() { setValid(FALSE); //for ( CollIndex i=0; i<childEsps_.entries(); i++ ) { // childEsps_[i]->getEspFragPCG()->invalidate(); //} } void pcgEspFragment::adjustDoP(Lng32 newDop) { for ( CollIndex i=0; i<childEsps_.entries(); i++ ) { Exchange* xch = childEsps_[i]; // Recursively adjust the dop for my child fragments. // Each exchange will have its own pcgEspFragment to work with. xch->doDopReduction(); } } void RelExpr::doDopReduction() { Int32 nc = getArity(); for (Lng32 i = 0; i < nc; i++) { child(i)->doDopReduction(); } } void Exchange::doDopReduction() { // // Once this method is called for the top most Exchange, we can // recursively call the same method for all the esp fragments via // the pointers (to esps) saved in the pcgEsgFragment objects. // Lng32 newDop = getEspFragPCG()->getNewDop(); if ( getEspFragPCG()->isValid() ) { // Adjust the partfunc for all nodes within the fragment, starting // from my child and down to every bottom-defining exchanges. child(0)->doDopReductionWithinFragment(newDop); } // Next recursively call the same method for all fragments below me. getEspFragPCG()->adjustDoP(newDop); } void RelExpr::doDopReductionWithinFragment(Lng32 newDoP) { adjustTopPartFunc(newDoP); if ( getOperatorType() == REL_EXCHANGE ) { // // Need to adjust the Logical part of the part func if // my child's part func is a LogPhy partfunc. // if ( child(0)->getPhysicalProperty()->getPlanExecutionLocation() == EXECUTE_IN_DP2) { PartitioningFunction *pf = child(0)->getPhysicalProperty()->getPartitioningFunction(); if ( pf->isALogPhysPartitioningFunction() ) child(0)->adjustTopPartFunc(newDoP); } return; } Int32 nc = getArity(); for (Lng32 i = 0; i < nc; i++) { child(i)->doDopReductionWithinFragment(newDoP); } } void RelExpr::adjustTopPartFunc(Lng32 newDop) { ((PhysicalProperty*)getPhysicalProperty())->scaleNumberOfPartitions(newDop); setDopReduced(TRUE); } // Required Resource Estimate Methods - Begin void RelExpr::computeRequiredResources(RequiredResources & reqResources, EstLogPropSharedPtr & inLP) { Int32 nc = getArity(); for (Lng32 i = 0; i < nc; i++) { if (child(i)) child(i)->computeRequiredResources(reqResources, inLP); else child(i).getLogExpr()->computeRequiredResources(reqResources, inLP); } computeMyRequiredResources(reqResources, inLP); } void Join::computeRequiredResources(RequiredResources & reqResources, EstLogPropSharedPtr & inLP) { Int32 nc = getArity(); if (child(0)) child(0)->computeRequiredResources(reqResources, inLP); else child(0).getLogExpr()->computeRequiredResources(reqResources, inLP); EstLogPropSharedPtr inputForRight = inLP; EstLogPropSharedPtr leftOutput = child(0).getGroupAttr()->outputLogProp(inLP); if(isTSJ()) { inputForRight = leftOutput; } if (child(1)) child(1)->computeRequiredResources(reqResources, inputForRight); else child(1).getLogExpr()->computeRequiredResources(reqResources, inputForRight); computeMyRequiredResources(reqResources, inLP); } void RequiredResources::accumulate(CostScalar memRsrcs, CostScalar cpuRsrcs, CostScalar dataAccessCost, CostScalar maxCard) { memoryResources_ += memRsrcs; cpuResources_ += cpuRsrcs; dataAccessCost_ += dataAccessCost; if(maxOperMemReq_ < memRsrcs) maxOperMemReq_ = memRsrcs; if(maxOperCPUReq_ < cpuRsrcs) maxOperCPUReq_ = cpuRsrcs; if(maxOperDataAccessCost_ < dataAccessCost) maxOperDataAccessCost_ = dataAccessCost; if(maxMaxCardinality_ < maxCard) maxMaxCardinality_ = maxCard; } void RelExpr::computeMyRequiredResources(RequiredResources & reqResources, EstLogPropSharedPtr & inLP) { CostScalar cpuResourcesRequired = csZero; CostScalar A = csOne; CostScalar B (getDefaultAsDouble(WORK_UNIT_ESP_DATA_COPY_COST)); Int32 nc = getArity(); for (Lng32 i = 0; i < nc; i++) { GroupAttributes * childGroupAttr = child(i).getGroupAttr(); CostScalar childCardinality = childGroupAttr->outputLogProp(inLP)->getResultCardinality(); CostScalar childRecordSize = childGroupAttr->getCharacteristicOutputs().getRowLength(); cpuResourcesRequired += (A * childCardinality) + (B * childCardinality * childRecordSize ); } CostScalar myMaxCard = getGroupAttr()->getResultMaxCardinalityForInput(inLP); reqResources.accumulate(csZero, cpuResourcesRequired, csZero, myMaxCard); } void RelRoot::computeMyRequiredResources(RequiredResources & reqResources, EstLogPropSharedPtr & inLP) { if (hasOrderBy()) { CostScalar memoryResourcesRequired = csZero; GroupAttributes * childGroupAttr = child(0).getGroupAttr(); CostScalar childCardinality = childGroupAttr->outputLogProp(inLP)->getResultCardinality(); CostScalar childRecordSize = childGroupAttr->getCharacteristicOutputs().getRowLength(); memoryResourcesRequired = (childCardinality * childRecordSize); reqResources.accumulate(memoryResourcesRequired, csZero, csZero); } // add the cpu resources RelExpr::computeMyRequiredResources(reqResources, inLP); } void MultiJoin::computeMyRequiredResources(RequiredResources & reqResources, EstLogPropSharedPtr & inLP) { // get the subset analysis for this MultiJoin JBBSubsetAnalysis * subsetAnalysis = getJBBSubset().getJBBSubsetAnalysis(); subsetAnalysis->computeRequiredResources(this,reqResources, inLP); } void Join::computeMyRequiredResources(RequiredResources & reqResources, EstLogPropSharedPtr & inLP) { CostScalar memoryResourcesRequired = csZero; // only get the max card for this join. The contribution from the children // of this join is done inside Join::computeReequiredResource() where // child(i)->computeRequiredResources() is called (i=0,1). These two calls // will call ::computeMyRequiredResoruce() of the corresponding RelExpr. // GroupAttributes * myGroupAttr = getGroupAttr(); CostScalar myMaxCard = myGroupAttr->getResultMaxCardinalityForInput(inLP); reqResources.accumulate(csZero, csZero, csZero, myMaxCard); if(!isTSJ()) { GroupAttributes * innerChildGroupAttr = child(1).getGroupAttr(); CostScalar innerChildCardinality = innerChildGroupAttr->outputLogProp(inLP)->getResultCardinality(); CostScalar innerChildRecordSize = innerChildGroupAttr->getCharacteristicOutputs().getRowLength(); memoryResourcesRequired = (innerChildCardinality * innerChildRecordSize); reqResources.accumulate(memoryResourcesRequired, csZero, csZero); // add the cpu resources RelExpr::computeMyRequiredResources(reqResources, inLP); } else{ // isTSJ() == TRUE CostScalar cpuResourcesRequired = csZero; CostScalar A = csOne; CostScalar B (getDefaultAsDouble(WORK_UNIT_ESP_DATA_COPY_COST)); Int32 nc = getArity(); EstLogPropSharedPtr inputForChild = inLP; for (Lng32 i = 0; i < nc; i++) { GroupAttributes * childGroupAttr = child(i).getGroupAttr(); CostScalar childCardinality = childGroupAttr->outputLogProp(inputForChild)->getResultCardinality(); CostScalar childRecordSize = childGroupAttr->getCharacteristicOutputs().getRowLength(); cpuResourcesRequired += (B * childCardinality * childRecordSize ); // do this only for the left child if(i < 1) cpuResourcesRequired += (A * childCardinality); inputForChild = child(i).getGroupAttr()->outputLogProp(inputForChild); } reqResources.accumulate(csZero, cpuResourcesRequired, csZero); } } void GroupByAgg::computeMyRequiredResources(RequiredResources & reqResources, EstLogPropSharedPtr & inLP) { CostScalar memoryResourcesRequired = csZero; GroupAttributes * childGroupAttr = child(0).getGroupAttr(); CostScalar childCardinality = childGroupAttr->outputLogProp(inLP)->getResultCardinality(); CostScalar childRecordSize = childGroupAttr->getCharacteristicOutputs().getRowLength(); memoryResourcesRequired = (childCardinality * childRecordSize); reqResources.accumulate(memoryResourcesRequired, csZero, csZero); // add the cpu resources RelExpr::computeMyRequiredResources(reqResources, inLP); } void Scan::computeMyRequiredResources(RequiredResources & reqResources, EstLogPropSharedPtr & inLP) { if(!(QueryAnalysis::Instance() && QueryAnalysis::Instance()->isAnalysisON())) return; //Get a handle to ASM AppliedStatMan * appStatMan = QueryAnalysis::ASM(); const TableAnalysis * tAnalysis = getTableDesc()->getTableAnalysis(); CANodeId tableId = tAnalysis->getNodeAnalysis()->getId(); // Find index joins and index-only scans addIndexInfo(); // Base table scan is one of the index only scans. CostScalar cpuCostIndexOnlyScan = computeCpuResourceForIndexOnlyScans(tableId); CostScalar cpuCostIndexJoinScan = computeCpuResourceForIndexJoinScans(tableId); CostScalar cpuResourcesRequired = cpuCostIndexOnlyScan; if ( getTableDesc()->getNATable()->isHbaseTable()) { if ( cpuCostIndexJoinScan < cpuResourcesRequired ) cpuResourcesRequired = cpuCostIndexJoinScan; } CostScalar dataAccessCost = tAnalysis->getFactTableNJAccessCost(); if(dataAccessCost < 0) { CostScalar rowsToScan = appStatMan-> getStatsForLocalPredsOnCKPOfJBBC(tableId)-> getResultCardinality(); CostScalar numOfProbes(csZero); // skip this for fact table under nested join dataAccessCost = tAnalysis->computeDataAccessCostForTable(numOfProbes, rowsToScan); } CostScalar myMaxCard = getGroupAttr()->getResultMaxCardinalityForInput(inLP); reqResources.accumulate(csZero, cpuResourcesRequired, dataAccessCost, myMaxCard ); } // Required Resource Estimate Methods - End CostScalar Scan::computeCpuResourceRequired(const CostScalar& rowsToScan, const CostScalar& rowSize) { CostScalar A = csOne; CostScalar B (getDefaultAsDouble(WORK_UNIT_ESP_DATA_COPY_COST)); CostScalar cpuResourcesRequired = (B * rowsToScan * rowSize); cpuResourcesRequired += (A * rowsToScan); return cpuResourcesRequired; } CostScalar Scan::computeCpuResourceForIndexOnlyScans(CANodeId tableId) { // If index only scans are available, find the most // promising index and compute the CPU resource for it. const SET(IndexProperty *)& indexOnlyScans = getIndexOnlyIndexes(); IndexProperty* smallestIndex = findSmallestIndex(indexOnlyScans); if ( !smallestIndex ) return COSTSCALAR_MAX; IndexDesc* iDesc = smallestIndex->getIndexDesc(); const ValueIdList &ikeys = iDesc->getIndexKey(); AppliedStatMan * appStatMan = QueryAnalysis::ASM(); EstLogPropSharedPtr estLpropPtr = appStatMan-> getStatsForLocalPredsOnPrefixOfColList(tableId, ikeys); if ( !(estLpropPtr.get()) ) return COSTSCALAR_MAX; return computeCpuResourceRequired(estLpropPtr->getResultCardinality(), iDesc->getRecordLength() ); } CostScalar Scan::computeCpuResourceForIndexJoinScans(CANodeId tableId) { // If index scans are available, find the index with most promising and // compute the CPU resource for it. const LIST(ScanIndexInfo *)& scanIndexJoins = getPossibleIndexJoins(); if ( scanIndexJoins.entries() == 0 ) return COSTSCALAR_MAX; IndexProperty* smallestIndex = findSmallestIndex(scanIndexJoins); IndexDesc* iDesc = smallestIndex->getIndexDesc(); CostScalar rowsToScan; return computeCpuResourceForIndexJoin(tableId, iDesc, iDesc->getIndexKey(), rowsToScan); } CostScalar Scan::computeCpuResourceForIndexJoin(CANodeId tableId, IndexDesc* iDesc, ValueIdSet& indexPredicates, CostScalar& rowsToScan) { ValueIdList ikeysCovered; UInt32 sz = iDesc->getIndexKey().entries(); for (CollIndex i=0; i<sz; i++) { ValueId x = iDesc->getIndexKey()[i]; if ( indexPredicates.containsAsEquiLocalPred(x) ) ikeysCovered.insertAt(i, x); else break; } return computeCpuResourceForIndexJoin(tableId, iDesc, ikeysCovered, rowsToScan); } CostScalar Scan::computeCpuResourceForIndexJoin(CANodeId tableId, IndexDesc* iDesc, const ValueIdList& ikeys, CostScalar& rowsToScan) { AppliedStatMan * appStatMan = QueryAnalysis::ASM(); EstLogPropSharedPtr estLpropPtr = appStatMan-> getStatsForLocalPredsOnPrefixOfColList(tableId, ikeys); if ( !(estLpropPtr.get()) ) { rowsToScan = COSTSCALAR_MAX; return COSTSCALAR_MAX; } rowsToScan = estLpropPtr->getResultCardinality(); CostScalar rowSize = iDesc->getRecordLength(); CostScalar cpuResourceForIndex = computeCpuResourceRequired(rowsToScan, rowSize); rowSize = getTableDesc()->getClusteringIndex()->getRecordLength(); CostScalar cpuResourceForBaseTable = computeCpuResourceRequired(rowsToScan, rowSize); return cpuResourceForIndex + cpuResourceForBaseTable; } IndexProperty* Scan::findSmallestIndex(const SET(IndexProperty *)& indexes) const { CollIndex entries = indexes.entries(); if ( entries == 0 ) return NULL; IndexProperty* smallestIndex = indexes[0]; for (CollIndex i=1; i<entries; i++ ) { IndexProperty* current = indexes[i]; if ( smallestIndex->compareIndexPromise(current) == LESS ) { smallestIndex = current; } } return smallestIndex; } IndexProperty* Scan::findSmallestIndex(const LIST(ScanIndexInfo *)& possibleIndexJoins) const { CollIndex entries = possibleIndexJoins_.entries(); if ( entries == 0 ) return NULL; IndexProperty* smallestIndex = findSmallestIndex(possibleIndexJoins[0]->usableIndexes_); for (CollIndex i=1; i<entries; i++ ) { IndexProperty* current = findSmallestIndex(possibleIndexJoins[i]->usableIndexes_); if ( smallestIndex->compareIndexPromise(current) == LESS ) { smallestIndex = current; } } return smallestIndex; } // This function checks if the passed RelExpr is a UDF rule created by a CQS // (REL_FORCE_ANY_SCALAR_UDF). If not, then RelExpr::patternMatch() is called. // If the CQS rule includes the UDF name this name is checked against the routine // name of this physical isolated scalar UDF. If the CQS rule includes the action // name, then this is checked against the action name of this physical isolated // scalar UDF as well. The function returns TRUE if so, otherwise FALSE. NABoolean PhysicalIsolatedScalarUDF::patternMatch(const RelExpr & other) const { // Check if CQS is a scalar UDF rule. if (other.getOperatorType() == REL_FORCE_ANY_SCALAR_UDF) { UDFForceWildCard &w = (UDFForceWildCard &) other; // Check function name, if specified in UDFForceWildCard. if (w.getFunctionName() != "") { QualifiedName funcName(w.getFunctionName(), 1 /* minimal 1 part name */); // Compare catalog, schema and udf parts separately, // if they exist in the wildcard const NAString& catName = funcName.getCatalogName(); const NAString& schName = funcName.getSchemaName(); const QualifiedName& x = getRoutineName(); if ((catName.length() > 0 && x.getCatalogName() != catName) || (schName.length() > 0 && x.getSchemaName() != schName) || x.getObjectName() != funcName.getObjectName()) return FALSE; } // Check action name, if specified in UDFForceWildCard. if (w.getActionName() != "") { NAString actionName = w.getActionName(); if (getActionNARoutine() && getActionNARoutine()->getActionName()) { // Compare only object parts. Right now actions don't support catalogs and schemas. // This is because action names can have a leading '$' as part of name. const NAString& x = *(getActionNARoutine()->getActionName()); if (x != actionName) return FALSE; } else return FALSE; } return TRUE; } else return RelExpr::patternMatch(other); } const NAString RelExpr::getCascadesTraceInfoStr() { NAString result("RelExpr Cascades Trace Info:\n"); result += " parent taskid: " + istring(getParentTaskId()) + "\n"; result += " sub taskid: " + istring(getSubTaskId()) + "\n"; result += " birth id: " + istring(getBirthId()) + "\n"; result += " memo exprid: " + istring(memoExprId_) + "\n"; result += " source memo exprid: " + istring(sourceMemoExprId_) + "\n"; result += " source groupid: " + istring(sourceGroupId_) + "\n"; char costLimitStr[50]; sprintf(costLimitStr," cost limit %g\n", costLimit_); result += costLimitStr; return result; } // remember the creator and source of this relexpr for cascades display gui void RelExpr::setCascadesTraceInfo(RelExpr *src) { CascadesTask * currentTask = CURRSTMT_OPTDEFAULTS->getCurrentTask(); if (currentTask) { // current task created this relexpr parentTaskId_ = currentTask->getParentTaskId(); stride_ = currentTask->getSubTaskId(); // remember time of my birth birthId_ = CURRSTMT_OPTDEFAULTS->getTaskCount(); // remember my source sourceGroupId_ = currentTask->getGroupId(); if (src) sourceMemoExprId_ = src->memoExprId_; // remember current task's context's CostLimit Context * context = currentTask->getContext(); if(context && context->getCostLimit()) costLimit_ = context->getCostLimit()->getCachedValue(); } // get my MemoExprId and advance it memoExprId_ = CURRSTMT_OPTDEFAULTS->updateGetMemoExprCount(); } NABoolean Join::childNodeContainSkew( CollIndex i, // IN: which child const ValueIdSet& joinPreds, // IN: the join predicate double threshold, // IN: the threshold SkewedValueList** skList // OUT: the skew list ) const { // Can not deal with multicolumn skew in this method. if ( joinPreds.entries() != 1 ) return FALSE; NABoolean statsExist; // a place holder Int32 skews = 0; for(ValueId vid = joinPreds.init(); joinPreds.next(vid); joinPreds.advance(vid)) { *skList = child(i).getGroupAttr()-> getSkewedValues(vid, threshold, statsExist, (*GLOBAL_EMPTY_INPUT_LOGPROP), isLeftJoin()/* include skewed NULLs only for left outer join */ ); if (*skList == NULL || (*skList)->entries() == 0) break; else skews++; } return ( skews == joinPreds.entries() ); } // // Check if some join column is of a SQL type whose run-time // implementation has a limitation for SB to work. // // return // TRUE: no limitation // FALSE: has limitation and SB should not be applied // NABoolean Join::singleColumnjoinPredOKforSB(ValueIdSet& joinPreds) { ValueId vId((CollIndex)0); joinPreds.next(vId); ItemExpr* iePtr = vId.getItemExpr(); if (iePtr->getOperatorType() == ITM_INSTANTIATE_NULL) { iePtr = iePtr -> child(0); } ValueIdSet vidSet; switch (iePtr->getOperatorType()) { case ITM_EQUAL: // this case is used to handle char type when // no VEG is formed for a char predicate, // or joins involving subqueries. case ITM_VEG_PREDICATE: case ITM_VEG_REFERENCE: // We only care columns of type ITM_BASECOLUMN (columns belonging to // base tables or table-valued stored procedures, see comment on class // BaseColumn). iePtr->findAll(ITM_BASECOLUMN, vidSet, TRUE, TRUE); // If no such columns can be found. Do not bother to continue further, // as only base table columns have the potential to be big and skewed. if ( vidSet.entries() == 0 ) return FALSE; break; default: return FALSE; } ValueId colVid((CollIndex)0); vidSet.next(colVid); if ( !colVid.getType().isSkewBusterSupportedType() ) return FALSE; // Additional test if ( colVid.getType().getTypeQualifier() == NA_NUMERIC_TYPE && colVid.getType().getTypeName() == LiteralNumeric ) { // Exact decimal numeric such as NUMERIC(18,15) can be handled, if // all columns involved in join are of the exact same precision and // and scale. The comparison ignores NULL attribute of the type (ALM 4953). for(ValueId x = vidSet.init(); vidSet.next(x); vidSet.advance(x)) { if ( NOT ((NumericType&)(colVid.getType())).equalIgnoreNull(x.getType())) return FALSE; } return TRUE; } else if ( DFS2REC::isAnyCharacter(colVid.getType().getFSDatatype()) ) { if ( ((const CharType&)colVid.getType()).getStrCharLimit() > (Lng32) CmpCommon::getDefaultNumeric(USTAT_MAX_CHAR_BOUNDARY_LEN) ) return FALSE; } return TRUE; } NABoolean Join::multiColumnjoinPredOKforSB(ValueIdSet& joinPreds) { for(ValueId x = joinPreds.init(); joinPreds.next(x); joinPreds.advance(x)) { ValueIdSet dummy(x); if ( !singleColumnjoinPredOKforSB(dummy) ) return FALSE; } return TRUE; } // The new way to capture MC skews. All such skews have been computed during // update stats. NABoolean Join::childNodeContainMultiColumnSkew( CollIndex i, // IN: which child to work on const ValueIdSet& joinPreds, // IN: the join predicate double mc_threshold, // IN: multi-column threshold Lng32 countOfPipelines, // IN: SkewedValueList** skList // OUT: the skew list ) { if (joinPreds.entries() <= 1) return FALSE; const ColStatDescList& theColList = child(i).outputLogProp((*GLOBAL_EMPTY_INPUT_LOGPROP))->colStats(); ValueId col; ValueIdSet lhsCols; CollIndex index = NULL_COLL_INDEX; const ValueIdSet& joiningCols = (i==0) ? getEquiJoinExprFromChild0() : getEquiJoinExprFromChild1() ; for (col = joiningCols.init(); joiningCols.next(col); joiningCols.advance(col) ) { theColList.getColStatDescIndex(index, col); if (index != NULL_COLL_INDEX) lhsCols.insert(theColList[index]->getColumn()); } ValueIdList dummyList; const MCSkewedValueList* mcSkewList = ((ColStatDescList&)theColList).getMCSkewedValueListForCols(lhsCols, dummyList); if ( mcSkewList == NULL ) return FALSE; // Apply the frequency threshold to each MC skew and store those passing // the thredhold test to the new skList CostScalar rc = child(i).getGroupAttr()->getResultCardinalityForEmptyInput(); CostScalar thresholdFrequency = rc * mc_threshold; *skList = new (CmpCommon::statementHeap()) SkewedValueList((CmpCommon::statementHeap())); for ( CollIndex i=0; i<mcSkewList->entries(); i++ ) { MCSkewedValue* itm = mcSkewList->at(i); if ( itm->getFrequency() >= thresholdFrequency ) { // Use an EncodedValue object to represent the current MC skew // and transfer the hash value to it. The hash value is // computed in EncodedValue::computeRunTimeHashValue() and is // the run-time version! No modification should be done to it // from this point on. EncodedValue mcSkewed = itm->getHash(); (*skList)->insertInOrder(mcSkewed); } } // Set the run-time hash status flag so that we will not try to build // the run-time hash again in // SkewedDataPartitioningFunction::buildHashListForSkewedValues(). (*skList)->setComputeFinalHash(FALSE); if ( (*skList)->entries() == 0) return FALSE; return TRUE; } // The old way to guess MC skews and repartition the data stream on one // of the columns with least skews. NABoolean Join::childNodeContainMultiColumnSkew( CollIndex i, // IN: which child to work on const ValueIdSet& joinPreds, // IN: the join predicate double mc_threshold, // IN: multi-column threshold double sc_threshold, // IN: single-column threshold Lng32 countOfPipelines, // IN: SkewedValueList** skList, // OUT: the skew list ValueId& vidOfEquiJoinWithSkew // OUT: the valueId of the column // whose skew list is returned ) const { if (joinPreds.entries() <= 1) return FALSE; typedef SkewedValueList* SkewedValueListPtr; SkewedValueList** skewLists; skewLists = new(CmpCommon::statementHeap()) SkewedValueListPtr[joinPreds.entries()]; CostScalar* skewFactors = new(CmpCommon::statementHeap()) CostScalar[joinPreds.entries()]; // A list of valueIdSets, each valueIdSet element contains a set of // columns from the join predicates. Each set has all columns from the // same table participating in the join predicates. ARRAY(ValueIdSet) mcArray(joinPreds.entries()); Int32 skews = 0, leastSkewList = 0; EncodedValue mostFreqVal; CostScalar productOfSkewFactors = csOne; CostScalar productOfUecs = csOne; CostScalar minOfSkewFactor = csMinusOne; CostScalar rc = csMinusOne; CostScalar currentSkew; CollIndex j = 0; NABoolean statsExist; for(ValueId vid = joinPreds.init(); joinPreds.next(vid); joinPreds.advance(vid)) { // Get the skew values for the join predicate in question. skewLists[skews] = child(i).getGroupAttr()-> getSkewedValues(vid, sc_threshold, statsExist, (*GLOBAL_EMPTY_INPUT_LOGPROP), isLeftJoin() /* include skewed NULLs only for left outer join */ ); // When the skew list is null, there are two possibilities. // 1. No stats exists, here we assume the worse (stats has not been updated), and // move to the next join predicate. // 2. The stats is present but we could not detect skews (e.g., the skews are // too small to pass the threshold test). We return FALSE to indicate that the // column is good enough to smooth out the potential skews in other columns. if ( skewLists[skews] == NULL ) { if ( !statsExist ) continue; else return FALSE; // no stats exist } // Pick the shortest skew list seen so far. The final shortest skew list // will be used for run-time skew detection. if ( skews == 0 || (skewLists[skews] && skewLists[skews] -> entries() < skewLists[leastSkewList] -> entries() ) ) { // Obtain the colstat for the child of the join predicate on // the other side of the join. CollIndex brSide = (i==0) ? 1 : 0; ColStatsSharedPtr colStats = child(brSide).getGroupAttr()-> getColStatsForSkewDetection(vid, (*GLOBAL_EMPTY_INPUT_LOGPROP)); if ( colStats == NULL ) return FALSE; // no stats exist for the inner. assume the worst // get the skew list const FrequentValueList & skInner = colStats->getFrequentValues(); CollIndex index = 0; const SkewedValueList& newList = *skewLists[skews]; CostScalar totalFreq = csZero; const NAType* nt = newList.getNAType(); NABoolean useHash = nt->useHashRepresentation(); for (CollIndex index = 0; index < skInner.entries(); index++) { const FrequentValue& fv = skInner[index]; EncodedValue skew = ( useHash ) ? fv.getHash() : fv.getEncodedValue(); if ( nt->getTypeQualifier() == NA_NUMERIC_TYPE && nt->getTypeName() == LiteralNumeric ) { skew = fv.getEncodedValue().computeHashForNumeric((SQLNumeric*)nt); } if ( newList.contains(skew) ) //totalFreq += fv.getFrequency() * fv.getProbability(); totalFreq += fv.getFrequency() ; } CostScalar totalInnerBroadcastInBytes = totalFreq * child(brSide).getGroupAttr()->getRecordLength() * countOfPipelines ; if (totalInnerBroadcastInBytes >= ActiveSchemaDB()->getDefaults() .getAsLong(MC_SKEW_INNER_BROADCAST_THRESHOLD)) // ACX QUERY 5 and 8 have skews on the inner side. Better // to bet on partitioning on all columns to handle the dual skews. // This has been proved by the performance run on 3/21/2012: a // 6% degradation when partition on the remaining non-skew column. return FALSE; leastSkewList = skews; vidOfEquiJoinWithSkew = vid; } // Get the skew factor for the join predicate in question. skewFactors[skews] = currentSkew = child(i).getGroupAttr()-> getSkewnessFactor(vid, mostFreqVal, (*GLOBAL_EMPTY_INPUT_LOGPROP)); // We compute SFa * SFb * SFc ... here productOfSkewFactors *= currentSkew; // Obtain the colstat for the ith child of the join predicate. ColStatsSharedPtr colStats = child(i).getGroupAttr()-> getColStatsForSkewDetection(vid, (*GLOBAL_EMPTY_INPUT_LOGPROP)); if ( colStats == NULL ) return FALSE; // no stats exist. Can not make the decision. return FALSE. // Compute UECa * UECb * UECc ... here productOfUecs *= colStats->getTotalUec(); // get the RC of the table if ( rc == csMinusOne ) rc = colStats->getRowcount(); // Compute the minimal of the skew factors seen so far if ( currentSkew.isGreaterThanZero() ) { if ( minOfSkewFactor == csMinusOne || minOfSkewFactor > currentSkew ) minOfSkewFactor = currentSkew; } skews++; // Collect join columns in this predicate into joinColumns data structure. ValueIdSet joinColumns; vid.getItemExpr() -> findAll(ITM_BASECOLUMN, joinColumns, TRUE, FALSE); // Separate out columns in the join predicates and group them per table. // // For example, if join predicates are t.a=s.b and t.b=s.b and t.c = s.c, // we will have // // mcArray[0] = {t.a, t.b, t.c}, // mcArray[1] = {s.a, s.b, s.c}, // // at the end of the loop over join predicates. // j = 0; for(ValueId x = joinColumns.init(); joinColumns.next(x); joinColumns.advance(x)) { if ( !mcArray.used(j) ) mcArray.insertAt(j, x); else { ValueIdSet& mcSet = mcArray[j]; mcSet.insert(x); } j++; } } // end of the loop of join predicates // Now we can find the multi-column UEC, using one of the two multi-column // ValueIdSets (one for each side of the equi-join predicate). The colstats // list for the side of the child contains the stats (including the mc ones). // one of the mc ones is what we are looking for. // ColStatDescList colStatDescList = child(i).getGroupAttr()-> outputLogProp((*GLOBAL_EMPTY_INPUT_LOGPROP))->getColStats(); CostScalar mcUec = csMinusOne; const MultiColumnUecList* uecList = colStatDescList.getUecList(); for(j=0; j < mcArray.entries() && mcUec == csMinusOne && uecList; j++) { const ValueIdSet& mc = mcArray[j]; // Do a look up with mc. if ( uecList ) mcUec = uecList->lookup(mc); } // // Compute the final value of // min( (SFa * SFb * ... *min(UECa * UECb..,RC))/UEC(abc..), // SFa, SFb, ..., ) // = min(productOfSkewFactors * min(productOfUecs, RC)/mcUEC, // minOfSkewFactor) // // min(productOfUecs, RC)/mcUEC = 1 when mcUEC is not found // CostScalar mcSkewFactor; if ( mcUec == csMinusOne || mcUec == csZero ) mcSkewFactor = MINOF(productOfSkewFactors, minOfSkewFactor); else mcSkewFactor = MINOF( productOfSkewFactors * MINOF(productOfUecs, rc) / mcUec, minOfSkewFactor ); if ( mcSkewFactor > mc_threshold ) { *skList = skewLists[leastSkewList]; return TRUE; } else return FALSE; } // // The content of this method is lifted from // DP2InsertCursorRule::nextSubstitute(). // A Note has been added in that method so that any changes // to it should be "copied" here. // NABoolean Insert::isSideTreeInsertFeasible() { // Sidetree insert is only supported for key sequenced, non-compressed, // non-audited tables with blocksize equal to 4K. // Return error, if this is not the case. Insert::InsertType itype = getInsertType(); // Sidetree insert requested? if (itype != Insert::VSBB_LOAD ) return FALSE; if ((getTableDesc()->getClusteringIndex()->getNAFileSet() ->isCompressed()) || (getTableDesc()->getClusteringIndex()->getNAFileSet() ->getBlockSize() < 4096) || (NOT getTableDesc()->getClusteringIndex()->getNAFileSet() ->isKeySequenced()) || (getTableDesc()->getClusteringIndex()->getNAFileSet() ->isAudited()) ) { return FALSE; } NABoolean isEntrySequencedTable = getTableDesc()->getClusteringIndex() ->getNAFileSet()->isEntrySequenced(); if ( !getInliningInfo().hasPipelinedActions() ) return TRUE; if (isEntrySequencedTable || getInliningInfo().isEffectiveGU() || getTolerateNonFatalError() == RelExpr::NOT_ATOMIC_) return FALSE; // SideInsert is not allowed when there are pipelined actions (RI, // IM or triggers) except MV range logging. This means the only rows // projected are the very first and last rows as the beginning and // end of the range. NABoolean rangeLoggingRequired = getTableDesc()->getNATable()->getMvAttributeBitmap(). getAutomaticRangeLoggingRequired(); if (getInliningInfo().isProjectMidRangeRows() || !rangeLoggingRequired) return FALSE; return TRUE; } // big memory growth percent (to be used by SSD overlow enhancement project) short RelExpr::bmoGrowthPercent(CostScalar e, CostScalar m) { // bmo growth is 10% if 100*abs(maxcard-expected)/expected <= 100% // otherwise its 25% CostScalar expectedRows = e.minCsOne(); CostScalar maxRows = m.minCsOne(); CostScalar difference = maxRows - expectedRows; CostScalar uncertainty = (_ABSOLUTE_VALUE_(difference.value()) / expectedRows.value()) * 100; if (uncertainty <= 100) return 10; else return 25; } CostScalar RelExpr::getChild0Cardinality(const Context* context) { EstLogPropSharedPtr inLogProp = context->getInputLogProp(); EstLogPropSharedPtr ch0OutputLogProp = child(0).outputLogProp(inLogProp); const CostScalar ch0RowCount = (ch0OutputLogProp) ? (ch0OutputLogProp->getResultCardinality()).minCsOne() : csOne; return ch0RowCount; }
1
8,105
Partitions is misspelled 8 times in this commit, might make sense to fix the spelling for all of those.
apache-trafodion
cpp
@@ -22,9 +22,11 @@ import shlex from PyQt5.QtCore import (pyqtSlot, pyqtSignal, QObject, QProcess, - QProcessEnvironment) + QProcessEnvironment, QUrl) -from qutebrowser.utils import message, log +from qutebrowser.utils import message, log, objreg + +from qutebrowser.browser import qutescheme # A mapping of QProcess::ErrorCode's to human-readable strings.
1
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2015-2017 Florian Bruhin (The Compiler) <[email protected]> # # This file is part of qutebrowser. # # qutebrowser is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # qutebrowser is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with qutebrowser. If not, see <http://www.gnu.org/licenses/>. """A QProcess which shows notifications in the GUI.""" import shlex from PyQt5.QtCore import (pyqtSlot, pyqtSignal, QObject, QProcess, QProcessEnvironment) from qutebrowser.utils import message, log # A mapping of QProcess::ErrorCode's to human-readable strings. ERROR_STRINGS = { QProcess.FailedToStart: "The process failed to start.", QProcess.Crashed: "The process crashed.", QProcess.Timedout: "The last waitFor...() function timed out.", QProcess.WriteError: ("An error occurred when attempting to write to the " "process."), QProcess.ReadError: ("An error occurred when attempting to read from the " "process."), QProcess.UnknownError: "An unknown error occurred.", } class GUIProcess(QObject): """An external process which shows notifications in the GUI. Args: cmd: The command which was started. args: A list of arguments which gets passed. verbose: Whether to show more messages. _started: Whether the underlying process is started. _proc: The underlying QProcess. _what: What kind of thing is spawned (process/editor/userscript/...). Used in messages. Signals: error/finished/started signals proxied from QProcess. """ error = pyqtSignal(QProcess.ProcessError) finished = pyqtSignal(int, QProcess.ExitStatus) started = pyqtSignal() def __init__(self, what, *, verbose=False, additional_env=None, parent=None): super().__init__(parent) self._what = what self.verbose = verbose self._started = False self.cmd = None self.args = None self._proc = QProcess(self) self._proc.error.connect(self.on_error) self._proc.error.connect(self.error) self._proc.finished.connect(self.on_finished) self._proc.finished.connect(self.finished) self._proc.started.connect(self.on_started) self._proc.started.connect(self.started) if additional_env is not None: procenv = QProcessEnvironment.systemEnvironment() for k, v in additional_env.items(): procenv.insert(k, v) self._proc.setProcessEnvironment(procenv) @pyqtSlot(QProcess.ProcessError) def on_error(self, error): """Show a message if there was an error while spawning.""" msg = ERROR_STRINGS[error] message.error("Error while spawning {}: {}".format(self._what, msg)) @pyqtSlot(int, QProcess.ExitStatus) def on_finished(self, code, status): """Show a message when the process finished.""" self._started = False log.procs.debug("Process finished with code {}, status {}.".format( code, status)) if status == QProcess.CrashExit: message.error("{} crashed!".format(self._what.capitalize())) elif status == QProcess.NormalExit and code == 0: if self.verbose: message.info("{} exited successfully.".format( self._what.capitalize())) else: assert status == QProcess.NormalExit # We call this 'status' here as it makes more sense to the user - # it's actually 'code'. message.error("{} exited with status {}, see :messages for " "details.".format(self._what.capitalize(), code)) stderr = bytes(self._proc.readAllStandardError()).decode('utf-8') stdout = bytes(self._proc.readAllStandardOutput()).decode('utf-8') if stdout: log.procs.error("Process stdout:\n" + stdout.strip()) if stderr: log.procs.error("Process stderr:\n" + stderr.strip()) @pyqtSlot() def on_started(self): """Called when the process started successfully.""" log.procs.debug("Process started.") assert not self._started self._started = True def _pre_start(self, cmd, args): """Prepare starting of a QProcess.""" if self._started: raise ValueError("Trying to start a running QProcess!") self.cmd = cmd self.args = args fake_cmdline = ' '.join(shlex.quote(e) for e in [cmd] + list(args)) log.procs.debug("Executing: {}".format(fake_cmdline)) if self.verbose: message.info('Executing: ' + fake_cmdline) def start(self, cmd, args, mode=None): """Convenience wrapper around QProcess::start.""" log.procs.debug("Starting process.") self._pre_start(cmd, args) if mode is None: self._proc.start(cmd, args) else: self._proc.start(cmd, args, mode) self._proc.closeWriteChannel() def start_detached(self, cmd, args, cwd=None): """Convenience wrapper around QProcess::startDetached.""" log.procs.debug("Starting detached.") self._pre_start(cmd, args) ok, _pid = self._proc.startDetached(cmd, args, cwd) if ok: log.procs.debug("Process started.") self._started = True else: message.error("Error while spawning {}: {}".format( self._what, ERROR_STRINGS[self._proc.error()])) def exit_status(self): return self._proc.exitStatus()
1
20,011
Please remove this blank line - those are only used to group Python/third-party/qutebrowser imports.
qutebrowser-qutebrowser
py
@@ -45,6 +45,8 @@ var ActionCmd = &cobra.Command{ Args: cobra.MinimumNArgs(1), } +var insecure bool + func init() { ActionCmd.AddCommand(actionHashCmd) ActionCmd.AddCommand(actionTransferCmd)
1
// Copyright (c) 2019 IoTeX // This is an alpha (internal) release and is not suitable for production. This source code is provided 'as is' and no // warranties are given as to title or non-infringement, merchantability or fitness for purpose and, to the extent // permitted by law, all liability for your use of the code is disclaimed. This source code is governed by Apache // License 2.0 that can be found in the LICENSE file. package action import ( "context" "encoding/hex" "fmt" "math/big" "syscall" "github.com/golang/protobuf/proto" "github.com/spf13/cobra" "go.uber.org/zap" "golang.org/x/crypto/ssh/terminal" "google.golang.org/grpc/status" "github.com/iotexproject/iotex-core/action" "github.com/iotexproject/iotex-core/cli/ioctl/cmd/account" "github.com/iotexproject/iotex-core/cli/ioctl/cmd/config" "github.com/iotexproject/iotex-core/cli/ioctl/util" "github.com/iotexproject/iotex-core/pkg/hash" "github.com/iotexproject/iotex-core/pkg/log" "github.com/iotexproject/iotex-core/pkg/util/byteutil" "github.com/iotexproject/iotex-core/protogen/iotexapi" ) // Flags var ( gasLimit uint64 gasPrice string nonce uint64 signer string bytecode []byte ) // ActionCmd represents the account command var ActionCmd = &cobra.Command{ Use: "action", Short: "Manage actions of IoTeX blockchain", Args: cobra.MinimumNArgs(1), } func init() { ActionCmd.AddCommand(actionHashCmd) ActionCmd.AddCommand(actionTransferCmd) ActionCmd.AddCommand(actionDeployCmd) ActionCmd.AddCommand(actionInvokeCmd) ActionCmd.AddCommand(actionClaimCmd) ActionCmd.AddCommand(actionDepositCmd) ActionCmd.PersistentFlags().StringVar(&config.ReadConfig.Endpoint, "endpoint", config.ReadConfig.Endpoint, "set endpoint for once") setActionFlags(actionTransferCmd, actionDeployCmd, actionInvokeCmd, actionClaimCmd, actionDepositCmd) ActionCmd.PersistentFlags().BoolVar(&config.IsInsecure, "insecure", false, "connect endpoint with insecure option") } func setActionFlags(cmds ...*cobra.Command) { for _, cmd := range cmds { cmd.Flags().Uint64VarP(&gasLimit, "gas-limit", "l", 0, "set gas limit") cmd.Flags().StringVarP(&gasPrice, "gas-price", "p", "1", "set gas price (unit: 10^(-6)Iotx)") cmd.Flags().StringVarP(&signer, "signer", "s", "", "choose a signing account") cmd.Flags().Uint64VarP(&nonce, "nonce", "n", 0, "set nonce") cmd.MarkFlagRequired("signer") if cmd == actionDeployCmd || cmd == actionInvokeCmd { cmd.Flags().BytesHexVarP(&bytecode, "bytecode", "b", nil, "set the byte code") cmd.MarkFlagRequired("gas-limit") cmd.MarkFlagRequired("bytecode") } } } // GetGasPrice gets the suggest gas price func GetGasPrice() (*big.Int, error) { conn, err := util.ConnectToEndpoint(config.IsInsecure) if err != nil { return nil, err } defer conn.Close() cli := iotexapi.NewAPIServiceClient(conn) ctx := context.Background() request := &iotexapi.SuggestGasPriceRequest{} response, err := cli.SuggestGasPrice(ctx, request) if err != nil { return nil, err } return new(big.Int).SetUint64(response.GasPrice), nil } func sendAction(elp action.Envelope) (string, error) { fmt.Printf("Enter password #%s:\n", signer) bytePassword, err := terminal.ReadPassword(int(syscall.Stdin)) if err != nil { log.L().Error("failed to get password", zap.Error(err)) return "", err } prvKey, err := account.KsAccountToPrivateKey(signer, string(bytePassword)) if err != nil { return "", err } defer prvKey.Zero() sealed, err := action.Sign(elp, prvKey) prvKey.Zero() if err != nil { log.L().Error("failed to sign action", zap.Error(err)) return "", err } selp := sealed.Proto() actionInfo, err := printActionProto(selp) if err != nil { return "", err } var confirm string fmt.Println("\n" + actionInfo + "\n" + "Please confirm your action.\n" + "Type 'YES' to continue, quit for anything else.") fmt.Scanf("%s", &confirm) if confirm != "YES" && confirm != "yes" { return "Quit", nil } fmt.Println() request := &iotexapi.SendActionRequest{Action: selp} conn, err := util.ConnectToEndpoint(config.IsInsecure) if err != nil { return "", err } defer conn.Close() cli := iotexapi.NewAPIServiceClient(conn) ctx := context.Background() _, err = cli.SendAction(ctx, request) if err != nil { sta, ok := status.FromError(err) if ok { return "", fmt.Errorf(sta.Message()) } return "", err } shash := hash.Hash256b(byteutil.Must(proto.Marshal(selp))) return "Action has been sent to blockchain.\n" + "Wait for several seconds and query this action by hash:\n" + hex.EncodeToString(shash[:]), nil }
1
17,390
`insecure` is a global variable (from `gochecknoglobals`)
iotexproject-iotex-core
go
@@ -479,6 +479,11 @@ func HTTPBackend(ctx *context.Context, cfg *serviceConfig) http.HandlerFunc { for _, route := range routes { r.URL.Path = strings.ToLower(r.URL.Path) // blue: In case some repo name has upper case name if m := route.reg.FindStringSubmatch(r.URL.Path); m != nil { + if setting.Repository.DisableHttpGit { + w.WriteHeader(http.StatusForbidden) + w.Write([]byte("Interacting with repositories by HTTP protocol is not allowed")) + return + } if route.method != r.Method { if r.Proto == "HTTP/1.1" { w.WriteHeader(http.StatusMethodNotAllowed)
1
// Copyright 2014 The Gogs Authors. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. package repo import ( "bytes" "compress/gzip" "fmt" "io" "io/ioutil" "net/http" "os" "os/exec" "path" "regexp" "runtime" "strconv" "strings" "time" git "github.com/gogits/git-module" "github.com/gogits/gogs/models" "github.com/gogits/gogs/modules/base" "github.com/gogits/gogs/modules/context" "github.com/gogits/gogs/modules/log" "github.com/gogits/gogs/modules/setting" ) func HTTP(ctx *context.Context) { username := ctx.Params(":username") reponame := strings.TrimSuffix(ctx.Params(":reponame"), ".git") var isPull bool service := ctx.Query("service") if service == "git-receive-pack" || strings.HasSuffix(ctx.Req.URL.Path, "git-receive-pack") { isPull = false } else if service == "git-upload-pack" || strings.HasSuffix(ctx.Req.URL.Path, "git-upload-pack") { isPull = true } else { isPull = (ctx.Req.Method == "GET") } isWiki := false if strings.HasSuffix(reponame, ".wiki") { isWiki = true reponame = reponame[:len(reponame)-5] } repoUser, err := models.GetUserByName(username) if err != nil { if models.IsErrUserNotExist(err) { ctx.Handle(http.StatusNotFound, "GetUserByName", nil) } else { ctx.Handle(http.StatusInternalServerError, "GetUserByName", err) } return } repo, err := models.GetRepositoryByName(repoUser.ID, reponame) if err != nil { if models.IsErrRepoNotExist(err) { ctx.Handle(http.StatusNotFound, "GetRepositoryByName", nil) } else { ctx.Handle(http.StatusInternalServerError, "GetRepositoryByName", err) } return } // Only public pull don't need auth. isPublicPull := !repo.IsPrivate && isPull var ( askAuth = !isPublicPull || setting.Service.RequireSignInView authUser *models.User authUsername string authPasswd string ) // check access if askAuth { authHead := ctx.Req.Header.Get("Authorization") if len(authHead) == 0 { ctx.Resp.Header().Set("WWW-Authenticate", "Basic realm=\".\"") ctx.Error(http.StatusUnauthorized) return } auths := strings.Fields(authHead) // currently check basic auth // TODO: support digit auth // FIXME: middlewares/context.go did basic auth check already, // maybe could use that one. if len(auths) != 2 || auths[0] != "Basic" { ctx.HandleText(http.StatusUnauthorized, "no basic auth and digit auth") return } authUsername, authPasswd, err = base.BasicAuthDecode(auths[1]) if err != nil { ctx.HandleText(http.StatusUnauthorized, "no basic auth and digit auth") return } authUser, err = models.UserSignIn(authUsername, authPasswd) if err != nil { if !models.IsErrUserNotExist(err) { ctx.Handle(http.StatusInternalServerError, "UserSignIn error: %v", err) return } // Assume username now is a token. token, err := models.GetAccessTokenBySHA(authUsername) if err != nil { if models.IsErrAccessTokenNotExist(err) || models.IsErrAccessTokenEmpty(err) { ctx.HandleText(http.StatusUnauthorized, "invalid token") } else { ctx.Handle(http.StatusInternalServerError, "GetAccessTokenBySha", err) } return } token.Updated = time.Now() if err = models.UpdateAccessToken(token); err != nil { ctx.Handle(http.StatusInternalServerError, "UpdateAccessToken", err) } authUser, err = models.GetUserByID(token.UID) if err != nil { ctx.Handle(http.StatusInternalServerError, "GetUserByID", err) return } } if !isPublicPull { var tp = models.ACCESS_MODE_WRITE if isPull { tp = models.ACCESS_MODE_READ } has, err := models.HasAccess(authUser, repo, tp) if err != nil { ctx.Handle(http.StatusInternalServerError, "HasAccess", err) return } else if !has { if tp == models.ACCESS_MODE_READ { has, err = models.HasAccess(authUser, repo, models.ACCESS_MODE_WRITE) if err != nil { ctx.Handle(http.StatusInternalServerError, "HasAccess2", err) return } else if !has { ctx.HandleText(http.StatusForbidden, "User permission denied") return } } else { ctx.HandleText(http.StatusForbidden, "User permission denied") return } } if !isPull && repo.IsMirror { ctx.HandleText(http.StatusForbidden, "mirror repository is read-only") return } } } callback := func(rpc string, input []byte) { if rpc != "receive-pack" || isWiki { return } var lastLine int64 = 0 for { head := input[lastLine : lastLine+2] if head[0] == '0' && head[1] == '0' { size, err := strconv.ParseInt(string(input[lastLine+2:lastLine+4]), 16, 32) if err != nil { log.Error(4, "%v", err) return } if size == 0 { //fmt.Println(string(input[lastLine:])) break } line := input[lastLine : lastLine+size] idx := bytes.IndexRune(line, '\000') if idx > -1 { line = line[:idx] } fields := strings.Fields(string(line)) if len(fields) >= 3 { oldCommitId := fields[0][4:] newCommitId := fields[1] refFullName := fields[2] // FIXME: handle error. if err = models.PushUpdate(models.PushUpdateOptions{ RefFullName: refFullName, OldCommitID: oldCommitId, NewCommitID: newCommitId, PusherID: authUser.ID, PusherName: authUser.Name, RepoUserName: username, RepoName: reponame, }); err == nil { go models.AddTestPullRequestTask(authUser, repo.ID, strings.TrimPrefix(refFullName, git.BRANCH_PREFIX), true) } } lastLine = lastLine + size } else { break } } } HTTPBackend(ctx, &serviceConfig{ UploadPack: true, ReceivePack: true, OnSucceed: callback, })(ctx.Resp, ctx.Req.Request) runtime.GC() } type serviceConfig struct { UploadPack bool ReceivePack bool OnSucceed func(rpc string, input []byte) } type serviceHandler struct { cfg *serviceConfig w http.ResponseWriter r *http.Request dir string file string } func (h *serviceHandler) setHeaderNoCache() { h.w.Header().Set("Expires", "Fri, 01 Jan 1980 00:00:00 GMT") h.w.Header().Set("Pragma", "no-cache") h.w.Header().Set("Cache-Control", "no-cache, max-age=0, must-revalidate") } func (h *serviceHandler) setHeaderCacheForever() { now := time.Now().Unix() expires := now + 31536000 h.w.Header().Set("Date", fmt.Sprintf("%d", now)) h.w.Header().Set("Expires", fmt.Sprintf("%d", expires)) h.w.Header().Set("Cache-Control", "public, max-age=31536000") } func (h *serviceHandler) sendFile(contentType string) { reqFile := path.Join(h.dir, h.file) fi, err := os.Stat(reqFile) if os.IsNotExist(err) { h.w.WriteHeader(http.StatusNotFound) return } h.w.Header().Set("Content-Type", contentType) h.w.Header().Set("Content-Length", fmt.Sprintf("%d", fi.Size())) h.w.Header().Set("Last-Modified", fi.ModTime().Format(http.TimeFormat)) http.ServeFile(h.w, h.r, reqFile) } type route struct { reg *regexp.Regexp method string handler func(serviceHandler) } var routes = []route{ {regexp.MustCompile("(.*?)/git-upload-pack$"), "POST", serviceUploadPack}, {regexp.MustCompile("(.*?)/git-receive-pack$"), "POST", serviceReceivePack}, {regexp.MustCompile("(.*?)/info/refs$"), "GET", getInfoRefs}, {regexp.MustCompile("(.*?)/HEAD$"), "GET", getTextFile}, {regexp.MustCompile("(.*?)/objects/info/alternates$"), "GET", getTextFile}, {regexp.MustCompile("(.*?)/objects/info/http-alternates$"), "GET", getTextFile}, {regexp.MustCompile("(.*?)/objects/info/packs$"), "GET", getInfoPacks}, {regexp.MustCompile("(.*?)/objects/info/[^/]*$"), "GET", getTextFile}, {regexp.MustCompile("(.*?)/objects/[0-9a-f]{2}/[0-9a-f]{38}$"), "GET", getLooseObject}, {regexp.MustCompile("(.*?)/objects/pack/pack-[0-9a-f]{40}\\.pack$"), "GET", getPackFile}, {regexp.MustCompile("(.*?)/objects/pack/pack-[0-9a-f]{40}\\.idx$"), "GET", getIdxFile}, } // FIXME: use process module func gitCommand(dir string, args ...string) []byte { cmd := exec.Command("git", args...) cmd.Dir = dir out, err := cmd.Output() if err != nil { log.GitLogger.Error(4, fmt.Sprintf("%v - %s", err, out)) } return out } func getGitConfig(option, dir string) string { out := string(gitCommand(dir, "config", option)) return out[0 : len(out)-1] } func getConfigSetting(service, dir string) bool { service = strings.Replace(service, "-", "", -1) setting := getGitConfig("http."+service, dir) if service == "uploadpack" { return setting != "false" } return setting == "true" } func hasAccess(service string, h serviceHandler, checkContentType bool) bool { if checkContentType { if h.r.Header.Get("Content-Type") != fmt.Sprintf("application/x-git-%s-request", service) { return false } } if !(service == "upload-pack" || service == "receive-pack") { return false } if service == "receive-pack" { return h.cfg.ReceivePack } if service == "upload-pack" { return h.cfg.UploadPack } return getConfigSetting(service, h.dir) } func serviceRPC(h serviceHandler, service string) { defer h.r.Body.Close() if !hasAccess(service, h, true) { h.w.WriteHeader(http.StatusUnauthorized) return } h.w.Header().Set("Content-Type", fmt.Sprintf("application/x-git-%s-result", service)) var ( reqBody = h.r.Body input []byte br io.Reader err error ) // Handle GZIP. if h.r.Header.Get("Content-Encoding") == "gzip" { reqBody, err = gzip.NewReader(reqBody) if err != nil { log.GitLogger.Error(2, "fail to create gzip reader: %v", err) h.w.WriteHeader(http.StatusInternalServerError) return } } if h.cfg.OnSucceed != nil { input, err = ioutil.ReadAll(reqBody) if err != nil { log.GitLogger.Error(2, "fail to read request body: %v", err) h.w.WriteHeader(http.StatusInternalServerError) return } br = bytes.NewReader(input) } else { br = reqBody } cmd := exec.Command("git", service, "--stateless-rpc", h.dir) cmd.Dir = h.dir cmd.Stdout = h.w cmd.Stdin = br if err := cmd.Run(); err != nil { log.GitLogger.Error(2, "fail to serve RPC(%s): %v", service, err) h.w.WriteHeader(http.StatusInternalServerError) return } if h.cfg.OnSucceed != nil { h.cfg.OnSucceed(service, input) } } func serviceUploadPack(h serviceHandler) { serviceRPC(h, "upload-pack") } func serviceReceivePack(h serviceHandler) { serviceRPC(h, "receive-pack") } func getServiceType(r *http.Request) string { serviceType := r.FormValue("service") if !strings.HasPrefix(serviceType, "git-") { return "" } return strings.Replace(serviceType, "git-", "", 1) } func updateServerInfo(dir string) []byte { return gitCommand(dir, "update-server-info") } func packetWrite(str string) []byte { s := strconv.FormatInt(int64(len(str)+4), 16) if len(s)%4 != 0 { s = strings.Repeat("0", 4-len(s)%4) + s } return []byte(s + str) } func getInfoRefs(h serviceHandler) { h.setHeaderNoCache() if hasAccess(getServiceType(h.r), h, false) { service := getServiceType(h.r) refs := gitCommand(h.dir, service, "--stateless-rpc", "--advertise-refs", ".") h.w.Header().Set("Content-Type", fmt.Sprintf("application/x-git-%s-advertisement", service)) h.w.WriteHeader(http.StatusOK) h.w.Write(packetWrite("# service=git-" + service + "\n")) h.w.Write([]byte("0000")) h.w.Write(refs) } else { updateServerInfo(h.dir) h.sendFile("text/plain; charset=utf-8") } } func getTextFile(h serviceHandler) { h.setHeaderNoCache() h.sendFile("text/plain") } func getInfoPacks(h serviceHandler) { h.setHeaderCacheForever() h.sendFile("text/plain; charset=utf-8") } func getLooseObject(h serviceHandler) { h.setHeaderCacheForever() h.sendFile("application/x-git-loose-object") } func getPackFile(h serviceHandler) { h.setHeaderCacheForever() h.sendFile("application/x-git-packed-objects") } func getIdxFile(h serviceHandler) { h.setHeaderCacheForever() h.sendFile("application/x-git-packed-objects-toc") } func getGitRepoPath(subdir string) (string, error) { if !strings.HasSuffix(subdir, ".git") { subdir += ".git" } fpath := path.Join(setting.RepoRootPath, subdir) if _, err := os.Stat(fpath); os.IsNotExist(err) { return "", err } return fpath, nil } func HTTPBackend(ctx *context.Context, cfg *serviceConfig) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { for _, route := range routes { r.URL.Path = strings.ToLower(r.URL.Path) // blue: In case some repo name has upper case name if m := route.reg.FindStringSubmatch(r.URL.Path); m != nil { if route.method != r.Method { if r.Proto == "HTTP/1.1" { w.WriteHeader(http.StatusMethodNotAllowed) w.Write([]byte("Method Not Allowed")) } else { w.WriteHeader(http.StatusBadRequest) w.Write([]byte("Bad Request")) } return } file := strings.Replace(r.URL.Path, m[1]+"/", "", 1) dir, err := getGitRepoPath(m[1]) if err != nil { log.GitLogger.Error(4, err.Error()) ctx.Handle(http.StatusNotFound, "HTTPBackend", err) return } route.handler(serviceHandler{cfg, w, r, dir, file}) return } } ctx.Handle(http.StatusNotFound, "HTTPBackend", nil) return } }
1
12,066
Same as above (HTTP in upper-case)
gogs-gogs
go
@@ -206,4 +206,11 @@ class YouTubeProviderTest extends AbstractProviderTest $this->assertSame(100, $properties['player_parameters']['height']); $this->assertSame(100, $properties['player_parameters']['width']); } + + public function testGetReferenceUrl() + { + $media = new Media(); + $media->setProviderReference('123456'); + $this->assertEquals('http://www.youtube.com/watch?v=123456', $this->getProvider()->getReferenceUrl($media)); + } }
1
<?php /* * This file is part of the Sonata Project package. * * (c) Thomas Rabaix <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\MediaBundle\Tests\Provider; use Buzz\Browser; use Buzz\Message\Response; use Imagine\Image\Box; use Sonata\MediaBundle\Provider\YouTubeProvider; use Sonata\MediaBundle\Tests\Entity\Media; use Sonata\MediaBundle\Thumbnail\FormatThumbnail; class YouTubeProviderTest extends AbstractProviderTest { public function getProvider(Browser $browser = null) { if (!$browser) { $browser = $this->getMockBuilder('Buzz\Browser')->getMock(); } $resizer = $this->getMock('Sonata\MediaBundle\Resizer\ResizerInterface'); $resizer->expects($this->any())->method('resize')->will($this->returnValue(true)); $resizer->expects($this->any())->method('getBox')->will($this->returnValue(new Box(100, 100))); $adapter = $this->getMock('Gaufrette\Adapter'); $filesystem = $this->getMock('Gaufrette\Filesystem', array('get'), array($adapter)); $file = $this->getMock('Gaufrette\File', array(), array('foo', $filesystem)); $filesystem->expects($this->any())->method('get')->will($this->returnValue($file)); $cdn = new \Sonata\MediaBundle\CDN\Server('/uploads/media'); $generator = new \Sonata\MediaBundle\Generator\DefaultGenerator(); $thumbnail = new FormatThumbnail('jpg'); $metadata = $this->getMock('Sonata\MediaBundle\Metadata\MetadataBuilderInterface'); $provider = new YouTubeProvider('file', $filesystem, $cdn, $generator, $thumbnail, $browser, $metadata); $provider->setResizer($resizer); return $provider; } public function testProvider() { $provider = $this->getProvider(); $media = new Media(); $media->setName('Nono le petit robot'); $media->setProviderName('youtube'); $media->setProviderReference('BDYAbAtaDzA'); $media->setContext('default'); $media->setProviderMetadata(json_decode('{"provider_url": "http:\/\/www.youtube.com\/", "title": "Nono le petit robot", "html": "<object width=\"425\" height=\"344\"><param name=\"movie\" value=\"http:\/\/www.youtube.com\/v\/BDYAbAtaDzA?fs=1\"><\/param><param name=\"allowFullScreen\" value=\"true\"><\/param><param name=\"allowscriptaccess\" value=\"always\"><\/param><embed src=\"http:\/\/www.youtube.com\/v\/BDYAbAtaDzA?fs=1\" type=\"application\/x-shockwave-flash\" width=\"425\" height=\"344\" allowscriptaccess=\"always\" allowfullscreen=\"true\"><\/embed><\/object>", "author_name": "timan38", "height": 344, "thumbnail_width": 480, "width": 425, "version": "1.0", "author_url": "http:\/\/www.youtube.com\/user\/timan38", "provider_name": "YouTube", "thumbnail_url": "http:\/\/i3.ytimg.com\/vi\/BDYAbAtaDzA\/hqdefault.jpg", "type": "video", "thumbnail_height": 360}', true)); $media->setId(1023457); $this->assertSame('http://i3.ytimg.com/vi/BDYAbAtaDzA/hqdefault.jpg', $provider->getReferenceImage($media)); $this->assertSame('default/0011/24', $provider->generatePath($media)); $this->assertSame('/uploads/media/default/0011/24/thumb_1023457_big.jpg', $provider->generatePublicUrl($media, 'big')); } public function testThumbnail() { $response = $this->getMock('Buzz\Message\AbstractMessage'); $response->expects($this->once())->method('getContent')->will($this->returnValue('content')); $browser = $this->getMockBuilder('Buzz\Browser')->getMock(); $browser->expects($this->once())->method('get')->will($this->returnValue($response)); $provider = $this->getProvider($browser); $media = new Media(); $media->setProviderName('youtube'); $media->setProviderReference('BDYAbAtaDzA'); $media->setContext('default'); $media->setProviderMetadata(json_decode('{"provider_url": "http:\/\/www.youtube.com\/", "title": "Nono le petit robot", "html": "<object width=\"425\" height=\"344\"><param name=\"movie\" value=\"http:\/\/www.youtube.com\/v\/BDYAbAtaDzA?fs=1\"><\/param><param name=\"allowFullScreen\" value=\"true\"><\/param><param name=\"allowscriptaccess\" value=\"always\"><\/param><embed src=\"http:\/\/www.youtube.com\/v\/BDYAbAtaDzA?fs=1\" type=\"application\/x-shockwave-flash\" width=\"425\" height=\"344\" allowscriptaccess=\"always\" allowfullscreen=\"true\"><\/embed><\/object>", "author_name": "timan38", "height": 344, "thumbnail_width": 480, "width": 425, "version": "1.0", "author_url": "http:\/\/www.youtube.com\/user\/timan38", "provider_name": "YouTube", "thumbnail_url": "http:\/\/i3.ytimg.com\/vi\/BDYAbAtaDzA\/hqdefault.jpg", "type": "video", "thumbnail_height": 360}', true)); $media->setId(1023457); $this->assertTrue($provider->requireThumbnails($media)); $provider->addFormat('big', array('width' => 200, 'height' => 100, 'constraint' => true)); $this->assertNotEmpty($provider->getFormats(), '::getFormats() return an array'); $provider->generateThumbnails($media); $this->assertSame('default/0011/24/thumb_1023457_big.jpg', $provider->generatePrivateUrl($media, 'big')); } public function testTransformWithSig() { $response = new Response(); $response->setContent(file_get_contents(__DIR__.'/../fixtures/valid_youtube.txt')); $browser = $this->getMockBuilder('Buzz\Browser')->getMock(); $browser->expects($this->once())->method('get')->will($this->returnValue($response)); $provider = $this->getProvider($browser); $provider->addFormat('big', array('width' => 200, 'height' => 100, 'constraint' => true)); $media = new Media(); $media->setBinaryContent('BDYAbAtaDzA'); $media->setId(1023456); // pre persist the media $provider->transform($media); $this->assertSame('Nono le petit robot', $media->getName(), '::getName() return the file name'); $this->assertSame('BDYAbAtaDzA', $media->getProviderReference(), '::getProviderReference() is set'); } /** * @dataProvider getUrls */ public function testTransformWithUrl($url) { $response = new Response(); $response->setContent(file_get_contents(__DIR__.'/../fixtures/valid_youtube.txt')); $browser = $this->getMockBuilder('Buzz\Browser')->getMock(); $browser->expects($this->once())->method('get')->will($this->returnValue($response)); $provider = $this->getProvider($browser); $provider->addFormat('big', array('width' => 200, 'height' => 100, 'constraint' => true)); $media = new Media(); $media->setBinaryContent($url); $media->setId(1023456); // pre persist the media $provider->transform($media); $this->assertSame('Nono le petit robot', $media->getName(), '::getName() return the file name'); $this->assertSame('BDYAbAtaDzA', $media->getProviderReference(), '::getProviderReference() is set'); } public static function getUrls() { return array( array('BDYAbAtaDzA'), array('http://www.youtube.com/watch?v=BDYAbAtaDzA&feature=feedrec_grec_index'), array('http://www.youtube.com/v/BDYAbAtaDzA?fs=1&amp;hl=en_US&amp;rel=0'), array('http://www.youtube.com/watch?v=BDYAbAtaDzA#t=0m10s'), array('http://www.youtube.com/embed/BDYAbAtaDzA?rel=0'), array('http://www.youtube.com/watch?v=BDYAbAtaDzA'), array('http://www.m.youtube.com/watch?v=BDYAbAtaDzA'), array('http://m.youtube.com/watch?v=BDYAbAtaDzA'), array('https://www.m.youtube.com/watch?v=BDYAbAtaDzA'), array('https://m.youtube.com/watch?v=BDYAbAtaDzA'), array('http://youtu.be/BDYAbAtaDzA'), ); } public function testForm() { if (!class_exists('\Sonata\AdminBundle\Form\FormMapper')) { $this->markTestSkipped("AdminBundle doesn't seem to be installed"); } $provider = $this->getProvider(); $admin = $this->getMock('Sonata\AdminBundle\Admin\AdminInterface'); $admin->expects($this->any()) ->method('trans') ->will($this->returnValue('message')); $formMapper = $this->getMock('Sonata\AdminBundle\Form\FormMapper', array('add', 'getAdmin'), array(), '', false); $formMapper->expects($this->exactly(8)) ->method('add') ->will($this->returnValue(null)); $provider->buildCreateForm($formMapper); $provider->buildEditForm($formMapper); } public function testHelperProperties() { $provider = $this->getProvider(); $provider->addFormat('admin', array('width' => 100)); $media = new Media(); $media->setName('Les tests'); $media->setProviderReference('ASDASDAS.png'); $media->setId(10); $media->setHeight(100); $media->setWidth(100); $properties = $provider->getHelperProperties($media, 'admin'); $this->assertInternalType('array', $properties); $this->assertSame(100, $properties['player_parameters']['height']); $this->assertSame(100, $properties['player_parameters']['width']); } }
1
7,881
This is getting repetitive maybe you could introduce an abstract test case with a `getExpectedUrl($providerReference)` method ?
sonata-project-SonataMediaBundle
php
@@ -0,0 +1,5 @@ +package reflect + +func MakeFunc(typ Type, fn func(args []Value) (results []Value)) Value { + return Value{} +}
1
1
12,391
I do not think returning `Value{}` is correct here. For example, `reflect.MakeFunc(...).Kind()` would return `reflect.Invalid` instead of `reflect.Func`. Therefore, I think this should panic instead.
tinygo-org-tinygo
go
@@ -73,7 +73,7 @@ function setProperty(dom, name, value, oldValue, isSvg) { else if (name[0]==='o' && name[1]==='n') { let useCapture = name !== (name=name.replace(/Capture$/, '')); let nameLower = name.toLowerCase(); - name = (nameLower in dom ? nameLower : name).substring(2); + name = (nameLower in window ? nameLower : name).substring(2); if (value) { if (!oldValue) dom.addEventListener(name, eventProxy, useCapture);
1
import { IS_NON_DIMENSIONAL } from '../constants'; import options from '../options'; /** * Diff the old and new properties of a VNode and apply changes to the DOM node * @param {import('../internal').PreactElement} dom The DOM node to apply * changes to * @param {object} newProps The new props * @param {object} oldProps The old props * @param {boolean} isSvg Whether or not this node is an SVG node */ export function diffProps(dom, newProps, oldProps, isSvg) { let keys = Object.keys(newProps).sort(); for (let i = 0; i < keys.length; i++) { if (keys[i]!=='children' && keys[i]!=='key' && (!oldProps || ((keys[i]==='value' || keys[i]==='checked') ? dom : oldProps)[keys[i]]!==newProps[keys[i]])) { setProperty(dom, keys[i], newProps[keys[i]], oldProps[keys[i]], isSvg); } } for (let i in oldProps) { if (i!=='children' && i!=='key' && (!newProps || !(i in newProps))) { setProperty(dom, i, null, oldProps[i], isSvg); } } } let CAMEL_REG = /-?(?=[A-Z])/g; /** * Set a property value on a DOM node * @param {import('../internal').PreactElement} dom The DOM node to modify * @param {string} name The name of the property to set * @param {*} value The value to set the property to * @param {*} oldValue The old value the property had * @param {boolean} isSvg Whether or not this DOM node is an SVG node or not */ function setProperty(dom, name, value, oldValue, isSvg) { let v; if (name==='class' || name==='className') name = isSvg ? 'class' : 'className'; if (name==='style') { /* Possible golfing activities for setting styles: * - we could just drop String style values. They're not supported in other VDOM libs. * - assigning to .style sets .style.cssText - TODO: benchmark this, might not be worth the bytes. * - assigning also casts to String, and ignores invalid values. This means assigning an Object clears all styles. */ let s = dom.style; if (typeof value==='string') { s.cssText = value; } else { if (typeof oldValue==='string') s.cssText = ''; else { // remove values not in the new list for (let i in oldValue) { if (value==null || !(i in value)) s.setProperty(i.replace(CAMEL_REG, '-'), ''); } } for (let i in value) { v = value[i]; if (oldValue==null || v!==oldValue[i]) { s.setProperty(i.replace(CAMEL_REG, '-'), typeof v==='number' && IS_NON_DIMENSIONAL.test(i)===false ? (v + 'px') : v); } } } } else if (name==='dangerouslySetInnerHTML') { return; } // Benchmark for comparison: https://esbench.com/bench/574c954bdb965b9a00965ac6 else if (name[0]==='o' && name[1]==='n') { let useCapture = name !== (name=name.replace(/Capture$/, '')); let nameLower = name.toLowerCase(); name = (nameLower in dom ? nameLower : name).substring(2); if (value) { if (!oldValue) dom.addEventListener(name, eventProxy, useCapture); } else { dom.removeEventListener(name, eventProxy, useCapture); } (dom._listeners || (dom._listeners = {}))[name] = value; } else if (name!=='list' && name!=='tagName' && !isSvg && (name in dom)) { dom[name] = value==null ? '' : value; } else if (value==null || value===false) { if (name!==(name = name.replace(/^xlink:?/, ''))) dom.removeAttributeNS('http://www.w3.org/1999/xlink', name.toLowerCase()); else dom.removeAttribute(name); } else if (typeof value!=='function') { if (name!==(name = name.replace(/^xlink:?/, ''))) dom.setAttributeNS('http://www.w3.org/1999/xlink', name.toLowerCase(), value); else dom.setAttribute(name, value); } } /** * Proxy an event to hooked event handlers * @param {Event} e The event object from the browser * @private */ function eventProxy(e) { return this._listeners[e.type](options.event ? options.event(e) : e); }
1
13,242
Does this work for Custom Elements? iirc we're lacking test cases for them. /cc @andrewiggins @developit
preactjs-preact
js
@@ -224,9 +224,7 @@ func (m *ipipManager) CompleteDeferredWork() error { for _, ip := range m.activeHostnameToIP { members = append(members, ip) } - for _, ip := range m.externalNodeCIDRs { - members = append(members, ip) - } + members = append(members, m.externalNodeCIDRs...) m.ipsetsDataplane.AddOrReplaceIPSet(m.ipSetMetadata, members) m.ipSetInSync = true }
1
// Copyright (c) 2016-2017, 2019 Tigera, Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package intdataplane import ( "net" "time" log "github.com/sirupsen/logrus" "github.com/vishvananda/netlink" "github.com/projectcalico/felix/ipsets" "github.com/projectcalico/felix/proto" "github.com/projectcalico/felix/rules" "github.com/projectcalico/libcalico-go/lib/set" ) // ipipManager manages the all-hosts IP set, which is used by some rules in our static chains // when IPIP is enabled. It doesn't actually program the rules, because they are part of the // top-level static chains. // // ipipManager also takes care of the configuration of the IPIP tunnel device. type ipipManager struct { ipsetsDataplane ipsetsDataplane // activeHostnameToIP maps hostname to string IP address. We don't bother to parse into // net.IPs because we're going to pass them directly to the IPSet API. activeHostnameToIP map[string]string ipSetInSync bool // Config for creating/refreshing the IP set. ipSetMetadata ipsets.IPSetMetadata // Dataplane shim. dataplane ipipDataplane // Configured list of external node ip cidr's to be added to the ipset. externalNodeCIDRs []string } func newIPIPManager( ipsetsDataplane ipsetsDataplane, maxIPSetSize int, externalNodeCidrs []string, ) *ipipManager { return newIPIPManagerWithShim(ipsetsDataplane, maxIPSetSize, realIPIPNetlink{}, externalNodeCidrs) } func newIPIPManagerWithShim( ipsetsDataplane ipsetsDataplane, maxIPSetSize int, dataplane ipipDataplane, externalNodeCIDRs []string, ) *ipipManager { ipipMgr := &ipipManager{ ipsetsDataplane: ipsetsDataplane, activeHostnameToIP: map[string]string{}, dataplane: dataplane, ipSetMetadata: ipsets.IPSetMetadata{ MaxSize: maxIPSetSize, SetID: rules.IPSetIDAllHostNets, Type: ipsets.IPSetTypeHashNet, }, externalNodeCIDRs: externalNodeCIDRs, } return ipipMgr } // KeepIPIPDeviceInSync is a goroutine that configures the IPIP tunnel device, then periodically // checks that it is still correctly configured. func (d *ipipManager) KeepIPIPDeviceInSync(mtu int, address net.IP) { log.Info("IPIP thread started.") for { err := d.configureIPIPDevice(mtu, address) if err != nil { log.WithError(err).Warn("Failed configure IPIP tunnel device, retrying...") time.Sleep(1 * time.Second) continue } time.Sleep(10 * time.Second) } } // configureIPIPDevice ensures the IPIP tunnel device is up and configures correctly. func (d *ipipManager) configureIPIPDevice(mtu int, address net.IP) error { logCxt := log.WithFields(log.Fields{ "mtu": mtu, "tunnelAddr": address, }) logCxt.Debug("Configuring IPIP tunnel") link, err := d.dataplane.LinkByName("tunl0") if err != nil { log.WithError(err).Info("Failed to get IPIP tunnel device, assuming it isn't present") // We call out to "ip tunnel", which takes care of loading the kernel module if // needed. The tunl0 device is actually created automatically by the kernel // module. err := d.dataplane.RunCmd("ip", "tunnel", "add", "tunl0", "mode", "ipip") if err != nil { log.WithError(err).Warning("Failed to add IPIP tunnel device") return err } link, err = d.dataplane.LinkByName("tunl0") if err != nil { log.WithError(err).Warning("Failed to get tunnel device") return err } } attrs := link.Attrs() oldMTU := attrs.MTU if oldMTU != mtu { logCxt.WithField("oldMTU", oldMTU).Info("Tunnel device MTU needs to be updated") if err := d.dataplane.LinkSetMTU(link, mtu); err != nil { log.WithError(err).Warn("Failed to set tunnel device MTU") return err } logCxt.Info("Updated tunnel MTU") } if attrs.Flags&net.FlagUp == 0 { logCxt.WithField("flags", attrs.Flags).Info("Tunnel wasn't admin up, enabling it") if err := d.dataplane.LinkSetUp(link); err != nil { log.WithError(err).Warn("Failed to set tunnel device up") return err } logCxt.Info("Set tunnel admin up") } if err := d.setLinkAddressV4("tunl0", address); err != nil { log.WithError(err).Warn("Failed to set tunnel device IP") return err } return nil } // setLinkAddressV4 updates the given link to set its local IP address. It removes any other // addresses. func (d *ipipManager) setLinkAddressV4(linkName string, address net.IP) error { logCxt := log.WithFields(log.Fields{ "link": linkName, "addr": address, }) logCxt.Debug("Setting local IPv4 address on link.") link, err := d.dataplane.LinkByName(linkName) if err != nil { log.WithError(err).WithField("name", linkName).Warning("Failed to get device") return err } addrs, err := d.dataplane.AddrList(link, netlink.FAMILY_V4) if err != nil { log.WithError(err).Warn("Failed to list interface addresses") return err } found := false for _, oldAddr := range addrs { if address != nil && oldAddr.IP.Equal(address) { logCxt.Debug("Address already present.") found = true continue } logCxt.WithField("oldAddr", oldAddr).Info("Removing old address") if err := d.dataplane.AddrDel(link, &oldAddr); err != nil { log.WithError(err).Warn("Failed to delete address") return err } } if !found && address != nil { logCxt.Info("Address wasn't present, adding it.") mask := net.CIDRMask(32, 32) ipNet := net.IPNet{ IP: address.Mask(mask), // Mask the IP to match ParseCIDR()'s behaviour. Mask: mask, } addr := &netlink.Addr{ IPNet: &ipNet, } if err := d.dataplane.AddrAdd(link, addr); err != nil { log.WithError(err).WithField("addr", address).Warn("Failed to add address") return err } } logCxt.Debug("Address set.") return nil } func (d *ipipManager) OnUpdate(msg interface{}) { switch msg := msg.(type) { case *proto.HostMetadataUpdate: log.WithField("hostanme", msg.Hostname).Debug("Host update/create") d.activeHostnameToIP[msg.Hostname] = msg.Ipv4Addr d.ipSetInSync = false case *proto.HostMetadataRemove: log.WithField("hostname", msg.Hostname).Debug("Host removed") delete(d.activeHostnameToIP, msg.Hostname) d.ipSetInSync = false } } func (m *ipipManager) CompleteDeferredWork() error { if !m.ipSetInSync { // For simplicity (and on the assumption that host add/removes are rare) rewrite // the whole IP set whenever we get a change. To replace this with delta handling // would require reference counting the IPs because it's possible for two hosts // to (at least transiently) share an IP. That would add occupancy and make the // code more complex. log.Info("All-hosts IP set out-of sync, refreshing it.") members := make([]string, 0, len(m.activeHostnameToIP)+len(m.externalNodeCIDRs)) for _, ip := range m.activeHostnameToIP { members = append(members, ip) } for _, ip := range m.externalNodeCIDRs { members = append(members, ip) } m.ipsetsDataplane.AddOrReplaceIPSet(m.ipSetMetadata, members) m.ipSetInSync = true } return nil } // ipsetsDataplane is a shim interface for mocking the IPSets object. type ipsetsDataplane interface { AddOrReplaceIPSet(setMetadata ipsets.IPSetMetadata, members []string) AddMembers(setID string, newMembers []string) RemoveMembers(setID string, removedMembers []string) RemoveIPSet(setID string) GetIPFamily() ipsets.IPFamily GetTypeOf(setID string) (ipsets.IPSetType, error) GetMembers(setID string) (set.Set, error) }
1
17,206
Same change just above?
projectcalico-felix
go
@@ -35,7 +35,8 @@ // Promise() being missing on some legacy browser, and a funky one // is Promise() present but buggy on WebOS 2 window.Promise = undefined; - window.Promise = undefined; + /* eslint-disable-next-line no-restricted-globals -- Explicit check on self needed */ + self.Promise = undefined; } if (!window.Promise) {
1
(function() { function injectScriptElement(src, onload) { if (!src) { return; } const script = document.createElement('script'); if (window.dashboardVersion) { src += `?v=${window.dashboardVersion}`; } script.src = src; script.setAttribute('async', ''); if (onload) { script.onload = onload; } document.head.appendChild(script); } function loadSite() { injectScriptElement( './libraries/alameda.js', function() { // onload of require library injectScriptElement('./scripts/site.js'); } ); } try { Promise.resolve(); } catch (ex) { // this checks for several cases actually, typical is // Promise() being missing on some legacy browser, and a funky one // is Promise() present but buggy on WebOS 2 window.Promise = undefined; window.Promise = undefined; } if (!window.Promise) { // Load Promise polyfill if they are not natively supported injectScriptElement( './libraries/npo.js', loadSite ); } else { loadSite(); } })();
1
17,484
I suppose `apploader.js` isn't used by WebWorkers. So `self` will always be `window` here.
jellyfin-jellyfin-web
js
@@ -7,13 +7,7 @@ test_name "bolt plan run should apply manifest block on remote hosts via ssh" do extend Acceptance::BoltCommandHelper ssh_nodes = select_hosts(roles: ['ssh']) - skip_targets = select_hosts(platform: [/debian-8/]) targets = "ssh_nodes" - if skip_targets.any? - ssh_nodes -= skip_targets - targets = ssh_nodes.each_with_object([]) { |node, acc| acc.push(node[:vmhostname]) }.join(",") - end - skip_test('no applicable nodes to test on') if ssh_nodes.empty? dir = bolt.tmpdir('apply_ssh')
1
# frozen_string_literal: true require 'bolt_command_helper' require 'json' test_name "bolt plan run should apply manifest block on remote hosts via ssh" do extend Acceptance::BoltCommandHelper ssh_nodes = select_hosts(roles: ['ssh']) skip_targets = select_hosts(platform: [/debian-8/]) targets = "ssh_nodes" if skip_targets.any? ssh_nodes -= skip_targets targets = ssh_nodes.each_with_object([]) { |node, acc| acc.push(node[:vmhostname]) }.join(",") end skip_test('no applicable nodes to test on') if ssh_nodes.empty? dir = bolt.tmpdir('apply_ssh') fixtures = File.absolute_path('files') filepath = File.join('/tmp', SecureRandom.uuid.to_s) step "create plan on bolt controller" do on(bolt, "mkdir -p #{dir}/modules") scp_to(bolt, File.join(fixtures, 'example_apply'), "#{dir}/modules/example_apply") end bolt_command = "bolt plan run example_apply filepath=#{filepath}" flags = { '--modulepath' => modulepath(File.join(dir, 'modules')), '--format' => 'json', '-t' => targets } teardown do on(ssh_nodes, "rm -rf #{filepath}") end step "execute `bolt plan run` via SSH with json output" do result = bolt_command_on(bolt, bolt_command, flags) assert_equal(0, result.exit_code, "Bolt did not exit with exit code 0") begin json = JSON.parse(result.stdout) rescue JSON::ParserError assert_equal("Output should be JSON", result.string, "Output should be JSON") end ssh_nodes.each do |node| # Verify that node succeeded host = node.hostname result = json.select { |n| n['target'] == host } assert_equal('success', result[0]['status'], "The task did not succeed on #{host}") # Verify the custom type was invoked logs = result[0]['value']['report']['logs'] warnings = logs.select { |l| l['level'] == 'warning' } assert_equal(1, warnings.count) assert_equal('Writing a MOTD!', warnings[0]['message']) # Verify that files were created on the target hello = on(node, "cat #{filepath}/hello.txt") assert_match(/^hi there I'm [a-zA-Z]+$/, hello.stdout) motd = on(node, "cat #{filepath}/motd") assert_equal("Today's #WordOfTheDay is 'gloss'", motd.stdout) end end step "puppet service should be stopped" do service_command = "bolt plan run example_apply::puppet_status" result = bolt_command_on(bolt, service_command, flags) assert_equal(0, result.exit_code, "Bolt did not exit with exit code 0") begin json = JSON.parse(result.stdout) rescue JSON::ParserError assert_equal("Output should be JSON", result.string, "Output should be JSON") end ssh_nodes.each do |node| # Verify that node succeeded host = node.hostname result = json.select { |n| n['target'] == host } assert_equal('success', result[0]['status'], "The task did not succeed on #{host}") assert_match(/stopped|absent/, result[0]['value']['status'], "Puppet must be stopped") assert_equal('false', result[0]['value']['enabled'], "Puppet must be disabled") end end step "apply as non-root user" do user = 'apply_nonroot' step 'create nonroot user on targets' do # managehome fails here, so we manage the homedir seprately on(ssh_nodes, "/opt/puppetlabs/bin/puppet resource user #{user} ensure=present") on(ssh_nodes, "/opt/puppetlabs/bin/puppet resource file $(echo ~#{user}) ensure=directory") teardown do on(ssh_nodes, "/opt/puppetlabs/bin/puppet resource file $(echo ~#{user}) ensure=absent") on(ssh_nodes, "/opt/puppetlabs/bin/puppet resource user #{user} ensure=absent") end end step 'create nonroot user-owned directory on targets' do filepath = "/tmp/mydir" on(ssh_nodes, "/opt/puppetlabs/bin/puppet resource file #{filepath} ensure=directory owner=#{user}") teardown do on(ssh_nodes, "/opt/puppetlabs/bin/puppet resource file #{filepath} ensure=absent") end end step 'disable requiretty for root user' do linux_nodes = ssh_nodes.reject { |host| host['platform'] =~ /osx/ } create_remote_file(linux_nodes, "/etc/sudoers.d/#{user}", <<-FILE) Defaults:root !requiretty FILE teardown do on(linux_nodes, "rm /etc/sudoers.d/#{user}") end end bolt_command = "bolt plan run example_apply filepath=#{filepath}" step "execute `bolt plan run run_as=#{user}` via SSH with json output" do result = bolt_command_on(bolt, bolt_command + " run_as=#{user}", flags) assert_equal(0, result.exit_code, "Bolt did not exit with exit code 0") begin json = JSON.parse(result.stdout) rescue JSON::ParserError assert_equal("Output should be JSON", result.string, "Output should be JSON") end ssh_nodes.each do |node| host = node.hostname result = json.select { |n| n['target'] == host }.first assert_equal('success', result['status'], "The task failed on #{host}") stat = if node['platform'] =~ /osx/ "stat -f %Su #{filepath}/hello.txt" else "stat -c %U #{filepath}/hello.txt" end owner_result = bolt_command_on(bolt, "bolt command run \"#{stat}\" -t #{host} --format json") # It's times like this I think I'm just a highly paid data parser owner = JSON.parse(owner_result.stdout)['items'].first['value']['stdout'].strip assert_equal(user, owner, "The file created in the apply block is not owned by the run_as user") end end end end
1
17,593
Since this var is no longer defined we should remove the `if skip_targets.any?` bit below.
puppetlabs-bolt
rb
@@ -170,6 +170,12 @@ def func_arn(function_name): return aws_stack.lambda_function_arn(function_name) +def func_qualifier(function_name, qualifier=None): + arn = aws_stack.lambda_function_arn(function_name) + if ARN_TO_LAMBDA.get(arn).qualifier_exists(qualifier): + return '{}:{}'.format(arn, qualifier) + + def check_batch_size_range(source_arn, batch_size=None): batch_size_entry = BATCH_SIZE_RANGES.get(source_arn.split(':')[2].lower()) if not batch_size_entry:
1
import re import os import imp import sys import json import uuid import time import base64 import logging import threading import traceback import hashlib import functools from io import BytesIO from datetime import datetime from six.moves import cStringIO as StringIO from six.moves.urllib.parse import urlparse from flask import Flask, Response, jsonify, request from localstack import config from localstack.constants import TEST_AWS_ACCOUNT_ID from localstack.utils.aws import aws_stack, aws_responses from localstack.services.awslambda import lambda_executors from localstack.services.awslambda.lambda_executors import ( LAMBDA_RUNTIME_PYTHON27, LAMBDA_RUNTIME_PYTHON36, LAMBDA_RUNTIME_PYTHON37, LAMBDA_RUNTIME_PYTHON38, LAMBDA_RUNTIME_NODEJS, LAMBDA_RUNTIME_NODEJS610, LAMBDA_RUNTIME_NODEJS810, LAMBDA_RUNTIME_JAVA8, LAMBDA_RUNTIME_JAVA11, LAMBDA_RUNTIME_DOTNETCORE2, LAMBDA_RUNTIME_DOTNETCORE21, LAMBDA_RUNTIME_DOTNETCORE31, LAMBDA_RUNTIME_GOLANG, LAMBDA_RUNTIME_RUBY, LAMBDA_RUNTIME_RUBY25, LAMBDA_RUNTIME_PROVIDED) from localstack.services.awslambda.multivalue_transformer import multi_value_dict_for_list from localstack.utils.common import ( to_str, to_bytes, load_file, save_file, TMP_FILES, ensure_readable, short_uid, json_safe, mkdir, unzip, is_zip_file, run, first_char_to_lower, timestamp_millis, now_utc, safe_requests, FuncThread, isoformat_milliseconds, synchronized) from localstack.utils.analytics import event_publisher from localstack.utils.http_utils import parse_chunked_data from localstack.utils.aws.aws_models import LambdaFunction # logger LOG = logging.getLogger(__name__) APP_NAME = 'lambda_api' PATH_ROOT = '/2015-03-31' ARCHIVE_FILE_PATTERN = '%s/lambda.handler.*.jar' % config.TMP_FOLDER LAMBDA_SCRIPT_PATTERN = '%s/lambda_script_*.py' % config.TMP_FOLDER # List of Lambda runtime names. Keep them in this list, mainly to silence the linter LAMBDA_RUNTIMES = [LAMBDA_RUNTIME_PYTHON27, LAMBDA_RUNTIME_PYTHON36, LAMBDA_RUNTIME_PYTHON37, LAMBDA_RUNTIME_PYTHON38, LAMBDA_RUNTIME_DOTNETCORE2, LAMBDA_RUNTIME_DOTNETCORE21, LAMBDA_RUNTIME_DOTNETCORE31, LAMBDA_RUNTIME_NODEJS, LAMBDA_RUNTIME_NODEJS610, LAMBDA_RUNTIME_NODEJS810, LAMBDA_RUNTIME_JAVA8, LAMBDA_RUNTIME_JAVA11, LAMBDA_RUNTIME_RUBY, LAMBDA_RUNTIME_RUBY25] DOTNET_LAMBDA_RUNTIMES = [LAMBDA_RUNTIME_DOTNETCORE2, LAMBDA_RUNTIME_DOTNETCORE21, LAMBDA_RUNTIME_DOTNETCORE31] # default timeout in seconds LAMBDA_DEFAULT_TIMEOUT = 3 # default handler and runtime LAMBDA_DEFAULT_HANDLER = 'handler.handler' LAMBDA_DEFAULT_RUNTIME = LAMBDA_RUNTIME_PYTHON38 LAMBDA_DEFAULT_STARTING_POSITION = 'LATEST' LAMBDA_ZIP_FILE_NAME = 'original_lambda_archive.zip' LAMBDA_JAR_FILE_NAME = 'original_lambda_archive.jar' INVALID_PARAMETER_VALUE_EXCEPTION = 'InvalidParameterValueException' VERSION_LATEST = '$LATEST' FUNCTION_MAX_SIZE = 69905067 BATCH_SIZE_RANGES = { 'kinesis': (100, 10000), 'dynamodb': (100, 1000), 'sqs': (10, 10) } app = Flask(APP_NAME) # map ARN strings to lambda function objects ARN_TO_LAMBDA = {} # list of event source mappings for the API EVENT_SOURCE_MAPPINGS = [] # mutex for access to CWD and ENV EXEC_MUTEX = threading.RLock(1) # whether to use Docker for execution DO_USE_DOCKER = None # start characters indicating that a lambda result should be parsed as JSON JSON_START_CHAR_MAP = { list: ('[',), tuple: ('[',), dict: ('{',), str: ('"',), bytes: ('"',), bool: ('t', 'f'), type(None): ('n',), int: ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'), float: ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9') } POSSIBLE_JSON_TYPES = (str, bytes) JSON_START_TYPES = tuple(set(JSON_START_CHAR_MAP.keys()) - set(POSSIBLE_JSON_TYPES)) JSON_START_CHARS = tuple(set(functools.reduce(lambda x, y: x + y, JSON_START_CHAR_MAP.values()))) # SQS listener thread settings SQS_LISTENER_THREAD = {} SQS_POLL_INTERVAL_SEC = 1 # lambda executor instance LAMBDA_EXECUTOR = lambda_executors.AVAILABLE_EXECUTORS.get(config.LAMBDA_EXECUTOR, lambda_executors.DEFAULT_EXECUTOR) # IAM policy constants IAM_POLICY_VERSION = '2012-10-17' POLICY_NAME_PATTERN = 'lambda_policy_%s' # Whether to check if the handler function exists while creating lambda function CHECK_HANDLER_ON_CREATION = False # Marker name to indicate that a bucket represents the local file system. This is used for testing # Serverless applications where we mount the Lambda code directly into the container from the host OS. BUCKET_MARKER_LOCAL = '__local__' class ClientError(Exception): def __init__(self, msg, code=400): super(ClientError, self).__init__(msg) self.code = code self.msg = msg def get_response(self): if isinstance(self.msg, Response): return self.msg return error_response(self.msg, self.code) class LambdaContext(object): def __init__(self, func_details, qualifier=None, context=None): self.function_name = func_details.name() self.function_version = func_details.get_qualifier_version(qualifier) self.client_context = context.get('client_context') self.invoked_function_arn = func_details.arn() if qualifier: self.invoked_function_arn += ':' + qualifier self.cognito_identity = context.get('identity') def get_remaining_time_in_millis(self): # TODO implement! return 1000 * 60 def cleanup(): global EVENT_SOURCE_MAPPINGS, ARN_TO_LAMBDA ARN_TO_LAMBDA = {} EVENT_SOURCE_MAPPINGS = [] LAMBDA_EXECUTOR.cleanup() def func_arn(function_name): return aws_stack.lambda_function_arn(function_name) def check_batch_size_range(source_arn, batch_size=None): batch_size_entry = BATCH_SIZE_RANGES.get(source_arn.split(':')[2].lower()) if not batch_size_entry: raise ValueError( INVALID_PARAMETER_VALUE_EXCEPTION, 'Unsupported event source type' ) batch_size = batch_size or batch_size_entry[0] if batch_size > batch_size_entry[1]: raise ValueError( INVALID_PARAMETER_VALUE_EXCEPTION, 'BatchSize {} exceeds the max of {}'.format(batch_size, batch_size_entry[1]) ) return batch_size def add_function_mapping(lambda_name, lambda_handler, lambda_cwd=None): arn = func_arn(lambda_name) ARN_TO_LAMBDA[arn].versions.get(VERSION_LATEST)['Function'] = lambda_handler ARN_TO_LAMBDA[arn].cwd = lambda_cwd def add_event_source(function_name, source_arn, enabled, batch_size=None): batch_size = check_batch_size_range(source_arn, batch_size) mapping = { 'UUID': str(uuid.uuid4()), 'StateTransitionReason': 'User action', 'LastModified': float(time.mktime(datetime.utcnow().timetuple())), 'BatchSize': batch_size, 'State': 'Enabled' if enabled in [True, None] else 'Disabled', 'FunctionArn': func_arn(function_name), 'EventSourceArn': source_arn, 'LastProcessingResult': 'OK', 'StartingPosition': LAMBDA_DEFAULT_STARTING_POSITION } EVENT_SOURCE_MAPPINGS.append(mapping) return mapping def update_event_source(uuid_value, function_name, enabled, batch_size): for m in EVENT_SOURCE_MAPPINGS: if uuid_value == m['UUID']: if function_name: m['FunctionArn'] = func_arn(function_name) batch_size = check_batch_size_range(m['EventSourceArn'], batch_size or m['BatchSize']) m['BatchSize'] = batch_size m['State'] = 'Enabled' if enabled is True else 'Disabled' m['LastModified'] = float(time.mktime(datetime.utcnow().timetuple())) return m return {} def delete_event_source(uuid_value): for i, m in enumerate(EVENT_SOURCE_MAPPINGS): if uuid_value == m['UUID']: return EVENT_SOURCE_MAPPINGS.pop(i) return {} @synchronized(lock=EXEC_MUTEX) def use_docker(): global DO_USE_DOCKER if DO_USE_DOCKER is None: DO_USE_DOCKER = False if 'docker' in config.LAMBDA_EXECUTOR: try: run('docker images', print_error=False) DO_USE_DOCKER = True except Exception: pass return DO_USE_DOCKER def get_stage_variables(api_id, stage): api_gateway_client = aws_stack.connect_to_service('apigateway') response = api_gateway_client.get_stage(restApiId=api_id, stageName=stage) return response.get('variables', None) def fix_proxy_path_params(path_params): proxy_path_param_value = path_params.get('proxy+') if not proxy_path_param_value: return del path_params['proxy+'] path_params['proxy'] = proxy_path_param_value def message_attributes_to_lower(message_attrs): """ Convert message attribute details (first characters) to lower case (e.g., stringValue, dataType). """ message_attrs = message_attrs or {} for _, attr in message_attrs.items(): if not isinstance(attr, dict): continue for key, value in dict(attr).items(): attr[first_char_to_lower(key)] = attr.pop(key) return message_attrs def process_apigateway_invocation(func_arn, path, payload, stage, api_id, headers={}, resource_path=None, method=None, path_params={}, query_string_params=None, request_context={}, event_context={}): try: resource_path = resource_path or path path_params = dict(path_params) fix_proxy_path_params(path_params) event = { 'path': path, 'headers': dict(headers), 'multiValueHeaders': multi_value_dict_for_list(headers), 'pathParameters': path_params, 'body': payload, 'isBase64Encoded': False, 'resource': resource_path, 'httpMethod': method, 'queryStringParameters': query_string_params, 'multiValueQueryStringParameters': multi_value_dict_for_list(query_string_params), 'requestContext': request_context, 'stageVariables': get_stage_variables(api_id, stage), } LOG.debug('Running Lambda function %s from API Gateway invocation: %s %s' % (func_arn, method or 'GET', path)) return run_lambda(event=event, context=event_context, func_arn=func_arn, asynchronous=not config.SYNCHRONOUS_API_GATEWAY_EVENTS) except Exception as e: LOG.warning('Unable to run Lambda function on API Gateway message: %s %s' % (e, traceback.format_exc())) def process_sns_notification(func_arn, topic_arn, subscription_arn, message, message_id, message_attributes, unsubscribe_url, subject='',): event = { 'Records': [{ 'EventSource': 'localstack:sns', 'EventVersion': '1.0', 'EventSubscriptionArn': subscription_arn, 'Sns': { 'Type': 'Notification', 'MessageId': message_id, 'TopicArn': topic_arn, 'Subject': subject, 'Message': message, 'Timestamp': timestamp_millis(), 'SignatureVersion': '1', # TODO Add a more sophisticated solution with an actual signature # Hardcoded 'Signature': 'EXAMPLEpH+..', 'SigningCertUrl': 'https://sns.us-east-1.amazonaws.com/SimpleNotificationService-000000000.pem', 'UnsubscribeUrl': unsubscribe_url, 'MessageAttributes': message_attributes } }] } return run_lambda(event=event, context={}, func_arn=func_arn, asynchronous=not config.SYNCHRONOUS_SNS_EVENTS) def process_kinesis_records(records, stream_name): def chunks(lst, n): # Yield successive n-sized chunks from lst. for i in range(0, len(lst), n): yield lst[i:i + n] # feed records into listening lambdas try: stream_arn = aws_stack.kinesis_stream_arn(stream_name) sources = get_event_sources(source_arn=stream_arn) for source in sources: arn = source['FunctionArn'] for chunk in chunks(records, source['BatchSize']): event = { 'Records': [ { 'eventID': 'shardId-000000000000:{0}'.format(rec['sequenceNumber']), 'eventSourceARN': stream_arn, 'eventSource': 'aws:kinesis', 'eventVersion': '1.0', 'eventName': 'aws:kinesis:record', 'invokeIdentityArn': 'arn:aws:iam::{0}:role/lambda-role'.format(TEST_AWS_ACCOUNT_ID), 'awsRegion': aws_stack.get_region(), 'kinesis': rec } for rec in chunk ] } run_lambda(event=event, context={}, func_arn=arn, asynchronous=not config.SYNCHRONOUS_KINESIS_EVENTS) except Exception as e: LOG.warning('Unable to run Lambda function on Kinesis records: %s %s' % (e, traceback.format_exc())) def start_lambda_sqs_listener(): if SQS_LISTENER_THREAD: return def send_event_to_lambda(queue_arn, queue_url, lambda_arn, messages, region): def delete_messages(result, func_arn, event, error=None, dlq_sent=None, **kwargs): if error and not dlq_sent: # Skip deleting messages from the queue in case of processing errors AND if # the message has not yet been sent to a dead letter queue (DLQ). # We'll pick them up and retry next time they become available on the queue. return sqs_client = aws_stack.connect_to_service('sqs') entries = [{'Id': r['receiptHandle'], 'ReceiptHandle': r['receiptHandle']} for r in records] sqs_client.delete_message_batch(QueueUrl=queue_url, Entries=entries) records = [] for msg in messages: message_attrs = message_attributes_to_lower(msg.get('MessageAttributes')) records.append({ 'body': msg['Body'], 'receiptHandle': msg['ReceiptHandle'], 'md5OfBody': msg['MD5OfBody'], 'eventSourceARN': queue_arn, 'eventSource': lambda_executors.EVENT_SOURCE_SQS, 'awsRegion': region, 'messageId': msg['MessageId'], 'attributes': msg.get('Attributes', {}), 'messageAttributes': message_attrs, 'md5OfMessageAttributes': msg.get('MD5OfMessageAttributes'), 'sqs': True, }) event = {'Records': records} # TODO implement retries, based on "RedrivePolicy.maxReceiveCount" in the queue settings run_lambda(event=event, context={}, func_arn=lambda_arn, asynchronous=True, callback=delete_messages) def listener_loop(*args): while True: try: sources = get_event_sources(source_arn=r'.*:sqs:.*') if not sources: # Temporarily disable polling if no event sources are configured # anymore. The loop will get restarted next time a message # arrives and if an event source is configured. SQS_LISTENER_THREAD.pop('_thread_') return sqs_client = aws_stack.connect_to_service('sqs') for source in sources: queue_arn = source['EventSourceArn'] lambda_arn = source['FunctionArn'] batch_size = max(min(source.get('BatchSize', 1), 10), 1) try: region_name = queue_arn.split(':')[3] queue_url = aws_stack.sqs_queue_url_for_arn(queue_arn) result = sqs_client.receive_message( QueueUrl=queue_url, MessageAttributeNames=['All'], MaxNumberOfMessages=batch_size ) messages = result.get('Messages') if not messages: continue send_event_to_lambda(queue_arn, queue_url, lambda_arn, messages, region=region_name) except Exception as e: LOG.debug('Unable to poll SQS messages for queue %s: %s' % (queue_arn, e)) except Exception: pass finally: time.sleep(SQS_POLL_INTERVAL_SEC) LOG.debug('Starting SQS message polling thread for Lambda API') SQS_LISTENER_THREAD['_thread_'] = FuncThread(listener_loop) SQS_LISTENER_THREAD['_thread_'].start() def process_sqs_message(queue_name, region_name=None): # feed message into the first listening lambda (message should only get processed once) try: region_name = region_name or aws_stack.get_region() queue_arn = aws_stack.sqs_queue_arn(queue_name, region_name=region_name) sources = get_event_sources(source_arn=queue_arn) arns = [s.get('FunctionArn') for s in sources] source = (sources or [None])[0] if not source: return False LOG.debug('Found %s source mappings for event from SQS queue %s: %s' % (len(arns), queue_arn, arns)) start_lambda_sqs_listener() return True except Exception as e: LOG.warning('Unable to run Lambda function on SQS messages: %s %s' % (e, traceback.format_exc())) def get_event_sources(func_name=None, source_arn=None): result = [] for m in EVENT_SOURCE_MAPPINGS: if not func_name or (m['FunctionArn'] in [func_name, func_arn(func_name)]): if _arn_match(mapped=m['EventSourceArn'], searched=source_arn): result.append(m) return result def _arn_match(mapped, searched): if not searched or mapped == searched: return True # Some types of ARNs can end with a path separated by slashes, for # example the ARN of a DynamoDB stream is tableARN/stream/ID. It's # a little counterintuitive that a more specific mapped ARN can # match a less specific ARN on the event, but some integration tests # rely on it for things like subscribing to a stream and matching an # event labeled with the table ARN. if re.match(r'^%s$' % searched, mapped): return True if mapped.startswith(searched): suffix = mapped[len(searched):] return suffix[0] == '/' return False def get_function_version(arn, version): func = ARN_TO_LAMBDA.get(arn) return format_func_details(func, version=version, always_add_version=True) def publish_new_function_version(arn): func_details = ARN_TO_LAMBDA.get(arn) versions = func_details.versions last_version = func_details.max_version() versions[str(last_version + 1)] = { 'CodeSize': versions.get(VERSION_LATEST).get('CodeSize'), 'CodeSha256': versions.get(VERSION_LATEST).get('CodeSha256'), 'Function': versions.get(VERSION_LATEST).get('Function'), 'RevisionId': str(uuid.uuid4()) } return get_function_version(arn, str(last_version + 1)) def do_list_versions(arn): return sorted([get_function_version(arn, version) for version in ARN_TO_LAMBDA.get(arn).versions.keys()], key=lambda k: str(k.get('Version'))) def do_update_alias(arn, alias, version, description=None): new_alias = { 'AliasArn': arn + ':' + alias, 'FunctionVersion': version, 'Name': alias, 'Description': description or '', 'RevisionId': str(uuid.uuid4()) } ARN_TO_LAMBDA.get(arn).aliases[alias] = new_alias return new_alias def run_lambda(event, context, func_arn, version=None, suppress_output=False, asynchronous=False, callback=None): if suppress_output: stdout_ = sys.stdout stderr_ = sys.stderr stream = StringIO() sys.stdout = stream sys.stderr = stream try: func_arn = aws_stack.fix_arn(func_arn) func_details = ARN_TO_LAMBDA.get(func_arn) if not func_details: return not_found_error(msg='The resource specified in the request does not exist.') context = LambdaContext(func_details, version, context) result = LAMBDA_EXECUTOR.execute(func_arn, func_details, event, context=context, version=version, asynchronous=asynchronous, callback=callback) except Exception as e: exc_type, exc_value, exc_traceback = sys.exc_info() response = { 'errorType': str(exc_type.__name__), 'errorMessage': str(e), 'stackTrace': traceback.format_tb(exc_traceback) } LOG.info('Error executing Lambda function %s: %s %s' % (func_arn, e, traceback.format_exc())) return Response(json.dumps(response), status=500) finally: if suppress_output: sys.stdout = stdout_ sys.stderr = stderr_ return result def exec_lambda_code(script, handler_function='handler', lambda_cwd=None, lambda_env=None): if lambda_cwd or lambda_env: EXEC_MUTEX.acquire() if lambda_cwd: previous_cwd = os.getcwd() os.chdir(lambda_cwd) sys.path = [lambda_cwd] + sys.path if lambda_env: previous_env = dict(os.environ) os.environ.update(lambda_env) # generate lambda file name lambda_id = 'l_%s' % short_uid() lambda_file = LAMBDA_SCRIPT_PATTERN.replace('*', lambda_id) save_file(lambda_file, script) # delete temporary .py and .pyc files on exit TMP_FILES.append(lambda_file) TMP_FILES.append('%sc' % lambda_file) try: pre_sys_modules_keys = set(sys.modules.keys()) try: handler_module = imp.load_source(lambda_id, lambda_file) module_vars = handler_module.__dict__ finally: # the above import can bring files for the function # (eg settings.py) into the global namespace. subsequent # calls can pick up file from another function, causing # general issues. post_sys_modules_keys = set(sys.modules.keys()) for key in post_sys_modules_keys: if key not in pre_sys_modules_keys: sys.modules.pop(key) except Exception as e: LOG.error('Unable to exec: %s %s' % (script, traceback.format_exc())) raise e finally: if lambda_cwd or lambda_env: if lambda_cwd: os.chdir(previous_cwd) sys.path.pop(0) if lambda_env: os.environ = previous_env EXEC_MUTEX.release() return module_vars[handler_function] def get_handler_file_from_name(handler_name, runtime=LAMBDA_DEFAULT_RUNTIME): # TODO: support Java Lambdas in the future if runtime.startswith(LAMBDA_RUNTIME_PROVIDED): return 'bootstrap' delimiter = '.' if runtime.startswith(LAMBDA_RUNTIME_NODEJS): file_ext = '.js' elif runtime.startswith(LAMBDA_RUNTIME_GOLANG): file_ext = '' elif runtime.startswith(tuple(DOTNET_LAMBDA_RUNTIMES)): file_ext = '.dll' delimiter = ':' elif runtime.startswith(LAMBDA_RUNTIME_RUBY): file_ext = '.rb' else: handler_name = handler_name.rpartition(delimiter)[0].replace(delimiter, os.path.sep) file_ext = '.py' return '%s%s' % (handler_name.split(delimiter)[0], file_ext) def get_handler_function_from_name(handler_name, runtime=LAMBDA_DEFAULT_RUNTIME): # TODO: support Java Lambdas in the future if runtime.startswith(tuple(DOTNET_LAMBDA_RUNTIMES)): return handler_name.split(':')[-1] else: return handler_name.split('.')[-1] def error_response(msg, code=500, error_type='InternalFailure'): LOG.warning(msg) return aws_responses.flask_error_response_json(msg, code=code, error_type=error_type) def get_zip_bytes(function_code): """Returns the ZIP file contents from a FunctionCode dict. :type function_code: dict :param function_code: https://docs.aws.amazon.com/lambda/latest/dg/API_FunctionCode.html :returns: bytes of the Zip file. """ function_code = function_code or {} if 'S3Bucket' in function_code: s3_client = aws_stack.connect_to_service('s3') bytes_io = BytesIO() try: s3_client.download_fileobj(function_code['S3Bucket'], function_code['S3Key'], bytes_io) zip_file_content = bytes_io.getvalue() except Exception as e: raise ClientError('Unable to fetch Lambda archive from S3: %s' % e, 404) elif 'ZipFile' in function_code: zip_file_content = function_code['ZipFile'] zip_file_content = base64.b64decode(zip_file_content) else: raise ClientError('No valid Lambda archive specified: %s' % list(function_code.keys())) return zip_file_content def get_java_handler(zip_file_content, main_file, func_details=None): """Creates a Java handler from an uploaded ZIP or JAR. :type zip_file_content: bytes :param zip_file_content: ZIP file bytes. :type handler: str :param handler: The lambda handler path. :type main_file: str :param main_file: Filepath to the uploaded ZIP or JAR file. :returns: function or flask.Response """ if is_zip_file(zip_file_content): def execute(event, context): result = lambda_executors.EXECUTOR_LOCAL.execute_java_lambda( event, context, main_file=main_file, func_details=func_details) return result return execute raise ClientError(error_response( 'Unable to extract Java Lambda handler - file is not a valid zip/jar file', 400, error_type='ValidationError')) def set_archive_code(code, lambda_name, zip_file_content=None): # get metadata lambda_arn = func_arn(lambda_name) lambda_details = ARN_TO_LAMBDA[lambda_arn] is_local_mount = code.get('S3Bucket') == BUCKET_MARKER_LOCAL if is_local_mount and config.LAMBDA_REMOTE_DOCKER: msg = 'Please note that Lambda mounts (bucket name "%s") cannot be used with LAMBDA_REMOTE_DOCKER=1' raise Exception(msg % BUCKET_MARKER_LOCAL) # Stop/remove any containers that this arn uses. LAMBDA_EXECUTOR.cleanup(lambda_arn) if is_local_mount: # Mount or use a local folder lambda executors can reference # WARNING: this means we're pointing lambda_cwd to a local path in the user's # file system! We must ensure that there is no data loss (i.e., we must *not* add # this folder to TMP_FILES or similar). return code['S3Key'] # get file content zip_file_content = zip_file_content or get_zip_bytes(code) # Save the zip file to a temporary file that the lambda executors can reference code_sha_256 = base64.standard_b64encode(hashlib.sha256(zip_file_content).digest()) latest_version = lambda_details.get_version(VERSION_LATEST) latest_version['CodeSize'] = len(zip_file_content) latest_version['CodeSha256'] = code_sha_256.decode('utf-8') tmp_dir = '%s/zipfile.%s' % (config.TMP_FOLDER, short_uid()) mkdir(tmp_dir) tmp_file = '%s/%s' % (tmp_dir, LAMBDA_ZIP_FILE_NAME) save_file(tmp_file, zip_file_content) TMP_FILES.append(tmp_dir) lambda_details.cwd = tmp_dir return tmp_dir def set_function_code(code, lambda_name, lambda_cwd=None): def generic_handler(event, context): raise ClientError(('Unable to find executor for Lambda function "%s". Note that ' + 'Node.js, Golang, and .Net Core Lambdas currently require LAMBDA_EXECUTOR=docker') % lambda_name) arn = func_arn(lambda_name) lambda_details = ARN_TO_LAMBDA[arn] runtime = lambda_details.runtime lambda_environment = lambda_details.envvars handler_name = lambda_details.handler = lambda_details.handler or LAMBDA_DEFAULT_HANDLER code_passed = code code = code or lambda_details.code is_local_mount = code.get('S3Bucket') == BUCKET_MARKER_LOCAL zip_file_content = None if code_passed: lambda_cwd = lambda_cwd or set_archive_code(code_passed, lambda_name) if not is_local_mount: # Save the zip file to a temporary file that the lambda executors can reference zip_file_content = get_zip_bytes(code_passed) else: lambda_cwd = lambda_cwd or lambda_details.cwd # get local lambda working directory tmp_file = '%s/%s' % (lambda_cwd, LAMBDA_ZIP_FILE_NAME) if not zip_file_content: zip_file_content = load_file(tmp_file, mode='rb') # Set the appropriate lambda handler. lambda_handler = generic_handler is_java = lambda_executors.is_java_lambda(runtime) if is_java: # The Lambda executors for Docker subclass LambdaExecutorContainers, which # runs Lambda in Docker by passing all *.jar files in the function working # directory as part of the classpath. Obtain a Java handler function below. lambda_handler = get_java_handler(zip_file_content, tmp_file, func_details=lambda_details) if not is_local_mount: # Lambda code must be uploaded in Zip format if not is_zip_file(zip_file_content): raise ClientError( 'Uploaded Lambda code for runtime ({}) is not in Zip format'.format(runtime)) # Unzip the Lambda archive contents unzip(tmp_file, lambda_cwd) # Obtain handler details for any non-Java Lambda function if not is_java: handler_file = get_handler_file_from_name(handler_name, runtime=runtime) handler_function = get_handler_function_from_name(handler_name, runtime=runtime) main_file = '%s/%s' % (lambda_cwd, handler_file) if CHECK_HANDLER_ON_CREATION and not os.path.exists(main_file): # Raise an error if (1) this is not a local mount lambda, or (2) we're # running Lambdas locally (not in Docker), or (3) we're using remote Docker. # -> We do *not* want to raise an error if we're using local mount in non-remote Docker if not is_local_mount or not use_docker() or config.LAMBDA_REMOTE_DOCKER: file_list = run('cd "%s"; du -d 3 .' % lambda_cwd) config_debug = ('Config for local mount, docker, remote: "%s", "%s", "%s"' % (is_local_mount, use_docker(), config.LAMBDA_REMOTE_DOCKER)) LOG.debug('Lambda archive content:\n%s' % file_list) raise ClientError(error_response( 'Unable to find handler script (%s) in Lambda archive. %s' % (main_file, config_debug), 400, error_type='ValidationError')) if runtime.startswith('python') and not use_docker(): try: # make sure the file is actually readable, then read contents ensure_readable(main_file) zip_file_content = load_file(main_file, mode='rb') # extract handler lambda_handler = exec_lambda_code( zip_file_content, handler_function=handler_function, lambda_cwd=lambda_cwd, lambda_env=lambda_environment) except Exception as e: raise ClientError('Unable to get handler function from lambda code.', e) add_function_mapping(lambda_name, lambda_handler, lambda_cwd) return {'FunctionName': lambda_name} def do_list_functions(): funcs = [] this_region = aws_stack.get_region() for f_arn, func in ARN_TO_LAMBDA.items(): if type(func) != LambdaFunction: continue # filter out functions of current region func_region = f_arn.split(':')[3] if func_region != this_region: continue func_name = f_arn.split(':function:')[-1] arn = func_arn(func_name) func_details = ARN_TO_LAMBDA.get(arn) if not func_details: # this can happen if we're accessing Lambdas from a different region (ARN mismatch) continue details = format_func_details(func_details) details['Tags'] = func.tags funcs.append(details) return funcs def format_func_details(func_details, version=None, always_add_version=False): version = version or VERSION_LATEST func_version = func_details.get_version(version) result = { 'CodeSha256': func_version.get('CodeSha256'), 'Role': func_details.role, 'KMSKeyArn': func_details.kms_key_arn, 'Version': version, 'VpcConfig': func_details.vpc_config, 'FunctionArn': func_details.arn(), 'FunctionName': func_details.name(), 'CodeSize': func_version.get('CodeSize'), 'Handler': func_details.handler, 'Runtime': func_details.runtime, 'Timeout': func_details.timeout, 'Description': func_details.description, 'MemorySize': func_details.memory_size, 'LastModified': func_details.last_modified, 'TracingConfig': {'Mode': 'PassThrough'}, 'RevisionId': func_version.get('RevisionId'), 'State': 'Active', 'LastUpdateStatus': 'Successful' } if func_details.dead_letter_config: result['DeadLetterConfig'] = func_details.dead_letter_config if func_details.envvars: result['Environment'] = { 'Variables': func_details.envvars } if (always_add_version or version != VERSION_LATEST) and len(result['FunctionArn'].split(':')) <= 7: result['FunctionArn'] += ':%s' % version return result def forward_to_fallback_url(func_arn, data): """ If LAMBDA_FALLBACK_URL is configured, forward the invocation of this non-existing Lambda to the configured URL. """ if not config.LAMBDA_FALLBACK_URL: return None lambda_name = aws_stack.lambda_function_name(func_arn) if config.LAMBDA_FALLBACK_URL.startswith('dynamodb://'): table_name = urlparse(config.LAMBDA_FALLBACK_URL.replace('dynamodb://', 'http://')).netloc dynamodb = aws_stack.connect_to_service('dynamodb') item = { 'id': {'S': short_uid()}, 'timestamp': {'N': str(now_utc())}, 'payload': {'S': str(data)}, 'function_name': {'S': lambda_name} } aws_stack.create_dynamodb_table(table_name, partition_key='id') dynamodb.put_item(TableName=table_name, Item=item) return '' if re.match(r'^https?://.+', config.LAMBDA_FALLBACK_URL): headers = {'lambda-function-name': lambda_name} response = safe_requests.post(config.LAMBDA_FALLBACK_URL, data, headers=headers) return response.content raise ClientError('Unexpected value for LAMBDA_FALLBACK_URL: %s' % config.LAMBDA_FALLBACK_URL) def get_lambda_policy(function): iam_client = aws_stack.connect_to_service('iam') policies = iam_client.list_policies(Scope='Local', MaxItems=500)['Policies'] docs = [] for p in policies: # !TODO: Cache policy documents instead of running N+1 API calls here! versions = iam_client.list_policy_versions(PolicyArn=p['Arn'])['Versions'] default_version = [v for v in versions if v.get('IsDefaultVersion')] versions = default_version or versions doc = versions[0]['Document'] doc = doc if isinstance(doc, dict) else json.loads(doc) if not isinstance(doc['Statement'], list): doc['Statement'] = [doc['Statement']] for stmt in doc['Statement']: stmt['Principal'] = stmt.get('Principal') or {'AWS': TEST_AWS_ACCOUNT_ID} doc['PolicyArn'] = p['Arn'] doc['Id'] = 'default' docs.append(doc) policy = [d for d in docs if d['Statement'][0]['Resource'] == func_arn(function)] return (policy or [None])[0] def not_found_error(ref=None, msg=None): if not msg: msg = 'The resource you requested does not exist.' if ref: msg = '%s not found: %s' % ('Function' if ':function:' in ref else 'Resource', ref) return error_response(msg, 404, error_type='ResourceNotFoundException') # ------------ # API METHODS # ------------ @app.before_request def before_request(): # fix to enable chunked encoding, as this is used by some Lambda clients transfer_encoding = request.headers.get('Transfer-Encoding', '').lower() if transfer_encoding == 'chunked': request.environ['wsgi.input_terminated'] = True @app.route('%s/functions' % PATH_ROOT, methods=['POST']) def create_function(): """ Create new function --- operationId: 'createFunction' parameters: - name: 'request' in: body """ arn = 'n/a' try: if len(request.data) > FUNCTION_MAX_SIZE: return error_response('Request must be smaller than %s bytes for the CreateFunction operation' % FUNCTION_MAX_SIZE, 413, error_type='RequestEntityTooLargeException') data = json.loads(to_str(request.data)) lambda_name = data['FunctionName'] event_publisher.fire_event(event_publisher.EVENT_LAMBDA_CREATE_FUNC, payload={'n': event_publisher.get_hash(lambda_name)}) arn = func_arn(lambda_name) if arn in ARN_TO_LAMBDA: return error_response('Function already exist: %s' % lambda_name, 409, error_type='ResourceConflictException') ARN_TO_LAMBDA[arn] = func_details = LambdaFunction(arn) func_details.versions = {VERSION_LATEST: {'RevisionId': str(uuid.uuid4())}} func_details.vpc_config = data.get('VpcConfig', {}) func_details.last_modified = isoformat_milliseconds(datetime.utcnow()) + '+0000' func_details.description = data.get('Description', '') func_details.handler = data['Handler'] func_details.runtime = data['Runtime'] func_details.envvars = data.get('Environment', {}).get('Variables', {}) func_details.tags = data.get('Tags', {}) func_details.timeout = data.get('Timeout', LAMBDA_DEFAULT_TIMEOUT) func_details.role = data['Role'] func_details.kms_key_arn = data.get('KMSKeyArn') func_details.memory_size = data.get('MemorySize') func_details.code = data['Code'] func_details.set_dead_letter_config(data) result = set_function_code(func_details.code, lambda_name) if isinstance(result, Response): del ARN_TO_LAMBDA[arn] return result # remove content from code attribute, if present func_details.code.pop('ZipFile', None) # prepare result result.update(format_func_details(func_details)) if data.get('Publish'): result['Version'] = publish_new_function_version(arn)['Version'] return jsonify(result or {}) except Exception as e: ARN_TO_LAMBDA.pop(arn, None) if isinstance(e, ClientError): return e.get_response() return error_response('Unknown error: %s %s' % (e, traceback.format_exc())) @app.route('%s/functions/<function>' % PATH_ROOT, methods=['GET']) def get_function(function): """ Get details for a single function --- operationId: 'getFunction' parameters: - name: 'request' in: body - name: 'function' in: path """ funcs = do_list_functions() for func in funcs: if func['FunctionName'] == function: result = { 'Configuration': func, 'Code': { 'Location': '%s/code' % request.url }, 'Tags': func['Tags'] } lambda_details = ARN_TO_LAMBDA.get(func['FunctionArn']) if lambda_details.concurrency is not None: result['Concurrency'] = lambda_details.concurrency return jsonify(result) return not_found_error(func_arn(function)) @app.route('%s/functions/' % PATH_ROOT, methods=['GET']) def list_functions(): """ List functions --- operationId: 'listFunctions' parameters: - name: 'request' in: body """ funcs = do_list_functions() result = { 'Functions': funcs } return jsonify(result) @app.route('%s/functions/<function>' % PATH_ROOT, methods=['DELETE']) def delete_function(function): """ Delete an existing function --- operationId: 'deleteFunction' parameters: - name: 'request' in: body """ arn = func_arn(function) # Stop/remove any containers that this arn uses. LAMBDA_EXECUTOR.cleanup(arn) try: ARN_TO_LAMBDA.pop(arn) except KeyError: return not_found_error(func_arn(function)) event_publisher.fire_event(event_publisher.EVENT_LAMBDA_DELETE_FUNC, payload={'n': event_publisher.get_hash(function)}) i = 0 while i < len(EVENT_SOURCE_MAPPINGS): mapping = EVENT_SOURCE_MAPPINGS[i] if mapping['FunctionArn'] == arn: del EVENT_SOURCE_MAPPINGS[i] i -= 1 i += 1 result = {} return jsonify(result) @app.route('%s/functions/<function>/code' % PATH_ROOT, methods=['PUT']) def update_function_code(function): """ Update the code of an existing function --- operationId: 'updateFunctionCode' parameters: - name: 'request' in: body """ data = json.loads(to_str(request.data)) result = set_function_code(data, function) arn = func_arn(function) func_details = ARN_TO_LAMBDA.get(arn) result.update(format_func_details(func_details)) if isinstance(result, Response): return result return jsonify(result or {}) @app.route('%s/functions/<function>/code' % PATH_ROOT, methods=['GET']) def get_function_code(function): """ Get the code of an existing function --- operationId: 'getFunctionCode' parameters: """ arn = func_arn(function) lambda_cwd = ARN_TO_LAMBDA[arn].cwd tmp_file = '%s/%s' % (lambda_cwd, LAMBDA_ZIP_FILE_NAME) return Response(load_file(tmp_file, mode='rb'), mimetype='application/zip', headers={'Content-Disposition': 'attachment; filename=lambda_archive.zip'}) @app.route('%s/functions/<function>/configuration' % PATH_ROOT, methods=['GET']) def get_function_configuration(function): """ Get the configuration of an existing function --- operationId: 'getFunctionConfiguration' parameters: """ arn = func_arn(function) lambda_details = ARN_TO_LAMBDA.get(arn) if not lambda_details: return not_found_error(arn) result = format_func_details(lambda_details) return jsonify(result) @app.route('%s/functions/<function>/configuration' % PATH_ROOT, methods=['PUT']) def update_function_configuration(function): """ Update the configuration of an existing function --- operationId: 'updateFunctionConfiguration' parameters: - name: 'request' in: body """ data = json.loads(to_str(request.data)) arn = func_arn(function) # Stop/remove any containers that this arn uses. LAMBDA_EXECUTOR.cleanup(arn) lambda_details = ARN_TO_LAMBDA.get(arn) if not lambda_details: return error_response('Unable to find Lambda function ARN "%s"' % arn, 404, error_type='ResourceNotFoundException') if data.get('Handler'): lambda_details.handler = data['Handler'] if data.get('Runtime'): lambda_details.runtime = data['Runtime'] lambda_details.set_dead_letter_config(data) env_vars = data.get('Environment', {}).get('Variables') if env_vars is not None: lambda_details.envvars = env_vars if data.get('Timeout'): lambda_details.timeout = data['Timeout'] return jsonify(data) def generate_policy_statement(sid, action, arn, sourcearn, principal): statement = { 'Sid': sid, 'Effect': 'Allow', 'Action': action, 'Resource': arn, } # Adds SourceArn only if SourceArn is present if sourcearn: condition = { 'ArnLike': { 'AWS:SourceArn': sourcearn } } statement['Condition'] = condition # Adds Principal only if Principal is present if principal: principal = { 'Service': principal } statement['Principal'] = principal return statement def generate_policy(sid, action, arn, sourcearn, principal): new_statement = generate_policy_statement(sid, action, arn, sourcearn, principal) policy = { 'Version': IAM_POLICY_VERSION, 'Id': 'LambdaFuncAccess-%s' % sid, 'Statement': [new_statement] } return policy @app.route('%s/functions/<function>/policy' % PATH_ROOT, methods=['POST']) def add_permission(function): data = json.loads(to_str(request.data)) iam_client = aws_stack.connect_to_service('iam') sid = data.get('StatementId') action = data.get('Action') principal = data.get('Principal') sourcearn = data.get('SourceArn') arn = func_arn(function) previous_policy = get_lambda_policy(function) if arn not in ARN_TO_LAMBDA: return not_found_error(func_arn(function)) if not re.match(r'lambda:[*]|lambda:[a-zA-Z]+|[*]', action): return error_response('1 validation error detected: Value "%s" at "action" failed to satisfy ' 'constraint: Member must satisfy regular expression pattern: ' '(lambda:[*]|lambda:[a-zA-Z]+|[*])' % action, 400, error_type='ValidationException') new_policy = generate_policy(sid, action, arn, sourcearn, principal) if previous_policy: statment_with_sid = next((statement for statement in previous_policy['Statement'] if statement['Sid'] == sid), None) if statment_with_sid: return error_response('The statement id (%s) provided already exists. Please provide a new statement id,' ' or remove the existing statement.' % sid, 400, error_type='ResourceConflictException') new_policy['Statement'].extend(previous_policy['Statement']) iam_client.delete_policy(PolicyArn=previous_policy['PolicyArn']) iam_client.create_policy(PolicyName=POLICY_NAME_PATTERN % function, PolicyDocument=json.dumps(new_policy), Description='Policy for Lambda function "%s"' % function) result = {'Statement': json.dumps(new_policy['Statement'][0])} return jsonify(result) @app.route('%s/functions/<function>/policy/<statement>' % PATH_ROOT, methods=['DELETE']) def remove_permission(function, statement): qualifier = request.args.get('Qualifier') iam_client = aws_stack.connect_to_service('iam') policy = get_lambda_policy(function) if not policy: return error_response('Unable to find policy for Lambda function "%s"' % function, 404, error_type='ResourceNotFoundException') iam_client.delete_policy(PolicyArn=policy['PolicyArn']) result = { 'FunctionName': function, 'Qualifier': qualifier, 'StatementId': policy['Statement'][0]['Sid'], } return jsonify(result) @app.route('%s/functions/<function>/policy' % PATH_ROOT, methods=['GET']) def get_policy(function): policy = get_lambda_policy(function) if not policy: return error_response('The resource you requested does not exist.', 404, error_type='ResourceNotFoundException') return jsonify({'Policy': json.dumps(policy), 'RevisionId': 'test1234'}) @app.route('%s/functions/<function>/invocations' % PATH_ROOT, methods=['POST']) def invoke_function(function): """ Invoke an existing function --- operationId: 'invokeFunction' parameters: - name: 'request' in: body """ # function here can either be an arn or a function name arn = func_arn(function) # arn can also contain a qualifier, extract it from there if so m = re.match('(arn:aws:lambda:.*:.*:function:[a-zA-Z0-9-_]+)(:.*)?', arn) if m and m.group(2): qualifier = m.group(2)[1:] arn = m.group(1) else: qualifier = request.args.get('Qualifier') data = request.get_data() if data: data = to_str(data) try: data = json.loads(data) except Exception: try: # try to read chunked content data = json.loads(parse_chunked_data(data)) except Exception: return error_response('The payload is not JSON: %s' % data, 415, error_type='UnsupportedMediaTypeException') # Default invocation type is RequestResponse invocation_type = request.environ.get('HTTP_X_AMZ_INVOCATION_TYPE', 'RequestResponse') def _create_response(result, status_code=200, headers={}): """ Create the final response for the given invocation result. """ details = { 'StatusCode': status_code, 'Payload': result, 'Headers': headers } if isinstance(result, Response): details['Payload'] = to_str(result.data) if result.status_code >= 400: details['FunctionError'] = 'Unhandled' elif isinstance(result, dict): for key in ('StatusCode', 'Payload', 'FunctionError'): if result.get(key): details[key] = result[key] # Try to parse parse payload as JSON was_json = False payload = details['Payload'] if payload and isinstance(payload, POSSIBLE_JSON_TYPES) and payload[0] in JSON_START_CHARS: try: details['Payload'] = json.loads(details['Payload']) was_json = True except Exception: pass # Set error headers if details.get('FunctionError'): details['Headers']['X-Amz-Function-Error'] = str(details['FunctionError']) details['Headers']['X-Amz-Log-Result'] = base64.b64encode(to_bytes('')) # TODO add logs! details['Headers']['X-Amz-Executed-Version'] = str(qualifier or VERSION_LATEST) # Construct response object response_obj = details['Payload'] if was_json or isinstance(response_obj, JSON_START_TYPES): response_obj = json_safe(response_obj) response_obj = jsonify(response_obj) details['Headers']['Content-Type'] = 'application/json' else: response_obj = str(response_obj) details['Headers']['Content-Type'] = 'text/plain' return response_obj, details['StatusCode'], details['Headers'] # check if this lambda function exists not_found = None if arn not in ARN_TO_LAMBDA: not_found = not_found_error(arn) elif qualifier and not ARN_TO_LAMBDA.get(arn).qualifier_exists(qualifier): not_found = not_found_error('{0}:{1}'.format(arn, qualifier)) if not_found: forward_result = forward_to_fallback_url(arn, data) if forward_result is not None: return _create_response(forward_result) return not_found if invocation_type == 'RequestResponse': context = {'client_context': request.headers.get('X-Amz-Client-Context')} result = run_lambda(asynchronous=False, func_arn=arn, event=data, context=context, version=qualifier) return _create_response(result) elif invocation_type == 'Event': run_lambda(asynchronous=True, func_arn=arn, event=data, context={}, version=qualifier) return _create_response('', status_code=202) elif invocation_type == 'DryRun': # Assume the dry run always passes. return _create_response('', status_code=204) return error_response('Invocation type not one of: RequestResponse, Event or DryRun', code=400, error_type='InvalidParameterValueException') @app.route('%s/event-source-mappings/' % PATH_ROOT, methods=['GET']) def list_EVENT_SOURCE_MAPPINGS(): """ List event source mappings --- operationId: 'listEventSourceMappings' """ event_source_arn = request.args.get('EventSourceArn') function_name = request.args.get('FunctionName') mappings = EVENT_SOURCE_MAPPINGS if event_source_arn: mappings = [m for m in mappings if event_source_arn == m.get('EventSourceArn')] if function_name: function_arn = func_arn(function_name) mappings = [m for m in mappings if function_arn == m.get('FunctionArn')] response = { 'EventSourceMappings': mappings } return jsonify(response) @app.route('%s/event-source-mappings/<mapping_uuid>' % PATH_ROOT, methods=['GET']) def get_event_source_mapping(mapping_uuid): """ Get an existing event source mapping --- operationId: 'getEventSourceMapping' parameters: - name: 'request' in: body """ mappings = EVENT_SOURCE_MAPPINGS mappings = [m for m in mappings if mapping_uuid == m.get('UUID')] if len(mappings) == 0: return not_found_error() return jsonify(mappings[0]) @app.route('%s/event-source-mappings/' % PATH_ROOT, methods=['POST']) def create_event_source_mapping(): """ Create new event source mapping --- operationId: 'createEventSourceMapping' parameters: - name: 'request' in: body """ data = json.loads(to_str(request.data)) try: mapping = add_event_source( data['FunctionName'], data['EventSourceArn'], data.get('Enabled'), data.get('BatchSize') ) return jsonify(mapping) except ValueError as error: error_type, message = error.args return error_response(message, code=400, error_type=error_type) @app.route('%s/event-source-mappings/<mapping_uuid>' % PATH_ROOT, methods=['PUT']) def update_event_source_mapping(mapping_uuid): """ Update an existing event source mapping --- operationId: 'updateEventSourceMapping' parameters: - name: 'request' in: body """ data = json.loads(request.data) if not mapping_uuid: return jsonify({}) function_name = data.get('FunctionName') or '' enabled = data.get('Enabled', True) batch_size = data.get('BatchSize') try: mapping = update_event_source(mapping_uuid, function_name, enabled, batch_size) return jsonify(mapping) except ValueError as error: error_type, message = error.args return error_response(message, code=400, error_type=error_type) @app.route('%s/event-source-mappings/<mapping_uuid>' % PATH_ROOT, methods=['DELETE']) def delete_event_source_mapping(mapping_uuid): """ Delete an event source mapping --- operationId: 'deleteEventSourceMapping' """ if not mapping_uuid: return jsonify({}) mapping = delete_event_source(mapping_uuid) return jsonify(mapping) @app.route('%s/functions/<function>/versions' % PATH_ROOT, methods=['POST']) def publish_version(function): arn = func_arn(function) if arn not in ARN_TO_LAMBDA: return not_found_error(arn) return jsonify(publish_new_function_version(arn)) @app.route('%s/functions/<function>/versions' % PATH_ROOT, methods=['GET']) def list_versions(function): arn = func_arn(function) if arn not in ARN_TO_LAMBDA: return not_found_error(arn) return jsonify({'Versions': do_list_versions(arn)}) @app.route('%s/functions/<function>/aliases' % PATH_ROOT, methods=['POST']) def create_alias(function): arn = func_arn(function) if arn not in ARN_TO_LAMBDA: return not_found_error(arn) data = json.loads(request.data) alias = data.get('Name') if alias in ARN_TO_LAMBDA.get(arn).aliases: return error_response('Alias already exists: %s' % arn + ':' + alias, 404, error_type='ResourceConflictException') version = data.get('FunctionVersion') description = data.get('Description') return jsonify(do_update_alias(arn, alias, version, description)) @app.route('%s/functions/<function>/aliases/<name>' % PATH_ROOT, methods=['PUT']) def update_alias(function, name): arn = func_arn(function) if arn not in ARN_TO_LAMBDA: return not_found_error(arn) if name not in ARN_TO_LAMBDA.get(arn).aliases: return not_found_error(msg='Alias not found: %s:%s' % (arn, name)) current_alias = ARN_TO_LAMBDA.get(arn).aliases.get(name) data = json.loads(request.data) version = data.get('FunctionVersion') or current_alias.get('FunctionVersion') description = data.get('Description') or current_alias.get('Description') return jsonify(do_update_alias(arn, name, version, description)) @app.route('%s/functions/<function>/aliases/<name>' % PATH_ROOT, methods=['GET']) def get_alias(function, name): arn = func_arn(function) if arn not in ARN_TO_LAMBDA: return not_found_error(arn) if name not in ARN_TO_LAMBDA.get(arn).aliases: return not_found_error(msg='Alias not found: %s:%s' % (arn, name)) return jsonify(ARN_TO_LAMBDA.get(arn).aliases.get(name)) @app.route('%s/functions/<function>/aliases' % PATH_ROOT, methods=['GET']) def list_aliases(function): arn = func_arn(function) if arn not in ARN_TO_LAMBDA: return not_found_error(arn) return jsonify({'Aliases': sorted(ARN_TO_LAMBDA.get(arn).aliases.values(), key=lambda x: x['Name'])}) @app.route('/<version>/functions/<function>/concurrency', methods=['PUT']) def put_concurrency(version, function): # the version for put_concurrency != PATH_ROOT, at the time of this # writing it's: /2017-10-31 for this endpoint # https://docs.aws.amazon.com/lambda/latest/dg/API_PutFunctionConcurrency.html arn = func_arn(function) data = json.loads(request.data) lambda_details = ARN_TO_LAMBDA.get(arn) if not lambda_details: return not_found_error(arn) lambda_details.concurrency = data return jsonify(data) @app.route('/<version>/tags/<arn>', methods=['GET']) def list_tags(version, arn): func_details = ARN_TO_LAMBDA.get(arn) if not func_details: return not_found_error(arn) result = {'Tags': func_details.tags} return jsonify(result) @app.route('/<version>/tags/<arn>', methods=['POST']) def tag_resource(version, arn): data = json.loads(request.data) tags = data.get('Tags', {}) if tags: func_details = ARN_TO_LAMBDA.get(arn) if not func_details: return not_found_error(arn) if func_details: func_details.tags.update(tags) return jsonify({}) @app.route('/<version>/tags/<arn>', methods=['DELETE']) def untag_resource(version, arn): tag_keys = request.args.getlist('tagKeys') func_details = ARN_TO_LAMBDA.get(arn) if not func_details: return not_found_error(arn) for tag_key in tag_keys: func_details.tags.pop(tag_key, None) return jsonify({}) @app.route('/2019-09-25/functions/<function>/event-invoke-config', methods=['PUT', 'POST']) def put_function_event_invoke_config(function): # TODO: resouce validation required to check if resource exists """ Add/Updates the configuration for asynchronous invocation for a function --- operationId: PutFunctionEventInvokeConfig | UpdateFunctionEventInvokeConfig parameters: - name: 'function' in: path - name: 'qualifier' in: path - name: 'request' in: body """ data = json.loads(to_str(request.data)) function_arn = func_arn(function) lambda_obj = ARN_TO_LAMBDA[function_arn] if request.method == 'PUT': response = lambda_obj.clear_function_event_invoke_config() response = lambda_obj.put_function_event_invoke_config(data) return jsonify({ 'LastModified': response.last_modified, 'FunctionArn': str(function_arn), 'MaximumRetryAttempts': response.max_retry_attempts, 'MaximumEventAgeInSeconds': response.max_event_age, 'DestinationConfig': { 'OnSuccess': { 'Destination': str(response.on_successful_invocation) }, 'OnFailure': { 'Destination': str(response.dead_letter_config) } } }) @app.route('/2019-09-25/functions/<function>/event-invoke-config', methods=['GET']) def get_function_event_invoke_config(function): """ Retrieves the configuration for asynchronous invocation for a function --- operationId: GetFunctionEventInvokeConfig parameters: - name: 'function' in: path - name: 'qualifier' in: path - name: 'request' in: body """ try: function_arn = func_arn(function) lambda_obj = ARN_TO_LAMBDA[function_arn] except Exception as e: return error_response(str(e), 400) response = lambda_obj.get_function_event_invoke_config() return jsonify(response) @app.route('/2019-09-25/functions/<function>/event-invoke-config', methods=['DELETE']) def delete_function_event_invoke_config(function): try: function_arn = func_arn(function) lambda_obj = ARN_TO_LAMBDA[function_arn] except Exception as e: return error_response(str(e), 400) lambda_obj.clear_function_event_invoke_config() return Response('', status=204) def serve(port, quiet=True): from localstack.services import generic_proxy # moved here to fix circular import errors # initialize the Lambda executor LAMBDA_EXECUTOR.startup() generic_proxy.serve_flask_app(app=app, port=port, quiet=quiet)
1
11,711
I think we should `return arn` as a fallback at the end of this function (otherwise the `['Resource']` entry below could become `None`).
localstack-localstack
py
@@ -41,6 +41,11 @@ type NATProxy struct { func (np *NATProxy) consumerHandOff(consumerPort int, remoteConn *net.UDPConn) chan struct{} { stop := make(chan struct{}) + if np.socketProtect == nil { + // shutdown pinger session since openvpn client will connect directly (without NATProxy) + remoteConn.Close() + return stop + } go np.consumerProxy(consumerPort, remoteConn, stop) return stop }
1
/* * Copyright (C) 2019 The "MysteriumNetwork/node" Authors. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package traversal import ( "fmt" "io" "net" "sync" log "github.com/cihub/seelog" "github.com/mysteriumnetwork/node/services" ) const logPrefix = "[NATProxy] " const bufferLen = 30000 // NATProxy provides traffic proxying functionality for registered services type NATProxy struct { servicePorts map[services.ServiceType]int addrLast *net.UDPAddr socketProtect func(socket int) bool once sync.Once } func (np *NATProxy) consumerHandOff(consumerPort int, remoteConn *net.UDPConn) chan struct{} { stop := make(chan struct{}) go np.consumerProxy(consumerPort, remoteConn, stop) return stop } // consumerProxy launches listener on pinger port and wait for openvpn connect // Read from listener socket and write to remoteConn // Read from remoteConn and write to listener socket func (np *NATProxy) consumerProxy(consumerPort int, remoteConn *net.UDPConn, stop chan struct{}) { log.Info(logPrefix, "Inside consumer NATProxy") laddr, err := net.ResolveUDPAddr("udp4", fmt.Sprintf("127.0.0.1:%d", consumerPort+1)) if err != nil { log.Error(logPrefix, "failed to get local address for consumer NATProxy: ", err) return } remoteConn.SetReadBuffer(bufferLen) remoteConn.SetWriteBuffer(bufferLen) fd, err := remoteConn.File() if err != nil { log.Error(logPrefix, "failed to fetch fd from: ", remoteConn) return } defer fd.Close() log.Info(logPrefix, "protecting socket: ", int(fd.Fd())) np.socketProtect(int(fd.Fd())) for { log.Info(logPrefix, "waiting connect from openvpn3 client process") // If for some reason consumer disconnects, new connection will be from different port proxyConn, err := net.ListenUDP("udp4", laddr) if err != nil { log.Errorf("%sfailed to listen for consumer proxy on: %v, %v", logPrefix, laddr, err) return } select { case <-stop: log.Info(logPrefix, "Stopping NATProxy handOff loop") proxyConn.Close() remoteConn.Close() return default: proxyConn.SetReadBuffer(bufferLen) proxyConn.SetWriteBuffer(bufferLen) np.joinUDPStreams(proxyConn, remoteConn, stop) proxyConn.Close() } } } func (np *NATProxy) joinUDPStreams(conn *net.UDPConn, remoteConn *net.UDPConn, stop chan struct{}) { log.Info(logPrefix, "start copying stream from consumer NATProxy to remote remoteConn") for { select { case <-stop: log.Info(logPrefix, "Stopping NATProxy joinUDPStreams") return default: } var buf [bufferLen]byte n, addr, err := conn.ReadFromUDP(buf[0:]) if err != nil { log.Errorf("%sFailed to read local process: %s cause: %s", logPrefix, conn.LocalAddr().String(), err) return } if n > 0 { _, err := remoteConn.Write(buf[:n]) if err != nil { log.Errorf("%sFailed to write remote peer: %s cause: %s", logPrefix, remoteConn.RemoteAddr().String(), err) return } if np.addrLast != addr { np.addrLast = addr go np.readWriteToAddr(remoteConn, conn, addr, stop) } } } } func (np *NATProxy) readWriteToAddr(conn *net.UDPConn, remoteConn *net.UDPConn, addr *net.UDPAddr, stop chan struct{}) { for { select { case <-stop: log.Info(logPrefix, "Stopping NATProxy readWriteToAddr loop") return default: } var buf [bufferLen]byte n, err := conn.Read(buf[0:]) if err != nil { log.Errorf("%sFailed to read remote peer: %s cause: %s", logPrefix, conn.LocalAddr().String(), err) return } if n > 0 { _, err := remoteConn.WriteToUDP(buf[:n], addr) if err != nil { log.Errorf("%sFailed to write to local process: %s cause: %s", logPrefix, remoteConn.LocalAddr().String(), err) return } } } } // NewNATProxy constructs an instance of NATProxy func NewNATProxy() *NATProxy { return &NATProxy{ servicePorts: make(map[services.ServiceType]int), } } // handOff traffic incoming through NATPinger punched hole should be handed off to NATPoxy func (np *NATProxy) handOff(serviceType services.ServiceType, incomingConn *net.UDPConn) { proxyConn, err := np.getConnection(serviceType) if err != nil { log.Error(logPrefix, "failed to connect to NATProxy: ", err) return } log.Info(logPrefix, "handing off a connection to a service on ", proxyConn.RemoteAddr().String()) go copyStreams(proxyConn, incomingConn) go copyStreams(incomingConn, proxyConn) } func copyStreams(dstConn *net.UDPConn, srcConn *net.UDPConn) { defer dstConn.Close() defer srcConn.Close() totalBytes, err := io.Copy(dstConn, srcConn) if err != nil { log.Error(logPrefix, "failed to writing / reading a stream to/from NATProxy: ", err) } log.Tracef("%stotal bytes transferred from %s to %s: %d", logPrefix, srcConn.RemoteAddr().String(), dstConn.RemoteAddr().String(), totalBytes) } func (np *NATProxy) registerServicePort(serviceType services.ServiceType, port int) { log.Infof("%sregistering service %s for port %d to NATProxy", logPrefix, serviceType, port) np.servicePorts[serviceType] = port } func (np *NATProxy) getConnection(serviceType services.ServiceType) (*net.UDPConn, error) { udpAddr, err := net.ResolveUDPAddr("udp4", fmt.Sprintf("127.0.0.1:%d", np.servicePorts[serviceType])) if err != nil { return nil, err } return net.DialUDP("udp", nil, udpAddr) } func (np *NATProxy) isAvailable(serviceType services.ServiceType) bool { return np.servicePorts[serviceType] > 0 } func (np *NATProxy) setProtectSocketCallback(socketProtect func(socket int) bool) { np.socketProtect = socketProtect }
1
14,386
Why session is started at all, if you need to shut it down e.g. DI should launch noopSession
mysteriumnetwork-node
go
@@ -184,7 +184,7 @@ type describer interface { } type workspaceDeleter interface { - DeleteAll() error + DeleteWorkspaceFile() error } type svcManifestReader interface {
1
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package cli import ( "encoding" "io" "github.com/aws/amazon-ecs-cli-v2/internal/pkg/aws/cloudwatchlogs" "github.com/aws/amazon-ecs-cli-v2/internal/pkg/aws/codepipeline" "github.com/aws/amazon-ecs-cli-v2/internal/pkg/aws/ecr" "github.com/aws/amazon-ecs-cli-v2/internal/pkg/aws/ecs" "github.com/aws/amazon-ecs-cli-v2/internal/pkg/config" "github.com/aws/amazon-ecs-cli-v2/internal/pkg/deploy" "github.com/aws/amazon-ecs-cli-v2/internal/pkg/deploy/cloudformation/stack" "github.com/aws/amazon-ecs-cli-v2/internal/pkg/describe" "github.com/aws/amazon-ecs-cli-v2/internal/pkg/docker/dockerfile" "github.com/aws/amazon-ecs-cli-v2/internal/pkg/term/command" "github.com/aws/amazon-ecs-cli-v2/internal/pkg/workspace" "github.com/aws/aws-sdk-go/aws/session" ) // actionCommand is the interface that every command that creates a resource implements. type actionCommand interface { // Validate returns an error if a flag's value is invalid. Validate() error // Ask prompts for flag values that are required but not passed in. Ask() error // Execute runs the command after collecting all required options. Execute() error // RecommendedActions returns a list of follow-up suggestions users can run once the command executes successfully. RecommendedActions() []string } // SSM store interface. type serviceStore interface { serviceCreator serviceGetter serviceLister serviceDeleter } type serviceCreator interface { CreateService(svc *config.Service) error } type serviceGetter interface { GetService(appName, svcName string) (*config.Service, error) } type serviceLister interface { ListServices(appName string) ([]*config.Service, error) } type serviceDeleter interface { DeleteService(appName, svcName string) error } type applicationStore interface { applicationCreator applicationGetter applicationLister applicationDeleter } type applicationCreator interface { CreateApplication(app *config.Application) error } type applicationGetter interface { GetApplication(appName string) (*config.Application, error) } type applicationLister interface { ListApplications() ([]*config.Application, error) } type applicationDeleter interface { DeleteApplication(name string) error } type environmentStore interface { environmentCreator environmentGetter environmentLister environmentDeleter } type environmentCreator interface { CreateEnvironment(env *config.Environment) error } type environmentGetter interface { GetEnvironment(appName string, environmentName string) (*config.Environment, error) } type environmentLister interface { ListEnvironments(appName string) ([]*config.Environment, error) } type environmentDeleter interface { DeleteEnvironment(appName, environmentName string) error } type store interface { applicationStore environmentStore serviceStore } // Secretsmanager interface. type secretsManager interface { secretCreator secretDeleter } type secretCreator interface { CreateSecret(secretName, secretString string) (string, error) } type secretDeleter interface { DeleteSecret(secretName string) error } type ecrService interface { GetRepository(name string) (string, error) GetECRAuth() (ecr.Auth, error) } type cwlogService interface { TaskLogEvents(logGroupName string, streamLastEventTime map[string]int64, opts ...cloudwatchlogs.GetLogEventsOpts) (*cloudwatchlogs.LogEventsOutput, error) LogGroupExists(logGroupName string) (bool, error) } type templater interface { Template() (string, error) } type stackSerializer interface { templater SerializedParameters() (string, error) } type dockerService interface { Build(uri, tag, path string) error Login(uri, username, password string) error Push(uri, tag string) error } type runner interface { Run(name string, args []string, options ...command.Option) error } type defaultSessionProvider interface { Default() (*session.Session, error) } type regionalSessionProvider interface { DefaultWithRegion(region string) (*session.Session, error) } type sessionFromRoleProvider interface { FromRole(roleARN string, region string) (*session.Session, error) } type profileNames interface { Names() []string } type sessionProvider interface { defaultSessionProvider regionalSessionProvider sessionFromRoleProvider } type describer interface { Describe() (describe.HumanJSONStringer, error) } type workspaceDeleter interface { DeleteAll() error } type svcManifestReader interface { ReadServiceManifest(svcName string) ([]byte, error) } type svcManifestWriter interface { WriteServiceManifest(marshaler encoding.BinaryMarshaler, svcName string) (string, error) } type wsPipelineManifestReader interface { ReadPipelineManifest() ([]byte, error) } type wsPipelineWriter interface { WritePipelineBuildspec(marshaler encoding.BinaryMarshaler) (string, error) WritePipelineManifest(marshaler encoding.BinaryMarshaler) (string, error) } type wsSvcDeleter interface { DeleteService(name string) error } type wsServiceLister interface { ServiceNames() ([]string, error) } type wsSvcReader interface { wsServiceLister svcManifestReader } type wsPipelineDeleter interface { DeletePipelineManifest() error wsPipelineManifestReader } type wsPipelineReader interface { wsServiceLister wsPipelineManifestReader } type wsAppManager interface { Create(appName string) error Summary() (*workspace.Summary, error) } type wsAddonManager interface { WriteAddon(f encoding.BinaryMarshaler, svc, name string) (string, error) wsSvcReader } type artifactUploader interface { PutArtifact(bucket, fileName string, data io.Reader) (string, error) } type bucketEmptier interface { EmptyBucket(bucket string) error } // Interfaces for deploying resources through CloudFormation. Facilitates mocking. type environmentDeployer interface { DeployEnvironment(env *deploy.CreateEnvironmentInput) error StreamEnvironmentCreation(env *deploy.CreateEnvironmentInput) (<-chan []deploy.ResourceEvent, <-chan deploy.CreateEnvironmentResponse) DeleteEnvironment(appName, envName string) error GetEnvironment(appName, envName string) (*config.Environment, error) } type svcDeleter interface { DeleteService(in deploy.DeleteServiceInput) error } type svcRemoverFromApp interface { RemoveServiceFromApp(app *config.Application, svcName string) error } type imageRemover interface { ClearRepository(repoName string) error // implemented by ECR Service } type pipelineDeployer interface { CreatePipeline(env *deploy.CreatePipelineInput) error UpdatePipeline(env *deploy.CreatePipelineInput) error PipelineExists(env *deploy.CreatePipelineInput) (bool, error) DeletePipeline(pipelineName string) error AddPipelineResourcesToApp(app *config.Application, region string) error appResourcesGetter // TODO: Add StreamPipelineCreation method } type appDeployer interface { DeployApp(in *deploy.CreateAppInput) error AddServiceToApp(app *config.Application, svcName string) error AddEnvToApp(app *config.Application, env *config.Environment) error DelegateDNSPermissions(app *config.Application, accountID string) error DeleteApp(name string) error } type appResourcesGetter interface { GetAppResourcesByRegion(app *config.Application, region string) (*stack.AppRegionalResources, error) GetRegionalAppResources(app *config.Application) ([]*stack.AppRegionalResources, error) } type deployer interface { environmentDeployer appDeployer pipelineDeployer } type domainValidator interface { DomainExists(domainName string) (bool, error) } type dockerfileParser interface { GetExposedPorts() ([]uint16, error) GetHealthCheck() (*dockerfile.HealthCheck, error) } type serviceArnGetter interface { GetServiceArn() (*ecs.ServiceArn, error) } type statusDescriber interface { Describe() (*describe.ServiceStatusDesc, error) } type envDescriber interface { Describe() (*describe.EnvDescription, error) } type resourceGroupsClient interface { GetResourcesByTags(resourceType string, tags map[string]string) ([]string, error) } type pipelineGetter interface { GetPipeline(pipelineName string) (*codepipeline.Pipeline, error) ListPipelineNamesByTags(tags map[string]string) ([]string, error) } type executor interface { Execute() error } type deletePipelineRunner interface { Run() error } type askExecutor interface { Ask() error executor } type appSelector interface { Application(prompt, help string) (string, error) } type appEnvSelector interface { appSelector Environment(prompt, help, app string) (string, error) } type configSelector interface { appEnvSelector Service(prompt, help, app string) (string, error) } type wsSelector interface { appEnvSelector Service(prompt, help string) (string, error) }
1
13,705
nit: can we rename the interface to `wsFileDeleter`
aws-copilot-cli
go
@@ -91,10 +91,10 @@ func hashRule(r *rule) string { // It's the struct used by reconciler. type CompletedRule struct { *rule - // Source Pods of this rule, can't coexist with ToAddresses. - FromAddresses v1beta1.GroupMemberPodSet - // Destination Pods of this rule, can't coexist with FromAddresses. - ToAddresses v1beta1.GroupMemberPodSet + // Source GroupMembers of this rule, can't coexist with ToAddresses. + FromAddresses v1beta1.GroupMemberSet + // Destination GroupMembers of this rule, can't coexist with FromAddresses. + ToAddresses v1beta1.GroupMemberSet // Target Pods of this rule. Pods v1beta1.GroupMemberPodSet }
1
// Copyright 2019 Antrea Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package networkpolicy import ( "crypto/sha1" // #nosec G505: not used for security purposes "encoding/hex" "encoding/json" "fmt" "sort" "sync" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/util/sets" "k8s.io/client-go/tools/cache" "k8s.io/klog/v2" "github.com/vmware-tanzu/antrea/pkg/agent/metrics" "github.com/vmware-tanzu/antrea/pkg/apis/networking/v1beta1" secv1alpha1 "github.com/vmware-tanzu/antrea/pkg/apis/security/v1alpha1" ) const ( RuleIDLength = 16 appliedToGroupIndex = "appliedToGroup" addressGroupIndex = "addressGroup" policyIndex = "policy" ) // rule is the struct stored in ruleCache, it contains necessary information // to construct a complete rule that can be used by reconciler to enforce. // The K8s NetworkPolicy object doesn't provide ID for its rule, here we // calculate an ID based on the rule's fields. That means: // 1. If a rule's selector/services/direction changes, it becomes "another" rule. // 2. If inserting rules before a rule or shuffling rules in a NetworkPolicy, we // can know the existing rules don't change and skip processing them. Note that // if a CNP/ANP rule's position (from top down) within a networkpolicy changes, it // affects the Priority of the rule. type rule struct { // ID is calculated from the hash value of all other fields. ID string // Direction of this rule. Direction v1beta1.Direction // Source Address of this rule, can't coexist with To. From v1beta1.NetworkPolicyPeer // Destination Address of this rule, can't coexist with From. To v1beta1.NetworkPolicyPeer // Protocols and Ports of this rule. Services []v1beta1.Service // Action of this rule. nil for k8s NetworkPolicy. Action *secv1alpha1.RuleAction // Priority of this rule within the NetworkPolicy. Defaults to -1 for k8s NetworkPolicy. Priority int32 // Priority of the NetworkPolicy to which this rule belong. nil for k8s NetworkPolicy. PolicyPriority *float64 // Targets of this rule. AppliedToGroups []string // The parent Policy ID. Used to identify rules belong to a specified // policy for deletion. PolicyUID types.UID // The metadata of parent Policy. Used to associate the rule with Policy // for troubleshooting purpose (logging and CLI). PolicyName string // PolicyNamespace is empty for ClusterNetworkPolicy. PolicyNamespace string } // hashRule calculates a string based on the rule's content. func hashRule(r *rule) string { hash := sha1.New() // #nosec G401: not used for security purposes b, _ := json.Marshal(r) hash.Write(b) hashValue := hex.EncodeToString(hash.Sum(nil)) return hashValue[:RuleIDLength] } // CompletedRule contains IPAddresses and Pods flattened from AddressGroups and AppliedToGroups. // It's the struct used by reconciler. type CompletedRule struct { *rule // Source Pods of this rule, can't coexist with ToAddresses. FromAddresses v1beta1.GroupMemberPodSet // Destination Pods of this rule, can't coexist with FromAddresses. ToAddresses v1beta1.GroupMemberPodSet // Target Pods of this rule. Pods v1beta1.GroupMemberPodSet } // String returns the string representation of the CompletedRule. func (r *CompletedRule) String() string { var addressString string if r.Direction == v1beta1.DirectionIn { addressString = fmt.Sprintf("FromAddressGroups: %d, FromIPBlocks: %d, FromAddresses: %d", len(r.From.AddressGroups), len(r.From.IPBlocks), len(r.FromAddresses)) } else { addressString = fmt.Sprintf("ToAddressGroups: %d, ToIPBlocks: %d, ToAddresses: %d", len(r.To.AddressGroups), len(r.To.IPBlocks), len(r.ToAddresses)) } return fmt.Sprintf("%s (Direction: %v, Pods: %d, %s, Services: %d, PolicyPriority: %v, RulePriority: %v)", r.ID, r.Direction, len(r.Pods), addressString, len(r.Services), r.PolicyPriority, r.Priority) } // isAntreaNetworkPolicyRule returns true if the rule is part of a ClusterNetworkPolicy. func (r *CompletedRule) isAntreaNetworkPolicyRule() bool { return r.PolicyPriority != nil } // ruleCache caches Antrea AddressGroups, AppliedToGroups and NetworkPolicies, // can construct complete rules that can be used by reconciler to enforce. type ruleCache struct { podSetLock sync.RWMutex // podSetByGroup stores the AppliedToGroup members. // It is a mapping from group name to a set of Pods. podSetByGroup map[string]v1beta1.GroupMemberPodSet addressSetLock sync.RWMutex // addressSetByGroup stores the AddressGroup members. // It is a mapping from group name to a set of Pods. addressSetByGroup map[string]v1beta1.GroupMemberPodSet policyMapLock sync.RWMutex // policyMap is a map using NetworkPolicy UID as the key. policyMap map[string]*types.NamespacedName // rules is a storage that supports listing rules using multiple indexing functions. // rules is thread-safe. rules cache.Indexer // dirtyRuleHandler is a callback that is run upon finding a rule out-of-sync. dirtyRuleHandler func(string) // podUpdates is a channel for receiving Pod updates from CNIServer. podUpdates <-chan v1beta1.PodReference } func (c *ruleCache) getNetworkPolicies(namespace string) []v1beta1.NetworkPolicy { ret := []v1beta1.NetworkPolicy{} c.policyMapLock.RLock() defer c.policyMapLock.RUnlock() for uid, np := range c.policyMap { if namespace == "" || np.Namespace == namespace { ret = append(ret, *c.buildNetworkPolicyFromRules(uid)) } } return ret } // getNetworkPolicy looks up and returns the cached NetworkPolicy. // nil is returned if the specified NetworkPolicy is not found. func (c *ruleCache) getNetworkPolicy(npName, npNamespace string) *v1beta1.NetworkPolicy { var npUID string c.policyMapLock.Lock() defer c.policyMapLock.Unlock() for uid, np := range c.policyMap { if np.Name == npName && np.Namespace == npNamespace { npUID = uid break } } if npUID == "" { // NetworkPolicy not found. return nil } return c.buildNetworkPolicyFromRules(npUID) } func (c *ruleCache) buildNetworkPolicyFromRules(uid string) *v1beta1.NetworkPolicy { var np *v1beta1.NetworkPolicy rules, _ := c.rules.ByIndex(policyIndex, uid) // Sort the rules by priority sort.Slice(rules, func(i, j int) bool { r1 := rules[i].(*rule) r2 := rules[j].(*rule) return r1.Priority < r2.Priority }) for _, ruleObj := range rules { np = addRuleToNetworkPolicy(np, ruleObj.(*rule)) } return np } // addRuleToNetworkPolicy adds a cached rule to the passed NetworkPolicy struct // and returns it. If np is nil, a new NetworkPolicy struct will be created. func addRuleToNetworkPolicy(np *v1beta1.NetworkPolicy, rule *rule) *v1beta1.NetworkPolicy { if np == nil { np = &v1beta1.NetworkPolicy{ ObjectMeta: metav1.ObjectMeta{UID: rule.PolicyUID, Name: rule.PolicyName, Namespace: rule.PolicyNamespace}, AppliedToGroups: rule.AppliedToGroups, } } np.Rules = append(np.Rules, v1beta1.NetworkPolicyRule{ Direction: rule.Direction, From: rule.From, To: rule.To, Services: rule.Services, Action: rule.Action, Priority: rule.Priority}) return np } func (c *ruleCache) getAppliedNetworkPolicies(pod, namespace string) []v1beta1.NetworkPolicy { var groups []string memberPod := &v1beta1.GroupMemberPod{Pod: &v1beta1.PodReference{pod, namespace}} c.podSetLock.RLock() for group, podSet := range c.podSetByGroup { if podSet.Has(memberPod) { groups = append(groups, group) } } c.podSetLock.RUnlock() npMap := make(map[string]*v1beta1.NetworkPolicy) for _, group := range groups { rules, _ := c.rules.ByIndex(appliedToGroupIndex, group) for _, ruleObj := range rules { rule := ruleObj.(*rule) np, ok := npMap[string(rule.PolicyUID)] np = addRuleToNetworkPolicy(np, rule) if !ok { // First rule for this NetworkPolicy npMap[string(rule.PolicyUID)] = np } } } ret := make([]v1beta1.NetworkPolicy, 0, len(npMap)) for _, np := range npMap { ret = append(ret, *np) } return ret } func (c *ruleCache) GetAddressGroups() []v1beta1.AddressGroup { var ret []v1beta1.AddressGroup c.addressSetLock.RLock() defer c.addressSetLock.RUnlock() for k, v := range c.addressSetByGroup { var pods []v1beta1.GroupMemberPod for _, pod := range v { pods = append(pods, *pod) } ret = append(ret, v1beta1.AddressGroup{ ObjectMeta: metav1.ObjectMeta{Name: k}, Pods: pods, }) } return ret } func (c *ruleCache) GetAppliedToGroups() []v1beta1.AppliedToGroup { var ret []v1beta1.AppliedToGroup c.podSetLock.RLock() defer c.podSetLock.RUnlock() for k, v := range c.podSetByGroup { var pods []v1beta1.GroupMemberPod for _, pod := range v.Items() { pods = append(pods, *pod) } ret = append(ret, v1beta1.AppliedToGroup{ ObjectMeta: metav1.ObjectMeta{Name: k}, Pods: pods, }) } return ret } // ruleKeyFunc knows how to get key of a *rule. func ruleKeyFunc(obj interface{}) (string, error) { rule := obj.(*rule) return rule.ID, nil } // addressGroupIndexFunc knows how to get addressGroups of a *rule. // It's provided to cache.Indexer to build an index of addressGroups. func addressGroupIndexFunc(obj interface{}) ([]string, error) { rule := obj.(*rule) addressGroups := make([]string, 0, len(rule.From.AddressGroups)+len(rule.To.AddressGroups)) addressGroups = append(addressGroups, rule.From.AddressGroups...) addressGroups = append(addressGroups, rule.To.AddressGroups...) return addressGroups, nil } // appliedToGroupIndexFunc knows how to get appliedToGroups of a *rule. // It's provided to cache.Indexer to build an index of appliedToGroups. func appliedToGroupIndexFunc(obj interface{}) ([]string, error) { rule := obj.(*rule) return rule.AppliedToGroups, nil } // policyIndexFunc knows how to get NetworkPolicy UID of a *rule. // It's provided to cache.Indexer to build an index of NetworkPolicy. func policyIndexFunc(obj interface{}) ([]string, error) { rule := obj.(*rule) return []string{string(rule.PolicyUID)}, nil } // newRuleCache returns a new *ruleCache. func newRuleCache(dirtyRuleHandler func(string), podUpdate <-chan v1beta1.PodReference) *ruleCache { rules := cache.NewIndexer( ruleKeyFunc, cache.Indexers{addressGroupIndex: addressGroupIndexFunc, appliedToGroupIndex: appliedToGroupIndexFunc, policyIndex: policyIndexFunc}, ) cache := &ruleCache{ podSetByGroup: make(map[string]v1beta1.GroupMemberPodSet), addressSetByGroup: make(map[string]v1beta1.GroupMemberPodSet), policyMap: make(map[string]*types.NamespacedName), rules: rules, dirtyRuleHandler: dirtyRuleHandler, podUpdates: podUpdate, } go cache.processPodUpdates() return cache } // processPodUpdates is an infinite loop that takes Pod update events from the // channel, finds out AppliedToGroups that contains this Pod and trigger // reconciling of related rules. // It can enforce NetworkPolicies to newly added Pods right after CNI ADD is // done if antrea-controller has computed the Pods' policies and propagated // them to this Node by their labels and NodeName, instead of waiting for their // IPs are reported to kube-apiserver and processed by antrea-controller. func (c *ruleCache) processPodUpdates() { for { select { case pod := <-c.podUpdates: func() { memberPod := &v1beta1.GroupMemberPod{Pod: &pod} c.podSetLock.RLock() defer c.podSetLock.RUnlock() for group, podSet := range c.podSetByGroup { if podSet.Has(memberPod) { c.onAppliedToGroupUpdate(group) } } }() } } } // GetAddressGroupNum gets the number of AddressGroup. func (c *ruleCache) GetAddressGroupNum() int { c.addressSetLock.RLock() defer c.addressSetLock.RUnlock() return len(c.addressSetByGroup) } // ReplaceAddressGroups atomically adds the given groups to the cache and deletes // the pre-existing groups that are not in the given groups from the cache. // It makes the cache in sync with the apiserver when restarting a watch. func (c *ruleCache) ReplaceAddressGroups(groups []*v1beta1.AddressGroup) { c.addressSetLock.Lock() defer c.addressSetLock.Unlock() oldGroupKeys := make(sets.String, len(c.addressSetByGroup)) for key := range c.addressSetByGroup { oldGroupKeys.Insert(key) } for _, group := range groups { oldGroupKeys.Delete(group.Name) c.addAddressGroupLocked(group) } for key := range oldGroupKeys { delete(c.addressSetByGroup, key) } return } // AddAddressGroup adds a new *v1beta1.AddressGroup to the cache. The rules // referencing it will be regarded as dirty. // It's safe to add an AddressGroup multiple times as it only overrides the // map, this could happen when the watcher reconnects to the Apiserver. func (c *ruleCache) AddAddressGroup(group *v1beta1.AddressGroup) error { c.addressSetLock.Lock() defer c.addressSetLock.Unlock() return c.addAddressGroupLocked(group) } func (c *ruleCache) addAddressGroupLocked(group *v1beta1.AddressGroup) error { podSet := v1beta1.GroupMemberPodSet{} for i := range group.Pods { // Must not store address of loop iterator variable as it's the same // address taking different values in each loop iteration, otherwise // podSet would eventually contain only the last value. // https://github.com/golang/go/wiki/CommonMistakes#using-reference-to-loop-iterator-variable podSet.Insert(&group.Pods[i]) } oldPodSet, exists := c.addressSetByGroup[group.Name] if exists && oldPodSet.Equal(podSet) { return nil } c.addressSetByGroup[group.Name] = podSet c.onAddressGroupUpdate(group.Name) return nil } // PatchAddressGroup updates a cached *v1beta1.AddressGroup. // The rules referencing it will be regarded as dirty. func (c *ruleCache) PatchAddressGroup(patch *v1beta1.AddressGroupPatch) error { c.addressSetLock.Lock() defer c.addressSetLock.Unlock() podSet, exists := c.addressSetByGroup[patch.Name] if !exists { return fmt.Errorf("AddressGroup %v doesn't exist in cache, can't be patched", patch.Name) } for i := range patch.AddedPods { podSet.Insert(&patch.AddedPods[i]) } for i := range patch.RemovedPods { podSet.Delete(&patch.RemovedPods[i]) } c.onAddressGroupUpdate(patch.Name) return nil } // DeleteAddressGroup deletes a cached *v1beta1.AddressGroup. // It should only happen when a group is no longer referenced by any rule, so // no need to mark dirty rules. func (c *ruleCache) DeleteAddressGroup(group *v1beta1.AddressGroup) error { c.addressSetLock.Lock() defer c.addressSetLock.Unlock() delete(c.addressSetByGroup, group.Name) return nil } // GetAppliedToGroupNum gets the number of AppliedToGroup. func (c *ruleCache) GetAppliedToGroupNum() int { c.podSetLock.RLock() defer c.podSetLock.RUnlock() return len(c.podSetByGroup) } // ReplaceAppliedToGroups atomically adds the given groups to the cache and deletes // the pre-existing groups that are not in the given groups from the cache. // It makes the cache in sync with the apiserver when restarting a watch. func (c *ruleCache) ReplaceAppliedToGroups(groups []*v1beta1.AppliedToGroup) { c.podSetLock.Lock() defer c.podSetLock.Unlock() oldGroupKeys := make(sets.String, len(c.podSetByGroup)) for key := range c.podSetByGroup { oldGroupKeys.Insert(key) } for _, group := range groups { oldGroupKeys.Delete(group.Name) c.addAppliedToGroupLocked(group) } for key := range oldGroupKeys { delete(c.podSetByGroup, key) } return } // AddAppliedToGroup adds a new *v1beta1.AppliedToGroup to the cache. The rules // referencing it will be regarded as dirty. // It's safe to add an AppliedToGroup multiple times as it only overrides the // map, this could happen when the watcher reconnects to the Apiserver. func (c *ruleCache) AddAppliedToGroup(group *v1beta1.AppliedToGroup) error { c.podSetLock.Lock() defer c.podSetLock.Unlock() return c.addAppliedToGroupLocked(group) } func (c *ruleCache) addAppliedToGroupLocked(group *v1beta1.AppliedToGroup) error { podSet := v1beta1.GroupMemberPodSet{} for i := range group.Pods { podSet.Insert(&group.Pods[i]) } oldPodSet, exists := c.podSetByGroup[group.Name] if exists && oldPodSet.Equal(podSet) { return nil } c.podSetByGroup[group.Name] = podSet c.onAppliedToGroupUpdate(group.Name) return nil } // PatchAppliedToGroup updates a cached *v1beta1.AppliedToGroupPatch. // The rules referencing it will be regarded as dirty. func (c *ruleCache) PatchAppliedToGroup(patch *v1beta1.AppliedToGroupPatch) error { c.podSetLock.Lock() defer c.podSetLock.Unlock() podSet, exists := c.podSetByGroup[patch.Name] if !exists { return fmt.Errorf("AppliedToGroup %v doesn't exist in cache, can't be patched", patch.Name) } for i := range patch.AddedPods { podSet.Insert(&patch.AddedPods[i]) } for i := range patch.RemovedPods { podSet.Delete(&patch.RemovedPods[i]) } c.onAppliedToGroupUpdate(patch.Name) return nil } // DeleteAppliedToGroup deletes a cached *v1beta1.AppliedToGroup. // It should only happen when a group is no longer referenced by any rule, so // no need to mark dirty rules. func (c *ruleCache) DeleteAppliedToGroup(group *v1beta1.AppliedToGroup) error { c.podSetLock.Lock() defer c.podSetLock.Unlock() delete(c.podSetByGroup, group.Name) return nil } // toRule converts v1beta1.NetworkPolicyRule to *rule. func toRule(r *v1beta1.NetworkPolicyRule, policy *v1beta1.NetworkPolicy) *rule { rule := &rule{ Direction: r.Direction, From: r.From, To: r.To, Services: r.Services, Action: r.Action, Priority: r.Priority, AppliedToGroups: policy.AppliedToGroups, PolicyUID: policy.UID, } rule.ID = hashRule(rule) rule.PolicyNamespace = policy.Namespace rule.PolicyName = policy.Name rule.PolicyPriority = policy.Priority return rule } // GetNetworkPolicyNum gets the number of NetworkPolicy. func (c *ruleCache) GetNetworkPolicyNum() int { c.policyMapLock.RLock() defer c.policyMapLock.RUnlock() return len(c.policyMap) } // ReplaceNetworkPolicies atomically adds the given policies to the cache and deletes // the pre-existing policies that are not in the given policies from the cache. // It makes the cache in sync with the apiserver when restarting a watch. func (c *ruleCache) ReplaceNetworkPolicies(policies []*v1beta1.NetworkPolicy) { c.policyMapLock.Lock() defer c.policyMapLock.Unlock() oldKeys := make(sets.String, len(c.policyMap)) for key := range c.policyMap { oldKeys.Insert(key) } for i := range policies { oldKeys.Delete(string(policies[i].UID)) c.addNetworkPolicyLocked(policies[i]) } for key := range oldKeys { c.deleteNetworkPolicyLocked(key) } return } // AddNetworkPolicy adds a new *v1beta1.NetworkPolicy to the cache. // It could happen that an existing NetworkPolicy is "added" again when the // watcher reconnects to the Apiserver, we use the same processing as // UpdateNetworkPolicy to ensure orphan rules are removed. func (c *ruleCache) AddNetworkPolicy(policy *v1beta1.NetworkPolicy) error { c.policyMapLock.Lock() defer c.policyMapLock.Unlock() return c.addNetworkPolicyLocked(policy) } func (c *ruleCache) addNetworkPolicyLocked(policy *v1beta1.NetworkPolicy) error { c.policyMap[string(policy.UID)] = &types.NamespacedName{policy.Namespace, policy.Name} metrics.NetworkPolicyCount.Inc() return c.UpdateNetworkPolicy(policy) } // UpdateNetworkPolicy updates a cached *v1beta1.NetworkPolicy. // The added rules and removed rules will be regarded as dirty. func (c *ruleCache) UpdateNetworkPolicy(policy *v1beta1.NetworkPolicy) error { existingRules, _ := c.rules.ByIndex(policyIndex, string(policy.UID)) ruleByID := map[string]interface{}{} for _, r := range existingRules { ruleByID[r.(*rule).ID] = r } for i := range policy.Rules { r := toRule(&policy.Rules[i], policy) if _, exists := ruleByID[r.ID]; exists { // If rule already exists, remove it from the map so the ones left finally are orphaned. klog.V(2).Infof("Rule %v was not changed", r.ID) delete(ruleByID, r.ID) } else { // If rule doesn't exist, add it to cache, mark it as dirty. c.rules.Add(r) // Count up antrea_agent_ingress_networkpolicy_rule_count or antrea_agent_egress_networkpolicy_rule_count if r.Direction == v1beta1.DirectionIn { metrics.IngressNetworkPolicyRuleCount.Inc() } else { metrics.EgressNetworkPolicyRuleCount.Inc() } c.dirtyRuleHandler(r.ID) } } // At this moment, the remaining rules are orphaned, remove them from store and mark them as dirty. for ruleID, r := range ruleByID { c.rules.Delete(r) // Count down antrea_agent_ingress_networkpolicy_rule_count or antrea_agent_egress_networkpolicy_rule_count if r.(*rule).Direction == v1beta1.DirectionIn { metrics.IngressNetworkPolicyRuleCount.Dec() } else { metrics.EgressNetworkPolicyRuleCount.Dec() } c.dirtyRuleHandler(ruleID) } return nil } // DeleteNetworkPolicy deletes a cached *v1beta1.NetworkPolicy. // All its rules will be regarded as dirty. func (c *ruleCache) DeleteNetworkPolicy(policy *v1beta1.NetworkPolicy) error { c.policyMapLock.Lock() defer c.policyMapLock.Unlock() return c.deleteNetworkPolicyLocked(string(policy.UID)) } func (c *ruleCache) deleteNetworkPolicyLocked(uid string) error { delete(c.policyMap, uid) existingRules, _ := c.rules.ByIndex(policyIndex, uid) for _, r := range existingRules { ruleID := r.(*rule).ID // Count down antrea_agent_ingress_networkpolicy_rule_count or antrea_agent_egress_networkpolicy_rule_count if r.(*rule).Direction == v1beta1.DirectionIn { metrics.IngressNetworkPolicyRuleCount.Dec() } else { metrics.EgressNetworkPolicyRuleCount.Dec() } c.rules.Delete(r) c.dirtyRuleHandler(ruleID) } metrics.NetworkPolicyCount.Dec() return nil } // GetCompletedRule constructs a *CompletedRule for the provided ruleID. // If the rule is not found or not completed due to missing group data, // the return value will indicate it. func (c *ruleCache) GetCompletedRule(ruleID string) (completedRule *CompletedRule, exists bool, completed bool) { obj, exists, _ := c.rules.GetByKey(ruleID) if !exists { return nil, false, false } r := obj.(*rule) var fromAddresses, toAddresses v1beta1.GroupMemberPodSet if r.Direction == v1beta1.DirectionIn { fromAddresses, completed = c.unionAddressGroups(r.From.AddressGroups) } else { toAddresses, completed = c.unionAddressGroups(r.To.AddressGroups) } if !completed { return nil, true, false } pods, completed := c.unionAppliedToGroups(r.AppliedToGroups) if !completed { return nil, true, false } completedRule = &CompletedRule{ rule: r, FromAddresses: fromAddresses, ToAddresses: toAddresses, Pods: pods, } return completedRule, true, true } // onAppliedToGroupUpdate gets rules referencing to the provided AppliedToGroup // and mark them as dirty. func (c *ruleCache) onAppliedToGroupUpdate(groupName string) { ruleIDs, _ := c.rules.IndexKeys(appliedToGroupIndex, groupName) for _, ruleID := range ruleIDs { c.dirtyRuleHandler(ruleID) } } // onAddressGroupUpdate gets rules referencing to the provided AddressGroup // and mark them as dirty. func (c *ruleCache) onAddressGroupUpdate(groupName string) { ruleIDs, _ := c.rules.IndexKeys(addressGroupIndex, groupName) for _, ruleID := range ruleIDs { c.dirtyRuleHandler(ruleID) } } // unionAddressGroups gets the union of addresses of the provided address groups. // If any group is not found, nil and false will be returned to indicate the // set is not complete yet. func (c *ruleCache) unionAddressGroups(groupNames []string) (v1beta1.GroupMemberPodSet, bool) { c.addressSetLock.RLock() defer c.addressSetLock.RUnlock() set := v1beta1.NewGroupMemberPodSet() for _, groupName := range groupNames { curSet, exists := c.addressSetByGroup[groupName] if !exists { klog.V(2).Infof("AddressGroup %v was not found", groupName) return nil, false } set = set.Union(curSet) } return set, true } // unionAppliedToGroups gets the union of pods of the provided appliedTo groups. // If any group is not found, nil and false will be returned to indicate the // set is not complete yet. func (c *ruleCache) unionAppliedToGroups(groupNames []string) (v1beta1.GroupMemberPodSet, bool) { c.podSetLock.RLock() defer c.podSetLock.RUnlock() set := v1beta1.NewGroupMemberPodSet() for _, groupName := range groupNames { curSet, exists := c.podSetByGroup[groupName] if !exists { klog.V(2).Infof("AppliedToGroup %v was not found", groupName) return nil, false } set = set.Union(curSet) } return set, true }
1
22,326
Why target cannot be external endpoints?
antrea-io-antrea
go
@@ -127,4 +127,8 @@ public interface CollectionAdminParams { /** Option to follow aliases when deciding the target of a collection admin command. */ String FOLLOW_ALIASES = "followAliases"; + + /** Prefix for automatically created config elements. */ + String AUTO_PREFIX = ".auto_"; + }
1
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.solr.common.params; import java.util.Arrays; import java.util.Collection; public interface CollectionAdminParams { /* Param used by DELETESTATUS call to clear all stored responses */ String FLUSH = "flush"; String COLLECTION = "collection"; String COUNT_PROP = "count"; String ROLE = "role"; /** Predefined system collection name. */ String SYSTEM_COLL = ".system"; /** * A parameter to specify list of Solr nodes to be used (e.g. for collection creation or restore operation). */ String CREATE_NODE_SET_PARAM = "createNodeSet"; /** * A parameter which specifies if the provided list of Solr nodes (via {@linkplain #CREATE_NODE_SET_PARAM}) * should be shuffled before being used. */ String CREATE_NODE_SET_SHUFFLE_PARAM = "createNodeSet.shuffle"; /** * A parameter to specify the name of the index backup strategy to be used. */ String INDEX_BACKUP_STRATEGY = "indexBackup"; /** * This constant defines the index backup strategy based on copying index files to desired location. */ String COPY_FILES_STRATEGY = "copy-files"; /** * This constant defines the strategy to not copy index files (useful for meta-data only backup). */ String NO_INDEX_BACKUP_STRATEGY = "none"; /** * This constant defines a list of valid index backup strategies. */ Collection<String> INDEX_BACKUP_STRATEGIES = Arrays.asList(COPY_FILES_STRATEGY, NO_INDEX_BACKUP_STRATEGY); /** * Name of collection property to set */ String PROPERTY_NAME = "propertyName"; /** * Value of collection property to set */ String PROPERTY_VALUE = "propertyValue"; /** * The name of the config set to be used for a collection */ String COLL_CONF = "collection.configName"; /** * The name of the collection with which a collection is to be co-located */ String WITH_COLLECTION = "withCollection"; /** * The reverse-link to WITH_COLLECTION flag. It is stored in the cluster state of the `withCollection` * and points to the collection on which the `withCollection` was specified. */ String COLOCATED_WITH = "COLOCATED_WITH"; /** * Used by cluster properties API as a wrapper key to provide defaults for collection, cluster etc. * * e.g. {defaults:{collection:{replicationFactor:2}}} */ String DEFAULTS = "defaults"; /** * Cluster wide defaults can be nested under this key e.g. * {defaults: {cluster:{useLegacyReplicaAssignment:false}}} */ String CLUSTER = "cluster"; /** * This cluster property decides whether Solr should use the legacy round-robin replica placement strategy * or the autoscaling policy based strategy to assign replicas to nodes. The default is false. */ String USE_LEGACY_REPLICA_ASSIGNMENT = "useLegacyReplicaAssignment"; /** * When creating a collection create also a specified alias. */ String ALIAS = "alias"; /** * Specifies the target of RENAME operation. */ String TARGET = "target"; /** * Prefix for {@link org.apache.solr.common.cloud.DocRouter} properties */ String ROUTER_PREFIX = "router."; /** Option to follow aliases when deciding the target of a collection admin command. */ String FOLLOW_ALIASES = "followAliases"; }
1
33,702
We use a suffix ".AUTOCREATED" for configsets, maybe we can use the same here?
apache-lucene-solr
java
@@ -27,7 +27,7 @@ namespace Samples { // Enable OpenTelemetry for the source "MyCompany.MyProduct.MyWebServer" // and use Console exporter - OpenTelemetrySdk.Default.EnableOpenTelemetry( + OpenTelemetrySdk.EnableOpenTelemetry( (builder) => builder.AddActivitySource("MyCompany.MyProduct.MyWebServer") .UseConsoleActivityExporter(opt => opt.DisplayAsJson = options.DisplayAsJson));
1
// <copyright file="TestConsoleActivity.cs" company="OpenTelemetry Authors"> // Copyright The OpenTelemetry Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> using System; using System.Diagnostics; using OpenTelemetry.Exporter.Console; using OpenTelemetry.Trace.Configuration; namespace Samples { internal class TestConsoleActivity { internal static object Run(ConsoleActivityOptions options) { // Enable OpenTelemetry for the source "MyCompany.MyProduct.MyWebServer" // and use Console exporter OpenTelemetrySdk.Default.EnableOpenTelemetry( (builder) => builder.AddActivitySource("MyCompany.MyProduct.MyWebServer") .UseConsoleActivityExporter(opt => opt.DisplayAsJson = options.DisplayAsJson)); // The above line is required only in Applications // which decide to use OT. // Libraries would simply write the following lines of code to // emit activities, which are the .NET representation of OT Spans. var source = new ActivitySource("MyCompany.MyProduct.MyWebServer"); // The below commented out line shows more likely code in a real world webserver. // using (var parent = source.StartActivity("HttpIn", ActivityKind.Server, HttpContext.Request.Headers["traceparent"] )) using (var parent = source.StartActivity("HttpIn", ActivityKind.Server)) { // TagNames can follow the OT guidelines // from https://github.com/open-telemetry/opentelemetry-specification/tree/master/specification/trace/semantic_conventions parent?.AddTag("http.method", "GET"); parent?.AddTag("http.host", "MyHostName"); if (parent != null) { parent.DisplayName = "HttpIn DisplayName"; // IsAllDataRequested is equivalent of Span.IsRecording if (parent.IsAllDataRequested) { parent.AddTag("expensive data", "This data is expensive to obtain. Avoid it if activity is not being recorded"); } } try { // Actual code to achieve the purpose of the library. // For websebserver example, this would be calling // user middlware pipeline. // There can be child activities. // In this example HttpOut is a child of HttpIn. using (var child = source.StartActivity("HttpOut", ActivityKind.Client)) { child?.AddTag("http.url", "www.mydependencyapi.com"); try { // do actual work. child?.AddEvent(new ActivityEvent("sample activity event.")); child?.AddTag("http.status_code", "200"); } catch (Exception) { child?.AddTag("http.status_code", "500"); } } parent?.AddTag("http.status_code", "200"); } catch (Exception) { parent?.AddTag("http.status_code", "500"); } } return null; } } }
1
14,243
This one won't be disposed. Should be (something like) `using var openTelemetry = OpenTelemetrySdk.EnableOpenTelemetry(` no?
open-telemetry-opentelemetry-dotnet
.cs
@@ -37,7 +37,7 @@ from logHandler import log import UIAUtils from comInterfaces import UIAutomationClient as UIA # F403: unable to detect undefined names -from comInterfaces .UIAutomationClient import * # noqa: F403 +from comInterfaces.UIAutomationClient import * # noqa: F403 import textInfos from typing import Dict from queue import Queue
1
# A part of NonVisual Desktop Access (NVDA) # Copyright (C) 2011-2021 NV Access Limited, Joseph Lee, Babbage B.V., Leonard de Ruijter # This file is covered by the GNU General Public License. # See the file COPYING for more details. import ctypes import ctypes.wintypes from ctypes import ( oledll, windll, ) from enum import ( Enum, ) import comtypes.client from comtypes.automation import VT_EMPTY from comtypes import ( COMError, COMObject, byref, CLSCTX_INPROC_SERVER, CoCreateInstance, ) import threading import time import config import api import appModuleHandler import controlTypes import winKernel import winUser import winVersion import eventHandler from logHandler import log import UIAUtils from comInterfaces import UIAutomationClient as UIA # F403: unable to detect undefined names from comInterfaces .UIAutomationClient import * # noqa: F403 import textInfos from typing import Dict from queue import Queue import aria HorizontalTextAlignment_Left=0 HorizontalTextAlignment_Centered=1 HorizontalTextAlignment_Right=2 HorizontalTextAlignment_Justified=3 # The name of the WDAG (Windows Defender Application Guard) process WDAG_PROCESS_NAME=u'hvsirdpclient' goodUIAWindowClassNames=[ # A WDAG (Windows Defender Application Guard) Window is always native UIA, even if it doesn't report as such. 'RAIL_WINDOW', "EXCEL6", ] badUIAWindowClassNames=[ # UIA events of candidate window interfere with MSAA events. "Microsoft.IME.CandidateWindow.View", "SysTreeView32", "WuDuiListView", "ComboBox", "msctls_progress32", "Edit", "CommonPlacesWrapperWndClass", "SysMonthCal32", "SUPERGRID", # Outlook 2010 message list "RichEdit", "RichEdit20", "RICHEDIT50W", "SysListView32", "Button", # #8944: The Foxit UIA implementation is incomplete and should not be used for now. "FoxitDocWnd", ] # #8405: used to detect UIA dialogs prior to Windows 10 RS5. UIADialogClassNames=[ "#32770", "NUIDialog", "Credential Dialog Xaml Host", # UAC dialog in Anniversary Update and later "Shell_Dialog", "Shell_Flyout", "Shell_SystemDialog", # Various dialogs in Windows 10 Settings app ] NVDAUnitsToUIAUnits: Dict[str, int] = { textInfos.UNIT_CHARACTER: UIA.TextUnit_Character, textInfos.UNIT_WORD: UIA.TextUnit_Word, textInfos.UNIT_LINE: UIA.TextUnit_Line, textInfos.UNIT_PARAGRAPH: UIA.TextUnit_Paragraph, textInfos.UNIT_PAGE: UIA.TextUnit_Page, textInfos.UNIT_READINGCHUNK: UIA.TextUnit_Line, textInfos.UNIT_STORY: UIA.TextUnit_Document, textInfos.UNIT_FORMATFIELD: UIA.TextUnit_Format, } UIAControlTypesToNVDARoles={ UIA_ButtonControlTypeId:controlTypes.ROLE_BUTTON, UIA_CalendarControlTypeId:controlTypes.ROLE_CALENDAR, UIA_CheckBoxControlTypeId:controlTypes.ROLE_CHECKBOX, UIA_ComboBoxControlTypeId:controlTypes.ROLE_COMBOBOX, UIA_EditControlTypeId:controlTypes.ROLE_EDITABLETEXT, UIA_HyperlinkControlTypeId:controlTypes.ROLE_LINK, UIA_ImageControlTypeId:controlTypes.ROLE_GRAPHIC, UIA_ListItemControlTypeId:controlTypes.ROLE_LISTITEM, UIA_ListControlTypeId:controlTypes.ROLE_LIST, UIA_MenuControlTypeId:controlTypes.ROLE_POPUPMENU, UIA_MenuBarControlTypeId:controlTypes.ROLE_MENUBAR, UIA_MenuItemControlTypeId:controlTypes.ROLE_MENUITEM, UIA_ProgressBarControlTypeId:controlTypes.ROLE_PROGRESSBAR, UIA_RadioButtonControlTypeId:controlTypes.ROLE_RADIOBUTTON, UIA_ScrollBarControlTypeId:controlTypes.ROLE_SCROLLBAR, UIA_SliderControlTypeId:controlTypes.ROLE_SLIDER, UIA_SpinnerControlTypeId:controlTypes.ROLE_SPINBUTTON, UIA_StatusBarControlTypeId:controlTypes.ROLE_STATUSBAR, UIA_TabControlTypeId:controlTypes.ROLE_TABCONTROL, UIA_TabItemControlTypeId:controlTypes.ROLE_TAB, UIA_TextControlTypeId:controlTypes.ROLE_STATICTEXT, UIA_ToolBarControlTypeId:controlTypes.ROLE_TOOLBAR, UIA_ToolTipControlTypeId:controlTypes.ROLE_TOOLTIP, UIA_TreeControlTypeId:controlTypes.ROLE_TREEVIEW, UIA_TreeItemControlTypeId:controlTypes.ROLE_TREEVIEWITEM, UIA_CustomControlTypeId:controlTypes.ROLE_UNKNOWN, UIA_GroupControlTypeId:controlTypes.ROLE_GROUPING, UIA_ThumbControlTypeId:controlTypes.ROLE_THUMB, UIA_DataGridControlTypeId:controlTypes.ROLE_DATAGRID, UIA_DataItemControlTypeId:controlTypes.ROLE_DATAITEM, UIA_DocumentControlTypeId:controlTypes.ROLE_DOCUMENT, UIA_SplitButtonControlTypeId:controlTypes.ROLE_SPLITBUTTON, UIA_WindowControlTypeId:controlTypes.ROLE_WINDOW, UIA_PaneControlTypeId:controlTypes.ROLE_PANE, UIA_HeaderControlTypeId:controlTypes.ROLE_HEADER, UIA_HeaderItemControlTypeId:controlTypes.ROLE_HEADERITEM, UIA_TableControlTypeId:controlTypes.ROLE_TABLE, UIA_TitleBarControlTypeId:controlTypes.ROLE_TITLEBAR, UIA_SeparatorControlTypeId:controlTypes.ROLE_SEPARATOR, } UIALiveSettingtoNVDAAriaLivePoliteness: Dict[str, aria.AriaLivePoliteness] = { UIA.Off: aria.AriaLivePoliteness.OFF, UIA.Polite: aria.AriaLivePoliteness.POLITE, UIA.Assertive: aria.AriaLivePoliteness.ASSERTIVE, } UIAPropertyIdsToNVDAEventNames={ UIA_NamePropertyId:"nameChange", UIA_HelpTextPropertyId:"descriptionChange", UIA_ExpandCollapseExpandCollapseStatePropertyId:"stateChange", UIA_ToggleToggleStatePropertyId:"stateChange", UIA_IsEnabledPropertyId:"stateChange", UIA_ValueValuePropertyId:"valueChange", UIA_RangeValueValuePropertyId:"valueChange", UIA_ControllerForPropertyId:"UIA_controllerFor", UIA_ItemStatusPropertyId:"UIA_itemStatus", } globalEventHandlerGroupUIAPropertyIds = { UIA.UIA_RangeValueValuePropertyId } localEventHandlerGroupUIAPropertyIds = ( set(UIAPropertyIdsToNVDAEventNames) - globalEventHandlerGroupUIAPropertyIds ) UIALandmarkTypeIdsToLandmarkNames: Dict[int, str] = { UIA.UIA_FormLandmarkTypeId: "form", UIA.UIA_NavigationLandmarkTypeId: "navigation", UIA.UIA_MainLandmarkTypeId: "main", UIA.UIA_SearchLandmarkTypeId: "search", } UIAEventIdsToNVDAEventNames={ UIA_LiveRegionChangedEventId:"liveRegionChange", UIA_SelectionItem_ElementSelectedEventId:"UIA_elementSelected", UIA_MenuOpenedEventId:"gainFocus", UIA_SelectionItem_ElementAddedToSelectionEventId:"stateChange", UIA_SelectionItem_ElementRemovedFromSelectionEventId:"stateChange", #UIA_MenuModeEndEventId:"menuModeEnd", UIA_ToolTipOpenedEventId:"UIA_toolTipOpened", #UIA_AsyncContentLoadedEventId:"documentLoadComplete", #UIA_ToolTipClosedEventId:"hide", UIA_Window_WindowOpenedEventId:"UIA_window_windowOpen", UIA_SystemAlertEventId:"UIA_systemAlert", } localEventHandlerGroupUIAEventIds = set() autoSelectDetectionAvailable = False if winVersion.getWinVer() >= winVersion.WIN10: UIAEventIdsToNVDAEventNames.update({ UIA.UIA_Text_TextChangedEventId: "textChange", UIA.UIA_Text_TextSelectionChangedEventId: "caret", }) localEventHandlerGroupUIAEventIds.update({ UIA.UIA_Text_TextChangedEventId, UIA.UIA_Text_TextSelectionChangedEventId, }) autoSelectDetectionAvailable = True globalEventHandlerGroupUIAEventIds = set(UIAEventIdsToNVDAEventNames) - localEventHandlerGroupUIAEventIds ignoreWinEventsMap = { UIA_AutomationPropertyChangedEventId: list(UIAPropertyIdsToNVDAEventNames.keys()), } for id in UIAEventIdsToNVDAEventNames.keys(): ignoreWinEventsMap[id] = [0] class AllowUiaInChromium(Enum): _DEFAULT = 0 # maps to 'when necessary' WHEN_NECESSARY = 1 # the current default YES = 2 NO = 3 @staticmethod def getConfig() -> 'AllowUiaInChromium': allow = AllowUiaInChromium(config.conf['UIA']['allowInChromium']) if allow == AllowUiaInChromium._DEFAULT: return AllowUiaInChromium.WHEN_NECESSARY return allow class UIAHandler(COMObject): _com_interfaces_ = [ UIA.IUIAutomationEventHandler, UIA.IUIAutomationFocusChangedEventHandler, UIA.IUIAutomationPropertyChangedEventHandler, UIA.IUIAutomationNotificationEventHandler, UIA.IUIAutomationActiveTextPositionChangedEventHandler, ] def __init__(self): super(UIAHandler,self).__init__() self.globalEventHandlerGroup = None self.localEventHandlerGroup = None self._localEventHandlerGroupElements = set() self.MTAThreadInitEvent=threading.Event() self.MTAThreadQueue = Queue() self.MTAThreadInitException=None self.MTAThread = threading.Thread( name=f"{self.__class__.__module__}.{self.__class__.__qualname__}.MTAThread", target=self.MTAThreadFunc ) self.MTAThread.daemon=True self.MTAThread.start() self.MTAThreadInitEvent.wait(2) if self.MTAThreadInitException: raise self.MTAThreadInitException def terminate(self): MTAThreadHandle = ctypes.wintypes.HANDLE( windll.kernel32.OpenThread( winKernel.SYNCHRONIZE, False, self.MTAThread.ident ) ) self.MTAThreadQueue.put_nowait(None) #Wait for the MTA thread to die (while still message pumping) if windll.user32.MsgWaitForMultipleObjects(1,byref(MTAThreadHandle),False,200,0)!=0: log.debugWarning("Timeout or error while waiting for UIAHandler MTA thread") windll.kernel32.CloseHandle(MTAThreadHandle) del self.MTAThread def MTAThreadFunc(self): try: oledll.ole32.CoInitializeEx(None,comtypes.COINIT_MULTITHREADED) isUIA8=False try: self.clientObject=CoCreateInstance(CUIAutomation8._reg_clsid_,interface=IUIAutomation,clsctx=CLSCTX_INPROC_SERVER) isUIA8=True except (COMError,WindowsError,NameError): self.clientObject=CoCreateInstance(CUIAutomation._reg_clsid_,interface=IUIAutomation,clsctx=CLSCTX_INPROC_SERVER) # #7345: Instruct UIA to never map MSAA winEvents to UIA propertyChange events. # These events are not needed by NVDA, and they can cause the UI Automation client library to become unresponsive if an application firing winEvents has a slow message pump. pfm=self.clientObject.proxyFactoryMapping for index in range(pfm.count): e=pfm.getEntry(index) entryChanged = False for eventId, propertyIds in ignoreWinEventsMap.items(): for propertyId in propertyIds: # Check if this proxy has mapped any winEvents to the UIA propertyChange event for this property ID try: oldWinEvents=e.getWinEventsForAutomationEvent(eventId,propertyId) except IndexError: # comtypes does not seem to correctly handle a returned empty SAFEARRAY, raising IndexError oldWinEvents=None if oldWinEvents: # As winEvents were mapped, replace them with an empty list e.setWinEventsForAutomationEvent(eventId,propertyId,[]) entryChanged = True if entryChanged: # Changes to an entry are not automatically picked up. # Therefore remove the entry and re-insert it. pfm.removeEntry(index) pfm.insertEntry(index,e) if isUIA8: # #8009: use appropriate interface based on highest supported interface. # #8338: made easier by traversing interfaces supported on Windows 8 and later in reverse. for interface in reversed(CUIAutomation8._com_interfaces_): try: self.clientObject=self.clientObject.QueryInterface(interface) break except COMError: pass # Windows 10 RS5 provides new performance features for UI Automation including event coalescing and connection recovery. # Enable all of these where available. if isinstance(self.clientObject,IUIAutomation6): self.clientObject.CoalesceEvents=CoalesceEventsOptions_Enabled self.clientObject.ConnectionRecoveryBehavior=ConnectionRecoveryBehaviorOptions_Enabled log.info("UIAutomation: %s"%self.clientObject.__class__.__mro__[1].__name__) self.windowTreeWalker=self.clientObject.createTreeWalker(self.clientObject.CreateNotCondition(self.clientObject.CreatePropertyCondition(UIA_NativeWindowHandlePropertyId,0))) self.windowCacheRequest=self.clientObject.CreateCacheRequest() self.windowCacheRequest.AddProperty(UIA_NativeWindowHandlePropertyId) self.UIAWindowHandleCache={} self.baseTreeWalker=self.clientObject.RawViewWalker self.baseCacheRequest=self.windowCacheRequest.Clone() for propertyId in (UIA_FrameworkIdPropertyId,UIA_AutomationIdPropertyId,UIA_ClassNamePropertyId,UIA_ControlTypePropertyId,UIA_ProviderDescriptionPropertyId,UIA_ProcessIdPropertyId,UIA_IsTextPatternAvailablePropertyId,UIA_IsContentElementPropertyId,UIA_IsControlElementPropertyId): self.baseCacheRequest.addProperty(propertyId) self.baseCacheRequest.addPattern(UIA_TextPatternId) self.rootElement=self.clientObject.getRootElementBuildCache(self.baseCacheRequest) self.reservedNotSupportedValue=self.clientObject.ReservedNotSupportedValue self.ReservedMixedAttributeValue=self.clientObject.ReservedMixedAttributeValue if config.conf['UIA']['selectiveEventRegistration']: self._createLocalEventHandlerGroup() self._registerGlobalEventHandlers() except Exception as e: self.MTAThreadInitException=e finally: self.MTAThreadInitEvent.set() while True: func = self.MTAThreadQueue.get() if func: try: func() except Exception: log.error("Exception in function queued to UIA MTA thread", exc_info=True) else: break self.clientObject.RemoveAllEventHandlers() def _registerGlobalEventHandlers(self): self.clientObject.AddFocusChangedEventHandler(self.baseCacheRequest, self) if isinstance(self.clientObject, UIA.IUIAutomation6): self.globalEventHandlerGroup = self.clientObject.CreateEventHandlerGroup() else: self.globalEventHandlerGroup = UIAUtils.FakeEventHandlerGroup(self.clientObject) self.globalEventHandlerGroup.AddPropertyChangedEventHandler( UIA.TreeScope_Subtree, self.baseCacheRequest, self, *self.clientObject.IntSafeArrayToNativeArray( globalEventHandlerGroupUIAPropertyIds if config.conf['UIA']['selectiveEventRegistration'] else UIAPropertyIdsToNVDAEventNames ) ) for eventId in ( globalEventHandlerGroupUIAEventIds if config.conf['UIA']['selectiveEventRegistration'] else UIAEventIdsToNVDAEventNames ): self.globalEventHandlerGroup.AddAutomationEventHandler( eventId, UIA.TreeScope_Subtree, self.baseCacheRequest, self ) # #7984: add support for notification event (IUIAutomation5, part of Windows 10 build 16299 and later). if isinstance(self.clientObject, UIA.IUIAutomation5): self.globalEventHandlerGroup.AddNotificationEventHandler( UIA.TreeScope_Subtree, self.baseCacheRequest, self ) if isinstance(self.clientObject, UIA.IUIAutomation6): self.globalEventHandlerGroup.AddActiveTextPositionChangedEventHandler( UIA.TreeScope_Subtree, self.baseCacheRequest, self ) self.addEventHandlerGroup(self.rootElement, self.globalEventHandlerGroup) def _createLocalEventHandlerGroup(self): if isinstance(self.clientObject, UIA.IUIAutomation6): self.localEventHandlerGroup = self.clientObject.CreateEventHandlerGroup() else: self.localEventHandlerGroup = UIAUtils.FakeEventHandlerGroup(self.clientObject) self.localEventHandlerGroup.AddPropertyChangedEventHandler( UIA.TreeScope_Ancestors | UIA.TreeScope_Element, self.baseCacheRequest, self, *self.clientObject.IntSafeArrayToNativeArray(localEventHandlerGroupUIAPropertyIds) ) for eventId in localEventHandlerGroupUIAEventIds: self.localEventHandlerGroup.AddAutomationEventHandler( eventId, UIA.TreeScope_Ancestors | UIA.TreeScope_Element, self.baseCacheRequest, self ) def addEventHandlerGroup(self, element, eventHandlerGroup): if isinstance(eventHandlerGroup, UIA.IUIAutomationEventHandlerGroup): self.clientObject.AddEventHandlerGroup(element, eventHandlerGroup) elif isinstance(eventHandlerGroup, UIAUtils.FakeEventHandlerGroup): eventHandlerGroup.registerToClientObject(element) else: raise NotImplementedError def removeEventHandlerGroup(self, element, eventHandlerGroup): if isinstance(eventHandlerGroup, UIA.IUIAutomationEventHandlerGroup): self.clientObject.RemoveEventHandlerGroup(element, eventHandlerGroup) elif isinstance(eventHandlerGroup, UIAUtils.FakeEventHandlerGroup): eventHandlerGroup.unregisterFromClientObject(element) else: raise NotImplementedError def addLocalEventHandlerGroupToElement(self, element, isFocus=False): if not self.localEventHandlerGroup or element in self._localEventHandlerGroupElements: return def func(): if isFocus: try: isStillFocus = self.clientObject.CompareElements(self.clientObject.GetFocusedElement(), element) except COMError: isStillFocus = False if not isStillFocus: return try: self.addEventHandlerGroup(element, self.localEventHandlerGroup) except COMError: log.error("Could not register for UIA events for element", exc_info=True) else: self._localEventHandlerGroupElements.add(element) self.MTAThreadQueue.put_nowait(func) def removeLocalEventHandlerGroupFromElement(self, element): if not self.localEventHandlerGroup or element not in self._localEventHandlerGroupElements: return def func(): try: self.removeEventHandlerGroup(element, self.localEventHandlerGroup) except COMError: # The old UIAElement has probably died as the window was closed. # The system should forget the old event registration itself. # Yet, as we don't expect this to happen very often, log a debug warning. log.debugWarning("Could not unregister for UIA events for element", exc_info=True) self._localEventHandlerGroupElements.remove(element) self.MTAThreadQueue.put_nowait(func) def IUIAutomationEventHandler_HandleAutomationEvent(self,sender,eventID): if not self.MTAThreadInitEvent.isSet(): # UIAHandler hasn't finished initialising yet, so just ignore this event. if _isDebug(): log.debug("HandleAutomationEvent: event received while not fully initialized") return if eventID==UIA_MenuOpenedEventId and eventHandler.isPendingEvents("gainFocus"): # We don't need the menuOpened event if focus has been fired, # as focus should be more correct. if _isDebug(): log.debug("HandleAutomationEvent: Ignored MenuOpenedEvent while focus event pending") return NVDAEventName=UIAEventIdsToNVDAEventNames.get(eventID,None) if not NVDAEventName: if _isDebug(): log.debugWarning(f"HandleAutomationEvent: Don't know how to handle event {eventID}") return focus = api.getFocusObject() import NVDAObjects.UIA if ( isinstance(focus, NVDAObjects.UIA.UIA) and self.clientObject.compareElements(focus.UIAElement, sender) ): pass elif not self.isNativeUIAElement(sender): if _isDebug(): log.debug( f"HandleAutomationEvent: Ignoring event {NVDAEventName} for non native element" ) return window = self.getNearestWindowHandle(sender) if window and not eventHandler.shouldAcceptEvent(NVDAEventName, windowHandle=window): if _isDebug(): log.debug( f"HandleAutomationEvent: Ignoring event {NVDAEventName} for shouldAcceptEvent=False" ) return try: obj = NVDAObjects.UIA.UIA(UIAElement=sender) except Exception: if _isDebug(): log.debugWarning( f"HandleAutomationEvent: Exception while creating object for event {NVDAEventName}", exc_info=True ) return if ( not obj or (NVDAEventName=="gainFocus" and not obj.shouldAllowUIAFocusEvent) or (NVDAEventName=="liveRegionChange" and not obj._shouldAllowUIALiveRegionChangeEvent) ): if _isDebug(): log.debug( "HandleAutomationEvent: " f"Ignoring event {NVDAEventName} because no object or ignored by object itself" ) return if obj==focus: obj=focus eventHandler.queueEvent(NVDAEventName,obj) # The last UIAElement that received a UIA focus event # This is updated no matter if this is a native element, the window is UIA blacklisted by NVDA, or the element is proxied from MSAA lastFocusedUIAElement=None def IUIAutomationFocusChangedEventHandler_HandleFocusChangedEvent(self,sender): if not self.MTAThreadInitEvent.isSet(): # UIAHandler hasn't finished initialising yet, so just ignore this event. if _isDebug(): log.debug("HandleFocusChangedEvent: event received while not fully initialized") return self.lastFocusedUIAElement = sender if not self.isNativeUIAElement(sender): if _isDebug(): log.debug("HandleFocusChangedEvent: Ignoring for non native element") return import NVDAObjects.UIA if isinstance(eventHandler.lastQueuedFocusObject,NVDAObjects.UIA.UIA): lastFocusObj = eventHandler.lastQueuedFocusObject # Ignore duplicate focus events. # It seems that it is possible for compareElements to return True, even though the objects are different. # Therefore, don't ignore the event if the last focus object has lost its hasKeyboardFocus state. try: if ( not lastFocusObj.shouldAllowDuplicateUIAFocusEvent and self.clientObject.compareElements(sender, lastFocusObj.UIAElement) and lastFocusObj.UIAElement.currentHasKeyboardFocus ): if _isDebug(): log.debugWarning("HandleFocusChangedEvent: Ignoring duplicate focus event") return except COMError: if _isDebug(): log.debugWarning( "HandleFocusChangedEvent: Couldn't check for duplicate focus event", exc_info=True ) window = self.getNearestWindowHandle(sender) if window and not eventHandler.shouldAcceptEvent("gainFocus", windowHandle=window): if _isDebug(): log.debug("HandleFocusChangedEvent: Ignoring for shouldAcceptEvent=False") return try: obj = NVDAObjects.UIA.UIA(UIAElement=sender) except Exception: if _isDebug(): log.debugWarning( "HandleFocusChangedEvent: Exception while creating object", exc_info=True ) return if not obj or not obj.shouldAllowUIAFocusEvent: if _isDebug(): log.debug( "HandleFocusChangedEvent: Ignoring because no object or ignored by object itself" ) return eventHandler.queueEvent("gainFocus",obj) def IUIAutomationPropertyChangedEventHandler_HandlePropertyChangedEvent(self,sender,propertyId,newValue): # #3867: For now manually force this VARIANT type to empty to get around a nasty double free in comtypes/ctypes. # We also don't use the value in this callback. newValue.vt=VT_EMPTY if not self.MTAThreadInitEvent.isSet(): # UIAHandler hasn't finished initialising yet, so just ignore this event. if _isDebug(): log.debug("HandlePropertyChangedEvent: event received while not fully initialized") return try: processId = sender.CachedProcessID except COMError: pass else: appMod = appModuleHandler.getAppModuleFromProcessID(processId) if not appMod.shouldProcessUIAPropertyChangedEvent(sender, propertyId): return NVDAEventName=UIAPropertyIdsToNVDAEventNames.get(propertyId,None) if not NVDAEventName: if _isDebug(): log.debugWarning(f"HandlePropertyChangedEvent: Don't know how to handle property {propertyId}") return focus = api.getFocusObject() import NVDAObjects.UIA if ( isinstance(focus, NVDAObjects.UIA.UIA) and self.clientObject.compareElements(focus.UIAElement, sender) ): pass elif not self.isNativeUIAElement(sender): if _isDebug(): log.debug( f"HandlePropertyChangedEvent: Ignoring event {NVDAEventName} for non native element" ) return window = self.getNearestWindowHandle(sender) if window and not eventHandler.shouldAcceptEvent(NVDAEventName, windowHandle=window): if _isDebug(): log.debug( f"HandlePropertyChangedEvent: Ignoring event {NVDAEventName} for shouldAcceptEvent=False" ) return try: obj = NVDAObjects.UIA.UIA(UIAElement=sender) except Exception: if _isDebug(): log.debugWarning( f"HandlePropertyChangedEvent: Exception while creating object for event {NVDAEventName}", exc_info=True ) return if not obj: if _isDebug(): log.debug(f"HandlePropertyChangedEvent: Ignoring event {NVDAEventName} because no object") return if obj==focus: obj=focus eventHandler.queueEvent(NVDAEventName,obj) def IUIAutomationNotificationEventHandler_HandleNotificationEvent( self, sender, NotificationKind, NotificationProcessing, displayString, activityId ): if not self.MTAThreadInitEvent.isSet(): # UIAHandler hasn't finished initialising yet, so just ignore this event. if _isDebug(): log.debug("HandleNotificationEvent: event received while not fully initialized") return import NVDAObjects.UIA try: obj = NVDAObjects.UIA.UIA(UIAElement=sender) except Exception: if _isDebug(): log.debugWarning( "HandleNotificationEvent: Exception while creating object: " f"NotificationProcessing={NotificationProcessing} " f"displayString={displayString} " f"activityId={activityId}", exc_info=True ) return if not obj: # Sometimes notification events can be fired on a UIAElement that has no windowHandle and does not connect through parents back to the desktop. # There is nothing we can do with these. if _isDebug(): log.debug( "HandleNotificationEvent: Ignoring because no object: " f"NotificationProcessing={NotificationProcessing} " f"displayString={displayString} " f"activityId={activityId}" ) return eventHandler.queueEvent("UIA_notification",obj, notificationKind=NotificationKind, notificationProcessing=NotificationProcessing, displayString=displayString, activityId=activityId) def IUIAutomationActiveTextPositionChangedEventHandler_HandleActiveTextPositionChangedEvent( self, sender, textRange ): if not self.MTAThreadInitEvent.isSet(): # UIAHandler hasn't finished initialising yet, so just ignore this event. if _isDebug(): log.debug("HandleActiveTextPositionchangedEvent: event received while not fully initialized") return import NVDAObjects.UIA try: obj = NVDAObjects.UIA.UIA(UIAElement=sender) except Exception: if _isDebug(): log.debugWarning( "HandleActiveTextPositionChangedEvent: Exception while creating object: ", exc_info=True ) return if not obj: if _isDebug(): log.debug( "HandleActiveTextPositionchangedEvent: Ignoring because no object: " ) return eventHandler.queueEvent("UIA_activeTextPositionChanged", obj, textRange=textRange) def _isBadUIAWindowClassName(self, windowClass): "Given a windowClassName, returns True if this is a known problematic UIA implementation." # #7497: Windows 10 Fall Creators Update has an incomplete UIA # implementation for console windows, therefore for now we should # ignore it. # It does not implement caret/selection, and probably has no new text # events. if windowClass == "ConsoleWindowClass" and config.conf['UIA']['winConsoleImplementation'] != "UIA": return True return windowClass in badUIAWindowClassNames def _isUIAWindowHelper(self,hwnd): # UIA in NVDA's process freezes in Windows 7 and below processID=winUser.getWindowThreadProcessID(hwnd)[0] if windll.kernel32.GetCurrentProcessId()==processID: return False import NVDAObjects.window windowClass=NVDAObjects.window.Window.normalizeWindowClassName(winUser.getClassName(hwnd)) # For certain window classes, we always want to use UIA. if windowClass in goodUIAWindowClassNames: return True # allow the appModule for the window to also choose if this window is good # An appModule should be able to override bad UIA class names as prescribed by core appModule=appModuleHandler.getAppModuleFromProcessID(processID) if appModule and appModule.isGoodUIAWindow(hwnd): return True # There are certain window classes that just had bad UIA implementations if self._isBadUIAWindowClassName(windowClass): return False # allow the appModule for the window to also choose if this window is bad if appModule and appModule.isBadUIAWindow(hwnd): return False if windowClass == "NetUIHWND" and appModule: # NetUIHWND is used for various controls in MS Office. # IAccessible should be used for NetUIHWND in versions older than 2016 # Fixes: lack of focus reporting (#4207), # Fixes: strange reporting of context menu items(#9252), # fixes: not being able to report ribbon sections when they starts with an edit field (#7067) # Note that #7067 is not fixed for Office 2016 and never. # Using IAccessible for NetUIHWND controls causes focus changes not to be reported # when the ribbon is collapsed. # Testing shows that these controls emits proper events but they are ignored by NVDA. isOfficeApp = appModule.productName.startswith(("Microsoft Office", "Microsoft Outlook")) isOffice2013OrOlder = int(appModule.productVersion.split(".")[0]) < 16 if isOfficeApp and isOffice2013OrOlder: parentHwnd = winUser.getAncestor(hwnd, winUser.GA_PARENT) while parentHwnd: if winUser.getClassName(parentHwnd) in ("Net UI Tool Window", "MsoCommandBar",): return False parentHwnd = winUser.getAncestor(parentHwnd, winUser.GA_PARENT) # Ask the window if it supports UIA natively res=windll.UIAutomationCore.UiaHasServerSideProvider(hwnd) if res: # The window does support UIA natively, but MS Word documents now # have a fairly usable UI Automation implementation. # However, builds of MS Office 2016 before build 9000 or so had bugs which # we cannot work around. # And even current builds of Office 2016 are still missing enough info from # UIA that it is still impossible to switch to UIA completely. # Therefore, if we can inject in-process, refuse to use UIA and instead # fall back to the MS Word object model. canUseOlderInProcessApproach = bool(appModule.helperLocalBindingHandle) if ( # An MS Word document window windowClass=="_WwG" # Disabling is only useful if we can inject in-process (and use our older code) and canUseOlderInProcessApproach # Allow the user to explicitly force UIA support for MS Word documents # no matter the Office version and not config.conf['UIA']['useInMSWordWhenAvailable'] ): return False # MS Excel spreadsheets now have a fairly usable UI Automation implementation. # However, builds of MS Office 2016 before build 9000 or so had bugs which we # cannot work around. # And even current builds of Office 2016 are still missing enough info from UIA # that it is still impossible to switch to UIA completely. # Therefore, if we can inject in-process, refuse to use UIA and instead fall # back to the MS Excel object model. elif ( # An MS Excel spreadsheet window windowClass == "EXCEL7" # Disabling is only useful if we can inject in-process (and use our older code) and appModule.helperLocalBindingHandle # Allow the user to explicitly force UIA support for MS Excel spreadsheets # no matter the Office version and not config.conf['UIA']['useInMSExcelWhenAvailable'] ): return False # Unless explicitly allowed, all Chromium implementations (including Edge) should not be UIA, # As their IA2 implementation is still better at the moment. elif ( windowClass == "Chrome_RenderWidgetHostHWND" and ( AllowUiaInChromium.getConfig() == AllowUiaInChromium.NO # Disabling is only useful if we can inject in-process (and use our older code) or ( canUseOlderInProcessApproach and AllowUiaInChromium.getConfig() != AllowUiaInChromium.YES # Users can prefer to use UIA ) ) ): return False return bool(res) def isUIAWindow(self,hwnd): now=time.time() v=self.UIAWindowHandleCache.get(hwnd,None) if not v or (now-v[1])>0.5: v=self._isUIAWindowHelper(hwnd),now self.UIAWindowHandleCache[hwnd]=v return v[0] def getNearestWindowHandle(self,UIAElement): if hasattr(UIAElement,"_nearestWindowHandle"): # Called previously. Use cached result. return UIAElement._nearestWindowHandle try: processID=UIAElement.cachedProcessID except COMError: return None appModule=appModuleHandler.getAppModuleFromProcessID(processID) # WDAG (Windows Defender application Guard) UIA elements should be treated as being from a remote machine, and therefore their window handles are completely invalid on this machine. # Therefore, jump all the way up to the root of the WDAG process and use that window handle as it is local to this machine. if appModule.appName==WDAG_PROCESS_NAME: condition=UIAUtils.createUIAMultiPropertyCondition({UIA_ClassNamePropertyId:[u'ApplicationFrameWindow',u'CabinetWClass']}) walker=self.clientObject.createTreeWalker(condition) else: # Not WDAG, just walk up to the nearest valid windowHandle walker=self.windowTreeWalker try: new=walker.NormalizeElementBuildCache(UIAElement,self.windowCacheRequest) except COMError: return None try: window=new.cachedNativeWindowHandle except COMError: window=None # Cache for future use to improve performance. UIAElement._nearestWindowHandle=window return window def isNativeUIAElement(self,UIAElement): #Due to issues dealing with UIA elements coming from the same process, we do not class these UIA elements as usable. #It seems to be safe enough to retreave the cached processID, but using tree walkers or fetching other properties causes a freeze. try: processID=UIAElement.cachedProcessId except COMError: return False if processID==windll.kernel32.GetCurrentProcessId(): return False # Whether this is a native element depends on whether its window natively supports UIA. windowHandle=self.getNearestWindowHandle(UIAElement) if windowHandle: if self.isUIAWindow(windowHandle): return True if winUser.getClassName(windowHandle)=="DirectUIHWND" and "IEFRAME.dll" in UIAElement.cachedProviderDescription and UIAElement.currentClassName in ("DownloadBox", "accessiblebutton", "DUIToolbarButton", "PushButton"): # This is the IE 9 downloads list. # #3354: UiaHasServerSideProvider returns false for the IE 9 downloads list window, # so we'd normally use MSAA for this control. # However, its MSAA implementation is broken (fires invalid events) if UIA is initialised, # whereas its UIA implementation works correctly. # Therefore, we must use UIA here. return True return False def _isDebug(): return config.conf["debugLog"]["UIA"]
1
32,361
Why this is in the diff?
nvaccess-nvda
py
@@ -136,6 +136,8 @@ type QuiesceDriver interface { type CloudBackupDriver interface { // CloudBackupCreate uploads snapshot of a volume to the cloud CloudBackupCreate(input *api.CloudBackupCreateRequest) error + // CloudBackupGroupCreate creates and then uploads volumegroup snapshots + CloudBackupGroupCreate(input *api.CloudBackupGroupCreateRequest) error // CloudBackupRestore downloads a cloud backup and restores it to a volume CloudBackupRestore(input *api.CloudBackupRestoreRequest) (*api.CloudBackupRestoreResponse, error) // CloudBackupEnumerate enumerates the backups for a given cluster/credential/volumeID
1
package volume import ( "errors" "github.com/libopenstorage/openstorage/api" ) var ( // ErrAlreadyShutdown returned when driver is shutdown ErrAlreadyShutdown = errors.New("VolumeDriverProvider already shutdown") // ErrExit returned when driver already registered ErrExist = errors.New("Already exists") // ErrDriverNotFound returned when a driver is not registered ErrDriverNotFound = errors.New("Driver implementation not found") // ErrDriverInitializing returned when a driver is initializing ErrDriverInitializing = errors.New("Driver is initializing") // ErrEnoEnt returned when volume does not exist ErrEnoEnt = errors.New("Volume does not exist.") // ErrEnomem returned when we are out of memory ErrEnomem = errors.New("Out of memory.") // ErrEinval returned when an invalid input is provided ErrEinval = errors.New("Invalid argument") // ErrVolDetached returned when volume is in detached state ErrVolDetached = errors.New("Volume is detached") // ErrVolAttached returned when volume is in attached state ErrVolAttached = errors.New("Volume is attached") // ErrVolAttachedOnRemoteNode returned when volume is in attached on different node ErrVolAttachedOnRemoteNode = errors.New("Volume is attached on another node") // ErrVolAttachedScale returned when volume is attached and can be scaled ErrVolAttachedScale = errors.New("Volume is attached on another node." + " Increase scale factor to create more instances") // ErrVolHasSnaps returned when volume has previous snapshots ErrVolHasSnaps = errors.New("Volume has snapshots associated") // ErrNotSupported returned when the operation is not supported ErrNotSupported = errors.New("Operation not supported") // ErrVolBusy returned when volume is in busy state ErrVolBusy = errors.New("Volume is busy") ) // Constants used by the VolumeDriver const ( // APIVersion for the volume management apis APIVersion = "v1" // PluginAPIBase where the docker unix socket resides PluginAPIBase = "/run/docker/plugins/" // DriverAPIBase where the osd unix socket resides DriverAPIBase = "/var/lib/osd/driver/" // MountBase for osd mountpoints MountBase = "/var/lib/osd/mounts/" // VolumeBase for osd volumes VolumeBase = "/var/lib/osd/" ) const ( // LocationConstaint is a label that specifies data location constraint. LocationConstraint = "LocationConstraint" // LocalNode is an alias for this node - similar to localhost. LocalNode = "LocalNode" ) // Store defines the interface for basic volume store operations type Store interface { // Lock volume specified by volumeID. Lock(volumeID string) (interface{}, error) // Lock volume with token obtained from call to Lock. Unlock(token interface{}) error // CreateVol returns error if volume with the same ID already existe. CreateVol(vol *api.Volume) error // GetVol from volumeID. GetVol(volumeID string) (*api.Volume, error) // UpdateVol with vol UpdateVol(vol *api.Volume) error // DeleteVol. Returns error if volume does not exist. DeleteVol(volumeID string) error } // VolumeDriver is the main interface to be implemented by any storage driver. // Every driver must at minimum implement the ProtoDriver sub interface. type VolumeDriver interface { IODriver ProtoDriver BlockDriver Enumerator } // IODriver interfaces applicable to object store interfaces. type IODriver interface { // Read sz bytes from specified volume at specified offset. // Return number of bytes read and error. Read(volumeID string, buf []byte, sz uint64, offset int64) (int64, error) // Write sz bytes from specified volume at specified offset. // Return number of bytes written and error. Write(volumeID string, buf []byte, sz uint64, offset int64) (int64, error) // Flush writes to stable storage. // Return error. Flush(volumeID string) error } // SnapshotDriver interfaces provides snapshot capability type SnapshotDriver interface { // Snapshot create volume snapshot. // Errors ErrEnoEnt may be returned Snapshot(volumeID string, readonly bool, locator *api.VolumeLocator, noRetry bool) (string, error) // Restore restores volume to specified snapshot. Restore(volumeID string, snapshotID string) error // GroupSnapshot takes a snapshot of specified volumegroup. SnapshotGroup(groupID string, labels map[string]string) (*api.GroupSnapCreateResponse, error) } // StatsDriver interface provides stats features type StatsDriver interface { // Stats for specified volume. // cumulative stats are /proc/diskstats style stats. // nonCumulative stats are stats for specific duration. // Errors ErrEnoEnt may be returned Stats(volumeID string, cumulative bool) (*api.Stats, error) // UsedSize returns currently used volume size. // Errors ErrEnoEnt may be returned. UsedSize(volumeID string) (uint64, error) // GetActiveRequests get active requests GetActiveRequests() (*api.ActiveRequests, error) } type QuiesceDriver interface { // Freezes mounted filesystem resulting in a quiesced volume state. // Only one freeze operation may be active at any given time per volume. // Unfreezes after timeout seconds if it is non-zero. // An optional quiesceID can be passed for driver-specific use. Quiesce(volumeID string, timeoutSeconds uint64, quiesceID string) error // Unfreezes mounted filesystem if it was frozen. Unquiesce(volumeID string) error } // CloudBackupDriver interface provides Cloud backup features type CloudBackupDriver interface { // CloudBackupCreate uploads snapshot of a volume to the cloud CloudBackupCreate(input *api.CloudBackupCreateRequest) error // CloudBackupRestore downloads a cloud backup and restores it to a volume CloudBackupRestore(input *api.CloudBackupRestoreRequest) (*api.CloudBackupRestoreResponse, error) // CloudBackupEnumerate enumerates the backups for a given cluster/credential/volumeID CloudBackupEnumerate(input *api.CloudBackupEnumerateRequest) (*api.CloudBackupEnumerateResponse, error) // CloudBackupDelete deletes the specified backup in cloud CloudBackupDelete(input *api.CloudBackupDeleteRequest) error // CloudBackupDelete deletes all the backups for a given volume in cloud CloudBackupDeleteAll(input *api.CloudBackupDeleteAllRequest) error // CloudBackupStatus indicates the most recent status of backup/restores CloudBackupStatus(input *api.CloudBackupStatusRequest) (*api.CloudBackupStatusResponse, error) // CloudBackupCatalog displays listing of backup content CloudBackupCatalog(input *api.CloudBackupCatalogRequest) (*api.CloudBackupCatalogResponse, error) // CloudBackupHistory displays past backup/restore operations on a volume CloudBackupHistory(input *api.CloudBackupHistoryRequest) (*api.CloudBackupHistoryResponse, error) // CloudBackupStateChange allows a current backup state transisions(pause/resume/stop) CloudBackupStateChange(input *api.CloudBackupStateChangeRequest) error // CloudBackupSchedCreate creates a schedule backup volume to cloud CloudBackupSchedCreate(input *api.CloudBackupSchedCreateRequest) (*api.CloudBackupSchedCreateResponse, error) // CloudBackupSchedDelete delete a volume backup schedule to cloud CloudBackupSchedDelete(input *api.CloudBackupSchedDeleteRequest) error // CloudBackupSchedEnumerate enumerates the configured backup schedules in the cluster CloudBackupSchedEnumerate() (*api.CloudBackupSchedEnumerateResponse, error) } // CloudMigrateDriver interface provides Cloud migration features type CloudMigrateDriver interface { // CloudMigrateStart starts a migrate operation CloudMigrateStart(request *api.CloudMigrateStartRequest) error // CloudMigrateCancel cancels a migrate operation CloudMigrateCancel(request *api.CloudMigrateCancelRequest) error // CloudMigrateStatus returns status for the migration operations CloudMigrateStatus() (*api.CloudMigrateStatusResponse, error) } // ProtoDriver must be implemented by all volume drivers. It specifies the // most basic functionality, such as creating and deleting volumes. type ProtoDriver interface { SnapshotDriver StatsDriver QuiesceDriver CredsDriver CloudBackupDriver CloudMigrateDriver // Name returns the name of the driver. Name() string // Type of this driver Type() api.DriverType // Version information of the driver Version() (*api.StorageVersion, error) // Create a new Vol for the specific volume spec. // It returns a system generated VolumeID that uniquely identifies the volume Create(locator *api.VolumeLocator, Source *api.Source, spec *api.VolumeSpec) (string, error) // Delete volume. // Errors ErrEnoEnt, ErrVolHasSnaps may be returned. Delete(volumeID string) error // Mount volume at specified path // Errors ErrEnoEnt, ErrVolDetached may be returned. Mount(volumeID string, mountPath string, options map[string]string) error // MountedAt return volume mounted at specified mountpath. MountedAt(mountPath string) string // Unmount volume at specified path // Errors ErrEnoEnt, ErrVolDetached may be returned. Unmount(volumeID string, mountPath string, options map[string]string) error // Update not all fields of the spec are supported, ErrNotSupported will be thrown for unsupported // updates. Set(volumeID string, locator *api.VolumeLocator, spec *api.VolumeSpec) error // Status returns a set of key-value pairs which give low // level diagnostic status about this driver. Status() [][2]string // Shutdown and cleanup. Shutdown() // DU specified volume and potentially the subfolder if provided. Catalog(volumeid, subfolder string, depth string) (api.CatalogResponse, error) } // Enumerator provides a set of interfaces to get details on a set of volumes. type Enumerator interface { // Inspect specified volumes. // Returns slice of volumes that were found. Inspect(volumeIDs []string) ([]*api.Volume, error) // Enumerate volumes that map to the volumeLocator. Locator fields may be regexp. // If locator fields are left blank, this will return all volumes. Enumerate(locator *api.VolumeLocator, labels map[string]string) ([]*api.Volume, error) // Enumerate snaps for specified volumes SnapEnumerate(volID []string, snapLabels map[string]string) ([]*api.Volume, error) } // StoreEnumerator combines Store and Enumerator capabilities type StoreEnumerator interface { Store Enumerator } // BlockDriver needs to be implemented by block volume drivers. Filesystem volume // drivers can ignore this interface and include the builtin DefaultBlockDriver. type BlockDriver interface { // Attach map device to the host. // On success the devicePath specifies location where the device is exported // Errors ErrEnoEnt, ErrVolAttached may be returned. Attach(volumeID string, attachOptions map[string]string) (string, error) // Detach device from the host. // Errors ErrEnoEnt, ErrVolDetached may be returned. Detach(volumeID string, options map[string]string) error } // CredsDriver provides methods to handle credentials type CredsDriver interface { // CredsCreate creates credential for a given cloud provider CredsCreate(params map[string]string) (string, error) // CredsList lists the configured credentials in the cluster CredsEnumerate() (map[string]interface{}, error) // CredsDelete deletes the credential associated credUUID CredsDelete(credUUID string) error // CredsValidate validates the credential associated credUUID CredsValidate(credUUID string) error } // VolumeDriverProvider provides VolumeDrivers. type VolumeDriverProvider interface { // Get gets the VolumeDriver for the given name. // If a VolumeDriver was not created for the given name, the error ErrDriverNotFound is returned. Get(name string) (VolumeDriver, error) // Shutdown shuts down all volume drivers. Shutdown() error } // VolumeDriverRegistry registers VolumeDrivers. type VolumeDriverRegistry interface { VolumeDriverProvider // New creates the VolumeDriver for the given name. // If a VolumeDriver was already created for the given name, the error ErrExist is returned. Register(name string, params map[string]string) error // Add inserts a new VolumeDriver provider with a well known name. Add(name string, init func(map[string]string) (VolumeDriver, error)) error // Removes driver from registry. Does nothing if driver name does not exist. Remove(name string) } // NewVolumeDriverRegistry constructs a new VolumeDriverRegistry. func NewVolumeDriverRegistry(nameToInitFunc map[string]func(map[string]string) (VolumeDriver, error)) VolumeDriverRegistry { return newVolumeDriverRegistry(nameToInitFunc) }
1
7,177
How is status determined? When the user calls CloudBackupCreate( src_volume_id ) they can then call CloudBackupStatus( src_volume_id ) Is there something similar for this new API?
libopenstorage-openstorage
go
@@ -232,6 +232,15 @@ export function diff( if ((tmp = options.diffed)) tmp(newVNode); } catch (e) { + // When we are hydrating and have excessDomChildren we don't know the _children this VNode + // should receive so it's safer to unmount them. Else on the subsequent error-boundary diff, + // we won't know the oldDom and insert an additional node instead of replace the prerendered one. (#2539) + if (isHydrating && excessDomChildren != null) { + for (tmp = excessDomChildren.length; tmp--; ) { + if (excessDomChildren[tmp] != null) removeNode(excessDomChildren[tmp]); + } + } + newVNode._original = null; options._catchError(e, newVNode, oldVNode); }
1
import { EMPTY_OBJ, EMPTY_ARR } from '../constants'; import { Component } from '../component'; import { Fragment } from '../create-element'; import { diffChildren } from './children'; import { diffProps, setProperty } from './props'; import { assign, removeNode } from '../util'; import options from '../options'; /** * Diff two virtual nodes and apply proper changes to the DOM * @param {import('../internal').PreactElement} parentDom The parent of the DOM element * @param {import('../internal').VNode} newVNode The new virtual node * @param {import('../internal').VNode} oldVNode The old virtual node * @param {object} globalContext The current context object. Modified by getChildContext * @param {boolean} isSvg Whether or not this element is an SVG node * @param {Array<import('../internal').PreactElement>} excessDomChildren * @param {Array<import('../internal').Component>} commitQueue List of components * which have callbacks to invoke in commitRoot * @param {Element | Text} oldDom The current attached DOM * element any new dom elements should be placed around. Likely `null` on first * render (except when hydrating). Can be a sibling DOM element when diffing * Fragments that have siblings. In most cases, it starts out as `oldChildren[0]._dom`. * @param {boolean} [isHydrating] Whether or not we are in hydration */ export function diff( parentDom, newVNode, oldVNode, globalContext, isSvg, excessDomChildren, commitQueue, oldDom, isHydrating ) { let tmp, newType = newVNode.type; // When passing through createElement it assigns the object // constructor as undefined. This to prevent JSON-injection. if (newVNode.constructor !== undefined) return null; if ((tmp = options._diff)) tmp(newVNode); try { outer: if (typeof newType == 'function') { let c, isNew, oldProps, oldState, snapshot, clearProcessingException; let newProps = newVNode.props; // Necessary for createContext api. Setting this property will pass // the context value as `this.context` just for this component. tmp = newType.contextType; let provider = tmp && globalContext[tmp._id]; let componentContext = tmp ? provider ? provider.props.value : tmp._defaultValue : globalContext; // Get component and set it to `c` if (oldVNode._component) { c = newVNode._component = oldVNode._component; clearProcessingException = c._processingException = c._pendingError; } else { // Instantiate the new component if ('prototype' in newType && newType.prototype.render) { newVNode._component = c = new newType(newProps, componentContext); // eslint-disable-line new-cap } else { newVNode._component = c = new Component(newProps, componentContext); c.constructor = newType; c.render = doRender; } if (provider) provider.sub(c); c.props = newProps; if (!c.state) c.state = {}; c.context = componentContext; c._globalContext = globalContext; isNew = c._dirty = true; c._renderCallbacks = []; } // Invoke getDerivedStateFromProps if (c._nextState == null) { c._nextState = c.state; } if (newType.getDerivedStateFromProps != null) { if (c._nextState == c.state) { c._nextState = assign({}, c._nextState); } assign( c._nextState, newType.getDerivedStateFromProps(newProps, c._nextState) ); } oldProps = c.props; oldState = c.state; // Invoke pre-render lifecycle methods if (isNew) { if ( newType.getDerivedStateFromProps == null && c.componentWillMount != null ) { c.componentWillMount(); } if (c.componentDidMount != null) { c._renderCallbacks.push(c.componentDidMount); } } else { if ( newType.getDerivedStateFromProps == null && newProps !== oldProps && c.componentWillReceiveProps != null ) { c.componentWillReceiveProps(newProps, componentContext); } if ( (!c._force && c.shouldComponentUpdate != null && c.shouldComponentUpdate( newProps, c._nextState, componentContext ) === false) || newVNode._original === oldVNode._original ) { c.props = newProps; c.state = c._nextState; // More info about this here: https://gist.github.com/JoviDeCroock/bec5f2ce93544d2e6070ef8e0036e4e8 if (newVNode._original !== oldVNode._original) c._dirty = false; c._vnode = newVNode; newVNode._dom = oldVNode._dom; newVNode._children = oldVNode._children; if (c._renderCallbacks.length) { commitQueue.push(c); } for (tmp = 0; tmp < newVNode._children.length; tmp++) { if (newVNode._children[tmp]) { newVNode._children[tmp]._parent = newVNode; } } break outer; } if (c.componentWillUpdate != null) { c.componentWillUpdate(newProps, c._nextState, componentContext); } if (c.componentDidUpdate != null) { c._renderCallbacks.push(() => { c.componentDidUpdate(oldProps, oldState, snapshot); }); } } c.context = componentContext; c.props = newProps; c.state = c._nextState; if ((tmp = options._render)) tmp(newVNode); c._dirty = false; c._vnode = newVNode; c._parentDom = parentDom; tmp = c.render(c.props, c.state, c.context); // Handle setState called in render, see #2553 c.state = c._nextState; if (c.getChildContext != null) { globalContext = assign(assign({}, globalContext), c.getChildContext()); } if (!isNew && c.getSnapshotBeforeUpdate != null) { snapshot = c.getSnapshotBeforeUpdate(oldProps, oldState); } let isTopLevelFragment = tmp != null && tmp.type == Fragment && tmp.key == null; let renderResult = isTopLevelFragment ? tmp.props.children : tmp; diffChildren( parentDom, Array.isArray(renderResult) ? renderResult : [renderResult], newVNode, oldVNode, globalContext, isSvg, excessDomChildren, commitQueue, oldDom, isHydrating ); c.base = newVNode._dom; if (c._renderCallbacks.length) { commitQueue.push(c); } if (clearProcessingException) { c._pendingError = c._processingException = null; } c._force = false; } else if ( excessDomChildren == null && newVNode._original === oldVNode._original ) { newVNode._children = oldVNode._children; newVNode._dom = oldVNode._dom; } else { newVNode._dom = diffElementNodes( oldVNode._dom, newVNode, oldVNode, globalContext, isSvg, excessDomChildren, commitQueue, isHydrating ); } if ((tmp = options.diffed)) tmp(newVNode); } catch (e) { newVNode._original = null; options._catchError(e, newVNode, oldVNode); } return newVNode._dom; } /** * @param {Array<import('../internal').Component>} commitQueue List of components * which have callbacks to invoke in commitRoot * @param {import('../internal').VNode} root */ export function commitRoot(commitQueue, root) { if (options._commit) options._commit(root, commitQueue); commitQueue.some(c => { try { commitQueue = c._renderCallbacks; c._renderCallbacks = []; commitQueue.some(cb => { cb.call(c); }); } catch (e) { options._catchError(e, c._vnode); } }); } /** * Diff two virtual nodes representing DOM element * @param {import('../internal').PreactElement} dom The DOM element representing * the virtual nodes being diffed * @param {import('../internal').VNode} newVNode The new virtual node * @param {import('../internal').VNode} oldVNode The old virtual node * @param {object} globalContext The current context object * @param {boolean} isSvg Whether or not this DOM node is an SVG node * @param {*} excessDomChildren * @param {Array<import('../internal').Component>} commitQueue List of components * which have callbacks to invoke in commitRoot * @param {boolean} isHydrating Whether or not we are in hydration * @returns {import('../internal').PreactElement} */ function diffElementNodes( dom, newVNode, oldVNode, globalContext, isSvg, excessDomChildren, commitQueue, isHydrating ) { let i; let oldProps = oldVNode.props; let newProps = newVNode.props; // Tracks entering and exiting SVG namespace when descending through the tree. isSvg = newVNode.type === 'svg' || isSvg; if (excessDomChildren != null) { for (i = 0; i < excessDomChildren.length; i++) { const child = excessDomChildren[i]; // if newVNode matches an element in excessDomChildren or the `dom` // argument matches an element in excessDomChildren, remove it from // excessDomChildren so it isn't later removed in diffChildren if ( child != null && ((newVNode.type === null ? child.nodeType === 3 : child.localName === newVNode.type) || dom == child) ) { dom = child; excessDomChildren[i] = null; break; } } } if (dom == null) { if (newVNode.type === null) { return document.createTextNode(newProps); } dom = isSvg ? document.createElementNS('http://www.w3.org/2000/svg', newVNode.type) : document.createElement( newVNode.type, newProps.is && { is: newProps.is } ); // we created a new parent, so none of the previously attached children can be reused: excessDomChildren = null; // we are creating a new node, so we can assume this is a new subtree (in case we are hydrating), this deopts the hydrate isHydrating = false; } if (newVNode.type === null) { if (oldProps !== newProps && dom.data != newProps) { dom.data = newProps; } } else { if (excessDomChildren != null) { excessDomChildren = EMPTY_ARR.slice.call(dom.childNodes); } oldProps = oldVNode.props || EMPTY_OBJ; let oldHtml = oldProps.dangerouslySetInnerHTML; let newHtml = newProps.dangerouslySetInnerHTML; // During hydration, props are not diffed at all (including dangerouslySetInnerHTML) // @TODO we should warn in debug mode when props don't match here. if (!isHydrating) { // But, if we are in a situation where we are using existing DOM (e.g. replaceNode) // we should read the existing DOM attributes to diff them if (excessDomChildren != null) { oldProps = {}; for (let i = 0; i < dom.attributes.length; i++) { oldProps[dom.attributes[i].name] = dom.attributes[i].value; } } if (newHtml || oldHtml) { // Avoid re-applying the same '__html' if it did not changed between re-render if (!newHtml || !oldHtml || newHtml.__html != oldHtml.__html) { dom.innerHTML = (newHtml && newHtml.__html) || ''; } } } diffProps(dom, newProps, oldProps, isSvg, isHydrating); // If the new vnode didn't have dangerouslySetInnerHTML, diff its children if (newHtml) { newVNode._children = []; } else { i = newVNode.props.children; diffChildren( dom, Array.isArray(i) ? i : [i], newVNode, oldVNode, globalContext, newVNode.type === 'foreignObject' ? false : isSvg, excessDomChildren, commitQueue, EMPTY_OBJ, isHydrating ); } // (as above, don't diff props during hydration) if (!isHydrating) { if ( 'value' in newProps && (i = newProps.value) !== undefined && i !== dom.value ) { setProperty(dom, 'value', i, oldProps.value, false); } if ( 'checked' in newProps && (i = newProps.checked) !== undefined && i !== dom.checked ) { setProperty(dom, 'checked', i, oldProps.checked, false); } } } return dom; } /** * Invoke or update a ref, depending on whether it is a function or object ref. * @param {object|function} ref * @param {any} value * @param {import('../internal').VNode} vnode */ export function applyRef(ref, value, vnode) { try { if (typeof ref == 'function') ref(value); else ref.current = value; } catch (e) { options._catchError(e, vnode); } } /** * Unmount a virtual node from the tree and apply DOM changes * @param {import('../internal').VNode} vnode The virtual node to unmount * @param {import('../internal').VNode} parentVNode The parent of the VNode that * initiated the unmount * @param {boolean} [skipRemove] Flag that indicates that a parent node of the * current element is already detached from the DOM. */ export function unmount(vnode, parentVNode, skipRemove) { let r; if (options.unmount) options.unmount(vnode); if ((r = vnode.ref)) { if (!r.current || r.current === vnode._dom) applyRef(r, null, parentVNode); } let dom; if (!skipRemove && typeof vnode.type != 'function') { skipRemove = (dom = vnode._dom) != null; } // Must be set to `undefined` to properly clean up `_nextDom` // for which `null` is a valid value. See comment in `create-element.js` vnode._dom = vnode._nextDom = undefined; if ((r = vnode._component) != null) { if (r.componentWillUnmount) { try { r.componentWillUnmount(); } catch (e) { options._catchError(e, parentVNode); } } r.base = r._parentDom = null; } if ((r = vnode._children)) { for (let i = 0; i < r.length; i++) { if (r[i]) unmount(r[i], parentVNode, skipRemove); } } if (dom != null) removeNode(dom); } /** The `.render()` method for a PFC backing instance. */ function doRender(props, state, context) { return this.constructor(props, context); }
1
15,861
We could pass `excessDomChildren` to `options._catchError` and only do this if an error-boundary catches the error. Not entirely sure if that's better.
preactjs-preact
js
@@ -464,7 +464,7 @@ class CombineAssets */ protected function setHashOnCombinerFilters($hash) { - $allFilters = call_user_func_array('array_merge', $this->getFilters()); + $allFilters = array_merge(...array_values($this->getFilters())); foreach ($allFilters as $filter) { if (method_exists($filter, 'setHash')) {
1
<?php namespace System\Classes; use App; use Url; use File; use Lang; use Event; use Cache; use Route; use Config; use Request; use Response; use October\Rain\Assetic\Asset\FileAsset; use October\Rain\Assetic\Asset\AssetCache; use October\Rain\Assetic\Asset\AssetCollection; use October\Rain\Assetic\Cache\FilesystemCache; use October\Rain\Assetic\Factory\AssetFactory; use System\Helpers\Cache as CacheHelper; use ApplicationException; use DateTime; /** * Combiner class used for combining JavaScript and StyleSheet files. * * This works by taking a collection of asset locations, serializing them, * then storing them in the session with a unique ID. The ID is then used * to generate a URL to the `/combine` route via the system controller. * * When the combine route is hit, the unique ID is used to serve up the * assets -- minified, compiled or both. Special E-Tags are used to prevent * compilation and delivery of cached assets that are unchanged. * * Use the `CombineAssets::combine` method to combine your own assets. * * The functionality of this class is controlled by these config items: * * - cms.enableAssetCache - Cache untouched assets * - cms.enableAssetMinify - Compress assets using minification * - cms.enableAssetDeepHashing - Advanced caching of imports * * @see System\Classes\SystemController System controller * @see https://octobercms.com/docs/services/session Session service * @package october\system * @author Alexey Bobkov, Samuel Georges */ class CombineAssets { use \October\Rain\Support\Traits\Singleton; /** * @var array A list of known JavaScript extensions. */ protected static $jsExtensions = ['js']; /** * @var array A list of known StyleSheet extensions. */ protected static $cssExtensions = ['css', 'less', 'scss', 'sass']; /** * @var array Aliases for asset file paths. */ protected $aliases = []; /** * @var array Bundles that are compiled to the filesystem. */ protected $bundles = []; /** * @var array Filters to apply to each file. */ protected $filters = []; /** * @var string The local path context to find assets. */ protected $localPath; /** * @var string The output folder for storing combined files. */ protected $storagePath; /** * @var bool Cache untouched files. */ public $useCache = false; /** * @var bool Compress (minify) asset files. */ public $useMinify = false; /** * @var bool When true, cache will be busted when an import is modified. * Enabling this feature will make page loading slower. */ public $useDeepHashing = false; /** * @var array Cache of registration callbacks. */ private static $callbacks = []; /** * Constructor */ public function init() { /* * Register preferences */ $this->useCache = Config::get('cms.enableAssetCache', false); $this->useMinify = Config::get('cms.enableAssetMinify', null); $this->useDeepHashing = Config::get('cms.enableAssetDeepHashing', null); if ($this->useMinify === null) { $this->useMinify = !Config::get('app.debug', false); } if ($this->useDeepHashing === null) { $this->useDeepHashing = Config::get('app.debug', false); } /* * Register JavaScript filters */ $this->registerFilter('js', new \October\Rain\Assetic\Filter\JavascriptImporter); /* * Register CSS filters */ $this->registerFilter('css', new \October\Rain\Assetic\Filter\CssImportFilter); $this->registerFilter(['css', 'less', 'scss'], new \October\Rain\Assetic\Filter\CssRewriteFilter); $this->registerFilter('less', new \October\Rain\Assetic\Filter\LessCompiler); $this->registerFilter('scss', new \October\Rain\Assetic\Filter\ScssCompiler); /* * Minification filters */ if ($this->useMinify) { $this->registerFilter('js', new \October\Rain\Assetic\Filter\JSMinFilter); $this->registerFilter(['css', 'less', 'scss'], new \October\Rain\Assetic\Filter\StylesheetMinify); } /* * Common Aliases */ $this->registerAlias('jquery', '~/modules/backend/assets/js/vendor/jquery-and-migrate.min.js'); $this->registerAlias('framework', '~/modules/system/assets/js/framework.js'); $this->registerAlias('framework.extras', '~/modules/system/assets/js/framework.extras.js'); $this->registerAlias('framework.extras.js', '~/modules/system/assets/js/framework.extras.js'); $this->registerAlias('framework.extras', '~/modules/system/assets/css/framework.extras.css'); $this->registerAlias('framework.extras.css', '~/modules/system/assets/css/framework.extras.css'); /* * Deferred registration */ foreach (static::$callbacks as $callback) { $callback($this); } } /** * Combines JavaScript or StyleSheet file references * to produce a page relative URL to the combined contents. * * $assets = [ * 'assets/vendor/mustache/mustache.js', * 'assets/js/vendor/jquery.ui.widget.js', * 'assets/js/vendor/canvas-to-blob.js', * ]; * * CombineAssets::combine($assets, base_path('plugins/acme/blog')); * * @param array $assets Collection of assets * @param string $localPath Prefix all assets with this path (optional) * @return string URL to contents. */ public static function combine($assets = [], $localPath = null) { return self::instance()->prepareRequest($assets, $localPath); } /** * Combines a collection of assets files to a destination file * * $assets = [ * 'assets/less/header.less', * 'assets/less/footer.less', * ]; * * CombineAssets::combineToFile( * $assets, * base_path('themes/website/assets/theme.less'), * base_path('themes/website') * ); * * @param array $assets Collection of assets * @param string $destination Write the combined file to this location * @param string $localPath Prefix all assets with this path (optional) * @return void */ public function combineToFile($assets, $destination, $localPath = null) { // Disable cache always $this->storagePath = null; // Prefix all assets if ($localPath) { if (substr($localPath, -1) !== '/') { $localPath = $localPath.'/'; } $assets = array_map(function ($asset) use ($localPath) { if (substr($asset, 0, 1) === '@') { return $asset; } return $localPath.$asset; }, $assets); } list($assets, $extension) = $this->prepareAssets($assets); $rewritePath = File::localToPublic(dirname($destination)); $combiner = $this->prepareCombiner($assets, $rewritePath); $contents = $combiner->dump(); File::put($destination, $contents); } /** * Returns the combined contents from a prepared cache identifier. * @param string $cacheKey Cache identifier. * @return string Combined file contents. */ public function getContents($cacheKey) { $cacheInfo = $this->getCache($cacheKey); if (!$cacheInfo) { throw new ApplicationException(Lang::get('system::lang.combiner.not_found', ['name'=>$cacheKey])); } $this->localPath = $cacheInfo['path']; $this->storagePath = storage_path('cms/combiner/assets'); /* * Analyse cache information */ $lastModifiedTime = gmdate("D, d M Y H:i:s \G\M\T", array_get($cacheInfo, 'lastMod')); $etag = array_get($cacheInfo, 'etag'); $mime = (array_get($cacheInfo, 'extension') == 'css') ? 'text/css' : 'application/javascript'; /* * Set 304 Not Modified header, if necessary */ $response = Response::make(); $response->header('Content-Type', $mime); $response->header('Cache-Control', 'private, max-age=604800'); $response->setLastModified(new DateTime($lastModifiedTime)); $response->setEtag($etag); $response->setPublic(); $modified = !$response->isNotModified(App::make('request')); /* * Request says response is cached, no code evaluation needed */ if ($modified) { $this->setHashOnCombinerFilters($cacheKey); $combiner = $this->prepareCombiner($cacheInfo['files']); $contents = $combiner->dump(); $response->setContent($contents); } return $response; } /** * Prepares an array of assets by normalizing the collection * and processing aliases. * @param array $assets * @return array */ protected function prepareAssets(array $assets) { if (!is_array($assets)) { $assets = [$assets]; } /* * Split assets in to groups. */ $combineJs = []; $combineCss = []; foreach ($assets as $asset) { /* * Allow aliases to go through without an extension */ if (substr($asset, 0, 1) == '@') { $combineJs[] = $asset; $combineCss[] = $asset; continue; } $extension = File::extension($asset); if (in_array($extension, self::$jsExtensions)) { $combineJs[] = $asset; continue; } if (in_array($extension, self::$cssExtensions)) { $combineCss[] = $asset; continue; } } /* * Determine which group of assets to combine. */ if (count($combineCss) > count($combineJs)) { $extension = 'css'; $assets = $combineCss; } else { $extension = 'js'; $assets = $combineJs; } /* * Apply registered aliases */ if ($aliasMap = $this->getAliases($extension)) { foreach ($assets as $key => $asset) { if (substr($asset, 0, 1) !== '@') { continue; } $_asset = substr($asset, 1); if (isset($aliasMap[$_asset])) { $assets[$key] = $aliasMap[$_asset]; } } } return [$assets, $extension]; } /** * Combines asset file references of a single type to produce * a URL reference to the combined contents. * @param array $assets List of asset files. * @param string $localPath File extension, used for aesthetic purposes only. * @return string URL to contents. */ protected function prepareRequest(array $assets, $localPath = null) { if (substr($localPath, -1) != '/') { $localPath = $localPath.'/'; } $this->localPath = $localPath; $this->storagePath = storage_path('cms/combiner/assets'); list($assets, $extension) = $this->prepareAssets($assets); /* * Cache and process */ $cacheKey = $this->getCacheKey($assets); $cacheInfo = $this->useCache ? $this->getCache($cacheKey) : false; if (!$cacheInfo) { $this->setHashOnCombinerFilters($cacheKey); $combiner = $this->prepareCombiner($assets); if ($this->useDeepHashing) { $factory = new AssetFactory($this->localPath); $lastMod = $factory->getLastModified($combiner); } else { $lastMod = $combiner->getLastModified(); } $cacheInfo = [ 'version' => $cacheKey.'-'.$lastMod, 'etag' => $cacheKey, 'lastMod' => $lastMod, 'files' => $assets, 'path' => $this->localPath, 'extension' => $extension ]; $this->putCache($cacheKey, $cacheInfo); } return $this->getCombinedUrl($cacheInfo['version']); } /** * Returns the combined contents from a prepared cache identifier. * @param array $assets List of asset files. * @param string $rewritePath * @return string Combined file contents. */ protected function prepareCombiner(array $assets, $rewritePath = null) { /** * @event cms.combiner.beforePrepare * Provides an opportunity to interact with the asset combiner before assets are combined. * >**NOTE**: Plugin's must be elevated (`$elevated = true` on Plugin.php) to be run on the /combine route and thus listen to this event * * Example usage: * * Event::listen('cms.combiner.beforePrepare', function ((\System\Classes\CombineAssets) $assetCombiner, (array) $assets) { * $assetCombiner->registerFilter(...) * }); * */ Event::fire('cms.combiner.beforePrepare', [$this, $assets]); $files = []; $filesSalt = null; foreach ($assets as $asset) { $filters = $this->getFilters(File::extension($asset)) ?: []; $path = file_exists($asset) ? $asset : (File::symbolizePath($asset, null) ?: $this->localPath . $asset); $files[] = new FileAsset($path, $filters, public_path()); $filesSalt .= $this->localPath . $asset; } $filesSalt = md5($filesSalt); $collection = new AssetCollection($files, [], $filesSalt); $collection->setTargetPath($this->getTargetPath($rewritePath)); if ($this->storagePath === null) { return $collection; } if (!File::isDirectory($this->storagePath)) { @File::makeDirectory($this->storagePath); } $cache = new FilesystemCache($this->storagePath); $cachedFiles = []; foreach ($files as $file) { $cachedFiles[] = new AssetCache($file, $cache); } $cachedCollection = new AssetCollection($cachedFiles, [], $filesSalt); $cachedCollection->setTargetPath($this->getTargetPath($rewritePath)); return $cachedCollection; } /** * Busts the cache based on a different cache key. * @return void */ protected function setHashOnCombinerFilters($hash) { $allFilters = call_user_func_array('array_merge', $this->getFilters()); foreach ($allFilters as $filter) { if (method_exists($filter, 'setHash')) { $filter->setHash($hash); } } } /** * Returns a deep hash on filters that support it. * @param array $assets List of asset files. * @return void */ protected function getDeepHashFromAssets($assets) { $key = ''; $assetFiles = array_map(function ($file) { return file_exists($file) ? $file : (File::symbolizePath($file, null) ?: $this->localPath . $file); }, $assets); foreach ($assetFiles as $file) { $filters = $this->getFilters(File::extension($file)); foreach ($filters as $filter) { if (method_exists($filter, 'hashAsset')) { $key .= $filter->hashAsset($file, $this->localPath); } } } return $key; } /** * Returns the URL used for accessing the combined files. * @param string $outputFilename A custom file name to use. * @return string */ protected function getCombinedUrl($outputFilename = 'undefined.css') { $combineAction = 'System\Classes\Controller@combine'; $actionExists = Route::getRoutes()->getByAction($combineAction) !== null; if ($actionExists) { return Url::action($combineAction, [$outputFilename], false); } return '/combine/'.$outputFilename; } /** * Returns the target path for use with the combiner. The target * path helps generate relative links within CSS. * * /combine returns combine/ * /index.php/combine returns index-php/combine/ * * @param string|null $path * @return string The new target path */ protected function getTargetPath($path = null) { if ($path === null) { $baseUri = substr(Request::getBaseUrl(), strlen(Request::getBasePath())); $path = $baseUri.'/combine'; } if (strpos($path, '/') === 0) { $path = substr($path, 1); } $path = str_replace('.', '-', $path).'/'; return $path; } // // Registration // /** * Registers a callback function that defines bundles. * The callback function should register bundles by calling the manager's * `registerBundle` method. This instance is passed to the callback * function as an argument. Usage: * * CombineAssets::registerCallback(function ($combiner) { * $combiner->registerBundle('~/modules/backend/assets/less/october.less'); * }); * * @param callable $callback A callable function. */ public static function registerCallback(callable $callback) { self::$callbacks[] = $callback; } // // Filters // /** * Register a filter to apply to the combining process. * @param string|array $extension Extension name. Eg: css * @param object $filter Collection of files to combine. * @return self */ public function registerFilter($extension, $filter) { if (is_array($extension)) { foreach ($extension as $_extension) { $this->registerFilter($_extension, $filter); } return; } $extension = strtolower($extension); if (!isset($this->filters[$extension])) { $this->filters[$extension] = []; } if ($filter !== null) { $this->filters[$extension][] = $filter; } return $this; } /** * Clears any registered filters. * @param string $extension Extension name. Eg: css * @return self */ public function resetFilters($extension = null) { if ($extension === null) { $this->filters = []; } else { $this->filters[$extension] = []; } return $this; } /** * Returns filters. * @param string $extension Extension name. Eg: css * @return self */ public function getFilters($extension = null) { if ($extension === null) { return $this->filters; } if (isset($this->filters[$extension])) { return $this->filters[$extension]; } return null; } // // Bundles // /** * Registers bundle. * @param string|array $files Files to be registered to bundle * @param string $destination Destination file will be compiled to. * @param string $extension Extension name. Eg: css * @return self */ public function registerBundle($files, $destination = null, $extension = null) { if (!is_array($files)) { $files = [$files]; } $firstFile = array_values($files)[0]; if ($extension === null) { $extension = File::extension($firstFile); } $extension = strtolower(trim($extension)); if ($destination === null) { $file = File::name($firstFile); $path = dirname($firstFile); $preprocessors = array_diff(self::$cssExtensions, ['css']); if (in_array($extension, $preprocessors)) { $cssPath = $path.'/../css'; if ( in_array(strtolower(basename($path)), $preprocessors) && File::isDirectory(File::symbolizePath($cssPath)) ) { $path = $cssPath; } $destination = $path.'/'.$file.'.css'; } else { $destination = $path.'/'.$file.'-min.'.$extension; } } $this->bundles[$extension][$destination] = $files; return $this; } /** * Returns bundles. * @param string $extension Extension name. Eg: css * @return self */ public function getBundles($extension = null) { if ($extension === null) { return $this->bundles; } if (isset($this->bundles[$extension])) { return $this->bundles[$extension]; } return null; } // // Aliases // /** * Register an alias to use for a longer file reference. * @param string $alias Alias name. Eg: framework * @param string $file Path to file to use for alias * @param string $extension Extension name. Eg: css * @return self */ public function registerAlias($alias, $file, $extension = null) { if ($extension === null) { $extension = File::extension($file); } $extension = strtolower($extension); if (!isset($this->aliases[$extension])) { $this->aliases[$extension] = []; } $this->aliases[$extension][$alias] = $file; return $this; } /** * Clears any registered aliases. * @param string $extension Extension name. Eg: css * @return self */ public function resetAliases($extension = null) { if ($extension === null) { $this->aliases = []; } else { $this->aliases[$extension] = []; } return $this; } /** * Returns aliases. * @param string $extension Extension name. Eg: css * @return self */ public function getAliases($extension = null) { if ($extension === null) { return $this->aliases; } if (isset($this->aliases[$extension])) { return $this->aliases[$extension]; } return null; } // // Cache // /** * Stores information about a asset collection against * a cache identifier. * @param string $cacheKey Cache identifier. * @param array $cacheInfo List of asset files. * @return bool Successful */ protected function putCache($cacheKey, array $cacheInfo) { $cacheKey = 'combiner.'.$cacheKey; if (Cache::has($cacheKey)) { return false; } $this->putCacheIndex($cacheKey); Cache::forever($cacheKey, base64_encode(serialize($cacheInfo))); return true; } /** * Look up information about a cache identifier. * @param string $cacheKey Cache identifier * @return array Cache information */ protected function getCache($cacheKey) { $cacheKey = 'combiner.'.$cacheKey; if (!Cache::has($cacheKey)) { return false; } return @unserialize(@base64_decode(Cache::get($cacheKey))); } /** * Builds a unique string based on assets * @param array $assets Asset files * @return string Unique identifier */ protected function getCacheKey(array $assets) { $cacheKey = $this->localPath . implode('|', $assets); /* * Deep hashing */ if ($this->useDeepHashing) { $cacheKey .= $this->getDeepHashFromAssets($assets); } $dataHolder = (object) ['key' => $cacheKey]; /** * @event cms.combiner.getCacheKey * Provides an opportunity to modify the asset combiner's cache key * * Example usage: * * Event::listen('cms.combiner.getCacheKey', function ((\System\Classes\CombineAssets) $assetCombiner, (stdClass) $dataHolder) { * $dataHolder->key = rand(); * }); * */ Event::fire('cms.combiner.getCacheKey', [$this, $dataHolder]); $cacheKey = $dataHolder->key; return md5($cacheKey); } /** * Resets the combiner cache * @return void */ public static function resetCache() { if (Cache::has('combiner.index')) { $index = (array) @unserialize(@base64_decode(Cache::get('combiner.index'))) ?: []; foreach ($index as $cacheKey) { Cache::forget($cacheKey); } Cache::forget('combiner.index'); } CacheHelper::instance()->clearCombiner(); } /** * Adds a cache identifier to the index store used for * performing a reset of the cache. * @param string $cacheKey Cache identifier * @return bool Returns false if identifier is already in store */ protected function putCacheIndex($cacheKey) { $index = []; if (Cache::has('combiner.index')) { $index = (array) @unserialize(@base64_decode(Cache::get('combiner.index'))) ?: []; } if (in_array($cacheKey, $index)) { return false; } $index[] = $cacheKey; Cache::forever('combiner.index', base64_encode(serialize($index))); return true; } }
1
19,343
In php8 named parameters were introduced and now it is required to match called method parameter name when setting parameters by array destructing or call_user_func_array() etc.
octobercms-october
php
@@ -82,6 +82,9 @@ func (b3 B3) Extract(ctx context.Context, supplier propagation.HTTPSupplier) con } else { sc = b3.extract(supplier) } + if !sc.IsValid() { + return ctx + } return ContextWithRemoteSpanContext(ctx, sc) }
1
// Copyright The OpenTelemetry Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package trace import ( "context" "fmt" "strings" "go.opentelemetry.io/otel/api/core" "go.opentelemetry.io/otel/api/propagation" ) const ( B3SingleHeader = "X-B3" B3DebugFlagHeader = "X-B3-Flags" B3TraceIDHeader = "X-B3-TraceId" B3SpanIDHeader = "X-B3-SpanId" B3SampledHeader = "X-B3-Sampled" B3ParentSpanIDHeader = "X-B3-ParentSpanId" ) // B3 propagator serializes core.SpanContext to/from B3 Headers. // This propagator supports both version of B3 headers, // 1. Single Header : // X-B3: {TraceId}-{SpanId}-{SamplingState}-{ParentSpanId} // 2. Multiple Headers: // X-B3-TraceId: {TraceId} // X-B3-ParentSpanId: {ParentSpanId} // X-B3-SpanId: {SpanId} // X-B3-Sampled: {SamplingState} // X-B3-Flags: {DebugFlag} // // If SingleHeader is set to true then X-B3 header is used to inject and extract. Otherwise, // separate headers are used to inject and extract. type B3 struct { SingleHeader bool } var _ propagation.HTTPPropagator = B3{} func (b3 B3) Inject(ctx context.Context, supplier propagation.HTTPSupplier) { sc := SpanFromContext(ctx).SpanContext() if !sc.IsValid() { return } if b3.SingleHeader { sampled := sc.TraceFlags & core.TraceFlagsSampled supplier.Set(B3SingleHeader, fmt.Sprintf("%s-%s-%.1d", sc.TraceID, sc.SpanID, sampled)) } else { supplier.Set(B3TraceIDHeader, sc.TraceID.String()) supplier.Set(B3SpanIDHeader, sc.SpanID.String()) var sampled string if sc.IsSampled() { sampled = "1" } else { sampled = "0" } supplier.Set(B3SampledHeader, sampled) } } // Extract retrieves B3 Headers from the supplier func (b3 B3) Extract(ctx context.Context, supplier propagation.HTTPSupplier) context.Context { var sc core.SpanContext if b3.SingleHeader { sc = b3.extractSingleHeader(supplier) } else { sc = b3.extract(supplier) } return ContextWithRemoteSpanContext(ctx, sc) } func (b3 B3) extract(supplier propagation.HTTPSupplier) core.SpanContext { tid, err := core.TraceIDFromHex(supplier.Get(B3TraceIDHeader)) if err != nil { return core.EmptySpanContext() } sid, err := core.SpanIDFromHex(supplier.Get(B3SpanIDHeader)) if err != nil { return core.EmptySpanContext() } sampled, ok := b3.extractSampledState(supplier.Get(B3SampledHeader)) if !ok { return core.EmptySpanContext() } debug, ok := b3.extracDebugFlag(supplier.Get(B3DebugFlagHeader)) if !ok { return core.EmptySpanContext() } if debug == core.TraceFlagsSampled { sampled = core.TraceFlagsSampled } sc := core.SpanContext{ TraceID: tid, SpanID: sid, TraceFlags: sampled, } if !sc.IsValid() { return core.EmptySpanContext() } return sc } func (b3 B3) extractSingleHeader(supplier propagation.HTTPSupplier) core.SpanContext { h := supplier.Get(B3SingleHeader) if h == "" || h == "0" { return core.EmptySpanContext() } sc := core.SpanContext{} parts := strings.Split(h, "-") l := len(parts) if l > 4 { return core.EmptySpanContext() } if l < 2 { return core.EmptySpanContext() } var err error sc.TraceID, err = core.TraceIDFromHex(parts[0]) if err != nil { return core.EmptySpanContext() } sc.SpanID, err = core.SpanIDFromHex(parts[1]) if err != nil { return core.EmptySpanContext() } if l > 2 { var ok bool sc.TraceFlags, ok = b3.extractSampledState(parts[2]) if !ok { return core.EmptySpanContext() } } if l == 4 { _, err = core.SpanIDFromHex(parts[3]) if err != nil { return core.EmptySpanContext() } } if !sc.IsValid() { return core.EmptySpanContext() } return sc } // extractSampledState parses the value of the X-B3-Sampled b3Header. func (b3 B3) extractSampledState(sampled string) (flag byte, ok bool) { switch sampled { case "", "0": return 0, true case "1": return core.TraceFlagsSampled, true case "true": if !b3.SingleHeader { return core.TraceFlagsSampled, true } case "d": if b3.SingleHeader { return core.TraceFlagsSampled, true } } return 0, false } // extracDebugFlag parses the value of the X-B3-Sampled b3Header. func (b3 B3) extracDebugFlag(debug string) (flag byte, ok bool) { switch debug { case "", "0": return 0, true case "1": return core.TraceFlagsSampled, true } return 0, false } func (b3 B3) GetAllKeys() []string { if b3.SingleHeader { return []string{B3SingleHeader} } return []string{B3TraceIDHeader, B3SpanIDHeader, B3SampledHeader} }
1
12,029
If instead we had `B3.extractSingleHeader` and `B3.extract` return a bool value as a second return value, we could avoid the byte array comparison in `TraceID.IsValid`. Did you consider that alternative?
open-telemetry-opentelemetry-go
go
@@ -56,7 +56,7 @@ return [ 'choose_file' => 'Datei auswählen', 'close' => 'Schließen', 'create' => 'Erstellen', - 'create_and_add_another' => 'Erstellen und weiter hinzufügen', + 'create_and_add_another' => 'Erstellen und weitere hinzufügen', 'create_and_continue' => 'Erstellen und weiter bearbeiten', 'save' => 'Speichern', 'save_and_continue' => 'Speichern und weiter bearbeiten',
1
<?php return [ 'page_title' => [ 'dashboard' => 'Dashboard', 'detail' => '%entity_label_singular% <small>(#%entity_short_id%)</small>', 'edit' => '%entity_label_singular% <small>(#%entity_short_id%)</small> bearbeiten', 'index' => '%entity_label_plural%', 'new' => '%entity_label_singular% erstellen', 'exception' => 'Fehler', ], 'datagrid' => [ 'hidden_results' => 'Einige Ergebnisse können aufgrund fehlender Berechtigungen nicht angezeigt werden.', 'no_results' => 'Keine Ergebnisse gefunden.', ], 'paginator' => [ 'first' => 'Erste', 'previous' => 'Zurück', 'next' => 'Nächste', 'last' => 'Letzte', 'counter' => '<strong>%start%</strong> - <strong>%end%</strong> von <strong>%results%</strong>', 'results' => '{0} Keine Ergebnisse|{1} <strong>1</strong> Ergebnis|]1,Inf] <strong>%count%</strong> Ergebnisse', ], 'label' => [ 'true' => 'Ja', 'false' => 'Nein', 'empty' => 'Leer', 'null' => 'Null', 'nullable_field' => 'Feld leer lassen', 'object' => 'PHP-Objekt', 'inaccessible' => 'Nicht zugreifbar', 'inaccessible.explanation' => 'Es gibt keine Getter-Methode für diese Eigenschaft oder die Eigenschaft ist nicht public', 'form.empty_value' => 'kein Wert', ], 'field' => [ 'code_editor.view_code' => 'Code anzeigen', 'text_editor.view_content' => 'Inhalt anzeigen', ], 'action' => [ 'entity_actions' => 'Aktionen', 'new' => '%entity_label_singular% erstellen', 'search' => 'Suchen', 'detail' => 'Anzeigen', 'edit' => 'Ändern', 'delete' => 'Löschen', 'cancel' => 'Abbrechen', 'index' => 'Zurück zur Übersicht', 'deselect' => 'Auswahl aufheben', 'add_new_item' => 'Neues Element hinzufügen', 'remove_item' => 'Element entfernen', 'choose_file' => 'Datei auswählen', 'close' => 'Schließen', 'create' => 'Erstellen', 'create_and_add_another' => 'Erstellen und weiter hinzufügen', 'create_and_continue' => 'Erstellen und weiter bearbeiten', 'save' => 'Speichern', 'save_and_continue' => 'Speichern und weiter bearbeiten', ], 'batch_action_modal' => [ 'title' => 'Möchten Sie die ausgewählten Elemente wirklich verändern?', 'content' => 'Diese Aktion kann nicht rückgängig gemacht werden.', 'action' => 'Fortfahren', ], 'delete_modal' => [ 'title' => 'Soll das Element wirklich gelöscht werden?', 'content' => 'Diese Aktion kann nicht rückgängig gemacht werden.', ], 'filter' => [ 'title' => 'Filtern', 'button.clear' => 'Zurücksetzen', 'button.apply' => 'Anwenden', 'label.is_equal_to' => 'ist gleich', 'label.is_not_equal_to' => 'ist nicht gleich', 'label.is_greater_than' => 'ist größer als', 'label.is_greater_than_or_equal_to' => 'ist größer oder gleich', 'label.is_less_than' => 'ist kleiner als', 'label.is_less_than_or_equal_to' => 'ist kleiner oder gleich', 'label.is_between' => 'ist zwischen', 'label.contains' => 'enthält', 'label.not_contains' => 'enthält nicht', 'label.starts_with' => 'beginnt mit', 'label.ends_with' => 'endet mit', 'label.exactly' => 'ist genau', 'label.not_exactly' => 'ist nicht genau', 'label.is_same' => 'ist gleich', 'label.is_not_same' => 'ist nicht gleich', 'label.is_after' => 'ist nach', 'label.is_after_or_same' => 'ist nach oder gleich', 'label.is_before' => 'ist vor', 'label.is_before_or_same' => 'ist vor oder gleich', ], 'form' => [ 'are_you_sure' => 'Vorgenommene Änderungen wurden noch nicht gespeichert.', 'tab.error_badge_title' => 'Eine ungültige Eingabe|%count% ungültige Eingaben', 'slug.confirm_text' => 'Wenn Sie den Slug ändern, kann dies Links auf anderen Seiten beschädigen.', ], 'user' => [ 'logged_in_as' => 'Angemeldet als', 'unnamed' => 'Unbenannter Benutzer', 'anonymous' => 'Anonymer Benutzer', 'sign_out' => 'Abmelden', 'exit_impersonation' => 'Benutzerimitation verlassen', ], 'login_page' => [ 'username' => 'Benutzername', 'password' => 'Passwort', 'sign_in' => 'Login', ], 'exception' => [ 'entity_not_found' => 'Dieses Element ist nicht mehr verfügbar.', 'entity_remove' => 'Dieses Element kann nicht gelöscht werden, weil andere Elemente davon abhängen.', 'forbidden_action' => 'Die gewünschte Aktion kann kann mit diesem Element nicht ausgeführt werden.', 'insufficient_entity_permission' => 'Sie haben keine Berechtigung, auf dieses Element zuzugreifen.', ], ];
1
12,698
I think this is more of a semantic difference than a typo - `weiter hinzufgen` is like `continue adding` whereas `weitere hinzufgen` is like `add more`. I think it makes sense to change it though
EasyCorp-EasyAdminBundle
php
@@ -227,3 +227,12 @@ class RecordsViewTest(BaseWebTest, unittest.TestCase): MINIMALIST_RECORD, headers=headers, status=200) + + def test_records_can_be_created_after_deletion(self): + self.app.delete(self.record_url, + headers=self.headers, + status=200) + headers = self.headers.copy() + headers['If-None-Match'] = '*' + self.app.put_json(self.record_url, MINIMALIST_RECORD, + headers=headers, status=201)
1
import json import mock from cliquet.utils import decode_header from .support import (BaseWebTest, unittest, MINIMALIST_RECORD, MINIMALIST_GROUP, MINIMALIST_BUCKET, MINIMALIST_COLLECTION, get_user_headers) class RecordsViewTest(BaseWebTest, unittest.TestCase): collection_url = '/buckets/beers/collections/barley/records' _record_url = '/buckets/beers/collections/barley/records/%s' def setUp(self): super(RecordsViewTest, self).setUp() self.app.put_json('/buckets/beers', MINIMALIST_BUCKET, headers=self.headers) self.app.put_json('/buckets/beers/collections/barley', MINIMALIST_COLLECTION, headers=self.headers) resp = self.app.post_json(self.collection_url, MINIMALIST_RECORD, headers=self.headers) self.record = resp.json['data'] self.record_url = self._record_url % self.record['id'] def test_records_can_be_accessed_by_id(self): self.app.get(self.record_url, headers=self.headers) def test_unknown_bucket_raises_403(self): other_bucket = self.collection_url.replace('beers', 'sodas') self.app.get(other_bucket, headers=self.headers, status=403) def test_unknown_collection_raises_404(self): other_collection = self.collection_url.replace('barley', 'pills') self.app.get(other_collection, headers=self.headers, status=404) def test_parent_collection_is_fetched_only_once_in_batch(self): batch = {'requests': []} nb_create = 25 for i in range(nb_create): request = {'method': 'POST', 'path': self.collection_url, 'body': MINIMALIST_RECORD} batch['requests'].append(request) with mock.patch.object(self.storage, 'get', wraps=self.storage.get) as patched: self.app.post_json('/batch', batch, headers=self.headers) self.assertEqual(patched.call_count, 1) def test_individual_collections_can_be_deleted(self): resp = self.app.get(self.collection_url, headers=self.headers) self.assertEqual(len(resp.json['data']), 1) self.app.delete(self.collection_url, headers=self.headers) resp = self.app.get(self.collection_url, headers=self.headers) self.assertEqual(len(resp.json['data']), 0) def test_records_can_be_added_to_collections(self): response = self.app.get(self.record_url, headers=self.headers) record = response.json['data'] del record['id'] del record['last_modified'] self.assertEquals(record, MINIMALIST_RECORD['data']) def test_records_are_isolated_by_bucket_and_by_collection(self): # By collection. self.app.put_json('/buckets/beers/collections/pills', MINIMALIST_BUCKET, headers=self.headers) other_collection = self.record_url.replace('barley', 'pills') self.app.get(other_collection, headers=self.headers, status=404) # By bucket. self.app.put_json('/buckets/sodas', MINIMALIST_BUCKET, headers=self.headers) self.app.put_json('/buckets/sodas/collections/barley', MINIMALIST_COLLECTION, headers=self.headers) other_bucket = self.record_url.replace('beers', 'sodas') self.app.get(other_bucket, headers=self.headers, status=404) # By bucket and by collection. self.app.put_json('/buckets/be', MINIMALIST_BUCKET, headers=self.headers) self.app.put_json('/buckets/be/collections/ba', MINIMALIST_COLLECTION, headers=self.headers) other = self.record_url.replace('barley', 'ba').replace('beers', 'be') self.app.get(other, headers=self.headers, status=404) def test_a_collection_named_group_do_not_interfere_with_groups(self): # Create a group. self.app.put_json('/buckets/beers/groups/test', MINIMALIST_GROUP, headers=self.headers) # Create a record in a collection named "group". self.app.put_json('/buckets/beers/collections/groups', MINIMALIST_COLLECTION, headers=self.headers) collection_group = self.collection_url.replace('barley', 'groups') self.app.post_json(collection_group, MINIMALIST_RECORD, headers=self.headers) # There is still only one group. resp = self.app.get('/buckets/beers/groups', headers=self.headers) self.assertEqual(len(resp.json['data']), 1) def test_records_can_be_filtered_on_any_field(self): self.app.post_json(self.collection_url, MINIMALIST_RECORD, headers=self.headers) response = self.app.get(self.collection_url + '?unknown=1', headers=self.headers) self.assertEqual(len(response.json['data']), 0) def test_records_can_be_sorted_on_any_field(self): for i in range(3): record = MINIMALIST_RECORD.copy() record['data']['name'] = 'Stout %s' % i self.app.post_json(self.collection_url, record, headers=self.headers) response = self.app.get(self.collection_url + '?_sort=-name', headers=self.headers) names = [i['name'] for i in response.json['data']] self.assertEqual(names, ['Stout 2', 'Stout 1', 'Stout 0', 'Hulled Barley']) def test_wrong_create_permissions_cannot_be_added_on_records(self): record = MINIMALIST_RECORD.copy() record['permissions'] = {'record:create': ['fxa:user']} self.app.put_json(self.record_url, record, headers=self.headers, status=400) def test_create_a_record_update_collection_timestamp(self): collection_resp = self.app.get(self.collection_url, headers=self.headers) old_timestamp = int( decode_header(json.loads(collection_resp.headers['ETag']))) self.app.post_json(self.collection_url, MINIMALIST_RECORD, headers=self.headers, status=201) collection_resp = self.app.get(self.collection_url, headers=self.headers) new_timestamp = int( decode_header(json.loads(collection_resp.headers['ETag']))) assert old_timestamp < new_timestamp def test_update_a_record_update_collection_timestamp(self): collection_resp = self.app.get(self.collection_url, headers=self.headers) old_timestamp = int( decode_header(json.loads(collection_resp.headers['ETag']))) self.app.put_json(self.record_url, MINIMALIST_RECORD, headers=self.headers, status=200) collection_resp = self.app.get(self.collection_url, headers=self.headers) new_timestamp = int( decode_header(json.loads(collection_resp.headers['ETag']))) assert old_timestamp < new_timestamp def test_delete_a_record_update_collection_timestamp(self): collection_resp = self.app.get(self.collection_url, headers=self.headers) old_timestamp = int( decode_header(json.loads(collection_resp.headers['ETag']))) self.app.delete(self.record_url, headers=self.headers, status=200) collection_resp = self.app.get(self.collection_url, headers=self.headers) new_timestamp = int( decode_header(json.loads(collection_resp.headers['ETag']))) assert old_timestamp < new_timestamp def test_record_is_accessible_by_group_member(self): # access as aaron self.aaron_headers = self.headers.copy() self.aaron_headers.update(**get_user_headers('aaron')) resp = self.app.get('/', headers=self.aaron_headers, status=200) self.create_group('beers', 'brewers', [resp.json['user']['id']]) record = MINIMALIST_RECORD.copy() record['permissions'] = {'read': ['/buckets/beers/groups/brewers']} self.app.put_json(self.record_url, record, headers=self.headers, status=200) self.app.get(self.record_url, headers=self.aaron_headers, status=200) def test_records_should_reject_unaccepted_request_content_type(self): headers = self.headers.copy() headers['Content-Type'] = 'text/plain' self.app.put(self.record_url, MINIMALIST_RECORD, headers=headers, status=415) def test_records_should_reject_unaccepted_client_accept(self): headers = self.headers.copy() headers['Accept'] = 'text/plain' self.app.get(self.record_url, MINIMALIST_RECORD, headers=headers, status=406) def test_records_should_accept_client_accept(self): headers = self.headers.copy() headers['Accept'] = '*/*' self.app.get(self.record_url, MINIMALIST_RECORD, headers=headers, status=200)
1
8,964
nit: 200 is superfluous
Kinto-kinto
py
@@ -246,7 +246,7 @@ TEST_F(SchemaTest, metaCommunication) { // Test unreserved keyword { cpp2::ExecutionResponse resp; - std::string query = "CREATE TAG upper(name string, EMAIL string, " + std::string query = "CREATE TAG upper(name string, email string, " "age int, gender string, row_timestamp timestamp)"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code);
1
/* Copyright (c) 2018 vesoft inc. All rights reserved. * * This source code is licensed under Apache 2.0 License, * attached with Common Clause Condition 1.0, found in the LICENSES directory. */ #include "base/Base.h" #include "graph/test/TestEnv.h" #include "graph/test/TestBase.h" #include "meta/test/TestUtils.h" DECLARE_int32(load_data_interval_secs); namespace nebula { namespace graph { class SchemaTest : public TestBase { protected: void SetUp() override { TestBase::SetUp(); // ... } void TearDown() override { // ... TestBase::TearDown(); } }; TEST_F(SchemaTest, TestComment) { auto client = gEnv->getClient(); ASSERT_NE(nullptr, client); // Test command is comment { cpp2::ExecutionResponse resp; std::string cmd = "# CREATE TAG TAG1"; auto code = client->execute(cmd, resp); ASSERT_EQ(cpp2::ErrorCode::E_STATEMENT_EMTPY, code); } { cpp2::ExecutionResponse resp; std::string cmd = "SHOW SPACES # show all spaces"; auto code = client->execute(cmd, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); } } TEST_F(SchemaTest, metaCommunication) { auto client = gEnv->getClient(); ASSERT_NE(nullptr, client); { cpp2::ExecutionResponse resp; std::string query = "SHOW HOSTS"; client->execute(query, resp); std::vector<std::tuple<std::string, std::string, std::string, int, std::string, std::string>> expected { {"127.0.0.1", std::to_string(gEnv->storageServerPort()), "online", 0, "No valid partition", "No valid partition"}, }; ASSERT_TRUE(verifyResult(resp, expected)); } // Test space not exist { cpp2::ExecutionResponse resp; std::string query = "USE not_exist_space"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::E_EXECUTION_ERROR, code); } // Test create space succeeded { cpp2::ExecutionResponse resp; std::string query = "CREATE SPACE default_space(partition_num=9, replica_factor=1)"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); } { cpp2::ExecutionResponse resp; std::string query = "DESCRIBE SPACE default_space"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); std::vector<std::tuple<int, std::string, int, int>> expected{ {1, "default_space", 9, 1}, }; ASSERT_TRUE(verifyResult(resp, expected)); } // Test desc space command { cpp2::ExecutionResponse resp; std::string query = "DESC SPACE default_space"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); std::vector<std::tuple<int, std::string, int, int>> expected{ {1, "default_space", 9, 1}, }; ASSERT_TRUE(verifyResult(resp, expected)); } { cpp2::ExecutionResponse resp; std::string query = "SHOW CREATE SPACE default_space"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); std::string createSpaceStr = "CREATE SPACE default_space (" "partition_num = 9, " "replica_factor = 1)"; std::vector<uniform_tuple_t<std::string, 2>> expected{ {"default_space", createSpaceStr}, }; ASSERT_TRUE(verifyResult(resp, expected)); } { cpp2::ExecutionResponse resp; std::string query = "CREATE SPACE space_with_default_options"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); } { cpp2::ExecutionResponse resp; std::string query = "DESCRIBE SPACE space_with_default_options"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); std::vector<std::tuple<int, std::string, int, int>> expected{ {2, "space_with_default_options", 1024, 1}, }; ASSERT_TRUE(verifyResult(resp, expected)); } { cpp2::ExecutionResponse resp; std::string query = "DROP SPACE space_with_default_options"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); } { cpp2::ExecutionResponse resp; std::string query = "USE default_space"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); } // Test same prop name { cpp2::ExecutionResponse resp; std::string query = "CREATE TAG samePropTag(name string, name int)"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::E_EXECUTION_ERROR, code); } // Test same prop name { cpp2::ExecutionResponse resp; std::string query = "CREATE EDGE samePropEdge(name string, name int)"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::E_EXECUTION_ERROR, code); } // Test create tag without prop { cpp2::ExecutionResponse resp; std::string query = "CREATE TAG tag1()"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); } { cpp2::ExecutionResponse resp; std::string query = "DESCRIBE TAG tag1"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); std::vector<uniform_tuple_t<std::string, 1>> expected{}; ASSERT_TRUE(verifyResult(resp, expected)); } { cpp2::ExecutionResponse resp; std::string query = "ALTER TAG tag1 ADD (id int, name string)"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); } { cpp2::ExecutionResponse resp; std::string query = "DESCRIBE TAG tag1"; client->execute(query, resp); std::vector<uniform_tuple_t<std::string, 2>> expected{ {"id", "int"}, {"name", "string"}, }; ASSERT_TRUE(verifyResult(resp, expected)); } // Test create tag succeeded { cpp2::ExecutionResponse resp; std::string query = "CREATE TAG person(name string, email string, " "age int, gender string, row_timestamp timestamp)"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); } { cpp2::ExecutionResponse resp; std::string query = "DESCRIBE TAG person"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); std::vector<uniform_tuple_t<std::string, 2>> expected{ {"name", "string"}, {"email", "string"}, {"age", "int"}, {"gender", "string"}, {"row_timestamp", "timestamp"}, }; ASSERT_TRUE(verifyResult(resp, expected)); } // Test desc tag command { cpp2::ExecutionResponse resp; std::string query = "DESC TAG person"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); std::vector<uniform_tuple_t<std::string, 2>> expected{ {"name", "string"}, {"email", "string"}, {"age", "int"}, {"gender", "string"}, {"row_timestamp", "timestamp"}, }; ASSERT_TRUE(verifyResult(resp, expected)); } { cpp2::ExecutionResponse resp; std::string query = "SHOW CREATE TAG person"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); std::string createTagStr = "CREATE TAG person (\n" " name string,\n" " email string,\n" " age int,\n" " gender string,\n" " row_timestamp timestamp\n" ") ttl_duration = 0, ttl_col = \"\""; std::vector<uniform_tuple_t<std::string, 2>> expected{ {"person", createTagStr}, }; ASSERT_TRUE(verifyResult(resp, expected)); } { // Test tag not exist cpp2::ExecutionResponse resp; std::string query = "DESCRIBE TAG not_exist"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::E_EXECUTION_ERROR, code); } // Test unreserved keyword { cpp2::ExecutionResponse resp; std::string query = "CREATE TAG upper(name string, EMAIL string, " "age int, gender string, row_timestamp timestamp)"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); } { cpp2::ExecutionResponse resp; std::string query = "DESCRIBE TAG upper"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); std::vector<uniform_tuple_t<std::string, 2>> expected{ {"name", "string"}, {"email", "string"}, {"age", "int"}, {"gender", "string"}, {"row_timestamp", "timestamp"}, }; ASSERT_TRUE(verifyResult(resp, expected)); } // Test existent tag { cpp2::ExecutionResponse resp; std::string query = "CREATE TAG person(id int)"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::E_EXECUTION_ERROR, code); } // Test nonexistent tag { cpp2::ExecutionResponse resp; std::string query = "DESCRIBE TAG not_exist"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::E_EXECUTION_ERROR, code); } // Test alter tag { cpp2::ExecutionResponse resp; std::string query = "ALTER TAG person " "ADD (col1 int, col2 string), " "CHANGE (age string), " "DROP (gender)"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); } { cpp2::ExecutionResponse resp; std::string query = "ALTER TAG person DROP (gender)"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::E_EXECUTION_ERROR, code); } { cpp2::ExecutionResponse resp; std::string query = "DESCRIBE TAG person"; client->execute(query, resp); std::vector<uniform_tuple_t<std::string, 2>> expected{ {"name", "string"}, {"email", "string"}, {"age", "string"}, {"row_timestamp", "timestamp"}, {"col1", "int"}, {"col2", "string"}, }; ASSERT_TRUE(verifyResult(resp, expected)); } { cpp2::ExecutionResponse resp; std::string query = "SHOW CREATE TAG person"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); std::string createTagStr = "CREATE TAG person (\n" " name string,\n" " email string,\n" " age string,\n" " row_timestamp timestamp,\n" " col1 int,\n" " col2 string\n" ") ttl_duration = 0, ttl_col = \"\""; std::vector<uniform_tuple_t<std::string, 2>> expected{ {"person", createTagStr}, }; ASSERT_TRUE(verifyResult(resp, expected)); } { cpp2::ExecutionResponse resp; std::string query = "SHOW TAGS"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); std::vector<uniform_tuple_t<std::string, 1>> expected{ {"tag1"}, {"person"}, {"upper"}, }; ASSERT_TRUE(verifyResult(resp, expected)); } // Test create edge without prop { cpp2::ExecutionResponse resp; std::string query = "CREATE EDGE edge1()"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); } { cpp2::ExecutionResponse resp; std::string query = "DESCRIBE EDGE edge1"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); } { cpp2::ExecutionResponse resp; std::string query = "ALTER EDGE edge1 ADD (id int, name string)"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); } { cpp2::ExecutionResponse resp; std::string query = "DESCRIBE EDGE edge1"; client->execute(query, resp); std::vector<uniform_tuple_t<std::string, 2>> expected{ {"id", "int"}, {"name", "string"}, }; ASSERT_TRUE(verifyResult(resp, expected)); } // Test create edge succeeded { cpp2::ExecutionResponse resp; std::string query = "CREATE EDGE buy(id int, time string)"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); } // Test existent edge { cpp2::ExecutionResponse resp; std::string query = "CREATE EDGE buy(id int, time string)"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::E_EXECUTION_ERROR, code); } { cpp2::ExecutionResponse resp; std::string query = "DESCRIBE EDGE buy"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); std::vector<uniform_tuple_t<std::string, 2>> expected{ {"id", "int"}, {"time", "string"}, }; EXPECT_TRUE(verifyResult(resp, expected)); } // Test nonexistent edge { cpp2::ExecutionResponse resp; std::string query = "DESCRIBE EDGE not_exist"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::E_EXECUTION_ERROR, code); } // Test desc edge { cpp2::ExecutionResponse resp; std::string query = "DESC EDGE buy"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); std::vector<uniform_tuple_t<std::string, 2>> expected{ {"id", "int"}, {"time", "string"}, }; EXPECT_TRUE(verifyResult(resp, expected)); } { cpp2::ExecutionResponse resp; std::string query = "SHOW CREATE EDGE buy"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); std::string createEdgeStr = "CREATE EDGE buy (\n" " id int,\n" " time string\n" ") ttl_duration = 0, ttl_col = \"\""; std::vector<uniform_tuple_t<std::string, 2>> expected{ {"buy", createEdgeStr}, }; EXPECT_TRUE(verifyResult(resp, expected)); } { // Test edge not exist cpp2::ExecutionResponse resp; std::string query = "DESCRIBE EDGE not_exist"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::E_EXECUTION_ERROR, code); } // Test create edge succeeded { cpp2::ExecutionResponse resp; std::string query = "CREATE EDGE education(id int, time timestamp, school string)"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); } { cpp2::ExecutionResponse resp; std::string query = "DESCRIBE EDGE education"; client->execute(query, resp); std::vector<uniform_tuple_t<std::string, 2>> expected{ {"id", "int"}, {"time", "timestamp"}, {"school", "string"}, }; EXPECT_TRUE(verifyResult(resp, expected)); } // Test show edges { cpp2::ExecutionResponse resp; std::string query = "SHOW EDGES"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); std::vector<uniform_tuple_t<std::string, 1>> expected{ {"edge1"}, {"buy"}, {"education"}, }; ASSERT_TRUE(verifyResult(resp, expected)); } // Test alter edge { cpp2::ExecutionResponse resp; std::string query = "ALTER EDGE education " "ADD (col1 int, col2 string), " "CHANGE (school int), " "DROP (id, time)"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); } { cpp2::ExecutionResponse resp; std::string query = "ALTER EDGE education DROP (id, time)"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::E_EXECUTION_ERROR, code); } { cpp2::ExecutionResponse resp; std::string query = "DESCRIBE EDGE education"; client->execute(query, resp); std::vector<uniform_tuple_t<std::string, 2>> expected{ {"school", "int"}, {"col1", "int"}, {"col2", "string"}, }; ASSERT_TRUE(verifyResult(resp, expected)); } // Test multi sentences { cpp2::ExecutionResponse resp; std::string query; for (auto i = 0u; i < 1000; i++) { query += "CREATE TAG tag10" + std::to_string(i) + "(name string);"; } auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); } { cpp2::ExecutionResponse resp; std::string query; for (auto i = 0u; i < 1000; i++) { query = "DESCRIBE TAG tag10" + std::to_string(i); client->execute(query, resp); std::vector<uniform_tuple_t<std::string, 2>> expected{ {"name", "string"}, }; ASSERT_TRUE(verifyResult(resp, expected)); } } // Test drop tag { cpp2::ExecutionResponse resp; std::string query = "DROP TAG person"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); } // Test drop edge { cpp2::ExecutionResponse resp; std::string query = "DROP EDGE buy"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); } // Test different tag and edge in different space { cpp2::ExecutionResponse resp; std::string query = "SHOW CREATE EDGE education"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); std::string createEdgeStr = "CREATE EDGE education (\n" " school int,\n" " col1 int,\n" " col2 string\n" ") ttl_duration = 0, ttl_col = \"\""; std::vector<uniform_tuple_t<std::string, 2>> expected{ {"education", createEdgeStr}, }; EXPECT_TRUE(verifyResult(resp, expected)); } // Test different tag and edge in different space { cpp2::ExecutionResponse resp; std::string query = "CREATE SPACE my_space(partition_num=9, replica_factor=1)"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); } { cpp2::ExecutionResponse resp; std::string query = "USE my_space"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); } { cpp2::ExecutionResponse resp; std::string query = "CREATE TAG animal(name string, kind string)"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); } { cpp2::ExecutionResponse resp; std::string query = "DESCRIBE TAG animal"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); std::vector<uniform_tuple_t<std::string, 2>> expected{ {"name", "string"}, {"kind", "string"}, }; ASSERT_TRUE(verifyResult(resp, expected)); } // Test the same tag in diff space { cpp2::ExecutionResponse resp; std::string query = "CREATE TAG person(name string, interest string)"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); } { cpp2::ExecutionResponse resp; std::string query = "SHOW TAGS"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); std::vector<uniform_tuple_t<std::string, 1>> expected{ {"animal"}, {"person"}, }; ASSERT_TRUE(verifyResult(resp, expected)); } // Test multi sentence { cpp2::ExecutionResponse resp; std::string query = "CREATE SPACE test_multi"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); query = "USE test_multi; CREATE Tag test_tag(); SHOW TAGS;"; code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); std::vector<uniform_tuple_t<std::string, 1>> expected1{ {"test_tag"}, }; ASSERT_TRUE(verifyResult(resp, expected1)); query = "USE test_multi; CREATE TAG test_tag1(); USE my_space; SHOW TAGS;"; code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); std::vector<uniform_tuple_t<std::string, 1>> expected2{ {"animal"}, {"person"}, }; ASSERT_TRUE(verifyResult(resp, expected2)); query = "DROP SPACE test_multi"; code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); } // Test drop space { cpp2::ExecutionResponse resp; std::string query = "DROP SPACE my_space"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); } { cpp2::ExecutionResponse resp; std::string query = "SHOW SPACES"; client->execute(query, resp); std::vector<uniform_tuple_t<std::string, 1>> expected{ {"default_space"}, }; ASSERT_TRUE(verifyResult(resp, expected)); } { cpp2::ExecutionResponse resp; std::string query = "DROP SPACE default_space"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); } { cpp2::ExecutionResponse resp; std::string query = "SHOW SPACES"; client->execute(query, resp); ASSERT_EQ(0, (*(resp.get_rows())).size()); } { cpp2::ExecutionResponse resp; std::string query = "SHOW HOSTS"; client->execute(query, resp); ASSERT_EQ(1, (*(resp.get_rows())).size()); } sleep(FLAGS_load_data_interval_secs + 1); } TEST_F(SchemaTest, TTLtest) { auto client = gEnv->getClient(); ASSERT_NE(nullptr, client); { cpp2::ExecutionResponse resp; std::string query = "SHOW HOSTS"; client->execute(query, resp); std::vector<std::tuple<std::string, std::string, std::string, int, std::string, std::string>> expected { {"127.0.0.1", std::to_string(gEnv->storageServerPort()), "online", 0, "No valid partition", "No valid partition"}, }; ASSERT_TRUE(verifyResult(resp, expected)); } { cpp2::ExecutionResponse resp; std::string query = "CREATE SPACE default_space(partition_num=9, replica_factor=1)"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); } { cpp2::ExecutionResponse resp; std::string query = "USE default_space"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); } // Tag with TTL test { cpp2::ExecutionResponse resp; std::string query = "CREATE TAG person(name string, email string, " "age int, gender string, row_timestamp timestamp)"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); } { cpp2::ExecutionResponse resp; std::string query = "DESCRIBE TAG person"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); std::vector<uniform_tuple_t<std::string, 2>> expected{ {"name", "string"}, {"email", "string"}, {"age", "int"}, {"gender", "string"}, {"row_timestamp", "timestamp"}, }; ASSERT_TRUE(verifyResult(resp, expected)); } { cpp2::ExecutionResponse resp; std::string query = "SHOW CREATE TAG person"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); std::string createTagStr = "CREATE TAG person (\n" " name string,\n" " email string,\n" " age int,\n" " gender string,\n" " row_timestamp timestamp\n" ") ttl_duration = 0, ttl_col = \"\""; std::vector<uniform_tuple_t<std::string, 2>> expected{ {"person", createTagStr}, }; ASSERT_TRUE(verifyResult(resp, expected)); } { cpp2::ExecutionResponse resp; std::string query = "CREATE TAG man(name string, email string, " "age int, gender string, row_timestamp timestamp)" "ttl_duration = 100, ttl_col = row_timestamp"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); } { cpp2::ExecutionResponse resp; std::string query = "SHOW CREATE TAG man"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); std::string createTagStr = "CREATE TAG man (\n" " name string,\n" " email string,\n" " age int,\n" " gender string,\n" " row_timestamp timestamp\n" ") ttl_duration = 100, ttl_col = row_timestamp"; std::vector<uniform_tuple_t<std::string, 2>> expected{ {"man", createTagStr}, }; ASSERT_TRUE(verifyResult(resp, expected)); } // Abnormal test { // Disable implicit ttl mode cpp2::ExecutionResponse resp; std::string query = "CREATE TAG woman(name string, email string, " "age int, gender string, row_timestamp timestamp)" "ttl_duration = 100"; auto code = client->execute(query, resp); ASSERT_NE(cpp2::ErrorCode::SUCCEEDED, code); } { // Disable when ttl_col is not an integer column or a timestamp column cpp2::ExecutionResponse resp; std::string query = "CREATE TAG woman(name string, email string, " "age int, gender string, row_timestamp timestamp)" "ttl_col = name"; auto code = client->execute(query, resp); ASSERT_NE(cpp2::ErrorCode::SUCCEEDED, code); } { cpp2::ExecutionResponse resp; std::string query = "CREATE TAG woman(name string, email string, " "age int, gender string, row_timestamp timestamp)" "ttl_duration = -100, ttl_col = row_timestamp"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); } { cpp2::ExecutionResponse resp; std::string query = "SHOW CREATE TAG woman"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); std::string createTagStr = "CREATE TAG woman (\n" " name string,\n" " email string,\n" " age int,\n" " gender string,\n" " row_timestamp timestamp\n" ") ttl_duration = 0, ttl_col = row_timestamp"; std::vector<uniform_tuple_t<std::string, 2>> expected{ {"woman", createTagStr}, }; ASSERT_TRUE(verifyResult(resp, expected)); } { cpp2::ExecutionResponse resp; std::string query = "CREATE TAG only_ttl_col(name string, email string, " "age int, gender string, row_timestamp timestamp)" "ttl_col = row_timestamp"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); } { cpp2::ExecutionResponse resp; std::string query = "SHOW CREATE TAG only_ttl_col"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); std::string createTagStr = "CREATE TAG only_ttl_col (\n" " name string,\n" " email string,\n" " age int,\n" " gender string,\n" " row_timestamp timestamp\n" ") ttl_duration = 0, ttl_col = row_timestamp"; std::vector<uniform_tuple_t<std::string, 2>> expected{ {"only_ttl_col", createTagStr}, }; ASSERT_TRUE(verifyResult(resp, expected)); } { cpp2::ExecutionResponse resp; std::string query = "ALTER TAG woman " "ttl_duration = 50, ttl_col = row_timestamp"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); } { cpp2::ExecutionResponse resp; std::string query = "SHOW CREATE TAG woman"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); std::string createTagStr = "CREATE TAG woman (\n" " name string,\n" " email string,\n" " age int,\n" " gender string,\n" " row_timestamp timestamp\n" ") ttl_duration = 50, ttl_col = row_timestamp"; std::vector<uniform_tuple_t<std::string, 2>> expected{ {"woman", createTagStr}, }; ASSERT_TRUE(verifyResult(resp, expected)); } { // Failed when alter tag to set ttl_col on not integer and timestamp column cpp2::ExecutionResponse resp; std::string query = "ALTER TAG woman " "ttl_col = name"; auto code = client->execute(query, resp); ASSERT_NE(cpp2::ErrorCode::SUCCEEDED, code); } { cpp2::ExecutionResponse resp; std::string query = "ALTER TAG woman " "Drop (name) ttl_duration = 200"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); } { cpp2::ExecutionResponse resp; std::string query = "SHOW CREATE TAG woman"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); std::string createTagStr = "CREATE TAG woman (\n" " email string,\n" " age int,\n" " gender string,\n" " row_timestamp timestamp\n" ") ttl_duration = 200, ttl_col = row_timestamp"; std::vector<uniform_tuple_t<std::string, 2>> expected{ {"woman", createTagStr}, }; ASSERT_TRUE(verifyResult(resp, expected)); } { // When the column is as TTL column, droping column failed cpp2::ExecutionResponse resp; std::string query = "ALTER TAG woman " "Drop (row_timestamp)"; auto code = client->execute(query, resp); ASSERT_NE(cpp2::ErrorCode::SUCCEEDED, code); } { // First remove TTL property, then drop column cpp2::ExecutionResponse resp; std::string query = "ALTER TAG woman " "ttl_col = age"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); } { cpp2::ExecutionResponse resp; std::string query = "SHOW CREATE TAG woman"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); std::string createTagStr = "CREATE TAG woman (\n" " email string,\n" " age int,\n" " gender string,\n" " row_timestamp timestamp\n" ") ttl_duration = 200, ttl_col = age"; std::vector<uniform_tuple_t<std::string, 2>> expected{ {"woman", createTagStr}, }; ASSERT_TRUE(verifyResult(resp, expected)); } { cpp2::ExecutionResponse resp; std::string query = "ALTER TAG woman " "Drop (row_timestamp)"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); } { cpp2::ExecutionResponse resp; std::string query = "SHOW CREATE TAG woman"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); std::string createTagStr = "CREATE TAG woman (\n" " email string,\n" " age int,\n" " gender string\n" ") ttl_duration = 200, ttl_col = age"; std::vector<uniform_tuple_t<std::string, 2>> expected{ {"woman", createTagStr}, }; ASSERT_TRUE(verifyResult(resp, expected)); } // Edge with TTL test { cpp2::ExecutionResponse resp; std::string query = "CREATE EDGE work(number string, start_time timestamp)"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); } { cpp2::ExecutionResponse resp; std::string query = "DESCRIBE EDGE work"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); std::vector<uniform_tuple_t<std::string, 2>> expected{ {"number", "string"}, {"start_time", "timestamp"}, }; ASSERT_TRUE(verifyResult(resp, expected)); } { cpp2::ExecutionResponse resp; std::string query = "SHOW CREATE EDGE work"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); std::string createEdgeStr = "CREATE EDGE work (\n" " number string,\n" " start_time timestamp\n" ") ttl_duration = 0, ttl_col = \"\""; std::vector<uniform_tuple_t<std::string, 2>> expected{ {"work", createEdgeStr}, }; ASSERT_TRUE(verifyResult(resp, expected)); } { cpp2::ExecutionResponse resp; std::string query = "CREATE EDGE work1(name string, email string, " "age int, gender string, row_timestamp timestamp)" "ttl_duration = 100, ttl_col = row_timestamp"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); } { cpp2::ExecutionResponse resp; std::string query = "SHOW CREATE EDGE work1"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); std::string createEdgeStr = "CREATE EDGE work1 (\n" " name string,\n" " email string,\n" " age int,\n" " gender string,\n" " row_timestamp timestamp\n" ") ttl_duration = 100, ttl_col = row_timestamp"; std::vector<uniform_tuple_t<std::string, 2>> expected{ {"work1", createEdgeStr}, }; ASSERT_TRUE(verifyResult(resp, expected)); } // Abnormal test { // Disable implicit ttl mode cpp2::ExecutionResponse resp; std::string query = "CREATE EDGE work2(number string, start_time timestamp)" "ttl_duration = 100"; auto code = client->execute(query, resp); ASSERT_NE(cpp2::ErrorCode::SUCCEEDED, code); } { // Disable when ttl_col is not an integer column or a timestamp column cpp2::ExecutionResponse resp; std::string query = "CREATE EDGE work2(number string, start_time timestamp)" "ttl_col = name"; auto code = client->execute(query, resp); ASSERT_NE(cpp2::ErrorCode::SUCCEEDED, code); } { cpp2::ExecutionResponse resp; std::string query = "CREATE EDGE work2(name string, email string, " "age int, gender string, start_time timestamp)" "ttl_duration = -100, ttl_col = start_time"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); } { cpp2::ExecutionResponse resp; std::string query = "SHOW CREATE EDGE work2"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); std::string createEdgeStr = "CREATE EDGE work2 (\n" " name string,\n" " email string,\n" " age int,\n" " gender string,\n" " start_time timestamp\n" ") ttl_duration = 0, ttl_col = start_time"; std::vector<uniform_tuple_t<std::string, 2>> expected{ {"work2", createEdgeStr}, }; ASSERT_TRUE(verifyResult(resp, expected)); } { cpp2::ExecutionResponse resp; std::string query = "CREATE EDGE edge_only_ttl_col(name string, email string, " "age int, gender string, row_timestamp timestamp)" "ttl_col = row_timestamp"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); } { cpp2::ExecutionResponse resp; std::string query = "SHOW CREATE EDGE edge_only_ttl_col"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); std::string createEdgeStr = "CREATE EDGE edge_only_ttl_col (\n" " name string,\n" " email string,\n" " age int,\n" " gender string,\n" " row_timestamp timestamp\n" ") ttl_duration = 0, ttl_col = row_timestamp"; std::vector<uniform_tuple_t<std::string, 2>> expected{ {"edge_only_ttl_col", createEdgeStr}, }; ASSERT_TRUE(verifyResult(resp, expected)); } { cpp2::ExecutionResponse resp; std::string query = "ALTER EDGE work2 " "ttl_duration = 50, ttl_col = start_time"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); } { cpp2::ExecutionResponse resp; std::string query = "SHOW CREATE EDGE work2"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); std::string createEdgeStr = "CREATE EDGE work2 (\n" " name string,\n" " email string,\n" " age int,\n" " gender string,\n" " start_time timestamp\n" ") ttl_duration = 50, ttl_col = start_time"; std::vector<uniform_tuple_t<std::string, 2>> expected{ {"work2", createEdgeStr}, }; ASSERT_TRUE(verifyResult(resp, expected)); } { // Failed when alter edge to set ttl_col on not integer and timestamp column cpp2::ExecutionResponse resp; std::string query = "ALTER EDGE work2 " "ttl_col = name"; auto code = client->execute(query, resp); ASSERT_NE(cpp2::ErrorCode::SUCCEEDED, code); } { cpp2::ExecutionResponse resp; std::string query = "ALTER EDGE work2 " "Drop (name) ttl_duration = 200"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); } { cpp2::ExecutionResponse resp; std::string query = "SHOW CREATE EDGE work2"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); std::string createEdgeStr = "CREATE EDGE work2 (\n" " email string,\n" " age int,\n" " gender string,\n" " start_time timestamp\n" ") ttl_duration = 200, ttl_col = start_time"; std::vector<uniform_tuple_t<std::string, 2>> expected{ {"work2", createEdgeStr}, }; ASSERT_TRUE(verifyResult(resp, expected)); } { // When the column is as TTL column, droping column failed cpp2::ExecutionResponse resp; std::string query = "ALTER EDGE work2 " "Drop (start_time)"; auto code = client->execute(query, resp); ASSERT_NE(cpp2::ErrorCode::SUCCEEDED, code); } { // First remove TTL property, then drop column cpp2::ExecutionResponse resp; std::string query = "ALTER EDGE work2 " "ttl_col = age"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); } { cpp2::ExecutionResponse resp; std::string query = "SHOW CREATE EDGE work2"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); std::string createEdgeStr = "CREATE EDGE work2 (\n" " email string,\n" " age int,\n" " gender string,\n" " start_time timestamp\n" ") ttl_duration = 200, ttl_col = age"; std::vector<uniform_tuple_t<std::string, 2>> expected{ {"work2", createEdgeStr}, }; ASSERT_TRUE(verifyResult(resp, expected)); } { cpp2::ExecutionResponse resp; std::string query = "ALTER EDGE work2 " "Drop (start_time)"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); } { cpp2::ExecutionResponse resp; std::string query = "DESCRIBE EDGE work2"; client->execute(query, resp); std::vector<uniform_tuple_t<std::string, 2>> expected{ {"email", "string"}, {"age", "int"}, {"gender", "string"}, }; ASSERT_TRUE(verifyResult(resp, expected)); } { cpp2::ExecutionResponse resp; std::string query = "SHOW CREATE EDGE work2"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); std::string createEdgeStr = "CREATE EDGE work2 (\n" " email string,\n" " age int,\n" " gender string\n" ") ttl_duration = 200, ttl_col = age"; std::vector<uniform_tuple_t<std::string, 2>> expected{ {"work2", createEdgeStr}, }; ASSERT_TRUE(verifyResult(resp, expected)); } { cpp2::ExecutionResponse resp; std::string query = "DROP SPACE default_space"; auto code = client->execute(query, resp); ASSERT_EQ(cpp2::ErrorCode::SUCCEEDED, code); } } } // namespace graph } // namespace nebula
1
18,292
This is testing `unreserved keyword`
vesoft-inc-nebula
cpp
@@ -829,6 +829,10 @@ static const MethodMapping projectionMethodMappings[] = { {PROJ_WKT2_NAME_METHOD_QUADRILATERALIZED_SPHERICAL_CUBE, 0, "Quadrilateralized_Spherical_Cube", "qsc", nullptr, paramsNatOrigin}, + + {PROJ_WKT2_NAME_METHOD_S2, 0, + "S2", "s2", nullptr, paramsNatOrigin}, + {PROJ_WKT2_NAME_METHOD_SPHERICAL_CROSS_TRACK_HEIGHT, 0, "Spherical_Cross_Track_Height", "sch", nullptr, paramsSch},
1
/****************************************************************************** * * Project: PROJ * Purpose: ISO19111:2019 implementation * Author: Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2018, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "parammappings.hpp" #include "oputils.hpp" #include "proj_constants.h" #include "proj/internal/internal.hpp" NS_PROJ_START using namespace internal; namespace operation { //! @cond Doxygen_Suppress const char *WKT1_LATITUDE_OF_ORIGIN = "latitude_of_origin"; const char *WKT1_CENTRAL_MERIDIAN = "central_meridian"; const char *WKT1_SCALE_FACTOR = "scale_factor"; const char *WKT1_FALSE_EASTING = "false_easting"; const char *WKT1_FALSE_NORTHING = "false_northing"; const char *WKT1_STANDARD_PARALLEL_1 = "standard_parallel_1"; const char *WKT1_STANDARD_PARALLEL_2 = "standard_parallel_2"; const char *WKT1_LATITUDE_OF_CENTER = "latitude_of_center"; const char *WKT1_LONGITUDE_OF_CENTER = "longitude_of_center"; const char *WKT1_AZIMUTH = "azimuth"; const char *WKT1_RECTIFIED_GRID_ANGLE = "rectified_grid_angle"; static const char *lat_0 = "lat_0"; static const char *lat_1 = "lat_1"; static const char *lat_2 = "lat_2"; static const char *lat_ts = "lat_ts"; static const char *lon_0 = "lon_0"; static const char *lon_1 = "lon_1"; static const char *lon_2 = "lon_2"; static const char *lonc = "lonc"; static const char *alpha = "alpha"; static const char *gamma = "gamma"; static const char *k_0 = "k_0"; static const char *k = "k"; static const char *x_0 = "x_0"; static const char *y_0 = "y_0"; static const char *h = "h"; // --------------------------------------------------------------------------- const ParamMapping paramLatitudeNatOrigin = { EPSG_NAME_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, WKT1_LATITUDE_OF_ORIGIN, common::UnitOfMeasure::Type::ANGULAR, lat_0}; static const ParamMapping paramLongitudeNatOrigin = { EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, WKT1_CENTRAL_MERIDIAN, common::UnitOfMeasure::Type::ANGULAR, lon_0}; static const ParamMapping paramScaleFactor = { EPSG_NAME_PARAMETER_SCALE_FACTOR_AT_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_SCALE_FACTOR_AT_NATURAL_ORIGIN, WKT1_SCALE_FACTOR, common::UnitOfMeasure::Type::SCALE, k_0}; static const ParamMapping paramScaleFactorK = { EPSG_NAME_PARAMETER_SCALE_FACTOR_AT_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_SCALE_FACTOR_AT_NATURAL_ORIGIN, WKT1_SCALE_FACTOR, common::UnitOfMeasure::Type::SCALE, k}; static const ParamMapping paramFalseEasting = { EPSG_NAME_PARAMETER_FALSE_EASTING, EPSG_CODE_PARAMETER_FALSE_EASTING, WKT1_FALSE_EASTING, common::UnitOfMeasure::Type::LINEAR, x_0}; static const ParamMapping paramFalseNorthing = { EPSG_NAME_PARAMETER_FALSE_NORTHING, EPSG_CODE_PARAMETER_FALSE_NORTHING, WKT1_FALSE_NORTHING, common::UnitOfMeasure::Type::LINEAR, y_0}; static const ParamMapping paramLatitudeFalseOrigin = { EPSG_NAME_PARAMETER_LATITUDE_FALSE_ORIGIN, EPSG_CODE_PARAMETER_LATITUDE_FALSE_ORIGIN, WKT1_LATITUDE_OF_ORIGIN, common::UnitOfMeasure::Type::ANGULAR, lat_0}; static const ParamMapping paramLongitudeFalseOrigin = { EPSG_NAME_PARAMETER_LONGITUDE_FALSE_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_FALSE_ORIGIN, WKT1_CENTRAL_MERIDIAN, common::UnitOfMeasure::Type::ANGULAR, lon_0}; static const ParamMapping paramFalseEastingOrigin = { EPSG_NAME_PARAMETER_EASTING_FALSE_ORIGIN, EPSG_CODE_PARAMETER_EASTING_FALSE_ORIGIN, WKT1_FALSE_EASTING, common::UnitOfMeasure::Type::LINEAR, x_0}; static const ParamMapping paramFalseNorthingOrigin = { EPSG_NAME_PARAMETER_NORTHING_FALSE_ORIGIN, EPSG_CODE_PARAMETER_NORTHING_FALSE_ORIGIN, WKT1_FALSE_NORTHING, common::UnitOfMeasure::Type::LINEAR, y_0}; static const ParamMapping paramLatitude1stStdParallel = { EPSG_NAME_PARAMETER_LATITUDE_1ST_STD_PARALLEL, EPSG_CODE_PARAMETER_LATITUDE_1ST_STD_PARALLEL, WKT1_STANDARD_PARALLEL_1, common::UnitOfMeasure::Type::ANGULAR, lat_1}; static const ParamMapping paramLatitude2ndStdParallel = { EPSG_NAME_PARAMETER_LATITUDE_2ND_STD_PARALLEL, EPSG_CODE_PARAMETER_LATITUDE_2ND_STD_PARALLEL, WKT1_STANDARD_PARALLEL_2, common::UnitOfMeasure::Type::ANGULAR, lat_2}; static const ParamMapping *const paramsNatOriginScale[] = { &paramLatitudeNatOrigin, &paramLongitudeNatOrigin, &paramScaleFactor, &paramFalseEasting, &paramFalseNorthing, nullptr}; static const ParamMapping *const paramsNatOriginScaleK[] = { &paramLatitudeNatOrigin, &paramLongitudeNatOrigin, &paramScaleFactorK, &paramFalseEasting, &paramFalseNorthing, nullptr}; static const ParamMapping paramLatFirstPoint = { "Latitude of 1st point", 0, "Latitude_Of_1st_Point", common::UnitOfMeasure::Type::ANGULAR, lat_1}; static const ParamMapping paramLongFirstPoint = { "Longitude of 1st point", 0, "Longitude_Of_1st_Point", common::UnitOfMeasure::Type::ANGULAR, lon_1}; static const ParamMapping paramLatSecondPoint = { "Latitude of 2nd point", 0, "Latitude_Of_2nd_Point", common::UnitOfMeasure::Type::ANGULAR, lat_2}; static const ParamMapping paramLongSecondPoint = { "Longitude of 2nd point", 0, "Longitude_Of_2nd_Point", common::UnitOfMeasure::Type::ANGULAR, lon_2}; static const ParamMapping *const paramsTPEQD[] = {&paramLatFirstPoint, &paramLongFirstPoint, &paramLatSecondPoint, &paramLongSecondPoint, &paramFalseEasting, &paramFalseNorthing, nullptr}; static const ParamMapping *const paramsTMG[] = { &paramLatitudeFalseOrigin, &paramLongitudeFalseOrigin, &paramFalseEastingOrigin, &paramFalseNorthingOrigin, nullptr}; static const ParamMapping paramLatFalseOriginLatOfCenter = { EPSG_NAME_PARAMETER_LATITUDE_FALSE_ORIGIN, EPSG_CODE_PARAMETER_LATITUDE_FALSE_ORIGIN, WKT1_LATITUDE_OF_CENTER, common::UnitOfMeasure::Type::ANGULAR, lat_0}; static const ParamMapping paramLongFalseOriginLongOfCenter = { EPSG_NAME_PARAMETER_LONGITUDE_FALSE_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_FALSE_ORIGIN, WKT1_LONGITUDE_OF_CENTER, common::UnitOfMeasure::Type::ANGULAR, lon_0}; static const ParamMapping *const paramsAEA[] = { &paramLatFalseOriginLatOfCenter, &paramLongFalseOriginLongOfCenter, &paramLatitude1stStdParallel, &paramLatitude2ndStdParallel, &paramFalseEastingOrigin, &paramFalseNorthingOrigin, nullptr}; static const ParamMapping *const paramsLCC2SP[] = { &paramLatitudeFalseOrigin, &paramLongitudeFalseOrigin, &paramLatitude1stStdParallel, &paramLatitude2ndStdParallel, &paramFalseEastingOrigin, &paramFalseNorthingOrigin, nullptr, }; static const ParamMapping paramEllipsoidScaleFactor = { EPSG_NAME_PARAMETER_ELLIPSOID_SCALE_FACTOR, EPSG_CODE_PARAMETER_ELLIPSOID_SCALE_FACTOR, nullptr, common::UnitOfMeasure::Type::SCALE, k_0}; static const ParamMapping *const paramsLCC2SPMichigan[] = { &paramLatitudeFalseOrigin, &paramLongitudeFalseOrigin, &paramLatitude1stStdParallel, &paramLatitude2ndStdParallel, &paramFalseEastingOrigin, &paramFalseNorthingOrigin, &paramEllipsoidScaleFactor, nullptr, }; static const ParamMapping paramLatNatLatCenter = { EPSG_NAME_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, WKT1_LATITUDE_OF_CENTER, common::UnitOfMeasure::Type::ANGULAR, lat_0}; static const ParamMapping paramLonNatLonCenter = { EPSG_NAME_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_NATURAL_ORIGIN, WKT1_LONGITUDE_OF_CENTER, common::UnitOfMeasure::Type::ANGULAR, lon_0}; static const ParamMapping *const paramsAEQD[]{ &paramLatNatLatCenter, &paramLonNatLonCenter, &paramFalseEasting, &paramFalseNorthing, nullptr}; static const ParamMapping *const paramsNatOrigin[] = { &paramLatitudeNatOrigin, &paramLongitudeNatOrigin, &paramFalseEasting, &paramFalseNorthing, nullptr}; static const ParamMapping paramLatNatOriginLat1 = { EPSG_NAME_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, WKT1_STANDARD_PARALLEL_1, common::UnitOfMeasure::Type::ANGULAR, lat_1}; static const ParamMapping *const paramsBonne[] = { &paramLatNatOriginLat1, &paramLongitudeNatOrigin, &paramFalseEasting, &paramFalseNorthing, nullptr}; static const ParamMapping paramLat1stParallelLatTs = { EPSG_NAME_PARAMETER_LATITUDE_1ST_STD_PARALLEL, EPSG_CODE_PARAMETER_LATITUDE_1ST_STD_PARALLEL, WKT1_STANDARD_PARALLEL_1, common::UnitOfMeasure::Type::ANGULAR, lat_ts}; static const ParamMapping *const paramsCEA[] = { &paramLat1stParallelLatTs, &paramLongitudeNatOrigin, &paramFalseEasting, &paramFalseNorthing, nullptr}; static const ParamMapping *const paramsEQDC[] = {&paramLatNatLatCenter, &paramLonNatLonCenter, &paramLatitude1stStdParallel, &paramLatitude2ndStdParallel, &paramFalseEasting, &paramFalseNorthing, nullptr}; static const ParamMapping *const paramsLonNatOrigin[] = { &paramLongitudeNatOrigin, &paramFalseEasting, &paramFalseNorthing, nullptr}; static const ParamMapping *const paramsEqc[] = { &paramLat1stParallelLatTs, &paramLatitudeNatOrigin, // extension of EPSG, but used by GDAL / PROJ &paramLongitudeNatOrigin, &paramFalseEasting, &paramFalseNorthing, nullptr}; static const ParamMapping paramSatelliteHeight = { "Satellite Height", 0, "satellite_height", common::UnitOfMeasure::Type::LINEAR, h}; static const ParamMapping *const paramsGeos[] = { &paramLongitudeNatOrigin, &paramSatelliteHeight, &paramFalseEasting, &paramFalseNorthing, nullptr}; static const ParamMapping paramLatCentreLatCenter = { EPSG_NAME_PARAMETER_LATITUDE_PROJECTION_CENTRE, EPSG_CODE_PARAMETER_LATITUDE_PROJECTION_CENTRE, WKT1_LATITUDE_OF_CENTER, common::UnitOfMeasure::Type::ANGULAR, lat_0}; static const ParamMapping paramLonCentreLonCenterLonc = { EPSG_NAME_PARAMETER_LONGITUDE_PROJECTION_CENTRE, EPSG_CODE_PARAMETER_LONGITUDE_PROJECTION_CENTRE, WKT1_LONGITUDE_OF_CENTER, common::UnitOfMeasure::Type::ANGULAR, lonc}; static const ParamMapping paramAzimuth = { EPSG_NAME_PARAMETER_AZIMUTH_INITIAL_LINE, EPSG_CODE_PARAMETER_AZIMUTH_INITIAL_LINE, WKT1_AZIMUTH, common::UnitOfMeasure::Type::ANGULAR, alpha}; static const ParamMapping paramAngleToSkewGrid = { EPSG_NAME_PARAMETER_ANGLE_RECTIFIED_TO_SKEW_GRID, EPSG_CODE_PARAMETER_ANGLE_RECTIFIED_TO_SKEW_GRID, WKT1_RECTIFIED_GRID_ANGLE, common::UnitOfMeasure::Type::ANGULAR, gamma}; static const ParamMapping paramScaleFactorInitialLine = { EPSG_NAME_PARAMETER_SCALE_FACTOR_INITIAL_LINE, EPSG_CODE_PARAMETER_SCALE_FACTOR_INITIAL_LINE, WKT1_SCALE_FACTOR, common::UnitOfMeasure::Type::SCALE, k}; static const ParamMapping *const paramsHomVariantA[] = { &paramLatCentreLatCenter, &paramLonCentreLonCenterLonc, &paramAzimuth, &paramAngleToSkewGrid, &paramScaleFactorInitialLine, &paramFalseEasting, &paramFalseNorthing, nullptr}; static const ParamMapping paramFalseEastingProjectionCentre = { EPSG_NAME_PARAMETER_EASTING_PROJECTION_CENTRE, EPSG_CODE_PARAMETER_EASTING_PROJECTION_CENTRE, WKT1_FALSE_EASTING, common::UnitOfMeasure::Type::LINEAR, x_0}; static const ParamMapping paramFalseNorthingProjectionCentre = { EPSG_NAME_PARAMETER_NORTHING_PROJECTION_CENTRE, EPSG_CODE_PARAMETER_NORTHING_PROJECTION_CENTRE, WKT1_FALSE_NORTHING, common::UnitOfMeasure::Type::LINEAR, y_0}; static const ParamMapping *const paramsHomVariantB[] = { &paramLatCentreLatCenter, &paramLonCentreLonCenterLonc, &paramAzimuth, &paramAngleToSkewGrid, &paramScaleFactorInitialLine, &paramFalseEastingProjectionCentre, &paramFalseNorthingProjectionCentre, nullptr}; static const ParamMapping paramLatPoint1 = { "Latitude of 1st point", 0, "latitude_of_point_1", common::UnitOfMeasure::Type::ANGULAR, lat_1}; static const ParamMapping paramLonPoint1 = { "Longitude of 1st point", 0, "longitude_of_point_1", common::UnitOfMeasure::Type::ANGULAR, lon_1}; static const ParamMapping paramLatPoint2 = { "Latitude of 2nd point", 0, "latitude_of_point_2", common::UnitOfMeasure::Type::ANGULAR, lat_2}; static const ParamMapping paramLonPoint2 = { "Longitude of 2nd point", 0, "longitude_of_point_2", common::UnitOfMeasure::Type::ANGULAR, lon_2}; static const ParamMapping *const paramsHomTwoPoint[] = { &paramLatCentreLatCenter, &paramLatPoint1, &paramLonPoint1, &paramLatPoint2, &paramLonPoint2, &paramScaleFactorInitialLine, &paramFalseEastingProjectionCentre, &paramFalseNorthingProjectionCentre, nullptr}; static const ParamMapping *const paramsIMWP[] = { &paramLongitudeNatOrigin, &paramLatFirstPoint, &paramLatSecondPoint, &paramFalseEasting, &paramFalseNorthing, nullptr}; static const ParamMapping paramLonCentreLonCenter = { EPSG_NAME_PARAMETER_LONGITUDE_OF_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_ORIGIN, WKT1_LONGITUDE_OF_CENTER, common::UnitOfMeasure::Type::ANGULAR, lon_0}; static const ParamMapping paramColatitudeConeAxis = { EPSG_NAME_PARAMETER_COLATITUDE_CONE_AXIS, EPSG_CODE_PARAMETER_COLATITUDE_CONE_AXIS, WKT1_AZIMUTH, common::UnitOfMeasure::Type::ANGULAR, "alpha"}; /* ignored by PROJ currently */ static const ParamMapping paramLatitudePseudoStdParallel = { EPSG_NAME_PARAMETER_LATITUDE_PSEUDO_STANDARD_PARALLEL, EPSG_CODE_PARAMETER_LATITUDE_PSEUDO_STANDARD_PARALLEL, "pseudo_standard_parallel_1", common::UnitOfMeasure::Type::ANGULAR, nullptr}; /* ignored by PROJ currently */ static const ParamMapping paramScaleFactorPseudoStdParallel = { EPSG_NAME_PARAMETER_SCALE_FACTOR_PSEUDO_STANDARD_PARALLEL, EPSG_CODE_PARAMETER_SCALE_FACTOR_PSEUDO_STANDARD_PARALLEL, WKT1_SCALE_FACTOR, common::UnitOfMeasure::Type::SCALE, k}; /* ignored by PROJ currently */ static const ParamMapping *const krovakParameters[] = { &paramLatCentreLatCenter, &paramLonCentreLonCenter, &paramColatitudeConeAxis, &paramLatitudePseudoStdParallel, &paramScaleFactorPseudoStdParallel, &paramFalseEasting, &paramFalseNorthing, nullptr}; static const ParamMapping *const paramsLaea[] = { &paramLatNatLatCenter, &paramLonNatLonCenter, &paramFalseEasting, &paramFalseNorthing, nullptr}; static const ParamMapping *const paramsMiller[] = { &paramLonNatLonCenter, &paramFalseEasting, &paramFalseNorthing, nullptr}; static const ParamMapping paramLatMerc1SP = { EPSG_NAME_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, nullptr, // always set to zero, not to be exported in WKT1 common::UnitOfMeasure::Type::ANGULAR, nullptr}; // always set to zero, not to be exported in PROJ strings static const ParamMapping *const paramsMerc1SP[] = { &paramLatMerc1SP, &paramLongitudeNatOrigin, &paramScaleFactorK, &paramFalseEasting, &paramFalseNorthing, nullptr}; static const ParamMapping *const paramsMerc2SP[] = { &paramLat1stParallelLatTs, &paramLongitudeNatOrigin, &paramFalseEasting, &paramFalseNorthing, nullptr}; static const ParamMapping *const paramsObliqueStereo[] = { &paramLatitudeNatOrigin, &paramLongitudeNatOrigin, &paramScaleFactorK, &paramFalseEasting, &paramFalseNorthing, nullptr}; static const ParamMapping paramLatStdParallel = { EPSG_NAME_PARAMETER_LATITUDE_STD_PARALLEL, EPSG_CODE_PARAMETER_LATITUDE_STD_PARALLEL, WKT1_LATITUDE_OF_ORIGIN, common::UnitOfMeasure::Type::ANGULAR, lat_ts}; static const ParamMapping paramsLonOrigin = { EPSG_NAME_PARAMETER_LONGITUDE_OF_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_OF_ORIGIN, WKT1_CENTRAL_MERIDIAN, common::UnitOfMeasure::Type::ANGULAR, lon_0}; static const ParamMapping *const paramsPolarStereo[] = { &paramLatStdParallel, &paramsLonOrigin, &paramFalseEasting, &paramFalseNorthing, nullptr}; static const ParamMapping *const paramsLonNatOriginLongitudeCentre[] = { &paramLonNatLonCenter, &paramFalseEasting, &paramFalseNorthing, nullptr}; static const ParamMapping paramLatTrueScaleWag3 = { "Latitude of true scale", 0, WKT1_LATITUDE_OF_ORIGIN, common::UnitOfMeasure::Type::ANGULAR, lat_ts}; static const ParamMapping *const paramsWag3[] = { &paramLatTrueScaleWag3, &paramLongitudeNatOrigin, &paramFalseEasting, &paramFalseNorthing, nullptr}; static const ParamMapping paramPegLat = { "Peg point latitude", 0, "peg_point_latitude", common::UnitOfMeasure::Type::ANGULAR, "plat_0"}; static const ParamMapping paramPegLon = { "Peg point longitude", 0, "peg_point_longitude", common::UnitOfMeasure::Type::ANGULAR, "plon_0"}; static const ParamMapping paramPegHeading = { "Peg point heading", 0, "peg_point_heading", common::UnitOfMeasure::Type::ANGULAR, "phdg_0"}; static const ParamMapping paramPegHeight = { "Peg point height", 0, "peg_point_height", common::UnitOfMeasure::Type::LINEAR, "h_0"}; static const ParamMapping *const paramsSch[] = { &paramPegLat, &paramPegLon, &paramPegHeading, &paramPegHeight, nullptr}; static const ParamMapping *const paramsWink1[] = { &paramLongitudeNatOrigin, &paramLat1stParallelLatTs, &paramFalseEasting, &paramFalseNorthing, nullptr}; static const ParamMapping *const paramsWink2[] = { &paramLongitudeNatOrigin, &paramLatitude1stStdParallel, &paramFalseEasting, &paramFalseNorthing, nullptr}; static const ParamMapping paramLatLoxim = { EPSG_NAME_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, WKT1_LATITUDE_OF_ORIGIN, common::UnitOfMeasure::Type::ANGULAR, lat_1}; static const ParamMapping *const paramsLoxim[] = { &paramLatLoxim, &paramLongitudeNatOrigin, &paramFalseEasting, &paramFalseNorthing, nullptr}; static const ParamMapping paramLonCentre = { EPSG_NAME_PARAMETER_LONGITUDE_PROJECTION_CENTRE, EPSG_CODE_PARAMETER_LONGITUDE_PROJECTION_CENTRE, WKT1_LONGITUDE_OF_CENTER, common::UnitOfMeasure::Type::ANGULAR, lon_0}; static const ParamMapping paramLabordeObliqueMercatorAzimuth = { EPSG_NAME_PARAMETER_AZIMUTH_INITIAL_LINE, EPSG_CODE_PARAMETER_AZIMUTH_INITIAL_LINE, WKT1_AZIMUTH, common::UnitOfMeasure::Type::ANGULAR, "azi"}; static const ParamMapping *const paramsLabordeObliqueMercator[] = { &paramLatCentreLatCenter, &paramLonCentre, &paramLabordeObliqueMercatorAzimuth, &paramScaleFactorInitialLine, &paramFalseEasting, &paramFalseNorthing, nullptr}; static const ParamMapping paramLatTopoOrigin = { EPSG_NAME_PARAMETER_LATITUDE_TOPOGRAPHIC_ORIGIN, EPSG_CODE_PARAMETER_LATITUDE_TOPOGRAPHIC_ORIGIN, nullptr, common::UnitOfMeasure::Type::ANGULAR, lat_0}; static const ParamMapping paramLonTopoOrigin = { EPSG_NAME_PARAMETER_LONGITUDE_TOPOGRAPHIC_ORIGIN, EPSG_CODE_PARAMETER_LONGITUDE_TOPOGRAPHIC_ORIGIN, nullptr, common::UnitOfMeasure::Type::ANGULAR, lon_0}; static const ParamMapping paramHeightTopoOrigin = { EPSG_NAME_PARAMETER_ELLIPSOIDAL_HEIGHT_TOPOCENTRIC_ORIGIN, EPSG_CODE_PARAMETER_ELLIPSOIDAL_HEIGHT_TOPOCENTRIC_ORIGIN, nullptr, common::UnitOfMeasure::Type::LINEAR, nullptr}; // unsupported by PROJ right now static const ParamMapping paramViewpointHeight = { EPSG_NAME_PARAMETER_VIEWPOINT_HEIGHT, EPSG_CODE_PARAMETER_VIEWPOINT_HEIGHT, nullptr, common::UnitOfMeasure::Type::LINEAR, "h"}; static const ParamMapping *const paramsVerticalPerspective[] = { &paramLatTopoOrigin, &paramLonTopoOrigin, &paramHeightTopoOrigin, // unsupported by PROJ right now &paramViewpointHeight, &paramFalseEasting, // PROJ addition &paramFalseNorthing, // PROJ addition nullptr}; static const ParamMapping paramProjectionPlaneOriginHeight = { EPSG_NAME_PARAMETER_PROJECTION_PLANE_ORIGIN_HEIGHT, EPSG_CODE_PARAMETER_PROJECTION_PLANE_ORIGIN_HEIGHT, nullptr, common::UnitOfMeasure::Type::LINEAR, "h_0"}; static const ParamMapping *const paramsColombiaUrban[] = { &paramLatitudeNatOrigin, &paramLongitudeNatOrigin, &paramFalseEasting, &paramFalseNorthing, &paramProjectionPlaneOriginHeight, nullptr}; static const ParamMapping paramGeocentricXTopocentricOrigin = { EPSG_NAME_PARAMETER_GEOCENTRIC_X_TOPOCENTRIC_ORIGIN, EPSG_CODE_PARAMETER_GEOCENTRIC_X_TOPOCENTRIC_ORIGIN, nullptr, common::UnitOfMeasure::Type::LINEAR, "X_0"}; static const ParamMapping paramGeocentricYTopocentricOrigin = { EPSG_NAME_PARAMETER_GEOCENTRIC_Y_TOPOCENTRIC_ORIGIN, EPSG_CODE_PARAMETER_GEOCENTRIC_Y_TOPOCENTRIC_ORIGIN, nullptr, common::UnitOfMeasure::Type::LINEAR, "Y_0"}; static const ParamMapping paramGeocentricZTopocentricOrigin = { EPSG_NAME_PARAMETER_GEOCENTRIC_Z_TOPOCENTRIC_ORIGIN, EPSG_CODE_PARAMETER_GEOCENTRIC_Z_TOPOCENTRIC_ORIGIN, nullptr, common::UnitOfMeasure::Type::LINEAR, "Z_0"}; static const ParamMapping *const paramsGeocentricTopocentric[] = { &paramGeocentricXTopocentricOrigin, &paramGeocentricYTopocentricOrigin, &paramGeocentricZTopocentricOrigin, nullptr}; static const ParamMapping paramHeightTopoOriginWithH0 = { EPSG_NAME_PARAMETER_ELLIPSOIDAL_HEIGHT_TOPOCENTRIC_ORIGIN, EPSG_CODE_PARAMETER_ELLIPSOIDAL_HEIGHT_TOPOCENTRIC_ORIGIN, nullptr, common::UnitOfMeasure::Type::LINEAR, "h_0"}; static const ParamMapping *const paramsGeographicTopocentric[] = { &paramLatTopoOrigin, &paramLonTopoOrigin, &paramHeightTopoOriginWithH0, nullptr}; static const MethodMapping projectionMethodMappings[] = { {EPSG_NAME_METHOD_TRANSVERSE_MERCATOR, EPSG_CODE_METHOD_TRANSVERSE_MERCATOR, "Transverse_Mercator", "tmerc", nullptr, paramsNatOriginScaleK}, {EPSG_NAME_METHOD_TRANSVERSE_MERCATOR_SOUTH_ORIENTATED, EPSG_CODE_METHOD_TRANSVERSE_MERCATOR_SOUTH_ORIENTATED, "Transverse_Mercator_South_Orientated", "tmerc", "axis=wsu", paramsNatOriginScaleK}, {PROJ_WKT2_NAME_METHOD_TWO_POINT_EQUIDISTANT, 0, "Two_Point_Equidistant", "tpeqd", nullptr, paramsTPEQD}, {EPSG_NAME_METHOD_TUNISIA_MAPPING_GRID, EPSG_CODE_METHOD_TUNISIA_MAPPING_GRID, "Tunisia_Mapping_Grid", nullptr, nullptr, // no proj equivalent paramsTMG}, {EPSG_NAME_METHOD_ALBERS_EQUAL_AREA, EPSG_CODE_METHOD_ALBERS_EQUAL_AREA, "Albers_Conic_Equal_Area", "aea", nullptr, paramsAEA}, {EPSG_NAME_METHOD_LAMBERT_CONIC_CONFORMAL_1SP, EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_1SP, "Lambert_Conformal_Conic_1SP", "lcc", nullptr, []() { static const ParamMapping paramLatLCC1SP = { EPSG_NAME_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, EPSG_CODE_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN, WKT1_LATITUDE_OF_ORIGIN, common::UnitOfMeasure::Type::ANGULAR, lat_1}; static const ParamMapping *const x[] = { &paramLatLCC1SP, &paramLongitudeNatOrigin, &paramScaleFactor, &paramFalseEasting, &paramFalseNorthing, nullptr, }; return x; }()}, {EPSG_NAME_METHOD_LAMBERT_CONIC_CONFORMAL_2SP, EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_2SP, "Lambert_Conformal_Conic_2SP", "lcc", nullptr, paramsLCC2SP}, // Oracle WKT {EPSG_NAME_METHOD_LAMBERT_CONIC_CONFORMAL_2SP, EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_2SP, "Lambert Conformal Conic", "lcc", nullptr, paramsLCC2SP}, {EPSG_NAME_METHOD_LAMBERT_CONIC_CONFORMAL_2SP_MICHIGAN, EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_2SP_MICHIGAN, nullptr, // no mapping to WKT1_GDAL "lcc", nullptr, paramsLCC2SPMichigan}, {EPSG_NAME_METHOD_LAMBERT_CONIC_CONFORMAL_2SP_BELGIUM, EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_2SP_BELGIUM, "Lambert_Conformal_Conic_2SP_Belgium", "lcc", nullptr, // FIXME: this is what is done in GDAL, but the formula of // LCC 2SP // Belgium in the EPSG 7.2 guidance is difference from the regular // LCC 2SP paramsLCC2SP}, {EPSG_NAME_METHOD_MODIFIED_AZIMUTHAL_EQUIDISTANT, EPSG_CODE_METHOD_MODIFIED_AZIMUTHAL_EQUIDISTANT, "Azimuthal_Equidistant", "aeqd", nullptr, paramsAEQD}, {EPSG_NAME_METHOD_GUAM_PROJECTION, EPSG_CODE_METHOD_GUAM_PROJECTION, nullptr, // no mapping to GDAL WKT1 "aeqd", "guam", paramsNatOrigin}, {EPSG_NAME_METHOD_BONNE, EPSG_CODE_METHOD_BONNE, "Bonne", "bonne", nullptr, paramsBonne}, {PROJ_WKT2_NAME_METHOD_COMPACT_MILLER, 0, "Compact_Miller", "comill", nullptr, paramsLonNatOrigin}, {EPSG_NAME_METHOD_LAMBERT_CYLINDRICAL_EQUAL_AREA_SPHERICAL, EPSG_CODE_METHOD_LAMBERT_CYLINDRICAL_EQUAL_AREA_SPHERICAL, "Cylindrical_Equal_Area", "cea", nullptr, paramsCEA}, {EPSG_NAME_METHOD_LAMBERT_CYLINDRICAL_EQUAL_AREA, EPSG_CODE_METHOD_LAMBERT_CYLINDRICAL_EQUAL_AREA, "Cylindrical_Equal_Area", "cea", nullptr, paramsCEA}, {EPSG_NAME_METHOD_CASSINI_SOLDNER, EPSG_CODE_METHOD_CASSINI_SOLDNER, "Cassini_Soldner", "cass", nullptr, paramsNatOrigin}, {EPSG_NAME_METHOD_HYPERBOLIC_CASSINI_SOLDNER, EPSG_CODE_METHOD_HYPERBOLIC_CASSINI_SOLDNER, nullptr, "cass", "hyperbolic", paramsNatOrigin}, {PROJ_WKT2_NAME_METHOD_EQUIDISTANT_CONIC, 0, "Equidistant_Conic", "eqdc", nullptr, paramsEQDC}, {PROJ_WKT2_NAME_METHOD_ECKERT_I, 0, "Eckert_I", "eck1", nullptr, paramsLonNatOrigin}, {PROJ_WKT2_NAME_METHOD_ECKERT_II, 0, "Eckert_II", "eck2", nullptr, paramsLonNatOrigin}, {PROJ_WKT2_NAME_METHOD_ECKERT_III, 0, "Eckert_III", "eck3", nullptr, paramsLonNatOrigin}, {PROJ_WKT2_NAME_METHOD_ECKERT_IV, 0, "Eckert_IV", "eck4", nullptr, paramsLonNatOrigin}, {PROJ_WKT2_NAME_METHOD_ECKERT_V, 0, "Eckert_V", "eck5", nullptr, paramsLonNatOrigin}, {PROJ_WKT2_NAME_METHOD_ECKERT_VI, 0, "Eckert_VI", "eck6", nullptr, paramsLonNatOrigin}, {EPSG_NAME_METHOD_EQUIDISTANT_CYLINDRICAL, EPSG_CODE_METHOD_EQUIDISTANT_CYLINDRICAL, "Equirectangular", "eqc", nullptr, paramsEqc}, {EPSG_NAME_METHOD_EQUIDISTANT_CYLINDRICAL_SPHERICAL, EPSG_CODE_METHOD_EQUIDISTANT_CYLINDRICAL_SPHERICAL, "Equirectangular", "eqc", nullptr, paramsEqc}, {PROJ_WKT2_NAME_METHOD_FLAT_POLAR_QUARTIC, 0, "Flat_Polar_Quartic", "mbtfpq", nullptr, paramsLonNatOrigin}, {PROJ_WKT2_NAME_METHOD_GALL_STEREOGRAPHIC, 0, "Gall_Stereographic", "gall", nullptr, paramsLonNatOrigin}, {PROJ_WKT2_NAME_METHOD_GOODE_HOMOLOSINE, 0, "Goode_Homolosine", "goode", nullptr, paramsLonNatOrigin}, {PROJ_WKT2_NAME_METHOD_INTERRUPTED_GOODE_HOMOLOSINE, 0, "Interrupted_Goode_Homolosine", "igh", nullptr, paramsLonNatOrigin}, {PROJ_WKT2_NAME_METHOD_INTERRUPTED_GOODE_HOMOLOSINE_OCEAN, 0, nullptr, "igh_o", nullptr, paramsLonNatOrigin}, // No proper WKT1 representation fr sweep=x {PROJ_WKT2_NAME_METHOD_GEOSTATIONARY_SATELLITE_SWEEP_X, 0, nullptr, "geos", "sweep=x", paramsGeos}, {PROJ_WKT2_NAME_METHOD_GEOSTATIONARY_SATELLITE_SWEEP_Y, 0, "Geostationary_Satellite", "geos", nullptr, paramsGeos}, {PROJ_WKT2_NAME_METHOD_GAUSS_SCHREIBER_TRANSVERSE_MERCATOR, 0, "Gauss_Schreiber_Transverse_Mercator", "gstmerc", nullptr, paramsNatOriginScale}, {PROJ_WKT2_NAME_METHOD_GNOMONIC, 0, "Gnomonic", "gnom", nullptr, paramsNatOrigin}, {EPSG_NAME_METHOD_HOTINE_OBLIQUE_MERCATOR_VARIANT_A, EPSG_CODE_METHOD_HOTINE_OBLIQUE_MERCATOR_VARIANT_A, "Hotine_Oblique_Mercator", "omerc", "no_uoff", paramsHomVariantA}, {EPSG_NAME_METHOD_HOTINE_OBLIQUE_MERCATOR_VARIANT_B, EPSG_CODE_METHOD_HOTINE_OBLIQUE_MERCATOR_VARIANT_B, "Hotine_Oblique_Mercator_Azimuth_Center", "omerc", nullptr, paramsHomVariantB}, {PROJ_WKT2_NAME_METHOD_HOTINE_OBLIQUE_MERCATOR_TWO_POINT_NATURAL_ORIGIN, 0, "Hotine_Oblique_Mercator_Two_Point_Natural_Origin", "omerc", nullptr, paramsHomTwoPoint}, {PROJ_WKT2_NAME_INTERNATIONAL_MAP_WORLD_POLYCONIC, 0, "International_Map_of_the_World_Polyconic", "imw_p", nullptr, paramsIMWP}, {EPSG_NAME_METHOD_KROVAK_NORTH_ORIENTED, EPSG_CODE_METHOD_KROVAK_NORTH_ORIENTED, "Krovak", "krovak", nullptr, krovakParameters}, {EPSG_NAME_METHOD_KROVAK, EPSG_CODE_METHOD_KROVAK, "Krovak", "krovak", "axis=swu", krovakParameters}, {EPSG_NAME_METHOD_LAMBERT_AZIMUTHAL_EQUAL_AREA, EPSG_CODE_METHOD_LAMBERT_AZIMUTHAL_EQUAL_AREA, "Lambert_Azimuthal_Equal_Area", "laea", nullptr, paramsLaea}, {EPSG_NAME_METHOD_LAMBERT_AZIMUTHAL_EQUAL_AREA_SPHERICAL, EPSG_CODE_METHOD_LAMBERT_AZIMUTHAL_EQUAL_AREA_SPHERICAL, "Lambert_Azimuthal_Equal_Area", "laea", nullptr, paramsLaea}, {PROJ_WKT2_NAME_METHOD_MILLER_CYLINDRICAL, 0, "Miller_Cylindrical", "mill", "R_A", paramsMiller}, {EPSG_NAME_METHOD_MERCATOR_VARIANT_A, EPSG_CODE_METHOD_MERCATOR_VARIANT_A, "Mercator_1SP", "merc", nullptr, paramsMerc1SP}, {EPSG_NAME_METHOD_MERCATOR_VARIANT_B, EPSG_CODE_METHOD_MERCATOR_VARIANT_B, "Mercator_2SP", "merc", nullptr, paramsMerc2SP}, {EPSG_NAME_METHOD_POPULAR_VISUALISATION_PSEUDO_MERCATOR, EPSG_CODE_METHOD_POPULAR_VISUALISATION_PSEUDO_MERCATOR, "Popular_Visualisation_Pseudo_Mercator", // particular case actually // handled manually "webmerc", nullptr, paramsNatOrigin}, {PROJ_WKT2_NAME_METHOD_MOLLWEIDE, 0, "Mollweide", "moll", nullptr, paramsLonNatOrigin}, {PROJ_WKT2_NAME_METHOD_NATURAL_EARTH, 0, "Natural_Earth", "natearth", nullptr, paramsLonNatOrigin}, {PROJ_WKT2_NAME_METHOD_NATURAL_EARTH_II, 0, "Natural_Earth_II", "natearth2", nullptr, paramsLonNatOrigin}, {EPSG_NAME_METHOD_NZMG, EPSG_CODE_METHOD_NZMG, "New_Zealand_Map_Grid", "nzmg", nullptr, paramsNatOrigin}, { EPSG_NAME_METHOD_OBLIQUE_STEREOGRAPHIC, EPSG_CODE_METHOD_OBLIQUE_STEREOGRAPHIC, "Oblique_Stereographic", "sterea", nullptr, paramsObliqueStereo, }, {EPSG_NAME_METHOD_ORTHOGRAPHIC, EPSG_CODE_METHOD_ORTHOGRAPHIC, "Orthographic", "ortho", nullptr, paramsNatOrigin}, {PROJ_WKT2_NAME_ORTHOGRAPHIC_SPHERICAL, 0, "Orthographic", "ortho", "f=0", paramsNatOrigin}, {PROJ_WKT2_NAME_METHOD_PATTERSON, 0, "Patterson", "patterson", nullptr, paramsLonNatOrigin}, {EPSG_NAME_METHOD_AMERICAN_POLYCONIC, EPSG_CODE_METHOD_AMERICAN_POLYCONIC, "Polyconic", "poly", nullptr, paramsNatOrigin}, {EPSG_NAME_METHOD_POLAR_STEREOGRAPHIC_VARIANT_A, EPSG_CODE_METHOD_POLAR_STEREOGRAPHIC_VARIANT_A, "Polar_Stereographic", "stere", nullptr, paramsObliqueStereo}, {EPSG_NAME_METHOD_POLAR_STEREOGRAPHIC_VARIANT_B, EPSG_CODE_METHOD_POLAR_STEREOGRAPHIC_VARIANT_B, "Polar_Stereographic", "stere", nullptr, paramsPolarStereo}, {PROJ_WKT2_NAME_METHOD_ROBINSON, 0, "Robinson", "robin", nullptr, paramsLonNatOriginLongitudeCentre}, {PROJ_WKT2_NAME_METHOD_SINUSOIDAL, 0, "Sinusoidal", "sinu", nullptr, paramsLonNatOriginLongitudeCentre}, {PROJ_WKT2_NAME_METHOD_STEREOGRAPHIC, 0, "Stereographic", "stere", nullptr, paramsObliqueStereo}, {PROJ_WKT2_NAME_METHOD_TIMES, 0, "Times", "times", nullptr, paramsLonNatOrigin}, {PROJ_WKT2_NAME_METHOD_VAN_DER_GRINTEN, 0, "VanDerGrinten", "vandg", "R_A", paramsLonNatOrigin}, {PROJ_WKT2_NAME_METHOD_WAGNER_I, 0, "Wagner_I", "wag1", nullptr, paramsLonNatOrigin}, {PROJ_WKT2_NAME_METHOD_WAGNER_II, 0, "Wagner_II", "wag2", nullptr, paramsLonNatOrigin}, {PROJ_WKT2_NAME_METHOD_WAGNER_III, 0, "Wagner_III", "wag3", nullptr, paramsWag3}, {PROJ_WKT2_NAME_METHOD_WAGNER_IV, 0, "Wagner_IV", "wag4", nullptr, paramsLonNatOrigin}, {PROJ_WKT2_NAME_METHOD_WAGNER_V, 0, "Wagner_V", "wag5", nullptr, paramsLonNatOrigin}, {PROJ_WKT2_NAME_METHOD_WAGNER_VI, 0, "Wagner_VI", "wag6", nullptr, paramsLonNatOrigin}, {PROJ_WKT2_NAME_METHOD_WAGNER_VII, 0, "Wagner_VII", "wag7", nullptr, paramsLonNatOrigin}, {PROJ_WKT2_NAME_METHOD_QUADRILATERALIZED_SPHERICAL_CUBE, 0, "Quadrilateralized_Spherical_Cube", "qsc", nullptr, paramsNatOrigin}, {PROJ_WKT2_NAME_METHOD_SPHERICAL_CROSS_TRACK_HEIGHT, 0, "Spherical_Cross_Track_Height", "sch", nullptr, paramsSch}, // The following methods have just the WKT <--> PROJ string mapping, but // no setter. Similarly to GDAL {"Aitoff", 0, "Aitoff", "aitoff", nullptr, paramsLonNatOrigin}, {"Winkel I", 0, "Winkel_I", "wink1", nullptr, paramsWink1}, {"Winkel II", 0, "Winkel_II", "wink2", nullptr, paramsWink2}, {"Winkel Tripel", 0, "Winkel_Tripel", "wintri", nullptr, paramsWink2}, {"Craster Parabolic", 0, "Craster_Parabolic", "crast", nullptr, paramsLonNatOrigin}, {"Loximuthal", 0, "Loximuthal", "loxim", nullptr, paramsLoxim}, {"Quartic Authalic", 0, "Quartic_Authalic", "qua_aut", nullptr, paramsLonNatOrigin}, {"Transverse Cylindrical Equal Area", 0, "Transverse_Cylindrical_Equal_Area", "tcea", nullptr, paramsObliqueStereo}, {EPSG_NAME_METHOD_EQUAL_EARTH, EPSG_CODE_METHOD_EQUAL_EARTH, nullptr, "eqearth", nullptr, paramsLonNatOrigin}, {EPSG_NAME_METHOD_LABORDE_OBLIQUE_MERCATOR, EPSG_CODE_METHOD_LABORDE_OBLIQUE_MERCATOR, "Laborde_Oblique_Mercator", "labrd", nullptr, paramsLabordeObliqueMercator}, {EPSG_NAME_METHOD_VERTICAL_PERSPECTIVE, EPSG_CODE_METHOD_VERTICAL_PERSPECTIVE, nullptr, "nsper", nullptr, paramsVerticalPerspective}, {EPSG_NAME_METHOD_COLOMBIA_URBAN, EPSG_CODE_METHOD_COLOMBIA_URBAN, nullptr, "col_urban", nullptr, paramsColombiaUrban}, {EPSG_NAME_METHOD_GEOCENTRIC_TOPOCENTRIC, EPSG_CODE_METHOD_GEOCENTRIC_TOPOCENTRIC, nullptr, "topocentric", nullptr, paramsGeocentricTopocentric}, {EPSG_NAME_METHOD_GEOGRAPHIC_TOPOCENTRIC, EPSG_CODE_METHOD_GEOGRAPHIC_TOPOCENTRIC, nullptr, nullptr, nullptr, paramsGeographicTopocentric}, }; const MethodMapping *getProjectionMethodMappings(size_t &nElts) { nElts = sizeof(projectionMethodMappings) / sizeof(projectionMethodMappings[0]); return projectionMethodMappings; } #define METHOD_NAME_CODE(method) \ { EPSG_NAME_METHOD_##method, EPSG_CODE_METHOD_##method } const struct MethodNameCode methodNameCodes[] = { // Projection methods METHOD_NAME_CODE(TRANSVERSE_MERCATOR), METHOD_NAME_CODE(TRANSVERSE_MERCATOR_SOUTH_ORIENTATED), METHOD_NAME_CODE(LAMBERT_CONIC_CONFORMAL_1SP), METHOD_NAME_CODE(NZMG), METHOD_NAME_CODE(TUNISIA_MAPPING_GRID), METHOD_NAME_CODE(ALBERS_EQUAL_AREA), METHOD_NAME_CODE(LAMBERT_CONIC_CONFORMAL_2SP), METHOD_NAME_CODE(LAMBERT_CONIC_CONFORMAL_2SP_BELGIUM), METHOD_NAME_CODE(LAMBERT_CONIC_CONFORMAL_2SP_MICHIGAN), METHOD_NAME_CODE(MODIFIED_AZIMUTHAL_EQUIDISTANT), METHOD_NAME_CODE(GUAM_PROJECTION), METHOD_NAME_CODE(BONNE), METHOD_NAME_CODE(LAMBERT_CYLINDRICAL_EQUAL_AREA_SPHERICAL), METHOD_NAME_CODE(LAMBERT_CYLINDRICAL_EQUAL_AREA), METHOD_NAME_CODE(CASSINI_SOLDNER), METHOD_NAME_CODE(EQUIDISTANT_CYLINDRICAL), METHOD_NAME_CODE(EQUIDISTANT_CYLINDRICAL_SPHERICAL), METHOD_NAME_CODE(HOTINE_OBLIQUE_MERCATOR_VARIANT_A), METHOD_NAME_CODE(HOTINE_OBLIQUE_MERCATOR_VARIANT_B), METHOD_NAME_CODE(KROVAK_NORTH_ORIENTED), METHOD_NAME_CODE(KROVAK), METHOD_NAME_CODE(LAMBERT_AZIMUTHAL_EQUAL_AREA), METHOD_NAME_CODE(POPULAR_VISUALISATION_PSEUDO_MERCATOR), METHOD_NAME_CODE(MERCATOR_VARIANT_A), METHOD_NAME_CODE(MERCATOR_VARIANT_B), METHOD_NAME_CODE(OBLIQUE_STEREOGRAPHIC), METHOD_NAME_CODE(AMERICAN_POLYCONIC), METHOD_NAME_CODE(POLAR_STEREOGRAPHIC_VARIANT_A), METHOD_NAME_CODE(POLAR_STEREOGRAPHIC_VARIANT_B), METHOD_NAME_CODE(EQUAL_EARTH), METHOD_NAME_CODE(LABORDE_OBLIQUE_MERCATOR), METHOD_NAME_CODE(VERTICAL_PERSPECTIVE), METHOD_NAME_CODE(COLOMBIA_URBAN), // Other conversions METHOD_NAME_CODE(CHANGE_VERTICAL_UNIT), METHOD_NAME_CODE(CHANGE_VERTICAL_UNIT_NO_CONV_FACTOR), METHOD_NAME_CODE(HEIGHT_DEPTH_REVERSAL), METHOD_NAME_CODE(AXIS_ORDER_REVERSAL_2D), METHOD_NAME_CODE(AXIS_ORDER_REVERSAL_3D), METHOD_NAME_CODE(GEOGRAPHIC_GEOCENTRIC), METHOD_NAME_CODE(GEOCENTRIC_TOPOCENTRIC), METHOD_NAME_CODE(GEOGRAPHIC_TOPOCENTRIC), // Transformations METHOD_NAME_CODE(LONGITUDE_ROTATION), METHOD_NAME_CODE(AFFINE_PARAMETRIC_TRANSFORMATION), METHOD_NAME_CODE(COORDINATE_FRAME_GEOCENTRIC), METHOD_NAME_CODE(COORDINATE_FRAME_GEOGRAPHIC_2D), METHOD_NAME_CODE(COORDINATE_FRAME_GEOGRAPHIC_3D), METHOD_NAME_CODE(POSITION_VECTOR_GEOCENTRIC), METHOD_NAME_CODE(POSITION_VECTOR_GEOGRAPHIC_2D), METHOD_NAME_CODE(POSITION_VECTOR_GEOGRAPHIC_3D), METHOD_NAME_CODE(GEOCENTRIC_TRANSLATION_GEOCENTRIC), METHOD_NAME_CODE(GEOCENTRIC_TRANSLATION_GEOGRAPHIC_2D), METHOD_NAME_CODE(GEOCENTRIC_TRANSLATION_GEOGRAPHIC_3D), METHOD_NAME_CODE(TIME_DEPENDENT_COORDINATE_FRAME_GEOCENTRIC), METHOD_NAME_CODE(TIME_DEPENDENT_COORDINATE_FRAME_GEOGRAPHIC_2D), METHOD_NAME_CODE(TIME_DEPENDENT_COORDINATE_FRAME_GEOGRAPHIC_3D), METHOD_NAME_CODE(TIME_DEPENDENT_POSITION_VECTOR_GEOCENTRIC), METHOD_NAME_CODE(TIME_DEPENDENT_POSITION_VECTOR_GEOGRAPHIC_2D), METHOD_NAME_CODE(TIME_DEPENDENT_POSITION_VECTOR_GEOGRAPHIC_3D), METHOD_NAME_CODE(MOLODENSKY_BADEKAS_CF_GEOCENTRIC), METHOD_NAME_CODE(MOLODENSKY_BADEKAS_CF_GEOGRAPHIC_2D), METHOD_NAME_CODE(MOLODENSKY_BADEKAS_CF_GEOGRAPHIC_3D), METHOD_NAME_CODE(MOLODENSKY_BADEKAS_PV_GEOCENTRIC), METHOD_NAME_CODE(MOLODENSKY_BADEKAS_PV_GEOGRAPHIC_2D), METHOD_NAME_CODE(MOLODENSKY_BADEKAS_PV_GEOGRAPHIC_3D), METHOD_NAME_CODE(MOLODENSKY), METHOD_NAME_CODE(ABRIDGED_MOLODENSKY), METHOD_NAME_CODE(GEOGRAPHIC2D_OFFSETS), METHOD_NAME_CODE(GEOGRAPHIC2D_WITH_HEIGHT_OFFSETS), METHOD_NAME_CODE(GEOGRAPHIC3D_OFFSETS), METHOD_NAME_CODE(VERTICAL_OFFSET), METHOD_NAME_CODE(NTV2), METHOD_NAME_CODE(NTV1), METHOD_NAME_CODE(NADCON), METHOD_NAME_CODE(VERTCON), METHOD_NAME_CODE(GEOCENTRIC_TRANSLATION_BY_GRID_INTERPOLATION_IGN), }; const MethodNameCode *getMethodNameCodes(size_t &nElts) { nElts = sizeof(methodNameCodes) / sizeof(methodNameCodes[0]); return methodNameCodes; } #define PARAM_NAME_CODE(method) \ { EPSG_NAME_PARAMETER_##method, EPSG_CODE_PARAMETER_##method } const struct ParamNameCode paramNameCodes[] = { // Parameters of projection methods PARAM_NAME_CODE(COLATITUDE_CONE_AXIS), PARAM_NAME_CODE(LATITUDE_OF_NATURAL_ORIGIN), PARAM_NAME_CODE(LONGITUDE_OF_NATURAL_ORIGIN), PARAM_NAME_CODE(SCALE_FACTOR_AT_NATURAL_ORIGIN), PARAM_NAME_CODE(FALSE_EASTING), PARAM_NAME_CODE(FALSE_NORTHING), PARAM_NAME_CODE(LATITUDE_PROJECTION_CENTRE), PARAM_NAME_CODE(LONGITUDE_PROJECTION_CENTRE), PARAM_NAME_CODE(AZIMUTH_INITIAL_LINE), PARAM_NAME_CODE(ANGLE_RECTIFIED_TO_SKEW_GRID), PARAM_NAME_CODE(SCALE_FACTOR_INITIAL_LINE), PARAM_NAME_CODE(EASTING_PROJECTION_CENTRE), PARAM_NAME_CODE(NORTHING_PROJECTION_CENTRE), PARAM_NAME_CODE(LATITUDE_PSEUDO_STANDARD_PARALLEL), PARAM_NAME_CODE(SCALE_FACTOR_PSEUDO_STANDARD_PARALLEL), PARAM_NAME_CODE(LATITUDE_FALSE_ORIGIN), PARAM_NAME_CODE(LONGITUDE_FALSE_ORIGIN), PARAM_NAME_CODE(LATITUDE_1ST_STD_PARALLEL), PARAM_NAME_CODE(LATITUDE_2ND_STD_PARALLEL), PARAM_NAME_CODE(EASTING_FALSE_ORIGIN), PARAM_NAME_CODE(NORTHING_FALSE_ORIGIN), PARAM_NAME_CODE(LATITUDE_STD_PARALLEL), PARAM_NAME_CODE(LONGITUDE_OF_ORIGIN), PARAM_NAME_CODE(ELLIPSOID_SCALE_FACTOR), PARAM_NAME_CODE(PROJECTION_PLANE_ORIGIN_HEIGHT), PARAM_NAME_CODE(GEOCENTRIC_X_TOPOCENTRIC_ORIGIN), PARAM_NAME_CODE(GEOCENTRIC_Y_TOPOCENTRIC_ORIGIN), PARAM_NAME_CODE(GEOCENTRIC_Z_TOPOCENTRIC_ORIGIN), // Parameters of transformations PARAM_NAME_CODE(SEMI_MAJOR_AXIS_DIFFERENCE), PARAM_NAME_CODE(FLATTENING_DIFFERENCE), PARAM_NAME_CODE(LATITUDE_LONGITUDE_DIFFERENCE_FILE), PARAM_NAME_CODE(GEOID_CORRECTION_FILENAME), PARAM_NAME_CODE(VERTICAL_OFFSET_FILE), PARAM_NAME_CODE(LATITUDE_DIFFERENCE_FILE), PARAM_NAME_CODE(LONGITUDE_DIFFERENCE_FILE), PARAM_NAME_CODE(UNIT_CONVERSION_SCALAR), PARAM_NAME_CODE(LATITUDE_OFFSET), PARAM_NAME_CODE(LONGITUDE_OFFSET), PARAM_NAME_CODE(VERTICAL_OFFSET), PARAM_NAME_CODE(GEOID_UNDULATION), PARAM_NAME_CODE(A0), PARAM_NAME_CODE(A1), PARAM_NAME_CODE(A2), PARAM_NAME_CODE(B0), PARAM_NAME_CODE(B1), PARAM_NAME_CODE(B2), PARAM_NAME_CODE(X_AXIS_TRANSLATION), PARAM_NAME_CODE(Y_AXIS_TRANSLATION), PARAM_NAME_CODE(Z_AXIS_TRANSLATION), PARAM_NAME_CODE(X_AXIS_ROTATION), PARAM_NAME_CODE(Y_AXIS_ROTATION), PARAM_NAME_CODE(Z_AXIS_ROTATION), PARAM_NAME_CODE(SCALE_DIFFERENCE), PARAM_NAME_CODE(RATE_X_AXIS_TRANSLATION), PARAM_NAME_CODE(RATE_Y_AXIS_TRANSLATION), PARAM_NAME_CODE(RATE_Z_AXIS_TRANSLATION), PARAM_NAME_CODE(RATE_X_AXIS_ROTATION), PARAM_NAME_CODE(RATE_Y_AXIS_ROTATION), PARAM_NAME_CODE(RATE_Z_AXIS_ROTATION), PARAM_NAME_CODE(RATE_SCALE_DIFFERENCE), PARAM_NAME_CODE(REFERENCE_EPOCH), PARAM_NAME_CODE(TRANSFORMATION_REFERENCE_EPOCH), PARAM_NAME_CODE(ORDINATE_1_EVAL_POINT), PARAM_NAME_CODE(ORDINATE_2_EVAL_POINT), PARAM_NAME_CODE(ORDINATE_3_EVAL_POINT), PARAM_NAME_CODE(GEOCENTRIC_TRANSLATION_FILE), }; const ParamNameCode *getParamNameCodes(size_t &nElts) { nElts = sizeof(paramNameCodes) / sizeof(paramNameCodes[0]); return paramNameCodes; } static const ParamMapping paramUnitConversionScalar = { EPSG_NAME_PARAMETER_UNIT_CONVERSION_SCALAR, EPSG_CODE_PARAMETER_UNIT_CONVERSION_SCALAR, nullptr, common::UnitOfMeasure::Type::SCALE, nullptr}; static const ParamMapping *const paramsChangeVerticalUnit[] = { &paramUnitConversionScalar, nullptr}; static const ParamMapping paramLongitudeOffset = { EPSG_NAME_PARAMETER_LONGITUDE_OFFSET, EPSG_CODE_PARAMETER_LONGITUDE_OFFSET, nullptr, common::UnitOfMeasure::Type::ANGULAR, nullptr}; static const ParamMapping *const paramsLongitudeRotation[] = { &paramLongitudeOffset, nullptr}; static const ParamMapping paramA0 = { EPSG_NAME_PARAMETER_A0, EPSG_CODE_PARAMETER_A0, nullptr, common::UnitOfMeasure::Type::UNKNOWN, nullptr}; static const ParamMapping paramA1 = { EPSG_NAME_PARAMETER_A1, EPSG_CODE_PARAMETER_A1, nullptr, common::UnitOfMeasure::Type::UNKNOWN, nullptr}; static const ParamMapping paramA2 = { EPSG_NAME_PARAMETER_A2, EPSG_CODE_PARAMETER_A2, nullptr, common::UnitOfMeasure::Type::UNKNOWN, nullptr}; static const ParamMapping paramB0 = { EPSG_NAME_PARAMETER_B0, EPSG_CODE_PARAMETER_B0, nullptr, common::UnitOfMeasure::Type::UNKNOWN, nullptr}; static const ParamMapping paramB1 = { EPSG_NAME_PARAMETER_B1, EPSG_CODE_PARAMETER_B1, nullptr, common::UnitOfMeasure::Type::UNKNOWN, nullptr}; static const ParamMapping paramB2 = { EPSG_NAME_PARAMETER_B2, EPSG_CODE_PARAMETER_B2, nullptr, common::UnitOfMeasure::Type::UNKNOWN, nullptr}; static const ParamMapping *const paramsAffineParametricTransformation[] = { &paramA0, &paramA1, &paramA2, &paramB0, &paramB1, &paramB2, nullptr}; static const ParamMapping paramXTranslation = { EPSG_NAME_PARAMETER_X_AXIS_TRANSLATION, EPSG_CODE_PARAMETER_X_AXIS_TRANSLATION, nullptr, common::UnitOfMeasure::Type::LINEAR, nullptr}; static const ParamMapping paramYTranslation = { EPSG_NAME_PARAMETER_Y_AXIS_TRANSLATION, EPSG_CODE_PARAMETER_Y_AXIS_TRANSLATION, nullptr, common::UnitOfMeasure::Type::LINEAR, nullptr}; static const ParamMapping paramZTranslation = { EPSG_NAME_PARAMETER_Z_AXIS_TRANSLATION, EPSG_CODE_PARAMETER_Z_AXIS_TRANSLATION, nullptr, common::UnitOfMeasure::Type::LINEAR, nullptr}; static const ParamMapping paramXRotation = { EPSG_NAME_PARAMETER_X_AXIS_ROTATION, EPSG_CODE_PARAMETER_X_AXIS_ROTATION, nullptr, common::UnitOfMeasure::Type::LINEAR, nullptr}; static const ParamMapping paramYRotation = { EPSG_NAME_PARAMETER_Y_AXIS_ROTATION, EPSG_CODE_PARAMETER_Y_AXIS_ROTATION, nullptr, common::UnitOfMeasure::Type::LINEAR, nullptr}; static const ParamMapping paramZRotation = { EPSG_NAME_PARAMETER_Z_AXIS_ROTATION, EPSG_CODE_PARAMETER_Z_AXIS_ROTATION, nullptr, common::UnitOfMeasure::Type::LINEAR, nullptr}; static const ParamMapping paramScaleDifference = { EPSG_NAME_PARAMETER_SCALE_DIFFERENCE, EPSG_CODE_PARAMETER_SCALE_DIFFERENCE, nullptr, common::UnitOfMeasure::Type::SCALE, nullptr}; static const ParamMapping *const paramsHelmert3[] = { &paramXTranslation, &paramYTranslation, &paramZTranslation, nullptr}; static const ParamMapping *const paramsHelmert7[] = { &paramXTranslation, &paramYTranslation, &paramZTranslation, &paramXRotation, &paramYRotation, &paramZRotation, &paramScaleDifference, nullptr}; static const ParamMapping paramRateXTranslation = { EPSG_NAME_PARAMETER_RATE_X_AXIS_TRANSLATION, EPSG_CODE_PARAMETER_RATE_X_AXIS_TRANSLATION, nullptr, common::UnitOfMeasure::Type::LINEAR, nullptr}; static const ParamMapping paramRateYTranslation = { EPSG_NAME_PARAMETER_RATE_Y_AXIS_TRANSLATION, EPSG_CODE_PARAMETER_RATE_Y_AXIS_TRANSLATION, nullptr, common::UnitOfMeasure::Type::LINEAR, nullptr}; static const ParamMapping paramRateZTranslation = { EPSG_NAME_PARAMETER_RATE_Z_AXIS_TRANSLATION, EPSG_CODE_PARAMETER_RATE_Z_AXIS_TRANSLATION, nullptr, common::UnitOfMeasure::Type::LINEAR, nullptr}; static const ParamMapping paramRateXRotation = { EPSG_NAME_PARAMETER_RATE_X_AXIS_ROTATION, EPSG_CODE_PARAMETER_RATE_X_AXIS_ROTATION, nullptr, common::UnitOfMeasure::Type::LINEAR, nullptr}; static const ParamMapping paramRateYRotation = { EPSG_NAME_PARAMETER_RATE_Y_AXIS_ROTATION, EPSG_CODE_PARAMETER_RATE_Y_AXIS_ROTATION, nullptr, common::UnitOfMeasure::Type::LINEAR, nullptr}; static const ParamMapping paramRateZRotation = { EPSG_NAME_PARAMETER_RATE_Z_AXIS_ROTATION, EPSG_CODE_PARAMETER_RATE_Z_AXIS_ROTATION, nullptr, common::UnitOfMeasure::Type::LINEAR, nullptr}; static const ParamMapping paramRateScaleDifference = { EPSG_NAME_PARAMETER_RATE_SCALE_DIFFERENCE, EPSG_CODE_PARAMETER_RATE_SCALE_DIFFERENCE, nullptr, common::UnitOfMeasure::Type::SCALE, nullptr}; static const ParamMapping paramReferenceEpoch = { EPSG_NAME_PARAMETER_REFERENCE_EPOCH, EPSG_CODE_PARAMETER_REFERENCE_EPOCH, nullptr, common::UnitOfMeasure::Type::TIME, nullptr}; static const ParamMapping *const paramsHelmert15[] = { &paramXTranslation, &paramYTranslation, &paramZTranslation, &paramXRotation, &paramYRotation, &paramZRotation, &paramScaleDifference, &paramRateXTranslation, &paramRateYTranslation, &paramRateZTranslation, &paramRateXRotation, &paramRateYRotation, &paramRateZRotation, &paramRateScaleDifference, &paramReferenceEpoch, nullptr}; static const ParamMapping paramOrdinate1EvalPoint = { EPSG_NAME_PARAMETER_ORDINATE_1_EVAL_POINT, EPSG_CODE_PARAMETER_ORDINATE_1_EVAL_POINT, nullptr, common::UnitOfMeasure::Type::LINEAR, nullptr}; static const ParamMapping paramOrdinate2EvalPoint = { EPSG_NAME_PARAMETER_ORDINATE_2_EVAL_POINT, EPSG_CODE_PARAMETER_ORDINATE_2_EVAL_POINT, nullptr, common::UnitOfMeasure::Type::LINEAR, nullptr}; static const ParamMapping paramOrdinate3EvalPoint = { EPSG_NAME_PARAMETER_ORDINATE_3_EVAL_POINT, EPSG_CODE_PARAMETER_ORDINATE_3_EVAL_POINT, nullptr, common::UnitOfMeasure::Type::LINEAR, nullptr}; static const ParamMapping *const paramsMolodenskyBadekas[] = { &paramXTranslation, &paramYTranslation, &paramZTranslation, &paramXRotation, &paramYRotation, &paramZRotation, &paramScaleDifference, &paramOrdinate1EvalPoint, &paramOrdinate2EvalPoint, &paramOrdinate3EvalPoint, nullptr}; static const ParamMapping paramSemiMajorAxisDifference = { EPSG_NAME_PARAMETER_SEMI_MAJOR_AXIS_DIFFERENCE, EPSG_CODE_PARAMETER_SEMI_MAJOR_AXIS_DIFFERENCE, nullptr, common::UnitOfMeasure::Type::LINEAR, nullptr}; static const ParamMapping paramFlatteningDifference = { EPSG_NAME_PARAMETER_FLATTENING_DIFFERENCE, EPSG_CODE_PARAMETER_FLATTENING_DIFFERENCE, nullptr, common::UnitOfMeasure::Type::NONE, nullptr}; static const ParamMapping *const paramsMolodensky[] = { &paramXTranslation, &paramYTranslation, &paramZTranslation, &paramSemiMajorAxisDifference, &paramFlatteningDifference, nullptr}; static const ParamMapping paramLatitudeOffset = { EPSG_NAME_PARAMETER_LATITUDE_OFFSET, EPSG_CODE_PARAMETER_LATITUDE_OFFSET, nullptr, common::UnitOfMeasure::Type::ANGULAR, nullptr}; static const ParamMapping *const paramsGeographic2DOffsets[] = { &paramLatitudeOffset, &paramLongitudeOffset, nullptr}; static const ParamMapping paramGeoidUndulation = { EPSG_NAME_PARAMETER_GEOID_UNDULATION, EPSG_CODE_PARAMETER_GEOID_UNDULATION, nullptr, common::UnitOfMeasure::Type::LINEAR, nullptr}; static const ParamMapping *const paramsGeographic2DWithHeightOffsets[] = { &paramLatitudeOffset, &paramLongitudeOffset, &paramGeoidUndulation, nullptr}; static const ParamMapping paramVerticalOffset = { EPSG_NAME_PARAMETER_VERTICAL_OFFSET, EPSG_CODE_PARAMETER_VERTICAL_OFFSET, nullptr, common::UnitOfMeasure::Type::LINEAR, nullptr}; static const ParamMapping *const paramsGeographic3DOffsets[] = { &paramLatitudeOffset, &paramLongitudeOffset, &paramVerticalOffset, nullptr}; static const ParamMapping *const paramsVerticalOffsets[] = { &paramVerticalOffset, nullptr}; static const ParamMapping paramLatitudeLongitudeDifferenceFile = { EPSG_NAME_PARAMETER_LATITUDE_LONGITUDE_DIFFERENCE_FILE, EPSG_CODE_PARAMETER_LATITUDE_LONGITUDE_DIFFERENCE_FILE, nullptr, common::UnitOfMeasure::Type::NONE, nullptr}; static const ParamMapping *const paramsNTV2[] = { &paramLatitudeLongitudeDifferenceFile, nullptr}; static const ParamMapping paramGeocentricTranslationFile = { EPSG_NAME_PARAMETER_GEOCENTRIC_TRANSLATION_FILE, EPSG_CODE_PARAMETER_GEOCENTRIC_TRANSLATION_FILE, nullptr, common::UnitOfMeasure::Type::NONE, nullptr}; static const ParamMapping *const paramsGeocentricTranslationGridInterpolationIGN[] = { &paramGeocentricTranslationFile, nullptr}; static const ParamMapping paramLatitudeDifferenceFile = { EPSG_NAME_PARAMETER_LATITUDE_DIFFERENCE_FILE, EPSG_CODE_PARAMETER_LATITUDE_DIFFERENCE_FILE, nullptr, common::UnitOfMeasure::Type::NONE, nullptr}; static const ParamMapping paramLongitudeDifferenceFile = { EPSG_NAME_PARAMETER_LONGITUDE_DIFFERENCE_FILE, EPSG_CODE_PARAMETER_LONGITUDE_DIFFERENCE_FILE, nullptr, common::UnitOfMeasure::Type::NONE, nullptr}; static const ParamMapping *const paramsNADCON[] = { &paramLatitudeDifferenceFile, &paramLongitudeDifferenceFile, nullptr}; static const ParamMapping paramVerticalOffsetFile = { EPSG_NAME_PARAMETER_VERTICAL_OFFSET_FILE, EPSG_CODE_PARAMETER_VERTICAL_OFFSET_FILE, nullptr, common::UnitOfMeasure::Type::NONE, nullptr}; static const ParamMapping *const paramsVERTCON[] = {&paramVerticalOffsetFile, nullptr}; static const ParamMapping paramSouthPoleLatGRIB = { PROJ_WKT2_NAME_PARAMETER_SOUTH_POLE_LATITUDE_GRIB_CONVENTION, 0, nullptr, common::UnitOfMeasure::Type::ANGULAR, nullptr}; static const ParamMapping paramSouthPoleLonGRIB = { PROJ_WKT2_NAME_PARAMETER_SOUTH_POLE_LONGITUDE_GRIB_CONVENTION, 0, nullptr, common::UnitOfMeasure::Type::ANGULAR, nullptr}; static const ParamMapping paramAxisRotationGRIB = { PROJ_WKT2_NAME_PARAMETER_AXIS_ROTATION_GRIB_CONVENTION, 0, nullptr, common::UnitOfMeasure::Type::ANGULAR, nullptr}; static const ParamMapping *const paramsPoleRotationGRIBConvention[] = { &paramSouthPoleLatGRIB, &paramSouthPoleLonGRIB, &paramAxisRotationGRIB, nullptr}; static const MethodMapping otherMethodMappings[] = { {EPSG_NAME_METHOD_CHANGE_VERTICAL_UNIT, EPSG_CODE_METHOD_CHANGE_VERTICAL_UNIT, nullptr, nullptr, nullptr, paramsChangeVerticalUnit}, {EPSG_NAME_METHOD_CHANGE_VERTICAL_UNIT_NO_CONV_FACTOR, EPSG_CODE_METHOD_CHANGE_VERTICAL_UNIT_NO_CONV_FACTOR, nullptr, nullptr, nullptr, nullptr}, {EPSG_NAME_METHOD_HEIGHT_DEPTH_REVERSAL, EPSG_CODE_METHOD_HEIGHT_DEPTH_REVERSAL, nullptr, nullptr, nullptr, nullptr}, {EPSG_NAME_METHOD_AXIS_ORDER_REVERSAL_2D, EPSG_CODE_METHOD_AXIS_ORDER_REVERSAL_2D, nullptr, nullptr, nullptr, nullptr}, {EPSG_NAME_METHOD_AXIS_ORDER_REVERSAL_3D, EPSG_CODE_METHOD_AXIS_ORDER_REVERSAL_3D, nullptr, nullptr, nullptr, nullptr}, {EPSG_NAME_METHOD_GEOGRAPHIC_GEOCENTRIC, EPSG_CODE_METHOD_GEOGRAPHIC_GEOCENTRIC, nullptr, nullptr, nullptr, nullptr}, {EPSG_NAME_METHOD_LONGITUDE_ROTATION, EPSG_CODE_METHOD_LONGITUDE_ROTATION, nullptr, nullptr, nullptr, paramsLongitudeRotation}, {EPSG_NAME_METHOD_AFFINE_PARAMETRIC_TRANSFORMATION, EPSG_CODE_METHOD_AFFINE_PARAMETRIC_TRANSFORMATION, nullptr, nullptr, nullptr, paramsAffineParametricTransformation}, {PROJ_WKT2_NAME_METHOD_POLE_ROTATION_GRIB_CONVENTION, 0, nullptr, nullptr, nullptr, paramsPoleRotationGRIBConvention}, {EPSG_NAME_METHOD_GEOCENTRIC_TRANSLATION_GEOCENTRIC, EPSG_CODE_METHOD_GEOCENTRIC_TRANSLATION_GEOCENTRIC, nullptr, nullptr, nullptr, paramsHelmert3}, {EPSG_NAME_METHOD_GEOCENTRIC_TRANSLATION_GEOGRAPHIC_2D, EPSG_CODE_METHOD_GEOCENTRIC_TRANSLATION_GEOGRAPHIC_2D, nullptr, nullptr, nullptr, paramsHelmert3}, {EPSG_NAME_METHOD_GEOCENTRIC_TRANSLATION_GEOGRAPHIC_3D, EPSG_CODE_METHOD_GEOCENTRIC_TRANSLATION_GEOGRAPHIC_3D, nullptr, nullptr, nullptr, paramsHelmert3}, {EPSG_NAME_METHOD_COORDINATE_FRAME_GEOCENTRIC, EPSG_CODE_METHOD_COORDINATE_FRAME_GEOCENTRIC, nullptr, nullptr, nullptr, paramsHelmert7}, {EPSG_NAME_METHOD_COORDINATE_FRAME_GEOGRAPHIC_2D, EPSG_CODE_METHOD_COORDINATE_FRAME_GEOGRAPHIC_2D, nullptr, nullptr, nullptr, paramsHelmert7}, {EPSG_NAME_METHOD_COORDINATE_FRAME_GEOGRAPHIC_3D, EPSG_CODE_METHOD_COORDINATE_FRAME_GEOGRAPHIC_3D, nullptr, nullptr, nullptr, paramsHelmert7}, {EPSG_NAME_METHOD_POSITION_VECTOR_GEOCENTRIC, EPSG_CODE_METHOD_POSITION_VECTOR_GEOCENTRIC, nullptr, nullptr, nullptr, paramsHelmert7}, {EPSG_NAME_METHOD_POSITION_VECTOR_GEOGRAPHIC_2D, EPSG_CODE_METHOD_POSITION_VECTOR_GEOGRAPHIC_2D, nullptr, nullptr, nullptr, paramsHelmert7}, {EPSG_NAME_METHOD_POSITION_VECTOR_GEOGRAPHIC_3D, EPSG_CODE_METHOD_POSITION_VECTOR_GEOGRAPHIC_3D, nullptr, nullptr, nullptr, paramsHelmert7}, {EPSG_NAME_METHOD_TIME_DEPENDENT_COORDINATE_FRAME_GEOCENTRIC, EPSG_CODE_METHOD_TIME_DEPENDENT_COORDINATE_FRAME_GEOCENTRIC, nullptr, nullptr, nullptr, paramsHelmert15}, {EPSG_NAME_METHOD_TIME_DEPENDENT_COORDINATE_FRAME_GEOGRAPHIC_2D, EPSG_CODE_METHOD_TIME_DEPENDENT_COORDINATE_FRAME_GEOGRAPHIC_2D, nullptr, nullptr, nullptr, paramsHelmert15}, {EPSG_NAME_METHOD_TIME_DEPENDENT_COORDINATE_FRAME_GEOGRAPHIC_3D, EPSG_CODE_METHOD_TIME_DEPENDENT_COORDINATE_FRAME_GEOGRAPHIC_3D, nullptr, nullptr, nullptr, paramsHelmert15}, {EPSG_NAME_METHOD_TIME_DEPENDENT_POSITION_VECTOR_GEOCENTRIC, EPSG_CODE_METHOD_TIME_DEPENDENT_POSITION_VECTOR_GEOCENTRIC, nullptr, nullptr, nullptr, paramsHelmert15}, {EPSG_NAME_METHOD_TIME_DEPENDENT_POSITION_VECTOR_GEOGRAPHIC_2D, EPSG_CODE_METHOD_TIME_DEPENDENT_POSITION_VECTOR_GEOGRAPHIC_2D, nullptr, nullptr, nullptr, paramsHelmert15}, {EPSG_NAME_METHOD_TIME_DEPENDENT_POSITION_VECTOR_GEOGRAPHIC_3D, EPSG_CODE_METHOD_TIME_DEPENDENT_POSITION_VECTOR_GEOGRAPHIC_3D, nullptr, nullptr, nullptr, paramsHelmert15}, {EPSG_NAME_METHOD_MOLODENSKY_BADEKAS_CF_GEOCENTRIC, EPSG_CODE_METHOD_MOLODENSKY_BADEKAS_CF_GEOCENTRIC, nullptr, nullptr, nullptr, paramsMolodenskyBadekas}, {EPSG_NAME_METHOD_MOLODENSKY_BADEKAS_CF_GEOGRAPHIC_2D, EPSG_CODE_METHOD_MOLODENSKY_BADEKAS_CF_GEOGRAPHIC_2D, nullptr, nullptr, nullptr, paramsMolodenskyBadekas}, {EPSG_NAME_METHOD_MOLODENSKY_BADEKAS_CF_GEOGRAPHIC_3D, EPSG_CODE_METHOD_MOLODENSKY_BADEKAS_CF_GEOGRAPHIC_3D, nullptr, nullptr, nullptr, paramsMolodenskyBadekas}, {EPSG_NAME_METHOD_MOLODENSKY_BADEKAS_PV_GEOCENTRIC, EPSG_CODE_METHOD_MOLODENSKY_BADEKAS_PV_GEOCENTRIC, nullptr, nullptr, nullptr, paramsMolodenskyBadekas}, {EPSG_NAME_METHOD_MOLODENSKY_BADEKAS_PV_GEOGRAPHIC_2D, EPSG_CODE_METHOD_MOLODENSKY_BADEKAS_PV_GEOGRAPHIC_2D, nullptr, nullptr, nullptr, paramsMolodenskyBadekas}, {EPSG_NAME_METHOD_MOLODENSKY_BADEKAS_PV_GEOGRAPHIC_3D, EPSG_CODE_METHOD_MOLODENSKY_BADEKAS_PV_GEOGRAPHIC_3D, nullptr, nullptr, nullptr, paramsMolodenskyBadekas}, {EPSG_NAME_METHOD_MOLODENSKY, EPSG_CODE_METHOD_MOLODENSKY, nullptr, nullptr, nullptr, paramsMolodensky}, {EPSG_NAME_METHOD_ABRIDGED_MOLODENSKY, EPSG_CODE_METHOD_ABRIDGED_MOLODENSKY, nullptr, nullptr, nullptr, paramsMolodensky}, {EPSG_NAME_METHOD_GEOGRAPHIC2D_OFFSETS, EPSG_CODE_METHOD_GEOGRAPHIC2D_OFFSETS, nullptr, nullptr, nullptr, paramsGeographic2DOffsets}, {EPSG_NAME_METHOD_GEOGRAPHIC2D_WITH_HEIGHT_OFFSETS, EPSG_CODE_METHOD_GEOGRAPHIC2D_WITH_HEIGHT_OFFSETS, nullptr, nullptr, nullptr, paramsGeographic2DWithHeightOffsets}, {EPSG_NAME_METHOD_GEOGRAPHIC3D_OFFSETS, EPSG_CODE_METHOD_GEOGRAPHIC3D_OFFSETS, nullptr, nullptr, nullptr, paramsGeographic3DOffsets}, {EPSG_NAME_METHOD_VERTICAL_OFFSET, EPSG_CODE_METHOD_VERTICAL_OFFSET, nullptr, nullptr, nullptr, paramsVerticalOffsets}, {EPSG_NAME_METHOD_NTV2, EPSG_CODE_METHOD_NTV2, nullptr, nullptr, nullptr, paramsNTV2}, {EPSG_NAME_METHOD_NTV1, EPSG_CODE_METHOD_NTV1, nullptr, nullptr, nullptr, paramsNTV2}, {EPSG_NAME_METHOD_GEOCENTRIC_TRANSLATION_BY_GRID_INTERPOLATION_IGN, EPSG_CODE_METHOD_GEOCENTRIC_TRANSLATION_BY_GRID_INTERPOLATION_IGN, nullptr, nullptr, nullptr, paramsGeocentricTranslationGridInterpolationIGN}, {EPSG_NAME_METHOD_NADCON, EPSG_CODE_METHOD_NADCON, nullptr, nullptr, nullptr, paramsNADCON}, {EPSG_NAME_METHOD_VERTCON, EPSG_CODE_METHOD_VERTCON, nullptr, nullptr, nullptr, paramsVERTCON}, {EPSG_NAME_METHOD_VERTCON_OLDNAME, EPSG_CODE_METHOD_VERTCON, nullptr, nullptr, nullptr, paramsVERTCON}, }; const MethodMapping *getOtherMethodMappings(size_t &nElts) { nElts = sizeof(otherMethodMappings) / sizeof(otherMethodMappings[0]); return otherMethodMappings; } // --------------------------------------------------------------------------- PROJ_NO_INLINE const MethodMapping *getMapping(int epsg_code) noexcept { for (const auto &mapping : projectionMethodMappings) { if (mapping.epsg_code == epsg_code) { return &mapping; } } return nullptr; } // --------------------------------------------------------------------------- const MethodMapping *getMapping(const OperationMethod *method) noexcept { const std::string &name(method->nameStr()); const int epsg_code = method->getEPSGCode(); for (const auto &mapping : projectionMethodMappings) { if ((epsg_code != 0 && mapping.epsg_code == epsg_code) || metadata::Identifier::isEquivalentName(mapping.wkt2_name, name.c_str())) { return &mapping; } } return nullptr; } // --------------------------------------------------------------------------- const MethodMapping *getMappingFromWKT1(const std::string &wkt1_name) noexcept { // Unusual for a WKT1 projection name, but mentioned in OGC 12-063r5 C.4.2 if (ci_starts_with(wkt1_name, "UTM zone")) { return getMapping(EPSG_CODE_METHOD_TRANSVERSE_MERCATOR); } for (const auto &mapping : projectionMethodMappings) { if (mapping.wkt1_name && metadata::Identifier::isEquivalentName( mapping.wkt1_name, wkt1_name.c_str())) { return &mapping; } } return nullptr; } // --------------------------------------------------------------------------- const MethodMapping *getMapping(const char *wkt2_name) noexcept { for (const auto &mapping : projectionMethodMappings) { if (metadata::Identifier::isEquivalentName(mapping.wkt2_name, wkt2_name)) { return &mapping; } } for (const auto &mapping : otherMethodMappings) { if (metadata::Identifier::isEquivalentName(mapping.wkt2_name, wkt2_name)) { return &mapping; } } return nullptr; } // --------------------------------------------------------------------------- std::vector<const MethodMapping *> getMappingsFromPROJName(const std::string &projName) { std::vector<const MethodMapping *> res; for (const auto &mapping : projectionMethodMappings) { if (mapping.proj_name_main && projName == mapping.proj_name_main) { res.push_back(&mapping); } } return res; } // --------------------------------------------------------------------------- const ParamMapping *getMapping(const MethodMapping *mapping, const OperationParameterNNPtr &param) { if (mapping->params == nullptr) { return nullptr; } // First try with id const int epsg_code = param->getEPSGCode(); if (epsg_code) { for (int i = 0; mapping->params[i] != nullptr; ++i) { const auto *paramMapping = mapping->params[i]; if (paramMapping->epsg_code == epsg_code) { return paramMapping; } } } // then equivalent name const std::string &name = param->nameStr(); for (int i = 0; mapping->params[i] != nullptr; ++i) { const auto *paramMapping = mapping->params[i]; if (metadata::Identifier::isEquivalentName(paramMapping->wkt2_name, name.c_str())) { return paramMapping; } } // and finally different name, but equivalent parameter for (int i = 0; mapping->params[i] != nullptr; ++i) { const auto *paramMapping = mapping->params[i]; if (areEquivalentParameters(paramMapping->wkt2_name, name)) { return paramMapping; } } return nullptr; } // --------------------------------------------------------------------------- const ParamMapping *getMappingFromWKT1(const MethodMapping *mapping, const std::string &wkt1_name) { for (int i = 0; mapping->params[i] != nullptr; ++i) { const auto *paramMapping = mapping->params[i]; if (paramMapping->wkt1_name && (metadata::Identifier::isEquivalentName(paramMapping->wkt1_name, wkt1_name.c_str()) || areEquivalentParameters(paramMapping->wkt1_name, wkt1_name))) { return paramMapping; } } return nullptr; } //! @endcond // --------------------------------------------------------------------------- } // namespace operation NS_PROJ_END
1
12,650
paramsNatOrigin doesn't include sUVtoST. I would just remove that definition for now
OSGeo-PROJ
cpp
@@ -71,9 +71,15 @@ func makeKMD() KeyMetadata { return emptyKeyMetadata{tlf.FakeID(0, tlf.Private), 1} } +func initBlockRetrievalQueueTest(t *testing.T) *blockRetrievalQueue { + q := newBlockRetrievalQueue(0, 0, newTestBlockRetrievalConfig(t, nil, nil)) + <-q.TogglePrefetcher(false, nil) + return q +} + func TestBlockRetrievalQueueBasic(t *testing.T) { t.Log("Add a block retrieval request to the queue and retrieve it.") - q := newBlockRetrievalQueue(0, 0, newTestBlockRetrievalConfig(t, nil, nil)) + q := initBlockRetrievalQueueTest(t) require.NotNil(t, q) defer q.Shutdown()
1
// Copyright 2016 Keybase Inc. All rights reserved. // Use of this source code is governed by a BSD // license that can be found in the LICENSE file. package libkbfs import ( "io" "testing" "github.com/keybase/client/go/protocol/keybase1" "github.com/keybase/kbfs/kbfsblock" "github.com/keybase/kbfs/tlf" "github.com/stretchr/testify/require" "golang.org/x/net/context" ) type testBlockRetrievalConfig struct { codecGetter logMaker testCache BlockCache bg blockGetter *testDiskBlockCacheGetter *testSyncedTlfGetterSetter initModeGetter } func newTestBlockRetrievalConfig(t *testing.T, bg blockGetter, dbc DiskBlockCache) *testBlockRetrievalConfig { return &testBlockRetrievalConfig{ newTestCodecGetter(), newTestLogMaker(t), NewBlockCacheStandard(10, getDefaultCleanBlockCacheCapacity()), bg, newTestDiskBlockCacheGetter(t, dbc), newTestSyncedTlfGetterSetter(), testInitModeGetter{InitDefault}, } } func (c *testBlockRetrievalConfig) BlockCache() BlockCache { return c.testCache } func (c testBlockRetrievalConfig) DataVersion() DataVer { return ChildHolesDataVer } func (c testBlockRetrievalConfig) blockGetter() blockGetter { return c.bg } func makeRandomBlockPointer(t *testing.T) BlockPointer { id, err := kbfsblock.MakeTemporaryID() require.NoError(t, err) return BlockPointer{ id, 5, 1, DirectBlock, kbfsblock.MakeContext( "fake creator", "fake writer", kbfsblock.RefNonce{0xb}, keybase1.BlockType_DATA, ), } } func makeKMD() KeyMetadata { return emptyKeyMetadata{tlf.FakeID(0, tlf.Private), 1} } func TestBlockRetrievalQueueBasic(t *testing.T) { t.Log("Add a block retrieval request to the queue and retrieve it.") q := newBlockRetrievalQueue(0, 0, newTestBlockRetrievalConfig(t, nil, nil)) require.NotNil(t, q) defer q.Shutdown() ctx := context.Background() ptr1 := makeRandomBlockPointer(t) block := &FileBlock{} t.Log("Request a block retrieval for ptr1.") _ = q.Request(ctx, defaultOnDemandRequestPriority, makeKMD(), ptr1, block, NoCacheEntry) t.Log("Begin working on the request.") br := q.popIfNotEmpty() defer q.FinalizeRequest(br, &FileBlock{}, io.EOF) require.Equal(t, ptr1, br.blockPtr) require.Equal(t, -1, br.index) require.Equal(t, defaultOnDemandRequestPriority, br.priority) require.Equal(t, uint64(0), br.insertionOrder) require.Len(t, br.requests, 1) require.Equal(t, block, br.requests[0].block) } func TestBlockRetrievalQueuePreemptPriority(t *testing.T) { t.Log("Preempt a lower-priority block retrieval request with a higher " + "priority request.") q := newBlockRetrievalQueue(0, 0, newTestBlockRetrievalConfig(t, nil, nil)) require.NotNil(t, q) defer q.Shutdown() ctx := context.Background() ptr1 := makeRandomBlockPointer(t) ptr2 := makeRandomBlockPointer(t) block := &FileBlock{} t.Log("Request a block retrieval for ptr1 and a higher priority " + "retrieval for ptr2.") _ = q.Request(ctx, defaultOnDemandRequestPriority, makeKMD(), ptr1, block, NoCacheEntry) _ = q.Request(ctx, defaultOnDemandRequestPriority+1, makeKMD(), ptr2, block, NoCacheEntry) t.Log("Begin working on the preempted ptr2 request.") br := q.popIfNotEmpty() defer q.FinalizeRequest(br, &FileBlock{}, io.EOF) require.Equal(t, ptr2, br.blockPtr) require.Equal(t, defaultOnDemandRequestPriority+1, br.priority) require.Equal(t, uint64(1), br.insertionOrder) t.Log("Begin working on the ptr1 request.") br = q.popIfNotEmpty() defer q.FinalizeRequest(br, &FileBlock{}, io.EOF) require.Equal(t, ptr1, br.blockPtr) require.Equal(t, defaultOnDemandRequestPriority, br.priority) require.Equal(t, uint64(0), br.insertionOrder) } func TestBlockRetrievalQueueInterleavedPreemption(t *testing.T) { t.Log("Handle a first request and then preempt another one.") q := newBlockRetrievalQueue(0, 0, newTestBlockRetrievalConfig(t, nil, nil)) require.NotNil(t, q) defer q.Shutdown() ctx := context.Background() ptr1 := makeRandomBlockPointer(t) ptr2 := makeRandomBlockPointer(t) block := &FileBlock{} t.Log("Request a block retrieval for ptr1 and ptr2.") _ = q.Request(ctx, defaultOnDemandRequestPriority, makeKMD(), ptr1, block, NoCacheEntry) _ = q.Request(ctx, defaultOnDemandRequestPriority, makeKMD(), ptr2, block, NoCacheEntry) t.Log("Begin working on the ptr1 request.") br := q.popIfNotEmpty() defer q.FinalizeRequest(br, &FileBlock{}, io.EOF) require.Equal(t, ptr1, br.blockPtr) require.Equal(t, defaultOnDemandRequestPriority, br.priority) require.Equal(t, uint64(0), br.insertionOrder) ptr3 := makeRandomBlockPointer(t) t.Log("Preempt the ptr2 request with the ptr3 request.") _ = q.Request(ctx, defaultOnDemandRequestPriority+1, makeKMD(), ptr3, block, NoCacheEntry) t.Log("Begin working on the ptr3 request.") br = q.popIfNotEmpty() defer q.FinalizeRequest(br, &FileBlock{}, io.EOF) require.Equal(t, ptr3, br.blockPtr) require.Equal(t, defaultOnDemandRequestPriority+1, br.priority) require.Equal(t, uint64(2), br.insertionOrder) t.Log("Begin working on the ptr2 request.") br = q.popIfNotEmpty() defer q.FinalizeRequest(br, &FileBlock{}, io.EOF) require.Equal(t, ptr2, br.blockPtr) require.Equal(t, defaultOnDemandRequestPriority, br.priority) require.Equal(t, uint64(1), br.insertionOrder) } func TestBlockRetrievalQueueMultipleRequestsSameBlock(t *testing.T) { t.Log("Request the same block multiple times.") q := newBlockRetrievalQueue(0, 0, newTestBlockRetrievalConfig(t, nil, nil)) require.NotNil(t, q) defer q.Shutdown() ctx := context.Background() ptr1 := makeRandomBlockPointer(t) block := &FileBlock{} t.Log("Request a block retrieval for ptr1 twice.") _ = q.Request(ctx, defaultOnDemandRequestPriority, makeKMD(), ptr1, block, NoCacheEntry) _ = q.Request(ctx, defaultOnDemandRequestPriority, makeKMD(), ptr1, block, NoCacheEntry) t.Log("Begin working on the ptr1 retrieval. Verify that it has 2 requests and that the queue is now empty.") br := q.popIfNotEmpty() defer q.FinalizeRequest(br, &FileBlock{}, io.EOF) require.Equal(t, ptr1, br.blockPtr) require.Equal(t, -1, br.index) require.Equal(t, defaultOnDemandRequestPriority, br.priority) require.Equal(t, uint64(0), br.insertionOrder) require.Len(t, br.requests, 2) require.Len(t, *q.heap, 0) require.Equal(t, block, br.requests[0].block) require.Equal(t, block, br.requests[1].block) } func TestBlockRetrievalQueueElevatePriorityExistingRequest(t *testing.T) { t.Log("Elevate the priority on an existing request.") q := newBlockRetrievalQueue(0, 0, newTestBlockRetrievalConfig(t, nil, nil)) require.NotNil(t, q) defer q.Shutdown() ctx := context.Background() ptr1 := makeRandomBlockPointer(t) ptr2 := makeRandomBlockPointer(t) ptr3 := makeRandomBlockPointer(t) block := &FileBlock{} t.Log("Request 3 block retrievals, each preempting the previous one.") _ = q.Request(ctx, defaultOnDemandRequestPriority, makeKMD(), ptr1, block, NoCacheEntry) _ = q.Request(ctx, defaultOnDemandRequestPriority+1, makeKMD(), ptr2, block, NoCacheEntry) _ = q.Request(ctx, defaultOnDemandRequestPriority+2, makeKMD(), ptr3, block, NoCacheEntry) t.Log("Begin working on the ptr3 retrieval.") br := q.popIfNotEmpty() defer q.FinalizeRequest(br, &FileBlock{}, io.EOF) require.Equal(t, ptr3, br.blockPtr) require.Equal(t, defaultOnDemandRequestPriority+2, br.priority) require.Equal(t, uint64(2), br.insertionOrder) t.Log("Preempt the remaining retrievals with another retrieval for ptr1.") _ = q.Request(ctx, defaultOnDemandRequestPriority+2, makeKMD(), ptr1, block, NoCacheEntry) t.Log("Begin working on the ptr1 retrieval. Verify that it has increased in priority and has 2 requests.") br = q.popIfNotEmpty() defer q.FinalizeRequest(br, &FileBlock{}, io.EOF) require.Equal(t, ptr1, br.blockPtr) require.Equal(t, defaultOnDemandRequestPriority+2, br.priority) require.Equal(t, uint64(0), br.insertionOrder) require.Len(t, br.requests, 2) t.Log("Begin working on the ptr2 retrieval.") br = q.popIfNotEmpty() defer q.FinalizeRequest(br, &FileBlock{}, io.EOF) require.Equal(t, ptr2, br.blockPtr) require.Equal(t, defaultOnDemandRequestPriority+1, br.priority) require.Equal(t, uint64(1), br.insertionOrder) } func TestBlockRetrievalQueueCurrentlyProcessingRequest(t *testing.T) { t.Log("Begin processing a request and then add another one for the same block.") q := newBlockRetrievalQueue(0, 0, newTestBlockRetrievalConfig(t, nil, nil)) require.NotNil(t, q) defer q.Shutdown() ctx := context.Background() ptr1 := makeRandomBlockPointer(t) block := &FileBlock{} t.Log("Request a block retrieval for ptr1.") _ = q.Request(ctx, defaultOnDemandRequestPriority, makeKMD(), ptr1, block, NoCacheEntry) t.Log("Begin working on the ptr1 retrieval. Verify that it has 1 request.") br := q.popIfNotEmpty() require.Equal(t, ptr1, br.blockPtr) require.Equal(t, -1, br.index) require.Equal(t, defaultOnDemandRequestPriority, br.priority) require.Equal(t, uint64(0), br.insertionOrder) require.Len(t, br.requests, 1) require.Equal(t, block, br.requests[0].block) t.Log("Request another block retrieval for ptr1 before it has finished. " + "Verify that the priority has elevated and there are now 2 requests.") _ = q.Request(ctx, defaultOnDemandRequestPriority+1, makeKMD(), ptr1, block, NoCacheEntry) require.Equal(t, defaultOnDemandRequestPriority+1, br.priority) require.Equal(t, uint64(0), br.insertionOrder) require.Len(t, br.requests, 2) require.Equal(t, block, br.requests[0].block) require.Equal(t, block, br.requests[1].block) t.Log("Finalize the existing request for ptr1.") q.FinalizeRequest(br, &FileBlock{}, nil) t.Log("Make another request for the same block. Verify that this is a new request.") _ = q.Request(ctx, defaultOnDemandRequestPriority+1, makeKMD(), ptr1, block, NoCacheEntry) br = q.popIfNotEmpty() defer q.FinalizeRequest(br, &FileBlock{}, io.EOF) require.Equal(t, defaultOnDemandRequestPriority+1, br.priority) require.Equal(t, uint64(1), br.insertionOrder) require.Len(t, br.requests, 1) require.Equal(t, block, br.requests[0].block) }
1
18,651
It feels like the test should be waiting for the prefetcher to shut down, but I don't have a great reason why other than that it might be confusing for debugging if there are still goroutines from old prefetchers lying. But I guess since `TogglePrefetcher(false)` doesn't actually set the prefetcher to nil, the queue shutdown method will still end up waiting for the shutdown to finish. If that sounds right, nevermind me.
keybase-kbfs
go
@@ -1,4 +1,4 @@ -//snippet-sourcedescription:[ListAccessKeys.java demonstrates how to list access keys associated with an AWS Identity and Access Management (IAM) user.] +//snippet-sourcedescription:[ListAccessKeys.java demonstrates how to list access keys associated with an AWS Identity and Access Management (AWS IAM) user.] //snippet-keyword:[AWS SDK for Java v2] //snippet-keyword:[Code Sample] //snippet-service:[AWS IAM]
1
//snippet-sourcedescription:[ListAccessKeys.java demonstrates how to list access keys associated with an AWS Identity and Access Management (IAM) user.] //snippet-keyword:[AWS SDK for Java v2] //snippet-keyword:[Code Sample] //snippet-service:[AWS IAM] //snippet-sourcetype:[full-example] //snippet-sourcedate:[11/02/2020] //snippet-sourceauthor:[scmacdon-aws] /* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package com.example.iam; // snippet-start:[iam.java2.list_access_keys.import] import software.amazon.awssdk.services.iam.model.AccessKeyMetadata; import software.amazon.awssdk.services.iam.model.IamException; import software.amazon.awssdk.services.iam.model.ListAccessKeysRequest; import software.amazon.awssdk.services.iam.model.ListAccessKeysResponse; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.iam.IamClient; // snippet-end:[iam.java2.list_access_keys.import] public class ListAccessKeys { public static void main(String[] args) { final String USAGE = "\n" + "Usage:\n" + " ListAccessKeys <userName> \n\n" + "Where:\n" + " userName - the name of the user for which access keys are retrieved. \n\n" ; if (args.length != 1) { System.out.println(USAGE); System.exit(1); } // Read the command line argument String userName = args[0]; Region region = Region.AWS_GLOBAL; IamClient iam = IamClient.builder() .region(region) .build(); listKeys(iam,userName) ; System.out.println("Done"); iam.close(); } // snippet-start:[iam.java2.list_access_keys.main] public static void listKeys( IamClient iam,String userName ){ try { boolean done = false; String newMarker = null; while (!done) { ListAccessKeysResponse response; if(newMarker == null) { ListAccessKeysRequest request = ListAccessKeysRequest.builder() .userName(userName).build(); response = iam.listAccessKeys(request); } else { ListAccessKeysRequest request = ListAccessKeysRequest.builder() .userName(userName) .marker(newMarker).build(); response = iam.listAccessKeys(request); } for (AccessKeyMetadata metadata : response.accessKeyMetadata()) { System.out.format("Retrieved access key %s", metadata.accessKeyId()); } if (!response.isTruncated()) { done = true; } else { newMarker = response.marker(); } } } catch (IamException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } // snippet-end:[iam.java2.list_access_keys.main] } }
1
18,247
AWS Identity and Access Management (IAM)
awsdocs-aws-doc-sdk-examples
rb
@@ -34,6 +34,7 @@ class LoadProjectsCloudsqlPipeline(base_pipeline.BasePipeline): """Pipeline to load project CloudSql data into Inventory.""" PROJECTS_RESOURCE_NAME = 'project_iam_policies' + RESOURCE_NAME = 'cloudsql' RESOURCE_NAME_INSTANCES = 'cloudsql_instances' RESOURCE_NAME_IPADDRESSES = 'cloudsql_ipaddresses' RESOURCE_NAME_AUTHORIZEDNETWORKS = ( # pylint: disable=invalid-name
1
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Pipeline to load project cloudsql data into Inventory.""" import json from dateutil import parser as dateutil_parser # pylint: disable=line-too-long from google.cloud.security.common.data_access import errors as data_access_errors from google.cloud.security.common.gcp_api import errors as api_errors from google.cloud.security.common.util import log_util from google.cloud.security.inventory import errors as inventory_errors from google.cloud.security.inventory.pipelines import base_pipeline # pylint: enable=line-too-long LOGGER = log_util.get_logger(__name__) class LoadProjectsCloudsqlPipeline(base_pipeline.BasePipeline): """Pipeline to load project CloudSql data into Inventory.""" PROJECTS_RESOURCE_NAME = 'project_iam_policies' RESOURCE_NAME_INSTANCES = 'cloudsql_instances' RESOURCE_NAME_IPADDRESSES = 'cloudsql_ipaddresses' RESOURCE_NAME_AUTHORIZEDNETWORKS = ( # pylint: disable=invalid-name 'cloudsql_ipconfiguration_authorizednetworks') MYSQL_DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S' def __init__(self, cycle_timestamp, configs, sqladmin_client, dao): """Constructor for the data pipeline. Args: cycle_timestamp: String of timestamp, formatted as YYYYMMDDTHHMMSSZ. configs: Dictionary of configurations. gcs_client: GCS API client. dao: Data access object. Returns: None """ super(LoadProjectsCloudsqlPipeline, self).__init__( cycle_timestamp, configs, sqladmin_client, dao) @staticmethod def _transform_data(cloudsql_instances_map): """Yield an iterator of loadable instances. Args: cloudsql_instnces_maps: An iterable of instances as per-project dictionary. Example: {'project_number': 11111, 'instances': instances_dict} Yields: An iterable of instances dictionary. """ for instances_map in cloudsql_instances_map: instances = instances_map['instances'] items = instances.get('items', []) for item in items: yield { 'project_number': instances_map['project_number'], 'name': item.get('name'), 'project': item.get('project'), 'backend_type': item.get('backendType'), 'connection_name': item.get('connectionName'), 'current_disk_size': int(item.get('currentDiskSize', 0)), 'database_version': item.get('databaseVersion'), 'failover_replica_available':\ item.get('failoverReplica', {}).get('available'), 'failover_replica_name':\ item.get('failoverReplica', {}).get('name'), 'instance_type': item.get('instanceType'), 'ipv6_address': item.get('ipv6Address'), 'kind': item.get('kind'), 'master_instance_name': item.get('masterInstanceName'), 'max_disk_size': int(item.get('maxDiskSize', 0)), 'on_premises_configuration_host_port':\ item.get('onPremisesConfiguration', {})\ .get('hostPort'), 'on_premises_configuration_kind':\ item.get('onPremisesConfiguration', {}).get('kind'), 'region': item.get('region'), 'replica_configuration':\ json.dumps(item.get('replicaConfiguration')), 'replica_names': json.dumps(item.get('replicaNames')), 'self_link': item.get('selfLink'), 'server_ca_cert': json.dumps(item.get('serverCaCert')), 'service_account_email_address':\ item.get('serviceAccountEmailAddress'), 'settings_activation_policy':\ item.get('settings', {}).get('activationPolicy'), 'settings_authorized_gae_applications':\ json.dumps(item.get('settings', {})\ .get('authorizedGaeApplications')), 'settings_availability_type':\ item.get('settings', {}).get('availabilityType'), 'settings_backup_configuration_binary_log_enabled':\ item.get('settings', {})\ .get('backupConfiguration', {})\ .get('binaryLogEnabled'), 'settings_backup_configuration_enabled':\ item.get('settings', {})\ .get('backupConfiguration', {}).get('enabled'), 'settings_backup_configuration_kind':\ item.get('settings', {})\ .get('backupConfiguration', {}).get('kind'), 'settings_backup_configuration_start_time':\ item.get('settings', {})\ .get('backupConfiguration', {}).get('startTime'), 'settings_crash_safe_replication_enabled':\ item.get('settings', {})\ .get('crashSafeReplicationEnabled'), 'settings_data_disk_size_gb':\ int(item.get('settings', {}).get('dataDiskSizeGb', 0)), 'settings_data_disk_type': item.get('settings', {}).get('dataDiskType'), 'settings_database_flags': json.dumps(item.get('settings', {})\ .get('databaseFlags')), 'settings_database_replication_enabled': item.get('settings', {})\ .get('databaseReplicationEnabled', {}), 'settings_ip_configuration_ipv4_enabled': item.get('settings', {}).get('ipConfiguration', {})\ .get('ipv4Enabled', {}), 'settings_ip_configuration_require_ssl': item.get('settings', {}).get('ipConfiguration', {})\ .get('requireSsl', {}), 'settings_kind': item.get('settings', {}).get('kind'), 'settings_labels': json.dumps(item.get('settings', {}).get('labels')), 'settings_location_preference_follow_gae_application':\ item.get('settings', {}).get('locationPreference', {})\ .get('followGaeApplication'), 'settings_location_preference_kind':\ item.get('settings', {}).get('locationPreference', {})\ .get('kind'), 'settings_location_preference_zone':\ item.get('settings', {}).get('locationPreference', {})\ .get('zone'), 'settings_maintenance_window':\ json.dumps(item.get('settings', {})\ .get('maintenanceWindow')), 'settings_pricing_plan':\ item.get('settings', {}).get('pricingPlan'), 'settings_replication_type':\ item.get('settings', {}).get('replicationType'), 'settings_settings_version':\ int(item.get('settings', {}).get('settingsVersion', 0)), 'settings_storage_auto_resize':\ item.get('settings', {}).get('storageAutoResize'), 'settings_storage_auto_resize_limit':\ int(item.get('settings', {})\ .get('storageAutoResizeLimit', 0)), 'settings_tier': item.get('settings', {}).get('tier'), 'state': item.get('state'), 'suspension_reason': \ json.dumps(item.get('suspensionReason')), } def _transform_authorizednetworks(self, cloudsql_instances_map): """Yield an iterator of loadable authorized networks of cloudsql instances. Args: cloudsql_instnces_maps: An iterable of instances as per-project dictionary. Example: {'project_number': 11111, 'instances': instances_dict} Yields: An iterable of authorized network dictionary. """ for instances_map in cloudsql_instances_map: instances = instances_map['instances'] items = instances.get('items', []) for item in items: authorizednetworks = item.get('settings', {})\ .get('ipConfiguration', {}).get('authorizedNetworks', [{}]) for network in authorizednetworks: if network.get('expirationTime') is not None: try: parsed_time = dateutil_parser\ .parse(network.get('expirationTime')) formatted_expirationtime = ( parsed_time\ .strftime(self.MYSQL_DATETIME_FORMAT)) except (TypeError, ValueError, AttributeError) as e: LOGGER.error( 'Unable to parse timeCreated' +\ 'from authorizednetworks: %s\n%s', network.get('expirationTime', ''), e) formatted_expirationtime = '1972-01-01 00:00:00' else: formatted_expirationtime = '1972-01-01 00:00:00' yield { 'project_number': instances_map['project_number'], 'instance_name': item.get('name'), 'kind': network.get('kind'), 'name': network.get('name'), 'value': network.get('value'), 'expiration_time': formatted_expirationtime } def _transform_ipaddresses(self, cloudsql_instances_map): """Yield an iterator of loadable ipAddresses of cloudsql instances. Args: cloudsql_instances_maps: An iterable of instances as per-project dictionary. Example: {'project_number': 11111, 'instances': instances_dict} Yields: An iterable of ipAddresses dictionary. """ for instances_map in cloudsql_instances_map: instances = instances_map['instances'] items = instances.get('items', []) for item in items: ipaddresses = item.get('ipAddresses', [{}]) for ipaddress in ipaddresses: if ipaddress.get('timeToRetire') is not None: try: parsed_time = dateutil_parser\ .parse(ipaddress.get('timeToRetire')) formatted_timetoretire = ( parsed_time\ .strftime(self.MYSQL_DATETIME_FORMAT)) except (TypeError, ValueError, AttributeError) as e: LOGGER.error( 'Unable to parse timeCreated' +\ ' from ipaddresses: %s\n%s', ipaddress.get('timeToRetire', ''), e) formatted_timetoretire = '1972-01-01 00:00:00' else: formatted_timetoretire = '1972-01-01 00:00:00' yield { 'project_number': instances_map['project_number'], 'instance_name': item.get('name'), 'ip_address': ipaddress.get('ipAddress'), 'type': ipaddress.get('type'), 'time_to_retire': formatted_timetoretire } # pylint: disable=arguments-differ def _transform(self, cloudsql_instances_map): """returns a dictionary of generators for a different types of resources Args: cloudsql_instnces_maps: An iterable of instances as per-project dictionary. Example: {'project_number': 11111, 'instances': instances_dict} Returns: A dict of iterables as a per resource type """ data_dict = {} data_dict[self.RESOURCE_NAME_INSTANCES] = \ self._transform_data(cloudsql_instances_map) data_dict[self.RESOURCE_NAME_AUTHORIZEDNETWORKS] = \ self._transform_authorizednetworks(cloudsql_instances_map) data_dict[self.RESOURCE_NAME_IPADDRESSES] = \ self._transform_ipaddresses(cloudsql_instances_map) return data_dict def _retrieve(self): """Retrieve the project cloudsql instances from GCP. Args: None Returns: instances_maps: List of instances as per-project dictionary. Example: [{project_number: project_number, instances: instances_dict}] Raises: LoadDataPipelineException: An error with loading data has occurred. """ # Get the projects for which we will retrieve the instances. try: project_numbers = self.dao.get_project_numbers( self.PROJECTS_RESOURCE_NAME, self.cycle_timestamp) except data_access_errors.MySQLError as e: raise inventory_errors.LoadDataPipelineError(e) instances_maps = [] for project_number in project_numbers: try: instances = self.api_client.get_instances( project_number) instances_map = {'project_number': project_number, 'instances': instances} instances_maps.append(instances_map) except api_errors.ApiExecutionError as e: LOGGER.error( 'Unable to get cloudsql instances for project %s:\n%s', project_number, e) return instances_maps def _get_loaded_count(self): """Get the count of how many of a instances has been loaded.""" try: self.count = self.dao.select_record_count( self.RESOURCE_NAME_INSTANCES, self.cycle_timestamp) except data_access_errors.MySQLError as e: LOGGER.error('Unable to retrieve record count for %s_%s:\n%s', self.RESOURCE_NAME_INSTANCES, self.cycle_timestamp, e) def run(self): """Runs the load Cloudsql data pipeline.""" instances_maps = self._retrieve() loadable_instances_dict = self._transform(instances_maps) self._load(self.RESOURCE_NAME_INSTANCES, \ loadable_instances_dict[self.RESOURCE_NAME_INSTANCES]) self._load(self.RESOURCE_NAME_IPADDRESSES, \ loadable_instances_dict[self.RESOURCE_NAME_IPADDRESSES]) self._load(self.RESOURCE_NAME_AUTHORIZEDNETWORKS, \ loadable_instances_dict[ self.RESOURCE_NAME_AUTHORIZEDNETWORKS ]) self._get_loaded_count()
1
26,092
As a long term thing, would it make sense to move the resource names as keys under the requirements map?
forseti-security-forseti-security
py
@@ -57,7 +57,7 @@ function traverseForHeaders(headerType, position, tableGrid) { * @return {Array<HTMLTableCellElement>} Array of headers associated to the table cell */ table.getHeaders = function(cell, tableGrid) { - if (cell.hasAttribute('headers')) { + if (cell.getAttribute('headers')) { return commons.dom.idrefs(cell, 'headers'); } if (!tableGrid) {
1
/* global table */ /** * Loop through the table grid looking for headers and caching the result. * @param {String} headerType The type of header to look for ("row" or "col") * @param {Object} position The position of the cell to start looking * @param {Array} tablegrid A matrix of the table obtained using axe.commons.table.toGrid * @return {Array<HTMLTableCellElement>} Array of HTMLTableCellElements that are headers */ function traverseForHeaders(headerType, position, tableGrid) { const property = headerType === 'row' ? '_rowHeaders' : '_colHeaders'; const predicate = headerType === 'row' ? table.isRowHeader : table.isColumnHeader; const rowEnd = headerType === 'row' ? position.y : 0; const colEnd = headerType === 'row' ? 0 : position.x; let headers; const cells = []; for (let row = position.y; row >= rowEnd && !headers; row--) { for (let col = position.x; col >= colEnd; col--) { const cell = tableGrid[row] ? tableGrid[row][col] : undefined; if (!cell) { continue; } // stop traversing once we've found a cache const vNode = axe.utils.getNodeFromTree(cell); if (vNode[property]) { headers = vNode[property]; break; } cells.push(cell); } } // need to check that the cells we've traversed are headers headers = (headers || []).concat(cells.filter(predicate)); // cache results cells.forEach(tableCell => { const vNode = axe.utils.getNodeFromTree(tableCell); vNode[property] = headers; }); return headers; } /** * Get any associated table headers for a `HTMLTableCellElement` * @method getHeaders * @memberof axe.commons.table * @instance * @param {HTMLTableCellElement} cell The cell of which to get headers * @param {Array} [tablegrid] A matrix of the table obtained using axe.commons.table.toGrid * @return {Array<HTMLTableCellElement>} Array of headers associated to the table cell */ table.getHeaders = function(cell, tableGrid) { if (cell.hasAttribute('headers')) { return commons.dom.idrefs(cell, 'headers'); } if (!tableGrid) { tableGrid = commons.table.toGrid(commons.dom.findUp(cell, 'table')); } const position = commons.table.getCellPosition(cell, tableGrid); // TODO: RTL text const rowHeaders = traverseForHeaders('row', position, tableGrid); const colHeaders = traverseForHeaders('col', position, tableGrid); return [].concat(rowHeaders, colHeaders).reverse(); };
1
15,376
That doesn't fix the whole problem. The issue lays in this line right here, not the one above. There are two problems with this line: 1. It finds things that aren't cells in the table 2. if it doesn't find anything, it shouldn't return empty here, but continue down to look for row/ column headers.
dequelabs-axe-core
js
@@ -38,7 +38,9 @@ public class NoUnusedPinCheckTask extends DefaultTask { @Input public final Set<String> getResolvedArtifacts() { - return BaselineVersions.getResolvedArtifacts(getProject()); + return getProject().getAllprojects().stream() + .flatMap(project -> BaselineVersions.getResolvedArtifacts(project).stream()) + .collect(Collectors.toSet()); } @InputFile
1
/* * (c) Copyright 2018 Palantir Technologies Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.palantir.baseline.plugins; import java.io.File; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import javax.inject.Inject; import org.apache.commons.lang3.tuple.Pair; import org.gradle.api.DefaultTask; import org.gradle.api.tasks.Input; import org.gradle.api.tasks.InputFile; import org.gradle.api.tasks.TaskAction; public class NoUnusedPinCheckTask extends DefaultTask { private final File propsFile; @Inject public NoUnusedPinCheckTask(File propsFile) { this.propsFile = propsFile; } @Input public final Set<String> getResolvedArtifacts() { return BaselineVersions.getResolvedArtifacts(getProject()); } @InputFile public final File getPropsFile() { return propsFile; } @TaskAction public final void checkNoUnusedPin() { Set<String> artifacts = getResolvedArtifacts(); List<String> unusedProps = VersionsPropsReader.readVersionsProps(getPropsFile()).stream() .map(Pair::getLeft) .filter(propName -> { String regex = propName.replaceAll("\\*", ".*"); return artifacts.stream().noneMatch(artifact -> artifact.matches(regex)); }) .collect(Collectors.toList()); if (!unusedProps.isEmpty()) { String unusedPropsString = String.join("\n", unusedProps); throw new RuntimeException("There are unused pins in your versions.props: \n" + unusedPropsString); } } }
1
6,651
I am pretty sure that this is infinite recursion as getAllProjects returns the project itself.
palantir-gradle-baseline
java
@@ -268,6 +268,7 @@ Blockly.Categories = { "sound": "sounds", "pen": "pen", "data": "data", + "dataLists": "data-lists", "event": "events", "control": "control", "sensing": "sensing",
1
/** * @license * Visual Blocks Editor * * Copyright 2016 Google Inc. * https://developers.google.com/blockly/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Blockly constants. * @author [email protected] (Rachel Fenichel) */ 'use strict'; goog.provide('Blockly.constants'); /** * Number of pixels the mouse must move before a drag starts. */ Blockly.DRAG_RADIUS = 3; /** * Number of pixels the mouse must move before a drag/scroll starts from the * flyout. Because the drag-intention is determined when this is reached, it is * larger than Blockly.DRAG_RADIUS so that the drag-direction is clearer. */ Blockly.FLYOUT_DRAG_RADIUS = 10; /** * Maximum misalignment between connections for them to snap together. */ Blockly.SNAP_RADIUS = 48; /** * Maximum misalignment between connections for them to snap together, * when a connection is already highlighted. */ Blockly.CONNECTING_SNAP_RADIUS = 68; /** * How much to prefer staying connected to the current connection over moving to * a new connection. The current previewed connection is considered to be this * much closer to the matching connection on the block than it actually is. */ Blockly.CURRENT_CONNECTION_PREFERENCE = 20; /** * Delay in ms between trigger and bumping unconnected block out of alignment. */ Blockly.BUMP_DELAY = 0; /** * Number of characters to truncate a collapsed block to. */ Blockly.COLLAPSE_CHARS = 30; /** * Length in ms for a touch to become a long press. */ Blockly.LONGPRESS = 750; /** * Prevent a sound from playing if another sound preceded it within this many * milliseconds. */ Blockly.SOUND_LIMIT = 100; /** * When dragging a block out of a stack, split the stack in two (true), or drag * out the block healing the stack (false). */ Blockly.DRAG_STACK = true; /** * The richness of block colours, regardless of the hue. * Must be in the range of 0 (inclusive) to 1 (exclusive). */ Blockly.HSV_SATURATION = 0.45; /** * The intensity of block colours, regardless of the hue. * Must be in the range of 0 (inclusive) to 1 (exclusive). */ Blockly.HSV_VALUE = 0.65; /** * Sprited icons and images. */ Blockly.SPRITE = { width: 96, height: 124, url: 'sprites.png' }; // Constants below this point are not intended to be changed. /** * Required name space for SVG elements. * @const */ Blockly.SVG_NS = 'http://www.w3.org/2000/svg'; /** * Required name space for HTML elements. * @const */ Blockly.HTML_NS = 'http://www.w3.org/1999/xhtml'; /** * ENUM for a right-facing value input. E.g. 'set item to' or 'return'. * @const */ Blockly.INPUT_VALUE = 1; /** * ENUM for a left-facing value output. E.g. 'random fraction'. * @const */ Blockly.OUTPUT_VALUE = 2; /** * ENUM for a down-facing block stack. E.g. 'if-do' or 'else'. * @const */ Blockly.NEXT_STATEMENT = 3; /** * ENUM for an up-facing block stack. E.g. 'break out of loop'. * @const */ Blockly.PREVIOUS_STATEMENT = 4; /** * ENUM for an dummy input. Used to add field(s) with no input. * @const */ Blockly.DUMMY_INPUT = 5; /** * ENUM for left alignment. * @const */ Blockly.ALIGN_LEFT = -1; /** * ENUM for centre alignment. * @const */ Blockly.ALIGN_CENTRE = 0; /** * ENUM for right alignment. * @const */ Blockly.ALIGN_RIGHT = 1; /** * ENUM for no drag operation. * @const */ Blockly.DRAG_NONE = 0; /** * ENUM for inside the sticky DRAG_RADIUS. * @const */ Blockly.DRAG_STICKY = 1; /** * ENUM for inside the non-sticky DRAG_RADIUS, for differentiating between * clicks and drags. * @const */ Blockly.DRAG_BEGIN = 1; /** * ENUM for freely draggable (outside the DRAG_RADIUS, if one applies). * @const */ Blockly.DRAG_FREE = 2; /** * Lookup table for determining the opposite type of a connection. * @const */ Blockly.OPPOSITE_TYPE = []; Blockly.OPPOSITE_TYPE[Blockly.INPUT_VALUE] = Blockly.OUTPUT_VALUE; Blockly.OPPOSITE_TYPE[Blockly.OUTPUT_VALUE] = Blockly.INPUT_VALUE; Blockly.OPPOSITE_TYPE[Blockly.NEXT_STATEMENT] = Blockly.PREVIOUS_STATEMENT; Blockly.OPPOSITE_TYPE[Blockly.PREVIOUS_STATEMENT] = Blockly.NEXT_STATEMENT; /** * ENUM for toolbox and flyout at top of screen. * @const */ Blockly.TOOLBOX_AT_TOP = 0; /** * ENUM for toolbox and flyout at bottom of screen. * @const */ Blockly.TOOLBOX_AT_BOTTOM = 1; /** * ENUM for toolbox and flyout at left of screen. * @const */ Blockly.TOOLBOX_AT_LEFT = 2; /** * ENUM for toolbox and flyout at right of screen. * @const */ Blockly.TOOLBOX_AT_RIGHT = 3; /** * ENUM for output shape: hexagonal (booleans/predicates). * @const */ Blockly.OUTPUT_SHAPE_HEXAGONAL = 1; /** * ENUM for output shape: rounded (numbers). * @const */ Blockly.OUTPUT_SHAPE_ROUND = 2; /** * ENUM for output shape: squared (any/all values; strings). * @const */ Blockly.OUTPUT_SHAPE_SQUARE = 3; /** * Radius of stack glow, in px. * @type {number} * @const */ Blockly.STACK_GLOW_RADIUS = 1.3; /** * Radius of replacement glow, in px. * @type {number} * @const */ Blockly.REPLACEMENT_GLOW_RADIUS = 2; /** * ENUM for categories. * @const */ Blockly.Categories = { "motion": "motion", "looks": "looks", "sound": "sounds", "pen": "pen", "data": "data", "event": "events", "control": "control", "sensing": "sensing", "operators": "operators", "more": "more" }; /** * ENUM representing that an event is not in any delete areas. * Null for backwards compatibility reasons. * @const */ Blockly.DELETE_AREA_NONE = null; /** * ENUM representing that an event is in the delete area of the trash can. * @const */ Blockly.DELETE_AREA_TRASH = 1; /** * ENUM representing that an event is in the delete area of the toolbox or * flyout. * @const */ Blockly.DELETE_AREA_TOOLBOX = 2; /** * String for use in the "custom" attribute of a category in toolbox xml. * This string indicates that the category should be dynamically populated with * variable blocks. * @const {string} */ Blockly.VARIABLE_CATEGORY_NAME = 'VARIABLE'; /** * String for use in the "custom" attribute of a category in toolbox xml. * This string indicates that the category should be dynamically populated with * procedure blocks. * @const {string} */ Blockly.PROCEDURE_CATEGORY_NAME = 'PROCEDURE'; /** * String for use in the dropdown created in field_variable. * This string indicates that this option in the dropdown is 'Rename * variable...' and if selected, should trigger the prompt to rename a variable. * @const {string} */ Blockly.RENAME_VARIABLE_ID = 'RENAME_VARIABLE_ID'; /** * String for use in the dropdown created in field_variable. * This string indicates that this option in the dropdown is 'Delete the "%1" * variable' and if selected, should trigger the prompt to delete a variable. * @const {string} */ Blockly.DELETE_VARIABLE_ID = 'DELETE_VARIABLE_ID'; /** * String for use in the dropdown created in field_variable, * specifically for broadcast messages. * This string indicates that this option in the dropdown is 'New message...' * and if selected, should trigger the prompt to create a new message. * @const {string} */ Blockly.NEW_BROADCAST_MESSAGE_ID = 'NEW_BROADCAST_MESSAGE_ID'; /** * String representing the variable type of broadcast message blocks. * This string, for use in differentiating between types of variables, * indicates that the current variable is a broadcast message. * @const {string} */ Blockly.BROADCAST_MESSAGE_VARIABLE_TYPE = 'broadcast_msg'; /** * String representing the variable type of list blocks. * This string, for use in differentiating between types of variables, * indicates that the current variable is a list. * @const {string} */ Blockly.LIST_VARIABLE_TYPE = 'list'; /** * The type of all procedure definition blocks. * @const {string} */ Blockly.PROCEDURES_DEFINITION_BLOCK_TYPE = 'procedures_definition'; /** * The type of all procedure prototype blocks. * @const {string} */ Blockly.PROCEDURES_PROTOTYPE_BLOCK_TYPE = 'procedures_prototype'; /** * The type of all procedure call blocks. * @const {string} */ Blockly.PROCEDURES_CALL_BLOCK_TYPE = 'procedures_call';
1
8,994
Something I didn't catch before I merged this PR, is the hyphenated constant a problem? E.g. should "data-lists" be "data_lists"? @paulkaplan
LLK-scratch-blocks
js
@@ -248,3 +248,7 @@ L2socket: use the provided L2socket import scapy.sendrecv scapy.sendrecv.sniff = sniff + +# If wpcap.dll is not available +if (not conf.use_winpcapy) and (not conf.use_pcap) and (not conf.use_dnet): + from scapy.arch.windows.disable_sendrecv import *
1
## This file is part of Scapy ## See http://www.secdev.org/projects/scapy for more informations ## Copyright (C) Philippe Biondi <[email protected]> ## This program is published under a GPLv2 license """ Instanciate part of the customizations needed to support Microsoft Windows. """ import itertools import os import re import socket import subprocess import sys import time from scapy.arch.consts import LOOPBACK_NAME from scapy.config import conf,ConfClass from scapy.base_classes import Gen, SetGen import scapy.plist as plist from scapy.utils import PcapReader from scapy.data import MTU, ETH_P_ARP WINDOWS = True def sndrcv(pks, pkt, timeout = 2, inter = 0, verbose=None, chainCC=0, retry=0, multi=0): if not isinstance(pkt, Gen): pkt = SetGen(pkt) if verbose is None: verbose = conf.verb from scapy.sendrecv import debug debug.recv = plist.PacketList([],"Unanswered") debug.sent = plist.PacketList([],"Sent") debug.match = plist.SndRcvList([]) nbrecv=0 ans = [] # do it here to fix random fields, so that parent and child have the same all_stimuli = tobesent = [p for p in pkt] notans = len(tobesent) hsent={} for i in tobesent: h = i.hashret() if h in hsent: hsent[h].append(i) else: hsent[h] = [i] if retry < 0: retry = -retry autostop=retry else: autostop=0 while retry >= 0: found=0 if timeout < 0: timeout = None pid=1 try: if WINDOWS or pid == 0: try: try: i = 0 if verbose: print "Begin emission:" for p in tobesent: pks.send(p) i += 1 time.sleep(inter) if verbose: print "Finished to send %i packets." % i except SystemExit: pass except KeyboardInterrupt: pass except: log_runtime.exception("--- Error sending packets") log_runtime.info("--- Error sending packets") finally: try: sent_times = [p.sent_time for p in all_stimuli if p.sent_time] except: pass if WINDOWS or pid > 0: # Timeout starts after last packet is sent (as in Unix version) if timeout: stoptime = time.time()+timeout else: stoptime = 0 remaintime = None try: try: while 1: if stoptime: remaintime = stoptime-time.time() if remaintime <= 0: break r = pks.recv(MTU) if r is None: continue ok = 0 h = r.hashret() if h in hsent: hlst = hsent[h] for i, sentpkt in enumerate(hlst): if r.answers(sentpkt): ans.append((sentpkt, r)) if verbose > 1: os.write(1, "*") ok = 1 if not multi: del hlst[i] notans -= 1 else: if not hasattr(sentpkt, '_answered'): notans -= 1 sentpkt._answered = 1 break if notans == 0 and not multi: break if not ok: if verbose > 1: os.write(1, ".") nbrecv += 1 if conf.debug_match: debug.recv.append(r) except KeyboardInterrupt: if chainCC: raise finally: if WINDOWS: for p,t in zip(all_stimuli, sent_times): p.sent_time = t finally: pass remain = list(itertools.chain(*hsent.itervalues())) if multi: remain = [p for p in remain if not hasattr(p, '_answered')] if autostop and len(remain) > 0 and len(remain) != len(tobesent): retry = autostop tobesent = remain if len(tobesent) == 0: break retry -= 1 if conf.debug_match: debug.sent=plist.PacketList(remain[:],"Sent") debug.match=plist.SndRcvList(ans[:]) #clean the ans list to delete the field _answered if (multi): for s,r in ans: if hasattr(s, '_answered'): del(s._answered) if verbose: print "\nReceived %i packets, got %i answers, remaining %i packets" % (nbrecv+len(ans), len(ans), notans) return plist.SndRcvList(ans),plist.PacketList(remain,"Unanswered") import scapy.sendrecv scapy.sendrecv.sndrcv = sndrcv def sniff(count=0, store=1, offline=None, prn = None, lfilter=None, L2socket=None, timeout=None, *arg, **karg): """Sniff packets sniff([count=0,] [prn=None,] [store=1,] [offline=None,] [lfilter=None,] + L2ListenSocket args) -> list of packets Select interface to sniff by setting conf.iface. Use show_interfaces() to see interface names. count: number of packets to capture. 0 means infinity store: wether to store sniffed packets or discard them prn: function to apply to each packet. If something is returned, it is displayed. Ex: ex: prn = lambda x: x.summary() filter: provide a BPF filter lfilter: python function applied to each packet to determine if further action may be done ex: lfilter = lambda x: x.haslayer(Padding) offline: pcap file to read packets from, instead of sniffing them timeout: stop sniffing after a given time (default: None) L2socket: use the provided L2socket """ c = 0 if offline is None: log_runtime.info('Sniffing on %s' % conf.iface) if L2socket is None: L2socket = conf.L2listen s = L2socket(type=ETH_P_ALL, *arg, **karg) else: flt = karg.get('filter') if flt is not None: if isinstance(offline, basestring): s = PcapReader( subprocess.Popen( [conf.prog.tcpdump, "-r", offline, "-w", "-", flt], stdout=subprocess.PIPE ).stdout ) else: s = PcapReader( subprocess.Popen( [conf.prog.tcpdump, "-r", "-", "-w", "-", flt], stdin=offline, stdout=subprocess.PIPE ).stdout ) else: s = PcapReader(offline) lst = [] if timeout is not None: stoptime = time.time()+timeout remain = None while 1: try: if timeout is not None: remain = stoptime-time.time() if remain <= 0: break try: p = s.recv(MTU) except PcapTimeoutElapsed: continue if p is None: break if lfilter and not lfilter(p): continue if store: lst.append(p) c += 1 if prn: r = prn(p) if r is not None: print r if 0 < count <= c: break except KeyboardInterrupt: break s.close() return plist.PacketList(lst,"Sniffed") import scapy.sendrecv scapy.sendrecv.sniff = sniff
1
9,024
Can you write the test as `if not (conf.use_winpcapy or conf.use_pcap or conf.use_dnet):`
secdev-scapy
py
@@ -23,6 +23,8 @@ class _Repository: self.description = check.opt_str_param(description, "description") def __call__(self, fn: Callable[[], Any]) -> RepositoryDefinition: + from dagster.core.asset_defs import ForeignAsset + check.callable_param(fn, "fn") if not self.name:
1
from functools import update_wrapper from typing import Any, Callable, Optional, Union from dagster import check from dagster.core.errors import DagsterInvalidDefinitionError from ..graph_definition import GraphDefinition from ..partition import PartitionSetDefinition from ..pipeline_definition import PipelineDefinition from ..repository_definition import ( VALID_REPOSITORY_DATA_DICT_KEYS, CachingRepositoryData, RepositoryData, RepositoryDefinition, ) from ..schedule_definition import ScheduleDefinition from ..sensor_definition import SensorDefinition class _Repository: def __init__(self, name: Optional[str] = None, description: Optional[str] = None): self.name = check.opt_str_param(name, "name") self.description = check.opt_str_param(description, "description") def __call__(self, fn: Callable[[], Any]) -> RepositoryDefinition: check.callable_param(fn, "fn") if not self.name: self.name = fn.__name__ repository_definitions = fn() if not ( isinstance(repository_definitions, list) or isinstance(repository_definitions, dict) or isinstance(repository_definitions, RepositoryData) ): raise DagsterInvalidDefinitionError( "Bad return value of type {type_} from repository construction function: must " "return list, dict, or RepositoryData. See the @repository decorator docstring for " "details and examples".format(type_=type(repository_definitions)), ) if isinstance(repository_definitions, list): bad_definitions = [] for i, definition in enumerate(repository_definitions): if not ( isinstance(definition, PipelineDefinition) or isinstance(definition, PartitionSetDefinition) or isinstance(definition, ScheduleDefinition) or isinstance(definition, SensorDefinition) or isinstance(definition, GraphDefinition) ): bad_definitions.append((i, type(definition))) if bad_definitions: bad_definitions_str = ", ".join( [ "value of type {type_} at index {i}".format(type_=type_, i=i) for i, type_ in bad_definitions ] ) raise DagsterInvalidDefinitionError( "Bad return value from repository construction function: all elements of list " "must be of type JobDefinition, GraphDefinition, PipelineDefinition, " "PartitionSetDefinition, ScheduleDefinition, or SensorDefinition. " f"Got {bad_definitions_str}." ) repository_data = CachingRepositoryData.from_list(repository_definitions) elif isinstance(repository_definitions, dict): if not set(repository_definitions.keys()).issubset(VALID_REPOSITORY_DATA_DICT_KEYS): raise DagsterInvalidDefinitionError( "Bad return value from repository construction function: dict must not contain " "keys other than {{'pipelines', 'partition_sets', 'schedules', 'jobs'}}: found " "{bad_keys}".format( bad_keys=", ".join( [ "'{key}'".format(key=key) for key in repository_definitions.keys() if key not in VALID_REPOSITORY_DATA_DICT_KEYS ] ) ) ) repository_data = CachingRepositoryData.from_dict(repository_definitions) elif isinstance(repository_definitions, RepositoryData): repository_data = repository_definitions repository_def = RepositoryDefinition( name=self.name, description=self.description, repository_data=repository_data ) update_wrapper(repository_def, fn) return repository_def def repository( name: Union[Optional[str], Callable[..., Any]] = None, description: Optional[str] = None ) -> Union[_Repository, RepositoryDefinition]: """Create a repository from the decorated function. The decorated function should take no arguments and its return value should one of: 1. ``List[Union[JobDefinition, PipelineDefinition, PartitionSetDefinition, ScheduleDefinition, SensorDefinition]]``. Use this form when you have no need to lazy load pipelines or other definitions. This is the typical use case. 2. A dict of the form: .. code-block:: python { 'jobs': Dict[str, Callable[[], JobDefinition]], 'pipelines': Dict[str, Callable[[], PipelineDefinition]], 'partition_sets': Dict[str, Callable[[], PartitionSetDefinition]], 'schedules': Dict[str, Callable[[], ScheduleDefinition]] 'sensors': Dict[str, Callable[[], SensorDefinition]] } This form is intended to allow definitions to be created lazily when accessed by name, which can be helpful for performance when there are many definitions in a repository, or when constructing the definitions is costly. 3. :py:class:`RepositoryData`. Return this object if you need fine-grained control over the construction and indexing of definitions within the repository, e.g., to create definitions dynamically from .yaml files in a directory. Args: name (Optional[str]): The name of the repository. Defaults to the name of the decorated function. description (Optional[str]): A string description of the repository. Example: .. code-block:: python ###################################################################### # A simple repository using the first form of the decorated function ###################################################################### @op(config_schema={n: Field(Int)}) def return_n(context): return context.op_config['n'] @job def simple_job(): return_n() @job def some_job(): ... @sensor(job=some_job) def some_sensor(): if foo(): yield RunRequest( run_key= ..., run_config={ 'ops': {'return_n': {'config': {'n': bar()}}} } ) @job def my_job(): ... my_schedule = ScheduleDefinition(cron_schedule="0 0 * * *", job=my_job) @repository def simple_repository(): return [simple_job, some_sensor, my_schedule] ###################################################################### # A lazy-loaded repository ###################################################################### def make_expensive_job(): @job def expensive_job(): for i in range(10000): return_n.alias(f'return_n_{i}')() return expensive_job def make_expensive_schedule(): @job def other_expensive_job(): for i in range(11000): return_n.alias(f'my_return_n_{i}')() return ScheduleDefinition(cron_schedule="0 0 * * *", job=other_expensive_job) @repository def lazy_loaded_repository(): return { 'jobs': {'expensive_job': make_expensive_job}, 'schedules': {'expensive_schedule: make_expensive_schedule} } ###################################################################### # A complex repository that lazily constructs jobs from a directory # of files in a bespoke YAML format ###################################################################### class ComplexRepositoryData(RepositoryData): def __init__(self, yaml_directory): self._yaml_directory = yaml_directory def get_all_jobs(self): return [ self._construct_job_def_from_yaml_file( self._yaml_file_for_job_name(file_name) ) for file_name in os.listdir(self._yaml_directory) ] ... @repository def complex_repository(): return ComplexRepositoryData('some_directory') """ if callable(name): check.invariant(description is None) return _Repository()(name) return _Repository(name=name, description=description)
1
17,490
we have to include foreign assets on the repository directly because they don't belong to a job? This seems very awkward... Is this a step towards the job-less assets on the repository? Did you consider having `build_asset_job` take in a set of foreign assets instead? I suppose we would then need to subclass it to be a more special `AssetJobDefinition` that can keep track of them.
dagster-io-dagster
py
@@ -14,8 +14,7 @@ TempDir::TempDir(const char* pathTemplate, bool deleteOnDestroy) : deleteOnDestroy_(deleteOnDestroy) { auto len = strlen(pathTemplate); std::unique_ptr<char[]> name(new char[len + 1]); - strncpy(name.get(), pathTemplate, len); - name.get()[len] = '\0'; + strcpy(name.get(), pathTemplate); VLOG(2) << "Trying to create the temp directory with pattern \"" << name.get() << "\"";
1
/* Copyright (c) 2018 - present, VE Software Inc. All rights reserved * * This source code is licensed under Apache 2.0 License * (found in the LICENSE.Apache file in the root directory) */ #include "base/Base.h" #include "fs/TempDir.h" namespace vesoft { namespace fs { TempDir::TempDir(const char* pathTemplate, bool deleteOnDestroy) : deleteOnDestroy_(deleteOnDestroy) { auto len = strlen(pathTemplate); std::unique_ptr<char[]> name(new char[len + 1]); strncpy(name.get(), pathTemplate, len); name.get()[len] = '\0'; VLOG(2) << "Trying to create the temp directory with pattern \"" << name.get() << "\""; if (!mkdtemp(name.get())) { // Failed LOG(ERROR) << "Failed to created the temp directory with template \"" << name.get() << "\" (" << errno << "): " << strerror(errno); } else { dirPath_ = std::move(name); VLOG(2) << "Created temporary directory " << dirPath_.get(); } } TempDir::~TempDir() { if (deleteOnDestroy_ && !!dirPath_) { FileUtils::remove(dirPath_.get(), true); } } } // namespace fs } // namespace vesoft
1
14,084
`-Wstringop-truncation` is a new kind of error detector introduced in GCC 8. As for this patch, these are two false-positives though.
vesoft-inc-nebula
cpp
@@ -36,7 +36,7 @@ const ( // ErrSharedConfigSourceCollision will be returned if a section contains both // source_profile and credential_source -var ErrSharedConfigSourceCollision = awserr.New(ErrCodeSharedConfig, "only source profile or credential source can be specified, not both", nil) +var ErrSharedConfigSourceCollision = awserr.New(ErrCodeSharedConfig, "only one credential type may be specified per profile: source profile, credential source, credential process, web identity token, or sso", nil) // ErrSharedConfigECSContainerEnvVarEmpty will be returned if the environment // variables are empty and Environment was set as the credential source
1
package session import ( "crypto/tls" "crypto/x509" "fmt" "io" "io/ioutil" "net/http" "os" "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/aws/client" "github.com/aws/aws-sdk-go/aws/corehandlers" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/csm" "github.com/aws/aws-sdk-go/aws/defaults" "github.com/aws/aws-sdk-go/aws/endpoints" "github.com/aws/aws-sdk-go/aws/request" ) const ( // ErrCodeSharedConfig represents an error that occurs in the shared // configuration logic ErrCodeSharedConfig = "SharedConfigErr" // ErrCodeLoadCustomCABundle error code for unable to load custom CA bundle. ErrCodeLoadCustomCABundle = "LoadCustomCABundleError" // ErrCodeLoadClientTLSCert error code for unable to load client TLS // certificate or key ErrCodeLoadClientTLSCert = "LoadClientTLSCertError" ) // ErrSharedConfigSourceCollision will be returned if a section contains both // source_profile and credential_source var ErrSharedConfigSourceCollision = awserr.New(ErrCodeSharedConfig, "only source profile or credential source can be specified, not both", nil) // ErrSharedConfigECSContainerEnvVarEmpty will be returned if the environment // variables are empty and Environment was set as the credential source var ErrSharedConfigECSContainerEnvVarEmpty = awserr.New(ErrCodeSharedConfig, "EcsContainer was specified as the credential_source, but 'AWS_CONTAINER_CREDENTIALS_RELATIVE_URI' was not set", nil) // ErrSharedConfigInvalidCredSource will be returned if an invalid credential source was provided var ErrSharedConfigInvalidCredSource = awserr.New(ErrCodeSharedConfig, "credential source values must be EcsContainer, Ec2InstanceMetadata, or Environment", nil) // A Session provides a central location to create service clients from and // store configurations and request handlers for those services. // // Sessions are safe to create service clients concurrently, but it is not safe // to mutate the Session concurrently. // // The Session satisfies the service client's client.ConfigProvider. type Session struct { Config *aws.Config Handlers request.Handlers options Options } // New creates a new instance of the handlers merging in the provided configs // on top of the SDK's default configurations. Once the Session is created it // can be mutated to modify the Config or Handlers. The Session is safe to be // read concurrently, but it should not be written to concurrently. // // If the AWS_SDK_LOAD_CONFIG environment is set to a truthy value, the New // method could now encounter an error when loading the configuration. When // The environment variable is set, and an error occurs, New will return a // session that will fail all requests reporting the error that occurred while // loading the session. Use NewSession to get the error when creating the // session. // // If the AWS_SDK_LOAD_CONFIG environment variable is set to a truthy value // the shared config file (~/.aws/config) will also be loaded, in addition to // the shared credentials file (~/.aws/credentials). Values set in both the // shared config, and shared credentials will be taken from the shared // credentials file. // // Deprecated: Use NewSession functions to create sessions instead. NewSession // has the same functionality as New except an error can be returned when the // func is called instead of waiting to receive an error until a request is made. func New(cfgs ...*aws.Config) *Session { // load initial config from environment envCfg, envErr := loadEnvConfig() if envCfg.EnableSharedConfig { var cfg aws.Config cfg.MergeIn(cfgs...) s, err := NewSessionWithOptions(Options{ Config: cfg, SharedConfigState: SharedConfigEnable, }) if err != nil { // Old session.New expected all errors to be discovered when // a request is made, and would report the errors then. This // needs to be replicated if an error occurs while creating // the session. msg := "failed to create session with AWS_SDK_LOAD_CONFIG enabled. " + "Use session.NewSession to handle errors occurring during session creation." // Session creation failed, need to report the error and prevent // any requests from succeeding. s = &Session{Config: defaults.Config()} s.logDeprecatedNewSessionError(msg, err, cfgs) } return s } s := deprecatedNewSession(envCfg, cfgs...) if envErr != nil { msg := "failed to load env config" s.logDeprecatedNewSessionError(msg, envErr, cfgs) } if csmCfg, err := loadCSMConfig(envCfg, []string{}); err != nil { if l := s.Config.Logger; l != nil { l.Log(fmt.Sprintf("ERROR: failed to load CSM configuration, %v", err)) } } else if csmCfg.Enabled { err := enableCSM(&s.Handlers, csmCfg, s.Config.Logger) if err != nil { msg := "failed to enable CSM" s.logDeprecatedNewSessionError(msg, err, cfgs) } } return s } // NewSession returns a new Session created from SDK defaults, config files, // environment, and user provided config files. Once the Session is created // it can be mutated to modify the Config or Handlers. The Session is safe to // be read concurrently, but it should not be written to concurrently. // // If the AWS_SDK_LOAD_CONFIG environment variable is set to a truthy value // the shared config file (~/.aws/config) will also be loaded in addition to // the shared credentials file (~/.aws/credentials). Values set in both the // shared config, and shared credentials will be taken from the shared // credentials file. Enabling the Shared Config will also allow the Session // to be built with retrieving credentials with AssumeRole set in the config. // // See the NewSessionWithOptions func for information on how to override or // control through code how the Session will be created, such as specifying the // config profile, and controlling if shared config is enabled or not. func NewSession(cfgs ...*aws.Config) (*Session, error) { opts := Options{} opts.Config.MergeIn(cfgs...) return NewSessionWithOptions(opts) } // SharedConfigState provides the ability to optionally override the state // of the session's creation based on the shared config being enabled or // disabled. type SharedConfigState int const ( // SharedConfigStateFromEnv does not override any state of the // AWS_SDK_LOAD_CONFIG env var. It is the default value of the // SharedConfigState type. SharedConfigStateFromEnv SharedConfigState = iota // SharedConfigDisable overrides the AWS_SDK_LOAD_CONFIG env var value // and disables the shared config functionality. SharedConfigDisable // SharedConfigEnable overrides the AWS_SDK_LOAD_CONFIG env var value // and enables the shared config functionality. SharedConfigEnable ) // Options provides the means to control how a Session is created and what // configuration values will be loaded. // type Options struct { // Provides config values for the SDK to use when creating service clients // and making API requests to services. Any value set in with this field // will override the associated value provided by the SDK defaults, // environment or config files where relevant. // // If not set, configuration values from from SDK defaults, environment, // config will be used. Config aws.Config // Overrides the config profile the Session should be created from. If not // set the value of the environment variable will be loaded (AWS_PROFILE, // or AWS_DEFAULT_PROFILE if the Shared Config is enabled). // // If not set and environment variables are not set the "default" // (DefaultSharedConfigProfile) will be used as the profile to load the // session config from. Profile string // Instructs how the Session will be created based on the AWS_SDK_LOAD_CONFIG // environment variable. By default a Session will be created using the // value provided by the AWS_SDK_LOAD_CONFIG environment variable. // // Setting this value to SharedConfigEnable or SharedConfigDisable // will allow you to override the AWS_SDK_LOAD_CONFIG environment variable // and enable or disable the shared config functionality. SharedConfigState SharedConfigState // Ordered list of files the session will load configuration from. // It will override environment variable AWS_SHARED_CREDENTIALS_FILE, AWS_CONFIG_FILE. SharedConfigFiles []string // When the SDK's shared config is configured to assume a role with MFA // this option is required in order to provide the mechanism that will // retrieve the MFA token. There is no default value for this field. If // it is not set an error will be returned when creating the session. // // This token provider will be called when ever the assumed role's // credentials need to be refreshed. Within the context of service clients // all sharing the same session the SDK will ensure calls to the token // provider are atomic. When sharing a token provider across multiple // sessions additional synchronization logic is needed to ensure the // token providers do not introduce race conditions. It is recommend to // share the session where possible. // // stscreds.StdinTokenProvider is a basic implementation that will prompt // from stdin for the MFA token code. // // This field is only used if the shared configuration is enabled, and // the config enables assume role wit MFA via the mfa_serial field. AssumeRoleTokenProvider func() (string, error) // When the SDK's shared config is configured to assume a role this option // may be provided to set the expiry duration of the STS credentials. // Defaults to 15 minutes if not set as documented in the // stscreds.AssumeRoleProvider. AssumeRoleDuration time.Duration // Reader for a custom Credentials Authority (CA) bundle in PEM format that // the SDK will use instead of the default system's root CA bundle. Use this // only if you want to replace the CA bundle the SDK uses for TLS requests. // // HTTP Client's Transport concrete implementation must be a http.Transport // or creating the session will fail. // // If the Transport's TLS config is set this option will cause the SDK // to overwrite the Transport's TLS config's RootCAs value. If the CA // bundle reader contains multiple certificates all of them will be loaded. // // Can also be specified via the environment variable: // // AWS_CA_BUNDLE=$HOME/ca_bundle // // Can also be specified via the shared config field: // // ca_bundle = $HOME/ca_bundle CustomCABundle io.Reader // Reader for the TLC client certificate that should be used by the SDK's // HTTP transport when making requests. The certificate must be paired with // a TLS client key file. Will be ignored if both are not provided. // // HTTP Client's Transport concrete implementation must be a http.Transport // or creating the session will fail. // // Can also be specified via the environment variable: // // AWS_SDK_GO_CLIENT_TLS_CERT=$HOME/my_client_cert ClientTLSCert io.Reader // Reader for the TLC client key that should be used by the SDK's HTTP // transport when making requests. The key must be paired with a TLS client // certificate file. Will be ignored if both are not provided. // // HTTP Client's Transport concrete implementation must be a http.Transport // or creating the session will fail. // // Can also be specified via the environment variable: // // AWS_SDK_GO_CLIENT_TLS_KEY=$HOME/my_client_key ClientTLSKey io.Reader // The handlers that the session and all API clients will be created with. // This must be a complete set of handlers. Use the defaults.Handlers() // function to initialize this value before changing the handlers to be // used by the SDK. Handlers request.Handlers // Allows specifying a custom endpoint to be used by the EC2 IMDS client // when making requests to the EC2 IMDS API. The must endpoint value must // include protocol prefix. // // If unset, will the EC2 IMDS client will use its default endpoint. // // Can also be specified via the environment variable, // AWS_EC2_METADATA_SERVICE_ENDPOINT. // // AWS_EC2_METADATA_SERVICE_ENDPOINT=http://169.254.169.254 // // If using an URL with an IPv6 address literal, the IPv6 address // component must be enclosed in square brackets. // // AWS_EC2_METADATA_SERVICE_ENDPOINT=http://[::1] EC2IMDSEndpoint string } // NewSessionWithOptions returns a new Session created from SDK defaults, config files, // environment, and user provided config files. This func uses the Options // values to configure how the Session is created. // // If the AWS_SDK_LOAD_CONFIG environment variable is set to a truthy value // the shared config file (~/.aws/config) will also be loaded in addition to // the shared credentials file (~/.aws/credentials). Values set in both the // shared config, and shared credentials will be taken from the shared // credentials file. Enabling the Shared Config will also allow the Session // to be built with retrieving credentials with AssumeRole set in the config. // // // Equivalent to session.New // sess := session.Must(session.NewSessionWithOptions(session.Options{})) // // // Specify profile to load for the session's config // sess := session.Must(session.NewSessionWithOptions(session.Options{ // Profile: "profile_name", // })) // // // Specify profile for config and region for requests // sess := session.Must(session.NewSessionWithOptions(session.Options{ // Config: aws.Config{Region: aws.String("us-east-1")}, // Profile: "profile_name", // })) // // // Force enable Shared Config support // sess := session.Must(session.NewSessionWithOptions(session.Options{ // SharedConfigState: session.SharedConfigEnable, // })) func NewSessionWithOptions(opts Options) (*Session, error) { var envCfg envConfig var err error if opts.SharedConfigState == SharedConfigEnable { envCfg, err = loadSharedEnvConfig() if err != nil { return nil, fmt.Errorf("failed to load shared config, %v", err) } } else { envCfg, err = loadEnvConfig() if err != nil { return nil, fmt.Errorf("failed to load environment config, %v", err) } } if len(opts.Profile) != 0 { envCfg.Profile = opts.Profile } switch opts.SharedConfigState { case SharedConfigDisable: envCfg.EnableSharedConfig = false case SharedConfigEnable: envCfg.EnableSharedConfig = true } return newSession(opts, envCfg, &opts.Config) } // Must is a helper function to ensure the Session is valid and there was no // error when calling a NewSession function. // // This helper is intended to be used in variable initialization to load the // Session and configuration at startup. Such as: // // var sess = session.Must(session.NewSession()) func Must(sess *Session, err error) *Session { if err != nil { panic(err) } return sess } // Wraps the endpoint resolver with a resolver that will return a custom // endpoint for EC2 IMDS. func wrapEC2IMDSEndpoint(resolver endpoints.Resolver, endpoint string) endpoints.Resolver { return endpoints.ResolverFunc( func(service, region string, opts ...func(*endpoints.Options)) ( endpoints.ResolvedEndpoint, error, ) { if service == ec2MetadataServiceID { return endpoints.ResolvedEndpoint{ URL: endpoint, SigningName: ec2MetadataServiceID, SigningRegion: region, }, nil } return resolver.EndpointFor(service, region) }) } func deprecatedNewSession(envCfg envConfig, cfgs ...*aws.Config) *Session { cfg := defaults.Config() handlers := defaults.Handlers() // Apply the passed in configs so the configuration can be applied to the // default credential chain cfg.MergeIn(cfgs...) if cfg.EndpointResolver == nil { // An endpoint resolver is required for a session to be able to provide // endpoints for service client configurations. cfg.EndpointResolver = endpoints.DefaultResolver() } if len(envCfg.EC2IMDSEndpoint) != 0 { cfg.EndpointResolver = wrapEC2IMDSEndpoint(cfg.EndpointResolver, envCfg.EC2IMDSEndpoint) } cfg.Credentials = defaults.CredChain(cfg, handlers) // Reapply any passed in configs to override credentials if set cfg.MergeIn(cfgs...) s := &Session{ Config: cfg, Handlers: handlers, options: Options{ EC2IMDSEndpoint: envCfg.EC2IMDSEndpoint, }, } initHandlers(s) return s } func enableCSM(handlers *request.Handlers, cfg csmConfig, logger aws.Logger) error { if logger != nil { logger.Log("Enabling CSM") } r, err := csm.Start(cfg.ClientID, csm.AddressWithDefaults(cfg.Host, cfg.Port)) if err != nil { return err } r.InjectHandlers(handlers) return nil } func newSession(opts Options, envCfg envConfig, cfgs ...*aws.Config) (*Session, error) { cfg := defaults.Config() handlers := opts.Handlers if handlers.IsEmpty() { handlers = defaults.Handlers() } // Get a merged version of the user provided config to determine if // credentials were. userCfg := &aws.Config{} userCfg.MergeIn(cfgs...) cfg.MergeIn(userCfg) // Ordered config files will be loaded in with later files overwriting // previous config file values. var cfgFiles []string if opts.SharedConfigFiles != nil { cfgFiles = opts.SharedConfigFiles } else { cfgFiles = []string{envCfg.SharedConfigFile, envCfg.SharedCredentialsFile} if !envCfg.EnableSharedConfig { // The shared config file (~/.aws/config) is only loaded if instructed // to load via the envConfig.EnableSharedConfig (AWS_SDK_LOAD_CONFIG). cfgFiles = cfgFiles[1:] } } // Load additional config from file(s) sharedCfg, err := loadSharedConfig(envCfg.Profile, cfgFiles, envCfg.EnableSharedConfig) if err != nil { if len(envCfg.Profile) == 0 && !envCfg.EnableSharedConfig && (envCfg.Creds.HasKeys() || userCfg.Credentials != nil) { // Special case where the user has not explicitly specified an AWS_PROFILE, // or session.Options.profile, shared config is not enabled, and the // environment has credentials, allow the shared config file to fail to // load since the user has already provided credentials, and nothing else // is required to be read file. Github(aws/aws-sdk-go#2455) } else if _, ok := err.(SharedConfigProfileNotExistsError); !ok { return nil, err } } if err := mergeConfigSrcs(cfg, userCfg, envCfg, sharedCfg, handlers, opts); err != nil { return nil, err } if err := setTLSOptions(&opts, cfg, envCfg, sharedCfg); err != nil { return nil, err } s := &Session{ Config: cfg, Handlers: handlers, options: opts, } initHandlers(s) if csmCfg, err := loadCSMConfig(envCfg, cfgFiles); err != nil { if l := s.Config.Logger; l != nil { l.Log(fmt.Sprintf("ERROR: failed to load CSM configuration, %v", err)) } } else if csmCfg.Enabled { err = enableCSM(&s.Handlers, csmCfg, s.Config.Logger) if err != nil { return nil, err } } return s, nil } type csmConfig struct { Enabled bool Host string Port string ClientID string } var csmProfileName = "aws_csm" func loadCSMConfig(envCfg envConfig, cfgFiles []string) (csmConfig, error) { if envCfg.CSMEnabled != nil { if *envCfg.CSMEnabled { return csmConfig{ Enabled: true, ClientID: envCfg.CSMClientID, Host: envCfg.CSMHost, Port: envCfg.CSMPort, }, nil } return csmConfig{}, nil } sharedCfg, err := loadSharedConfig(csmProfileName, cfgFiles, false) if err != nil { if _, ok := err.(SharedConfigProfileNotExistsError); !ok { return csmConfig{}, err } } if sharedCfg.CSMEnabled != nil && *sharedCfg.CSMEnabled == true { return csmConfig{ Enabled: true, ClientID: sharedCfg.CSMClientID, Host: sharedCfg.CSMHost, Port: sharedCfg.CSMPort, }, nil } return csmConfig{}, nil } func setTLSOptions(opts *Options, cfg *aws.Config, envCfg envConfig, sharedCfg sharedConfig) error { // CA Bundle can be specified in both environment variable shared config file. var caBundleFilename = envCfg.CustomCABundle if len(caBundleFilename) == 0 { caBundleFilename = sharedCfg.CustomCABundle } // Only use environment value if session option is not provided. customTLSOptions := map[string]struct { filename string field *io.Reader errCode string }{ "custom CA bundle PEM": {filename: caBundleFilename, field: &opts.CustomCABundle, errCode: ErrCodeLoadCustomCABundle}, "custom client TLS cert": {filename: envCfg.ClientTLSCert, field: &opts.ClientTLSCert, errCode: ErrCodeLoadClientTLSCert}, "custom client TLS key": {filename: envCfg.ClientTLSKey, field: &opts.ClientTLSKey, errCode: ErrCodeLoadClientTLSCert}, } for name, v := range customTLSOptions { if len(v.filename) != 0 && *v.field == nil { f, err := os.Open(v.filename) if err != nil { return awserr.New(v.errCode, fmt.Sprintf("failed to open %s file", name), err) } defer f.Close() *v.field = f } } // Setup HTTP client with custom cert bundle if enabled if opts.CustomCABundle != nil { if err := loadCustomCABundle(cfg.HTTPClient, opts.CustomCABundle); err != nil { return err } } // Setup HTTP client TLS certificate and key for client TLS authentication. if opts.ClientTLSCert != nil && opts.ClientTLSKey != nil { if err := loadClientTLSCert(cfg.HTTPClient, opts.ClientTLSCert, opts.ClientTLSKey); err != nil { return err } } else if opts.ClientTLSCert == nil && opts.ClientTLSKey == nil { // Do nothing if neither values are available. } else { return awserr.New(ErrCodeLoadClientTLSCert, fmt.Sprintf("client TLS cert(%t) and key(%t) must both be provided", opts.ClientTLSCert != nil, opts.ClientTLSKey != nil), nil) } return nil } func getHTTPTransport(client *http.Client) (*http.Transport, error) { var t *http.Transport switch v := client.Transport.(type) { case *http.Transport: t = v default: if client.Transport != nil { return nil, fmt.Errorf("unsupported transport, %T", client.Transport) } } if t == nil { // Nil transport implies `http.DefaultTransport` should be used. Since // the SDK cannot modify, nor copy the `DefaultTransport` specifying // the values the next closest behavior. t = getCustomTransport() } return t, nil } func loadCustomCABundle(client *http.Client, bundle io.Reader) error { t, err := getHTTPTransport(client) if err != nil { return awserr.New(ErrCodeLoadCustomCABundle, "unable to load custom CA bundle, HTTPClient's transport unsupported type", err) } p, err := loadCertPool(bundle) if err != nil { return err } if t.TLSClientConfig == nil { t.TLSClientConfig = &tls.Config{} } t.TLSClientConfig.RootCAs = p client.Transport = t return nil } func loadCertPool(r io.Reader) (*x509.CertPool, error) { b, err := ioutil.ReadAll(r) if err != nil { return nil, awserr.New(ErrCodeLoadCustomCABundle, "failed to read custom CA bundle PEM file", err) } p := x509.NewCertPool() if !p.AppendCertsFromPEM(b) { return nil, awserr.New(ErrCodeLoadCustomCABundle, "failed to load custom CA bundle PEM file", err) } return p, nil } func loadClientTLSCert(client *http.Client, certFile, keyFile io.Reader) error { t, err := getHTTPTransport(client) if err != nil { return awserr.New(ErrCodeLoadClientTLSCert, "unable to get usable HTTP transport from client", err) } cert, err := ioutil.ReadAll(certFile) if err != nil { return awserr.New(ErrCodeLoadClientTLSCert, "unable to get read client TLS cert file", err) } key, err := ioutil.ReadAll(keyFile) if err != nil { return awserr.New(ErrCodeLoadClientTLSCert, "unable to get read client TLS key file", err) } clientCert, err := tls.X509KeyPair(cert, key) if err != nil { return awserr.New(ErrCodeLoadClientTLSCert, "unable to load x509 key pair from client cert", err) } tlsCfg := t.TLSClientConfig if tlsCfg == nil { tlsCfg = &tls.Config{} } tlsCfg.Certificates = append(tlsCfg.Certificates, clientCert) t.TLSClientConfig = tlsCfg client.Transport = t return nil } func mergeConfigSrcs(cfg, userCfg *aws.Config, envCfg envConfig, sharedCfg sharedConfig, handlers request.Handlers, sessOpts Options, ) error { // Region if not already set by user if len(aws.StringValue(cfg.Region)) == 0 { if len(envCfg.Region) > 0 { cfg.WithRegion(envCfg.Region) } else if envCfg.EnableSharedConfig && len(sharedCfg.Region) > 0 { cfg.WithRegion(sharedCfg.Region) } } if cfg.EnableEndpointDiscovery == nil { if envCfg.EnableEndpointDiscovery != nil { cfg.WithEndpointDiscovery(*envCfg.EnableEndpointDiscovery) } else if envCfg.EnableSharedConfig && sharedCfg.EnableEndpointDiscovery != nil { cfg.WithEndpointDiscovery(*sharedCfg.EnableEndpointDiscovery) } } // Regional Endpoint flag for STS endpoint resolving mergeSTSRegionalEndpointConfig(cfg, []endpoints.STSRegionalEndpoint{ userCfg.STSRegionalEndpoint, envCfg.STSRegionalEndpoint, sharedCfg.STSRegionalEndpoint, endpoints.LegacySTSEndpoint, }) // Regional Endpoint flag for S3 endpoint resolving mergeS3UsEast1RegionalEndpointConfig(cfg, []endpoints.S3UsEast1RegionalEndpoint{ userCfg.S3UsEast1RegionalEndpoint, envCfg.S3UsEast1RegionalEndpoint, sharedCfg.S3UsEast1RegionalEndpoint, endpoints.LegacyS3UsEast1Endpoint, }) ec2IMDSEndpoint := sessOpts.EC2IMDSEndpoint if len(ec2IMDSEndpoint) == 0 { ec2IMDSEndpoint = envCfg.EC2IMDSEndpoint } if len(ec2IMDSEndpoint) != 0 { cfg.EndpointResolver = wrapEC2IMDSEndpoint(cfg.EndpointResolver, ec2IMDSEndpoint) } // Configure credentials if not already set by the user when creating the // Session. if cfg.Credentials == credentials.AnonymousCredentials && userCfg.Credentials == nil { creds, err := resolveCredentials(cfg, envCfg, sharedCfg, handlers, sessOpts) if err != nil { return err } cfg.Credentials = creds } cfg.S3UseARNRegion = userCfg.S3UseARNRegion if cfg.S3UseARNRegion == nil { cfg.S3UseARNRegion = &envCfg.S3UseARNRegion } if cfg.S3UseARNRegion == nil { cfg.S3UseARNRegion = &sharedCfg.S3UseARNRegion } return nil } func mergeSTSRegionalEndpointConfig(cfg *aws.Config, values []endpoints.STSRegionalEndpoint) { for _, v := range values { if v != endpoints.UnsetSTSEndpoint { cfg.STSRegionalEndpoint = v break } } } func mergeS3UsEast1RegionalEndpointConfig(cfg *aws.Config, values []endpoints.S3UsEast1RegionalEndpoint) { for _, v := range values { if v != endpoints.UnsetS3UsEast1Endpoint { cfg.S3UsEast1RegionalEndpoint = v break } } } func initHandlers(s *Session) { // Add the Validate parameter handler if it is not disabled. s.Handlers.Validate.Remove(corehandlers.ValidateParametersHandler) if !aws.BoolValue(s.Config.DisableParamValidation) { s.Handlers.Validate.PushBackNamed(corehandlers.ValidateParametersHandler) } } // Copy creates and returns a copy of the current Session, copying the config // and handlers. If any additional configs are provided they will be merged // on top of the Session's copied config. // // // Create a copy of the current Session, configured for the us-west-2 region. // sess.Copy(&aws.Config{Region: aws.String("us-west-2")}) func (s *Session) Copy(cfgs ...*aws.Config) *Session { newSession := &Session{ Config: s.Config.Copy(cfgs...), Handlers: s.Handlers.Copy(), options: s.options, } initHandlers(newSession) return newSession } // ClientConfig satisfies the client.ConfigProvider interface and is used to // configure the service client instances. Passing the Session to the service // client's constructor (New) will use this method to configure the client. func (s *Session) ClientConfig(service string, cfgs ...*aws.Config) client.Config { s = s.Copy(cfgs...) region := aws.StringValue(s.Config.Region) resolved, err := s.resolveEndpoint(service, region, s.Config) if err != nil { s.Handlers.Validate.PushBack(func(r *request.Request) { if len(r.ClientInfo.Endpoint) != 0 { // Error occurred while resolving endpoint, but the request // being invoked has had an endpoint specified after the client // was created. return } r.Error = err }) } return client.Config{ Config: s.Config, Handlers: s.Handlers, PartitionID: resolved.PartitionID, Endpoint: resolved.URL, SigningRegion: resolved.SigningRegion, SigningNameDerived: resolved.SigningNameDerived, SigningName: resolved.SigningName, } } const ec2MetadataServiceID = "ec2metadata" func (s *Session) resolveEndpoint(service, region string, cfg *aws.Config) (endpoints.ResolvedEndpoint, error) { if ep := aws.StringValue(cfg.Endpoint); len(ep) != 0 { return endpoints.ResolvedEndpoint{ URL: endpoints.AddScheme(ep, aws.BoolValue(cfg.DisableSSL)), SigningRegion: region, }, nil } resolved, err := cfg.EndpointResolver.EndpointFor(service, region, func(opt *endpoints.Options) { opt.DisableSSL = aws.BoolValue(cfg.DisableSSL) opt.UseDualStack = aws.BoolValue(cfg.UseDualStack) // Support for STSRegionalEndpoint where the STSRegionalEndpoint is // provided in envConfig or sharedConfig with envConfig getting // precedence. opt.STSRegionalEndpoint = cfg.STSRegionalEndpoint // Support for S3UsEast1RegionalEndpoint where the S3UsEast1RegionalEndpoint is // provided in envConfig or sharedConfig with envConfig getting // precedence. opt.S3UsEast1RegionalEndpoint = cfg.S3UsEast1RegionalEndpoint // Support the condition where the service is modeled but its // endpoint metadata is not available. opt.ResolveUnknownService = true }, ) if err != nil { return endpoints.ResolvedEndpoint{}, err } return resolved, nil } // ClientConfigNoResolveEndpoint is the same as ClientConfig with the exception // that the EndpointResolver will not be used to resolve the endpoint. The only // endpoint set must come from the aws.Config.Endpoint field. func (s *Session) ClientConfigNoResolveEndpoint(cfgs ...*aws.Config) client.Config { s = s.Copy(cfgs...) var resolved endpoints.ResolvedEndpoint if ep := aws.StringValue(s.Config.Endpoint); len(ep) > 0 { resolved.URL = endpoints.AddScheme(ep, aws.BoolValue(s.Config.DisableSSL)) resolved.SigningRegion = aws.StringValue(s.Config.Region) } return client.Config{ Config: s.Config, Handlers: s.Handlers, Endpoint: resolved.URL, SigningRegion: resolved.SigningRegion, SigningNameDerived: resolved.SigningNameDerived, SigningName: resolved.SigningName, } } // logDeprecatedNewSessionError function enables error handling for session func (s *Session) logDeprecatedNewSessionError(msg string, err error, cfgs []*aws.Config) { // Session creation failed, need to report the error and prevent // any requests from succeeding. s.Config.MergeIn(cfgs...) s.Config.Logger.Log("ERROR:", msg, "Error:", err) s.Handlers.Validate.PushBack(func(r *request.Request) { r.Error = err }) }
1
10,307
Can we port this error msg to v2 too? This one is better, as it explicitly states what sources are allowed.
aws-aws-sdk-go
go
@@ -3,6 +3,7 @@ var f = require('util').format; var test = require('./shared').assert; var setupDatabase = require('./shared').setupDatabase; +const { ReadPreference } = require('../..'); const Db = require('../../lib/db'); const expect = require('chai').expect;
1
'use strict'; var f = require('util').format; var test = require('./shared').assert; var setupDatabase = require('./shared').setupDatabase; const Db = require('../../lib/db'); const expect = require('chai').expect; describe('MongoClient', function() { before(function() { return setupDatabase(this.configuration); }); it('Should Correctly Do MongoClient with bufferMaxEntries:0 and ordered execution', { metadata: { requires: { topology: ['single', 'ssl', 'wiredtiger'] } }, // The actual test we wish to run test: function(done) { const configuration = this.configuration; if (configuration.usingUnifiedTopology()) { // the new topology is far more resilient in these scenarios, making very difficult // to reproduce the issues tested here. return this.skip(); } const client = configuration.newClient({}, { bufferMaxEntries: 0, sslValidate: false }); client.connect(function(err, client) { var db = client.db(configuration.db); // Listener for closing event var closeListener = function() { // Let's insert a document var collection = db.collection('test_object_id_generation.data2'); // Insert another test document and collect using ObjectId var docs = []; for (var i = 0; i < 1500; i++) docs.push({ a: i }); collection.insert(docs, configuration.writeConcern(), function(err) { test.ok(err != null); test.ok(err.message.indexOf('0') !== -1); // Let's close the db client.close(done); }); }; // Add listener to close event db.once('close', closeListener); // Ensure death of server instance client.topology.connections()[0].destroy(); }); } }); it('Should Correctly Do MongoClient with bufferMaxEntries:0 and unordered execution', { metadata: { requires: { topology: ['single', 'ssl', 'wiredtiger'] } }, // The actual test we wish to run test: function(done) { const configuration = this.configuration; if (configuration.usingUnifiedTopology()) { // the new topology is far more resilient in these scenarios, making very difficult // to reproduce the issues tested here. return this.skip(); } const client = configuration.newClient({}, { bufferMaxEntries: 0, sslValidate: false }); client.connect(function(err, client) { var db = client.db(configuration.db); // Listener for closing event var closeListener = function() { // Let's insert a document var collection = db.collection('test_object_id_generation.data_3'); // Insert another test document and collect using ObjectId var docs = []; for (var i = 0; i < 1500; i++) docs.push({ a: i }); var opts = configuration.writeConcern(); opts.keepGoing = true; // Execute insert collection.insert(docs, opts, function(err) { test.ok(err != null); test.ok(err.message.indexOf('0') !== -1); // Let's close the db client.close(done); }); }; // Add listener to close event db.once('close', closeListener); // Ensure death of server instance client.topology.connections()[0].destroy(); }); } }); it('Should correctly pass through extra db options', { metadata: { requires: { topology: ['single'] } }, // The actual test we wish to run test: function(done) { var configuration = this.configuration; const client = configuration.newClient( {}, { w: 1, wtimeout: 1000, fsync: true, j: true, readPreference: 'nearest', readPreferenceTags: { loc: 'ny' }, native_parser: false, forceServerObjectId: true, pkFactory: function() { return 1; }, serializeFunctions: true, raw: true, numberOfRetries: 10, bufferMaxEntries: 0 } ); client.connect(function(err, client) { var db = client.db(configuration.db); test.equal(1, db.writeConcern.w); test.equal(1000, db.writeConcern.wtimeout); test.equal(true, db.writeConcern.fsync); test.equal(true, db.writeConcern.j); test.equal('nearest', db.s.readPreference.mode); test.deepEqual({ loc: 'ny' }, db.s.readPreference.tags); test.equal(false, db.s.nativeParser); test.equal(true, db.s.options.forceServerObjectId); test.equal(1, db.s.pkFactory()); test.equal(true, db.s.options.serializeFunctions); test.equal(true, db.s.options.raw); test.equal(10, db.s.options.numberOfRetries); test.equal(0, db.s.options.bufferMaxEntries); client.close(done); }); } }); it('Should correctly pass through extra server options', { metadata: { requires: { topology: ['single'] } }, // The actual test we wish to run test: function(done) { const configuration = this.configuration; if (configuration.usingUnifiedTopology()) { // skipped for direct legacy variable inspection return this.skip(); } const client = configuration.newClient( {}, { poolSize: 10, autoReconnect: false, noDelay: false, keepAlive: true, keepAliveInitialDelay: 100, connectTimeoutMS: 444444, socketTimeoutMS: 555555 } ); client.connect(function(err, client) { var db = client.db(configuration.db); test.equal(10, db.s.topology.s.poolSize); test.equal(false, db.s.topology.autoReconnect); test.equal(444444, db.s.topology.s.clonedOptions.connectionTimeout); test.equal(555555, db.s.topology.s.clonedOptions.socketTimeout); test.equal(true, db.s.topology.s.clonedOptions.keepAlive); test.equal(100, db.s.topology.s.clonedOptions.keepAliveInitialDelay); client.close(done); }); } }); it.skip('Should correctly pass through extra replicaset options', { metadata: { requires: { topology: ['replicaset'] } }, // The actual test we wish to run test: function(done) { // NOTE: skipped because this test is using explicit variable names not used by // mongo-orchestration. This behavior should be unit tested without depending // on the test harness used. const configuration = this.configuration; if (configuration.usingUnifiedTopology()) { // skipped for direct legacy variable inspection return this.skip(); } var url = configuration.url().replace('rs_name=rs', 'rs_name=rs1'); const client = configuration.newClient(url, { replSet: { ha: false, haInterval: 10000, replicaSet: 'rs', secondaryAcceptableLatencyMS: 100, connectWithNoPrimary: true, poolSize: 1, socketOptions: { noDelay: false, keepAlive: true, keepAliveInitialDelay: 100, connectTimeoutMS: 444444, socketTimeoutMS: 555555 } } }); client.connect(function(err, client) { expect(err).to.not.exist; var db = client.db(configuration.db); test.equal(false, db.s.topology.s.clonedOptions.ha); test.equal(10000, db.s.topology.s.clonedOptions.haInterval); test.equal('rs', db.s.topology.s.clonedOptions.setName); test.equal(100, db.s.topology.s.clonedOptions.acceptableLatency); test.equal(true, db.s.topology.s.clonedOptions.secondaryOnlyConnectionAllowed); test.equal(1, db.s.topology.s.clonedOptions.size); test.equal(444444, db.s.topology.s.clonedOptions.connectionTimeout); test.equal(555555, db.s.topology.s.clonedOptions.socketTimeout); test.equal(true, db.s.topology.s.clonedOptions.keepAlive); test.equal(100, db.s.topology.s.clonedOptions.keepAliveInitialDelay); client.close(done); }); } }); it('Should correctly pass through extra sharded options', { metadata: { requires: { topology: ['sharded'] } }, // The actual test we wish to run test: function(done) { const configuration = this.configuration; if (configuration.usingUnifiedTopology()) { // skipped for direct legacy variable inspection return this.skip(); } const client = configuration.newClient( {}, { ha: false, haInterval: 10000, acceptableLatencyMS: 100, poolSize: 1, socketOptions: { noDelay: false, keepAlive: true, keepAliveInitialDelay: 100, connectTimeoutMS: 444444, socketTimeoutMS: 555555 } } ); client.connect(function(err, client) { expect(err).to.not.exist; var db = client.db(configuration.db); test.equal(false, db.s.topology.s.clonedOptions.ha); test.equal(10000, db.s.topology.s.clonedOptions.haInterval); test.equal(100, db.s.topology.s.clonedOptions.localThresholdMS); test.equal(1, db.s.topology.s.clonedOptions.poolSize); test.equal(444444, db.s.topology.s.clonedOptions.connectionTimeout); test.equal(555555, db.s.topology.s.clonedOptions.socketTimeout); test.equal(true, db.s.topology.s.clonedOptions.keepAlive); test.equal(100, db.s.topology.s.clonedOptions.keepAliveInitialDelay); client.close(done); }); } }); it('Should correctly set MaxPoolSize on single server', { metadata: { requires: { topology: ['single'] } }, // The actual test we wish to run test: function(done) { const configuration = this.configuration; if (configuration.usingUnifiedTopology()) { // skipped for direct legacy variable inspection return this.skip(); } var url = configuration.url(); url = url.indexOf('?') !== -1 ? f('%s&%s', url, 'maxPoolSize=100') : f('%s?%s', url, 'maxPoolSize=100'); const client = configuration.newClient(url); client.connect(function(err, client) { test.equal(1, client.topology.connections().length); test.equal(100, client.topology.s.coreTopology.s.pool.size); client.close(done); }); } }); it('Should correctly set MaxPoolSize on replicaset server', { metadata: { requires: { topology: ['replicaset'], unifiedTopology: false } }, // The actual test we wish to run test: function(done) { var configuration = this.configuration; var url = configuration.url(); url = url.indexOf('?') !== -1 ? f('%s&%s', url, 'maxPoolSize=100') : f('%s?%s', url, 'maxPoolSize=100'); const client = configuration.newClient(url); client.connect(function(err, client) { test.ok(client.topology.connections().length >= 1); var connections = client.topology.connections(); for (var i = 0; i < connections.length; i++) { test.equal(10000, connections[i].connectionTimeout); test.equal(360000, connections[i].socketTimeout); } client.close(); const secondClient = configuration.newClient(url, { connectTimeoutMS: 15000, socketTimeoutMS: 30000 }); secondClient.connect(function(err) { test.equal(null, err); test.ok(secondClient.topology.connections().length >= 1); var connections = secondClient.topology.connections(); for (var i = 0; i < connections.length; i++) { test.equal(15000, connections[i].connectionTimeout); test.equal(30000, connections[i].socketTimeout); } secondClient.close(done); }); }); } }); it('Should correctly set MaxPoolSize on sharded server', { metadata: { requires: { topology: ['sharded'], unifiedTopology: false } }, // The actual test we wish to run test: function(done) { var configuration = this.configuration; var url = configuration.url(); url = url.indexOf('?') !== -1 ? f('%s&%s', url, 'maxPoolSize=100') : f('%s?%s', url, 'maxPoolSize=100'); const client = configuration.newClient(url); client.connect(function(err, client) { test.ok(client.topology.connections().length >= 1); client.close(done); }); } }); /** * @ignore */ it('Should fail due to wrong uri user:password@localhost', { metadata: { requires: { topology: ['single', 'replicaset', 'sharded', 'ssl', 'heap', 'wiredtiger'] } }, // The actual test we wish to run test: function(done) { var configuration = this.configuration; const client = configuration.newClient('user:password@localhost:27017/test'); client.connect(function(err) { expect(err).to.exist.and.to.have.property('message', 'Invalid connection string'); done(); }); } }); /** * @ignore */ it('Should fail due to wrong uri user:password@localhost, with new url parser', { metadata: { requires: { topology: ['single', 'replicaset', 'sharded', 'ssl', 'heap', 'wiredtiger'] } }, // The actual test we wish to run test: function(done) { var configuration = this.configuration; const client = configuration.newClient('user:password@localhost:27017/test', { useNewUrlParser: true }); client.connect(function(err) { test.equal(err.message, 'Invalid connection string'); done(); }); } }); /** * @ignore */ it('correctly error out when no socket available on MongoClient `connect`', { metadata: { requires: { topology: ['single', 'replicaset', 'sharded', 'ssl', 'heap', 'wiredtiger'] } }, // The actual test we wish to run test: function(done) { var configuration = this.configuration; const client = configuration.newClient('mongodb://localhost:27088/test', { serverSelectionTimeoutMS: 10 }); client.connect(function(err) { test.ok(err != null); done(); }); } }); it('should correctly connect to mongodb using domain socket', { metadata: { requires: { topology: ['single'] } }, // The actual test we wish to run test: function(done) { var configuration = this.configuration; const client = configuration.newClient('mongodb://%2Ftmp%2Fmongodb-27017.sock/test'); client.connect(function(err) { test.equal(null, err); client.close(done); }); } }); /** * @ignore */ it('correctly connect setting keepAlive to 100', { metadata: { requires: { topology: ['single', 'replicaset', 'sharded', 'ssl', 'heap', 'wiredtiger'], unifiedTopology: false } }, // The actual test we wish to run test: function(done) { var configuration = this.configuration; const client = configuration.newClient( {}, { keepAlive: true, keepAliveInitialDelay: 100 } ); client.connect(function(err, client) { test.equal(null, err); var connection = client.topology.connections()[0]; test.equal(true, connection.keepAlive); test.equal(100, connection.keepAliveInitialDelay); client.close(); const secondClient = configuration.newClient({}, { keepAlive: false }); secondClient.connect(function(err) { test.equal(null, err); secondClient.topology.connections().forEach(function(x) { test.equal(false, x.keepAlive); }); secondClient.close(done); }); }); } }); /** * @ignore */ it('default keepAlive behavior', { metadata: { requires: { topology: ['single', 'replicaset', 'sharded', 'ssl', 'heap', 'wiredtiger'], unifiedTopology: false } }, // The actual test we wish to run test: function(done) { var configuration = this.configuration; const client = configuration.newClient(); client.connect(function(err, client) { test.equal(null, err); client.topology.connections().forEach(function(x) { test.equal(true, x.keepAlive); }); client.close(done); }); } }); it('should fail dure to garbage connection string', { metadata: { requires: { topology: ['single'] } }, // The actual test we wish to run test: function(done) { var configuration = this.configuration; const client = configuration.newClient('mongodb://unknownhost:36363/ddddd', { serverSelectionTimeoutMS: 10 }); client.connect(function(err) { test.ok(err != null); done(); }); } }); it.skip('Should fail to connect due to instances not being mongos proxies', { metadata: { requires: { topology: ['replicaset'] } }, // The actual test we wish to run test: function(done) { // NOTE: skipped because this test is using explicit variable names not used by // mongo-orchestration. This behavior should be unit tested without depending // on the test harness used. var configuration = this.configuration; if (configuration.usingUnifiedTopology()) { // this is no longer relevant with the unified topology return this.skip(); } var url = configuration .url() .replace('replicaSet=rs', '') .replace('localhost:31000', 'localhost:31000,localhost:31001'); const client = configuration.newClient(url); client.connect(function(err) { test.ok(err != null); done(); }); } }); it('Should correctly pass through appname', { metadata: { requires: { topology: ['single', 'replicaset', 'sharded'] } }, // The actual test we wish to run test: function(done) { var configuration = this.configuration; var url = configuration.url(); if (url.indexOf('replicaSet') !== -1) { url = f('%s&appname=hello%20world', configuration.url()); } else { url = f('%s?appname=hello%20world', configuration.url()); } const client = configuration.newClient(url); client.connect(function(err, client) { test.equal(null, err); test.equal('hello world', client.topology.clientMetadata.application.name); client.close(done); }); } }); it('Should correctly pass through appname in options', { metadata: { requires: { topology: ['single', 'replicaset', 'sharded'] } }, // The actual test we wish to run test: function(done) { var configuration = this.configuration; var url = configuration.url(); const client = configuration.newClient(url, { appname: 'hello world' }); client.connect(err => { test.equal(null, err); test.equal('hello world', client.topology.clientMetadata.application.name); client.close(done); }); } }); it('Should correctly pass through socketTimeoutMS and connectTimeoutMS', { metadata: { requires: { topology: ['single', 'replicaset', 'sharded'] } }, // The actual test we wish to run test: function(done) { var configuration = this.configuration; const client = configuration.newClient( {}, { socketTimeoutMS: 0, connectTimeoutMS: 0 } ); client.connect(function(err, client) { test.equal(null, err); var db = client.db(configuration.db); if (db.s.topology.s.clonedOptions) { test.equal(0, db.s.topology.s.clonedOptions.connectionTimeout); test.equal(0, db.s.topology.s.clonedOptions.socketTimeout); } else { test.equal(0, db.s.topology.s.options.connectionTimeout); test.equal(0, db.s.topology.s.options.socketTimeout); } client.close(done); }); } }); it('Should correctly pass through socketTimeoutMS and connectTimeoutMS from uri', { metadata: { requires: { topology: ['single'] } }, // The actual test we wish to run test: function(done) { const configuration = this.configuration; if (configuration.usingUnifiedTopology()) { // skipped for direct legacy variable inspection return this.skip(); } var uri = f('%s?socketTimeoutMS=120000&connectTimeoutMS=15000', configuration.url()); const client = configuration.newClient(uri); client.connect(function(err, client) { test.equal(null, err); test.equal(120000, client.topology.s.coreTopology.s.options.socketTimeout); test.equal(15000, client.topology.s.coreTopology.s.options.connectionTimeout); client.close(done); }); } }); ////////////////////////////////////////////////////////////////////////////////////////// // // new MongoClient connection tests // ////////////////////////////////////////////////////////////////////////////////////////// it('Should open a new MongoClient connection', { metadata: { requires: { topology: ['single'] } }, // The actual test we wish to run test: function(done) { var configuration = this.configuration; const client = configuration.newClient(); client.connect(function(err, mongoclient) { test.equal(null, err); mongoclient .db('integration_tests') .collection('new_mongo_client_collection') .insertOne({ a: 1 }, function(err, r) { test.equal(null, err); test.ok(r); mongoclient.close(done); }); }); } }); it('Should open a new MongoClient connection using promise', { metadata: { requires: { topology: ['single'] } }, // The actual test we wish to run test: function(done) { var configuration = this.configuration; const client = configuration.newClient(); client.connect().then(function(mongoclient) { mongoclient .db('integration_tests') .collection('new_mongo_client_collection') .insertOne({ a: 1 }) .then(function(r) { test.ok(r); mongoclient.close(done); }); }); } }); it('Should use compression from URI', { metadata: { requires: { topology: ['single'], unifiedTopology: false } }, // The actual test we wish to run test: function(done) { const configuration = this.configuration; const url = `mongodb://${configuration.host}:${configuration.port}/?compressors=zlib`; const client = configuration.newClient(url, { useNewUrlParser: true }); client.connect(function(err, client) { expect(err).to.not.exist; const db = client.db('integration_tests'); db.collection('new_mongo_client_collection').insertOne({ a: 1 }, (err, r) => { expect(err).to.not.exist; expect(r.connection.options.compression).to.deep.equal({ compressors: ['zlib'] }); client.close(done); }); }); } }); it('should be able to access a database named "constructor"', function() { const client = this.configuration.newClient(); let err; return client .connect() .then(() => { const db = client.db('constructor'); expect(db).to.not.be.a('function'); expect(db).to.be.an.instanceOf(Db); }) .catch(_err => (err = _err)) .then(() => client.close()) .catch(() => {}) .then(() => { if (err) { throw err; } }); }); });
1
18,653
The convention so far has been to require directly from the defining file (in this case `../../read_preference') . I think the concern has been mostly about the potential for circular dependency cycles
mongodb-node-mongodb-native
js
@@ -10,8 +10,9 @@ from ..registry import PIPELINES @PIPELINES.register_module class LoadImageFromFile(object): - def __init__(self, to_float32=False): + def __init__(self, to_float32=False, color_type='color'): self.to_float32 = to_float32 + self.color_type = color_type def __call__(self, results): if results['img_prefix'] is not None:
1
import os.path as osp import mmcv import numpy as np import pycocotools.mask as maskUtils from ..registry import PIPELINES @PIPELINES.register_module class LoadImageFromFile(object): def __init__(self, to_float32=False): self.to_float32 = to_float32 def __call__(self, results): if results['img_prefix'] is not None: filename = osp.join(results['img_prefix'], results['img_info']['filename']) else: filename = results['img_info']['filename'] img = mmcv.imread(filename) if self.to_float32: img = img.astype(np.float32) results['filename'] = filename results['img'] = img results['img_shape'] = img.shape results['ori_shape'] = img.shape return results def __repr__(self): return self.__class__.__name__ + '(to_float32={})'.format( self.to_float32) @PIPELINES.register_module class LoadAnnotations(object): def __init__(self, with_bbox=True, with_label=True, with_mask=False, with_seg=False, poly2mask=True): self.with_bbox = with_bbox self.with_label = with_label self.with_mask = with_mask self.with_seg = with_seg self.poly2mask = poly2mask def _load_bboxes(self, results): ann_info = results['ann_info'] results['gt_bboxes'] = ann_info['bboxes'] gt_bboxes_ignore = ann_info.get('bboxes_ignore', None) if gt_bboxes_ignore is not None: results['gt_bboxes_ignore'] = gt_bboxes_ignore results['bbox_fields'].append('gt_bboxes_ignore') results['bbox_fields'].append('gt_bboxes') return results def _load_labels(self, results): results['gt_labels'] = results['ann_info']['labels'] return results def _poly2mask(self, mask_ann, img_h, img_w): if isinstance(mask_ann, list): # polygon -- a single object might consist of multiple parts # we merge all parts into one mask rle code rles = maskUtils.frPyObjects(mask_ann, img_h, img_w) rle = maskUtils.merge(rles) elif isinstance(mask_ann['counts'], list): # uncompressed RLE rle = maskUtils.frPyObjects(mask_ann, img_h, img_w) else: # rle rle = mask_ann mask = maskUtils.decode(rle) return mask def _load_masks(self, results): h, w = results['img_info']['height'], results['img_info']['width'] gt_masks = results['ann_info']['masks'] if self.poly2mask: gt_masks = [self._poly2mask(mask, h, w) for mask in gt_masks] results['gt_masks'] = gt_masks results['mask_fields'].append('gt_masks') return results def _load_semantic_seg(self, results): results['gt_semantic_seg'] = mmcv.imread( osp.join(results['seg_prefix'], results['ann_info']['seg_map']), flag='unchanged').squeeze() results['seg_fields'].append('gt_semantic_seg') return results def __call__(self, results): if self.with_bbox: results = self._load_bboxes(results) if results is None: return None if self.with_label: results = self._load_labels(results) if self.with_mask: results = self._load_masks(results) if self.with_seg: results = self._load_semantic_seg(results) return results def __repr__(self): repr_str = self.__class__.__name__ repr_str += ('(with_bbox={}, with_label={}, with_mask={},' ' with_seg={})').format(self.with_bbox, self.with_label, self.with_mask, self.with_seg) return repr_str @PIPELINES.register_module class LoadProposals(object): def __init__(self, num_max_proposals=None): self.num_max_proposals = num_max_proposals def __call__(self, results): proposals = results['proposals'] if proposals.shape[1] not in (4, 5): raise AssertionError( 'proposals should have shapes (n, 4) or (n, 5), ' 'but found {}'.format(proposals.shape)) proposals = proposals[:, :4] if self.num_max_proposals is not None: proposals = proposals[:self.num_max_proposals] if len(proposals) == 0: proposals = np.array([[0, 0, 0, 0]], dtype=np.float32) results['proposals'] = proposals results['bbox_fields'].append('proposals') return results def __repr__(self): return self.__class__.__name__ + '(num_max_proposals={})'.format( self.num_max_proposals)
1
18,455
I suggest expanding dims here to simplify the formatting.
open-mmlab-mmdetection
py
@@ -9,7 +9,7 @@ from pyramid.paster import bootstrap from kinto.config import init -CONFIG_FILE = 'config/kinto.ini' +CONFIG_FILE = 'kinto/config/kinto.ini' def main(args=None):
1
from __future__ import print_function import argparse import os import sys from six.moves import input from cliquet.scripts import cliquet from pyramid.scripts import pserve from pyramid.paster import bootstrap from kinto.config import init CONFIG_FILE = 'config/kinto.ini' def main(args=None): """The main routine.""" if args is None: args = sys.argv[1:] parser = argparse.ArgumentParser(description="Kinto commands") parser.add_argument('--ini', help='Application configuration file', dest='ini_file', required=False, default=CONFIG_FILE) parser.add_argument('--backend', help='Specify backend', dest='backend', required=False, default=None) subparsers = parser.add_subparsers(title='subcommands', description='valid subcommands', help='init/start/migrate') parser_init = subparsers.add_parser('init') parser_init.set_defaults(which='init') parser_migrate = subparsers.add_parser('migrate') parser_migrate.set_defaults(which='migrate') parser_start = subparsers.add_parser('start') parser_start.set_defaults(which='start') args = vars(parser.parse_args()) config_file = args['ini_file'] if args['which'] == 'init': if os.path.exists(config_file): print("%s already exist." % config_file, file=sys.stderr) sys.exit(1) backend = args['backend'] if not backend: while True: prompt = ("Which backend to use? " "(1 - postgresql, 2 - redis, default - memory) ") answer = input(prompt).strip() try: backends = {"1": "postgresql", "2": "redis", "": "memory"} backend = backends[answer] break except KeyError: pass init(config_file, backend) elif args['which'] == 'migrate': env = bootstrap(config_file) cliquet.init_schema(env) elif args['which'] == 'start': pserve_argv = ['pserve', config_file, '--reload'] pserve.main(pserve_argv) if __name__ == "__main__": main()
1
8,339
Why do you need to specify the kinto prefix here?
Kinto-kinto
py
@@ -45,7 +45,7 @@ class FPN(nn.Module): >>> self = FPN(in_channels, 11, len(in_channels)).eval() >>> outputs = self.forward(inputs) >>> for i in range(len(outputs)): - ... print('outputs[{}].shape = {!r}'.format(i, outputs[i].shape)) + ... print(f'outputs[{i}].shape = {outputs[i].shape!r}') outputs[0].shape = torch.Size([1, 11, 340, 340]) outputs[1].shape = torch.Size([1, 11, 170, 170]) outputs[2].shape = torch.Size([1, 11, 84, 84])
1
import torch.nn as nn import torch.nn.functional as F from mmcv.cnn import xavier_init from mmdet.core import auto_fp16 from mmdet.ops import ConvModule from ..builder import NECKS @NECKS.register_module class FPN(nn.Module): """ Feature Pyramid Network. This is an implementation of - Feature Pyramid Networks for Object Detection (https://arxiv.org/abs/1612.03144) Args: in_channels (List[int]): Number of input channels per scale. out_channels (int): Number of output channels (used at each scale) num_outs (int): Number of output scales. start_level (int): Index of the start input backbone level used to build the feature pyramid. Default: 0. end_level (int): Index of the end input backbone level (exclusive) to build the feature pyramid. Default: -1, which means the last level. add_extra_convs (bool): Whether to add conv layers on top of the original feature maps. Default: False. extra_convs_on_inputs (bool): Whether to apply extra conv on the original feature from the backbone. Default: False. relu_before_extra_convs (bool): Whether to apply relu before the extra conv. Default: False. no_norm_on_lateral (bool): Whether to apply norm on lateral. Default: False. conv_cfg (dict): Config dict for convolution layer. Default: None. norm_cfg (dict): Config dict for normalization layer. Default: None. act_cfg (str): Config dict for activation layer in ConvModule. Default: None. Example: >>> import torch >>> in_channels = [2, 3, 5, 7] >>> scales = [340, 170, 84, 43] >>> inputs = [torch.rand(1, c, s, s) ... for c, s in zip(in_channels, scales)] >>> self = FPN(in_channels, 11, len(in_channels)).eval() >>> outputs = self.forward(inputs) >>> for i in range(len(outputs)): ... print('outputs[{}].shape = {!r}'.format(i, outputs[i].shape)) outputs[0].shape = torch.Size([1, 11, 340, 340]) outputs[1].shape = torch.Size([1, 11, 170, 170]) outputs[2].shape = torch.Size([1, 11, 84, 84]) outputs[3].shape = torch.Size([1, 11, 43, 43]) """ def __init__(self, in_channels, out_channels, num_outs, start_level=0, end_level=-1, add_extra_convs=False, extra_convs_on_inputs=True, relu_before_extra_convs=False, no_norm_on_lateral=False, conv_cfg=None, norm_cfg=None, act_cfg=None): super(FPN, self).__init__() assert isinstance(in_channels, list) self.in_channels = in_channels self.out_channels = out_channels self.num_ins = len(in_channels) self.num_outs = num_outs self.relu_before_extra_convs = relu_before_extra_convs self.no_norm_on_lateral = no_norm_on_lateral self.fp16_enabled = False if end_level == -1: self.backbone_end_level = self.num_ins assert num_outs >= self.num_ins - start_level else: # if end_level < inputs, no extra level is allowed self.backbone_end_level = end_level assert end_level <= len(in_channels) assert num_outs == end_level - start_level self.start_level = start_level self.end_level = end_level self.add_extra_convs = add_extra_convs self.extra_convs_on_inputs = extra_convs_on_inputs self.lateral_convs = nn.ModuleList() self.fpn_convs = nn.ModuleList() for i in range(self.start_level, self.backbone_end_level): l_conv = ConvModule( in_channels[i], out_channels, 1, conv_cfg=conv_cfg, norm_cfg=norm_cfg if not self.no_norm_on_lateral else None, act_cfg=act_cfg, inplace=False) fpn_conv = ConvModule( out_channels, out_channels, 3, padding=1, conv_cfg=conv_cfg, norm_cfg=norm_cfg, act_cfg=act_cfg, inplace=False) self.lateral_convs.append(l_conv) self.fpn_convs.append(fpn_conv) # add extra conv layers (e.g., RetinaNet) extra_levels = num_outs - self.backbone_end_level + self.start_level if add_extra_convs and extra_levels >= 1: for i in range(extra_levels): if i == 0 and self.extra_convs_on_inputs: in_channels = self.in_channels[self.backbone_end_level - 1] else: in_channels = out_channels extra_fpn_conv = ConvModule( in_channels, out_channels, 3, stride=2, padding=1, conv_cfg=conv_cfg, norm_cfg=norm_cfg, act_cfg=act_cfg, inplace=False) self.fpn_convs.append(extra_fpn_conv) # default init_weights for conv(msra) and norm in ConvModule def init_weights(self): for m in self.modules(): if isinstance(m, nn.Conv2d): xavier_init(m, distribution='uniform') @auto_fp16() def forward(self, inputs): assert len(inputs) == len(self.in_channels) # build laterals laterals = [ lateral_conv(inputs[i + self.start_level]) for i, lateral_conv in enumerate(self.lateral_convs) ] # build top-down path used_backbone_levels = len(laterals) for i in range(used_backbone_levels - 1, 0, -1): prev_shape = laterals[i - 1].shape[2:] laterals[i - 1] += F.interpolate( laterals[i], size=prev_shape, mode='nearest') # build outputs # part 1: from original levels outs = [ self.fpn_convs[i](laterals[i]) for i in range(used_backbone_levels) ] # part 2: add extra levels if self.num_outs > len(outs): # use max pool to get more levels on top of outputs # (e.g., Faster R-CNN, Mask R-CNN) if not self.add_extra_convs: for i in range(self.num_outs - used_backbone_levels): outs.append(F.max_pool2d(outs[-1], 1, stride=2)) # add conv layers on top of original feature maps (RetinaNet) else: if self.extra_convs_on_inputs: orig = inputs[self.backbone_end_level - 1] outs.append(self.fpn_convs[used_backbone_levels](orig)) else: outs.append(self.fpn_convs[used_backbone_levels](outs[-1])) for i in range(used_backbone_levels + 1, self.num_outs): if self.relu_before_extra_convs: outs.append(self.fpn_convs[i](F.relu(outs[-1]))) else: outs.append(self.fpn_convs[i](outs[-1])) return tuple(outs)
1
19,264
The `!r` is unnecessary.
open-mmlab-mmdetection
py
@@ -161,7 +161,7 @@ func (o *lazyCredsOpener) OpenBucketURL(ctx context.Context, u *url.URL) (*blob. isMSIEnvironment := adal.MSIAvailable(ctx, adal.CreateSender()) - if accountKey != "" { + if accountKey != "" || sasToken != "" { o.opener, o.err = openerFromEnv(accountName, accountKey, sasToken, storageDomain, protocol) } else if isMSIEnvironment { o.opener, o.err = openerFromMSI(accountName, storageDomain, protocol)
1
// Copyright 2018 The Go Cloud Development Kit Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package azureblob provides a blob implementation that uses Azure Storage’s // BlockBlob. Use OpenBucket to construct a *blob.Bucket. // // NOTE: SignedURLs for PUT created with this package are not fully portable; // they will not work unless the PUT request includes a "x-ms-blob-type" header // set to "BlockBlob". // See https://stackoverflow.com/questions/37824136/put-on-sas-blob-url-without-specifying-x-ms-blob-type-header. // // URLs // // For blob.OpenBucket, azureblob registers for the scheme "azblob". // The default URL opener will use credentials from the environment variables // AZURE_STORAGE_ACCOUNT, AZURE_STORAGE_KEY, and AZURE_STORAGE_SAS_TOKEN. // AZURE_STORAGE_ACCOUNT is required, along with one of the other two. // AZURE_STORAGE_DOMAIN can optionally be used to provide an Azure Environment // blob storage domain to use. If no AZURE_STORAGE_DOMAIN is provided, the // default Azure public domain "blob.core.windows.net" will be used. Check // the Azure Developer Guide for your particular cloud environment to see // the proper blob storage domain name to provide. // To customize the URL opener, or for more details on the URL format, // see URLOpener. // See https://gocloud.dev/concepts/urls/ for background information. // // Escaping // // Go CDK supports all UTF-8 strings; to make this work with services lacking // full UTF-8 support, strings must be escaped (during writes) and unescaped // (during reads). The following escapes are performed for azureblob: // - Blob keys: ASCII characters 0-31, 92 ("\"), and 127 are escaped to // "__0x<hex>__". Additionally, the "/" in "../" and a trailing "/" in a // key (e.g., "foo/") are escaped in the same way. // - Metadata keys: Per https://docs.microsoft.com/en-us/azure/storage/blobs/storage-properties-metadata, // Azure only allows C# identifiers as metadata keys. Therefore, characters // other than "[a-z][A-z][0-9]_" are escaped using "__0x<hex>__". In addition, // characters "[0-9]" are escaped when they start the string. // URL encoding would not work since "%" is not valid. // - Metadata values: Escaped using URL encoding. // // As // // azureblob exposes the following types for As: // - Bucket: *azblob.ContainerURL // - Error: azblob.StorageError // - ListObject: azblob.BlobItemInternal for objects, azblob.BlobPrefix for "directories" // - ListOptions.BeforeList: *azblob.ListBlobsSegmentOptions // - Reader: azblob.DownloadResponse // - Reader.BeforeRead: *azblob.BlockBlobURL, *azblob.BlobAccessConditions // - Attributes: azblob.BlobGetPropertiesResponse // - CopyOptions.BeforeCopy: azblob.Metadata, *azblob.ModifiedAccessConditions, *azblob.BlobAccessConditions // - WriterOptions.BeforeWrite: *azblob.UploadStreamToBlockBlobOptions // - SignedURLOptions.BeforeSign: *azblob.BlobSASSignatureValues package azureblob import ( "context" "errors" "fmt" "io" "net/http" "net/url" "os" "sort" "strconv" "strings" "sync" "time" "github.com/Azure/azure-pipeline-go/pipeline" "github.com/Azure/azure-storage-blob-go/azblob" "github.com/Azure/go-autorest/autorest/adal" "github.com/Azure/go-autorest/autorest/azure" "github.com/google/uuid" "github.com/google/wire" "gocloud.dev/blob" "gocloud.dev/blob/driver" "gocloud.dev/gcerrors" "gocloud.dev/internal/escape" "gocloud.dev/internal/gcerr" "gocloud.dev/internal/useragent" ) const ( tokenRefreshTolerance = 300 ) // Options sets options for constructing a *blob.Bucket backed by Azure Block Blob. type Options struct { // Credential represents the authorizer for SignedURL. // Required to use SignedURL. If you're using MSI for authentication, this will // attempt to be loaded lazily the first time you call SignedURL. Credential azblob.StorageAccountCredential // SASToken can be provided along with anonymous credentials to use // delegated privileges. // See https://docs.microsoft.com/en-us/azure/storage/common/storage-dotnet-shared-access-signature-part-1#shared-access-signature-parameters. SASToken SASToken // StorageDomain can be provided to specify an Azure Cloud Environment // domain to target for the blob storage account (i.e. public, government, china). // The default value is "blob.core.windows.net". Possible values will look similar // to this but are different for each cloud (i.e. "blob.core.govcloudapi.net" for USGovernment). // Check the Azure developer guide for the cloud environment where your bucket resides. StorageDomain StorageDomain // Protocol can be provided to specify protocol to access Azure Blob Storage. // Protocols that can be specified are "http" for local emulator and "https" for general. // If blank is specified, "https" will be used. Protocol Protocol } const ( defaultMaxDownloadRetryRequests = 3 // download retry policy (Azure default is zero) defaultPageSize = 1000 // default page size for ListPaged (Azure default is 5000) defaultUploadBuffers = 5 // configure the number of rotating buffers that are used when uploading (for degree of parallelism) defaultUploadBlockSize = 8 * 1024 * 1024 // configure the upload buffer size ) func init() { blob.DefaultURLMux().RegisterBucket(Scheme, new(lazyCredsOpener)) } // Set holds Wire providers for this package. var Set = wire.NewSet( NewPipeline, wire.Struct(new(Options), "Credential", "SASToken"), wire.Struct(new(URLOpener), "AccountName", "Pipeline", "Options"), ) // lazyCredsOpener obtains credentials from the environment on the first call // to OpenBucketURL. type lazyCredsOpener struct { init sync.Once opener *URLOpener err error } func (o *lazyCredsOpener) OpenBucketURL(ctx context.Context, u *url.URL) (*blob.Bucket, error) { o.init.Do(func() { // Use default credential info from the environment. // Ignore errors, as we'll get errors from OpenBucket later. accountName, _ := DefaultAccountName() accountKey, _ := DefaultAccountKey() sasToken, _ := DefaultSASToken() storageDomain, _ := DefaultStorageDomain() protocol, _ := DefaultProtocol() isMSIEnvironment := adal.MSIAvailable(ctx, adal.CreateSender()) if accountKey != "" { o.opener, o.err = openerFromEnv(accountName, accountKey, sasToken, storageDomain, protocol) } else if isMSIEnvironment { o.opener, o.err = openerFromMSI(accountName, storageDomain, protocol) } else { o.opener, o.err = openerFromAnon(accountName, storageDomain, protocol) } }) if o.err != nil { return nil, fmt.Errorf("open bucket %v: %v", u, o.err) } return o.opener.OpenBucketURL(ctx, u) } // Scheme is the URL scheme gcsblob registers its URLOpener under on // blob.DefaultMux. const Scheme = "azblob" // URLOpener opens Azure URLs like "azblob://mybucket". // // The URL host is used as the bucket name. // // The following query options are supported: // - domain: The domain name used to access the Azure Blob storage (e.g. blob.core.windows.net) type URLOpener struct { // AccountName must be specified. AccountName AccountName // Pipeline must be set to a non-nil value. Pipeline pipeline.Pipeline // Options specifies the options to pass to OpenBucket. Options Options } func openerFromEnv(accountName AccountName, accountKey AccountKey, sasToken SASToken, storageDomain StorageDomain, protocol Protocol) (*URLOpener, error) { // azblob.Credential is an interface; we will use either a SharedKeyCredential // or anonymous credentials. If the former, we will also fill in // Options.Credential so that SignedURL will work. var credential azblob.Credential var storageAccountCredential azblob.StorageAccountCredential if accountKey != "" { sharedKeyCred, err := NewCredential(accountName, accountKey) if err != nil { return nil, fmt.Errorf("invalid credentials %s/%s: %v", accountName, accountKey, err) } credential = sharedKeyCred storageAccountCredential = sharedKeyCred } else { credential = azblob.NewAnonymousCredential() } return &URLOpener{ AccountName: accountName, Pipeline: NewPipeline(credential, azblob.PipelineOptions{}), Options: Options{ Credential: storageAccountCredential, SASToken: sasToken, StorageDomain: storageDomain, Protocol: protocol, }, }, nil } // openerFromAnon creates an anonymous credential backend URLOpener func openerFromAnon(accountName AccountName, storageDomain StorageDomain, protocol Protocol) (*URLOpener, error) { return &URLOpener{ AccountName: accountName, Pipeline: NewPipeline(azblob.NewAnonymousCredential(), azblob.PipelineOptions{}), Options: Options{ StorageDomain: storageDomain, Protocol: protocol, }, }, nil } var defaultTokenRefreshFunction = func(spToken *adal.ServicePrincipalToken) func(credential azblob.TokenCredential) time.Duration { return func(credential azblob.TokenCredential) time.Duration { err := spToken.Refresh() if err != nil { return 0 } expiresIn, err := strconv.ParseInt(string(spToken.Token().ExpiresIn), 10, 64) if err != nil { return 0 } credential.SetToken(spToken.Token().AccessToken) return time.Duration(expiresIn-tokenRefreshTolerance) * time.Second } } // openerFromMSI acquires an MSI token and returns TokenCredential backed URLOpener func openerFromMSI(accountName AccountName, storageDomain StorageDomain, protocol Protocol) (*URLOpener, error) { spToken, err := getMSIServicePrincipalToken(azure.PublicCloud.ResourceIdentifiers.Storage) if err != nil { return nil, fmt.Errorf("failure acquiring token from MSI endpoint %w", err) } err = spToken.Refresh() if err != nil { return nil, fmt.Errorf("failure refreshing token from MSI endpoint %w", err) } credential := azblob.NewTokenCredential(spToken.Token().AccessToken, defaultTokenRefreshFunction(spToken)) return &URLOpener{ AccountName: accountName, Pipeline: NewPipeline(credential, azblob.PipelineOptions{}), Options: Options{ StorageDomain: storageDomain, Protocol: protocol, }, }, nil } // getMSIServicePrincipalToken retrieves Azure API Service Principal token. func getMSIServicePrincipalToken(resource string) (*adal.ServicePrincipalToken, error) { msiEndpoint, err := adal.GetMSIEndpoint() if err != nil { return nil, fmt.Errorf("failed to get the managed service identity endpoint: %v", err) } token, err := adal.NewServicePrincipalTokenFromMSI(msiEndpoint, resource) if err != nil { return nil, fmt.Errorf("failed to create the managed service identity token: %v", err) } return token, nil } // OpenBucketURL opens a blob.Bucket based on u. func (o *URLOpener) OpenBucketURL(ctx context.Context, u *url.URL) (*blob.Bucket, error) { opts := new(Options) *opts = o.Options err := setOptionsFromURLParams(u.Query(), opts) if err != nil { return nil, err } return OpenBucket(ctx, o.Pipeline, o.AccountName, u.Host, opts) } func setOptionsFromURLParams(q url.Values, o *Options) error { for param, values := range q { if len(values) > 1 { return fmt.Errorf("multiple values of %v not allowed", param) } value := values[0] switch param { case "domain": o.StorageDomain = StorageDomain(value) default: return fmt.Errorf("unknown query parameter %q", param) } } return nil } // DefaultIdentity is a Wire provider set that provides an Azure storage // account name, key, and SharedKeyCredential from environment variables. var DefaultIdentity = wire.NewSet( DefaultAccountName, DefaultAccountKey, NewCredential, wire.Bind(new(azblob.Credential), new(*azblob.SharedKeyCredential)), wire.Value(azblob.PipelineOptions{}), ) // SASTokenIdentity is a Wire provider set that provides an Azure storage // account name, SASToken, and anonymous credential from environment variables. var SASTokenIdentity = wire.NewSet( DefaultAccountName, DefaultSASToken, azblob.NewAnonymousCredential, wire.Value(azblob.PipelineOptions{}), ) // AccountName is an Azure storage account name. type AccountName string // AccountKey is an Azure storage account key (primary or secondary). type AccountKey string // SASToken is an Azure shared access signature. // https://docs.microsoft.com/en-us/azure/storage/common/storage-dotnet-shared-access-signature-part-1 type SASToken string // StorageDomain is an Azure Cloud Environment domain name to target // (i.e. blob.core.windows.net, blob.core.govcloudapi.net, blob.core.chinacloudapi.cn). // It is read from the AZURE_STORAGE_DOMAIN environment variable. type StorageDomain string // Protocol is an protocol to access Azure Blob Storage. // It must be "http" or "https". // It is read from the AZURE_STORAGE_PROTOCOL environment variable. type Protocol string // DefaultAccountName loads the Azure storage account name from the // AZURE_STORAGE_ACCOUNT environment variable. func DefaultAccountName() (AccountName, error) { s := os.Getenv("AZURE_STORAGE_ACCOUNT") if s == "" { return "", errors.New("azureblob: environment variable AZURE_STORAGE_ACCOUNT not set") } return AccountName(s), nil } // DefaultAccountKey loads the Azure storage account key (primary or secondary) // from the AZURE_STORAGE_KEY environment variable. func DefaultAccountKey() (AccountKey, error) { s := os.Getenv("AZURE_STORAGE_KEY") if s == "" { return "", errors.New("azureblob: environment variable AZURE_STORAGE_KEY not set") } return AccountKey(s), nil } // DefaultSASToken loads a Azure SAS token from the AZURE_STORAGE_SAS_TOKEN // environment variable. func DefaultSASToken() (SASToken, error) { s := os.Getenv("AZURE_STORAGE_SAS_TOKEN") if s == "" { return "", errors.New("azureblob: environment variable AZURE_STORAGE_SAS_TOKEN not set") } return SASToken(s), nil } // DefaultStorageDomain loads the desired Azure Cloud to target from // the AZURE_STORAGE_DOMAIN environment variable. func DefaultStorageDomain() (StorageDomain, error) { s := os.Getenv("AZURE_STORAGE_DOMAIN") return StorageDomain(s), nil } // DefaultProtocol loads the protocol to access Azure Blob Storage from the // AZURE_STORAGE_PROTOCOL environment variable. func DefaultProtocol() (Protocol, error) { s := os.Getenv("AZURE_STORAGE_PROTOCOL") return Protocol(s), nil } // NewCredential creates a SharedKeyCredential. func NewCredential(accountName AccountName, accountKey AccountKey) (*azblob.SharedKeyCredential, error) { return azblob.NewSharedKeyCredential(string(accountName), string(accountKey)) } // NewPipeline creates a Pipeline for making HTTP requests to Azure. func NewPipeline(credential azblob.Credential, opts azblob.PipelineOptions) pipeline.Pipeline { opts.Telemetry.Value = useragent.AzureUserAgentPrefix("blob") + opts.Telemetry.Value return azblob.NewPipeline(credential, opts) } // bucket represents a Azure Storage Account Container, which handles read, // write and delete operations on objects within it. // See https://docs.microsoft.com/en-us/azure/storage/blobs/storage-blobs-introduction. type bucket struct { name string pageMarkers map[string]azblob.Marker serviceURL *azblob.ServiceURL containerURL azblob.ContainerURL opts *Options mu sync.Mutex // protect the fields below credentialExpiration time.Time delegationCredentials azblob.StorageAccountCredential } // OpenBucket returns a *blob.Bucket backed by Azure Storage Account. See the package // documentation for an example and // https://godoc.org/github.com/Azure/azure-storage-blob-go/azblob // for more details. func OpenBucket(ctx context.Context, pipeline pipeline.Pipeline, accountName AccountName, containerName string, opts *Options) (*blob.Bucket, error) { b, err := openBucket(ctx, pipeline, accountName, containerName, opts) if err != nil { return nil, err } return blob.NewBucket(b), nil } func openBucket(ctx context.Context, pipeline pipeline.Pipeline, accountName AccountName, containerName string, opts *Options) (*bucket, error) { if pipeline == nil { return nil, errors.New("azureblob.OpenBucket: pipeline is required") } if accountName == "" { return nil, errors.New("azureblob.OpenBucket: accountName is required") } if containerName == "" { return nil, errors.New("azureblob.OpenBucket: containerName is required") } if opts == nil { opts = &Options{} } if opts.StorageDomain == "" { // If opts.StorageDomain is missing, use default domain. opts.StorageDomain = "blob.core.windows.net" } switch opts.Protocol { case "": // If opts.Protocol is missing, use "https". opts.Protocol = "https" case "https", "http": default: return nil, errors.New("azureblob.OpenBucket: protocol must be http or https") } d := string(opts.StorageDomain) var u string // The URL structure of the local emulator is a bit different from the real one. if strings.HasPrefix(d, "127.0.0.1") || strings.HasPrefix(d, "localhost") { u = fmt.Sprintf("%s://%s/%s", opts.Protocol, opts.StorageDomain, accountName) // http://127.0.0.1:10000/devstoreaccount1 } else { u = fmt.Sprintf("%s://%s.%s", opts.Protocol, accountName, opts.StorageDomain) // https://myaccount.blob.core.windows.net } blobURL, err := url.Parse(u) if err != nil { return nil, err } if opts.SASToken != "" { // The Azure portal includes a leading "?" for the SASToken, which we // don't want here. blobURL.RawQuery = strings.TrimPrefix(string(opts.SASToken), "?") } serviceURL := azblob.NewServiceURL(*blobURL, pipeline) return &bucket{ name: containerName, pageMarkers: map[string]azblob.Marker{}, serviceURL: &serviceURL, containerURL: serviceURL.NewContainerURL(containerName), opts: opts, }, nil } // Close implements driver.Close. func (b *bucket) Close() error { return nil } // Copy implements driver.Copy. func (b *bucket) Copy(ctx context.Context, dstKey, srcKey string, opts *driver.CopyOptions) error { dstKey = escapeKey(dstKey, false) dstBlobURL := b.containerURL.NewBlobURL(dstKey) srcKey = escapeKey(srcKey, false) srcURL := b.containerURL.NewBlobURL(srcKey).URL() md := azblob.Metadata{} mac := azblob.ModifiedAccessConditions{} bac := azblob.BlobAccessConditions{} at := azblob.AccessTierNone btm := azblob.BlobTagsMap{} if opts.BeforeCopy != nil { asFunc := func(i interface{}) bool { switch v := i.(type) { case *azblob.Metadata: *v = md return true case **azblob.ModifiedAccessConditions: *v = &mac return true case **azblob.BlobAccessConditions: *v = &bac return true } return false } if err := opts.BeforeCopy(asFunc); err != nil { return err } } resp, err := dstBlobURL.StartCopyFromURL(ctx, srcURL, md, mac, bac, at, btm) if err != nil { return err } copyStatus := resp.CopyStatus() nErrors := 0 for copyStatus == azblob.CopyStatusPending { // Poll until the copy is complete. time.Sleep(500 * time.Millisecond) propertiesResp, err := dstBlobURL.GetProperties(ctx, azblob.BlobAccessConditions{}, azblob.ClientProvidedKeyOptions{}) if err != nil { // A GetProperties failure may be transient, so allow a couple // of them before giving up. nErrors++ if ctx.Err() != nil || nErrors == 3 { return err } } copyStatus = propertiesResp.CopyStatus() } if copyStatus != azblob.CopyStatusSuccess { return fmt.Errorf("Copy failed with status: %s", copyStatus) } return nil } // Delete implements driver.Delete. func (b *bucket) Delete(ctx context.Context, key string) error { key = escapeKey(key, false) blockBlobURL := b.containerURL.NewBlockBlobURL(key) _, err := blockBlobURL.Delete(ctx, azblob.DeleteSnapshotsOptionInclude, azblob.BlobAccessConditions{}) return err } // reader reads an azblob. It implements io.ReadCloser. type reader struct { body io.ReadCloser attrs driver.ReaderAttributes raw *azblob.DownloadResponse } func (r *reader) Read(p []byte) (int, error) { return r.body.Read(p) } func (r *reader) Close() error { return r.body.Close() } func (r *reader) Attributes() *driver.ReaderAttributes { return &r.attrs } func (r *reader) As(i interface{}) bool { p, ok := i.(*azblob.DownloadResponse) if !ok { return false } *p = *r.raw return true } // NewRangeReader implements driver.NewRangeReader. func (b *bucket) NewRangeReader(ctx context.Context, key string, offset, length int64, opts *driver.ReaderOptions) (driver.Reader, error) { key = escapeKey(key, false) blockBlobURL := b.containerURL.NewBlockBlobURL(key) blockBlobURLp := &blockBlobURL accessConditions := &azblob.BlobAccessConditions{} end := length if end < 0 { end = azblob.CountToEnd } if opts.BeforeRead != nil { asFunc := func(i interface{}) bool { if p, ok := i.(**azblob.BlockBlobURL); ok { *p = blockBlobURLp return true } if p, ok := i.(**azblob.BlobAccessConditions); ok { *p = accessConditions return true } return false } if err := opts.BeforeRead(asFunc); err != nil { return nil, err } } blobDownloadResponse, err := blockBlobURLp.Download(ctx, offset, end, *accessConditions, false, azblob.ClientProvidedKeyOptions{}) if err != nil { return nil, err } attrs := driver.ReaderAttributes{ ContentType: blobDownloadResponse.ContentType(), Size: getSize(blobDownloadResponse.ContentLength(), blobDownloadResponse.ContentRange()), ModTime: blobDownloadResponse.LastModified(), } var body io.ReadCloser if length == 0 { body = http.NoBody } else { body = blobDownloadResponse.Body(azblob.RetryReaderOptions{MaxRetryRequests: defaultMaxDownloadRetryRequests}) } return &reader{ body: body, attrs: attrs, raw: blobDownloadResponse, }, nil } func getSize(contentLength int64, contentRange string) int64 { // Default size to ContentLength, but that's incorrect for partial-length reads, // where ContentLength refers to the size of the returned Body, not the entire // size of the blob. ContentRange has the full size. size := contentLength if contentRange != "" { // Sample: bytes 10-14/27 (where 27 is the full size). parts := strings.Split(contentRange, "/") if len(parts) == 2 { if i, err := strconv.ParseInt(parts[1], 10, 64); err == nil { size = i } } } return size } // As implements driver.As. func (b *bucket) As(i interface{}) bool { p, ok := i.(**azblob.ContainerURL) if !ok { return false } *p = &b.containerURL return true } // As implements driver.ErrorAs. func (b *bucket) ErrorAs(err error, i interface{}) bool { switch v := err.(type) { case azblob.StorageError: if p, ok := i.(*azblob.StorageError); ok { *p = v return true } } return false } func (b *bucket) ErrorCode(err error) gcerrors.ErrorCode { serr, ok := err.(azblob.StorageError) switch { case !ok: // This happens with an invalid storage account name; the host // is something like invalidstorageaccount.blob.core.windows.net. if strings.Contains(err.Error(), "no such host") { return gcerrors.NotFound } return gcerrors.Unknown case serr.ServiceCode() == azblob.ServiceCodeBlobNotFound || serr.Response().StatusCode == 404: // Check and fail both the SDK ServiceCode and the Http Response Code for NotFound return gcerrors.NotFound case serr.ServiceCode() == azblob.ServiceCodeAuthenticationFailed: return gcerrors.PermissionDenied default: return gcerrors.Unknown } } // Attributes implements driver.Attributes. func (b *bucket) Attributes(ctx context.Context, key string) (*driver.Attributes, error) { key = escapeKey(key, false) blockBlobURL := b.containerURL.NewBlockBlobURL(key) blobPropertiesResponse, err := blockBlobURL.GetProperties(ctx, azblob.BlobAccessConditions{}, azblob.ClientProvidedKeyOptions{}) if err != nil { return nil, err } azureMD := blobPropertiesResponse.NewMetadata() md := make(map[string]string, len(azureMD)) for k, v := range azureMD { // See the package comments for more details on escaping of metadata // keys & values. md[escape.HexUnescape(k)] = escape.URLUnescape(v) } return &driver.Attributes{ CacheControl: blobPropertiesResponse.CacheControl(), ContentDisposition: blobPropertiesResponse.ContentDisposition(), ContentEncoding: blobPropertiesResponse.ContentEncoding(), ContentLanguage: blobPropertiesResponse.ContentLanguage(), ContentType: blobPropertiesResponse.ContentType(), Size: blobPropertiesResponse.ContentLength(), CreateTime: blobPropertiesResponse.CreationTime(), ModTime: blobPropertiesResponse.LastModified(), MD5: blobPropertiesResponse.ContentMD5(), ETag: fmt.Sprintf("%v", blobPropertiesResponse.ETag()), Metadata: md, AsFunc: func(i interface{}) bool { p, ok := i.(*azblob.BlobGetPropertiesResponse) if !ok { return false } *p = *blobPropertiesResponse return true }, }, nil } // ListPaged implements driver.ListPaged. func (b *bucket) ListPaged(ctx context.Context, opts *driver.ListOptions) (*driver.ListPage, error) { pageSize := opts.PageSize if pageSize == 0 { pageSize = defaultPageSize } marker := azblob.Marker{} if len(opts.PageToken) > 0 { if m, ok := b.pageMarkers[string(opts.PageToken)]; ok { marker = m } } azOpts := azblob.ListBlobsSegmentOptions{ MaxResults: int32(pageSize), Prefix: escapeKey(opts.Prefix, true), } if opts.BeforeList != nil { asFunc := func(i interface{}) bool { p, ok := i.(**azblob.ListBlobsSegmentOptions) if !ok { return false } *p = &azOpts return true } if err := opts.BeforeList(asFunc); err != nil { return nil, err } } listBlob, err := b.containerURL.ListBlobsHierarchySegment(ctx, marker, escapeKey(opts.Delimiter, true), azOpts) if err != nil { return nil, err } page := &driver.ListPage{} page.Objects = []*driver.ListObject{} for _, blobPrefix := range listBlob.Segment.BlobPrefixes { page.Objects = append(page.Objects, &driver.ListObject{ Key: unescapeKey(blobPrefix.Name), Size: 0, IsDir: true, AsFunc: func(i interface{}) bool { p, ok := i.(*azblob.BlobPrefix) if !ok { return false } *p = blobPrefix return true }}) } for _, blobInfo := range listBlob.Segment.BlobItems { page.Objects = append(page.Objects, &driver.ListObject{ Key: unescapeKey(blobInfo.Name), ModTime: blobInfo.Properties.LastModified, Size: *blobInfo.Properties.ContentLength, MD5: blobInfo.Properties.ContentMD5, IsDir: false, AsFunc: func(i interface{}) bool { p, ok := i.(*azblob.BlobItemInternal) if !ok { return false } *p = blobInfo return true }, }) } if listBlob.NextMarker.NotDone() { token := uuid.New().String() b.pageMarkers[token] = listBlob.NextMarker page.NextPageToken = []byte(token) } if len(listBlob.Segment.BlobPrefixes) > 0 && len(listBlob.Segment.BlobItems) > 0 { sort.Slice(page.Objects, func(i, j int) bool { return page.Objects[i].Key < page.Objects[j].Key }) } return page, nil } func (b *bucket) refreshDelegationCredentials(ctx context.Context) (azblob.StorageAccountCredential, error) { b.mu.Lock() defer b.mu.Unlock() if time.Now().UTC().After(b.credentialExpiration) { validPeriod := 48 * time.Hour currentTime := time.Now().UTC() expires := currentTime.Add(validPeriod) keyInfo := azblob.NewKeyInfo(currentTime, expires) creds, err := b.serviceURL.GetUserDelegationCredential(ctx, keyInfo, nil /* default timeout */, nil /* no request id */) if err != nil { return nil, err } b.credentialExpiration = expires b.delegationCredentials = creds } return b.delegationCredentials, nil } // SignedURL implements driver.SignedURL. func (b *bucket) SignedURL(ctx context.Context, key string, opts *driver.SignedURLOptions) (string, error) { var credential azblob.StorageAccountCredential if b.opts.Credential != nil { credential = b.opts.Credential } else if isMSIEnvironment := adal.MSIAvailable(ctx, adal.CreateSender()); isMSIEnvironment { var err error credential, err = b.refreshDelegationCredentials(ctx) if err != nil { return "", gcerr.New(gcerr.Internal, err, 1, "azureblob: unable to generate User Delegation Credential") } } else { return "", gcerr.New(gcerr.Unimplemented, nil, 1, "azureblob: to use SignedURL, you must call OpenBucket with a non-nil Options.Credential") } if opts.ContentType != "" || opts.EnforceAbsentContentType { return "", gcerr.New(gcerr.Unimplemented, nil, 1, "azureblob: does not enforce Content-Type on PUT") } key = escapeKey(key, false) blockBlobURL := b.containerURL.NewBlockBlobURL(key) srcBlobParts := azblob.NewBlobURLParts(blockBlobURL.URL()) perms := azblob.BlobSASPermissions{} switch opts.Method { case http.MethodGet: perms.Read = true case http.MethodPut: perms.Create = true perms.Write = true case http.MethodDelete: perms.Delete = true default: return "", fmt.Errorf("unsupported Method %s", opts.Method) } signVals := &azblob.BlobSASSignatureValues{ Protocol: azblob.SASProtocolHTTPS, ExpiryTime: time.Now().UTC().Add(opts.Expiry), ContainerName: b.name, BlobName: srcBlobParts.BlobName, Permissions: perms.String(), } if opts.BeforeSign != nil { asFunc := func(i interface{}) bool { v, ok := i.(**azblob.BlobSASSignatureValues) if ok { *v = signVals } return ok } if err := opts.BeforeSign(asFunc); err != nil { return "", err } } var err error if srcBlobParts.SAS, err = signVals.NewSASQueryParameters(credential); err != nil { return "", err } srcBlobURLWithSAS := srcBlobParts.URL() return srcBlobURLWithSAS.String(), nil } type writer struct { ctx context.Context blockBlobURL *azblob.BlockBlobURL uploadOpts *azblob.UploadStreamToBlockBlobOptions w *io.PipeWriter donec chan struct{} err error } // escapeKey does all required escaping for UTF-8 strings to work with Azure. // isPrefix indicates whether the key is a full key, or a prefix/delimiter. func escapeKey(key string, isPrefix bool) string { return escape.HexEscape(key, func(r []rune, i int) bool { c := r[i] switch { // Azure does not work well with backslashes in blob names. case c == '\\': return true // Azure doesn't handle these characters (determined via experimentation). case c < 32 || c == 127: return true // Escape trailing "/" for full keys, otherwise Azure can't address them // consistently. case !isPrefix && i == len(key)-1 && c == '/': return true // For "../", escape the trailing slash. case i > 1 && r[i] == '/' && r[i-1] == '.' && r[i-2] == '.': return true } return false }) } // unescapeKey reverses escapeKey. func unescapeKey(key string) string { return escape.HexUnescape(key) } // NewTypedWriter implements driver.NewTypedWriter. func (b *bucket) NewTypedWriter(ctx context.Context, key string, contentType string, opts *driver.WriterOptions) (driver.Writer, error) { key = escapeKey(key, false) blockBlobURL := b.containerURL.NewBlockBlobURL(key) if opts.BufferSize == 0 { opts.BufferSize = defaultUploadBlockSize } md := make(map[string]string, len(opts.Metadata)) for k, v := range opts.Metadata { // See the package comments for more details on escaping of metadata // keys & values. e := escape.HexEscape(k, func(runes []rune, i int) bool { c := runes[i] switch { case i == 0 && c >= '0' && c <= '9': return true case escape.IsASCIIAlphanumeric(c): return false case c == '_': return false } return true }) if _, ok := md[e]; ok { return nil, fmt.Errorf("duplicate keys after escaping: %q => %q", k, e) } md[e] = escape.URLEscape(v) } uploadOpts := &azblob.UploadStreamToBlockBlobOptions{ BufferSize: opts.BufferSize, MaxBuffers: defaultUploadBuffers, Metadata: md, BlobHTTPHeaders: azblob.BlobHTTPHeaders{ CacheControl: opts.CacheControl, ContentDisposition: opts.ContentDisposition, ContentEncoding: opts.ContentEncoding, ContentLanguage: opts.ContentLanguage, ContentMD5: opts.ContentMD5, ContentType: contentType, }, } if opts.BeforeWrite != nil { asFunc := func(i interface{}) bool { p, ok := i.(**azblob.UploadStreamToBlockBlobOptions) if !ok { return false } *p = uploadOpts return true } if err := opts.BeforeWrite(asFunc); err != nil { return nil, err } } return &writer{ ctx: ctx, blockBlobURL: &blockBlobURL, uploadOpts: uploadOpts, donec: make(chan struct{}), }, nil } // Write appends p to w. User must call Close to close the w after done writing. func (w *writer) Write(p []byte) (int, error) { if len(p) == 0 { return 0, nil } if w.w == nil { pr, pw := io.Pipe() w.w = pw if err := w.open(pr); err != nil { return 0, err } } return w.w.Write(p) } func (w *writer) open(pr *io.PipeReader) error { go func() { defer close(w.donec) var body io.Reader if pr == nil { body = http.NoBody } else { body = pr } _, w.err = azblob.UploadStreamToBlockBlob(w.ctx, body, *w.blockBlobURL, *w.uploadOpts) if w.err != nil { if pr != nil { pr.CloseWithError(w.err) } return } }() return nil } // Close completes the writer and closes it. Any error occurring during write will // be returned. If a writer is closed before any Write is called, Close will // create an empty file at the given key. func (w *writer) Close() error { if w.w == nil { w.open(nil) } else if err := w.w.Close(); err != nil { return err } <-w.donec return w.err }
1
20,390
I didn't see existing tests for this `OpenBucketURL`. Not sure if it's easy to do without mocking these `opener` calls.
google-go-cloud
go
@@ -21,6 +21,8 @@ namespace AutoRest.Go.TemplateModels // (null or empty if the model is not paged). public string NextLink; + public bool PreparerNeeded; + public ModelTemplateModel(CompositeType source) { this.LoadFrom(source);
1
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using AutoRest.Core.ClientModel; using AutoRest.Core.Utilities; namespace AutoRest.Go.TemplateModels { public class ModelTemplateModel : CompositeType { private readonly IScopeProvider _scope = new VariableScopeProvider(); // True if the type is returned by a method public bool IsResponseType; // Name of the field containing the URL used to retrieve the next result set // (null or empty if the model is not paged). public string NextLink; public ModelTemplateModel(CompositeType source) { this.LoadFrom(source); PropertyTemplateModels = new List<PropertyTemplateModel>(); source.Properties.ForEach(p => PropertyTemplateModels.Add(new PropertyTemplateModel(p))); } public IScopeProvider Scope { get { return _scope; } } public virtual IEnumerable<string> Imports { get { var imports = new HashSet<string>(); (this as CompositeType).AddImports(imports); return imports; } } public List<PropertyTemplateModel> PropertyTemplateModels { get; private set; } } }
1
23,110
Should we default to `true` ?
Azure-autorest
java
@@ -15,6 +15,7 @@ import ( uconfig "go.uber.org/config" "github.com/iotexproject/iotex-core/address" + "github.com/iotexproject/iotex-core/consensus/fsm" "github.com/iotexproject/iotex-core/crypto" "github.com/iotexproject/iotex-core/pkg/keypair" )
1
// Copyright (c) 2018 IoTeX // This is an alpha (internal) release and is not suitable for production. This source code is provided 'as is' and no // warranties are given as to title or non-infringement, merchantability or fitness for purpose and, to the extent // permitted by law, all liability for your use of the code is disclaimed. This source code is governed by Apache // License 2.0 that can be found in the LICENSE file. package config import ( "flag" "os" "time" "github.com/pkg/errors" uconfig "go.uber.org/config" "github.com/iotexproject/iotex-core/address" "github.com/iotexproject/iotex-core/crypto" "github.com/iotexproject/iotex-core/pkg/keypair" ) // IMPORTANT: to define a config, add a field or a new config type to the existing config types. In addition, provide // the default value in Default var. func init() { flag.StringVar(&_overwritePath, "config-path", "", "Config path") flag.StringVar(&_secretPath, "secret-path", "", "Secret path") flag.StringVar(&_subChainPath, "sub-config-path", "", "Sub chain Config path") } var ( // overwritePath is the path to the config file which overwrite default values _overwritePath string // secretPath is the path to the config file store secret values _secretPath string _subChainPath string ) const ( // DelegateType represents the delegate node type DelegateType = "delegate" // FullNodeType represents the full node type FullNodeType = "full_node" // LightweightType represents the lightweight type LightweightType = "lightweight" // RollDPoSScheme means randomized delegated proof of stake RollDPoSScheme = "ROLLDPOS" // StandaloneScheme means that the node creates a block periodically regardless of others (if there is any) StandaloneScheme = "STANDALONE" // NOOPScheme means that the node does not create only block NOOPScheme = "NOOP" ) var ( // Default is the default config Default = Config{ NodeType: FullNodeType, Network: Network{ Host: "127.0.0.1", Port: 4689, ExternalHost: "", ExternalPort: 4689, BootstrapNodes: make([]string, 0), }, Chain: Chain{ ChainDBPath: "/tmp/chain.db", TrieDBPath: "/tmp/trie.db", ID: 1, Address: "", ProducerPubKey: keypair.EncodePublicKey(keypair.ZeroPublicKey), ProducerPrivKey: keypair.EncodePrivateKey(keypair.ZeroPrivateKey), GenesisActionsPath: "", EmptyGenesis: false, NumCandidates: 101, EnableFallBackToFreshDB: false, EnableSubChainStartInGenesis: false, EnableGasCharge: false, }, ActPool: ActPool{ MaxNumActsPerPool: 32000, MaxNumActsPerAcct: 2000, MaxNumActsToPick: 0, }, Consensus: Consensus{ Scheme: NOOPScheme, RollDPoS: RollDPoS{ DelegateInterval: 10 * time.Second, ProposerInterval: 10 * time.Second, UnmatchedEventTTL: 3 * time.Second, UnmatchedEventInterval: 100 * time.Millisecond, RoundStartTTL: 10 * time.Second, AcceptProposeTTL: time.Second, AcceptProposalEndorseTTL: time.Second, AcceptCommitEndorseTTL: time.Second, Delay: 5 * time.Second, NumSubEpochs: 1, EventChanSize: 10000, NumDelegates: 21, TimeBasedRotation: false, EnableDKG: false, }, BlockCreationInterval: 10 * time.Second, }, BlockSync: BlockSync{ Interval: 10 * time.Second, BufferSize: 16, }, Dispatcher: Dispatcher{ EventChanSize: 10000, }, Explorer: Explorer{ Enabled: false, UseRDS: false, Port: 14004, TpsWindow: 10, GasStation: GasStation{ SuggestBlockWindow: 20, DefaultGas: 1, Percentile: 60, }, MaxTransferPayloadBytes: 1024, }, Indexer: Indexer{ Enabled: false, NodeAddr: "", }, System: System{ HeartbeatInterval: 10 * time.Second, HTTPProfilingPort: 0, HTTPMetricsPort: 8080, StartSubChainInterval: 10 * time.Second, }, DB: DB{ UseBadgerDB: false, NumRetries: 3, }, } // ErrInvalidCfg indicates the invalid config value ErrInvalidCfg = errors.New("invalid config value") // Validates is the collection config validation functions Validates = []Validate{ ValidateKeyPair, ValidateConsensusScheme, ValidateRollDPoS, ValidateDispatcher, ValidateExplorer, ValidateActPool, ValidateChain, } ) // Network is the config struct for network package type ( Network struct { Host string `yaml:"host"` Port int `yaml:"port"` ExternalHost string `yaml:"externalHost"` ExternalPort int `yaml:"externalPort"` BootstrapNodes []string `yaml:"bootstrapNodes"` } // Chain is the config struct for blockchain package Chain struct { ChainDBPath string `yaml:"chainDBPath"` TrieDBPath string `yaml:"trieDBPath"` ID uint32 `yaml:"id"` Address string `yaml:"address"` ProducerPubKey string `yaml:"producerPubKey"` ProducerPrivKey string `yaml:"producerPrivKey"` GenesisActionsPath string `yaml:"genesisActionsPath"` EmptyGenesis bool `yaml:"emptyGenesis"` NumCandidates uint `yaml:"numCandidates"` EnableFallBackToFreshDB bool `yaml:"enableFallbackToFreshDb"` EnableSubChainStartInGenesis bool `yaml:"enableSubChainStartInGenesis"` // enable gas charge for block producer EnableGasCharge bool `yaml:"enableGasCharge"` } // Consensus is the config struct for consensus package Consensus struct { // There are three schemes that are supported Scheme string `yaml:"scheme"` RollDPoS RollDPoS `yaml:"rollDPoS"` BlockCreationInterval time.Duration `yaml:"blockCreationInterval"` } // BlockSync is the config struct for the BlockSync BlockSync struct { Interval time.Duration `yaml:"interval"` // update duration BufferSize uint64 `yaml:"bufferSize"` } // RollDPoS is the config struct for RollDPoS consensus package RollDPoS struct { DelegateInterval time.Duration `yaml:"delegateInterval"` ProposerInterval time.Duration `yaml:"proposerInterval"` UnmatchedEventTTL time.Duration `yaml:"unmatchedEventTTL"` UnmatchedEventInterval time.Duration `yaml:"unmatchedEventInterval"` RoundStartTTL time.Duration `yaml:"roundStartTTL"` AcceptProposeTTL time.Duration `yaml:"acceptProposeTTL"` AcceptProposalEndorseTTL time.Duration `yaml:"acceptProposalEndorseTTL"` AcceptCommitEndorseTTL time.Duration `yaml:"acceptCommitEndorseTTL"` Delay time.Duration `yaml:"delay"` NumSubEpochs uint `yaml:"numSubEpochs"` EventChanSize uint `yaml:"eventChanSize"` NumDelegates uint `yaml:"numDelegates"` TimeBasedRotation bool `yaml:"timeBasedRotation"` EnableDKG bool `yaml:"enableDKG"` } // Dispatcher is the dispatcher config Dispatcher struct { EventChanSize uint `yaml:"eventChanSize"` } // Explorer is the explorer service config Explorer struct { Enabled bool `yaml:"enabled"` IsTest bool `yaml:"isTest"` UseRDS bool `yaml:"useRDS"` Port int `yaml:"port"` TpsWindow int `yaml:"tpsWindow"` GasStation GasStation `yaml:"gasStation"` // MaxTransferPayloadBytes limits how many bytes a playload can contain at most MaxTransferPayloadBytes uint64 `yaml:"maxTransferPayloadBytes"` } // GasStation is the gas station config GasStation struct { SuggestBlockWindow int `yaml:"suggestBlockWindow"` DefaultGas int `yaml:"defaultGas"` Percentile int `yaml:"Percentile"` } // Indexer is the index service config Indexer struct { Enabled bool `yaml:"enabled"` NodeAddr string `yaml:"nodeAddr"` } // System is the system config System struct { HeartbeatInterval time.Duration `yaml:"heartbeatInterval"` // HTTPProfilingPort is the port number to access golang performance profiling data of a blockchain node. It is // 0 by default, meaning performance profiling has been disabled HTTPProfilingPort int `yaml:"httpProfilingPort"` HTTPMetricsPort int `yaml:"httpMetricsPort"` StartSubChainInterval time.Duration `yaml:"startSubChainInterval"` } // ActPool is the actpool config ActPool struct { // MaxNumActsPerPool indicates maximum number of actions the whole actpool can hold MaxNumActsPerPool uint64 `yaml:"maxNumActsPerPool"` // MaxNumActsPerAcct indicates maximum number of actions an account queue can hold MaxNumActsPerAcct uint64 `yaml:"maxNumActsPerAcct"` // MaxNumActsToPick indicates maximum number of actions to pick to mint a block. Default is 0, which means no // limit on the number of actions to pick. MaxNumActsToPick uint64 `yaml:"maxNumActsToPick"` } // DB is the config for database DB struct { DbPath string `yaml:"dbPath"` // Use BadgerDB, otherwise use BoltDB UseBadgerDB bool `yaml:"useBadgerDB"` // NumRetries is the number of retries NumRetries uint8 `yaml:"numRetries"` // RDS is the config for rds RDS RDS `yaml:"RDS"` } // RDS is the cloud rds config RDS struct { // AwsRDSEndpoint is the endpoint of aws rds AwsRDSEndpoint string `yaml:"awsRDSEndpoint"` // AwsRDSPort is the port of aws rds AwsRDSPort uint64 `yaml:"awsRDSPort"` // AwsRDSUser is the user to access aws rds AwsRDSUser string `yaml:"awsRDSUser"` // AwsPass is the pass to access aws rds AwsPass string `yaml:"awsPass"` // AwsDBName is the db name of aws rds AwsDBName string `yaml:"awsDBName"` } // Config is the root config struct, each package's config should be put as its sub struct Config struct { NodeType string `yaml:"nodeType"` Network Network `yaml:"network"` Chain Chain `yaml:"chain"` ActPool ActPool `yaml:"actPool"` Consensus Consensus `yaml:"consensus"` BlockSync BlockSync `yaml:"blockSync"` Dispatcher Dispatcher `yaml:"dispatcher"` Explorer Explorer `yaml:"explorer"` Indexer Indexer `yaml:"indexer"` System System `yaml:"system"` DB DB `yaml:"db"` } // Validate is the interface of validating the config Validate func(Config) error ) // New creates a config instance. It first loads the default configs. If the config path is not empty, it will read from // the file and override the default configs. By default, it will apply all validation functions. To bypass validation, // use DoNotValidate instead. func New(validates ...Validate) (Config, error) { opts := make([]uconfig.YAMLOption, 0) opts = append(opts, uconfig.Static(Default)) opts = append(opts, uconfig.Expand(os.LookupEnv)) if _overwritePath != "" { opts = append(opts, uconfig.File(_overwritePath)) } if _secretPath != "" { opts = append(opts, uconfig.File(_secretPath)) } yaml, err := uconfig.NewYAML(opts...) if err != nil { return Config{}, errors.Wrap(err, "failed to init config") } var cfg Config if err := yaml.Get(uconfig.Root).Populate(&cfg); err != nil { return Config{}, errors.Wrap(err, "failed to unmarshal YAML config to struct") } // By default, the config needs to pass all the validation if len(validates) == 0 { validates = Validates } for _, validate := range validates { if err := validate(cfg); err != nil { return Config{}, errors.Wrap(err, "failed to validate config") } } return cfg, nil } // NewSub create config for sub chain. func NewSub(validates ...Validate) (Config, error) { if _subChainPath == "" { return Config{}, nil } opts := make([]uconfig.YAMLOption, 0) opts = append(opts, uconfig.Static(Default)) opts = append(opts, uconfig.Expand(os.LookupEnv)) opts = append(opts, uconfig.File(_subChainPath)) if _secretPath != "" { opts = append(opts, uconfig.File(_secretPath)) } yaml, err := uconfig.NewYAML(opts...) if err != nil { return Config{}, errors.Wrap(err, "failed to init config") } var cfg Config if err := yaml.Get(uconfig.Root).Populate(&cfg); err != nil { return Config{}, errors.Wrap(err, "failed to unmarshal YAML config to struct") } // By default, the config needs to pass all the validation if len(validates) == 0 { validates = Validates } for _, validate := range validates { if err := validate(cfg); err != nil { return Config{}, errors.Wrap(err, "failed to validate config") } } return cfg, nil } // IsDelegate returns true if the node type is Delegate func (cfg Config) IsDelegate() bool { return cfg.NodeType == DelegateType } // IsFullnode returns true if the node type is Fullnode func (cfg Config) IsFullnode() bool { return cfg.NodeType == FullNodeType } // IsLightweight returns true if the node type is Lightweight func (cfg Config) IsLightweight() bool { return cfg.NodeType == LightweightType } // BlockchainAddress returns the address derived from the configured chain ID and public key func (cfg Config) BlockchainAddress() (address.Address, error) { pk, err := keypair.DecodePublicKey(cfg.Chain.ProducerPubKey) if err != nil { return nil, errors.Wrapf(err, "error when decoding public key %s", cfg.Chain.ProducerPubKey) } pkHash := keypair.HashPubKey(pk) return address.New(cfg.Chain.ID, pkHash[:]), nil } // KeyPair returns the decoded public and private key pair func (cfg Config) KeyPair() (keypair.PublicKey, keypair.PrivateKey, error) { pk, err := keypair.DecodePublicKey(cfg.Chain.ProducerPubKey) if err != nil { return keypair.ZeroPublicKey, keypair.ZeroPrivateKey, errors.Wrapf(err, "error when decoding public key %s", cfg.Chain.ProducerPubKey) } sk, err := keypair.DecodePrivateKey(cfg.Chain.ProducerPrivKey) if err != nil { return keypair.ZeroPublicKey, keypair.ZeroPrivateKey, errors.Wrapf(err, "error when decoding private key %s", cfg.Chain.ProducerPrivKey) } return pk, sk, nil } // ValidateKeyPair validates the block producer address func ValidateKeyPair(cfg Config) error { priKey, err := keypair.DecodePrivateKey(cfg.Chain.ProducerPrivKey) if err != nil { return err } pubKey, err := keypair.DecodePublicKey(cfg.Chain.ProducerPubKey) if err != nil { return err } // Validate producer pubkey and prikey by signing a dummy message and verify it validationMsg := "connecting the physical world block by block" sig := crypto.EC283.Sign(priKey, []byte(validationMsg)) if !crypto.EC283.Verify(pubKey, []byte(validationMsg), sig) { return errors.Wrap(ErrInvalidCfg, "block producer has unmatched pubkey and prikey") } return nil } // ValidateChain validates the chain configure func ValidateChain(cfg Config) error { if cfg.Chain.NumCandidates <= 0 { return errors.Wrapf(ErrInvalidCfg, "candidate number should be greater than 0") } if cfg.Consensus.Scheme == RollDPoSScheme && cfg.Chain.NumCandidates < cfg.Consensus.RollDPoS.NumDelegates { return errors.Wrapf(ErrInvalidCfg, "candidate number should be greater than or equal to delegate number") } return nil } // ValidateConsensusScheme validates the if scheme and node type match func ValidateConsensusScheme(cfg Config) error { switch cfg.NodeType { case DelegateType: case FullNodeType: if cfg.Consensus.Scheme != NOOPScheme { return errors.Wrap(ErrInvalidCfg, "consensus scheme of fullnode should be NOOP") } case LightweightType: if cfg.Consensus.Scheme != NOOPScheme { return errors.Wrap(ErrInvalidCfg, "consensus scheme of lightweight node should be NOOP") } default: return errors.Wrapf(ErrInvalidCfg, "unknown node type %s", cfg.NodeType) } return nil } // ValidateDispatcher validates the dispatcher configs func ValidateDispatcher(cfg Config) error { if cfg.Dispatcher.EventChanSize <= 0 { return errors.Wrap(ErrInvalidCfg, "dispatcher event chan size should be greater than 0") } return nil } // ValidateRollDPoS validates the roll-DPoS configs func ValidateRollDPoS(cfg Config) error { if cfg.Consensus.Scheme != RollDPoSScheme { return nil } rollDPoS := cfg.Consensus.RollDPoS if rollDPoS.EventChanSize <= 0 { return errors.Wrap(ErrInvalidCfg, "roll-DPoS event chan size should be greater than 0") } if rollDPoS.NumDelegates <= 0 { return errors.Wrap(ErrInvalidCfg, "roll-DPoS event delegate number should be greater than 0") } ttl := rollDPoS.AcceptCommitEndorseTTL + rollDPoS.AcceptProposeTTL + rollDPoS.AcceptProposalEndorseTTL if ttl >= rollDPoS.ProposerInterval { return errors.Wrap(ErrInvalidCfg, "roll-DPoS ttl sum is larger than proposer interval") } return nil } // ValidateExplorer validates the explorer configs func ValidateExplorer(cfg Config) error { if cfg.Explorer.Enabled && cfg.Explorer.TpsWindow <= 0 { return errors.Wrap(ErrInvalidCfg, "tps window is not a positive integer when the explorer is enabled") } return nil } // ValidateActPool validates the given config func ValidateActPool(cfg Config) error { maxNumActPerPool := cfg.ActPool.MaxNumActsPerPool maxNumActPerAcct := cfg.ActPool.MaxNumActsPerAcct if maxNumActPerPool <= 0 || maxNumActPerAcct <= 0 { return errors.Wrap( ErrInvalidCfg, "maximum number of actions per pool or per account cannot be zero or negative", ) } if maxNumActPerPool < maxNumActPerAcct { return errors.Wrap( ErrInvalidCfg, "maximum number of actions per pool cannot be less than maximum number of actions per account", ) } return nil } // DoNotValidate validates the given config func DoNotValidate(cfg Config) error { return nil }
1
14,356
File is not `goimports`-ed (from `goimports`)
iotexproject-iotex-core
go
@@ -54,11 +54,14 @@ const rules = [ use: [ { loader: 'babel-loader', - query: { - presets: [ [ '@babel/env', { - useBuiltIns: 'entry', - corejs: 2, - } ], '@babel/preset-react' ], + options: { + babelrc: false, + configFile: false, + cacheDirectory: true, + presets: [ + '@wordpress/default', + '@babel/preset-react', + ], }, }, {
1
/** * Webpack config. * * Site Kit by Google, Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Node dependencies */ const fs = require( 'fs' ); const path = require( 'path' ); /** * External dependencies */ const CircularDependencyPlugin = require( 'circular-dependency-plugin' ); const MiniCssExtractPlugin = require( 'mini-css-extract-plugin' ); const TerserPlugin = require( 'terser-webpack-plugin' ); const WebpackBar = require( 'webpackbar' ); const { ProvidePlugin } = require( 'webpack' ); const projectPath = ( relativePath ) => { return path.resolve( fs.realpathSync( process.cwd() ), relativePath ); }; const noAMDParserRule = { parser: { amd: false } }; const siteKitExternals = { 'googlesitekit-api': [ 'googlesitekit', 'api' ], 'googlesitekit-data': [ 'googlesitekit', 'data' ], 'googlesitekit-modules': [ 'googlesitekit', 'modules' ], 'googlesitekit-widgets': [ 'googlesitekit', 'widgets' ], }; const externals = { ...siteKitExternals }; const rules = [ noAMDParserRule, { test: /\.js$/, exclude: /node_modules/, use: [ { loader: 'babel-loader', query: { presets: [ [ '@babel/env', { useBuiltIns: 'entry', corejs: 2, } ], '@babel/preset-react' ], }, }, { loader: 'eslint-loader', options: { quiet: true, formatter: require( 'eslint' ).CLIEngine.getFormatter( 'stylish' ), }, }, ], ...noAMDParserRule, }, ]; const resolve = { alias: { '@wordpress/api-fetch__non-shim': require.resolve( '@wordpress/api-fetch' ), '@wordpress/api-fetch$': path.resolve( 'assets/js/api-fetch-shim.js' ), '@wordpress/element__non-shim': require.resolve( '@wordpress/element' ), '@wordpress/element$': path.resolve( 'assets/js/element-shim.js' ), '@wordpress/hooks__non-shim': require.resolve( '@wordpress/hooks' ), '@wordpress/hooks$': path.resolve( 'assets/js/hooks-shim.js' ), }, modules: [ projectPath( '.' ), 'node_modules' ], }; const webpackConfig = ( mode ) => { return [ // Build the settings js.. { entry: { // New Modules (Post-JSR). 'googlesitekit-api': './assets/js/googlesitekit-api.js', 'googlesitekit-data': './assets/js/googlesitekit-data.js', 'googlesitekit-datastore-site': './assets/js/googlesitekit-datastore-site.js', 'googlesitekit-datastore-user': './assets/js/googlesitekit-datastore-user.js', 'googlesitekit-datastore-forms': './assets/js/googlesitekit-datastore-forms.js', 'googlesitekit-modules': './assets/js/googlesitekit-modules.js', 'googlesitekit-widgets': './assets/js/googlesitekit-widgets.js', 'googlesitekit-modules-adsense': './assets/js/googlesitekit-modules-adsense.js', 'googlesitekit-modules-analytics': './assets/js/googlesitekit-modules-analytics.js', 'googlesitekit-modules-pagespeed-insights': 'assets/js/googlesitekit-modules-pagespeed-insights.js', 'googlesitekit-modules-search-console': './assets/js/googlesitekit-modules-search-console.js', 'googlesitekit-modules-tagmanager': './assets/js/googlesitekit-modules-tagmanager.js', 'googlesitekit-modules-optimize': './assets/js/googlesitekit-modules-optimize.js', // Old Modules 'googlesitekit-activation': './assets/js/googlesitekit-activation.js', 'googlesitekit-settings': './assets/js/googlesitekit-settings.js', 'googlesitekit-dashboard': './assets/js/googlesitekit-dashboard.js', 'googlesitekit-dashboard-details': './assets/js/googlesitekit-dashboard-details.js', 'googlesitekit-dashboard-splash': './assets/js/googlesitekit-dashboard-splash.js', 'googlesitekit-wp-dashboard': './assets/js/googlesitekit-wp-dashboard.js', 'googlesitekit-adminbar-loader': './assets/js/googlesitekit-adminbar-loader.js', 'googlesitekit-admin': './assets/js/googlesitekit-admin.js', 'googlesitekit-module': './assets/js/googlesitekit-module.js', // Needed to test if a browser extension blocks this by naming convention. 'pagead2.ads': './assets/js/pagead2.ads.js', }, externals, output: { filename: '[name].js', path: __dirname + '/dist/assets/js', chunkFilename: '[name]-[chunkhash].js', publicPath: '', /** * If multiple webpack runtimes (from different compilations) are used on the same webpage, * there is a risk of conflicts of on-demand chunks in the global namespace. * * @see (@link https://webpack.js.org/configuration/output/#outputjsonpfunction) */ jsonpFunction: '__googlesitekit_webpackJsonp', }, performance: { maxEntrypointSize: 175000, }, module: { rules, }, plugins: [ new ProvidePlugin( { React: 'react', } ), new WebpackBar( { name: 'Module Entry Points', color: '#fbbc05', } ), new CircularDependencyPlugin( { exclude: /node_modules/, failOnError: true, allowAsyncCycles: false, cwd: process.cwd(), } ), ], optimization: { minimizer: [ new TerserPlugin( { parallel: true, sourceMap: false, cache: true, terserOptions: { // We preserve function names that start with capital letters as // they're _likely_ component names, and these are useful to have // in tracebacks and error messages. keep_fnames: /__|_x|_n|_nx|sprintf|^[A-Z].+$/, output: { comments: /translators:/i, }, }, extractComments: false, } ), ], runtimeChunk: false, splitChunks: { cacheGroups: { vendor: { chunks: 'initial', name: 'googlesitekit-vendor', filename: 'googlesitekit-vendor.js', enforce: true, test: /[\\/]node_modules[\\/]/, }, }, }, }, resolve, }, // Build the main plugin admin css. { entry: { admin: './assets/sass/admin.scss', adminbar: './assets/sass/adminbar.scss', wpdashboard: './assets/sass/wpdashboard.scss', }, module: { rules: [ { test: /\.scss$/, use: [ MiniCssExtractPlugin.loader, { loader: 'css-loader', options: { minimize: ( 'production' === mode ), }, }, 'postcss-loader', { loader: 'sass-loader', options: { includePaths: [ 'node_modules' ], }, }, ], }, { test: /\.(png|woff|woff2|eot|ttf|svg|gif)$/, use: { loader: 'url-loader?limit=100000' }, }, ], }, plugins: [ new MiniCssExtractPlugin( { filename: '/assets/css/[name].css', } ), new WebpackBar( { name: 'Plugin CSS', color: '#4285f4', } ), ], }, ]; }; const testBundle = () => { return { entry: { 'e2e-api-fetch': './tests/e2e/assets/e2e-api-fetch.js', 'e2e-redux-logger': './tests/e2e/assets/e2e-redux-logger.js', }, output: { filename: '[name].js', path: __dirname + '/dist/assets/js', chunkFilename: '[name].js', publicPath: '', }, module: { rules, }, plugins: [ new WebpackBar( { name: 'Test files', color: '#34a853', } ), ], externals, resolve, }; }; module.exports = { externals, noAMDParserRule, projectPath, resolve, rules, siteKitExternals, }; module.exports.default = ( ...args ) => { const { includeTests, mode } = args[ 1 ]; const config = webpackConfig( mode ); if ( mode !== 'production' || includeTests ) { // Build the test files if we aren't doing a production build. config.push( testBundle() ); } return config; };
1
30,282
Shouldn't these options also include `@babel/preset-env`? Also I see you set `babelrc` to `false`, could we rely on our existing `.babelrc` file? Feels like some duplicate configuration otherwise.
google-site-kit-wp
js
@@ -1609,7 +1609,7 @@ func (wn *WebsocketNetwork) removePeer(peer *wsPeer, reason disconnectReason) { // first logging, then take the lock and do the actual accounting. // definitely don't change this to do the logging while holding the lock. localAddr, _ := wn.Address() - wn.log.With("event", "Disconnected").With("remote", peer.rootURL).With("local", localAddr).Infof("Peer %v disconnected", peer.rootURL) + wn.log.With("event", "Disconnected").With("remote", peer.rootURL).With("local", localAddr).Infof("Peer %v disconnected: %v", peer.rootURL, reason) peerAddr := peer.OriginAddress() // we might be able to get addr out of conn, or it might be closed if peerAddr == "" && peer.conn != nil {
1
// Copyright (C) 2019 Algorand, Inc. // This file is part of go-algorand // // go-algorand is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // go-algorand is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with go-algorand. If not, see <https://www.gnu.org/licenses/>. package network import ( "container/heap" "context" "encoding/base64" "errors" "fmt" "io/ioutil" "math" "math/rand" "net" "net/http" "net/url" "path" "regexp" "runtime" "sort" "strconv" "strings" "sync" "sync/atomic" "time" "github.com/algorand/go-deadlock" "github.com/algorand/websocket" "github.com/gorilla/mux" "golang.org/x/net/netutil" "golang.org/x/sys/unix" "github.com/algorand/go-algorand/config" "github.com/algorand/go-algorand/crypto" "github.com/algorand/go-algorand/logging" "github.com/algorand/go-algorand/logging/telemetryspec" "github.com/algorand/go-algorand/protocol" tools_network "github.com/algorand/go-algorand/tools/network" "github.com/algorand/go-algorand/util/metrics" ) const incomingThreads = 20 const broadcastThreads = 4 const messageFilterSize = 5000 // messages greater than that size may be blocked by incoming/outgoing filter // httpServerReadHeaderTimeout is the amount of time allowed to read // request headers. The connection's read deadline is reset // after reading the headers and the Handler can decide what // is considered too slow for the body. const httpServerReadHeaderTimeout = time.Second * 10 // httpServerWriteTimeout is the maximum duration before timing out // writes of the response. It is reset whenever a new // request's header is read. const httpServerWriteTimeout = time.Second * 60 // httpServerIdleTimeout is the maximum amount of time to wait for the // next request when keep-alives are enabled. If httpServerIdleTimeout // is zero, the value of ReadTimeout is used. If both are // zero, ReadHeaderTimeout is used. const httpServerIdleTimeout = time.Second * 4 // MaxHeaderBytes controls the maximum number of bytes the // server will read parsing the request header's keys and // values, including the request line. It does not limit the // size of the request body. const httpServerMaxHeaderBytes = 4096 // MaxInt is the maximum int which might be int32 or int64 const MaxInt = int((^uint(0)) >> 1) // connectionActivityMonitorInterval is the interval at which we check // if any of the connected peers have been idle for a long while and // need to be disconnected. const connectionActivityMonitorInterval = 3 * time.Minute // maxPeerInactivityDuration is the maximum allowed duration for a // peer to remain completly idle (i.e. no inbound or outbound communication), before // we discard the connection. const maxPeerInactivityDuration = 5 * time.Minute // maxMessageQueueDuration is the maximum amount of time a message is allowed to be waiting // in the various queues before being sent. Once that deadline has reached, sending the message // is pointless, as it's too stale to be of any value const maxMessageQueueDuration = 25 * time.Second // slowWritingPeerMonitorInterval is the interval at which we peek on the connected peers to // verify that their current outgoing message is not being blocked for too long. const slowWritingPeerMonitorInterval = 5 * time.Second var networkIncomingConnections = metrics.MakeGauge(metrics.NetworkIncomingConnections) var networkOutgoingConnections = metrics.MakeGauge(metrics.NetworkOutgoingConnections) var networkIncomingBufferMicros = metrics.MakeCounter(metrics.MetricName{Name: "algod_network_rx_buffer_micros_total", Description: "microseconds spent by incoming messages on the receive buffer"}) var networkHandleMicros = metrics.MakeCounter(metrics.MetricName{Name: "algod_network_rx_handle_micros_total", Description: "microseconds spent by protocol handlers in the receive thread"}) var networkBroadcasts = metrics.MakeCounter(metrics.MetricName{Name: "algod_network_broadcasts_total", Description: "number of broadcast operations"}) var networkBroadcastQueueMicros = metrics.MakeCounter(metrics.MetricName{Name: "algod_network_broadcast_queue_micros_total", Description: "microseconds broadcast requests sit on queue"}) var networkBroadcastSendMicros = metrics.MakeCounter(metrics.MetricName{Name: "algod_network_broadcast_send_micros_total", Description: "microseconds spent broadcasting"}) var networkBroadcastsDropped = metrics.MakeCounter(metrics.MetricName{Name: "algod_broadcasts_dropped_total", Description: "number of broadcast messages not sent to any peer"}) var networkPeerBroadcastDropped = metrics.MakeCounter(metrics.MetricName{Name: "algod_peer_broadcast_dropped_total", Description: "number of broadcast messages not sent to some peer"}) var networkSlowPeerDrops = metrics.MakeCounter(metrics.MetricName{Name: "algod_network_slow_drops_total", Description: "number of peers dropped for being slow to send to"}) var networkIdlePeerDrops = metrics.MakeCounter(metrics.MetricName{Name: "algod_network_idle_drops_total", Description: "number of peers dropped due to idle connection"}) var networkBroadcastQueueFull = metrics.MakeCounter(metrics.MetricName{Name: "algod_network_broadcast_queue_full_total", Description: "number of messages that were drops due to full broadcast queue"}) var minPing = metrics.MakeGauge(metrics.MetricName{Name: "algod_network_peer_min_ping_seconds", Description: "Network round trip time to fastest peer in seconds."}) var meanPing = metrics.MakeGauge(metrics.MetricName{Name: "algod_network_peer_mean_ping_seconds", Description: "Network round trip time to average peer in seconds."}) var medianPing = metrics.MakeGauge(metrics.MetricName{Name: "algod_network_peer_median_ping_seconds", Description: "Network round trip time to median peer in seconds."}) var maxPing = metrics.MakeGauge(metrics.MetricName{Name: "algod_network_peer_max_ping_seconds", Description: "Network round trip time to slowest peer in seconds."}) var peers = metrics.MakeGauge(metrics.MetricName{Name: "algod_network_peers", Description: "Number of active peers."}) var incomingPeers = metrics.MakeGauge(metrics.MetricName{Name: "algod_network_incoming_peers", Description: "Number of active incoming peers."}) var outgoingPeers = metrics.MakeGauge(metrics.MetricName{Name: "algod_network_outgoing_peers", Description: "Number of active outgoing peers."}) // Peer opaque interface for referring to a neighbor in the network type Peer interface{} // PeerOption allows users to specify a subset of peers to query type PeerOption int const ( // PeersConnectedOut specifies all peers with outgoing connections PeersConnectedOut PeerOption = iota // PeersConnectedIn specifies all peers with inbound connections PeersConnectedIn PeerOption = iota // PeersPhonebook specifies all peers in the phonebook PeersPhonebook PeerOption = iota ) // GossipNode represents a node in the gossip network type GossipNode interface { Address() (string, bool) Broadcast(ctx context.Context, tag protocol.Tag, data []byte, wait bool, except Peer) error Relay(ctx context.Context, tag protocol.Tag, data []byte, wait bool, except Peer) error Disconnect(badnode Peer) DisconnectPeers() Ready() chan struct{} // RegisterHTTPHandler path accepts gorilla/mux path annotations RegisterHTTPHandler(path string, handler http.Handler) // RequestConnectOutgoing asks the system to actually connect to peers. // `replace` optionally drops existing connections before making new ones. // `quit` chan allows cancellation. TODO: use `context` RequestConnectOutgoing(replace bool, quit <-chan struct{}) // Get a list of Peers we could potentially send a direct message to. GetPeers(options ...PeerOption) []Peer // Start threads, listen on sockets. Start() // Close sockets. Stop threads. Stop() // RegisterHandlers adds to the set of given message handlers. RegisterHandlers(dispatch []TaggedMessageHandler) // ClearHandlers deregisters all the existing message handlers. ClearHandlers() } // IncomingMessage represents a message arriving from some peer in our p2p network type IncomingMessage struct { Sender Peer Tag Tag Data []byte Err error Net GossipNode // Received is time.Time.UnixNano() Received int64 // processing is a channel that is used by messageHandlerThread // to indicate that it has started processing this message. It // is used to ensure fairness across peers in terms of processing // messages. processing chan struct{} } // Tag is a short string (2 bytes) marking a type of message type Tag = protocol.Tag func highPriorityTag(tag protocol.Tag) bool { return tag == protocol.AgreementVoteTag || tag == protocol.ProposalPayloadTag } // OutgoingMessage represents a message we want to send. type OutgoingMessage struct { Action ForwardingPolicy Tag Tag Payload []byte } // ForwardingPolicy is an enum indicating to whom we should send a message type ForwardingPolicy int const ( // Ignore - discard (don't forward) Ignore ForwardingPolicy = iota // Disconnect - disconnect from the peer that sent this message Disconnect // Broadcast - forward to everyone (except the sender) Broadcast ) // MessageHandler takes a IncomingMessage (e.g., vote, transaction), processes it, and returns what (if anything) // to send to the network in response. // The ForwardingPolicy field of the returned OutgoingMessage indicates whether to reply directly to the sender // (unicast), propagate to everyone except the sender (broadcast), or do nothing (ignore). type MessageHandler interface { Handle(message IncomingMessage) OutgoingMessage } // HandlerFunc represents an implemenation of the MessageHandler interface type HandlerFunc func(message IncomingMessage) OutgoingMessage // Handle implements MessageHandler.Handle, calling the handler with the IncomingKessage and returning the OutgoingMessage func (f HandlerFunc) Handle(message IncomingMessage) OutgoingMessage { return f(message) } // TaggedMessageHandler receives one type of broadcast messages type TaggedMessageHandler struct { Tag MessageHandler } // Propagate is a convenience function to save typing in the common case of a message handler telling us to propagate an incoming message // "return network.Propagate(msg)" instead of "return network.OutgoingMsg{network.Broadcast, msg.Tag, msg.Data}" func Propagate(msg IncomingMessage) OutgoingMessage { return OutgoingMessage{Broadcast, msg.Tag, msg.Data} } // GossipNetworkPath is the URL path to connect to the websocket gossip node at. // Contains {genesisID} param to be handled by gorilla/mux const GossipNetworkPath = "/v1/{genesisID}/gossip" // WebsocketNetwork implements GossipNode type WebsocketNetwork struct { listener net.Listener server http.Server router *mux.Router scheme string // are we serving http or https ? upgrader websocket.Upgrader config config.Local log logging.Logger readBuffer chan IncomingMessage wg sync.WaitGroup handlers Multiplexer ctx context.Context ctxCancel context.CancelFunc peersLock deadlock.RWMutex peers []*wsPeer broadcastQueueHighPrio chan broadcastRequest broadcastQueueBulk chan broadcastRequest phonebook *MultiPhonebook GenesisID string NetworkID protocol.NetworkID RandomID string ready int32 readyChan chan struct{} meshUpdateRequests chan meshRequest // Keep a record of pending outgoing connections so // we don't start duplicates connection attempts. // Needs to be locked because it's accessed from the // meshThread and also threads started to run tryConnect() tryConnectAddrs map[string]int64 tryConnectLock deadlock.Mutex incomingMsgFilter *messageFilter // message filter to remove duplicate incoming messages from different peers eventualReadyDelay time.Duration relayMessages bool // True if we should relay messages from other nodes (nominally true for relays, false otherwise) prioScheme NetPrioScheme prioTracker *prioTracker prioResponseChan chan *wsPeer // outgoingMessagesBufferSize is the size used for outgoing messages. outgoingMessagesBufferSize int // slowWritingPeerMonitorInterval defines the interval between two consecutive tests for slow peer writing slowWritingPeerMonitorInterval time.Duration requestsTracker *RequestTracker requestsLogger *RequestLogger } type broadcastRequest struct { tag Tag data []byte except *wsPeer done chan struct{} enqueueTime time.Time } // Address returns a string and whether that is a 'final' address or guessed. // Part of GossipNode interface func (wn *WebsocketNetwork) Address() (string, bool) { parsedURL := url.URL{Scheme: wn.scheme} var connected bool if wn.listener == nil { parsedURL.Host = wn.config.NetAddress connected = false } else { parsedURL.Host = wn.listener.Addr().String() connected = true } return parsedURL.String(), connected } // PublicAddress what we tell other nodes to connect to. // Might be different than our locally percieved network address due to NAT/etc. // Returns config "PublicAddress" if available, otherwise local addr. func (wn *WebsocketNetwork) PublicAddress() string { if len(wn.config.PublicAddress) > 0 { return wn.config.PublicAddress } localAddr, _ := wn.Address() return localAddr } // Broadcast sends a message. // If except is not nil then we will not send it to that neighboring Peer. // if wait is true then the call blocks until the packet has actually been sent to all neighbors. // TODO: add `priority` argument so that we don't have to guess it based on tag func (wn *WebsocketNetwork) Broadcast(ctx context.Context, tag protocol.Tag, data []byte, wait bool, except Peer) error { request := broadcastRequest{tag: tag, data: data, enqueueTime: time.Now()} if except != nil { request.except = except.(*wsPeer) } broadcastQueue := wn.broadcastQueueBulk if highPriorityTag(tag) { broadcastQueue = wn.broadcastQueueHighPrio } if wait { request.done = make(chan struct{}) select { case broadcastQueue <- request: // ok, enqueued //wn.log.Debugf("broadcast enqueued") case <-wn.ctx.Done(): return errNetworkClosing case <-ctx.Done(): return errBcastCallerCancel } select { case <-request.done: //wn.log.Debugf("broadcast done") return nil case <-wn.ctx.Done(): return errNetworkClosing case <-ctx.Done(): return errBcastCallerCancel } } // no wait select { case broadcastQueue <- request: //wn.log.Debugf("broadcast enqueued nowait") return nil default: wn.log.Debugf("broadcast queue full") // broadcastQueue full, and we're not going to wait for it. networkBroadcastQueueFull.Inc(nil) return errBcastQFull } } // Relay message func (wn *WebsocketNetwork) Relay(ctx context.Context, tag protocol.Tag, data []byte, wait bool, except Peer) error { if wn.relayMessages { return wn.Broadcast(ctx, tag, data, wait, except) } return nil } func (wn *WebsocketNetwork) disconnectThread(badnode Peer, reason disconnectReason) { defer wn.wg.Done() wn.disconnect(badnode, reason) } // Disconnect from a peer, probably due to protocol errors. func (wn *WebsocketNetwork) Disconnect(node Peer) { wn.disconnect(node, disconnectBadData) } // Disconnect from a peer, probably due to protocol errors. func (wn *WebsocketNetwork) disconnect(badnode Peer, reason disconnectReason) { if badnode == nil { return } peer := badnode.(*wsPeer) peer.CloseAndWait() wn.removePeer(peer, reason) } func closeWaiter(wg *sync.WaitGroup, peer *wsPeer) { defer wg.Done() peer.CloseAndWait() } // DisconnectPeers shuts down all connections func (wn *WebsocketNetwork) DisconnectPeers() { wn.peersLock.Lock() defer wn.peersLock.Unlock() closeGroup := sync.WaitGroup{} closeGroup.Add(len(wn.peers)) for _, peer := range wn.peers { go closeWaiter(&closeGroup, peer) } wn.peers = wn.peers[:0] closeGroup.Wait() } // Ready returns a chan that will be closed when we have a minimum number of peer connections active func (wn *WebsocketNetwork) Ready() chan struct{} { return wn.readyChan } // RegisterHTTPHandler path accepts gorilla/mux path annotations func (wn *WebsocketNetwork) RegisterHTTPHandler(path string, handler http.Handler) { wn.router.Handle(path, handler) } // RequestConnectOutgoing tries to actually do the connect to new peers. // `replace` drop all connections first and find new peers. func (wn *WebsocketNetwork) RequestConnectOutgoing(replace bool, quit <-chan struct{}) { request := meshRequest{disconnect: false} if quit != nil { request.done = make(chan struct{}) } select { case wn.meshUpdateRequests <- request: case <-quit: return } if request.done != nil { select { case <-request.done: case <-quit: } } } // GetPeers returns a snapshot of our Peer list, according to the specified options. // Peers may be duplicated and refer to the same underlying node. func (wn *WebsocketNetwork) GetPeers(options ...PeerOption) []Peer { outPeers := make([]Peer, 0) for _, option := range options { switch option { case PeersConnectedOut: wn.peersLock.RLock() for _, peer := range wn.peers { if peer.outgoing { outPeers = append(outPeers, Peer(peer)) } } wn.peersLock.RUnlock() case PeersPhonebook: // return copy of phonebook, which probably also contains peers we're connected to, but if it doesn't maybe we shouldn't be making new connections to those peers (because they disappeared from the directory) var addrs []string addrs = wn.phonebook.GetAddresses(1000) for _, addr := range addrs { outPeers = append(outPeers, &wsPeerCore{net: wn, rootURL: addr}) } case PeersConnectedIn: wn.peersLock.RLock() for _, peer := range wn.peers { if !peer.outgoing { outPeers = append(outPeers, Peer(peer)) } } wn.peersLock.RUnlock() } } return outPeers } func (wn *WebsocketNetwork) setup() { wn.upgrader.ReadBufferSize = 4096 wn.upgrader.WriteBufferSize = 4096 wn.upgrader.EnableCompression = false wn.router = mux.NewRouter() wn.router.Handle(GossipNetworkPath, wn) wn.requestsTracker = makeRequestsTracker(wn.router, wn.log, wn.config) if wn.config.EnableRequestLogger { wn.requestsLogger = makeRequestLogger(wn.requestsTracker, wn.log) wn.server.Handler = wn.requestsLogger } else { wn.server.Handler = wn.requestsTracker } wn.server.ReadHeaderTimeout = httpServerReadHeaderTimeout wn.server.WriteTimeout = httpServerWriteTimeout wn.server.IdleTimeout = httpServerIdleTimeout wn.server.MaxHeaderBytes = httpServerMaxHeaderBytes wn.ctx, wn.ctxCancel = context.WithCancel(context.Background()) wn.relayMessages = wn.config.NetAddress != "" || wn.config.ForceRelayMessages // roughly estimate the number of messages that could be sent over the lifespan of a single round. wn.outgoingMessagesBufferSize = int(config.Consensus[protocol.ConsensusCurrentVersion].NumProposers*2 + config.Consensus[protocol.ConsensusCurrentVersion].SoftCommitteeSize + config.Consensus[protocol.ConsensusCurrentVersion].CertCommitteeSize + config.Consensus[protocol.ConsensusCurrentVersion].NextCommitteeSize + config.Consensus[protocol.ConsensusCurrentVersion].LateCommitteeSize + config.Consensus[protocol.ConsensusCurrentVersion].RedoCommitteeSize + config.Consensus[protocol.ConsensusCurrentVersion].DownCommitteeSize) wn.broadcastQueueHighPrio = make(chan broadcastRequest, wn.outgoingMessagesBufferSize) wn.broadcastQueueBulk = make(chan broadcastRequest, 100) wn.meshUpdateRequests = make(chan meshRequest, 5) wn.readyChan = make(chan struct{}) wn.tryConnectAddrs = make(map[string]int64) wn.eventualReadyDelay = time.Minute wn.prioTracker = newPrioTracker(wn) if wn.slowWritingPeerMonitorInterval == 0 { wn.slowWritingPeerMonitorInterval = slowWritingPeerMonitorInterval } readBufferLen := wn.config.IncomingConnectionsLimit + wn.config.GossipFanout if readBufferLen < 100 { readBufferLen = 100 } if readBufferLen > 10000 { readBufferLen = 10000 } wn.readBuffer = make(chan IncomingMessage, readBufferLen) var rbytes [10]byte rand.Read(rbytes[:]) wn.RandomID = base64.StdEncoding.EncodeToString(rbytes[:]) if wn.config.EnableIncomingMessageFilter { wn.incomingMsgFilter = makeMessageFilter(wn.config.IncomingMessageFilterBucketCount, wn.config.IncomingMessageFilterBucketSize) } } func (wn *WebsocketNetwork) rlimitIncomingConnections() error { var lim unix.Rlimit err := unix.Getrlimit(unix.RLIMIT_NOFILE, &lim) if err != nil { return err } // If rlim_max is not sufficient, reduce IncomingConnectionsLimit var rlimitMaxCap uint64 if lim.Max < wn.config.ReservedFDs { rlimitMaxCap = 0 } else { rlimitMaxCap = lim.Max - wn.config.ReservedFDs } if rlimitMaxCap > uint64(MaxInt) { rlimitMaxCap = uint64(MaxInt) } if wn.config.IncomingConnectionsLimit > int(rlimitMaxCap) { wn.log.Warnf("Reducing IncomingConnectionsLimit from %d to %d since RLIMIT_NOFILE is %d", wn.config.IncomingConnectionsLimit, rlimitMaxCap, lim.Max) wn.config.IncomingConnectionsLimit = int(rlimitMaxCap) } // Set rlim_cur to match IncomingConnectionsLimit newLimit := uint64(wn.config.IncomingConnectionsLimit) + wn.config.ReservedFDs if newLimit > lim.Cur { if runtime.GOOS == "darwin" && newLimit > 10240 && lim.Max == 0x7fffffffffffffff { // The max file limit is 10240, even though // the max returned by Getrlimit is 1<<63-1. // This is OPEN_MAX in sys/syslimits.h. // see https://github.com/golang/go/issues/30401 newLimit = 10240 } lim.Cur = newLimit err = unix.Setrlimit(unix.RLIMIT_NOFILE, &lim) if err != nil { return err } } return nil } // Start makes network connections and threads func (wn *WebsocketNetwork) Start() { var err error if wn.config.IncomingConnectionsLimit < 0 { wn.config.IncomingConnectionsLimit = MaxInt } // Make sure we do not accept more incoming connections than our // open file rlimit, with some headroom for other FDs (DNS, log // files, SQLite files, telemetry, ...) err = wn.rlimitIncomingConnections() if err != nil { wn.log.Error("ws network start: rlimitIncomingConnections ", err) return } if wn.config.NetAddress != "" { listener, err := net.Listen("tcp", wn.config.NetAddress) if err != nil { wn.log.Errorf("network could not listen %v: %s", wn.config.NetAddress, err) return } // wrap the original listener with a limited connection listener listener = netutil.LimitListener(listener, wn.config.IncomingConnectionsLimit) // wrap the limited connection listener with a requests tracker listener wn.listener = wn.requestsTracker.Listener(listener) wn.log.Debugf("listening on %s", wn.listener.Addr().String()) } if wn.config.TLSCertFile != "" && wn.config.TLSKeyFile != "" { wn.scheme = "https" } else { wn.scheme = "http" } wn.meshUpdateRequests <- meshRequest{false, nil} wn.RegisterHandlers(pingHandlers) wn.RegisterHandlers(prioHandlers) if wn.listener != nil { wn.wg.Add(1) go wn.httpdThread() } wn.wg.Add(1) go wn.meshThread() if wn.config.PeerPingPeriodSeconds > 0 { wn.wg.Add(1) go wn.pingThread() } for i := 0; i < incomingThreads; i++ { wn.wg.Add(1) go wn.messageHandlerThread() } for i := 0; i < broadcastThreads; i++ { wn.wg.Add(1) go wn.broadcastThread() } wn.wg.Add(1) go wn.prioWeightRefresh() wn.log.Infof("serving genesisID=%s on %#v with RandomID=%s", wn.GenesisID, wn.PublicAddress(), wn.RandomID) } func (wn *WebsocketNetwork) httpdThread() { defer wn.wg.Done() var err error if wn.config.TLSCertFile != "" && wn.config.TLSKeyFile != "" { err = wn.server.ServeTLS(wn.listener, wn.config.TLSCertFile, wn.config.TLSKeyFile) } else { err = wn.server.Serve(wn.listener) } if err == http.ErrServerClosed { } else if err != nil { wn.log.Info("ws net http server exited ", err) } } // innerStop context for shutting down peers func (wn *WebsocketNetwork) innerStop() { wn.peersLock.Lock() defer wn.peersLock.Unlock() wn.wg.Add(len(wn.peers)) for _, peer := range wn.peers { go closeWaiter(&wn.wg, peer) } wn.peers = wn.peers[:0] } // Stop closes network connections and stops threads. // Stop blocks until all activity on this node is done. func (wn *WebsocketNetwork) Stop() { wn.innerStop() var listenAddr string if wn.listener != nil { listenAddr = wn.listener.Addr().String() } wn.ctxCancel() ctx, timeoutCancel := context.WithTimeout(context.Background(), 5*time.Second) defer timeoutCancel() err := wn.server.Shutdown(ctx) if err != nil { wn.log.Warnf("problem shutting down %s: %v", listenAddr, err) } wn.wg.Wait() if wn.listener != nil { wn.log.Debugf("closed %s", listenAddr) } } // RegisterHandlers registers the set of given message handlers. func (wn *WebsocketNetwork) RegisterHandlers(dispatch []TaggedMessageHandler) { wn.handlers.RegisterHandlers(dispatch) } // ClearHandlers deregisters all the existing message handlers. func (wn *WebsocketNetwork) ClearHandlers() { wn.handlers.ClearHandlers() } func (wn *WebsocketNetwork) setHeaders(header http.Header) { myTelemetryGUID := wn.log.GetTelemetryHostName() header.Set(TelemetryIDHeader, myTelemetryGUID) header.Set(ProtocolVersionHeader, ProtocolVersion) header.Set(AddressHeader, wn.PublicAddress()) header.Set(NodeRandomHeader, wn.RandomID) } // checkServerResponseVariables check that the version and random-id in the request headers matches the server ones. // it returns true if it's a match, and false otherwise. func (wn *WebsocketNetwork) checkServerResponseVariables(header http.Header, addr string) bool { otherVersion := header.Get(ProtocolVersionHeader) if otherVersion != ProtocolVersion { wn.log.Infof("new peer %s version mismatch, mine=%s theirs=%s, headers %#v", addr, ProtocolVersion, otherVersion, header) return false } otherRandom := header.Get(NodeRandomHeader) if otherRandom == wn.RandomID || otherRandom == "" { // This is pretty harmless and some configurations of phonebooks or DNS records make this likely. Quietly filter it out. if otherRandom == "" { // missing header. wn.log.Warnf("new peer %s did not include random ID header in request. mine=%s headers %#v", addr, wn.RandomID, header) } else { wn.log.Debugf("new peer %s has same node random id, am I talking to myself? %s", addr, wn.RandomID) } return false } otherGenesisID := header.Get(GenesisHeader) if wn.GenesisID != otherGenesisID { if otherGenesisID != "" { wn.log.Warnf("new peer %#v genesis mismatch, mine=%#v theirs=%#v, headers %#v", addr, wn.GenesisID, otherGenesisID, header) } else { wn.log.Warnf("new peer %#v did not include genesis header in response. mine=%#v headers %#v", addr, wn.GenesisID, header) } return false } return true } // getCommonHeaders retreives the common headers for both incoming and outgoing connections from the provided headers. func getCommonHeaders(headers http.Header) (otherTelemetryGUID, otherInstanceName, otherPublicAddr string) { otherTelemetryGUID = logging.SanitizeTelemetryString(headers.Get(TelemetryIDHeader), 1) otherInstanceName = logging.SanitizeTelemetryString(headers.Get(InstanceNameHeader), 2) otherPublicAddr = logging.SanitizeTelemetryString(headers.Get(AddressHeader), 1) return } // checkIncomingConnectionLimits perform the connection limits counting for the incoming connections. func (wn *WebsocketNetwork) checkIncomingConnectionLimits(response http.ResponseWriter, request *http.Request, remoteHost, otherTelemetryGUID, otherInstanceName string) int { if wn.numIncomingPeers() >= wn.config.IncomingConnectionsLimit { networkConnectionsDroppedTotal.Inc(map[string]string{"reason": "incoming_connection_limit"}) wn.log.EventWithDetails(telemetryspec.Network, telemetryspec.ConnectPeerFailEvent, telemetryspec.ConnectPeerFailEventDetails{ Address: remoteHost, HostName: otherTelemetryGUID, Incoming: true, InstanceName: otherInstanceName, Reason: "Connection Limit", }) response.WriteHeader(http.StatusServiceUnavailable) return http.StatusServiceUnavailable } totalConnections := wn.connectedForIP(remoteHost) if totalConnections >= wn.config.MaxConnectionsPerIP { networkConnectionsDroppedTotal.Inc(map[string]string{"reason": "incoming_connection_per_ip_limit"}) wn.log.EventWithDetails(telemetryspec.Network, telemetryspec.ConnectPeerFailEvent, telemetryspec.ConnectPeerFailEventDetails{ Address: remoteHost, HostName: otherTelemetryGUID, Incoming: true, InstanceName: otherInstanceName, Reason: "Remote IP Connection Limit", }) response.WriteHeader(http.StatusServiceUnavailable) return http.StatusServiceUnavailable } return http.StatusOK } // checkIncomingConnectionVariables checks the variables that were provided on the request, and compares them to the // local server supported parameters. If all good, it returns http.StatusOK; otherwise, it write the error to the ResponseWriter // and returns the http status. func (wn *WebsocketNetwork) checkIncomingConnectionVariables(response http.ResponseWriter, request *http.Request) int { // check to see that the genesisID in the request URI is valid and matches the supported one. pathVars := mux.Vars(request) otherGenesisID, hasGenesisID := pathVars["genesisID"] if !hasGenesisID || otherGenesisID == "" { networkConnectionsDroppedTotal.Inc(map[string]string{"reason": "missing genesis-id"}) response.WriteHeader(http.StatusNotFound) return http.StatusNotFound } if wn.GenesisID != otherGenesisID { wn.log.Warnf("new peer %#v genesis mismatch, mine=%#v theirs=%#v, headers %#v", request.RemoteAddr, wn.GenesisID, otherGenesisID, request.Header) networkConnectionsDroppedTotal.Inc(map[string]string{"reason": "mismatching genesis-id"}) response.WriteHeader(http.StatusPreconditionFailed) response.Write([]byte("mismatching genesis ID")) return http.StatusPreconditionFailed } otherVersion := request.Header.Get(ProtocolVersionHeader) if otherVersion != ProtocolVersion { wn.log.Infof("new peer %s version mismatch, mine=%s theirs=%s, headers %#v", request.RemoteAddr, ProtocolVersion, otherVersion, request.Header) networkConnectionsDroppedTotal.Inc(map[string]string{"reason": "mismatching protocol version"}) response.WriteHeader(http.StatusPreconditionFailed) message := fmt.Sprintf("Requested version %s = %s mismatches server version", ProtocolVersionHeader, otherVersion) n, err := response.Write([]byte(message)) if err != nil { wn.log.Warnf("ws failed to write response '%s' : n = %d err = %v", message, n, err) } return http.StatusPreconditionFailed } otherRandom := request.Header.Get(NodeRandomHeader) if otherRandom == "" { // This is pretty harmless and some configurations of phonebooks or DNS records make this likely. Quietly filter it out. var message string // missing header. wn.log.Warnf("new peer %s did not include random ID header in request. mine=%s headers %#v", request.RemoteAddr, wn.RandomID, request.Header) networkConnectionsDroppedTotal.Inc(map[string]string{"reason": "missing random ID header"}) message = fmt.Sprintf("Request was missing a %s header", NodeRandomHeader) response.WriteHeader(http.StatusPreconditionFailed) n, err := response.Write([]byte(message)) if err != nil { wn.log.Warnf("ws failed to write response '%s' : n = %d err = %v", message, n, err) } return http.StatusPreconditionFailed } else if otherRandom == wn.RandomID { // This is pretty harmless and some configurations of phonebooks or DNS records make this likely. Quietly filter it out. var message string wn.log.Debugf("new peer %s has same node random id, am I talking to myself? %s", request.RemoteAddr, wn.RandomID) networkConnectionsDroppedTotal.Inc(map[string]string{"reason": "matching random ID header"}) message = fmt.Sprintf("Request included matching %s=%s header", NodeRandomHeader, otherRandom) response.WriteHeader(http.StatusLoopDetected) n, err := response.Write([]byte(message)) if err != nil { wn.log.Warnf("ws failed to write response '%s' : n = %d err = %v", message, n, err) } return http.StatusLoopDetected } return http.StatusOK } // ServerHTTP handles the gossip network functions over websockets func (wn *WebsocketNetwork) ServeHTTP(response http.ResponseWriter, request *http.Request) { trackedRequest := wn.requestsTracker.GetTrackedRequest(request) if wn.checkIncomingConnectionLimits(response, request, trackedRequest.remoteHost, trackedRequest.otherTelemetryGUID, trackedRequest.otherInstanceName) != http.StatusOK { // we've already logged and written all response(s). return } if wn.checkIncomingConnectionVariables(response, request) != http.StatusOK { // we've already logged and written all response(s). return } // if UseXForwardedForAddressField is not empty, attempt to override the otherPublicAddr with the X Forwarded For origin trackedRequest.otherPublicAddr = trackedRequest.remoteAddr requestHeader := make(http.Header) wn.setHeaders(requestHeader) requestHeader.Set(GenesisHeader, wn.GenesisID) var challenge string if wn.prioScheme != nil { challenge = wn.prioScheme.NewPrioChallenge() requestHeader.Set(PriorityChallengeHeader, challenge) } conn, err := wn.upgrader.Upgrade(response, request, requestHeader) if err != nil { wn.log.Info("ws upgrade fail ", err) networkConnectionsDroppedTotal.Inc(map[string]string{"reason": "ws upgrade fail"}) return } // we want to tell the response object that the status was changed to 101 ( switching protocols ) so that it will be logged. if wn.requestsLogger != nil { wn.requestsLogger.SetStatusCode(response, http.StatusSwitchingProtocols) } peer := &wsPeer{ wsPeerCore: wsPeerCore{ net: wn, rootURL: trackedRequest.otherPublicAddr, originAddress: trackedRequest.remoteHost, }, conn: conn, outgoing: false, InstanceName: trackedRequest.otherInstanceName, incomingMsgFilter: wn.incomingMsgFilter, prioChallenge: challenge, createTime: trackedRequest.created, } peer.TelemetryGUID = trackedRequest.otherTelemetryGUID peer.init(wn.config, wn.outgoingMessagesBufferSize) wn.addPeer(peer) localAddr, _ := wn.Address() wn.log.With("event", "ConnectedIn").With("remote", trackedRequest.otherPublicAddr).With("local", localAddr).Infof("Accepted incoming connection from peer %s", trackedRequest.otherPublicAddr) wn.log.EventWithDetails(telemetryspec.Network, telemetryspec.ConnectPeerEvent, telemetryspec.PeerEventDetails{ Address: trackedRequest.remoteHost, HostName: trackedRequest.otherTelemetryGUID, Incoming: true, InstanceName: trackedRequest.otherInstanceName, }) peers.Set(float64(wn.NumPeers()), nil) incomingPeers.Set(float64(wn.numIncomingPeers()), nil) } func (wn *WebsocketNetwork) messageHandlerThread() { defer wn.wg.Done() inactivityCheckTicker := time.NewTicker(connectionActivityMonitorInterval) defer inactivityCheckTicker.Stop() for { select { case <-wn.ctx.Done(): return case msg := <-wn.readBuffer: if msg.processing != nil { // The channel send should never block, but just in case.. select { case msg.processing <- struct{}{}: default: wn.log.Warnf("could not send on msg.processing") } } if wn.config.EnableOutgoingNetworkMessageFiltering && len(msg.Data) >= messageFilterSize { wn.sendFilterMessage(msg) } //wn.log.Debugf("msg handling %#v [%d]byte", msg.Tag, len(msg.Data)) start := time.Now() // now, send to global handlers outmsg := wn.handlers.Handle(msg) handled := time.Now() bufferNanos := start.UnixNano() - msg.Received networkIncomingBufferMicros.AddUint64(uint64(bufferNanos/1000), nil) handleTime := handled.Sub(start) networkHandleMicros.AddUint64(uint64(handleTime.Nanoseconds()/1000), nil) switch outmsg.Action { case Disconnect: wn.wg.Add(1) go wn.disconnectThread(msg.Sender, disconnectBadData) case Broadcast: wn.Broadcast(wn.ctx, msg.Tag, msg.Data, false, msg.Sender) default: } case <-inactivityCheckTicker.C: // go over the peers and ensure we have some type of communication going on. wn.checkPeersConnectivity() } } } // checkPeersConnectivity tests the last timestamp where each of these // peers was communicated with, and disconnect the peer if it has been too long since // last time. func (wn *WebsocketNetwork) checkPeersConnectivity() { wn.peersLock.Lock() defer wn.peersLock.Unlock() currentTime := time.Now() for _, peer := range wn.peers { lastPacketTime := peer.GetLastPacketTime() timeSinceLastPacket := currentTime.Sub(time.Unix(0, lastPacketTime)) if timeSinceLastPacket > maxPeerInactivityDuration { wn.wg.Add(1) go wn.disconnectThread(peer, disconnectIdleConn) networkIdlePeerDrops.Inc(nil) } } } // checkSlowWritingPeers tests each of the peer's current message timestamp. // if that timestamp is too old, it means that the transmission of that message // takes longer than desired. In that case, it will disconnect the peer, allowing it to reconnect // to a faster network endpoint. func (wn *WebsocketNetwork) checkSlowWritingPeers() { wn.peersLock.Lock() defer wn.peersLock.Unlock() currentTime := time.Now() for _, peer := range wn.peers { if peer.CheckSlowWritingPeer(currentTime) { wn.wg.Add(1) go wn.disconnectThread(peer, disconnectSlowConn) networkSlowPeerDrops.Inc(nil) } } } func (wn *WebsocketNetwork) sendFilterMessage(msg IncomingMessage) { digest := generateMessageDigest(msg.Tag, msg.Data) //wn.log.Debugf("send filter %s(%d) %v", msg.Tag, len(msg.Data), digest) wn.Broadcast(context.Background(), protocol.MsgSkipTag, digest[:], false, msg.Sender) } func (wn *WebsocketNetwork) broadcastThread() { defer wn.wg.Done() var peers []*wsPeer slowWritingPeerCheckTicker := time.NewTicker(wn.slowWritingPeerMonitorInterval) defer slowWritingPeerCheckTicker.Stop() for { // broadcast from high prio channel as long as we can // we want to try and keep this as a single case select with a default, since go compiles a single-case // select with a default into a more efficient non-blocking receive, instead of compiling it to the general-purpose selectgo select { case request := <-wn.broadcastQueueHighPrio: wn.innerBroadcast(request, true, &peers) continue default: } // if nothing high prio, broadcast anything select { case request := <-wn.broadcastQueueHighPrio: wn.innerBroadcast(request, true, &peers) case <-slowWritingPeerCheckTicker.C: wn.checkSlowWritingPeers() continue case request := <-wn.broadcastQueueBulk: wn.innerBroadcast(request, false, &peers) case <-wn.ctx.Done(): return } } } func (wn *WebsocketNetwork) peerSnapshot(dest []*wsPeer) []*wsPeer { wn.peersLock.RLock() defer wn.peersLock.RUnlock() if cap(dest) >= len(wn.peers) { dest = dest[:len(wn.peers)] } else { dest = make([]*wsPeer, len(wn.peers)) } copy(dest, wn.peers) return dest } // prio is set if the broadcast is a high-priority broadcast. func (wn *WebsocketNetwork) innerBroadcast(request broadcastRequest, prio bool, ppeers *[]*wsPeer) { if request.done != nil { defer close(request.done) } broadcastQueueDuration := time.Now().Sub(request.enqueueTime) networkBroadcastQueueMicros.AddUint64(uint64(broadcastQueueDuration.Nanoseconds()/1000), nil) if broadcastQueueDuration > maxMessageQueueDuration { networkBroadcastsDropped.Inc(nil) return } start := time.Now() tbytes := []byte(request.tag) mbytes := make([]byte, len(tbytes)+len(request.data)) copy(mbytes, tbytes) copy(mbytes[len(tbytes):], request.data) var digest crypto.Digest if request.tag != protocol.MsgSkipTag && len(request.data) >= messageFilterSize { digest = crypto.Hash(mbytes) } *ppeers = wn.peerSnapshot(*ppeers) peers := *ppeers // first send to all the easy outbound peers who don't block, get them started. sentMessageCount := 0 for pi, peer := range peers { if wn.config.BroadcastConnectionsLimit >= 0 && sentMessageCount >= wn.config.BroadcastConnectionsLimit { break } if peer == request.except { peers[pi] = nil continue } ok := peer.writeNonBlock(mbytes, prio, digest, request.enqueueTime) if ok { peers[pi] = nil sentMessageCount++ continue } networkPeerBroadcastDropped.Inc(nil) } dt := time.Now().Sub(start) networkBroadcasts.Inc(nil) networkBroadcastSendMicros.AddUint64(uint64(dt.Nanoseconds()/1000), nil) } // NumPeers returns number of peers we connect to (all peers incoming and outbound). func (wn *WebsocketNetwork) NumPeers() int { wn.peersLock.RLock() defer wn.peersLock.RUnlock() return len(wn.peers) } func (wn *WebsocketNetwork) numOutgoingPeers() int { wn.peersLock.RLock() defer wn.peersLock.RUnlock() count := 0 for _, peer := range wn.peers { if peer.outgoing { count++ } } return count } func (wn *WebsocketNetwork) numIncomingPeers() int { wn.peersLock.RLock() defer wn.peersLock.RUnlock() count := 0 for _, peer := range wn.peers { if !peer.outgoing { count++ } } return count } // isConnectedTo returns true if addr matches any connected peer, based on the peer's root url. func (wn *WebsocketNetwork) isConnectedTo(addr string) bool { wn.peersLock.RLock() defer wn.peersLock.RUnlock() for _, peer := range wn.peers { if addr == peer.rootURL { return true } } return false } // connectedForIP returns number of peers with same host func (wn *WebsocketNetwork) connectedForIP(host string) (totalConnections int) { wn.peersLock.RLock() defer wn.peersLock.RUnlock() totalConnections = 0 for _, peer := range wn.peers { if host == peer.OriginAddress() { totalConnections++ } } return } const meshThreadInterval = time.Minute type meshRequest struct { disconnect bool done chan struct{} } func imin(a, b int) int { if a < b { return a } return b } // meshThread maintains the network, e.g. that we have sufficient connectivity to peers func (wn *WebsocketNetwork) meshThread() { defer wn.wg.Done() timer := time.NewTicker(meshThreadInterval) defer timer.Stop() for { var request meshRequest select { case <-timer.C: request.disconnect = false request.done = nil case request = <-wn.meshUpdateRequests: case <-wn.ctx.Done(): return } if request.disconnect { wn.DisconnectPeers() } // TODO: only do DNS fetch every N seconds? Honor DNS TTL? Trust DNS library we're using to handle caching and TTL? dnsBootstrapArray := wn.config.DNSBootstrapArray(wn.NetworkID) for _, dnsBootstrap := range dnsBootstrapArray { dnsAddrs := wn.getDNSAddrs(dnsBootstrap) if len(dnsAddrs) > 0 { wn.log.Debugf("got %d dns addrs, %#v", len(dnsAddrs), dnsAddrs[:imin(5, len(dnsAddrs))]) dnsPhonebook := wn.phonebook.GetPhonebook(dnsBootstrap) if dnsPhonebook == nil { // create one, if we don't have one already. dnsPhonebook = MakeThreadsafePhonebook() wn.phonebook.AddOrUpdatePhonebook(dnsBootstrap, dnsPhonebook) } if tsPhonebook, ok := dnsPhonebook.(*ThreadsafePhonebook); ok { tsPhonebook.ReplacePeerList(dnsAddrs) } } else { wn.log.Infof("got no DNS addrs for network %s", wn.NetworkID) } } desired := wn.config.GossipFanout numOutgoing := wn.numOutgoingPeers() + wn.numOutgoingPending() need := desired - numOutgoing if need > 0 { // get more than we need so that we can ignore duplicates newAddrs := wn.phonebook.GetAddresses(desired + numOutgoing) for _, na := range newAddrs { if na == wn.config.PublicAddress { continue } gossipAddr, ok := wn.tryConnectReserveAddr(na) if ok { wn.wg.Add(1) go wn.tryConnect(na, gossipAddr) need-- if need == 0 { break } } } } if request.done != nil { close(request.done) } } } // prioWeightRefreshTime controls how often we refresh the weights // of connected peers. const prioWeightRefreshTime = time.Minute // prioWeightRefresh periodically refreshes the weights of connected peers. func (wn *WebsocketNetwork) prioWeightRefresh() { defer wn.wg.Done() ticker := time.NewTicker(prioWeightRefreshTime) defer ticker.Stop() var peers []*wsPeer for { select { case <-ticker.C: case <-wn.ctx.Done(): return } peers = wn.peerSnapshot(peers) for _, peer := range peers { wn.peersLock.RLock() addr := peer.prioAddress weight := peer.prioWeight wn.peersLock.RUnlock() newWeight := wn.prioScheme.GetPrioWeight(addr) if newWeight != weight { wn.peersLock.Lock() wn.prioTracker.setPriority(peer, addr, newWeight) wn.peersLock.Unlock() } } } } // Wake up the thread to do work this often. const pingThreadPeriod = 30 * time.Second // If ping stats are older than this, don't include in metrics. const maxPingAge = 30 * time.Minute // pingThread wakes up periodically to refresh the ping times on peers and update the metrics gauges. func (wn *WebsocketNetwork) pingThread() { defer wn.wg.Done() ticker := time.NewTicker(pingThreadPeriod) defer ticker.Stop() for { select { case <-ticker.C: case <-wn.ctx.Done(): return } sendList := wn.peersToPing() wn.log.Debugf("ping %d peers...", len(sendList)) for _, peer := range sendList { if !peer.sendPing() { // if we failed to send a ping, see how long it was since last successfull ping. lastPingSent, _ := peer.pingTimes() wn.log.Infof("failed to ping to %v for the past %f seconds", peer, time.Now().Sub(lastPingSent).Seconds()) } } } } // Walks list of peers, gathers list of peers to ping, also calculates statistics. func (wn *WebsocketNetwork) peersToPing() []*wsPeer { wn.peersLock.RLock() defer wn.peersLock.RUnlock() // Never flood outbound traffic by trying to ping all the peers at once. // Send to at most one fifth of the peers. maxSend := 1 + (len(wn.peers) / 5) out := make([]*wsPeer, 0, maxSend) now := time.Now() // a list to sort to find median times := make([]float64, 0, len(wn.peers)) var min = math.MaxFloat64 var max float64 var sum float64 pingPeriod := time.Duration(wn.config.PeerPingPeriodSeconds) * time.Second for _, peer := range wn.peers { lastPingSent, lastPingRoundTripTime := peer.pingTimes() sendToNow := now.Sub(lastPingSent) if (sendToNow > pingPeriod) && (len(out) < maxSend) { out = append(out, peer) } if (lastPingRoundTripTime > 0) && (sendToNow < maxPingAge) { ftime := lastPingRoundTripTime.Seconds() sum += ftime times = append(times, ftime) if ftime < min { min = ftime } if ftime > max { max = ftime } } } if len(times) != 0 { sort.Float64s(times) median := times[len(times)/2] medianPing.Set(median, nil) mean := sum / float64(len(times)) meanPing.Set(mean, nil) minPing.Set(min, nil) maxPing.Set(max, nil) wn.log.Infof("ping times min=%f mean=%f median=%f max=%f", min, mean, median, max) } return out } func (wn *WebsocketNetwork) getDNSAddrs(dnsBootstrap string) []string { srvPhonebook, err := tools_network.ReadFromSRV("algobootstrap", dnsBootstrap, wn.config.FallbackDNSResolverAddress) if err != nil { // only log this warning on testnet or devnet if wn.NetworkID == config.Devnet || wn.NetworkID == config.Testnet { wn.log.Warnf("Cannot lookup SRV record for %s: %v", dnsBootstrap, err) } return nil } return srvPhonebook } // ProtocolVersionHeader HTTP header for protocol version. TODO: this may be unneeded redundance since we also have url versioning "/v1/..." const ProtocolVersionHeader = "X-Algorand-Version" // ProtocolVersion is the current version attached to the ProtocolVersionHeader header const ProtocolVersion = "1" // TelemetryIDHeader HTTP header for telemetry-id for logging const TelemetryIDHeader = "X-Algorand-TelId" // GenesisHeader HTTP header for genesis id to make sure we're on the same chain const GenesisHeader = "X-Algorand-Genesis" // NodeRandomHeader HTTP header that a node uses to make sure it's not talking to itself const NodeRandomHeader = "X-Algorand-NodeRandom" // AddressHeader HTTP header by which an inbound connection reports its public address const AddressHeader = "X-Algorand-Location" // InstanceNameHeader HTTP header by which an inbound connection reports an ID to distinguish multiple local nodes. const InstanceNameHeader = "X-Algorand-InstanceName" // PriorityChallengeHeader HTTP header informs a client about the challenge it should sign to increase network priority. const PriorityChallengeHeader = "X-Algorand-PriorityChallenge" // TooManyRequestsRetryAfterHeader HTTP header let the client know when to make the next connection attempt const TooManyRequestsRetryAfterHeader = "Retry-After" // UserAgentHeader is the HTTP header identify the user agent. const UserAgentHeader = "User-Agent" var websocketsScheme = map[string]string{"http": "ws", "https": "wss"} var errBadAddr = errors.New("bad address") var errNetworkClosing = errors.New("WebsocketNetwork shutting down") var errBcastCallerCancel = errors.New("caller cancelled broadcast") var errBcastQFull = errors.New("broadcast queue full") // HostColonPortPattern matches "^[^:]+:\\d+$" e.g. "foo.com.:1234" var HostColonPortPattern = regexp.MustCompile("^[^:]+:\\d+$") // ParseHostOrURL handles "host:port" or a full URL. // Standard library net/url.Parse chokes on "host:port". func ParseHostOrURL(addr string) (*url.URL, error) { var parsedURL *url.URL if HostColonPortPattern.MatchString(addr) { parsedURL = &url.URL{Scheme: "http", Host: addr} return parsedURL, nil } return url.Parse(addr) } // addrToGossipAddr parses host:port or a URL and returns the URL to the websocket interface at that address. func (wn *WebsocketNetwork) addrToGossipAddr(addr string) (string, error) { parsedURL, err := ParseHostOrURL(addr) if err != nil { wn.log.Warnf("could not parse addr %#v: %s", addr, err) return "", errBadAddr } parsedURL.Scheme = websocketsScheme[parsedURL.Scheme] if parsedURL.Scheme == "" { parsedURL.Scheme = "ws" } parsedURL.Path = strings.Replace(path.Join(parsedURL.Path, GossipNetworkPath), "{genesisID}", wn.GenesisID, -1) return parsedURL.String(), nil } // tryConnectReserveAddr synchronously checks that addr is not already being connected to, returns (websocket URL or "", true if connection may procede) func (wn *WebsocketNetwork) tryConnectReserveAddr(addr string) (gossipAddr string, ok bool) { wn.tryConnectLock.Lock() defer wn.tryConnectLock.Unlock() _, exists := wn.tryConnectAddrs[addr] if exists { return "", false } gossipAddr, err := wn.addrToGossipAddr(addr) if err != nil { return "", false } _, exists = wn.tryConnectAddrs[gossipAddr] if exists { return "", false } // WARNING: isConnectedTo takes wn.peersLock; to avoid deadlock, never try to take wn.peersLock outside an attempt to lock wn.tryConnectLock if wn.isConnectedTo(addr) { return "", false } now := time.Now().Unix() wn.tryConnectAddrs[addr] = now wn.tryConnectAddrs[gossipAddr] = now return gossipAddr, true } // tryConnectReleaseAddr should be called when connection succedes and becomes a peer or fails and is no longer being attempted func (wn *WebsocketNetwork) tryConnectReleaseAddr(addr, gossipAddr string) { wn.tryConnectLock.Lock() defer wn.tryConnectLock.Unlock() delete(wn.tryConnectAddrs, addr) delete(wn.tryConnectAddrs, gossipAddr) } func (wn *WebsocketNetwork) numOutgoingPending() int { wn.tryConnectLock.Lock() defer wn.tryConnectLock.Unlock() return len(wn.tryConnectAddrs) } var websocketDialer = websocket.Dialer{ Proxy: http.ProxyFromEnvironment, HandshakeTimeout: 45 * time.Second, EnableCompression: false, } // tryConnect opens websocket connection and checks initial connection parameters. // addr should be 'host:port' or a URL, gossipAddr is the websocket endpoint URL func (wn *WebsocketNetwork) tryConnect(addr, gossipAddr string) { defer wn.tryConnectReleaseAddr(addr, gossipAddr) defer func() { if xpanic := recover(); xpanic != nil { wn.log.Errorf("panic in tryConnect: %v", xpanic) } }() defer wn.wg.Done() requestHeader := make(http.Header) wn.setHeaders(requestHeader) SetUserAgentHeader(requestHeader) myInstanceName := wn.log.GetInstanceName() requestHeader.Set(InstanceNameHeader, myInstanceName) conn, response, err := websocketDialer.DialContext(wn.ctx, gossipAddr, requestHeader) if err != nil { if err == websocket.ErrBadHandshake { // reading here from ioutil is safe only because it came from DialContext above, which alredy finsihed reading all the data from the network // and placed it all in a ioutil.NopCloser reader. bodyBytes, _ := ioutil.ReadAll(response.Body) errString := string(bodyBytes) if len(errString) > 128 { errString = errString[:128] } // we're guaranteed to have a valid response object. switch response.StatusCode { case http.StatusPreconditionFailed: wn.log.Warnf("ws connect(%s) fail - bad handshake, precondition failed : '%s'", gossipAddr, errString) case http.StatusLoopDetected: wn.log.Infof("ws connect(%s) aborted due to connecting to self", gossipAddr) case http.StatusTooManyRequests: wn.log.Infof("ws connect(%s) aborted due to connecting too frequently", gossipAddr) retryAfterHeader := response.Header.Get(TooManyRequestsRetryAfterHeader) if retryAfter, retryParseErr := strconv.ParseUint(retryAfterHeader, 10, 32); retryParseErr == nil { // we've got a retry-after header. // convert it to a timestamp so that we could use it. retryAfterTime := time.Now().Add(time.Duration(retryAfter) * time.Second) wn.phonebook.UpdateRetryAfter(addr, retryAfterTime) } default: wn.log.Warnf("ws connect(%s) fail - bad handshake, Status code = %d, Headers = %#v, Body = %s", gossipAddr, response.StatusCode, response.Header, errString) } } else { wn.log.Warnf("ws connect(%s) fail: %s", gossipAddr, err) } return } // no need to test the response.StatusCode since we know it's going to be http.StatusSwitchingProtocols, as it's already being tested inside websocketDialer.DialContext. // checking the headers here is abit redundent; the server has already verified that the headers match. But we will need this in the future - // once our server would support multiple protocols, we would need to verify here that we use the correct protocol, out of the "proposed" protocols we have provided in the // request headers. if !wn.checkServerResponseVariables(response.Header, gossipAddr) { // The error was already logged, so no need to log again. return } peer := &wsPeer{wsPeerCore: wsPeerCore{net: wn, rootURL: addr}, conn: conn, outgoing: true, incomingMsgFilter: wn.incomingMsgFilter, createTime: time.Now()} peer.TelemetryGUID = response.Header.Get(TelemetryIDHeader) peer.init(wn.config, wn.outgoingMessagesBufferSize) wn.addPeer(peer) localAddr, _ := wn.Address() wn.log.With("event", "ConnectedOut").With("remote", addr).With("local", localAddr).Infof("Made outgoing connection to peer %v", addr) wn.log.EventWithDetails(telemetryspec.Network, telemetryspec.ConnectPeerEvent, telemetryspec.PeerEventDetails{ Address: justHost(conn.RemoteAddr().String()), HostName: peer.TelemetryGUID, Incoming: false, InstanceName: myInstanceName, }) peers.Set(float64(wn.NumPeers()), nil) outgoingPeers.Set(float64(wn.numOutgoingPeers()), nil) if wn.prioScheme != nil { challenge := response.Header.Get(PriorityChallengeHeader) if challenge != "" { resp := wn.prioScheme.MakePrioResponse(challenge) if resp != nil { mbytes := append([]byte(protocol.NetPrioResponseTag), resp...) sent := peer.writeNonBlock(mbytes, true, crypto.Digest{}, time.Now()) if !sent { wn.log.With("remote", addr).With("local", localAddr).Warnf("could not send priority response to %v", addr) } } } } } // NewWebsocketNetwork constructor for websockets based gossip network func NewWebsocketNetwork(log logging.Logger, config config.Local, phonebook Phonebook, genesisID string, networkID protocol.NetworkID) (wn *WebsocketNetwork, err error) { outerPhonebook := MakeMultiPhonebook() outerPhonebook.AddOrUpdatePhonebook("default", phonebook) wn = &WebsocketNetwork{log: log, config: config, phonebook: outerPhonebook, GenesisID: genesisID, NetworkID: networkID} wn.setup() return wn, nil } // NewWebsocketGossipNode constructs a websocket network node and returns it as a GossipNode interface implementation func NewWebsocketGossipNode(log logging.Logger, config config.Local, phonebook Phonebook, genesisID string, networkID protocol.NetworkID) (gn GossipNode, err error) { return NewWebsocketNetwork(log, config, phonebook, genesisID, networkID) } // SetPrioScheme specifies the network priority scheme for a network node func (wn *WebsocketNetwork) SetPrioScheme(s NetPrioScheme) { wn.prioScheme = s } // called from wsPeer to report that it has closed func (wn *WebsocketNetwork) peerRemoteClose(peer *wsPeer, reason disconnectReason) { wn.removePeer(peer, reason) } func (wn *WebsocketNetwork) removePeer(peer *wsPeer, reason disconnectReason) { // first logging, then take the lock and do the actual accounting. // definitely don't change this to do the logging while holding the lock. localAddr, _ := wn.Address() wn.log.With("event", "Disconnected").With("remote", peer.rootURL).With("local", localAddr).Infof("Peer %v disconnected", peer.rootURL) peerAddr := peer.OriginAddress() // we might be able to get addr out of conn, or it might be closed if peerAddr == "" && peer.conn != nil { paddr := peer.conn.RemoteAddr() if paddr != nil { peerAddr = justHost(paddr.String()) } } if peerAddr == "" { // didn't get addr from peer, try from url url, err := url.Parse(peer.rootURL) if err == nil { peerAddr = justHost(url.Host) } else { // use whatever it is peerAddr = justHost(peer.rootURL) } } wn.log.EventWithDetails(telemetryspec.Network, telemetryspec.DisconnectPeerEvent, telemetryspec.DisconnectPeerEventDetails{ PeerEventDetails: telemetryspec.PeerEventDetails{ Address: peerAddr, HostName: peer.TelemetryGUID, Incoming: !peer.outgoing, InstanceName: peer.InstanceName, }, Reason: string(reason), }) peers.Set(float64(wn.NumPeers()), nil) incomingPeers.Set(float64(wn.numIncomingPeers()), nil) outgoingPeers.Set(float64(wn.numOutgoingPeers()), nil) wn.peersLock.Lock() defer wn.peersLock.Unlock() if peer.peerIndex < len(wn.peers) && wn.peers[peer.peerIndex] == peer { heap.Remove(peersHeap{wn}, peer.peerIndex) wn.prioTracker.removePeer(peer) } wn.countPeersSetGauges() } func (wn *WebsocketNetwork) addPeer(peer *wsPeer) { wn.peersLock.Lock() defer wn.peersLock.Unlock() for _, p := range wn.peers { if p == peer { wn.log.Error("dup peer added %#v", peer) return } } heap.Push(peersHeap{wn}, peer) wn.prioTracker.setPriority(peer, peer.prioAddress, peer.prioWeight) wn.countPeersSetGauges() if len(wn.peers) >= wn.config.GossipFanout { // we have a quorum of connected peers, if we weren't ready before, we are now if atomic.CompareAndSwapInt32(&wn.ready, 0, 1) { wn.log.Debug("ready") close(wn.readyChan) } } else if atomic.LoadInt32(&wn.ready) == 0 { // but if we're not ready in a minute, call whatever peers we've got as good enough wn.wg.Add(1) go wn.eventualReady() } } func (wn *WebsocketNetwork) eventualReady() { defer wn.wg.Done() minute := time.NewTimer(wn.eventualReadyDelay) select { case <-wn.ctx.Done(): case <-minute.C: if atomic.CompareAndSwapInt32(&wn.ready, 0, 1) { wn.log.Debug("ready") close(wn.readyChan) } } } // should be run from inside a context holding wn.peersLock func (wn *WebsocketNetwork) countPeersSetGauges() { numIn := 0 numOut := 0 for _, xp := range wn.peers { if xp.outgoing { numOut++ } else { numIn++ } } networkIncomingConnections.Set(float64(numIn), nil) networkOutgoingConnections.Set(float64(numOut), nil) } func justHost(hostPort string) string { host, _, err := net.SplitHostPort(hostPort) if err != nil { return hostPort } return host } // SetUserAgentHeader adds the User-Agent header to the provided heades map. func SetUserAgentHeader(header http.Header) { version := config.GetCurrentVersion() ua := fmt.Sprintf("algod/%d.%d (%s; commit=%s; %d) %s(%s)", version.Major, version.Minor, version.Channel, version.CommitHash, version.BuildNumber, runtime.GOOS, runtime.GOARCH) header.Set(UserAgentHeader, ua) }
1
36,821
Nit: We can use `%s` since `disconnectReason` is a string.
algorand-go-algorand
go
@@ -17,7 +17,8 @@ X_test = df_test.drop(0, axis=1).values print('Start training...') # train -gbm = lgb.LGBMRegressor(objective='regression', +gbm = lgb.LGBMRegressor(boosting_type='rgf', + objective='regression', num_leaves=31, learning_rate=0.05, n_estimators=20)
1
# coding: utf-8 # pylint: disable = invalid-name, C0111 import lightgbm as lgb import pandas as pd from sklearn.metrics import mean_squared_error from sklearn.model_selection import GridSearchCV # load or create your dataset print('Load data...') df_train = pd.read_csv('../regression/regression.train', header=None, sep='\t') df_test = pd.read_csv('../regression/regression.test', header=None, sep='\t') y_train = df_train[0].values y_test = df_test[0].values X_train = df_train.drop(0, axis=1).values X_test = df_test.drop(0, axis=1).values print('Start training...') # train gbm = lgb.LGBMRegressor(objective='regression', num_leaves=31, learning_rate=0.05, n_estimators=20) gbm.fit(X_train, y_train, eval_set=[(X_test, y_test)], eval_metric='l1', early_stopping_rounds=5) print('Start predicting...') # predict y_pred = gbm.predict(X_test, num_iteration=gbm.best_iteration_) # eval print('The rmse of prediction is:', mean_squared_error(y_test, y_pred) ** 0.5) # feature importances print('Feature importances:', list(gbm.feature_importances_)) # other scikit-learn modules estimator = lgb.LGBMRegressor(num_leaves=31) param_grid = { 'learning_rate': [0.01, 0.1, 1], 'n_estimators': [20, 40] } gbm = GridSearchCV(estimator, param_grid) gbm.fit(X_train, y_train) print('Best parameters found by grid search are:', gbm.best_params_)
1
18,370
I think it's better to create a new example
microsoft-LightGBM
cpp
@@ -392,7 +392,7 @@ void ResolveOperation(Action &action, const RENDER_PASS_STATE &rp_state, const V if (aspect_mask) { action(aspect_string, "resolve read", src_at, dst_at, attachment_views[src_at], - SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ, kDepthStencilAttachmentRasterOrder, offset, extent, + SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ, kAttachmentRasterOrder, offset, extent, aspect_mask); action(aspect_string, "resolve write", src_at, dst_at, attachment_views[dst_at], SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, kAttachmentRasterOrder, offset, extent, aspect_mask);
1
/* Copyright (c) 2019-2020 The Khronos Group Inc. * Copyright (c) 2019-2020 Valve Corporation * Copyright (c) 2019-2020 LunarG, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Author: John Zulauf <[email protected]> */ #include <limits> #include <vector> #include <memory> #include <bitset> #include "synchronization_validation.h" static const char *string_SyncHazardVUID(SyncHazard hazard) { switch (hazard) { case SyncHazard::NONE: return "SYNC-HAZARD-NONE"; break; case SyncHazard::READ_AFTER_WRITE: return "SYNC-HAZARD-READ_AFTER_WRITE"; break; case SyncHazard::WRITE_AFTER_READ: return "SYNC-HAZARD-WRITE_AFTER_READ"; break; case SyncHazard::WRITE_AFTER_WRITE: return "SYNC-HAZARD-WRITE_AFTER_WRITE"; break; case SyncHazard::READ_RACING_WRITE: return "SYNC-HAZARD-READ-RACING-WRITE"; break; case SyncHazard::WRITE_RACING_WRITE: return "SYNC-HAZARD-WRITE-RACING-WRITE"; break; case SyncHazard::WRITE_RACING_READ: return "SYNC-HAZARD-WRITE-RACING-READ"; break; default: assert(0); } return "SYNC-HAZARD-INVALID"; } static bool IsHazardVsRead(SyncHazard hazard) { switch (hazard) { case SyncHazard::NONE: return false; break; case SyncHazard::READ_AFTER_WRITE: return false; break; case SyncHazard::WRITE_AFTER_READ: return true; break; case SyncHazard::WRITE_AFTER_WRITE: return false; break; case SyncHazard::READ_RACING_WRITE: return false; break; case SyncHazard::WRITE_RACING_WRITE: return false; break; case SyncHazard::WRITE_RACING_READ: return true; break; default: assert(0); } return false; } static const char *string_SyncHazard(SyncHazard hazard) { switch (hazard) { case SyncHazard::NONE: return "NONR"; break; case SyncHazard::READ_AFTER_WRITE: return "READ_AFTER_WRITE"; break; case SyncHazard::WRITE_AFTER_READ: return "WRITE_AFTER_READ"; break; case SyncHazard::WRITE_AFTER_WRITE: return "WRITE_AFTER_WRITE"; break; case SyncHazard::READ_RACING_WRITE: return "READ_RACING_WRITE"; break; case SyncHazard::WRITE_RACING_WRITE: return "WRITE_RACING_WRITE"; break; case SyncHazard::WRITE_RACING_READ: return "WRITE_RACING_READ"; break; default: assert(0); } return "INVALID HAZARD"; } static const SyncStageAccessInfoType *SyncStageAccessInfoFromMask(SyncStageAccessFlags flags) { // Return the info for the first bit found const SyncStageAccessInfoType *info = nullptr; for (size_t i = 0; i < flags.size(); i++) { if (flags.test(i)) { info = &syncStageAccessInfoByStageAccessIndex[i]; break; } } return info; } static std::string string_SyncStageAccessFlags(const SyncStageAccessFlags &flags, const char *sep = "|") { std::string out_str; if (flags.none()) { out_str = "0"; } else { for (size_t i = 0; i < syncStageAccessInfoByStageAccessIndex.size(); i++) { const auto &info = syncStageAccessInfoByStageAccessIndex[i]; if ((flags & info.stage_access_bit).any()) { if (!out_str.empty()) { out_str.append(sep); } out_str.append(info.name); } } if (out_str.length() == 0) { out_str.append("Unhandled SyncStageAccess"); } } return out_str; } static std::string string_UsageTag(const HazardResult &hazard) { const auto &tag = hazard.tag; assert(hazard.usage_index < static_cast<SyncStageAccessIndex>(syncStageAccessInfoByStageAccessIndex.size())); const auto &usage_info = syncStageAccessInfoByStageAccessIndex[hazard.usage_index]; std::stringstream out; const auto *info = SyncStageAccessInfoFromMask(hazard.prior_access); const char *stage_access_name = info ? info->name : "INVALID_STAGE_ACCESS"; out << "(usage: " << usage_info.name << ", prior_usage: " << stage_access_name; if (IsHazardVsRead(hazard.hazard)) { const auto barriers = hazard.access_state->GetReadBarriers(hazard.prior_access); out << ", read_barriers: " << string_VkPipelineStageFlags(barriers); } else { SyncStageAccessFlags write_barrier = hazard.access_state->GetWriteBarriers(); out << ", write_barriers: " << string_SyncStageAccessFlags(write_barrier); } out << ", command: " << CommandTypeString(tag.command); out << ", seq_no: " << (tag.index & 0xFFFFFFFF) << ", reset_no: " << (tag.index >> 32) << ")"; return out.str(); } // NOTE: the attachement read flag is put *only* in the access scope and not in the exect scope, since the ordering // rules apply only to this specific access for this stage, and not the stage as a whole. The ordering detection // also reflects this special case for read hazard detection (using access instead of exec scope) static constexpr VkPipelineStageFlags kColorAttachmentExecScope = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; static const SyncStageAccessFlags kColorAttachmentAccessScope = SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ_BIT | SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ_NONCOHERENT_BIT_EXT | SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE_BIT | SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT; // Note: this is intentionally not in the exec scope static constexpr VkPipelineStageFlags kDepthStencilAttachmentExecScope = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT; static const SyncStageAccessFlags kDepthStencilAttachmentAccessScope = SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT | SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT | SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT; // Note: this is intentionally not in the exec scope static const SyncOrderingBarrier kColorAttachmentRasterOrder = {kColorAttachmentExecScope, kColorAttachmentAccessScope}; static const SyncOrderingBarrier kDepthStencilAttachmentRasterOrder = {kDepthStencilAttachmentExecScope, kDepthStencilAttachmentAccessScope}; static const SyncOrderingBarrier kAttachmentRasterOrder = {kDepthStencilAttachmentExecScope | kColorAttachmentExecScope, kDepthStencilAttachmentAccessScope | kColorAttachmentAccessScope}; // Sometimes we have an internal access conflict, and we using the kCurrentCommandTag to set and detect in temporary/proxy contexts static const ResourceUsageTag kCurrentCommandTag(ResourceUsageTag::kMaxIndex, CMD_NONE); static VkDeviceSize ResourceBaseAddress(const BINDABLE &bindable) { return bindable.binding.offset + bindable.binding.mem_state->fake_base_address; } static bool SimpleBinding(const BINDABLE &bindable) { return !bindable.sparse && bindable.binding.mem_state; } inline VkDeviceSize GetRealWholeSize(VkDeviceSize offset, VkDeviceSize size, VkDeviceSize whole_size) { if (size == VK_WHOLE_SIZE) { return (whole_size - offset); } return size; } static inline VkDeviceSize GetBufferWholeSize(const BUFFER_STATE &buf_state, VkDeviceSize offset, VkDeviceSize size) { return GetRealWholeSize(offset, size, buf_state.createInfo.size); } template <typename T> static ResourceAccessRange MakeRange(const T &has_offset_and_size) { return ResourceAccessRange(has_offset_and_size.offset, (has_offset_and_size.offset + has_offset_and_size.size)); } static ResourceAccessRange MakeRange(VkDeviceSize start, VkDeviceSize size) { return ResourceAccessRange(start, (start + size)); } static inline ResourceAccessRange MakeRange(const BUFFER_STATE &buffer, VkDeviceSize offset, VkDeviceSize size) { return MakeRange(offset, GetBufferWholeSize(buffer, offset, size)); } static inline ResourceAccessRange MakeRange(const BUFFER_VIEW_STATE &buf_view_state) { return MakeRange(*buf_view_state.buffer_state.get(), buf_view_state.create_info.offset, buf_view_state.create_info.range); } // Expand the pipeline stage without regard to whether the are valid w.r.t. queue or extension VkPipelineStageFlags ExpandPipelineStages(VkQueueFlags queue_flags, VkPipelineStageFlags stage_mask) { VkPipelineStageFlags expanded = stage_mask; if (VK_PIPELINE_STAGE_ALL_COMMANDS_BIT & stage_mask) { expanded = expanded & ~VK_PIPELINE_STAGE_ALL_COMMANDS_BIT; for (const auto &all_commands : syncAllCommandStagesByQueueFlags) { if (all_commands.first & queue_flags) { expanded |= all_commands.second; } } } if (VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT & stage_mask) { expanded = expanded & ~VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT; expanded |= syncAllCommandStagesByQueueFlags.at(VK_QUEUE_GRAPHICS_BIT) & ~VK_PIPELINE_STAGE_HOST_BIT; } return expanded; } VkPipelineStageFlags RelatedPipelineStages(VkPipelineStageFlags stage_mask, const std::map<VkPipelineStageFlagBits, VkPipelineStageFlags> &map) { VkPipelineStageFlags unscanned = stage_mask; VkPipelineStageFlags related = 0; for (const auto &entry : map) { const auto &stage = entry.first; if (stage & unscanned) { related = related | entry.second; unscanned = unscanned & ~stage; if (!unscanned) break; } } return related; } VkPipelineStageFlags WithEarlierPipelineStages(VkPipelineStageFlags stage_mask) { return stage_mask | RelatedPipelineStages(stage_mask, syncLogicallyEarlierStages); } VkPipelineStageFlags WithLaterPipelineStages(VkPipelineStageFlags stage_mask) { return stage_mask | RelatedPipelineStages(stage_mask, syncLogicallyLaterStages); } static const ResourceAccessRange full_range(std::numeric_limits<VkDeviceSize>::min(), std::numeric_limits<VkDeviceSize>::max()); ResourceAccessRange GetBufferRange(VkDeviceSize offset, VkDeviceSize buf_whole_size, uint32_t first_index, uint32_t count, VkDeviceSize stride) { VkDeviceSize range_start = offset + first_index * stride; VkDeviceSize range_size = 0; if (count == UINT32_MAX) { range_size = buf_whole_size - range_start; } else { range_size = count * stride; } return MakeRange(range_start, range_size); } SyncStageAccessIndex GetSyncStageAccessIndexsByDescriptorSet(VkDescriptorType descriptor_type, const interface_var &descriptor_data, VkShaderStageFlagBits stage_flag) { if (descriptor_type == VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT) { assert(stage_flag == VK_SHADER_STAGE_FRAGMENT_BIT); return SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ; } auto stage_access = syncStageAccessMaskByShaderStage.find(stage_flag); if (stage_access == syncStageAccessMaskByShaderStage.end()) { assert(0); } if (descriptor_type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER || descriptor_type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC) { return stage_access->second.uniform_read; } // If the desriptorSet is writable, we don't need to care SHADER_READ. SHADER_WRITE is enough. // Because if write hazard happens, read hazard might or might not happen. // But if write hazard doesn't happen, read hazard is impossible to happen. if (descriptor_data.is_writable) { return stage_access->second.shader_write; } return stage_access->second.shader_read; } bool IsImageLayoutDepthWritable(VkImageLayout image_layout) { return (image_layout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL || image_layout == VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL || image_layout == VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL) ? true : false; } bool IsImageLayoutStencilWritable(VkImageLayout image_layout) { return (image_layout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL || image_layout == VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL || image_layout == VK_IMAGE_LAYOUT_STENCIL_ATTACHMENT_OPTIMAL) ? true : false; } // Class AccessContext stores the state of accesses specific to a Command, Subpass, or Queue const std::array<AccessContext::AddressType, AccessContext::kAddressTypeCount> AccessContext::kAddressTypes = { AccessContext::AddressType::kLinearAddress, AccessContext::AddressType::kIdealizedAddress}; template <typename Action> static void ApplyOverImageRange(const IMAGE_STATE &image_state, const VkImageSubresourceRange &subresource_range_arg, Action &action) { // At this point the "apply over range" logic only supports a single memory binding if (!SimpleBinding(image_state)) return; auto subresource_range = NormalizeSubresourceRange(image_state.createInfo, subresource_range_arg); subresource_adapter::ImageRangeGenerator range_gen(*image_state.fragment_encoder.get(), subresource_range, {0, 0, 0}, image_state.createInfo.extent); const auto base_address = ResourceBaseAddress(image_state); for (; range_gen->non_empty(); ++range_gen) { action((*range_gen + base_address)); } } // Tranverse the attachment resolves for this a specific subpass, and do action() to them. // Used by both validation and record operations // // The signature for Action() reflect the needs of both uses. template <typename Action> void ResolveOperation(Action &action, const RENDER_PASS_STATE &rp_state, const VkRect2D &render_area, const std::vector<const IMAGE_VIEW_STATE *> &attachment_views, uint32_t subpass) { VkExtent3D extent = CastTo3D(render_area.extent); VkOffset3D offset = CastTo3D(render_area.offset); const auto &rp_ci = rp_state.createInfo; const auto *attachment_ci = rp_ci.pAttachments; const auto &subpass_ci = rp_ci.pSubpasses[subpass]; // Color resolves -- require an inuse color attachment and a matching inuse resolve attachment const auto *color_attachments = subpass_ci.pColorAttachments; const auto *color_resolve = subpass_ci.pResolveAttachments; if (color_resolve && color_attachments) { for (uint32_t i = 0; i < subpass_ci.colorAttachmentCount; i++) { const auto &color_attach = color_attachments[i].attachment; const auto &resolve_attach = subpass_ci.pResolveAttachments[i].attachment; if ((color_attach != VK_ATTACHMENT_UNUSED) && (resolve_attach != VK_ATTACHMENT_UNUSED)) { action("color", "resolve read", color_attach, resolve_attach, attachment_views[color_attach], SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ, kColorAttachmentRasterOrder, offset, extent, 0); action("color", "resolve write", color_attach, resolve_attach, attachment_views[resolve_attach], SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, kColorAttachmentRasterOrder, offset, extent, 0); } } } // Depth stencil resolve only if the extension is present const auto ds_resolve = lvl_find_in_chain<VkSubpassDescriptionDepthStencilResolve>(subpass_ci.pNext); if (ds_resolve && ds_resolve->pDepthStencilResolveAttachment && (ds_resolve->pDepthStencilResolveAttachment->attachment != VK_ATTACHMENT_UNUSED) && subpass_ci.pDepthStencilAttachment && (subpass_ci.pDepthStencilAttachment->attachment != VK_ATTACHMENT_UNUSED)) { const auto src_at = subpass_ci.pDepthStencilAttachment->attachment; const auto src_ci = attachment_ci[src_at]; // The formats are required to match so we can pick either const bool resolve_depth = (ds_resolve->depthResolveMode != VK_RESOLVE_MODE_NONE) && FormatHasDepth(src_ci.format); const bool resolve_stencil = (ds_resolve->stencilResolveMode != VK_RESOLVE_MODE_NONE) && FormatHasStencil(src_ci.format); const auto dst_at = ds_resolve->pDepthStencilResolveAttachment->attachment; VkImageAspectFlags aspect_mask = 0u; // Figure out which aspects are actually touched during resolve operations const char *aspect_string = nullptr; if (resolve_depth && resolve_stencil) { // Validate all aspects together aspect_mask = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT; aspect_string = "depth/stencil"; } else if (resolve_depth) { // Validate depth only aspect_mask = VK_IMAGE_ASPECT_DEPTH_BIT; aspect_string = "depth"; } else if (resolve_stencil) { // Validate all stencil only aspect_mask = VK_IMAGE_ASPECT_STENCIL_BIT; aspect_string = "stencil"; } if (aspect_mask) { action(aspect_string, "resolve read", src_at, dst_at, attachment_views[src_at], SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ, kDepthStencilAttachmentRasterOrder, offset, extent, aspect_mask); action(aspect_string, "resolve write", src_at, dst_at, attachment_views[dst_at], SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, kAttachmentRasterOrder, offset, extent, aspect_mask); } } } // Action for validating resolve operations class ValidateResolveAction { public: ValidateResolveAction(VkRenderPass render_pass, uint32_t subpass, const AccessContext &context, const SyncValidator &sync_state, const char *func_name) : render_pass_(render_pass), subpass_(subpass), context_(context), sync_state_(sync_state), func_name_(func_name), skip_(false) {} void operator()(const char *aspect_name, const char *attachment_name, uint32_t src_at, uint32_t dst_at, const IMAGE_VIEW_STATE *view, SyncStageAccessIndex current_usage, const SyncOrderingBarrier &ordering, const VkOffset3D &offset, const VkExtent3D &extent, VkImageAspectFlags aspect_mask) { HazardResult hazard; hazard = context_.DetectHazard(view, current_usage, ordering, offset, extent, aspect_mask); if (hazard.hazard) { skip_ |= sync_state_.LogError(render_pass_, string_SyncHazardVUID(hazard.hazard), "%s: Hazard %s in subpass %" PRIu32 "during %s %s, from attachment %" PRIu32 " to resolve attachment %" PRIu32 ". Access info %s.", func_name_, string_SyncHazard(hazard.hazard), subpass_, aspect_name, attachment_name, src_at, dst_at, string_UsageTag(hazard).c_str()); } } // Providing a mechanism for the constructing caller to get the result of the validation bool GetSkip() const { return skip_; } private: VkRenderPass render_pass_; const uint32_t subpass_; const AccessContext &context_; const SyncValidator &sync_state_; const char *func_name_; bool skip_; }; // Update action for resolve operations class UpdateStateResolveAction { public: UpdateStateResolveAction(AccessContext &context, const ResourceUsageTag &tag) : context_(context), tag_(tag) {} void operator()(const char *aspect_name, const char *attachment_name, uint32_t src_at, uint32_t dst_at, const IMAGE_VIEW_STATE *view, SyncStageAccessIndex current_usage, const SyncOrderingBarrier &ordering, const VkOffset3D &offset, const VkExtent3D &extent, VkImageAspectFlags aspect_mask) { // Ignores validation only arguments... context_.UpdateAccessState(view, current_usage, offset, extent, aspect_mask, tag_); } private: AccessContext &context_; const ResourceUsageTag &tag_; }; void HazardResult::Set(const ResourceAccessState *access_state_, SyncStageAccessIndex usage_index_, SyncHazard hazard_, const SyncStageAccessFlags &prior_, const ResourceUsageTag &tag_) { access_state = std::unique_ptr<const ResourceAccessState>(new ResourceAccessState(*access_state_)); usage_index = usage_index_; hazard = hazard_; prior_access = prior_; tag = tag_; } AccessContext::AccessContext(uint32_t subpass, VkQueueFlags queue_flags, const std::vector<SubpassDependencyGraphNode> &dependencies, const std::vector<AccessContext> &contexts, const AccessContext *external_context) { Reset(); const auto &subpass_dep = dependencies[subpass]; prev_.reserve(subpass_dep.prev.size()); prev_by_subpass_.resize(subpass, nullptr); // Can't be more prevs than the subpass we're on for (const auto &prev_dep : subpass_dep.prev) { const auto prev_pass = prev_dep.first->pass; const auto &prev_barriers = prev_dep.second; assert(prev_dep.second.size()); prev_.emplace_back(&contexts[prev_pass], queue_flags, prev_barriers); prev_by_subpass_[prev_pass] = &prev_.back(); } async_.reserve(subpass_dep.async.size()); for (const auto async_subpass : subpass_dep.async) { // TODO -- review why async is storing non-const async_.emplace_back(const_cast<AccessContext *>(&contexts[async_subpass])); } if (subpass_dep.barrier_from_external.size()) { src_external_ = TrackBack(external_context, queue_flags, subpass_dep.barrier_from_external); } if (subpass_dep.barrier_to_external.size()) { dst_external_ = TrackBack(this, queue_flags, subpass_dep.barrier_to_external); } } template <typename Detector> HazardResult AccessContext::DetectPreviousHazard(AddressType type, const Detector &detector, const ResourceAccessRange &range) const { ResourceAccessRangeMap descent_map; ResolvePreviousAccess(type, range, &descent_map, nullptr); HazardResult hazard; for (auto prev = descent_map.begin(); prev != descent_map.end() && !hazard.hazard; ++prev) { hazard = detector.Detect(prev); } return hazard; } // A recursive range walker for hazard detection, first for the current context and the (DetectHazardRecur) to walk // the DAG of the contexts (for example subpasses) template <typename Detector> HazardResult AccessContext::DetectHazard(AddressType type, const Detector &detector, const ResourceAccessRange &range, DetectOptions options) const { HazardResult hazard; if (static_cast<uint32_t>(options) & DetectOptions::kDetectAsync) { // Async checks don't require recursive lookups, as the async lists are exhaustive for the top-level context // so we'll check these first for (const auto &async_context : async_) { hazard = async_context->DetectAsyncHazard(type, detector, range); if (hazard.hazard) return hazard; } } const bool detect_prev = (static_cast<uint32_t>(options) & DetectOptions::kDetectPrevious) != 0; const auto &accesses = GetAccessStateMap(type); const auto from = accesses.lower_bound(range); const auto to = accesses.upper_bound(range); ResourceAccessRange gap = {range.begin, range.begin}; for (auto pos = from; pos != to; ++pos) { // Cover any leading gap, or gap between entries if (detect_prev) { // TODO: After profiling we may want to change the descent logic such that we don't recur per gap... // Cover any leading gap, or gap between entries gap.end = pos->first.begin; // We know this begin is < range.end if (gap.non_empty()) { // Recur on all gaps hazard = DetectPreviousHazard(type, detector, gap); if (hazard.hazard) return hazard; } // Set up for the next gap. If pos..end is >= range.end, loop will exit, and trailing gap will be empty gap.begin = pos->first.end; } hazard = detector.Detect(pos); if (hazard.hazard) return hazard; } if (detect_prev) { // Detect in the trailing empty as needed gap.end = range.end; if (gap.non_empty()) { hazard = DetectPreviousHazard(type, detector, gap); } } return hazard; } // A non recursive range walker for the asynchronous contexts (those we have no barriers with) template <typename Detector> HazardResult AccessContext::DetectAsyncHazard(AddressType type, const Detector &detector, const ResourceAccessRange &range) const { auto &accesses = GetAccessStateMap(type); const auto from = accesses.lower_bound(range); const auto to = accesses.upper_bound(range); HazardResult hazard; for (auto pos = from; pos != to && !hazard.hazard; ++pos) { hazard = detector.DetectAsync(pos); } return hazard; } struct ApplySubpassTransitionBarriersAction { ApplySubpassTransitionBarriersAction(const std::vector<SyncBarrier> &barriers_) : barriers(barriers_) {} void operator()(ResourceAccessState *access) const { assert(access); access->ApplyBarriers(barriers, true); } const std::vector<SyncBarrier> &barriers; }; struct ApplyTrackbackBarriersAction { ApplyTrackbackBarriersAction(const std::vector<SyncBarrier> &barriers_) : barriers(barriers_) {} void operator()(ResourceAccessState *access) const { assert(access); assert(!access->HasPendingState()); access->ApplyBarriers(barriers, false); access->ApplyPendingBarriers(kCurrentCommandTag); } const std::vector<SyncBarrier> &barriers; }; // Splits a single map entry into piece matching the entries in [first, last) the total range over [first, last) must be // contained with entry. Entry must be an iterator pointing to dest, first and last must be iterators pointing to a // *different* map from dest. // Returns the position past the last resolved range -- the entry covering the remainder of entry->first not included in the // range [first, last) template <typename BarrierAction> static void ResolveMapToEntry(ResourceAccessRangeMap *dest, ResourceAccessRangeMap::iterator entry, ResourceAccessRangeMap::const_iterator first, ResourceAccessRangeMap::const_iterator last, BarrierAction &barrier_action) { auto at = entry; for (auto pos = first; pos != last; ++pos) { // Every member of the input iterator range must fit within the remaining portion of entry assert(at->first.includes(pos->first)); assert(at != dest->end()); // Trim up at to the same size as the entry to resolve at = sparse_container::split(at, *dest, pos->first); auto access = pos->second; // intentional copy barrier_action(&access); at->second.Resolve(access); ++at; // Go to the remaining unused section of entry } } static SyncBarrier MergeBarriers(const std::vector<SyncBarrier> &barriers) { SyncBarrier merged = {}; for (const auto &barrier : barriers) { merged.Merge(barrier); } return merged; } template <typename BarrierAction> void AccessContext::ResolveAccessRange(AddressType type, const ResourceAccessRange &range, BarrierAction &barrier_action, ResourceAccessRangeMap *resolve_map, const ResourceAccessState *infill_state, bool recur_to_infill) const { if (!range.non_empty()) return; ResourceRangeMergeIterator current(*resolve_map, GetAccessStateMap(type), range.begin); while (current->range.non_empty() && range.includes(current->range.begin)) { const auto current_range = current->range & range; if (current->pos_B->valid) { const auto &src_pos = current->pos_B->lower_bound; auto access = src_pos->second; // intentional copy barrier_action(&access); if (current->pos_A->valid) { const auto trimmed = sparse_container::split(current->pos_A->lower_bound, *resolve_map, current_range); trimmed->second.Resolve(access); current.invalidate_A(trimmed); } else { auto inserted = resolve_map->insert(current->pos_A->lower_bound, std::make_pair(current_range, access)); current.invalidate_A(inserted); // Update the parallel iterator to point at the insert segment } } else { // we have to descend to fill this gap if (recur_to_infill) { if (current->pos_A->valid) { // Dest is valid, so we need to accumulate along the DAG and then resolve... in an N-to-1 resolve operation ResourceAccessRangeMap gap_map; ResolvePreviousAccess(type, current_range, &gap_map, infill_state); ResolveMapToEntry(resolve_map, current->pos_A->lower_bound, gap_map.begin(), gap_map.end(), barrier_action); } else { // There isn't anything in dest in current)range, so we can accumulate directly into it. ResolvePreviousAccess(type, current_range, resolve_map, infill_state); // Need to apply the barrier to the accesses we accumulated, noting that we haven't updated current for (auto pos = resolve_map->lower_bound(current_range); pos != current->pos_A->lower_bound; ++pos) { barrier_action(&pos->second); } } // Given that there could be gaps we need to seek carefully to not repeatedly search the same gaps in the next // iterator of the outer while. // Set the parallel iterator to the end of this range s.t. ++ will move us to the next range whether or // not the end of the range is a gap. For the seek to work, first we need to warn the parallel iterator // we stepped on the dest map const auto seek_to = current_range.end - 1; // The subtraction is safe as range can't be empty (loop condition) current.invalidate_A(); // Changes current->range current.seek(seek_to); } else if (!current->pos_A->valid && infill_state) { // If we didn't find anything in the current range, and we aren't reccuring... we infill if required auto inserted = resolve_map->insert(current->pos_A->lower_bound, std::make_pair(current->range, *infill_state)); current.invalidate_A(inserted); // Update the parallel iterator to point at the correct segment after insert } } ++current; } // Infill if range goes passed both the current and resolve map prior contents if (recur_to_infill && (current->range.end < range.end)) { ResourceAccessRange trailing_fill_range = {current->range.end, range.end}; ResourceAccessRangeMap gap_map; const auto the_end = resolve_map->end(); ResolvePreviousAccess(type, trailing_fill_range, &gap_map, infill_state); for (auto &access : gap_map) { barrier_action(&access.second); resolve_map->insert(the_end, access); } } } void AccessContext::ResolvePreviousAccess(AddressType type, const ResourceAccessRange &range, ResourceAccessRangeMap *descent_map, const ResourceAccessState *infill_state) const { if ((prev_.size() == 0) && (src_external_.context == nullptr)) { if (range.non_empty() && infill_state) { descent_map->insert(std::make_pair(range, *infill_state)); } } else { // Look for something to fill the gap further along. for (const auto &prev_dep : prev_) { const ApplyTrackbackBarriersAction barrier_action(prev_dep.barriers); prev_dep.context->ResolveAccessRange(type, range, barrier_action, descent_map, infill_state); } if (src_external_.context) { const ApplyTrackbackBarriersAction barrier_action(src_external_.barriers); src_external_.context->ResolveAccessRange(type, range, barrier_action, descent_map, infill_state); } } } AccessContext::AddressType AccessContext::ImageAddressType(const IMAGE_STATE &image) { return (image.fragment_encoder->IsLinearImage()) ? AddressType::kLinearAddress : AddressType::kIdealizedAddress; } static SyncStageAccessIndex ColorLoadUsage(VkAttachmentLoadOp load_op) { const auto stage_access = (load_op == VK_ATTACHMENT_LOAD_OP_LOAD) ? SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ : SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE; return stage_access; } static SyncStageAccessIndex DepthStencilLoadUsage(VkAttachmentLoadOp load_op) { const auto stage_access = (load_op == VK_ATTACHMENT_LOAD_OP_LOAD) ? SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_READ : SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE; return stage_access; } // Caller must manage returned pointer static AccessContext *CreateStoreResolveProxyContext(const AccessContext &context, const RENDER_PASS_STATE &rp_state, uint32_t subpass, const VkRect2D &render_area, std::vector<const IMAGE_VIEW_STATE *> attachment_views) { auto *proxy = new AccessContext(context); proxy->UpdateAttachmentResolveAccess(rp_state, render_area, attachment_views, subpass, kCurrentCommandTag); proxy->UpdateAttachmentStoreAccess(rp_state, render_area, attachment_views, subpass, kCurrentCommandTag); return proxy; } template <typename BarrierAction> class ResolveAccessRangeFunctor { public: ResolveAccessRangeFunctor(const AccessContext &context, AccessContext::AddressType address_type, ResourceAccessRangeMap *descent_map, const ResourceAccessState *infill_state, BarrierAction &barrier_action) : context_(context), address_type_(address_type), descent_map_(descent_map), infill_state_(infill_state), barrier_action_(barrier_action) {} ResolveAccessRangeFunctor() = delete; void operator()(const ResourceAccessRange &range) const { context_.ResolveAccessRange(address_type_, range, barrier_action_, descent_map_, infill_state_); } private: const AccessContext &context_; const AccessContext::AddressType address_type_; ResourceAccessRangeMap *const descent_map_; const ResourceAccessState *infill_state_; BarrierAction &barrier_action_; }; template <typename BarrierAction> void AccessContext::ResolveAccessRange(const IMAGE_STATE &image_state, const VkImageSubresourceRange &subresource_range, BarrierAction &barrier_action, AddressType address_type, ResourceAccessRangeMap *descent_map, const ResourceAccessState *infill_state) const { const ResolveAccessRangeFunctor<BarrierAction> action(*this, address_type, descent_map, infill_state, barrier_action); ApplyOverImageRange(image_state, subresource_range, action); } // Layout transitions are handled as if the were occuring in the beginning of the next subpass bool AccessContext::ValidateLayoutTransitions(const SyncValidator &sync_state, const RENDER_PASS_STATE &rp_state, const VkRect2D &render_area, uint32_t subpass, const std::vector<const IMAGE_VIEW_STATE *> &attachment_views, const char *func_name) const { bool skip = false; // As validation methods are const and precede the record/update phase, for any tranistions from the immediately // previous subpass, we have to validate them against a copy of the AccessContext, with resolve operations applied, as // those affects have not been recorded yet. // // Note: we could be more efficient by tracking whether or not we actually *have* any changes (e.g. attachment resolve) // to apply and only copy then, if this proves a hot spot. std::unique_ptr<AccessContext> proxy_for_prev; TrackBack proxy_track_back; const auto &transitions = rp_state.subpass_transitions[subpass]; for (const auto &transition : transitions) { const bool prev_needs_proxy = transition.prev_pass != VK_SUBPASS_EXTERNAL && (transition.prev_pass + 1 == subpass); const auto *track_back = GetTrackBackFromSubpass(transition.prev_pass); if (prev_needs_proxy) { if (!proxy_for_prev) { proxy_for_prev.reset(CreateStoreResolveProxyContext(*track_back->context, rp_state, transition.prev_pass, render_area, attachment_views)); proxy_track_back = *track_back; proxy_track_back.context = proxy_for_prev.get(); } track_back = &proxy_track_back; } auto hazard = DetectSubpassTransitionHazard(*track_back, attachment_views[transition.attachment]); if (hazard.hazard) { skip |= sync_state.LogError(rp_state.renderPass, string_SyncHazardVUID(hazard.hazard), "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32 " image layout transition (old_layout: %s, new_layout: %s). Access info %s.", func_name, string_SyncHazard(hazard.hazard), subpass, transition.attachment, string_VkImageLayout(transition.old_layout), string_VkImageLayout(transition.new_layout), string_UsageTag(hazard).c_str()); } } return skip; } bool AccessContext::ValidateLoadOperation(const SyncValidator &sync_state, const RENDER_PASS_STATE &rp_state, const VkRect2D &render_area, uint32_t subpass, const std::vector<const IMAGE_VIEW_STATE *> &attachment_views, const char *func_name) const { bool skip = false; const auto *attachment_ci = rp_state.createInfo.pAttachments; VkExtent3D extent = CastTo3D(render_area.extent); VkOffset3D offset = CastTo3D(render_area.offset); for (uint32_t i = 0; i < rp_state.createInfo.attachmentCount; i++) { if (subpass == rp_state.attachment_first_subpass[i]) { if (attachment_views[i] == nullptr) continue; const IMAGE_VIEW_STATE &view = *attachment_views[i]; const IMAGE_STATE *image = view.image_state.get(); if (image == nullptr) continue; const auto &ci = attachment_ci[i]; // Need check in the following way // 1) if the usage bit isn't in the dest_access_scope, and there is layout traniition for initial use, report hazard // vs. transition // 2) if there isn't a layout transition, we need to look at the external context with a "detect hazard" operation // for each aspect loaded. const bool has_depth = FormatHasDepth(ci.format); const bool has_stencil = FormatHasStencil(ci.format); const bool is_color = !(has_depth || has_stencil); const SyncStageAccessIndex load_index = has_depth ? DepthStencilLoadUsage(ci.loadOp) : ColorLoadUsage(ci.loadOp); const SyncStageAccessIndex stencil_load_index = has_stencil ? DepthStencilLoadUsage(ci.stencilLoadOp) : load_index; HazardResult hazard; const char *aspect = nullptr; auto hazard_range = view.normalized_subresource_range; bool checked_stencil = false; if (is_color) { hazard = DetectHazard(*image, load_index, view.normalized_subresource_range, kColorAttachmentRasterOrder, offset, extent); aspect = "color"; } else { if (has_depth) { hazard_range.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT; hazard = DetectHazard(*image, load_index, hazard_range, kDepthStencilAttachmentRasterOrder, offset, extent); aspect = "depth"; } if (!hazard.hazard && has_stencil) { hazard_range.aspectMask = VK_IMAGE_ASPECT_STENCIL_BIT; hazard = DetectHazard(*image, stencil_load_index, hazard_range, kDepthStencilAttachmentRasterOrder, offset, extent); aspect = "stencil"; checked_stencil = true; } } if (hazard.hazard) { auto load_op_string = string_VkAttachmentLoadOp(checked_stencil ? ci.stencilLoadOp : ci.loadOp); if (hazard.tag == kCurrentCommandTag) { // Hazard vs. ILT skip |= sync_state.LogError(rp_state.renderPass, string_SyncHazardVUID(hazard.hazard), "%s: Hazard %s vs. layout transition in subpass %" PRIu32 " for attachment %" PRIu32 " aspect %s during load with loadOp %s.", func_name, string_SyncHazard(hazard.hazard), subpass, i, aspect, load_op_string); } else { skip |= sync_state.LogError(rp_state.renderPass, string_SyncHazardVUID(hazard.hazard), "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32 " aspect %s during load with loadOp %s. Access info %s.", func_name, string_SyncHazard(hazard.hazard), subpass, i, aspect, load_op_string, string_UsageTag(hazard).c_str()); } } } } return skip; } // Store operation validation can ignore resolve (before it) and layout tranistions after it. The first is ignored // because of the ordering guarantees w.r.t. sample access and that the resolve validation hasn't altered the state, because // store is part of the same Next/End operation. // The latter is handled in layout transistion validation directly bool AccessContext::ValidateStoreOperation(const SyncValidator &sync_state, const RENDER_PASS_STATE &rp_state, const VkRect2D &render_area, uint32_t subpass, const std::vector<const IMAGE_VIEW_STATE *> &attachment_views, const char *func_name) const { bool skip = false; const auto *attachment_ci = rp_state.createInfo.pAttachments; VkExtent3D extent = CastTo3D(render_area.extent); VkOffset3D offset = CastTo3D(render_area.offset); for (uint32_t i = 0; i < rp_state.createInfo.attachmentCount; i++) { if (subpass == rp_state.attachment_last_subpass[i]) { if (attachment_views[i] == nullptr) continue; const IMAGE_VIEW_STATE &view = *attachment_views[i]; const IMAGE_STATE *image = view.image_state.get(); if (image == nullptr) continue; const auto &ci = attachment_ci[i]; // The spec states that "don't care" is an operation with VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, // so we assume that an implementation is *free* to write in that case, meaning that for correctness // sake, we treat DONT_CARE as writing. const bool has_depth = FormatHasDepth(ci.format); const bool has_stencil = FormatHasStencil(ci.format); const bool is_color = !(has_depth || has_stencil); const bool store_op_stores = ci.storeOp != VK_ATTACHMENT_STORE_OP_NONE_QCOM; if (!has_stencil && !store_op_stores) continue; HazardResult hazard; const char *aspect = nullptr; bool checked_stencil = false; if (is_color) { hazard = DetectHazard(*image, SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, view.normalized_subresource_range, kAttachmentRasterOrder, offset, extent); aspect = "color"; } else { const bool stencil_op_stores = ci.stencilStoreOp != VK_ATTACHMENT_STORE_OP_NONE_QCOM; auto hazard_range = view.normalized_subresource_range; if (has_depth && store_op_stores) { hazard_range.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT; hazard = DetectHazard(*image, SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, hazard_range, kAttachmentRasterOrder, offset, extent); aspect = "depth"; } if (!hazard.hazard && has_stencil && stencil_op_stores) { hazard_range.aspectMask = VK_IMAGE_ASPECT_STENCIL_BIT; hazard = DetectHazard(*image, SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, hazard_range, kAttachmentRasterOrder, offset, extent); aspect = "stencil"; checked_stencil = true; } } if (hazard.hazard) { const char *const op_type_string = checked_stencil ? "stencilStoreOp" : "storeOp"; const char *const store_op_string = string_VkAttachmentStoreOp(checked_stencil ? ci.stencilStoreOp : ci.storeOp); skip |= sync_state.LogError(rp_state.renderPass, string_SyncHazardVUID(hazard.hazard), "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32 " %s aspect during store with %s %s. Access info %s", func_name, string_SyncHazard(hazard.hazard), subpass, i, aspect, op_type_string, store_op_string, string_UsageTag(hazard).c_str()); } } } return skip; } bool AccessContext::ValidateResolveOperations(const SyncValidator &sync_state, const RENDER_PASS_STATE &rp_state, const VkRect2D &render_area, const std::vector<const IMAGE_VIEW_STATE *> &attachment_views, const char *func_name, uint32_t subpass) const { ValidateResolveAction validate_action(rp_state.renderPass, subpass, *this, sync_state, func_name); ResolveOperation(validate_action, rp_state, render_area, attachment_views, subpass); return validate_action.GetSkip(); } class HazardDetector { SyncStageAccessIndex usage_index_; public: HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const { return pos->second.DetectHazard(usage_index_); } HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos) const { return pos->second.DetectAsyncHazard(usage_index_); } HazardDetector(SyncStageAccessIndex usage) : usage_index_(usage) {} }; class HazardDetectorWithOrdering { const SyncStageAccessIndex usage_index_; const SyncOrderingBarrier &ordering_; public: HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const { return pos->second.DetectHazard(usage_index_, ordering_); } HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos) const { return pos->second.DetectAsyncHazard(usage_index_); } HazardDetectorWithOrdering(SyncStageAccessIndex usage, const SyncOrderingBarrier &ordering) : usage_index_(usage), ordering_(ordering) {} }; HazardResult AccessContext::DetectHazard(AddressType type, SyncStageAccessIndex usage_index, const ResourceAccessRange &range) const { HazardDetector detector(usage_index); return DetectHazard(type, detector, range, DetectOptions::kDetectAll); } HazardResult AccessContext::DetectHazard(const BUFFER_STATE &buffer, SyncStageAccessIndex usage_index, const ResourceAccessRange &range) const { if (!SimpleBinding(buffer)) return HazardResult(); return DetectHazard(AddressType::kLinearAddress, usage_index, range + ResourceBaseAddress(buffer)); } template <typename Detector> HazardResult AccessContext::DetectHazard(Detector &detector, const IMAGE_STATE &image, const VkImageSubresourceRange &subresource_range, const VkOffset3D &offset, const VkExtent3D &extent, DetectOptions options) const { if (!SimpleBinding(image)) return HazardResult(); subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, offset, extent); const auto address_type = ImageAddressType(image); const auto base_address = ResourceBaseAddress(image); for (; range_gen->non_empty(); ++range_gen) { HazardResult hazard = DetectHazard(address_type, detector, (*range_gen + base_address), options); if (hazard.hazard) return hazard; } return HazardResult(); } HazardResult AccessContext::DetectHazard(const IMAGE_STATE &image, SyncStageAccessIndex current_usage, const VkImageSubresourceLayers &subresource, const VkOffset3D &offset, const VkExtent3D &extent) const { VkImageSubresourceRange subresource_range = {subresource.aspectMask, subresource.mipLevel, 1, subresource.baseArrayLayer, subresource.layerCount}; return DetectHazard(image, current_usage, subresource_range, offset, extent); } HazardResult AccessContext::DetectHazard(const IMAGE_STATE &image, SyncStageAccessIndex current_usage, const VkImageSubresourceRange &subresource_range, const VkOffset3D &offset, const VkExtent3D &extent) const { HazardDetector detector(current_usage); return DetectHazard(detector, image, subresource_range, offset, extent, DetectOptions::kDetectAll); } HazardResult AccessContext::DetectHazard(const IMAGE_STATE &image, SyncStageAccessIndex current_usage, const VkImageSubresourceRange &subresource_range, const SyncOrderingBarrier &ordering, const VkOffset3D &offset, const VkExtent3D &extent) const { HazardDetectorWithOrdering detector(current_usage, ordering); return DetectHazard(detector, image, subresource_range, offset, extent, DetectOptions::kDetectAll); } // Some common code for looking at attachments, if there's anything wrong, we return no hazard, core validation // should have reported the issue regarding an invalid attachment entry HazardResult AccessContext::DetectHazard(const IMAGE_VIEW_STATE *view, SyncStageAccessIndex current_usage, const SyncOrderingBarrier &ordering, const VkOffset3D &offset, const VkExtent3D &extent, VkImageAspectFlags aspect_mask) const { if (view != nullptr) { const IMAGE_STATE *image = view->image_state.get(); if (image != nullptr) { auto *detect_range = &view->normalized_subresource_range; VkImageSubresourceRange masked_range; if (aspect_mask) { // If present and non-zero, restrict the normalized range to aspects present in aspect_mask masked_range = view->normalized_subresource_range; masked_range.aspectMask = aspect_mask & masked_range.aspectMask; detect_range = &masked_range; } // NOTE: The range encoding code is not robust to invalid ranges, so we protect it from our change if (detect_range->aspectMask) { return DetectHazard(*image, current_usage, *detect_range, ordering, offset, extent); } } } return HazardResult(); } class BarrierHazardDetector { public: BarrierHazardDetector(SyncStageAccessIndex usage_index, VkPipelineStageFlags src_exec_scope, SyncStageAccessFlags src_access_scope) : usage_index_(usage_index), src_exec_scope_(src_exec_scope), src_access_scope_(src_access_scope) {} HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const { return pos->second.DetectBarrierHazard(usage_index_, src_exec_scope_, src_access_scope_); } HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos) const { // Async barrier hazard detection can use the same path as the usage index is not IsRead, but is IsWrite return pos->second.DetectAsyncHazard(usage_index_); } private: SyncStageAccessIndex usage_index_; VkPipelineStageFlags src_exec_scope_; SyncStageAccessFlags src_access_scope_; }; HazardResult AccessContext::DetectBarrierHazard(AddressType type, SyncStageAccessIndex current_usage, VkPipelineStageFlags src_exec_scope, const SyncStageAccessFlags &src_access_scope, const ResourceAccessRange &range, DetectOptions options) const { BarrierHazardDetector detector(current_usage, src_exec_scope, src_access_scope); return DetectHazard(type, detector, range, options); } HazardResult AccessContext::DetectImageBarrierHazard(const IMAGE_STATE &image, VkPipelineStageFlags src_exec_scope, const SyncStageAccessFlags &src_access_scope, const VkImageSubresourceRange &subresource_range, DetectOptions options) const { BarrierHazardDetector detector(SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION, src_exec_scope, src_access_scope); VkOffset3D zero_offset = {0, 0, 0}; return DetectHazard(detector, image, subresource_range, zero_offset, image.createInfo.extent, options); } HazardResult AccessContext::DetectImageBarrierHazard(const IMAGE_STATE &image, VkPipelineStageFlags src_exec_scope, const SyncStageAccessFlags &src_stage_accesses, const VkImageMemoryBarrier &barrier) const { auto subresource_range = NormalizeSubresourceRange(image.createInfo, barrier.subresourceRange); const auto src_access_scope = SyncStageAccess::AccessScope(src_stage_accesses, barrier.srcAccessMask); return DetectImageBarrierHazard(image, src_exec_scope, src_access_scope, subresource_range, kDetectAll); } template <typename Flags, typename Map> SyncStageAccessFlags AccessScopeImpl(Flags flag_mask, const Map &map) { SyncStageAccessFlags scope = 0; for (const auto &bit_scope : map) { if (flag_mask < bit_scope.first) break; if (flag_mask & bit_scope.first) { scope |= bit_scope.second; } } return scope; } SyncStageAccessFlags SyncStageAccess::AccessScopeByStage(VkPipelineStageFlags stages) { return AccessScopeImpl(stages, syncStageAccessMaskByStageBit); } SyncStageAccessFlags SyncStageAccess::AccessScopeByAccess(VkAccessFlags accesses) { return AccessScopeImpl(accesses, syncStageAccessMaskByAccessBit); } // Getting from stage mask and access mask to stage/acess masks is something we need to be good at... SyncStageAccessFlags SyncStageAccess::AccessScope(VkPipelineStageFlags stages, VkAccessFlags accesses) { // The access scope is the intersection of all stage/access types possible for the enabled stages and the enables // accesses (after doing a couple factoring of common terms the union of stage/access intersections is the intersections // of the union of all stage/access types for all the stages and the same unions for the access mask... return AccessScopeByStage(stages) & AccessScopeByAccess(accesses); } template <typename Action> void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const ResourceAccessRange &range, const Action &action) { // TODO: Optimization for operations that do a pure overwrite (i.e. WRITE usages which rewrite the state, vs READ usages // that do incrementalupdates auto pos = accesses->lower_bound(range); if (pos == accesses->end() || !pos->first.intersects(range)) { // The range is empty, fill it with a default value. pos = action.Infill(accesses, pos, range); } else if (range.begin < pos->first.begin) { // Leading empty space, infill pos = action.Infill(accesses, pos, ResourceAccessRange(range.begin, pos->first.begin)); } else if (pos->first.begin < range.begin) { // Trim the beginning if needed pos = accesses->split(pos, range.begin, sparse_container::split_op_keep_both()); ++pos; } const auto the_end = accesses->end(); while ((pos != the_end) && pos->first.intersects(range)) { if (pos->first.end > range.end) { pos = accesses->split(pos, range.end, sparse_container::split_op_keep_both()); } pos = action(accesses, pos); if (pos == the_end) break; auto next = pos; ++next; if ((pos->first.end < range.end) && (next != the_end) && !next->first.is_subsequent_to(pos->first)) { // Need to infill if next is disjoint VkDeviceSize limit = (next == the_end) ? range.end : std::min(range.end, next->first.begin); ResourceAccessRange new_range(pos->first.end, limit); next = action.Infill(accesses, next, new_range); } pos = next; } } struct UpdateMemoryAccessStateFunctor { using Iterator = ResourceAccessRangeMap::iterator; Iterator Infill(ResourceAccessRangeMap *accesses, Iterator pos, ResourceAccessRange range) const { // this is only called on gaps, and never returns a gap. ResourceAccessState default_state; context.ResolvePreviousAccess(type, range, accesses, &default_state); return accesses->lower_bound(range); } Iterator operator()(ResourceAccessRangeMap *accesses, Iterator pos) const { auto &access_state = pos->second; access_state.Update(usage, tag); return pos; } UpdateMemoryAccessStateFunctor(AccessContext::AddressType type_, const AccessContext &context_, SyncStageAccessIndex usage_, const ResourceUsageTag &tag_) : type(type_), context(context_), usage(usage_), tag(tag_) {} const AccessContext::AddressType type; const AccessContext &context; const SyncStageAccessIndex usage; const ResourceUsageTag &tag; }; // This functor applies a single barrier, updating the "pending state" in each touched memory range, but does not // resolve the pendinging state. Suitable for processing Image and Buffer barriers from PipelineBarriers or Events class ApplyBarrierFunctor { public: using Iterator = ResourceAccessRangeMap::iterator; inline Iterator Infill(ResourceAccessRangeMap *accesses, Iterator pos, ResourceAccessRange range) const { return pos; } Iterator operator()(ResourceAccessRangeMap *accesses, Iterator pos) const { auto &access_state = pos->second; access_state.ApplyBarrier(barrier_, layout_transition_); return pos; } ApplyBarrierFunctor(const SyncBarrier &barrier, bool layout_transition) : barrier_(barrier), layout_transition_(layout_transition) {} private: const SyncBarrier barrier_; const bool layout_transition_; }; // This functor applies a collection of barriers, updating the "pending state" in each touched memory range, and optionally // resolves the pending state. Suitable for processing Global memory barriers, or Subpass Barriers when the "final" barrier // of a collection is known/present. class ApplyBarrierOpsFunctor { public: using Iterator = ResourceAccessRangeMap::iterator; inline Iterator Infill(ResourceAccessRangeMap *accesses, Iterator pos, ResourceAccessRange range) const { return pos; } struct BarrierOp { SyncBarrier barrier; bool layout_transition; BarrierOp(const SyncBarrier &barrier_, bool layout_transition_) : barrier(barrier_), layout_transition(layout_transition_) {} BarrierOp() = default; }; Iterator operator()(ResourceAccessRangeMap *accesses, Iterator pos) const { auto &access_state = pos->second; for (const auto op : barrier_ops_) { access_state.ApplyBarrier(op.barrier, op.layout_transition); } if (resolve_) { // If this is the last (or only) batch, we can do the pending resolve as the last step in this operation to avoid // another walk access_state.ApplyPendingBarriers(tag_); } return pos; } // A valid tag is required IFF any of the barriers ops are a layout transition, as transitions are write ops ApplyBarrierOpsFunctor(bool resolve, size_t size_hint, const ResourceUsageTag &tag) : resolve_(resolve), barrier_ops_(), tag_(tag) { if (size_hint) { barrier_ops_.reserve(size_hint); } }; // A valid tag is required IFF layout_transition is true, as transitions are write ops ApplyBarrierOpsFunctor(bool resolve, const std::vector<SyncBarrier> &barriers, bool layout_transition, const ResourceUsageTag &tag) : resolve_(resolve), barrier_ops_(), tag_(tag) { barrier_ops_.reserve(barriers.size()); for (const auto &barrier : barriers) { barrier_ops_.emplace_back(barrier, layout_transition); } } void PushBack(const SyncBarrier &barrier, bool layout_transition) { barrier_ops_.emplace_back(barrier, layout_transition); } void PushBack(const std::vector<SyncBarrier> &barriers, bool layout_transition) { barrier_ops_.reserve(barrier_ops_.size() + barriers.size()); for (const auto &barrier : barriers) { barrier_ops_.emplace_back(barrier, layout_transition); } } private: bool resolve_; std::vector<BarrierOp> barrier_ops_; const ResourceUsageTag &tag_; }; void AccessContext::UpdateAccessState(AddressType type, SyncStageAccessIndex current_usage, const ResourceAccessRange &range, const ResourceUsageTag &tag) { UpdateMemoryAccessStateFunctor action(type, *this, current_usage, tag); UpdateMemoryAccessState(&GetAccessStateMap(type), range, action); } void AccessContext::UpdateAccessState(const BUFFER_STATE &buffer, SyncStageAccessIndex current_usage, const ResourceAccessRange &range, const ResourceUsageTag &tag) { if (!SimpleBinding(buffer)) return; const auto base_address = ResourceBaseAddress(buffer); UpdateAccessState(AddressType::kLinearAddress, current_usage, range + base_address, tag); } void AccessContext::UpdateAccessState(const IMAGE_STATE &image, SyncStageAccessIndex current_usage, const VkImageSubresourceRange &subresource_range, const VkOffset3D &offset, const VkExtent3D &extent, const ResourceUsageTag &tag) { if (!SimpleBinding(image)) return; subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, offset, extent); const auto address_type = ImageAddressType(image); const auto base_address = ResourceBaseAddress(image); UpdateMemoryAccessStateFunctor action(address_type, *this, current_usage, tag); for (; range_gen->non_empty(); ++range_gen) { UpdateMemoryAccessState(&GetAccessStateMap(address_type), (*range_gen + base_address), action); } } void AccessContext::UpdateAccessState(const IMAGE_VIEW_STATE *view, SyncStageAccessIndex current_usage, const VkOffset3D &offset, const VkExtent3D &extent, VkImageAspectFlags aspect_mask, const ResourceUsageTag &tag) { if (view != nullptr) { const IMAGE_STATE *image = view->image_state.get(); if (image != nullptr) { auto *update_range = &view->normalized_subresource_range; VkImageSubresourceRange masked_range; if (aspect_mask) { // If present and non-zero, restrict the normalized range to aspects present in aspect_mask masked_range = view->normalized_subresource_range; masked_range.aspectMask = aspect_mask & masked_range.aspectMask; update_range = &masked_range; } UpdateAccessState(*image, current_usage, *update_range, offset, extent, tag); } } } void AccessContext::UpdateAccessState(const IMAGE_STATE &image, SyncStageAccessIndex current_usage, const VkImageSubresourceLayers &subresource, const VkOffset3D &offset, const VkExtent3D &extent, const ResourceUsageTag &tag) { VkImageSubresourceRange subresource_range = {subresource.aspectMask, subresource.mipLevel, 1, subresource.baseArrayLayer, subresource.layerCount}; UpdateAccessState(image, current_usage, subresource_range, offset, extent, tag); } template <typename Action> void AccessContext::UpdateResourceAccess(const BUFFER_STATE &buffer, const ResourceAccessRange &range, const Action action) { if (!SimpleBinding(buffer)) return; const auto base_address = ResourceBaseAddress(buffer); UpdateMemoryAccessState(&GetAccessStateMap(AddressType::kLinearAddress), (range + base_address), action); } template <typename Action> void AccessContext::UpdateResourceAccess(const IMAGE_STATE &image, const VkImageSubresourceRange &subresource_range, const Action action) { if (!SimpleBinding(image)) return; const auto address_type = ImageAddressType(image); auto *accesses = &GetAccessStateMap(address_type); subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, {0, 0, 0}, image.createInfo.extent); const auto base_address = ResourceBaseAddress(image); for (; range_gen->non_empty(); ++range_gen) { UpdateMemoryAccessState(accesses, (*range_gen + base_address), action); } } void AccessContext::UpdateAttachmentResolveAccess(const RENDER_PASS_STATE &rp_state, const VkRect2D &render_area, const std::vector<const IMAGE_VIEW_STATE *> &attachment_views, uint32_t subpass, const ResourceUsageTag &tag) { UpdateStateResolveAction update(*this, tag); ResolveOperation(update, rp_state, render_area, attachment_views, subpass); } void AccessContext::UpdateAttachmentStoreAccess(const RENDER_PASS_STATE &rp_state, const VkRect2D &render_area, const std::vector<const IMAGE_VIEW_STATE *> &attachment_views, uint32_t subpass, const ResourceUsageTag &tag) { const auto *attachment_ci = rp_state.createInfo.pAttachments; VkExtent3D extent = CastTo3D(render_area.extent); VkOffset3D offset = CastTo3D(render_area.offset); for (uint32_t i = 0; i < rp_state.createInfo.attachmentCount; i++) { if (rp_state.attachment_last_subpass[i] == subpass) { if (attachment_views[i] == nullptr) continue; // UNUSED const auto &view = *attachment_views[i]; const IMAGE_STATE *image = view.image_state.get(); if (image == nullptr) continue; const auto &ci = attachment_ci[i]; const bool has_depth = FormatHasDepth(ci.format); const bool has_stencil = FormatHasStencil(ci.format); const bool is_color = !(has_depth || has_stencil); const bool store_op_stores = ci.storeOp != VK_ATTACHMENT_STORE_OP_NONE_QCOM; if (is_color && store_op_stores) { UpdateAccessState(*image, SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, view.normalized_subresource_range, offset, extent, tag); } else { auto update_range = view.normalized_subresource_range; if (has_depth && store_op_stores) { update_range.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT; UpdateAccessState(*image, SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, update_range, offset, extent, tag); } const bool stencil_op_stores = ci.stencilStoreOp != VK_ATTACHMENT_STORE_OP_NONE_QCOM; if (has_stencil && stencil_op_stores) { update_range.aspectMask = VK_IMAGE_ASPECT_STENCIL_BIT; UpdateAccessState(*image, SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, update_range, offset, extent, tag); } } } } } template <typename Action> void AccessContext::ApplyGlobalBarriers(const Action &barrier_action) { // Note: Barriers do *not* cross context boundaries, applying to accessess within.... (at least for renderpass subpasses) for (const auto address_type : kAddressTypes) { UpdateMemoryAccessState(&GetAccessStateMap(address_type), full_range, barrier_action); } } void AccessContext::ResolveChildContexts(const std::vector<AccessContext> &contexts) { for (uint32_t subpass_index = 0; subpass_index < contexts.size(); subpass_index++) { auto &context = contexts[subpass_index]; ApplyTrackbackBarriersAction barrier_action(context.GetDstExternalTrackBack().barriers); for (const auto address_type : kAddressTypes) { context.ResolveAccessRange(address_type, full_range, barrier_action, &GetAccessStateMap(address_type), nullptr, false); } } } // Suitable only for *subpass* access contexts HazardResult AccessContext::DetectSubpassTransitionHazard(const TrackBack &track_back, const IMAGE_VIEW_STATE *attach_view) const { if (!attach_view) return HazardResult(); const auto image_state = attach_view->image_state.get(); if (!image_state) return HazardResult(); // We should never ask for a transition from a context we don't have assert(track_back.context); // Do the detection against the specific prior context independent of other contexts. (Synchronous only) // Hazard detection for the transition can be against the merged of the barriers (it only uses src_...) const auto merged_barrier = MergeBarriers(track_back.barriers); HazardResult hazard = track_back.context->DetectImageBarrierHazard(*image_state, merged_barrier.src_exec_scope, merged_barrier.src_access_scope, attach_view->normalized_subresource_range, kDetectPrevious); if (!hazard.hazard) { // The Async hazard check is against the current context's async set. hazard = DetectImageBarrierHazard(*image_state, merged_barrier.src_exec_scope, merged_barrier.src_access_scope, attach_view->normalized_subresource_range, kDetectAsync); } return hazard; } void AccessContext::RecordLayoutTransitions(const RENDER_PASS_STATE &rp_state, uint32_t subpass, const std::vector<const IMAGE_VIEW_STATE *> &attachment_views, const ResourceUsageTag &tag) { const auto &transitions = rp_state.subpass_transitions[subpass]; const ResourceAccessState empty_infill; for (const auto &transition : transitions) { const auto prev_pass = transition.prev_pass; const auto attachment_view = attachment_views[transition.attachment]; if (!attachment_view) continue; const auto *image = attachment_view->image_state.get(); if (!image) continue; if (!SimpleBinding(*image)) continue; const auto *trackback = GetTrackBackFromSubpass(prev_pass); assert(trackback); // Import the attachments into the current context const auto *prev_context = trackback->context; assert(prev_context); const auto address_type = ImageAddressType(*image); auto &target_map = GetAccessStateMap(address_type); ApplySubpassTransitionBarriersAction barrier_action(trackback->barriers); prev_context->ResolveAccessRange(*image, attachment_view->normalized_subresource_range, barrier_action, address_type, &target_map, &empty_infill); } // If there were no transitions skip this global map walk if (transitions.size()) { ApplyBarrierOpsFunctor apply_pending_action(true /* resolve */, 0, tag); ApplyGlobalBarriers(apply_pending_action); } } // Class CommandBufferAccessContext: Keep track of resource access state information for a specific command buffer bool CommandBufferAccessContext::ValidateBeginRenderPass(const RENDER_PASS_STATE &rp_state, const VkRenderPassBeginInfo *pRenderPassBegin, const VkSubpassBeginInfoKHR *pSubpassBeginInfo, const char *func_name) const { // Check if any of the layout transitions are hazardous.... but we don't have the renderpass context to work with, so we bool skip = false; assert(pRenderPassBegin); if (nullptr == pRenderPassBegin) return skip; const uint32_t subpass = 0; // Construct the state we can use to validate against... (since validation is const and RecordCmdBeginRenderPass // hasn't happened yet) const std::vector<AccessContext> empty_context_vector; AccessContext temp_context(subpass, queue_flags_, rp_state.subpass_dependencies, empty_context_vector, const_cast<AccessContext *>(&cb_access_context_)); // Create a view list const auto fb_state = sync_state_->Get<FRAMEBUFFER_STATE>(pRenderPassBegin->framebuffer); assert(fb_state); if (nullptr == fb_state) return skip; // NOTE: Must not use COMMAND_BUFFER_STATE variant of this as RecordCmdBeginRenderPass hasn't run and thus // the activeRenderPass.* fields haven't been set. const auto views = sync_state_->GetAttachmentViews(*pRenderPassBegin, *fb_state); // Validate transitions skip |= temp_context.ValidateLayoutTransitions(*sync_state_, rp_state, pRenderPassBegin->renderArea, subpass, views, func_name); // Validate load operations if there were no layout transition hazards if (!skip) { temp_context.RecordLayoutTransitions(rp_state, subpass, views, kCurrentCommandTag); skip |= temp_context.ValidateLoadOperation(*sync_state_, rp_state, pRenderPassBegin->renderArea, subpass, views, func_name); } return skip; } bool CommandBufferAccessContext::ValidateDispatchDrawDescriptorSet(VkPipelineBindPoint pipelineBindPoint, const char *func_name) const { bool skip = false; const PIPELINE_STATE *pPipe = nullptr; const std::vector<LAST_BOUND_STATE::PER_SET> *per_sets = nullptr; GetCurrentPipelineAndDesriptorSetsFromCommandBuffer(*cb_state_.get(), pipelineBindPoint, &pPipe, &per_sets); if (!pPipe || !per_sets) { return skip; } using DescriptorClass = cvdescriptorset::DescriptorClass; using BufferDescriptor = cvdescriptorset::BufferDescriptor; using ImageDescriptor = cvdescriptorset::ImageDescriptor; using ImageSamplerDescriptor = cvdescriptorset::ImageSamplerDescriptor; using TexelDescriptor = cvdescriptorset::TexelDescriptor; for (const auto &stage_state : pPipe->stage_state) { if (stage_state.stage_flag == VK_SHADER_STAGE_FRAGMENT_BIT && pPipe->graphicsPipelineCI.pRasterizationState && pPipe->graphicsPipelineCI.pRasterizationState->rasterizerDiscardEnable) continue; for (const auto &set_binding : stage_state.descriptor_uses) { cvdescriptorset::DescriptorSet *descriptor_set = (*per_sets)[set_binding.first.first].bound_descriptor_set; cvdescriptorset::DescriptorSetLayout::ConstBindingIterator binding_it(descriptor_set->GetLayout().get(), set_binding.first.second); const auto descriptor_type = binding_it.GetType(); cvdescriptorset::IndexRange index_range = binding_it.GetGlobalIndexRange(); auto array_idx = 0; if (binding_it.IsVariableDescriptorCount()) { index_range.end = index_range.start + descriptor_set->GetVariableDescriptorCount(); } SyncStageAccessIndex sync_index = GetSyncStageAccessIndexsByDescriptorSet(descriptor_type, set_binding.second, stage_state.stage_flag); for (uint32_t i = index_range.start; i < index_range.end; ++i, ++array_idx) { uint32_t index = i - index_range.start; const auto *descriptor = descriptor_set->GetDescriptorFromGlobalIndex(i); switch (descriptor->GetClass()) { case DescriptorClass::ImageSampler: case DescriptorClass::Image: { const IMAGE_VIEW_STATE *img_view_state = nullptr; VkImageLayout image_layout; if (descriptor->GetClass() == DescriptorClass::ImageSampler) { const auto image_sampler_descriptor = static_cast<const ImageSamplerDescriptor *>(descriptor); img_view_state = image_sampler_descriptor->GetImageViewState(); image_layout = image_sampler_descriptor->GetImageLayout(); } else { const auto image_descriptor = static_cast<const ImageDescriptor *>(descriptor); img_view_state = image_descriptor->GetImageViewState(); image_layout = image_descriptor->GetImageLayout(); } if (!img_view_state) continue; const IMAGE_STATE *img_state = img_view_state->image_state.get(); VkExtent3D extent = {}; VkOffset3D offset = {}; if (sync_index == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ) { extent = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.extent); offset = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.offset); } else { extent = img_state->createInfo.extent; } HazardResult hazard; const auto &subresource_range = img_view_state->normalized_subresource_range; if (descriptor_type == VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT) { // Input attachments are subject to raster ordering rules hazard = current_context_->DetectHazard(*img_state, sync_index, subresource_range, kAttachmentRasterOrder, offset, extent); } else { hazard = current_context_->DetectHazard(*img_state, sync_index, subresource_range, offset, extent); } if (hazard.hazard && !sync_state_->SupressedBoundDescriptorWAW(hazard)) { skip |= sync_state_->LogError( img_view_state->image_view, string_SyncHazardVUID(hazard.hazard), "%s: Hazard %s for %s, in %s, and %s, %s, type: %s, imageLayout: %s, binding #%" PRIu32 ", index %" PRIu32 ". Access info %s.", func_name, string_SyncHazard(hazard.hazard), sync_state_->report_data->FormatHandle(img_view_state->image_view).c_str(), sync_state_->report_data->FormatHandle(cb_state_->commandBuffer).c_str(), sync_state_->report_data->FormatHandle(pPipe->pipeline).c_str(), sync_state_->report_data->FormatHandle(descriptor_set->GetSet()).c_str(), string_VkDescriptorType(descriptor_type), string_VkImageLayout(image_layout), set_binding.first.second, index, string_UsageTag(hazard).c_str()); } break; } case DescriptorClass::TexelBuffer: { auto buf_view_state = static_cast<const TexelDescriptor *>(descriptor)->GetBufferViewState(); if (!buf_view_state) continue; const BUFFER_STATE *buf_state = buf_view_state->buffer_state.get(); const ResourceAccessRange range = MakeRange(*buf_view_state); auto hazard = current_context_->DetectHazard(*buf_state, sync_index, range); if (hazard.hazard && !sync_state_->SupressedBoundDescriptorWAW(hazard)) { skip |= sync_state_->LogError( buf_view_state->buffer_view, string_SyncHazardVUID(hazard.hazard), "%s: Hazard %s for %s in %s, %s, and %s, type: %s, binding #%d index %d. Access info %s.", func_name, string_SyncHazard(hazard.hazard), sync_state_->report_data->FormatHandle(buf_view_state->buffer_view).c_str(), sync_state_->report_data->FormatHandle(cb_state_->commandBuffer).c_str(), sync_state_->report_data->FormatHandle(pPipe->pipeline).c_str(), sync_state_->report_data->FormatHandle(descriptor_set->GetSet()).c_str(), string_VkDescriptorType(descriptor_type), set_binding.first.second, index, string_UsageTag(hazard).c_str()); } break; } case DescriptorClass::GeneralBuffer: { const auto *buffer_descriptor = static_cast<const BufferDescriptor *>(descriptor); auto buf_state = buffer_descriptor->GetBufferState(); if (!buf_state) continue; const ResourceAccessRange range = MakeRange(*buf_state, buffer_descriptor->GetOffset(), buffer_descriptor->GetRange()); auto hazard = current_context_->DetectHazard(*buf_state, sync_index, range); if (hazard.hazard && !sync_state_->SupressedBoundDescriptorWAW(hazard)) { skip |= sync_state_->LogError( buf_state->buffer, string_SyncHazardVUID(hazard.hazard), "%s: Hazard %s for %s in %s, %s, and %s, type: %s, binding #%d index %d. Access info %s.", func_name, string_SyncHazard(hazard.hazard), sync_state_->report_data->FormatHandle(buf_state->buffer).c_str(), sync_state_->report_data->FormatHandle(cb_state_->commandBuffer).c_str(), sync_state_->report_data->FormatHandle(pPipe->pipeline).c_str(), sync_state_->report_data->FormatHandle(descriptor_set->GetSet()).c_str(), string_VkDescriptorType(descriptor_type), set_binding.first.second, index, string_UsageTag(hazard).c_str()); } break; } // TODO: INLINE_UNIFORM_BLOCK_EXT, ACCELERATION_STRUCTURE_KHR default: break; } } } } return skip; } void CommandBufferAccessContext::RecordDispatchDrawDescriptorSet(VkPipelineBindPoint pipelineBindPoint, const ResourceUsageTag &tag) { const PIPELINE_STATE *pPipe = nullptr; const std::vector<LAST_BOUND_STATE::PER_SET> *per_sets = nullptr; GetCurrentPipelineAndDesriptorSetsFromCommandBuffer(*cb_state_.get(), pipelineBindPoint, &pPipe, &per_sets); if (!pPipe || !per_sets) { return; } using DescriptorClass = cvdescriptorset::DescriptorClass; using BufferDescriptor = cvdescriptorset::BufferDescriptor; using ImageDescriptor = cvdescriptorset::ImageDescriptor; using ImageSamplerDescriptor = cvdescriptorset::ImageSamplerDescriptor; using TexelDescriptor = cvdescriptorset::TexelDescriptor; for (const auto &stage_state : pPipe->stage_state) { if (stage_state.stage_flag == VK_SHADER_STAGE_FRAGMENT_BIT && pPipe->graphicsPipelineCI.pRasterizationState && pPipe->graphicsPipelineCI.pRasterizationState->rasterizerDiscardEnable) continue; for (const auto &set_binding : stage_state.descriptor_uses) { cvdescriptorset::DescriptorSet *descriptor_set = (*per_sets)[set_binding.first.first].bound_descriptor_set; cvdescriptorset::DescriptorSetLayout::ConstBindingIterator binding_it(descriptor_set->GetLayout().get(), set_binding.first.second); const auto descriptor_type = binding_it.GetType(); cvdescriptorset::IndexRange index_range = binding_it.GetGlobalIndexRange(); auto array_idx = 0; if (binding_it.IsVariableDescriptorCount()) { index_range.end = index_range.start + descriptor_set->GetVariableDescriptorCount(); } SyncStageAccessIndex sync_index = GetSyncStageAccessIndexsByDescriptorSet(descriptor_type, set_binding.second, stage_state.stage_flag); for (uint32_t i = index_range.start; i < index_range.end; ++i, ++array_idx) { const auto *descriptor = descriptor_set->GetDescriptorFromGlobalIndex(i); switch (descriptor->GetClass()) { case DescriptorClass::ImageSampler: case DescriptorClass::Image: { const IMAGE_VIEW_STATE *img_view_state = nullptr; if (descriptor->GetClass() == DescriptorClass::ImageSampler) { img_view_state = static_cast<const ImageSamplerDescriptor *>(descriptor)->GetImageViewState(); } else { img_view_state = static_cast<const ImageDescriptor *>(descriptor)->GetImageViewState(); } if (!img_view_state) continue; const IMAGE_STATE *img_state = img_view_state->image_state.get(); VkExtent3D extent = {}; VkOffset3D offset = {}; if (sync_index == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ) { extent = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.extent); offset = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.offset); } else { extent = img_state->createInfo.extent; } current_context_->UpdateAccessState(*img_state, sync_index, img_view_state->normalized_subresource_range, offset, extent, tag); break; } case DescriptorClass::TexelBuffer: { auto buf_view_state = static_cast<const TexelDescriptor *>(descriptor)->GetBufferViewState(); if (!buf_view_state) continue; const BUFFER_STATE *buf_state = buf_view_state->buffer_state.get(); const ResourceAccessRange range = MakeRange(*buf_view_state); current_context_->UpdateAccessState(*buf_state, sync_index, range, tag); break; } case DescriptorClass::GeneralBuffer: { const auto *buffer_descriptor = static_cast<const BufferDescriptor *>(descriptor); auto buf_state = buffer_descriptor->GetBufferState(); if (!buf_state) continue; const ResourceAccessRange range = MakeRange(*buf_state, buffer_descriptor->GetOffset(), buffer_descriptor->GetRange()); current_context_->UpdateAccessState(*buf_state, sync_index, range, tag); break; } // TODO: INLINE_UNIFORM_BLOCK_EXT, ACCELERATION_STRUCTURE_KHR default: break; } } } } } bool CommandBufferAccessContext::ValidateDrawVertex(uint32_t vertexCount, uint32_t firstVertex, const char *func_name) const { bool skip = false; const auto *pPipe = GetCurrentPipelineFromCommandBuffer(*cb_state_.get(), VK_PIPELINE_BIND_POINT_GRAPHICS); if (!pPipe) { return skip; } const auto &binding_buffers = cb_state_->current_vertex_buffer_binding_info.vertex_buffer_bindings; const auto &binding_buffers_size = binding_buffers.size(); const auto &binding_descriptions_size = pPipe->vertex_binding_descriptions_.size(); for (size_t i = 0; i < binding_descriptions_size; ++i) { const auto &binding_description = pPipe->vertex_binding_descriptions_[i]; if (binding_description.binding < binding_buffers_size) { const auto &binding_buffer = binding_buffers[binding_description.binding]; if (binding_buffer.buffer == VK_NULL_HANDLE) continue; auto *buf_state = sync_state_->Get<BUFFER_STATE>(binding_buffer.buffer); const ResourceAccessRange range = GetBufferRange(binding_buffer.offset, buf_state->createInfo.size, firstVertex, vertexCount, binding_description.stride); auto hazard = current_context_->DetectHazard(*buf_state, SYNC_VERTEX_INPUT_VERTEX_ATTRIBUTE_READ, range); if (hazard.hazard) { skip |= sync_state_->LogError( buf_state->buffer, string_SyncHazardVUID(hazard.hazard), "%s: Hazard %s for vertex %s in %s. Access info %s.", func_name, string_SyncHazard(hazard.hazard), sync_state_->report_data->FormatHandle(buf_state->buffer).c_str(), sync_state_->report_data->FormatHandle(cb_state_->commandBuffer).c_str(), string_UsageTag(hazard).c_str()); } } } return skip; } void CommandBufferAccessContext::RecordDrawVertex(uint32_t vertexCount, uint32_t firstVertex, const ResourceUsageTag &tag) { const auto *pPipe = GetCurrentPipelineFromCommandBuffer(*cb_state_.get(), VK_PIPELINE_BIND_POINT_GRAPHICS); if (!pPipe) { return; } const auto &binding_buffers = cb_state_->current_vertex_buffer_binding_info.vertex_buffer_bindings; const auto &binding_buffers_size = binding_buffers.size(); const auto &binding_descriptions_size = pPipe->vertex_binding_descriptions_.size(); for (size_t i = 0; i < binding_descriptions_size; ++i) { const auto &binding_description = pPipe->vertex_binding_descriptions_[i]; if (binding_description.binding < binding_buffers_size) { const auto &binding_buffer = binding_buffers[binding_description.binding]; if (binding_buffer.buffer == VK_NULL_HANDLE) continue; auto *buf_state = sync_state_->Get<BUFFER_STATE>(binding_buffer.buffer); const ResourceAccessRange range = GetBufferRange(binding_buffer.offset, buf_state->createInfo.size, firstVertex, vertexCount, binding_description.stride); current_context_->UpdateAccessState(*buf_state, SYNC_VERTEX_INPUT_VERTEX_ATTRIBUTE_READ, range, tag); } } } bool CommandBufferAccessContext::ValidateDrawVertexIndex(uint32_t indexCount, uint32_t firstIndex, const char *func_name) const { bool skip = false; if (cb_state_->index_buffer_binding.buffer == VK_NULL_HANDLE) return skip; auto *index_buf_state = sync_state_->Get<BUFFER_STATE>(cb_state_->index_buffer_binding.buffer); const auto index_size = GetIndexAlignment(cb_state_->index_buffer_binding.index_type); const ResourceAccessRange range = GetBufferRange(cb_state_->index_buffer_binding.offset, index_buf_state->createInfo.size, firstIndex, indexCount, index_size); auto hazard = current_context_->DetectHazard(*index_buf_state, SYNC_VERTEX_INPUT_INDEX_READ, range); if (hazard.hazard) { skip |= sync_state_->LogError( index_buf_state->buffer, string_SyncHazardVUID(hazard.hazard), "%s: Hazard %s for index %s in %s. Access info %s.", func_name, string_SyncHazard(hazard.hazard), sync_state_->report_data->FormatHandle(index_buf_state->buffer).c_str(), sync_state_->report_data->FormatHandle(cb_state_->commandBuffer).c_str(), string_UsageTag(hazard).c_str()); } // TODO: For now, we detect the whole vertex buffer. Index buffer could be changed until SubmitQueue. // We will detect more accurate range in the future. skip |= ValidateDrawVertex(UINT32_MAX, 0, func_name); return skip; } void CommandBufferAccessContext::RecordDrawVertexIndex(uint32_t indexCount, uint32_t firstIndex, const ResourceUsageTag &tag) { if (cb_state_->index_buffer_binding.buffer == VK_NULL_HANDLE) return; auto *index_buf_state = sync_state_->Get<BUFFER_STATE>(cb_state_->index_buffer_binding.buffer); const auto index_size = GetIndexAlignment(cb_state_->index_buffer_binding.index_type); const ResourceAccessRange range = GetBufferRange(cb_state_->index_buffer_binding.offset, index_buf_state->createInfo.size, firstIndex, indexCount, index_size); current_context_->UpdateAccessState(*index_buf_state, SYNC_VERTEX_INPUT_INDEX_READ, range, tag); // TODO: For now, we detect the whole vertex buffer. Index buffer could be changed until SubmitQueue. // We will detect more accurate range in the future. RecordDrawVertex(UINT32_MAX, 0, tag); } bool CommandBufferAccessContext::ValidateDrawSubpassAttachment(const char *func_name) const { bool skip = false; if (!current_renderpass_context_) return skip; skip |= current_renderpass_context_->ValidateDrawSubpassAttachment(*sync_state_, *cb_state_.get(), cb_state_->activeRenderPassBeginInfo.renderArea, func_name); return skip; } void CommandBufferAccessContext::RecordDrawSubpassAttachment(const ResourceUsageTag &tag) { if (current_renderpass_context_) current_renderpass_context_->RecordDrawSubpassAttachment(*cb_state_.get(), cb_state_->activeRenderPassBeginInfo.renderArea, tag); } bool CommandBufferAccessContext::ValidateNextSubpass(const char *func_name) const { bool skip = false; if (!current_renderpass_context_) return skip; skip |= current_renderpass_context_->ValidateNextSubpass(*sync_state_, cb_state_->activeRenderPassBeginInfo.renderArea, func_name); return skip; } bool CommandBufferAccessContext::ValidateEndRenderpass(const char *func_name) const { // TODO: Things to add here. // Validate Preserve attachments bool skip = false; if (!current_renderpass_context_) return skip; skip |= current_renderpass_context_->ValidateEndRenderPass(*sync_state_, cb_state_->activeRenderPassBeginInfo.renderArea, func_name); return skip; } void CommandBufferAccessContext::RecordBeginRenderPass(const ResourceUsageTag &tag) { assert(sync_state_); if (!cb_state_) return; // Create an access context the current renderpass. render_pass_contexts_.emplace_back(); current_renderpass_context_ = &render_pass_contexts_.back(); current_renderpass_context_->RecordBeginRenderPass(*sync_state_, *cb_state_, &cb_access_context_, queue_flags_, tag); current_context_ = &current_renderpass_context_->CurrentContext(); } void CommandBufferAccessContext::RecordNextSubpass(const RENDER_PASS_STATE &rp_state, const ResourceUsageTag &tag) { assert(current_renderpass_context_); current_renderpass_context_->RecordNextSubpass(cb_state_->activeRenderPassBeginInfo.renderArea, tag); current_context_ = &current_renderpass_context_->CurrentContext(); } void CommandBufferAccessContext::RecordEndRenderPass(const RENDER_PASS_STATE &render_pass, const ResourceUsageTag &tag) { assert(current_renderpass_context_); if (!current_renderpass_context_) return; current_renderpass_context_->RecordEndRenderPass(&cb_access_context_, cb_state_->activeRenderPassBeginInfo.renderArea, tag); current_context_ = &cb_access_context_; current_renderpass_context_ = nullptr; } bool RenderPassAccessContext::ValidateDrawSubpassAttachment(const SyncValidator &sync_state, const CMD_BUFFER_STATE &cmd, const VkRect2D &render_area, const char *func_name) const { bool skip = false; const auto *pPipe = GetCurrentPipelineFromCommandBuffer(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS); if (!pPipe || (pPipe->graphicsPipelineCI.pRasterizationState && pPipe->graphicsPipelineCI.pRasterizationState->rasterizerDiscardEnable)) { return skip; } const auto &list = pPipe->fragmentShader_writable_output_location_list; const auto &subpass = rp_state_->createInfo.pSubpasses[current_subpass_]; VkExtent3D extent = CastTo3D(render_area.extent); VkOffset3D offset = CastTo3D(render_area.offset); const auto &current_context = CurrentContext(); // Subpass's inputAttachment has been done in ValidateDispatchDrawDescriptorSet if (subpass.pColorAttachments && subpass.colorAttachmentCount && !list.empty()) { for (const auto location : list) { if (location >= subpass.colorAttachmentCount || subpass.pColorAttachments[location].attachment == VK_ATTACHMENT_UNUSED) continue; const IMAGE_VIEW_STATE *img_view_state = attachment_views_[subpass.pColorAttachments[location].attachment]; HazardResult hazard = current_context.DetectHazard(img_view_state, SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, kColorAttachmentRasterOrder, offset, extent); if (hazard.hazard) { skip |= sync_state.LogError(img_view_state->image_view, string_SyncHazardVUID(hazard.hazard), "%s: Hazard %s for %s in %s, Subpass #%d, and pColorAttachments #%d. Access info %s.", func_name, string_SyncHazard(hazard.hazard), sync_state.report_data->FormatHandle(img_view_state->image_view).c_str(), sync_state.report_data->FormatHandle(cmd.commandBuffer).c_str(), cmd.activeSubpass, location, string_UsageTag(hazard).c_str()); } } } // PHASE1 TODO: Add layout based read/vs. write selection. // PHASE1 TODO: Read operations for both depth and stencil are possible in the future. if (pPipe->graphicsPipelineCI.pDepthStencilState && subpass.pDepthStencilAttachment && subpass.pDepthStencilAttachment->attachment != VK_ATTACHMENT_UNUSED) { const IMAGE_VIEW_STATE *img_view_state = attachment_views_[subpass.pDepthStencilAttachment->attachment]; bool depth_write = false, stencil_write = false; // PHASE1 TODO: These validation should be in core_checks. if (!FormatIsStencilOnly(img_view_state->create_info.format) && pPipe->graphicsPipelineCI.pDepthStencilState->depthTestEnable && pPipe->graphicsPipelineCI.pDepthStencilState->depthWriteEnable && IsImageLayoutDepthWritable(subpass.pDepthStencilAttachment->layout)) { depth_write = true; } // PHASE1 TODO: It needs to check if stencil is writable. // If failOp, passOp, or depthFailOp are not KEEP, and writeMask isn't 0, it's writable. // If depth test is disable, it's considered depth test passes, and then depthFailOp doesn't run. // PHASE1 TODO: These validation should be in core_checks. if (!FormatIsDepthOnly(img_view_state->create_info.format) && pPipe->graphicsPipelineCI.pDepthStencilState->stencilTestEnable && IsImageLayoutStencilWritable(subpass.pDepthStencilAttachment->layout)) { stencil_write = true; } // PHASE1 TODO: Add EARLY stage detection based on ExecutionMode. if (depth_write) { HazardResult hazard = current_context.DetectHazard(img_view_state, SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, kDepthStencilAttachmentRasterOrder, offset, extent, VK_IMAGE_ASPECT_DEPTH_BIT); if (hazard.hazard) { skip |= sync_state.LogError( img_view_state->image_view, string_SyncHazardVUID(hazard.hazard), "%s: Hazard %s for %s in %s, Subpass #%d, and depth part of pDepthStencilAttachment. Access info %s.", func_name, string_SyncHazard(hazard.hazard), sync_state.report_data->FormatHandle(img_view_state->image_view).c_str(), sync_state.report_data->FormatHandle(cmd.commandBuffer).c_str(), cmd.activeSubpass, string_UsageTag(hazard).c_str()); } } if (stencil_write) { HazardResult hazard = current_context.DetectHazard(img_view_state, SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, kDepthStencilAttachmentRasterOrder, offset, extent, VK_IMAGE_ASPECT_STENCIL_BIT); if (hazard.hazard) { skip |= sync_state.LogError( img_view_state->image_view, string_SyncHazardVUID(hazard.hazard), "%s: Hazard %s for %s in %s, Subpass #%d, and stencil part of pDepthStencilAttachment. Access info %s.", func_name, string_SyncHazard(hazard.hazard), sync_state.report_data->FormatHandle(img_view_state->image_view).c_str(), sync_state.report_data->FormatHandle(cmd.commandBuffer).c_str(), cmd.activeSubpass, string_UsageTag(hazard).c_str()); } } } return skip; } void RenderPassAccessContext::RecordDrawSubpassAttachment(const CMD_BUFFER_STATE &cmd, const VkRect2D &render_area, const ResourceUsageTag &tag) { const auto *pPipe = GetCurrentPipelineFromCommandBuffer(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS); if (!pPipe || (pPipe->graphicsPipelineCI.pRasterizationState && pPipe->graphicsPipelineCI.pRasterizationState->rasterizerDiscardEnable)) { return; } const auto &list = pPipe->fragmentShader_writable_output_location_list; const auto &subpass = rp_state_->createInfo.pSubpasses[current_subpass_]; VkExtent3D extent = CastTo3D(render_area.extent); VkOffset3D offset = CastTo3D(render_area.offset); auto &current_context = CurrentContext(); // Subpass's inputAttachment has been done in RecordDispatchDrawDescriptorSet if (subpass.pColorAttachments && subpass.colorAttachmentCount && !list.empty()) { for (const auto location : list) { if (location >= subpass.colorAttachmentCount || subpass.pColorAttachments[location].attachment == VK_ATTACHMENT_UNUSED) continue; const IMAGE_VIEW_STATE *img_view_state = attachment_views_[subpass.pColorAttachments[location].attachment]; current_context.UpdateAccessState(img_view_state, SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, offset, extent, 0, tag); } } // PHASE1 TODO: Add layout based read/vs. write selection. // PHASE1 TODO: Read operations for both depth and stencil are possible in the future. if (pPipe->graphicsPipelineCI.pDepthStencilState && subpass.pDepthStencilAttachment && subpass.pDepthStencilAttachment->attachment != VK_ATTACHMENT_UNUSED) { const IMAGE_VIEW_STATE *img_view_state = attachment_views_[subpass.pDepthStencilAttachment->attachment]; bool depth_write = false, stencil_write = false; // PHASE1 TODO: These validation should be in core_checks. if (!FormatIsStencilOnly(img_view_state->create_info.format) && pPipe->graphicsPipelineCI.pDepthStencilState->depthTestEnable && pPipe->graphicsPipelineCI.pDepthStencilState->depthWriteEnable && IsImageLayoutDepthWritable(subpass.pDepthStencilAttachment->layout)) { depth_write = true; } // PHASE1 TODO: It needs to check if stencil is writable. // If failOp, passOp, or depthFailOp are not KEEP, and writeMask isn't 0, it's writable. // If depth test is disable, it's considered depth test passes, and then depthFailOp doesn't run. // PHASE1 TODO: These validation should be in core_checks. if (!FormatIsDepthOnly(img_view_state->create_info.format) && pPipe->graphicsPipelineCI.pDepthStencilState->stencilTestEnable && IsImageLayoutStencilWritable(subpass.pDepthStencilAttachment->layout)) { stencil_write = true; } // PHASE1 TODO: Add EARLY stage detection based on ExecutionMode. if (depth_write) { current_context.UpdateAccessState(img_view_state, SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, offset, extent, VK_IMAGE_ASPECT_DEPTH_BIT, tag); } if (stencil_write) { current_context.UpdateAccessState(img_view_state, SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, offset, extent, VK_IMAGE_ASPECT_STENCIL_BIT, tag); } } } bool RenderPassAccessContext::ValidateNextSubpass(const SyncValidator &sync_state, const VkRect2D &render_area, const char *func_name) const { // PHASE1 TODO: Add Validate Preserve attachments bool skip = false; skip |= CurrentContext().ValidateResolveOperations(sync_state, *rp_state_, render_area, attachment_views_, func_name, current_subpass_); skip |= CurrentContext().ValidateStoreOperation(sync_state, *rp_state_, render_area, current_subpass_, attachment_views_, func_name); const auto next_subpass = current_subpass_ + 1; const auto &next_context = subpass_contexts_[next_subpass]; skip |= next_context.ValidateLayoutTransitions(sync_state, *rp_state_, render_area, next_subpass, attachment_views_, func_name); if (!skip) { // To avoid complex (and buggy) duplication of the affect of layout transitions on load operations, we'll record them // on a copy of the (empty) next context. // Note: The resource access map should be empty so hopefully this copy isn't too horrible from a perf POV. AccessContext temp_context(next_context); temp_context.RecordLayoutTransitions(*rp_state_, next_subpass, attachment_views_, kCurrentCommandTag); skip |= temp_context.ValidateLoadOperation(sync_state, *rp_state_, render_area, next_subpass, attachment_views_, func_name); } return skip; } bool RenderPassAccessContext::ValidateEndRenderPass(const SyncValidator &sync_state, const VkRect2D &render_area, const char *func_name) const { // PHASE1 TODO: Validate Preserve bool skip = false; skip |= CurrentContext().ValidateResolveOperations(sync_state, *rp_state_, render_area, attachment_views_, func_name, current_subpass_); skip |= CurrentContext().ValidateStoreOperation(sync_state, *rp_state_, render_area, current_subpass_, attachment_views_, func_name); skip |= ValidateFinalSubpassLayoutTransitions(sync_state, render_area, func_name); return skip; } AccessContext *RenderPassAccessContext::CreateStoreResolveProxy(const VkRect2D &render_area) const { return CreateStoreResolveProxyContext(CurrentContext(), *rp_state_, current_subpass_, render_area, attachment_views_); } bool RenderPassAccessContext::ValidateFinalSubpassLayoutTransitions(const SyncValidator &sync_state, const VkRect2D &render_area, const char *func_name) const { bool skip = false; // As validation methods are const and precede the record/update phase, for any tranistions from the current (last) // subpass, we have to validate them against a copy of the current AccessContext, with resolve operations applied. // Note: we could be more efficient by tracking whether or not we actually *have* any changes (e.g. attachment resolve) // to apply and only copy then, if this proves a hot spot. std::unique_ptr<AccessContext> proxy_for_current; // Validate the "finalLayout" transitions to external // Get them from where there we're hidding in the extra entry. const auto &final_transitions = rp_state_->subpass_transitions.back(); for (const auto &transition : final_transitions) { const auto &attach_view = attachment_views_[transition.attachment]; const auto &trackback = subpass_contexts_[transition.prev_pass].GetDstExternalTrackBack(); assert(trackback.context); // Transitions are given implicit transitions if the StateTracker is working correctly auto *context = trackback.context; if (transition.prev_pass == current_subpass_) { if (!proxy_for_current) { // We haven't recorded resolve ofor the current_subpass, so we need to copy current and update it *as if* proxy_for_current.reset(CreateStoreResolveProxy(render_area)); } context = proxy_for_current.get(); } // Use the merged barrier for the hazard check (safe since it just considers the src (first) scope. const auto merged_barrier = MergeBarriers(trackback.barriers); auto hazard = context->DetectImageBarrierHazard(*attach_view->image_state, merged_barrier.src_exec_scope, merged_barrier.src_access_scope, attach_view->normalized_subresource_range, AccessContext::DetectOptions::kDetectPrevious); if (hazard.hazard) { skip |= sync_state.LogError(rp_state_->renderPass, string_SyncHazardVUID(hazard.hazard), "%s: Hazard %s with last use subpass %" PRIu32 " for attachment %" PRIu32 " final image layout transition (old_layout: %s, new_layout: %s). Access info %s.", func_name, string_SyncHazard(hazard.hazard), transition.prev_pass, transition.attachment, string_VkImageLayout(transition.old_layout), string_VkImageLayout(transition.new_layout), string_UsageTag(hazard).c_str()); } } return skip; } void RenderPassAccessContext::RecordLayoutTransitions(const ResourceUsageTag &tag) { // Add layout transitions... subpass_contexts_[current_subpass_].RecordLayoutTransitions(*rp_state_, current_subpass_, attachment_views_, tag); } void RenderPassAccessContext::RecordLoadOperations(const VkRect2D &render_area, const ResourceUsageTag &tag) { const auto *attachment_ci = rp_state_->createInfo.pAttachments; auto &subpass_context = subpass_contexts_[current_subpass_]; VkExtent3D extent = CastTo3D(render_area.extent); VkOffset3D offset = CastTo3D(render_area.offset); for (uint32_t i = 0; i < rp_state_->createInfo.attachmentCount; i++) { if (rp_state_->attachment_first_subpass[i] == current_subpass_) { if (attachment_views_[i] == nullptr) continue; // UNUSED const auto &view = *attachment_views_[i]; const IMAGE_STATE *image = view.image_state.get(); if (image == nullptr) continue; const auto &ci = attachment_ci[i]; const bool has_depth = FormatHasDepth(ci.format); const bool has_stencil = FormatHasStencil(ci.format); const bool is_color = !(has_depth || has_stencil); if (is_color) { subpass_context.UpdateAccessState(*image, ColorLoadUsage(ci.loadOp), view.normalized_subresource_range, offset, extent, tag); } else { auto update_range = view.normalized_subresource_range; if (has_depth) { update_range.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT; subpass_context.UpdateAccessState(*image, DepthStencilLoadUsage(ci.loadOp), update_range, offset, extent, tag); } if (has_stencil) { update_range.aspectMask = VK_IMAGE_ASPECT_STENCIL_BIT; subpass_context.UpdateAccessState(*image, DepthStencilLoadUsage(ci.stencilLoadOp), update_range, offset, extent, tag); } } } } } void RenderPassAccessContext::RecordBeginRenderPass(const SyncValidator &state, const CMD_BUFFER_STATE &cb_state, const AccessContext *external_context, VkQueueFlags queue_flags, const ResourceUsageTag &tag) { current_subpass_ = 0; rp_state_ = cb_state.activeRenderPass.get(); subpass_contexts_.reserve(rp_state_->createInfo.subpassCount); // Add this for all subpasses here so that they exsist during next subpass validation for (uint32_t pass = 0; pass < rp_state_->createInfo.subpassCount; pass++) { subpass_contexts_.emplace_back(pass, queue_flags, rp_state_->subpass_dependencies, subpass_contexts_, external_context); } attachment_views_ = state.GetCurrentAttachmentViews(cb_state); RecordLayoutTransitions(tag); RecordLoadOperations(cb_state.activeRenderPassBeginInfo.renderArea, tag); } void RenderPassAccessContext::RecordNextSubpass(const VkRect2D &render_area, const ResourceUsageTag &tag) { // Resolves are against *prior* subpass context and thus *before* the subpass increment CurrentContext().UpdateAttachmentResolveAccess(*rp_state_, render_area, attachment_views_, current_subpass_, tag); CurrentContext().UpdateAttachmentStoreAccess(*rp_state_, render_area, attachment_views_, current_subpass_, tag); current_subpass_++; assert(current_subpass_ < subpass_contexts_.size()); RecordLayoutTransitions(tag); RecordLoadOperations(render_area, tag); } void RenderPassAccessContext::RecordEndRenderPass(AccessContext *external_context, const VkRect2D &render_area, const ResourceUsageTag &tag) { // Add the resolve and store accesses CurrentContext().UpdateAttachmentResolveAccess(*rp_state_, render_area, attachment_views_, current_subpass_, tag); CurrentContext().UpdateAttachmentStoreAccess(*rp_state_, render_area, attachment_views_, current_subpass_, tag); // Export the accesses from the renderpass... external_context->ResolveChildContexts(subpass_contexts_); // Add the "finalLayout" transitions to external // Get them from where there we're hidding in the extra entry. // Not that since *final* always comes from *one* subpass per view, we don't have to accumulate the barriers // TODO Aliasing we may need to reconsider barrier accumulation... though I don't know that it would be valid for aliasing // that had mulitple final layout transistions from mulitple final subpasses. const auto &final_transitions = rp_state_->subpass_transitions.back(); for (const auto &transition : final_transitions) { const auto &attachment = attachment_views_[transition.attachment]; const auto &last_trackback = subpass_contexts_[transition.prev_pass].GetDstExternalTrackBack(); assert(&subpass_contexts_[transition.prev_pass] == last_trackback.context); ApplyBarrierOpsFunctor barrier_ops(true /* resolve */, last_trackback.barriers, true /* layout transition */, tag); external_context->UpdateResourceAccess(*attachment->image_state, attachment->normalized_subresource_range, barrier_ops); } } SyncBarrier::SyncBarrier(VkQueueFlags queue_flags, const VkSubpassDependency2 &barrier) { const auto src_stage_mask = ExpandPipelineStages(queue_flags, barrier.srcStageMask); src_exec_scope = WithEarlierPipelineStages(src_stage_mask); src_access_scope = SyncStageAccess::AccessScope(src_stage_mask, barrier.srcAccessMask); const auto dst_stage_mask = ExpandPipelineStages(queue_flags, barrier.dstStageMask); dst_exec_scope = WithLaterPipelineStages(dst_stage_mask); dst_access_scope = SyncStageAccess::AccessScope(dst_stage_mask, barrier.dstAccessMask); } // Apply a list of barriers, without resolving pending state, useful for subpass layout transitions void ResourceAccessState::ApplyBarriers(const std::vector<SyncBarrier> &barriers, bool layout_transition) { for (const auto &barrier : barriers) { ApplyBarrier(barrier, layout_transition); } } // ApplyBarriers is design for *fully* inclusive barrier lists without layout tranistions. Designed use was for // inter-subpass barriers for lazy-evaluation of parent context memory ranges. Subpass layout transistions are *not* done // lazily, s.t. no previous access reports should need layout transitions. void ResourceAccessState::ApplyBarriers(const std::vector<SyncBarrier> &barriers, const ResourceUsageTag &tag) { assert(!pending_layout_transition); // This should never be call in the middle of another barrier application assert(pending_write_barriers.none()); assert(!pending_write_dep_chain); for (const auto &barrier : barriers) { ApplyBarrier(barrier, false); } ApplyPendingBarriers(tag); } HazardResult ResourceAccessState::DetectHazard(SyncStageAccessIndex usage_index) const { HazardResult hazard; auto usage = FlagBit(usage_index); const auto usage_stage = PipelineStageBit(usage_index); if (IsRead(usage)) { if (IsRAWHazard(usage_stage, usage)) { hazard.Set(this, usage_index, READ_AFTER_WRITE, last_write, write_tag); } } else { // Write operation: // Check for read operations more recent than last_write (as setting last_write clears reads, that would be *any* // If reads exists -- test only against them because either: // * the reads were hazards, and we've reported the hazard, so just test the current write vs. the read operations // * the read weren't hazards, and thus if the write is safe w.r.t. the reads, no hazard vs. last_write is possible if // the current write happens after the reads, so just test the write against the reades // Otherwise test against last_write // // Look for casus belli for WAR if (last_read_count) { for (uint32_t read_index = 0; read_index < last_read_count; read_index++) { const auto &read_access = last_reads[read_index]; if (IsReadHazard(usage_stage, read_access)) { hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag); break; } } } else if (last_write.any() && IsWriteHazard(usage)) { // Write-After-Write check -- if we have a previous write to test against hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag); } } return hazard; } HazardResult ResourceAccessState::DetectHazard(SyncStageAccessIndex usage_index, const SyncOrderingBarrier &ordering) const { // The ordering guarantees act as barriers to the last accesses, independent of synchronization operations HazardResult hazard; const auto usage_bit = FlagBit(usage_index); const auto usage_stage = PipelineStageBit(usage_index); const bool input_attachment_ordering = (ordering.access_scope & SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT).any(); const bool last_write_is_ordered = (last_write & ordering.access_scope).any(); if (IsRead(usage_bit)) { // Exclude RAW if no write, or write not most "most recent" operation w.r.t. usage; bool is_raw_hazard = IsRAWHazard(usage_stage, usage_bit); if (is_raw_hazard) { // NOTE: we know last_write is non-zero // See if the ordering rules save us from the simple RAW check above // First check to see if the current usage is covered by the ordering rules const bool usage_is_input_attachment = (usage_index == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ); const bool usage_is_ordered = (input_attachment_ordering && usage_is_input_attachment) || (0 != (usage_stage & ordering.exec_scope)); if (usage_is_ordered) { // Now see of the most recent write (or a subsequent read) are ordered const bool most_recent_is_ordered = last_write_is_ordered || (0 != GetOrderedStages(ordering)); is_raw_hazard = !most_recent_is_ordered; } } if (is_raw_hazard) { hazard.Set(this, usage_index, READ_AFTER_WRITE, last_write, write_tag); } } else { // Only check for WAW if there are no reads since last_write bool usage_write_is_ordered = (usage_bit & ordering.access_scope).any(); if (last_read_count) { // Look for any WAR hazards outside the ordered set of stages VkPipelineStageFlags ordered_stages = 0; if (usage_write_is_ordered) { // If the usage is ordered, we can ignore all ordered read stages w.r.t. WAR) ordered_stages = GetOrderedStages(ordering); } // If we're tracking any reads that aren't ordered against the current write, got to check 'em all. if ((ordered_stages & last_read_stages) != last_read_stages) { for (uint32_t read_index = 0; read_index < last_read_count; read_index++) { const auto &read_access = last_reads[read_index]; if (read_access.stage & ordered_stages) continue; // but we can skip the ordered ones if (IsReadHazard(usage_stage, read_access)) { hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag); break; } } } } else if (!(last_write_is_ordered && usage_write_is_ordered)) { if (last_write.any() && IsWriteHazard(usage_bit)) { hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag); } } } return hazard; } // Asynchronous Hazards occur between subpasses with no connection through the DAG HazardResult ResourceAccessState::DetectAsyncHazard(SyncStageAccessIndex usage_index) const { HazardResult hazard; auto usage = FlagBit(usage_index); if (IsRead(usage)) { if (last_write != 0) { hazard.Set(this, usage_index, READ_RACING_WRITE, last_write, write_tag); } } else { if (last_write != 0) { hazard.Set(this, usage_index, WRITE_RACING_WRITE, last_write, write_tag); } else if (last_read_count > 0) { // Any read could be reported, so we'll just pick the first one arbitrarily hazard.Set(this, usage_index, WRITE_RACING_READ, last_reads[0].access, last_reads[0].tag); } } return hazard; } HazardResult ResourceAccessState::DetectBarrierHazard(SyncStageAccessIndex usage_index, VkPipelineStageFlags src_exec_scope, const SyncStageAccessFlags &src_access_scope) const { // Only supporting image layout transitions for now assert(usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION); HazardResult hazard; // only test for WAW if there no intervening read operations. // See DetectHazard(SyncStagetAccessIndex) above for more details. if (last_read_count) { // Look at the reads if any for (uint32_t read_index = 0; read_index < last_read_count; read_index++) { const auto &read_access = last_reads[read_index]; // If the read stage is not in the src sync sync // *AND* not execution chained with an existing sync barrier (that's the or) // then the barrier access is unsafe (R/W after R) if ((src_exec_scope & (read_access.stage | read_access.barriers)) == 0) { hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag); break; } } } else if (last_write.any()) { // If the previous write is *not* in the 1st access scope // *AND* the current barrier is not in the dependency chain // *AND* the there is no prior memory barrier for the previous write in the dependency chain // then the barrier access is unsafe (R/W after W) if (((last_write & src_access_scope) == 0) && ((src_exec_scope & write_dependency_chain) == 0) && (write_barriers == 0)) { // TODO: Do we need a difference hazard name for this? hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag); } } return hazard; } // The logic behind resolves is the same as update, we assume that earlier hazards have be reported, and that no // tranistive hazard can exists with a hazard between the earlier operations. Yes, an early hazard can mask that another // exists, but if you fix *that* hazard it either fixes or unmasks the subsequent ones. void ResourceAccessState::Resolve(const ResourceAccessState &other) { if (write_tag.IsBefore(other.write_tag)) { // If this is a later write, we've reported any exsiting hazard, and we can just overwrite as the more recent // operation *this = other; } else if (!other.write_tag.IsBefore(write_tag)) { // This is the *equals* case for write operations, we merged the write barriers and the read state (but without the // dependency chaining logic or any stage expansion) write_barriers |= other.write_barriers; pending_write_barriers |= other.pending_write_barriers; pending_layout_transition |= other.pending_layout_transition; pending_write_dep_chain |= other.pending_write_dep_chain; // Merge the read states const auto pre_merge_count = last_read_count; const auto pre_merge_stages = last_read_stages; for (uint32_t other_read_index = 0; other_read_index < other.last_read_count; other_read_index++) { auto &other_read = other.last_reads[other_read_index]; if (pre_merge_stages & other_read.stage) { // Merge in the barriers for read stages that exist in *both* this and other // TODO: This is N^2 with stages... perhaps the ReadStates should be sorted by stage index. // but we should wait on profiling data for that. for (uint32_t my_read_index = 0; my_read_index < pre_merge_count; my_read_index++) { auto &my_read = last_reads[my_read_index]; if (other_read.stage == my_read.stage) { if (my_read.tag.IsBefore(other_read.tag)) { // Other is more recent, copy in the state my_read.access = other_read.access; my_read.tag = other_read.tag; my_read.pending_dep_chain = other_read.pending_dep_chain; // TODO: Phase 2 -- review the state merge logic to avoid false positive from overwriting the barriers // May require tracking more than one access per stage. my_read.barriers = other_read.barriers; if (my_read.stage == VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT) { // Since I'm overwriting the fragement stage read, also update the input attachment info // as this is the only stage that affects it. input_attachment_read = other.input_attachment_read; } } else if (other_read.tag.IsBefore(my_read.tag)) { // The read tags match so merge the barriers my_read.barriers |= other_read.barriers; my_read.pending_dep_chain |= other_read.pending_dep_chain; } break; } } } else { // The other read stage doesn't exist in this, so add it. last_reads[last_read_count] = other_read; last_read_count++; last_read_stages |= other_read.stage; if (other_read.stage == VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT) { input_attachment_read = other.input_attachment_read; } } } read_execution_barriers |= other.read_execution_barriers; } // the else clause would be that other write is before this write... in which case we supercede the other state and // ignore it. } void ResourceAccessState::Update(SyncStageAccessIndex usage_index, const ResourceUsageTag &tag) { // Move this logic in the ResourceStateTracker as methods, thereof (or we'll repeat it for every flavor of resource... const auto usage_bit = FlagBit(usage_index); if (IsRead(usage_index)) { // Mulitple outstanding reads may be of interest and do dependency chains independently // However, for purposes of barrier tracking, only one read per pipeline stage matters const auto usage_stage = PipelineStageBit(usage_index); uint32_t update_index = kStageCount; if (usage_stage & last_read_stages) { for (uint32_t read_index = 0; read_index < last_read_count; read_index++) { if (last_reads[read_index].stage == usage_stage) { update_index = read_index; break; } } assert(update_index < last_read_count); } else { assert(last_read_count < last_reads.size()); update_index = last_read_count++; last_read_stages |= usage_stage; } last_reads[update_index].Set(usage_stage, usage_bit, 0, tag); // Fragment shader reads come in two flavors, and we need to track if the one we're tracking is the special one. if (usage_stage == VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT) { // TODO Revisit re: multiple reads for a given stage input_attachment_read = (usage_bit == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT); } } else { // Assume write // TODO determine what to do with READ-WRITE operations if any SetWrite(usage_bit, tag); } } // Clobber last read and all barriers... because all we have is DANGER, DANGER, WILL ROBINSON!!! // if the last_reads/last_write were unsafe, we've reported them, in either case the prior access is irrelevant. // We can overwrite them as *this* write is now after them. // // Note: intentionally ignore pending barriers and chains (i.e. don't apply or clear them), let ApplyPendingBarriers handle them. void ResourceAccessState::SetWrite(const SyncStageAccessFlags &usage_bit, const ResourceUsageTag &tag) { last_read_count = 0; last_read_stages = 0; read_execution_barriers = 0; input_attachment_read = false; // Denotes no outstanding input attachment read after the last write. write_barriers = 0; write_dependency_chain = 0; write_tag = tag; last_write = usage_bit; } // Apply the memory barrier without updating the existing barriers. The execution barrier // changes the "chaining" state, but to keep barriers independent, we defer this until all barriers // of the batch have been processed. Also, depending on whether layout transition happens, we'll either // replace the current write barriers or add to them, so accumulate to pending as well. void ResourceAccessState::ApplyBarrier(const SyncBarrier &barrier, bool layout_transition) { // For independent barriers we need to track what the new barriers and dependency chain *will* be when we're done // applying the memory barriers // NOTE: We update the write barrier if the write is in the first access scope or if there is a layout // transistion, under the theory of "most recent access". If the read/write *isn't* safe // vs. this layout transition DetectBarrierHazard should report it. We treat the layout // transistion *as* a write and in scope with the barrier (it's before visibility). if (layout_transition || InSourceScopeOrChain(barrier.src_exec_scope, barrier.src_access_scope)) { pending_write_barriers |= barrier.dst_access_scope; pending_write_dep_chain |= barrier.dst_exec_scope; } // Track layout transistion as pending as we can't modify last_write until all barriers processed pending_layout_transition |= layout_transition; if (!pending_layout_transition) { // Once we're dealing with a layout transition (which is modelled as a *write*) then the last reads/writes/chains // don't need to be tracked as we're just going to zero them. for (uint32_t read_index = 0; read_index < last_read_count; read_index++) { ReadState &access = last_reads[read_index]; // The | implements the "dependency chain" logic for this access, as the barriers field stores the second sync scope if (barrier.src_exec_scope & (access.stage | access.barriers)) { access.pending_dep_chain |= barrier.dst_exec_scope; } } } } void ResourceAccessState::ApplyPendingBarriers(const ResourceUsageTag &tag) { if (pending_layout_transition) { // SetWrite clobbers the read count, and thus we don't have to clear the read_state out. SetWrite(SYNC_IMAGE_LAYOUT_TRANSITION_BIT, tag); // Side effect notes below pending_layout_transition = false; } // Apply the accumulate execution barriers (and thus update chaining information) // for layout transition, read count is zeroed by SetWrite, so this will be skipped. for (uint32_t read_index = 0; read_index < last_read_count; read_index++) { ReadState &access = last_reads[read_index]; access.barriers |= access.pending_dep_chain; read_execution_barriers |= access.barriers; access.pending_dep_chain = 0; } // We OR in the accumulated write chain and barriers even in the case of a layout transition as SetWrite zeros them. write_dependency_chain |= pending_write_dep_chain; write_barriers |= pending_write_barriers; pending_write_dep_chain = 0; pending_write_barriers = 0; } // This should be just Bits or Index, but we don't have an invalid state for Index VkPipelineStageFlags ResourceAccessState::GetReadBarriers(const SyncStageAccessFlags &usage_bit) const { VkPipelineStageFlags barriers = 0U; for (uint32_t read_index = 0; read_index < last_read_count; read_index++) { const auto &read_access = last_reads[read_index]; if ((read_access.access & usage_bit).any()) { barriers = read_access.barriers; break; } } return barriers; } inline bool ResourceAccessState::IsRAWHazard(VkPipelineStageFlagBits usage_stage, const SyncStageAccessFlags &usage) const { assert(IsRead(usage)); // Only RAW vs. last_write if it doesn't happen-after any other read because either: // * the previous reads are not hazards, and thus last_write must be visible and available to // any reads that happen after. // * the previous reads *are* hazards to last_write, have been reported, and if that hazard is fixed // the current read will be also not be a hazard, thus reporting a hazard here adds no needed information. return last_write.any() && (0 == (read_execution_barriers & usage_stage)) && IsWriteHazard(usage); } VkPipelineStageFlags ResourceAccessState::GetOrderedStages(const SyncOrderingBarrier &ordering) const { // Whether the stage are in the ordering scope only matters if the current write is ordered VkPipelineStageFlags ordered_stages = last_read_stages & ordering.exec_scope; // Special input attachment handling as always (not encoded in exec_scop) const bool input_attachment_ordering = (ordering.access_scope & SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT).any(); if (input_attachment_ordering && input_attachment_read) { // If we have an input attachment in last_reads and input attachments are ordered we all that stage ordered_stages |= VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT; } return ordered_stages; } inline ResourceAccessState::ReadState *ResourceAccessState::GetReadStateForStage(VkPipelineStageFlagBits stage, uint32_t search_limit) { ReadState *read_state = nullptr; search_limit = std::min(search_limit, last_read_count); for (uint32_t i = 0; i < search_limit; i++) { if (last_reads[i].stage == stage) { read_state = &last_reads[i]; break; } } return read_state; } void SyncValidator::ResetCommandBufferCallback(VkCommandBuffer command_buffer) { auto *access_context = GetAccessContextNoInsert(command_buffer); if (access_context) { access_context->Reset(); } } void SyncValidator::FreeCommandBufferCallback(VkCommandBuffer command_buffer) { auto access_found = cb_access_state.find(command_buffer); if (access_found != cb_access_state.end()) { access_found->second->Reset(); cb_access_state.erase(access_found); } } void SyncValidator::ApplyGlobalBarriers(AccessContext *context, VkPipelineStageFlags src_exec_scope, VkPipelineStageFlags dst_exec_scope, SyncStageAccessFlags src_access_scope, SyncStageAccessFlags dst_access_scope, uint32_t memory_barrier_count, const VkMemoryBarrier *pMemoryBarriers, const ResourceUsageTag &tag) { ApplyBarrierOpsFunctor barriers_functor(true /* resolve */, std::min<uint32_t>(1, memory_barrier_count), tag); for (uint32_t barrier_index = 0; barrier_index < memory_barrier_count; barrier_index++) { const auto &barrier = pMemoryBarriers[barrier_index]; SyncBarrier sync_barrier(src_exec_scope, SyncStageAccess::AccessScope(src_access_scope, barrier.srcAccessMask), dst_exec_scope, SyncStageAccess::AccessScope(dst_access_scope, barrier.dstAccessMask)); barriers_functor.PushBack(sync_barrier, false); } if (0 == memory_barrier_count) { // If there are no global memory barriers, force an exec barrier barriers_functor.PushBack(SyncBarrier(src_exec_scope, 0, dst_exec_scope, 0), false); } context->ApplyGlobalBarriers(barriers_functor); } void SyncValidator::ApplyBufferBarriers(AccessContext *context, VkPipelineStageFlags src_exec_scope, const SyncStageAccessFlags &src_stage_accesses, VkPipelineStageFlags dst_exec_scope, const SyncStageAccessFlags &dst_stage_accesses, uint32_t barrier_count, const VkBufferMemoryBarrier *barriers) { for (uint32_t index = 0; index < barrier_count; index++) { auto barrier = barriers[index]; // barrier is a copy const auto *buffer = Get<BUFFER_STATE>(barrier.buffer); if (!buffer) continue; barrier.size = GetBufferWholeSize(*buffer, barrier.offset, barrier.size); const ResourceAccessRange range = MakeRange(barrier); const auto src_access_scope = AccessScope(src_stage_accesses, barrier.srcAccessMask); const auto dst_access_scope = AccessScope(dst_stage_accesses, barrier.dstAccessMask); const SyncBarrier sync_barrier(src_exec_scope, src_access_scope, dst_exec_scope, dst_access_scope); const ApplyBarrierFunctor update_action(sync_barrier, false /* layout_transition */); context->UpdateResourceAccess(*buffer, range, update_action); } } void SyncValidator::ApplyImageBarriers(AccessContext *context, VkPipelineStageFlags src_exec_scope, const SyncStageAccessFlags &src_stage_accesses, VkPipelineStageFlags dst_exec_scope, const SyncStageAccessFlags &dst_stage_accesses, uint32_t barrier_count, const VkImageMemoryBarrier *barriers, const ResourceUsageTag &tag) { for (uint32_t index = 0; index < barrier_count; index++) { const auto &barrier = barriers[index]; const auto *image = Get<IMAGE_STATE>(barrier.image); if (!image) continue; auto subresource_range = NormalizeSubresourceRange(image->createInfo, barrier.subresourceRange); bool layout_transition = barrier.oldLayout != barrier.newLayout; const auto src_access_scope = AccessScope(src_stage_accesses, barrier.srcAccessMask); const auto dst_access_scope = AccessScope(dst_stage_accesses, barrier.dstAccessMask); const SyncBarrier sync_barrier(src_exec_scope, src_access_scope, dst_exec_scope, dst_access_scope); const ApplyBarrierFunctor barrier_action(sync_barrier, layout_transition); context->UpdateResourceAccess(*image, subresource_range, barrier_action); } } bool SyncValidator::PreCallValidateCmdCopyBuffer(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkBuffer dstBuffer, uint32_t regionCount, const VkBufferCopy *pRegions) const { bool skip = false; const auto *cb_context = GetAccessContext(commandBuffer); assert(cb_context); if (!cb_context) return skip; const auto *context = cb_context->GetCurrentAccessContext(); // If we have no previous accesses, we have no hazards const auto *src_buffer = Get<BUFFER_STATE>(srcBuffer); const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer); for (uint32_t region = 0; region < regionCount; region++) { const auto &copy_region = pRegions[region]; if (src_buffer) { const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size); auto hazard = context->DetectHazard(*src_buffer, SYNC_TRANSFER_TRANSFER_READ, src_range); if (hazard.hazard) { // TODO -- add tag information to log msg when useful. skip |= LogError(srcBuffer, string_SyncHazardVUID(hazard.hazard), "vkCmdCopyBuffer: Hazard %s for srcBuffer %s, region %" PRIu32 ". Access info %s.", string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcBuffer).c_str(), region, string_UsageTag(hazard).c_str()); } } if (dst_buffer && !skip) { const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size); auto hazard = context->DetectHazard(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, dst_range); if (hazard.hazard) { skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard), "vkCmdCopyBuffer: Hazard %s for dstBuffer %s, region %" PRIu32 ". Access info %s.", string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstBuffer).c_str(), region, string_UsageTag(hazard).c_str()); } } if (skip) break; } return skip; } void SyncValidator::PreCallRecordCmdCopyBuffer(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkBuffer dstBuffer, uint32_t regionCount, const VkBufferCopy *pRegions) { auto *cb_context = GetAccessContext(commandBuffer); assert(cb_context); const auto tag = cb_context->NextCommandTag(CMD_COPYBUFFER); auto *context = cb_context->GetCurrentAccessContext(); const auto *src_buffer = Get<BUFFER_STATE>(srcBuffer); const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer); for (uint32_t region = 0; region < regionCount; region++) { const auto &copy_region = pRegions[region]; if (src_buffer) { const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size); context->UpdateAccessState(*src_buffer, SYNC_TRANSFER_TRANSFER_READ, src_range, tag); } if (dst_buffer) { const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size); context->UpdateAccessState(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, dst_range, tag); } } } bool SyncValidator::PreCallValidateCmdCopyBuffer2KHR(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2KHR *pCopyBufferInfos) const { bool skip = false; const auto *cb_context = GetAccessContext(commandBuffer); assert(cb_context); if (!cb_context) return skip; const auto *context = cb_context->GetCurrentAccessContext(); // If we have no previous accesses, we have no hazards const auto *src_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->srcBuffer); const auto *dst_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->dstBuffer); for (uint32_t region = 0; region < pCopyBufferInfos->regionCount; region++) { const auto &copy_region = pCopyBufferInfos->pRegions[region]; if (src_buffer) { const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size); auto hazard = context->DetectHazard(*src_buffer, SYNC_TRANSFER_TRANSFER_READ, src_range); if (hazard.hazard) { // TODO -- add tag information to log msg when useful. skip |= LogError(pCopyBufferInfos->srcBuffer, string_SyncHazardVUID(hazard.hazard), "vkCmdCopyBuffer2KHR(): Hazard %s for srcBuffer %s, region %" PRIu32 ". Access info %s.", string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyBufferInfos->srcBuffer).c_str(), region, string_UsageTag(hazard).c_str()); } } if (dst_buffer && !skip) { const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size); auto hazard = context->DetectHazard(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, dst_range); if (hazard.hazard) { skip |= LogError(pCopyBufferInfos->dstBuffer, string_SyncHazardVUID(hazard.hazard), "vkCmdCopyBuffer2KHR(): Hazard %s for dstBuffer %s, region %" PRIu32 ". Access info %s.", string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyBufferInfos->dstBuffer).c_str(), region, string_UsageTag(hazard).c_str()); } } if (skip) break; } return skip; } void SyncValidator::PreCallRecordCmdCopyBuffer2KHR(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2KHR *pCopyBufferInfos) { auto *cb_context = GetAccessContext(commandBuffer); assert(cb_context); const auto tag = cb_context->NextCommandTag(CMD_COPYBUFFER2KHR); auto *context = cb_context->GetCurrentAccessContext(); const auto *src_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->srcBuffer); const auto *dst_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->dstBuffer); for (uint32_t region = 0; region < pCopyBufferInfos->regionCount; region++) { const auto &copy_region = pCopyBufferInfos->pRegions[region]; if (src_buffer) { const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size); context->UpdateAccessState(*src_buffer, SYNC_TRANSFER_TRANSFER_READ, src_range, tag); } if (dst_buffer) { const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size); context->UpdateAccessState(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, dst_range, tag); } } } bool SyncValidator::PreCallValidateCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout, VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount, const VkImageCopy *pRegions) const { bool skip = false; const auto *cb_access_context = GetAccessContext(commandBuffer); assert(cb_access_context); if (!cb_access_context) return skip; const auto *context = cb_access_context->GetCurrentAccessContext(); assert(context); if (!context) return skip; const auto *src_image = Get<IMAGE_STATE>(srcImage); const auto *dst_image = Get<IMAGE_STATE>(dstImage); for (uint32_t region = 0; region < regionCount; region++) { const auto &copy_region = pRegions[region]; if (src_image) { auto hazard = context->DetectHazard(*src_image, SYNC_TRANSFER_TRANSFER_READ, copy_region.srcSubresource, copy_region.srcOffset, copy_region.extent); if (hazard.hazard) { skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard), "vkCmdCopyImage: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region, string_UsageTag(hazard).c_str()); } } if (dst_image) { VkExtent3D dst_copy_extent = GetAdjustedDestImageExtent(src_image->createInfo.format, dst_image->createInfo.format, copy_region.extent); auto hazard = context->DetectHazard(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, copy_region.dstSubresource, copy_region.dstOffset, dst_copy_extent); if (hazard.hazard) { skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard), "vkCmdCopyImage: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region, string_UsageTag(hazard).c_str()); } if (skip) break; } } return skip; } void SyncValidator::PreCallRecordCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout, VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount, const VkImageCopy *pRegions) { auto *cb_access_context = GetAccessContext(commandBuffer); assert(cb_access_context); const auto tag = cb_access_context->NextCommandTag(CMD_COPYIMAGE); auto *context = cb_access_context->GetCurrentAccessContext(); assert(context); auto *src_image = Get<IMAGE_STATE>(srcImage); auto *dst_image = Get<IMAGE_STATE>(dstImage); for (uint32_t region = 0; region < regionCount; region++) { const auto &copy_region = pRegions[region]; if (src_image) { context->UpdateAccessState(*src_image, SYNC_TRANSFER_TRANSFER_READ, copy_region.srcSubresource, copy_region.srcOffset, copy_region.extent, tag); } if (dst_image) { VkExtent3D dst_copy_extent = GetAdjustedDestImageExtent(src_image->createInfo.format, dst_image->createInfo.format, copy_region.extent); context->UpdateAccessState(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, copy_region.dstSubresource, copy_region.dstOffset, dst_copy_extent, tag); } } } bool SyncValidator::PreCallValidateCmdCopyImage2KHR(VkCommandBuffer commandBuffer, const VkCopyImageInfo2KHR *pCopyImageInfo) const { bool skip = false; const auto *cb_access_context = GetAccessContext(commandBuffer); assert(cb_access_context); if (!cb_access_context) return skip; const auto *context = cb_access_context->GetCurrentAccessContext(); assert(context); if (!context) return skip; const auto *src_image = Get<IMAGE_STATE>(pCopyImageInfo->srcImage); const auto *dst_image = Get<IMAGE_STATE>(pCopyImageInfo->dstImage); for (uint32_t region = 0; region < pCopyImageInfo->regionCount; region++) { const auto &copy_region = pCopyImageInfo->pRegions[region]; if (src_image) { auto hazard = context->DetectHazard(*src_image, SYNC_TRANSFER_TRANSFER_READ, copy_region.srcSubresource, copy_region.srcOffset, copy_region.extent); if (hazard.hazard) { skip |= LogError(pCopyImageInfo->srcImage, string_SyncHazardVUID(hazard.hazard), "vkCmdCopyImage2KHR: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyImageInfo->srcImage).c_str(), region, string_UsageTag(hazard).c_str()); } } if (dst_image) { VkExtent3D dst_copy_extent = GetAdjustedDestImageExtent(src_image->createInfo.format, dst_image->createInfo.format, copy_region.extent); auto hazard = context->DetectHazard(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, copy_region.dstSubresource, copy_region.dstOffset, dst_copy_extent); if (hazard.hazard) { skip |= LogError(pCopyImageInfo->dstImage, string_SyncHazardVUID(hazard.hazard), "vkCmdCopyImage2KHR: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyImageInfo->dstImage).c_str(), region, string_UsageTag(hazard).c_str()); } if (skip) break; } } return skip; } void SyncValidator::PreCallRecordCmdCopyImage2KHR(VkCommandBuffer commandBuffer, const VkCopyImageInfo2KHR *pCopyImageInfo) { auto *cb_access_context = GetAccessContext(commandBuffer); assert(cb_access_context); const auto tag = cb_access_context->NextCommandTag(CMD_COPYIMAGE2KHR); auto *context = cb_access_context->GetCurrentAccessContext(); assert(context); auto *src_image = Get<IMAGE_STATE>(pCopyImageInfo->srcImage); auto *dst_image = Get<IMAGE_STATE>(pCopyImageInfo->dstImage); for (uint32_t region = 0; region < pCopyImageInfo->regionCount; region++) { const auto &copy_region = pCopyImageInfo->pRegions[region]; if (src_image) { context->UpdateAccessState(*src_image, SYNC_TRANSFER_TRANSFER_READ, copy_region.srcSubresource, copy_region.srcOffset, copy_region.extent, tag); } if (dst_image) { VkExtent3D dst_copy_extent = GetAdjustedDestImageExtent(src_image->createInfo.format, dst_image->createInfo.format, copy_region.extent); context->UpdateAccessState(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, copy_region.dstSubresource, copy_region.dstOffset, dst_copy_extent, tag); } } } bool SyncValidator::PreCallValidateCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags, uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers, uint32_t bufferMemoryBarrierCount, const VkBufferMemoryBarrier *pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount, const VkImageMemoryBarrier *pImageMemoryBarriers) const { bool skip = false; const auto *cb_access_context = GetAccessContext(commandBuffer); assert(cb_access_context); if (!cb_access_context) return skip; const auto *context = cb_access_context->GetCurrentAccessContext(); assert(context); if (!context) return skip; const auto src_stage_mask = ExpandPipelineStages(cb_access_context->GetQueueFlags(), srcStageMask); const auto src_exec_scope = WithEarlierPipelineStages(src_stage_mask); auto src_stage_accesses = AccessScopeByStage(src_stage_mask); // Validate Image Layout transitions for (uint32_t index = 0; index < imageMemoryBarrierCount; index++) { const auto &barrier = pImageMemoryBarriers[index]; if (barrier.newLayout == barrier.oldLayout) continue; // Only interested in layout transitions at this point. const auto *image_state = Get<IMAGE_STATE>(barrier.image); if (!image_state) continue; const auto hazard = context->DetectImageBarrierHazard(*image_state, src_exec_scope, src_stage_accesses, barrier); if (hazard.hazard) { // PHASE1 TODO -- add tag information to log msg when useful. skip |= LogError(barrier.image, string_SyncHazardVUID(hazard.hazard), "vkCmdPipelineBarrier: Hazard %s for image barrier %" PRIu32 " %s. Access info %s.", string_SyncHazard(hazard.hazard), index, report_data->FormatHandle(barrier.image).c_str(), string_UsageTag(hazard).c_str()); } } return skip; } void SyncValidator::PreCallRecordCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags, uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers, uint32_t bufferMemoryBarrierCount, const VkBufferMemoryBarrier *pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount, const VkImageMemoryBarrier *pImageMemoryBarriers) { auto *cb_access_context = GetAccessContext(commandBuffer); assert(cb_access_context); if (!cb_access_context) return; const auto tag = cb_access_context->NextCommandTag(CMD_PIPELINEBARRIER); auto access_context = cb_access_context->GetCurrentAccessContext(); assert(access_context); if (!access_context) return; const auto src_stage_mask = ExpandPipelineStages(cb_access_context->GetQueueFlags(), srcStageMask); auto src_stage_accesses = AccessScopeByStage(src_stage_mask); const auto dst_stage_mask = ExpandPipelineStages(cb_access_context->GetQueueFlags(), dstStageMask); auto dst_stage_accesses = AccessScopeByStage(dst_stage_mask); const auto src_exec_scope = WithEarlierPipelineStages(src_stage_mask); const auto dst_exec_scope = WithLaterPipelineStages(dst_stage_mask); // These two apply barriers one at a time as the are restricted to the resource ranges specified per each barrier, // but do not update the dependency chain information (but set the "pending" state) // s.t. the order independence // of the barriers is maintained. ApplyBufferBarriers(access_context, src_exec_scope, src_stage_accesses, dst_exec_scope, dst_stage_accesses, bufferMemoryBarrierCount, pBufferMemoryBarriers); ApplyImageBarriers(access_context, src_exec_scope, src_stage_accesses, dst_exec_scope, dst_stage_accesses, imageMemoryBarrierCount, pImageMemoryBarriers, tag); // Apply the global barriers last as is it walks all memory, it can also clean up the "pending" state without requiring an // additional pass, updating the dependency chains *last* as it goes along. // This is needed to guarantee order independence of the three lists. ApplyGlobalBarriers(access_context, src_exec_scope, dst_exec_scope, src_stage_accesses, dst_stage_accesses, memoryBarrierCount, pMemoryBarriers, tag); } void SyncValidator::PostCallRecordCreateDevice(VkPhysicalDevice gpu, const VkDeviceCreateInfo *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkDevice *pDevice, VkResult result) { // The state tracker sets up the device state StateTracker::PostCallRecordCreateDevice(gpu, pCreateInfo, pAllocator, pDevice, result); // Add the callback hooks for the functions that are either broadly or deeply used and that the ValidationStateTracker // refactor would be messier without. // TODO: Find a good way to do this hooklessly. ValidationObject *device_object = GetLayerDataPtr(get_dispatch_key(*pDevice), layer_data_map); ValidationObject *validation_data = GetValidationObject(device_object->object_dispatch, LayerObjectTypeSyncValidation); SyncValidator *sync_device_state = static_cast<SyncValidator *>(validation_data); sync_device_state->SetCommandBufferResetCallback([sync_device_state](VkCommandBuffer command_buffer) -> void { sync_device_state->ResetCommandBufferCallback(command_buffer); }); sync_device_state->SetCommandBufferFreeCallback([sync_device_state](VkCommandBuffer command_buffer) -> void { sync_device_state->FreeCommandBufferCallback(command_buffer); }); } bool SyncValidator::ValidateBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin, const VkSubpassBeginInfoKHR *pSubpassBeginInfo, const char *func_name) const { bool skip = false; const auto rp_state = Get<RENDER_PASS_STATE>(pRenderPassBegin->renderPass); auto cb_context = GetAccessContext(commandBuffer); if (rp_state && cb_context) { skip |= cb_context->ValidateBeginRenderPass(*rp_state, pRenderPassBegin, pSubpassBeginInfo, func_name); } return skip; } bool SyncValidator::PreCallValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin, VkSubpassContents contents) const { bool skip = StateTracker::PreCallValidateCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents); auto subpass_begin_info = lvl_init_struct<VkSubpassBeginInfo>(); subpass_begin_info.contents = contents; skip |= ValidateBeginRenderPass(commandBuffer, pRenderPassBegin, &subpass_begin_info, "vkCmdBeginRenderPass"); return skip; } bool SyncValidator::PreCallValidateCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin, const VkSubpassBeginInfoKHR *pSubpassBeginInfo) const { bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo); skip |= ValidateBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, "vkCmdBeginRenderPass2"); return skip; } bool SyncValidator::PreCallValidateCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin, const VkSubpassBeginInfoKHR *pSubpassBeginInfo) const { bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo); skip |= ValidateBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, "vkCmdBeginRenderPass2KHR"); return skip; } void SyncValidator::PostCallRecordBeginCommandBuffer(VkCommandBuffer commandBuffer, const VkCommandBufferBeginInfo *pBeginInfo, VkResult result) { // The state tracker sets up the command buffer state StateTracker::PostCallRecordBeginCommandBuffer(commandBuffer, pBeginInfo, result); // Create/initialize the structure that trackers accesses at the command buffer scope. auto cb_access_context = GetAccessContext(commandBuffer); assert(cb_access_context); cb_access_context->Reset(); } void SyncValidator::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin, const VkSubpassBeginInfo *pSubpassBeginInfo, CMD_TYPE command) { auto cb_context = GetAccessContext(commandBuffer); if (cb_context) { cb_context->RecordBeginRenderPass(cb_context->NextCommandTag(command)); } } void SyncValidator::PostCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin, VkSubpassContents contents) { StateTracker::PostCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents); auto subpass_begin_info = lvl_init_struct<VkSubpassBeginInfo>(); subpass_begin_info.contents = contents; RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, &subpass_begin_info, CMD_BEGINRENDERPASS); } void SyncValidator::PostCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin, const VkSubpassBeginInfo *pSubpassBeginInfo) { StateTracker::PostCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo); RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2); } void SyncValidator::PostCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin, const VkSubpassBeginInfo *pSubpassBeginInfo) { StateTracker::PostCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo); RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2); } bool SyncValidator::ValidateCmdNextSubpass(VkCommandBuffer commandBuffer, const VkSubpassBeginInfoKHR *pSubpassBeginInfo, const VkSubpassEndInfoKHR *pSubpassEndInfo, const char *func_name) const { bool skip = false; auto cb_context = GetAccessContext(commandBuffer); assert(cb_context); auto cb_state = cb_context->GetCommandBufferState(); if (!cb_state) return skip; auto rp_state = cb_state->activeRenderPass; if (!rp_state) return skip; skip |= cb_context->ValidateNextSubpass(func_name); return skip; } bool SyncValidator::PreCallValidateCmdNextSubpass(VkCommandBuffer commandBuffer, VkSubpassContents contents) const { bool skip = StateTracker::PreCallValidateCmdNextSubpass(commandBuffer, contents); auto subpass_begin_info = lvl_init_struct<VkSubpassBeginInfo>(); subpass_begin_info.contents = contents; skip |= ValidateCmdNextSubpass(commandBuffer, &subpass_begin_info, nullptr, "vkCmdNextSubpass"); return skip; } bool SyncValidator::PreCallValidateCmdNextSubpass2KHR(VkCommandBuffer commandBuffer, const VkSubpassBeginInfoKHR *pSubpassBeginInfo, const VkSubpassEndInfoKHR *pSubpassEndInfo) const { bool skip = StateTracker::PreCallValidateCmdNextSubpass2KHR(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo); skip |= ValidateCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, "vkCmdNextSubpass2KHR"); return skip; } bool SyncValidator::PreCallValidateCmdNextSubpass2(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo, const VkSubpassEndInfo *pSubpassEndInfo) const { bool skip = StateTracker::PreCallValidateCmdNextSubpass2(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo); skip |= ValidateCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, "vkCmdNextSubpass2"); return skip; } void SyncValidator::RecordCmdNextSubpass(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo, const VkSubpassEndInfo *pSubpassEndInfo, CMD_TYPE command) { auto cb_context = GetAccessContext(commandBuffer); assert(cb_context); auto cb_state = cb_context->GetCommandBufferState(); if (!cb_state) return; auto rp_state = cb_state->activeRenderPass; if (!rp_state) return; cb_context->RecordNextSubpass(*rp_state, cb_context->NextCommandTag(command)); } void SyncValidator::PostCallRecordCmdNextSubpass(VkCommandBuffer commandBuffer, VkSubpassContents contents) { StateTracker::PostCallRecordCmdNextSubpass(commandBuffer, contents); auto subpass_begin_info = lvl_init_struct<VkSubpassBeginInfo>(); subpass_begin_info.contents = contents; RecordCmdNextSubpass(commandBuffer, &subpass_begin_info, nullptr, CMD_NEXTSUBPASS); } void SyncValidator::PostCallRecordCmdNextSubpass2(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo, const VkSubpassEndInfo *pSubpassEndInfo) { StateTracker::PostCallRecordCmdNextSubpass2(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo); RecordCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2); } void SyncValidator::PostCallRecordCmdNextSubpass2KHR(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo, const VkSubpassEndInfo *pSubpassEndInfo) { StateTracker::PostCallRecordCmdNextSubpass2KHR(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo); RecordCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2); } bool SyncValidator::ValidateCmdEndRenderPass(VkCommandBuffer commandBuffer, const VkSubpassEndInfoKHR *pSubpassEndInfo, const char *func_name) const { bool skip = false; auto cb_context = GetAccessContext(commandBuffer); assert(cb_context); auto cb_state = cb_context->GetCommandBufferState(); if (!cb_state) return skip; auto rp_state = cb_state->activeRenderPass; if (!rp_state) return skip; skip |= cb_context->ValidateEndRenderpass(func_name); return skip; } bool SyncValidator::PreCallValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const { bool skip = StateTracker::PreCallValidateCmdEndRenderPass(commandBuffer); skip |= ValidateCmdEndRenderPass(commandBuffer, nullptr, "vkEndRenderPass"); return skip; } bool SyncValidator::PreCallValidateCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfoKHR *pSubpassEndInfo) const { bool skip = StateTracker::PreCallValidateCmdEndRenderPass2(commandBuffer, pSubpassEndInfo); skip |= ValidateCmdEndRenderPass(commandBuffer, pSubpassEndInfo, "vkEndRenderPass2"); return skip; } bool SyncValidator::PreCallValidateCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfoKHR *pSubpassEndInfo) const { bool skip = StateTracker::PreCallValidateCmdEndRenderPass2KHR(commandBuffer, pSubpassEndInfo); skip |= ValidateCmdEndRenderPass(commandBuffer, pSubpassEndInfo, "vkEndRenderPass2KHR"); return skip; } void SyncValidator::RecordCmdEndRenderPass(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo, CMD_TYPE command) { // Resolve the all subpass contexts to the command buffer contexts auto cb_context = GetAccessContext(commandBuffer); assert(cb_context); auto cb_state = cb_context->GetCommandBufferState(); if (!cb_state) return; const auto *rp_state = cb_state->activeRenderPass.get(); if (!rp_state) return; cb_context->RecordEndRenderPass(*rp_state, cb_context->NextCommandTag(command)); } // Simple heuristic rule to detect WAW operations representing algorithmically safe or increment // updates to a resource which do not conflict at the byte level. // TODO: Revisit this rule to see if it needs to be tighter or looser // TODO: Add programatic control over suppression heuristics bool SyncValidator::SupressedBoundDescriptorWAW(const HazardResult &hazard) const { return (hazard.hazard == WRITE_AFTER_WRITE) && (FlagBit(hazard.usage_index) == hazard.prior_access); } void SyncValidator::PostCallRecordCmdEndRenderPass(VkCommandBuffer commandBuffer) { RecordCmdEndRenderPass(commandBuffer, nullptr, CMD_ENDRENDERPASS); StateTracker::PostCallRecordCmdEndRenderPass(commandBuffer); } void SyncValidator::PostCallRecordCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo) { RecordCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2); StateTracker::PostCallRecordCmdEndRenderPass2(commandBuffer, pSubpassEndInfo); } void SyncValidator::PostCallRecordCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo) { RecordCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2); StateTracker::PostCallRecordCmdEndRenderPass2KHR(commandBuffer, pSubpassEndInfo); } template <typename BufferImageCopyRegionType> bool SyncValidator::ValidateCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount, const BufferImageCopyRegionType *pRegions, CopyCommandVersion version) const { bool skip = false; const auto *cb_access_context = GetAccessContext(commandBuffer); assert(cb_access_context); if (!cb_access_context) return skip; const bool is_2khr = (version == COPY_COMMAND_VERSION_2); const char *func_name = is_2khr ? "vkCmdCopyBufferToImage2KHR()" : "vkCmdCopyBufferToImage()"; const auto *context = cb_access_context->GetCurrentAccessContext(); assert(context); if (!context) return skip; const auto *src_buffer = Get<BUFFER_STATE>(srcBuffer); const auto *dst_image = Get<IMAGE_STATE>(dstImage); for (uint32_t region = 0; region < regionCount; region++) { const auto &copy_region = pRegions[region]; if (src_buffer) { ResourceAccessRange src_range = MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, dst_image->createInfo.format)); auto hazard = context->DetectHazard(*src_buffer, SYNC_TRANSFER_TRANSFER_READ, src_range); if (hazard.hazard) { // PHASE1 TODO -- add tag information to log msg when useful. skip |= LogError(srcBuffer, string_SyncHazardVUID(hazard.hazard), "%s: Hazard %s for srcBuffer %s, region %" PRIu32 ". Access info %s.", func_name, string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcBuffer).c_str(), region, string_UsageTag(hazard).c_str()); } } if (dst_image) { auto hazard = context->DetectHazard(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, copy_region.imageSubresource, copy_region.imageOffset, copy_region.imageExtent); if (hazard.hazard) { skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard), "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", func_name, string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region, string_UsageTag(hazard).c_str()); } if (skip) break; } if (skip) break; } return skip; } bool SyncValidator::PreCallValidateCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount, const VkBufferImageCopy *pRegions) const { return ValidateCmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions, COPY_COMMAND_VERSION_1); } bool SyncValidator::PreCallValidateCmdCopyBufferToImage2KHR(VkCommandBuffer commandBuffer, const VkCopyBufferToImageInfo2KHR *pCopyBufferToImageInfo) const { return ValidateCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage, pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount, pCopyBufferToImageInfo->pRegions, COPY_COMMAND_VERSION_2); } template <typename BufferImageCopyRegionType> void SyncValidator::RecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount, const BufferImageCopyRegionType *pRegions, CopyCommandVersion version) { auto *cb_access_context = GetAccessContext(commandBuffer); assert(cb_access_context); const bool is_2khr = (version == COPY_COMMAND_VERSION_2); const CMD_TYPE cmd_type = is_2khr ? CMD_COPYBUFFERTOIMAGE2KHR : CMD_COPYBUFFERTOIMAGE; const auto tag = cb_access_context->NextCommandTag(cmd_type); auto *context = cb_access_context->GetCurrentAccessContext(); assert(context); const auto *src_buffer = Get<BUFFER_STATE>(srcBuffer); const auto *dst_image = Get<IMAGE_STATE>(dstImage); for (uint32_t region = 0; region < regionCount; region++) { const auto &copy_region = pRegions[region]; if (src_buffer) { ResourceAccessRange src_range = MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, dst_image->createInfo.format)); context->UpdateAccessState(*src_buffer, SYNC_TRANSFER_TRANSFER_READ, src_range, tag); } if (dst_image) { context->UpdateAccessState(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, copy_region.imageSubresource, copy_region.imageOffset, copy_region.imageExtent, tag); } } } void SyncValidator::PreCallRecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount, const VkBufferImageCopy *pRegions) { StateTracker::PreCallRecordCmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions); RecordCmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions, COPY_COMMAND_VERSION_1); } void SyncValidator::PreCallRecordCmdCopyBufferToImage2KHR(VkCommandBuffer commandBuffer, const VkCopyBufferToImageInfo2KHR *pCopyBufferToImageInfo) { StateTracker::PreCallRecordCmdCopyBufferToImage2KHR(commandBuffer, pCopyBufferToImageInfo); RecordCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage, pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount, pCopyBufferToImageInfo->pRegions, COPY_COMMAND_VERSION_2); } template <typename BufferImageCopyRegionType> bool SyncValidator::ValidateCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout, VkBuffer dstBuffer, uint32_t regionCount, const BufferImageCopyRegionType *pRegions, CopyCommandVersion version) const { bool skip = false; const auto *cb_access_context = GetAccessContext(commandBuffer); assert(cb_access_context); if (!cb_access_context) return skip; const bool is_2khr = (version == COPY_COMMAND_VERSION_2); const char *func_name = is_2khr ? "vkCmdCopyImageToBuffer2KHR()" : "vkCmdCopyImageToBuffer()"; const auto *context = cb_access_context->GetCurrentAccessContext(); assert(context); if (!context) return skip; const auto *src_image = Get<IMAGE_STATE>(srcImage); const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer); const auto dst_mem = (dst_buffer && !dst_buffer->sparse) ? dst_buffer->binding.mem_state->mem : VK_NULL_HANDLE; for (uint32_t region = 0; region < regionCount; region++) { const auto &copy_region = pRegions[region]; if (src_image) { auto hazard = context->DetectHazard(*src_image, SYNC_TRANSFER_TRANSFER_READ, copy_region.imageSubresource, copy_region.imageOffset, copy_region.imageExtent); if (hazard.hazard) { skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard), "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", func_name, string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region, string_UsageTag(hazard).c_str()); } } if (dst_mem) { ResourceAccessRange dst_range = MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, src_image->createInfo.format)); auto hazard = context->DetectHazard(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, dst_range); if (hazard.hazard) { skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard), "%s: Hazard %s for dstBuffer %s, region %" PRIu32 ". Access info %s.", func_name, string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstBuffer).c_str(), region, string_UsageTag(hazard).c_str()); } } if (skip) break; } return skip; } bool SyncValidator::PreCallValidateCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout, VkBuffer dstBuffer, uint32_t regionCount, const VkBufferImageCopy *pRegions) const { return ValidateCmdCopyImageToBuffer(commandBuffer, srcImage, srcImageLayout, dstBuffer, regionCount, pRegions, COPY_COMMAND_VERSION_1); } bool SyncValidator::PreCallValidateCmdCopyImageToBuffer2KHR(VkCommandBuffer commandBuffer, const VkCopyImageToBufferInfo2KHR *pCopyImageToBufferInfo) const { return ValidateCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout, pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount, pCopyImageToBufferInfo->pRegions, COPY_COMMAND_VERSION_2); } template <typename BufferImageCopyRegionType> void SyncValidator::RecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout, VkBuffer dstBuffer, uint32_t regionCount, const BufferImageCopyRegionType *pRegions, CopyCommandVersion version) { auto *cb_access_context = GetAccessContext(commandBuffer); assert(cb_access_context); const bool is_2khr = (version == COPY_COMMAND_VERSION_2); const CMD_TYPE cmd_type = is_2khr ? CMD_COPYIMAGETOBUFFER2KHR : CMD_COPYIMAGETOBUFFER; const auto tag = cb_access_context->NextCommandTag(cmd_type); auto *context = cb_access_context->GetCurrentAccessContext(); assert(context); const auto *src_image = Get<IMAGE_STATE>(srcImage); auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer); const auto dst_mem = (dst_buffer && !dst_buffer->sparse) ? dst_buffer->binding.mem_state->mem : VK_NULL_HANDLE; const VulkanTypedHandle dst_handle(dst_mem, kVulkanObjectTypeDeviceMemory); for (uint32_t region = 0; region < regionCount; region++) { const auto &copy_region = pRegions[region]; if (src_image) { context->UpdateAccessState(*src_image, SYNC_TRANSFER_TRANSFER_READ, copy_region.imageSubresource, copy_region.imageOffset, copy_region.imageExtent, tag); } if (dst_buffer) { ResourceAccessRange dst_range = MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, src_image->createInfo.format)); context->UpdateAccessState(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, dst_range, tag); } } } void SyncValidator::PreCallRecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout, VkBuffer dstBuffer, uint32_t regionCount, const VkBufferImageCopy *pRegions) { StateTracker::PreCallRecordCmdCopyImageToBuffer(commandBuffer, srcImage, srcImageLayout, dstBuffer, regionCount, pRegions); RecordCmdCopyImageToBuffer(commandBuffer, srcImage, srcImageLayout, dstBuffer, regionCount, pRegions, COPY_COMMAND_VERSION_1); } void SyncValidator::PreCallRecordCmdCopyImageToBuffer2KHR(VkCommandBuffer commandBuffer, const VkCopyImageToBufferInfo2KHR *pCopyImageToBufferInfo) { StateTracker::PreCallRecordCmdCopyImageToBuffer2KHR(commandBuffer, pCopyImageToBufferInfo); RecordCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout, pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount, pCopyImageToBufferInfo->pRegions, COPY_COMMAND_VERSION_2); } template <typename RegionType> bool SyncValidator::ValidateCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout, VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount, const RegionType *pRegions, VkFilter filter, const char *apiName) const { bool skip = false; const auto *cb_access_context = GetAccessContext(commandBuffer); assert(cb_access_context); if (!cb_access_context) return skip; const auto *context = cb_access_context->GetCurrentAccessContext(); assert(context); if (!context) return skip; const auto *src_image = Get<IMAGE_STATE>(srcImage); const auto *dst_image = Get<IMAGE_STATE>(dstImage); for (uint32_t region = 0; region < regionCount; region++) { const auto &blit_region = pRegions[region]; if (src_image) { VkOffset3D offset = {std::min(blit_region.srcOffsets[0].x, blit_region.srcOffsets[1].x), std::min(blit_region.srcOffsets[0].y, blit_region.srcOffsets[1].y), std::min(blit_region.srcOffsets[0].z, blit_region.srcOffsets[1].z)}; VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.srcOffsets[1].x - blit_region.srcOffsets[0].x)), static_cast<uint32_t>(abs(blit_region.srcOffsets[1].y - blit_region.srcOffsets[0].y)), static_cast<uint32_t>(abs(blit_region.srcOffsets[1].z - blit_region.srcOffsets[0].z))}; auto hazard = context->DetectHazard(*src_image, SYNC_TRANSFER_TRANSFER_READ, blit_region.srcSubresource, offset, extent); if (hazard.hazard) { skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard), "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", apiName, string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region, string_UsageTag(hazard).c_str()); } } if (dst_image) { VkOffset3D offset = {std::min(blit_region.dstOffsets[0].x, blit_region.dstOffsets[1].x), std::min(blit_region.dstOffsets[0].y, blit_region.dstOffsets[1].y), std::min(blit_region.dstOffsets[0].z, blit_region.dstOffsets[1].z)}; VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.dstOffsets[1].x - blit_region.dstOffsets[0].x)), static_cast<uint32_t>(abs(blit_region.dstOffsets[1].y - blit_region.dstOffsets[0].y)), static_cast<uint32_t>(abs(blit_region.dstOffsets[1].z - blit_region.dstOffsets[0].z))}; auto hazard = context->DetectHazard(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, blit_region.dstSubresource, offset, extent); if (hazard.hazard) { skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard), "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", apiName, string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region, string_UsageTag(hazard).c_str()); } if (skip) break; } } return skip; } bool SyncValidator::PreCallValidateCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout, VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount, const VkImageBlit *pRegions, VkFilter filter) const { return ValidateCmdBlitImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount, pRegions, filter, "vkCmdBlitImage"); } bool SyncValidator::PreCallValidateCmdBlitImage2KHR(VkCommandBuffer commandBuffer, const VkBlitImageInfo2KHR *pBlitImageInfo) const { return ValidateCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage, pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions, pBlitImageInfo->filter, "vkCmdBlitImage2KHR"); } template <typename RegionType> void SyncValidator::RecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout, VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount, const RegionType *pRegions, VkFilter filter, ResourceUsageTag tag) { auto *cb_access_context = GetAccessContext(commandBuffer); assert(cb_access_context); auto *context = cb_access_context->GetCurrentAccessContext(); assert(context); auto *src_image = Get<IMAGE_STATE>(srcImage); auto *dst_image = Get<IMAGE_STATE>(dstImage); for (uint32_t region = 0; region < regionCount; region++) { const auto &blit_region = pRegions[region]; if (src_image) { VkOffset3D offset = {std::min(blit_region.srcOffsets[0].x, blit_region.srcOffsets[1].x), std::min(blit_region.srcOffsets[0].y, blit_region.srcOffsets[1].y), std::min(blit_region.srcOffsets[0].z, blit_region.srcOffsets[1].z)}; VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.srcOffsets[1].x - blit_region.srcOffsets[0].x)), static_cast<uint32_t>(abs(blit_region.srcOffsets[1].y - blit_region.srcOffsets[0].y)), static_cast<uint32_t>(abs(blit_region.srcOffsets[1].z - blit_region.srcOffsets[0].z))}; context->UpdateAccessState(*src_image, SYNC_TRANSFER_TRANSFER_READ, blit_region.srcSubresource, offset, extent, tag); } if (dst_image) { VkOffset3D offset = {std::min(blit_region.dstOffsets[0].x, blit_region.dstOffsets[1].x), std::min(blit_region.dstOffsets[0].y, blit_region.dstOffsets[1].y), std::min(blit_region.dstOffsets[0].z, blit_region.dstOffsets[1].z)}; VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.dstOffsets[1].x - blit_region.dstOffsets[0].x)), static_cast<uint32_t>(abs(blit_region.dstOffsets[1].y - blit_region.dstOffsets[0].y)), static_cast<uint32_t>(abs(blit_region.dstOffsets[1].z - blit_region.dstOffsets[0].z))}; context->UpdateAccessState(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, blit_region.dstSubresource, offset, extent, tag); } } } void SyncValidator::PreCallRecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout, VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount, const VkImageBlit *pRegions, VkFilter filter) { auto *cb_access_context = GetAccessContext(commandBuffer); assert(cb_access_context); const auto tag = cb_access_context->NextCommandTag(CMD_BLITIMAGE); StateTracker::PreCallRecordCmdBlitImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount, pRegions, filter); RecordCmdBlitImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount, pRegions, filter, tag); } void SyncValidator::PreCallRecordCmdBlitImage2KHR(VkCommandBuffer commandBuffer, const VkBlitImageInfo2KHR *pBlitImageInfo) { StateTracker::PreCallRecordCmdBlitImage2KHR(commandBuffer, pBlitImageInfo); auto *cb_access_context = GetAccessContext(commandBuffer); assert(cb_access_context); const auto tag = cb_access_context->NextCommandTag(CMD_BLITIMAGE2KHR); RecordCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage, pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions, pBlitImageInfo->filter, tag); } bool SyncValidator::ValidateIndirectBuffer(const AccessContext &context, VkCommandBuffer commandBuffer, const VkDeviceSize struct_size, const VkBuffer buffer, const VkDeviceSize offset, const uint32_t drawCount, const uint32_t stride, const char *function) const { bool skip = false; if (drawCount == 0) return skip; const auto *buf_state = Get<BUFFER_STATE>(buffer); VkDeviceSize size = struct_size; if (drawCount == 1 || stride == size) { if (drawCount > 1) size *= drawCount; const ResourceAccessRange range = MakeRange(offset, size); auto hazard = context.DetectHazard(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range); if (hazard.hazard) { skip |= LogError(buf_state->buffer, string_SyncHazardVUID(hazard.hazard), "%s: Hazard %s for indirect %s in %s. Access info %s.", function, string_SyncHazard(hazard.hazard), report_data->FormatHandle(buffer).c_str(), report_data->FormatHandle(commandBuffer).c_str(), string_UsageTag(hazard).c_str()); } } else { for (uint32_t i = 0; i < drawCount; ++i) { const ResourceAccessRange range = MakeRange(offset + i * stride, size); auto hazard = context.DetectHazard(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range); if (hazard.hazard) { skip |= LogError(buf_state->buffer, string_SyncHazardVUID(hazard.hazard), "%s: Hazard %s for indirect %s in %s. Access info %s.", function, string_SyncHazard(hazard.hazard), report_data->FormatHandle(buffer).c_str(), report_data->FormatHandle(commandBuffer).c_str(), string_UsageTag(hazard).c_str()); break; } } } return skip; } void SyncValidator::RecordIndirectBuffer(AccessContext &context, const ResourceUsageTag &tag, const VkDeviceSize struct_size, const VkBuffer buffer, const VkDeviceSize offset, const uint32_t drawCount, uint32_t stride) { const auto *buf_state = Get<BUFFER_STATE>(buffer); VkDeviceSize size = struct_size; if (drawCount == 1 || stride == size) { if (drawCount > 1) size *= drawCount; const ResourceAccessRange range = MakeRange(offset, size); context.UpdateAccessState(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range, tag); } else { for (uint32_t i = 0; i < drawCount; ++i) { const ResourceAccessRange range = MakeRange(offset + i * stride, size); context.UpdateAccessState(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range, tag); } } } bool SyncValidator::ValidateCountBuffer(const AccessContext &context, VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, const char *function) const { bool skip = false; const auto *count_buf_state = Get<BUFFER_STATE>(buffer); const ResourceAccessRange range = MakeRange(offset, 4); auto hazard = context.DetectHazard(*count_buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range); if (hazard.hazard) { skip |= LogError(count_buf_state->buffer, string_SyncHazardVUID(hazard.hazard), "%s: Hazard %s for countBuffer %s in %s. Access info %s.", function, string_SyncHazard(hazard.hazard), report_data->FormatHandle(buffer).c_str(), report_data->FormatHandle(commandBuffer).c_str(), string_UsageTag(hazard).c_str()); } return skip; } void SyncValidator::RecordCountBuffer(AccessContext &context, const ResourceUsageTag &tag, VkBuffer buffer, VkDeviceSize offset) { const auto *count_buf_state = Get<BUFFER_STATE>(buffer); const ResourceAccessRange range = MakeRange(offset, 4); context.UpdateAccessState(*count_buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range, tag); } bool SyncValidator::PreCallValidateCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) const { bool skip = false; const auto *cb_access_context = GetAccessContext(commandBuffer); assert(cb_access_context); if (!cb_access_context) return skip; skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, "vkCmdDispatch"); return skip; } void SyncValidator::PreCallRecordCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) { StateTracker::PreCallRecordCmdDispatch(commandBuffer, x, y, z); auto *cb_access_context = GetAccessContext(commandBuffer); assert(cb_access_context); const auto tag = cb_access_context->NextCommandTag(CMD_DISPATCH); cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, tag); } bool SyncValidator::PreCallValidateCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) const { bool skip = false; const auto *cb_access_context = GetAccessContext(commandBuffer); assert(cb_access_context); if (!cb_access_context) return skip; const auto *context = cb_access_context->GetCurrentAccessContext(); assert(context); if (!context) return skip; skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, "vkCmdDispatchIndirect"); skip |= ValidateIndirectBuffer(*context, commandBuffer, sizeof(VkDispatchIndirectCommand), buffer, offset, 1, sizeof(VkDispatchIndirectCommand), "vkCmdDispatchIndirect"); return skip; } void SyncValidator::PreCallRecordCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) { StateTracker::PreCallRecordCmdDispatchIndirect(commandBuffer, buffer, offset); auto *cb_access_context = GetAccessContext(commandBuffer); assert(cb_access_context); const auto tag = cb_access_context->NextCommandTag(CMD_DISPATCHINDIRECT); auto *context = cb_access_context->GetCurrentAccessContext(); assert(context); cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, tag); RecordIndirectBuffer(*context, tag, sizeof(VkDispatchIndirectCommand), buffer, offset, 1, sizeof(VkDispatchIndirectCommand)); } bool SyncValidator::PreCallValidateCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount, uint32_t firstVertex, uint32_t firstInstance) const { bool skip = false; const auto *cb_access_context = GetAccessContext(commandBuffer); assert(cb_access_context); if (!cb_access_context) return skip; skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, "vkCmdDraw"); skip |= cb_access_context->ValidateDrawVertex(vertexCount, firstVertex, "vkCmdDraw"); skip |= cb_access_context->ValidateDrawSubpassAttachment("vkCmdDraw"); return skip; } void SyncValidator::PreCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount, uint32_t firstVertex, uint32_t firstInstance) { StateTracker::PreCallRecordCmdDraw(commandBuffer, vertexCount, instanceCount, firstVertex, firstInstance); auto *cb_access_context = GetAccessContext(commandBuffer); assert(cb_access_context); const auto tag = cb_access_context->NextCommandTag(CMD_DRAW); cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag); cb_access_context->RecordDrawVertex(vertexCount, firstVertex, tag); cb_access_context->RecordDrawSubpassAttachment(tag); } bool SyncValidator::PreCallValidateCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount, uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const { bool skip = false; const auto *cb_access_context = GetAccessContext(commandBuffer); assert(cb_access_context); if (!cb_access_context) return skip; skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, "vkCmdDrawIndexed"); skip |= cb_access_context->ValidateDrawVertexIndex(indexCount, firstIndex, "vkCmdDrawIndexed"); skip |= cb_access_context->ValidateDrawSubpassAttachment("vkCmdDrawIndexed"); return skip; } void SyncValidator::PreCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount, uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) { StateTracker::PreCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance); auto *cb_access_context = GetAccessContext(commandBuffer); assert(cb_access_context); const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDEXED); cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag); cb_access_context->RecordDrawVertexIndex(indexCount, firstIndex, tag); cb_access_context->RecordDrawSubpassAttachment(tag); } bool SyncValidator::PreCallValidateCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, uint32_t drawCount, uint32_t stride) const { bool skip = false; if (drawCount == 0) return skip; const auto *cb_access_context = GetAccessContext(commandBuffer); assert(cb_access_context); if (!cb_access_context) return skip; const auto *context = cb_access_context->GetCurrentAccessContext(); assert(context); if (!context) return skip; skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, "vkCmdDrawIndirect"); skip |= cb_access_context->ValidateDrawSubpassAttachment("vkCmdDrawIndirect"); skip |= ValidateIndirectBuffer(*context, commandBuffer, sizeof(VkDrawIndirectCommand), buffer, offset, drawCount, stride, "vkCmdDrawIndirect"); // TODO: For now, we validate the whole vertex buffer. It might cause some false positive. // VkDrawIndirectCommand buffer could be changed until SubmitQueue. // We will validate the vertex buffer in SubmitQueue in the future. skip |= cb_access_context->ValidateDrawVertex(UINT32_MAX, 0, "vkCmdDrawIndirect"); return skip; } void SyncValidator::PreCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, uint32_t drawCount, uint32_t stride) { StateTracker::PreCallRecordCmdDrawIndirect(commandBuffer, buffer, offset, drawCount, stride); if (drawCount == 0) return; auto *cb_access_context = GetAccessContext(commandBuffer); assert(cb_access_context); const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDIRECT); auto *context = cb_access_context->GetCurrentAccessContext(); assert(context); cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag); cb_access_context->RecordDrawSubpassAttachment(tag); RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndirectCommand), buffer, offset, drawCount, stride); // TODO: For now, we record the whole vertex buffer. It might cause some false positive. // VkDrawIndirectCommand buffer could be changed until SubmitQueue. // We will record the vertex buffer in SubmitQueue in the future. cb_access_context->RecordDrawVertex(UINT32_MAX, 0, tag); } bool SyncValidator::PreCallValidateCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, uint32_t drawCount, uint32_t stride) const { bool skip = false; if (drawCount == 0) return skip; const auto *cb_access_context = GetAccessContext(commandBuffer); assert(cb_access_context); if (!cb_access_context) return skip; const auto *context = cb_access_context->GetCurrentAccessContext(); assert(context); if (!context) return skip; skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, "vkCmdDrawIndexedIndirect"); skip |= cb_access_context->ValidateDrawSubpassAttachment("vkCmdDrawIndexedIndirect"); skip |= ValidateIndirectBuffer(*context, commandBuffer, sizeof(VkDrawIndexedIndirectCommand), buffer, offset, drawCount, stride, "vkCmdDrawIndexedIndirect"); // TODO: For now, we validate the whole index and vertex buffer. It might cause some false positive. // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue. // We will validate the index and vertex buffer in SubmitQueue in the future. skip |= cb_access_context->ValidateDrawVertexIndex(UINT32_MAX, 0, "vkCmdDrawIndexedIndirect"); return skip; } void SyncValidator::PreCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, uint32_t drawCount, uint32_t stride) { StateTracker::PreCallRecordCmdDrawIndexedIndirect(commandBuffer, buffer, offset, drawCount, stride); auto *cb_access_context = GetAccessContext(commandBuffer); assert(cb_access_context); const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDEXEDINDIRECT); auto *context = cb_access_context->GetCurrentAccessContext(); assert(context); cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag); cb_access_context->RecordDrawSubpassAttachment(tag); RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndexedIndirectCommand), buffer, offset, drawCount, stride); // TODO: For now, we record the whole index and vertex buffer. It might cause some false positive. // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue. // We will record the index and vertex buffer in SubmitQueue in the future. cb_access_context->RecordDrawVertexIndex(UINT32_MAX, 0, tag); } bool SyncValidator::ValidateCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount, uint32_t stride, const char *function) const { bool skip = false; const auto *cb_access_context = GetAccessContext(commandBuffer); assert(cb_access_context); if (!cb_access_context) return skip; const auto *context = cb_access_context->GetCurrentAccessContext(); assert(context); if (!context) return skip; skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, function); skip |= cb_access_context->ValidateDrawSubpassAttachment(function); skip |= ValidateIndirectBuffer(*context, commandBuffer, sizeof(VkDrawIndirectCommand), buffer, offset, maxDrawCount, stride, function); skip |= ValidateCountBuffer(*context, commandBuffer, countBuffer, countBufferOffset, function); // TODO: For now, we validate the whole vertex buffer. It might cause some false positive. // VkDrawIndirectCommand buffer could be changed until SubmitQueue. // We will validate the vertex buffer in SubmitQueue in the future. skip |= cb_access_context->ValidateDrawVertex(UINT32_MAX, 0, function); return skip; } bool SyncValidator::PreCallValidateCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount, uint32_t stride) const { return ValidateCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride, "vkCmdDrawIndirectCount"); } void SyncValidator::PreCallRecordCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount, uint32_t stride) { StateTracker::PreCallRecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride); auto *cb_access_context = GetAccessContext(commandBuffer); assert(cb_access_context); const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDIRECTCOUNT); auto *context = cb_access_context->GetCurrentAccessContext(); assert(context); cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag); cb_access_context->RecordDrawSubpassAttachment(tag); RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndirectCommand), buffer, offset, 1, stride); RecordCountBuffer(*context, tag, countBuffer, countBufferOffset); // TODO: For now, we record the whole vertex buffer. It might cause some false positive. // VkDrawIndirectCommand buffer could be changed until SubmitQueue. // We will record the vertex buffer in SubmitQueue in the future. cb_access_context->RecordDrawVertex(UINT32_MAX, 0, tag); } bool SyncValidator::PreCallValidateCmdDrawIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount, uint32_t stride) const { return ValidateCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride, "vkCmdDrawIndirectCountKHR"); } void SyncValidator::PreCallRecordCmdDrawIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount, uint32_t stride) { StateTracker::PreCallRecordCmdDrawIndirectCountKHR(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride); PreCallRecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride); } bool SyncValidator::PreCallValidateCmdDrawIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount, uint32_t stride) const { return ValidateCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride, "vkCmdDrawIndirectCountAMD"); } void SyncValidator::PreCallRecordCmdDrawIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount, uint32_t stride) { StateTracker::PreCallRecordCmdDrawIndirectCountAMD(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride); PreCallRecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride); } bool SyncValidator::ValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount, uint32_t stride, const char *function) const { bool skip = false; const auto *cb_access_context = GetAccessContext(commandBuffer); assert(cb_access_context); if (!cb_access_context) return skip; const auto *context = cb_access_context->GetCurrentAccessContext(); assert(context); if (!context) return skip; skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, function); skip |= cb_access_context->ValidateDrawSubpassAttachment(function); skip |= ValidateIndirectBuffer(*context, commandBuffer, sizeof(VkDrawIndexedIndirectCommand), buffer, offset, maxDrawCount, stride, function); skip |= ValidateCountBuffer(*context, commandBuffer, countBuffer, countBufferOffset, function); // TODO: For now, we validate the whole index and vertex buffer. It might cause some false positive. // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue. // We will validate the index and vertex buffer in SubmitQueue in the future. skip |= cb_access_context->ValidateDrawVertexIndex(UINT32_MAX, 0, function); return skip; } bool SyncValidator::PreCallValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount, uint32_t stride) const { return ValidateCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride, "vkCmdDrawIndexedIndirectCount"); } void SyncValidator::PreCallRecordCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount, uint32_t stride) { StateTracker::PreCallRecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride); auto *cb_access_context = GetAccessContext(commandBuffer); assert(cb_access_context); const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDEXEDINDIRECTCOUNT); auto *context = cb_access_context->GetCurrentAccessContext(); assert(context); cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag); cb_access_context->RecordDrawSubpassAttachment(tag); RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndexedIndirectCommand), buffer, offset, 1, stride); RecordCountBuffer(*context, tag, countBuffer, countBufferOffset); // TODO: For now, we record the whole index and vertex buffer. It might cause some false positive. // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue. // We will update the index and vertex buffer in SubmitQueue in the future. cb_access_context->RecordDrawVertexIndex(UINT32_MAX, 0, tag); } bool SyncValidator::PreCallValidateCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount, uint32_t stride) const { return ValidateCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride, "vkCmdDrawIndexedIndirectCountKHR"); } void SyncValidator::PreCallRecordCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount, uint32_t stride) { StateTracker::PreCallRecordCmdDrawIndexedIndirectCountKHR(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride); PreCallRecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride); } bool SyncValidator::PreCallValidateCmdDrawIndexedIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount, uint32_t stride) const { return ValidateCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride, "vkCmdDrawIndexedIndirectCountAMD"); } void SyncValidator::PreCallRecordCmdDrawIndexedIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount, uint32_t stride) { StateTracker::PreCallRecordCmdDrawIndexedIndirectCountAMD(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride); PreCallRecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride); } bool SyncValidator::PreCallValidateCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout, const VkClearColorValue *pColor, uint32_t rangeCount, const VkImageSubresourceRange *pRanges) const { bool skip = false; const auto *cb_access_context = GetAccessContext(commandBuffer); assert(cb_access_context); if (!cb_access_context) return skip; const auto *context = cb_access_context->GetCurrentAccessContext(); assert(context); if (!context) return skip; const auto *image_state = Get<IMAGE_STATE>(image); for (uint32_t index = 0; index < rangeCount; index++) { const auto &range = pRanges[index]; if (image_state) { auto hazard = context->DetectHazard(*image_state, SYNC_TRANSFER_TRANSFER_WRITE, range, {0, 0, 0}, image_state->createInfo.extent); if (hazard.hazard) { skip |= LogError(image, string_SyncHazardVUID(hazard.hazard), "vkCmdClearColorImage: Hazard %s for %s, range index %" PRIu32 ". Access info %s.", string_SyncHazard(hazard.hazard), report_data->FormatHandle(image).c_str(), index, string_UsageTag(hazard).c_str()); } } } return skip; } void SyncValidator::PreCallRecordCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout, const VkClearColorValue *pColor, uint32_t rangeCount, const VkImageSubresourceRange *pRanges) { StateTracker::PreCallRecordCmdClearColorImage(commandBuffer, image, imageLayout, pColor, rangeCount, pRanges); auto *cb_access_context = GetAccessContext(commandBuffer); assert(cb_access_context); const auto tag = cb_access_context->NextCommandTag(CMD_CLEARCOLORIMAGE); auto *context = cb_access_context->GetCurrentAccessContext(); assert(context); const auto *image_state = Get<IMAGE_STATE>(image); for (uint32_t index = 0; index < rangeCount; index++) { const auto &range = pRanges[index]; if (image_state) { context->UpdateAccessState(*image_state, SYNC_TRANSFER_TRANSFER_WRITE, range, {0, 0, 0}, image_state->createInfo.extent, tag); } } } bool SyncValidator::PreCallValidateCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout, const VkClearDepthStencilValue *pDepthStencil, uint32_t rangeCount, const VkImageSubresourceRange *pRanges) const { bool skip = false; const auto *cb_access_context = GetAccessContext(commandBuffer); assert(cb_access_context); if (!cb_access_context) return skip; const auto *context = cb_access_context->GetCurrentAccessContext(); assert(context); if (!context) return skip; const auto *image_state = Get<IMAGE_STATE>(image); for (uint32_t index = 0; index < rangeCount; index++) { const auto &range = pRanges[index]; if (image_state) { auto hazard = context->DetectHazard(*image_state, SYNC_TRANSFER_TRANSFER_WRITE, range, {0, 0, 0}, image_state->createInfo.extent); if (hazard.hazard) { skip |= LogError(image, string_SyncHazardVUID(hazard.hazard), "vkCmdClearDepthStencilImage: Hazard %s for %s, range index %" PRIu32 ". Access info %s.", string_SyncHazard(hazard.hazard), report_data->FormatHandle(image).c_str(), index, string_UsageTag(hazard).c_str()); } } } return skip; } void SyncValidator::PreCallRecordCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout, const VkClearDepthStencilValue *pDepthStencil, uint32_t rangeCount, const VkImageSubresourceRange *pRanges) { StateTracker::PreCallRecordCmdClearDepthStencilImage(commandBuffer, image, imageLayout, pDepthStencil, rangeCount, pRanges); auto *cb_access_context = GetAccessContext(commandBuffer); assert(cb_access_context); const auto tag = cb_access_context->NextCommandTag(CMD_CLEARDEPTHSTENCILIMAGE); auto *context = cb_access_context->GetCurrentAccessContext(); assert(context); const auto *image_state = Get<IMAGE_STATE>(image); for (uint32_t index = 0; index < rangeCount; index++) { const auto &range = pRanges[index]; if (image_state) { context->UpdateAccessState(*image_state, SYNC_TRANSFER_TRANSFER_WRITE, range, {0, 0, 0}, image_state->createInfo.extent, tag); } } } bool SyncValidator::PreCallValidateCmdCopyQueryPoolResults(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t firstQuery, uint32_t queryCount, VkBuffer dstBuffer, VkDeviceSize dstOffset, VkDeviceSize stride, VkQueryResultFlags flags) const { bool skip = false; const auto *cb_access_context = GetAccessContext(commandBuffer); assert(cb_access_context); if (!cb_access_context) return skip; const auto *context = cb_access_context->GetCurrentAccessContext(); assert(context); if (!context) return skip; const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer); if (dst_buffer) { const ResourceAccessRange range = MakeRange(dstOffset, stride * queryCount); auto hazard = context->DetectHazard(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, range); if (hazard.hazard) { skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard), "vkCmdCopyQueryPoolResults: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstBuffer).c_str(), string_UsageTag(hazard).c_str()); } } // TODO:Track VkQueryPool return skip; } void SyncValidator::PreCallRecordCmdCopyQueryPoolResults(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t firstQuery, uint32_t queryCount, VkBuffer dstBuffer, VkDeviceSize dstOffset, VkDeviceSize stride, VkQueryResultFlags flags) { StateTracker::PreCallRecordCmdCopyQueryPoolResults(commandBuffer, queryPool, firstQuery, queryCount, dstBuffer, dstOffset, stride, flags); auto *cb_access_context = GetAccessContext(commandBuffer); assert(cb_access_context); const auto tag = cb_access_context->NextCommandTag(CMD_COPYQUERYPOOLRESULTS); auto *context = cb_access_context->GetCurrentAccessContext(); assert(context); const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer); if (dst_buffer) { const ResourceAccessRange range = MakeRange(dstOffset, stride * queryCount); context->UpdateAccessState(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, range, tag); } // TODO:Track VkQueryPool } bool SyncValidator::PreCallValidateCmdFillBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset, VkDeviceSize size, uint32_t data) const { bool skip = false; const auto *cb_access_context = GetAccessContext(commandBuffer); assert(cb_access_context); if (!cb_access_context) return skip; const auto *context = cb_access_context->GetCurrentAccessContext(); assert(context); if (!context) return skip; const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer); if (dst_buffer) { const ResourceAccessRange range = MakeRange(*dst_buffer, dstOffset, size); auto hazard = context->DetectHazard(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, range); if (hazard.hazard) { skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard), "vkCmdFillBuffer: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstBuffer).c_str(), string_UsageTag(hazard).c_str()); } } return skip; } void SyncValidator::PreCallRecordCmdFillBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset, VkDeviceSize size, uint32_t data) { StateTracker::PreCallRecordCmdFillBuffer(commandBuffer, dstBuffer, dstOffset, size, data); auto *cb_access_context = GetAccessContext(commandBuffer); assert(cb_access_context); const auto tag = cb_access_context->NextCommandTag(CMD_FILLBUFFER); auto *context = cb_access_context->GetCurrentAccessContext(); assert(context); const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer); if (dst_buffer) { const ResourceAccessRange range = MakeRange(*dst_buffer, dstOffset, size); context->UpdateAccessState(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, range, tag); } } bool SyncValidator::PreCallValidateCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout, VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount, const VkImageResolve *pRegions) const { bool skip = false; const auto *cb_access_context = GetAccessContext(commandBuffer); assert(cb_access_context); if (!cb_access_context) return skip; const auto *context = cb_access_context->GetCurrentAccessContext(); assert(context); if (!context) return skip; const auto *src_image = Get<IMAGE_STATE>(srcImage); const auto *dst_image = Get<IMAGE_STATE>(dstImage); for (uint32_t region = 0; region < regionCount; region++) { const auto &resolve_region = pRegions[region]; if (src_image) { auto hazard = context->DetectHazard(*src_image, SYNC_TRANSFER_TRANSFER_READ, resolve_region.srcSubresource, resolve_region.srcOffset, resolve_region.extent); if (hazard.hazard) { skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard), "vkCmdResolveImage: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region, string_UsageTag(hazard).c_str()); } } if (dst_image) { auto hazard = context->DetectHazard(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, resolve_region.dstSubresource, resolve_region.dstOffset, resolve_region.extent); if (hazard.hazard) { skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard), "vkCmdResolveImage: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region, string_UsageTag(hazard).c_str()); } if (skip) break; } } return skip; } void SyncValidator::PreCallRecordCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout, VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount, const VkImageResolve *pRegions) { StateTracker::PreCallRecordCmdResolveImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount, pRegions); auto *cb_access_context = GetAccessContext(commandBuffer); assert(cb_access_context); const auto tag = cb_access_context->NextCommandTag(CMD_RESOLVEIMAGE); auto *context = cb_access_context->GetCurrentAccessContext(); assert(context); auto *src_image = Get<IMAGE_STATE>(srcImage); auto *dst_image = Get<IMAGE_STATE>(dstImage); for (uint32_t region = 0; region < regionCount; region++) { const auto &resolve_region = pRegions[region]; if (src_image) { context->UpdateAccessState(*src_image, SYNC_TRANSFER_TRANSFER_READ, resolve_region.srcSubresource, resolve_region.srcOffset, resolve_region.extent, tag); } if (dst_image) { context->UpdateAccessState(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, resolve_region.dstSubresource, resolve_region.dstOffset, resolve_region.extent, tag); } } } bool SyncValidator::PreCallValidateCmdResolveImage2KHR(VkCommandBuffer commandBuffer, const VkResolveImageInfo2KHR *pResolveImageInfo) const { bool skip = false; const auto *cb_access_context = GetAccessContext(commandBuffer); assert(cb_access_context); if (!cb_access_context) return skip; const auto *context = cb_access_context->GetCurrentAccessContext(); assert(context); if (!context) return skip; const auto *src_image = Get<IMAGE_STATE>(pResolveImageInfo->srcImage); const auto *dst_image = Get<IMAGE_STATE>(pResolveImageInfo->dstImage); for (uint32_t region = 0; region < pResolveImageInfo->regionCount; region++) { const auto &resolve_region = pResolveImageInfo->pRegions[region]; if (src_image) { auto hazard = context->DetectHazard(*src_image, SYNC_TRANSFER_TRANSFER_READ, resolve_region.srcSubresource, resolve_region.srcOffset, resolve_region.extent); if (hazard.hazard) { skip |= LogError(pResolveImageInfo->srcImage, string_SyncHazardVUID(hazard.hazard), "vkCmdResolveImage2KHR: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", string_SyncHazard(hazard.hazard), report_data->FormatHandle(pResolveImageInfo->srcImage).c_str(), region, string_UsageTag(hazard).c_str()); } } if (dst_image) { auto hazard = context->DetectHazard(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, resolve_region.dstSubresource, resolve_region.dstOffset, resolve_region.extent); if (hazard.hazard) { skip |= LogError(pResolveImageInfo->dstImage, string_SyncHazardVUID(hazard.hazard), "vkCmdResolveImage2KHR: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", string_SyncHazard(hazard.hazard), report_data->FormatHandle(pResolveImageInfo->dstImage).c_str(), region, string_UsageTag(hazard).c_str()); } if (skip) break; } } return skip; } void SyncValidator::PreCallRecordCmdResolveImage2KHR(VkCommandBuffer commandBuffer, const VkResolveImageInfo2KHR *pResolveImageInfo) { StateTracker::PreCallRecordCmdResolveImage2KHR(commandBuffer, pResolveImageInfo); auto *cb_access_context = GetAccessContext(commandBuffer); assert(cb_access_context); const auto tag = cb_access_context->NextCommandTag(CMD_RESOLVEIMAGE2KHR); auto *context = cb_access_context->GetCurrentAccessContext(); assert(context); auto *src_image = Get<IMAGE_STATE>(pResolveImageInfo->srcImage); auto *dst_image = Get<IMAGE_STATE>(pResolveImageInfo->dstImage); for (uint32_t region = 0; region < pResolveImageInfo->regionCount; region++) { const auto &resolve_region = pResolveImageInfo->pRegions[region]; if (src_image) { context->UpdateAccessState(*src_image, SYNC_TRANSFER_TRANSFER_READ, resolve_region.srcSubresource, resolve_region.srcOffset, resolve_region.extent, tag); } if (dst_image) { context->UpdateAccessState(*dst_image, SYNC_TRANSFER_TRANSFER_WRITE, resolve_region.dstSubresource, resolve_region.dstOffset, resolve_region.extent, tag); } } } bool SyncValidator::PreCallValidateCmdUpdateBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset, VkDeviceSize dataSize, const void *pData) const { bool skip = false; const auto *cb_access_context = GetAccessContext(commandBuffer); assert(cb_access_context); if (!cb_access_context) return skip; const auto *context = cb_access_context->GetCurrentAccessContext(); assert(context); if (!context) return skip; const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer); if (dst_buffer) { // VK_WHOLE_SIZE not allowed const ResourceAccessRange range = MakeRange(dstOffset, dataSize); auto hazard = context->DetectHazard(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, range); if (hazard.hazard) { skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard), "vkCmdUpdateBuffer: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstBuffer).c_str(), string_UsageTag(hazard).c_str()); } } return skip; } void SyncValidator::PreCallRecordCmdUpdateBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset, VkDeviceSize dataSize, const void *pData) { StateTracker::PreCallRecordCmdUpdateBuffer(commandBuffer, dstBuffer, dstOffset, dataSize, pData); auto *cb_access_context = GetAccessContext(commandBuffer); assert(cb_access_context); const auto tag = cb_access_context->NextCommandTag(CMD_UPDATEBUFFER); auto *context = cb_access_context->GetCurrentAccessContext(); assert(context); const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer); if (dst_buffer) { // VK_WHOLE_SIZE not allowed const ResourceAccessRange range = MakeRange(dstOffset, dataSize); context->UpdateAccessState(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, range, tag); } } bool SyncValidator::PreCallValidateCmdWriteBufferMarkerAMD(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage, VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) const { bool skip = false; const auto *cb_access_context = GetAccessContext(commandBuffer); assert(cb_access_context); if (!cb_access_context) return skip; const auto *context = cb_access_context->GetCurrentAccessContext(); assert(context); if (!context) return skip; const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer); if (dst_buffer) { const ResourceAccessRange range = MakeRange(dstOffset, 4); auto hazard = context->DetectHazard(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, range); if (hazard.hazard) { skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard), "vkCmdWriteBufferMarkerAMD: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstBuffer).c_str(), string_UsageTag(hazard).c_str()); } } return skip; } void SyncValidator::PreCallRecordCmdWriteBufferMarkerAMD(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage, VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) { StateTracker::PreCallRecordCmdWriteBufferMarkerAMD(commandBuffer, pipelineStage, dstBuffer, dstOffset, marker); auto *cb_access_context = GetAccessContext(commandBuffer); assert(cb_access_context); const auto tag = cb_access_context->NextCommandTag(CMD_WRITEBUFFERMARKERAMD); auto *context = cb_access_context->GetCurrentAccessContext(); assert(context); const auto *dst_buffer = Get<BUFFER_STATE>(dstBuffer); if (dst_buffer) { const ResourceAccessRange range = MakeRange(dstOffset, 4); context->UpdateAccessState(*dst_buffer, SYNC_TRANSFER_TRANSFER_WRITE, range, tag); } }
1
14,702
The stages are correct, but the more forgiving `kAttachmentRasterOrder` should be used, based on a review of the spec. That should give the same effect of suppressing the false positive conflict between the DEPTH R/W and resolve. > End-of-subpass multisample resolves are treated as color attachment writes for the purposes of synchronization. This applies to resolve operations for both color and depth/stencil attachments. That is, they are considered to execute in the VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT pipeline stage and their writes are synchronized with VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT. Synchronization between rendering within a subpass and any resolve operations at the end of the subpass occurs automatically, without need for explicit dependencies or pipeline barriers.
KhronosGroup-Vulkan-ValidationLayers
cpp
@@ -64,7 +64,7 @@ class AcidBasePair(object): #: Administration Substance Registration System Standard Operating Procedure guide. ACID_BASE_PAIRS = ( AcidBasePair('-OSO3H', 'OS(=O)(=O)[OH]', 'OS(=O)(=O)[O-]'), - AcidBasePair('–SO3H', '[!O]S(=O)(=O)[OH]', '[!O]S(=O)(=O)[O-]'), + AcidBasePair('--SO3H', '[!O]S(=O)(=O)[OH]', '[!O]S(=O)(=O)[O-]'), AcidBasePair('-OSO2H', 'O[SD3](=O)[OH]', 'O[SD3](=O)[O-]'), AcidBasePair('-SO2H', '[!O][SD3](=O)[OH]', '[!O][SD3](=O)[O-]'), AcidBasePair('-OPO3H2', 'OP(=O)([OH])[OH]', 'OP(=O)([OH])[O-]'),
1
# -*- coding: utf-8 -*- """ molvs.charge ~~~~~~~~~~~~ This module implements tools for manipulating charges on molecules. In particular, :class:`~molvs.charge.Reionizer`, which competitively reionizes acids such that the strongest acids ionize first, and :class:`~molvs.charge.Uncharger`, which attempts to neutralize ionized acids and bases on a molecule. :copyright: Copyright 2016 by Matt Swain. :license: MIT, see LICENSE file for more details. """ from __future__ import print_function from __future__ import unicode_literals from __future__ import division import copy import logging from rdkit import Chem from .utils import memoized_property log = logging.getLogger(__name__) class AcidBasePair(object): """An acid and its conjugate base, defined by SMARTS. A strength-ordered list of AcidBasePairs can be used to ensure the strongest acids in a molecule ionize first. """ def __init__(self, name, acid, base): """Initialize an AcidBasePair with the following parameters: :param string name: A name for this AcidBasePair. :param string acid: SMARTS pattern for the protonated acid. :param string base: SMARTS pattern for the conjugate ionized base. """ log.debug('Initializing AcidBasePair: %s', name) self.name = name self.acid_str = acid self.base_str = base @memoized_property def acid(self): log.debug('Loading AcidBasePair acid: %s', self.name) return Chem.MolFromSmarts(self.acid_str) @memoized_property def base(self): log.debug('Loading AcidBasePair base: %s', self.name) return Chem.MolFromSmarts(self.base_str) def __repr__(self): return 'AcidBasePair({!r}, {!r}, {!r})'.format(self.name, self.acid_str, self.base_str) def __str__(self): return self.name #: The default list of AcidBasePairs, sorted from strongest to weakest. This list is derived from the Food and Drug #: Administration Substance Registration System Standard Operating Procedure guide. ACID_BASE_PAIRS = ( AcidBasePair('-OSO3H', 'OS(=O)(=O)[OH]', 'OS(=O)(=O)[O-]'), AcidBasePair('–SO3H', '[!O]S(=O)(=O)[OH]', '[!O]S(=O)(=O)[O-]'), AcidBasePair('-OSO2H', 'O[SD3](=O)[OH]', 'O[SD3](=O)[O-]'), AcidBasePair('-SO2H', '[!O][SD3](=O)[OH]', '[!O][SD3](=O)[O-]'), AcidBasePair('-OPO3H2', 'OP(=O)([OH])[OH]', 'OP(=O)([OH])[O-]'), AcidBasePair('-PO3H2', '[!O]P(=O)([OH])[OH]', '[!O]P(=O)([OH])[O-]'), AcidBasePair('-CO2H', 'C(=O)[OH]', 'C(=O)[O-]'), AcidBasePair('thiophenol', 'c[SH]', 'c[S-]'), AcidBasePair('(-OPO3H)-', 'OP(=O)([O-])[OH]', 'OP(=O)([O-])[O-]'), AcidBasePair('(-PO3H)-', '[!O]P(=O)([O-])[OH]', '[!O]P(=O)([O-])[O-]'), AcidBasePair('phthalimide', 'O=C2c1ccccc1C(=O)[NH]2', 'O=C2c1ccccc1C(=O)[N-]2'), AcidBasePair('CO3H (peracetyl)', 'C(=O)O[OH]', 'C(=O)O[O-]'), AcidBasePair('alpha-carbon-hydrogen-nitro group', 'O=N(O)[CH]', 'O=N(O)[C-]'), AcidBasePair('-SO2NH2', 'S(=O)(=O)[NH2]', 'S(=O)(=O)[NH-]'), AcidBasePair('-OBO2H2', 'OB([OH])[OH]', 'OB([OH])[O-]'), AcidBasePair('-BO2H2', '[!O]B([OH])[OH]', '[!O]B([OH])[O-]'), AcidBasePair('phenol', 'c[OH]', 'c[O-]'), AcidBasePair('SH (aliphatic)', 'C[SH]', 'C[S-]'), AcidBasePair('(-OBO2H)-', 'OB([O-])[OH]', 'OB([O-])[O-]'), AcidBasePair('(-BO2H)-', '[!O]B([O-])[OH]', '[!O]B([O-])[O-]'), AcidBasePair('cyclopentadiene', 'C1=CC=C[CH2]1', 'c1ccc[cH-]1'), AcidBasePair('-CONH2', 'C(=O)[NH2]', 'C(=O)[NH-]'), AcidBasePair('imidazole', 'c1cnc[nH]1', 'c1cnc[n-]1'), AcidBasePair('-OH (aliphatic alcohol)', '[CX4][OH]', '[CX4][O-]'), AcidBasePair('alpha-carbon-hydrogen-keto group', 'O=C([!O])[C!H0+0]', 'O=C([!O])[C-]'), AcidBasePair('alpha-carbon-hydrogen-acetyl ester group', 'OC(=O)[C!H0+0]', 'OC(=O)[C-]'), AcidBasePair('sp carbon hydrogen', 'C#[CH]', 'C#[C-]'), AcidBasePair('alpha-carbon-hydrogen-sulfone group', 'CS(=O)(=O)[C!H0+0]', 'CS(=O)(=O)[C-]'), AcidBasePair('alpha-carbon-hydrogen-sulfoxide group', 'C[SD3](=O)[C!H0+0]', 'C[SD3](=O)[C-]'), AcidBasePair('-NH2', '[CX4][NH2]', '[CX4][NH-]'), AcidBasePair('benzyl hydrogen', 'c[CX4H2]', 'c[CX3H-]'), AcidBasePair('sp2-carbon hydrogen', '[CX3]=[CX3!H0+0]', '[CX3]=[CX2-]'), AcidBasePair('sp3-carbon hydrogen', '[CX4!H0+0]', '[CX3-]'), ) class ChargeCorrection(object): """An atom that should have a certain charge applied, defined by a SMARTS pattern.""" def __init__(self, name, smarts, charge): """Initialize a ChargeCorrection with the following parameters: :param string name: A name for this ForcedAtomCharge. :param string smarts: SMARTS pattern to match. Charge is applied to the first atom. :param int charge: The charge to apply. """ log.debug('Initializing ChargeCorrection: %s', name) self.name = name self.smarts_str = smarts self.charge = charge @memoized_property def smarts(self): log.debug('Loading ChargeCorrection smarts: %s', self.name) return Chem.MolFromSmarts(self.smarts_str) def __repr__(self): return 'ChargeCorrection({!r}, {!r}, {!r})'.format(self.name, self.smarts_str, self.charge) def __str__(self): return self.name #: The default list of ChargeCorrections. CHARGE_CORRECTIONS = ( ChargeCorrection('[Li,Na,K]', '[Li,Na,K;X0+0]', 1), ChargeCorrection('[Mg,Ca]', '[Mg,Ca;X0+0]', 2), ChargeCorrection('[Cl]', '[Cl;X0+0]', -1), # TODO: Extend to other incorrectly charged atoms ) class Reionizer(object): """A class to fix charges and reionize a molecule such that the strongest acids ionize first.""" def __init__(self, acid_base_pairs=ACID_BASE_PAIRS, charge_corrections=CHARGE_CORRECTIONS): """Initialize a Reionizer with the following parameter: :param acid_base_pairs: A list of :class:`AcidBasePairs <molvs.charge.AcidBasePair>` to reionize, sorted from strongest to weakest. :param charge_corrections: A list of :class:`ChargeCorrections <molvs.charge.ChargeCorrection>`. """ log.debug('Initializing Reionizer') self.acid_base_pairs = acid_base_pairs self.charge_corrections = charge_corrections def __call__(self, mol): """Calling a Reionizer instance like a function is the same as calling its reionize(mol) method.""" return self.reionize(mol) def reionize(self, mol): """Enforce charges on certain atoms, then perform competitive reionization. First, charge corrections are applied to ensure, for example, that free metals are correctly ionized. Then, if a molecule with multiple acid groups is partially ionized, ensure the strongest acids ionize first. The algorithm works as follows: - Use SMARTS to find the strongest protonated acid and the weakest ionized acid. - If the ionized acid is weaker than the protonated acid, swap proton and repeat. :param mol: The molecule to reionize. :type mol: :rdkit:`Mol <Chem.rdchem.Mol-class.html>` :return: The reionized molecule. :rtype: :rdkit:`Mol <Chem.rdchem.Mol-class.html>` """ log.debug('Running Reionizer') start_charge = Chem.GetFormalCharge(mol) # Apply forced charge corrections for cc in self.charge_corrections: for match in mol.GetSubstructMatches(cc.smarts): atom = mol.GetAtomWithIdx(match[0]) log.info('Applying charge correction %s (%s %+d)', cc.name, atom.GetSymbol(), cc.charge) atom.SetFormalCharge(cc.charge) current_charge = Chem.GetFormalCharge(mol) charge_diff = Chem.GetFormalCharge(mol) - start_charge # If molecule is now neutral, assume everything is now fixed # But otherwise, if charge has become more positive, look for additional protonated acid groups to ionize if not current_charge == 0: while charge_diff > 0: ppos, poccur = self._strongest_protonated(mol) if ppos is None: break log.info('Ionizing %s to balance previous charge corrections', self.acid_base_pairs[ppos].name) patom = mol.GetAtomWithIdx(poccur[-1]) patom.SetFormalCharge(patom.GetFormalCharge() - 1) if patom.GetNumExplicitHs() > 0: patom.SetNumExplicitHs(patom.GetNumExplicitHs() - 1) # else: patom.UpdatePropertyCache() charge_diff -= 1 already_moved = set() while True: ppos, poccur = self._strongest_protonated(mol) ipos, ioccur = self._weakest_ionized(mol) if ioccur and poccur and ppos < ipos: if poccur[-1] == ioccur[-1]: # Bad! H wouldn't be moved, resulting in infinite loop. log.warning('Aborted reionization due to unexpected situation') break key = tuple(sorted([poccur[-1], ioccur[-1]])) if key in already_moved: log.warning('Aborting reionization to avoid infinite loop due to it being ambiguous where to put a Hydrogen') break already_moved.add(key) log.info('Moved proton from %s to %s', self.acid_base_pairs[ppos].name, self.acid_base_pairs[ipos].name) # Remove hydrogen from strongest protonated patom = mol.GetAtomWithIdx(poccur[-1]) patom.SetFormalCharge(patom.GetFormalCharge() - 1) # If no implicit Hs to autoremove, and at least 1 explicit H to remove, reduce explicit count by 1 if patom.GetNumImplicitHs() == 0 and patom.GetNumExplicitHs() > 0: patom.SetNumExplicitHs(patom.GetNumExplicitHs() - 1) # TODO: Remove any chiral label on patom? patom.UpdatePropertyCache() # Add hydrogen to weakest ionized iatom = mol.GetAtomWithIdx(ioccur[-1]) iatom.SetFormalCharge(iatom.GetFormalCharge() + 1) # Increase explicit H count if no implicit, or aromatic N or P, or non default valence state if (iatom.GetNoImplicit() or ((patom.GetAtomicNum() == 7 or patom.GetAtomicNum() == 15) and patom.GetIsAromatic()) or iatom.GetTotalValence() not in list(Chem.GetPeriodicTable().GetValenceList(iatom.GetAtomicNum()))): iatom.SetNumExplicitHs(iatom.GetNumExplicitHs() + 1) iatom.UpdatePropertyCache() else: break # TODO: Canonical ionization position if multiple equivalent positions? Chem.SanitizeMol(mol) return mol def _strongest_protonated(self, mol): for position, pair in enumerate(self.acid_base_pairs): for occurrence in mol.GetSubstructMatches(pair.acid): return position, occurrence return None, None def _weakest_ionized(self, mol): for position, pair in enumerate(reversed(self.acid_base_pairs)): for occurrence in mol.GetSubstructMatches(pair.base): return len(self.acid_base_pairs) - position - 1, occurrence return None, None class Uncharger(object): """Class for neutralizing ionized acids and bases. This class uncharges molecules by adding and/or removing hydrogens. For zwitterions, hydrogens are moved to eliminate charges where possible. However, in cases where there is a positive charge that is not neutralizable, an attempt is made to also preserve the corresponding negative charge. The method is derived from the neutralise module in `Francis Atkinson's standardiser tool <https://github.com/flatkinson/standardiser>`_, which is released under the Apache License v2.0. """ def __init__(self): log.debug('Initializing Uncharger') #: Neutralizable positive charge (with hydrogens attached) self._pos_h = Chem.MolFromSmarts('[+!H0!$(*~[-])]') #: Non-neutralizable positive charge (no hydrogens attached) self._pos_quat = Chem.MolFromSmarts('[+H0!$(*~[-])]') #: Negative charge, not bonded to a positive charge with no hydrogens self._neg = Chem.MolFromSmarts('[-!$(*~[+H0])]') #: Negative oxygen bonded to [C,P,S]=O, negative aromatic nitrogen? self._neg_acid = Chem.MolFromSmarts('[$([O-][C,P,S]=O),$([n-]1nnnc1),$(n1[n-]nnc1)]') def __call__(self, mol): """Calling an Uncharger instance like a function is the same as calling its uncharge(mol) method.""" return self.uncharge(mol) def uncharge(self, mol): """Neutralize molecule by adding/removing hydrogens. Attempts to preserve zwitterions. :param mol: The molecule to uncharge. :type mol: :rdkit:`Mol <Chem.rdchem.Mol-class.html>` :return: The uncharged molecule. :rtype: :rdkit:`Mol <Chem.rdchem.Mol-class.html>` """ log.debug('Running Uncharger') mol = copy.deepcopy(mol) # Get atom ids for matches p = [x[0] for x in mol.GetSubstructMatches(self._pos_h)] q = [x[0] for x in mol.GetSubstructMatches(self._pos_quat)] n = [x[0] for x in mol.GetSubstructMatches(self._neg)] a = [x[0] for x in mol.GetSubstructMatches(self._neg_acid)] # Neutralize negative charges if q: # Surplus negative charges more than non-neutralizable positive charges neg_surplus = len(n) - len(q) if a and neg_surplus > 0: # zwitterion with more negative charges than quaternary positive centres while neg_surplus > 0 and a: # Add hydrogen to first negative acid atom, increase formal charge # Until quaternary positive == negative total or no more negative acid atom = mol.GetAtomWithIdx(a.pop(0)) atom.SetNumExplicitHs(atom.GetNumExplicitHs() + 1) atom.SetFormalCharge(atom.GetFormalCharge() + 1) neg_surplus -= 1 log.info('Removed negative charge') else: # for atom in [mol.GetAtomWithIdx(x) for x in n]: while atom.GetFormalCharge() < 0: atom.SetNumExplicitHs(atom.GetNumExplicitHs() + 1) atom.SetFormalCharge(atom.GetFormalCharge() + 1) log.info('Removed negative charge') # Neutralize positive charges for atom in [mol.GetAtomWithIdx(x) for x in p]: # Remove hydrogen and reduce formal change until neutral or no more hydrogens while atom.GetFormalCharge() > 0 and atom.GetNumExplicitHs() > 0: atom.SetNumExplicitHs(atom.GetNumExplicitHs() - 1) atom.SetFormalCharge(atom.GetFormalCharge() - 1) log.info('Removed positive charge') return mol
1
18,817
To be consistent, I think it should actually just be a single `-`
rdkit-rdkit
cpp
@@ -6,6 +6,7 @@ import yaml from datetime import datetime from listenbrainz.utils import escape, convert_to_unix_timestamp +from flask import current_app def flatten_dict(d, seperator='', parent_key=''): """
1
# coding=utf-8 import calendar import time import ujson import yaml from datetime import datetime from listenbrainz.utils import escape, convert_to_unix_timestamp def flatten_dict(d, seperator='', parent_key=''): """ Flattens a nested dictionary structure into a single dict. Args: d: the dict to be flattened seperator: the seperator used in keys in the flattened dict parent_key: the key that is prefixed to all keys generated during flattening Returns: Flattened dict with keys such as key1.key2 """ result = [] for key, value in d.items(): new_key = "{}{}{}".format(parent_key, seperator, str(key)) if isinstance(value, dict): result.extend(list(flatten_dict(value, '.', new_key).items())) else: result.append((new_key, value)) return dict(result) class Listen(object): """ Represents a listen object """ # keys that we use ourselves for private usage PRIVATE_KEYS = ( 'inserted_timestamp', ) # keys in additional_info that we support explicitly and are not superfluous SUPPORTED_KEYS = ( 'artist_mbids', 'release_group_mbid', 'release_mbid', 'recording_mbid', 'track_mbid', 'work_mbids', 'tracknumber', 'isrc', 'spotify_id', 'tags', 'artist_msid', 'release_msid', 'recording_msid', ) TOP_LEVEL_KEYS = ( 'time', 'user_name', 'artist_name', 'track_name', 'release_name', ) def __init__(self, user_id=None, user_name=None, timestamp=None, artist_msid=None, release_msid=None, recording_msid=None, dedup_tag=0, inserted_timestamp=None, data=None): self.user_id = user_id self.user_name = user_name # determine the type of timestamp and do the right thing if isinstance(timestamp, int) or isinstance(timestamp, float): self.ts_since_epoch = int(timestamp) self.timestamp = datetime.utcfromtimestamp(self.ts_since_epoch) else: if timestamp: self.timestamp = timestamp self.ts_since_epoch = calendar.timegm(self.timestamp.utctimetuple()) else: self.timestamp = 0 self.ts_since_epoch = 0 self.artist_msid = artist_msid self.release_msid = release_msid self.recording_msid = recording_msid self.dedup_tag = dedup_tag self.inserted_timestamp = inserted_timestamp if data is None: self.data = {'additional_info': {}} else: try: data['additional_info'] = flatten_dict(data['additional_info']) except TypeError: # TypeError may occur here because PostgresListenStore passes strings # to data sometimes. If that occurs, we don't need to do anything. pass self.data = data @classmethod def from_json(cls, j): """Factory to make Listen() objects from a dict""" return cls( user_id=j.get('user_id'), user_name=j.get('user_name', ''), timestamp=datetime.utcfromtimestamp(float(j['listened_at'])), artist_msid=j['track_metadata']['additional_info'].get('artist_msid'), release_msid=j['track_metadata']['additional_info'].get('release_msid'), recording_msid=j.get('recording_msid'), dedup_tag=j.get('dedup_tag', 0), data=j.get('track_metadata') ) @classmethod def from_influx(cls, row): """ Factory to make Listen objects from an influx row """ def convert_comma_seperated_string_to_list(string): if not string: return [] return [val for val in string.split(',')] t = convert_to_unix_timestamp(row['time']) data = { 'release_msid': row.get('release_msid'), 'release_mbid': row.get('release_mbid'), 'recording_mbid': row.get('recording_mbid'), 'release_group_mbid': row.get('release_group_mbid'), 'artist_mbids': convert_comma_seperated_string_to_list(row.get('artist_mbids', '')), 'tags': convert_comma_seperated_string_to_list(row.get('tags', '')), 'work_mbids': convert_comma_seperated_string_to_list(row.get('work_mbids', '')), 'isrc': row.get('isrc'), 'spotify_id': row.get('spotify_id'), 'tracknumber': row.get('tracknumber'), 'track_mbid': row.get('track_mbid'), } # The influx row can contain many fields that are user-generated. # We only need to add those fields which have some value in them to additional_info. # Also, we need to make sure that we don't add fields like time, user_name etc. into # the additional_info. for key, value in row.items(): if key not in data and key not in Listen.TOP_LEVEL_KEYS + Listen.PRIVATE_KEYS and value is not None: try: value = ujson.loads(value) data[key] = value continue except (ValueError, TypeError): pass # there are some lists in the database that were converted to string # via str(list) so they can't be loaded via json. # Example: "['Blank & Jones']" # However, yaml parses them safely and correctly try: value = yaml.safe_load(value) data[key] = value continue except ValueError: pass data[key] = value return cls( timestamp=t, user_name=row.get('user_name'), artist_msid=row.get('artist_msid'), recording_msid=row.get('recording_msid'), release_msid=row.get('release_msid'), inserted_timestamp=row.get('inserted_timestamp'), data={ 'additional_info': data, 'artist_name': row.get('artist_name'), 'track_name': row.get('track_name'), 'release_name': row.get('release_name'), } ) def to_api(self): """ Converts listen into the format in which listens are returned in the payload by the api on get_listen requests Returns: dict with fields 'track_metadata', 'listened_at' and 'recording_msid' """ track_metadata = self.data.copy() track_metadata['additional_info']['artist_msid'] = self.artist_msid track_metadata['additional_info']['release_msid'] = self.release_msid data = { 'track_metadata': track_metadata, 'listened_at': self.ts_since_epoch, 'recording_msid': self.recording_msid, } return data def to_json(self): return { 'user_id': self.user_id, 'user_name': self.user_name, 'timestamp': self.timestamp, 'track_metadata': self.data, 'recording_msid': self.recording_msid } def to_influx(self, measurement): """ Converts listen into dict that can be submitted to influx directly. Returns: a dict with appropriate values of measurement, time, tags and fields """ data = { 'measurement' : measurement, 'time' : self.ts_since_epoch, 'fields' : { 'user_name' : escape(self.user_name), 'artist_name' : self.data['artist_name'], 'artist_msid' : self.artist_msid, 'artist_mbids' : ",".join(self.data['additional_info'].get('artist_mbids', [])), 'release_name' : self.data.get('release_name', ''), 'release_msid' : self.release_msid, 'release_mbid' : self.data['additional_info'].get('release_mbid', ''), 'track_name' : self.data['track_name'], 'recording_msid' : self.recording_msid, 'recording_mbid' : self.data['additional_info'].get('recording_mbid', ''), 'tags' : ",".join(self.data['additional_info'].get('tags', [])), 'release_group_mbid': self.data['additional_info'].get('release_group_mbid', ''), 'track_mbid': self.data['additional_info'].get('track_mbid', ''), 'work_mbids': ','.join(self.data['additional_info'].get('work_mbids', [])), 'tracknumber': self.data['additional_info'].get('tracknumber', ''), 'isrc': self.data['additional_info'].get('isrc', ''), 'spotify_id': self.data['additional_info'].get('spotify_id', ''), 'inserted_timestamp': int(time.time()), } } # if we need a dedup tag, then add it to the row if self.dedup_tag > 0: data['tags'] = {'dedup_tag': self.dedup_tag} # add the user generated keys present in additional info to fields for key, value in self.data['additional_info'].items(): if key in Listen.PRIVATE_KEYS: continue if key not in Listen.SUPPORTED_KEYS: data['fields'][key] = ujson.dumps(value) return data def validate(self): return (self.user_id is not None and self.timestamp is not None and self.artist_msid is not None and self.recording_msid is not None and self.data is not None) @property def date(self): return self.timestamp def __repr__(self): return str(self).encode("utf-8") def __unicode__(self): return "<Listen: user_name: %s, time: %s, artist_msid: %s, release_msid: %s, recording_msid: %s, artist_name: %s, track_name: %s>" % \ (self.user_name, self.ts_since_epoch, self.artist_msid, self.release_msid, self.recording_msid, self.data['artist_name'], self.data['track_name'])
1
15,135
this seems extraneous.
metabrainz-listenbrainz-server
py
@@ -795,7 +795,7 @@ func (s *Suite) Define() { By("Sanity-check the issued Certificate") err = f.Helper().ValidateCertificate(f.Namespace.Name, "testcert", validations...) Expect(err).NotTo(HaveOccurred()) - }, featureset.OnlySAN) + }, featureset.OnlySAN, featureset.LongDomainFeatureSet) s.it(f, "should allow updating an existing certificate with a new DNS Name", func(issuerRef cmmeta.ObjectReference) { testCertificate := &cmapi.Certificate{
1
/* Copyright 2020 The cert-manager Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package certificates import ( "context" "time" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" "k8s.io/client-go/util/retry" cmapi "github.com/jetstack/cert-manager/pkg/apis/certmanager/v1" cmmeta "github.com/jetstack/cert-manager/pkg/apis/meta/v1" "github.com/jetstack/cert-manager/pkg/util" "github.com/jetstack/cert-manager/pkg/util/pki" "github.com/jetstack/cert-manager/test/e2e/framework" "github.com/jetstack/cert-manager/test/e2e/framework/helper/featureset" "github.com/jetstack/cert-manager/test/e2e/framework/helper/validation" "github.com/jetstack/cert-manager/test/e2e/framework/helper/validation/certificates" e2eutil "github.com/jetstack/cert-manager/test/e2e/util" ) // Defines simple conformance tests that can be run against any issuer type. // If Complete has not been called on this Suite before Define, it will be // automatically called. func (s *Suite) Define() { Describe("with issuer type "+s.Name, func() { ctx := context.Background() f := framework.NewDefaultFramework("certificates") sharedIPAddress := "127.0.0.1" // Wrap this in a BeforeEach else flags will not have been parsed and // f.Config will not be populated at the time that this code is run. BeforeEach(func() { if s.completed { return } s.complete(f) if s.UseIngressIPAddress { sharedIPAddress = f.Config.Addons.ACMEServer.IngressIP } }) By("Running test suite with the following unsupported features: " + s.UnsupportedFeatures.String()) s.it(f, "should issue a basic, defaulted certificate for a single distinct DNS Name", func(issuerRef cmmeta.ObjectReference) { testCertificate := &cmapi.Certificate{ ObjectMeta: metav1.ObjectMeta{ Name: "testcert", Namespace: f.Namespace.Name, }, Spec: cmapi.CertificateSpec{ SecretName: "testcert-tls", IssuerRef: issuerRef, DNSNames: []string{e2eutil.RandomSubdomain(s.DomainSuffix)}, }, } By("Creating a Certificate") err := f.CRClient.Create(ctx, testCertificate) Expect(err).NotTo(HaveOccurred()) By("Waiting for the Certificate to be issued...") _, err = f.Helper().WaitForCertificateReady(f.Namespace.Name, "testcert", time.Minute*5) Expect(err).NotTo(HaveOccurred()) By("Validating the issued Certificate...") err = f.Helper().ValidateCertificate(f.Namespace.Name, "testcert", validation.CertificateSetForUnsupportedFeatureSet(s.UnsupportedFeatures)...) Expect(err).NotTo(HaveOccurred()) }, featureset.OnlySAN) s.it(f, "should issue a CA certificate with the CA basicConstraint set", func(issuerRef cmmeta.ObjectReference) { testCertificate := &cmapi.Certificate{ ObjectMeta: metav1.ObjectMeta{ Name: "testcert", Namespace: f.Namespace.Name, }, Spec: cmapi.CertificateSpec{ SecretName: "testcert-tls", IsCA: true, IssuerRef: issuerRef, DNSNames: []string{e2eutil.RandomSubdomain(s.DomainSuffix)}, }, } By("Creating a Certificate") err := f.CRClient.Create(ctx, testCertificate) Expect(err).NotTo(HaveOccurred()) By("Waiting for the Certificate to be issued...") _, err = f.Helper().WaitForCertificateReady(f.Namespace.Name, "testcert", time.Minute*5) Expect(err).NotTo(HaveOccurred()) By("Validating the issued Certificate...") err = f.Helper().ValidateCertificate(f.Namespace.Name, "testcert", validation.CertificateSetForUnsupportedFeatureSet(s.UnsupportedFeatures)...) Expect(err).NotTo(HaveOccurred()) }, featureset.IssueCAFeature) s.it(f, "should issue an ECDSA, defaulted certificate for a single distinct DNS Name", func(issuerRef cmmeta.ObjectReference) { testCertificate := &cmapi.Certificate{ ObjectMeta: metav1.ObjectMeta{ Name: "testcert", Namespace: f.Namespace.Name, }, Spec: cmapi.CertificateSpec{ SecretName: "testcert-tls", PrivateKey: &cmapi.CertificatePrivateKey{ Algorithm: cmapi.ECDSAKeyAlgorithm, }, DNSNames: []string{e2eutil.RandomSubdomain(s.DomainSuffix)}, IssuerRef: issuerRef, }, } By("Creating a Certificate") err := f.CRClient.Create(ctx, testCertificate) Expect(err).NotTo(HaveOccurred()) By("Waiting for the Certificate to be issued...") _, err = f.Helper().WaitForCertificateReady(f.Namespace.Name, "testcert", time.Minute*5) Expect(err).NotTo(HaveOccurred()) By("Validating the issued Certificate...") err = f.Helper().ValidateCertificate(f.Namespace.Name, "testcert", validation.CertificateSetForUnsupportedFeatureSet(s.UnsupportedFeatures)...) Expect(err).NotTo(HaveOccurred()) }, featureset.ECDSAFeature, featureset.OnlySAN) s.it(f, "should issue an Ed25519, defaulted certificate for a single distinct DNS Name", func(issuerRef cmmeta.ObjectReference) { testCertificate := &cmapi.Certificate{ ObjectMeta: metav1.ObjectMeta{ Name: "testcert", Namespace: f.Namespace.Name, }, Spec: cmapi.CertificateSpec{ SecretName: "testcert-tls", PrivateKey: &cmapi.CertificatePrivateKey{ Algorithm: cmapi.Ed25519KeyAlgorithm, }, DNSNames: []string{e2eutil.RandomSubdomain(s.DomainSuffix)}, IssuerRef: issuerRef, }, } By("Creating a Certificate") err := f.CRClient.Create(ctx, testCertificate) Expect(err).NotTo(HaveOccurred()) By("Waiting for the Certificate to be issued...") _, err = f.Helper().WaitForCertificateReady(f.Namespace.Name, "testcert", time.Minute*5) Expect(err).NotTo(HaveOccurred()) By("Validating the issued Certificate...") err = f.Helper().ValidateCertificate(f.Namespace.Name, "testcert", validation.CertificateSetForUnsupportedFeatureSet(s.UnsupportedFeatures)...) Expect(err).NotTo(HaveOccurred()) }, featureset.OnlySAN, featureset.Ed25519FeatureSet) s.it(f, "should issue a basic, defaulted certificate for a single Common Name", func(issuerRef cmmeta.ObjectReference) { // Some issuers use the CN to define the cert's "ID" // if one cert manages to be in an error state in the issuer it might throw an error // this makes the CN more unique cn := "test-common-name-" + util.RandStringRunes(10) testCertificate := &cmapi.Certificate{ ObjectMeta: metav1.ObjectMeta{ Name: "testcert", Namespace: f.Namespace.Name, }, Spec: cmapi.CertificateSpec{ SecretName: "testcert-tls", IssuerRef: issuerRef, CommonName: cn, }, } By("Creating a Certificate") err := f.CRClient.Create(ctx, testCertificate) Expect(err).NotTo(HaveOccurred()) By("Waiting for the Certificate to be issued...") _, err = f.Helper().WaitForCertificateReady(f.Namespace.Name, "testcert", time.Minute*5) Expect(err).NotTo(HaveOccurred()) By("Validating the issued Certificate...") err = f.Helper().ValidateCertificate(f.Namespace.Name, "testcert", validation.CertificateSetForUnsupportedFeatureSet(s.UnsupportedFeatures)...) Expect(err).NotTo(HaveOccurred()) }, featureset.CommonNameFeature) s.it(f, "should issue an ECDSA, defaulted certificate for a single Common Name", func(issuerRef cmmeta.ObjectReference) { // Some issuers use the CN to define the cert's "ID" // if one cert manages to be in an error state in the issuer it might throw an error // this makes the CN more unique cn := "test-common-name-" + util.RandStringRunes(10) testCertificate := &cmapi.Certificate{ ObjectMeta: metav1.ObjectMeta{ Name: "testcert", Namespace: f.Namespace.Name, }, Spec: cmapi.CertificateSpec{ SecretName: "testcert-tls", PrivateKey: &cmapi.CertificatePrivateKey{ Algorithm: cmapi.ECDSAKeyAlgorithm, }, CommonName: cn, IssuerRef: issuerRef, }, } By("Creating a Certificate") err := f.CRClient.Create(ctx, testCertificate) Expect(err).NotTo(HaveOccurred()) By("Waiting for the Certificate to be issued...") _, err = f.Helper().WaitForCertificateReady(f.Namespace.Name, "testcert", time.Minute*5) Expect(err).NotTo(HaveOccurred()) By("Validating the issued Certificate...") err = f.Helper().ValidateCertificate(f.Namespace.Name, "testcert", validation.CertificateSetForUnsupportedFeatureSet(s.UnsupportedFeatures)...) Expect(err).NotTo(HaveOccurred()) }, featureset.ECDSAFeature, featureset.CommonNameFeature) s.it(f, "should issue an Ed25519, defaulted certificate for a single Common Name", func(issuerRef cmmeta.ObjectReference) { // Some issuers use the CN to define the cert's "ID" // if one cert manages to be in an error state in the issuer it might throw an error // this makes the CN more unique cn := "test-common-name-" + util.RandStringRunes(10) testCertificate := &cmapi.Certificate{ ObjectMeta: metav1.ObjectMeta{ Name: "testcert", Namespace: f.Namespace.Name, }, Spec: cmapi.CertificateSpec{ SecretName: "testcert-tls", PrivateKey: &cmapi.CertificatePrivateKey{ Algorithm: cmapi.Ed25519KeyAlgorithm, }, CommonName: cn, IssuerRef: issuerRef, }, } By("Creating a Certificate") err := f.CRClient.Create(ctx, testCertificate) Expect(err).NotTo(HaveOccurred()) By("Waiting for the Certificate to be issued...") _, err = f.Helper().WaitForCertificateReady(f.Namespace.Name, "testcert", time.Minute*5) Expect(err).NotTo(HaveOccurred()) By("Validating the issued Certificate...") err = f.Helper().ValidateCertificate(f.Namespace.Name, "testcert", validation.CertificateSetForUnsupportedFeatureSet(s.UnsupportedFeatures)...) Expect(err).NotTo(HaveOccurred()) }, featureset.Ed25519FeatureSet, featureset.CommonNameFeature) s.it(f, "should issue a certificate that defines an IP Address", func(issuerRef cmmeta.ObjectReference) { testCertificate := &cmapi.Certificate{ ObjectMeta: metav1.ObjectMeta{ Name: "testcert", Namespace: f.Namespace.Name, }, Spec: cmapi.CertificateSpec{ SecretName: "testcert-tls", IPAddresses: []string{sharedIPAddress}, IssuerRef: issuerRef, }, } By("Creating a Certificate") err := f.CRClient.Create(ctx, testCertificate) Expect(err).NotTo(HaveOccurred()) By("Waiting for the Certificate to be issued...") _, err = f.Helper().WaitForCertificateReady(f.Namespace.Name, "testcert", time.Minute*5) Expect(err).NotTo(HaveOccurred()) By("Validating the issued Certificate...") err = f.Helper().ValidateCertificate(f.Namespace.Name, "testcert", validation.CertificateSetForUnsupportedFeatureSet(s.UnsupportedFeatures)...) Expect(err).NotTo(HaveOccurred()) }, featureset.IPAddressFeature) s.it(f, "should issue a certificate that defines a DNS Name and IP Address", func(issuerRef cmmeta.ObjectReference) { testCertificate := &cmapi.Certificate{ ObjectMeta: metav1.ObjectMeta{ Name: "testcert", Namespace: f.Namespace.Name, }, Spec: cmapi.CertificateSpec{ SecretName: "testcert-tls", IPAddresses: []string{sharedIPAddress}, DNSNames: []string{e2eutil.RandomSubdomain(s.DomainSuffix)}, IssuerRef: issuerRef, }, } By("Creating a Certificate") err := f.CRClient.Create(ctx, testCertificate) Expect(err).NotTo(HaveOccurred()) By("Waiting for the Certificate to be issued...") _, err = f.Helper().WaitForCertificateReady(f.Namespace.Name, "testcert", time.Minute*5) Expect(err).NotTo(HaveOccurred()) By("Validating the issued Certificate...") err = f.Helper().ValidateCertificate(f.Namespace.Name, "testcert", validation.CertificateSetForUnsupportedFeatureSet(s.UnsupportedFeatures)...) Expect(err).NotTo(HaveOccurred()) }, featureset.OnlySAN, featureset.IPAddressFeature) s.it(f, "should issue a certificate that defines a Common Name and IP Address", func(issuerRef cmmeta.ObjectReference) { // Some issuers use the CN to define the cert's "ID" // if one cert manages to be in an error state in the issuer it might throw an error // this makes the CN more unique cn := "test-common-name-" + util.RandStringRunes(10) testCertificate := &cmapi.Certificate{ ObjectMeta: metav1.ObjectMeta{ Name: "testcert", Namespace: f.Namespace.Name, }, Spec: cmapi.CertificateSpec{ SecretName: "testcert-tls", CommonName: cn, IPAddresses: []string{sharedIPAddress}, IssuerRef: issuerRef, }, } By("Creating a Certificate") err := f.CRClient.Create(ctx, testCertificate) Expect(err).NotTo(HaveOccurred()) By("Waiting for the Certificate to be issued...") _, err = f.Helper().WaitForCertificateReady(f.Namespace.Name, "testcert", time.Minute*5) Expect(err).NotTo(HaveOccurred()) By("Validating the issued Certificate...") err = f.Helper().ValidateCertificate(f.Namespace.Name, "testcert", validation.CertificateSetForUnsupportedFeatureSet(s.UnsupportedFeatures)...) Expect(err).NotTo(HaveOccurred()) }, featureset.CommonNameFeature, featureset.IPAddressFeature) s.it(f, "should issue a certificate that defines an Email Address", func(issuerRef cmmeta.ObjectReference) { testCertificate := &cmapi.Certificate{ ObjectMeta: metav1.ObjectMeta{ Name: "testcert", Namespace: f.Namespace.Name, }, Spec: cmapi.CertificateSpec{ SecretName: "testcert-tls", EmailAddresses: []string{"[email protected]"}, IssuerRef: issuerRef, }, } By("Creating a Certificate") err := f.CRClient.Create(ctx, testCertificate) Expect(err).NotTo(HaveOccurred()) By("Waiting for the Certificate to be issued...") _, err = f.Helper().WaitForCertificateReady(f.Namespace.Name, "testcert", time.Minute*5) Expect(err).NotTo(HaveOccurred()) By("Validating the issued Certificate...") err = f.Helper().ValidateCertificate(f.Namespace.Name, "testcert", validation.CertificateSetForUnsupportedFeatureSet(s.UnsupportedFeatures)...) Expect(err).NotTo(HaveOccurred()) }, featureset.EmailSANsFeature, featureset.OnlySAN) s.it(f, "should issue a certificate that defines a Common Name and URI SAN", func(issuerRef cmmeta.ObjectReference) { // Some issuers use the CN to define the cert's "ID" // if one cert manages to be in an error state in the issuer it might throw an error // this makes the CN more unique cn := "test-common-name-" + util.RandStringRunes(10) testCertificate := &cmapi.Certificate{ ObjectMeta: metav1.ObjectMeta{ Name: "testcert", Namespace: f.Namespace.Name, }, Spec: cmapi.CertificateSpec{ SecretName: "testcert-tls", CommonName: cn, URIs: []string{"spiffe://cluster.local/ns/sandbox/sa/foo"}, IssuerRef: issuerRef, }, } By("Creating a Certificate") err := f.CRClient.Create(ctx, testCertificate) Expect(err).NotTo(HaveOccurred()) By("Waiting for the Certificate to be issued...") _, err = f.Helper().WaitForCertificateReady(f.Namespace.Name, "testcert", time.Minute*5) Expect(err).NotTo(HaveOccurred()) By("Validating the issued Certificate...") err = f.Helper().ValidateCertificate(f.Namespace.Name, "testcert", validation.CertificateSetForUnsupportedFeatureSet(s.UnsupportedFeatures)...) Expect(err).NotTo(HaveOccurred()) }, featureset.URISANsFeature, featureset.CommonNameFeature) s.it(f, "should issue a certificate that defines a 2 distinct DNS Names with one copied to the Common Name", func(issuerRef cmmeta.ObjectReference) { testCertificate := &cmapi.Certificate{ ObjectMeta: metav1.ObjectMeta{ Name: "testcert", Namespace: f.Namespace.Name, }, Spec: cmapi.CertificateSpec{ SecretName: "testcert-tls", CommonName: e2eutil.RandomSubdomain(s.DomainSuffix), IssuerRef: issuerRef, }, } testCertificate.Spec.DNSNames = []string{ testCertificate.Spec.CommonName, e2eutil.RandomSubdomain(s.DomainSuffix), } By("Creating a Certificate") err := f.CRClient.Create(ctx, testCertificate) Expect(err).NotTo(HaveOccurred()) By("Waiting for the Certificate to be issued...") _, err = f.Helper().WaitForCertificateReady(f.Namespace.Name, "testcert", time.Minute*5) Expect(err).NotTo(HaveOccurred()) By("Validating the issued Certificate...") err = f.Helper().ValidateCertificate(f.Namespace.Name, "testcert", validation.CertificateSetForUnsupportedFeatureSet(s.UnsupportedFeatures)...) Expect(err).NotTo(HaveOccurred()) }, featureset.CommonNameFeature) s.it(f, "should issue a certificate that defines a distinct DNS Name and another distinct Common Name", func(issuerRef cmmeta.ObjectReference) { testCertificate := &cmapi.Certificate{ ObjectMeta: metav1.ObjectMeta{ Name: "testcert", Namespace: f.Namespace.Name, }, Spec: cmapi.CertificateSpec{ SecretName: "testcert-tls", CommonName: e2eutil.RandomSubdomain(s.DomainSuffix), IssuerRef: issuerRef, DNSNames: []string{e2eutil.RandomSubdomain(s.DomainSuffix)}, }, } By("Creating a Certificate") err := f.CRClient.Create(ctx, testCertificate) Expect(err).NotTo(HaveOccurred()) By("Waiting for the Certificate to be issued...") _, err = f.Helper().WaitForCertificateReady(f.Namespace.Name, "testcert", time.Minute*5) Expect(err).NotTo(HaveOccurred()) By("Validating the issued Certificate...") err = f.Helper().ValidateCertificate(f.Namespace.Name, "testcert", validation.CertificateSetForUnsupportedFeatureSet(s.UnsupportedFeatures)...) Expect(err).NotTo(HaveOccurred()) }, featureset.CommonNameFeature) s.it(f, "should issue a certificate that defines a DNS Name and sets a duration", func(issuerRef cmmeta.ObjectReference) { testCertificate := &cmapi.Certificate{ ObjectMeta: metav1.ObjectMeta{ Name: "testcert", Namespace: f.Namespace.Name, }, Spec: cmapi.CertificateSpec{ SecretName: "testcert-tls", IssuerRef: issuerRef, DNSNames: []string{e2eutil.RandomSubdomain(s.DomainSuffix)}, Duration: &metav1.Duration{ Duration: time.Hour * 896, }, }, } By("Creating a Certificate") err := f.CRClient.Create(ctx, testCertificate) Expect(err).NotTo(HaveOccurred()) By("Waiting for the Certificate to be issued...") _, err = f.Helper().WaitForCertificateReady(f.Namespace.Name, "testcert", time.Minute*5) Expect(err).NotTo(HaveOccurred()) By("Validating the issued Certificate...") err = f.Helper().ValidateCertificate(f.Namespace.Name, "testcert", validation.CertificateSetForUnsupportedFeatureSet(s.UnsupportedFeatures)...) Expect(err).NotTo(HaveOccurred()) // We set a weird time here as the duration with should never be used as // a default by an issuer. This lets us test issuers are using our given // duration. // We set a 30 second buffer time here since Vault issues certificates // with an extra 30 seconds on its duration. f.CertificateDurationValid(testCertificate, time.Hour*896, 30*time.Second) }, featureset.DurationFeature, featureset.OnlySAN) s.it(f, "should issue a certificate that defines a wildcard DNS Name", func(issuerRef cmmeta.ObjectReference) { testCertificate := &cmapi.Certificate{ ObjectMeta: metav1.ObjectMeta{ Name: "testcert", Namespace: f.Namespace.Name, }, Spec: cmapi.CertificateSpec{ SecretName: "testcert-tls", IssuerRef: issuerRef, DNSNames: []string{"*." + e2eutil.RandomSubdomain(s.DomainSuffix)}, }, } By("Creating a Certificate") err := f.CRClient.Create(ctx, testCertificate) Expect(err).NotTo(HaveOccurred()) By("Waiting for the Certificate to be issued...") _, err = f.Helper().WaitForCertificateReady(f.Namespace.Name, "testcert", time.Minute*5) Expect(err).NotTo(HaveOccurred()) By("Validating the issued Certificate...") err = f.Helper().ValidateCertificate(f.Namespace.Name, "testcert", validation.CertificateSetForUnsupportedFeatureSet(s.UnsupportedFeatures)...) Expect(err).NotTo(HaveOccurred()) }, featureset.WildcardsFeature, featureset.OnlySAN) s.it(f, "should issue a certificate that includes only a URISANs name", func(issuerRef cmmeta.ObjectReference) { testCertificate := &cmapi.Certificate{ ObjectMeta: metav1.ObjectMeta{ Name: "testcert", Namespace: f.Namespace.Name, }, Spec: cmapi.CertificateSpec{ SecretName: "testcert-tls", URIs: []string{ "spiffe://cluster.local/ns/sandbox/sa/foo", }, IssuerRef: issuerRef, }, } By("Creating a Certificate") err := f.CRClient.Create(ctx, testCertificate) Expect(err).NotTo(HaveOccurred()) By("Waiting for the Certificate to be issued...") _, err = f.Helper().WaitForCertificateReady(f.Namespace.Name, "testcert", time.Minute*5) Expect(err).NotTo(HaveOccurred()) By("Validating the issued Certificate...") err = f.Helper().ValidateCertificate(f.Namespace.Name, "testcert", validation.CertificateSetForUnsupportedFeatureSet(s.UnsupportedFeatures)...) Expect(err).NotTo(HaveOccurred()) }, featureset.URISANsFeature, featureset.OnlySAN) s.it(f, "should issue a certificate that includes arbitrary key usages", func(issuerRef cmmeta.ObjectReference) { testCertificate := &cmapi.Certificate{ ObjectMeta: metav1.ObjectMeta{ Name: "testcert", Namespace: f.Namespace.Name, }, Spec: cmapi.CertificateSpec{ SecretName: "testcert-tls", DNSNames: []string{e2eutil.RandomSubdomain(s.DomainSuffix)}, IssuerRef: issuerRef, Usages: []cmapi.KeyUsage{ cmapi.UsageSigning, cmapi.UsageDataEncipherment, cmapi.UsageServerAuth, cmapi.UsageClientAuth, }, }, } By("Creating a Certificate") err := f.CRClient.Create(ctx, testCertificate) Expect(err).NotTo(HaveOccurred()) By("Waiting for the Certificate to be issued...") _, err = f.Helper().WaitForCertificateReady(f.Namespace.Name, "testcert", time.Minute*5) Expect(err).NotTo(HaveOccurred()) By("Validating the issued Certificate...") validations := []certificates.ValidationFunc{ certificates.ExpectKeyUsageExtKeyUsageClientAuth, certificates.ExpectKeyUsageExtKeyUsageServerAuth, certificates.ExpectKeyUsageUsageDigitalSignature, certificates.ExpectKeyUsageUsageDataEncipherment, } validations = append(validations, validation.CertificateSetForUnsupportedFeatureSet(s.UnsupportedFeatures)...) err = f.Helper().ValidateCertificate(f.Namespace.Name, "testcert", validations...) Expect(err).NotTo(HaveOccurred()) }, featureset.KeyUsagesFeature, featureset.OnlySAN) s.it(f, "should issue another certificate with the same private key if the existing certificate and CertificateRequest are deleted", func(issuerRef cmmeta.ObjectReference) { testCertificate := &cmapi.Certificate{ ObjectMeta: metav1.ObjectMeta{ Name: "testcert", Namespace: f.Namespace.Name, }, Spec: cmapi.CertificateSpec{ SecretName: "testcert-tls", DNSNames: []string{e2eutil.RandomSubdomain(s.DomainSuffix)}, IssuerRef: issuerRef, }, } By("Creating a Certificate") err := f.CRClient.Create(ctx, testCertificate) Expect(err).NotTo(HaveOccurred()) By("Waiting for the Certificate to be issued...") _, err = f.Helper().WaitForCertificateReady(f.Namespace.Name, "testcert", time.Minute*5) Expect(err).NotTo(HaveOccurred()) By("Validating the issued Certificate...") err = f.Helper().ValidateCertificate(f.Namespace.Name, "testcert", validation.CertificateSetForUnsupportedFeatureSet(s.UnsupportedFeatures)...) Expect(err).NotTo(HaveOccurred()) By("Deleting existing certificate data in Secret") sec, err := f.KubeClientSet.CoreV1().Secrets(f.Namespace.Name). Get(context.TODO(), testCertificate.Spec.SecretName, metav1.GetOptions{}) Expect(err).NotTo(HaveOccurred(), "failed to get secret containing signed certificate key pair data") sec = sec.DeepCopy() crtPEM1 := sec.Data[corev1.TLSCertKey] crt1, err := pki.DecodeX509CertificateBytes(crtPEM1) Expect(err).NotTo(HaveOccurred(), "failed to get decode first signed certificate data") sec.Data[corev1.TLSCertKey] = []byte{} _, err = f.KubeClientSet.CoreV1().Secrets(f.Namespace.Name).Update(context.TODO(), sec, metav1.UpdateOptions{}) Expect(err).NotTo(HaveOccurred(), "failed to update secret by deleting the signed certificate data") By("Waiting for the Certificate to re-issue a certificate") sec, err = f.Helper().WaitForSecretCertificateData(f.Namespace.Name, sec.Name, time.Minute*5) Expect(err).NotTo(HaveOccurred(), "failed to wait for secret to have a valid 2nd certificate") crtPEM2 := sec.Data[corev1.TLSCertKey] crt2, err := pki.DecodeX509CertificateBytes(crtPEM2) Expect(err).NotTo(HaveOccurred(), "failed to get decode second signed certificate data") By("Ensuing both certificates are signed by same private key") match, err := pki.PublicKeysEqual(crt1.PublicKey, crt2.PublicKey) Expect(err).NotTo(HaveOccurred(), "failed to check public keys of both signed certificates") if !match { Fail("Both signed certificates not signed by same private key") } }, featureset.ReusePrivateKeyFeature, featureset.OnlySAN) s.it(f, "should issue a certificate for a single distinct DNS Name defined by an ingress with annotations", func(issuerRef cmmeta.ObjectReference) { ingClient := f.KubeClientSet.NetworkingV1beta1().Ingresses(f.Namespace.Name) name := "testcert-ingress" secretName := "testcert-ingress-tls" By("Creating an Ingress with the issuer name annotation set") ingress, err := ingClient.Create(context.TODO(), e2eutil.NewIngress(name, secretName, map[string]string{ "cert-manager.io/issuer": issuerRef.Name, "cert-manager.io/issuer-kind": issuerRef.Kind, "cert-manager.io/issuer-group": issuerRef.Group, }, e2eutil.RandomSubdomain(s.DomainSuffix)), metav1.CreateOptions{}) Expect(err).NotTo(HaveOccurred()) certName := ingress.Spec.TLS[0].SecretName By("Waiting for the Certificate to exist...") Expect(e2eutil.WaitForCertificateToExist( f.CertManagerClientSet.CertmanagerV1().Certificates(f.Namespace.Name), certName, time.Minute, )).NotTo(HaveOccurred()) By("Waiting for the Certificate to be issued...") _, err = f.Helper().WaitForCertificateReady(f.Namespace.Name, certName, time.Minute*5) Expect(err).NotTo(HaveOccurred()) By("Validating the issued Certificate...") err = f.Helper().ValidateCertificate(f.Namespace.Name, certName, validation.CertificateSetForUnsupportedFeatureSet(s.UnsupportedFeatures)...) Expect(err).NotTo(HaveOccurred()) }, featureset.OnlySAN) s.it(f, "should issue a certificate defined by an ingress with certificate field annotations", func(issuerRef cmmeta.ObjectReference) { ingClient := f.KubeClientSet.NetworkingV1beta1().Ingresses(f.Namespace.Name) name := "testcert-ingress" secretName := "testcert-ingress-tls" domain := e2eutil.RandomSubdomain(s.DomainSuffix) duration := time.Hour * 999 renewBefore := time.Hour * 111 By("Creating an Ingress with annotations for issuerRef and other Certificate fields") ingress, err := ingClient.Create(context.TODO(), e2eutil.NewIngress(name, secretName, map[string]string{ "cert-manager.io/issuer": issuerRef.Name, "cert-manager.io/issuer-kind": issuerRef.Kind, "cert-manager.io/issuer-group": issuerRef.Group, "cert-manager.io/common-name": domain, "cert-manager.io/duration": duration.String(), "cert-manager.io/renew-before": renewBefore.String(), }, domain), metav1.CreateOptions{}) Expect(err).NotTo(HaveOccurred()) certName := ingress.Spec.TLS[0].SecretName By("Waiting for the Certificate to exist...") Expect(e2eutil.WaitForCertificateToExist( f.CertManagerClientSet.CertmanagerV1().Certificates(f.Namespace.Name), certName, time.Minute, )).NotTo(HaveOccurred()) By("Waiting for the Certificate to be issued...") _, err = f.Helper().WaitForCertificateReady(f.Namespace.Name, certName, time.Minute*5) Expect(err).NotTo(HaveOccurred()) // Verify that the ingres-shim has translated all the supplied // annotations into equivalent Certificate field values By("Validating the created Certificate") err = f.Helper().ValidateCertificate( f.Namespace.Name, certName, func(certificate *cmapi.Certificate, _ *corev1.Secret) error { Expect(certificate.Spec.DNSNames).To(ConsistOf(domain)) Expect(certificate.Spec.CommonName).To(Equal(domain)) Expect(certificate.Spec.Duration.Duration).To(Equal(duration)) Expect(certificate.Spec.RenewBefore.Duration).To(Equal(renewBefore)) return nil }, ) Expect(err).NotTo(HaveOccurred()) // Verify that the issuer has preserved all the Certificate values // in the signed certificate By("Validating the issued Certificate...") err = f.Helper().ValidateCertificate(f.Namespace.Name, certName, validation.CertificateSetForUnsupportedFeatureSet(s.UnsupportedFeatures)...) Expect(err).NotTo(HaveOccurred()) }) s.it(f, "Creating a Gateway with annotations for issuerRef and other Certificate fields", func(issuerRef cmmeta.ObjectReference) { name := "testcert-gateway" secretName := "testcert-gateway-tls" domain := e2eutil.RandomSubdomain(s.DomainSuffix) duration := time.Hour * 999 renewBefore := time.Hour * 111 By("Creating a Gateway with annotations for issuerRef and other Certificate fields") gw, route := e2eutil.NewGateway(name, f.Namespace.Name, secretName, map[string]string{ "cert-manager.io/issuer": issuerRef.Name, "cert-manager.io/issuer-kind": issuerRef.Kind, "cert-manager.io/issuer-group": issuerRef.Group, "cert-manager.io/common-name": domain, "cert-manager.io/duration": duration.String(), "cert-manager.io/renew-before": renewBefore.String(), }, domain) gw, err := f.GWClientSet.NetworkingV1alpha1().Gateways(f.Namespace.Name).Create(context.TODO(), gw, metav1.CreateOptions{}) Expect(err).NotTo(HaveOccurred()) _, err = f.GWClientSet.NetworkingV1alpha1().HTTPRoutes(f.Namespace.Name).Create(context.TODO(), route, metav1.CreateOptions{}) Expect(err).NotTo(HaveOccurred()) // XXX(Mael): the CertificateRef seems to contain the Gateway name // "testcert-gateway" instead of the secretName // "testcert-gateway-tls". certName := gw.Spec.Listeners[0].TLS.CertificateRef.Name By("Waiting for the Certificate to exist...") Expect(e2eutil.WaitForCertificateToExist( f.CertManagerClientSet.CertmanagerV1().Certificates(f.Namespace.Name), certName, time.Minute, )).NotTo(HaveOccurred()) // Verify that the ingres-shim has translated all the supplied // annotations into equivalent Certificate field values By("Validating the created Certificate") cert, err := f.CertManagerClientSet.CertmanagerV1().Certificates(f.Namespace.Name).Get(context.TODO(), certName, metav1.GetOptions{}) Expect(err).NotTo(HaveOccurred()) Expect(cert.Spec.DNSNames).To(ConsistOf(domain)) Expect(cert.Spec.CommonName).To(Equal(domain)) Expect(cert.Spec.Duration.Duration).To(Equal(duration)) Expect(cert.Spec.RenewBefore.Duration).To(Equal(renewBefore)) }) s.it(f, "should issue a certificate that defines a long domain", func(issuerRef cmmeta.ObjectReference) { // the maximum length of a single segment of the domain being requested const maxLengthOfDomainSegment = 63 testCertificate := &cmapi.Certificate{ ObjectMeta: metav1.ObjectMeta{ Name: "testcert", Namespace: f.Namespace.Name, }, Spec: cmapi.CertificateSpec{ SecretName: "testcert-tls", DNSNames: []string{e2eutil.RandomSubdomainLength(s.DomainSuffix, maxLengthOfDomainSegment)}, IssuerRef: issuerRef, }, } validations := validation.CertificateSetForUnsupportedFeatureSet(s.UnsupportedFeatures) By("Creating a Certificate") err := f.CRClient.Create(ctx, testCertificate) Expect(err).NotTo(HaveOccurred()) By("Waiting for the Certificate to be issued...") _, err = f.Helper().WaitForCertificateReady(f.Namespace.Name, "testcert", time.Minute*5) Expect(err).NotTo(HaveOccurred()) By("Sanity-check the issued Certificate") err = f.Helper().ValidateCertificate(f.Namespace.Name, "testcert", validations...) Expect(err).NotTo(HaveOccurred()) }, featureset.OnlySAN) s.it(f, "should allow updating an existing certificate with a new DNS Name", func(issuerRef cmmeta.ObjectReference) { testCertificate := &cmapi.Certificate{ ObjectMeta: metav1.ObjectMeta{ Name: "testcert", Namespace: f.Namespace.Name, }, Spec: cmapi.CertificateSpec{ SecretName: "testcert-tls", DNSNames: []string{e2eutil.RandomSubdomain(s.DomainSuffix)}, IssuerRef: issuerRef, }, } validations := validation.CertificateSetForUnsupportedFeatureSet(s.UnsupportedFeatures) By("Creating a Certificate") err := f.CRClient.Create(ctx, testCertificate) Expect(err).NotTo(HaveOccurred()) By("Waiting for the Certificate to be ready") _, err = f.Helper().WaitForCertificateReady(f.Namespace.Name, "testcert", time.Minute*5) Expect(err).NotTo(HaveOccurred()) By("Sanity-check the issued Certificate") err = f.Helper().ValidateCertificate(f.Namespace.Name, "testcert", validations...) Expect(err).NotTo(HaveOccurred()) By("Getting the latest version of the Certificate") cert, err := f.Helper().CMClient.CertmanagerV1().Certificates(f.Namespace.Name).Get(context.TODO(), "testcert", metav1.GetOptions{}) Expect(err).NotTo(HaveOccurred()) By("Updating the Certificate after having added an additional dnsName") newDNSName := e2eutil.RandomSubdomain(s.DomainSuffix) err = retry.RetryOnConflict(retry.DefaultRetry, func() error { err := f.CRClient.Get(context.Background(), types.NamespacedName{Namespace: f.Namespace.Name, Name: "testcert"}, cert) if err != nil { return err } cert.Spec.DNSNames = append(cert.Spec.DNSNames, newDNSName) return f.CRClient.Update(context.TODO(), cert) }) Expect(err).NotTo(HaveOccurred()) By("Waiting for the Certificate Ready condition to be updated") _, err = f.Helper().WaitForCertificateReadyUpdate(cert, time.Minute*5) Expect(err).NotTo(HaveOccurred()) By("Sanity-check the issued Certificate") err = f.Helper().ValidateCertificate(f.Namespace.Name, "testcert", validations...) Expect(err).NotTo(HaveOccurred()) }, featureset.OnlySAN) s.it(f, "should issue a certificate that defines a wildcard DNS Name and its apex DNS Name", func(issuerRef cmmeta.ObjectReference) { dnsDomain := e2eutil.RandomSubdomain(s.DomainSuffix) testCertificate := &cmapi.Certificate{ ObjectMeta: metav1.ObjectMeta{ Name: "testcert", Namespace: f.Namespace.Name, }, Spec: cmapi.CertificateSpec{ SecretName: "testcert-tls", IssuerRef: issuerRef, DNSNames: []string{"*." + dnsDomain, dnsDomain}, }, } By("Creating a Certificate") err := f.CRClient.Create(ctx, testCertificate) Expect(err).NotTo(HaveOccurred()) // use a longer timeout for this, as it requires performing 2 dns validations in serial By("Waiting for the Certificate to be issued...") _, err = f.Helper().WaitForCertificateReady(f.Namespace.Name, "testcert", time.Minute*10) Expect(err).NotTo(HaveOccurred()) By("Validating the issued Certificate...") err = f.Helper().ValidateCertificate(f.Namespace.Name, "testcert", validation.CertificateSetForUnsupportedFeatureSet(s.UnsupportedFeatures)...) Expect(err).NotTo(HaveOccurred()) }, featureset.WildcardsFeature, featureset.OnlySAN) }) }
1
28,566
Ah, I see here that 'LongDomain' is defined as something that contains a subdomain segment that is `maxLengthOfDomainSegment` long (which I think is 63 characters) - I don't think any public ACME servers/Let's Encrypt's staging environment has a restriction on this? if it does, and the 'pebble' based ACME server does not, then Pebble needs modifying to also fail in these cases as it aims to replicate the ACME RFC as closely as possible
jetstack-cert-manager
go
@@ -112,12 +112,13 @@ module Travis 'cdbs qpdf texinfo libssh2-1-dev devscripts '\ "#{optional_apt_pkgs}", retry: true - r_filename = "R-#{r_version}-$(lsb_release -cs).xz" - r_url = "https://travis-ci.rstudio.org/#{r_filename}" + r_filename = "r-#{r_version}_1_amd64.deb" + os_version = "$(lsb_release -rs | tr -d '.')" + r_url = "https://cdn.rstudio.com/r/ubuntu-#{os_version}/pkgs/#{r_filename}" sh.cmd "curl -fLo /tmp/#{r_filename} #{r_url}", retry: true - sh.cmd "tar xJf /tmp/#{r_filename} -C ~" - sh.export 'PATH', "${TRAVIS_HOME}/R-bin/bin:$PATH", echo: false - sh.export 'LD_LIBRARY_PATH', "${TRAVIS_HOME}/R-bin/lib:$LD_LIBRARY_PATH", echo: false + sh.cmd "sudo apt-get install gdebi-core" + sh.cmd "sudo gdebi r-#{r_version}_1_amd64.deb" + sh.export 'PATH', "/opt/R/#{r_version}/bin:$PATH", echo: false sh.rm "/tmp/#{r_filename}" sh.cmd "sudo mkdir -p /usr/local/lib/R/site-library $R_LIBS_USER"
1
# Maintained by: # Jim Hester @jimhester [email protected] # Jeroen Ooms @jeroen [email protected] # module Travis module Build class Script class R < Script DEFAULTS = { # Basic config options cran: 'https://cloud.r-project.org', repos: {}, warnings_are_errors: true, # Dependencies (installed in this order) apt_packages: [], brew_packages: [], r_binary_packages: [], r_packages: [], bioc_packages: [], r_github_packages: [], # Build/test options r_build_args: '', r_check_args: '--as-cran', # Heavy dependencies pandoc: true, latex: true, fortran: true, pandoc_version: '2.2', # Bioconductor bioc: 'https://bioconductor.org/biocLite.R', bioc_required: false, bioc_check: false, bioc_use_devel: false, disable_homebrew: false, use_devtools: false, r: 'release' } def initialize(data) # TODO: Is there a way to avoid explicitly naming arguments here? super @remotes_installed = false @devtools_installed = false @bioc_installed = false end def export super sh.export 'TRAVIS_R_VERSION', r_version, echo: false sh.export 'TRAVIS_R_VERSION_STRING', config[:r].to_s, echo: false sh.export 'R_LIBS_USER', '~/R/Library', echo: false sh.export 'R_LIBS_SITE', '/usr/local/lib/R/site-library:/usr/lib/R/site-library', echo: false sh.export '_R_CHECK_CRAN_INCOMING_', 'false', echo: false sh.export 'NOT_CRAN', 'true', echo: false end def configure super sh.echo 'R for Travis-CI is not officially supported, '\ 'but is community maintained.', ansi: :green sh.echo 'Please file any issues at https://travis-ci.community/c/languages/r' sh.echo 'and mention @jeroen and @jimhester in the issue' sh.fold 'R-install' do sh.with_options({ assert: true, echo: true, timing: true }) do sh.echo 'Installing R', ansi: :yellow case config[:os] when 'linux' # This key is added implicitly by the marutter PPA below #sh.cmd 'apt-key adv --keyserver ha.pool.sks-keyservers.net '\ #'--recv-keys E298A3A825C0D65DFD57CBB651716619E084DAB9', sudo: true # Add marutter's c2d4u plus ppa dependencies as listed on launchpad if r_version_less_than('3.5.0') sh.cmd 'sudo add-apt-repository -y "ppa:marutter/rrutter"' sh.cmd 'sudo add-apt-repository -y "ppa:marutter/c2d4u"' elsif r_version_less_than('4.0.0') sh.cmd 'sudo add-apt-repository -y "ppa:marutter/rrutter3.5"' sh.cmd 'sudo add-apt-repository -y "ppa:marutter/c2d4u3.5"' else sh.cmd 'sudo add-apt-repository -y "ppa:marutter/rrutter4.0"' sh.cmd 'sudo add-apt-repository -y "ppa:c2d4u.team/c2d4u4.0+"' end # Extra PPAs that do not depend on R version sh.cmd 'sudo add-apt-repository -y "ppa:ubuntugis/ppa"' sh.cmd 'sudo add-apt-repository -y "ppa:cran/travis"' # Both c2d4u and c2d4u3.5 depend on this ppa for ffmpeg sh.if "$(lsb_release -cs) = 'trusty'" do sh.cmd 'sudo add-apt-repository -y "ppa:kirillshkrogalev/ffmpeg-next"' end # Update after adding all repositories. Retry several # times to work around flaky connection to Launchpad PPAs. sh.cmd 'travis_apt_get_update', retry: true # Install precompiled R # Install only the dependencies for an R development environment except for # libpcre3-dev or r-base-core because they will be included in # the R binary tarball. # Dependencies queried with `apt-cache depends -i r-base-dev`. # qpdf and texinfo are also needed for --as-cran # checks: # https://stat.ethz.ch/pipermail/r-help//2012-September/335676.html optional_apt_pkgs = "" optional_apt_pkgs << "gfortran" if config[:fortran] sh.cmd 'sudo apt-get install -y --no-install-recommends '\ 'build-essential gcc g++ libblas-dev liblapack-dev '\ 'libncurses5-dev libreadline-dev libjpeg-dev '\ 'libpcre3-dev libpng-dev zlib1g-dev libbz2-dev liblzma-dev libicu-dev '\ 'cdbs qpdf texinfo libssh2-1-dev devscripts '\ "#{optional_apt_pkgs}", retry: true r_filename = "R-#{r_version}-$(lsb_release -cs).xz" r_url = "https://travis-ci.rstudio.org/#{r_filename}" sh.cmd "curl -fLo /tmp/#{r_filename} #{r_url}", retry: true sh.cmd "tar xJf /tmp/#{r_filename} -C ~" sh.export 'PATH', "${TRAVIS_HOME}/R-bin/bin:$PATH", echo: false sh.export 'LD_LIBRARY_PATH', "${TRAVIS_HOME}/R-bin/lib:$LD_LIBRARY_PATH", echo: false sh.rm "/tmp/#{r_filename}" sh.cmd "sudo mkdir -p /usr/local/lib/R/site-library $R_LIBS_USER" sh.cmd 'sudo chmod 2777 /usr/local/lib/R /usr/local/lib/R/site-library $R_LIBS_USER' when 'osx' # We want to update, but we don't need the 800+ lines of # output. unless config[:disable_homebrew] sh.cmd 'brew update >/dev/null', retry: true sh.cmd 'brew install checkbashisms || true' end # R-devel builds available at mac.r-project.org if r_version == 'devel' r_url = "https://mac.r-project.org/high-sierra/R-devel/R-devel.pkg" # The latest release is the only one available in /bin/macosx elsif r_version == r_latest r_url = "#{repos[:CRAN]}/bin/macosx/R-latest.pkg" # 3.2.5 was never built for OS X so # we need to use 3.2.4-revised, which is the same codebase # https://stat.ethz.ch/pipermail/r-devel/2016-May/072642.html elsif r_version == '3.2.5' r_url = "#{repos[:CRAN]}/bin/macosx/old/R-3.2.4-revised.pkg" # the old archive has moved after 3.4.0 elsif r_version_less_than('3.4.0') r_url = "#{repos[:CRAN]}/bin/macosx/old/R-#{r_version}.pkg" else r_url = "#{repos[:CRAN]}/bin/macosx/el-capitan/base/R-#{r_version}.pkg" end # Install from latest CRAN binary build for OS X sh.cmd "curl -fLo /tmp/R.pkg #{r_url}", retry: true sh.echo 'Installing OS X binary package for R' sh.cmd 'sudo installer -pkg "/tmp/R.pkg" -target /' sh.rm '/tmp/R.pkg' setup_fortran_osx if config[:fortran] else sh.failure "Operating system not supported: #{config[:os]}" end # Set repos in ~/.Rprofile repos_str = repos.collect {|k,v| "#{k} = \"#{v}\""}.join(", ") options_repos = "options(repos = c(#{repos_str}))" sh.cmd %Q{echo '#{options_repos}' > ~/.Rprofile.site} sh.export 'R_PROFILE', "~/.Rprofile.site", echo: false # PDF manual requires latex if config[:latex] setup_latex else config[:r_check_args] = config[:r_check_args] + " --no-manual" config[:r_build_args] = config[:r_build_args] + " --no-manual" end setup_bioc if needs_bioc? setup_pandoc if config[:pandoc] # Removes preinstalled homebrew disable_homebrew if config[:disable_homebrew] end end end def announce super sh.fold 'R-session-info' do sh.echo 'R session information', ansi: :yellow sh.cmd 'Rscript -e \'sessionInfo()\'' end end def install super sh.if '! -e DESCRIPTION' do sh.failure "No DESCRIPTION file found, user must supply their own install and script steps" end sh.fold "R-dependencies" do sh.echo 'Installing package dependencies', ansi: :yellow # Install any declared packages apt_install config[:apt_packages] brew_install config[:brew_packages] r_binary_install config[:r_binary_packages] r_install config[:r_packages] r_install config[:bioc_packages] r_github_install config[:r_github_packages] # Install dependencies for the package we're testing. install_deps end if @devtools_installed sh.fold 'R-installed-versions' do sh.echo 'Installed package versions', ansi: :yellow sh.cmd 'Rscript -e \'devtools::session_info(installed.packages()[, "Package"])\'' end end end def script # Build the package sh.if '! -e DESCRIPTION' do sh.failure "No DESCRIPTION file found, user must supply their own install and script steps" end tarball_script = '$version = $1 if (/^Version:\s(\S+)/);'\ '$package = $1 if (/^Package:\s*(\S+)/);'\ 'END { print "${package}_$version.tar.gz" }'\ sh.export 'PKG_TARBALL', "$(perl -ne '#{tarball_script}' DESCRIPTION)", echo: false sh.fold 'R-build' do sh.echo 'Building package', ansi: :yellow sh.echo "Building with: R CMD build ${R_BUILD_ARGS}" sh.cmd "R CMD build #{config[:r_build_args]} .", assert: true end # Check the package sh.fold 'R-check' do sh.echo 'Checking package', ansi: :yellow # Test the package sh.echo 'Checking with: R CMD check "${PKG_TARBALL}" '\ "#{config[:r_check_args]}" sh.cmd "R CMD check \"${PKG_TARBALL}\" #{config[:r_check_args]}; "\ "CHECK_RET=$?", assert: false end export_rcheck_dir if config[:bioc_check] # BiocCheck the package sh.fold 'Bioc-check' do sh.echo 'Checking with: BiocCheck( "${PKG_TARBALL}" ) ' sh.cmd 'Rscript -e "BiocCheck::BiocCheck(\"${PKG_TARBALL}\", \'quit-with-status\'=TRUE)"' end end if @devtools_installed # Output check summary sh.cmd 'Rscript -e "message(devtools::check_failures(path = \"${RCHECK_DIR}\"))"', echo: false end # Build fails if R CMD check fails sh.if '$CHECK_RET -ne 0' do dump_error_logs sh.failure 'R CMD check failed' end # Turn warnings into errors, if requested. if config[:warnings_are_errors] sh.cmd 'grep -q -R "WARNING" "${RCHECK_DIR}/00check.log"', echo: false, assert: false sh.if '$? -eq 0' do dump_error_logs sh.failure "Found warnings, treating as errors (as requested)." end end end def setup_cache if data.cache?(:packages) sh.fold 'package cache' do sh.echo 'Setting up package cache', ansi: :yellow directory_cache.add '$R_LIBS_USER' end end end def cache_slug super << '--R-' << r_version end def use_directory_cache? super || data.cache?(:packages) end private def needs_bioc? config[:bioc_required] || !config[:bioc_packages].empty? end def packages_as_arg(packages) packages = Array(packages) quoted_pkgs = packages.collect{|p| "\"#{p}\""} "c(#{quoted_pkgs.join(', ')})" end def as_r_boolean(bool) bool ? "TRUE" : "FALSE" end def r_install(packages) return if packages.empty? packages = Array(packages) sh.echo "Installing R packages: #{packages.join(', ')}" pkg_arg = packages_as_arg(packages) install_script = "install.packages(#{pkg_arg});"\ "if (!all(#{pkg_arg} %in% installed.packages())) {"\ ' q(status = 1, save = "no")'\ '}' sh.cmd "Rscript -e '#{install_script}'" end def r_github_install(packages) return if packages.empty? packages = Array(packages) setup_remotes setup_devtools if config[:use_devtools] sh.echo "Installing R packages from GitHub: #{packages.join(', ')}" pkg_arg = packages_as_arg(packages) install_script = "remotes::install_github(#{pkg_arg})" sh.cmd "Rscript -e '#{install_script}'" end def r_binary_install(packages) return if packages.empty? packages = Array(packages) if config[:os] == 'linux' if config[:dist] == 'precise' sh.echo "R binary packages not supported for 'dist: precise', "\ ' falling back to source install' return r_install packages end sh.echo "Installing *binary* R packages: #{packages.join(', ')}" apt_install packages.collect{|p| "r-cran-#{p.downcase}"} else sh.echo "R binary packages not supported on #{config[:os]}, "\ 'falling back to source install' r_install packages end end def apt_install(packages) return if packages.empty? packages = Array(packages) return unless (config[:os] == 'linux') pkg_arg = packages.join(' ') sh.echo "Installing apt packages: #{packages.join(', ')}" sh.cmd "sudo apt-get install -y #{pkg_arg}", retry: true end def brew_install(packages) return if packages.empty? packages = Array(packages) return unless (config[:os] == 'osx') pkg_arg = packages.join(' ') sh.echo "Installing brew packages: #{packages.join(', ')}" sh.cmd "brew install #{pkg_arg}", retry: true end def install_deps setup_remotes setup_devtools if config[:use_devtools] install_script = 'deps <- remotes::dev_package_deps(dependencies = NA);'\ 'remotes::install_deps(dependencies = TRUE);'\ 'if (!all(deps$package %in% installed.packages())) {'\ ' message("missing: ", paste(setdiff(deps$package, installed.packages()), collapse=", "));'\ ' q(status = 1, save = "no")'\ '}' sh.cmd "Rscript -e '#{install_script}'" end def export_rcheck_dir # Simply strip the tarball name until the last _ and add '.Rcheck', # relevant R code # https://github.com/wch/r-source/blob/840a972338042b14aa5855cc431b2d0decf68234/src/library/tools/R/check.R#L4608-L4615 sh.export 'RCHECK_DIR', "$(expr \"$PKG_TARBALL\" : '\\(.*\\)_').Rcheck", echo: false end def dump_error_logs dump_log("fail") dump_log("log") dump_log("out") end def dump_log(type) sh.fold "#{type} logs" do sh.echo "R CMD check #{type} logs", ansi: :yellow cmd = 'for name in '\ "$(find \"${RCHECK_DIR}\" -type f -name \"*#{type}\");"\ 'do '\ 'echo ">>> Filename: ${name} <<<";'\ 'cat ${name};'\ 'done' sh.cmd cmd end end def setup_bioc unless @bioc_installed sh.fold 'Bioconductor' do sh.echo 'Installing Bioconductor', ansi: :yellow bioc_install_script = if r_version_less_than("3.5.0") "source(\"#{config[:bioc]}\");"\ 'tryCatch('\ " useDevel(#{as_r_boolean(config[:bioc_use_devel])}),"\ ' error=function(e) {if (!grepl("already in use", e$message)) {e}}'\ ' );'\ 'cat(append = TRUE, file = "~/.Rprofile.site", "options(repos = BiocInstaller::biocinstallRepos());")' else 'if (!requireNamespace("BiocManager", quietly=TRUE))'\ ' install.packages("BiocManager");'\ "if (#{as_r_boolean(config[:bioc_use_devel])})"\ ' BiocManager::install(version = "devel", ask = FALSE);'\ 'cat(append = TRUE, file = "~/.Rprofile.site", "options(repos = BiocManager::repositories());")' end sh.cmd "Rscript -e '#{bioc_install_script}'", retry: true bioc_install_bioccheck = if r_version_less_than("3.5.0") 'BiocInstaller::biocLite("BiocCheck")' else 'BiocManager::install("BiocCheck")' end if config[:bioc_check] sh.cmd "Rscript -e '#{bioc_install_bioccheck}'" end end end @bioc_installed = true end def setup_remotes unless @remotes_installed case config[:os] when 'linux' # We can't use remotes binaries because R versions < 3.5 are not # compatible with R versions >= 3.5 r_install ['remotes'] else remotes_check = '!requireNamespace("remotes", quietly = TRUE)' remotes_install = 'install.packages("remotes")' sh.cmd "Rscript -e 'if (#{remotes_check}) #{remotes_install}'", retry: true end end @remotes_installed = true end def setup_devtools unless @devtools_installed case config[:os] when 'linux' # We can't use devtools binaries because R versions < 3.5 are not # compatible with R versions >= 3.5 r_install ['devtools'] else devtools_check = '!requireNamespace("devtools", quietly = TRUE)' devtools_install = 'install.packages("devtools")' sh.cmd "Rscript -e 'if (#{devtools_check}) #{devtools_install}'", retry: true end end @devtools_installed = true end def setup_latex case config[:os] when 'linux' texlive_filename = 'texlive.tar.gz' texlive_url = 'https://github.com/jimhester/ubuntu-bin/releases/download/latest/texlive.tar.gz' sh.cmd "curl -fLo /tmp/#{texlive_filename} #{texlive_url}", retry: true sh.cmd "tar xzf /tmp/#{texlive_filename} -C ~" sh.export 'PATH', "${TRAVIS_HOME}/texlive/bin/x86_64-linux:$PATH" sh.cmd 'tlmgr update --self', assert: false when 'osx' # We use basictex due to disk space constraints. mactex = 'BasicTeX.pkg' # TODO: Confirm that this will route us to the nearest mirror. sh.cmd "curl -fLo \"/tmp/#{mactex}\" --retry 3 http://mirror.ctan.org/systems/mac/mactex/"\ "#{mactex}" sh.echo 'Installing OS X binary package for MacTeX' sh.cmd "sudo installer -pkg \"/tmp/#{mactex}\" -target /" sh.rm "/tmp/#{mactex}" sh.export 'PATH', '/usr/texbin:/Library/TeX/texbin:$PATH' sh.cmd 'sudo tlmgr update --self', assert: false # Install common packages sh.cmd 'sudo tlmgr install inconsolata upquote '\ 'courier courier-scaled helvetic', assert: false end end def setup_pandoc case config[:os] when 'linux' pandoc_filename = "pandoc-#{config[:pandoc_version]}-1-amd64.deb" pandoc_url = "https://github.com/jgm/pandoc/releases/download/#{config[:pandoc_version]}/"\ "#{pandoc_filename}" # Download and install pandoc sh.cmd "curl -fLo /tmp/#{pandoc_filename} #{pandoc_url}" sh.cmd "sudo dpkg -i /tmp/#{pandoc_filename}" # Fix any missing dependencies sh.cmd "sudo apt-get install -f" # Cleanup sh.rm "/tmp/#{pandoc_filename}" when 'osx' # Change OS name if requested version is less than 1.19.2.2 # Name change was introduced in v2.0 of pandoc. # c.f. "Build Infrastructure Improvements" section of # https://github.com/jgm/pandoc/releases/tag/2.0 # Lastly, the last binary for macOS before 2.0 is 1.19.2.1 os_short_name = version_check_less_than("#{config[:pandoc_version]}", "1.19.2.2") ? "macOS" : "osx" pandoc_filename = "pandoc-#{config[:pandoc_version]}-#{os_short_name}.pkg" pandoc_url = "https://github.com/jgm/pandoc/releases/download/#{config[:pandoc_version]}/"\ "#{pandoc_filename}" # Download and install pandoc sh.cmd "curl -fLo /tmp/#{pandoc_filename} #{pandoc_url}" sh.cmd "sudo installer -pkg \"/tmp/#{pandoc_filename}\" -target /" # Cleanup sh.rm "/tmp/#{pandoc_filename}" end end # Install gfortran libraries the precompiled binaries are linked to def setup_fortran_osx return unless (config[:os] == 'osx') if r_version_less_than('3.4') sh.cmd 'curl -fLo /tmp/gfortran.tar.bz2 http://r.research.att.com/libs/gfortran-4.8.2-darwin13.tar.bz2', retry: true sh.cmd 'sudo tar fvxz /tmp/gfortran.tar.bz2 -C /' sh.rm '/tmp/gfortran.tar.bz2' elsif r_version_less_than('3.7') sh.cmd "curl -fLo /tmp/gfortran61.dmg #{repos[:CRAN]}/contrib/extra/macOS/gfortran-6.1-ElCapitan.dmg", retry: true sh.cmd 'sudo hdiutil attach /tmp/gfortran61.dmg -mountpoint /Volumes/gfortran' sh.cmd 'sudo installer -pkg "/Volumes/gfortran/gfortran-6.1-ElCapitan/gfortran.pkg" -target /' sh.cmd 'sudo hdiutil detach /Volumes/gfortran' sh.rm '/tmp/gfortran61.dmg' else sh.cmd "curl -fLo /tmp/gfortran82.dmg https://github.com/fxcoudert/gfortran-for-macOS/releases/download/8.2/gfortran-8.2-Mojave.dmg", retry: true sh.cmd 'sudo hdiutil attach /tmp/gfortran82.dmg -mountpoint /Volumes/gfortran' sh.cmd 'sudo installer -pkg "/Volumes/gfortran/gfortran-8.2-Mojave/gfortran.pkg" -target /' sh.cmd 'sudo hdiutil detach /Volumes/gfortran' sh.rm '/tmp/gfortran82.dmg' end end # Uninstalls the preinstalled homebrew # See FAQ: https://docs.brew.sh/FAQ#how-do-i-uninstall-homebrew def disable_homebrew return unless (config[:os] == 'osx') sh.cmd "curl -fsSOL https://raw.githubusercontent.com/Homebrew/install/master/uninstall.sh" sh.cmd "sudo /bin/bash uninstall.sh --force" sh.cmd "rm uninstall.sh" sh.cmd "hash -r" sh.cmd "git config --global --unset protocol.version || true" end # Abstract out version check def version_check_less_than(version_str_new, version_str_old) Gem::Version.new(version_str_old) < Gem::Version.new(version_str_new) end def r_version @r_version ||= normalized_r_version end def r_version_less_than(str) return if normalized_r_version == 'devel' # always false (devel is highest version) version_check_less_than(str, normalized_r_version) end def normalized_r_version(v=Array(config[:r]).first.to_s) case v when 'release' then '4.0.0' when 'oldrel' then '3.6.3' when '3.0' then '3.0.3' when '3.1' then '3.1.3' when '3.2' then '3.2.5' when '3.3' then '3.3.3' when '3.4' then '3.4.4' when '3.5' then '3.5.3' when '3.6' then '3.6.3' when '4.0' then '4.0.0' when 'bioc-devel' config[:bioc_required] = true config[:bioc_use_devel] = true config[:r] = 'release' normalized_r_version('release') when 'bioc-release' config[:bioc_required] = true config[:bioc_use_devel] = false config[:r] = 'release' normalized_r_version('release') else v end end def r_latest normalized_r_version('release') end def repos @repos ||= normalized_repos end # If CRAN is not set in repos set it with cran def normalized_repos v = config[:repos] if not v.has_key?(:CRAN) v[:CRAN] = config[:cran] end # If the version is less than 3.2 we need to use http repositories if r_version_less_than('3.2') v.each {|_, url| url.sub!(/^https:/, "http:")} config[:bioc].sub!(/^https:/, "http:") end v end end end end end
1
17,526
I think you need `-y` here to prevent a user confirmation prompt
travis-ci-travis-build
rb
@@ -100,6 +100,7 @@ bool dynamo_heap_initialized = false; bool dynamo_started = false; bool automatic_startup = false; bool control_all_threads = false; +bool dynamo_avx512_code_in_use = false; #ifdef WINDOWS bool dr_early_injected = false; int dr_early_injected_location = INJECT_LOCATION_Invalid;
1
/* ********************************************************** * Copyright (c) 2010-2019 Google, Inc. All rights reserved. * Copyright (c) 2000-2010 VMware, Inc. All rights reserved. * **********************************************************/ /* * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of VMware, Inc. nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL VMWARE, INC. OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. */ /* Copyright (c) 2003-2007 Determina Corp. */ /* Copyright (c) 2001-2003 Massachusetts Institute of Technology */ /* Copyright (c) 2000-2001 Hewlett-Packard Company */ /* * dynamo.c -- initialization and cleanup routines for DynamoRIO */ #include "globals.h" #include "configure_defines.h" #include "link.h" #include "fragment.h" #include "fcache.h" #include "emit.h" #include "dispatch.h" #include "utils.h" #include "monitor.h" #include "vmareas.h" #ifdef SIDELINE # include "sideline.h" #endif #ifdef PAPI # include "perfctr.h" #endif #ifdef CLIENT_INTERFACE # include "instrument.h" #endif #include "hotpatch.h" #include "moduledb.h" #include "module_shared.h" #include "synch.h" #include "native_exec.h" #include "jit_opt.h" #ifdef ANNOTATIONS # include "annotations.h" #endif #ifdef WINDOWS /* for close handle, duplicate handle, free memory and constants associated with them */ /* also for nt_terminate_process_for_app() */ # include "ntdll.h" # include "nudge.h" /* to get generic_nudge_target() address for an assert */ #endif #ifdef RCT_IND_BRANCH # include "rct.h" #endif #include "perscache.h" #ifdef VMX86_SERVER # include "vmkuw.h" #endif #ifndef STANDALONE_UNIT_TEST # ifdef __AVX512F__ # error "DynamoRIO core should run without AVX-512 instructions to remain \ portable and to avoid frequency scaling." # endif #endif /* global thread-shared variables */ bool dynamo_initialized = false; bool dynamo_heap_initialized = false; bool dynamo_started = false; bool automatic_startup = false; bool control_all_threads = false; #ifdef WINDOWS bool dr_early_injected = false; int dr_early_injected_location = INJECT_LOCATION_Invalid; bool dr_earliest_injected = false; static void *dr_earliest_inject_args; /* should be set if we are controlling the primary thread, either by * injecting initially (!dr_injected_secondary_thread), or by retaking * over (dr_late_injected_primary_thread). Used only for debugging * purposes, yet can't rely on !dr_injected_secondary_thread very * early in the process */ bool dr_injected_primary_thread = false; bool dr_injected_secondary_thread = false; /* should be set once we retakeover the primary thread for -inject_primary */ bool dr_late_injected_primary_thread = false; #endif /* WINDOWS */ /* flags to indicate when DR is being initialized / exited using the API */ bool dr_api_entry = false; bool dr_api_exit = false; #ifdef RETURN_AFTER_CALL bool dr_preinjected = false; #endif /* RETURN_AFTER_CALL */ #ifdef UNIX static bool dynamo_exiting = false; #endif bool dynamo_exited = false; bool dynamo_exited_all_other_threads = false; bool dynamo_exited_and_cleaned = false; #ifdef DEBUG bool dynamo_exited_log_and_stats = false; #endif /* Only used in release build to decide whether synch is needed, justifying * its placement in .nspdata. If we use it for more we should protect it. */ DECLARE_NEVERPROT_VAR(bool dynamo_all_threads_synched, false); bool dynamo_resetting = false; #if defined(CLIENT_INTERFACE) || defined(STANDALONE_UNIT_TEST) bool standalone_library = false; #endif #ifdef UNIX bool post_execve = false; #endif /* initial stack so we don't have to use app's */ byte *d_r_initstack; event_t dr_app_started; event_t dr_attach_finished; #ifdef WINDOWS /* PR203701: separate stack for error reporting when the dstack is exhausted */ # define EXCEPTION_STACK_SIZE (2 * PAGE_SIZE) DECLARE_NEVERPROT_VAR(byte *exception_stack, NULL); #endif /*******************************************************/ /* separate segment of Non-Self-Protected data to avoid data section * protection issues -- we need to write to these vars in bootstrapping * spots where we cannot unprotect first */ START_DATA_SECTION(NEVER_PROTECTED_SECTION, "w"); /* spinlock used in assembly trampolines when we can't spare registers for more */ mutex_t initstack_mutex VAR_IN_SECTION(NEVER_PROTECTED_SECTION) = INIT_SPINLOCK_FREE(initstack_mutex); byte *initstack_app_xsp VAR_IN_SECTION(NEVER_PROTECTED_SECTION) = 0; /* keeps track of how many threads are in cleanup_and_terminate */ volatile int exiting_thread_count VAR_IN_SECTION(NEVER_PROTECTED_SECTION) = 0; /* Tracks newly created threads not yet on the all_threads list. */ volatile int uninit_thread_count VAR_IN_SECTION(NEVER_PROTECTED_SECTION) = 0; /* This is unprotected to allow stats to be written while the data * segment is still protected (right now the only ones are selfmod stats) */ static dr_statistics_t nonshared_stats VAR_IN_SECTION(NEVER_PROTECTED_SECTION) = { { 0 }, }; /* Each lock protects its corresponding datasec_start, datasec_end, and * datasec_writable variables. */ static mutex_t datasec_lock[DATASEC_NUM] VAR_IN_SECTION(NEVER_PROTECTED_SECTION) = { { 0 } }; /* back to normal section */ END_DATA_SECTION() /*******************************************************/ /* Like a recursive lock: 0==readonly, 1+=writable. * This would be a simple array, but we need each in its own protected * section, as this could be exploited. */ const uint datasec_writable_neverprot = 1; /* always writable */ uint datasec_writable_rareprot = 1; DECLARE_FREQPROT_VAR(uint datasec_writable_freqprot, 1); DECLARE_CXTSWPROT_VAR(uint datasec_writable_cxtswprot, 1); static app_pc datasec_start[DATASEC_NUM]; static app_pc datasec_end[DATASEC_NUM]; const uint DATASEC_SELFPROT[] = { 0, SELFPROT_DATA_RARE, SELFPROT_DATA_FREQ, SELFPROT_DATA_CXTSW, }; const char *const DATASEC_NAMES[] = { NEVER_PROTECTED_SECTION, RARELY_PROTECTED_SECTION, FREQ_PROTECTED_SECTION, CXTSW_PROTECTED_SECTION, }; /* kept in unprotected heap to avoid issues w/ data segment being RO */ typedef struct _protect_info_t { /* FIXME: this needs to be a recursive lock to handle signals * and exceptions! */ mutex_t lock; int num_threads_unprot; /* # threads in DR code */ int num_threads_suspended; } protect_info_t; static protect_info_t *protect_info; static void data_section_init(void); static void data_section_exit(void); #ifdef DEBUG /*************************/ # include <time.h> /* FIXME: not all dynamo_options references are #ifdef DEBUG * are we trying to hardcode the options for a release build? */ # ifdef UNIX /* linux include files for mmap stuff*/ # include <sys/ipc.h> # include <sys/types.h> # include <unistd.h> # endif static uint starttime; file_t main_logfile = INVALID_FILE; #endif /* DEBUG ****************************/ dr_statistics_t *d_r_stats = NULL; DECLARE_FREQPROT_VAR(static int num_known_threads, 0); #ifdef UNIX /* i#237/PR 498284: vfork threads that execve need to be separately delay-freed */ DECLARE_FREQPROT_VAR(int num_execve_threads, 0); #endif DECLARE_FREQPROT_VAR(static uint threads_ever_count, 0); /* FIXME : not static so os.c can hand walk it for dump core */ /* FIXME: use new generic_table_t and generic_hash_* routines */ thread_record_t **all_threads; /* ALL_THREADS_HASH_BITS-bit addressed hash table */ /* these locks are used often enough that we put them in .cspdata: */ /* not static so can be referenced in win32/os.c for SuspendThread handling, * FIXME : is almost completely redundant in usage with thread_initexit_lock * maybe replace this lock with thread_initexit_lock? */ DECLARE_CXTSWPROT_VAR(mutex_t all_threads_lock, INIT_LOCK_FREE(all_threads_lock)); /* used for synch to prevent thread creation/deletion in critical periods * due to its use for flushing, this lock cannot be held while couldbelinking! */ DECLARE_CXTSWPROT_VAR(mutex_t thread_initexit_lock, INIT_LOCK_FREE(thread_initexit_lock)); /* recursive to handle signals/exceptions while in DR code */ DECLARE_CXTSWPROT_VAR(static recursive_lock_t thread_in_DR_exclusion, INIT_RECURSIVE_LOCK(thread_in_DR_exclusion)); static thread_synch_state_t exit_synch_state(void); static void synch_with_threads_at_exit(thread_synch_state_t synch_res, bool pre_exit); /****************************************************************************/ #ifdef DEBUG static const char * main_logfile_name(void) { return get_app_name_for_path(); } static const char * thread_logfile_name(void) { return "log"; } #endif /* DEBUG */ /****************************************************************************/ static void statistics_pre_init(void) { /* until it's set up for real, point at static var * really only logmask and loglevel are meaningful, so be careful! * statistics_init and create_log_directory are the only routines that * use stats before it's set up for real, currently */ /* The indirection here is left over from when we used to allow alternative * locations for stats (namely shared memory for the old MIT gui). */ d_r_stats = &nonshared_stats; d_r_stats->process_id = get_process_id(); strncpy(d_r_stats->process_name, get_application_name(), MAXIMUM_PATH); d_r_stats->process_name[MAXIMUM_PATH - 1] = '\0'; ASSERT(strlen(d_r_stats->process_name) > 0); d_r_stats->num_stats = 0; } static void statistics_init(void) { /* should have called statistics_pre_init() first */ ASSERT(d_r_stats == &nonshared_stats); ASSERT(d_r_stats->num_stats == 0); #ifndef DEBUG if (!DYNAMO_OPTION(global_rstats)) { /* references to stat values should return 0 (static var) */ return; } #endif d_r_stats->num_stats = 0 #ifdef DEBUG # define STATS_DEF(desc, name) +1 #else # define RSTATS_DEF(desc, name) +1 #endif #include "statsx.h" #undef STATS_DEF #undef RSTATS_DEF ; /* We inline the stat description to make it easy for external processes * to view our stats: they don't have to chase pointers, and we could put * this in shared memory easily. However, we do waste some memory, but * not much in release build. */ #ifdef DEBUG # define STATS_DEF(desc, statname) \ strncpy(d_r_stats->statname##_pair.name, desc, \ BUFFER_SIZE_ELEMENTS(d_r_stats->statname##_pair.name)); \ NULL_TERMINATE_BUFFER(d_r_stats->statname##_pair.name); #else # define RSTATS_DEF(desc, statname) \ strncpy(d_r_stats->statname##_pair.name, desc, \ BUFFER_SIZE_ELEMENTS(d_r_stats->statname##_pair.name)); \ NULL_TERMINATE_BUFFER(d_r_stats->statname##_pair.name); #endif #include "statsx.h" #undef STATS_DEF #undef RSTATS_DEF } static void statistics_exit(void) { if (doing_detach) memset(d_r_stats, 0, sizeof(*d_r_stats)); /* for possible re-attach */ d_r_stats = NULL; } dr_statistics_t * get_dr_stats(void) { return d_r_stats; } /* initialize per-process dynamo state; this must be called before any * threads are created and before any other API calls are made; * returns zero on success, non-zero on failure */ DYNAMORIO_EXPORT int dynamorio_app_init(void) { int size; if (!dynamo_initialized /* we do enter if nullcalls is on */) { #ifdef UNIX os_page_size_init((const char **)our_environ, is_our_environ_followed_by_auxv()); #endif #ifdef WINDOWS /* MUST do this before making any system calls */ syscalls_init(); #endif /* avoid time() for libc independence */ DODEBUG(starttime = query_time_seconds();); #ifdef UNIX if (getenv(DYNAMORIO_VAR_EXECVE) != NULL) { post_execve = true; # ifdef VMX86_SERVER /* PR 458917: our gdt slot was not cleared on exec so we need to * clear it now to ensure we don't leak it and eventually run out of * slots. We could alternatively call os_tls_exit() prior to * execve, since syscalls use thread-private fcache_enter, but * complex to recover from execve failure, so instead we pass which * TLS index we had. */ os_tls_pre_init(atoi(getenv(DYNAMORIO_VAR_EXECVE))); # endif /* important to remove it, don't want to propagate to forked children, etc. */ /* i#909: unsetenv is unsafe as it messes up auxv access, so we disable */ disable_env(DYNAMORIO_VAR_EXECVE); /* check that it's gone: we've had problems with unsetenv */ ASSERT(getenv(DYNAMORIO_VAR_EXECVE) == NULL); } else post_execve = false; #endif /* default non-zero dynamo settings (options structure is * initialized to 0 automatically) */ #ifdef DEBUG # ifndef INTERNAL nonshared_stats.logmask = LOG_ALL_RELEASE; # else nonshared_stats.logmask = LOG_ALL; # endif statistics_pre_init(); #endif d_r_config_init(); options_init(); #ifdef WINDOWS syscalls_init_options_read(); /* must be called after options_init * but before init_syscall_trampolines */ #endif utils_init(); data_section_init(); #ifdef DEBUG /* decision: nullcalls WILL create a dynamorio.log file and * fill it with perfctr stats! */ if (d_r_stats->loglevel > 0) { main_logfile = open_log_file(main_logfile_name(), NULL, 0); LOG(GLOBAL, LOG_TOP, 1, "global log file fd=%d\n", main_logfile); } else { /* loglevel 0 means we don't create a log file! * if the loglevel is later raised, too bad! it all goes to stderr! * N.B.: when checking for no logdir, we check for empty string or * first char '<'! */ strncpy(d_r_stats->logdir, "<none (loglevel was 0 on startup)>", MAXIMUM_PATH - 1); d_r_stats->logdir[MAXIMUM_PATH - 1] = '\0'; /* if max no null */ main_logfile = INVALID_FILE; } # ifdef PAPI /* setup hardware performance counting */ hardware_perfctr_init(); # endif DOLOG(1, LOG_TOP, { print_version_and_app_info(GLOBAL); }); /* now exit if nullcalls, now that perfctrs are set up */ if (INTERNAL_OPTION(nullcalls)) { print_file(main_logfile, "** nullcalls is set, NOT taking over execution **\n\n"); return SUCCESS; } LOG(GLOBAL, LOG_TOP, 1, PRODUCT_NAME "'s stack size: %d Kb\n", DYNAMORIO_STACK_SIZE / 1024); #endif /* !DEBUG */ /* set up exported statistics struct */ #ifndef DEBUG statistics_pre_init(); #endif statistics_init(); #ifdef VMX86_SERVER /* Must be before {vmm,d_r}_heap_init() */ vmk_init_lib(); #endif /* initialize components (CAUTION: order is important here) */ vmm_heap_init(); /* must be called even if not using vmm heap */ #ifdef CLIENT_INTERFACE /* PR 200207: load the client lib before callback_interception_init * since the client library load would hit our own hooks (xref hotpatch * cases about that) -- though -private_loader removes that issue. */ instrument_load_client_libs(); #endif d_r_heap_init(); dynamo_heap_initialized = true; /* The process start event should be done after d_r_os_init() but before * process_control_int() because the former initializes event logging * and the latter can kill the process if a violation occurs. */ SYSLOG(SYSLOG_INFORMATION, IF_CLIENT_INTERFACE_ELSE(INFO_PROCESS_START_CLIENT, INFO_PROCESS_START), IF_CLIENT_INTERFACE_ELSE(2, 3), get_application_name(), get_application_pid() _IF_NOT_CLIENT_INTERFACE(get_application_md5())); #ifdef PROCESS_CONTROL if (IS_PROCESS_CONTROL_ON()) /* Case 8594. */ process_control_init(); #endif #ifdef WINDOWS /* Now that DR is set up, perform any final clean-up, before * we do our address space scans. */ if (dr_earliest_injected) earliest_inject_cleanup(dr_earliest_inject_args); #endif dynamo_vm_areas_init(); d_r_decode_init(); proc_init(); modules_init(); /* before vm_areas_init() */ d_r_os_init(); config_heap_init(); /* after heap_init */ /* Setup for handling faults in loader_init() */ /* initial stack so we don't have to use app's * N.B.: we never de-allocate d_r_initstack (see comments in app_exit) */ d_r_initstack = (byte *)stack_alloc(DYNAMORIO_STACK_SIZE, NULL); LOG(GLOBAL, LOG_SYNCH, 2, "d_r_initstack is " PFX "-" PFX "\n", d_r_initstack - DYNAMORIO_STACK_SIZE, d_r_initstack); #ifdef WINDOWS /* PR203701: separate stack for error reporting when the * dstack is exhausted */ exception_stack = (byte *)stack_alloc(EXCEPTION_STACK_SIZE, NULL); #endif #ifdef WINDOWS if (!INTERNAL_OPTION(noasynch)) { /* We split the hooks up: first we put in just Ki* to catch * exceptions in client init routines (PR 200207), but we don't want * syscall hooks so client init can scan syscalls. * Xref PR 216934 where this was originally down below 1st thread init, * before we had GLOBAL_DCONTEXT. */ callback_interception_init_start(); } #endif /* WINDOWS */ #ifdef WINDOWS /* loader initialization, finalize the private lib load. * i#338: this must be before d_r_arch_init() for Windows, but Linux * wants it later (i#2751). */ loader_init(); #endif d_r_arch_init(); synch_init(); #ifdef KSTATS kstat_init(); #endif d_r_monitor_init(); fcache_init(); d_r_link_init(); fragment_init(); moduledb_init(); /* before vm_areas_init, after heap_init */ perscache_init(); /* before vm_areas_init */ native_exec_init(); /* before vm_areas_init, after arch_init */ if (!DYNAMO_OPTION(thin_client)) { #ifdef HOT_PATCHING_INTERFACE /* must init hotp before vm_areas_init() calls find_executable_vm_areas() */ if (DYNAMO_OPTION(hot_patching)) hotp_init(); #endif } #ifdef INTERNAL { char initial_options[MAX_OPTIONS_STRING]; get_dynamo_options_string(&dynamo_options, initial_options, sizeof(initial_options), true); SYSLOG_INTERNAL_INFO("Initial options = %s", initial_options); DOLOG(1, LOG_TOP, { get_pcache_dynamo_options_string(&dynamo_options, initial_options, sizeof(initial_options), OP_PCACHE_LOCAL); LOG(GLOBAL, LOG_TOP, 1, "Initial pcache-affecting options = %s\n", initial_options); }); } #endif /* INTERNAL */ LOG(GLOBAL, LOG_TOP, 1, "\n"); /* initialize thread hashtable */ /* Note: for thin_client, this isn't needed if it is only going to * look for spawned processes; however, if we plan to promote from * thin_client to hotp_only mode (highly likely), this would be needed. * For now, leave it in there unless thin_client footprint becomes an * issue. */ size = HASHTABLE_SIZE(ALL_THREADS_HASH_BITS) * sizeof(thread_record_t *); all_threads = (thread_record_t **)global_heap_alloc(size HEAPACCT(ACCT_THREAD_MGT)); memset(all_threads, 0, size); if (!INTERNAL_OPTION(nop_initial_bblock) IF_WINDOWS( || !check_sole_thread())) /* some other thread is already here! */ bb_lock_start = true; #ifdef SIDELINE /* initialize sideline thread after thread table is set up */ if (dynamo_options.sideline) sideline_init(); #endif /* thread-specific initialization for the first thread we inject in * (in a race with injected threads, sometimes it is not the primary thread) */ /* i#117/PR 395156: it'd be nice to have mc here but would * require changing start/stop API */ dynamo_thread_init(NULL, NULL, NULL _IF_CLIENT_INTERFACE(false)); #ifndef WINDOWS /* i#2751: we need TLS to be set up to relocate and call init funcs. */ loader_init(); #endif /* We move vm_areas_init() below dynamo_thread_init() so we can have * two things: 1) a dcontext and 2) a SIGSEGV handler, for TRY/EXCEPT * inside vm_areas_init() for PR 361594's probes and for d_r_safe_read(). * This means vm_areas_thread_init() runs before vm_areas_init(). */ if (!DYNAMO_OPTION(thin_client)) { vm_areas_init(); #ifdef RCT_IND_BRANCH /* relies on is_in_dynamo_dll() which needs vm_areas_init */ rct_init(); #endif } else { /* This is needed to handle exceptions in thin_client mode, mostly * internal ones, but can be app ones too. */ dynamo_vm_areas_lock(); find_dynamo_library_vm_areas(); dynamo_vm_areas_unlock(); } #ifdef ANNOTATIONS annotation_init(); #endif jitopt_init(); dr_attach_finished = create_broadcast_event(); /* New client threads rely on dr_app_started being initialized, so do * that before initializing clients. */ dr_app_started = create_broadcast_event(); #ifdef CLIENT_INTERFACE /* client last, in case it depends on other inits: must be after * dynamo_thread_init so the client can use a dcontext (PR 216936). * Note that we *load* the client library before installing our hooks, * but call the client's init routine afterward so that we correctly * report crashes (PR 200207). * Note: DllMain in client libraries can crash and we still won't * report; better document that client libraries shouldn't have * DllMain. */ instrument_init(); /* To give clients a chance to process pcaches as we load them, we * delay the loading until we've initialized the clients. */ vm_area_delay_load_coarse_units(); #endif #ifdef WINDOWS if (!INTERNAL_OPTION(noasynch)) callback_interception_init_finish(); /* split for PR 200207: see above */ #endif if (SELF_PROTECT_ON_CXT_SWITCH) { protect_info = (protect_info_t *)global_unprotected_heap_alloc( sizeof(protect_info_t) HEAPACCT(ACCT_OTHER)); ASSIGN_INIT_LOCK_FREE(protect_info->lock, protect_info); protect_info->num_threads_unprot = 0; /* ENTERING_DR() below will inc to 1 */ protect_info->num_threads_suspended = 0; if (INTERNAL_OPTION(single_privileged_thread)) { /* FIXME: thread_initexit_lock must be a recursive lock! */ ASSERT_NOT_IMPLEMENTED(false); /* grab the lock now -- the thread that is in dynamo must be holding * the lock, and we are the initial thread in dynamo! */ d_r_mutex_lock(&thread_initexit_lock); } /* ENTERING_DR will increment, so decrement first * FIXME: waste of protection change since will nop-unprotect! */ if (TEST(SELFPROT_DATA_CXTSW, DYNAMO_OPTION(protect_mask))) datasec_writable_cxtswprot = 0; /* FIXME case 8073: remove once freqprot not every cxt sw */ if (TEST(SELFPROT_DATA_FREQ, DYNAMO_OPTION(protect_mask))) datasec_writable_freqprot = 0; } /* this thread is now entering DR */ ENTERING_DR(); #ifdef WINDOWS if (DYNAMO_OPTION(early_inject)) { /* AFTER callback_interception_init and self protect init and * ENTERING_DR() */ early_inject_init(); } #endif } dynamo_initialized = true; /* Protect .data, assuming all vars there have been initialized. */ SELF_PROTECT_DATASEC(DATASEC_RARELY_PROT); /* internal-only options for testing run-once (case 3990) */ if (INTERNAL_OPTION(unsafe_crash_process)) { SYSLOG_INTERNAL_ERROR("Crashing the process deliberately!"); *((int *)PTR_UINT_MINUS_1) = 0; } if (INTERNAL_OPTION(unsafe_hang_process)) { event_t never_signaled = create_event(); SYSLOG_INTERNAL_ERROR("Hanging the process deliberately!"); wait_for_event(never_signaled, 0); destroy_event(never_signaled); } return SUCCESS; } #ifdef UNIX void dynamorio_fork_init(dcontext_t *dcontext) { /* on a fork we want to re-initialize some data structures, especially * log files, which we want a separate directory for */ thread_record_t **threads; int i, num_threads; # ifdef DEBUG char parent_logdir[MAXIMUM_PATH]; # endif /* re-cache app name, etc. that are using parent pid before we * create log dirs (xref i#189/PR 452168) */ os_fork_init(dcontext); /* sanity check, plus need to set this for statistics_init: * even if parent did an execve, env var should be reset by now */ post_execve = (getenv(DYNAMORIO_VAR_EXECVE) != NULL); ASSERT(!post_execve); # ifdef DEBUG /* copy d_r_stats->logdir * d_r_stats->logdir is static, so current copy is fine, don't need * frozen copy */ strncpy(parent_logdir, d_r_stats->logdir, MAXIMUM_PATH - 1); d_r_stats->logdir[MAXIMUM_PATH - 1] = '\0'; /* if max no null */ # endif if (get_log_dir(PROCESS_DIR, NULL, NULL)) { /* we want brand new log dir */ enable_new_log_dir(); create_log_dir(PROCESS_DIR); } # ifdef DEBUG /* just like dynamorio_app_init, create main_logfile before stats */ if (d_r_stats->loglevel > 0) { /* we want brand new log files. os_fork_init() closed inherited files. */ main_logfile = open_log_file(main_logfile_name(), NULL, 0); print_file(main_logfile, "%s\n", dynamorio_version_string); print_file(main_logfile, "New log file for child %d forked by parent %d\n", d_r_get_thread_id(), get_parent_id()); print_file(main_logfile, "Parent's log dir: %s\n", parent_logdir); } d_r_stats->process_id = get_process_id(); if (d_r_stats->loglevel > 0) { /* FIXME: share these few lines of code w/ dynamorio_app_init? */ LOG(GLOBAL, LOG_TOP, 1, "Running: %s\n", d_r_stats->process_name); # ifndef _WIN32_WCE LOG(GLOBAL, LOG_TOP, 1, "DYNAMORIO_OPTIONS: %s\n", option_string); # endif } # endif /* DEBUG */ vmm_heap_fork_init(dcontext); /* must re-hash parent entry in threads table, plus no longer have any * other threads (fork -> we're alone in address space), so clear * out entire thread table, then add child */ d_r_mutex_lock(&thread_initexit_lock); get_list_of_threads_ex(&threads, &num_threads, true /*include execve*/); for (i = 0; i < num_threads; i++) { if (threads[i] == dcontext->thread_record) remove_thread(threads[i]->id); else dynamo_other_thread_exit(threads[i]); } d_r_mutex_unlock(&thread_initexit_lock); global_heap_free(threads, num_threads * sizeof(thread_record_t *) HEAPACCT(ACCT_THREAD_MGT)); add_thread(get_process_id(), d_r_get_thread_id(), true /*under dynamo control*/, dcontext); GLOBAL_STAT(num_threads) = 1; # ifdef DEBUG if (d_r_stats->loglevel > 0) { /* need a new thread-local logfile */ dcontext->logfile = open_log_file(thread_logfile_name(), NULL, 0); print_file(dcontext->logfile, "%s\n", dynamorio_version_string); print_file(dcontext->logfile, "New log file for child %d forked by parent %d\n", d_r_get_thread_id(), get_parent_id()); LOG(THREAD, LOG_TOP | LOG_THREADS, 1, "THREAD %d (dcontext " PFX ")\n\n", d_r_get_thread_id(), dcontext); } # endif num_threads = 1; /* FIXME: maybe should have a callback list for who wants to be notified * on a fork -- probably everyone who makes a log file on init. */ fragment_fork_init(dcontext); /* this must be called after dynamo_other_thread_exit() above */ signal_fork_init(dcontext); # ifdef CLIENT_INTERFACE if (CLIENTS_EXIST()) { instrument_fork_init(dcontext); } # endif } #endif /* UNIX */ #if defined(CLIENT_INTERFACE) || defined(STANDALONE_UNIT_TEST) /* To make DynamoRIO useful as a library for a standalone client * application (as opposed to a client library that works with * DynamoRIO in executing a target application). This makes DynamoRIO * useful as an IA-32 disassembly library, etc. */ dcontext_t * standalone_init(void) { dcontext_t *dcontext; if (dynamo_initialized) return GLOBAL_DCONTEXT; standalone_library = true; /* We have release-build stats now so this is not just DEBUG */ d_r_stats = &nonshared_stats; /* No reason to limit heap size when there's no code cache. */ IF_X64(dynamo_options.reachable_heap = false;) dynamo_options.vm_base_near_app = false; # if defined(INTERNAL) && defined(DEADLOCK_AVOIDANCE) /* avoid issues w/ GLOBAL_DCONTEXT instead of thread dcontext */ dynamo_options.deadlock_avoidance = false; # endif # ifdef UNIX os_page_size_init((const char **)our_environ, is_our_environ_followed_by_auxv()); # endif # ifdef WINDOWS /* MUST do this before making any system calls */ if (!syscalls_init()) return NULL; /* typically b/c of unsupported OS version */ # endif d_r_config_init(); options_init(); vmm_heap_init(); d_r_heap_init(); dynamo_heap_initialized = true; dynamo_vm_areas_init(); d_r_decode_init(); proc_init(); d_r_os_init(); config_heap_init(); # ifdef STANDALONE_UNIT_TEST os_tls_init(); dcontext = create_new_dynamo_context(true /*initial*/, NULL, NULL); set_thread_private_dcontext(dcontext); /* sanity check */ ASSERT(get_thread_private_dcontext() == dcontext); heap_thread_init(dcontext); # ifdef DEBUG /* FIXME: share code w/ main init routine? */ nonshared_stats.logmask = LOG_ALL; options_init(); if (d_r_stats->loglevel > 0) { char initial_options[MAX_OPTIONS_STRING]; main_logfile = open_log_file(main_logfile_name(), NULL, 0); print_file(main_logfile, "%s\n", dynamorio_version_string); print_file(main_logfile, "Log file for standalone unit test\n"); get_dynamo_options_string(&dynamo_options, initial_options, sizeof(initial_options), true); SYSLOG_INTERNAL_INFO("Initial options = %s", initial_options); print_file(main_logfile, "\n"); } # endif /* DEBUG */ # else /* rather than ask the user to call some thread-init routine in * every thread, we just use global dcontext everywhere (i#548) */ dcontext = GLOBAL_DCONTEXT; # endif /* since we do not export any dr_standalone_exit(), we clean up any .1config * file right now. the only loss if that we can't synch options: but that * should be less important for standalone. we disabling synching. */ /* options are never made read-only for standalone */ dynamo_options.dynamic_options = false; dynamo_initialized = true; return dcontext; } void standalone_exit(void) { /* We support re-attach by setting doing_detach. */ doing_detach = true; config_heap_exit(); os_fast_exit(); os_slow_exit(); dynamo_vm_areas_exit(); d_r_heap_exit(); vmm_heap_exit(); options_exit(); d_r_config_exit(); doing_detach = false; standalone_library = false; dynamo_initialized = false; } #endif /* Perform exit tasks that require full thread data structs, which we have * already cleaned up by the time we reach dynamo_shared_exit() for both * debug and detach paths. */ void dynamo_process_exit_with_thread_info(void) { perscache_fast_exit(); /* "fast" b/c called in release as well */ } /* shared between app_exit and detach */ int dynamo_shared_exit(thread_record_t *toexit /* must ==cur thread for Linux */ _IF_WINDOWS(bool detach_stacked_callbacks)) { DEBUG_DECLARE(uint endtime); /* set this now, could already be set */ dynamo_exited = true; /* avoid time() for libc independence */ DODEBUG(endtime = query_time_seconds();); LOG(GLOBAL, LOG_STATS, 1, "\n#### Statistics for entire process:\n"); LOG(GLOBAL, LOG_STATS, 1, "Total running time: %d seconds\n", endtime - starttime); #ifdef PAPI hardware_perfctr_exit(); #endif #ifdef DEBUG # if defined(INTERNAL) && defined(X86) print_optimization_stats(); # endif /* INTERNAL && X86 */ DOLOG(1, LOG_STATS, { dump_global_stats(false); }); #endif /* DEBUG */ if (SELF_PROTECT_ON_CXT_SWITCH) { DELETE_LOCK(protect_info->lock); global_unprotected_heap_free(protect_info, sizeof(protect_info_t) HEAPACCT(ACCT_OTHER)); } /* call all component exit routines (CAUTION: order is important here) */ DELETE_RECURSIVE_LOCK(thread_in_DR_exclusion); DOSTATS({ LOG(GLOBAL, LOG_TOP | LOG_THREADS, 1, "fcache_stats_exit: before fragment cleanup\n"); DOLOG(1, LOG_CACHE, fcache_stats_exit();); }); #ifdef RCT_IND_BRANCH if (!DYNAMO_OPTION(thin_client)) rct_exit(); #endif fragment_exit(); #ifdef ANNOTATIONS annotation_exit(); #endif jitopt_exit(); #ifdef CLIENT_INTERFACE /* We tell the client as soon as possible in case it wants to use services from other * components. Must be after fragment_exit() so that the client gets all the * fragment_deleted() callbacks (xref PR 228156). FIXME - might be issues with the * client trying to use api routines that depend on fragment state. */ instrument_exit(); # ifdef CLIENT_SIDELINE /* We only need do a second synch-all if there are sideline client threads. */ if (d_r_get_num_threads() > 1) synch_with_threads_at_exit(exit_synch_state(), false /*post-exit*/); /* only current thread is alive */ dynamo_exited_all_other_threads = true; # endif /* CLIENT_SIDELINE */ /* Some lock can only be deleted if only one thread left. */ instrument_exit_post_sideline(); #endif /* CLIENT_INTERFACE */ fragment_exit_post_sideline(); /* The dynamo_exited_and_cleaned should be set after the second synch-all. * If it is set earlier after the first synch-all, some client thread may * have memory leak due to dynamo_thread_exit_pre_client being skipped in * dynamo_thread_exit_common called from exiting client threads. */ dynamo_exited_and_cleaned = true; destroy_event(dr_app_started); destroy_event(dr_attach_finished); /* we want dcontext around for loader_exit() */ if (get_thread_private_dcontext() != NULL) loader_thread_exit(get_thread_private_dcontext()); loader_exit(); if (toexit != NULL) { /* free detaching thread's dcontext */ #ifdef WINDOWS /* If we use dynamo_thread_exit() when toexit is the current thread, * it results in asserts in the win32.tls test, so we stick with this. */ d_r_mutex_lock(&thread_initexit_lock); dynamo_other_thread_exit(toexit, false); d_r_mutex_unlock(&thread_initexit_lock); #else /* On Linux, restoring segment registers can only be done * on the current thread, which must be toexit. */ ASSERT(toexit->id == d_r_get_thread_id()); dynamo_thread_exit(); #endif } if (IF_WINDOWS_ELSE(!detach_stacked_callbacks, true)) { /* We don't fully free cur thread until after client exit event (PR 536058) */ if (thread_lookup(d_r_get_thread_id()) == NULL) { LOG(GLOBAL, LOG_TOP | LOG_THREADS, 1, "Current thread never under DynamoRIO control, not exiting it\n"); } else { /* call thread_exit even if !under_dynamo_control, could have * been at one time */ /* exit this thread now */ dynamo_thread_exit(); } } /* now that the final thread is exited, free the all_threads memory */ d_r_mutex_lock(&all_threads_lock); global_heap_free(all_threads, HASHTABLE_SIZE(ALL_THREADS_HASH_BITS) * sizeof(thread_record_t *) HEAPACCT(ACCT_THREAD_MGT)); all_threads = NULL; d_r_mutex_unlock(&all_threads_lock); #ifdef WINDOWS # ifdef CLIENT_INTERFACE /* for -private_loader we do this here to catch more exit-time crashes */ if (!INTERNAL_OPTION(noasynch) && INTERNAL_OPTION(private_loader) && !doing_detach) callback_interception_unintercept(); # endif /* callback_interception_exit must be after fragment exit for CLIENT_INTERFACE so * that fragment_exit->frees fragments->instrument_fragment_deleted-> * hide_tag_from_fragment->is_intercepted_app_pc won't crash. xref PR 228156 */ if (!INTERNAL_OPTION(noasynch)) { callback_interception_exit(); } #endif d_r_link_exit(); fcache_exit(); d_r_monitor_exit(); synch_exit(); d_r_arch_exit(IF_WINDOWS(detach_stacked_callbacks)); #ifdef CALL_PROFILE /* above os_exit to avoid eventlog_mutex trigger if we're the first to * create a log file */ profile_callers_exit(); #endif os_fast_exit(); os_slow_exit(); native_exec_exit(); /* before vm_areas_exit for using dynamo_areas */ vm_areas_exit(); perscache_slow_exit(); /* fast called in dynamo_process_exit_with_thread_info() */ modules_exit(); /* after aslr_exit() from os_slow_exit(), * after vm_areas & perscache exits */ moduledb_exit(); /* before heap_exit */ #ifdef HOT_PATCHING_INTERFACE if (DYNAMO_OPTION(hot_patching)) hotp_exit(); #endif #ifdef WINDOWS /* Free exception stack before calling heap_exit */ stack_free(exception_stack, EXCEPTION_STACK_SIZE); exception_stack = NULL; #endif config_heap_exit(); d_r_heap_exit(); vmm_heap_exit(); diagnost_exit(); data_section_exit(); /* funny dependences: options exit just frees lock, not destroying * any options that are needed for other exits, so do it prior to * checking locks in debug build */ options_exit(); utils_exit(); d_r_config_exit(); #ifdef KSTATS kstat_exit(); #endif DELETE_LOCK(all_threads_lock); DELETE_LOCK(thread_initexit_lock); DOLOG(1, LOG_STATS, { /* dump after cleaning up to make it easy to check if stats that * are inc-ed and dec-ed actually come down to 0 */ dump_global_stats(false); }); if (INTERNAL_OPTION(rstats_to_stderr)) dump_global_rstats_to_stderr(); statistics_exit(); #ifdef DEBUG # ifdef DEADLOCK_AVOIDANCE ASSERT(locks_not_closed() == 0); # endif dynamo_exited_log_and_stats = true; if (main_logfile != STDERR) { /* do it this way just in case someone tries to log to the global file * right now */ file_t file_temp = main_logfile; main_logfile = INVALID_FILE; close_log_file(file_temp); } #else # ifdef DEADLOCK_AVOIDANCE ASSERT(locks_not_closed() == 0); # endif #endif /* DEBUG */ dynamo_initialized = false; dynamo_started = false; return SUCCESS; } /* NOINLINE because dynamorio_app_exit is a stopping point. */ NOINLINE int dynamorio_app_exit(void) { return dynamo_process_exit(); } /* synchs with all threads using synch type synch_res. * also sets dynamo_exited to true. * does not resume the threads but does release the thread_initexit_lock. */ static void synch_with_threads_at_exit(thread_synch_state_t synch_res, bool pre_exit) { int num_threads; thread_record_t **threads; DEBUG_DECLARE(bool ok;) /* If we fail to suspend a thread (e.g., privilege * problems) ignore it. XXX: retry instead? */ uint flags = THREAD_SYNCH_SUSPEND_FAILURE_IGNORE; if (pre_exit) { /* i#297: we only synch client threads after process exit event. */ flags |= THREAD_SYNCH_SKIP_CLIENT_THREAD; } LOG(GLOBAL, LOG_TOP | LOG_THREADS, 1, "\nsynch_with_threads_at_exit: cleaning up %d un-terminated threads\n", d_r_get_num_threads()); #if defined(CLIENT_INTERFACE) && defined(WINDOWS) /* make sure client nudges are finished */ wait_for_outstanding_nudges(); #endif /* xref case 8747, requesting suspended is preferable to terminated and it * doesn't make a difference here which we use (since the process is about * to die). * On Linux, however, we do not have dependencies on OS thread * properties like we do on Windows (TEB, etc.), and our suspended * threads use their sigstacks and ostd data structs, making cleanup * while still catching other leaks more difficult: thus it's * simpler to terminate and then clean up. FIXME: by terminating * we'll raise SIGCHLD that may not have been raised natively if the * whole group went down in a single SYS_exit_group. Instead we * could have the suspended thread move from the sigstack-reliant * loop to a stack-free loop (xref i#95). */ IF_UNIX(dynamo_exiting = true;) /* include execve-exited vfork threads */ DEBUG_DECLARE(ok =) synch_with_all_threads(synch_res, &threads, &num_threads, /* Case 6821: other synch-all-thread uses that * only care about threads carrying fcache * state can ignore us */ THREAD_SYNCH_NO_LOCKS_NO_XFER, flags); ASSERT(ok); ASSERT(threads == NULL && num_threads == 0); /* We asked for CLEANED */ /* the synch_with_all_threads function grabbed the * thread_initexit_lock for us! */ /* do this now after all threads we know about are killed and * while we hold the thread_initexit_lock so any new threads that * are waiting on it won't get in our way (see thread_init()) */ dynamo_exited = true; end_synch_with_all_threads(threads, num_threads, false /*don't resume*/); } static thread_synch_state_t exit_synch_state(void) { thread_synch_state_t synch_res = IF_WINDOWS_ELSE(THREAD_SYNCH_SUSPENDED_AND_CLEANED, THREAD_SYNCH_TERMINATED_AND_CLEANED); #if defined(DR_APP_EXPORTS) && defined(UNIX) if (dr_api_exit) { /* Don't terminate the app's threads in case the app plans to continue * after dr_app_cleanup(). Note that today we don't fully support that * anyway: the app should use dr_app_stop_and_cleanup() whose detach * code won't come here. */ synch_res = THREAD_SYNCH_SUSPENDED_AND_CLEANED; } #endif return synch_res; } #ifdef DEBUG /* cleanup after the application has exited */ static int dynamo_process_exit_cleanup(void) { /* CAUTION: this should only be invoked after all app threads have stopped */ if (!dynamo_exited && !INTERNAL_OPTION(nullcalls)) { dcontext_t *dcontext; APP_EXPORT_ASSERT(dynamo_initialized, "Improper DynamoRIO initialization"); dcontext = get_thread_private_dcontext(); /* we deliberately do NOT clean up d_r_initstack (which was * allocated using a separate mmap and so is not part of some * large unit that is de-allocated), as it is used in special * circumstances to call us...FIXME: is this memory leak ok? * is there a better solution besides assuming the app stack? */ # ifdef SIDELINE if (dynamo_options.sideline) { /* exit now to make thread cleanup simpler */ sideline_exit(); } # endif /* perform exit tasks that require full thread data structs */ dynamo_process_exit_with_thread_info(); if (INTERNAL_OPTION(single_privileged_thread)) { d_r_mutex_unlock(&thread_initexit_lock); } /* if ExitProcess called before all threads terminated, they won't * all have gone through dynamo_thread_exit, so clean them up now * so we can get stats about them * * we don't check control_all_threads b/c we're just killing * the threads we know about here */ synch_with_threads_at_exit(exit_synch_state(), true /*pre-exit*/); # ifndef CLIENT_SIDELINE /* no sideline thread, synchall done */ dynamo_exited_all_other_threads = true; # endif /* now that APC interception point is unpatched and * dynamorio_exited is set and we've killed all the theads we know * about, assumption is that no other threads will be running in * dynamorio code from here on out (esp. when we get into shared exit) * that will do anything that could be dangerous (could possibly be * a thread in the APC interception code prior to reaching thread_init * but it will only global log and do thread_lookup which should be * safe throughout) */ /* In order to pass the client a dcontext in the process exit event * we do some thread cleanup early for the final thread so we can delay * the rest (PR 536058). This is a little risky in that we * clean up dcontext->fragment_field, which is used for lots of * things like couldbelinking (and thus we have to disable some API * routines in the thread exit event: i#1989). */ dynamo_thread_exit_pre_client(get_thread_private_dcontext(), d_r_get_thread_id()); # ifdef WINDOWS /* FIXME : our call un-interception isn't atomic so (miniscule) chance * of something going wrong if new thread is just hitting its init APC */ /* w/ the app's loader we must remove our LdrUnloadDll hook * before we unload the client lib (and thus we miss client * exit crashes): xref PR 200207. */ if (!INTERNAL_OPTION(noasynch) IF_CLIENT_INTERFACE(&&!INTERNAL_OPTION(private_loader))) { callback_interception_unintercept(); } # else /* UNIX */ unhook_vsyscall(); # endif /* UNIX */ return dynamo_shared_exit(NULL /* not detaching */ _IF_WINDOWS(false /* not detaching */)); } return SUCCESS; } #endif /* DEBUG */ int dynamo_nullcalls_exit(void) { /* this routine is used when nullcalls is turned on * simply to get perfctr numbers in a log file */ ASSERT(INTERNAL_OPTION(nullcalls)); #ifdef PAPI hardware_perfctr_exit(); #endif #ifdef DEBUG if (main_logfile != STDERR) { close_log_file(main_logfile); main_logfile = INVALID_FILE; } #endif /* DEBUG */ dynamo_exited = true; return SUCCESS; } /* called when we see that the process is about to exit */ int dynamo_process_exit(void) { #ifndef DEBUG bool each_thread; #endif SELF_UNPROTECT_DATASEC(DATASEC_RARELY_PROT); synchronize_dynamic_options(); SYSLOG(SYSLOG_INFORMATION, INFO_PROCESS_STOP, 2, get_application_name(), get_application_pid()); #ifdef DEBUG if (!dynamo_exited) { if (INTERNAL_OPTION(nullcalls)) { /* if nullcalls is on we still do perfctr stats, and this is * the only place we can print them out and exit */ dynamo_nullcalls_exit(); } else { /* we don't check automatic_startup -- even if the app_ * interface is used, we are about to be gone from the process * address space, so we clean up now */ LOG(GLOBAL, LOG_TOP, 1, "\ndynamo_process_exit from thread " TIDFMT " -- cleaning up dynamo\n", d_r_get_thread_id()); dynamo_process_exit_cleanup(); } } return SUCCESS; #else if (dynamo_exited) return SUCCESS; /* don't need to do much! * we didn't create any IPC objects or anything that might be persistent * beyond our death, we're not holding any systemwide locks, etc. */ /* It is not clear whether the Event Log service handles unterminated connections */ /* Do we need profile data for each thread? * Note that windows prof_pcs duplicates the thread walk in d_r_os_exit() * FIXME: should combine that thread walk with this one */ each_thread = TRACEDUMP_ENABLED(); # ifdef UNIX each_thread = each_thread || INTERNAL_OPTION(profile_pcs); # endif # ifdef KSTATS each_thread = each_thread || DYNAMO_OPTION(kstats); # endif # ifdef CLIENT_INTERFACE each_thread = each_thread || /* If we don't need a thread exit event, avoid the possibility of * racy crashes (PR 470957) by not calling instrument_thread_exit() */ (!INTERNAL_OPTION(nullcalls) && dr_thread_exit_hook_exists() && !DYNAMO_OPTION(skip_thread_exit_at_exit)); # endif if (DYNAMO_OPTION(synch_at_exit) /* by default we synch if any exit event exists */ IF_CLIENT_INTERFACE( || (!DYNAMO_OPTION(multi_thread_exit) && dr_exit_hook_exists()) || (!DYNAMO_OPTION(skip_thread_exit_at_exit) && dr_thread_exit_hook_exists()))) { /* needed primarily for CLIENT_INTERFACE but technically all configurations * can have racy crashes at exit time (xref PR 470957) */ synch_with_threads_at_exit(exit_synch_state(), true /*pre-exit*/); # ifndef CLIENT_SIDELINE dynamo_exited_all_other_threads = true; # endif } else dynamo_exited = true; if (each_thread) { thread_record_t **threads; int num, i; d_r_mutex_lock(&thread_initexit_lock); get_list_of_threads(&threads, &num); for (i = 0; i < num; i++) { # ifdef CLIENT_SIDELINE if (IS_CLIENT_THREAD(threads[i]->dcontext)) continue; # endif /* FIXME: separate trace dump from rest of fragment cleanup code */ if (TRACEDUMP_ENABLED() IF_CLIENT_INTERFACE(|| true)) { /* We always want to call this for CI builds so we can get the * dr_fragment_deleted() callbacks. */ fragment_thread_exit(threads[i]->dcontext); } # ifdef UNIX if (INTERNAL_OPTION(profile_pcs)) pcprofile_thread_exit(threads[i]->dcontext); # endif # ifdef KSTATS if (DYNAMO_OPTION(kstats)) kstat_thread_exit(threads[i]->dcontext); # endif # ifdef CLIENT_INTERFACE /* Inform client of all thread exits */ if (!INTERNAL_OPTION(nullcalls) && !DYNAMO_OPTION(skip_thread_exit_at_exit)) { instrument_thread_exit_event(threads[i]->dcontext); /* i#1617: ensure we do all cleanup of priv libs */ if (threads[i]->id != d_r_get_thread_id()) /* i#1617: must delay this */ loader_thread_exit(threads[i]->dcontext); } # endif } global_heap_free(threads, num * sizeof(thread_record_t *) HEAPACCT(ACCT_THREAD_MGT)); d_r_mutex_unlock(&thread_initexit_lock); } /* PR 522783: must be before we clear dcontext (if CLIENT_INTERFACE)! */ /* must also be prior to fragment_exit so we actually freeze pcaches (i#703) */ dynamo_process_exit_with_thread_info(); /* FIXME: separate trace dump from rest of fragment cleanup code. For client * interface we need to call fragment_exit to get all the fragment deleted events. */ if (TRACEDUMP_ENABLED() IF_CLIENT_INTERFACE(|| dr_fragment_deleted_hook_exists())) fragment_exit(); /* Inform client of process exit */ # ifdef CLIENT_INTERFACE if (!INTERNAL_OPTION(nullcalls)) { # ifdef WINDOWS /* instrument_exit() unloads the client library, so make sure * LdrUnloadDll isn't hooked if using the app loader. */ if (!INTERNAL_OPTION(noasynch) IF_CLIENT_INTERFACE(&&!INTERNAL_OPTION(private_loader))) { callback_interception_unintercept(); } # endif # ifdef UNIX /* i#2976: unhook prior to client exit if modules are being watched */ if (dr_modload_hook_exists()) unhook_vsyscall(); # endif /* Must be after fragment_exit() so that the client gets all the * fragment_deleted() callbacks (xref PR 228156). FIXME - might be issues * with the client trying to use api routines that depend on fragment state. */ instrument_exit(); # ifdef CLIENT_SIDELINE /* We only need do a second synch-all if there are sideline client threads. */ if (d_r_get_num_threads() > 1) synch_with_threads_at_exit(exit_synch_state(), false /*post-exit*/); dynamo_exited_all_other_threads = true; # endif /* Some lock can only be deleted if one thread left. */ instrument_exit_post_sideline(); /* i#1617: We need to call client library fini routines for global * destructors, etc. */ if (!INTERNAL_OPTION(nullcalls) && !DYNAMO_OPTION(skip_thread_exit_at_exit)) loader_thread_exit(get_thread_private_dcontext()); loader_exit(); /* for -private_loader we do this here to catch more exit-time crashes */ # ifdef WINDOWS if (!INTERNAL_OPTION(noasynch) IF_CLIENT_INTERFACE(&&INTERNAL_OPTION(private_loader))) callback_interception_unintercept(); # endif } # endif /* CLIENT_INTERFACE */ fragment_exit_post_sideline(); # ifdef CALL_PROFILE profile_callers_exit(); # endif # ifdef KSTATS if (DYNAMO_OPTION(kstats)) kstat_exit(); # endif /* so make sure eventlog connection is terminated (if present) */ os_fast_exit(); if (INTERNAL_OPTION(rstats_to_stderr)) dump_global_rstats_to_stderr(); return SUCCESS; #endif /* !DEBUG */ } void dynamo_exit_post_detach(void) { /* i#2157: best-effort re-init in case of re-attach */ do_once_generation++; /* Increment the generation in case we re-attach */ dynamo_initialized = false; dynamo_heap_initialized = false; automatic_startup = false; control_all_threads = false; dr_api_entry = false; dr_api_exit = false; #ifdef UNIX dynamo_exiting = false; #endif dynamo_exited = false; dynamo_exited_all_other_threads = false; dynamo_exited_and_cleaned = false; #ifdef DEBUG dynamo_exited_log_and_stats = false; #endif dynamo_resetting = false; #ifdef UNIX post_execve = false; #endif vm_areas_post_exit(); heap_post_exit(); } dcontext_t * create_new_dynamo_context(bool initial, byte *dstack_in, priv_mcontext_t *mc) { dcontext_t *dcontext; size_t alloc = sizeof(dcontext_t) + proc_get_cache_line_size(); void *alloc_start = (void *)((TEST(SELFPROT_GLOBAL, dynamo_options.protect_mask) && !TEST(SELFPROT_DCONTEXT, dynamo_options.protect_mask)) ? /* if protecting global but not dcontext, put whole thing in unprot mem */ global_unprotected_heap_alloc(alloc HEAPACCT(ACCT_OTHER)) : global_heap_alloc(alloc HEAPACCT(ACCT_OTHER))); dcontext = (dcontext_t *)proc_bump_to_end_of_cache_line((ptr_uint_t)alloc_start); ASSERT(proc_is_cache_aligned(dcontext)); #ifdef X86 /* 264138: ensure xmm/ymm slots are aligned so we can use vmovdqa */ ASSERT(ALIGNED(get_mcontext(dcontext)->simd, ZMM_REG_SIZE)); /* also ensure we don't have extra padding beyond x86.asm defines */ ASSERT(sizeof(priv_mcontext_t) == IF_X64_ELSE(18, 10) * sizeof(reg_t) + PRE_XMM_PADDING + MCXT_TOTAL_SIMD_SLOTS_SIZE); #elif defined(ARM) /* FIXME i#1551: add arm alignment check if any */ #endif /* X86/ARM */ /* Put here all one-time dcontext field initialization * Make sure to update create_callback_dcontext to shared * fields across callback dcontexts for the same thread. */ /* must set to 0 so can tell if initialized for callbacks! */ memset(dcontext, 0x0, sizeof(dcontext_t)); dcontext->allocated_start = alloc_start; /* we share a single dstack across all callbacks */ if (initial) { /* DrMi#1723: our dstack needs to be at a higher address than the app * stack. If mc passed, use its xsp; else use cur xsp (initial thread * is on the app stack here: xref i#1105), for lower bound for dstack. */ byte *app_xsp; if (mc == NULL) GET_STACK_PTR(app_xsp); else app_xsp = (byte *)mc->xsp; if (dstack_in == NULL) { dcontext->dstack = (byte *)stack_alloc(DYNAMORIO_STACK_SIZE, app_xsp); } else dcontext->dstack = dstack_in; /* xref i#149/PR 403015 */ #ifdef WINDOWS DOCHECK(1, { if (dcontext->dstack < app_xsp) SYSLOG_INTERNAL_WARNING_ONCE("dstack is below app xsp"); }); #endif } else { /* dstack may be pre-allocated only at thread init, not at callback */ ASSERT(dstack_in == NULL); } if (TEST(SELFPROT_DCONTEXT, dynamo_options.protect_mask)) { dcontext->upcontext.separate_upcontext = global_unprotected_heap_alloc( sizeof(unprotected_context_t) HEAPACCT(ACCT_OTHER)); /* don't need to initialize upcontext */ LOG(GLOBAL, LOG_TOP, 2, "new dcontext=" PFX ", dcontext->upcontext=" PFX "\n", dcontext, dcontext->upcontext.separate_upcontext); dcontext->upcontext_ptr = dcontext->upcontext.separate_upcontext; } else dcontext->upcontext_ptr = &(dcontext->upcontext.upcontext); #ifdef HOT_PATCHING_INTERFACE /* Set the hot patch exception state to be empty/unused. */ DODEBUG(memset(&dcontext->hotp_excpt_state, -1, sizeof(dr_jmp_buf_t));); #endif ASSERT(dcontext->try_except.try_except_state == NULL); DODEBUG({ dcontext->logfile = INVALID_FILE; }); dcontext->owning_thread = d_r_get_thread_id(); #ifdef UNIX dcontext->owning_process = get_process_id(); #endif /* thread_record is set in add_thread */ /* all of the thread-private fcache and hashtable fields are shared * among all dcontext instances of a thread, so the caller must * set those fields */ /* rest of dcontext initialization happens in initialize_dynamo_context(), * which is executed for each dr_app_start() and each * callback start */ return dcontext; } static void delete_dynamo_context(dcontext_t *dcontext, bool free_stack) { if (free_stack) { ASSERT(dcontext->dstack != NULL); ASSERT(!is_currently_on_dstack(dcontext)); LOG(GLOBAL, LOG_THREADS, 1, "Freeing DR stack " PFX "\n", dcontext->dstack); stack_free(dcontext->dstack, DYNAMORIO_STACK_SIZE); } /* else will be cleaned up by caller */ ASSERT(dcontext->try_except.try_except_state == NULL); if (TEST(SELFPROT_DCONTEXT, dynamo_options.protect_mask)) { global_unprotected_heap_free(dcontext->upcontext.separate_upcontext, sizeof(unprotected_context_t) HEAPACCT(ACCT_OTHER)); } if (TEST(SELFPROT_GLOBAL, dynamo_options.protect_mask) && !TEST(SELFPROT_DCONTEXT, dynamo_options.protect_mask)) { /* if protecting global but not dcontext, we put whole thing in unprot mem */ global_unprotected_heap_free(dcontext->allocated_start, sizeof(dcontext_t) + proc_get_cache_line_size() HEAPACCT(ACCT_OTHER)); } else { global_heap_free(dcontext->allocated_start, sizeof(dcontext_t) + proc_get_cache_line_size() HEAPACCT(ACCT_OTHER)); } } /* This routine is called not only at thread initialization, * but for every callback, etc. that gets a fresh execution * environment! */ void initialize_dynamo_context(dcontext_t *dcontext) { /* we can't just zero out the whole thing b/c we have persistent state * (fields kept across callbacks, like dstack, module-private fields, next & * prev, etc.) */ memset(dcontext->upcontext_ptr, 0, sizeof(unprotected_context_t)); dcontext->initialized = true; dcontext->whereami = DR_WHERE_APP; dcontext->next_tag = NULL; dcontext->native_exec_postsyscall = NULL; memset(dcontext->native_retstack, 0, sizeof(dcontext->native_retstack)); dcontext->native_retstack_cur = 0; dcontext->isa_mode = DEFAULT_ISA_MODE; #ifdef ARM dcontext->encode_state[0] = 0; dcontext->encode_state[1] = 0; dcontext->decode_state[0] = 0; dcontext->decode_state[1] = 0; #endif dcontext->sys_num = 0; #ifdef WINDOWS # ifdef CLIENT_INTERFACE dcontext->app_errno = 0; # ifdef DEBUG dcontext->is_client_thread_exiting = false; # endif # endif dcontext->sys_param_base = NULL; /* always initialize aslr_context */ dcontext->aslr_context.sys_aslr_clobbered = 0; dcontext->aslr_context.randomized_section_handle = INVALID_HANDLE_VALUE; dcontext->aslr_context.original_image_section_handle = INVALID_HANDLE_VALUE; dcontext->aslr_context.original_section_base = ASLR_INVALID_SECTION_BASE; # ifdef DEBUG dcontext->aslr_context.last_app_section_handle = INVALID_HANDLE_VALUE; # endif /* note that aslr_context.last_child_padded is preserved across callbacks */ dcontext->ignore_enterexit = false; #else dcontext->sys_param0 = 0; dcontext->sys_param1 = 0; dcontext->sys_param2 = 0; #endif #ifdef UNIX dcontext->signals_pending = false; #endif /* all thread-private fields are initialized in dynamo_thread_init * or in create_callback_dcontext because they must be initialized differently * in those two cases */ set_last_exit(dcontext, (linkstub_t *)get_starting_linkstub()); #ifdef PROFILE_RDTSC dcontext->start_time = (uint64)0; dcontext->prev_fragment = NULL; dcontext->cache_frag_count = (uint64)0; { int i; for (i = 0; i < 10; i++) { dcontext->cache_time[i] = (uint64)0; dcontext->cache_count[i] = (uint64)0; } } #endif #ifdef DEBUG dcontext->in_opnd_disassemble = false; #endif #ifdef WINDOWS /* Other pieces of DR -- callback & APC handling, detach -- test * asynch_target to determine where the next app pc to execute is * stored. Init it to 0 to indicate that this context's most recent * syscall was not executed from handle_system_call(). */ dcontext->asynch_target = NULL; /* next_saved and prev_unused are zeroed out when dcontext is * created; we shouldn't zero them here, they may have valid data */ dcontext->valid = true; #endif #ifdef HOT_PATCHING_INTERFACE dcontext->nudge_thread = false; /* Fix for case 5367. */ #endif #ifdef CHECK_RETURNS_SSE2 /* initialize sse2 index with 0 * go ahead and use eax, it's dead (about to return) */ # ifdef UNIX asm("movl $0, %eax"); asm("pinsrw $7,%eax,%xmm7"); # else # error NYI # endif #endif /* We don't need to initialize dcontext->coarse_exit as it is only * read when last_exit indicates a coarse exit, which sets the fields. */ dcontext->go_native = false; } #ifdef WINDOWS /* on windows we use a new dcontext for each callback context */ dcontext_t * create_callback_dcontext(dcontext_t *old_dcontext) { dcontext_t *new_dcontext = create_new_dynamo_context(false, NULL, NULL); new_dcontext->valid = false; /* all of these fields are shared among all dcontexts of a thread: */ new_dcontext->owning_thread = old_dcontext->owning_thread; # ifdef UNIX new_dcontext->owning_process = old_dcontext->owning_process; # endif new_dcontext->thread_record = old_dcontext->thread_record; /* now that we have clean stack usage we can share a single stack */ ASSERT(old_dcontext->dstack != NULL); new_dcontext->dstack = old_dcontext->dstack; new_dcontext->isa_mode = old_dcontext->isa_mode; new_dcontext->link_field = old_dcontext->link_field; new_dcontext->monitor_field = old_dcontext->monitor_field; new_dcontext->fcache_field = old_dcontext->fcache_field; new_dcontext->fragment_field = old_dcontext->fragment_field; new_dcontext->heap_field = old_dcontext->heap_field; new_dcontext->vm_areas_field = old_dcontext->vm_areas_field; new_dcontext->os_field = old_dcontext->os_field; new_dcontext->synch_field = old_dcontext->synch_field; /* case 8958: copy win32_start_addr in case we produce a forensics file * from within a callback. */ new_dcontext->win32_start_addr = old_dcontext->win32_start_addr; # ifdef CLIENT_INTERFACE /* FlsData is persistent across callbacks */ new_dcontext->app_fls_data = old_dcontext->app_fls_data; new_dcontext->priv_fls_data = old_dcontext->priv_fls_data; new_dcontext->app_nt_rpc = old_dcontext->app_nt_rpc; new_dcontext->priv_nt_rpc = old_dcontext->priv_nt_rpc; new_dcontext->app_nls_cache = old_dcontext->app_nls_cache; new_dcontext->priv_nls_cache = old_dcontext->priv_nls_cache; # endif new_dcontext->app_stack_limit = old_dcontext->app_stack_limit; new_dcontext->app_stack_base = old_dcontext->app_stack_base; new_dcontext->teb_base = old_dcontext->teb_base; # ifdef UNIX new_dcontext->signal_field = old_dcontext->signal_field; new_dcontext->pcprofile_field = old_dcontext->pcprofile_field; # endif new_dcontext->private_code = old_dcontext->private_code; # ifdef CLIENT_INTERFACE new_dcontext->client_data = old_dcontext->client_data; # endif # ifdef DEBUG new_dcontext->logfile = old_dcontext->logfile; new_dcontext->thread_stats = old_dcontext->thread_stats; # endif # ifdef DEADLOCK_AVOIDANCE new_dcontext->thread_owned_locks = old_dcontext->thread_owned_locks; # endif # ifdef KSTATS new_dcontext->thread_kstats = old_dcontext->thread_kstats; # endif /* at_syscall is real time based, not app context based, so shared * * FIXME: Yes need to share when swapping at NtCallbackReturn, but * want to keep old so when return from cb will do post-syscall for * syscall that triggered cb in the first place! * Plus, new cb calls initialize_dynamo_context(), which clears this field * anyway! This all works now b/c we don't have alertable syscalls * that we do post-syscall processing on. */ new_dcontext->upcontext_ptr->at_syscall = old_dcontext->upcontext_ptr->at_syscall; # ifdef HOT_PATCHING_INTERFACE /* Fix for case 5367. */ /* hotp_excpt_state should be unused at this point. If it is used, it can * be only because a hot patch made a system call with a callback. This is * a bug because hot patches can't do system calls, let alone one with * callbacks. */ DOCHECK(1, { dr_jmp_buf_t empty; memset(&empty, -1, sizeof(dr_jmp_buf_t)); ASSERT(memcmp(&old_dcontext->hotp_excpt_state, &empty, sizeof(dr_jmp_buf_t)) == 0); }); new_dcontext->nudge_thread = old_dcontext->nudge_thread; # endif /* our exceptions should be handled within one DR context switch */ ASSERT(old_dcontext->try_except.try_except_state == NULL); new_dcontext->local_state = old_dcontext->local_state; # ifdef WINDOWS new_dcontext->aslr_context.last_child_padded = old_dcontext->aslr_context.last_child_padded; # endif LOG(new_dcontext->logfile, LOG_TOP, 2, "made new dcontext " PFX " (old=" PFX ")\n", new_dcontext, old_dcontext); return new_dcontext; } #endif bool is_thread_initialized(void) { #if defined(UNIX) && defined(HAVE_TLS) /* We don't want to pay the d_r_get_thread_id() cost on every * get_thread_private_dcontext() when we only really need the * check for this call here, so we explicitly check. */ if (get_tls_thread_id() != get_sys_thread_id()) return false; #endif return (get_thread_private_dcontext() != NULL); } bool is_thread_known(thread_id_t tid) { return (thread_lookup(tid) != NULL); } #ifdef UNIX /* i#237/PR 498284: a thread about to execute SYS_execve should be considered * exited, but we can't easily clean up it for real immediately */ void mark_thread_execve(thread_record_t *tr, bool execve) { ASSERT((execve && !tr->execve) || (!execve && tr->execve)); tr->execve = execve; d_r_mutex_lock(&all_threads_lock); if (execve) { /* since we free on a second vfork we should never accumulate * more than one */ ASSERT(num_execve_threads == 0); num_execve_threads++; } else { ASSERT(num_execve_threads > 0); num_execve_threads--; } d_r_mutex_unlock(&all_threads_lock); } #endif /* UNIX */ int d_r_get_num_threads(void) { return num_known_threads IF_UNIX(-num_execve_threads); } bool is_last_app_thread(void) { return (d_r_get_num_threads() == IF_CLIENT_INTERFACE(get_num_client_threads() +) 1); } /* This routine takes a snapshot of all the threads known to DR, * NOT LIMITED to those currently under DR control! * It returns an array of thread_record_t* and the length of the array * The caller must free the array using global_heap_free * The caller must hold the thread_initexit_lock to ensure that threads * are not created or destroyed before the caller is done with the list * The caller CANNOT be could_be_linking, else a deadlock with flushing * can occur (unless the caller is the one flushing) */ static void get_list_of_threads_common(thread_record_t ***list, int *num _IF_UNIX(bool include_execve)) { int i, cur = 0, max_num; thread_record_t *tr; thread_record_t **mylist; /* Only a flushing thread can get the thread snapshot while being * couldbelinking -- else a deadlock w/ flush! * FIXME: this assert should be on any acquisition of thread_initexit_lock! */ ASSERT(is_self_flushing() || !is_self_couldbelinking()); ASSERT(all_threads != NULL); ASSERT_OWN_MUTEX(true, &thread_initexit_lock); d_r_mutex_lock(&all_threads_lock); /* Do not include vfork threads that exited via execve, unless we're exiting */ max_num = IF_UNIX_ELSE((include_execve || dynamo_exiting) ? num_known_threads : d_r_get_num_threads(), d_r_get_num_threads()); mylist = (thread_record_t **)global_heap_alloc( max_num * sizeof(thread_record_t *) HEAPACCT(ACCT_THREAD_MGT)); for (i = 0; i < HASHTABLE_SIZE(ALL_THREADS_HASH_BITS); i++) { for (tr = all_threads[i]; tr != NULL; tr = tr->next) { /* include those for which !tr->under_dynamo_control */ /* don't include those that exited for execve. there should be * no race b/c vfork suspends the parent. xref i#237/PR 498284. */ if (IF_UNIX_ELSE(!tr->execve || include_execve || dynamo_exiting, true)) { mylist[cur] = tr; cur++; } } } ASSERT(cur > 0); IF_WINDOWS(ASSERT(cur == max_num)); if (cur < max_num) { mylist = (thread_record_t **)global_heap_realloc( mylist, max_num, cur, sizeof(thread_record_t *) HEAPACCT(ACCT_THREAD_MGT)); } *num = cur; *list = mylist; d_r_mutex_unlock(&all_threads_lock); } void get_list_of_threads(thread_record_t ***list, int *num) { get_list_of_threads_common(list, num _IF_UNIX(false)); } #ifdef UNIX void get_list_of_threads_ex(thread_record_t ***list, int *num, bool include_execve) { get_list_of_threads_common(list, num, include_execve); } #endif /* assumes caller can ensure that thread is either suspended or self to * avoid races */ thread_record_t * thread_lookup(thread_id_t tid) { thread_record_t *tr; uint hindex; /* check that caller is self or has initexit_lock * FIXME: no way to tell who has initexit_lock */ ASSERT(mutex_testlock(&thread_initexit_lock) || tid == d_r_get_thread_id()); hindex = HASH_FUNC_BITS(tid, ALL_THREADS_HASH_BITS); d_r_mutex_lock(&all_threads_lock); if (all_threads == NULL) { tr = NULL; } else { tr = all_threads[hindex]; } while (tr != NULL) { if (tr->id == tid) { d_r_mutex_unlock(&all_threads_lock); return tr; } tr = tr->next; } d_r_mutex_unlock(&all_threads_lock); return NULL; } /* assumes caller can ensure that thread is either suspended or self to * avoid races */ uint get_thread_num(thread_id_t tid) { thread_record_t *tr = thread_lookup(tid); if (tr != NULL) return tr->num; else return 0; /* yes can't distinguish from 1st thread, who cares */ } void add_thread(IF_WINDOWS_ELSE_NP(HANDLE hthread, process_id_t pid), thread_id_t tid, bool under_dynamo_control, dcontext_t *dcontext) { thread_record_t *tr; uint hindex; ASSERT(all_threads != NULL); /* add entry to thread hashtable */ tr = (thread_record_t *)global_heap_alloc(sizeof(thread_record_t) HEAPACCT(ACCT_THREAD_MGT)); #ifdef WINDOWS /* we duplicate the thread pseudo-handle, this should give us full rights * Note that instead asking explicitly for THREAD_ALL_ACCESS or just for * THREAD_TERMINATE|THREAD_SUSPEND_RESUME|THREAD_GET_CONTEXT|THREAD_SET_CONTEXT * does not seem able to acquire more rights than simply duplicating the * app handle gives. */ LOG(GLOBAL, LOG_THREADS, 1, "Thread %d app handle rights: " PFX "\n", tid, nt_get_handle_access_rights(hthread)); duplicate_handle(NT_CURRENT_PROCESS, hthread, NT_CURRENT_PROCESS, &tr->handle, 0, 0, DUPLICATE_SAME_ACCESS | DUPLICATE_SAME_ATTRIBUTES); /* We prob. only need TERMINATE (for kill thread), SUSPEND/RESUME/GET_CONTEXT * (for synchronizing), and SET_CONTEXT (+ synchronizing requirements, for * detach). All access includes this and quite a bit more. */ # if 0 /* eventually should be a real assert, but until we have a story for the * injected detach threads, have to ifdef out even the ASSERT_CURIOSITY * (even a syslog internal warning is prob. to noisy for QA) */ ASSERT_CURIOSITY(TESTALL(THREAD_ALL_ACCESS, nt_get_handle_access_rights(tr->handle))); # endif LOG(GLOBAL, LOG_THREADS, 1, "Thread %d our handle rights: " PFX "\n", tid, nt_get_handle_access_rights(tr->handle)); tr->retakeover = false; #else tr->pid = pid; tr->execve = false; #endif tr->id = tid; ASSERT(tid != INVALID_THREAD_ID); /* ensure os never assigns invalid id to a thread */ tr->under_dynamo_control = under_dynamo_control; tr->dcontext = dcontext; if (dcontext != NULL) /* we allow NULL for dr_create_client_thread() */ dcontext->thread_record = tr; d_r_mutex_lock(&all_threads_lock); tr->num = threads_ever_count++; hindex = HASH_FUNC_BITS(tr->id, ALL_THREADS_HASH_BITS); tr->next = all_threads[hindex]; all_threads[hindex] = tr; /* must be inside all_threads_lock to avoid race w/ get_list_of_threads */ RSTATS_ADD_PEAK(num_threads, 1); RSTATS_INC(num_threads_created); num_known_threads++; d_r_mutex_unlock(&all_threads_lock); } /* return false if couldn't find the thread */ bool remove_thread(IF_WINDOWS_(HANDLE hthread) thread_id_t tid) { thread_record_t *tr = NULL, *prevtr; uint hindex = HASH_FUNC_BITS(tid, ALL_THREADS_HASH_BITS); ASSERT(all_threads != NULL); d_r_mutex_lock(&all_threads_lock); for (tr = all_threads[hindex], prevtr = NULL; tr; prevtr = tr, tr = tr->next) { if (tr->id == tid) { if (prevtr) prevtr->next = tr->next; else all_threads[hindex] = tr->next; /* must be inside all_threads_lock to avoid race w/ get_list_of_threads */ RSTATS_DEC(num_threads); #ifdef UNIX if (tr->execve) { ASSERT(num_execve_threads > 0); num_execve_threads--; } #endif num_known_threads--; #ifdef WINDOWS close_handle(tr->handle); #endif global_heap_free(tr, sizeof(thread_record_t) HEAPACCT(ACCT_THREAD_MGT)); break; } } d_r_mutex_unlock(&all_threads_lock); return (tr != NULL); } /* this bool is protected by reset_pending_lock */ DECLARE_FREQPROT_VAR(static bool reset_at_nth_thread_triggered, false); /* thread-specific initialization * if dstack_in is NULL, then a dstack is allocated; else dstack_in is used * as the thread's dstack * mc can be NULL for the initial thread * returns -1 if current thread has already been initialized */ /* On UNIX, if dstack_in != NULL, the parent of this new thread must have * increased uninit_thread_count. */ int dynamo_thread_init(byte *dstack_in, priv_mcontext_t *mc, void *os_data _IF_CLIENT_INTERFACE(bool client_thread)) { dcontext_t *dcontext; /* due to lock issues (see below) we need another var */ bool reset_at_nth_thread_pending = false; bool under_dynamo_control = true; APP_EXPORT_ASSERT(dynamo_initialized || dynamo_exited || d_r_get_num_threads() == 0 IF_CLIENT_INTERFACE(|| client_thread), PRODUCT_NAME " not initialized"); if (INTERNAL_OPTION(nullcalls)) { ASSERT(uninit_thread_count == 0); return SUCCESS; } /* note that ENTERING_DR is assumed to have already happened: in apc handler * for win32, in new_thread_setup for linux, in main init for 1st thread */ #if defined(WINDOWS) && defined(DR_APP_EXPORTS) /* We need to identify a thread we intercepted in its APC when we * take over all threads on dr_app_start(). Stack and pc checks aren't * simple b/c it can be in ntdll waiting on a lock. */ if (dr_api_entry) os_take_over_mark_thread(d_r_get_thread_id()); #endif /* Try to handle externally injected threads */ if (dynamo_initialized && !bb_lock_start) pre_second_thread(); /* synch point so thread creation can be prevented for critical periods */ d_r_mutex_lock(&thread_initexit_lock); /* XXX i#2611: during detach, there is a race where a thread can * reach here on Windows despite init_apc_go_native (i#2600). */ ASSERT_BUG_NUM(2611, !doing_detach); /* The assumption is that if dynamo_exited, then we are about to exit and * clean up, initializing this thread then would be dangerous, better to * wait here for the app to die. */ /* under current implementation of process exit, can happen only under * debug build, or app_start app_exit interface */ while (dynamo_exited) { /* logging should be safe, though might not actually result in log * message */ DODEBUG_ONCE(LOG(GLOBAL, LOG_THREADS, 1, "Thread %d reached initialization point while dynamo exiting, " "waiting for app to exit\n", d_r_get_thread_id());); d_r_mutex_unlock(&thread_initexit_lock); os_thread_yield(); /* just in case we want to support exited and then restarted at some * point */ d_r_mutex_lock(&thread_initexit_lock); } if (is_thread_initialized()) { d_r_mutex_unlock(&thread_initexit_lock); #if defined(WINDOWS) && defined(DR_APP_EXPORTS) if (dr_api_entry) os_take_over_unmark_thread(d_r_get_thread_id()); #endif return -1; } os_tls_init(); dcontext = create_new_dynamo_context(true /*initial*/, dstack_in, mc); initialize_dynamo_context(dcontext); set_thread_private_dcontext(dcontext); /* sanity check */ ASSERT(get_thread_private_dcontext() == dcontext); /* set local state pointer for access from other threads */ dcontext->local_state = get_local_state(); /* set initial mcontext, if known */ if (mc != NULL) *get_mcontext(dcontext) = *mc; /* For hotp_only, the thread should run native, not under dr. However, * the core should still get control of the thread at hook points to track * what the application is doing & at patched points to execute hot patches. * It is the same for thin_client except that there are fewer hooks, only to * follow children. */ if (RUNNING_WITHOUT_CODE_CACHE()) under_dynamo_control = false; /* add entry to thread hashtable before creating logdir so have thread num. * otherwise we'd like to do this only after we'd fully initialized the thread, but we * hold the thread_initexit_lock, so nobody should be listing us -- thread_lookup * on other than self, or a thread list, should only be done while the initexit_lock * is held. CHECK: is this always correct? thread_lookup does have an assert * to try and enforce but cannot tell who has the lock. */ add_thread(IF_WINDOWS_ELSE(NT_CURRENT_THREAD, get_process_id()), d_r_get_thread_id(), under_dynamo_control, dcontext); #ifdef UNIX /* i#2600: Not easy on Windows: we rely on init_apc_go_native there. */ if (dstack_in != NULL) { /* Else not a thread creation we observed */ ASSERT(uninit_thread_count > 0); ATOMIC_DEC(int, uninit_thread_count); } #endif #if defined(WINDOWS) && defined(DR_APP_EXPORTS) /* Now that the thread is in the main thread table we don't need to remember it */ if (dr_api_entry) os_take_over_unmark_thread(d_r_get_thread_id()); #endif LOG(GLOBAL, LOG_TOP | LOG_THREADS, 1, "\ndynamo_thread_init: %d thread(s) now, dcontext=" PFX ", #=%d, id=" TIDFMT ", pid=" PIDFMT "\n\n", GLOBAL_STAT(num_threads), dcontext, get_thread_num(d_r_get_thread_id()), d_r_get_thread_id(), get_process_id()); DOLOG(1, LOG_STATS, { dump_global_stats(false); }); #ifdef DEBUG if (d_r_stats->loglevel > 0) { dcontext->logfile = open_log_file(thread_logfile_name(), NULL, 0); print_file(dcontext->logfile, "%s\n", dynamorio_version_string); } else { dcontext->logfile = INVALID_FILE; } DOLOG(1, LOG_TOP | LOG_THREADS, { LOG(THREAD, LOG_TOP | LOG_THREADS, 1, PRODUCT_NAME " built with: %s\n", DYNAMORIO_DEFINES); LOG(THREAD, LOG_TOP | LOG_THREADS, 1, PRODUCT_NAME " built on: %s\n", dynamorio_buildmark); }); LOG(THREAD, LOG_TOP | LOG_THREADS, 1, "%sTHREAD %d (dcontext " PFX ")\n\n", IF_CLIENT_INTERFACE_ELSE(client_thread ? "CLIENT " : "", ""), d_r_get_thread_id(), dcontext); LOG(THREAD, LOG_TOP | LOG_THREADS, 1, "DR stack is " PFX "-" PFX " (passed in " PFX ")\n", dcontext->dstack - DYNAMORIO_STACK_SIZE, dcontext->dstack, dstack_in); #endif #ifdef DEADLOCK_AVOIDANCE locks_thread_init(dcontext); #endif heap_thread_init(dcontext); DOSTATS({ stats_thread_init(dcontext); }); #ifdef KSTATS kstat_thread_init(dcontext); #endif os_thread_init(dcontext, os_data); arch_thread_init(dcontext); synch_thread_init(dcontext); if (!DYNAMO_OPTION(thin_client)) vm_areas_thread_init(dcontext); monitor_thread_init(dcontext); fcache_thread_init(dcontext); link_thread_init(dcontext); fragment_thread_init(dcontext); /* OS thread init after synch_thread_init and other setup can handle signals, etc. */ os_thread_init_finalize(dcontext, os_data); /* This lock has served its purposes: A) a barrier to thread creation for those * iterating over threads, B) mutex for add_thread, and C) mutex for synch_field * to be set up. * So we release it to shrink the time spent w/ this big lock, in particular * to avoid holding it while running private lib thread init code (i#875). */ d_r_mutex_unlock(&thread_initexit_lock); #ifdef CLIENT_INTERFACE /* Set up client data needed in loader_thread_init for IS_CLIENT_THREAD */ instrument_client_thread_init(dcontext, client_thread); #endif loader_thread_init(dcontext); if (!DYNAMO_OPTION(thin_client)) { #ifdef CLIENT_INTERFACE /* put client last, may depend on other thread inits. * Note that we are calling this prior to instrument_init() * now (PR 216936), which is required to initialize * the client dcontext field prior to instrument_init(). */ instrument_thread_init(dcontext, client_thread, mc != NULL); #endif #ifdef SIDELINE if (dynamo_options.sideline) { /* wake up sideline thread -- ok to call if thread already awake */ sideline_start(); } #endif } /* must check # threads while holding thread_initexit_lock, yet cannot * call fcache_reset_all_caches_proactively while holding it due to * rank order of reset_pending_lock which we must also hold -- so we * set a local bool reset_at_nth_thread_pending */ if (DYNAMO_OPTION(reset_at_nth_thread) != 0 && !reset_at_nth_thread_triggered && (uint)d_r_get_num_threads() == DYNAMO_OPTION(reset_at_nth_thread)) { d_r_mutex_lock(&reset_pending_lock); if (!reset_at_nth_thread_triggered) { reset_at_nth_thread_triggered = true; reset_at_nth_thread_pending = true; } d_r_mutex_unlock(&reset_pending_lock); } DOLOG(1, LOG_STATS, { dump_thread_stats(dcontext, false); }); if (reset_at_nth_thread_pending) { d_r_mutex_lock(&reset_pending_lock); /* fcache_reset_all_caches_proactively() will unlock */ fcache_reset_all_caches_proactively(RESET_ALL); } return SUCCESS; } /* We don't free cur thread until after client exit event (PR 536058) except for * fragment_thread_exit(). Since this is called outside of dynamo_thread_exit() * on process exit we assume fine to skip enter_threadexit(). */ void dynamo_thread_exit_pre_client(dcontext_t *dcontext, thread_id_t id) { /* fcache stats needs to examine fragment state, so run it before * fragment exit, but real fcache exit needs to be after fragment exit */ #ifdef DEBUG fcache_thread_exit_stats(dcontext); #endif /* must abort now to avoid deleting possibly un-deletable fragments * monitor_thread_exit remains later b/c of monitor_remove_fragment calls */ trace_abort_and_delete(dcontext); fragment_thread_exit(dcontext); #ifdef CLIENT_INTERFACE IF_WINDOWS(loader_pre_client_thread_exit(dcontext)); instrument_thread_exit_event(dcontext); #endif } /* thread-specific cleanup */ /* Note : if this routine is not called by thread id, then other_thread should * be true and the calling thread should hold the thread_initexit_lock */ static int dynamo_thread_exit_common(dcontext_t *dcontext, thread_id_t id, IF_WINDOWS_(bool detach_stacked_callbacks) bool other_thread) { dcontext_t *dcontext_tmp; #ifdef WINDOWS dcontext_t *dcontext_next; int num_dcontext; #endif bool on_dstack = !other_thread && is_currently_on_dstack(dcontext); /* cache this now for use after freeing dcontext */ local_state_t *local_state = dcontext->local_state; if (INTERNAL_OPTION(nullcalls) || dcontext == NULL) return SUCCESS; /* make sure don't get into deadlock w/ flusher */ enter_threadexit(dcontext); /* synch point so thread exiting can be prevented for critical periods */ /* see comment at start of method for other thread exit */ if (!other_thread) d_r_mutex_lock(&thread_initexit_lock); ASSERT_OWN_MUTEX(true, &thread_initexit_lock); #ifdef WINDOWS /* need to clean up thread stack before clean up other thread data, but * after we're made nolinking */ os_thread_stack_exit(dcontext); /* free the thread's application stack if requested */ if (dcontext->free_app_stack) { byte *base; /* only used for nudge threads currently */ ASSERT(dcontext->nudge_target == generic_nudge_target); if (get_stack_bounds(dcontext, &base, NULL)) { NTSTATUS res; ASSERT(base != NULL); res = nt_free_virtual_memory(base); ASSERT(NT_SUCCESS(res)); } else { /* stack should be available here */ ASSERT_NOT_REACHED(); } } #endif #ifdef SIDELINE /* N.B.: do not clean up any data structures while sideline thread * is still running! put it to sleep for duration of this routine! */ if (!DYNAMO_OPTION(thin_client)) { if (dynamo_options.sideline) { /* put sideline thread to sleep */ sideline_stop(); /* sideline_stop will not return until sideline thread is asleep */ } } #endif LOG(GLOBAL, LOG_TOP | LOG_THREADS, 1, "\ndynamo_thread_exit (thread #%d id=" TIDFMT "): %d thread(s) now\n\n", get_thread_num(id), id, GLOBAL_STAT(num_threads) - 1); DOLOG(1, LOG_STATS, { dump_global_stats(false); }); LOG(THREAD, LOG_STATS | LOG_THREADS, 1, "\n## Statistics for this thread:\n"); #ifdef PROFILE_RDTSC if (dynamo_options.profile_times) { int i; ASSERT(dcontext); LOG(THREAD, LOG_STATS | LOG_THREADS, 1, "\nTop ten cache times:\n"); for (i = 0; i < 10; i++) { if (dcontext->cache_time[i] > (uint64)0) { uint top_part, bottom_part; divide_int64_print(dcontext->cache_time[i], kilo_hertz, false, 3, &top_part, &bottom_part); LOG(THREAD, LOG_STATS | LOG_THREADS, 1, "\t#%2d = %6u.%.3u ms, %9d hits\n", i + 1, top_part, bottom_part, (int)dcontext->cache_count[i]); } } LOG(THREAD, LOG_STATS | LOG_THREADS, 1, "\n"); } #endif /* In order to pass the client a dcontext in the process exit event * we do some thread cleanup early for the final thread so we can delay * the rest (PR 536058) */ if (!dynamo_exited_and_cleaned) dynamo_thread_exit_pre_client(dcontext, id); #ifdef CLIENT_INTERFACE /* PR 243759: don't free client_data until after all fragment deletion events */ if (!DYNAMO_OPTION(thin_client)) instrument_thread_exit(dcontext); #endif /* i#920: we can't take segment/timer/asynch actions for other threads. * This must be called after dynamo_thread_exit_pre_client where * we called event callbacks. */ if (!other_thread) dynamo_thread_not_under_dynamo(dcontext); /* We clean up priv libs prior to setting tls dc to NULL so we can use * TRY_EXCEPT when calling the priv lib entry routine */ if (!dynamo_exited || (other_thread && (IF_WINDOWS_ELSE(!doing_detach, true) || dcontext->owning_thread != d_r_get_thread_id()))) /* else already did this */ loader_thread_exit(dcontext); /* set tls dc to NULL prior to cleanup, to avoid problems handling * alarm signals received during cleanup (we'll suppress if tls * dc==NULL which seems the right thing to do: not worth our * effort to pass to another thread if thread-group-shared alarm, * and if thread-private then thread would have exited soon * anyway). see PR 596127. */ /* make sure we invalidate the dcontext before releasing the memory */ /* when cleaning up other threads, we cannot set their dcs to null, * but we only do this at dynamorio_app_exit so who cares */ /* This must be called after instrument_thread_exit, which uses * get_thread_private_dcontext for app/dr state checks. */ if (id == d_r_get_thread_id()) set_thread_private_dcontext(NULL); fcache_thread_exit(dcontext); link_thread_exit(dcontext); monitor_thread_exit(dcontext); if (!DYNAMO_OPTION(thin_client)) vm_areas_thread_exit(dcontext); synch_thread_exit(dcontext); arch_thread_exit(dcontext _IF_WINDOWS(detach_stacked_callbacks)); os_thread_exit(dcontext, other_thread); DOLOG(1, LOG_STATS, { dump_thread_stats(dcontext, false); }); #ifdef KSTATS kstat_thread_exit(dcontext); #endif DOSTATS({ stats_thread_exit(dcontext); }); heap_thread_exit(dcontext); #ifdef DEADLOCK_AVOIDANCE locks_thread_exit(dcontext); #endif #ifdef DEBUG if (dcontext->logfile != INVALID_FILE) { os_flush(dcontext->logfile); close_log_file(dcontext->logfile); } #endif /* remove thread from threads hashtable */ remove_thread(IF_WINDOWS_(NT_CURRENT_THREAD) id); dcontext_tmp = dcontext; #ifdef WINDOWS /* clean up all the dcs */ num_dcontext = 0; # ifdef DCONTEXT_IN_EDI /* go to one end of list */ while (dcontext_tmp->next_saved) dcontext_tmp = dcontext_tmp->next_saved; # else /* already at one end of list */ # endif /* delete through to other end */ while (dcontext_tmp) { num_dcontext++; dcontext_next = dcontext_tmp->prev_unused; delete_dynamo_context(dcontext_tmp, dcontext_tmp == dcontext /*do not free dup cb stacks*/ && !on_dstack /*do not free own stack*/); dcontext_tmp = dcontext_next; } LOG(GLOBAL, LOG_STATS | LOG_THREADS, 1, "\tdynamo contexts used: %d\n", num_dcontext); #else /* UNIX */ delete_dynamo_context(dcontext_tmp, !on_dstack /*do not free own stack*/); #endif /* UNIX */ os_tls_exit(local_state, other_thread); #ifdef SIDELINE /* see notes above -- we can now wake up sideline thread */ if (dynamo_options.sideline && d_r_get_num_threads() > 0) { sideline_start(); } #endif if (!other_thread) { d_r_mutex_unlock(&thread_initexit_lock); /* FIXME: once thread_initexit_lock is released, we're not on * thread list, and a terminate targeting us could kill us in the middle * of this call -- but this can't come before the unlock b/c the lock's * in the data segment! (see case 3121) * (note we do not re-protect for process exit, see !dynamo_exited check * in exiting_dynamorio) */ if (!on_dstack) { EXITING_DR(); /* else, caller will clean up stack and then call EXITING_DR(), * probably via dynamo_thread_stack_free_and_exit(), as the stack free * must be done before the exit */ } } return SUCCESS; } /* NOINLINE because dynamo_thread_exit is a stopping point. */ NOINLINE int dynamo_thread_exit(void) { dcontext_t *dcontext = get_thread_private_dcontext(); return dynamo_thread_exit_common(dcontext, d_r_get_thread_id(), IF_WINDOWS_(false) false); } /* NOTE : you must hold thread_initexit_lock to call this function! */ int dynamo_other_thread_exit(thread_record_t *tr _IF_WINDOWS(bool detach_stacked_callbacks)) { /* FIXME: Usually a safe spot for cleaning other threads should be * under num_exits_dir_syscall, but for now rewinding all the way */ KSTOP_REWIND_DC(tr->dcontext, thread_measured); KSTART_DC(tr->dcontext, thread_measured); return dynamo_thread_exit_common(tr->dcontext, tr->id, IF_WINDOWS_(detach_stacked_callbacks) true); } /* Called from another stack to finish cleaning up a thread. * The final steps are to free the stack and perform the exit hook. */ void dynamo_thread_stack_free_and_exit(byte *stack) { if (stack != NULL) { stack_free(stack, DYNAMORIO_STACK_SIZE); /* ASSUMPTION: if stack is NULL here, the exit was done earlier * (fixes case 6967) */ EXITING_DR(); } } #ifdef DR_APP_EXPORTS /* API routine to initialize DR */ DR_APP_API int dr_app_setup(void) { /* FIXME: we either have to disallow the client calling this with * more than one thread running, or we have to suspend all the threads. * We should share the suspend-and-takeover loop (and for dr_app_setup_and_start * share the takeover portion) from dr_app_start(). */ int res; dcontext_t *dcontext; dr_api_entry = true; res = dynamorio_app_init(); /* For dr_api_entry, we do not install all our signal handlers during init (to avoid * races: i#2335): we delay until dr_app_start(). Plus the vsyscall hook is * not set up until we find out the syscall method. Thus we're already * "os_process_not_under_dynamorio". * We can't as easily avoid initializing the thread TLS and then dropping * it, however, as parts of init assume we have TLS. */ dcontext = get_thread_private_dcontext(); dynamo_thread_not_under_dynamo(dcontext); return res; } /* API routine to exit DR */ DR_APP_API int dr_app_cleanup(void) { thread_record_t *tr; SELF_UNPROTECT_DATASEC(DATASEC_RARELY_PROT); dr_api_exit = true; SELF_PROTECT_DATASEC(DATASEC_RARELY_PROT); /* to keep properly nested */ /* XXX: The dynamo_thread_[not_]under_dynamo() routines are not idempotent, * and must be balanced! On Linux, they track the shared itimer refcount, * so a mismatch will lead to a refleak or negative refcount. * dynamorio_app_exit() will call dynamo_thread_not_under_dynamo(), so we * must ensure that we are under DR before calling it. Therefore, we * require that the caller call dr_app_stop() before calling * dr_app_cleanup(). However, we cannot make a usage assertion to that * effect without addressing the FIXME comments in * dynamo_thread_not_under_dynamo() about updating tr->under_dynamo_control. */ tr = thread_lookup(d_r_get_thread_id()); if (tr != NULL && tr->dcontext != NULL) { os_process_under_dynamorio_initiate(tr->dcontext); os_process_under_dynamorio_complete(tr->dcontext); dynamo_thread_under_dynamo(tr->dcontext); } return dynamorio_app_exit(); } /* Called by dr_app_start in arch-specific assembly file */ void dr_app_start_helper(priv_mcontext_t *mc) { apicheck(dynamo_initialized, PRODUCT_NAME " not initialized"); LOG(GLOBAL, LOG_TOP, 1, "dr_app_start in thread " TIDFMT "\n", d_r_get_thread_id()); LOG(THREAD_GET, LOG_TOP, 1, "dr_app_start\n"); if (!INTERNAL_OPTION(nullcalls)) { /* Adjust the app stack to account for the return address + alignment. * See dr_app_start in x86.asm. */ mc->xsp += DYNAMO_START_XSP_ADJUST; dynamo_start(mc); /* the interpreter takes over from here */ } } /* Dummy routine that returns control to the app if it is currently * under dynamo control. * NOINLINE because dr_app_stop is a stopping point. */ DR_APP_API NOINLINE void dr_app_stop(void) { /* the application regains control in here */ } /* NOINLINE because dr_app_stop_and_cleanup is a stopping point. */ DR_APP_API NOINLINE void dr_app_stop_and_cleanup(void) { dr_app_stop_and_cleanup_with_stats(NULL); } /* NOINLINE because dr_app_stop_and_cleanup_with_stats is a stopping point. */ DR_APP_API NOINLINE void dr_app_stop_and_cleanup_with_stats(dr_stats_t *drstats) { /* XXX i#95: today this is a full detach, while a separated dr_app_cleanup() * is not. We should try and have dr_app_cleanup() take this detach path * here (and then we can simplify exit_synch_state()) but it's more complicated * and we need to resolve the unbounded dr_app_stop() time. */ if (dynamo_initialized && !dynamo_exited && !doing_detach) { detach_on_permanent_stack(true /*internal*/, true /*do cleanup*/, drstats); } /* the application regains control in here */ } DR_APP_API int dr_app_setup_and_start(void) { int r = dr_app_setup(); if (r == SUCCESS) dr_app_start(); return r; } #endif /* For use by threads that start and stop whether dynamo controls them. */ void dynamo_thread_under_dynamo(dcontext_t *dcontext) { LOG(THREAD, LOG_ASYNCH, 2, "thread %d under DR control\n", dcontext->owning_thread); ASSERT(dcontext != NULL); /* FIXME: mark under_dynamo_control? * see comments in not routine below */ os_thread_under_dynamo(dcontext); #ifdef SIDELINE if (dynamo_options.sideline) { /* wake up sideline thread -- ok to call if thread already awake */ sideline_start(); } #endif dcontext->currently_stopped = false; dcontext->go_native = false; } /* For use by threads that start and stop whether dynamo controls them. * This must be called by the owner of dcontext and not another * non-executing thread. */ void dynamo_thread_not_under_dynamo(dcontext_t *dcontext) { ASSERT_MESSAGE(CHKLVL_ASSERTS + 1 /*expensive*/, "can only act on executing thread", dcontext == get_thread_private_dcontext()); if (dcontext == NULL) return; LOG(THREAD, LOG_ASYNCH, 2, "thread %d not under DR control\n", dcontext->owning_thread); dcontext->currently_stopped = true; os_thread_not_under_dynamo(dcontext); #ifdef SIDELINE /* FIXME: if # active threads is 0, then put sideline thread to sleep! */ if (dynamo_options.sideline) { /* put sideline thread to sleep */ sideline_stop(); } #endif #ifdef DEBUG os_flush(dcontext->logfile); #endif } #define MAX_TAKE_OVER_ATTEMPTS 8 /* Mark this thread as under DR, and take over other threads in the current process. */ void dynamorio_take_over_threads(dcontext_t *dcontext) { /* We repeatedly check if there are other threads in the process, since * while we're checking one may be spawning additional threads. */ bool found_threads; uint attempts = 0; os_process_under_dynamorio_initiate(dcontext); /* We can start this thread now that we've set up process-wide actions such * as handling signals. */ dynamo_thread_under_dynamo(dcontext); signal_event(dr_app_started); SELF_UNPROTECT_DATASEC(DATASEC_RARELY_PROT); dynamo_started = true; SELF_PROTECT_DATASEC(DATASEC_RARELY_PROT); /* XXX i#1305: we should suspend all the other threads for DR init to * satisfy the parts of the init process that assume there are no races. */ do { found_threads = os_take_over_all_unknown_threads(dcontext); attempts++; if (found_threads && !bb_lock_start) bb_lock_start = true; } while (found_threads && attempts < MAX_TAKE_OVER_ATTEMPTS); os_process_under_dynamorio_complete(dcontext); /* End the barrier to new threads. */ signal_event(dr_attach_finished); if (found_threads) { REPORT_FATAL_ERROR_AND_EXIT(FAILED_TO_TAKE_OVER_THREADS, 2, get_application_name(), get_application_pid()); } char buf[16]; int num_threads = d_r_get_num_threads(); if (num_threads > 1) { /* avoid for early injection */ snprintf(buf, BUFFER_SIZE_ELEMENTS(buf), "%d", num_threads); NULL_TERMINATE_BUFFER(buf); SYSLOG(SYSLOG_INFORMATION, INFO_ATTACHED, 3, buf, get_application_name(), get_application_pid()); } } /* Called by dynamorio_app_take_over in arch-specific assembly file */ void dynamorio_app_take_over_helper(priv_mcontext_t *mc) { static bool have_taken_over = false; /* ASSUMPTION: not an actual write */ SELF_UNPROTECT_DATASEC(DATASEC_RARELY_PROT); APP_EXPORT_ASSERT(dynamo_initialized, PRODUCT_NAME " not initialized"); #ifdef RETURN_AFTER_CALL /* FIXME : this is set after dynamo_initialized, so a slight race with * an injected thread turning on .C protection before the main thread * sets this. */ dr_preinjected = true; /* currently only relevant on Win32 */ #endif LOG(GLOBAL, LOG_TOP, 1, "taking over via preinject in %s\n", __FUNCTION__); if (!INTERNAL_OPTION(nullcalls) && !have_taken_over) { have_taken_over = true; LOG(GLOBAL, LOG_TOP, 1, "dynamorio_app_take_over\n"); /* set this flag to indicate that we should run until the program dies: */ automatic_startup = true; if (DYNAMO_OPTION(inject_primary)) take_over_primary_thread(); /* who knows when this was called -- no guarantee we control all threads -- * unless we were auto-injected (preinject library calls this routine) */ control_all_threads = automatic_startup; SELF_PROTECT_DATASEC(DATASEC_RARELY_PROT); /* Adjust the app stack to account for the return address + alignment. * See dynamorio_app_take_over in x86.asm. */ mc->xsp += DYNAMO_START_XSP_ADJUST; /* For hotp_only and thin_client, the app should run native, except * for our hooks. * This is where apps hooked using appinit key are let go native. * Even though control is going to native app code, we want * automatic_startup and control_all_threads set. */ if (!RUNNING_WITHOUT_CODE_CACHE()) dynamo_start(mc); /* the interpreter takes over from here */ } else SELF_PROTECT_DATASEC(DATASEC_RARELY_PROT); } #ifdef WINDOWS extern app_pc parent_early_inject_address; /* from os.c */ /* in arch-specific assembly file */ void dynamorio_app_take_over(void); DYNAMORIO_EXPORT void dynamorio_app_init_and_early_takeover(uint inject_location, void *restore_code) { int res; ASSERT(!dynamo_initialized && !dynamo_exited); /* This routine combines dynamorio_app_init() and dynamrio_app_takeover into * a single routine that also handles any early injection cleanup needed. */ ASSERT_NOT_IMPLEMENTED(inject_location != INJECT_LOCATION_KiUserApc); /* currently only Ldr* hook points are known to work */ ASSERT_CURIOSITY(INJECT_LOCATION_IS_LDR(inject_location)); /* See notes in os.c DLLMain. When early injected we are unable to find * the address of LdrpLoadDll so we use the parent's value which is passed * to us at the start of restore_code. FIXME - if we start using multiple * inject locations we'll probably have to ensure we always pass this. */ if (INJECT_LOCATION_IS_LDR(inject_location)) { parent_early_inject_address = *(app_pc *)restore_code; } dr_early_injected = true; dr_early_injected_location = inject_location; res = dynamorio_app_init(); ASSERT(res == SUCCESS); ASSERT(dynamo_initialized && !dynamo_exited); LOG(GLOBAL, LOG_TOP, 1, "taking over via early injection in %s\n", __FUNCTION__); /* FIXME - restore code needs to be freed, but we have to return through it * first... could instead duplicate its tail here if we wrap this * routine in asm or eqv. pass the continuation state in as args. */ ASSERT(inject_location != INJECT_LOCATION_KiUserApc); dynamorio_app_take_over(); } /* Called with DR library mapped in but without its imports processed. */ void dynamorio_earliest_init_takeover_C(byte *arg_ptr) { int res; bool earliest_inject; /* Windows-specific code for the most part */ earliest_inject = earliest_inject_init(arg_ptr); /* Initialize now that DR dll imports are hooked up */ if (earliest_inject) { dr_earliest_injected = true; dr_earliest_inject_args = arg_ptr; } else dr_early_injected = true; res = dynamorio_app_init(); ASSERT(res == SUCCESS); ASSERT(dynamo_initialized && !dynamo_exited); LOG(GLOBAL, LOG_TOP, 1, "taking over via earliest injection in %s\n", __FUNCTION__); /* earliest_inject_cleanup() is called within dynamorio_app_init() to avoid * confusing the exec areas scan */ /* Take over at retaddr * * XXX i#626: app_takeover sets preinjected for rct (should prob. rename) * which needs to be done whenever we takeover not at the bottom of the * callstack. For earliest won't need to set this if we takeover * in such a way as to handle the return back to our hook code without a * violation -- though currently we will see 3 rets (return from * dynamorio_app_take_over(), return from here, and return from * dynamorio_earliest_init_takeover() to app hook code). * Should we have dynamorio_earliest_init_takeover() set up an * mcontext that we can go to directly instead of interpreting * the returns in our own code? That would make tools that shadow * callstacks simpler too. */ dynamorio_app_take_over(); } #endif /* WINDOWS */ /*************************************************************************** * SELF-PROTECTION */ /* FIXME: even with -single_privileged_thread, we aren't fully protected, * because there's a window between us resuming the other threads and * returning to our caller where another thread could clobber our return * address or something. */ static void dynamorio_protect(void) { ASSERT(SELF_PROTECT_ON_CXT_SWITCH); LOG(GLOBAL, LOG_DISPATCH, 4, "dynamorio_protect thread=" TIDFMT "\n", d_r_get_thread_id()); /* we don't protect local heap here, that's done lazily */ d_r_mutex_lock(&protect_info->lock); ASSERT(protect_info->num_threads_unprot > 0); /* FIXME: nice to also catch double enters but would need to track more info */ if (protect_info->num_threads_unprot <= 0) { /* Defensive code to prevent crashes from double exits (the theory * for case 7631/8030). However, this precludes an extra exit+enter * pair from working properly (though an extra enter+exit will continue * to work), though such a pair would have crashed if another thread * had entered in the interim anyway. */ protect_info->num_threads_unprot = 0; d_r_mutex_unlock(&protect_info->lock); return; } protect_info->num_threads_unprot--; if (protect_info->num_threads_unprot > 0) { /* other threads still in DR, cannot protect global memory */ LOG(GLOBAL, LOG_DISPATCH, 4, "dynamorio_protect: not last thread => nop\n"); d_r_mutex_unlock(&protect_info->lock); return; } SELF_PROTECT_GLOBAL(READONLY); if (INTERNAL_OPTION(single_privileged_thread)) { /* FIXME: want to resume threads and allow thread creation only * _after_ protect data segment, but lock is in data segment! */ if (protect_info->num_threads_suspended > 0) { thread_record_t *tr; int i, num = 0; /* we do not need to grab the all_threads_lock because * no threads can be added or removed so who cares if we * access the data structure simultaneously with another * reader of it */ for (i = 0; i < HASHTABLE_SIZE(ALL_THREADS_HASH_BITS); i++) { for (tr = all_threads[i]; tr; tr = tr->next) { if (tr->under_dynamo_control) { os_thread_resume(all_threads[i]); num++; } } } ASSERT(num == protect_info->num_threads_suspended); protect_info->num_threads_suspended = 0; } /* thread init/exit can proceed now */ d_r_mutex_unlock(&thread_initexit_lock); } /* FIXME case 8073: temporary until we put in unprots in the * right places. if we were to leave this here we'd want to combine * .fspdata and .cspdata for more efficient prot changes. */ SELF_PROTECT_DATASEC(DATASEC_FREQ_PROT); SELF_PROTECT_DATASEC(DATASEC_CXTSW_PROT); d_r_mutex_unlock(&protect_info->lock); } static void dynamorio_unprotect(void) { ASSERT(SELF_PROTECT_ON_CXT_SWITCH); d_r_mutex_lock( &protect_info->lock); /* lock in unprot heap, not data segment, so safe! */ protect_info->num_threads_unprot++; if (protect_info->num_threads_unprot == 1) { /* was protected, so we need to do the unprotection */ SELF_UNPROTECT_DATASEC(DATASEC_CXTSW_PROT); /* FIXME case 8073: temporary until we put in unprots in the * right places. if we were to leave this here we'd want to combine * .fspdata and .cspdata for more efficient prot changes. */ SELF_UNPROTECT_DATASEC(DATASEC_FREQ_PROT); if (INTERNAL_OPTION(single_privileged_thread)) { /* FIXME: want to suspend all other threads _before_ unprotecting anything, * but need to guarantee no new threads while we're suspending them, * and can't do that without setting a lock => need data segment! */ d_r_mutex_lock(&thread_initexit_lock); if (d_r_get_num_threads() > 1) { thread_record_t *tr; int i; /* current multiple-thread solution: suspend all other threads! */ ASSERT(protect_info->num_threads_suspended == 0); /* we do not need to grab the all_threads_lock because * no threads can be added or removed so who cares if we * access the data structure simultaneously with another * reader of it */ for (i = 0; i < HASHTABLE_SIZE(ALL_THREADS_HASH_BITS); i++) { for (tr = all_threads[i]; tr; tr = tr->next) { if (tr->under_dynamo_control) { DEBUG_DECLARE(bool ok =) os_thread_suspend(all_threads[i]); ASSERT(ok); protect_info->num_threads_suspended++; } } } } /* we don't unlock or resume threads until we re-enter cache */ } SELF_PROTECT_GLOBAL(WRITABLE); } /* we don't re-protect local heap here, that's done at points where * it was protected lazily */ d_r_mutex_unlock(&protect_info->lock); LOG(GLOBAL, LOG_DISPATCH, 4, "dynamorio_unprotect thread=" TIDFMT "\n", d_r_get_thread_id()); } #ifdef DEBUG const char * get_data_section_name(app_pc pc) { uint i; for (i = 0; i < DATASEC_NUM; i++) { if (pc >= datasec_start[i] && pc < datasec_end[i]) return DATASEC_NAMES[i]; } return NULL; } bool check_should_be_protected(uint sec) { /* Blindly asserting that a data section is protected is racy as * another thread could be in an unprot window. We use some * heuristics to try and identify bugs where a section is left * unprot, but it's not easy. */ if (/* case 8107: for INJECT_LOCATION_LdrpLoadImportModule we * load a helper library and end up in d_r_dispatch() for * syscall_while_native before DR is initialized. */ !dynamo_initialized || # ifdef WINDOWS /* case 8113: detach currently unprots .data prior to its * thread synch, so don't count anything after that */ doing_detach || # endif !TEST(DATASEC_SELFPROT[sec], DYNAMO_OPTION(protect_mask)) || DATASEC_PROTECTED(sec)) return true; STATS_INC(datasec_not_prot); /* FIXME: even checking d_r_get_num_threads()==1 is still racy as a thread could * exit, and it's not worth grabbing thread_initexit_lock here.. */ if (threads_ever_count == 1 # ifdef DR_APP_EXPORTS /* For start/stop, can be other threads running around so we bail on * perfect protection */ && !dr_api_entry # endif ) return false; /* FIXME: no count of threads in DR or anything so can't conclude much * Just return true and hope developer looks at datasec_not_prot stats. * We do have an ASSERT_CURIOSITY on the stat in data_section_exit(). */ return true; } # ifdef WINDOWS /* Assumed to only be called about DR dll writable regions */ bool data_sections_enclose_region(app_pc start, app_pc end) { /* Rather than solve the general enclose problem by sorting, * we subtract each piece we find. * It used to be that on 32-bit .data|.fspdata|.cspdata|.nspdata formed * the only writable region, with .pdata between .data and .fspdata on 64. * But building with VS2012, I'm seeing the sections in other orders (i#1075). * And with x64 reachability we moved the interception buffer in .data, * and marking it +rx results in sub-section calls to here. */ int i; bool found_start = false, found_end = false; ssize_t sz = end - start; for (i = 0; i < DATASEC_NUM; i++) { if (datasec_start[i] <= end && datasec_end[i] >= start) { byte *overlap_start = MAX(datasec_start[i], start); byte *overlap_end = MIN(datasec_end[i], end); sz -= overlap_end - overlap_start; } } return sz == 0; } # endif /* WINDOWS */ #endif /* DEBUG */ static void get_data_section_bounds(uint sec) { /* FIXME: on linux we should include .got and .dynamic in one of our * sections, requiring specifying the order of sections (case 3789)! * Should use an ld script to ensure that .nspdata is last, or find a unique * attribute to force separation (perhaps mark as rwx, then * remove the x at init time?) ld 2.15 puts it at the end, but * ld 2.13 puts .got and .dynamic after it! For now we simply * don't protect subsequent guys. * On win32 there are no other rw sections, fortunately. */ ASSERT(sec >= 0 && sec < DATASEC_NUM); /* for DEBUG we use for data_sections_enclose_region() */ ASSERT(IF_WINDOWS(IF_DEBUG(true ||)) TEST(DATASEC_SELFPROT[sec], dynamo_options.protect_mask)); d_r_mutex_lock(&datasec_lock[sec]); ASSERT(datasec_start[sec] == NULL); get_named_section_bounds(get_dynamorio_dll_start(), DATASEC_NAMES[sec], &datasec_start[sec], &datasec_end[sec]); d_r_mutex_unlock(&datasec_lock[sec]); ASSERT(ALIGNED(datasec_start[sec], PAGE_SIZE)); ASSERT(ALIGNED(datasec_end[sec], PAGE_SIZE)); ASSERT(datasec_start[sec] < datasec_end[sec]); #ifdef WINDOWS if (IF_DEBUG(true ||) TEST(DATASEC_SELFPROT[sec], dynamo_options.protect_mask)) merge_writecopy_pages(datasec_start[sec], datasec_end[sec]); #endif } #ifdef UNIX /* We get into problems if we keep a .section open across string literals, etc. * (such as when wrapping a function to get its local-scope statics in that section), * but the VAR_IN_SECTION does the real work for us, just so long as we have one * .section decl somewhere. */ DECLARE_DATA_SECTION(RARELY_PROTECTED_SECTION, "w") DECLARE_DATA_SECTION(FREQ_PROTECTED_SECTION, "w") DECLARE_DATA_SECTION(NEVER_PROTECTED_SECTION, "w") END_DATA_SECTION_DECLARATIONS() #endif static void data_section_init(void) { uint i; for (i = 0; i < DATASEC_NUM; i++) { if (datasec_start[i] != NULL) { /* We were called early due to an early syslog. * We still retain our slightly later normal init position so we can * log, etc. in normal runs. */ return; } ASSIGN_INIT_LOCK_FREE(datasec_lock[i], datasec_selfprot_lock); /* for DEBUG we use for data_sections_enclose_region() */ if (IF_WINDOWS(IF_DEBUG(true ||)) TEST(DATASEC_SELFPROT[i], dynamo_options.protect_mask)) { get_data_section_bounds(i); } } DOCHECK(1, { /* ensure no overlaps */ uint j; for (i = 0; i < DATASEC_NUM; i++) { for (j = i + 1; j < DATASEC_NUM; j++) { ASSERT(datasec_start[i] >= datasec_end[j] || datasec_start[j] >= datasec_end[i]); } } }); } static void data_section_exit(void) { uint i; DOSTATS({ /* There can't have been that many races. * A failure to re-protect should result in a ton of d_r_dispatch * entrances w/ .data unprot, so should show up here. * However, an app with threads that are initializing in DR and thus * unprotected .data while other threads are running new code (such as * on attach) can easily rack up hundreds of unprot cache entrances. */ ASSERT_CURIOSITY(GLOBAL_STAT(datasec_not_prot) < 5000); }); for (i = 0; i < DATASEC_NUM; i++) DELETE_LOCK(datasec_lock[i]); } #define DATASEC_WRITABLE_MOD(which, op) \ ((which) == DATASEC_RARELY_PROT \ ? (datasec_writable_rareprot op) \ : ((which) == DATASEC_CXTSW_PROT \ ? (datasec_writable_cxtswprot op) \ : ((which) == DATASEC_FREQ_PROT \ ? (datasec_writable_freqprot op) \ : (ASSERT_NOT_REACHED(), datasec_writable_neverprot)))) /* WARNING: any DO_ONCE will call this routine, so don't call anything here * that has a DO_ONCE, to avoid deadlock! */ void protect_data_section(uint sec, bool writable) { ASSERT(sec >= 0 && sec < DATASEC_NUM); ASSERT(TEST(DATASEC_SELFPROT[sec], dynamo_options.protect_mask)); /* We can be called very early before data_section_init() so init here * (data_section_init() has no dependences). */ if (datasec_start[sec] == NULL) { /* should only happen early in init */ ASSERT(!dynamo_initialized); data_section_init(); } d_r_mutex_lock(&datasec_lock[sec]); ASSERT(datasec_start[sec] != NULL); /* if using libc, we cannot print while data segment is read-only! * thus, if making it writable, do that first, otherwise do it last. * w/ ntdll this is not a problem. */ /* Remember that multiple threads can be doing (unprotect,protect) pairs of * calls simultaneously. The datasec_lock makes each individual call atomic, * and if all calls are properly nested, our use of counters should result in * the proper protection only after the final protect call and not in the * middle of some other thread's writes to the data section. */ if (writable) { /* On-context-switch protection has a separate mechanism for * only protecting when the final thread leaves DR */ ASSERT_CURIOSITY(DATASEC_WRITABLE(sec) <= 2); /* shouldn't nest too deep! */ if (DATASEC_WRITABLE(sec) == 0) { make_writable(datasec_start[sec], datasec_end[sec] - datasec_start[sec]); STATS_INC(datasec_prot_changes); } else STATS_INC(datasec_prot_wasted_calls); (void)DATASEC_WRITABLE_MOD(sec, ++); } LOG(TEST(DATASEC_SELFPROT[sec], SELFPROT_ON_CXT_SWITCH) ? THREAD_GET : GLOBAL, LOG_VMAREAS, TEST(DATASEC_SELFPROT[sec], SELFPROT_ON_CXT_SWITCH) ? 3U : 2U, "protect_data_section: thread " TIDFMT " %s (recur %d, stat %d) %s %s %d\n", d_r_get_thread_id(), DATASEC_WRITABLE(sec) == 1 ? "changing" : "nop", DATASEC_WRITABLE(sec), GLOBAL_STAT(datasec_not_prot), DATASEC_NAMES[sec], writable ? "rw" : "r", DATASEC_WRITABLE(sec)); if (!writable) { ASSERT(DATASEC_WRITABLE(sec) > 0); (void)DATASEC_WRITABLE_MOD(sec, --); if (DATASEC_WRITABLE(sec) == 0) { make_unwritable(datasec_start[sec], datasec_end[sec] - datasec_start[sec]); STATS_INC(datasec_prot_changes); } else STATS_INC(datasec_prot_wasted_calls); } d_r_mutex_unlock(&datasec_lock[sec]); } /* enter/exit DR hooks */ void entering_dynamorio(void) { if (SELF_PROTECT_ON_CXT_SWITCH) dynamorio_unprotect(); ASSERT(HOOK_ENABLED); LOG(GLOBAL, LOG_DISPATCH, 3, "entering_dynamorio thread=" TIDFMT "\n", d_r_get_thread_id()); STATS_INC(num_entering_DR); if (INTERNAL_OPTION(single_thread_in_DR)) { acquire_recursive_lock(&thread_in_DR_exclusion); LOG(GLOBAL, LOG_DISPATCH, 3, "entering_dynamorio thread=" TIDFMT " count=%d\n", d_r_get_thread_id(), thread_in_DR_exclusion.count); } } void exiting_dynamorio(void) { ASSERT(HOOK_ENABLED); LOG(GLOBAL, LOG_DISPATCH, 3, "exiting_dynamorio thread=" TIDFMT "\n", d_r_get_thread_id()); STATS_INC(num_exiting_DR); if (INTERNAL_OPTION(single_thread_in_DR)) { /* thread init/exit can proceed now */ LOG(GLOBAL, LOG_DISPATCH, 3, "exiting_dynamorio thread=" TIDFMT " count=%d\n", d_r_get_thread_id(), thread_in_DR_exclusion.count - 1); release_recursive_lock(&thread_in_DR_exclusion); } if (SELF_PROTECT_ON_CXT_SWITCH && !dynamo_exited) dynamorio_protect(); } /* Note this includes any stack guard pages */ bool is_on_initstack(byte *esp) { return (esp <= d_r_initstack && esp > d_r_initstack - DYNAMORIO_STACK_SIZE); } /* Note this includes any stack guard pages */ bool is_on_dstack(dcontext_t *dcontext, byte *esp) { return (esp <= dcontext->dstack && esp > dcontext->dstack - DYNAMORIO_STACK_SIZE); } bool is_currently_on_dstack(dcontext_t *dcontext) { byte *cur_esp; GET_STACK_PTR(cur_esp); return is_on_dstack(dcontext, cur_esp); } void pre_second_thread(void) { /* i#1111: nop-out bb_building_lock until 2nd thread created. * While normally we'll call this in the primary thread while not holding * the lock, it's possible on Windows for an externally injected thread * (or for a thread sneakily created by some native_exec code w/o going * through ntdll wrappers) to appear. We solve the problem of the main * thread currently holding bb_building_lock and us turning its * unlock into an error by the bb_lock_would_have bool in * SHARED_BB_UNLOCK(). */ if (!bb_lock_start) { d_r_mutex_lock(&bb_building_lock); SELF_UNPROTECT_DATASEC(DATASEC_RARELY_PROT); bb_lock_start = true; SELF_PROTECT_DATASEC(DATASEC_RARELY_PROT); d_r_mutex_unlock(&bb_building_lock); } }
1
17,614
Repeating: I don't think this should be a core-wide global var. This should be isolated to arch/x86 or at least arch/, maybe inside getter/setters as mentioned above.
DynamoRIO-dynamorio
c
@@ -55,8 +55,11 @@ class JMeterExecutor(ScenarioExecutor, WidgetProvider, FileLister): """ MIRRORS_SOURCE = "https://archive.apache.org/dist/jmeter/binaries/" JMETER_DOWNLOAD_LINK = "https://archive.apache.org/dist/jmeter/binaries/apache-jmeter-{version}.zip" + PLUGINS_MANAGER = 'https://repo1.maven.org/maven2/kg/apc/jmeter-plugins-manager/0.8/jmeter-plugins-manager-0.8.jar' + CMDRUNNER = 'http://search.maven.org/remotecontent?filepath=kg/apc/cmdrunner/2.0/cmdrunner-2.0.jar' + PLUGINS = ["jpgc-casutg", "jpgc-dummy", "jpgc-ffw", "jpgc-fifo", "jpgc-functions", + "jpgc-json", "jpgc-perfmon", "jpgc-prmctl", "jpgc-tst"] JMETER_VER = "3.0" - PLUGINS_DOWNLOAD_TPL = "http://jmeter-plugins.org/files/JMeterPlugins-{plugin}-1.4.0.zip" UDP_PORT_NUMBER = None def __init__(self):
1
""" Module holds all stuff regarding JMeter tool usage Copyright 2015 BlazeMeter Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import csv import fnmatch import json import mimetypes import os import re import socket import subprocess import tempfile import time import traceback from collections import Counter, namedtuple from distutils.version import LooseVersion from math import ceil from cssselect import GenericTranslator from bzt.engine import ScenarioExecutor, Scenario, FileLister from bzt.jmx import JMX from bzt.modules.aggregator import ConsolidatingAggregator, ResultsReader, DataPoint, KPISet from bzt.modules.console import WidgetProvider, SidebarWidget from bzt.modules.provisioning import Local from bzt.six import iteritems, string_types, StringIO, etree, binary_type from bzt.six import request as http_request from bzt.utils import get_full_path, EXE_SUFFIX, MirrorsManager from bzt.utils import shell_exec, ensure_is_dict, dehumanize_time, BetterDict, guess_csv_dialect from bzt.utils import unzip, RequiredTool, JavaVM, shutdown_process, ProgressBarContext, TclLibrary class JMeterExecutor(ScenarioExecutor, WidgetProvider, FileLister): """ JMeter executor module :type modified_jmx: str :type jmeter_log: str :type properties_file: str :type sys_properties_file: str """ MIRRORS_SOURCE = "https://archive.apache.org/dist/jmeter/binaries/" JMETER_DOWNLOAD_LINK = "https://archive.apache.org/dist/jmeter/binaries/apache-jmeter-{version}.zip" JMETER_VER = "3.0" PLUGINS_DOWNLOAD_TPL = "http://jmeter-plugins.org/files/JMeterPlugins-{plugin}-1.4.0.zip" UDP_PORT_NUMBER = None def __init__(self): super(JMeterExecutor, self).__init__() self.original_jmx = None self.modified_jmx = None self.jmeter_log = None self.properties_file = None self.sys_properties_file = None self.kpi_jtl = None self.log_jtl = None self.process = None self.start_time = None self.end_time = None self.retcode = None self.widget = None self.distributed_servers = [] self.management_port = None self.reader = None self._env = {} self.resource_files_collector = None def prepare(self): """ Preparation for JMeter involves either getting existing JMX and modifying it, or generating new JMX from input data. Then, original JMX is modified to contain JTL writing classes with required settings and have workload as suggested by Provisioning :raise ValueError: """ self.jmeter_log = self.engine.create_artifact("jmeter", ".log") self._set_remote_port() self.run_checklist() self.distributed_servers = self.execution.get('distributed', self.distributed_servers) scenario = self.get_scenario() is_jmx_generated = False if Scenario.SCRIPT in scenario and scenario[Scenario.SCRIPT]: self.original_jmx = self.get_script_path() elif scenario.get("requests"): self.original_jmx = self.__jmx_from_requests() is_jmx_generated = True else: raise ValueError("You must specify either a JMX file or list of requests to run JMeter") load = self.get_load() modified = self.__get_modified_jmx(self.original_jmx, load) self.modified_jmx = self.__save_modified_jmx(modified, self.original_jmx, is_jmx_generated) self.__set_jmeter_properties(scenario) self.__set_system_properties() self.__set_jvm_properties() if isinstance(self.engine.aggregator, ConsolidatingAggregator): self.reader = JTLReader(self.kpi_jtl, self.log, self.log_jtl) self.reader.is_distributed = len(self.distributed_servers) > 0 self.engine.aggregator.add_underling(self.reader) def __set_system_properties(self): sys_props = self.settings.get("system-properties") if sys_props: self.log.debug("Additional system properties %s", sys_props) sys_props_file = self.engine.create_artifact("system", ".properties") JMeterExecutor.__write_props_to_file(sys_props_file, sys_props) self.sys_properties_file = sys_props_file def __set_jvm_properties(self): heap_size = self.settings.get("memory-xmx", None) if heap_size is not None: self.log.debug("Setting JVM heap size to %s", heap_size) self._env["JVM_ARGS"] = "-Xmx%s" % heap_size def __set_jmeter_properties(self, scenario): props = self.settings.get("properties") props_local = scenario.get("properties") if self.distributed_servers and self.settings.get("gui", False): props_local.merge({"remote_hosts": ",".join(self.distributed_servers)}) props_local.update({"jmeterengine.nongui.port": self.management_port}) props_local.update({"jmeterengine.nongui.maxport": self.management_port}) props_local.update({"jmeter.save.saveservice.timestamp_format": "ms"}) props.merge(props_local) user_cp = self.engine.artifacts_dir if 'user.classpath' in props: user_cp += os.pathsep + props['user.classpath'] props['user.classpath'] = user_cp.replace(os.path.sep, "/") # replace to avoid Windows issue if props: self.log.debug("Additional properties: %s", props) props_file = self.engine.create_artifact("jmeter-bzt", ".properties") JMeterExecutor.__write_props_to_file(props_file, props) self.properties_file = props_file def startup(self): """ Should start JMeter as fast as possible. """ cmdline = [self.settings.get("path")] # default is set when prepared if not self.settings.get("gui", False): cmdline += ["-n"] cmdline += ["-t", os.path.abspath(self.modified_jmx)] if self.jmeter_log: cmdline += ["-j", os.path.abspath(self.jmeter_log)] if self.properties_file: cmdline += ["-q", os.path.abspath(self.properties_file)] if self.sys_properties_file: cmdline += ["-S", os.path.abspath(self.sys_properties_file)] if self.distributed_servers and not self.settings.get("gui", False): cmdline += ['-R%s' % ','.join(self.distributed_servers)] self.start_time = time.time() try: # FIXME: muting stderr and stdout is bad self.process = self.execute(cmdline, stderr=None, env=self._env) except OSError as exc: self.log.error("Failed to start JMeter: %s", traceback.format_exc()) self.log.error("Failed command: %s", cmdline) raise RuntimeError("Failed to start JMeter: %s" % exc) def check(self): """ Checks if JMeter is still running. Also checks if resulting JTL contains any data and throws exception otherwise. :return: bool :raise RuntimeWarning: """ if self.widget: self.widget.update() self.retcode = self.process.poll() if self.retcode is not None: if self.retcode != 0: self.log.info("JMeter exit code: %s", self.retcode) raise RuntimeError("JMeter exited with non-zero code") return True return False def shutdown(self): """ If JMeter is still running - let's stop it. """ max_attempts = self.settings.get("shutdown-wait", 5) if self._process_stopped(1): return try: if not self.settings.get("gui", False): udp_sock = socket.socket(type=socket.SOCK_DGRAM) self.log.info("Sending Shutdown command to JMeter on port %d...", self.management_port) udp_sock.sendto(b"Shutdown", ("localhost", self.management_port)) if self._process_stopped(max_attempts): self.log.debug("JMeter stopped on Shutdown command") return self.log.info("Sending StopTestNow command to JMeter on port %d...", self.management_port) udp_sock.sendto(b"StopTestNow", ("localhost", self.management_port)) if self._process_stopped(max_attempts): self.log.debug("JMeter stopped on StopTestNow command") return finally: if not self._process_stopped(1): self.log.warning("JMeter process is still alive, killing it") shutdown_process(self.process, self.log) if self.start_time: self.end_time = time.time() self.log.debug("JMeter worked for %s seconds", self.end_time - self.start_time) def post_process(self): self.engine.existing_artifact(self.modified_jmx, True) if self.reader and not self.reader.buffer and self.start_time is not None: msg = "Empty results JTL, most likely JMeter failed: %s" raise RuntimeWarning(msg % self.kpi_jtl) def _process_stopped(self, cycles): while cycles > 0: cycles -= 1 if self.process and self.process.poll() is None: time.sleep(self.engine.check_interval) else: return True return False def _set_remote_port(self): """ set management udp port :return: """ if not JMeterExecutor.UDP_PORT_NUMBER: JMeterExecutor.UDP_PORT_NUMBER = self.settings.get("shutdown-port", 4445) else: JMeterExecutor.UDP_PORT_NUMBER += 1 while not self.__port_is_free(JMeterExecutor.UDP_PORT_NUMBER): self.log.debug("Port %d is busy, trying next one", JMeterExecutor.UDP_PORT_NUMBER) if JMeterExecutor.UDP_PORT_NUMBER == 65535: self.log.error("No free ports for management interface") raise RuntimeError else: JMeterExecutor.UDP_PORT_NUMBER += 1 self.management_port = JMeterExecutor.UDP_PORT_NUMBER self.log.debug("Using port %d for management", self.management_port) def __port_is_free(self, port_num): """ :return: Bool """ udp_sock = socket.socket(type=socket.SOCK_DGRAM) try: self.log.debug("Checking if port %d is free", port_num) udp_sock.bind(("localhost", port_num)) udp_sock.close() self.log.debug("Port %d is free", port_num) return True except socket.error: self.log.debug("Port %d is busy", port_num) return False @staticmethod def __apply_ramp_up(jmx, ramp_up): """ Apply ramp up period in seconds to ThreadGroup.ramp_time :param jmx: JMX :param ramp_up: int ramp_up period :return: """ rampup_sel = "stringProp[name='ThreadGroup.ramp_time']" xpath = GenericTranslator().css_to_xpath(rampup_sel) for group in jmx.enabled_thread_groups(): prop = group.xpath(xpath) prop[0].text = str(ramp_up) @staticmethod def __apply_stepping_ramp_up(jmx, load): """ Change all thread groups to step groups, use ramp-up/steps :param jmx: JMX :param load: load :return: """ step_time = int(load.ramp_up / load.steps) thread_groups = jmx.tree.findall(".//ThreadGroup") for thread_group in thread_groups: thread_cnc = int(thread_group.find(".//*[@name='ThreadGroup.num_threads']").text) tg_name = thread_group.attrib["testname"] thread_step = int(ceil(float(thread_cnc) / load.steps)) step_group = JMX.get_stepping_thread_group(thread_cnc, thread_step, step_time, load.hold + step_time, tg_name) thread_group.getparent().replace(thread_group, step_group) @staticmethod def __apply_duration(jmx, duration): """ Apply duration to ThreadGroup.duration :param jmx: JMX :param duration: int :return: """ sched_sel = "[name='ThreadGroup.scheduler']" sched_xpath = GenericTranslator().css_to_xpath(sched_sel) dur_sel = "[name='ThreadGroup.duration']" dur_xpath = GenericTranslator().css_to_xpath(dur_sel) for group in jmx.enabled_thread_groups(): group.xpath(sched_xpath)[0].text = 'true' group.xpath(dur_xpath)[0].text = str(int(duration)) loops_element = group.find(".//elementProp[@name='ThreadGroup.main_controller']") loops_loop_count = loops_element.find("*[@name='LoopController.loops']") loops_loop_count.getparent().replace(loops_loop_count, JMX.int_prop("LoopController.loops", -1)) @staticmethod def __apply_iterations(jmx, iterations): """ Apply iterations to LoopController.loops :param jmx: JMX :param iterations: int :return: """ sel = "elementProp>[name='LoopController.loops']" xpath = GenericTranslator().css_to_xpath(sel) flag_sel = "elementProp>[name='LoopController.continue_forever']" flag_xpath = GenericTranslator().css_to_xpath(flag_sel) for group in jmx.enabled_thread_groups(): sprop = group.xpath(xpath) bprop = group.xpath(flag_xpath) if iterations: bprop[0].text = 'false' sprop[0].text = str(iterations) def __apply_concurrency(self, jmx, concurrency): """ Apply concurrency to ThreadGroup.num_threads :param jmx: JMX :param concurrency: int :return: """ # TODO: what to do when they used non-standard thread groups? tnum_sel = "stringProp[name='ThreadGroup.num_threads']" tnum_xpath = GenericTranslator().css_to_xpath(tnum_sel) orig_sum = 0.0 for group in jmx.enabled_thread_groups(): othreads = group.xpath(tnum_xpath) orig_sum += int(othreads[0].text) self.log.debug("Original threads: %s", orig_sum) leftover = concurrency for group in jmx.enabled_thread_groups(): othreads = group.xpath(tnum_xpath) orig = int(othreads[0].text) new = int(round(concurrency * orig / orig_sum)) leftover -= new othreads[0].text = str(new) if leftover < 0: msg = "Had to add %s more threads to maintain thread group proportion" self.log.warning(msg, -leftover) elif leftover > 0: msg = "%s threads left undistributed due to thread group proportion" self.log.warning(msg, leftover) def __convert_to_normal_tg(self, jmx, load): """ Convert all TGs to simple ThreadGroup :param jmx: JMX :param load: :return: """ if load.iterations or load.concurrency or load.duration: for group in jmx.enabled_thread_groups(all_types=True): if group.tag != 'ThreadGroup': testname = group.get('testname') self.log.warning("Converting %s (%s) to normal ThreadGroup", group.tag, testname) group_concurrency = JMeterExecutor.__get_concurrency_from_tg(group) on_error = JMeterExecutor.__get_tg_action_on_error(group) if group_concurrency: new_group = JMX.get_thread_group(group_concurrency, 0, -1, testname, on_error) else: new_group = JMX.get_thread_group(1, 0, -1, testname, on_error) group.getparent().replace(group, new_group) @staticmethod def __get_concurrency_from_tg(thread_group): """ :param thread_group: etree.Element :return: """ concurrency_element = thread_group.find(".//stringProp[@name='ThreadGroup.num_threads']") if concurrency_element is not None: return int(concurrency_element.text) @staticmethod def __get_tg_action_on_error(thread_group): action = thread_group.find(".//stringProp[@name='ThreadGroup.on_sample_error']") if action is not None: return action.text @staticmethod def __add_shaper(jmx, load): """ Add shaper :param jmx: JMX :param load: namedtuple("LoadSpec", ('concurrency', "throughput", 'ramp_up', 'hold', 'iterations', 'duration')) :return: """ if load.throughput and load.duration: etree_shaper = jmx.get_rps_shaper() if load.ramp_up: jmx.add_rps_shaper_schedule(etree_shaper, 1, load.throughput, load.ramp_up) if load.hold: jmx.add_rps_shaper_schedule(etree_shaper, load.throughput, load.throughput, load.hold) jmx.append(JMeterScenarioBuilder.TEST_PLAN_SEL, etree_shaper) jmx.append(JMeterScenarioBuilder.TEST_PLAN_SEL, etree.Element("hashTree")) def __add_stepping_shaper(self, jmx, load): """ adds stepping shaper 1) warning if any ThroughputTimer found 2) add VariableThroughputTimer to test plan :param jmx: JMX :param load: load :return: """ timers_patterns = ["ConstantThroughputTimer", "kg.apc.jmeter.timers.VariableThroughputTimer"] for timer_pattern in timers_patterns: for timer in jmx.tree.findall(".//%s" % timer_pattern): self.log.warning("Test plan already use %s", timer.attrib['testname']) step_rps = int(round(float(load.throughput) / load.steps)) step_time = int(round(float(load.ramp_up) / load.steps)) step_shaper = jmx.get_rps_shaper() for step in range(1, int(load.steps + 1)): step_load = step * step_rps if step != load.steps: jmx.add_rps_shaper_schedule(step_shaper, step_load, step_load, step_time) else: if load.hold: jmx.add_rps_shaper_schedule(step_shaper, step_load, step_load, step_time + load.hold) jmx.append(JMeterScenarioBuilder.TEST_PLAN_SEL, step_shaper) jmx.append(JMeterScenarioBuilder.TEST_PLAN_SEL, etree.Element("hashTree")) @staticmethod def __disable_listeners(jmx): """ Set ResultCollector to disabled :param jmx: JMX :return: """ sel = 'stringProp[name=filename]' xpath = GenericTranslator().css_to_xpath(sel) listeners = jmx.get('ResultCollector') for listener in listeners: file_setting = listener.xpath(xpath) if not file_setting or not file_setting[0].text: listener.set("enabled", "false") def __apply_load_settings(self, jmx, load): self.__convert_to_normal_tg(jmx, load) if load.concurrency: self.__apply_concurrency(jmx, load.concurrency) if load.hold or (load.ramp_up and not load.iterations): JMeterExecutor.__apply_duration(jmx, int(load.duration)) if load.iterations: JMeterExecutor.__apply_iterations(jmx, int(load.iterations)) if load.ramp_up: JMeterExecutor.__apply_ramp_up(jmx, int(load.ramp_up)) if load.steps: JMeterExecutor.__apply_stepping_ramp_up(jmx, load) if load.throughput: if load.steps: self.__add_stepping_shaper(jmx, load) else: JMeterExecutor.__add_shaper(jmx, load) @staticmethod def __fill_empty_delimiters(jmx): delimiters = jmx.get("CSVDataSet>stringProp[name='delimiter']") for delimiter in delimiters: if not delimiter.text: delimiter.text = ',' @staticmethod def __add_listener(lst, jmx): jmx.append(JMeterScenarioBuilder.TEST_PLAN_SEL, lst) jmx.append(JMeterScenarioBuilder.TEST_PLAN_SEL, etree.Element("hashTree")) def __add_result_writers(self, jmx): self.kpi_jtl = self.engine.create_artifact("kpi", ".jtl") kpi_lst = jmx.new_kpi_listener(self.kpi_jtl) self.__add_listener(kpi_lst, jmx) jtl_log_level = self.execution.get('write-xml-jtl', 'error') if jtl_log_level == 'error': self.log_jtl = self.engine.create_artifact("error", ".jtl") log_lst = jmx.new_xml_listener(self.log_jtl, False) self.__add_listener(log_lst, jmx) elif jtl_log_level == 'full': self.log_jtl = self.engine.create_artifact("trace", ".jtl") log_lst = jmx.new_xml_listener(self.log_jtl, True) self.__add_listener(log_lst, jmx) def __force_tran_parent_sample(self, jmx): scenario = self.get_scenario() if scenario.get("force-parent-sample", True): self.log.debug("Enforcing parent sample for transaction controller") jmx.set_text('TransactionController > boolProp[name="TransactionController.parent"]', 'true') def __get_modified_jmx(self, original, load): """ add two listeners to test plan: - to collect basic stats for KPIs - to collect detailed errors/trace info :return: path to artifact """ self.log.debug("Load: %s", load) jmx = JMX(original) if self.get_scenario().get("disable-listeners", True): JMeterExecutor.__disable_listeners(jmx) user_def_vars = self.get_scenario().get("variables") if user_def_vars: jmx.append(JMeterScenarioBuilder.TEST_PLAN_SEL, jmx.add_user_def_vars_elements(user_def_vars)) jmx.append(JMeterScenarioBuilder.TEST_PLAN_SEL, etree.Element("hashTree")) self.__apply_modifications(jmx) self.__apply_load_settings(jmx, load) self.__add_result_writers(jmx) self.__force_tran_parent_sample(jmx) self.__fill_empty_delimiters(jmx) return jmx def __save_modified_jmx(self, jmx, original_jmx_path, is_jmx_generated): script_name, _ = os.path.splitext(os.path.basename(original_jmx_path)) modified_script_name = "modified_" + script_name if is_jmx_generated: filename = self.engine.create_artifact(modified_script_name, ".jmx") else: filename = os.path.join(os.path.dirname(original_jmx_path), modified_script_name + ".jmx") jmx.save(filename) return filename def __jmx_from_requests(self): """ Generate jmx file from requests :return: """ filename = self.engine.create_artifact("requests", ".jmx") jmx = JMeterScenarioBuilder(self) jmx.save(filename) self.settings.merge(jmx.system_props) return filename @staticmethod def __write_props_to_file(file_path, params): """ Write properties to file :param file_path: :param params: :return: """ with open(file_path, 'w') as fds: for key, val in iteritems(params): fds.write("%s=%s\n" % (key, val)) def get_widget(self): """ Add progress widget to console screen sidebar :return: """ if not self.widget: label = "%s" % self self.widget = SidebarWidget(self, "JMeter: " + label.split('/')[1]) return self.widget def __modify_resources_paths_in_jmx(self, jmx, file_list): """ Modify resource files paths in jmx etree :param jmx: JMX :param file_list: list :return: """ for filename in file_list: file_path = self.engine.find_file(filename) if os.path.exists(file_path): file_path_elements = jmx.xpath('//stringProp[text()="%s"]' % file_path) for file_path_element in file_path_elements: basename = os.path.basename(file_path) self.log.debug("Replacing JMX path %s with %s", file_path_element.text, basename) file_path_element.text = basename else: self.log.warning("File not found: %s", file_path) def resource_files(self): """ Get list of resource files, modify jmx file paths if necessary """ resource_files = set() # get all resource files from requests scenario = self.get_scenario() self.resource_files_collector = ResourceFilesCollector(self) files_from_requests = self.res_files_from_scenario(scenario) if not self.original_jmx: self.original_jmx = self.get_script_path() if self.original_jmx and os.path.exists(self.original_jmx): jmx = JMX(self.original_jmx) resource_files_from_jmx = JMeterExecutor.__get_resource_files_from_jmx(jmx) if resource_files_from_jmx: if not isinstance(self.engine.provisioning, Local): self.__modify_resources_paths_in_jmx(jmx.tree, resource_files_from_jmx) script_name, script_ext = os.path.splitext(os.path.basename(self.original_jmx)) self.original_jmx = self.engine.create_artifact(script_name, script_ext) jmx.save(self.original_jmx) resource_files.update(resource_files_from_jmx) resource_files.update(files_from_requests) if self.original_jmx: resource_files.add(self.original_jmx) return list(resource_files) @staticmethod def __get_resource_files_from_jmx(jmx): """ Get list of resource files paths from jmx scenario :return: (file list) """ resource_files = [] exclude_elements = ['kg.apc.jmeter.jmxmon.JMXMonCollector', 'JSR223Listener', 'kg.apc.jmeter.vizualizers.CorrectedResultCollector', 'kg.apc.jmeter.reporters.FlexibleFileWriter', 'BSFListener', 'kg.apc.jmeter.dbmon.DbMonCollector', 'BeanShellListener', 'MailerResultCollector', 'kg.apc.jmeter.perfmon.PerfMonCollector', 'ResultCollector', 'kg.apc.jmeter.vizualizers.CompositeResultCollector', 'kg.apc.jmeter.reporters.LoadosophiaUploader'] search_patterns = ["File.path", "filename", "BeanShellSampler.filename"] for pattern in search_patterns: resource_elements = jmx.tree.findall(".//stringProp[@name='%s']" % pattern) for resource_element in resource_elements: # check if none of parents are disabled parent = resource_element.getparent() parent_disabled = False while parent is not None: # ? if parent.get('enabled') == 'false' or parent.tag in exclude_elements: parent_disabled = True break parent = parent.getparent() if resource_element.text and parent_disabled is False: resource_files.append(resource_element.text) return resource_files def res_files_from_scenario(self, scenario): files = [] data_sources = scenario.data.get('data-sources') if data_sources: for data_source in data_sources: if isinstance(data_source, string_types): files.append(data_source) elif isinstance(data_source, dict): files.append(data_source['path']) requests_parser = RequestsParser(self.engine) requests = requests_parser.extract_requests(scenario) for req in requests: files.extend(self.res_files_from_request(req)) return files def res_files_from_request(self, request): if self.resource_files_collector is None: self.resource_files_collector = ResourceFilesCollector(self) return self.resource_files_collector.visit(request) def __apply_modifications(self, jmx): """ :type jmx: JMX """ modifs = self.get_scenario().get("modifications") if 'disable' in modifs: self.__apply_enable_disable(modifs, 'disable', jmx) if 'enable' in modifs: self.__apply_enable_disable(modifs, 'enable', jmx) if 'set-prop' in modifs: items = modifs['set-prop'] for path, text in iteritems(items): parts = path.split('>') if len(parts) < 2: raise ValueError("Property selector must have at least 2 levels") sel = "[testname='%s']" % parts[0] # TODO: support wildcards in element names for add in parts[1:]: sel += ">[name='%s']" % add if not jmx.set_text(sel, text): self.log.warn("No elements matched for set-prop: %s", path) def __apply_enable_disable(self, modifs, action, jmx): items = modifs[action] if not isinstance(items, list): modifs[action] = [items] items = modifs[action] for name in items: candidates = jmx.get("[testname]") for candidate in candidates: if fnmatch.fnmatch(candidate.get('testname'), name): jmx.set_enabled("[testname='%s']" % candidate.get('testname'), True if action == 'enable' else False) def run_checklist(self): """ check tools """ required_tools = [JavaVM("", "", self.log), TclLibrary(self.log)] for tool in required_tools: if not tool.check_if_installed(): self.log.info("Installing %s", tool.tool_name) tool.install() jmeter_path = self.settings.get("path", "~/.bzt/jmeter-taurus/") jmeter_path = get_full_path(jmeter_path) jmeter_version = self.settings.get("version", JMeterExecutor.JMETER_VER) download_link = self.settings.get("download-link", JMeterExecutor.JMETER_DOWNLOAD_LINK) plugin_download_link = self.settings.get("plugins-download-link", JMeterExecutor.PLUGINS_DOWNLOAD_TPL) tool = JMeter(jmeter_path, self.log, jmeter_version, download_link, plugin_download_link) if self._need_to_install(tool): self.log.info("Installing %s", tool.tool_name) tool.install() self.settings['path'] = tool.tool_path @staticmethod def _need_to_install(tool): end_str_l = os.path.join('bin', 'jmeter' + EXE_SUFFIX) end_str_s = os.path.join('bin', 'jmeter') if os.path.isfile(tool.tool_path): if tool.check_if_installed(): # all ok, it's really tool path return False else: # probably it's path to other tool) raise ValueError('Wrong tool path: %s' % tool.tool_path) if os.path.isdir(tool.tool_path): # it's dir: fix tool path and install if needed tool.tool_path = os.path.join(tool.tool_path, end_str_l) if tool.check_if_installed(): return False else: return True # similar to future jmeter directory if not (tool.tool_path.endswith(end_str_l) or tool.tool_path.endswith(end_str_s)): tool.tool_path = os.path.join(tool.tool_path, end_str_l) return True class JTLReader(ResultsReader): """ Class to read KPI JTL :type errors_reader: JTLErrorsReader """ def __init__(self, filename, parent_logger, errors_filename): super(JTLReader, self).__init__() self.is_distributed = False self.log = parent_logger.getChild(self.__class__.__name__) self.csvreader = IncrementalCSVReader(self.log, filename) self.read_records = 0 if errors_filename: self.errors_reader = JTLErrorsReader(errors_filename, parent_logger) else: self.errors_reader = None def _read(self, last_pass=False): """ Generator method that returns next portion of data :type last_pass: bool """ if self.errors_reader: self.errors_reader.read_file() for row in self.csvreader.read(last_pass): label = row["label"] if self.is_distributed: concur = int(row["grpThreads"]) trname = row["Hostname"] + row["threadName"][:row["threadName"].rfind('-')] else: concur = int(row["allThreads"]) trname = '' rtm = int(row["elapsed"]) / 1000.0 ltc = int(row["Latency"]) / 1000.0 if "Connect" in row: cnn = int(row["Connect"]) / 1000.0 if cnn < ltc: # this is generally bad idea... ltc -= cnn # fixing latency included into connect time else: cnn = None rcd = row["responseCode"] if rcd.endswith('Exception'): rcd = rcd.split('.')[-1] if row["success"] != "true": error = row["responseMessage"] else: error = None tstmp = int(int(row["timeStamp"]) / 1000) self.read_records += 1 yield tstmp, label, concur, rtm, cnn, ltc, rcd, error, trname def _calculate_datapoints(self, final_pass=False): for point in super(JTLReader, self)._calculate_datapoints(final_pass): if self.errors_reader: data = self.errors_reader.get_data(point[DataPoint.TIMESTAMP]) for label, label_data in iteritems(point[DataPoint.CURRENT]): if label in data: label_data[KPISet.ERRORS] = data[label] else: label_data[KPISet.ERRORS] = {} yield point class IncrementalCSVReader(object): """ JTL csv reader """ def __init__(self, parent_logger, filename): self.buffer = StringIO() self.csv_reader = csv.DictReader(self.buffer, []) self.log = parent_logger.getChild(self.__class__.__name__) self.indexes = {} self.partial_buffer = "" self.offset = 0 self.filename = filename self.fds = None def read(self, last_pass=False): """ read data from jtl yield csv row :type last_pass: bool """ if not self.fds and not self.__open_fds(): self.log.debug("No data to start reading yet") return self.log.debug("Reading JTL: %s", self.filename) self.fds.seek(self.offset) # without this we have stuck reads on Mac if last_pass: lines = self.fds.readlines() # unlimited else: lines = self.fds.readlines(1024 * 1024) # 1MB limit to read self.offset = self.fds.tell() self.log.debug("Read lines: %s / %s bytes", len(lines), len(''.join(lines))) for line in lines: if not line.endswith("\n"): self.partial_buffer += line continue line = "%s%s" % (self.partial_buffer, line) self.partial_buffer = "" if not self.csv_reader.fieldnames: self.csv_reader.dialect = guess_csv_dialect(line) self.csv_reader.fieldnames += line.strip().split(self.csv_reader.dialect.delimiter) self.log.debug("Analyzed header line: %s", self.csv_reader.fieldnames) continue self.buffer.write(line) self.buffer.seek(0) for row in self.csv_reader: yield row self.buffer.seek(0) self.buffer.truncate(0) def __open_fds(self): """ Opens JTL file for reading """ if not os.path.isfile(self.filename): self.log.debug("File not appeared yet: %s", self.filename) return False fsize = os.path.getsize(self.filename) if not fsize: self.log.debug("File is empty: %s", self.filename) return False if fsize <= self.offset: self.log.debug("Waiting file to grow larget than %s, current: %s", self.offset, fsize) return False self.log.debug("Opening file: %s", self.filename) self.fds = open(self.filename) self.fds.seek(self.offset) return True def __del__(self): if self.fds: self.fds.close() class JTLErrorsReader(object): """ Reader for errors.jtl, which is in XML max-verbose format :type filename: str :type parent_logger: logging.Logger """ assertionMessage = GenericTranslator().css_to_xpath("assertionResult>failureMessage") url_xpath = GenericTranslator().css_to_xpath("java\\.net\\.URL") def __init__(self, filename, parent_logger): # http://stackoverflow.com/questions/9809469/python-sax-to-lxml-for-80gb-xml/9814580#9814580 super(JTLErrorsReader, self).__init__() self.log = parent_logger.getChild(self.__class__.__name__) self.parser = etree.XMLPullParser(events=('end',)) # context = etree.iterparse(self.fds, events=('end',)) self.offset = 0 self.filename = filename self.fds = None self.buffer = BetterDict() self.failed_processing = False def __del__(self): if self.fds: self.fds.close() def read_file(self): """ Read the next part of the file :return: """ if self.failed_processing: return if not self.fds: if os.path.exists(self.filename) and os.path.getsize(self.filename): # getsize check to not stuck on mac self.log.debug("Opening %s", self.filename) self.fds = open(self.filename, 'rb') else: self.log.debug("File not exists: %s", self.filename) return self.fds.seek(self.offset) read = self.fds.read(1024 * 1024) if read.strip(): try: self.parser.feed(read) # "Huge input lookup" error without capping :) except etree.XMLSyntaxError as exc: self.failed_processing = True self.log.debug("Error reading errors.jtl: %s", traceback.format_exc()) self.log.warning("Failed to parse errors XML: %s", exc) self.offset = self.fds.tell() for _action, elem in self.parser.read_events(): del _action if elem.getparent() is not None and elem.getparent().tag == 'testResults': if elem.get('s'): result = elem.get('s') else: result = elem.xpath('success')[0].text if result == 'false': if elem.items(): self.__extract_standard(elem) else: self.__extract_nonstandard(elem) # cleanup processed from the memory elem.clear() while elem.getprevious() is not None: del elem.getparent()[0] def get_data(self, max_ts): """ Get accumulated errors data up to specified timestamp :param max_ts: :return: """ result = BetterDict() for t_stamp in sorted(self.buffer.keys()): if t_stamp > max_ts: break labels = self.buffer.pop(t_stamp) for label, label_data in iteritems(labels): res = result.get(label, []) for err_item in label_data: KPISet.inc_list(res, ('msg', err_item['msg']), err_item) return result def __extract_standard(self, elem): t_stamp = int(elem.get("ts")) / 1000 label = elem.get("lb") r_code = elem.get("rc") urls = elem.xpath(self.url_xpath) if urls: url = Counter({urls[0].text: 1}) else: url = Counter() errtype = KPISet.ERRTYPE_ERROR failed_assertion = self.__get_failed_assertion(elem) if failed_assertion is not None: errtype = KPISet.ERRTYPE_ASSERT message = self.get_failure_message(elem) if message is None: message = elem.get('rm') err_item = KPISet.error_item_skel(message, r_code, 1, errtype, url) KPISet.inc_list(self.buffer.get(t_stamp).get(label, []), ("msg", message), err_item) KPISet.inc_list(self.buffer.get(t_stamp).get('', []), ("msg", message), err_item) def __extract_nonstandard(self, elem): t_stamp = int(self.__get_child(elem, 'timeStamp')) / 1000 # NOTE: will it be sometimes EndTime? label = self.__get_child(elem, "label") message = self.__get_child(elem, "responseMessage") r_code = self.__get_child(elem, "responseCode") urls = elem.xpath(self.url_xpath) if urls: url = Counter({urls[0].text: 1}) else: url = Counter() errtype = KPISet.ERRTYPE_ERROR massert = elem.xpath(self.assertionMessage) if len(massert): errtype = KPISet.ERRTYPE_ASSERT message = massert[0].text err_item = KPISet.error_item_skel(message, r_code, 1, errtype, url) KPISet.inc_list(self.buffer.get(t_stamp).get(label, []), ("msg", message), err_item) KPISet.inc_list(self.buffer.get(t_stamp).get('', []), ("msg", message), err_item) def get_failure_message(self, element): """ Returns failure message """ failed_assertion = self.__get_failed_assertion(element) if failed_assertion is not None: assertion_message = self.__get_assertion_message(failed_assertion) if assertion_message: return assertion_message else: return element.get('rm') r_code = element.get('rc') if r_code and r_code.startswith("2"): if element.get('s') == "false": children = [elem for elem in element.iterchildren() if elem.tag == "httpSample"] for child in children: child_message = self.get_failure_message(child) if child_message: return child_message else: return element.get('rm') def __get_assertion_message(self, assertion_element): """ Returns assertion failureMessage if "failureMessage" element exists """ failure_message_elem = assertion_element.find("failureMessage") if failure_message_elem is not None: msg = failure_message_elem.text if msg.startswith("The operation lasted too long"): msg = "The operation lasted too long" return msg def __get_failed_assertion(self, element): """ Returns first failed assertion, or None """ assertions = [elem for elem in element.iterchildren() if elem.tag == "assertionResult"] for assertion in assertions: if self.__assertion_is_failed(assertion): return assertion def __assertion_is_failed(self, assertion_element): """ returns True if assertion failed """ failed = assertion_element.find("failure") error = assertion_element.find("error") if failed.text == "true" or error.text == "true": return True return False def __get_child(self, elem, tag): for child in elem: if child.tag == tag: return child.text class JMeterScenarioBuilder(JMX): """ Helper to build JMeter test plan from Scenario :param executor: ScenarioExecutor :param original: inherited from JMX """ def __init__(self, executor, original=None): super(JMeterScenarioBuilder, self).__init__(original) self.executor = executor self.scenario = executor.get_scenario() self.engine = executor.engine self.system_props = BetterDict() self.request_compiler = None def __gen_managers(self, scenario): elements = [] headers = scenario.get_headers() if headers: elements.append(self._get_header_mgr(headers)) elements.append(etree.Element("hashTree")) if scenario.get("store-cache", True): elements.append(self._get_cache_mgr()) elements.append(etree.Element("hashTree")) if scenario.get("store-cookie", True): elements.append(self._get_cookie_mgr()) elements.append(etree.Element("hashTree")) if scenario.get("use-dns-cache-mgr", True): elements.append(self.get_dns_cache_mgr()) elements.append(etree.Element("hashTree")) self.system_props.merge({"system-properties": {"sun.net.inetaddr.ttl": 0}}) return elements @staticmethod def smart_time(any_time): try: smart_time = int(1000 * dehumanize_time(any_time)) except ValueError: smart_time = any_time return smart_time def __gen_defaults(self, scenario): default_address = scenario.get("default-address", None) retrieve_resources = scenario.get("retrieve-resources", True) concurrent_pool_size = scenario.get("concurrent-pool-size", 4) timeout = scenario.get("timeout", None) timeout = self.smart_time(timeout) elements = [self._get_http_defaults(default_address, timeout, retrieve_resources, concurrent_pool_size), etree.Element("hashTree")] return elements def __add_think_time(self, children, req): global_ttime = self.scenario.get("think-time", None) if req.think_time is not None: ttime = self.smart_time(req.think_time) elif global_ttime is not None: ttime = self.smart_time(global_ttime) else: ttime = None if ttime is not None: children.append(JMX._get_constant_timer(ttime)) children.append(etree.Element("hashTree")) def __add_extractors(self, children, req): extractors = req.config.get("extract-regexp", BetterDict()) for varname in extractors: cfg = ensure_is_dict(extractors, varname, "regexp") extractor = JMX._get_extractor(varname, cfg.get('subject', 'body'), cfg['regexp'], cfg.get('template', 1), cfg.get('match-no', 1), cfg.get('default', 'NOT_FOUND')) children.append(extractor) children.append(etree.Element("hashTree")) jextractors = req.config.get("extract-jsonpath", BetterDict()) for varname in jextractors: cfg = ensure_is_dict(jextractors, varname, "jsonpath") children.append(JMX._get_json_extractor(varname, cfg['jsonpath'], cfg.get('default', 'NOT_FOUND'))) children.append(etree.Element("hashTree")) css_jquery_extors = req.config.get("extract-css-jquery", BetterDict()) for varname in css_jquery_extors: cfg = ensure_is_dict(css_jquery_extors, varname, "expression") extractor = self._get_jquerycss_extractor(varname, cfg['expression'], cfg.get('attribute', ""), cfg.get('match-no', 0), cfg.get('default', 'NOT_FOUND')) children.append(extractor) children.append(etree.Element("hashTree")) xpath_extractors = req.config.get("extract-xpath", BetterDict()) for varname in xpath_extractors: cfg = ensure_is_dict(xpath_extractors, varname, "xpath") children.append(JMX._get_xpath_extractor(varname, cfg['xpath'], cfg.get('default', 'NOT_FOUND'), cfg.get('validate-xml', False), cfg.get('ignore-whitespace', True), cfg.get('use-tolerant-parser', False))) children.append(etree.Element("hashTree")) def __add_assertions(self, children, req): assertions = req.config.get("assert", []) for idx, assertion in enumerate(assertions): assertion = ensure_is_dict(assertions, idx, "contains") if not isinstance(assertion['contains'], list): assertion['contains'] = [assertion['contains']] children.append(JMX._get_resp_assertion(assertion.get("subject", Scenario.FIELD_BODY), assertion['contains'], assertion.get('regexp', True), assertion.get('not', False), assertion.get('assume-success', False)), ) children.append(etree.Element("hashTree")) jpath_assertions = req.config.get("assert-jsonpath", []) for idx, assertion in enumerate(jpath_assertions): assertion = ensure_is_dict(jpath_assertions, idx, "jsonpath") component = JMX._get_json_path_assertion(assertion['jsonpath'], assertion.get('expected-value', ''), assertion.get('validate', False), assertion.get('expect-null', False), assertion.get('invert', False), ) children.append(component) children.append(etree.Element("hashTree")) xpath_assertions = req.config.get("assert-xpath", []) for idx, assertion in enumerate(xpath_assertions): assertion = ensure_is_dict(xpath_assertions, idx, "xpath") component = JMX._get_xpath_assertion(assertion['xpath'], assertion.get('validate-xml', False), assertion.get('ignore-whitespace', True), assertion.get('use-tolerant-parser', False), assertion.get('invert', False)) children.append(component) children.append(etree.Element("hashTree")) def _get_merged_ci_headers(self, req, header): def dic_lower(dic): return {k.lower(): dic[k].lower() for k in dic} ci_scenario_headers = dic_lower(self.scenario.get_headers()) ci_request_headers = dic_lower(req.headers) headers = BetterDict() headers.merge(ci_scenario_headers) headers.merge(ci_request_headers) if header.lower() in headers: return headers[header] else: return None def __gen_requests(self, scenario): requests_parser = RequestsParser(self.engine) requests = list(requests_parser.extract_requests(scenario)) elements = [] for compiled in self.compile_requests(requests): elements.extend(compiled) return elements def compile_scenario(self, scenario): elements = [] elements.extend(self.__gen_managers(scenario)) elements.extend(self.__gen_defaults(scenario)) elements.extend(self.__gen_datasources(scenario)) elements.extend(self.__gen_requests(scenario)) return elements def compile_http_request(self, request): global_timeout = self.scenario.get("timeout", None) global_keepalive = self.scenario.get("keepalive", True) if request.timeout is not None: timeout = self.smart_time(request.timeout) elif global_timeout is not None: timeout = self.smart_time(global_timeout) else: timeout = None content_type = self._get_merged_ci_headers(request, 'content-type') if content_type == 'application/json' and isinstance(request.body, dict): body = json.dumps(request.body) else: body = request.body http = JMX._get_http_request(request.url, request.label, request.method, timeout, body, global_keepalive, request.upload_files) children = etree.Element("hashTree") if request.headers: children.append(JMX._get_header_mgr(request.headers)) children.append(etree.Element("hashTree")) self.__add_think_time(children, request) self.__add_assertions(children, request) if timeout is not None: children.append(JMX._get_dur_assertion(timeout)) children.append(etree.Element("hashTree")) self.__add_extractors(children, request) return [http, children] def compile_if_block(self, block): elements = [] # TODO: pass jmeter IfController options if_controller = JMX._get_if_controller(block.condition) then_children = etree.Element("hashTree") for compiled in self.compile_requests(block.then_clause): for element in compiled: then_children.append(element) elements.extend([if_controller, then_children]) if block.else_clause: inverted_condition = "!(" + block.condition + ")" else_controller = JMX._get_if_controller(inverted_condition) else_children = etree.Element("hashTree") for compiled in self.compile_requests(block.else_clause): for element in compiled: else_children.append(element) elements.extend([else_controller, else_children]) return elements def compile_loop_block(self, block): elements = [] loop_controller = JMX._get_loop_controller(block.loops) children = etree.Element("hashTree") for compiled in self.compile_requests(block.requests): for element in compiled: children.append(element) elements.extend([loop_controller, children]) return elements def compile_while_block(self, block): elements = [] controller = JMX._get_while_controller(block.condition) children = etree.Element("hashTree") for compiled in self.compile_requests(block.requests): for element in compiled: children.append(element) elements.extend([controller, children]) return elements def compile_foreach_block(self, block): """ :type block: ForEachBlock """ elements = [] controller = JMX._get_foreach_controller(block.input_var, block.loop_var) children = etree.Element("hashTree") for compiled in self.compile_requests(block.requests): for element in compiled: children.append(element) elements.extend([controller, children]) return elements def compile_transaction_block(self, block): elements = [] controller = JMX._get_transaction_controller(block.name) children = etree.Element("hashTree") for compiled in self.compile_requests(block.requests): for element in compiled: children.append(element) elements.extend([controller, children]) return elements def compile_include_scenario_block(self, block): elements = [] controller = JMX._get_simple_controller(block.scenario_name) children = etree.Element("hashTree") scenario = self.executor.get_scenario(name=block.scenario_name) for element in self.compile_scenario(scenario): children.append(element) elements.extend([controller, children]) return elements def compile_requests(self, requests): if self.request_compiler is None: self.request_compiler = RequestCompiler(self) return [self.request_compiler.visit(request) for request in requests] def __generate(self): """ Generate the test plan """ thread_group = self.get_thread_group(concurrency=1, rampup=0, iterations=-1) thread_group_ht = etree.Element("hashTree", type="tg") # NOTE: set realistic dns-cache and JVM prop by default? self.request_compiler = RequestCompiler(self) for element in self.compile_scenario(self.scenario): thread_group_ht.append(element) results_tree = self._get_results_tree() results_tree_ht = etree.Element("hashTree") self.append(self.TEST_PLAN_SEL, thread_group) self.append(self.TEST_PLAN_SEL, thread_group_ht) self.append(self.TEST_PLAN_SEL, results_tree) self.append(self.TEST_PLAN_SEL, results_tree_ht) def save(self, filename): """ Generate test plan and save :type filename: str """ # NOTE: bad design, as repetitive save will duplicate stuff self.__generate() super(JMeterScenarioBuilder, self).save(filename) def __gen_datasources(self, scenario): sources = scenario.get("data-sources", []) if not sources: return [] if not isinstance(sources, list): raise ValueError("data-sources is not a list") elements = [] for idx, source in enumerate(sources): source = ensure_is_dict(sources, idx, "path") source_path = self.executor.engine.find_file(source["path"]) delimiter = source.get("delimiter", self.__guess_delimiter(source_path)) config = JMX._get_csv_config(os.path.abspath(source_path), delimiter, source.get("quoted", False), source.get("loop", True)) elements.append(config) elements.append(etree.Element("hashTree")) return elements def __guess_delimiter(self, path): with open(path) as fhd: header = fhd.read(4096) # 4KB is enough for header try: delimiter = guess_csv_dialect(header).delimiter except BaseException as exc: self.log.debug(traceback.format_exc()) self.log.warning('CSV dialect detection failed (%s), default delimiter selected (",")', exc) delimiter = "," # default value return delimiter class JMeter(RequiredTool): """ JMeter tool """ def __init__(self, tool_path, parent_logger, jmeter_version, jmeter_download_link, plugin_link): super(JMeter, self).__init__("JMeter", tool_path) self.log = parent_logger.getChild(self.__class__.__name__) self.version = jmeter_version self.mirror_manager = JMeterMirrorsManager(self.log, self.version, jmeter_download_link) self.plugins = ["Standard", "Extras", "ExtrasLibs", "WebDriver"] self.plugin_link = plugin_link def check_if_installed(self): self.log.debug("Trying jmeter: %s", self.tool_path) try: with tempfile.NamedTemporaryFile(prefix="jmeter", suffix="log", delete=False) as jmlog: jm_proc = shell_exec([self.tool_path, '-j', jmlog.name, '--version'], stderr=subprocess.STDOUT) jmout, jmerr = jm_proc.communicate() self.log.debug("JMeter check: %s / %s", jmout, jmerr) os.remove(jmlog.name) if isinstance(jmout, binary_type): jmout = jmout.decode() if "is too low to run JMeter" in jmout: self.log.error(jmout) raise ValueError("Java version is too low to run JMeter") return True except OSError: self.log.debug("JMeter check failed.") return False def install(self): full_tool_path = get_full_path(self.tool_path) dest = get_full_path(os.path.join(os.path.dirname(full_tool_path), os.path.pardir)) with super(JMeter, self).install_with_mirrors(dest, ".zip") as jmeter_dist: self.log.info("Unzipping %s to %s", jmeter_dist.name, dest) unzip(jmeter_dist.name, dest, 'apache-jmeter-%s' % self.version) os.remove(jmeter_dist.name) # set exec permissions os.chmod(os.path.join(dest, 'bin', 'jmeter'), 0o755) os.chmod(os.path.join(dest, 'bin', 'jmeter' + EXE_SUFFIX), 0o755) if not self.check_if_installed(): raise RuntimeError("Unable to run %s after installation!" % self.tool_name) for plugin in self.plugins: plugin_dist = tempfile.NamedTemporaryFile(suffix=".zip", delete=False, prefix=plugin) plugin_download_link = self.plugin_link.format(plugin=plugin) self.log.info("Downloading %s", plugin_download_link) downloader = http_request.FancyURLopener() with ProgressBarContext() as pbar: try: downloader.retrieve(plugin_download_link, plugin_dist.name, pbar.download_callback) except BaseException as exc: self.log.error("Error while downloading %s", plugin_download_link) raise exc self.log.info("Unzipping %s", plugin_dist.name) unzip(plugin_dist.name, dest) plugin_dist.close() os.remove(plugin_dist.name) cleaner = JarCleaner(self.log) cleaner.clean(os.path.join(dest, 'lib')) class JarCleaner(object): def __init__(self, parent_logger): self.log = parent_logger.getChild(self.__class__.__name__) @staticmethod def __extract_version(jar): version_str = jar.split('-')[-1] return version_str.replace('.jar', '') def clean(self, path): """ Remove old jars :param path: str """ self.log.debug("Removing old jars from %s", path) jarlib = namedtuple("jarlib", ("file_name", "lib_name", "version")) jars = [fname for fname in os.listdir(path) if '-' in fname and os.path.isfile(os.path.join(path, fname))] jar_libs = [jarlib(file_name=jar, lib_name='-'.join(jar.split('-')[:-1]), version=JarCleaner.__extract_version(jar)) for jar in jars] duplicated_libraries = set() for jar_lib_obj in jar_libs: similar_packages = [lib for lib in jar_libs if lib.lib_name == jar_lib_obj.lib_name] if len(similar_packages) > 1: right_version = max(similar_packages, key=lambda lib: LooseVersion(lib.version)) similar_packages.remove(right_version) duplicated_libraries.update(similar_packages) for old_lib in duplicated_libraries: os.remove(os.path.join(path, old_lib.file_name)) self.log.debug("Old jar removed %s", old_lib.file_name) class JMeterMirrorsManager(MirrorsManager): def __init__(self, parent_logger, jmeter_version, download_link): self.jmeter_version = str(jmeter_version) self.download_link = download_link super(JMeterMirrorsManager, self).__init__(JMeterExecutor.MIRRORS_SOURCE, parent_logger) def _parse_mirrors(self): links = [] if self.page_source is not None: self.log.debug('Parsing mirrors...') href_search_pattern = re.compile(r'<a href="apache\-jmeter\-([^"]*?)\.zip">') jmeter_versions = href_search_pattern.findall(self.page_source) if self.jmeter_version in jmeter_versions: archive_name = "apache-jmeter-{version}.zip".format(version=self.jmeter_version) links.append(self.base_link + archive_name) else: self.log.warning("Can't find link for JMeter %s, will use download-link", self.jmeter_version) default_link = self.download_link.format(version=self.jmeter_version) if default_link not in links: links.append(default_link) self.log.debug('Total mirrors: %d', len(links)) return links class Request(object): def __init__(self, config): self.config = config class HTTPRequest(Request): def __init__(self, url, label, method, headers, timeout, think_time, body, upload_files, config): super(HTTPRequest, self).__init__(config) self.url = url self.label = label self.method = method self.headers = headers self.timeout = timeout self.think_time = think_time self.body = body self.upload_files = upload_files def __repr__(self): return "HTTPRequest(url=%s, method=%s)" % (self.url, self.method) class IfBlock(Request): def __init__(self, condition, then_clause, else_clause, config): super(IfBlock, self).__init__(config) self.condition = condition self.then_clause = then_clause self.else_clause = else_clause def __repr__(self): then_clause = [repr(req) for req in self.then_clause] else_clause = [repr(req) for req in self.else_clause] return "IfBlock(condition=%s, then=%s, else=%s)" % (self.condition, then_clause, else_clause) class LoopBlock(Request): def __init__(self, loops, requests, config): super(LoopBlock, self).__init__(config) self.loops = loops self.requests = requests def __repr__(self): requests = [repr(req) for req in self.requests] return "LoopBlock(loops=%s, requests=%s)" % (self.loops, requests) class WhileBlock(Request): def __init__(self, condition, requests, config): super(WhileBlock, self).__init__(config) self.condition = condition self.requests = requests def __repr__(self): requests = [repr(req) for req in self.requests] return "WhileBlock(condition=%s, requests=%s)" % (self.condition, requests) class ForEachBlock(Request): def __init__(self, input_var, loop_var, requests, config): super(ForEachBlock, self).__init__(config) self.input_var = input_var self.loop_var = loop_var self.requests = requests def __repr__(self): requests = [repr(req) for req in self.requests] fmt = "ForEachBlock(input=%s, loop_var=%s, requests=%s)" return fmt % (self.input_var, self.loop_var, requests) class TransactionBlock(Request): def __init__(self, name, requests, config): super(TransactionBlock, self).__init__(config) self.name = name self.requests = requests def __repr__(self): requests = [repr(req) for req in self.requests] fmt = "TransactionBlock(name=%s, requests=%s)" return fmt % (self.name, requests) class IncludeScenarioBlock(Request): def __init__(self, scenario_name, config): super(IncludeScenarioBlock, self).__init__(config) self.scenario_name = scenario_name class RequestsParser(object): def __init__(self, engine): self.engine = engine def __parse_request(self, req): if 'if' in req: condition = req.get("if") # TODO: apply some checks to `condition`? then_clause = req.get("then", ValueError("'then' clause is mandatory for 'if' blocks")) then_requests = self.__parse_requests(then_clause) else_clause = req.get("else", []) else_requests = self.__parse_requests(else_clause) return IfBlock(condition, then_requests, else_requests, req) elif 'loop' in req: loops = req.get("loop") do_block = req.get("do", ValueError("'do' option is mandatory for 'loop' blocks")) do_requests = self.__parse_requests(do_block) return LoopBlock(loops, do_requests, req) elif 'while' in req: condition = req.get("while") do_block = req.get("do", ValueError("'do' option is mandatory for 'while' blocks")) do_requests = self.__parse_requests(do_block) return WhileBlock(condition, do_requests, req) elif 'foreach' in req: iteration_str = req.get("foreach") match = re.match(r'(.+) in (.+)', iteration_str) if not match: raise ValueError("'foreach' value should be in format '<elementName> in <collection>'") loop_var, input_var = match.groups() do_block = req.get("do", ValueError("'do' field is mandatory for 'foreach' blocks")) do_requests = self.__parse_requests(do_block) return ForEachBlock(input_var, loop_var, do_requests, req) elif 'transaction' in req: name = req.get('transaction') do_block = req.get('do', ValueError("'do' field is mandatory for transaction blocks")) do_requests = self.__parse_requests(do_block) return TransactionBlock(name, do_requests, req) elif 'include-scenario' in req: name = req.get('include-scenario') return IncludeScenarioBlock(name, req) else: url = req.get("url", ValueError("Option 'url' is mandatory for request")) label = req.get("label", url) method = req.get("method", "GET") headers = req.get("headers", {}) timeout = req.get("timeout", None) think_time = req.get("think-time", None) body = None bodyfile = req.get("body-file", None) if bodyfile: bodyfile_path = self.engine.find_file(bodyfile) with open(bodyfile_path) as fhd: body = fhd.read() body = req.get("body", body) upload_files = req.get("upload-files", []) for file_dict in upload_files: file_dict.get("param", ValueError("Items from upload-files must specify parameter name")) path = file_dict.get('path', ValueError("Items from upload-files must specify path to file")) mime = mimetypes.guess_type(path)[0] or "application/octet-stream" file_dict.get('mime-type', mime) return HTTPRequest(url, label, method, headers, timeout, think_time, body, upload_files, req) def __parse_requests(self, raw_requests): requests = [] for key in range(len(raw_requests)): # pylint: disable=consider-using-enumerate if not isinstance(raw_requests[key], dict): req = ensure_is_dict(raw_requests, key, "url") else: req = raw_requests[key] requests.append(self.__parse_request(req)) return requests def extract_requests(self, scenario): requests = scenario.get("requests", []) return list(self.__parse_requests(requests)) class RequestVisitor(object): def __init__(self): self.path = [] def visit(self, node): class_name = node.__class__.__name__.lower() visitor = getattr(self, 'visit_' + class_name, None) if visitor is not None: return visitor(node) raise ValueError("Visitor for class %s not found" % class_name) class ResourceFilesCollector(RequestVisitor): def __init__(self, executor): """ :param executor: JMeterExecutor """ super(ResourceFilesCollector, self).__init__() self.executor = executor def visit_httprequest(self, request): files = [] body_file = request.config.get('body-file') if body_file: files.append(body_file) return files def visit_ifblock(self, block): files = [] for request in block.then_clause: files.extend(self.visit(request)) for request in block.else_clause: files.extend(self.visit(request)) return files def visit_loopblock(self, block): files = [] for request in block.requests: files.extend(self.visit(request)) return files def visit_whileblock(self, block): files = [] for request in block.requests: files.extend(self.visit(request)) return files def visit_foreachblock(self, block): files = [] for request in block.requests: files.extend(self.visit(request)) return files def visit_transactionblock(self, block): files = [] for request in block.requests: files.extend(self.visit(request)) return files def visit_includescenarioblock(self, block): scenario_name = block.scenario_name if scenario_name in self.path: raise ValueError("Mutual recursion detected in include-scenario blocks (scenario %s)" % scenario_name) self.path.append(scenario_name) scenario = self.executor.get_scenario(name=block.scenario_name) return self.executor.res_files_from_scenario(scenario) class RequestCompiler(RequestVisitor): def __init__(self, jmx_builder): super(RequestCompiler, self).__init__() self.jmx_builder = jmx_builder def visit_httprequest(self, request): return self.jmx_builder.compile_http_request(request) def visit_ifblock(self, block): return self.jmx_builder.compile_if_block(block) def visit_loopblock(self, block): return self.jmx_builder.compile_loop_block(block) def visit_whileblock(self, block): return self.jmx_builder.compile_while_block(block) def visit_foreachblock(self, block): return self.jmx_builder.compile_foreach_block(block) def visit_transactionblock(self, block): return self.jmx_builder.compile_transaction_block(block) def visit_includescenarioblock(self, block): scenario_name = block.scenario_name if scenario_name in self.path: raise ValueError("Mutual recursion detected in include-scenario blocks (scenario %s)" % scenario_name) self.path.append(scenario_name) return self.jmx_builder.compile_include_scenario_block(block)
1
13,778
right URL is like in cmdrunner, using search.maven .org
Blazemeter-taurus
py
@@ -32,9 +32,9 @@ namespace OpenTelemetry.Exporter #if NETSTANDARD2_1 /// <summary> /// Gets or sets the target to which the exporter is going to send traces or metrics. - /// The valid syntax is described at https://github.com/grpc/grpc/blob/master/doc/naming.md. + /// The valid syntax is described at https://github.com/grpc/grpc/blob/master/doc/naming.md. The endpoint value should start with http or https. /// </summary> - public Uri Endpoint { get; set; } = new Uri("http://localhost:4317"); + public string Endpoint { get; set; } = "http://localhost:4317"; #else /// <summary> /// Gets or sets the target to which the exporter is going to send traces or metrics.
1
// <copyright file="OtlpExporterOptions.cs" company="OpenTelemetry Authors"> // Copyright The OpenTelemetry Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> using System; using System.Collections.Generic; using System.Diagnostics; using Grpc.Core; #if NETSTANDARD2_1 using Grpc.Net.Client; #endif namespace OpenTelemetry.Exporter { /// <summary> /// Configuration options for the OpenTelemetry Protocol (OTLP) exporter. /// </summary> public class OtlpExporterOptions { #if NETSTANDARD2_1 /// <summary> /// Gets or sets the target to which the exporter is going to send traces or metrics. /// The valid syntax is described at https://github.com/grpc/grpc/blob/master/doc/naming.md. /// </summary> public Uri Endpoint { get; set; } = new Uri("http://localhost:4317"); #else /// <summary> /// Gets or sets the target to which the exporter is going to send traces or metrics. /// The valid syntax is described at https://github.com/grpc/grpc/blob/master/doc/naming.md. /// </summary> public string Endpoint { get; set; } = "localhost:4317"; #endif #if NETSTANDARD2_1 /// <summary> /// Gets or sets the gRPC channel options. /// </summary> public GrpcChannelOptions GrpcChannelOptions { get; set; } #else /// <summary> /// Gets or sets the client-side channel credentials. Used for creation of a secure channel. /// The default is "insecure". See detais at https://grpc.io/docs/guides/auth/#credential-types. /// </summary> public ChannelCredentials Credentials { get; set; } = ChannelCredentials.Insecure; /// <summary> /// Gets or sets the gRPC channel options. /// </summary> public IEnumerable<ChannelOption> ChannelOptions { get; set; } #endif /// <summary> /// Gets or sets optional headers for the connection. Refer to the <a href="https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/exporter.md#specifying-headers-via-environment-variables"> /// specification</a> for information on the expected format for Headers. /// </summary> public string Headers { get; set; } /// <summary> /// Gets or sets the max waiting time (in milliseconds) for the backend to process each span batch. The default value is 10000. /// </summary> public int TimeoutMilliseconds { get; set; } = 10000; /// <summary> /// Gets or sets the export processor type to be used with the OpenTelemetry Protocol Exporter. /// </summary> public ExportProcessorType ExportProcessorType { get; set; } = ExportProcessorType.Batch; /// <summary> /// Gets or sets the BatchExportProcessor options. Ignored unless ExportProcessorType is Batch. /// </summary> public BatchExportProcessorOptions<Activity> BatchExportProcessorOptions { get; set; } = new BatchExportProcessorOptions<Activity>(); } }
1
19,140
The link to valid syntax is not really applicable for NET2_1, right?
open-telemetry-opentelemetry-dotnet
.cs
@@ -16,6 +16,13 @@ // PubSub. Use OpenTopic to construct a *pubsub.Topic, and/or OpenSubscription // to construct a *pubsub.Subscription. // +// Escaping +// +// Go CDK supports all UTF-8 strings; some strings are escaped (during writes) +// and unescaped (during reads) to ensure compatibility with the provider: +// - Metadata keys: No escaping required. +// - Metadata values: No escaping required. +// // As // // gcspubsub exposes the following types for As:
1
// Copyright 2018 The Go Cloud Development Kit Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package gcppubsub provides a pubsub implementation that uses GCP // PubSub. Use OpenTopic to construct a *pubsub.Topic, and/or OpenSubscription // to construct a *pubsub.Subscription. // // As // // gcspubsub exposes the following types for As: // - Topic: *raw.PublisherClient // - Subscription: *raw.SubscriberClient // - Message: *pb.PubsubMessage // - Error: *google.golang.org/grpc/status.Status package gcppubsub // import "gocloud.dev/pubsub/gcppubsub" import ( "context" "fmt" raw "cloud.google.com/go/pubsub/apiv1" "gocloud.dev/gcerrors" "gocloud.dev/gcp" "gocloud.dev/internal/gcerr" "gocloud.dev/internal/useragent" "gocloud.dev/pubsub" "gocloud.dev/pubsub/driver" "google.golang.org/api/option" pb "google.golang.org/genproto/googleapis/pubsub/v1" "google.golang.org/grpc" "google.golang.org/grpc/credentials" "google.golang.org/grpc/credentials/oauth" "google.golang.org/grpc/status" ) const endPoint = "pubsub.googleapis.com:443" type topic struct { path string client *raw.PublisherClient } // Dial opens a gRPC connection to the GCP Pub Sub API. // // The second return value is a function that can be called to clean up // the connection opened by Dial. func Dial(ctx context.Context, ts gcp.TokenSource) (*grpc.ClientConn, func(), error) { conn, err := grpc.DialContext(ctx, endPoint, grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, "")), grpc.WithPerRPCCredentials(oauth.TokenSource{TokenSource: ts}), useragent.GRPCDialOption("pubsub"), ) if err != nil { return nil, nil, err } return conn, func() { conn.Close() }, nil } // PublisherClient returns a *raw.PublisherClient that can be used in OpenTopic. func PublisherClient(ctx context.Context, conn *grpc.ClientConn) (*raw.PublisherClient, error) { return raw.NewPublisherClient(ctx, option.WithGRPCConn(conn)) } // SubscriberClient returns a *raw.SubscriberClient that can be used in OpenSubscription. func SubscriberClient(ctx context.Context, conn *grpc.ClientConn) (*raw.SubscriberClient, error) { return raw.NewSubscriberClient(ctx, option.WithGRPCConn(conn)) } // TopicOptions will contain configuration for topics. type TopicOptions struct{} // OpenTopic returns a *pubsub.Topic backed by an existing GCP PubSub topic // topicName in the given projectID. See the package documentation for an // example. func OpenTopic(ctx context.Context, client *raw.PublisherClient, proj gcp.ProjectID, topicName string, opts *TopicOptions) *pubsub.Topic { dt := openTopic(ctx, client, proj, topicName) return pubsub.NewTopic(dt) } // openTopic returns the driver for OpenTopic. This function exists so the test // harness can get the driver interface implementation if it needs to. func openTopic(ctx context.Context, client *raw.PublisherClient, proj gcp.ProjectID, topicName string) driver.Topic { path := fmt.Sprintf("projects/%s/topics/%s", proj, topicName) return &topic{path, client} } // SendBatch implements driver.Topic.SendBatch. func (t *topic) SendBatch(ctx context.Context, dms []*driver.Message) error { // The PubSub service limits the number of messages in a single Publish RPC. const maxPublishCount = 1000 for len(dms) > 0 { n := len(dms) if n > maxPublishCount { n = maxPublishCount } batch := dms[:n] dms = dms[n:] var ms []*pb.PubsubMessage for _, dm := range batch { ms = append(ms, &pb.PubsubMessage{ Data: dm.Body, Attributes: dm.Metadata, }) } req := &pb.PublishRequest{ Topic: t.path, Messages: ms, } if _, err := t.client.Publish(ctx, req); err != nil { return err } } return nil } // IsRetryable implements driver.Topic.IsRetryable. func (t *topic) IsRetryable(error) bool { // The client handles retries. return false } // As implements driver.Topic.As. func (t *topic) As(i interface{}) bool { c, ok := i.(**raw.PublisherClient) if !ok { return false } *c = t.client return true } // ErrorAs implements driver.Topic.ErrorAs func (*topic) ErrorAs(err error, target interface{}) bool { return errorAs(err, target) } func errorAs(err error, target interface{}) bool { s, ok := status.FromError(err) if !ok { return false } p, ok := target.(**status.Status) if !ok { return false } *p = s return true } func (*topic) ErrorCode(err error) gcerrors.ErrorCode { return gcerr.GRPCCode(err) } type subscription struct { client *raw.SubscriberClient path string } // SubscriptionOptions will contain configuration for subscriptions. type SubscriptionOptions struct{} // OpenSubscription returns a *pubsub.Subscription backed by an existing GCP // PubSub subscription subscriptionName in the given projectID. See the package // documentation for an example. func OpenSubscription(ctx context.Context, client *raw.SubscriberClient, proj gcp.ProjectID, subscriptionName string, opts *SubscriptionOptions) *pubsub.Subscription { ds := openSubscription(ctx, client, proj, subscriptionName) return pubsub.NewSubscription(ds, nil) } // openSubscription returns a driver.Subscription. func openSubscription(ctx context.Context, client *raw.SubscriberClient, projectID gcp.ProjectID, subscriptionName string) driver.Subscription { path := fmt.Sprintf("projects/%s/subscriptions/%s", projectID, subscriptionName) return &subscription{client, path} } // ReceiveBatch implements driver.Subscription.ReceiveBatch. func (s *subscription) ReceiveBatch(ctx context.Context, maxMessages int) ([]*driver.Message, error) { req := &pb.PullRequest{ Subscription: s.path, ReturnImmediately: false, MaxMessages: int32(maxMessages), } resp, err := s.client.Pull(ctx, req) if err != nil { return nil, err } var ms []*driver.Message for _, rm := range resp.ReceivedMessages { rmm := rm.Message m := &driver.Message{ Body: rmm.Data, Metadata: rmm.Attributes, AckID: rm.AckId, AsFunc: messageAsFunc(rmm), } ms = append(ms, m) } return ms, nil } func messageAsFunc(pm *pb.PubsubMessage) func(interface{}) bool { return func(i interface{}) bool { p, ok := i.(**pb.PubsubMessage) if !ok { return false } *p = pm return true } } // SendAcks implements driver.Subscription.SendAcks. func (s *subscription) SendAcks(ctx context.Context, ids []driver.AckID) error { var ids2 []string for _, id := range ids { ids2 = append(ids2, id.(string)) } return s.client.Acknowledge(ctx, &pb.AcknowledgeRequest{ Subscription: s.path, AckIds: ids2, }) } // IsRetryable implements driver.Subscription.IsRetryable. func (s *subscription) IsRetryable(error) bool { // The client handles retries. return false } // As implements driver.Subscription.As. func (s *subscription) As(i interface{}) bool { c, ok := i.(**raw.SubscriberClient) if !ok { return false } *c = s.client return true } // ErrorAs implements driver.Subscription.ErrorAs func (*subscription) ErrorAs(err error, target interface{}) bool { return errorAs(err, target) } func (*subscription) ErrorCode(err error) gcerrors.ErrorCode { return gcerr.GRPCCode(err) }
1
14,277
Shouldn't it be more specific, like "gcppubsub supports all UTF-8 strings"?
google-go-cloud
go
@@ -59,14 +59,14 @@ public class CdcrReplicationHandlerTest extends BaseCdcrDistributedZkTest { } /** - * Test the scenario where the slave is killed from the start. The replication + * Test the scenario where the secondary is killed from the start. The replication * strategy should fetch all the missing tlog files from the leader. */ @Test @ShardsFixed(num = 2) public void testFullReplication() throws Exception { - List<CloudJettyRunner> slaves = this.getShardToSlaveJetty(SOURCE_COLLECTION, SHARD1); - slaves.get(0).jetty.stop(); + List<CloudJettyRunner> secondaries = this.getShardToSecondaryJetty(SOURCE_COLLECTION, SHARD1); + secondaries.get(0).jetty.stop(); for (int i = 0; i < 10; i++) { List<SolrInputDocument> docs = new ArrayList<>();
1
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.solr.cloud.cdcr; import java.io.File; import java.io.IOException; import java.lang.invoke.MethodHandles; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.apache.lucene.util.LuceneTestCase.Nightly; import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.impl.CloudSolrClient; import org.apache.solr.common.SolrInputDocument; import org.apache.solr.common.util.SolrNamedThreadFactory; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class is testing the cdcr extension to the {@link org.apache.solr.handler.ReplicationHandler} and * {@link org.apache.solr.handler.IndexFetcher}. */ @Nightly public class CdcrReplicationHandlerTest extends BaseCdcrDistributedZkTest { private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); @Override public void distribSetUp() throws Exception { schemaString = "schema15.xml"; // we need a string id createTargetCollection = false; // we do not need the target cluster shardCount = 1; // we need only one shard // we need a persistent directory, otherwise the UpdateHandler will erase existing tlog files after restarting a node System.setProperty("solr.directoryFactory", "solr.StandardDirectoryFactory"); super.distribSetUp(); } /** * Test the scenario where the slave is killed from the start. The replication * strategy should fetch all the missing tlog files from the leader. */ @Test @ShardsFixed(num = 2) public void testFullReplication() throws Exception { List<CloudJettyRunner> slaves = this.getShardToSlaveJetty(SOURCE_COLLECTION, SHARD1); slaves.get(0).jetty.stop(); for (int i = 0; i < 10; i++) { List<SolrInputDocument> docs = new ArrayList<>(); for (int j = i * 10; j < (i * 10) + 10; j++) { docs.add(getDoc(id, Integer.toString(j))); } index(SOURCE_COLLECTION, docs); } assertNumDocs(100, SOURCE_COLLECTION); // Restart the slave node to trigger Replication strategy this.restartServer(slaves.get(0)); this.assertUpdateLogsEquals(SOURCE_COLLECTION, 10); } /** * Test the scenario where the slave is killed before receiving all the documents. The replication * strategy should fetch all the missing tlog files from the leader. */ @Test @ShardsFixed(num = 2) public void testPartialReplication() throws Exception { for (int i = 0; i < 5; i++) { List<SolrInputDocument> docs = new ArrayList<>(); for (int j = i * 20; j < (i * 20) + 20; j++) { docs.add(getDoc(id, Integer.toString(j))); } index(SOURCE_COLLECTION, docs); } List<CloudJettyRunner> slaves = this.getShardToSlaveJetty(SOURCE_COLLECTION, SHARD1); slaves.get(0).jetty.stop(); for (int i = 5; i < 10; i++) { List<SolrInputDocument> docs = new ArrayList<>(); for (int j = i * 20; j < (i * 20) + 20; j++) { docs.add(getDoc(id, Integer.toString(j))); } index(SOURCE_COLLECTION, docs); } assertNumDocs(200, SOURCE_COLLECTION); // Restart the slave node to trigger Replication strategy this.restartServer(slaves.get(0)); // at this stage, the slave should have replicated the 5 missing tlog files this.assertUpdateLogsEquals(SOURCE_COLLECTION, 10); } /** * Test the scenario where the slave is killed before receiving a commit. This creates a truncated tlog * file on the slave node. The replication strategy should detect this truncated file, and fetch the * non-truncated file from the leader. */ @Test @ShardsFixed(num = 2) public void testPartialReplicationWithTruncatedTlog() throws Exception { CloudSolrClient client = createCloudClient(SOURCE_COLLECTION); List<CloudJettyRunner> slaves = this.getShardToSlaveJetty(SOURCE_COLLECTION, SHARD1); try { for (int i = 0; i < 10; i++) { for (int j = i * 20; j < (i * 20) + 20; j++) { client.add(getDoc(id, Integer.toString(j))); // Stop the slave in the middle of a batch to create a truncated tlog on the slave if (j == 45) { slaves.get(0).jetty.stop(); } } commit(SOURCE_COLLECTION); } } finally { client.close(); } assertNumDocs(200, SOURCE_COLLECTION); // Restart the slave node to trigger Replication recovery this.restartServer(slaves.get(0)); // at this stage, the slave should have replicated the 5 missing tlog files this.assertUpdateLogsEquals(SOURCE_COLLECTION, 10); } /** * Test the scenario where the slave first recovered with a PeerSync strategy, then with a Replication strategy. * The PeerSync strategy will generate a single tlog file for all the missing updates on the slave node. * If a Replication strategy occurs at a later stage, it should remove this tlog file generated by PeerSync * and fetch the corresponding tlog files from the leader. */ @Test @ShardsFixed(num = 2) public void testPartialReplicationAfterPeerSync() throws Exception { for (int i = 0; i < 5; i++) { List<SolrInputDocument> docs = new ArrayList<>(); for (int j = i * 10; j < (i * 10) + 10; j++) { docs.add(getDoc(id, Integer.toString(j))); } index(SOURCE_COLLECTION, docs); } List<CloudJettyRunner> slaves = this.getShardToSlaveJetty(SOURCE_COLLECTION, SHARD1); slaves.get(0).jetty.stop(); for (int i = 5; i < 10; i++) { List<SolrInputDocument> docs = new ArrayList<>(); for (int j = i * 10; j < (i * 10) + 10; j++) { docs.add(getDoc(id, Integer.toString(j))); } index(SOURCE_COLLECTION, docs); } assertNumDocs(100, SOURCE_COLLECTION); // Restart the slave node to trigger PeerSync recovery // (the update windows between leader and slave is small enough) this.restartServer(slaves.get(0)); slaves.get(0).jetty.stop(); for (int i = 10; i < 15; i++) { List<SolrInputDocument> docs = new ArrayList<>(); for (int j = i * 20; j < (i * 20) + 20; j++) { docs.add(getDoc(id, Integer.toString(j))); } index(SOURCE_COLLECTION, docs); } // restart the slave node to trigger Replication recovery this.restartServer(slaves.get(0)); // at this stage, the slave should have replicated the 5 missing tlog files this.assertUpdateLogsEquals(SOURCE_COLLECTION, 15); } /** * Test the scenario where the slave is killed while the leader is still receiving updates. * The slave should buffer updates while in recovery, then replay them at the end of the recovery. * If updates were properly buffered and replayed, then the slave should have the same number of documents * than the leader. This checks if cdcr tlog replication interferes with buffered updates - SOLR-8263. */ @Test @ShardsFixed(num = 2) public void testReplicationWithBufferedUpdates() throws Exception { List<CloudJettyRunner> slaves = this.getShardToSlaveJetty(SOURCE_COLLECTION, SHARD1); AtomicInteger numDocs = new AtomicInteger(0); ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(new SolrNamedThreadFactory("cdcr-test-update-scheduler")); executor.scheduleWithFixedDelay(new UpdateThread(numDocs), 10, 10, TimeUnit.MILLISECONDS); // Restart the slave node to trigger Replication strategy this.restartServer(slaves.get(0)); // shutdown the update thread and wait for its completion executor.shutdown(); executor.awaitTermination(500, TimeUnit.MILLISECONDS); // check that we have the expected number of documents in the cluster assertNumDocs(numDocs.get(), SOURCE_COLLECTION); // check that we have the expected number of documents on the slave assertNumDocs(numDocs.get(), slaves.get(0)); } private void assertNumDocs(int expectedNumDocs, CloudJettyRunner jetty) throws InterruptedException, IOException, SolrServerException { SolrClient client = createNewSolrServer(jetty.url); try { int cnt = 30; // timeout after 15 seconds AssertionError lastAssertionError = null; while (cnt > 0) { try { assertEquals(expectedNumDocs, client.query(new SolrQuery("*:*")).getResults().getNumFound()); return; } catch (AssertionError e) { lastAssertionError = e; cnt--; Thread.sleep(500); } } throw new AssertionError("Timeout while trying to assert number of documents @ " + jetty.url, lastAssertionError); } finally { client.close(); } } private class UpdateThread implements Runnable { private AtomicInteger numDocs; private UpdateThread(AtomicInteger numDocs) { this.numDocs = numDocs; } @Override public void run() { try { List<SolrInputDocument> docs = new ArrayList<>(); for (int j = numDocs.get(); j < (numDocs.get() + 10); j++) { docs.add(getDoc(id, Integer.toString(j))); } index(SOURCE_COLLECTION, docs); numDocs.getAndAdd(10); if (log.isInfoEnabled()) { log.info("Sent batch of {} updates - numDocs:{}", docs.size(), numDocs); } } catch (Exception e) { throw new RuntimeException(e); } } } private List<CloudJettyRunner> getShardToSlaveJetty(String collection, String shard) { List<CloudJettyRunner> jetties = new ArrayList<>(shardToJetty.get(collection).get(shard)); CloudJettyRunner leader = shardToLeaderJetty.get(collection).get(shard); jetties.remove(leader); return jetties; } /** * Asserts that the update logs are in sync between the leader and slave. The leader and the slaves * must have identical tlog files. */ protected void assertUpdateLogsEquals(String collection, int numberOfTLogs) throws Exception { CollectionInfo info = collectInfo(collection); Map<String, List<CollectionInfo.CoreInfo>> shardToCoresMap = info.getShardToCoresMap(); for (String shard : shardToCoresMap.keySet()) { Map<Long, Long> leaderFilesMeta = this.getFilesMeta(info.getLeader(shard).ulogDir); Map<Long, Long> slaveFilesMeta = this.getFilesMeta(info.getReplicas(shard).get(0).ulogDir); assertEquals("Incorrect number of tlog files on the leader", numberOfTLogs, leaderFilesMeta.size()); assertEquals("Incorrect number of tlog files on the slave", numberOfTLogs, slaveFilesMeta.size()); for (Long leaderFileVersion : leaderFilesMeta.keySet()) { assertTrue("Slave is missing a tlog for version " + leaderFileVersion, slaveFilesMeta.containsKey(leaderFileVersion)); assertEquals("Slave's tlog file size differs for version " + leaderFileVersion, leaderFilesMeta.get(leaderFileVersion), slaveFilesMeta.get(leaderFileVersion)); } } } private Map<Long, Long> getFilesMeta(String dir) { File file = new File(dir); if (!file.isDirectory()) { assertTrue("Path to tlog " + dir + " does not exists or it's not a directory.", false); } Map<Long, Long> filesMeta = new HashMap<>(); for (File tlogFile : file.listFiles()) { filesMeta.put(Math.abs(Long.parseLong(tlogFile.getName().substring(tlogFile.getName().lastIndexOf('.') + 1))), tlogFile.length()); } return filesMeta; } }
1
36,012
Everything in this class is SolrCloud-related, not legacy replication
apache-lucene-solr
java
@@ -1122,15 +1122,8 @@ drbbdup_prepare_redirect(dr_mcontext_t *mcontext, drbbdup_manager_t *manager, { /* Restore flags and scratch reg to their original app values. */ if (!manager->are_flags_dead) { - reg_t val; - uint sahf; - reg_t newval = mcontext->xflags; - val = (reg_t)drbbdup_get_tls_raw_slot_val(DRBBDUP_FLAG_REG_SLOT); - sahf = (val & 0xff00) >> 8; - newval &= ~(EFLAGS_ARITH); - newval |= sahf; - if (TEST(1, val)) /* seto */ - newval |= EFLAGS_OF; + reg_t val = (reg_t)drbbdup_get_tls_raw_slot_val(DRBBDUP_FLAG_REG_SLOT); + reg_t newval = dr_merge_arith_flags(mcontext->xflags, val); mcontext->xflags = newval; } if (!manager->is_scratch_reg_dead) {
1
/* ********************************************************** * Copyright (c) 2013-2020 Google, Inc. All rights reserved. * **********************************************************/ /* * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of Google, Inc. nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL GOOGLE, INC. OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. */ #include "dr_defines.h" #include "dr_api.h" #include "drmgr.h" #include "drreg.h" #include "hashtable.h" #include "drbbdup.h" #include <string.h> #include <stdint.h> #include "../ext_utils.h" #ifdef DEBUG # define ASSERT(x, msg) DR_ASSERT_MSG(x, msg) # define LOG(dc, mask, level, ...) dr_log(dc, mask, level, __VA_ARGS__) #else # define ASSERT(x, msg) # define LOG(dc, mask, level, ...) #endif /* DynamoRIO Basic Block Duplication Extension: a code builder that * duplicates code of basic blocks and dispatches control according to runtime * conditions so that different instrumentation may be efficiently executed. */ /* TODO i#4134: ARM not yet supported. */ #ifndef X86 # error ARM is not yet supported #endif #define HASH_BIT_TABLE 13 /* Definitions for drbbdup's hit-table that drives dynamic case handling. * Essentially, a hash-table tracks which BBs are frequently encountering * new unhandled cases. */ #define TABLE_SIZE 65536 /* Must be a power of 2 to perform efficient mod. */ typedef enum { DRBBDUP_ENCODING_SLOT = 0, DRBBDUP_XAX_REG_SLOT = 1, DRBBDUP_FLAG_REG_SLOT = 2, DRBBDUP_HIT_TABLE_SLOT = 3, DRBBDUP_SLOT_COUNT = 4, /* Need to update if more slots are added. */ } drbbdup_thread_slots_t; /* A scratch register used by drbbdup's dispatcher. */ #define DRBBDUP_SCRATCH_REG DR_REG_XAX /* Special index values are used to help guide case selection. */ #define DRBBDUP_DEFAULT_INDEX -1 #define DRBBDUP_IGNORE_INDEX -2 /* Contains information of a case that maps to a copy of a bb. */ typedef struct { uintptr_t encoding; /* The encoding specific to the case. */ bool is_defined; /* Denotes whether the case is defined. */ } drbbdup_case_t; /* Contains per bb information required for managing bb copies. */ typedef struct { int ref_counter; bool enable_dup; /* Denotes whether to duplicate blocks. */ bool enable_dynamic_handling; /* Denotes whether to dynamically generate cases. */ bool are_flags_dead; /* Denotes whether flags are dead at the start of a bb. */ bool is_scratch_reg_dead; /* Denotes whether DRBBDUP_SCRATCH_REG is dead at start. */ bool is_gen; /* Denotes whether a new bb copy is dynamically being generated. */ drbbdup_case_t default_case; drbbdup_case_t *cases; /* Is NULL if enable_dup is not set. */ } drbbdup_manager_t; /* Label types. */ typedef enum { DRBBDUP_LABEL_START = 78, /* Denotes the start of a bb copy. */ DRBBDUP_LABEL_EXIT = 79, /* Denotes the end of all bb copies. */ } drbbdup_label_t; typedef struct { int case_index; /* Used to keep track of the current case during insertion. */ void *orig_analysis_data; /* Analysis data accessible for all cases. */ void *default_analysis_data; /* Analysis data specific to default case. */ void **case_analysis_data; /* Analysis data specific to cases. */ uint16_t hit_counts[TABLE_SIZE]; /* Keeps track of hit-counts of unhandled cases. */ instr_t *first_instr; /* The first instr of the bb copy being considered. */ instr_t *last_instr; /* The last instr of the bb copy being considered. */ } drbbdup_per_thread; static uint ref_count = 0; /* Instance count of drbbdup. */ static hashtable_t manager_table; /* Maps bbs with book-keeping data. */ static drbbdup_options_t opts; static void *rw_lock = NULL; /* An outlined code cache (storing a clean call) for dynamically generating a case. */ static app_pc new_case_cache_pc = NULL; static int tls_idx = -1; /* For thread local storage info. */ static reg_id_t tls_raw_reg; static uint tls_raw_base; static uintptr_t * drbbdup_set_tls_raw_slot_addr(drbbdup_thread_slots_t slot_idx) { ASSERT(0 <= slot_idx && slot_idx < DRBBDUP_SLOT_COUNT, "out-of-bounds slot index"); byte *base = dr_get_dr_segment_base(tls_raw_reg); return (uintptr_t *)(base + tls_raw_base); } static void drbbdup_set_tls_raw_slot_val(drbbdup_thread_slots_t slot_idx, uintptr_t val) { uintptr_t *addr = drbbdup_set_tls_raw_slot_addr(slot_idx); *addr = val; } static uintptr_t drbbdup_get_tls_raw_slot_val(drbbdup_thread_slots_t slot_idx) { uintptr_t *addr = drbbdup_set_tls_raw_slot_addr(slot_idx); return *addr; } static opnd_t drbbdup_get_tls_raw_slot_opnd(drbbdup_thread_slots_t slot_idx) { return opnd_create_far_base_disp_ex(tls_raw_reg, REG_NULL, REG_NULL, 1, tls_raw_base + (slot_idx * (sizeof(void *))), OPSZ_PTR, false, true, false); } drbbdup_status_t drbbdup_set_encoding(uintptr_t encoding) { drbbdup_set_tls_raw_slot_val(DRBBDUP_ENCODING_SLOT, encoding); return DRBBDUP_SUCCESS; } opnd_t drbbdup_get_encoding_opnd() { return drbbdup_get_tls_raw_slot_opnd(DRBBDUP_ENCODING_SLOT); } static void drbbdup_spill_register(void *drcontext, instrlist_t *ilist, instr_t *where, int slot_idx, reg_id_t reg_id) { opnd_t slot_opnd = drbbdup_get_tls_raw_slot_opnd(slot_idx); instr_t *instr = INSTR_CREATE_mov_st(drcontext, slot_opnd, opnd_create_reg(reg_id)); instrlist_meta_preinsert(ilist, where, instr); } static void drbbdup_restore_register(void *drcontext, instrlist_t *ilist, instr_t *where, int slot_idx, reg_id_t reg_id) { opnd_t slot_opnd = drbbdup_get_tls_raw_slot_opnd(slot_idx); instr_t *instr = INSTR_CREATE_mov_ld(drcontext, opnd_create_reg(reg_id), slot_opnd); instrlist_meta_preinsert(ilist, where, instr); } /* Returns whether or not instr is a special instruction that must be the last instr in a * bb in accordance to DR rules. */ static bool drbbdup_is_special_instr(instr_t *instr) { return instr_is_syscall(instr) || instr_is_cti(instr) || instr_is_ubr(instr) || instr_is_interrupt(instr); } /**************************************************************************** * DUPlICATION PHASE * * This phase is responsible for performing the actual duplications of bbs. */ /* Returns the number of bb duplications excluding the default case. */ static uint drbbdup_count(drbbdup_manager_t *manager) { ASSERT(manager != NULL, "should not be NULL"); uint count = 0; int i; for (i = 0; i < opts.dup_limit; i++) { /* If case is defined, increment the counter. */ if (manager->cases[i].is_defined) count++; } return count; } /* Clone from original instrlist, but place duplication in bb. */ static void drbbdup_add_copy(void *drcontext, instrlist_t *bb, instrlist_t *orig_bb) { if (instrlist_first(orig_bb) != NULL) { instrlist_t *dup = instrlist_clone(drcontext, orig_bb); instr_t *start = instrlist_first(dup); instrlist_prepend(bb, start); /* Empty list and destroy. Do not use clear as instrs are needed. */ instrlist_init(dup); instrlist_destroy(drcontext, dup); } } /* Creates a manager, which contains book-keeping data for a fragment. */ static drbbdup_manager_t * drbbdup_create_manager(void *drcontext, void *tag, instrlist_t *bb) { drbbdup_manager_t *manager = dr_global_alloc(sizeof(drbbdup_manager_t)); memset(manager, 0, sizeof(drbbdup_manager_t)); manager->cases = NULL; ASSERT(opts.dup_limit > 0, "dup limit should be greater than zero"); manager->cases = dr_global_alloc(sizeof(drbbdup_case_t) * opts.dup_limit); memset(manager->cases, 0, sizeof(drbbdup_case_t) * opts.dup_limit); manager->enable_dup = true; manager->enable_dynamic_handling = true; manager->ref_counter = 1; manager->is_gen = false; ASSERT(opts.set_up_bb_dups != NULL, "set up call-back cannot be NULL"); manager->default_case.encoding = opts.set_up_bb_dups(manager, drcontext, tag, bb, &manager->enable_dup, &manager->enable_dynamic_handling, opts.user_data); /* XXX i#3778: To remove once we support specific fragment deletion. */ DR_ASSERT_MSG(!manager->enable_dynamic_handling, "dynamic case generation is not yet supported"); /* Check whether user wants copies for this particular bb. */ if (!manager->enable_dup && manager->cases != NULL) { /* Multiple cases not wanted. Destroy cases. */ dr_global_free(manager->cases, sizeof(drbbdup_case_t) * opts.dup_limit); manager->cases = NULL; } manager->default_case.is_defined = true; return manager; } /* Transforms the bb to contain additional copies (within the same fragment). */ static void drbbdup_set_up_copies(void *drcontext, instrlist_t *bb, drbbdup_manager_t *manager) { ASSERT(manager != NULL, "manager should not be NULL"); ASSERT(manager->enable_dup, "bb duplication should be enabled"); ASSERT(manager->cases != NULL, "cases should not be NULL"); /* Example: Lets say we have the following bb: * mov ebx ecx * mov esi eax * ret * * We require 2 cases, we need to construct the bb as follows: * LABEL 1 * mov ebx ecx * mov esi eax * jmp EXIT LABEL * * LABEL 2 * mov ebx ecx * mov esi eax * EXIT LABEL * ret * * The inclusion of the dispatcher is left for the instrumentation stage. * * Note, we add jmp instructions here and DR will set them to meta automatically. */ /* We create a duplication here to keep track of original bb. */ instrlist_t *original = instrlist_clone(drcontext, bb); /* If the last instruction is a system call/cti, we remove it from the original. * This is done so that we do not copy such instructions and abide by DR rules. */ instr_t *last = instrlist_last_app(original); if (drbbdup_is_special_instr(last)) { instrlist_remove(original, last); instr_destroy(drcontext, last); } /* Tell drreg to ignore control flow as it is ensured that all registers * are live at the start of bb copies. */ drreg_set_bb_properties(drcontext, DRREG_IGNORE_CONTROL_FLOW); /* Restoration at the end of the block is not done automatically * by drreg but is managed by drbbdup. Different cases could * have different registers spilled and therefore restoration is * specific to cases. During the insert stage, drbbdup restores * all unreserved registers upon exit of a bb copy by calling * drreg_restore_all(). */ drreg_set_bb_properties(drcontext, DRREG_USER_RESTORES_AT_BB_END); /* Create an EXIT label. */ instr_t *exit_label = INSTR_CREATE_label(drcontext); opnd_t exit_label_opnd = opnd_create_instr(exit_label); instr_set_note(exit_label, (void *)(intptr_t)DRBBDUP_LABEL_EXIT); /* Prepend a START label. */ instr_t *label = INSTR_CREATE_label(drcontext); instr_set_note(label, (void *)(intptr_t)DRBBDUP_LABEL_START); instrlist_meta_preinsert(bb, instrlist_first(bb), label); /* Perform duplication. */ int num_copies = (int)drbbdup_count(manager); ASSERT(num_copies >= 1, "there must be at least one copy"); int start = num_copies - 1; int i; for (i = start; i >= 0; i--) { /* Prepend a jmp targeting the EXIT label. */ instr_t *jmp_exit = INSTR_CREATE_jmp(drcontext, exit_label_opnd); instrlist_preinsert(bb, instrlist_first(bb), jmp_exit); /* Prepend a copy. */ drbbdup_add_copy(drcontext, bb, original); /* Prepend a START label. */ label = INSTR_CREATE_label(drcontext); instr_set_note(label, (void *)(intptr_t)DRBBDUP_LABEL_START); instrlist_meta_preinsert(bb, instrlist_first(bb), label); } /* Delete original. We are done from making further copies. */ instrlist_clear_and_destroy(drcontext, original); /* Add the EXIT label to the last copy of the bb. * If there is a syscall, place the exit label prior, leaving the syscall * last. Again, this is to abide by DR rules. */ last = instrlist_last(bb); if (drbbdup_is_special_instr(last)) instrlist_meta_preinsert(bb, last, exit_label); else instrlist_meta_postinsert(bb, last, exit_label); } static dr_emit_flags_t drbbdup_duplicate_phase(void *drcontext, void *tag, instrlist_t *bb, bool for_trace, bool translating, OUT void **user_data) { if (translating) return DR_EMIT_DEFAULT; app_pc pc = instr_get_app_pc(instrlist_first_app(bb)); ASSERT(pc != NULL, "pc cannot be NULL"); dr_rwlock_write_lock(rw_lock); drbbdup_manager_t *manager = (drbbdup_manager_t *)hashtable_lookup(&manager_table, pc); /* A manager is created if there does not exit one that does not already * book-keeping this bb. */ if (manager == NULL) { manager = drbbdup_create_manager(drcontext, tag, bb); ASSERT(manager != NULL, "created manager cannot be NULL"); hashtable_add(&manager_table, pc, manager); } else { /* A manager is already book-keeping this bb. Two scenarios are considered: * 1) A new case is registered and re-instrumentation is * triggered via flushing. * 2) The bb has been deleted by DR due to other reasons (e.g. memory) * and re-instrumented again. * * If we are handling a new case, there is no need to increment ref. */ if (manager->is_gen) manager->is_gen = false; else manager->ref_counter++; } if (manager->enable_dup) { /* Add the copies. */ drbbdup_set_up_copies(drcontext, bb, manager); } /* XXX i#4134: statistics -- add the following stat increments here: * 1) avg bb size * 2) bb instrum count * 3) dups enabled */ dr_rwlock_write_unlock(rw_lock); return DR_EMIT_STORE_TRANSLATIONS; } /**************************************************************************** * ANALYSIS PHASE */ /* Determines whether or not we reached a special label recognisable by drbbdup. */ static bool drbbdup_is_at_label(instr_t *check_instr, drbbdup_label_t label) { if (check_instr == NULL) return false; /* If it is not a meta label just skip! */ if (!(instr_is_label(check_instr) && instr_is_meta(check_instr))) return false; /* Notes are inspected to check whether the label is relevant to drbbdup. */ drbbdup_label_t actual_label = (drbbdup_label_t)(uintptr_t)instr_get_note(check_instr); return actual_label == label; } /* Returns true if at the start of a bb version is reached. */ static bool drbbdup_is_at_start(instr_t *check_instr) { return drbbdup_is_at_label(check_instr, DRBBDUP_LABEL_START); } /* Returns true if at the end of a bb version is reached. */ static bool drbbdup_is_at_end(instr_t *check_instr) { if (drbbdup_is_at_label(check_instr, DRBBDUP_LABEL_EXIT)) return true; if (instr_is_cti(check_instr)) { instr_t *next_instr = instr_get_next(check_instr); return drbbdup_is_at_label(next_instr, DRBBDUP_LABEL_START); } return false; } /* Iterates forward to the start of the next bb copy. Returns NULL upon failure. */ static instr_t * drbbdup_next_start(instr_t *instr) { while (instr != NULL && !drbbdup_is_at_start(instr)) instr = instr_get_next(instr); return instr; } static instr_t * drbbdup_first_app(instrlist_t *bb) { instr_t *instr = instrlist_first_app(bb); /* We also check for at end labels, because the jmp inserted by drbbdup is * an app instr which should not be considered. */ while (instr != NULL && (drbbdup_is_at_start(instr) || drbbdup_is_at_end(instr))) instr = instr_get_next_app(instr); return instr; } /* Iterates forward to the end of the next bb copy. Returns NULL upon failure. */ static instr_t * drbbdup_next_end(instr_t *instr) { while (instr != NULL && !drbbdup_is_at_end(instr)) instr = instr_get_next(instr); return instr; } /* Extracts a single bb copy from the overall bb starting from start. * start is also set to the beginning of next bb copy for easy chaining. * Overall, separate instr lists simplify user call-backs. * The returned instr list needs to be destroyed using instrlist_clear_and_destroy(). */ static instrlist_t * drbbdup_extract_single_bb_copy(void *drcontext, instrlist_t *bb, instr_t *start, OUT instr_t **next) { instrlist_t *case_bb = instrlist_create(drcontext); ASSERT(start != NULL, "start instruction cannot be NULL"); ASSERT(instr_get_note(start) == (void *)DRBBDUP_LABEL_START, "start instruction should be a START label"); instr_t *instr = instr_get_next(start); /* Skip START label. */ while (instr != NULL && !drbbdup_is_at_end(instr)) { instr_t *instr_cpy = instr_clone(drcontext, instr); instrlist_append(case_bb, instr_cpy); instr = instr_get_next(instr); } ASSERT(instr != NULL, "end instruction cannot be NULL"); ASSERT(!drbbdup_is_at_start(instr), "end cannot be at start"); /* Point to the next bb. */ if (next != NULL) *next = drbbdup_next_start(instr); /* Also include the last instruction in the bb if it is a * syscall/cti instr. */ instr_t *last_instr = instrlist_last(bb); if (drbbdup_is_special_instr(last_instr)) { instr_t *instr_cpy = instr_clone(drcontext, last_instr); instrlist_append(case_bb, instr_cpy); } return case_bb; } /* Trigger orig analysis event. This useful to set up and share common data * that transcends over different cases. */ static void * drbbdup_do_orig_analysis(drbbdup_manager_t *manager, void *drcontext, void *tag, instrlist_t *bb, instr_t *start) { if (opts.analyze_orig == NULL) return NULL; void *orig_analysis_data = NULL; if (manager->enable_dup) { instrlist_t *case_bb = drbbdup_extract_single_bb_copy(drcontext, bb, start, NULL); opts.analyze_orig(drcontext, tag, case_bb, opts.user_data, &orig_analysis_data); instrlist_clear_and_destroy(drcontext, case_bb); } else { /* For bb with no wanted copies, simply invoke the call-back with original bb. */ opts.analyze_orig(drcontext, tag, bb, opts.user_data, &orig_analysis_data); } return orig_analysis_data; } /* Performs analysis specific to a case. */ static void * drbbdup_do_case_analysis(drbbdup_manager_t *manager, void *drcontext, void *tag, instrlist_t *bb, instr_t *strt, const drbbdup_case_t *case_info, void *orig_analysis_data) { if (opts.analyze_case == NULL) return NULL; void *case_analysis_data = NULL; if (manager->enable_dup) { instrlist_t *case_bb = drbbdup_extract_single_bb_copy(drcontext, bb, strt, NULL); /* Let the user analyse the BB for the given case. */ opts.analyze_case(drcontext, tag, case_bb, case_info->encoding, opts.user_data, orig_analysis_data, &case_analysis_data); instrlist_clear_and_destroy(drcontext, case_bb); } else { /* For bb with no wanted copies, simply invoke the call-back with the original * bb. */ opts.analyze_case(drcontext, tag, bb, case_info->encoding, opts.user_data, orig_analysis_data, &case_analysis_data); } return case_analysis_data; } static dr_emit_flags_t drbbdup_analyse_phase(void *drcontext, void *tag, instrlist_t *bb, bool for_trace, bool translating, void *user_data) { drbbdup_case_t *case_info = NULL; instr_t *first = instrlist_first(bb); /* Store analysis data in thread storage. */ drbbdup_per_thread *pt = (drbbdup_per_thread *)drmgr_get_tls_field(drcontext, tls_idx); app_pc pc = instr_get_app_pc(drbbdup_first_app(bb)); ASSERT(pc != NULL, "pc cannot be NULL"); dr_rwlock_read_lock(rw_lock); drbbdup_manager_t *manager = (drbbdup_manager_t *)hashtable_lookup(&manager_table, pc); ASSERT(manager != NULL, "manager cannot be NULL"); /* Perform orig analysis - only done once regardless of how many copies. */ pt->orig_analysis_data = drbbdup_do_orig_analysis(manager, drcontext, tag, bb, first); /* Perform analysis for default case. Note, we do the analysis even if the manager * does not have dups enabled. */ case_info = &manager->default_case; ASSERT(case_info->is_defined, "default case must be defined"); pt->default_analysis_data = drbbdup_do_case_analysis( manager, drcontext, tag, bb, first, case_info, pt->orig_analysis_data); /* Perform analysis for each (non-default) case. */ if (manager->enable_dup) { ASSERT(manager->cases != NULL, "case information must exit"); int i; for (i = 0; i < opts.dup_limit; i++) { case_info = &manager->cases[i]; if (case_info->is_defined) { pt->case_analysis_data[i] = drbbdup_do_case_analysis(manager, drcontext, tag, bb, first, case_info, pt->orig_analysis_data); } } } dr_rwlock_read_unlock(rw_lock); return DR_EMIT_DEFAULT; } /**************************************************************************** * LINK/INSTRUMENTATION PHASE * * After the analysis phase, the link phase kicks in. The link phase * is responsible for linking the flow of execution to bbs * based on the case being handled. Essentially, it inserts the dispatcher. */ /* When control reaches a bb, we need to restore regs used by the dispatcher's jump. * This function inserts the restoration landing. */ static void drbbdup_insert_landing_restoration(void *drcontext, instrlist_t *bb, instr_t *where, const drbbdup_manager_t *manager) { if (!manager->are_flags_dead) { drbbdup_restore_register(drcontext, bb, where, 2, DRBBDUP_SCRATCH_REG); dr_restore_arith_flags_from_xax(drcontext, bb, where); } if (!manager->is_scratch_reg_dead) drbbdup_restore_register(drcontext, bb, where, 1, DRBBDUP_SCRATCH_REG); } /* Calculates hash index of a particular bb to access the hit table. */ static uint drbbdup_get_hitcount_hash(intptr_t bb_id) { uint hash = ((uint)bb_id) & (TABLE_SIZE - 1); ASSERT(hash < TABLE_SIZE, "index to hit table should be within bounds"); return hash; } /* Insert encoding of runtime case by invoking user call-back. */ static void drbbdup_encode_runtime_case(void *drcontext, drbbdup_per_thread *pt, void *tag, instrlist_t *bb, instr_t *where, drbbdup_manager_t *manager) { /* XXX i#4134: statistics -- insert code that tracks the number of times the fragment * is executed. */ /* Spill scratch register and flags. We use drreg to check their liveness but * manually perform the spilling for finer control across branches used by the * dispatcher. */ drreg_are_aflags_dead(drcontext, where, &manager->are_flags_dead); if (!manager->is_scratch_reg_dead) drbbdup_spill_register(drcontext, bb, where, 1, DRBBDUP_SCRATCH_REG); drreg_is_register_dead(drcontext, DRBBDUP_SCRATCH_REG, where, &manager->is_scratch_reg_dead); if (!manager->are_flags_dead) { dr_save_arith_flags_to_xax(drcontext, bb, where); drbbdup_spill_register(drcontext, bb, where, 2, DRBBDUP_SCRATCH_REG); if (!manager->is_scratch_reg_dead) drbbdup_restore_register(drcontext, bb, where, 1, DRBBDUP_SCRATCH_REG); } /* Encoding is application-specific and therefore we need to user to define the * encoding of the runtime case. We invoke a user-defined call-back. */ ASSERT(opts.insert_encode, "The encode call-back cannot be NULL"); /* Note, we could tell the user not to reserve flags and scratch register since * drbbdup is doing that already. However, for flexibility/backwards compatibility * ease, this might not be the best approach. */ opts.insert_encode(drcontext, tag, bb, where, opts.user_data, pt->orig_analysis_data); /* Restore all unreserved registers used by the call-back. */ drreg_restore_all(drcontext, bb, where); #ifdef X86_32 /* Load the encoding to the scratch register. * The dispatcher could compare directly via mem, but this will * destroy micro-fusing (mem and immed). */ opnd_t scratch_reg_opnd = opnd_create_reg(DRBBDUP_SCRATCH_REG); opnd_t opnd = drbbdup_get_encoding_opnd(); instr_t *instr = INSTR_CREATE_mov_ld(drcontext, scratch_reg_opnd, opnd); instrlist_meta_preinsert(bb, where, instr); #endif } /* At the start of a bb copy, dispatcher code is inserted. The runtime encoding * is compared with the encoding of the defined case, and if they match control * falls-through to execute the bb. Otherwise, control branches to the next bb * via next_label. */ static void drbbdup_insert_dispatch(void *drcontext, instrlist_t *bb, instr_t *where, drbbdup_manager_t *manager, instr_t *next_label, drbbdup_case_t *current_case) { instr_t *instr; ASSERT(next_label != NULL, "the label to the next bb copy cannot be NULL"); #ifdef X86_64 opnd_t scratch_reg_opnd = opnd_create_reg(DRBBDUP_SCRATCH_REG); instrlist_insert_mov_immed_ptrsz(drcontext, current_case->encoding, scratch_reg_opnd, bb, where, NULL, NULL); instr = INSTR_CREATE_cmp(drcontext, drbbdup_get_encoding_opnd(), scratch_reg_opnd); instrlist_meta_preinsert(bb, where, instr); #elif X86_32 /* Note, DRBBDUP_SCRATCH_REG contains the runtime case encoding. */ opnd_t opnd = opnd_create_immed_uint(current_case->encoding, OPSZ_PTR); instr = INSTR_CREATE_cmp(drcontext, opnd_create_reg(DRBBDUP_SCRATCH_REG), opnd); instrlist_meta_preinsert(bb, where, instr); #endif /* If runtime encoding not equal to encoding of current case, just jump to next. */ instr = INSTR_CREATE_jcc(drcontext, OP_jnz, opnd_create_instr(next_label)); instrlist_meta_preinsert(bb, where, instr); /* If fall-through, restore regs back to their original values. */ drbbdup_insert_landing_restoration(drcontext, bb, where, manager); } /* Returns whether or not additional cases should be handled by checking if the * copy limit, defined by the user, has been reached. */ static bool drbbdup_do_dynamic_handling(drbbdup_manager_t *manager) { drbbdup_case_t *drbbdup_case; int i; for (i = 0; i < opts.dup_limit; i++) { drbbdup_case = &manager->cases[i]; /* Search for empty undefined slot. */ if (!drbbdup_case->is_defined) return true; } return false; } /* Insert trigger for dynamic case handling. */ static void drbbdup_insert_dynamic_handling(void *drcontext, app_pc translation_pc, void *tag, instrlist_t *bb, instr_t *where, drbbdup_manager_t *manager) { instr_t *instr; opnd_t opnd; instr_t *done_label = INSTR_CREATE_label(drcontext); opnd_t mask_opnd = opnd_create_reg(DRBBDUP_SCRATCH_REG); /* Check whether case limit has not been reached. */ if (drbbdup_do_dynamic_handling(manager)) { drbbdup_case_t *default_info = &manager->default_case; ASSERT(default_info->is_defined, "default case must be defined"); /* Jump if runtime encoding matches default encoding. * Unknown encoding encountered upon fall-through. */ opnd = opnd_create_immed_uint((uintptr_t)default_info->encoding, OPSZ_PTR); instr = INSTR_CREATE_cmp(drcontext, mask_opnd, opnd); instrlist_meta_preinsert(bb, where, instr); instr = INSTR_CREATE_jcc(drcontext, OP_jz, opnd_create_instr(done_label)); instrlist_meta_preinsert(bb, where, instr); /* Don't bother insertion if threshold limit is zero. */ if (opts.hit_threshold > 0) { /* Update hit count and check whether threshold is reached. */ opnd_t hit_table_opnd = drbbdup_get_tls_raw_slot_opnd(DRBBDUP_HIT_TABLE_SLOT); /* Load the hit counter table. */ instr = INSTR_CREATE_mov_ld(drcontext, mask_opnd, hit_table_opnd); instrlist_meta_preinsert(bb, where, instr); /* Register hit. */ uint hash = drbbdup_get_hitcount_hash((intptr_t)translation_pc); opnd_t hit_count_opnd = OPND_CREATE_MEM16(DRBBDUP_SCRATCH_REG, hash * sizeof(ushort)); opnd = opnd_create_immed_uint(1, OPSZ_2); instr = INSTR_CREATE_sub(drcontext, hit_count_opnd, opnd); instrlist_meta_preinsert(bb, where, instr); /* Load bb tag to register so that it can be accessed by outlined clean * call. */ instrlist_insert_mov_immed_ptrsz(drcontext, (ptr_int_t)tag, mask_opnd, bb, where, NULL, NULL); /* Jump if hit reaches zero. */ opnd = opnd_create_pc(new_case_cache_pc); instr = INSTR_CREATE_jcc(drcontext, OP_jz, opnd); instrlist_meta_preinsert(bb, where, instr); } else { /* Load bb tag to register so that it can be accessed by outlined clean * call. */ instr = INSTR_CREATE_mov_imm(drcontext, mask_opnd, opnd_create_immed_int((intptr_t)tag, OPSZ_PTR)); instrlist_meta_preinsert(bb, where, instr); /* Jump to outlined clean call code for new case registration. */ opnd = opnd_create_pc(new_case_cache_pc); instr = INSTR_CREATE_jmp(drcontext, opnd); instrlist_meta_preinsert(bb, where, instr); } } /* XXX i#4134: Insert code for dynamic handling here. */ instrlist_meta_preinsert(bb, where, done_label); } /* Inserts code right before the last bb copy which is used to handle the default * case. */ static void drbbdup_insert_dispatch_end(void *drcontext, app_pc translation_pc, void *tag, instrlist_t *bb, instr_t *where, drbbdup_manager_t *manager) { /* Check whether dynamic case handling is enabled by the user to handle an unkown * case encoding. */ if (manager->enable_dynamic_handling) { drbbdup_insert_dynamic_handling(drcontext, translation_pc, tag, bb, where, manager); } /* Last bb version is always the default case. */ drbbdup_insert_landing_restoration(drcontext, bb, where, manager); } static void drbbdup_instrument_instr(void *drcontext, void *tag, instrlist_t *bb, instr_t *instr, instr_t *where, drbbdup_per_thread *pt, drbbdup_manager_t *manager) { drbbdup_case_t *drbbdup_case = NULL; void *analysis_data = NULL; ASSERT(opts.instrument_instr, "instrument call-back function cannot be NULL"); ASSERT(pt->case_index != DRBBDUP_IGNORE_INDEX, "case index cannot be ignored"); if (pt->case_index == DRBBDUP_DEFAULT_INDEX) { /* Use default case. */ drbbdup_case = &manager->default_case; analysis_data = pt->default_analysis_data; } else { ASSERT(pt->case_analysis_data != NULL, "container for analysis data cannot be NULL"); ASSERT(pt->case_index >= 0 && pt->case_index < opts.dup_limit, "case index cannot be out-of-bounds"); ASSERT(manager->enable_dup, "bb dup must be enabled"); drbbdup_case = &manager->cases[pt->case_index]; analysis_data = pt->case_analysis_data[pt->case_index]; } ASSERT(drbbdup_case->is_defined, "case must be defined upon instrumentation"); opts.instrument_instr(drcontext, tag, bb, instr, where, drbbdup_case->encoding, opts.user_data, pt->orig_analysis_data, analysis_data); } /* Support different instrumentation for different bb copies. Tracks which case is * currently being considered via an index (namely pt->case_index) in thread-local * storage, and update this index upon encountering the start/end of bb copies. */ static void drbbdup_instrument_dups(void *drcontext, app_pc pc, void *tag, instrlist_t *bb, instr_t *instr, drbbdup_per_thread *pt, drbbdup_manager_t *manager) { drbbdup_case_t *drbbdup_case = NULL; ASSERT(manager->cases != NULL, "case info should not be NULL"); ASSERT(pt != NULL, "thread-local storage should not be NULL"); instr_t *last = instrlist_last_app(bb); bool is_last_special = drbbdup_is_special_instr(last); /* Insert runtime case encoding at start. */ if (drmgr_is_first_instr(drcontext, instr)) { ASSERT(pt->case_index == -1, "case index should start at -1"); drbbdup_encode_runtime_case(drcontext, pt, tag, bb, instr, manager); } if (drbbdup_is_at_start(instr)) { instr_t *next_instr = instr_get_next(instr); /* Skip START label. */ instr_t *end_instr = drbbdup_next_end(next_instr); ASSERT(end_instr != NULL, "end instruction cannot be NULL"); /* Cache first and last instructions. */ if (next_instr == end_instr && is_last_special) pt->first_instr = last; else pt->first_instr = next_instr; /* Update cache to first instr. */ if (is_last_special) pt->last_instr = last; else pt->last_instr = instr_get_prev(end_instr); /* Update cache to last instr. */ /* Check whether we reached the last bb version (namely the default case). */ instr_t *next_bb_label = drbbdup_next_start(end_instr); if (next_bb_label == NULL) { pt->case_index = DRBBDUP_DEFAULT_INDEX; /* Refer to default. */ drbbdup_insert_dispatch_end(drcontext, pc, tag, bb, next_instr, manager); } else { /* We have reached the start of a new bb version (not the last one). */ bool found = false; int i; for (i = pt->case_index + 1; i < opts.dup_limit; i++) { drbbdup_case = &manager->cases[i]; if (drbbdup_case->is_defined) { found = true; break; } } ASSERT(found, "mismatch between bb copy count and case count detected"); ASSERT(drbbdup_case->is_defined, "the found case cannot be undefined"); ASSERT(pt->case_index + 1 == i, "the next case considered should be the next increment"); pt->case_index = i; /* Move on to the next case. */ drbbdup_insert_dispatch(drcontext, bb, next_instr /* insert after START label. */, manager, next_bb_label, drbbdup_case); } /* XXX i#4134: statistics -- insert code that tracks the number of times the * current case (pt->case_index) is executed. */ } else if (drbbdup_is_at_end(instr)) { /* Handle last special instruction (if present). */ if (is_last_special) { drbbdup_instrument_instr(drcontext, tag, bb, last, instr, pt, manager); if (pt->case_index == DRBBDUP_DEFAULT_INDEX) { pt->case_index = DRBBDUP_IGNORE_INDEX; /* Ignore remaining instructions. */ } } drreg_restore_all(drcontext, bb, instr); } else if (pt->case_index == DRBBDUP_IGNORE_INDEX) { /* Ignore instruction. */ ASSERT(drbbdup_is_special_instr(instr), "ignored instr should be cti or syscall"); } else { /* Instrument instructions inside the bb specified by pt->case_index. */ drbbdup_instrument_instr(drcontext, tag, bb, instr, instr, pt, manager); } } static void drbbdup_instrument_without_dups(void *drcontext, void *tag, instrlist_t *bb, instr_t *instr, drbbdup_per_thread *pt, drbbdup_manager_t *manager) { ASSERT(manager->cases == NULL, "case info should not be needed"); ASSERT(pt != NULL, "thread-local storage should not be NULL"); if (drmgr_is_first_instr(drcontext, instr)) { pt->first_instr = instr; pt->last_instr = instrlist_last(bb); ASSERT(drmgr_is_last_instr(drcontext, pt->last_instr), "instr should be last"); } /* No dups wanted! Just instrument normally using default case. */ ASSERT(pt->case_index == DRBBDUP_DEFAULT_INDEX, "case index should direct to default case"); drbbdup_instrument_instr(drcontext, tag, bb, instr, instr, pt, manager); } /* Invokes user call-backs to destroy analysis data. */ static void drbbdup_destroy_all_analyses(void *drcontext, drbbdup_manager_t *manager, drbbdup_per_thread *pt) { if (opts.destroy_case_analysis != NULL) { if (pt->case_analysis_data != NULL) { int i; for (i = 0; i < opts.dup_limit; i++) { if (pt->case_analysis_data[i] != NULL) { opts.destroy_case_analysis(drcontext, manager->cases[i].encoding, opts.user_data, pt->orig_analysis_data, pt->case_analysis_data[i]); pt->case_analysis_data[i] = NULL; } } } if (pt->default_analysis_data != NULL) { opts.destroy_case_analysis(drcontext, manager->default_case.encoding, opts.user_data, pt->orig_analysis_data, pt->default_analysis_data); pt->default_analysis_data = NULL; } } if (opts.destroy_orig_analysis != NULL) { if (pt->orig_analysis_data != NULL) { opts.destroy_orig_analysis(drcontext, opts.user_data, pt->orig_analysis_data); pt->orig_analysis_data = NULL; } } } static dr_emit_flags_t drbbdup_link_phase(void *drcontext, void *tag, instrlist_t *bb, instr_t *instr, bool for_trace, bool translating, void *user_data) { drbbdup_per_thread *pt = (drbbdup_per_thread *)drmgr_get_tls_field(drcontext, tls_idx); app_pc pc = instr_get_app_pc(drbbdup_first_app(bb)); ASSERT(pc != NULL, "pc cannot be NULL"); ASSERT(opts.instrument_instr != NULL, "instrumentation call-back must not be NULL"); /* Start off with the default case index. */ if (drmgr_is_first_instr(drcontext, instr)) pt->case_index = DRBBDUP_DEFAULT_INDEX; dr_rwlock_read_lock(rw_lock); drbbdup_manager_t *manager = (drbbdup_manager_t *)hashtable_lookup(&manager_table, pc); ASSERT(manager != NULL, "manager cannot be NULL"); if (manager->enable_dup) drbbdup_instrument_dups(drcontext, pc, tag, bb, instr, pt, manager); else drbbdup_instrument_without_dups(drcontext, tag, bb, instr, pt, manager); if (drmgr_is_last_instr(drcontext, instr)) drbbdup_destroy_all_analyses(drcontext, manager, pt); dr_rwlock_read_unlock(rw_lock); return DR_EMIT_DEFAULT; } static bool drbbdup_encoding_already_included(drbbdup_manager_t *manager, uintptr_t encoding_check) { drbbdup_case_t *drbbdup_case; if (manager->enable_dup) { int i; for (i = 0; i < opts.dup_limit; i++) { drbbdup_case = &manager->cases[i]; if (drbbdup_case->is_defined && drbbdup_case->encoding == encoding_check) return true; } } /* Check default case. */ drbbdup_case = &manager->default_case; if (drbbdup_case->is_defined && drbbdup_case->encoding == encoding_check) return true; return false; } static bool drbbdup_include_encoding(drbbdup_manager_t *manager, uintptr_t new_encoding) { if (manager->enable_dup) { int i; drbbdup_case_t *dup_case; for (i = 0; i < opts.dup_limit; i++) { dup_case = &manager->cases[i]; if (!dup_case->is_defined) { dup_case->is_defined = true; dup_case->encoding = new_encoding; return true; } } } return false; } /**************************************************************************** * Dynamic case handling via flushing. */ static void drbbdup_prepare_redirect(dr_mcontext_t *mcontext, drbbdup_manager_t *manager, app_pc bb_pc) { /* Restore flags and scratch reg to their original app values. */ if (!manager->are_flags_dead) { reg_t val; uint sahf; reg_t newval = mcontext->xflags; val = (reg_t)drbbdup_get_tls_raw_slot_val(DRBBDUP_FLAG_REG_SLOT); sahf = (val & 0xff00) >> 8; newval &= ~(EFLAGS_ARITH); newval |= sahf; if (TEST(1, val)) /* seto */ newval |= EFLAGS_OF; mcontext->xflags = newval; } if (!manager->is_scratch_reg_dead) { reg_set_value(DRBBDUP_SCRATCH_REG, mcontext, (reg_t)drbbdup_get_tls_raw_slot_val(DRBBDUP_XAX_REG_SLOT)); } mcontext->pc = bb_pc; /* redirect execution to the start of the bb. */ } static void drbbdup_handle_new_case() { void *drcontext = dr_get_current_drcontext(); drbbdup_per_thread *pt = (drbbdup_per_thread *)drmgr_get_tls_field(drcontext, tls_idx); /* Must use DR_MC_ALL due to dr_redirect_execution. */ dr_mcontext_t mcontext = { sizeof(mcontext), DR_MC_ALL, }; dr_get_mcontext(drcontext, &mcontext); /* Scratch register holds the tag. */ void *tag = (void *)reg_get_value(DRBBDUP_SCRATCH_REG, &mcontext); instrlist_t *ilist = decode_as_bb(drcontext, dr_fragment_app_pc(tag)); app_pc pc = instr_get_app_pc(drbbdup_first_app(ilist)); ASSERT(pc != NULL, "pc cannot be NULL"); bool do_flush = false; /* Get the missing case. */ uintptr_t new_encoding = drbbdup_get_tls_raw_slot_val(DRBBDUP_ENCODING_SLOT); dr_rwlock_write_lock(rw_lock); drbbdup_manager_t *manager = (drbbdup_manager_t *)hashtable_lookup(&manager_table, pc); ASSERT(manager != NULL, "manager cannot be NULL"); ASSERT(manager->enable_dup, "duplication should be enabled"); ASSERT(new_encoding != manager->default_case.encoding, "unhandled encoding cannot be the default case"); /* Could have been turned off potentially by another thread. */ if (manager->enable_dynamic_handling) { /* Case already registered potentially by another thread. */ if (!drbbdup_encoding_already_included(manager, new_encoding)) { /* By default, do case gen. */ bool do_gen = true; if (opts.allow_gen != NULL) { do_gen = opts.allow_gen(drcontext, tag, ilist, new_encoding, &manager->enable_dynamic_handling, opts.user_data); } if (do_gen) drbbdup_include_encoding(manager, new_encoding); /* Flush only if a new case needs to be generated or * dynamic handling has been disabled. */ do_flush = do_gen || !manager->enable_dynamic_handling; if (do_flush) { /* Mark that flushing is happening for drbbdup. */ manager->is_gen = true; /* Increment counter so manager won't get freed due to flushing. */ manager->ref_counter++; } /* XXX i#4134: statistics -- Add increment to keep track generated cases. */ } } /* Regardless of whether or not flushing is going to happen, redirection will * always be performed. */ drbbdup_prepare_redirect(&mcontext, manager, pc); dr_rwlock_write_unlock(rw_lock); instrlist_clear_and_destroy(drcontext, ilist); /* Refresh hit counter. */ if (opts.hit_threshold > 0) { uint hash = drbbdup_get_hitcount_hash((intptr_t)pc); DR_ASSERT(pt->hit_counts[hash] == 0); pt->hit_counts[hash] = opts.hit_threshold; /* Reset threshold. */ } /* Delete bb fragment. */ if (do_flush) { LOG(drcontext, DR_LOG_ALL, 2, "%s Found new case! Going to flush bb with" "pc %p to generate a copy to handle the new case.\n", __FUNCTION__, pc); /* No locks held upon fragment deletion. */ /* XXX i#3778: To include once we support specific fragment deletion. */ #if 0 dr_delete_shared_fragment(tag); #endif } dr_redirect_execution(&mcontext); } static app_pc init_fp_cache(void (*clean_call_func)()) { app_pc cache_pc; instrlist_t *ilist; void *drcontext = dr_get_current_drcontext(); size_t size = dr_page_size(); ilist = instrlist_create(drcontext); dr_insert_clean_call(drcontext, ilist, NULL, (void *)clean_call_func, false, 0); /* Allocate code cache, and set Read-Write-Execute permissions using * dr_nonheap_alloc function. */ cache_pc = (app_pc)dr_nonheap_alloc( size, DR_MEMPROT_READ | DR_MEMPROT_WRITE | DR_MEMPROT_EXEC); byte *end = instrlist_encode(drcontext, ilist, cache_pc, true); DR_ASSERT(end - cache_pc <= (int)size); instrlist_clear_and_destroy(drcontext, ilist); /* Change the permission Read-Write-Execute permissions. */ dr_memory_protect(cache_pc, size, DR_MEMPROT_READ | DR_MEMPROT_EXEC); return cache_pc; } static void destroy_fp_cache(app_pc cache_pc) { ASSERT(cache_pc, "Code cache should not be NULL"); dr_nonheap_free(cache_pc, dr_page_size()); } /**************************************************************************** * Frag Deletion */ static void deleted_frag(void *drcontext, void *tag) { /* Note, drcontext could be NULL during process exit. */ if (drcontext == NULL) return; app_pc bb_pc = dr_fragment_app_pc(tag); dr_rwlock_write_lock(rw_lock); drbbdup_manager_t *manager = (drbbdup_manager_t *)hashtable_lookup(&manager_table, bb_pc); if (manager != NULL) { ASSERT(manager->ref_counter > 0, "ref count should be greater than zero"); manager->ref_counter--; if (manager->ref_counter <= 0) hashtable_remove(&manager_table, bb_pc); } dr_rwlock_write_unlock(rw_lock); } /**************************************************************************** * INTERFACE */ drbbdup_status_t drbbdup_register_case_encoding(void *drbbdup_ctx, uintptr_t encoding) { drbbdup_manager_t *manager = (drbbdup_manager_t *)drbbdup_ctx; if (drbbdup_encoding_already_included(manager, encoding)) return DRBBDUP_ERROR_CASE_ALREADY_REGISTERED; if (drbbdup_include_encoding(manager, encoding)) return DRBBDUP_SUCCESS; else return DRBBDUP_ERROR_CASE_LIMIT_REACHED; } drbbdup_status_t drbbdup_is_first_instr(void *drcontext, instr_t *instr, bool *is_start) { if (instr == NULL || is_start == NULL) return DRBBDUP_ERROR_INVALID_PARAMETER; drbbdup_per_thread *pt = (drbbdup_per_thread *)drmgr_get_tls_field(drcontext, tls_idx); if (pt == NULL) return DRBBDUP_ERROR; *is_start = pt->first_instr == instr; return DRBBDUP_SUCCESS; } drbbdup_status_t drbbdup_is_last_instr(void *drcontext, instr_t *instr, bool *is_last) { if (instr == NULL || is_last == NULL) return DRBBDUP_ERROR_INVALID_PARAMETER; drbbdup_per_thread *pt = (drbbdup_per_thread *)drmgr_get_tls_field(drcontext, tls_idx); if (pt == NULL) return DRBBDUP_ERROR; *is_last = pt->last_instr == instr; return DRBBDUP_SUCCESS; } /**************************************************************************** * THREAD INIT AND EXIT */ static void drbbdup_destroy_manager(void *manager_opaque) { drbbdup_manager_t *manager = (drbbdup_manager_t *)manager_opaque; ASSERT(manager != NULL, "manager should not be NULL"); if (manager->enable_dup && manager->cases != NULL) { ASSERT(opts.dup_limit > 0, "dup limit should be greater than zero"); dr_global_free(manager->cases, sizeof(drbbdup_case_t) * opts.dup_limit); } dr_global_free(manager, sizeof(drbbdup_manager_t)); } static void drbbdup_thread_init(void *drcontext) { drbbdup_per_thread *pt = (drbbdup_per_thread *)dr_thread_alloc(drcontext, sizeof(drbbdup_per_thread)); pt->case_index = 0; pt->orig_analysis_data = NULL; ASSERT(opts.dup_limit > 0, "dup limit should be greater than zero"); pt->case_analysis_data = dr_thread_alloc(drcontext, sizeof(void *) * opts.dup_limit); memset(pt->case_analysis_data, 0, sizeof(void *) * opts.dup_limit); /* Init hit table. */ for (int i = 0; i < TABLE_SIZE; i++) pt->hit_counts[i] = opts.hit_threshold; drbbdup_set_tls_raw_slot_val(DRBBDUP_HIT_TABLE_SLOT, (uintptr_t)pt->hit_counts); drmgr_set_tls_field(drcontext, tls_idx, (void *)pt); } static void drbbdup_thread_exit(void *drcontext) { drbbdup_per_thread *pt = (drbbdup_per_thread *)drmgr_get_tls_field(drcontext, tls_idx); ASSERT(pt != NULL, "thread-local storage should not be NULL"); ASSERT(opts.dup_limit > 0, "dup limit should be greater than zero"); dr_thread_free(drcontext, pt->case_analysis_data, sizeof(void *) * opts.dup_limit); dr_thread_free(drcontext, pt, sizeof(drbbdup_per_thread)); } /**************************************************************************** * INIT AND EXIT */ static bool drbbdup_check_options(drbbdup_options_t *ops_in) { if (ops_in != NULL && ops_in->set_up_bb_dups != NULL && ops_in->insert_encode != NULL && ops_in->instrument_instr && ops_in->dup_limit > 0) return true; return false; } drbbdup_status_t drbbdup_init(drbbdup_options_t *ops_in) { /* Return with error if drbbdup has already been initialised. */ if (ref_count != 0) return DRBBDUP_ERROR_ALREADY_INITIALISED; if (!drbbdup_check_options(ops_in)) return DRBBDUP_ERROR_INVALID_PARAMETER; memcpy(&opts, ops_in, sizeof(drbbdup_options_t)); drreg_options_t drreg_ops = { sizeof(drreg_ops), 0 /* no regs needed */, false, NULL, true }; drmgr_priority_t priority = { sizeof(drmgr_priority_t), DRMGR_PRIORITY_NAME_DRBBDUP, NULL, NULL, DRMGR_PRIORITY_DRBBDUP }; if (!drmgr_register_bb_instrumentation_ex_event( drbbdup_duplicate_phase, drbbdup_analyse_phase, drbbdup_link_phase, NULL, &priority) || !drmgr_register_thread_init_event(drbbdup_thread_init) || !drmgr_register_thread_exit_event(drbbdup_thread_exit) || !dr_raw_tls_calloc(&tls_raw_reg, &tls_raw_base, DRBBDUP_SLOT_COUNT, 0) || drreg_init(&drreg_ops) != DRREG_SUCCESS) return DRBBDUP_ERROR; dr_register_delete_event(deleted_frag); tls_idx = drmgr_register_tls_field(); if (tls_idx == -1) return DRBBDUP_ERROR; new_case_cache_pc = init_fp_cache(drbbdup_handle_new_case); if (new_case_cache_pc == NULL) return DRBBDUP_ERROR; /* Initialise hash table that keeps track of defined cases per * basic block. */ hashtable_init_ex(&manager_table, HASH_BIT_TABLE, HASH_INTPTR, false, false, drbbdup_destroy_manager, NULL, NULL); rw_lock = dr_rwlock_create(); if (rw_lock == NULL) return DRBBDUP_ERROR; ref_count++; return DRBBDUP_SUCCESS; } drbbdup_status_t drbbdup_exit(void) { DR_ASSERT(ref_count > 0); ref_count--; if (ref_count == 0) { destroy_fp_cache(new_case_cache_pc); if (!drmgr_unregister_bb_instrumentation_ex_event(drbbdup_duplicate_phase, drbbdup_analyse_phase, drbbdup_link_phase, NULL) || !drmgr_unregister_thread_init_event(drbbdup_thread_init) || !drmgr_unregister_thread_exit_event(drbbdup_thread_exit) || !dr_raw_tls_cfree(tls_raw_base, DRBBDUP_SLOT_COUNT) || !drmgr_unregister_tls_field(tls_idx) || !dr_unregister_delete_event(deleted_frag) || drreg_exit() != DRREG_SUCCESS) return DRBBDUP_ERROR; hashtable_delete(&manager_table); dr_rwlock_destroy(rw_lock); } else { /* Cannot have more than one initialisation of drbbdup. */ return DRBBDUP_ERROR; } return DRBBDUP_SUCCESS; }
1
20,292
Could just assign directly and eliminate the `newval` var.
DynamoRIO-dynamorio
c
@@ -27,11 +27,13 @@ import ( const ( inProgressLabel = "in progress" issueTitleComment = "Please edit the title of this issue with the name of the affected package, followed by a colon, followed by a short summary of the issue. Example: `blob/gcsblob: not blobby enough`." + pullRequestTitleComment = "Please edit the title of this pull request with the name of the affected package, followed by a colon, followed by a short summary of the change. Example: `blob/gcsblob: improve comments`." branchesInForkCloseComment = "Please create pull requests from your own fork instead of from branches in the main repository. Also, please delete this branch." ) var ( - issueTitleRegexp = regexp.MustCompile("^[a-z0-9/]+: .*$") + issueTitleRegexp = regexp.MustCompile("^[a-z0-9/]+: .*$") + pullRequestTitleRegexp = issueTitleRegexp ) // issueData is information about an issue event.
1
// Copyright 2018 The Go Cloud Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package main import ( "context" "fmt" "log" "regexp" "strings" "github.com/google/go-github/github" ) const ( inProgressLabel = "in progress" issueTitleComment = "Please edit the title of this issue with the name of the affected package, followed by a colon, followed by a short summary of the issue. Example: `blob/gcsblob: not blobby enough`." branchesInForkCloseComment = "Please create pull requests from your own fork instead of from branches in the main repository. Also, please delete this branch." ) var ( issueTitleRegexp = regexp.MustCompile("^[a-z0-9/]+: .*$") ) // issueData is information about an issue event. // See the github documentation for more details about the fields: // https://godoc.org/github.com/google/go-github/github#IssuesEvent type issueData struct { // Action that this event is for. // Possible values are: "assigned", "unassigned", "labeled", "unlabeled", "opened", "closed", "reopened", "edited". Action string // Repo is the repository the pull request wants to commit to. Repo string // Owner is the owner of the repository. Owner string // Issue the event is for. Issue *github.Issue // Change made as part of the event. Change *github.EditChange } func (i *issueData) String() string { return fmt.Sprintf("[%s issue #%d]", i.Action, i.Issue.GetNumber()) } // hasLabel returns true iff the issue has the given label. func hasLabel(iss *github.Issue, label string) bool { for i := range iss.Labels { if iss.Labels[i].GetName() == label { return true } } return false } // titleChanged returns true iff the title changed. func titleChanged(title string, edit *github.EditChange) bool { return edit != nil && edit.Title != nil && edit.Title.From != nil && *edit.Title.From != title } // processIssueEvent identifies actions that should be taken based on the issue // event represented by data. func processIssueEvent(data *issueData) *issueEdits { edits := &issueEdits{} log.Printf("Identifying actions for issue: %v", data) defer log.Printf("-> %v", edits) if data.Action == "closed" && hasLabel(data.Issue, inProgressLabel) { edits.RemoveLabels = append(edits.RemoveLabels, inProgressLabel) } // Add a comment if the title doesn't match our regexp, and it's a new issue, // or an issue whose title has just been modified. if !issueTitleRegexp.MatchString(data.Issue.GetTitle()) && (data.Action == "opened" || (data.Action == "edited" && titleChanged(data.Issue.GetTitle(), data.Change))) { edits.AddComments = append(edits.AddComments, issueTitleComment) } return edits } // issueEdits captures all of the edits to be made to an issue. type issueEdits struct { RemoveLabels []string AddComments []string } func (i *issueEdits) String() string { var actions []string for _, label := range i.RemoveLabels { actions = append(actions, fmt.Sprintf("removing %q label", label)) } for _, comment := range i.AddComments { actions = append(actions, fmt.Sprintf("adding comment %q", comment)) } if len(actions) == 0 { return "[no changes]" } return strings.Join(actions, ", ") } // Execute applies all of the requested edits, aborting on error. func (i *issueEdits) Execute(ctx context.Context, client *github.Client, data *issueData) error { for _, label := range i.RemoveLabels { _, err := client.Issues.RemoveLabelForIssue(ctx, data.Owner, data.Repo, data.Issue.GetNumber(), label) if err != nil { return err } } for _, comment := range i.AddComments { _, _, err := client.Issues.CreateComment(ctx, data.Owner, data.Repo, data.Issue.GetNumber(), &github.IssueComment{ Body: github.String(comment)}) if err != nil { return err } } return nil } // pullRequestData is information about a pull request event. // See the github documentation for more details about the fields: // https://godoc.org/github.com/google/go-github/github#PullRequestEvent type pullRequestData struct { // Action that this event is for. // Possible values are: "assigned", "unassigned", "labeled", "unlabeled", "opened", "closed", "reopened", "edited". Action string // Repo is the repository the pull request wants to commit to. Repo string // Owner is the owner of the repository. Owner string // PullRequest the event is for. PullRequest *github.PullRequest // Change made as part of the event. Change *github.EditChange } func (pr *pullRequestData) String() string { return fmt.Sprintf("[%s #%d]", pr.Action, pr.PullRequest.GetNumber()) } // processPullRequestEvent identifies actions that should be taken based on the // pull request event represented by data. func processPullRequestEvent(data *pullRequestData) *pullRequestEdits { edits := &pullRequestEdits{} log.Printf("Identifying actions for pull request: %v", data) defer log.Printf("-> %v", edits) // If the pull request is from a branch of the main repo, close it and request that it come from a fork instead. if data.Action == "opened" && data.PullRequest.GetHead().GetRepo().GetName() == data.Repo { edits.Close = true edits.AddComments = append(edits.AddComments, branchesInForkCloseComment) // Short circuit since we're closing anyway. return edits } return edits } // pullRequestEdits captures all of the edits to be made to an issue. type pullRequestEdits struct { Close bool AddComments []string } func (i *pullRequestEdits) String() string { var actions []string if i.Close { actions = append(actions, "close") } for _, comment := range i.AddComments { actions = append(actions, fmt.Sprintf("add comment %q", comment)) } if len(actions) == 0 { return "[no changes]" } return strings.Join(actions, ", ") } // Execute applies all of the requested edits, aborting on error. func (i *pullRequestEdits) Execute(ctx context.Context, client *github.Client, data *pullRequestData) error { for _, comment := range i.AddComments { // Note: Use the Issues service since we're adding a top-level comment: // https://developer.github.com/v3/guides/working-with-comments/. _, _, err := client.Issues.CreateComment(ctx, data.Owner, data.Repo, data.PullRequest.GetNumber(), &github.IssueComment{ Body: github.String(comment)}) if err != nil { return err } } if i.Close { _, _, err := client.PullRequests.Edit(ctx, data.Owner, data.Repo, data.PullRequest.GetNumber(), &github.PullRequest{ State: github.String("closed"), }) if err != nil { return err } } return nil }
1
11,110
... with the name of the affected package, or "all", followed by a colon,...
google-go-cloud
go
@@ -48,6 +48,10 @@ namespace PrepareRelease "src/Datadog.Trace.ClrProfiler.Managed/Datadog.Trace.ClrProfiler.Managed.csproj", NugetVersionReplace); + SynchronizeVersion( + "src/Datadog.Trace.ClrProfiler.Managed.Core/Datadog.Trace.ClrProfiler.Managed.Core.csproj", + NugetVersionReplace); + SynchronizeVersion( "src/Datadog.Trace.ClrProfiler.Native/CMakeLists.txt", text => FullVersionReplace(text, "."));
1
using System; using System.IO; using System.Text; using System.Text.RegularExpressions; using Datadog.Core.Tools; namespace PrepareRelease { public static class SetAllVersions { public static void Run() { Console.WriteLine($"Updating version instances to {VersionString()}"); SynchronizeVersion( "integrations.json", FullAssemblyNameReplace); SynchronizeVersion( "docker/package.sh", text => Regex.Replace(text, $"VERSION={VersionPattern()}", $"VERSION={VersionString()}")); SynchronizeVersion( "customer-samples/ConsoleApp/Alpine3.9.dockerfile", text => Regex.Replace(text, $"ARG TRACER_VERSION={VersionPattern()}", $"ARG TRACER_VERSION={VersionString()}")); SynchronizeVersion( "customer-samples/ConsoleApp/Alpine3.10.dockerfile", text => Regex.Replace(text, $"ARG TRACER_VERSION={VersionPattern()}", $"ARG TRACER_VERSION={VersionString()}")); SynchronizeVersion( "customer-samples/ConsoleApp/Debian.dockerfile", text => Regex.Replace(text, $"ARG TRACER_VERSION={VersionPattern()}", $"ARG TRACER_VERSION={VersionString()}")); SynchronizeVersion( "reproductions/AutomapperTest/Dockerfile", text => Regex.Replace(text, $"ARG TRACER_VERSION={VersionPattern()}", $"ARG TRACER_VERSION={VersionString()}")); SynchronizeVersion( "src/Datadog.Trace.ClrProfiler.Managed.Loader/Datadog.Trace.ClrProfiler.Managed.Loader.csproj", NugetVersionReplace); SynchronizeVersion( "src/Datadog.Trace.ClrProfiler.Managed.Loader/Startup.cs", FullAssemblyNameReplace); SynchronizeVersion( "src/Datadog.Trace.ClrProfiler.Managed/Datadog.Trace.ClrProfiler.Managed.csproj", NugetVersionReplace); SynchronizeVersion( "src/Datadog.Trace.ClrProfiler.Native/CMakeLists.txt", text => FullVersionReplace(text, ".")); SynchronizeVersion( "src/Datadog.Trace.ClrProfiler.Native/Resource.rc", text => { text = FullVersionReplace(text, ","); text = FullVersionReplace(text, "."); return text; }); SynchronizeVersion( "src/Datadog.Trace.ClrProfiler.Native/version.h", text => FullVersionReplace(text, ".")); SynchronizeVersion( "src/Datadog.Trace.OpenTracing/Datadog.Trace.OpenTracing.csproj", NugetVersionReplace); SynchronizeVersion( "src/Datadog.Trace/Datadog.Trace.csproj", NugetVersionReplace); SynchronizeVersion( "src/Datadog.Trace.AspNet/Datadog.Trace.AspNet.csproj", NugetVersionReplace); SynchronizeVersion( "src/Datadog.Trace.AspNet/AssemblyInfo.cs", text => MajorAssemblyVersionReplace(text, ".")); SynchronizeVersion( "deploy/Datadog.Trace.ClrProfiler.WindowsInstaller/Datadog.Trace.ClrProfiler.WindowsInstaller.wixproj", WixProjReplace); Console.WriteLine($"Completed synchronizing versions to {VersionString()}"); } private static string FullVersionReplace(string text, string split) { return Regex.Replace(text, VersionPattern(split), VersionString(split), RegexOptions.Singleline); } private static string FullAssemblyNameReplace(string text) { return Regex.Replace(text, AssemblyString(VersionPattern()), AssemblyString(VersionString()), RegexOptions.Singleline); } private static string MajorAssemblyVersionReplace(string text, string split) { return Regex.Replace(text, VersionPattern(fourPartVersion: true), MajorVersionString(split), RegexOptions.Singleline); } private static string NugetVersionReplace(string text) { return Regex.Replace(text, $"<Version>{VersionPattern(withPrereleasePostfix: true)}</Version>", $"<Version>{VersionString(withPrereleasePostfix: true)}</Version>", RegexOptions.Singleline); } private static string NuspecVersionReplace(string text) { return Regex.Replace(text, $"<version>{VersionPattern(withPrereleasePostfix: true)}</version>", $"<version>{VersionString(withPrereleasePostfix: true)}</version>", RegexOptions.Singleline); } private static string WixProjReplace(string text) { text = Regex.Replace( text, $"<OutputName>datadog-dotnet-apm-{VersionPattern(withPrereleasePostfix: true)}-\\$\\(Platform\\)</OutputName>", $"<OutputName>datadog-dotnet-apm-{VersionString(withPrereleasePostfix: true)}-$(Platform)</OutputName>", RegexOptions.Singleline); text = Regex.Replace( text, $"InstallerVersion={VersionPattern()}", $"InstallerVersion={VersionString()}", RegexOptions.Singleline); return text; } private static void SynchronizeVersion(string path, Func<string, string> transform) { var solutionDirectory = EnvironmentTools.GetSolutionDirectory(); var fullPath = Path.Combine(solutionDirectory, path); Console.WriteLine($"Updating version instances for {path}"); if (!File.Exists(fullPath)) { throw new Exception($"File not found to version: {path}"); } var fileContent = File.ReadAllText(fullPath); var newFileContent = transform(fileContent); File.WriteAllText(fullPath, newFileContent, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); } private static string MajorVersionString(string split = ".") { return $"{TracerVersion.Major}{split}0{split}0{split}0"; } private static string VersionString(string split = ".", bool withPrereleasePostfix = false) { var newVersion = $"{TracerVersion.Major}{split}{TracerVersion.Minor}{split}{TracerVersion.Patch}"; // this gets around a compiler warning about unreachable code below var isPreRelease = TracerVersion.IsPreRelease; // ReSharper disable once ConditionIsAlwaysTrueOrFalse if (withPrereleasePostfix && isPreRelease) { newVersion = newVersion + "-prerelease"; } return newVersion; } private static string VersionPattern(string split = ".", bool withPrereleasePostfix = false, bool fourPartVersion = false) { if (split == ".") { split = @"\."; } var pattern = $@"\d+{split}\d+{split}\d+"; if (fourPartVersion) { pattern = pattern + $@"{split}\d+"; } if (withPrereleasePostfix) { pattern = pattern + "(\\-prerelease)?"; } return pattern; } private static string AssemblyString(string versionText) { return $"Datadog.Trace.ClrProfiler.Managed, Version={versionText}.0, Culture=neutral, PublicKeyToken=def86d061d0d2eeb"; } } }
1
16,668
We'll want to remove this one if we make the assembly version constant.
DataDog-dd-trace-dotnet
.cs
@@ -51,6 +51,7 @@ class Frontend extends Generator { $this->setup_blog_colors(); $this->setup_form_fields_style(); $this->setup_single_post_style(); + $this->setup_single_page_style(); } /**
1
<?php /** * Style generator based on settings. * * @package Neve\Core\Styles */ namespace Neve\Core\Styles; use Neve\Core\Settings\Config; use Neve\Core\Settings\Mods; use Neve\Customizer\Defaults\Layout; use Neve\Customizer\Defaults\Single_Post; /** * Class Generator for Frontend. * * @package Neve\Core\Styles */ class Frontend extends Generator { use Css_Vars; use Single_Post; use Layout; /** * Box shadow map values * * @var string[] */ private $box_shadow_map = [ 1 => '0 1px 3px -2px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.1)', 2 => '0 3px 6px -5px rgba(0, 0, 0, 0.1), 0 4px 8px rgba(0, 0, 0, 0.1)', 3 => '0 10px 20px rgba(0, 0, 0, 0.1), 0 4px 8px rgba(0, 0, 0, 0.1)', 4 => '0 14px 28px rgba(0, 0, 0, 0.12), 0 10px 10px rgba(0, 0, 0, 0.12)', 5 => '0 16px 38px -12px rgba(0,0,0,0.56), 0 4px 25px 0 rgba(0,0,0,0.12), 0 8px 10px -5px rgba(0,0,0,0.2)', ]; /** * Generator constructor. */ public function __construct() { $this->_subscribers = []; $this->setup_container(); $this->setup_blog_layout(); $this->setup_legacy_gutenberg_palette(); $this->setup_layout_subscribers(); $this->setup_buttons(); $this->setup_typography(); $this->setup_blog_meta(); $this->setup_blog_typography(); $this->setup_blog_colors(); $this->setup_form_fields_style(); $this->setup_single_post_style(); } /** * Setup the container styles. * * @return void */ private function setup_container() { if ( ! neve_is_new_skin() ) { $this->_subscribers['.container'] = [ Config::CSS_PROP_MAX_WIDTH => [ Dynamic_Selector::META_KEY => Config::MODS_CONTAINER_WIDTH, Dynamic_Selector::META_IS_RESPONSIVE => true, ], ]; return; } $this->_subscribers[] = [ Dynamic_Selector::KEY_SELECTOR => ':root', Dynamic_Selector::KEY_RULES => $this->get_container_rules(), ]; } /** * Setup legacy gutenberg palette for old users. */ private function setup_legacy_gutenberg_palette() { $is_new_user = get_option( 'neve_new_user' ); $imported_starter_site = get_option( 'neve_imported_demo' ); if ( $is_new_user === 'yes' && $imported_starter_site !== 'yes' ) { return; } $this->_subscribers['.has-neve-button-color-color'] = [ Config::CSS_PROP_COLOR => [ Dynamic_Selector::META_KEY => Config::MODS_BUTTON_PRIMARY_STYLE . '.background', Dynamic_Selector::META_IMPORTANT => true, Dynamic_Selector::META_DEFAULT => '#0366d6', ], ]; $this->_subscribers['.has-neve-button-color-background-color'] = [ Config::CSS_PROP_BACKGROUND_COLOR => [ Dynamic_Selector::META_KEY => Config::MODS_BUTTON_PRIMARY_STYLE . '.background', Dynamic_Selector::META_IMPORTANT => true, Dynamic_Selector::META_DEFAULT => '#0366d6', ], ]; } /** * Setup legacy blog colors. */ private function setup_legacy_blog_colors() { $this->_subscribers['.cover-post .inner, .cover-post .inner a:not(.button), .cover-post .inner a:not(.button):hover, .cover-post .inner a:not(.button):focus, .cover-post .inner li'] = [ Config::CSS_PROP_COLOR => [ Dynamic_Selector::META_KEY => 'neve_blog_covers_text_color', ], ]; $selector = get_theme_mod( 'neve_blog_archive_layout', 'grid' ) === 'covers' ? '.cover-post.nv-post-thumbnail-wrap' : '.nv-post-thumbnail-wrap img'; $this->_subscribers[ $selector ] = [ Config::CSS_PROP_BOX_SHADOW => [ Dynamic_Selector::META_KEY => 'neve_post_thumbnail_box_shadow', Dynamic_Selector::META_FILTER => function ( $css_prop, $value, $meta, $device ) { if ( absint( $value ) === 0 ) { return ''; } if ( ! array_key_exists( absint( $value ), $this->box_shadow_map ) ) { return ''; } return sprintf( '%s:%s;', $css_prop, $this->box_shadow_map[ $value ] ); }, ], ]; } /** * Add css for blog colors. */ public function setup_blog_colors() { if ( ! neve_is_new_skin() ) { $this->setup_legacy_blog_colors(); return; } $layout = get_theme_mod( 'neve_blog_archive_layout', 'grid' ); if ( $layout === 'covers' ) { $this->_subscribers['.cover-post'] = [ '--color' => 'neve_blog_covers_text_color', ]; } $this->_subscribers['.nv-post-thumbnail-wrap'] = [ '--boxShadow' => [ Dynamic_Selector::META_KEY => 'neve_post_thumbnail_box_shadow', Dynamic_Selector::META_FILTER => function ( $css_prop, $value, $meta, $device ) { if ( absint( $value ) === 0 ) { return ''; } if ( ! array_key_exists( absint( $value ), $this->box_shadow_map ) ) { return ''; } return sprintf( '%s:%s;', $css_prop, $this->box_shadow_map[ $value ] ); }, ], ]; } /** * Add css for blog typography. */ public function setup_blog_typography() { if ( ! neve_is_new_skin() ) { $this->setup_legacy_blog_typography(); return; } $archive_typography = [ Config::CSS_SELECTOR_ARCHIVE_POST_TITLE => [ 'mod' => Config::MODS_TYPEFACE_ARCHIVE_POST_TITLE, 'font' => Config::MODS_FONT_HEADINGS, ], Config::CSS_SELECTOR_ARCHIVE_POST_EXCERPT => [ 'mod' => Config::MODS_TYPEFACE_ARCHIVE_POST_EXCERPT, 'font' => Config::MODS_FONT_GENERAL, ], Config::CSS_SELECTOR_ARCHIVE_POST_META => [ 'mod' => Config::MODS_TYPEFACE_ARCHIVE_POST_META, 'font' => Config::MODS_FONT_GENERAL, ], Config::CSS_SELECTOR_SINGLE_POST_TITLE => [ 'mod' => Config::MODS_TYPEFACE_SINGLE_POST_TITLE, 'font' => Config::MODS_FONT_HEADINGS, ], Config::CSS_SELECTOR_SINGLE_POST_META => [ 'mod' => Config::MODS_TYPEFACE_SINGLE_POST_META, 'font' => Config::MODS_FONT_GENERAL, ], Config::CSS_SELECTOR_SINGLE_POST_COMMENT_TITLE => [ 'mod' => Config::MODS_TYPEFACE_SINGLE_POST_COMMENT_TITLE, 'font' => Config::MODS_FONT_HEADINGS, ], ]; foreach ( $archive_typography as $selector => $args ) { $this->_subscribers[ $selector ] = [ '--fontSize' => [ Dynamic_Selector::META_KEY => $args['mod'] . '.fontSize', Dynamic_Selector::META_IS_RESPONSIVE => true, Dynamic_Selector::META_SUFFIX => 'px', ], '--lineHeight' => [ Dynamic_Selector::META_KEY => $args['mod'] . '.lineHeight', Dynamic_Selector::META_IS_RESPONSIVE => true, Dynamic_Selector::META_SUFFIX => '', ], '--letterSpacing' => [ Dynamic_Selector::META_KEY => $args['mod'] . '.letterSpacing', Dynamic_Selector::META_IS_RESPONSIVE => true, Dynamic_Selector::META_SUFFIX => 'px', ], '--fontWeight' => [ Dynamic_Selector::META_KEY => $args['mod'] . '.fontWeight', 'font' => 'mods_' . $args['font'], ], '--textTransform' => $args['mod'] . '.textTransform', ]; } } /** * Add css for blog layout. * * Removed grid in new skin CSS so this should handle the grid. * * @since 3.0.0 * * @return bool|void */ public function setup_blog_layout() { if ( ! neve_is_new_skin() ) { return false; } $this->_subscribers[':root'] = [ '--postWidth' => [ Dynamic_Selector::META_KEY => 'neve_grid_layout', Dynamic_Selector::META_IS_RESPONSIVE => true, Dynamic_Selector::META_DEFAULT => $this->grid_columns_default(), Dynamic_Selector::META_FILTER => function ( $css_prop, $value, $meta, $device ) { $blog_layout = get_theme_mod( 'neve_blog_archive_layout', 'grid' ); if ( ! in_array( $blog_layout, [ 'grid', 'covers' ], true ) ) { return sprintf( '%s:%s;', $css_prop, '100%' ); } if ( $value < 1 ) { $value = 1; } return sprintf( '%s:%s;', $css_prop, 100 / $value . '%' ); }, ], ]; } /** * Setups the legacy typography, used before 3.0. * * @since 3.0.0 */ public function setup_legacy_typography() { $this->_subscribers[ Config::CSS_SELECTOR_TYPEFACE_GENERAL ] = [ Config::CSS_PROP_FONT_SIZE => [ Dynamic_Selector::META_KEY => Config::MODS_TYPEFACE_GENERAL . '.fontSize', Dynamic_Selector::META_IS_RESPONSIVE => true, Dynamic_Selector::META_SUFFIX => 'px', ], Config::CSS_PROP_LINE_HEIGHT => [ Dynamic_Selector::META_KEY => Config::MODS_TYPEFACE_GENERAL . '.lineHeight', Dynamic_Selector::META_IS_RESPONSIVE => true, Dynamic_Selector::META_SUFFIX => '', ], Config::CSS_PROP_LETTER_SPACING => [ Dynamic_Selector::META_KEY => Config::MODS_TYPEFACE_GENERAL . '.letterSpacing', Dynamic_Selector::META_IS_RESPONSIVE => true, ], Config::CSS_PROP_FONT_WEIGHT => [ Dynamic_Selector::META_KEY => Config::MODS_TYPEFACE_GENERAL . '.fontWeight', 'font' => 'mods_' . Config::MODS_FONT_GENERAL, ], Config::CSS_PROP_TEXT_TRANSFORM => Config::MODS_TYPEFACE_GENERAL . '.textTransform', Config::CSS_PROP_FONT_FAMILY => Config::MODS_FONT_GENERAL, ]; foreach ( neve_get_headings_selectors() as $id => $heading_selector ) { $heading_mod = sprintf( 'neve_%s_typeface_general', $id ); $this->_subscribers[ $heading_selector ] = [ Config::CSS_PROP_FONT_SIZE => [ Dynamic_Selector::META_KEY => $heading_mod . '.fontSize', Dynamic_Selector::META_IS_RESPONSIVE => true, Dynamic_Selector::META_SUFFIX => 'em', ], Config::CSS_PROP_LINE_HEIGHT => [ Dynamic_Selector::META_KEY => $heading_mod . '.lineHeight', Dynamic_Selector::META_IS_RESPONSIVE => true, Dynamic_Selector::META_SUFFIX => '', ], Config::CSS_PROP_LETTER_SPACING => [ Dynamic_Selector::META_KEY => $heading_mod . '.letterSpacing', Dynamic_Selector::META_IS_RESPONSIVE => true, ], Config::CSS_PROP_FONT_WEIGHT => [ Dynamic_Selector::META_KEY => $heading_mod . '.fontWeight', 'font' => 'mods_' . Config::MODS_FONT_HEADINGS, ], Config::CSS_PROP_TEXT_TRANSFORM => $heading_mod . '.textTransform', Config::CSS_PROP_FONT_FAMILY => Config::MODS_FONT_HEADINGS, ]; } // Legacy filters. $extra_selectors_heading = apply_filters( 'neve_headings_font_family_selectors', '' ); if ( ! empty( $extra_selectors_heading ) ) { $extra_selectors_heading = ltrim( $extra_selectors_heading, ', ' ); $this->_subscribers[ $extra_selectors_heading ] = [ Config::CSS_PROP_FONT_FAMILY => Config::MODS_FONT_HEADINGS, ]; } $extra_selectors_body = apply_filters( 'neve_body_font_family_selectors', '' ); if ( ! empty( $extra_selectors_body ) ) { $extra_selectors_body = ltrim( $extra_selectors_body, ', ' ); $this->_subscribers[ $extra_selectors_body ] = [ Config::CSS_PROP_LETTER_SPACING => [ Dynamic_Selector::META_KEY => Config::MODS_TYPEFACE_GENERAL . '.letterSpacing', Dynamic_Selector::META_IS_RESPONSIVE => true, ], Config::CSS_PROP_FONT_WEIGHT => [ Dynamic_Selector::META_KEY => Config::MODS_TYPEFACE_GENERAL . '.fontWeight', 'font' => 'mods_' . Config::MODS_FONT_GENERAL, ], Config::CSS_PROP_TEXT_TRANSFORM => Config::MODS_TYPEFACE_GENERAL . '.textTransform', Config::CSS_PROP_FONT_FAMILY => Config::MODS_FONT_GENERAL, ]; } } /** * Setup typography subscribers. */ public function setup_typography() { if ( ! neve_is_new_skin() ) { $this->setup_legacy_typography(); return; } $rules = $this->get_typography_rules(); $this->_subscribers[] = [ Dynamic_Selector::KEY_SELECTOR => ':root', Dynamic_Selector::KEY_RULES => $rules, ]; } /** * Setup legacy button. */ private function setup_legacy_buttons() { // Primary button config. $this->_subscribers[] = [ Dynamic_Selector::KEY_SELECTOR => Config::CSS_SELECTOR_BTN_PRIMARY_NORMAL, Dynamic_Selector::KEY_RULES => [ Config::CSS_PROP_BACKGROUND_COLOR => [ Dynamic_Selector::META_KEY => Config::MODS_BUTTON_PRIMARY_STYLE . '.background', Dynamic_Selector::META_DEFAULT => 'var(--nv-primary-accent)', ], Config::CSS_PROP_COLOR => Config::MODS_BUTTON_PRIMARY_STYLE . '.text', Config::CSS_PROP_BORDER_RADIUS => Config::MODS_BUTTON_PRIMARY_STYLE . '.borderRadius', Config::CSS_PROP_CUSTOM_BTN_TYPE => Config::MODS_BUTTON_PRIMARY_STYLE . '.type', Config::CSS_PROP_BORDER_WIDTH => Config::MODS_BUTTON_PRIMARY_STYLE . '.borderWidth', ], Dynamic_Selector::KEY_CONTEXT => [ Dynamic_Selector::CONTEXT_FRONTEND => true, ], ]; $this->_subscribers[] = [ Dynamic_Selector::KEY_SELECTOR => Config::CSS_SELECTOR_BTN_PRIMARY_NORMAL, Dynamic_Selector::KEY_RULES => [ Config::CSS_PROP_FONT_SIZE => [ Dynamic_Selector::META_KEY => Config::MODS_BUTTON_TYPEFACE . '.fontSize', Dynamic_Selector::META_IS_RESPONSIVE => true, Dynamic_Selector::META_SUFFIX => 'em', ], Config::CSS_PROP_LINE_HEIGHT => [ Dynamic_Selector::META_KEY => Config::MODS_BUTTON_TYPEFACE . '.lineHeight', Dynamic_Selector::META_IS_RESPONSIVE => true, Dynamic_Selector::META_SUFFIX => '', ], Config::CSS_PROP_LETTER_SPACING => [ Dynamic_Selector::META_KEY => Config::MODS_BUTTON_TYPEFACE . '.letterSpacing', Dynamic_Selector::META_IS_RESPONSIVE => true, ], Config::CSS_PROP_FONT_WEIGHT => [ Dynamic_Selector::META_KEY => Config::MODS_BUTTON_TYPEFACE . '.fontWeight', 'font' => 'mods_' . Config::MODS_FONT_GENERAL, ], Config::CSS_PROP_TEXT_TRANSFORM => Config::MODS_BUTTON_TYPEFACE . '.textTransform', ], ]; $this->_subscribers[] = [ Dynamic_Selector::KEY_SELECTOR => Config::CSS_SELECTOR_BTN_PRIMARY_HOVER, Dynamic_Selector::KEY_RULES => [ Config::CSS_PROP_BACKGROUND_COLOR => Config::MODS_BUTTON_PRIMARY_STYLE . '.backgroundHover', Config::CSS_PROP_COLOR => Config::MODS_BUTTON_PRIMARY_STYLE . '.textHover', ], Dynamic_Selector::KEY_CONTEXT => [ Dynamic_Selector::CONTEXT_FRONTEND => true, ], ]; $secondary_rules = [ Dynamic_Selector::KEY_RULES => [ Config::CSS_PROP_BACKGROUND_COLOR => [ Dynamic_Selector::META_KEY => Config::MODS_BUTTON_SECONDARY_STYLE . '.background', Dynamic_Selector::META_DEFAULT => 'rgba(0,0,0,0)', ], Config::CSS_PROP_COLOR => [ Dynamic_Selector::META_KEY => Config::MODS_BUTTON_SECONDARY_STYLE . '.text', Dynamic_Selector::META_DEFAULT => 'var(--nv-text-color)', ], Config::CSS_PROP_BORDER_RADIUS => Config::MODS_BUTTON_SECONDARY_STYLE . '.borderRadius', Config::CSS_PROP_CUSTOM_BTN_TYPE => Config::MODS_BUTTON_SECONDARY_STYLE . '.type', Config::CSS_PROP_BORDER_WIDTH => Config::MODS_BUTTON_SECONDARY_STYLE . '.borderWidth', ], Dynamic_Selector::KEY_CONTEXT => [ Dynamic_Selector::CONTEXT_FRONTEND => true, ], ]; $this->_subscribers [] = array_merge( [ Dynamic_Selector::KEY_SELECTOR => Config::CSS_SELECTOR_BTN_SECONDARY_NORMAL ], $secondary_rules ); $this->_subscribers [] = array_merge( [ Dynamic_Selector::KEY_SELECTOR => Config::CSS_SELECTOR_BTN_SECONDARY_DEFAULT ], $secondary_rules ); $this->_subscribers[] = [ Dynamic_Selector::KEY_SELECTOR => Config::CSS_SELECTOR_BTN_SECONDARY_NORMAL, Dynamic_Selector::KEY_RULES => [ Config::CSS_PROP_FONT_SIZE => [ Dynamic_Selector::META_KEY => Config::MODS_SECONDARY_BUTTON_TYPEFACE . '.fontSize', Dynamic_Selector::META_IS_RESPONSIVE => true, Dynamic_Selector::META_SUFFIX => 'em', ], Config::CSS_PROP_LINE_HEIGHT => [ Dynamic_Selector::META_KEY => Config::MODS_SECONDARY_BUTTON_TYPEFACE . '.lineHeight', Dynamic_Selector::META_IS_RESPONSIVE => true, Dynamic_Selector::META_SUFFIX => '', ], Config::CSS_PROP_LETTER_SPACING => [ Dynamic_Selector::META_KEY => Config::MODS_SECONDARY_BUTTON_TYPEFACE . '.letterSpacing', Dynamic_Selector::META_IS_RESPONSIVE => true, ], Config::CSS_PROP_FONT_WEIGHT => [ Dynamic_Selector::META_KEY => Config::MODS_SECONDARY_BUTTON_TYPEFACE . '.fontWeight', 'font' => 'mods_' . Config::MODS_FONT_GENERAL, ], Config::CSS_PROP_TEXT_TRANSFORM => Config::MODS_SECONDARY_BUTTON_TYPEFACE . '.textTransform', ], ]; $secondary_rules_hover = [ Dynamic_Selector::KEY_RULES => [ Config::CSS_PROP_BACKGROUND_COLOR => [ Dynamic_Selector::META_KEY => Config::MODS_BUTTON_SECONDARY_STYLE . '.backgroundHover', Dynamic_Selector::META_DEFAULT => 'rgba(0,0,0,0)', ], Config::CSS_PROP_COLOR => [ Dynamic_Selector::META_KEY => Config::MODS_BUTTON_SECONDARY_STYLE . '.textHover', Dynamic_Selector::META_DEFAULT => 'var(--nv-text-color)', ], ], Dynamic_Selector::KEY_CONTEXT => [ Dynamic_Selector::CONTEXT_FRONTEND => true, ], ]; $this->_subscribers[] = array_merge( $secondary_rules_hover, [ Dynamic_Selector::KEY_SELECTOR => Config::CSS_SELECTOR_BTN_SECONDARY_HOVER ] ); $this->_subscribers[] = array_merge( $secondary_rules_hover, [ Dynamic_Selector::KEY_SELECTOR => Config::CSS_SELECTOR_BTN_SECONDARY_DEFAULT_HOVER ] ); $this->_subscribers[] = [ Dynamic_Selector::KEY_SELECTOR => Config::CSS_SELECTOR_BTN_PRIMARY_PADDING, Dynamic_Selector::KEY_RULES => [ Config::CSS_PROP_PADDING => [ Dynamic_Selector::META_KEY => Config::MODS_BUTTON_PRIMARY_PADDING, Dynamic_Selector::META_IS_RESPONSIVE => true, ], ], Dynamic_Selector::KEY_CONTEXT => [ Dynamic_Selector::CONTEXT_FRONTEND => true, ], ]; $this->_subscribers[] = [ Dynamic_Selector::KEY_SELECTOR => Config::CSS_SELECTOR_BTN_SECONDARY_PADDING, Dynamic_Selector::KEY_RULES => [ Config::CSS_PROP_PADDING => [ Dynamic_Selector::META_KEY => Config::MODS_BUTTON_SECONDARY_PADDING, Dynamic_Selector::META_IS_RESPONSIVE => true, ], ], Dynamic_Selector::KEY_CONTEXT => [ Dynamic_Selector::CONTEXT_FRONTEND => true, ], ]; if ( ! class_exists( 'WooCommerce', false ) ) { return; } $this->_subscribers[] = [ Dynamic_Selector::KEY_SELECTOR => '.woocommerce-mini-cart__buttons .button.checkout', Dynamic_Selector::KEY_RULES => [ Config::CSS_PROP_BACKGROUND_COLOR => [ Dynamic_Selector::META_KEY => Config::MODS_BUTTON_PRIMARY_STYLE . '.background', Dynamic_Selector::META_DEFAULT => 'var(--nv-primary-accent)', ], Config::CSS_PROP_COLOR => Config::MODS_BUTTON_PRIMARY_STYLE . '.text', Config::CSS_PROP_BORDER_RADIUS => Config::MODS_BUTTON_PRIMARY_STYLE . '.borderRadius', Config::CSS_PROP_CUSTOM_BTN_TYPE => Config::MODS_BUTTON_PRIMARY_STYLE . '.type', Config::CSS_PROP_BORDER_WIDTH => Config::MODS_BUTTON_PRIMARY_STYLE . '.borderWidth', ], Dynamic_Selector::KEY_CONTEXT => [ Dynamic_Selector::CONTEXT_FRONTEND => true, ], ]; $this->_subscribers[] = [ Dynamic_Selector::KEY_SELECTOR => '.woocommerce-mini-cart__buttons .button.checkout:hover', Dynamic_Selector::KEY_RULES => [ Config::CSS_PROP_BACKGROUND_COLOR => Config::MODS_BUTTON_PRIMARY_STYLE . '.backgroundHover', Config::CSS_PROP_COLOR => Config::MODS_BUTTON_PRIMARY_STYLE . '.textHover', ], Dynamic_Selector::KEY_CONTEXT => [ Dynamic_Selector::CONTEXT_FRONTEND => true, ], ]; $this->_subscribers [] = [ Dynamic_Selector::KEY_SELECTOR => '.woocommerce .woocommerce-mini-cart__buttons.buttons a.button.wc-forward:not(.checkout)', Dynamic_Selector::KEY_RULES => [ Config::CSS_PROP_BACKGROUND_COLOR => Config::MODS_BUTTON_SECONDARY_STYLE . '.background', Config::CSS_PROP_COLOR => [ Dynamic_Selector::META_KEY => Config::MODS_BUTTON_SECONDARY_STYLE . '.text', Dynamic_Selector::META_DEFAULT => 'var(--nv-text-color)', ], Config::CSS_PROP_BORDER_RADIUS => Config::MODS_BUTTON_SECONDARY_STYLE . '.borderRadius', Config::CSS_PROP_CUSTOM_BTN_TYPE => Config::MODS_BUTTON_SECONDARY_STYLE . '.type', Config::CSS_PROP_BORDER_WIDTH => Config::MODS_BUTTON_SECONDARY_STYLE . '.borderWidth', ], Dynamic_Selector::KEY_CONTEXT => [ Dynamic_Selector::CONTEXT_FRONTEND => true, ], ]; $this->_subscribers[] = [ Dynamic_Selector::KEY_SELECTOR => '.woocommerce .woocommerce-mini-cart__buttons.buttons a.button.wc-forward:not(.checkout):hover', Dynamic_Selector::KEY_RULES => [ Config::CSS_PROP_BACKGROUND_COLOR => Config::MODS_BUTTON_SECONDARY_STYLE . '.backgroundHover', Config::CSS_PROP_COLOR => [ Dynamic_Selector::META_KEY => Config::MODS_BUTTON_SECONDARY_STYLE . '.textHover', Dynamic_Selector::META_DEFAULT => 'var(--nv-text-color)', ], ], Dynamic_Selector::KEY_CONTEXT => [ Dynamic_Selector::CONTEXT_FRONTEND => true, ], ]; } /** * Setup button subscribers. */ public function setup_buttons() { if ( ! neve_is_new_skin() ) { $this->setup_legacy_buttons(); return; } $rules = $this->get_button_rules(); $this->_subscribers[] = [ Dynamic_Selector::KEY_SELECTOR => ':root', Dynamic_Selector::KEY_RULES => $rules, ]; } /** * Setup settings subscribers for layout. * * TODO: Exclude sidebar CSS when there is not sidebar option selected. * TODO: Better exclude classes when Woo is not present, i.e shop-sidebar class is added even when Woo is not used. */ public function setup_layout_subscribers() { $is_advanced_on = Mods::get( Config::MODS_ADVANCED_LAYOUT_OPTIONS, neve_is_new_skin() ); if ( ! $is_advanced_on ) { $this->_subscribers['#content .container .col, #content .container-fluid .col'] = [ Config::CSS_PROP_MAX_WIDTH => [ Dynamic_Selector::META_KEY => Config::MODS_SITEWIDE_CONTENT_WIDTH, Dynamic_Selector::META_SUFFIX => '%', Dynamic_Selector::META_DEVICE_ONLY => Dynamic_Selector::DESKTOP, ], ]; $this->_subscribers['.alignfull > [class*="__inner-container"], .alignwide > [class*="__inner-container"]'] = [ Config::CSS_PROP_MAX_WIDTH => [ Dynamic_Selector::META_KEY => Config::MODS_SITEWIDE_CONTENT_WIDTH, Dynamic_Selector::META_DEFAULT => 70, Dynamic_Selector::META_IS_RESPONSIVE => true, Dynamic_Selector::META_FILTER => function ( $css_prop, $value, $meta, $device ) { $width = Mods::to_json( Config::MODS_CONTAINER_WIDTH ); if ( $device === Dynamic_Selector::DESKTOP ) { return sprintf( 'max-width:%spx', round( ( $value / 100 ) * $width[ $device ] - Config::CONTENT_DEFAULT_PADDING ) ); } if ( $device === Dynamic_Selector::MOBILE ) { return sprintf( 'max-width:%spx;margin:auto', ( $width[ $device ] - Config::CONTENT_DEFAULT_PADDING ) ); } return ''; }, ], ]; $this->_subscribers['.container-fluid .alignfull > [class*="__inner-container"], .container-fluid .alignwide > [class*="__inner-container"]'] = [ Config::CSS_PROP_MAX_WIDTH => [ Dynamic_Selector::META_KEY => Config::MODS_SITEWIDE_CONTENT_WIDTH, Dynamic_Selector::META_DEVICE_ONLY => Dynamic_Selector::DESKTOP, Dynamic_Selector::META_FILTER => function ( $css_prop, $value, $meta, $device ) { return sprintf( 'max-width:calc(%s%% + %spx)', $value, Config::CONTENT_DEFAULT_PADDING / 2 ); }, ], ]; $this->_subscribers['.nv-sidebar-wrap, .nv-sidebar-wrap.shop-sidebar'] = [ Config::CSS_PROP_MAX_WIDTH => [ Dynamic_Selector::META_KEY => Config::MODS_SITEWIDE_CONTENT_WIDTH, Dynamic_Selector::META_FILTER => 'minus_100', Dynamic_Selector::META_DEVICE_ONLY => Dynamic_Selector::DESKTOP, Dynamic_Selector::META_SUFFIX => '%', ], ]; return; } // Others content width. $this->_subscribers['body:not(.single):not(.archive):not(.blog):not(.search) .neve-main > .container .col, body.post-type-archive-course .neve-main > .container .col, body.post-type-archive-llms_membership .neve-main > .container .col'] = [ Config::CSS_PROP_MAX_WIDTH => [ Dynamic_Selector::META_KEY => Config::MODS_OTHERS_CONTENT_WIDTH, Dynamic_Selector::META_DEFAULT => $this->sidebar_layout_width_default( Config::MODS_OTHERS_CONTENT_WIDTH ), Dynamic_Selector::META_DEVICE_ONLY => Dynamic_Selector::DESKTOP, Dynamic_Selector::META_SUFFIX => '%', ], ]; $this->_subscribers['body:not(.single):not(.archive):not(.blog):not(.search) .nv-sidebar-wrap, body.post-type-archive-course .nv-sidebar-wrap, body.post-type-archive-llms_membership .nv-sidebar-wrap'] = [ Config::CSS_PROP_MAX_WIDTH => [ Dynamic_Selector::META_KEY => Config::MODS_OTHERS_CONTENT_WIDTH, Dynamic_Selector::META_DEFAULT => $this->sidebar_layout_width_default( Config::MODS_OTHERS_CONTENT_WIDTH ), Dynamic_Selector::META_DEVICE_ONLY => Dynamic_Selector::DESKTOP, Dynamic_Selector::META_FILTER => 'minus_100', Dynamic_Selector::META_SUFFIX => '%', ], ]; // Archive content width. $this->_subscribers['.neve-main > .archive-container .nv-index-posts.col'] = [ Config::CSS_PROP_MAX_WIDTH => [ Dynamic_Selector::META_KEY => Config::MODS_ARCHIVE_CONTENT_WIDTH, Dynamic_Selector::META_DEFAULT => $this->sidebar_layout_width_default( Config::MODS_ARCHIVE_CONTENT_WIDTH ), Dynamic_Selector::META_DEVICE_ONLY => Dynamic_Selector::DESKTOP, Dynamic_Selector::META_SUFFIX => '%', ], ]; $this->_subscribers['.neve-main > .archive-container .nv-sidebar-wrap'] = [ Config::CSS_PROP_MAX_WIDTH => [ Dynamic_Selector::META_KEY => Config::MODS_ARCHIVE_CONTENT_WIDTH, Dynamic_Selector::META_DEFAULT => $this->sidebar_layout_width_default( Config::MODS_ARCHIVE_CONTENT_WIDTH ), Dynamic_Selector::META_DEVICE_ONLY => Dynamic_Selector::DESKTOP, Dynamic_Selector::META_FILTER => 'minus_100', Dynamic_Selector::META_SUFFIX => '%', ], ]; // Single content width. $this->_subscribers['.neve-main > .single-post-container .nv-single-post-wrap.col'] = [ Config::CSS_PROP_MAX_WIDTH => [ Dynamic_Selector::META_KEY => Config::MODS_SINGLE_CONTENT_WIDTH, Dynamic_Selector::META_DEFAULT => $this->sidebar_layout_width_default( Config::MODS_SINGLE_CONTENT_WIDTH ), Dynamic_Selector::META_DEVICE_ONLY => Dynamic_Selector::DESKTOP, Dynamic_Selector::META_SUFFIX => '%', ], ]; $this->_subscribers['.single-post-container .alignfull > [class*="__inner-container"], .single-post-container .alignwide > [class*="__inner-container"]'] = [ Config::CSS_PROP_MAX_WIDTH => [ Dynamic_Selector::META_KEY => Config::MODS_SINGLE_CONTENT_WIDTH, Dynamic_Selector::META_DEFAULT => $this->sidebar_layout_width_default( Config::MODS_SINGLE_CONTENT_WIDTH ), Dynamic_Selector::META_IS_RESPONSIVE => true, Dynamic_Selector::META_FILTER => function ( $css_prop, $value, $meta, $device ) { $width = Mods::to_json( Config::MODS_CONTAINER_WIDTH ); $value = $device !== Dynamic_Selector::DESKTOP ? ( $width[ $device ] - Config::CONTENT_DEFAULT_PADDING ) : round( ( $value / 100 ) * $width[ $device ] - Config::CONTENT_DEFAULT_PADDING ); return sprintf( 'max-width:%spx', $value ); }, ], ]; $this->_subscribers['.container-fluid.single-post-container .alignfull > [class*="__inner-container"], .container-fluid.single-post-container .alignwide > [class*="__inner-container"]'] = [ Config::CSS_PROP_MAX_WIDTH => [ Dynamic_Selector::META_KEY => Config::MODS_SINGLE_CONTENT_WIDTH, Dynamic_Selector::META_DEFAULT => $this->sidebar_layout_width_default( Config::MODS_SINGLE_CONTENT_WIDTH ), Dynamic_Selector::META_DEVICE_ONLY => Dynamic_Selector::DESKTOP, Dynamic_Selector::META_FILTER => function ( $css_prop, $value, $meta, $device ) { return sprintf( 'max-width:calc(%s%% + %spx)', $value, Config::CONTENT_DEFAULT_PADDING / 2 ); }, ], ]; $this->_subscribers['.neve-main > .single-post-container .nv-sidebar-wrap'] = [ Config::CSS_PROP_MAX_WIDTH => [ Dynamic_Selector::META_KEY => Config::MODS_SINGLE_CONTENT_WIDTH, Dynamic_Selector::META_DEFAULT => $this->sidebar_layout_width_default( Config::MODS_SINGLE_CONTENT_WIDTH ), Dynamic_Selector::META_DEVICE_ONLY => Dynamic_Selector::DESKTOP, Dynamic_Selector::META_FILTER => 'minus_100', Dynamic_Selector::META_SUFFIX => '%', ], ]; // TODO provide context handler for better checks. if ( ! class_exists( 'WooCommerce', false ) ) { return; } $this->_subscribers['.archive.woocommerce .neve-main > .shop-container .nv-shop.col'] = [ Config::CSS_PROP_MAX_WIDTH => [ Dynamic_Selector::META_KEY => Config::MODS_SHOP_ARCHIVE_CONTENT_WIDTH, Dynamic_Selector::META_DEFAULT => $this->sidebar_layout_width_default( Config::MODS_SHOP_ARCHIVE_CONTENT_WIDTH ), Dynamic_Selector::META_DEVICE_ONLY => Dynamic_Selector::DESKTOP, Dynamic_Selector::META_SUFFIX => '%', ], ]; $this->_subscribers['.archive.woocommerce .neve-main > .shop-container .nv-sidebar-wrap'] = [ Config::CSS_PROP_MAX_WIDTH => [ Dynamic_Selector::META_KEY => Config::MODS_SHOP_ARCHIVE_CONTENT_WIDTH, Dynamic_Selector::META_DEFAULT => $this->sidebar_layout_width_default( Config::MODS_SHOP_ARCHIVE_CONTENT_WIDTH ), Dynamic_Selector::META_DEVICE_ONLY => Dynamic_Selector::DESKTOP, Dynamic_Selector::META_FILTER => 'minus_100', Dynamic_Selector::META_SUFFIX => '%', ], ]; $this->_subscribers['.single-product .neve-main > .shop-container .nv-shop.col'] = [ Config::CSS_PROP_MAX_WIDTH => [ Dynamic_Selector::META_KEY => Config::MODS_SHOP_SINGLE_CONTENT_WIDTH, Dynamic_Selector::META_DEFAULT => $this->sidebar_layout_width_default( Config::MODS_SHOP_SINGLE_CONTENT_WIDTH ), Dynamic_Selector::META_DEVICE_ONLY => Dynamic_Selector::DESKTOP, Dynamic_Selector::META_SUFFIX => '%', ], ]; $this->_subscribers['.single-product .alignfull > [class*="__inner-container"], .single-product .alignwide > [class*="__inner-container"]'] = [ Config::CSS_PROP_MAX_WIDTH => [ Dynamic_Selector::META_KEY => Config::MODS_SHOP_SINGLE_CONTENT_WIDTH, Dynamic_Selector::META_DEFAULT => $this->sidebar_layout_width_default( Config::MODS_SHOP_SINGLE_CONTENT_WIDTH ), Dynamic_Selector::META_IS_RESPONSIVE => true, Dynamic_Selector::META_FILTER => function ( $css_prop, $value, $meta, $device ) { $width = Mods::to_json( Config::MODS_CONTAINER_WIDTH ); $value = $device !== Dynamic_Selector::DESKTOP ? ( $width[ $device ] - Config::CONTENT_DEFAULT_PADDING ) : round( ( $value / 100 ) * $width[ $device ] - Config::CONTENT_DEFAULT_PADDING ); return sprintf( 'max-width:%spx', $value ); }, ], ]; $this->_subscribers['.single-product .container-fluid .alignfull > [class*="__inner-container"], .single-product .alignwide > [class*="__inner-container"]'] = [ Config::CSS_PROP_MAX_WIDTH => [ Dynamic_Selector::META_KEY => Config::MODS_SHOP_SINGLE_CONTENT_WIDTH, Dynamic_Selector::META_DEFAULT => $this->sidebar_layout_width_default( Config::MODS_SHOP_SINGLE_CONTENT_WIDTH ), Dynamic_Selector::META_DEVICE_ONLY => Dynamic_Selector::DESKTOP, Dynamic_Selector::META_FILTER => function ( $css_prop, $value, $meta, $device ) { return sprintf( 'max-width:calc(%s%% + %spx)', $value, Config::CONTENT_DEFAULT_PADDING / 2 ); }, ], ]; $this->_subscribers['.single-product .neve-main > .shop-container .nv-sidebar-wrap'] = [ Config::CSS_PROP_MAX_WIDTH => [ Dynamic_Selector::META_KEY => Config::MODS_SHOP_SINGLE_CONTENT_WIDTH, Dynamic_Selector::META_DEFAULT => $this->sidebar_layout_width_default( Config::MODS_SHOP_SINGLE_CONTENT_WIDTH ), Dynamic_Selector::META_DEVICE_ONLY => Dynamic_Selector::DESKTOP, Dynamic_Selector::META_FILTER => 'minus_100', Dynamic_Selector::META_SUFFIX => '%', ], ]; } /** * Adds form field styles */ private function setup_form_fields_style() { if ( ! neve_is_new_skin() ) { $this->setup_legacy_form_fields_style(); return; } $border_width_default = array_fill_keys( Config::$directional_keys, '2' ); $border_radius_default = array_fill_keys( Config::$directional_keys, '3' ); $this->_subscribers[] = [ Dynamic_Selector::KEY_SELECTOR => ':root', Dynamic_Selector::KEY_RULES => [ '--formFieldBorderWidth' => [ Dynamic_Selector::META_KEY => Config::MODS_FORM_FIELDS_BORDER_WIDTH, Dynamic_Selector::META_SUFFIX => 'px', Dynamic_Selector::META_DEFAULT => $border_width_default, 'directional-prop' => Config::CSS_PROP_BORDER_WIDTH, ], '--formFieldBorderRadius' => [ Dynamic_Selector::META_KEY => Config::MODS_FORM_FIELDS_BORDER_RADIUS, Dynamic_Selector::META_SUFFIX => 'px', Dynamic_Selector::META_DEFAULT => $border_radius_default, 'directional-prop' => Config::CSS_PROP_BORDER_RADIUS, ], '--formFieldBgColor' => [ Dynamic_Selector::META_KEY => Config::MODS_FORM_FIELDS_BACKGROUND_COLOR, Dynamic_Selector::META_DEFAULT => 'var(--nv-site-bg)', ], '--formFieldBorderColor' => [ Dynamic_Selector::META_KEY => Config::MODS_FORM_FIELDS_BORDER_COLOR, Dynamic_Selector::META_DEFAULT => '#dddddd', ], '--formFieldColor' => [ Dynamic_Selector::META_KEY => Config::MODS_FORM_FIELDS_COLOR, Dynamic_Selector::META_DEFAULT => 'var(--nv-text-color)', ], '--formFieldPadding' => [ Dynamic_Selector::META_KEY => Config::MODS_FORM_FIELDS_PADDING, Dynamic_Selector::META_DEFAULT => Mods::get_alternative_mod_default( Config::MODS_FORM_FIELDS_PADDING ), Dynamic_Selector::META_SUFFIX => 'px', Dynamic_Selector::META_IS_RESPONSIVE => false, 'directional-prop' => Config::CSS_PROP_PADDING, ], '--formFieldTextTransform' => [ Dynamic_Selector::META_KEY => Config::MODS_FORM_FIELDS_TYPEFACE . '.textTransform', Dynamic_Selector::META_IS_RESPONSIVE => false, ], '--formFieldFontSize' => [ Dynamic_Selector::META_KEY => Config::MODS_FORM_FIELDS_TYPEFACE . '.fontSize', Dynamic_Selector::META_SUFFIX => 'px', Dynamic_Selector::META_IS_RESPONSIVE => true, ], '--formFieldLineHeight' => [ Dynamic_Selector::META_KEY => Config::MODS_FORM_FIELDS_TYPEFACE . '.lineHeight', Dynamic_Selector::META_SUFFIX => '', Dynamic_Selector::META_IS_RESPONSIVE => true, ], '--formFieldLetterSpacing' => [ Dynamic_Selector::META_KEY => Config::MODS_FORM_FIELDS_TYPEFACE . '.letterSpacing', Dynamic_Selector::META_SUFFIX => 'px', Dynamic_Selector::META_IS_RESPONSIVE => true, ], '--formFieldFontWeight' => [ Dynamic_Selector::META_KEY => Config::MODS_FORM_FIELDS_TYPEFACE . '.fontWeight', ], // Form Labels '--formLabelFontSize' => [ Dynamic_Selector::META_KEY => Config::MODS_FORM_FIELDS_LABELS_TYPEFACE . '.fontSize', Dynamic_Selector::META_IS_RESPONSIVE => true, Dynamic_Selector::META_SUFFIX => 'px', ], '--formLabelLineHeight' => [ Dynamic_Selector::META_KEY => Config::MODS_FORM_FIELDS_LABELS_TYPEFACE . '.lineHeight', Dynamic_Selector::META_IS_RESPONSIVE => true, Dynamic_Selector::META_SUFFIX => '', ], '--formLabelLetterSpacing' => [ Dynamic_Selector::META_KEY => Config::MODS_FORM_FIELDS_LABELS_TYPEFACE . '.letterSpacing', Dynamic_Selector::META_IS_RESPONSIVE => true, ], '--formLabelFontWeight' => [ Dynamic_Selector::META_KEY => Config::MODS_FORM_FIELDS_LABELS_TYPEFACE . '.fontWeight', ], '--formLabelTextTransform' => [ Dynamic_Selector::META_KEY => Config::MODS_FORM_FIELDS_LABELS_TYPEFACE . '.textTransform', ], ], ]; // Form button style. Override if needed. $form_buttons_type = get_theme_mod( 'neve_form_button_type', 'primary' ); if ( $form_buttons_type === 'primary' ) { return; } $this->_subscribers[ Config::CSS_SELECTOR_FORM_BUTTON ]['background-color'] = [ 'key' => 'neve_form_button_type', 'override' => 'var(--secondaryBtnBg, transparent)', ]; $this->_subscribers[ Config::CSS_SELECTOR_FORM_BUTTON ]['color'] = [ 'key' => 'neve_form_button_type', 'override' => 'var(--secondaryBtnColor)', ]; $this->_subscribers[ Config::CSS_SELECTOR_FORM_BUTTON ]['padding'] = [ 'key' => 'neve_form_button_type', 'override' => 'var(--secondaryBtnPadding, 7px 12px)', ]; $this->_subscribers[ Config::CSS_SELECTOR_FORM_BUTTON ]['border-radius'] = [ 'key' => 'neve_form_button_type', 'override' => 'var(--secondaryBtnBorderRadius, 3px)', ]; $this->_subscribers[ Config::CSS_SELECTOR_FORM_BUTTON_HOVER ]['background-color'] = [ 'key' => 'neve_form_button_type', 'override' => 'var(--secondaryBtnHoverBg, transparent)', ]; $this->_subscribers[ Config::CSS_SELECTOR_FORM_BUTTON_HOVER ]['color'] = [ 'key' => 'neve_form_button_type', 'override' => 'var(--secondaryBtnHoverColor)', ]; $mod_key_secondary = Config::MODS_BUTTON_SECONDARY_STYLE; $default_secondary = Mods::get_alternative_mod_default( Config::MODS_BUTTON_SECONDARY_STYLE ); $secondary_values = get_theme_mod( $mod_key_secondary, $default_secondary ); if ( ! isset( $secondary_values['type'] ) || $secondary_values['type'] !== 'outline' ) { return; } $this->_subscribers[ Config::CSS_SELECTOR_FORM_BUTTON ]['border-width'] = [ 'key' => 'neve_form_button_type', 'override' => 'var(--secondaryBtnBorderWidth, 3px)', ]; $this->_subscribers[ Config::CSS_SELECTOR_FORM_BUTTON ]['border-color'] = [ 'key' => 'neve_form_button_type', 'override' => 'var(--secondaryBtnHoverColor)', ]; $this->_subscribers[ Config::CSS_SELECTOR_FORM_BUTTON_HOVER ]['border-color'] = [ 'key' => 'neve_form_button_type', 'override' => 'var(--secondaryBtnHoverColor)', ]; } /** * Add form buttons selectors to the Buttons selector. * * @param string $selector the CSS selector received from the filter. * * @return string */ public function add_form_buttons( $selector ) { return ( $selector . ', form input[type="submit"], form button[type="submit"]' ); } /** * Add form buttons hover selectors to the Buttons selector. * * @param string $selector the CSS selector received from the filter. * * @return string */ public function add_form_buttons_hover( $selector ) { return ( $selector . ', form input[type="submit"]:hover, form button[type="submit"]:hover' ); } /** * Add css for blog meta. */ public function setup_blog_meta() { if ( ! neve_is_new_skin() ) { $this->setup_blog_meta_legacy(); return; } $rules = [ '--avatarSize' => [ Dynamic_Selector::META_KEY => Config::MODS_ARCHIVE_POST_META_AUTHOR_AVATAR_SIZE, Dynamic_Selector::META_IS_RESPONSIVE => true, Dynamic_Selector::META_SUFFIX => 'px', Dynamic_Selector::META_DEFAULT => '{ "mobile": 20, "tablet": 20, "desktop": 20 }', ], ]; $rules_single = [ '--avatarSize' => [ Dynamic_Selector::META_KEY => Config::MODS_SINGLE_POST_META_AUTHOR_AVATAR_SIZE, Dynamic_Selector::META_IS_RESPONSIVE => true, Dynamic_Selector::META_SUFFIX => 'px', Dynamic_Selector::META_DEFAULT => Mods::get( 'neve_author_avatar_size', '{ "mobile": 20, "tablet": 20, "desktop": 20 }' ), ], ]; $this->_subscribers[] = [ 'selectors' => '.nv-meta-list', 'rules' => $rules, ]; $this->_subscribers[] = [ 'selectors' => '.single .nv-meta-list', 'rules' => $rules_single, ]; } /** * Add css for blog meta. */ public function setup_blog_meta_legacy() { $meta_key = Config::MODS_ARCHIVE_POST_META_AUTHOR_AVATAR_SIZE; if ( is_singular( 'post' ) ) { $meta_key = Config::MODS_SINGLE_POST_META_AUTHOR_AVATAR_SIZE; } $this->_subscribers[] = [ Dynamic_Selector::KEY_SELECTOR => '.nv-meta-list .meta.author img.photo', Dynamic_Selector::KEY_RULES => [ Config::CSS_PROP_HEIGHT => [ Dynamic_Selector::META_KEY => $meta_key, Dynamic_Selector::META_IS_RESPONSIVE => true, ], Config::CSS_PROP_WIDTH => [ Dynamic_Selector::META_KEY => $meta_key, Dynamic_Selector::META_IS_RESPONSIVE => true, ], ], ]; } /** * Setup legacy form field styles. */ private function setup_legacy_form_fields_style() { $this->_subscribers[ Config::CSS_SELECTOR_FORM_INPUTS ] = [ Config::CSS_PROP_BACKGROUND_COLOR => Config::MODS_FORM_FIELDS_BACKGROUND_COLOR, Config::CSS_PROP_BORDER_WIDTH => Config::MODS_FORM_FIELDS_BORDER_WIDTH, Config::CSS_PROP_BORDER_RADIUS => Config::MODS_FORM_FIELDS_BORDER_RADIUS, Config::CSS_PROP_BORDER_COLOR => Config::MODS_FORM_FIELDS_BORDER_COLOR, Config::CSS_PROP_COLOR => [ Dynamic_Selector::META_KEY => Config::MODS_FORM_FIELDS_COLOR, Dynamic_Selector::META_DEFAULT => 'var(--nv-text-color)', ], Config::CSS_PROP_PADDING => [ Dynamic_Selector::META_KEY => Config::MODS_FORM_FIELDS_PADDING, Dynamic_Selector::META_IS_RESPONSIVE => false, ], Config::CSS_PROP_TEXT_TRANSFORM => [ Dynamic_Selector::META_KEY => Config::MODS_FORM_FIELDS_TYPEFACE . '.textTransform', Dynamic_Selector::META_IS_RESPONSIVE => false, Dynamic_Selector::META_SUFFIX => '', ], Config::CSS_PROP_FONT_SIZE => [ Dynamic_Selector::META_KEY => Config::MODS_FORM_FIELDS_TYPEFACE . '.fontSize', Dynamic_Selector::META_IS_RESPONSIVE => true, Dynamic_Selector::META_SUFFIX => 'px', ], Config::CSS_PROP_LINE_HEIGHT => [ Dynamic_Selector::META_KEY => Config::MODS_FORM_FIELDS_TYPEFACE . '.lineHeight', Dynamic_Selector::META_IS_RESPONSIVE => true, Dynamic_Selector::META_SUFFIX => '', ], Config::CSS_PROP_LETTER_SPACING => [ Dynamic_Selector::META_KEY => Config::MODS_FORM_FIELDS_TYPEFACE . '.letterSpacing', Dynamic_Selector::META_IS_RESPONSIVE => true, ], Config::CSS_PROP_FONT_WEIGHT => [ Dynamic_Selector::META_KEY => Config::MODS_FORM_FIELDS_TYPEFACE . '.fontWeight', ], Config::CSS_PROP_FONT_FAMILY => Config::MODS_FONT_GENERAL, ]; $this->_subscribers[ Config::CSS_SELECTOR_FORM_INPUTS_LABELS ] = [ Config::CSS_PROP_FONT_SIZE => [ Dynamic_Selector::META_KEY => Config::MODS_FORM_FIELDS_LABELS_TYPEFACE . '.fontSize', Dynamic_Selector::META_IS_RESPONSIVE => true, Dynamic_Selector::META_SUFFIX => 'px', ], Config::CSS_PROP_LINE_HEIGHT => [ Dynamic_Selector::META_KEY => Config::MODS_FORM_FIELDS_LABELS_TYPEFACE . '.lineHeight', Dynamic_Selector::META_IS_RESPONSIVE => true, Dynamic_Selector::META_SUFFIX => '', ], Config::CSS_PROP_LETTER_SPACING => [ Dynamic_Selector::META_KEY => Config::MODS_FORM_FIELDS_LABELS_TYPEFACE . '.letterSpacing', Dynamic_Selector::META_IS_RESPONSIVE => true, ], Config::CSS_PROP_FONT_WEIGHT => [ Dynamic_Selector::META_KEY => Config::MODS_FORM_FIELDS_LABELS_TYPEFACE . '.fontWeight', ], Config::CSS_PROP_TEXT_TRANSFORM => [ Dynamic_Selector::META_KEY => Config::MODS_FORM_FIELDS_LABELS_TYPEFACE . '.textTransform', ], ]; $this->_subscribers[ Config::CSS_SELECTOR_FORM_SEARCH_INPUTS ] = [ Config::CSS_PROP_PADDING_RIGHT => [ Dynamic_Selector::META_KEY => Config::MODS_FORM_FIELDS_PADDING . '.right', Dynamic_Selector::META_FILTER => function ( $css_prop, $value, $meta, $device ) { $value = absint( $value ) + 33; return sprintf( '%s:%s !important;', $css_prop, $value . 'px' ); }, Dynamic_Selector::META_DEFAULT => 12, Dynamic_Selector::META_IS_RESPONSIVE => false, ], Config::CSS_PROP_FONT_FAMILY => Config::MODS_FONT_GENERAL, ]; /** * Form buttons. */ $form_buttons_type = get_theme_mod( 'neve_form_button_type', 'primary' ); if ( $form_buttons_type === 'primary' ) { add_filter( 'neve_selectors_' . Config::CSS_SELECTOR_BTN_PRIMARY_NORMAL, [ $this, 'add_form_buttons' ] ); add_filter( 'neve_selectors_' . Config::CSS_SELECTOR_BTN_PRIMARY_PADDING, [ $this, 'add_form_buttons' ] ); add_filter( 'neve_selectors_' . Config::CSS_SELECTOR_BTN_PRIMARY_HOVER, [ $this, 'add_form_buttons_hover', ] ); return; } add_filter( 'neve_selectors_' . Config::CSS_SELECTOR_BTN_SECONDARY_NORMAL, [ $this, 'add_form_buttons' ] ); add_filter( 'neve_selectors_' . Config::CSS_SELECTOR_BTN_SECONDARY_PADDING, [ $this, 'add_form_buttons' ] ); add_filter( 'neve_selectors_' . Config::CSS_SELECTOR_BTN_SECONDARY_HOVER, [ $this, 'add_form_buttons_hover' ] ); } /** * Add css for single post. */ private function setup_single_post_style() { if ( ! neve_is_new_skin() ) { return; } $cover_rules = [ '--height' => [ Dynamic_Selector::META_KEY => Config::MODS_POST_COVER_HEIGHT, Dynamic_Selector::META_IS_RESPONSIVE => true, Dynamic_Selector::META_AS_JSON => true, Dynamic_Selector::META_SUFFIX => 'responsive_suffix', Dynamic_Selector::META_DEFAULT => '{ "mobile": "400", "tablet": "400", "desktop": "400" }', ], '--padding' => [ Dynamic_Selector::META_KEY => Config::MODS_POST_COVER_PADDING, Dynamic_Selector::META_IS_RESPONSIVE => true, Dynamic_Selector::META_DEFAULT => $this->padding_default( 'cover' ), 'directional-prop' => Config::CSS_PROP_PADDING, ], '--vAlign' => [ Dynamic_Selector::META_KEY => Config::MODS_POST_COVER_TITLE_POSITION, Dynamic_Selector::META_IS_RESPONSIVE => true, Dynamic_Selector::META_DEFAULT => [ 'mobile' => 'center', 'tablet' => 'center', 'desktop' => 'center', ], ], ]; $this->_subscribers[] = [ 'selectors' => '.nv-post-cover', 'rules' => $cover_rules, ]; $title_rules = [ '--color' => [ Dynamic_Selector::META_KEY => Config::MODS_POST_COVER_TEXT_COLOR, ], ]; $this->_subscribers[] = [ 'selectors' => '.nv-post-cover .nv-title-meta-wrap', 'rules' => $title_rules, ]; $boxed_title_rules = [ '--padding' => [ Dynamic_Selector::META_KEY => Config::MODS_POST_COVER_BOXED_TITLE_PADDING, Dynamic_Selector::META_IS_RESPONSIVE => true, Dynamic_Selector::META_DEFAULT => $this->padding_default( 'cover' ), 'directional-prop' => Config::CSS_PROP_PADDING, ], '--bgColor' => [ Dynamic_Selector::META_KEY => Config::MODS_POST_COVER_BOXED_TITLE_BACKGROUND, Dynamic_Selector::META_DEFAULT => 'var(--nv-dark-bg)', ], ]; $this->_subscribers[] = [ 'selectors' => '.nv-is-boxed.nv-title-meta-wrap', 'rules' => $boxed_title_rules, ]; $overlay_rules = [ '--bgColor' => [ Dynamic_Selector::META_KEY => Config::MODS_POST_COVER_BACKGROUND_COLOR, ], '--blendMode' => [ Dynamic_Selector::META_KEY => Config::MODS_POST_COVER_BLEND_MODE, ], '--opacity' => [ Dynamic_Selector::META_KEY => Config::MODS_POST_COVER_OVERLAY_OPACITY, Dynamic_Selector::META_DEFAULT => 50, ], ]; $this->_subscribers[] = [ 'selectors' => '.nv-overlay', 'rules' => $overlay_rules, ]; $boxed_comments_rules = [ '--padding' => [ Dynamic_Selector::META_KEY => Config::MODS_POST_COMMENTS_PADDING, Dynamic_Selector::META_IS_RESPONSIVE => true, Dynamic_Selector::META_DEFAULT => $this->padding_default(), 'directional-prop' => Config::CSS_PROP_PADDING, ], '--bgColor' => [ Dynamic_Selector::META_KEY => Config::MODS_POST_COMMENTS_BACKGROUND_COLOR, ], '--color' => [ Dynamic_Selector::META_KEY => Config::MODS_POST_COMMENTS_TEXT_COLOR, ], ]; $this->_subscribers[] = [ 'selectors' => '.nv-is-boxed.nv-comments-wrap', 'rules' => $boxed_comments_rules, ]; $boxed_comment_form_rules = [ '--padding' => [ Dynamic_Selector::META_KEY => Config::MODS_POST_COMMENTS_FORM_PADDING, Dynamic_Selector::META_IS_RESPONSIVE => true, Dynamic_Selector::META_DEFAULT => $this->padding_default(), 'directional-prop' => Config::CSS_PROP_PADDING, ], '--bgColor' => [ Dynamic_Selector::META_KEY => Config::MODS_POST_COMMENTS_FORM_BACKGROUND_COLOR, ], '--color' => [ Dynamic_Selector::META_KEY => Config::MODS_POST_COMMENTS_FORM_TEXT_COLOR, ], ]; $this->_subscribers[] = [ 'selectors' => '.nv-is-boxed.comment-respond', 'rules' => $boxed_comment_form_rules, ]; $spacing_rules = [ '--spacing' => [ Dynamic_Selector::META_KEY => Config::MODS_SINGLE_POST_ELEMENTS_SPACING, Dynamic_Selector::META_IS_RESPONSIVE => true, Dynamic_Selector::META_SUFFIX => 'px', ], ]; $this->_subscribers[] = [ 'selectors' => '.nv-single-post-wrap', 'rules' => $spacing_rules, ]; } /** * Setup legacy blog typography. */ private function setup_legacy_blog_typography() { $archive_typography = array( Config::CSS_SELECTOR_ARCHIVE_POST_TITLE => Config::MODS_TYPEFACE_ARCHIVE_POST_TITLE, Config::CSS_SELECTOR_ARCHIVE_POST_EXCERPT => Config::MODS_TYPEFACE_ARCHIVE_POST_EXCERPT, Config::CSS_SELECTOR_ARCHIVE_POST_META => Config::MODS_TYPEFACE_ARCHIVE_POST_META, Config::CSS_SELECTOR_SINGLE_POST_TITLE => Config::MODS_TYPEFACE_SINGLE_POST_TITLE, Config::CSS_SELECTOR_SINGLE_POST_META => Config::MODS_TYPEFACE_SINGLE_POST_META, Config::CSS_SELECTOR_SINGLE_POST_COMMENT_TITLE => Config::MODS_TYPEFACE_SINGLE_POST_COMMENT_TITLE, ); foreach ( $archive_typography as $selector => $mod ) { $this->_subscribers[ $selector ] = [ Config::CSS_PROP_FONT_SIZE => [ Dynamic_Selector::META_KEY => $mod . '.fontSize', Dynamic_Selector::META_IS_RESPONSIVE => true, Dynamic_Selector::META_SUFFIX => 'px', ], Config::CSS_PROP_LINE_HEIGHT => [ Dynamic_Selector::META_KEY => $mod . '.lineHeight', Dynamic_Selector::META_IS_RESPONSIVE => true, Dynamic_Selector::META_SUFFIX => '', ], Config::CSS_PROP_LETTER_SPACING => [ Dynamic_Selector::META_KEY => $mod . '.letterSpacing', Dynamic_Selector::META_IS_RESPONSIVE => true, ], Config::CSS_PROP_FONT_WEIGHT => [ Dynamic_Selector::META_KEY => $mod . '.fontWeight', ], Config::CSS_PROP_TEXT_TRANSFORM => $mod . '.textTransform', ]; } } }
1
22,226
Can we have a single function here that uses the same subscribers and just changes meta based on context?
Codeinwp-neve
php
@@ -513,8 +513,9 @@ hsa_executable_t load_executable(const string& file, hsa_executable_t executable return executable; } -// To force HIP to load the kernels and to setup the function -// symbol map on program startup +// HIP startup kernel loader logic +// When enabled HIP_STARTUP_LOADER, HIP will load the kernels and setup +// the function symbol map on program startup class startup_kernel_loader { private: startup_kernel_loader() { functions(); }
1
#include "../include/hip/hcc_detail/program_state.hpp" #include "../include/hip/hcc_detail/code_object_bundle.hpp" #include "hip_hcc_internal.h" #include "hsa_helpers.hpp" #include "trace_helper.h" #include "elfio/elfio.hpp" #include <link.h> #include <hsa/hsa.h> #include <hsa/hsa_ext_amd.h> #include <cassert> #include <cstddef> #include <cstdint> #include <memory> #include <mutex> #include <sstream> #include <stdexcept> #include <string> #include <unordered_map> #include <unordered_set> #include <utility> #include <vector> using namespace ELFIO; using namespace hip_impl; using namespace std; namespace { struct Symbol { string name; ELFIO::Elf64_Addr value = 0; Elf_Xword size = 0; Elf_Half sect_idx = 0; uint8_t bind = 0; uint8_t type = 0; uint8_t other = 0; }; inline Symbol read_symbol(const symbol_section_accessor& section, unsigned int idx) { assert(idx < section.get_symbols_num()); Symbol r; section.get_symbol(idx, r.name, r.value, r.size, r.bind, r.type, r.sect_idx, r.other); return r; } template <typename P> inline section* find_section_if(elfio& reader, P p) { const auto it = find_if(reader.sections.begin(), reader.sections.end(), move(p)); return it != reader.sections.end() ? *it : nullptr; } vector<string> copy_names_of_undefined_symbols(const symbol_section_accessor& section) { vector<string> r; for (auto i = 0u; i != section.get_symbols_num(); ++i) { // TODO: this is boyscout code, caching the temporaries // may be of worth. auto tmp = read_symbol(section, i); if (tmp.sect_idx == SHN_UNDEF && !tmp.name.empty()) { r.push_back(std::move(tmp.name)); } } return r; } const std::unordered_map<std::string, std::pair<ELFIO::Elf64_Addr, ELFIO::Elf_Xword>>& symbol_addresses(bool rebuild = false) { static unordered_map<string, pair<Elf64_Addr, Elf_Xword>> r; static once_flag f; auto cons = [rebuild]() { if (rebuild) { r.clear(); } dl_iterate_phdr( [](dl_phdr_info* info, size_t, void*) { static constexpr const char self[] = "/proc/self/exe"; elfio reader; static unsigned int iter = 0u; if (reader.load(!iter ? self : info->dlpi_name)) { auto it = find_section_if( reader, [](const class section* x) { return x->get_type() == SHT_SYMTAB; }); if (it) { const symbol_section_accessor symtab{reader, it}; for (auto i = 0u; i != symtab.get_symbols_num(); ++i) { auto tmp = read_symbol(symtab, i); if (tmp.type == STT_OBJECT && tmp.sect_idx != SHN_UNDEF) { const auto addr = tmp.value + (iter ? info->dlpi_addr : 0); r.emplace(move(tmp.name), make_pair(addr, tmp.size)); } } } ++iter; } return 0; }, nullptr); }; call_once(f, cons); if (rebuild) { cons(); } return r; } void associate_code_object_symbols_with_host_allocation(const elfio& reader, section* code_object_dynsym, hsa_agent_t agent, hsa_executable_t executable) { if (!code_object_dynsym) return; const auto undefined_symbols = copy_names_of_undefined_symbols(symbol_section_accessor{reader, code_object_dynsym}); for (auto&& x : undefined_symbols) { if (globals().find(x) != globals().cend()) return; const auto it1 = symbol_addresses().find(x); if (it1 == symbol_addresses().cend()) { throw runtime_error{"Global symbol: " + x + " is undefined."}; } static mutex mtx; lock_guard<mutex> lck{mtx}; if (globals().find(x) != globals().cend()) return; globals().emplace(x, (void*)(it1->second.first)); void* p = nullptr; hsa_amd_memory_lock(reinterpret_cast<void*>(it1->second.first), it1->second.second, nullptr, // All agents. 0, &p); hsa_executable_agent_global_variable_define(executable, agent, x.c_str(), p); } } vector<char> code_object_blob_for_process() { static constexpr const char self[] = "/proc/self/exe"; static constexpr const char kernel_section[] = ".kernel"; elfio reader; if (!reader.load(self)) { throw runtime_error{"Failed to load ELF file for current process."}; } auto kernels = find_section_if(reader, [](const section* x) { return x->get_name() == kernel_section; }); vector<char> r; if (kernels) { r.insert(r.end(), kernels->get_data(), kernels->get_data() + kernels->get_size()); } return r; } const unordered_map<hsa_isa_t, vector<vector<char>>>& code_object_blobs(bool rebuild = false) { static unordered_map<hsa_isa_t, vector<vector<char>>> r; static once_flag f; auto cons = [rebuild]() { // names of shared libraries who .kernel sections already loaded static unordered_set<string> lib_names; static vector<vector<char>> blobs{code_object_blob_for_process()}; if (rebuild) { r.clear(); blobs.clear(); } dl_iterate_phdr( [](dl_phdr_info* info, std::size_t, void*) { elfio tmp; if ((lib_names.find(info->dlpi_name) == lib_names.end()) && (tmp.load(info->dlpi_name))) { const auto it = find_section_if( tmp, [](const section* x) { return x->get_name() == ".kernel"; }); if (it) { blobs.emplace_back( it->get_data(), it->get_data() + it->get_size()); // register the shared library as already loaded lib_names.emplace(info->dlpi_name); } } return 0; }, nullptr); for (auto&& blob : blobs) { Bundled_code_header tmp{blob}; if (valid(tmp)) { for (auto&& bundle : bundles(tmp)) { r[triple_to_hsa_isa(bundle.triple)].push_back(bundle.blob); } } } }; call_once(f, cons); if (rebuild) { cons(); } return r; } vector<pair<uintptr_t, string>> function_names_for(const elfio& reader, section* symtab) { vector<pair<uintptr_t, string>> r; symbol_section_accessor symbols{reader, symtab}; for (auto i = 0u; i != symbols.get_symbols_num(); ++i) { // TODO: this is boyscout code, caching the temporaries // may be of worth. auto tmp = read_symbol(symbols, i); if (tmp.type == STT_FUNC && tmp.sect_idx != SHN_UNDEF && !tmp.name.empty()) { r.emplace_back(tmp.value, tmp.name); } } return r; } const vector<pair<uintptr_t, string>>& function_names_for_process(bool rebuild = false) { static constexpr const char self[] = "/proc/self/exe"; static vector<pair<uintptr_t, string>> r; static once_flag f; auto cons = [rebuild]() { elfio reader; if (!reader.load(self)) { throw runtime_error{"Failed to load the ELF file for the current process."}; } auto symtab = find_section_if(reader, [](const section* x) { return x->get_type() == SHT_SYMTAB; }); if (symtab) r = function_names_for(reader, symtab); }; call_once(f, cons); if (rebuild) { cons(); } return r; } const unordered_map<string, vector<hsa_executable_symbol_t>>& kernels(bool rebuild = false) { static unordered_map<string, vector<hsa_executable_symbol_t>> r; static once_flag f; auto cons = [rebuild]() { if (rebuild) { r.clear(); executables(rebuild); } static const auto copy_kernels = [](hsa_executable_t, hsa_agent_t, hsa_executable_symbol_t s, void*) { if (type(s) == HSA_SYMBOL_KIND_KERNEL) r[name(s)].push_back(s); return HSA_STATUS_SUCCESS; }; for (auto&& agent_executables : executables()) { for (auto&& executable : agent_executables.second) { hsa_executable_iterate_agent_symbols(executable, agent_executables.first, copy_kernels, nullptr); } } }; call_once(f, cons); if (rebuild) { cons(); } return r; } void load_code_object_and_freeze_executable( const string& file, hsa_agent_t agent, hsa_executable_t executable) { // TODO: the following sequence is inefficient, should be refactored // into a single load of the file and subsequent ELFIO // processing. static const auto cor_deleter = [](hsa_code_object_reader_t* p) { if (p) { hsa_code_object_reader_destroy(*p); delete p; } }; using RAII_code_reader = unique_ptr<hsa_code_object_reader_t, decltype(cor_deleter)>; if (!file.empty()) { RAII_code_reader tmp{new hsa_code_object_reader_t, cor_deleter}; hsa_code_object_reader_create_from_memory(file.data(), file.size(), tmp.get()); hsa_executable_load_agent_code_object(executable, agent, *tmp, nullptr, nullptr); hsa_executable_freeze(executable, nullptr); static vector<RAII_code_reader> code_readers; static mutex mtx; lock_guard<mutex> lck{mtx}; code_readers.push_back(move(tmp)); } } } // namespace namespace hip_impl { const unordered_map<hsa_agent_t, vector<hsa_executable_t>>& executables(bool rebuild) { // TODO: This leaks the hsa_executable_ts, it should use RAII. static unordered_map<hsa_agent_t, vector<hsa_executable_t>> r; static once_flag f; auto cons = [rebuild]() { static const auto accelerators = hc::accelerator::get_all(); if (rebuild) { // do NOT clear r so we reuse instances of hsa_executable_t // created previously code_object_blobs(rebuild); } for (auto&& acc : accelerators) { auto agent = static_cast<hsa_agent_t*>(acc.get_hsa_agent()); if (!agent || !acc.is_hsa_accelerator()) continue; hsa_agent_iterate_isas(*agent, [](hsa_isa_t x, void* pa) { const auto it = code_object_blobs().find(x); if (it != code_object_blobs().cend()) { hsa_agent_t a = *static_cast<hsa_agent_t*>(pa); for (auto&& blob : it->second) { hsa_executable_t tmp = {}; hsa_executable_create_alt( HSA_PROFILE_FULL, HSA_DEFAULT_FLOAT_ROUNDING_MODE_DEFAULT, nullptr, &tmp); // TODO: this is massively inefficient and only // meant for illustration. string blob_to_str{blob.cbegin(), blob.cend()}; tmp = load_executable(blob_to_str, tmp, a); if (tmp.handle) r[a].push_back(tmp); } } return HSA_STATUS_SUCCESS; }, agent); } }; call_once(f, cons); if (rebuild) { cons(); } return r; } const unordered_map<uintptr_t, string>& function_names(bool rebuild) { static unordered_map<uintptr_t, string> r{function_names_for_process().cbegin(), function_names_for_process().cend()}; static once_flag f; auto cons = [rebuild]() { if (rebuild) { r.clear(); function_names_for_process(rebuild); r.insert(function_names_for_process().cbegin(), function_names_for_process().cend()); } dl_iterate_phdr( [](dl_phdr_info* info, size_t, void*) { elfio tmp; if (tmp.load(info->dlpi_name)) { const auto it = find_section_if( tmp, [](const section* x) { return x->get_type() == SHT_SYMTAB; }); if (it) { auto n = function_names_for(tmp, it); for (auto&& f : n) f.first += info->dlpi_addr; r.insert(make_move_iterator(n.begin()), make_move_iterator(n.end())); } } return 0; }, nullptr); }; call_once(f, cons); if (rebuild) { static mutex mtx; lock_guard<mutex> lck{mtx}; cons(); } return r; } const unordered_map<uintptr_t, vector<pair<hsa_agent_t, Kernel_descriptor>>>& functions(bool rebuild) { static unordered_map<uintptr_t, vector<pair<hsa_agent_t, Kernel_descriptor>>> r; static once_flag f; auto cons = [rebuild]() { if (rebuild) { // do NOT clear r so we reuse instances of pair<hsa_agent_t, Kernel_descriptor> // created previously function_names(rebuild); kernels(rebuild); globals(rebuild); } for (auto&& function : function_names()) { const auto it = kernels().find(function.second); if (it != kernels().cend()) { for (auto&& kernel_symbol : it->second) { r[function.first].emplace_back( agent(kernel_symbol), Kernel_descriptor{kernel_object(kernel_symbol), it->first}); } } } }; call_once(f, cons); if (rebuild) { static mutex mtx; lock_guard<mutex> lck{mtx}; cons(); } return r; } unordered_map<string, void*>& globals(bool rebuild) { static unordered_map<string, void*> r; static once_flag f; auto cons =[rebuild]() { if (rebuild) { r.clear(); symbol_addresses(rebuild); } r.reserve(symbol_addresses().size()); }; call_once(f, cons); if (rebuild) { cons(); } return r; } hsa_executable_t load_executable(const string& file, hsa_executable_t executable, hsa_agent_t agent) { elfio reader; stringstream tmp{file}; if (!reader.load(tmp)) return hsa_executable_t{}; const auto code_object_dynsym = find_section_if( reader, [](const ELFIO::section* x) { return x->get_type() == SHT_DYNSYM; }); associate_code_object_symbols_with_host_allocation(reader, code_object_dynsym, agent, executable); load_code_object_and_freeze_executable(file, agent, executable); return executable; } // To force HIP to load the kernels and to setup the function // symbol map on program startup class startup_kernel_loader { private: startup_kernel_loader() { functions(); } startup_kernel_loader(const startup_kernel_loader&) = delete; startup_kernel_loader& operator=(const startup_kernel_loader&) = delete; static startup_kernel_loader skl; }; startup_kernel_loader startup_kernel_loader::skl; } // Namespace hip_impl.
1
7,046
where would ` static startup_kernel_loader skl;` be instantiated? if it's not instantiated anywhere should this be removed?
ROCm-Developer-Tools-HIP
cpp
@@ -0,0 +1,14 @@ +const webkitGetAsEntryApi = require('./utils/webkitGetAsEntryApi') +const getFilesAndDirectoriesApi = require('./utils/getFilesAndDirectoriesApi') +const fallbackApi = require('./utils/fallbackApi') + +module.exports = function getDroppedFiles (dataTransfer, callback) { + if (dataTransfer.items[0] && 'webkitGetAsEntry' in dataTransfer.items[0]) { + webkitGetAsEntryApi(dataTransfer, callback) + } else if ('getFilesAndDirectories' in dataTransfer) { + // Doesn't actually work in firefox, maybe in previous versions. webkitGetAsEntryApi() works. + getFilesAndDirectoriesApi(dataTransfer, callback) + } else { + fallbackApi(dataTransfer, callback) + } +}
1
1
11,592
I think we should move those util functions that work with drag-drop to @uppy/utils, so they can be shared (maybe later) with drag-drop plugin? Otherwise it will continue to depend on drag-drop module.
transloadit-uppy
js
@@ -732,12 +732,6 @@ func (m *Volume) Contains(mid string) bool { // Copy makes a deep copy of VolumeSpec func (s *VolumeSpec) Copy() *VolumeSpec { spec := *s - if s.VolumeLabels != nil { - spec.VolumeLabels = make(map[string]string) - for k, v := range s.VolumeLabels { - spec.VolumeLabels[k] = v - } - } if s.ReplicaSet != nil { spec.ReplicaSet = &ReplicaSet{Nodes: make([]string, len(s.ReplicaSet.Nodes))} copy(spec.ReplicaSet.Nodes, s.ReplicaSet.Nodes)
1
package api import ( "fmt" "math" "strconv" "strings" "time" "github.com/golang/protobuf/ptypes" "github.com/mohae/deepcopy" ) // Strings for VolumeSpec const ( Name = "name" Token = "token" SpecNodes = "nodes" SpecParent = "parent" SpecEphemeral = "ephemeral" SpecShared = "shared" SpecJournal = "journal" SpecSharedv4 = "sharedv4" SpecCascaded = "cascaded" SpecSticky = "sticky" SpecSecure = "secure" SpecCompressed = "compressed" SpecSize = "size" SpecScale = "scale" SpecFilesystem = "fs" SpecBlockSize = "block_size" SpecQueueDepth = "queue_depth" SpecHaLevel = "repl" SpecPriority = "io_priority" SpecSnapshotInterval = "snap_interval" SpecSnapshotSchedule = "snap_schedule" SpecAggregationLevel = "aggregation_level" SpecDedupe = "dedupe" SpecPassphrase = "secret_key" SpecAutoAggregationValue = "auto" SpecGroup = "group" SpecGroupEnforce = "fg" SpecZones = "zones" SpecRacks = "racks" SpecRack = "rack" SpecRegions = "regions" SpecLabels = "labels" SpecPriorityAlias = "priority_io" SpecIoProfile = "io_profile" SpecAsyncIo = "async_io" SpecEarlyAck = "early_ack" // SpecBestEffortLocationProvisioning default is false. If set provisioning request will succeed // even if specified data location parameters could not be satisfied. SpecBestEffortLocationProvisioning = "best_effort_location_provisioning" // SpecForceUnsuppportedFsType is of type boolean and if true it sets // the VolumeSpec.force_unsupported_fs_type. When set to true it asks // the driver to use an unsupported value of VolumeSpec.format if possible SpecForceUnsupportedFsType = "force_unsupported_fs_type" ) // OptionKey specifies a set of recognized query params. const ( // OptName query parameter used to lookup volume by name. OptName = "Name" // OptVolumeID query parameter used to lookup volume by ID. OptVolumeID = "VolumeID" // OptSnapID query parameter used to lookup snapshot by ID. OptSnapID = "SnapID" // OptLabel query parameter used to lookup volume by set of labels. OptLabel = "Label" // OptConfigLabel query parameter used to lookup volume by set of labels. OptConfigLabel = "ConfigLabel" // OptCumulative query parameter used to request cumulative stats. OptCumulative = "Cumulative" // OptTimeout query parameter used to indicate timeout seconds OptTimeoutSec = "TimeoutSec" // OptQuiesceID query parameter use for quiesce OptQuiesceID = "QuiesceID" // OptCredUUID is the UUID of the credential OptCredUUID = "CredUUID" // OptCredName indicates unique name of credential OptCredName = "CredName" // OptCredType indicates type of credential OptCredType = "CredType" // OptCredEncrKey is the key used to encrypt data OptCredEncrKey = "CredEncrypt" // OptCredRegion indicates the region for s3 OptCredRegion = "CredRegion" // OptCredDisableSSL indicated if SSL should be disabled OptCredDisableSSL = "CredDisableSSL" // OptCredEndpoint indicate the cloud endpoint OptCredEndpoint = "CredEndpoint" // OptCredAccKey for s3 OptCredAccessKey = "CredAccessKey" // OptCredSecretKey for s3 OptCredSecretKey = "CredSecretKey" // OptCredBucket is the optional bucket name OptCredBucket = "CredBucket" // OptCredGoogleProjectID projectID for google cloud OptCredGoogleProjectID = "CredProjectID" // OptCredGoogleJsonKey for google cloud OptCredGoogleJsonKey = "CredJsonKey" // OptCredAzureAccountName is the account name for // azure as the cloud provider OptCredAzureAccountName = "CredAccountName" // OptOptCredAzureAccountKey is the accountkey for // azure as the cloud provider OptCredAzureAccountKey = "CredAccountKey" // OptCloudBackupID is the backID in the cloud OptCloudBackupID = "CloudBackID" // OptSrcVolID is the source volume ID of the backup OptSrcVolID = "SrcVolID" // OptBkupOpState is the desired operational state // (stop/pause/resume) of backup/restore OptBkupOpState = "OpState" // OptBackupSchedUUID is the UUID of the backup-schedule OptBackupSchedUUID = "BkupSchedUUID" // OptVolumeSubFolder query parameter used to catalog a particular path inside a volume OptCatalogSubFolder = "subfolder" // OptCatalogMaxDepth query parameter used to limit the depth we return OptCatalogMaxDepth = "depth" ) // Api clientserver Constants const ( OsdVolumePath = "osd-volumes" OsdSnapshotPath = "osd-snapshot" OsdCredsPath = "osd-creds" OsdBackupPath = "osd-backup" OsdMigratePath = "osd-migrate" OsdMigrateStartPath = OsdMigratePath + "/start" OsdMigrateCancelPath = OsdMigratePath + "/cancel" OsdMigrateStatusPath = OsdMigratePath + "/status" TimeLayout = "Jan 2 15:04:05 UTC 2006" ) const ( // AutoAggregation value indicates driver to select aggregation level. AutoAggregation = math.MaxUint32 ) // Node describes the state of a node. // It includes the current physical state (CPU, memory, storage, network usage) as // well as the containers running on the system. // // swagger:model type Node struct { // Id of the node. Id string // SchedulerNodeName is name of the node in scheduler context. It can be // empty if unable to get the name from the scheduler. SchedulerNodeName string // Cpu usage of the node. Cpu float64 // percentage. // Total Memory of the node MemTotal uint64 // Used Memory of the node MemUsed uint64 // Free Memory of the node MemFree uint64 // Average load (percentage) Avgload int // Node Status see (Status object) Status Status // GenNumber of the node GenNumber uint64 // List of disks on this node. Disks map[string]StorageResource // List of storage pools this node supports Pools []StoragePool // Management IP MgmtIp string // Data IP DataIp string // Timestamp Timestamp time.Time // Start time of this node StartTime time.Time // Hostname of this node Hostname string // Node data for this node (EX: Public IP, Provider, City..) NodeData map[string]interface{} // User defined labels for node. Key Value pairs NodeLabels map[string]string // GossipPort is the port used by the gossip protocol GossipPort string } // FluentDConfig describes ip and port of a fluentdhost. // DEPRECATED // // swagger:model type FluentDConfig struct { IP string `json:"ip"` Port string `json:"port"` } // TunnelConfig describes key, cert and endpoint of a reverse proxy tunnel // DEPRECATED // // swagger:model type TunnelConfig struct { Key string `json:"key"` Cert string `json:"cert"` Endpoint string `json:"tunnel_endpoint"` } // Cluster represents the state of the cluster. // // swagger:model type Cluster struct { Status Status // Id of the cluster. // // required: true Id string // Id of the node on which this cluster object is initialized NodeId string // array of all the nodes in the cluster. Nodes []Node // Logging url for the cluster. LoggingURL string // Management url for the cluster ManagementURL string // FluentD Host for the cluster FluentDConfig FluentDConfig // TunnelConfig for the cluster [key, cert, endpoint] TunnelConfig TunnelConfig } // CredCreateRequest is the input for CredCreate command type CredCreateRequest struct { // InputParams is map describing cloud provide InputParams map[string]string } // CredCreateResponse is returned for CredCreate command type CredCreateResponse struct { // UUID of the credential that was just created UUID string } // StatPoint represents the basic structure of a single Stat reported // TODO: This is the first step to introduce stats in openstorage. // Follow up task is to introduce an API for logging stats type StatPoint struct { // Name of the Stat Name string // Tags for the Stat Tags map[string]string // Fields and values of the stat Fields map[string]interface{} // Timestamp in Unix format Timestamp int64 } type CloudBackupCreateRequest struct { // VolumeID of the volume for which cloudbackup is requested VolumeID string // CredentialUUID is cloud credential to be used for backup CredentialUUID string // Full indicates if full backup is desired even though incremental is possible Full bool // Name is optional unique id to be used for this backup // If not specified backup creates this by default Name string // Labels are list of key value pairs to tag the cloud backup. These labels // are stored in the metadata associated with the backup. Labels map[string]string } type CloudBackupCreateResponse struct { // Name of the task performing this backup Name string } type CloudBackupGroupCreateRequest struct { // GroupID indicates backup request for a volumegroup with this group id GroupID string // Labels indicates backup request for a volume group with these labels Labels map[string]string // VolumeIDs are a list of volume IDs to use for the backup request // If multiple of GroupID, Labels or VolumeIDs are specified, volumes matching all of // them are backed up to cloud VolumeIDs []string // CredentialUUID is cloud credential to be used for backup CredentialUUID string // Full indicates if full backup is desired even though incremental is possible Full bool } type CloudBackupRestoreRequest struct { // ID is the backup ID being restored ID string // RestoreVolumeName is optional volume Name of the new volume to be created // in the cluster for restoring the cloudbackup RestoreVolumeName string // CredentialUUID is the credential to be used for restore operation CredentialUUID string // NodeID is the optional NodeID for provisioning restore // volume (ResoreVolumeName should not be specified) NodeID string // Name is optional unique id to be used for this restore op // restore creates this by default Name string } type CloudBackupRestoreResponse struct { // RestoreVolumeID is the volumeID to which the backup is being restored RestoreVolumeID string // Name of the task performing this restore Name string } type CloudBackupGenericRequest struct { // SrcVolumeID is optional Source VolumeID for the request SrcVolumeID string // ClusterID is the optional clusterID for the request ClusterID string // CredentialUUID is the credential for cloud to be used for the request CredentialUUID string // All if set to true, backups for all clusters in the cloud are processed All bool } type CloudBackupInfo struct { // ID is the ID of the cloud backup ID string // SrcVolumeID is Source volumeID of the backup SrcVolumeID string // SrcvolumeName is name of the sourceVolume of the backup SrcVolumeName string // Timestamp is the timestamp at which the source volume // was backed up to cloud Timestamp time.Time // Metadata associated with the backup Metadata map[string]string // Status indicates the status of the backup Status string } type CloudBackupEnumerateRequest struct { CloudBackupGenericRequest } type CloudBackupEnumerateResponse struct { // Backups is list of backups in cloud for given volume/cluster/s Backups []CloudBackupInfo } type CloudBackupDeleteRequest struct { // ID is the ID of the cloud backup ID string // CredentialUUID is the credential for cloud to be used for the request CredentialUUID string // Force Delete cloudbackup even if there are dependencies Force bool } type CloudBackupDeleteAllRequest struct { CloudBackupGenericRequest } type CloudBackupStatusRequest struct { // SrcVolumeID optional volumeID to list status of backup/restore SrcVolumeID string // Local indicates if only those backups/restores that are // active on current node must be returned Local bool // Name of the backup/restore task. If this is specified, SrcVolumeID is // ignored Name string } type CloudBackupOpType string const ( CloudBackupOp = CloudBackupOpType("Backup") CloudRestoreOp = CloudBackupOpType("Restore") ) type CloudBackupStatusType string const ( CloudBackupStatusNotStarted = CloudBackupStatusType("NotStarted") CloudBackupStatusDone = CloudBackupStatusType("Done") CloudBackupStatusAborted = CloudBackupStatusType("Aborted") CloudBackupStatusPaused = CloudBackupStatusType("Paused") CloudBackupStatusStopped = CloudBackupStatusType("Stopped") CloudBackupStatusActive = CloudBackupStatusType("Active") CloudBackupStatusQueued = CloudBackupStatusType("Queued") CloudBackupStatusFailed = CloudBackupStatusType("Failed") ) const ( CloudBackupRequestedStatePause = "pause" CloudBackupRequestedStateResume = "resume" CloudBackupRequestedStateStop = "stop" ) type CloudBackupStatus struct { // ID is the ID for the operation ID string // OpType indicates if this is a backup or restore OpType CloudBackupOpType // State indicates if the op is currently active/done/failed Status CloudBackupStatusType // BytesDone indicates Bytes uploaded/downloaded so far BytesDone uint64 // BytesTotal is the total number of bytes being transferred BytesTotal uint64 // EtaSeconds estimated time in seconds for backup/restore completion EtaSeconds int64 // StartTime indicates Op's start time StartTime time.Time // CompletedTime indicates Op's completed time CompletedTime time.Time // NodeID is the ID of the node where this Op is active NodeID string // SrcVolumeID is either the volume being backed-up or target volume to // which a cloud backup is being restored SrcVolumeID string // Info currently indicates only failure cause in case of failed backup/restore Info []string // CredentialUUID used for this backup/restore op CredentialUUID string } type CloudBackupStatusResponse struct { // statuses is list of currently active/failed/done backup/restores // map key is the id of the task Statuses map[string]CloudBackupStatus } type CloudBackupCatalogRequest struct { // ID is Backup ID in the cloud ID string // CredentialUUID is the credential for cloud CredentialUUID string } type CloudBackupCatalogResponse struct { // Contents is listing of backup contents Contents []string } type CloudBackupHistoryRequest struct { // SrcVolumeID is volumeID for which history of backup/restore // is being requested SrcVolumeID string } type CloudBackupHistoryItem struct { // SrcVolumeID is volume ID which was backedup SrcVolumeID string // TimeStamp is the time at which either backup completed/failed Timestamp time.Time // Status indicates whether backup was completed/failed Status string } type CloudBackupHistoryResponse struct { // HistoryList is list of past backup/restores in the cluster HistoryList []CloudBackupHistoryItem } type CloudBackupStateChangeRequest struct { // Name of the backup/restore task for which state change // is being requested Name string // RequestedState is desired state of the op // can be pause/resume/stop RequestedState string } type CloudBackupScheduleInfo struct { // SrcVolumeID is the schedule's source volume SrcVolumeID string // CredentialUUID is the cloud credential used with this schedule CredentialUUID string // Schedule is the frequence of backup Schedule string // MaxBackups are the maximum number of backups retained // in cloud.Older backups are deleted MaxBackups uint // GroupID indicates the group of volumes for this cloudbackup schedule GroupID string // Labels indicates a volume group for this cloudsnap schedule Labels map[string]string // Full indicates if scheduled backups must be full always Full bool } type CloudBackupSchedCreateRequest struct { CloudBackupScheduleInfo } type CloudBackupGroupSchedCreateRequest struct { // GroupID indicates the group of volumes for which cloudbackup schedule is // being created GroupID string // Labels indicates a volume group for which this group cloudsnap schedule is // being created. If this is provided GroupId is not needed and vice-versa. Labels map[string]string // VolumeIDs are a list of volume IDs to use for the backup request // If multiple of GroupID, Labels or VolumeIDs are specified, volumes matching all of // them are backed up to cloud VolumeIDs []string // CredentialUUID is cloud credential to be used with this schedule CredentialUUID string // Schedule is the frequency of backup Schedule string // MaxBackups are the maximum number of backups retained // in cloud.Older backups are deleted MaxBackups uint // Full indicates if scheduled backups must be full always Full bool } type CloudBackupSchedCreateResponse struct { // UUID is the UUID of the newly created schedule UUID string } type CloudBackupSchedDeleteRequest struct { // UUID is UUID of the schedule to be deleted UUID string } type CloudBackupSchedEnumerateResponse struct { // Schedule is map of schedule uuid to scheduleInfo Schedules map[string]CloudBackupScheduleInfo } // Defines the response for CapacityUsage request type CapacityUsageResponse struct { CapacityUsageInfo *CapacityUsageInfo // Describes the err if all of the usage details could not be obtained Error error } // // DriverTypeSimpleValueOf returns the string format of DriverType func DriverTypeSimpleValueOf(s string) (DriverType, error) { obj, err := simpleValueOf("driver_type", DriverType_value, s) return DriverType(obj), err } // SimpleString returns the string format of DriverType func (x DriverType) SimpleString() string { return simpleString("driver_type", DriverType_name, int32(x)) } // FSTypeSimpleValueOf returns the string format of FSType func FSTypeSimpleValueOf(s string) (FSType, error) { obj, err := simpleValueOf("fs_type", FSType_value, s) return FSType(obj), err } // SimpleString returns the string format of DriverType func (x FSType) SimpleString() string { return simpleString("fs_type", FSType_name, int32(x)) } // CosTypeSimpleValueOf returns the string format of CosType func CosTypeSimpleValueOf(s string) (CosType, error) { obj, exists := CosType_value[strings.ToUpper(s)] if !exists { return -1, fmt.Errorf("Invalid cos value: %s", s) } return CosType(obj), nil } // SimpleString returns the string format of CosType func (x CosType) SimpleString() string { return simpleString("cos_type", CosType_name, int32(x)) } // GraphDriverChangeTypeSimpleValueOf returns the string format of GraphDriverChangeType func GraphDriverChangeTypeSimpleValueOf(s string) (GraphDriverChangeType, error) { obj, err := simpleValueOf("graph_driver_change_type", GraphDriverChangeType_value, s) return GraphDriverChangeType(obj), err } // SimpleString returns the string format of GraphDriverChangeType func (x GraphDriverChangeType) SimpleString() string { return simpleString("graph_driver_change_type", GraphDriverChangeType_name, int32(x)) } // VolumeActionParamSimpleValueOf returns the string format of VolumeAction func VolumeActionParamSimpleValueOf(s string) (VolumeActionParam, error) { obj, err := simpleValueOf("volume_action_param", VolumeActionParam_value, s) return VolumeActionParam(obj), err } // SimpleString returns the string format of VolumeAction func (x VolumeActionParam) SimpleString() string { return simpleString("volume_action_param", VolumeActionParam_name, int32(x)) } // VolumeStateSimpleValueOf returns the string format of VolumeState func VolumeStateSimpleValueOf(s string) (VolumeState, error) { obj, err := simpleValueOf("volume_state", VolumeState_value, s) return VolumeState(obj), err } // SimpleString returns the string format of VolumeState func (x VolumeState) SimpleString() string { return simpleString("volume_state", VolumeState_name, int32(x)) } // VolumeStatusSimpleValueOf returns the string format of VolumeStatus func VolumeStatusSimpleValueOf(s string) (VolumeStatus, error) { obj, err := simpleValueOf("volume_status", VolumeStatus_value, s) return VolumeStatus(obj), err } // SimpleString returns the string format of VolumeStatus func (x VolumeStatus) SimpleString() string { return simpleString("volume_status", VolumeStatus_name, int32(x)) } // IoProfileSimpleValueOf returns the string format of IoProfile func IoProfileSimpleValueOf(s string) (IoProfile, error) { obj, err := simpleValueOf("io_profile", IoProfile_value, s) return IoProfile(obj), err } // SimpleString returns the string format of IoProfile func (x IoProfile) SimpleString() string { return simpleString("io_profile", IoProfile_name, int32(x)) } func simpleValueOf(typeString string, valueMap map[string]int32, s string) (int32, error) { obj, ok := valueMap[strings.ToUpper(fmt.Sprintf("%s_%s", typeString, s))] if !ok { return 0, fmt.Errorf("no openstorage.%s for %s", strings.ToUpper(typeString), s) } return obj, nil } func simpleString(typeString string, nameMap map[int32]string, v int32) string { s, ok := nameMap[v] if !ok { return strconv.Itoa(int(v)) } return strings.TrimPrefix(strings.ToLower(s), fmt.Sprintf("%s_", strings.ToLower(typeString))) } func toSec(ms uint64) uint64 { return ms / 1000 } // WriteThroughput returns the write throughput func (v *Stats) WriteThroughput() uint64 { intv := toSec(v.IntervalMs) if intv == 0 { return 0 } return (v.WriteBytes) / intv } // ReadThroughput returns the read throughput func (v *Stats) ReadThroughput() uint64 { intv := toSec(v.IntervalMs) if intv == 0 { return 0 } return (v.ReadBytes) / intv } // Latency returns latency func (v *Stats) Latency() uint64 { ops := v.Writes + v.Reads if ops == 0 { return 0 } return (uint64)((v.IoMs * 1000) / ops) } // Read latency returns avg. time required for read operation to complete func (v *Stats) ReadLatency() uint64 { if v.Reads == 0 { return 0 } return (uint64)((v.ReadMs * 1000) / v.Reads) } // Write latency returns avg. time required for write operation to complete func (v *Stats) WriteLatency() uint64 { if v.Writes == 0 { return 0 } return (uint64)((v.WriteMs * 1000) / v.Writes) } // Iops returns iops func (v *Stats) Iops() uint64 { intv := toSec(v.IntervalMs) if intv == 0 { return 0 } return (v.Writes + v.Reads) / intv } // Scaled returns true if the volume is scaled. func (v *Volume) Scaled() bool { return v.Spec.Scale > 1 } // Contains returns true if mid is a member of volume's replication set. func (m *Volume) Contains(mid string) bool { rsets := m.GetReplicaSets() for _, rset := range rsets { for _, node := range rset.Nodes { if node == mid { return true } } } return false } // Copy makes a deep copy of VolumeSpec func (s *VolumeSpec) Copy() *VolumeSpec { spec := *s if s.VolumeLabels != nil { spec.VolumeLabels = make(map[string]string) for k, v := range s.VolumeLabels { spec.VolumeLabels[k] = v } } if s.ReplicaSet != nil { spec.ReplicaSet = &ReplicaSet{Nodes: make([]string, len(s.ReplicaSet.Nodes))} copy(spec.ReplicaSet.Nodes, s.ReplicaSet.Nodes) } return &spec } // Copy makes a deep copy of Node func (s *Node) Copy() *Node { localCopy := deepcopy.Copy(*s) nodeCopy := localCopy.(Node) return &nodeCopy } func (v Volume) IsClone() bool { return v.Source != nil && len(v.Source.Parent) != 0 && !v.Readonly } func (v Volume) IsSnapshot() bool { return v.Source != nil && len(v.Source.Parent) != 0 && v.Readonly } func (v Volume) DisplayId() string { if v.Locator != nil { return fmt.Sprintf("%s (%s)", v.Locator.Name, v.Id) } else { return v.Id } } // ToStorageNode converts a Node structure to an exported gRPC StorageNode struct func (s *Node) ToStorageNode() *StorageNode { node := &StorageNode{ Id: s.Id, SchedulerNodeName: s.SchedulerNodeName, Cpu: s.Cpu, MemTotal: s.MemTotal, MemUsed: s.MemUsed, MemFree: s.MemFree, AvgLoad: int64(s.Avgload), Status: s.Status, MgmtIp: s.MgmtIp, DataIp: s.DataIp, Hostname: s.Hostname, } node.Disks = make(map[string]*StorageResource) for k, v := range s.Disks { node.Disks[k] = &v } node.NodeLabels = make(map[string]string) for k, v := range s.NodeLabels { node.NodeLabels[k] = v } node.Pools = make([]*StoragePool, len(s.Pools)) for i, v := range s.Pools { node.Pools[i] = &v } return node } // ToStorageCluster converts a Cluster structure to an exported gRPC StorageCluster struct func (c *Cluster) ToStorageCluster() *StorageCluster { cluster := &StorageCluster{ Status: c.Status, // Due to history, the cluster ID is normally the name of the cluster, not the // unique identifier Name: c.Id, } return cluster } func CloudBackupStatusTypeToSdkCloudBackupStatusType( t CloudBackupStatusType, ) SdkCloudBackupStatusType { switch t { case CloudBackupStatusNotStarted: return SdkCloudBackupStatusType_SdkCloudBackupStatusTypeNotStarted case CloudBackupStatusDone: return SdkCloudBackupStatusType_SdkCloudBackupStatusTypeDone case CloudBackupStatusAborted: return SdkCloudBackupStatusType_SdkCloudBackupStatusTypeAborted case CloudBackupStatusPaused: return SdkCloudBackupStatusType_SdkCloudBackupStatusTypePaused case CloudBackupStatusStopped: return SdkCloudBackupStatusType_SdkCloudBackupStatusTypeStopped case CloudBackupStatusActive: return SdkCloudBackupStatusType_SdkCloudBackupStatusTypeActive case CloudBackupStatusFailed: return SdkCloudBackupStatusType_SdkCloudBackupStatusTypeFailed default: return SdkCloudBackupStatusType_SdkCloudBackupStatusTypeUnknown } } func StringToSdkCloudBackupStatusType(s string) SdkCloudBackupStatusType { return CloudBackupStatusTypeToSdkCloudBackupStatusType(CloudBackupStatusType(s)) } func (b *CloudBackupInfo) ToSdkCloudBackupInfo() *SdkCloudBackupInfo { info := &SdkCloudBackupInfo{ Id: b.ID, SrcVolumeId: b.SrcVolumeID, SrcVolumeName: b.SrcVolumeName, Metadata: b.Metadata, } info.Timestamp, _ = ptypes.TimestampProto(b.Timestamp) info.Status = StringToSdkCloudBackupStatusType(b.Status) return info } func (r *CloudBackupEnumerateResponse) ToSdkCloudBackupEnumerateWithFiltersResponse() *SdkCloudBackupEnumerateWithFiltersResponse { resp := &SdkCloudBackupEnumerateWithFiltersResponse{ Backups: make([]*SdkCloudBackupInfo, len(r.Backups)), } for i, v := range r.Backups { resp.Backups[i] = v.ToSdkCloudBackupInfo() } return resp } func CloudBackupOpTypeToSdkCloudBackupOpType(t CloudBackupOpType) SdkCloudBackupOpType { switch t { case CloudBackupOp: return SdkCloudBackupOpType_SdkCloudBackupOpTypeBackupOp case CloudRestoreOp: return SdkCloudBackupOpType_SdkCloudBackupOpTypeRestoreOp default: return SdkCloudBackupOpType_SdkCloudBackupOpTypeUnknown } } func StringToSdkCloudBackupOpType(s string) SdkCloudBackupOpType { return CloudBackupOpTypeToSdkCloudBackupOpType(CloudBackupOpType(s)) } func (s CloudBackupStatus) ToSdkCloudBackupStatus() *SdkCloudBackupStatus { status := &SdkCloudBackupStatus{ BackupId: s.ID, Optype: CloudBackupOpTypeToSdkCloudBackupOpType(s.OpType), Status: CloudBackupStatusTypeToSdkCloudBackupStatusType(s.Status), BytesDone: s.BytesDone, NodeId: s.NodeID, Info: s.Info, CredentialId: s.CredentialUUID, SrcVolumeId: s.SrcVolumeID, EtaSeconds: s.EtaSeconds, BytesTotal: s.BytesTotal, } status.StartTime, _ = ptypes.TimestampProto(s.StartTime) status.CompletedTime, _ = ptypes.TimestampProto(s.CompletedTime) return status } func (r *CloudBackupStatusResponse) ToSdkCloudBackupStatusResponse() *SdkCloudBackupStatusResponse { resp := &SdkCloudBackupStatusResponse{ Statuses: make(map[string]*SdkCloudBackupStatus), } for k, v := range r.Statuses { resp.Statuses[k] = v.ToSdkCloudBackupStatus() } return resp } func (h CloudBackupHistoryItem) ToSdkCloudBackupHistoryItem() *SdkCloudBackupHistoryItem { item := &SdkCloudBackupHistoryItem{ SrcVolumeId: h.SrcVolumeID, Status: StringToSdkCloudBackupStatusType(h.Status), } item.Timestamp, _ = ptypes.TimestampProto(h.Timestamp) return item } func (r *CloudBackupHistoryResponse) ToSdkCloudBackupHistoryResponse() *SdkCloudBackupHistoryResponse { resp := &SdkCloudBackupHistoryResponse{ HistoryList: make([]*SdkCloudBackupHistoryItem, len(r.HistoryList)), } for i, v := range r.HistoryList { resp.HistoryList[i] = v.ToSdkCloudBackupHistoryItem() } return resp }
1
7,768
Migrate the spec.Labels to locator.Labels ?
libopenstorage-openstorage
go
@@ -250,7 +250,7 @@ func TestS3_EmptyBucket(t *testing.T) { gotErr := service.EmptyBucket(tc.inBucket) - if gotErr != nil { + if tc.wantErr != nil { require.EqualError(t, gotErr, tc.wantErr.Error()) } })
1
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package s3 import ( "bytes" "errors" "fmt" "strconv" "testing" "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/s3" "github.com/aws/aws-sdk-go/service/s3/s3manager" "github.com/aws/copilot-cli/internal/pkg/aws/s3/mocks" "github.com/golang/mock/gomock" "github.com/stretchr/testify/require" ) func TestS3_PutArtifact(t *testing.T) { buf := &bytes.Buffer{} fmt.Fprint(buf, "some data") timeNow := strconv.FormatInt(time.Now().Unix(), 10) testCases := map[string]struct { inBucket string inFileName string inData *bytes.Buffer mockS3ManagerClient func(m *mocks.Mocks3ManagerApi) wantErr error wantPath string }{ "should put artifact to s3 bucket and return the path": { inBucket: "mockBucket", inData: buf, inFileName: "my-app.addons.stack.yml", mockS3ManagerClient: func(m *mocks.Mocks3ManagerApi) { m.EXPECT().Upload(&s3manager.UploadInput{ Body: buf, Bucket: aws.String("mockBucket"), Key: aws.String(fmt.Sprintf("manual/%s/my-app.addons.stack.yml", timeNow)), }).Return(&s3manager.UploadOutput{ Location: fmt.Sprintf("https://mockBucket/manual/%s/my-app.addons.stack.yml", timeNow), }, nil) }, wantPath: fmt.Sprintf("https://mockBucket/manual/%s/my-app.addons.stack.yml", timeNow), }, "should return error if fail to upload": { inBucket: "mockBucket", inData: buf, inFileName: "my-app.addons.stack.yml", mockS3ManagerClient: func(m *mocks.Mocks3ManagerApi) { m.EXPECT().Upload(&s3manager.UploadInput{ Body: buf, Bucket: aws.String("mockBucket"), Key: aws.String(fmt.Sprintf("manual/%s/my-app.addons.stack.yml", timeNow)), }).Return(nil, errors.New("some error")) }, wantErr: fmt.Errorf(fmt.Sprintf("put manual/%s/my-app.addons.stack.yml to bucket mockBucket: some error", timeNow)), }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { // GIVEN ctrl := gomock.NewController(t) defer ctrl.Finish() mockS3ManagerClient := mocks.NewMocks3ManagerApi(ctrl) tc.mockS3ManagerClient(mockS3ManagerClient) service := S3{ s3Manager: mockS3ManagerClient, } gotPath, gotErr := service.PutArtifact(tc.inBucket, tc.inFileName, tc.inData) if gotErr != nil { require.EqualError(t, gotErr, tc.wantErr.Error()) } else { require.Equal(t, tc.wantPath, gotPath) } }) } } func TestS3_EmptyBucket(t *testing.T) { batchObject1 := make([]*s3.ObjectVersion, 1000) batchObject2 := make([]*s3.ObjectVersion, 10) deleteMarkers := make([]*s3.DeleteMarkerEntry, 10) batchObjectID1 := make([]*s3.ObjectIdentifier, 1000) batchObjectID2 := make([]*s3.ObjectIdentifier, 10) batchObjectID3 := make([]*s3.ObjectIdentifier, 20) for i := 0; i < 1000; i++ { batchObject1[i] = &s3.ObjectVersion{ Key: aws.String("mockKey"), VersionId: aws.String("mockVersion"), } batchObjectID1[i] = &s3.ObjectIdentifier{ Key: aws.String("mockKey"), VersionId: aws.String("mockVersion"), } } for i := 0; i < 10; i++ { batchObject2[i] = &s3.ObjectVersion{ Key: aws.String("mockKey"), VersionId: aws.String("mockVersion"), } deleteMarkers[i] = &s3.DeleteMarkerEntry{ Key: aws.String("mockKey"), VersionId: aws.String("mockVersion"), } batchObjectID2[i] = &s3.ObjectIdentifier{ Key: aws.String("mockKey"), VersionId: aws.String("mockVersion"), } batchObjectID3[i] = &s3.ObjectIdentifier{ Key: aws.String("mockKey"), VersionId: aws.String("mockVersion"), } batchObjectID3[i+10] = &s3.ObjectIdentifier{ Key: aws.String("mockKey"), VersionId: aws.String("mockVersion"), } } testCases := map[string]struct { inBucket string mockS3Client func(m *mocks.Mocks3Api) wantErr error }{ "should delete all objects within the bucket": { inBucket: "mockBucket", mockS3Client: func(m *mocks.Mocks3Api) { m.EXPECT().ListObjectVersions(&s3.ListObjectVersionsInput{ Bucket: aws.String("mockBucket"), }).Return(&s3.ListObjectVersionsOutput{ IsTruncated: aws.Bool(false), Versions: batchObject2, }, nil) m.EXPECT().DeleteObjects(&s3.DeleteObjectsInput{ Bucket: aws.String("mockBucket"), Delete: &s3.Delete{ Objects: batchObjectID2, }, }).Return(&s3.DeleteObjectsOutput{}, nil) }, wantErr: nil, }, "should batch delete all objects within the bucket": { inBucket: "mockBucket", mockS3Client: func(m *mocks.Mocks3Api) { m.EXPECT().ListObjectVersions(&s3.ListObjectVersionsInput{ Bucket: aws.String("mockBucket"), }).Return(&s3.ListObjectVersionsOutput{ IsTruncated: aws.Bool(true), Versions: batchObject1, }, nil) m.EXPECT().DeleteObjects(&s3.DeleteObjectsInput{ Bucket: aws.String("mockBucket"), Delete: &s3.Delete{ Objects: batchObjectID1, }, }).Return(&s3.DeleteObjectsOutput{}, nil) m.EXPECT().ListObjectVersions(&s3.ListObjectVersionsInput{ Bucket: aws.String("mockBucket"), }).Return(&s3.ListObjectVersionsOutput{ IsTruncated: aws.Bool(false), Versions: batchObject2, }, nil) m.EXPECT().DeleteObjects(&s3.DeleteObjectsInput{ Bucket: aws.String("mockBucket"), Delete: &s3.Delete{ Objects: batchObjectID2, }, }).Return(&s3.DeleteObjectsOutput{}, nil) }, wantErr: nil, }, "should delete all objects within the bucket including delete markers": { inBucket: "mockBucket", mockS3Client: func(m *mocks.Mocks3Api) { m.EXPECT().ListObjectVersions(&s3.ListObjectVersionsInput{ Bucket: aws.String("mockBucket"), }).Return(&s3.ListObjectVersionsOutput{ IsTruncated: aws.Bool(false), Versions: batchObject2, DeleteMarkers: deleteMarkers, }, nil) m.EXPECT().DeleteObjects(&s3.DeleteObjectsInput{ Bucket: aws.String("mockBucket"), Delete: &s3.Delete{ Objects: batchObjectID3, }, }).Return(&s3.DeleteObjectsOutput{}, nil) }, wantErr: nil, }, "should wrap up error if fail to list objects": { inBucket: "mockBucket", mockS3Client: func(m *mocks.Mocks3Api) { m.EXPECT().ListObjectVersions(&s3.ListObjectVersionsInput{ Bucket: aws.String("mockBucket"), }).Return(nil, errors.New("some error")) }, wantErr: fmt.Errorf("list objects for bucket mockBucket: some error"), }, "should wrap up error if fail to delete objects": { inBucket: "mockBucket", mockS3Client: func(m *mocks.Mocks3Api) { m.EXPECT().ListObjectVersions(&s3.ListObjectVersionsInput{ Bucket: aws.String("mockBucket"), }).Return(&s3.ListObjectVersionsOutput{ IsTruncated: aws.Bool(false), Versions: batchObject2, }, nil) m.EXPECT().DeleteObjects(&s3.DeleteObjectsInput{ Bucket: aws.String("mockBucket"), Delete: &s3.Delete{ Objects: batchObjectID2, }, }).Return(nil, errors.New("some error")) }, wantErr: fmt.Errorf("delete objects for bucket mockBucket: some error"), }, } for name, tc := range testCases { t.Run(name, func(t *testing.T) { // GIVEN ctrl := gomock.NewController(t) defer ctrl.Finish() mockS3Client := mocks.NewMocks3Api(ctrl) tc.mockS3Client(mockS3Client) service := S3{ s3Client: mockS3Client, } gotErr := service.EmptyBucket(tc.inBucket) if gotErr != nil { require.EqualError(t, gotErr, tc.wantErr.Error()) } }) } }
1
14,684
The test case already existed but it never tested properly because of the conditional in the test.
aws-copilot-cli
go
@@ -68,11 +68,9 @@ public class PartitionField implements Serializable { } PartitionField that = (PartitionField) other; - return ( - sourceId == that.sourceId && + return sourceId == that.sourceId && name.equals(that.name) && - transform.equals(that.transform) - ); + transform.equals(that.transform); } @Override
1
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.iceberg; import com.google.common.base.Objects; import java.io.Serializable; import org.apache.iceberg.transforms.Transform; /** * Represents a single field in a {@link PartitionSpec}. */ public class PartitionField implements Serializable { private final int sourceId; private final String name; private final Transform<?, ?> transform; PartitionField(int sourceId, String name, Transform<?, ?> transform) { this.sourceId = sourceId; this.name = name; this.transform = transform; } /** * @return the field id of the source field in the {@link PartitionSpec spec's} table schema */ public int sourceId() { return sourceId; } /** * @return the name of this partition field */ public String name() { return name; } /** * @return the transform used to produce partition values from source values */ public Transform<?, ?> transform() { return transform; } @Override public boolean equals(Object other) { if (this == other) { return true; } if (other == null || getClass() != other.getClass()) { return false; } PartitionField that = (PartitionField) other; return ( sourceId == that.sourceId && name.equals(that.name) && transform.equals(that.transform) ); } @Override public int hashCode() { return Objects.hashCode(sourceId, name, transform); } }
1
13,100
I'm okay with this, but I don't see a lot of benefit to removing unnecessary parens. If extra parens make something more readable (like this) or clarify order of operations even when matching the default, I would say we should keep them.
apache-iceberg
java
@@ -138,7 +138,7 @@ public class IndexSchema { protected List<SchemaField> fieldsWithDefaultValue = new ArrayList<>(); protected Collection<SchemaField> requiredFields = new HashSet<>(); - protected volatile DynamicField[] dynamicFields; + protected DynamicField[] dynamicFields = new DynamicField[] {}; public DynamicField[] getDynamicFields() { return dynamicFields; } protected Map<String, SchemaField> dynamicFieldCache = new ConcurrentHashMap<>();
1
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.solr.schema; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import java.io.IOException; import java.io.Writer; import java.lang.invoke.MethodHandles; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.DelegatingAnalyzerWrapper; import org.apache.lucene.index.IndexableField; import org.apache.lucene.queries.payloads.PayloadDecoder; import org.apache.lucene.search.similarities.Similarity; import org.apache.lucene.util.Version; import org.apache.solr.common.MapSerializable; import org.apache.solr.common.SolrException; import org.apache.solr.common.SolrException.ErrorCode; import org.apache.solr.common.params.CommonParams; import org.apache.solr.common.params.MapSolrParams; import org.apache.solr.common.params.ModifiableSolrParams; import org.apache.solr.common.params.SolrParams; import org.apache.solr.common.util.NamedList; import org.apache.solr.common.util.Pair; import org.apache.solr.common.util.SimpleOrderedMap; import org.apache.solr.core.SolrCore; import org.apache.solr.core.SolrResourceLoader; import org.apache.solr.core.XmlConfigFile; import org.apache.solr.request.LocalSolrQueryRequest; import org.apache.solr.response.SchemaXmlWriter; import org.apache.solr.response.SolrQueryResponse; import org.apache.solr.search.similarities.SchemaSimilarityFactory; import org.apache.solr.uninverting.UninvertingReader; import org.apache.solr.util.DOMUtil; import org.apache.solr.util.PayloadUtils; import org.apache.solr.util.plugin.SolrCoreAware; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static java.util.Collections.singletonMap; /** * <code>IndexSchema</code> contains information about the valid fields in an index * and the types of those fields. * * */ public class IndexSchema { public static final String COPY_FIELD = "copyField"; public static final String COPY_FIELDS = COPY_FIELD + "s"; public static final String DEFAULT_SCHEMA_FILE = "schema.xml"; public static final String DESTINATION = "dest"; public static final String DYNAMIC_FIELD = "dynamicField"; public static final String DYNAMIC_FIELDS = DYNAMIC_FIELD + "s"; public static final String FIELD = "field"; public static final String FIELDS = FIELD + "s"; public static final String FIELD_TYPE = "fieldType"; public static final String FIELD_TYPES = FIELD_TYPE + "s"; public static final String INTERNAL_POLY_FIELD_PREFIX = "*" + FieldType.POLY_FIELD_SEPARATOR; public static final String LUCENE_MATCH_VERSION_PARAM = "luceneMatchVersion"; public static final String MAX_CHARS = "maxChars"; public static final String NAME = "name"; public static final String NEST_PARENT_FIELD_NAME = "_nest_parent_"; public static final String NEST_PATH_FIELD_NAME = "_nest_path_"; public static final String REQUIRED = "required"; public static final String SCHEMA = "schema"; public static final String SIMILARITY = "similarity"; public static final String SLASH = "/"; public static final String SOURCE = "source"; public static final String TYPE = "type"; public static final String TYPES = "types"; public static final String ROOT_FIELD_NAME = "_root_"; public static final String UNIQUE_KEY = "uniqueKey"; public static final String VERSION = "version"; private static final String AT = "@"; private static final String DESTINATION_DYNAMIC_BASE = "destDynamicBase"; private static final String SOLR_CORE_NAME = "solr.core.name"; private static final String SOURCE_DYNAMIC_BASE = "sourceDynamicBase"; private static final String SOURCE_EXPLICIT_FIELDS = "sourceExplicitFields"; private static final String TEXT_FUNCTION = "text()"; private static final String XPATH_OR = " | "; private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); protected String resourceName; protected String name; protected final Version luceneVersion; protected float version; protected final SolrResourceLoader loader; protected Map<String,SchemaField> fields = new HashMap<>(); protected Map<String,FieldType> fieldTypes = new HashMap<>(); protected List<SchemaField> fieldsWithDefaultValue = new ArrayList<>(); protected Collection<SchemaField> requiredFields = new HashSet<>(); protected volatile DynamicField[] dynamicFields; public DynamicField[] getDynamicFields() { return dynamicFields; } protected Map<String, SchemaField> dynamicFieldCache = new ConcurrentHashMap<>(); private Analyzer indexAnalyzer; private Analyzer queryAnalyzer; protected List<SchemaAware> schemaAware = new ArrayList<>(); protected Map<String, List<CopyField>> copyFieldsMap = new HashMap<>(); public Map<String,List<CopyField>> getCopyFieldsMap() { return Collections.unmodifiableMap(copyFieldsMap); } protected DynamicCopy[] dynamicCopyFields; public DynamicCopy[] getDynamicCopyFields() { return dynamicCopyFields; } private Map<FieldType, PayloadDecoder> decoders = new HashMap<>(); // cache to avoid scanning token filters repeatedly, unnecessarily /** * keys are all fields copied to, count is num of copyField * directives that target them. */ protected Map<SchemaField, Integer> copyFieldTargetCounts = new HashMap<>(); /** * Constructs a schema using the specified resource name and stream. * @see SolrResourceLoader#openSchema * By default, this follows the normal config path directory searching rules. * @see SolrResourceLoader#openResource */ public IndexSchema(String name, InputSource is, Version luceneVersion, SolrResourceLoader resourceLoader) { this(luceneVersion, resourceLoader); this.resourceName = Objects.requireNonNull(name); try { readSchema(is); loader.inform(loader); } catch (IOException e) { throw new RuntimeException(e); } } protected IndexSchema(Version luceneVersion, SolrResourceLoader loader) { this.luceneVersion = Objects.requireNonNull(luceneVersion); this.loader = loader; } /** * The resource loader to be used to load components related to the schema when the schema is loading * / initialising. * It should <em>not</em> be used for any other purpose or time; * consider {@link SolrCore#getResourceLoader()} instead. * @since solr 1.4 */ public SolrResourceLoader getResourceLoader() { //TODO consider asserting the schema has not finished loading somehow? return loader; } /** Gets the name of the resource used to instantiate this schema. */ public String getResourceName() { return resourceName; } /** Sets the name of the resource used to instantiate this schema. */ public void setResourceName(String resourceName) { this.resourceName = resourceName; } /** Gets the name of the schema as specified in the schema resource. */ public String getSchemaName() { return name; } /** The Default Lucene Match Version for this IndexSchema */ public Version getDefaultLuceneMatchVersion() { return luceneVersion; } public float getVersion() { return version; } /** * Provides direct access to the Map containing all explicit * (ie: non-dynamic) fields in the index, keyed on field name. * * <p> * Modifying this Map (or any item in it) will affect the real schema * </p> * * <p> * NOTE: this function is not thread safe. However, it is safe to use within the standard * <code>inform( SolrCore core )</code> function for <code>SolrCoreAware</code> classes. * Outside <code>inform</code>, this could potentially throw a ConcurrentModificationException * </p> */ public Map<String,SchemaField> getFields() { return fields; } /** * Provides direct access to the Map containing all Field Types * in the index, keyed on field type name. * * <p> * Modifying this Map (or any item in it) will affect the real schema. However if you * make any modifications, be sure to call {@link IndexSchema#refreshAnalyzers()} to * update the Analyzers for the registered fields. * </p> * * <p> * NOTE: this function is not thread safe. However, it is safe to use within the standard * <code>inform( SolrCore core )</code> function for <code>SolrCoreAware</code> classes. * Outside <code>inform</code>, this could potentially throw a ConcurrentModificationException * </p> */ public Map<String,FieldType> getFieldTypes() { return fieldTypes; } /** * Provides direct access to the List containing all fields with a default value */ public List<SchemaField> getFieldsWithDefaultValue() { return fieldsWithDefaultValue; } /** * Provides direct access to the List containing all required fields. This * list contains all fields with default values. */ public Collection<SchemaField> getRequiredFields() { return requiredFields; } protected Similarity similarity; /** * Returns the Similarity used for this index */ public Similarity getSimilarity() { if (null == similarity) { similarity = similarityFactory.getSimilarity(); } return similarity; } protected SimilarityFactory similarityFactory; protected boolean isExplicitSimilarity = false; /** Returns the SimilarityFactory that constructed the Similarity for this index */ public SimilarityFactory getSimilarityFactory() { return similarityFactory; } /** * Returns the Analyzer used when indexing documents for this index * * <p> * This Analyzer is field (and dynamic field) name aware, and delegates to * a field specific Analyzer based on the field type. * </p> */ public Analyzer getIndexAnalyzer() { return indexAnalyzer; } /** * Returns the Analyzer used when searching this index * * <p> * This Analyzer is field (and dynamic field) name aware, and delegates to * a field specific Analyzer based on the field type. * </p> */ public Analyzer getQueryAnalyzer() { return queryAnalyzer; } protected SchemaField uniqueKeyField; /** * Unique Key field specified in the schema file * @return null if this schema has no unique key field */ public SchemaField getUniqueKeyField() { return uniqueKeyField; } protected String uniqueKeyFieldName; protected FieldType uniqueKeyFieldType; /** * The raw (field type encoded) value of the Unique Key field for * the specified Document * @return null if this schema has no unique key field * @see #printableUniqueKey */ public IndexableField getUniqueKeyField(org.apache.lucene.document.Document doc) { return doc.getField(uniqueKeyFieldName); // this should return null if name is null } /** * The printable value of the Unique Key field for * the specified Document * @return null if this schema has no unique key field */ public String printableUniqueKey(org.apache.lucene.document.Document doc) { IndexableField f = doc.getField(uniqueKeyFieldName); return f==null ? null : uniqueKeyFieldType.toExternal(f); } private SchemaField getIndexedField(String fname) { SchemaField f = getFields().get(fname); if (f==null) { throw new RuntimeException("unknown field '" + fname + "'"); } if (!f.indexed()) { throw new RuntimeException("'"+fname+"' is not an indexed field:" + f); } return f; } /** * This will re-create the Analyzers. If you make any modifications to * the Field map ({@link IndexSchema#getFields()}, this function is required * to synch the internally cached field analyzers. * * @since solr 1.3 */ public void refreshAnalyzers() { indexAnalyzer = new SolrIndexAnalyzer(); queryAnalyzer = new SolrQueryAnalyzer(); } /** @see UninvertingReader */ public Function<String, UninvertingReader.Type> getUninversionMapper() { return name -> { SchemaField sf = getFieldOrNull(name); if (sf == null) { return null; } if (sf.isUninvertible()) { return sf.getType().getUninversionType(sf); } // else... // It would be nice to throw a helpful error here, with a good useful message for the user, // but unfortunately, inspite of the UninvertingReader class jdoc claims that the uninversion // process is lazy, that doesn't mean it's lazy as of "When a caller attempts ot use doc values" // // The *mapping* function is consulted on LeafReader init/wrap for every FieldInfos found w/o docValues. // // So if we throw an error here instead of returning null, the act of just opening a // newSearcher will trigger that error for any field, even if no one ever attempts to uninvert it return null; }; } /** * Writes the schema in schema.xml format to the given writer */ void persist(Writer writer) throws IOException { final SolrQueryResponse response = new SolrQueryResponse(); response.add(IndexSchema.SCHEMA, getNamedPropertyValues()); final SolrParams args = (new ModifiableSolrParams()).set("indent", "on"); final LocalSolrQueryRequest req = new LocalSolrQueryRequest(null, args); final SchemaXmlWriter schemaXmlWriter = new SchemaXmlWriter(writer, req, response); schemaXmlWriter.setEmitManagedSchemaDoNotEditWarning(true); schemaXmlWriter.writeResponse(); schemaXmlWriter.close(); } public boolean isMutable() { return false; } private class SolrIndexAnalyzer extends DelegatingAnalyzerWrapper { protected final HashMap<String, Analyzer> analyzers; SolrIndexAnalyzer() { super(PER_FIELD_REUSE_STRATEGY); analyzers = analyzerCache(); } protected HashMap<String, Analyzer> analyzerCache() { HashMap<String, Analyzer> cache = new HashMap<>(); for (SchemaField f : getFields().values()) { Analyzer analyzer = f.getType().getIndexAnalyzer(); cache.put(f.getName(), analyzer); } return cache; } @Override protected Analyzer getWrappedAnalyzer(String fieldName) { Analyzer analyzer = analyzers.get(fieldName); return analyzer != null ? analyzer : getDynamicFieldType(fieldName).getIndexAnalyzer(); } } private class SolrQueryAnalyzer extends SolrIndexAnalyzer { SolrQueryAnalyzer() {} @Override protected HashMap<String, Analyzer> analyzerCache() { HashMap<String, Analyzer> cache = new HashMap<>(); for (SchemaField f : getFields().values()) { Analyzer analyzer = f.getType().getQueryAnalyzer(); cache.put(f.getName(), analyzer); } return cache; } @Override protected Analyzer getWrappedAnalyzer(String fieldName) { Analyzer analyzer = analyzers.get(fieldName); return analyzer != null ? analyzer : getDynamicFieldType(fieldName).getQueryAnalyzer(); } } protected void readSchema(InputSource is) { assert null != is : "schema InputSource should never be null"; try { // pass the config resource loader to avoid building an empty one for no reason: // in the current case though, the stream is valid so we wont load the resource by name XmlConfigFile schemaConf = new XmlConfigFile(loader, SCHEMA, is, SLASH+SCHEMA+SLASH); Document document = schemaConf.getDocument(); final XPath xpath = schemaConf.getXPath(); String expression = stepsToPath(SCHEMA, AT + NAME); Node nd = (Node) xpath.evaluate(expression, document, XPathConstants.NODE); String coreName = getCoreName("null"); StringBuilder sb = new StringBuilder(); // Another case where the initialization from the test harness is different than the "real world" sb.append("["); sb.append(coreName); sb.append("] "); if (nd==null) { sb.append("schema has no name!"); log.warn(sb.toString()); } else { name = nd.getNodeValue(); sb.append("Schema "); sb.append(NAME); sb.append("="); sb.append(name); log.info(sb.toString()); } // /schema/@version expression = stepsToPath(SCHEMA, AT + VERSION); version = schemaConf.getFloat(expression, 1.0f); // load the Field Types final FieldTypePluginLoader typeLoader = new FieldTypePluginLoader(this, fieldTypes, schemaAware); expression = getFieldTypeXPathExpressions(); NodeList nodes = (NodeList) xpath.evaluate(expression, document, XPathConstants.NODESET); typeLoader.load(loader, nodes); // load the fields Map<String,Boolean> explicitRequiredProp = loadFields(document, xpath); expression = stepsToPath(SCHEMA, SIMILARITY); // /schema/similarity Node node = (Node) xpath.evaluate(expression, document, XPathConstants.NODE); similarityFactory = readSimilarity(loader, node); if (similarityFactory == null) { final Class<?> simClass = SchemaSimilarityFactory.class; // use the loader to ensure proper SolrCoreAware handling similarityFactory = loader.newInstance(simClass.getName(), SimilarityFactory.class); similarityFactory.init(new ModifiableSolrParams()); } else { isExplicitSimilarity = true; } if ( ! (similarityFactory instanceof SolrCoreAware)) { // if the sim factory isn't SolrCoreAware (and hence schema aware), // then we are responsible for erroring if a field type is trying to specify a sim. for (FieldType ft : fieldTypes.values()) { if (null != ft.getSimilarity()) { String msg = "FieldType '" + ft.getTypeName() + "' is configured with a similarity, but the global similarity does not support it: " + similarityFactory.getClass(); log.error(msg); throw new SolrException(ErrorCode.SERVER_ERROR, msg); } } } // /schema/defaultSearchField/text() expression = stepsToPath(SCHEMA, "defaultSearchField", TEXT_FUNCTION); node = (Node) xpath.evaluate(expression, document, XPathConstants.NODE); if (node != null) { throw new SolrException(ErrorCode.SERVER_ERROR, "Setting defaultSearchField in schema not supported since Solr 7"); } // /schema/solrQueryParser/@defaultOperator expression = stepsToPath(SCHEMA, "solrQueryParser", AT + "defaultOperator"); node = (Node) xpath.evaluate(expression, document, XPathConstants.NODE); if (node != null) { throw new SolrException(ErrorCode.SERVER_ERROR, "Setting default operator in schema (solrQueryParser/@defaultOperator) not supported"); } // /schema/uniqueKey/text() expression = stepsToPath(SCHEMA, UNIQUE_KEY, TEXT_FUNCTION); node = (Node) xpath.evaluate(expression, document, XPathConstants.NODE); if (node==null) { log.warn("no " + UNIQUE_KEY + " specified in schema."); } else { uniqueKeyField=getIndexedField(node.getNodeValue().trim()); uniqueKeyFieldName=uniqueKeyField.getName(); uniqueKeyFieldType=uniqueKeyField.getType(); // we fail on init if the ROOT field is *explicitly* defined as incompatible with uniqueKey // we don't want ot fail if there happens to be a dynamicField matching ROOT, (ie: "*") // because the user may not care about child docs at all. The run time code // related to child docs can catch that if it happens if (fields.containsKey(ROOT_FIELD_NAME) && ! isUsableForChildDocs()) { String msg = ROOT_FIELD_NAME + " field must be defined using the exact same fieldType as the " + UNIQUE_KEY + " field ("+uniqueKeyFieldName+") uses: " + uniqueKeyFieldType.getTypeName(); log.error(msg); throw new SolrException(ErrorCode.SERVER_ERROR, msg); } if (null != uniqueKeyField.getDefaultValue()) { String msg = UNIQUE_KEY + " field ("+uniqueKeyFieldName+ ") can not be configured with a default value ("+ uniqueKeyField.getDefaultValue()+")"; log.error(msg); throw new SolrException(ErrorCode.SERVER_ERROR, msg); } if (!uniqueKeyField.stored()) { log.warn(UNIQUE_KEY + " is not stored - distributed search and MoreLikeThis will not work"); } if (uniqueKeyField.multiValued()) { String msg = UNIQUE_KEY + " field ("+uniqueKeyFieldName+ ") can not be configured to be multivalued"; log.error(msg); throw new SolrException(ErrorCode.SERVER_ERROR, msg); } if (uniqueKeyField.getType().isPointField()) { String msg = UNIQUE_KEY + " field ("+uniqueKeyFieldName+ ") can not be configured to use a Points based FieldType: " + uniqueKeyField.getType().getTypeName(); log.error(msg); throw new SolrException(ErrorCode.SERVER_ERROR, msg); } // Unless the uniqueKeyField is marked 'required=false' then make sure it exists if( Boolean.FALSE != explicitRequiredProp.get( uniqueKeyFieldName ) ) { uniqueKeyField.required = true; requiredFields.add(uniqueKeyField); } } /////////////// parse out copyField commands /////////////// // Map<String,ArrayList<SchemaField>> cfields = new HashMap<String,ArrayList<SchemaField>>(); // expression = "/schema/copyField"; dynamicCopyFields = new DynamicCopy[] {}; loadCopyFields(document, xpath); postReadInform(); } catch (SolrException e) { throw new SolrException(ErrorCode.getErrorCode(e.code()), "Can't load schema " + loader.resourceLocation(resourceName) + ": " + e.getMessage(), e); } catch(Exception e) { // unexpected exception... throw new SolrException(ErrorCode.SERVER_ERROR, "Can't load schema " + loader.resourceLocation(resourceName) + ": " + e.getMessage(), e); } // create the field analyzers refreshAnalyzers(); log.info("Loaded schema {}/{} with uniqueid field {}", name, version, uniqueKeyFieldName); } private String getCoreName(String defaultVal) { if (loader != null && loader.getCoreProperties() != null) { return loader.getCoreProperties().getProperty(SOLR_CORE_NAME, defaultVal); } else { return defaultVal; } } protected void postReadInform() { //Run the callbacks on SchemaAware now that everything else is done for (SchemaAware aware : schemaAware) { aware.inform(this); } } /** * Loads fields and dynamic fields. * * @return a map from field name to explicit required value */ protected synchronized Map<String,Boolean> loadFields(Document document, XPath xpath) throws XPathExpressionException { // Hang on to the fields that say if they are required -- this lets us set a reasonable default for the unique key Map<String,Boolean> explicitRequiredProp = new HashMap<>(); ArrayList<DynamicField> dFields = new ArrayList<>(); // /schema/field | /schema/dynamicField | /schema/fields/field | /schema/fields/dynamicField String expression = stepsToPath(SCHEMA, FIELD) + XPATH_OR + stepsToPath(SCHEMA, DYNAMIC_FIELD) + XPATH_OR + stepsToPath(SCHEMA, FIELDS, FIELD) + XPATH_OR + stepsToPath(SCHEMA, FIELDS, DYNAMIC_FIELD); NodeList nodes = (NodeList)xpath.evaluate(expression, document, XPathConstants.NODESET); for (int i=0; i<nodes.getLength(); i++) { Node node = nodes.item(i); NamedNodeMap attrs = node.getAttributes(); String name = DOMUtil.getAttr(attrs, NAME, "field definition"); log.trace("reading field def "+name); String type = DOMUtil.getAttr(attrs, TYPE, "field " + name); FieldType ft = fieldTypes.get(type); if (ft==null) { throw new SolrException (ErrorCode.BAD_REQUEST, "Unknown " + FIELD_TYPE + " '" + type + "' specified on field " + name); } Map<String,String> args = DOMUtil.toMapExcept(attrs, NAME, TYPE); if (null != args.get(REQUIRED)) { explicitRequiredProp.put(name, Boolean.valueOf(args.get(REQUIRED))); } SchemaField f = SchemaField.create(name,ft,args); if (node.getNodeName().equals(FIELD)) { SchemaField old = fields.put(f.getName(),f); if( old != null ) { String msg = "[schema.xml] Duplicate field definition for '" + f.getName() + "' [[["+old.toString()+"]]] and [[["+f.toString()+"]]]"; throw new SolrException(ErrorCode.SERVER_ERROR, msg ); } log.debug("field defined: " + f); if( f.getDefaultValue() != null ) { log.debug(name+" contains default value: " + f.getDefaultValue()); fieldsWithDefaultValue.add( f ); } if (f.isRequired()) { log.debug(name+" is required in this schema"); requiredFields.add(f); } } else if (node.getNodeName().equals(DYNAMIC_FIELD)) { if (isValidDynamicField(dFields, f)) { addDynamicFieldNoDupCheck(dFields, f); } } else { // we should never get here throw new RuntimeException("Unknown field type"); } } //fields with default values are by definition required //add them to required fields, and we only have to loop once // in DocumentBuilder.getDoc() requiredFields.addAll(fieldsWithDefaultValue); dynamicFields = dynamicFieldListToSortedArray(dFields); return explicitRequiredProp; } /** * Sort the dynamic fields and stuff them in a normal array for faster access. */ protected static DynamicField[] dynamicFieldListToSortedArray(List<DynamicField> dynamicFieldList) { // Avoid creating the array twice by converting to an array first and using Arrays.sort(), // rather than Collections.sort() then converting to an array, since Collections.sort() // copies to an array first, then sets each collection member from the array. DynamicField[] dFields = dynamicFieldList.toArray(new DynamicField[dynamicFieldList.size()]); Arrays.sort(dFields); log.trace("Dynamic Field Ordering:" + Arrays.toString(dFields)); return dFields; } /** * Loads the copy fields */ protected synchronized void loadCopyFields(Document document, XPath xpath) throws XPathExpressionException { String expression = "//" + COPY_FIELD; NodeList nodes = (NodeList)xpath.evaluate(expression, document, XPathConstants.NODESET); for (int i=0; i<nodes.getLength(); i++) { Node node = nodes.item(i); NamedNodeMap attrs = node.getAttributes(); String source = DOMUtil.getAttr(attrs, SOURCE, COPY_FIELD + " definition"); String dest = DOMUtil.getAttr(attrs, DESTINATION, COPY_FIELD + " definition"); String maxChars = DOMUtil.getAttr(attrs, MAX_CHARS); int maxCharsInt = CopyField.UNLIMITED; if (maxChars != null) { try { maxCharsInt = Integer.parseInt(maxChars); } catch (NumberFormatException e) { log.warn("Couldn't parse " + MAX_CHARS + " attribute for " + COPY_FIELD + " from " + source + " to " + dest + " as integer. The whole field will be copied."); } } if (dest.equals(uniqueKeyFieldName)) { String msg = UNIQUE_KEY + " field ("+uniqueKeyFieldName+ ") can not be the " + DESTINATION + " of a " + COPY_FIELD + "(" + SOURCE + "=" +source+")"; log.error(msg); throw new SolrException(ErrorCode.SERVER_ERROR, msg); } registerCopyField(source, dest, maxCharsInt); } for (Map.Entry<SchemaField, Integer> entry : copyFieldTargetCounts.entrySet()) { if (entry.getValue() > 1 && !entry.getKey().multiValued()) { log.warn("Field " + entry.getKey().name + " is not multivalued "+ "and destination for multiple " + COPY_FIELDS + " ("+ entry.getValue()+")"); } } } /** * Converts a sequence of path steps into a rooted path, by inserting slashes in front of each step. * @param steps The steps to join with slashes to form a path * @return a rooted path: a leading slash followed by the given steps joined with slashes */ private String stepsToPath(String... steps) { StringBuilder builder = new StringBuilder(); for (String step : steps) { builder.append(SLASH).append(step); } return builder.toString(); } /** Returns true if the given name has exactly one asterisk either at the start or end of the name */ protected static boolean isValidFieldGlob(String name) { if (name.startsWith("*") || name.endsWith("*")) { int count = 0; for (int pos = 0 ; pos < name.length() && -1 != (pos = name.indexOf('*', pos)) ; ++pos) ++count; if (1 == count) return true; } return false; } protected boolean isValidDynamicField(List<DynamicField> dFields, SchemaField f) { String glob = f.getName(); if (f.getDefaultValue() != null) { throw new SolrException(ErrorCode.SERVER_ERROR, DYNAMIC_FIELD + " can not have a default value: " + glob); } if (f.isRequired()) { throw new SolrException(ErrorCode.SERVER_ERROR, DYNAMIC_FIELD + " can not be required: " + glob); } if ( ! isValidFieldGlob(glob)) { String msg = "Dynamic field name '" + glob + "' should have either a leading or a trailing asterisk, and no others."; throw new SolrException(ErrorCode.SERVER_ERROR, msg); } if (isDuplicateDynField(dFields, f)) { String msg = "[schema.xml] Duplicate DynamicField definition for '" + glob + "'"; throw new SolrException(ErrorCode.SERVER_ERROR, msg); } return true; } /** * Register one or more new Dynamic Fields with the Schema. * @param fields The sequence of {@link org.apache.solr.schema.SchemaField} */ public void registerDynamicFields(SchemaField... fields) { List<DynamicField> dynFields = new ArrayList<>(asList(dynamicFields)); for (SchemaField field : fields) { if (isDuplicateDynField(dynFields, field)) { log.debug("dynamic field already exists: dynamic field: [" + field.getName() + "]"); } else { log.debug("dynamic field creation for schema field: " + field.getName()); addDynamicFieldNoDupCheck(dynFields, field); } } dynamicFields = dynamicFieldListToSortedArray(dynFields); } private void addDynamicFieldNoDupCheck(List<DynamicField> dFields, SchemaField f) { dFields.add(new DynamicField(f)); log.debug("dynamic field defined: " + f); } protected boolean isDuplicateDynField(List<DynamicField> dFields, SchemaField f) { for (DynamicField df : dFields) { if (df.getRegex().equals(f.name)) return true; } return false; } public void registerCopyField( String source, String dest ) { registerCopyField(source, dest, CopyField.UNLIMITED); } /** * <p> * NOTE: this function is not thread safe. However, it is safe to use within the standard * <code>inform( SolrCore core )</code> function for <code>SolrCoreAware</code> classes. * Outside <code>inform</code>, this could potentially throw a ConcurrentModificationException * </p> * * @see SolrCoreAware */ public void registerCopyField(String source, String dest, int maxChars) { log.debug(COPY_FIELD + " " + SOURCE + "='" + source + "' " + DESTINATION + "='" + dest + "' " + MAX_CHARS + "=" + maxChars); DynamicField destDynamicField = null; SchemaField destSchemaField = fields.get(dest); SchemaField sourceSchemaField = fields.get(source); DynamicField sourceDynamicBase = null; DynamicField destDynamicBase = null; boolean sourceIsDynamicFieldReference = false; boolean sourceIsExplicitFieldGlob = false; final String invalidGlobMessage = "is an invalid glob: either it contains more than one asterisk," + " or the asterisk occurs neither at the start nor at the end."; final boolean sourceIsGlob = isValidFieldGlob(source); if (source.contains("*") && ! sourceIsGlob) { String msg = "copyField source :'" + source + "' " + invalidGlobMessage; throw new SolrException(ErrorCode.SERVER_ERROR, msg); } if (dest.contains("*") && ! isValidFieldGlob(dest)) { String msg = "copyField dest :'" + dest + "' " + invalidGlobMessage; throw new SolrException(ErrorCode.SERVER_ERROR, msg); } if (null == sourceSchemaField && sourceIsGlob) { Pattern pattern = Pattern.compile(source.replace("*", ".*")); // glob->regex for (String field : fields.keySet()) { if (pattern.matcher(field).matches()) { sourceIsExplicitFieldGlob = true; break; } } } if (null == destSchemaField || (null == sourceSchemaField && ! sourceIsExplicitFieldGlob)) { // Go through dynamicFields array only once, collecting info for both source and dest fields, if needed for (DynamicField dynamicField : dynamicFields) { if (null == sourceSchemaField && ! sourceIsDynamicFieldReference && ! sourceIsExplicitFieldGlob) { if (dynamicField.matches(source)) { sourceIsDynamicFieldReference = true; if ( ! source.equals(dynamicField.getRegex())) { sourceDynamicBase = dynamicField; } } } if (null == destSchemaField) { if (dest.equals(dynamicField.getRegex())) { destDynamicField = dynamicField; destSchemaField = dynamicField.prototype; } else if (dynamicField.matches(dest)) { destSchemaField = dynamicField.makeSchemaField(dest); destDynamicField = new DynamicField(destSchemaField); destDynamicBase = dynamicField; } } if (null != destSchemaField && (null != sourceSchemaField || sourceIsDynamicFieldReference || sourceIsExplicitFieldGlob)) { break; } } } if (null == sourceSchemaField && ! sourceIsGlob && ! sourceIsDynamicFieldReference) { String msg = "copyField source :'" + source + "' is not a glob and doesn't match any explicit field or dynamicField."; throw new SolrException(ErrorCode.SERVER_ERROR, msg); } if (null == destSchemaField) { String msg = "copyField dest :'" + dest + "' is not an explicit field and doesn't match a dynamicField."; throw new SolrException(ErrorCode.SERVER_ERROR, msg); } if (sourceIsGlob) { if (null != destDynamicField) { // source: glob ; dest: dynamic field ref registerDynamicCopyField(new DynamicCopy(source, destDynamicField, maxChars, sourceDynamicBase, destDynamicBase)); incrementCopyFieldTargetCount(destSchemaField); } else { // source: glob ; dest: explicit field destDynamicField = new DynamicField(destSchemaField); registerDynamicCopyField(new DynamicCopy(source, destDynamicField, maxChars, sourceDynamicBase, null)); incrementCopyFieldTargetCount(destSchemaField); } } else if (sourceIsDynamicFieldReference) { if (null != destDynamicField) { // source: no-asterisk dynamic field ref ; dest: dynamic field ref registerDynamicCopyField(new DynamicCopy(source, destDynamicField, maxChars, sourceDynamicBase, destDynamicBase)); incrementCopyFieldTargetCount(destSchemaField); } else { // source: no-asterisk dynamic field ref ; dest: explicit field sourceSchemaField = getField(source); registerExplicitSrcAndDestFields(source, maxChars, destSchemaField, sourceSchemaField); } } else { if (null != destDynamicField) { // source: explicit field ; dest: dynamic field reference if (destDynamicField.pattern instanceof DynamicReplacement.DynamicPattern.NameEquals) { // Dynamic dest with no asterisk is acceptable registerDynamicCopyField(new DynamicCopy(source, destDynamicField, maxChars, sourceDynamicBase, destDynamicBase)); incrementCopyFieldTargetCount(destSchemaField); } else { // source: explicit field ; dest: dynamic field with an asterisk String msg = "copyField only supports a dynamic destination with an asterisk " + "if the source also has an asterisk"; throw new SolrException(ErrorCode.SERVER_ERROR, msg); } } else { // source & dest: explicit fields registerExplicitSrcAndDestFields(source, maxChars, destSchemaField, sourceSchemaField); } } } protected void registerExplicitSrcAndDestFields(String source, int maxChars, SchemaField destSchemaField, SchemaField sourceSchemaField) { List<CopyField> copyFieldList = copyFieldsMap.get(source); if (copyFieldList == null) { copyFieldList = new ArrayList<>(); copyFieldsMap.put(source, copyFieldList); } copyFieldList.add(new CopyField(sourceSchemaField, destSchemaField, maxChars)); incrementCopyFieldTargetCount(destSchemaField); } private void incrementCopyFieldTargetCount(SchemaField dest) { copyFieldTargetCounts.put(dest, copyFieldTargetCounts.containsKey(dest) ? copyFieldTargetCounts.get(dest) + 1 : 1); } private void registerDynamicCopyField( DynamicCopy dcopy ) { if( dynamicCopyFields == null ) { dynamicCopyFields = new DynamicCopy[] {dcopy}; } else { DynamicCopy[] temp = new DynamicCopy[dynamicCopyFields.length+1]; System.arraycopy(dynamicCopyFields,0,temp,0,dynamicCopyFields.length); temp[temp.length -1] = dcopy; dynamicCopyFields = temp; } log.trace("Dynamic Copy Field:" + dcopy); } static SimilarityFactory readSimilarity(SolrResourceLoader loader, Node node) { if (node==null) { return null; } else { SimilarityFactory similarityFactory; final String classArg = ((Element) node).getAttribute(SimilarityFactory.CLASS_NAME); final Object obj = loader.newInstance(classArg, Object.class, "search.similarities."); if (obj instanceof SimilarityFactory) { // configure a factory, get a similarity back final NamedList<Object> namedList = DOMUtil.childNodesToNamedList(node); namedList.add(SimilarityFactory.CLASS_NAME, classArg); SolrParams params = namedList.toSolrParams(); similarityFactory = (SimilarityFactory)obj; similarityFactory.init(params); } else { // just like always, assume it's a Similarity and get a ClassCastException - reasonable error handling similarityFactory = new SimilarityFactory() { @Override public Similarity getSimilarity() { return (Similarity) obj; } }; } return similarityFactory; } } public static abstract class DynamicReplacement implements Comparable<DynamicReplacement> { abstract protected static class DynamicPattern { protected final String regex; protected final String fixedStr; protected DynamicPattern(String regex, String fixedStr) { this.regex = regex; this.fixedStr = fixedStr; } static DynamicPattern createPattern(String regex) { if (regex.startsWith("*")) { return new NameEndsWith(regex); } else if (regex.endsWith("*")) { return new NameStartsWith(regex); } else { return new NameEquals(regex); } } /** Returns true if the given name matches this pattern */ abstract boolean matches(String name); /** Returns the remainder of the given name after removing this pattern's fixed string component */ abstract String remainder(String name); /** Returns the result of combining this pattern's fixed string component with the given replacement */ abstract String subst(String replacement); /** Returns the length of the original regex, including the asterisk, if any. */ public int length() { return regex.length(); } private static class NameStartsWith extends DynamicPattern { NameStartsWith(String regex) { super(regex, regex.substring(0, regex.length() - 1)); } boolean matches(String name) { return name.startsWith(fixedStr); } String remainder(String name) { return name.substring(fixedStr.length()); } String subst(String replacement) { return fixedStr + replacement; } } private static class NameEndsWith extends DynamicPattern { NameEndsWith(String regex) { super(regex, regex.substring(1)); } boolean matches(String name) { return name.endsWith(fixedStr); } String remainder(String name) { return name.substring(0, name.length() - fixedStr.length()); } String subst(String replacement) { return replacement + fixedStr; } } private static class NameEquals extends DynamicPattern { NameEquals(String regex) { super(regex, regex); } boolean matches(String name) { return regex.equals(name); } String remainder(String name) { return ""; } String subst(String replacement) { return fixedStr; } } } protected DynamicPattern pattern; public boolean matches(String name) { return pattern.matches(name); } protected DynamicReplacement(String regex) { pattern = DynamicPattern.createPattern(regex); } /** * Sort order is based on length of regex. Longest comes first. * @param other The object to compare to. * @return a negative integer, zero, or a positive integer * as this object is less than, equal to, or greater than * the specified object. */ @Override public int compareTo(DynamicReplacement other) { return other.pattern.length() - pattern.length(); } /** Returns the regex used to create this instance's pattern */ public String getRegex() { return pattern.regex; } } public final static class DynamicField extends DynamicReplacement { private final SchemaField prototype; public SchemaField getPrototype() { return prototype; } DynamicField(SchemaField prototype) { super(prototype.name); this.prototype=prototype; } SchemaField makeSchemaField(String name) { // could have a cache instead of returning a new one each time, but it might // not be worth it. // Actually, a higher level cache could be worth it to avoid too many // .startsWith() and .endsWith() comparisons. it depends on how many // dynamic fields there are. return new SchemaField(prototype, name); } @Override public String toString() { return prototype.toString(); } } public static class DynamicCopy extends DynamicReplacement { private final DynamicField destination; private final int maxChars; public int getMaxChars() { return maxChars; } final DynamicField sourceDynamicBase; public DynamicField getSourceDynamicBase() { return sourceDynamicBase; } final DynamicField destDynamicBase; public DynamicField getDestDynamicBase() { return destDynamicBase; } DynamicCopy(String sourceRegex, DynamicField destination, int maxChars, DynamicField sourceDynamicBase, DynamicField destDynamicBase) { super(sourceRegex); this.destination = destination; this.maxChars = maxChars; this.sourceDynamicBase = sourceDynamicBase; this.destDynamicBase = destDynamicBase; } public DynamicField getDestination() { return destination; } public String getDestFieldName() { return destination.getRegex(); } /** * Generates a destination field name based on this source pattern, * by substituting the remainder of this source pattern into the * the given destination pattern. */ public SchemaField getTargetField(String sourceField) { String remainder = pattern.remainder(sourceField); String targetFieldName = destination.pattern.subst(remainder); return destination.makeSchemaField(targetFieldName); } @Override public String toString() { return destination.prototype.toString(); } } public SchemaField[] getDynamicFieldPrototypes() { SchemaField[] df = new SchemaField[dynamicFields.length]; for (int i=0;i<dynamicFields.length;i++) { df[i] = dynamicFields[i].prototype; } return df; } public String getDynamicPattern(String fieldName) { for (DynamicField df : dynamicFields) { if (df.matches(fieldName)) return df.getRegex(); } return null; } /** * Does the schema explicitly define the specified field, i.e. not as a result * of a copyField declaration? We consider it explicitly defined if it matches * a field name or a dynamicField name. * @return true if explicitly declared in the schema. */ public boolean hasExplicitField(String fieldName) { if (fields.containsKey(fieldName)) { return true; } for (DynamicField df : dynamicFields) { if (fieldName.equals(df.getRegex())) return true; } return false; } /** * Is the specified field dynamic or not. * @return true if the specified field is dynamic */ public boolean isDynamicField(String fieldName) { if(fields.containsKey(fieldName)) { return false; } for (DynamicField df : dynamicFields) { if (df.matches(fieldName)) return true; } return false; } /** * Returns the SchemaField that should be used for the specified field name, or * null if none exists. * * @param fieldName may be an explicitly defined field or a name that * matches a dynamic field. * @see #getFieldType * @see #getField(String) * @return The {@link org.apache.solr.schema.SchemaField} */ public SchemaField getFieldOrNull(String fieldName) { SchemaField f = fields.get(fieldName); if (f != null) return f; f = dynamicFieldCache.get(fieldName); if (f != null) return f; for (DynamicField df : dynamicFields) { if (df.matches(fieldName)) { dynamicFieldCache.put(fieldName, f = df.makeSchemaField(fieldName)); break; } } return f; } /** * Returns the SchemaField that should be used for the specified field name * * @param fieldName may be an explicitly defined field or a name that * matches a dynamic field. * @throws SolrException if no such field exists * @see #getFieldType * @see #getFieldOrNull(String) * @return The {@link SchemaField} */ public SchemaField getField(String fieldName) { SchemaField f = getFieldOrNull(fieldName); if (f != null) return f; // Hmmm, default field could also be implemented with a dynamic field of "*". // It would have to be special-cased and only used if nothing else matched. /*** REMOVED -YCS if (defaultFieldType != null) return new SchemaField(fieldName,defaultFieldType); ***/ throw new SolrException(ErrorCode.BAD_REQUEST,"undefined field: \""+fieldName+"\""); } /** * Returns the FieldType for the specified field name. * * <p> * This method exists because it can be more efficient then * {@link #getField} for dynamic fields if a full SchemaField isn't needed. * </p> * * @param fieldName may be an explicitly created field, or a name that * excercises a dynamic field. * @throws SolrException if no such field exists * @see #getField(String) * @see #getFieldTypeNoEx */ public FieldType getFieldType(String fieldName) { SchemaField f = fields.get(fieldName); if (f != null) return f.getType(); return getDynamicFieldType(fieldName); } /** * Given the name of a {@link org.apache.solr.schema.FieldType} (not to be confused with {@link #getFieldType(String)} which * takes in the name of a field), return the {@link org.apache.solr.schema.FieldType}. * @param fieldTypeName The name of the {@link org.apache.solr.schema.FieldType} * @return The {@link org.apache.solr.schema.FieldType} or null. */ public FieldType getFieldTypeByName(String fieldTypeName){ return fieldTypes.get(fieldTypeName); } /** * Returns the FieldType for the specified field name. * * <p> * This method exists because it can be more efficient then * {@link #getField} for dynamic fields if a full SchemaField isn't needed. * </p> * * @param fieldName may be an explicitly created field, or a name that * exercises a dynamic field. * @return null if field is not defined. * @see #getField(String) * @see #getFieldTypeNoEx */ public FieldType getFieldTypeNoEx(String fieldName) { SchemaField f = fields.get(fieldName); if (f != null) return f.getType(); return dynFieldType(fieldName); } /** * Returns the FieldType of the best matching dynamic field for * the specified field name * * @param fieldName may be an explicitly created field, or a name that * exercises a dynamic field. * @throws SolrException if no such field exists * @see #getField(String) * @see #getFieldTypeNoEx */ public FieldType getDynamicFieldType(String fieldName) { for (DynamicField df : dynamicFields) { if (df.matches(fieldName)) return df.prototype.getType(); } throw new SolrException(ErrorCode.BAD_REQUEST,"undefined field "+fieldName); } private FieldType dynFieldType(String fieldName) { for (DynamicField df : dynamicFields) { if (df.matches(fieldName)) return df.prototype.getType(); } return null; } /** * Get all copy fields, both the static and the dynamic ones. * @return Array of fields copied into this field */ public List<String> getCopySources(String destField) { SchemaField f = getField(destField); if (!isCopyFieldTarget(f)) { return Collections.emptyList(); } List<String> fieldNames = new ArrayList<>(); for (Map.Entry<String, List<CopyField>> cfs : copyFieldsMap.entrySet()) { for (CopyField copyField : cfs.getValue()) { if (copyField.getDestination().getName().equals(destField)) { fieldNames.add(copyField.getSource().getName()); } } } if (null != dynamicCopyFields) { for (DynamicCopy dynamicCopy : dynamicCopyFields) { if (dynamicCopy.getDestFieldName().equals(destField)) { fieldNames.add(dynamicCopy.getRegex()); } } } return fieldNames; } /** * Get all copy fields for a specified source field, both static * and dynamic ones. * @return List of CopyFields to copy to. * @since solr 1.4 */ // This is useful when we need the maxSize param of each CopyField public List<CopyField> getCopyFieldsList(final String sourceField){ final List<CopyField> result = new ArrayList<>(); if (null != dynamicCopyFields) { for (DynamicCopy dynamicCopy : dynamicCopyFields) { if (dynamicCopy.matches(sourceField)) { result.add(new CopyField(getField(sourceField), dynamicCopy.getTargetField(sourceField), dynamicCopy.maxChars)); } } } List<CopyField> fixedCopyFields = copyFieldsMap.get(sourceField); if (null != fixedCopyFields) { result.addAll(fixedCopyFields); } return result; } /** * Check if a field is used as the destination of a copyField operation * * @since solr 1.3 */ public boolean isCopyFieldTarget( SchemaField f ) { return copyFieldTargetCounts.containsKey( f ); } /** * Get a map of property name -&gt; value for the whole schema. */ public Map getNamedPropertyValues() { return getNamedPropertyValues(null, new MapSolrParams(Collections.EMPTY_MAP)); } public static class SchemaProps implements MapSerializable { private static final String SOURCE_FIELD_LIST = IndexSchema.SOURCE + "." + CommonParams.FL; private static final String DESTINATION_FIELD_LIST = IndexSchema.DESTINATION + "." + CommonParams.FL; public final String name; private final SolrParams params; private final IndexSchema schema; boolean showDefaults, includeDynamic; Set<String> requestedFields; private Set<String> requestedSourceFields; private Set<String> requestedDestinationFields; public enum Handler { NAME(IndexSchema.NAME, sp -> sp.schema.getSchemaName()), VERSION(IndexSchema.VERSION, sp -> sp.schema.getVersion()), UNIQUE_KEY(IndexSchema.UNIQUE_KEY, sp -> sp.schema.uniqueKeyFieldName), SIMILARITY(IndexSchema.SIMILARITY, sp -> sp.schema.isExplicitSimilarity ? sp.schema.similarityFactory.getNamedPropertyValues() : null), FIELD_TYPES(IndexSchema.FIELD_TYPES, sp -> new TreeMap<>(sp.schema.fieldTypes) .values().stream() .map(it -> it.getNamedPropertyValues(sp.showDefaults)) .collect(Collectors.toList())), FIELDS(IndexSchema.FIELDS, sp -> { List<SimpleOrderedMap> result = (sp.requestedFields != null ? sp.requestedFields : new TreeSet<>(sp.schema.fields.keySet())) .stream() .map(sp.schema::getFieldOrNull) .filter(it -> it != null) .filter(it -> sp.includeDynamic || !sp.schema.isDynamicField(it.name)) .map(sp::getProperties) .collect(Collectors.toList()); if (sp.includeDynamic && sp.requestedFields == null) { result.addAll(sp.applyDynamic()); } return result; }), DYNAMIC_FIELDS(IndexSchema.DYNAMIC_FIELDS, sp -> Stream.of(sp.schema.dynamicFields) .filter(it -> !it.getRegex().startsWith(INTERNAL_POLY_FIELD_PREFIX)) .filter(it -> sp.requestedFields == null || sp.requestedFields.contains(it.getPrototype().getName())) .map(it -> sp.getProperties(it.getPrototype())) .collect(Collectors.toList())), COPY_FIELDS(IndexSchema.COPY_FIELDS, sp -> sp.schema.getCopyFieldProperties(false, sp.requestedSourceFields, sp.requestedDestinationFields)); final Function<SchemaProps, Object> fun; public final String realName, nameLower; Handler(String name, Function<SchemaProps, Object> fun) { this.fun = fun; this.realName = name; nameLower = name.toLowerCase(Locale.ROOT); } public String getRealName(){ return realName; } public String getNameLower(){ return nameLower; } } SchemaProps(String name, SolrParams params, IndexSchema schema) { this.name = name; this.params = params; this.schema = schema; showDefaults = params.getBool("showDefaults", false); includeDynamic = params.getBool("includeDynamic", false); requestedSourceFields = readMultiVals(SOURCE_FIELD_LIST); requestedDestinationFields = readMultiVals(DESTINATION_FIELD_LIST); requestedFields = readMultiVals(CommonParams.FL); } public Collection applyDynamic(){ return (Collection) Handler.DYNAMIC_FIELDS.fun.apply(this); } private Set<String> readMultiVals(String name) { String flParam = params.get(name); if (null != flParam) { String[] fields = flParam.trim().split("[,\\s]+"); if (fields.length > 0) return new LinkedHashSet<>(Stream.of(fields) .filter(it -> !it.trim().isEmpty()) .collect(Collectors.toList())); } return null; } SimpleOrderedMap getProperties(SchemaField sf) { SimpleOrderedMap<Object> result = sf.getNamedPropertyValues(showDefaults); if (schema.isDynamicField(sf.name)) { String dynamicBase = schema.getDynamicPattern(sf.getName()); // Add dynamicBase property if it's different from the field name. if (!sf.getName().equals(dynamicBase)) { result.add("dynamicBase", dynamicBase); } } return result; } @Override public Map<String, Object> toMap(Map<String, Object> map) { return Stream.of(Handler.values()) .filter(it -> name == null || it.nameLower.equals(name)) .map(it -> new Pair<>(it.realName, it.fun.apply(this))) .filter(it->it.second() != null) .collect(Collectors.toMap( Pair::first, Pair::second, (v1, v2) -> v2, LinkedHashMap::new)); } } public static Map<String,String> nameMapping = Collections.unmodifiableMap(Stream.of(SchemaProps.Handler.values()) .collect(Collectors.toMap(SchemaProps.Handler::getNameLower , SchemaProps.Handler::getRealName))); public Map<String, Object> getNamedPropertyValues(String name, SolrParams params) { return new SchemaProps(name, params, this).toMap(new LinkedHashMap<>()); } /** * Returns a list of copyField directives, with optional details and optionally restricting to those * directives that contain the requested source and/or destination field names. * * @param showDetails If true, source and destination dynamic bases, and explicit fields matched by source globs, * will be added to dynamic copyField directives where appropriate * @param requestedSourceFields If not null, output is restricted to those copyField directives * with the requested source field names * @param requestedDestinationFields If not null, output is restricted to those copyField directives * with the requested destination field names * @return a list of copyField directives */ public List<SimpleOrderedMap<Object>> getCopyFieldProperties (boolean showDetails, Set<String> requestedSourceFields, Set<String> requestedDestinationFields) { List<SimpleOrderedMap<Object>> copyFieldProperties = new ArrayList<>(); SortedMap<String,List<CopyField>> sortedCopyFields = new TreeMap<>(copyFieldsMap); for (List<CopyField> copyFields : sortedCopyFields.values()) { copyFields = new ArrayList<>(copyFields); Collections.sort(copyFields, (cf1, cf2) -> { // sources are all the same, just sorting by destination here return cf1.getDestination().getName().compareTo(cf2.getDestination().getName()); }); for (CopyField copyField : copyFields) { final String source = copyField.getSource().getName(); final String destination = copyField.getDestination().getName(); if ( (null == requestedSourceFields || requestedSourceFields.contains(source)) && (null == requestedDestinationFields || requestedDestinationFields.contains(destination))) { SimpleOrderedMap<Object> props = new SimpleOrderedMap<>(); props.add(SOURCE, source); props.add(DESTINATION, destination); if (0 != copyField.getMaxChars()) { props.add(MAX_CHARS, copyField.getMaxChars()); } copyFieldProperties.add(props); } } } if (null != dynamicCopyFields) { for (IndexSchema.DynamicCopy dynamicCopy : dynamicCopyFields) { final String source = dynamicCopy.getRegex(); final String destination = dynamicCopy.getDestFieldName(); if ((null == requestedSourceFields || requestedSourceFields.contains(source)) && (null == requestedDestinationFields || requestedDestinationFields.contains(destination))) { SimpleOrderedMap<Object> dynamicCopyProps = new SimpleOrderedMap<>(); dynamicCopyProps.add(SOURCE, dynamicCopy.getRegex()); if (showDetails) { IndexSchema.DynamicField sourceDynamicBase = dynamicCopy.getSourceDynamicBase(); if (null != sourceDynamicBase) { dynamicCopyProps.add(SOURCE_DYNAMIC_BASE, sourceDynamicBase.getRegex()); } else if (source.contains("*")) { List<String> sourceExplicitFields = new ArrayList<>(); Pattern pattern = Pattern.compile(source.replace("*", ".*")); // glob->regex for (String field : fields.keySet()) { if (pattern.matcher(field).matches()) { sourceExplicitFields.add(field); } } if (sourceExplicitFields.size() > 0) { Collections.sort(sourceExplicitFields); dynamicCopyProps.add(SOURCE_EXPLICIT_FIELDS, sourceExplicitFields); } } } dynamicCopyProps.add(DESTINATION, dynamicCopy.getDestFieldName()); if (showDetails) { IndexSchema.DynamicField destDynamicBase = dynamicCopy.getDestDynamicBase(); if (null != destDynamicBase) { dynamicCopyProps.add(DESTINATION_DYNAMIC_BASE, destDynamicBase.getRegex()); } } if (0 != dynamicCopy.getMaxChars()) { dynamicCopyProps.add(MAX_CHARS, dynamicCopy.getMaxChars()); } copyFieldProperties.add(dynamicCopyProps); } } } return copyFieldProperties; } /** * Copies this schema, adds the given field to the copy * Requires synchronizing on the object returned by * {@link #getSchemaUpdateLock()}. * * @param newField the SchemaField to add * @param persist to persist the schema or not * @return a new IndexSchema based on this schema with newField added * @see #newField(String, String, Map) */ public IndexSchema addField(SchemaField newField, boolean persist) { return addFields(Collections.singletonList(newField), Collections.emptyMap(), persist); } public IndexSchema addField(SchemaField newField) { return addField(newField, true); } /** * Copies this schema, adds the given field to the copy * Requires synchronizing on the object returned by * {@link #getSchemaUpdateLock()}. * * @param newField the SchemaField to add * @param copyFieldNames 0 or more names of targets to copy this field to. The targets must already exist. * @return a new IndexSchema based on this schema with newField added * @see #newField(String, String, Map) */ public IndexSchema addField(SchemaField newField, Collection<String> copyFieldNames) { return addFields(singletonList(newField), singletonMap(newField.getName(), copyFieldNames), true); } /** * Copies this schema, adds the given fields to the copy. * Requires synchronizing on the object returned by * {@link #getSchemaUpdateLock()}. * * @param newFields the SchemaFields to add * @return a new IndexSchema based on this schema with newFields added * @see #newField(String, String, Map) */ public IndexSchema addFields(Collection<SchemaField> newFields) { return addFields(newFields, Collections.<String, Collection<String>>emptyMap(), true); } /** * Copies this schema, adds the given fields to the copy * Requires synchronizing on the object returned by * {@link #getSchemaUpdateLock()}. * * @param newFields the SchemaFields to add * @param copyFieldNames 0 or more names of targets to copy this field to. The target fields must already exist. * @param persist Persist the schema or not * @return a new IndexSchema based on this schema with newFields added * @see #newField(String, String, Map) */ public IndexSchema addFields(Collection<SchemaField> newFields, Map<String, Collection<String>> copyFieldNames, boolean persist) { String msg = "This IndexSchema is not mutable."; log.error(msg); throw new SolrException(ErrorCode.SERVER_ERROR, msg); } /** * Copies this schema, deletes the named fields from the copy. * <p> * The schema will not be persisted. * <p> * Requires synchronizing on the object returned by * {@link #getSchemaUpdateLock()}. * * @param names the names of the fields to delete * @return a new IndexSchema based on this schema with the named fields deleted */ public IndexSchema deleteFields(Collection<String> names) { String msg = "This IndexSchema is not mutable."; log.error(msg); throw new SolrException(ErrorCode.SERVER_ERROR, msg); } /** * Copies this schema, deletes the named field from the copy, creates a new field * with the same name using the given args, then rebinds any referring copy fields * to the replacement field. * * <p> * The schema will not be persisted. * <p> * Requires synchronizing on the object returned by {@link #getSchemaUpdateLock()}. * * @param fieldName The name of the field to be replaced * @param replacementFieldType The field type of the replacement field * @param replacementArgs Initialization params for the replacement field * @return a new IndexSchema based on this schema with the named field replaced */ public IndexSchema replaceField(String fieldName, FieldType replacementFieldType, Map<String,?> replacementArgs) { String msg = "This IndexSchema is not mutable."; log.error(msg); throw new SolrException(ErrorCode.SERVER_ERROR, msg); } /** * Copies this schema, adds the given dynamic fields to the copy, * Requires synchronizing on the object returned by * {@link #getSchemaUpdateLock()}. * * @param newDynamicFields the SchemaFields to add * @param copyFieldNames 0 or more names of targets to copy this field to. The target fields must already exist. * @param persist to persist the schema or not * @return a new IndexSchema based on this schema with newDynamicFields added * @see #newDynamicField(String, String, Map) */ public IndexSchema addDynamicFields (Collection<SchemaField> newDynamicFields, Map<String, Collection<String>> copyFieldNames, boolean persist) { String msg = "This IndexSchema is not mutable."; log.error(msg); throw new SolrException(ErrorCode.SERVER_ERROR, msg); } /** * Copies this schema, deletes the named dynamic fields from the copy. * <p> * The schema will not be persisted. * <p> * Requires synchronizing on the object returned by * {@link #getSchemaUpdateLock()}. * * @param fieldNamePatterns the names of the dynamic fields to delete * @return a new IndexSchema based on this schema with the named dynamic fields deleted */ public IndexSchema deleteDynamicFields(Collection<String> fieldNamePatterns) { String msg = "This IndexSchema is not mutable."; log.error(msg); throw new SolrException(ErrorCode.SERVER_ERROR, msg); } /** * Copies this schema, deletes the named dynamic field from the copy, creates a new dynamic * field with the same field name pattern using the given args, then rebinds any referring * dynamic copy fields to the replacement dynamic field. * * <p> * The schema will not be persisted. * <p> * Requires synchronizing on the object returned by {@link #getSchemaUpdateLock()}. * * @param fieldNamePattern The glob for the dynamic field to be replaced * @param replacementFieldType The field type of the replacement dynamic field * @param replacementArgs Initialization params for the replacement dynamic field * @return a new IndexSchema based on this schema with the named dynamic field replaced */ public ManagedIndexSchema replaceDynamicField (String fieldNamePattern, FieldType replacementFieldType, Map<String,?> replacementArgs) { String msg = "This IndexSchema is not mutable."; log.error(msg); throw new SolrException(ErrorCode.SERVER_ERROR, msg); } /** * Copies this schema and adds the new copy fields to the copy * Requires synchronizing on the object returned by * {@link #getSchemaUpdateLock()}. * * @see #addCopyFields(String,Collection,int) to limit the number of copied characters. * * @param copyFields Key is the name of the source field name, value is a collection of target field names. Fields must exist. * @param persist to persist the schema or not * @return The new Schema with the copy fields added */ public IndexSchema addCopyFields(Map<String, Collection<String>> copyFields, boolean persist) { String msg = "This IndexSchema is not mutable."; log.error(msg); throw new SolrException(ErrorCode.SERVER_ERROR, msg); } /** * Copies this schema and adds the new copy fields to the copy. * * Requires synchronizing on the object returned by * {@link #getSchemaUpdateLock()} * * @param source source field name * @param destinations collection of target field names * @param maxChars max number of characters to copy from the source to each * of the destinations. Use {@link CopyField#UNLIMITED} * if you don't want to limit the number of copied chars. * @return The new Schema with the copy fields added */ public IndexSchema addCopyFields(String source, Collection<String> destinations, int maxChars) { String msg = "This IndexSchema is not mutable."; log.error(msg); throw new SolrException(ErrorCode.SERVER_ERROR, msg); } /** * Copies this schema and deletes the given copy fields from the copy. * <p> * The schema will not be persisted. * <p> * Requires synchronizing on the object returned by * {@link #getSchemaUpdateLock()}. * * @param copyFields Key is the name of the source field name, value is a collection of target field names. * Each corresponding copy field directives must exist. * @return The new Schema with the copy fields deleted */ public IndexSchema deleteCopyFields(Map<String, Collection<String>> copyFields) { String msg = "This IndexSchema is not mutable."; log.error(msg); throw new SolrException(ErrorCode.SERVER_ERROR, msg); } /** * Returns a SchemaField if the given fieldName does not already * exist in this schema, and does not match any dynamic fields * in this schema. The resulting SchemaField can be used in a call * to {@link #addField(SchemaField)}. * * @param fieldName the name of the field to add * @param fieldType the field type for the new field * @param options the options to use when creating the SchemaField * @return The created SchemaField * @see #addField(SchemaField) */ public SchemaField newField(String fieldName, String fieldType, Map<String,?> options) { String msg = "This IndexSchema is not mutable."; log.error(msg); throw new SolrException(ErrorCode.SERVER_ERROR, msg); } /** * Returns a SchemaField if the given dynamic field glob does not already * exist in this schema, and does not match any dynamic fields * in this schema. The resulting SchemaField can be used in a call * to {@link #addField(SchemaField)}. * * @param fieldNamePattern the pattern for the dynamic field to add * @param fieldType the field type for the new field * @param options the options to use when creating the SchemaField * @return The created SchemaField * @see #addField(SchemaField) */ public SchemaField newDynamicField(String fieldNamePattern, String fieldType, Map<String,?> options) { String msg = "This IndexSchema is not mutable."; log.error(msg); throw new SolrException(ErrorCode.SERVER_ERROR, msg); } /** * Returns the schema update lock that should be synchronized on * to update the schema. Only applicable to mutable schemas. * * @return the schema update lock object to synchronize on */ public Object getSchemaUpdateLock() { String msg = "This IndexSchema is not mutable."; log.error(msg); throw new SolrException(ErrorCode.SERVER_ERROR, msg); } /** * Copies this schema, adds the given field type to the copy, * Requires synchronizing on the object returned by * {@link #getSchemaUpdateLock()}. * * @param fieldTypeList a list of FieldTypes to add * @param persist to persist the schema or not * @return a new IndexSchema based on this schema with the new types added * @see #newFieldType(String, String, Map) */ public IndexSchema addFieldTypes(List<FieldType> fieldTypeList, boolean persist) { String msg = "This IndexSchema is not mutable."; log.error(msg); throw new SolrException(ErrorCode.SERVER_ERROR, msg); } /** * Copies this schema, deletes the named field types from the copy. * <p> * The schema will not be persisted. * <p> * Requires synchronizing on the object returned by {@link #getSchemaUpdateLock()}. * * @param names the names of the field types to delete * @return a new IndexSchema based on this schema with the named field types deleted */ public IndexSchema deleteFieldTypes(Collection<String> names) { String msg = "This IndexSchema is not mutable."; log.error(msg); throw new SolrException(ErrorCode.SERVER_ERROR, msg); } /** * Copies this schema, deletes the named field type from the copy, creates a new field type * with the same name using the given args, rebuilds fields and dynamic fields of the given * type, then rebinds any referring copy fields to the rebuilt fields. * * <p> * The schema will not be persisted. * <p> * Requires synchronizing on the object returned by {@link #getSchemaUpdateLock()}. * * @param typeName The name of the field type to be replaced * @param replacementClassName The class name of the replacement field type * @param replacementArgs Initialization params for the replacement field type * @return a new IndexSchema based on this schema with the named field type replaced */ public IndexSchema replaceFieldType(String typeName, String replacementClassName, Map<String,Object> replacementArgs) { String msg = "This IndexSchema is not mutable."; log.error(msg); throw new SolrException(ErrorCode.SERVER_ERROR, msg); } /** * Returns a FieldType if the given typeName does not already * exist in this schema. The resulting FieldType can be used in a call * to {@link #addFieldTypes(java.util.List, boolean)}. * * @param typeName the name of the type to add * @param className the name of the FieldType class * @param options the options to use when creating the FieldType * @return The created FieldType * @see #addFieldTypes(java.util.List, boolean) */ public FieldType newFieldType(String typeName, String className, Map<String,?> options) { String msg = "This IndexSchema is not mutable."; log.error(msg); throw new SolrException(ErrorCode.SERVER_ERROR, msg); } protected String getFieldTypeXPathExpressions() { // /schema/fieldtype | /schema/fieldType | /schema/types/fieldtype | /schema/types/fieldType String expression = stepsToPath(SCHEMA, FIELD_TYPE.toLowerCase(Locale.ROOT)) // backcompat(?) + XPATH_OR + stepsToPath(SCHEMA, FIELD_TYPE) + XPATH_OR + stepsToPath(SCHEMA, TYPES, FIELD_TYPE.toLowerCase(Locale.ROOT)) + XPATH_OR + stepsToPath(SCHEMA, TYPES, FIELD_TYPE); return expression; } /** * Helper method that returns <code>true</code> if the {@link #ROOT_FIELD_NAME} uses the exact * same 'type' as the {@link #getUniqueKeyField()} * * @lucene.internal */ public boolean isUsableForChildDocs() { //TODO make this boolean a field so it needn't be looked up each time? FieldType rootType = getFieldTypeNoEx(ROOT_FIELD_NAME); return (null != uniqueKeyFieldType && null != rootType && rootType.getTypeName().equals(uniqueKeyFieldType.getTypeName())); } /** * Helper method that returns <code>true</code> if the {@link #ROOT_FIELD_NAME} uses the exact * same 'type' as the {@link #getUniqueKeyField()} and has {@link #NEST_PATH_FIELD_NAME} * defined as a {@link NestPathField} * @lucene.internal */ public boolean savesChildDocRelations() { //TODO make this boolean a field so it needn't be looked up each time? if (!isUsableForChildDocs()) { return false; } FieldType nestPathType = getFieldTypeNoEx(NEST_PATH_FIELD_NAME); return nestPathType instanceof NestPathField; } /** * Does this schema supports partial updates (aka atomic updates) and child docs as well. */ public boolean supportsPartialUpdatesOfChildDocs() { if (savesChildDocRelations() == false) { return false; } SchemaField rootField = getField(IndexSchema.ROOT_FIELD_NAME); return rootField.stored() || rootField.hasDocValues(); } public PayloadDecoder getPayloadDecoder(String field) { FieldType ft = getFieldType(field); if (ft == null) return null; return decoders.computeIfAbsent(ft, f -> PayloadUtils.getPayloadDecoder(ft)); } }
1
30,560
@sarowe why was this volatile? It's fishy to see this as the only volatile field.
apache-lucene-solr
java
@@ -0,0 +1,13 @@ +package org.apache.servicecomb.serviceregistry.task.event; + +/** + * 一句话功能简述 + * 功能详细描述 + * @author m00416667 + * @version [版本号, ] + * @see [相关类/方法] + * @since [产品/模块版本] + * Package Name:org.apache.servicecomb.serviceregistry.task.event + */ +public class InstanceRegistryFailedEvent { +}
1
1
9,502
template is not correct?
apache-servicecomb-java-chassis
java
@@ -0,0 +1,4 @@ +from mmdet.utils import Registry + +ASSIGNERS = Registry('assigner') +SAMPLERS = Registry('sampler')
1
1
19,052
Rename the registies to `BBOX_ASSIGNERS` and `BBOX_SAMPLERS` to avoid ambiguity. There is also a registry for dataset sampler.
open-mmlab-mmdetection
py
@@ -89,9 +89,7 @@ module Beaker describe "provisioning and cleanup" do before :each do - vagrant.should_receive( :make_vfile ).with( @hosts ).once - - vagrant.should_receive( :vagrant_cmd ).with( "destroy --force" ).once + FakeFS.activate! vagrant.should_receive( :vagrant_cmd ).with( "up" ).once @hosts.each do |host| host_prev_name = host['user']
1
require 'spec_helper' module Beaker describe Vagrant do let( :vagrant ) { Beaker::Vagrant.new( @hosts, make_opts ) } before :each do @hosts = make_hosts() end it "can make a Vagranfile for a set of hosts" do FakeFS.activate! path = vagrant.instance_variable_get( :@vagrant_path ) vagrant.stub( :randmac ).and_return( "0123456789" ) vagrant.make_vfile( @hosts ) expect( File.read( File.expand_path( File.join( path, "Vagrantfile") ) ) ).to be === "Vagrant.configure(\"2\") do |c|\n c.vm.define 'vm1' do |v|\n v.vm.hostname = 'vm1'\n v.vm.box = 'vm1_of_my_box'\n v.vm.box_url = 'http://address.for.my.box.vm1'\n v.vm.base_mac = '0123456789'\n v.vm.network :private_network, ip: \"ip.address.for.vm1\", :netmask => \"255.255.0.0\"\n end\n c.vm.define 'vm2' do |v|\n v.vm.hostname = 'vm2'\n v.vm.box = 'vm2_of_my_box'\n v.vm.box_url = 'http://address.for.my.box.vm2'\n v.vm.base_mac = '0123456789'\n v.vm.network :private_network, ip: \"ip.address.for.vm2\", :netmask => \"255.255.0.0\"\n end\n c.vm.define 'vm3' do |v|\n v.vm.hostname = 'vm3'\n v.vm.box = 'vm3_of_my_box'\n v.vm.box_url = 'http://address.for.my.box.vm3'\n v.vm.base_mac = '0123456789'\n v.vm.network :private_network, ip: \"ip.address.for.vm3\", :netmask => \"255.255.0.0\"\n end\n c.vm.provider :virtualbox do |vb|\n vb.customize [\"modifyvm\", :id, \"--memory\", \"1024\"]\n end\nend\n" end it "can generate a new /etc/hosts file referencing each host" do @hosts.each do |host| vagrant.should_receive( :set_etc_hosts ).with( host, "127.0.0.1\tlocalhost localhost.localdomain\nip.address.for.vm1\tvm1\nip.address.for.vm2\tvm2\nip.address.for.vm3\tvm3\n" ).once end vagrant.hack_etc_hosts( @hosts ) end context "can copy vagrant's key to root .ssh on each host" do it "can copy to root on unix" do host = @hosts[0] host[:platform] = 'unix' Command.should_receive( :new ).with("sudo su -c \"cp -r .ssh /root/.\"").once vagrant.copy_ssh_to_root( host ) end it "can copy to Administrator on windows" do host = @hosts[0] host[:platform] = 'windows' Command.should_receive( :new ).with("sudo su -c \"cp -r .ssh /home/Administrator/.\"").once vagrant.copy_ssh_to_root( host ) end end it "can generate a ssh-config file" do host = @hosts[0] name = host.name Dir.stub( :chdir ).and_yield() out = double( 'stdout' ) out.stub( :read ).and_return("Host #{host.name} HostName 127.0.0.1 User vagrant Port 2222 UserKnownHostsFile /dev/null StrictHostKeyChecking no PasswordAuthentication no IdentityFile /home/root/.vagrant.d/insecure_private_key IdentitiesOnly yes") wait_thr = OpenStruct.new state = mock( 'state' ) state.stub( :success? ).and_return( true ) wait_thr.value = state Open3.stub( :popen3 ).with( 'vagrant', 'ssh-config', host.name ).and_return( [ "", out, "", wait_thr ]) file = double( 'file' ) file.stub( :path ).and_return( '/path/sshconfig' ) file.stub( :rewind ).and_return( true ) Tempfile.should_receive( :new ).with( "#{host.name}").and_return( file ) file.should_receive( :write ).with("Host ip.address.for.#{name}\n HostName 127.0.0.1\n User root\n Port 2222\n UserKnownHostsFile /dev/null\n StrictHostKeyChecking no\n PasswordAuthentication no\n IdentityFile /home/root/.vagrant.d/insecure_private_key\n IdentitiesOnly yes") vagrant.set_ssh_config( host, 'root' ) expect( host['ssh'] ).to be === { :config => file.path } expect( host['user']).to be === 'root' end describe "provisioning and cleanup" do before :each do vagrant.should_receive( :make_vfile ).with( @hosts ).once vagrant.should_receive( :vagrant_cmd ).with( "destroy --force" ).once vagrant.should_receive( :vagrant_cmd ).with( "up" ).once @hosts.each do |host| host_prev_name = host['user'] vagrant.should_receive( :set_ssh_config ).with( host, 'vagrant' ).once vagrant.should_receive( :copy_ssh_to_root ).with( host ).once vagrant.should_receive( :set_ssh_config ).with( host, host_prev_name ).once end vagrant.should_receive( :hack_etc_hosts ).with( @hosts ).once end it "can provision a set of hosts" do vagrant.provision end it "can cleanup" do vagrant.should_receive( :vagrant_cmd ).with( "destroy --force" ).once FileUtils.should_receive( :rm_rf ).once vagrant.provision vagrant.cleanup end end end end
1
4,868
This is no longer stubbed on every test. Perhaps it should be, and should be unstubbed in the single case that it matters.
voxpupuli-beaker
rb
@@ -188,6 +188,11 @@ module BoltServer [200, GC.stat.to_json] end + get '/admin/status' do + stats = Puma.stats + [200, stats.is_a?(Hash) ? stats.to_json : stats] + end + get '/500_error' do raise 'Unexpected error' end
1
# frozen_string_literal: true require 'sinatra' require 'addressable/uri' require 'bolt' require 'bolt/error' require 'bolt/target' require 'bolt_server/file_cache' require 'bolt/task/puppet_server' require 'json' require 'json-schema' module BoltServer class TransportApp < Sinatra::Base # This disables Sinatra's error page generation set :show_exceptions, false # These partial schemas are reused to build multiple request schemas PARTIAL_SCHEMAS = %w[target-any target-ssh target-winrm task].freeze # These schemas combine shared schemas to describe client requests REQUEST_SCHEMAS = %w[ action-check_node_connections action-run_command action-run_task action-run_script action-upload_file transport-ssh transport-winrm ].freeze def initialize(config) @config = config @schemas = Hash[REQUEST_SCHEMAS.map do |basename| [basename, JSON.parse(File.read(File.join(__dir__, ['schemas', "#{basename}.json"])))] end] PARTIAL_SCHEMAS.each do |basename| schema_content = JSON.parse(File.read(File.join(__dir__, ['schemas', 'partials', "#{basename}.json"]))) shared_schema = JSON::Schema.new(schema_content, Addressable::URI.parse("partial:#{basename}")) JSON::Validator.add_schema(shared_schema) end @executor = Bolt::Executor.new(0) @file_cache = BoltServer::FileCache.new(@config).setup super(nil) end def scrub_stack_trace(result) if result.dig(:result, '_error', 'details', 'stack_trace') result[:result]['_error']['details'].reject! { |k| k == 'stack_trace' } end result end def validate_schema(schema, body) schema_error = JSON::Validator.fully_validate(schema, body) if schema_error.any? Bolt::Error.new("There was an error validating the request body.", 'boltserver/schema-error', schema_error) end end # Turns a Bolt::ResultSet object into a status hash that is fit # to return to the client in a response. # # If the `result_set` has more than one result, the status hash # will have a `status` value and a list of target `results`. # If the `result_set` contains only one item, it will be returned # as a single result object. Set `aggregate` to treat it as a set # of results with length 1 instead. def result_set_to_status_hash(result_set, aggregate: false) scrubbed_results = result_set.map do |result| scrub_stack_trace(result.status_hash) end if aggregate || scrubbed_results.length > 1 # For actions that act on multiple targets, construct a status hash for the aggregate result all_succeeded = scrubbed_results.all? { |r| r[:status] == 'success' } { status: all_succeeded ? 'success' : 'failure', result: scrubbed_results } else # If there was only one target, return the first result on its own scrubbed_results.first end end def run_task(target, body) error = validate_schema(@schemas["action-run_task"], body) return [], error unless error.nil? task = Bolt::Task::PuppetServer.new(body['task'], @file_cache) parameters = body['parameters'] || {} [@executor.run_task(target, task, parameters), nil] end def run_command(target, body) error = validate_schema(@schemas["action-run_command"], body) return [], error unless error.nil? command = body['command'] [@executor.run_command(target, command), nil] end def check_node_connections(targets, body) error = validate_schema(@schemas["action-check_node_connections"], body) return [], error unless error.nil? # Puppet Enterprise's orchestrator service uses the # check_node_connections endpoint to check whether nodes that should be # contacted over SSH or WinRM are responsive. The wait time here is 0 # because the endpoint is meant to be used for a single check of all # nodes; External implementations of wait_until_available (like # orchestrator's) should contact the endpoint in their own loop. [@executor.wait_until_available(targets, wait_time: 0), nil] end def upload_file(target, body) error = validate_schema(@schemas["action-upload_file"], body) return [], error unless error.nil? files = body['files'] destination = body['destination'] job_id = body['job_id'] cache_dir = @file_cache.create_cache_dir(job_id.to_s) FileUtils.mkdir_p(cache_dir) files.each do |file| relative_path = file['relative_path'] uri = file['uri'] sha256 = file['sha256'] kind = file['kind'] path = File.join(cache_dir, relative_path) if kind == 'file' # The parent should already be created by `directory` entries, # but this is to be on the safe side. parent = File.dirname(path) FileUtils.mkdir_p(parent) @file_cache.serial_execute { @file_cache.download_file(path, sha256, uri) } elsif kind == 'directory' # Create directory in cache so we can move files in. FileUtils.mkdir_p(path) else return [400, Bolt::Error.new("Invalid `kind` of '#{kind}' supplied. Must be `file` or `directory`.", 'boltserver/schema-error').to_json] end end # We need to special case the scenario where only one file was # included in the request to download. Otherwise, the call to upload_file # will attempt to upload with a directory as a source and potentially a # filename as a destination on the host. In that case the end result will # be the file downloaded to a directory with the same name as the source # filename, rather than directly to the filename set in the destination. upload_source = if files.size == 1 && files[0]['kind'] == 'file' File.join(cache_dir, files[0]['relative_path']) else cache_dir end [@executor.upload_file(target, upload_source, destination), nil] end def run_script(target, body) error = validate_schema(@schemas["action-run_script"], body) return [], error unless error.nil? # Download the file onto the machine. file_location = @file_cache.update_file(body['script']) [@executor.run_script(target, file_location, body['arguments'])] end get '/' do 200 end if ENV['RACK_ENV'] == 'dev' get '/admin/gc' do GC.start 200 end end get '/admin/gc_stat' do [200, GC.stat.to_json] end get '/500_error' do raise 'Unexpected error' end ACTIONS = %w[ check_node_connections run_command run_task run_script upload_file ].freeze def make_ssh_target(target_hash) defaults = { 'host-key-check' => false } overrides = { 'load-config' => false } opts = defaults.merge(target_hash.clone).merge(overrides) if opts['private-key-content'] private_key_content = opts.delete('private-key-content') opts['private-key'] = { 'key-data' => private_key_content } end Bolt::Target.new(target_hash['hostname'], opts) end post '/ssh/:action' do not_found unless ACTIONS.include?(params[:action]) content_type :json body = JSON.parse(request.body.read) error = validate_schema(@schemas["transport-ssh"], body) return [400, error.to_json] unless error.nil? targets = (body['targets'] || [body['target']]).map do |target| make_ssh_target(target) end result_set, error = method(params[:action]).call(targets, body) return [400, error.to_json] unless error.nil? aggregate = body['target'].nil? [200, result_set_to_status_hash(result_set, aggregate: aggregate).to_json] end def make_winrm_target(target_hash) overrides = { 'protocol' => 'winrm' } opts = target_hash.clone.merge(overrides) Bolt::Target.new(target_hash['hostname'], opts) end post '/winrm/:action' do not_found unless ACTIONS.include?(params[:action]) content_type :json body = JSON.parse(request.body.read) error = validate_schema(@schemas["transport-winrm"], body) return [400, error.to_json] unless error.nil? targets = (body['targets'] || [body['target']]).map do |target| make_winrm_target(target) end result_set, error = method(params[:action]).call(targets, body) return [400, error.to_json] if error aggregate = body['target'].nil? [200, result_set_to_status_hash(result_set, aggregate: aggregate).to_json] end error 404 do err = Bolt::Error.new("Could not find route #{request.path}", 'boltserver/not-found') [404, err.to_json] end error 500 do e = env['sinatra.error'] err = Bolt::Error.new("500: Unknown error: #{e.message}", 'boltserver/server-error') [500, err.to_json] end end end
1
13,559
This seems much simpler! I'm not sure I follow what you mean by the threading part... Also tests are not liking this constant. Might need a require or to fully qualify this.
puppetlabs-bolt
rb
@@ -5902,6 +5902,7 @@ os_forge_exception(app_pc target_pc, dr_exception_type_t type) switch (type) { case ILLEGAL_INSTRUCTION_EXCEPTION: sig = SIGILL; break; case UNREADABLE_MEMORY_EXECUTION_EXCEPTION: sig = SIGSEGV; break; + case SINGLE_STEP_EXCEPTION: ASSERT_NOT_IMPLEMENTED(false); /* cf i#2144 */ case IN_PAGE_ERROR_EXCEPTION: /* fall-through: Windows only */ default: ASSERT_NOT_REACHED(); sig = SIGSEGV; break; }
1
/* ********************************************************** * Copyright (c) 2011-2017 Google, Inc. All rights reserved. * Copyright (c) 2000-2010 VMware, Inc. All rights reserved. * **********************************************************/ /* * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of VMware, Inc. nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL VMWARE, INC. OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. */ /* Copyright (c) 2003-2007 Determina Corp. */ /* Copyright (c) 2001-2003 Massachusetts Institute of Technology */ /* Copyright (c) 2000-2001 Hewlett-Packard Company */ /* * signal.c - dynamorio signal handler */ #include <errno.h> #undef errno #include "signal_private.h" /* pulls in globals.h for us, in right order */ #ifdef LINUX /* We want to build on older toolchains so we have our own copy of signal * data structures */ # include "include/sigcontext.h" # include "include/signalfd.h" # include "../globals.h" /* after our sigcontext.h, to preclude bits/sigcontext.h */ #elif defined(MACOS) # include "../globals.h" /* this defines _XOPEN_SOURCE for Mac */ # include <signal.h> /* after globals.h, for _XOPEN_SOURCE from os_exports.h */ #endif #ifdef LINUX # include <linux/sched.h> #endif #include <sys/time.h> #include <sys/types.h> #include <sys/wait.h> #include <ucontext.h> #include <string.h> /* for memcpy and memset */ #include "os_private.h" #include "../fragment.h" #include "../fcache.h" #include "../perfctr.h" #include "arch.h" #include "../monitor.h" /* for trace_abort */ #include "../link.h" /* for linking interrupted fragment_t */ #include "instr.h" /* to find target of SIGSEGV */ #include "decode.h" /* to find target of SIGSEGV */ #include "decode_fast.h" /* to handle self-mod code */ #include "../synch.h" #include "../nudge.h" #include "disassemble.h" #include "ksynch.h" #include "tls.h" /* tls_reinstate_selector */ #include "../translate.h" #ifdef LINUX # include "include/syscall.h" #else # include <sys/syscall.h> #endif #ifdef CLIENT_INTERFACE # include "instrument.h" #endif #ifdef VMX86_SERVER # include <errno.h> #endif #ifdef MACOS /* Define the Linux names, which the code is already using */ # define SA_NOMASK SA_NODEFER # define SA_ONESHOT SA_RESETHAND #endif /**** data structures ***************************************************/ /* The signal numbers are slightly different between operating systems. * To support differing default actions, we have separate arrays, rather * than indirecting to a single all-signals array. */ extern int default_action[]; /* We know that many signals are always asynchronous. * Others, however, may be synchronous or may not -- e.g., another process * could send us a SIGSEGV, and there is no way we can tell whether it * was generated by a real memory fault or not. Thus we have to assume * that we must not delay any SIGSEGV deliveries. */ extern bool can_always_delay[]; static inline bool sig_is_alarm_signal(int sig) { return (sig == SIGALRM || sig == SIGVTALRM || sig == SIGPROF); } /* we do not use SIGSTKSZ b/c for things like code modification * we end up calling many core routines and so want more space * (though currently non-debug stack size == SIGSTKSZ (8KB)) */ /* this size is assumed in heap.c's threadunits_exit leak relaxation */ #define SIGSTACK_SIZE DYNAMORIO_STACK_SIZE /* this flag not defined in our headers */ #define SA_RESTORER 0x04000000 /* if no app sigaction, it's RT, since that's our handler */ #ifdef LINUX # define IS_RT_FOR_APP(info, sig) \ IF_X64_ELSE(true, ((info)->app_sigaction[(sig)] == NULL ? true : \ (TEST(SA_SIGINFO, (info)->app_sigaction[(sig)]->flags)))) #elif defined(MACOS) # define IS_RT_FOR_APP(info, sig) (true) #endif /* kernel sets size and sp to 0 for SS_DISABLE * when asked, will hand back SS_ONSTACK only if current xsp is inside the * alt stack; otherwise, if an alt stack is registered, it will give flags of 0 * We do not support the "legacy stack switching" that uses the restorer field * as seen in kernel sources. */ #define APP_HAS_SIGSTACK(info) \ ((info)->app_sigstack.ss_sp != NULL && (info)->app_sigstack.ss_flags != SS_DISABLE) /* If we only intercept a few signals, we leave whether un-intercepted signals * are blocked unchanged and stored in the kernel. If we intercept all (not * quite yet: PR 297033, hence the need for this macro) we emulate the mask for * all. */ #define EMULATE_SIGMASK(info, sig) \ (DYNAMO_OPTION(intercept_all_signals) || (info)->we_intercept[(sig)]) /* i#27: custom data to pass to the child of a clone */ /* PR i#149/403015: clone record now passed via a new dstack */ typedef struct _clone_record_t { byte *dstack; /* dstack for new thread - allocated by parent thread */ #ifdef MACOS /* XXX i#1403: once we have lower-level, earlier thread interception we can * likely switch to something closer to what we do on Linux. * This is used for bsdthread_create, where app_thread_xsp is NULL; * for vfork, app_thread_xsp is non-NULL and this is unused. */ void *thread_arg; #endif reg_t app_thread_xsp; /* app xsp preserved for new thread to use */ app_pc continuation_pc; thread_id_t caller_id; int clone_sysnum; uint clone_flags; thread_sig_info_t info; thread_sig_info_t *parent_info; void *pcprofile_info; #ifdef AARCHXX /* To ensure we have the right value as of the point of the clone, we * store it here (we'll have races if we try to get it during new thread * init). */ reg_t app_stolen_value; # ifndef AARCH64 dr_isa_mode_t isa_mode; # endif /* To ensure we have the right app lib tls base in child thread, * we store it here if necessary (clone w/o CLONE_SETTLS or vfork). */ void *app_lib_tls_base; #endif /* we leave some padding at base of stack for dynamorio_clone * to store values */ reg_t for_dynamorio_clone[4]; } clone_record_t; /* i#350: set up signal handler for safe_read/faults during init */ static thread_sig_info_t init_info; static kernel_sigset_t init_sigmask; #ifdef DEBUG static bool removed_sig_handler; #endif /**** function prototypes ***********************************************/ /* in x86.asm */ void master_signal_handler(int sig, siginfo_t *siginfo, kernel_ucontext_t *ucxt); static void set_handler_and_record_app(dcontext_t *dcontext, thread_sig_info_t *info, int sig, kernel_sigaction_t *act); static void intercept_signal(dcontext_t *dcontext, thread_sig_info_t *info, int sig); static void signal_info_init_sigaction(dcontext_t *dcontext, thread_sig_info_t *info); static void signal_info_exit_sigaction(dcontext_t *dcontext, thread_sig_info_t *info, bool other_thread); static bool execute_handler_from_cache(dcontext_t *dcontext, int sig, sigframe_rt_t *our_frame, sigcontext_t *sc_orig, fragment_t *f _IF_CLIENT(byte *access_address)); static bool execute_handler_from_dispatch(dcontext_t *dcontext, int sig); /* Execute default action from code cache and may terminate the process. * If returns, the return value decides if caller should restore * the untranslated context. */ static bool execute_default_from_cache(dcontext_t *dcontext, int sig, sigframe_rt_t *frame, sigcontext_t *sc_orig); static void execute_default_from_dispatch(dcontext_t *dcontext, int sig, sigframe_rt_t *frame); static bool handle_alarm(dcontext_t *dcontext, int sig, kernel_ucontext_t *ucxt); static bool handle_suspend_signal(dcontext_t *dcontext, kernel_ucontext_t *ucxt, sigframe_rt_t *frame); static bool handle_nudge_signal(dcontext_t *dcontext, siginfo_t *siginfo, kernel_ucontext_t *ucxt); static void init_itimer(dcontext_t *dcontext, bool first); static bool set_actual_itimer(dcontext_t *dcontext, int which, thread_sig_info_t *info, bool enable); #ifdef DEBUG static void dump_sigset(dcontext_t *dcontext, kernel_sigset_t *set); #endif static bool is_sys_kill(dcontext_t *dcontext, byte *pc, byte *xsp, siginfo_t *info); int sigaction_syscall(int sig, kernel_sigaction_t *act, kernel_sigaction_t *oact) { #if defined(X64) && !defined(VMX86_SERVER) && defined(LINUX) /* PR 305020: must have SA_RESTORER for x64 */ if (act != NULL && !TEST(SA_RESTORER, act->flags)) { act->flags |= SA_RESTORER; act->restorer = (void (*)(void)) dynamorio_sigreturn; } #endif return dynamorio_syscall(IF_MACOS_ELSE(SYS_sigaction,SYS_rt_sigaction), 4, sig, act, oact, sizeof(kernel_sigset_t)); } static inline bool signal_is_interceptable(int sig) { return (sig != SIGKILL && sig != SIGSTOP); } static inline int sigaltstack_syscall(const stack_t *newstack, stack_t *oldstack) { return dynamorio_syscall(SYS_sigaltstack, 2, newstack, oldstack); } static inline int getitimer_syscall(int which, struct itimerval *val) { return dynamorio_syscall(SYS_getitimer, 2, which, val); } static inline int setitimer_syscall(int which, struct itimerval *val, struct itimerval *old) { return dynamorio_syscall(SYS_setitimer, 3, which, val, old); } static inline int sigprocmask_syscall(int how, kernel_sigset_t *set, kernel_sigset_t *oset, size_t sigsetsize) { return dynamorio_syscall(IF_MACOS_ELSE(SYS_sigprocmask,SYS_rt_sigprocmask), 4, how, set, oset, sigsetsize); } static void unblock_all_signals(kernel_sigset_t *oset) { kernel_sigset_t set; kernel_sigemptyset(&set); sigprocmask_syscall(SIG_SETMASK, &set, oset, sizeof(set)); } /* exported for stackdump.c */ bool set_default_signal_action(int sig) { kernel_sigset_t set; kernel_sigaction_t act; int rc; memset(&act, 0, sizeof(act)); act.handler = (handler_t) SIG_DFL; /* arm the signal */ rc = sigaction_syscall(sig, &act, NULL); DODEBUG({ removed_sig_handler = true; }); /* If we're in our handler now, we have to unblock */ kernel_sigemptyset(&set); kernel_sigaddset(&set, sig); sigprocmask_syscall(SIG_UNBLOCK, &set, NULL, sizeof(set)); return (rc == 0); } static bool set_ignore_signal_action(int sig) { kernel_sigaction_t act; int rc; memset(&act, 0, sizeof(act)); act.handler = (handler_t) SIG_IGN; /* arm the signal */ rc = sigaction_syscall(sig, &act, NULL); return (rc == 0); } /* We assume that signal handlers will be shared most of the time * (pthreads shares them) * Rather than start out with the handler table in local memory and then * having to transfer to global, we just always use global */ static void handler_free(dcontext_t *dcontext, void *p, size_t size) { global_heap_free(p, size HEAPACCT(ACCT_OTHER)); } static void * handler_alloc(dcontext_t *dcontext, size_t size) { return global_heap_alloc(size HEAPACCT(ACCT_OTHER)); } /**** top-level routines ***********************************************/ static bool os_itimers_thread_shared(void) { static bool itimers_shared; static bool cached = false; if (!cached) { file_t f = os_open("/proc/version", OS_OPEN_READ); if (f != INVALID_FILE) { char buf[128]; int major, minor, rel; os_read(f, buf, BUFFER_SIZE_ELEMENTS(buf)); NULL_TERMINATE_BUFFER(buf); if (sscanf(buf, "%*s %*s %d.%d.%d", &major, &minor, &rel) == 3) { /* Linux NPTL in kernel 2.6.12+ has POSIX-style itimers shared * among threads. */ LOG(GLOBAL, LOG_ASYNCH, 1, "kernel version = %d.%d.%d\n", major, minor, rel); itimers_shared = ((major == 2 && minor >= 6 && rel >= 12) || (major >= 3 /* linux-3.0 or above */)); cached = true; } os_close(f); } if (!cached) { /* assume not shared */ itimers_shared = false; cached = true; } LOG(GLOBAL, LOG_ASYNCH, 1, "itimers are %s\n", itimers_shared ? "thread-shared" : "thread-private"); } return itimers_shared; } static void unset_initial_crash_handlers(dcontext_t *dcontext) { ASSERT(init_info.app_sigaction != NULL); signal_info_exit_sigaction(GLOBAL_DCONTEXT, &init_info, false/*!other_thread*/); /* Undo the unblock-all */ sigprocmask_syscall(SIG_SETMASK, &init_sigmask, NULL, sizeof(init_sigmask)); DOLOG(2, LOG_ASYNCH, { LOG(THREAD, LOG_ASYNCH, 2, "initial app signal mask:\n"); dump_sigset(dcontext, &init_sigmask); }); } void signal_init(void) { kernel_sigset_t set; IF_LINUX(IF_X86_64(ASSERT(ALIGNED(offsetof(sigpending_t, xstate), AVX_ALIGNMENT)))); IF_MACOS(ASSERT(sizeof(kernel_sigset_t) == sizeof(__darwin_sigset_t))); os_itimers_thread_shared(); /* Set up a handler for safe_read (or other fault detection) during * DR init before thread is initialized. * * XXX: could set up a clone_record_t and pass to the initial * signal_thread_inherit() but that would require further code changes. * Could also call signal_thread_inherit to init this, but we don't want * to intercept timer signals, etc. before we're ready to handle them, * so we do a partial init. */ signal_info_init_sigaction(GLOBAL_DCONTEXT, &init_info); intercept_signal(GLOBAL_DCONTEXT, &init_info, SIGSEGV); intercept_signal(GLOBAL_DCONTEXT, &init_info, SIGBUS); kernel_sigemptyset(&set); kernel_sigaddset(&set, SIGSEGV); kernel_sigaddset(&set, SIGBUS); sigprocmask_syscall(SIG_UNBLOCK, &set, &init_sigmask, sizeof(set)); IF_LINUX(signalfd_init()); signal_arch_init(); } void signal_exit() { IF_LINUX(signalfd_exit()); #ifdef DEBUG if (stats->loglevel > 0 && (stats->logmask & (LOG_ASYNCH|LOG_STATS)) != 0) { LOG(GLOBAL, LOG_ASYNCH|LOG_STATS, 1, "Total signals delivered: %d\n", GLOBAL_STAT(num_signals)); } #endif } #ifdef HAVE_SIGALTSTACK /* Separated out to run from the dstack (i#2016: see below). */ static void set_our_alt_stack(void *arg) { thread_sig_info_t *info = (thread_sig_info_t *) arg; DEBUG_DECLARE(int rc =) sigaltstack_syscall(&info->sigstack, &info->app_sigstack); ASSERT(rc == 0); } #endif void signal_thread_init(dcontext_t *dcontext) { thread_sig_info_t *info = HEAP_TYPE_ALLOC(dcontext, thread_sig_info_t, ACCT_OTHER, PROTECTED); size_t pend_unit_size = sizeof(sigpending_t) + /* include alignment for xsave on xstate */ signal_frame_extra_size(true) /* sigpending_t has xstate inside it already */ IF_LINUX(IF_X86(- sizeof(struct _xstate))); IF_LINUX(IF_X86(ASSERT(ALIGNED(pend_unit_size, AVX_ALIGNMENT)))); /* all fields want to be initialized to 0 */ memset(info, 0, sizeof(thread_sig_info_t)); dcontext->signal_field = (void *) info; /* our special heap to avoid reentrancy problems * composed entirely of sigpending_t units * Note that it's fine to have the special heap do page-at-a-time * committing, which does not use locks (unless triggers reset!), * but if we need a new unit that will grab a lock: we try to * avoid that by limiting the # of pending alarm signals (PR 596768). */ info->sigheap = special_heap_init_aligned(pend_unit_size, IF_X86_ELSE(AVX_ALIGNMENT, 0), false /* cannot have any locking */, false /* -x */, true /* persistent */); #ifdef HAVE_SIGALTSTACK /* set up alternate stack * i#552 we may terminate the process without freeing the stack, so we * stack_alloc it to exempt from the memory leak check. */ info->sigstack.ss_sp = (char *) stack_alloc(SIGSTACK_SIZE, NULL) - SIGSTACK_SIZE; info->sigstack.ss_size = SIGSTACK_SIZE; /* kernel will set xsp to sp+size to grow down from there, we don't have to */ info->sigstack.ss_flags = 0; /* i#2016: for late takeover, this app thread may already be on its own alt * stack. Not setting SA_ONSTACK for SUSPEND_SIGNAL is not sufficient to avoid * this, as our SUSPEND_SIGNAL can interrupt the app inside its own signal * handler. Thus, we simply swap to another stack temporarily to avoid the * kernel complaining. The dstack is set up but it has the clone record and * initial mcxt, so we use the new alt stack. */ call_switch_stack((void *)info, (byte *)info->sigstack.ss_sp + info->sigstack.ss_size, set_our_alt_stack, NULL, true/*return*/); LOG(THREAD, LOG_ASYNCH, 1, "signal stack is "PFX" - "PFX"\n", info->sigstack.ss_sp, info->sigstack.ss_sp + info->sigstack.ss_size); /* app_sigstack dealt with below, based on parentage */ #endif kernel_sigemptyset(&info->app_sigblocked); ASSIGN_INIT_LOCK_FREE(info->child_lock, child_lock); /* someone must call signal_thread_inherit() to finish initialization: * for first thread, called from initial setup; else, from new_thread_setup * or share_siginfo_after_take_over. */ } bool is_thread_signal_info_initialized(dcontext_t *dcontext) { thread_sig_info_t *info = (thread_sig_info_t*)dcontext->signal_field; return info->fully_initialized; } /* i#27: create custom data to pass to the child of a clone * since we can't rely on being able to find the caller, or that * its syscall data is still valid, once in the child. * * i#149/ PR 403015: The clone record is passed to the new thread via the dstack * created for it. Unlike before, where the child thread would create its own * dstack, now the parent thread creates the dstack. Also, switches app stack * to dstack. * * XXX i#1403: for Mac we want to eventually do lower-level earlier interception * of threads, but for now we're later and higher-level, intercepting the user * thread function on the new thread's stack. We ignore app_thread_xsp. */ void * #ifdef MACOS create_clone_record(dcontext_t *dcontext, reg_t *app_thread_xsp, app_pc thread_func, void *thread_arg) #else create_clone_record(dcontext_t *dcontext, reg_t *app_thread_xsp) #endif { clone_record_t *record; byte *dstack = stack_alloc(DYNAMORIO_STACK_SIZE, NULL); LOG(THREAD, LOG_ASYNCH, 1, "create_clone_record: dstack for new thread is "PFX"\n", dstack); #ifdef MACOS if (app_thread_xsp == NULL) { record = HEAP_TYPE_ALLOC(GLOBAL_DCONTEXT, clone_record_t, ACCT_THREAD_MGT, true/*prot*/); record->app_thread_xsp = 0; record->continuation_pc = thread_func; record->thread_arg = thread_arg; record->clone_flags = CLONE_THREAD | CLONE_VM | CLONE_SIGHAND | SIGCHLD; } else { #endif /* Note, the stack grows to low memory addr, so dstack points to the high * end of the allocated stack region. So, we must subtract to get space for * the clone record. */ record = (clone_record_t *) (dstack - sizeof(clone_record_t)); record->app_thread_xsp = *app_thread_xsp; /* asynch_target is set in dispatch() prior to calling pre_system_call(). */ record->continuation_pc = dcontext->asynch_target; record->clone_flags = dcontext->sys_param0; #ifdef MACOS } #endif LOG(THREAD, LOG_ASYNCH, 1, "allocated clone record: "PFX"\n", record); record->dstack = dstack; record->caller_id = dcontext->owning_thread; record->clone_sysnum = dcontext->sys_num; record->info = *((thread_sig_info_t *)dcontext->signal_field); record->parent_info = (thread_sig_info_t *) dcontext->signal_field; record->pcprofile_info = dcontext->pcprofile_field; #ifdef AARCHXX record->app_stolen_value = get_stolen_reg_val(get_mcontext(dcontext)); # ifndef AARCH64 record->isa_mode = dr_get_isa_mode(dcontext); # endif /* If the child thread shares the same TLS with parent by not setting * CLONE_SETTLS or vfork, we put the TLS base here and clear the * thread register in new_thread_setup, so that DR can distinguish * this case from normal pthread thread creation. */ record->app_lib_tls_base = (!TEST(CLONE_SETTLS, record->clone_flags)) ? os_get_app_tls_base(dcontext, TLS_REG_LIB) : NULL; #endif LOG(THREAD, LOG_ASYNCH, 1, "create_clone_record: thread "TIDFMT", pc "PFX"\n", record->caller_id, record->continuation_pc); #ifdef MACOS if (app_thread_xsp != NULL) { #endif /* Set the thread stack to point to the dstack, below the clone record. * Note: it's glibc who sets up the arg to the thread start function; * the kernel just does a fork + stack swap, so we can get away w/ our * own stack swap if we restore before the glibc asm code takes over. */ /* i#754: set stack to be XSTATE aligned for saving YMM registers */ ASSERT(ALIGNED(XSTATE_ALIGNMENT, REGPARM_END_ALIGN)); *app_thread_xsp = ALIGN_BACKWARD(record, XSTATE_ALIGNMENT); #ifdef MACOS } #endif return (void *) record; } /* This is to support dr_create_client_thread() */ void set_clone_record_fields(void *record, reg_t app_thread_xsp, app_pc continuation_pc, uint clone_sysnum, uint clone_flags) { clone_record_t *rec = (clone_record_t *) record; ASSERT(rec != NULL); rec->app_thread_xsp = app_thread_xsp; rec->continuation_pc = continuation_pc; rec->clone_sysnum = clone_sysnum; rec->clone_flags = clone_flags; } /* i#149/PR 403015: The clone record is passed to the new thread by placing it * at the bottom of the dstack, i.e., the high memory. So the new thread gets * it from the base of the dstack. The dstack is then set as the app stack. * * CAUTION: don't use a lot of stack in this routine as it gets invoked on the * dstack from new_thread_setup - this is because this routine assumes * no more than a page of dstack has been used so far since the clone * system call was done. */ void * get_clone_record(reg_t xsp) { clone_record_t *record; byte *dstack_base; /* xsp should be in a dstack, i.e., dynamorio heap. */ ASSERT(is_dynamo_address((app_pc) xsp)); /* The (size of the clone record + * stack used by new_thread_start (only for setting up priv_mcontext_t) + * stack used by new_thread_setup before calling get_clone_record()) * is less than a page. This is verified by the assert below. If it does * exceed a page, it won't happen at random during runtime, but in a * predictable way during development, which will be caught by the assert. * The current usage is about 800 bytes for clone_record + * sizeof(priv_mcontext_t) + few words in new_thread_setup before * get_clone_record() is called. */ dstack_base = (byte *) ALIGN_FORWARD(xsp, PAGE_SIZE); record = (clone_record_t *) (dstack_base - sizeof(clone_record_t)); /* dstack_base and the dstack in the clone record should be the same. */ ASSERT(dstack_base == record->dstack); #ifdef MACOS ASSERT(record->app_thread_xsp != 0); /* else it's not in dstack */ #endif return (void *) record; } /* i#149/PR 403015: App xsp is passed to the new thread via the clone record. */ reg_t get_clone_record_app_xsp(void *record) { ASSERT(record != NULL); return ((clone_record_t *) record)->app_thread_xsp; } #ifdef MACOS void * get_clone_record_thread_arg(void *record) { ASSERT(record != NULL); return ((clone_record_t *) record)->thread_arg; } #endif byte * get_clone_record_dstack(void *record) { ASSERT(record != NULL); return ((clone_record_t *) record)->dstack; } #ifdef AARCHXX reg_t get_clone_record_stolen_value(void *record) { ASSERT(record != NULL); return ((clone_record_t *) record)->app_stolen_value; } # ifndef AARCH64 uint /* dr_isa_mode_t but we have a header ordering problem */ get_clone_record_isa_mode(void *record) { ASSERT(record != NULL); return ((clone_record_t *) record)->isa_mode; } # endif void set_thread_register_from_clone_record(void *record) { /* If record->app_lib_tls_base is not NULL, it means the parent * thread did not setup TLS for the child, and we need clear the * thread register. */ if (((clone_record_t *)record)->app_lib_tls_base != NULL) write_thread_register(NULL); } void set_app_lib_tls_base_from_clone_record(dcontext_t *dcontext, void *record) { if (((clone_record_t *)record)->app_lib_tls_base != NULL) { /* child and parent share the same TLS */ os_set_app_tls_base(dcontext, TLS_REG_LIB, ((clone_record_t *)record)->app_lib_tls_base); } } #endif /* Initializes info's app_sigaction, restorer_valid, and we_intercept fields */ static void signal_info_init_sigaction(dcontext_t *dcontext, thread_sig_info_t *info) { info->app_sigaction = (kernel_sigaction_t **) handler_alloc(dcontext, SIGARRAY_SIZE * sizeof(kernel_sigaction_t *)); memset(info->app_sigaction, 0, SIGARRAY_SIZE * sizeof(kernel_sigaction_t *)); memset(&info->restorer_valid, -1, SIGARRAY_SIZE * sizeof(info->restorer_valid[0])); info->we_intercept = (bool *) handler_alloc(dcontext, SIGARRAY_SIZE * sizeof(bool)); memset(info->we_intercept, 0, SIGARRAY_SIZE * sizeof(bool)); } /* Cleans up info's app_sigaction and we_intercept entries */ static void signal_info_exit_sigaction(dcontext_t *dcontext, thread_sig_info_t *info, bool other_thread) { int i; kernel_sigaction_t act; memset(&act, 0, sizeof(act)); act.handler = (handler_t) SIG_DFL; kernel_sigemptyset(&act.mask); /* does mask matter for SIG_DFL? */ for (i = 1; i <= MAX_SIGNUM; i++) { if (!other_thread) { if (info->app_sigaction[i] != NULL) { /* Restore to old handler, but not if exiting whole * process: else may get itimer during cleanup, so we * set to SIG_IGN. We do this for detach in * signal_remove_alarm_handlers(). */ if (dynamo_exited && !doing_detach) { info->app_sigaction[i]->handler = (handler_t) SIG_IGN; sigaction_syscall(i, info->app_sigaction[i], NULL); } LOG(THREAD, LOG_ASYNCH, 2, "\trestoring "PFX" as handler for %d\n", info->app_sigaction[i]->handler, i); sigaction_syscall(i, info->app_sigaction[i], NULL); } else if (info->we_intercept[i]) { /* restore to default */ LOG(THREAD, LOG_ASYNCH, 2, "\trestoring SIG_DFL as handler for %d\n", i); sigaction_syscall(i, &act, NULL); } } if (info->app_sigaction[i] != NULL) { handler_free(dcontext, info->app_sigaction[i], sizeof(kernel_sigaction_t)); } } handler_free(dcontext, info->app_sigaction, SIGARRAY_SIZE * sizeof(kernel_sigaction_t *)); info->app_sigaction = NULL; handler_free(dcontext, info->we_intercept, SIGARRAY_SIZE * sizeof(bool)); info->we_intercept = NULL; } /* Called once a new thread's dcontext is created. * Inherited and shared fields are set up here. * The clone_record contains the continuation pc, which is returned. */ app_pc signal_thread_inherit(dcontext_t *dcontext, void *clone_record) { app_pc res = NULL; clone_record_t *record = (clone_record_t *) clone_record; thread_sig_info_t *info = (thread_sig_info_t *) dcontext->signal_field; int i; if (record != NULL) { app_pc continuation_pc = record->continuation_pc; LOG(THREAD, LOG_ASYNCH, 1, "continuation pc is "PFX"\n", continuation_pc); LOG(THREAD, LOG_ASYNCH, 1, "parent tid is "TIDFMT", parent sysnum is %d(%s), clone flags="PIFX"\n", record->caller_id, record->clone_sysnum, #ifdef SYS_vfork (record->clone_sysnum == SYS_vfork) ? "vfork" : #endif (IF_LINUX(record->clone_sysnum == SYS_clone ? "clone" :) IF_MACOS(record->clone_sysnum == SYS_bsdthread_create ? "bsdthread_create":) "unexpected"), record->clone_flags); #ifdef SYS_vfork if (record->clone_sysnum == SYS_vfork) { /* The above clone_flags argument is bogus. SYS_vfork doesn't have a free register to keep the hardcoded value see /usr/src/linux/arch/i386/kernel/process.c */ /* CHECK: is this the only place real clone flags are needed? */ record->clone_flags = CLONE_VFORK | CLONE_VM | SIGCHLD; } #endif /* handlers are either inherited or shared */ if (TEST(CLONE_SIGHAND, record->clone_flags)) { /* need to share table of handlers! */ LOG(THREAD, LOG_ASYNCH, 2, "sharing signal handlers with parent\n"); info->shared_app_sigaction = true; info->shared_refcount = record->info.shared_refcount; info->shared_lock = record->info.shared_lock; info->app_sigaction = record->info.app_sigaction; info->we_intercept = record->info.we_intercept; mutex_lock(info->shared_lock); (*info->shared_refcount)++; #ifdef DEBUG for (i = 1; i <= MAX_SIGNUM; i++) { if (info->app_sigaction[i] != NULL) { LOG(THREAD, LOG_ASYNCH, 2, "\thandler for signal %d is "PFX"\n", i, info->app_sigaction[i]->handler); } } #endif mutex_unlock(info->shared_lock); } else { /* copy handlers */ LOG(THREAD, LOG_ASYNCH, 2, "inheriting signal handlers from parent\n"); info->app_sigaction = (kernel_sigaction_t **) handler_alloc(dcontext, SIGARRAY_SIZE * sizeof(kernel_sigaction_t *)); memset(info->app_sigaction, 0, SIGARRAY_SIZE * sizeof(kernel_sigaction_t *)); for (i = 1; i <= MAX_SIGNUM; i++) { info->restorer_valid[i] = -1; /* clear cache */ if (record->info.app_sigaction[i] != NULL) { info->app_sigaction[i] = (kernel_sigaction_t *) handler_alloc(dcontext, sizeof(kernel_sigaction_t)); memcpy(info->app_sigaction[i], record->info.app_sigaction[i], sizeof(kernel_sigaction_t)); LOG(THREAD, LOG_ASYNCH, 2, "\thandler for signal %d is "PFX"\n", i, info->app_sigaction[i]->handler); } } info->we_intercept = (bool *) handler_alloc(dcontext, SIGARRAY_SIZE * sizeof(bool)); memcpy(info->we_intercept, record->info.we_intercept, SIGARRAY_SIZE * sizeof(bool)); mutex_lock(&record->info.child_lock); record->info.num_unstarted_children--; mutex_unlock(&record->info.child_lock); /* this should be safe since parent should wait for us */ mutex_lock(&record->parent_info->child_lock); record->parent_info->num_unstarted_children--; mutex_unlock(&record->parent_info->child_lock); } /* itimers are either private or shared */ if (TEST(CLONE_THREAD, record->clone_flags) && os_itimers_thread_shared()) { ASSERT(record->info.shared_itimer); LOG(THREAD, LOG_ASYNCH, 2, "sharing itimers with parent\n"); info->shared_itimer = true; info->shared_itimer_refcount = record->info.shared_itimer_refcount; info->shared_itimer_underDR = record->info.shared_itimer_underDR; info->shared_itimer_lock = record->info.shared_itimer_lock; info->itimer = record->info.itimer; acquire_recursive_lock(info->shared_itimer_lock); (*info->shared_itimer_refcount)++; release_recursive_lock(info->shared_itimer_lock); /* shared_itimer_underDR will be incremented in start_itimer() */ } else { info->shared_itimer = false; init_itimer(dcontext, false/*!first thread*/); } if (APP_HAS_SIGSTACK(info)) { /* parent was under our control, so the real sigstack we see is just * the parent's being inherited -- clear it now */ memset(&info->app_sigstack, 0, sizeof(stack_t)); info->app_sigstack.ss_flags |= SS_DISABLE; } /* rest of state is never shared. * app_sigstack should already be in place, when we set up our sigstack * we asked for old sigstack. * FIXME: are current pending or blocked inherited? */ res = continuation_pc; #ifdef MACOS if (record->app_thread_xsp != 0) { HEAP_TYPE_FREE(GLOBAL_DCONTEXT, record, clone_record_t, ACCT_THREAD_MGT, true/*prot*/); } #endif } else { /* Initialize in isolation */ if (APP_HAS_SIGSTACK(info)) { /* parent was NOT under our control, so the real sigstack we see is * a real sigstack that was present before we took control */ LOG(THREAD, LOG_ASYNCH, 1, "app already has signal stack "PFX" - "PFX"\n", info->app_sigstack.ss_sp, info->app_sigstack.ss_sp + info->app_sigstack.ss_size); } signal_info_init_sigaction(dcontext, info); info->shared_itimer = false; /* we'll set to true if a child is created */ init_itimer(dcontext, true/*first*/); /* We split init vs start for the signal handlers and mask. We do not * install ours until we start running the app, to avoid races like * i#2335. We'll set them up when os_process_under_dynamorio_*() invokes * signal_reinstate_handlers(). All we do now is mark which signals we * want to intercept. */ if (DYNAMO_OPTION(intercept_all_signals)) { /* PR 304708: to support client signal handlers without * the complexity of per-thread and per-signal callbacks * we always intercept all signals. We also check here * for handlers the app registered before our init. */ for (i=1; i<=MAX_SIGNUM; i++) { /* cannot intercept KILL or STOP */ if (signal_is_interceptable(i) && /* FIXME PR 297033: we don't support intercepting DEFAULT_STOP / * DEFAULT_CONTINUE signals. Once add support, update * dr_register_signal_event() comments. */ default_action[i] != DEFAULT_STOP && default_action[i] != DEFAULT_CONTINUE) info->we_intercept[i] = true; } } else { /* we intercept the following signals ourselves: */ info->we_intercept[SIGSEGV] = true; /* PR 313665: look for DR crashes on unaligned memory or mmap bounds */ info->we_intercept[SIGBUS] = true; /* PR 212090: the signal we use to suspend threads */ info->we_intercept[SUSPEND_SIGNAL] = true; #ifdef PAPI /* use SIGPROF for updating gui so it can be distinguished from SIGVTALRM */ info->we_intercept[SIGPROF] = true; #endif /* vtalarm only used with pc profiling. it interferes w/ PAPI * so arm this signal only if necessary */ if (INTERNAL_OPTION(profile_pcs)) { info->we_intercept[SIGVTALRM] = true; } #ifdef CLIENT_INTERFACE info->we_intercept[SIGALRM] = true; #endif #ifdef SIDELINE info->we_intercept[SIGCHLD] = true; #endif /* i#61/PR 211530: the signal we use for nudges */ info->we_intercept[NUDGESIG_SIGNUM] = true; } /* should be 1st thread */ if (get_num_threads() > 1) ASSERT_NOT_REACHED(); /* FIXME: any way to recover if not 1st thread? */ res = NULL; } /* only when SIGVTALRM handler is in place should we start itimer (PR 537743) */ if (INTERNAL_OPTION(profile_pcs)) { /* even if the parent thread exits, we can use a pointer to its * pcprofile_info b/c when shared it's process-shared and is not freed * until the entire process exits */ pcprofile_thread_init(dcontext, info->shared_itimer, (record == NULL) ? NULL : record->pcprofile_info); } /* Assumed to be async safe. */ info->fully_initialized = true; return res; } /* When taking over existing app threads, we assume they're using pthreads and * expect to share signal handlers, memory, thread group id, etc. */ void share_siginfo_after_take_over(dcontext_t *dcontext, dcontext_t *takeover_dc) { clone_record_t crec = {0,}; thread_sig_info_t *parent_siginfo = (thread_sig_info_t*)takeover_dc->signal_field; /* Create a fake clone record with the given siginfo. All threads in the * same thread group must share signal handlers since Linux 2.5.35, but we * have to guess at the other flags. * FIXME i#764: If we take over non-pthreads threads, we'll need some way to * tell if they're sharing signal handlers or not. */ crec.caller_id = takeover_dc->owning_thread; #ifdef LINUX crec.clone_sysnum = SYS_clone; #else ASSERT_NOT_IMPLEMENTED(false); /* FIXME i#58: NYI on Mac */ #endif crec.clone_flags = PTHREAD_CLONE_FLAGS; crec.parent_info = parent_siginfo; crec.info = *parent_siginfo; crec.pcprofile_info = takeover_dc->pcprofile_field; signal_thread_inherit(dcontext, &crec); } /* This is split from os_fork_init() so the new logfiles are available * (xref i#189/PR 452168). It had to be after dynamo_other_thread_exit() * called in dynamorio_fork_init() after os_fork_init() else we clean * up data structs used in signal_thread_exit(). */ void signal_fork_init(dcontext_t *dcontext) { thread_sig_info_t *info = (thread_sig_info_t *) dcontext->signal_field; int i; /* Child of fork is a single thread in a new process so should * start over w/ no sharing (xref i#190/PR 452178) */ if (info->shared_app_sigaction) { info->shared_app_sigaction = false; if (info->shared_lock != NULL) { DELETE_LOCK(*info->shared_lock); global_heap_free(info->shared_lock, sizeof(mutex_t) HEAPACCT(ACCT_OTHER)); } if (info->shared_refcount != NULL) global_heap_free(info->shared_refcount, sizeof(int) HEAPACCT(ACCT_OTHER)); info->shared_lock = NULL; info->shared_refcount = NULL; } if (info->shared_itimer) { /* itimers are not inherited across fork */ info->shared_itimer = false; if (os_itimers_thread_shared()) global_heap_free(info->itimer, sizeof(*info->itimer) HEAPACCT(ACCT_OTHER)); else heap_free(dcontext, info->itimer, sizeof(*info->itimer) HEAPACCT(ACCT_OTHER)); info->itimer = NULL; /* reset by init_itimer */ ASSERT(info->shared_itimer_lock != NULL); DELETE_RECURSIVE_LOCK(*info->shared_itimer_lock); global_heap_free(info->shared_itimer_lock, sizeof(*info->shared_itimer_lock) HEAPACCT(ACCT_OTHER)); info->shared_itimer_lock = NULL; ASSERT(info->shared_itimer_refcount != NULL); global_heap_free(info->shared_itimer_refcount, sizeof(int) HEAPACCT(ACCT_OTHER)); info->shared_itimer_refcount = NULL; ASSERT(info->shared_itimer_underDR != NULL); global_heap_free(info->shared_itimer_underDR, sizeof(int) HEAPACCT(ACCT_OTHER)); info->shared_itimer_underDR = NULL; init_itimer(dcontext, true/*first*/); } info->num_unstarted_children = 0; for (i = 1; i <= MAX_SIGNUM; i++) { /* "A child created via fork(2) initially has an empty pending signal set" */ dcontext->signals_pending = 0; while (info->sigpending[i] != NULL) { sigpending_t *temp = info->sigpending[i]; info->sigpending[i] = temp->next; special_heap_free(info->sigheap, temp); } } if (INTERNAL_OPTION(profile_pcs)) { pcprofile_fork_init(dcontext); } /* Assumed to be async safe. */ info->fully_initialized = true; } #ifdef DEBUG static bool sigsegv_handler_is_ours(void) { int rc; kernel_sigaction_t oldact; rc = sigaction_syscall(SIGSEGV, NULL, &oldact); return (rc == 0 && oldact.handler == (handler_t)master_signal_handler); } #endif /* DEBUG */ #if defined(X86) && defined(LINUX) static byte * get_xstate_buffer(dcontext_t *dcontext) { /* See thread_sig_info_t.xstate_buf comments for why this is in TLS. */ thread_sig_info_t *info = (thread_sig_info_t *) dcontext->signal_field; if (info->xstate_buf == NULL) { info->xstate_alloc = heap_alloc(dcontext, signal_frame_extra_size(true) HEAPACCT(ACCT_OTHER)); info->xstate_buf = (byte *) ALIGN_FORWARD(info->xstate_alloc, XSTATE_ALIGNMENT); ASSERT(info->xstate_alloc + signal_frame_extra_size(true) >= info->xstate_buf + signal_frame_extra_size(false)); } return info->xstate_buf; } #endif void signal_thread_exit(dcontext_t *dcontext, bool other_thread) { thread_sig_info_t *info = (thread_sig_info_t *) dcontext->signal_field; int i; /* i#1012: DR's signal handler should always be installed before this point. */ ASSERT(sigsegv_handler_is_ours() || removed_sig_handler); while (info->num_unstarted_children > 0) { /* must wait for children to start and copy our state * before we destroy it! */ os_thread_yield(); } if (dynamo_exited) { /* stop itimers before removing signal handlers */ for (i = 0; i < NUM_ITIMERS; i++) set_actual_itimer(dcontext, i, info, false/*disable*/); } #if defined(X86) && defined(LINUX) if (info->xstate_alloc != NULL) { heap_free(dcontext, info->xstate_alloc, signal_frame_extra_size(true) HEAPACCT(ACCT_OTHER)); } #endif /* FIXME: w/ shared handlers, if parent (the owner here) dies, * can children keep living w/ a copy of the handlers? */ if (info->shared_app_sigaction) { mutex_lock(info->shared_lock); (*info->shared_refcount)--; mutex_unlock(info->shared_lock); } if (!info->shared_app_sigaction || *info->shared_refcount == 0) { LOG(THREAD, LOG_ASYNCH, 2, "signal handler cleanup:\n"); signal_info_exit_sigaction(dcontext, info, other_thread); if (info->shared_lock != NULL) { DELETE_LOCK(*info->shared_lock); global_heap_free(info->shared_lock, sizeof(mutex_t) HEAPACCT(ACCT_OTHER)); } if (info->shared_refcount != NULL) global_heap_free(info->shared_refcount, sizeof(int) HEAPACCT(ACCT_OTHER)); } if (info->shared_itimer) { acquire_recursive_lock(info->shared_itimer_lock); (*info->shared_itimer_refcount)--; release_recursive_lock(info->shared_itimer_lock); } if (!info->shared_itimer || *info->shared_itimer_refcount == 0) { if (INTERNAL_OPTION(profile_pcs)) { /* no cleanup needed for non-final thread in group */ pcprofile_thread_exit(dcontext); } if (os_itimers_thread_shared()) global_heap_free(info->itimer, sizeof(*info->itimer) HEAPACCT(ACCT_OTHER)); else heap_free(dcontext, info->itimer, sizeof(*info->itimer) HEAPACCT(ACCT_OTHER)); if (info->shared_itimer_lock != NULL) { DELETE_RECURSIVE_LOCK(*info->shared_itimer_lock); global_heap_free(info->shared_itimer_lock, sizeof(recursive_lock_t) HEAPACCT(ACCT_OTHER)); ASSERT(info->shared_itimer_refcount != NULL); global_heap_free(info->shared_itimer_refcount, sizeof(int) HEAPACCT(ACCT_OTHER)); ASSERT(info->shared_itimer_underDR != NULL); global_heap_free(info->shared_itimer_underDR, sizeof(int) HEAPACCT(ACCT_OTHER)); } } for (i = 1; i <= MAX_SIGNUM; i++) { /* pending queue is per-thread and not shared */ while (info->sigpending[i] != NULL) { sigpending_t *temp = info->sigpending[i]; info->sigpending[i] = temp->next; special_heap_free(info->sigheap, temp); } } signal_swap_mask(dcontext, true/*to_app*/); #ifdef HAVE_SIGALTSTACK /* Remove our sigstack and restore the app sigstack if it had one. */ if (!other_thread) { LOG(THREAD, LOG_ASYNCH, 2, "removing our signal stack "PFX" - "PFX"\n", info->sigstack.ss_sp, info->sigstack.ss_sp + info->sigstack.ss_size); if (APP_HAS_SIGSTACK(info)) { LOG(THREAD, LOG_ASYNCH, 2, "restoring app signal stack "PFX" - "PFX"\n", info->app_sigstack.ss_sp, info->app_sigstack.ss_sp + info->app_sigstack.ss_size); } else { ASSERT(TEST(SS_DISABLE, info->app_sigstack.ss_flags)); } if (info->sigstack.ss_sp != NULL) { /* i#552: to raise client exit event, we may call dynamo_process_exit * on sigstack in signal handler. * In that case we set sigstack (ss_sp) NULL to avoid stack swap. */ # ifdef MACOS if (info->app_sigstack.ss_sp == NULL) { /* Kernel fails w/ ENOMEM (even for SS_DISABLE) if ss_size is too small */ info->sigstack.ss_flags = SS_DISABLE; i = sigaltstack_syscall(&info->sigstack, NULL); /* i#1814: kernel gives EINVAL if last handler didn't call sigreturn! */ ASSERT(i == 0 || i == -EINVAL); } else { i = sigaltstack_syscall(&info->app_sigstack, NULL); /* i#1814: kernel gives EINVAL if last handler didn't call sigreturn! */ ASSERT(i == 0 || i == -EINVAL); } # else i = sigaltstack_syscall(&info->app_sigstack, NULL); ASSERT(i == 0); # endif } } #endif IF_LINUX(signalfd_thread_exit(dcontext, info)); special_heap_exit(info->sigheap); DELETE_LOCK(info->child_lock); #ifdef DEBUG /* for non-debug we do fast exit path and don't free local heap */ # ifdef HAVE_SIGALTSTACK if (info->sigstack.ss_sp != NULL) { /* i#552: to raise client exit event, we may call dynamo_process_exit * on sigstack in signal handler. * In that case we set sigstack (ss_sp) NULL to avoid stack free. */ stack_free(info->sigstack.ss_sp + info->sigstack.ss_size, info->sigstack.ss_size); } # endif HEAP_TYPE_FREE(dcontext, info, thread_sig_info_t, ACCT_OTHER, PROTECTED); #endif #ifdef PAPI /* use SIGPROF for updating gui so it can be distinguished from SIGVTALRM */ set_itimer_callback(dcontext, ITIMER_PROF, 500, (void (*func)(dcontext_t *, priv_mcontext_t *)) perfctr_update_gui()); #endif } void set_handler_sigact(kernel_sigaction_t *act, int sig, handler_t handler) { act->handler = handler; #ifdef MACOS /* This is the real target */ act->tramp = (tramp_t) handler; #endif act->flags = SA_SIGINFO; /* send 3 args to handler */ #ifdef HAVE_SIGALTSTACK act->flags |= SA_ONSTACK; /* use our sigstack */ #endif #if defined(X64) && !defined(VMX86_SERVER) && defined(LINUX) /* PR 305020: must have SA_RESTORER for x64 */ act->flags |= SA_RESTORER; act->restorer = (void (*)(void)) dynamorio_sigreturn; #endif /* We block most signals within our handler */ kernel_sigfillset(&act->mask); /* i#184/PR 450670: we let our suspend signal interrupt our own handler * We never send more than one before resuming, so no danger to stack usage * from our own: but app could pile them up. */ kernel_sigdelset(&act->mask, SUSPEND_SIGNAL); /* i#193/PR 287309: we need to NOT suppress further SIGSEGV, for decode faults, * for try/except, and for !HAVE_MEMINFO probes. * Just like SUSPEND_SIGNAL, if app sends repeated SEGV, could run out of * alt stack: seems too corner-case to be worth increasing stack size. */ kernel_sigdelset(&act->mask, SIGSEGV); if (sig == SUSPEND_SIGNAL || sig == SIGSEGV) act->flags |= SA_NODEFER; /* Sigset is a 1 or 2 elt array of longs on X64/X86. Treat as 2 elt of * uint32. */ IF_DEBUG(uint32 *mask_sig = (uint32*)&act->mask.sig[0]); LOG(THREAD_GET, LOG_ASYNCH, 3, "mask for our handler is "PFX" "PFX"\n", mask_sig[0], mask_sig[1]); } static void set_our_handler_sigact(kernel_sigaction_t *act, int sig) { set_handler_sigact(act, sig, (handler_t) master_signal_handler); } static void set_handler_and_record_app(dcontext_t *dcontext, thread_sig_info_t *info, int sig, kernel_sigaction_t *act) { int rc; kernel_sigaction_t oldact; ASSERT(sig <= MAX_SIGNUM); /* arm the signal */ rc = sigaction_syscall(sig, act, &oldact); ASSERT(rc == 0 /* Workaround for PR 223720, which was fixed in ESX4.0 but * is present in ESX3.5 and earlier: vmkernel treats * 63 and 64 as invalid signal numbers. */ IF_VMX86(|| (sig >= 63 && rc == -EINVAL)) ); if (rc != 0) /* be defensive: app will probably still work */ return; if (oldact.handler != (handler_t) SIG_DFL && oldact.handler != (handler_t) master_signal_handler) { /* save the app's action for sig */ if (info->shared_app_sigaction) { /* app_sigaction structure is shared */ mutex_lock(info->shared_lock); } if (info->app_sigaction[sig] != NULL) { /* go ahead and toss the old one, it's up to the app to store * and then restore later if it wants to */ handler_free(dcontext, info->app_sigaction[sig], sizeof(kernel_sigaction_t)); } info->app_sigaction[sig] = (kernel_sigaction_t *) handler_alloc(dcontext, sizeof(kernel_sigaction_t)); memcpy(info->app_sigaction[sig], &oldact, sizeof(kernel_sigaction_t)); /* clear cache */ info->restorer_valid[sig] = -1; if (info->shared_app_sigaction) mutex_unlock(info->shared_lock); #ifdef DEBUG if (oldact.handler == (handler_t) SIG_IGN) { LOG(THREAD, LOG_ASYNCH, 2, "app already installed SIG_IGN as sigaction for signal %d\n", sig); } else { LOG(THREAD, LOG_ASYNCH, 2, "app already installed "PFX" as sigaction flags=0x%x for signal %d\n", oldact.handler, oldact.flags, sig); } #endif } LOG(THREAD, LOG_ASYNCH, 3, "\twe intercept signal %d\n", sig); } /* Set up master_signal_handler as the handler for signal "sig", * for the current thread. Since we deal with kernel data structures * in our interception of system calls, we use them here as well, * to avoid having to translate to/from libc data structures. */ static void intercept_signal(dcontext_t *dcontext, thread_sig_info_t *info, int sig) { kernel_sigaction_t act; ASSERT(sig <= MAX_SIGNUM); set_our_handler_sigact(&act, sig); set_handler_and_record_app(dcontext, info, sig, &act); } static void intercept_signal_ignore_initially(dcontext_t *dcontext, thread_sig_info_t *info, int sig) { kernel_sigaction_t act; ASSERT(sig <= MAX_SIGNUM); memset(&act, 0, sizeof(act)); act.handler = (handler_t) SIG_IGN; set_handler_and_record_app(dcontext, info, sig, &act); } static void intercept_signal_no_longer_ignore(dcontext_t *dcontext, thread_sig_info_t *info, int sig) { kernel_sigaction_t act; int rc; ASSERT(sig <= MAX_SIGNUM); set_our_handler_sigact(&act, sig); rc = sigaction_syscall(sig, &act, NULL); ASSERT(rc == 0); } /* i#1921: For proper single-threaded native execution with re-takeover we need * to propagate signals. For now we only support going completely native in * this thread but without a full detach, so we abandon our signal handlers w/o * freeing memory up front. * We also use this for the start/stop interface where we are going fully native * for all threads. */ void signal_remove_handlers(dcontext_t *dcontext) { thread_sig_info_t *info = (thread_sig_info_t *) dcontext->signal_field; int i; kernel_sigaction_t act; memset(&act, 0, sizeof(act)); act.handler = (handler_t) SIG_DFL; kernel_sigemptyset(&act.mask); for (i = 1; i <= MAX_SIGNUM; i++) { if (info->app_sigaction[i] != NULL) { LOG(THREAD, LOG_ASYNCH, 2, "\trestoring "PFX" as handler for %d\n", info->app_sigaction[i]->handler, i); sigaction_syscall(i, info->app_sigaction[i], NULL); } else if (info->we_intercept[i]) { /* restore to default */ LOG(THREAD, LOG_ASYNCH, 2, "\trestoring SIG_DFL as handler for %d\n", i); sigaction_syscall(i, &act, NULL); } } } void signal_remove_alarm_handlers(dcontext_t *dcontext) { thread_sig_info_t *info = (thread_sig_info_t *) dcontext->signal_field; int i; for (i = 1; i <= MAX_SIGNUM; i++) { if (!info->we_intercept[i]) continue; if (sig_is_alarm_signal(i)) { set_ignore_signal_action(i); } } } /* For attaching mid-run, we assume regular POSIX with handlers global to just one * thread group in the process. * We also use this routine for the initial setup of our handlers, which we * split from signal_thread_inherit() to support start/stop. */ void signal_reinstate_handlers(dcontext_t *dcontext, bool ignore_alarm) { thread_sig_info_t *info = (thread_sig_info_t *) dcontext->signal_field; int i; for (i = 1; i <= MAX_SIGNUM; i++) { bool skip = false; if (!info->we_intercept[i]) { skip = true; if (signal_is_interceptable(i)) { /* We do have to intercept everything the app does. * If the app removes its handler, we'll never remove ours, which we * can live with. */ kernel_sigaction_t oldact; int rc = sigaction_syscall(i, NULL, &oldact); ASSERT(rc == 0); if (rc == 0 && oldact.handler != (handler_t) SIG_DFL && oldact.handler != (handler_t) master_signal_handler) { skip = false; } } } if (skip) continue; if (sig_is_alarm_signal(i) && ignore_alarm) { LOG(THREAD, LOG_ASYNCH, 2, "\tignoring %d initially\n", i); intercept_signal_ignore_initially(dcontext, info, i); } else { LOG(THREAD, LOG_ASYNCH, 2, "\trestoring DR handler for %d\n", i); intercept_signal(dcontext, info, i); } } } void signal_reinstate_alarm_handlers(dcontext_t *dcontext) { thread_sig_info_t *info = (thread_sig_info_t *) dcontext->signal_field; int i; for (i = 1; i <= MAX_SIGNUM; i++) { if (!info->we_intercept[i] || !sig_is_alarm_signal(i)) continue; LOG(THREAD, LOG_ASYNCH, 2, "\trestoring DR handler for %d\n", i); intercept_signal_no_longer_ignore(dcontext, info, i); } } /**** system call handlers ***********************************************/ /* FIXME: invalid pointer passed to kernel will currently show up * probably as a segfault in our handlers below...need to make them * look like kernel, and pass error code back to os.c */ void handle_clone(dcontext_t *dcontext, uint flags) { thread_sig_info_t *info = (thread_sig_info_t *) dcontext->signal_field; if ((flags & CLONE_VM) == 0) { /* separate process not sharing memory */ if ((flags & CLONE_SIGHAND) != 0) { /* FIXME: how deal with this? * "man clone" says: "Since Linux 2.6.0-test6, flags must also * include CLONE_VM if CLONE_SIGHAND is specified" */ LOG(THREAD, LOG_ASYNCH, 1, "WARNING: !CLONE_VM but CLONE_SIGHAND!\n"); ASSERT_NOT_IMPLEMENTED(false); } return; } pre_second_thread(); if ((flags & CLONE_SIGHAND) != 0) { /* need to share table of handlers! */ LOG(THREAD, LOG_ASYNCH, 2, "handle_clone: CLONE_SIGHAND set!\n"); if (!info->shared_app_sigaction) { /* this is the start of a chain of sharing * no synch needed here, child not created yet */ info->shared_app_sigaction = true; info->shared_refcount = (int *) global_heap_alloc(sizeof(int) HEAPACCT(ACCT_OTHER)); *info->shared_refcount = 1; info->shared_lock = (mutex_t *) global_heap_alloc(sizeof(mutex_t) HEAPACCT(ACCT_OTHER)); ASSIGN_INIT_LOCK_FREE(*info->shared_lock, shared_lock); } /* else, some ancestor is already owner */ } else { /* child will inherit copy of current table -> cannot modify it * until child is scheduled! FIXME: any other way? */ mutex_lock(&info->child_lock); info->num_unstarted_children++; mutex_unlock(&info->child_lock); } if (TEST(CLONE_THREAD, flags) && os_itimers_thread_shared()) { if (!info->shared_itimer) { /* this is the start of a chain of sharing * no synch needed here, child not created yet */ info->shared_itimer = true; info->shared_itimer_refcount = (int *) global_heap_alloc(sizeof(int) HEAPACCT(ACCT_OTHER)); *info->shared_itimer_refcount = 1; info->shared_itimer_underDR = (int *) global_heap_alloc(sizeof(int) HEAPACCT(ACCT_OTHER)); *info->shared_itimer_underDR = 1; info->shared_itimer_lock = (recursive_lock_t *) global_heap_alloc(sizeof(*info->shared_itimer_lock) HEAPACCT(ACCT_OTHER)); ASSIGN_INIT_RECURSIVE_LOCK_FREE(*info->shared_itimer_lock, shared_itimer_lock); } /* else, some ancestor already created */ } } /* Returns false if should NOT issue syscall. * In such a case, the result is in "result". * We could instead issue the syscall and expect it to fail, which would have a more * accurate error code, but that risks missing a failure (e.g., RT on Android * which in some cases returns success on bugus params). * It seems better to err on the side of the wrong error code or failing when * we shouldn't, than to think it failed when it didn't, which is more complex * to deal with. */ bool handle_sigaction(dcontext_t *dcontext, int sig, const kernel_sigaction_t *act, prev_sigaction_t *oact, size_t sigsetsize, OUT uint *result) { thread_sig_info_t *info = (thread_sig_info_t *) dcontext->signal_field; kernel_sigaction_t *save; kernel_sigaction_t local_act; if (sigsetsize != sizeof(kernel_sigset_t)) { *result = EINVAL; return false; } if (act != NULL) { /* Linux checks readability before checking the signal number. */ if (!safe_read(act, sizeof(local_act), &local_act)) { *result = EFAULT; return false; } } /* i#1135: app may pass invalid signum to find MAX_SIGNUM */ if (sig <= 0 || sig > MAX_SIGNUM || (act != NULL && !signal_is_interceptable(sig))) { *result = EINVAL; return false; } if (act != NULL) { /* app is installing a new action */ while (info->num_unstarted_children > 0) { /* must wait for children to start and copy our state * before we modify it! */ os_thread_yield(); } info->sigaction_param = act; } if (info->shared_app_sigaction) { /* app_sigaction structure is shared */ mutex_lock(info->shared_lock); } if (oact != NULL) { /* Keep a copy of the prior one for post-syscall to hand to the app. */ info->use_kernel_prior_sigaction = false; if (info->app_sigaction[sig] == NULL) { if (info->we_intercept[sig]) { /* need to pretend there is no handler */ memset(&info->prior_app_sigaction, 0, sizeof(info->prior_app_sigaction)); info->prior_app_sigaction.handler = (handler_t) SIG_DFL; } else { info->use_kernel_prior_sigaction = true; } } else { memcpy(&info->prior_app_sigaction, info->app_sigaction[sig], sizeof(info->prior_app_sigaction)); } } if (act != NULL) { if (local_act.handler == (handler_t) SIG_IGN || local_act.handler == (handler_t) SIG_DFL) { LOG(THREAD, LOG_ASYNCH, 2, "app installed %s as sigaction for signal %d\n", (local_act.handler == (handler_t) SIG_IGN) ? "SIG_IGN" : "SIG_DFL", sig); if (!info->we_intercept[sig]) { /* let the SIG_IGN/SIG_DFL go through, we want to remove our * handler. we delete the stored app_sigaction in post_ */ if (info->shared_app_sigaction) mutex_unlock(info->shared_lock); return true; } } else { LOG(THREAD, LOG_ASYNCH, 2, "app installed "PFX" as sigaction for signal %d\n", local_act.handler, sig); DOLOG(2, LOG_ASYNCH, { LOG(THREAD, LOG_ASYNCH, 2, "signal mask for handler:\n"); dump_sigset(dcontext, (kernel_sigset_t *) &local_act.mask); }); } /* save app's entire sigaction struct */ save = (kernel_sigaction_t *) handler_alloc(dcontext, sizeof(kernel_sigaction_t)); memcpy(save, &local_act, sizeof(kernel_sigaction_t)); /* Remove the unblockable sigs */ kernel_sigdelset(&save->mask, SIGKILL); kernel_sigdelset(&save->mask, SIGSTOP); if (info->app_sigaction[sig] != NULL) { /* go ahead and toss the old one, it's up to the app to store * and then restore later if it wants to */ handler_free(dcontext, info->app_sigaction[sig], sizeof(kernel_sigaction_t)); } info->app_sigaction[sig] = save; LOG(THREAD, LOG_ASYNCH, 3, "\tflags = "PFX", %s = "PFX"\n", local_act.flags, IF_MACOS_ELSE("tramp","restorer"), IF_MACOS_ELSE(local_act.tramp, local_act.restorer)); /* clear cache */ info->restorer_valid[sig] = -1; } if (info->shared_app_sigaction) mutex_unlock(info->shared_lock); if (info->we_intercept[sig]) { /* cancel the syscall */ *result = handle_post_sigaction(dcontext, true, sig, act, oact, sigsetsize); return false; } if (act != NULL) { /* Now hand kernel our master handler instead of app's. */ set_our_handler_sigact(&info->our_sigaction, sig); set_syscall_param(dcontext, 1, (reg_t)&info->our_sigaction); /* FIXME PR 297033: we don't support intercepting DEFAULT_STOP / * DEFAULT_CONTINUE signals b/c we can't generate the default * action: if the app registers a handler, though, we should work * properly if we never see SIG_DFL. */ } return true; } /* os.c thinks it's passing us struct_sigaction, really it's kernel_sigaction_t, * which has fields in different order. * Only called on success. * Returns the desired app return value (caller will negate if nec). */ uint handle_post_sigaction(dcontext_t *dcontext, bool success, int sig, const kernel_sigaction_t *act, prev_sigaction_t *oact, size_t sigsetsize) { thread_sig_info_t *info = (thread_sig_info_t *) dcontext->signal_field; if (act != NULL) { /* Restore app register value, in case we changed it. */ set_syscall_param(dcontext, 1, (reg_t)info->sigaction_param); } if (!success) return 0; /* don't change return value */ ASSERT(sig <= MAX_SIGNUM && sig > 0); if (oact != NULL) { if (info->use_kernel_prior_sigaction) { /* Real syscall succeeded with oact so it must be readable, barring races. */ ASSERT(oact->handler == (handler_t) SIG_IGN || oact->handler == (handler_t) SIG_DFL); } else { /* We may have skipped the syscall so we have to check writability */ #ifdef MACOS /* On MacOS prev_sigaction_t is a different type (i#2105) */ bool fault = true; TRY_EXCEPT(dcontext, { oact->handler = info->prior_app_sigaction.handler; oact->mask = info->prior_app_sigaction.mask; oact->flags = info->prior_app_sigaction.flags; fault = false; } , { /* EXCEPT */ /* nothing: fault is already true */ }); if (fault) return EFAULT; #else if (!safe_write_ex(oact, sizeof(*oact), &info->prior_app_sigaction, NULL)) { /* We actually don't have to undo installing any passed action * b/c the Linux kernel does that *before* checking oact perms. */ return EFAULT; } #endif } } /* If installing IGN or DFL, delete ours. * XXX: This is racy. We can't hold the lock across the syscall, though. * What we should do is just drop support for -no_intercept_all_signals, * which is off by default anyway and never turned off. */ if (act != NULL && /* De-ref here should work barring races: already racy and non-default so not * bothering with safe_read. */ ((act->handler == (handler_t) SIG_IGN || act->handler == (handler_t) SIG_DFL) && !info->we_intercept[sig]) && info->app_sigaction[sig] != NULL) { if (info->shared_app_sigaction) mutex_lock(info->shared_lock); /* remove old stored app action */ handler_free(dcontext, info->app_sigaction[sig], sizeof(kernel_sigaction_t)); info->app_sigaction[sig] = NULL; if (info->shared_app_sigaction) mutex_unlock(info->shared_lock); } return 0; } #ifdef LINUX static bool convert_old_sigaction_to_kernel(dcontext_t *dcontext, kernel_sigaction_t *ks, const old_sigaction_t *os) { bool res = false; TRY_EXCEPT(dcontext, { ks->handler = os->handler; ks->flags = os->flags; ks->restorer = os->restorer; kernel_sigemptyset(&ks->mask); ks->mask.sig[0] = os->mask; res = true; } , { /* EXCEPT */ /* nothing: res is already false */ }); return res; } static bool convert_kernel_sigaction_to_old(dcontext_t *dcontext, old_sigaction_t *os, const kernel_sigaction_t *ks) { bool res = false; TRY_EXCEPT(dcontext, { os->handler = ks->handler; os->flags = ks->flags; os->restorer = ks->restorer; os->mask = ks->mask.sig[0]; res = true; } , { /* EXCEPT */ /* nothing: res is already false */ }); return res; } /* Returns false (and "result") if should NOT issue syscall. */ bool handle_old_sigaction(dcontext_t *dcontext, int sig, const old_sigaction_t *act, old_sigaction_t *oact, OUT uint *result) { kernel_sigaction_t kact; kernel_sigaction_t okact; bool res; if (act != NULL) { if (!convert_old_sigaction_to_kernel(dcontext, &kact, act)) { *result = EFAULT; return false; } } res = handle_sigaction(dcontext, sig, act == NULL ? NULL : &kact, oact == NULL ? NULL : &okact, sizeof(kernel_sigset_t), result); if (!res) *result = handle_post_old_sigaction(dcontext, true, sig, act, oact); return res; } /* Returns the desired app return value (caller will negate if nec). */ uint handle_post_old_sigaction(dcontext_t *dcontext, bool success, int sig, const old_sigaction_t *act, old_sigaction_t *oact) { kernel_sigaction_t kact; kernel_sigaction_t okact; ptr_uint_t res; if (act != NULL && success) { if (!convert_old_sigaction_to_kernel(dcontext, &kact, act)) { ASSERT(!success); return EFAULT; } } if (oact != NULL && success) { if (!convert_old_sigaction_to_kernel(dcontext, &okact, oact)) { ASSERT(!success); return EFAULT; } } res = handle_post_sigaction(dcontext, success, sig, act == NULL ? NULL : &kact, oact == NULL ? NULL : &okact, sizeof(kernel_sigset_t)); if (res == 0 && oact != NULL) { if (!convert_kernel_sigaction_to_old(dcontext, oact, &okact)) { return EFAULT; } } return res; } #endif /* LINUX */ /* Returns false if should NOT issue syscall */ bool handle_sigaltstack(dcontext_t *dcontext, const stack_t *stack, stack_t *old_stack) { thread_sig_info_t *info = (thread_sig_info_t *) dcontext->signal_field; if (old_stack != NULL) { *old_stack = info->app_sigstack; } if (stack != NULL) { info->app_sigstack = *stack; LOG(THREAD, LOG_ASYNCH, 2, "app set up signal stack "PFX" - "PFX" %s\n", stack->ss_sp, stack->ss_sp + stack->ss_size - 1, (APP_HAS_SIGSTACK(info)) ? "enabled" : "disabled"); return false; /* always cancel syscall */ } return true; } /* Blocked signals: * In general, we don't need to keep track of blocked signals. * We only need to do so for those signals we intercept ourselves. * Thus, info->app_sigblocked ONLY contains entries for signals * we intercept ourselves. * PR 304708: we now intercept all signals. */ static void set_blocked(dcontext_t *dcontext, kernel_sigset_t *set, bool absolute) { thread_sig_info_t *info = (thread_sig_info_t *) dcontext->signal_field; int i; if (absolute) { /* discard current blocked signals, re-set from new mask */ kernel_sigemptyset(&info->app_sigblocked); } /* else, OR in the new set */ for (i=1; i<=MAX_SIGNUM; i++) { if (EMULATE_SIGMASK(info, i) && kernel_sigismember(set, i)) { kernel_sigaddset(&info->app_sigblocked, i); } } #ifdef DEBUG if (stats->loglevel >= 3 && (stats->logmask & LOG_ASYNCH) != 0) { LOG(THREAD, LOG_ASYNCH, 3, "blocked signals are now:\n"); dump_sigset(dcontext, &info->app_sigblocked); } #endif } void signal_set_mask(dcontext_t *dcontext, kernel_sigset_t *sigset) { set_blocked(dcontext, sigset, true/*absolute*/); } void signal_swap_mask(dcontext_t *dcontext, bool to_app) { thread_sig_info_t *info = (thread_sig_info_t *) dcontext->signal_field; if (to_app) { if (init_info.app_sigaction != NULL) { /* This is the first execution of the app. * We need to remove our own init-time handler and mask. */ unset_initial_crash_handlers(dcontext); return; } sigprocmask_syscall(SIG_SETMASK, &info->app_sigblocked, NULL, sizeof(info->app_sigblocked)); } else { unblock_all_signals(&info->app_sigblocked); DOLOG(2, LOG_ASYNCH, { LOG(THREAD, LOG_ASYNCH, 2, "thread %d's initial app signal mask:\n", get_thread_id()); dump_sigset(dcontext, &info->app_sigblocked); }); } } /* Scans over info->sigpending to see if there are any unblocked, pending * signals, and sets dcontext->signals_pending if there are. Do this after * modifying the set of signals blocked by the application. */ static void check_signals_pending(dcontext_t *dcontext, thread_sig_info_t *info) { int i; if (dcontext->signals_pending != 0) return; for (i=1; i<=MAX_SIGNUM; i++) { if (info->sigpending[i] != NULL && !kernel_sigismember(&info->app_sigblocked, i) && !dcontext->signals_pending) { /* We only update the application's set of blocked signals from * syscall handlers, so we know we'll go back to dispatch and see * this flag right away. */ LOG(THREAD, LOG_ASYNCH, 3, "\tsetting signals_pending flag\n"); dcontext->signals_pending = 1; break; } } } /* Returns whether to execute the syscall */ bool handle_sigprocmask(dcontext_t *dcontext, int how, kernel_sigset_t *app_set, kernel_sigset_t *oset, size_t sigsetsize) { thread_sig_info_t *info = (thread_sig_info_t *) dcontext->signal_field; int i; kernel_sigset_t safe_set; /* If we're intercepting all, we emulate the whole thing */ bool execute_syscall = !DYNAMO_OPTION(intercept_all_signals); LOG(THREAD, LOG_ASYNCH, 2, "handle_sigprocmask\n"); if (oset != NULL) info->pre_syscall_app_sigblocked = info->app_sigblocked; if (app_set != NULL && safe_read(app_set, sizeof(safe_set), &safe_set)) { if (execute_syscall) { /* The syscall will execute, so remove from the set passed * to it. We restore post-syscall. * XXX i#1187: we could crash here touching app memory -- could * use TRY, but the app could pass read-only memory and it * would work natively! Better to swap in our own * allocated data struct. There's a transparency issue w/ * races too if another thread looks at this memory. This * won't happen by default b/c -intercept_all_signals is * on by default so we don't try to solve all these * issues. */ info->pre_syscall_app_sigprocmask = safe_set; } if (how == SIG_BLOCK) { /* The set of blocked signals is the union of the current * set and the set argument. */ for (i=1; i<=MAX_SIGNUM; i++) { if (EMULATE_SIGMASK(info, i) && kernel_sigismember(&safe_set, i)) { kernel_sigaddset(&info->app_sigblocked, i); if (execute_syscall) kernel_sigdelset(app_set, i); } } } else if (how == SIG_UNBLOCK) { /* The signals in set are removed from the current set of * blocked signals. */ for (i=1; i<=MAX_SIGNUM; i++) { if (EMULATE_SIGMASK(info, i) && kernel_sigismember(&safe_set, i)) { kernel_sigdelset(&info->app_sigblocked, i); if (execute_syscall) kernel_sigdelset(app_set, i); } } } else if (how == SIG_SETMASK) { /* The set of blocked signals is set to the argument set. */ kernel_sigemptyset(&info->app_sigblocked); for (i=1; i<=MAX_SIGNUM; i++) { if (EMULATE_SIGMASK(info, i) && kernel_sigismember(&safe_set, i)) { kernel_sigaddset(&info->app_sigblocked, i); if (execute_syscall) kernel_sigdelset(app_set, i); } } } #ifdef DEBUG if (stats->loglevel >= 3 && (stats->logmask & LOG_ASYNCH) != 0) { LOG(THREAD, LOG_ASYNCH, 3, "blocked signals are now:\n"); dump_sigset(dcontext, &info->app_sigblocked); } #endif /* make sure we deliver pending signals that are now unblocked * FIXME: consider signal #S, which we intercept ourselves. * If S arrives, then app blocks it prior to our delivering it, * we then won't deliver it until app unblocks it...is this a * problem? Could have arrived a little later and then we would * do same thing, but this way kernel may send one more than would * get w/o dynamo? This goes away if we deliver signals * prior to letting app do a syscall. */ check_signals_pending(dcontext, info); } if (!execute_syscall) { handle_post_sigprocmask(dcontext, how, app_set, oset, sigsetsize); return false; /* skip syscall */ } else return true; } /* need to add in our signals that the app thinks are blocked */ void handle_post_sigprocmask(dcontext_t *dcontext, int how, kernel_sigset_t *app_set, kernel_sigset_t *oset, size_t sigsetsize) { thread_sig_info_t *info = (thread_sig_info_t *) dcontext->signal_field; int i; if (!DYNAMO_OPTION(intercept_all_signals)) { /* Restore app memory */ safe_write_ex(app_set, sizeof(*app_set), &info->pre_syscall_app_sigprocmask, NULL); } if (oset != NULL) { if (DYNAMO_OPTION(intercept_all_signals)) safe_write_ex(oset, sizeof(*oset), &info->pre_syscall_app_sigblocked, NULL); else { /* the syscall wrote to oset already, so just add any additional */ for (i=1; i<=MAX_SIGNUM; i++) { if (EMULATE_SIGMASK(info, i) && /* use the pre-syscall value: do not take into account changes * from this syscall itself! (PR 523394) */ kernel_sigismember(&info->pre_syscall_app_sigblocked, i)) { kernel_sigaddset(oset, i); } } } } } void handle_sigsuspend(dcontext_t *dcontext, kernel_sigset_t *set, size_t sigsetsize) { thread_sig_info_t *info = (thread_sig_info_t *) dcontext->signal_field; int i; ASSERT(set != NULL); LOG(THREAD, LOG_ASYNCH, 2, "handle_sigsuspend\n"); info->in_sigsuspend = true; info->app_sigblocked_save = info->app_sigblocked; kernel_sigemptyset(&info->app_sigblocked); for (i=1; i<=MAX_SIGNUM; i++) { if (EMULATE_SIGMASK(info, i) && kernel_sigismember(set, i)) { kernel_sigaddset(&info->app_sigblocked, i); kernel_sigdelset(set, i); } } #ifdef DEBUG if (stats->loglevel >= 3 && (stats->logmask & LOG_ASYNCH) != 0) { LOG(THREAD, LOG_ASYNCH, 3, "in sigsuspend, blocked signals are now:\n"); dump_sigset(dcontext, &info->app_sigblocked); } #endif } /**** utility routines ***********************************************/ #ifdef DEBUG static void dump_sigset(dcontext_t *dcontext, kernel_sigset_t *set) { int sig; for (sig=1; sig<=MAX_SIGNUM; sig++) { if (kernel_sigismember(set, sig)) LOG(THREAD, LOG_ASYNCH, 1, "\t%d = blocked\n", sig); } } #endif /* DEBUG */ /* PR 205795: to avoid lock problems w/ in_fcache (it grabs a lock, we * could have interrupted someone holding that), we first check * whereami --- if whereami is WHERE_FCACHE we still check the pc * to distinguish generated routines, but at least we're certain * it's not in DR where it could own a lock. * We can't use is_on_dstack() here b/c we need to handle clean call * arg crashes -- which is too bad since checking client dll and DR dll is * not sufficient due to calls to ntdll, libc, or pc being in gencode. */ static bool safe_is_in_fcache(dcontext_t *dcontext, app_pc pc, app_pc xsp) { if (dcontext->whereami != WHERE_FCACHE || IF_CLIENT_INTERFACE(is_in_client_lib(pc) ||) is_in_dynamo_dll(pc) || is_on_initstack(xsp)) return false; /* Reasonably certain not in DR code, so no locks should be held */ return in_fcache(pc); } static bool safe_is_in_coarse_stubs(dcontext_t *dcontext, app_pc pc, app_pc xsp) { if (dcontext->whereami != WHERE_FCACHE || IF_CLIENT_INTERFACE(is_in_client_lib(pc) ||) is_in_dynamo_dll(pc) || is_on_initstack(xsp)) return false; /* Reasonably certain not in DR code, so no locks should be held */ return in_coarse_stubs(pc); } static bool is_on_alt_stack(dcontext_t *dcontext, byte *sp) { #ifdef HAVE_SIGALTSTACK thread_sig_info_t *info = (thread_sig_info_t *) dcontext->signal_field; return (sp >= (byte *) info->sigstack.ss_sp && /* deliberate equality check since stacks often init to top */ sp <= (byte *) (info->sigstack.ss_sp + info->sigstack.ss_size)); #else return false; #endif } /* The caller must initialize ucxt, including its fpstate pointer for x86 Linux. */ static void sig_full_initialize(sig_full_cxt_t *sc_full, kernel_ucontext_t *ucxt) { sc_full->sc = SIGCXT_FROM_UCXT(ucxt); #ifdef X86 sc_full->fp_simd_state = NULL; /* we have a ptr inside sigcontext_t */ #elif defined(ARM) sc_full->fp_simd_state = &ucxt->coproc.uc_vfp; #elif defined(AARCH64) sc_full->fp_simd_state = &ucxt->uc_mcontext.__reserved; #else ASSERT_NOT_IMPLEMENTED(false); #endif } void sigcontext_to_mcontext(priv_mcontext_t *mc, sig_full_cxt_t *sc_full) { sigcontext_t *sc = sc_full->sc; ASSERT(mc != NULL && sc != NULL); #ifdef X86 mc->xax = sc->SC_XAX; mc->xbx = sc->SC_XBX; mc->xcx = sc->SC_XCX; mc->xdx = sc->SC_XDX; mc->xsi = sc->SC_XSI; mc->xdi = sc->SC_XDI; mc->xbp = sc->SC_XBP; mc->xsp = sc->SC_XSP; mc->xflags = sc->SC_XFLAGS; mc->pc = (app_pc) sc->SC_XIP; # ifdef X64 mc->r8 = sc->SC_FIELD(r8); mc->r9 = sc->SC_FIELD(r9); mc->r10 = sc->SC_FIELD(r10); mc->r11 = sc->SC_FIELD(r11); mc->r12 = sc->SC_FIELD(r12); mc->r13 = sc->SC_FIELD(r13); mc->r14 = sc->SC_FIELD(r14); mc->r15 = sc->SC_FIELD(r15); # endif /* X64 */ #elif defined(AARCH64) memcpy(&mc->r0, &sc->SC_FIELD(regs[0]), sizeof(mc->r0) * 31); mc->sp = sc->SC_FIELD(sp); mc->pc = (void *)sc->SC_FIELD(pc); mc->nzcv = sc->SC_FIELD(pstate); #elif defined (ARM) mc->r0 = sc->SC_FIELD(arm_r0); mc->r1 = sc->SC_FIELD(arm_r1); mc->r2 = sc->SC_FIELD(arm_r2); mc->r3 = sc->SC_FIELD(arm_r3); mc->r4 = sc->SC_FIELD(arm_r4); mc->r5 = sc->SC_FIELD(arm_r5); mc->r6 = sc->SC_FIELD(arm_r6); mc->r7 = sc->SC_FIELD(arm_r7); mc->r8 = sc->SC_FIELD(arm_r8); mc->r9 = sc->SC_FIELD(arm_r9); mc->r10 = sc->SC_FIELD(arm_r10); mc->r11 = sc->SC_FIELD(arm_fp); mc->r12 = sc->SC_FIELD(arm_ip); mc->r13 = sc->SC_FIELD(arm_sp); mc->r14 = sc->SC_FIELD(arm_lr); mc->r15 = sc->SC_FIELD(arm_pc); mc->cpsr= sc->SC_FIELD(arm_cpsr); # ifdef X64 # error NYI on AArch64 # endif /* X64 */ #endif /* X86/ARM */ sigcontext_to_mcontext_simd(mc, sc_full); } /* Note that unlike mcontext_to_context(), this routine does not fill in * any state that is not present in the mcontext: in particular, it assumes * the sigcontext already contains the native fpstate. If the caller * is generating a synthetic sigcontext, the caller should call * save_fpstate() before calling this routine. */ /* XXX: on ARM, sigreturn needs the T bit set in the sigcontext_t cpsr field in * order to return to Thumb mode. But, our mcontext doesn't have the T bit (b/c * usermode can't read it). Thus callers must either modify an mcontext * obtained from sigcontext_to_mcontext() or must call set_pc_mode_in_cpsr() in * order to create a proper sigcontext for sigreturn. All callers here do so. * The only external non-Windows caller of thread_set_mcontext() is * translate_from_synchall_to_dispatch() who first does a thread_get_mcontext() * and tweaks that context, so cpsr should be there. */ void mcontext_to_sigcontext(sig_full_cxt_t *sc_full, priv_mcontext_t *mc) { sigcontext_t *sc = sc_full->sc; ASSERT(mc != NULL && sc != NULL); #ifdef X86 sc->SC_XAX = mc->xax; sc->SC_XBX = mc->xbx; sc->SC_XCX = mc->xcx; sc->SC_XDX = mc->xdx; sc->SC_XSI = mc->xsi; sc->SC_XDI = mc->xdi; sc->SC_XBP = mc->xbp; sc->SC_XSP = mc->xsp; sc->SC_XFLAGS = mc->xflags; sc->SC_XIP = (ptr_uint_t) mc->pc; # ifdef X64 sc->SC_FIELD(r8) = mc->r8; sc->SC_FIELD(r9) = mc->r9; sc->SC_FIELD(r10) = mc->r10; sc->SC_FIELD(r11) = mc->r11; sc->SC_FIELD(r12) = mc->r12; sc->SC_FIELD(r13) = mc->r13; sc->SC_FIELD(r14) = mc->r14; sc->SC_FIELD(r15) = mc->r15; # endif /* X64 */ #elif defined(AARCH64) memcpy(&sc->SC_FIELD(regs[0]), &mc->r0, sizeof(mc->r0) * 31); sc->SC_FIELD(sp) = mc->sp; sc->SC_FIELD(pc) = (ptr_uint_t)mc->pc; sc->SC_FIELD(pstate) = mc->nzcv; #elif defined(ARM) sc->SC_FIELD(arm_r0) = mc->r0; sc->SC_FIELD(arm_r1) = mc->r1; sc->SC_FIELD(arm_r2) = mc->r2; sc->SC_FIELD(arm_r3) = mc->r3; sc->SC_FIELD(arm_r4) = mc->r4; sc->SC_FIELD(arm_r5) = mc->r5; sc->SC_FIELD(arm_r6) = mc->r6; sc->SC_FIELD(arm_r7) = mc->r7; sc->SC_FIELD(arm_r8) = mc->r8; sc->SC_FIELD(arm_r9) = mc->r9; sc->SC_FIELD(arm_r10) = mc->r10; sc->SC_FIELD(arm_fp) = mc->r11; sc->SC_FIELD(arm_ip) = mc->r12; sc->SC_FIELD(arm_sp) = mc->r13; sc->SC_FIELD(arm_lr) = mc->r14; sc->SC_FIELD(arm_pc) = mc->r15; sc->SC_FIELD(arm_cpsr)= mc->cpsr; # ifdef X64 # error NYI on AArch64 # endif /* X64 */ #endif /* X86/ARM */ mcontext_to_sigcontext_simd(sc_full, mc); } static void ucontext_to_mcontext(priv_mcontext_t *mc, kernel_ucontext_t *uc) { sig_full_cxt_t sc_full; sig_full_initialize(&sc_full, uc); sigcontext_to_mcontext(mc, &sc_full); } static void mcontext_to_ucontext(kernel_ucontext_t *uc, priv_mcontext_t *mc) { sig_full_cxt_t sc_full; sig_full_initialize(&sc_full, uc); mcontext_to_sigcontext(&sc_full, mc); } #ifdef AARCHXX static void set_sigcxt_stolen_reg(sigcontext_t *sc, reg_t val) { *(&sc->SC_R0 + (dr_reg_stolen - DR_REG_R0)) = val; } static reg_t get_sigcxt_stolen_reg(sigcontext_t *sc) { return *(&sc->SC_R0 + (dr_reg_stolen - DR_REG_R0)); } # ifndef AARCH64 static dr_isa_mode_t get_pc_mode_from_cpsr(sigcontext_t *sc) { return TEST(EFLAGS_T, sc->SC_XFLAGS) ? DR_ISA_ARM_THUMB : DR_ISA_ARM_A32; } static void set_pc_mode_in_cpsr(sigcontext_t *sc, dr_isa_mode_t isa_mode) { if (isa_mode == DR_ISA_ARM_THUMB) sc->SC_XFLAGS |= EFLAGS_T; else sc->SC_XFLAGS &= ~EFLAGS_T; } # endif #endif /* Returns whether successful. If avoid_failure, tries to translate * at least pc if not successful. Pass f if known. */ static bool translate_sigcontext(dcontext_t *dcontext, kernel_ucontext_t *uc, bool avoid_failure, fragment_t *f) { bool success = false; priv_mcontext_t mcontext; sigcontext_t *sc = SIGCXT_FROM_UCXT(uc); ucontext_to_mcontext(&mcontext, uc); /* FIXME: if cannot find exact match, we're in trouble! * probably ok to delay, since that indicates not a synchronous * signal. */ /* FIXME : in_fcache() (called by recreate_app_state) grabs fcache * fcache_unit_areas.lock, we could deadlock! Also on initexit_lock * == PR 205795/1317 */ /* For safe recreation we need to either be couldbelinking or hold the * initexit lock (to keep someone from flushing current fragment), the * initexit lock is easier */ mutex_lock(&thread_initexit_lock); /* PR 214962: we assume we're going to relocate to this stored context, * so we restore memory now */ if (translate_mcontext(dcontext->thread_record, &mcontext, true/*restore memory*/, f)) { mcontext_to_ucontext(uc, &mcontext); success = true; } else { if (avoid_failure) { ASSERT_NOT_REACHED(); /* is ok to break things, is UNIX :) */ /* FIXME : what to do? reg state might be wrong at least get pc */ if (safe_is_in_fcache(dcontext, (cache_pc)sc->SC_XIP, (app_pc)sc->SC_XSP)) { sc->SC_XIP = (ptr_uint_t)recreate_app_pc(dcontext, mcontext.pc, f); ASSERT(sc->SC_XIP != (ptr_uint_t)NULL); } else { /* FIXME : can't even get pc right, what do we do here? */ sc->SC_XIP = 0; } } } mutex_unlock(&thread_initexit_lock); /* FIXME i#2095: restore the app's segment register value(s). */ LOG(THREAD, LOG_ASYNCH, 3, "\ttranslate_sigcontext: just set frame's eip to "PFX"\n", sc->SC_XIP); return success; } /* Takes an os-specific context */ void thread_set_self_context(void *cxt) { #ifdef X86 if (!INTERNAL_OPTION(use_sigreturn_setcontext)) { sigcontext_t *sc = (sigcontext_t *) cxt; dr_jmp_buf_t buf; buf.xbx = sc->SC_XBX; buf.xcx = sc->SC_XCX; buf.xdi = sc->SC_XDI; buf.xsi = sc->SC_XSI; buf.xbp = sc->SC_XBP; /* XXX: this is not fully transparent: it assumes the target stack * is valid and that we can clobber the slot beyond TOS. * Using this instead of sigreturn is meant mainly as a diagnostic * to help debug future issues with sigreturn (xref i#2080). */ buf.xsp = sc->SC_XSP - XSP_SZ; /* extra slot for retaddr */ buf.xip = sc->SC_XIP; # ifdef X64 buf.r8 = sc->r8; buf.r9 = sc->r9; buf.r10 = sc->r10; buf.r11 = sc->r11; buf.r12 = sc->r12; buf.r13 = sc->r13; buf.r14 = sc->r14; buf.r15 = sc->r15; # endif dr_longjmp(&buf, sc->SC_XAX); return; } #endif dcontext_t *dcontext = get_thread_private_dcontext(); /* Unlike Windows we can't say "only set this subset of the * full machine state", so we need to get the rest of the state, */ sigframe_rt_t frame; #if defined(LINUX) || defined(DEBUG) sigcontext_t *sc = (sigcontext_t *) cxt; #endif app_pc xsp_for_sigreturn; #ifdef VMX86_SERVER ASSERT_NOT_IMPLEMENTED(false); /* PR 405694: can't use regular sigreturn! */ #endif memset(&frame, 0, sizeof(frame)); #ifdef LINUX # ifdef X86 byte *xstate = get_xstate_buffer(dcontext); frame.uc.uc_mcontext.fpstate = &((struct _xstate *)xstate)->fpstate; # endif /* X86 */ frame.uc.uc_mcontext = *sc; #endif save_fpstate(dcontext, &frame); /* The kernel calls do_sigaltstack on sys_rt_sigreturn primarily to ensure * the frame is ok, but the side effect is we can mess up our own altstack * settings if we're not careful. Having invalid ss_size looks good for * kernel 2.6.23.9 at least so we leave frame.uc.uc_stack as all zeros. */ /* make sure sigreturn's mask setting doesn't change anything */ sigprocmask_syscall(SIG_SETMASK, NULL, (kernel_sigset_t *) &frame.uc.uc_sigmask, sizeof(frame.uc.uc_sigmask)); LOG(THREAD_GET, LOG_ASYNCH, 2, "thread_set_self_context: pc="PFX"\n", sc->SC_XIP); LOG(THREAD_GET, LOG_ASYNCH, 3, "full sigcontext\n"); DOLOG(LOG_ASYNCH, 3, { dump_sigcontext(dcontext, get_sigcontext_from_rt_frame(&frame)); }); /* set up xsp to point at &frame + sizeof(char*) */ xsp_for_sigreturn = ((app_pc)&frame) + sizeof(char*); #ifdef X86 asm("mov %0, %%"ASM_XSP : : "m"(xsp_for_sigreturn)); # ifdef MACOS ASSERT_NOT_IMPLEMENTED(false && "need to pass 2 params to SYS_sigreturn"); asm("jmp _dynamorio_sigreturn"); # else asm("jmp dynamorio_sigreturn"); # endif /* MACOS/LINUX */ #elif defined(AARCH64) ASSERT_NOT_IMPLEMENTED(false); /* FIXME i#1569 */ #elif defined(ARM) asm("ldr "ASM_XSP", %0" : : "m"(xsp_for_sigreturn)); asm("b dynamorio_sigreturn"); #endif /* X86/ARM */ ASSERT_NOT_REACHED(); } static void thread_set_segment_registers(sigcontext_t *sc) { #ifdef X86 /* Fill in the segment registers */ __asm__ __volatile__("mov %%cs, %%ax; mov %%ax, %0" : "=m"(sc->SC_FIELD(cs)) : : "eax"); # ifndef X64 __asm__ __volatile__("mov %%ss, %%ax; mov %%ax, %0" : "=m"(sc->SC_FIELD(ss)) : : "eax"); __asm__ __volatile__("mov %%ds, %%ax; mov %%ax, %0" : "=m"(sc->SC_FIELD(ds)) : : "eax"); __asm__ __volatile__("mov %%es, %%ax; mov %%ax, %0" : "=m"(sc->SC_FIELD(es)) : : "eax"); # endif __asm__ __volatile__("mov %%fs, %%ax; mov %%ax, %0" : "=m"(sc->SC_FIELD(fs)) : : "eax"); __asm__ __volatile__("mov %%gs, %%ax; mov %%ax, %0" : "=m"(sc->SC_FIELD(gs)) : : "eax"); #endif } /* Takes a priv_mcontext_t */ void thread_set_self_mcontext(priv_mcontext_t *mc) { kernel_ucontext_t ucxt; sig_full_cxt_t sc_full; sig_full_initialize(&sc_full, &ucxt); #if defined(LINUX) && defined(X86) sc_full.sc->fpstate = NULL; /* for mcontext_to_sigcontext */ #endif mcontext_to_sigcontext(&sc_full, mc); thread_set_segment_registers(sc_full.sc); /* sigreturn takes the mode from cpsr */ IF_ARM(set_pc_mode_in_cpsr(sc_full.sc, dr_get_isa_mode(get_thread_private_dcontext()))); /* thread_set_self_context will fill in the real fp/simd state for x86 */ thread_set_self_context((void *)sc_full.sc); ASSERT_NOT_REACHED(); } #ifdef LINUX static bool sig_has_restorer(thread_sig_info_t *info, int sig) { # ifdef VMX86_SERVER /* vmkernel ignores SA_RESTORER (PR 405694) */ return false; # endif if (info->app_sigaction[sig] == NULL) return false; if (TEST(SA_RESTORER, info->app_sigaction[sig]->flags)) return true; if (info->app_sigaction[sig]->restorer == NULL) return false; /* we cache the result due to the safe_read cost */ if (info->restorer_valid[sig] == -1) { /* With older kernels, don't seem to need flag: if sa_restorer != * NULL kernel will use it. But with newer kernels that's not * true, and sometimes libc does pass non-NULL. */ # ifdef X86 /* Signal restorer code for Ubuntu 7.04: * 0xffffe420 <__kernel_sigreturn+0>: pop %eax * 0xffffe421 <__kernel_sigreturn+1>: mov $0x77,%eax * 0xffffe426 <__kernel_sigreturn+6>: int $0x80 * * 0xffffe440 <__kernel_rt_sigreturn+0>: mov $0xad,%eax * 0xffffe445 <__kernel_rt_sigreturn+5>: int $0x80 */ static const byte SIGRET_NONRT[8] = {0x58, 0xb8, 0x77, 0x00, 0x00, 0x00, 0xcd, 0x80}; static const byte SIGRET_RT[8] = {0xb8, 0xad, 0x00, 0x00, 0x00, 0xcd, 0x80}; # elif defined(ARM) static const byte SIGRET_NONRT[8] = {0x77, 0x70, 0xa0, 0xe3, 0x00, 0x00, 0x00, 0xef}; static const byte SIGRET_RT[8] = {0xad, 0x70, 0xa0, 0xe3, 0x00, 0x00, 0x00, 0xef}; # elif defined(AARCH64) static const byte SIGRET_NONRT[8] = { 0 }; /* unused */ static const byte SIGRET_RT[8] = /* FIXME i#1569: untested */ /* mov w8, #139 ; svc #0 */ {0x68, 0x11, 0x80, 0x52, 0x01, 0x00, 0x00, 0xd4}; # endif byte buf[MAX(sizeof(SIGRET_NONRT), sizeof(SIGRET_RT))]= {0}; # ifdef AARCH64 ASSERT_NOT_TESTED(); /* See SIGRET_RT, above. */ # endif if (safe_read(info->app_sigaction[sig]->restorer, sizeof(buf), buf) && ((IS_RT_FOR_APP(info, sig) && memcmp(buf, SIGRET_RT, sizeof(SIGRET_RT)) == 0) || (!IS_RT_FOR_APP(info, sig) && memcmp(buf, SIGRET_NONRT, sizeof(SIGRET_NONRT)) == 0))) { LOG(THREAD_GET, LOG_ASYNCH, 2, "sig_has_restorer %d: "PFX" looks like restorer, using w/o flag\n", sig, info->app_sigaction[sig]->restorer); info->restorer_valid[sig] = 1; } else info->restorer_valid[sig] = 0; } return (info->restorer_valid[sig] == 1); } #endif /* Returns the size of the frame for delivering to the app. * For x64 this does NOT include struct _fpstate. */ static uint get_app_frame_size(thread_sig_info_t *info, int sig) { if (IS_RT_FOR_APP(info, sig)) return sizeof(sigframe_rt_t); #ifdef LINUX else return sizeof(sigframe_plain_t); #endif } static kernel_ucontext_t * get_ucontext_from_rt_frame(sigframe_rt_t *frame) { #if defined(MACOS) && !defined(X64) /* Padding makes it unsafe to access uc on frame from kernel */ return frame->puc; #else return &frame->uc; #endif } sigcontext_t * get_sigcontext_from_rt_frame(sigframe_rt_t *frame) { return SIGCXT_FROM_UCXT(get_ucontext_from_rt_frame(frame)); } static sigcontext_t * get_sigcontext_from_app_frame(thread_sig_info_t *info, int sig, void *frame) { sigcontext_t *sc = NULL; /* initialize to satisfy Mac clang */ bool rtframe = IS_RT_FOR_APP(info, sig); if (rtframe) sc = get_sigcontext_from_rt_frame((sigframe_rt_t *)frame); #ifdef LINUX else { # ifdef X86 sc = (sigcontext_t *) &(((sigframe_plain_t *)frame)->sc); # elif defined(ARM) sc = SIGCXT_FROM_UCXT(&(((sigframe_plain_t *)frame)->uc)); # else ASSERT_NOT_REACHED(); # endif } #endif return sc; } static sigcontext_t * get_sigcontext_from_pending(thread_sig_info_t *info, int sig) { ASSERT(info->sigpending[sig] != NULL); return get_sigcontext_from_rt_frame(&info->sigpending[sig]->rt_frame); } /* Returns the address on the appropriate signal stack where we should copy * the frame. * If frame is NULL, assumes signal happened while in DR and has been delayed, * and thus we need to provide fpstate regardless of whether the original * had it. If frame is non-NULL, matches frame's amount of fpstate. */ static byte * get_sigstack_frame_ptr(dcontext_t *dcontext, int sig, sigframe_rt_t *frame) { thread_sig_info_t *info = (thread_sig_info_t *) dcontext->signal_field; sigcontext_t *sc = (frame == NULL) ? get_sigcontext_from_pending(info, sig) : get_sigcontext_from_rt_frame(frame); byte *sp; if (frame != NULL) { /* signal happened while in cache, grab interrupted xsp */ sp = (byte *) sc->SC_XSP; LOG(THREAD, LOG_ASYNCH, 3, "get_sigstack_frame_ptr: using frame's xsp "PFX"\n", sp); } else { /* signal happened while in DR, use stored xsp */ sp = (byte *) get_mcontext(dcontext)->xsp; LOG(THREAD, LOG_ASYNCH, 3, "get_sigstack_frame_ptr: using app xsp "PFX"\n", sp); } if (APP_HAS_SIGSTACK(info)) { /* app has own signal stack */ LOG(THREAD, LOG_ASYNCH, 3, "get_sigstack_frame_ptr: app has own stack "PFX"\n", info->app_sigstack.ss_sp); LOG(THREAD, LOG_ASYNCH, 3, "\tcur sp="PFX" vs app stack "PFX"-"PFX"\n", sp, info->app_sigstack.ss_sp, info->app_sigstack.ss_sp + info->app_sigstack.ss_size); if (sp > (byte *)info->app_sigstack.ss_sp && sp - (byte *)info->app_sigstack.ss_sp < info->app_sigstack.ss_size) { /* we're currently in the alt stack, so use current xsp */ LOG(THREAD, LOG_ASYNCH, 3, "\tinside alt stack, so using current xsp "PFX"\n", sp); } else { /* need to go to top, stack grows down */ sp = info->app_sigstack.ss_sp + info->app_sigstack.ss_size; LOG(THREAD, LOG_ASYNCH, 3, "\tnot inside alt stack, so using base xsp "PFX"\n", sp); } } /* now get frame pointer: need to go down to first field of frame */ sp -= get_app_frame_size(info, sig); #if defined(LINUX) && defined(X86) if (frame == NULL) { /* XXX i#641: we always include space for full xstate, * even if we don't use it all, which does not match what the * kernel does, but we're not tracking app actions to know whether * we can skip lazy fpstate on the delay */ sp -= signal_frame_extra_size(true); } else { if (sc->fpstate != NULL) { /* The kernel doesn't seem to lazily include avx, so we don't either, * which simplifies all our frame copying: if YMM_ENABLED() and the * fpstate pointer is non-NULL, then we assume there's space for * full xstate */ sp -= signal_frame_extra_size(true); DOCHECK(1, { if (YMM_ENABLED()) { ASSERT_CURIOSITY(sc->fpstate->sw_reserved.magic1 == FP_XSTATE_MAGIC1); ASSERT(sc->fpstate->sw_reserved.extended_size <= signal_frame_extra_size(true)); } }); } } #endif /* LINUX && X86 */ /* PR 369907: don't forget the redzone */ sp -= REDZONE_SIZE; /* Align to 16-bytes. The kernel does this for both 32 and 64-bit code * these days, so we do as well. */ sp = (byte *) ALIGN_BACKWARD(sp, 16); IF_X86(sp -= sizeof(reg_t)); /* Model retaddr. */ LOG(THREAD, LOG_ASYNCH, 3, "\tplacing frame at "PFX"\n", sp); return sp; } #if defined(LINUX) && !defined(X64) static void convert_frame_to_nonrt(dcontext_t *dcontext, int sig, sigframe_rt_t *f_old, sigframe_plain_t *f_new) { # ifdef X86 sigcontext_t *sc_old = get_sigcontext_from_rt_frame(f_old); f_new->pretcode = f_old->pretcode; f_new->sig = f_old->sig; memcpy(&f_new->sc, get_sigcontext_from_rt_frame(f_old), sizeof(sigcontext_t)); if (sc_old->fpstate != NULL) { /* up to caller to include enough space for fpstate at end */ byte *new_fpstate = (byte *) ALIGN_FORWARD(((byte *)f_new) + sizeof(*f_new), XSTATE_ALIGNMENT); memcpy(new_fpstate, sc_old->fpstate, signal_frame_extra_size(false)); f_new->sc.fpstate = (struct _fpstate *) new_fpstate; } f_new->sc.oldmask = f_old->uc.uc_sigmask.sig[0]; memcpy(&f_new->extramask, &f_old->uc.uc_sigmask.sig[1], (_NSIG_WORDS-1) * sizeof(uint)); memcpy(&f_new->retcode, &f_old->retcode, RETCODE_SIZE); /* now fill in our extra field */ f_new->sig_noclobber = f_new->sig; # elif defined(ARM) memcpy(&f_new->uc, &f_old->uc, sizeof(f_new->uc)); memcpy(f_new->retcode, f_old->retcode, sizeof(f_new->retcode)); /* now fill in our extra field */ f_new->sig_noclobber = f_old->info.si_signo; # endif /* X86 */ LOG(THREAD, LOG_ASYNCH, 3, "\tconverted sig=%d rt frame to non-rt frame\n", f_new->sig_noclobber); } /* separated out to avoid the stack size cost on the common path */ static void convert_frame_to_nonrt_partial(dcontext_t *dcontext, int sig, sigframe_rt_t *f_old, sigframe_plain_t *f_new, size_t size) { # ifdef X86 /* We create a full-size buffer for conversion and then copy the partial amount. */ byte *frame_and_xstate = heap_alloc(dcontext, sizeof(sigframe_plain_t) + signal_frame_extra_size(true) HEAPACCT(ACCT_OTHER)); sigframe_plain_t *f_plain = (sigframe_plain_t *) frame_and_xstate; ASSERT_NOT_TESTED(); /* XXX: we have no test of this for change to heap_alloc */ convert_frame_to_nonrt(dcontext, sig, f_old, f_plain); memcpy(f_new, f_plain, size); heap_free(dcontext, frame_and_xstate, sizeof(sigframe_plain_t) + signal_frame_extra_size(true) HEAPACCT(ACCT_OTHER)); # elif defined(ARM) /* FIXME i#1551: NYI on ARM */ ASSERT_NOT_IMPLEMENTED(false); # endif /* X86/ARM */ } #endif /* Exported for call from master_signal_handler asm routine. * For the rt signal frame f_old that was copied to f_new, updates * the intra-frame absolute pointers to point to the new addresses * in f_new. * Only updates the pretcode to the stored app restorer if for_app. */ void fixup_rtframe_pointers(dcontext_t *dcontext, int sig, sigframe_rt_t *f_old, sigframe_rt_t *f_new, bool for_app) { if (dcontext == NULL) dcontext = get_thread_private_dcontext(); ASSERT(dcontext != NULL); #if defined(X86) && defined(LINUX) thread_sig_info_t *info = (thread_sig_info_t *) dcontext->signal_field; bool has_restorer = sig_has_restorer(info, sig); # ifdef DEBUG uint level = 3; # if !defined(HAVE_MEMINFO) /* avoid logging every single TRY probe fault */ if (!dynamo_initialized) level = 5; # endif # endif if (has_restorer && for_app) f_new->pretcode = (char *) info->app_sigaction[sig]->restorer; else { # ifdef VMX86_SERVER /* PR 404712: skip kernel's restorer code */ if (for_app) f_new->pretcode = (char *) dynamorio_sigreturn; # else # ifdef X64 ASSERT(!for_app || doing_detach); /* detach uses a frame to go native */ # else /* only point at retcode if old one was -- with newer OS, points at * vsyscall page and there is no restorer, yet stack restorer code left * there for gdb compatibility */ if (f_old->pretcode == f_old->retcode) f_new->pretcode = f_new->retcode; /* else, pointing at vsyscall, or we set it to dynamorio_sigreturn in * master_signal_handler */ LOG(THREAD, LOG_ASYNCH, level, "\tleaving pretcode with old value\n"); # endif # endif } # ifndef X64 f_new->pinfo = &(f_new->info); f_new->puc = &(f_new->uc); # endif if (f_old->uc.uc_mcontext.fpstate != NULL) { uint frame_size = get_app_frame_size(info, sig); byte *frame_end = ((byte *)f_new) + frame_size; byte *tgt = (byte *) ALIGN_FORWARD(frame_end, XSTATE_ALIGNMENT); ASSERT(tgt - frame_end <= signal_frame_extra_size(true)); memcpy(tgt, f_old->uc.uc_mcontext.fpstate, sizeof(struct _fpstate)); f_new->uc.uc_mcontext.fpstate = (struct _fpstate *) tgt; if (YMM_ENABLED()) { struct _xstate *xstate_new = (struct _xstate *) tgt; struct _xstate *xstate_old = (struct _xstate *) f_old->uc.uc_mcontext.fpstate; memcpy(&xstate_new->xstate_hdr, &xstate_old->xstate_hdr, sizeof(xstate_new->xstate_hdr)); memcpy(&xstate_new->ymmh, &xstate_old->ymmh, sizeof(xstate_new->ymmh)); } LOG(THREAD, LOG_ASYNCH, level+1, "\tfpstate old="PFX" new="PFX"\n", f_old->uc.uc_mcontext.fpstate, f_new->uc.uc_mcontext.fpstate); } else { /* if fpstate is not set up, we're delivering signal immediately, * and we shouldn't need an fpstate since DR code won't modify it; * only if we delayed will we need it, and when delaying we make * room and set up the pointer in copy_frame_to_pending. * xref i#641. */ LOG(THREAD, LOG_ASYNCH, level+1, "\tno fpstate needed\n"); } LOG(THREAD, LOG_ASYNCH, level, "\tretaddr = "PFX"\n", f_new->pretcode); # ifdef RETURN_AFTER_CALL info->signal_restorer_retaddr = (app_pc) f_new->pretcode; # endif /* 32-bit kernel copies to aligned buf first */ IF_X64(ASSERT(ALIGNED(f_new->uc.uc_mcontext.fpstate, 16))); #elif defined(MACOS) # ifndef X64 f_new->pinfo = &(f_new->info); f_new->puc = &(f_new->uc); # endif f_new->puc->uc_mcontext = (IF_X64_ELSE(_STRUCT_MCONTEXT64, _STRUCT_MCONTEXT32) *) &f_new->mc; LOG(THREAD, LOG_ASYNCH, 3, "\tf_new="PFX", &handler="PFX"\n", f_new, &f_new->handler); ASSERT(!for_app || ALIGNED(&f_new->handler, 16)); #endif /* X86 && LINUX */ } static void memcpy_rt_frame(sigframe_rt_t *frame, byte *dst, bool from_pending) { #if defined(MACOS) && !defined(X64) if (!from_pending) { /* The kernel puts padding in the middle. We collapse that padding here * and re-align when we copy to the app stack. * We should not reference fields from mc onward in what the kernel put * on the stack, as our sigframe_rt_t layout does not match the kernel's * variable mid-struct padding. */ sigcontext_t *sc = SIGCXT_FROM_UCXT(frame->puc); memcpy(dst, frame, offsetof(sigframe_rt_t, puc) + sizeof(frame->puc)); memcpy(&((sigframe_rt_t*)dst)->mc, sc, sizeof(sigframe_rt_t) - offsetof(sigframe_rt_t, mc)); return; } #endif memcpy(dst, frame, sizeof(sigframe_rt_t)); } /* Copies frame to sp. * PR 304708: we now leave in rt form right up until we copy to the * app stack, so that we can deliver to a client at a safe spot * in rt form, so this routine now converts to a plain frame if necessary. * If no restorer, touches up pretcode * (and if rt_frame, touches up pinfo and puc) * Also touches up fpstate pointer */ static void copy_frame_to_stack(dcontext_t *dcontext, int sig, sigframe_rt_t *frame, byte *sp, bool from_pending) { thread_sig_info_t *info = (thread_sig_info_t *) dcontext->signal_field; bool rtframe = IS_RT_FOR_APP(info, sig); uint frame_size = get_app_frame_size(info, sig); #if defined(LINUX) && defined(X86_32) bool has_restorer = sig_has_restorer(info, sig); #endif byte *check_pc; uint size = frame_size; #if defined(LINUX) && defined(X86) sigcontext_t *sc = get_sigcontext_from_rt_frame(frame); size += (sc->fpstate == NULL ? 0 : signal_frame_extra_size(true)); #endif /* LINUX && X86 */ LOG(THREAD, LOG_ASYNCH, 3, "copy_frame_to_stack: rt=%d, src="PFX", sp="PFX"\n", rtframe, frame, sp); /* before we write to the app's stack we need to see if it's writable */ check_pc = (byte *) ALIGN_BACKWARD(sp, PAGE_SIZE); while (check_pc < (byte *)sp + size) { uint prot; DEBUG_DECLARE(bool ok = ) get_memory_info(check_pc, NULL, NULL, &prot); ASSERT(ok); if (!TEST(MEMPROT_WRITE, prot)) { size_t rest = (byte *)sp + size - check_pc; if (is_executable_area_writable(check_pc)) { LOG(THREAD, LOG_ASYNCH, 2, "\tcopy_frame_to_stack: part of stack is unwritable-by-us @"PFX"\n", check_pc); flush_fragments_and_remove_region(dcontext, check_pc, rest, false /* don't own initexit_lock */, false /* keep futures */); } else { LOG(THREAD, LOG_ASYNCH, 2, "\tcopy_frame_to_stack: part of stack is unwritable @"PFX"\n", check_pc); /* copy what we can */ if (rtframe) memcpy(sp, frame, rest); #if defined(LINUX) && !defined(X64) else { convert_frame_to_nonrt_partial(dcontext, sig, frame, (sigframe_plain_t *) sp, rest); } #endif /* now throw exception * FIXME: what give as address? what does kernel use? * If the app intercepts SIGSEGV then we'll come right back * here, so we terminate explicitly instead. FIXME: set exit * code properly: xref PR 205310. */ if (info->app_sigaction[SIGSEGV] == NULL) os_forge_exception(0, UNREADABLE_MEMORY_EXECUTION_EXCEPTION); else os_terminate(dcontext, TERMINATE_PROCESS); ASSERT_NOT_REACHED(); } } check_pc += PAGE_SIZE; } if (rtframe) { ASSERT(frame_size == sizeof(*frame)); memcpy_rt_frame(frame, sp, from_pending); } #if defined(LINUX) && !defined(X64) else convert_frame_to_nonrt(dcontext, sig, frame, (sigframe_plain_t *) sp); #endif /* if !has_restorer we do NOT add the restorer code to the exec list here, * to avoid removal problems (if handler never returns) and consistency problems * (would have to mark as selfmod right now if on stack). * for PROGRAM_SHEPHERDING we recognize as a pattern, and for consistency we * allow entire region once try to execute -- not a performance worry since should * very rarely be on the stack: should either be libc restorer code or with recent * OS in rx vsyscall page. */ /* fix up pretcode, pinfo, puc, fpstate */ if (rtframe) { fixup_rtframe_pointers(dcontext, sig, frame, (sigframe_rt_t *) sp, true/*for app*/); } #if defined(X86) && defined(LINUX) else { # ifdef X64 ASSERT_NOT_REACHED(); # else sigframe_plain_t *f_new = (sigframe_plain_t *) sp; # ifndef VMX86_SERVER sigframe_plain_t *f_old = (sigframe_plain_t *) frame; # endif if (has_restorer) f_new->pretcode = (char *) info->app_sigaction[sig]->restorer; else { # ifdef VMX86_SERVER /* PR 404712: skip kernel's restorer code */ f_new->pretcode = (char *) dynamorio_nonrt_sigreturn; # else /* see comments in rt case above */ if (f_old->pretcode == f_old->retcode) f_new->pretcode = f_new->retcode; else { /* whether we set to dynamorio_sigreturn in master_signal_handler * or it's still vsyscall page, we have to convert to non-rt */ f_new->pretcode = (char *) dynamorio_nonrt_sigreturn; } /* else, pointing at vsyscall most likely */ LOG(THREAD, LOG_ASYNCH, 3, "\tleaving pretcode with old value\n"); # endif } /* convert_frame_to_nonrt*() should have updated fpstate pointer. * The inlined fpstate is no longer used on new kernels, and we do that * as well on older kernels. */ ASSERT(f_new->sc.fpstate != &f_new->fpstate); LOG(THREAD, LOG_ASYNCH, 3, "\tretaddr = "PFX"\n", f_new->pretcode); # ifdef RETURN_AFTER_CALL info->signal_restorer_retaddr = (app_pc) f_new->pretcode; # endif /* 32-bit kernel copies to aligned buf so no assert on fpstate alignment */ # endif /* X64 */ } #endif /* X86 && LINUX */ #ifdef MACOS /* Update handler field, which is passed to the libc trampoline, to app */ ASSERT(info->app_sigaction[sig] != NULL); ((sigframe_rt_t *)sp)->handler = (app_pc) info->app_sigaction[sig]->handler; #endif } /* Copies frame to pending slot. * PR 304708: we now leave in rt form right up until we copy to the * app stack, so that we can deliver to a client at a safe spot * in rt form. */ static void copy_frame_to_pending(dcontext_t *dcontext, int sig, sigframe_rt_t *frame _IF_CLIENT(byte *access_address)) { thread_sig_info_t *info = (thread_sig_info_t *) dcontext->signal_field; sigframe_rt_t *dst = &(info->sigpending[sig]->rt_frame); memcpy_rt_frame(frame, (byte *)dst, false/*!already pending*/); #if defined(LINUX) && defined(X86) /* For lazy fpstate, it's possible there was no fpstate when the kernel * sent us the frame, but in between then and now the app executed some * fp or xmm/ymm instrs. Today we always add fpstate just in case. * XXX i#641 optimization: track whether any fp/xmm/ymm * instrs happened and avoid this. */ /* we'll fill in updated fpstate at delivery time, but we go ahead and * copy now in case our own retrieval somehow misses some fields */ if (frame->uc.uc_mcontext.fpstate != NULL) { memcpy(&info->sigpending[sig]->xstate, frame->uc.uc_mcontext.fpstate, /* XXX: assuming full xstate if avx is enabled */ signal_frame_extra_size(false)); } /* we must set the pointer now so that later save_fpstate, etc. work */ dst->uc.uc_mcontext.fpstate = (struct _fpstate *) &info->sigpending[sig]->xstate; #endif /* LINUX && X86 */ #ifdef CLIENT_INTERFACE info->sigpending[sig]->access_address = access_address; #endif info->sigpending[sig]->use_sigcontext = false; #ifdef MACOS /* We rely on puc to find sc to we have to fix it up */ fixup_rtframe_pointers(dcontext, sig, frame, dst, false/*!for app*/); #endif LOG(THREAD, LOG_ASYNCH, 3, "copy_frame_to_pending from "PFX"\n", frame); DOLOG(3, LOG_ASYNCH, { LOG(THREAD, LOG_ASYNCH, 3, "sigcontext:\n"); dump_sigcontext(dcontext, get_sigcontext_from_rt_frame(dst)); }); } /**** real work ***********************************************/ /* transfer control from signal handler to fcache return routine */ static void transfer_from_sig_handler_to_fcache_return(dcontext_t *dcontext, sigcontext_t *sc, app_pc next_pc, linkstub_t *last_exit) { dcontext->next_tag = canonicalize_pc_target(dcontext, next_pc); IF_ARM(dr_set_isa_mode(dcontext, get_pc_mode_from_cpsr(sc), NULL)); /* Set our sigreturn context to point to fcache_return! * Then we'll go back through kernel, appear in fcache_return, * and go through dispatch & interp, without messing up dynamo stack. * Note that even if this is a write in the shared cache, we * still go to the private fcache_return for simplicity. */ sc->SC_XIP = (ptr_uint_t) fcache_return_routine(dcontext); #ifdef AARCHXX /* We do not have to set dr_reg_stolen in dcontext's mcontext here * because dcontext's mcontext is stale and we used the mcontext * created from recreate_app_state_internal with the original sigcontext. */ /* We restore dr_reg_stolen's app value in recreate_app_state_internal, * so now we need set dr_reg_stolen to hold DR's TLS before sigreturn * from DR's handler. */ ASSERT(get_sigcxt_stolen_reg(sc) != (reg_t) *get_dr_tls_base_addr()); set_sigcxt_stolen_reg(sc, (reg_t) *get_dr_tls_base_addr()); # ifndef AARCH64 /* We're going to our fcache_return gencode which uses DEFAULT_ISA_MODE */ set_pc_mode_in_cpsr(sc, DEFAULT_ISA_MODE); # endif #endif #if defined(X64) || defined(ARM) /* x64 always uses shared gencode */ get_local_state_extended()->spill_space.IF_X86_ELSE(xax, r0) = sc->IF_X86_ELSE(SC_XAX, SC_R0); # ifdef AARCH64 /* X1 needs to be spilled because of br x1 in exit stubs. */ get_local_state_extended()->spill_space.r1 = sc->SC_R1; # endif #else get_mcontext(dcontext)->IF_X86_ELSE(xax, r0) = sc->IF_X86_ELSE(SC_XAX, SC_R0); #endif LOG(THREAD, LOG_ASYNCH, 2, "\tsaved xax "PFX"\n", sc->IF_X86_ELSE(SC_XAX, SC_R0)); sc->IF_X86_ELSE(SC_XAX, SC_R0) = (ptr_uint_t) last_exit; LOG(THREAD, LOG_ASYNCH, 2, "\tset next_tag to "PFX", resuming in fcache_return\n", next_pc); LOG(THREAD, LOG_ASYNCH, 3, "transfer_from_sig_handler_to_fcache_return\n"); DOLOG(3, LOG_ASYNCH, { LOG(THREAD, LOG_ASYNCH, 3, "sigcontext:\n"); dump_sigcontext(dcontext, sc); }); } #ifdef CLIENT_INTERFACE static dr_signal_action_t send_signal_to_client(dcontext_t *dcontext, int sig, sigframe_rt_t *frame, sigcontext_t *raw_sc, byte *access_address, bool blocked, fragment_t *fragment) { kernel_ucontext_t *uc = get_ucontext_from_rt_frame(frame); dr_siginfo_t si; dr_signal_action_t action; /* XXX #1615: we need a full ucontext to store pre-xl8 simd values. * Right now we share the same simd values with post-xl8. */ sig_full_cxt_t raw_sc_full; sig_full_initialize(&raw_sc_full, uc); raw_sc_full.sc = raw_sc; if (!dr_signal_hook_exists()) return DR_SIGNAL_DELIVER; LOG(THREAD, LOG_ASYNCH, 2, "sending signal to client\n"); si.sig = sig; si.drcontext = (void *) dcontext; /* It's safe to allocate since we do not send signals that interrupt DR. * With priv_mcontext_t x2 that's a little big for stack alloc. */ si.mcontext = heap_alloc(dcontext, sizeof(*si.mcontext) HEAPACCT(ACCT_OTHER)); si.raw_mcontext = heap_alloc(dcontext, sizeof(*si.raw_mcontext) HEAPACCT(ACCT_OTHER)); dr_mcontext_init(si.mcontext); dr_mcontext_init(si.raw_mcontext); /* i#207: fragment tag and fcache start pc on fault. */ si.fault_fragment_info.tag = NULL; si.fault_fragment_info.cache_start_pc = NULL; /* i#182/PR 449996: we provide the pre-translation context */ if (raw_sc != NULL) { fragment_t wrapper; si.raw_mcontext_valid = true; sigcontext_to_mcontext(dr_mcontext_as_priv_mcontext(si.raw_mcontext), &raw_sc_full); /* i#207: fragment tag and fcache start pc on fault. */ /* FIXME: we should avoid the fragment_pclookup since it is expensive * and since we already did the work of a lookup when translating */ if (fragment == NULL) fragment = fragment_pclookup(dcontext, si.raw_mcontext->pc, &wrapper); if (fragment != NULL && !hide_tag_from_client(fragment->tag)) { si.fault_fragment_info.tag = fragment->tag; si.fault_fragment_info.cache_start_pc = FCACHE_ENTRY_PC(fragment); si.fault_fragment_info.is_trace = TEST(FRAG_IS_TRACE, fragment->flags); si.fault_fragment_info.app_code_consistent = !TESTANY(FRAG_WAS_DELETED|FRAG_SELFMOD_SANDBOXED, fragment->flags); } } else si.raw_mcontext_valid = false; /* The client has no way to calculate this when using * instrumentation that deliberately faults (to shift a rare event * out of the fastpath) so we provide it. When raw_mcontext is * available the client can calculate it, but we provide it as a * convenience anyway. */ si.access_address = access_address; si.blocked = blocked; ucontext_to_mcontext(dr_mcontext_as_priv_mcontext(si.mcontext), uc); /* We disallow the client calling dr_redirect_execution(), so we * will not leak si */ action = instrument_signal(dcontext, &si); if (action == DR_SIGNAL_DELIVER || action == DR_SIGNAL_REDIRECT) { /* propagate client changes */ CLIENT_ASSERT(si.mcontext->flags == DR_MC_ALL, "signal mcontext flags cannot be changed"); mcontext_to_ucontext(uc, dr_mcontext_as_priv_mcontext(si.mcontext)); } else if (action == DR_SIGNAL_SUPPRESS && raw_sc != NULL) { /* propagate client changes */ CLIENT_ASSERT(si.raw_mcontext->flags == DR_MC_ALL, "signal mcontext flags cannot be changed"); mcontext_to_sigcontext(&raw_sc_full, dr_mcontext_as_priv_mcontext(si.raw_mcontext)); } heap_free(dcontext, si.mcontext, sizeof(*si.mcontext) HEAPACCT(ACCT_OTHER)); heap_free(dcontext, si.raw_mcontext, sizeof(*si.raw_mcontext) HEAPACCT(ACCT_OTHER)); return action; } /* Returns false if caller should exit */ static bool handle_client_action_from_cache(dcontext_t *dcontext, int sig, dr_signal_action_t action, sigframe_rt_t *our_frame, sigcontext_t *sc_orig, bool blocked) { thread_sig_info_t *info = (thread_sig_info_t *) dcontext->signal_field; kernel_ucontext_t *uc = get_ucontext_from_rt_frame(our_frame); sigcontext_t *sc = SIGCXT_FROM_UCXT(uc); /* in order to pass to the client, we come all the way here for signals * the app has no handler for */ if (action == DR_SIGNAL_REDIRECT) { /* send_signal_to_client copied mcontext into our * master_signal_handler frame, so we set up for fcache_return w/ * the mcontext state and this as next_tag */ ucontext_to_mcontext(get_mcontext(dcontext), uc); transfer_from_sig_handler_to_fcache_return(dcontext, sc, (app_pc) sc->SC_XIP, (linkstub_t *) get_asynch_linkstub()); if (is_building_trace(dcontext)) { LOG(THREAD, LOG_ASYNCH, 3, "\tsquashing trace-in-progress\n"); trace_abort(dcontext); } return false; } else if (action == DR_SIGNAL_SUPPRESS || (!blocked && info->app_sigaction[sig] != NULL && info->app_sigaction[sig]->handler == (handler_t)SIG_IGN)) { LOG(THREAD, LOG_ASYNCH, 2, "%s: not delivering!\n", (action == DR_SIGNAL_SUPPRESS) ? "client suppressing signal" : "app signal handler is SIG_IGN"); /* restore original (untranslated) sc */ *get_sigcontext_from_rt_frame(our_frame) = *sc_orig; return false; } else if (!blocked && /* no BYPASS for blocked */ (action == DR_SIGNAL_BYPASS || (info->app_sigaction[sig] == NULL || info->app_sigaction[sig]->handler == (handler_t)SIG_DFL))) { LOG(THREAD, LOG_ASYNCH, 2, "%s: executing default action\n", (action == DR_SIGNAL_BYPASS) ? "client forcing default" : "app signal handler is SIG_DFL"); if (execute_default_from_cache(dcontext, sig, our_frame, sc_orig)) { /* if we haven't terminated, restore original (untranslated) sc * on request. */ *get_sigcontext_from_rt_frame(our_frame) = *sc_orig; LOG(THREAD, LOG_ASYNCH, 2, "%s: restored xsp="PFX", xip="PFX"\n", __FUNCTION__, get_sigcontext_from_rt_frame(our_frame)->SC_XSP, get_sigcontext_from_rt_frame(our_frame)->SC_XIP); } return false; } CLIENT_ASSERT(action == DR_SIGNAL_DELIVER, "invalid signal event return value"); return true; } #endif static void abort_on_fault(dcontext_t *dcontext, uint dumpcore_flag, app_pc pc, int sig, sigframe_rt_t *frame, const char *prefix, const char *signame, const char *where) { kernel_ucontext_t *ucxt = &frame->uc; sigcontext_t *sc = SIGCXT_FROM_UCXT(ucxt); #if defined(STATIC_LIBRARY) && defined(LINUX) thread_sig_info_t *info = (thread_sig_info_t *) dcontext->signal_field; uint orig_dumpcore_flag = dumpcore_flag; if (init_info.app_sigaction != NULL) info = &init_info; /* use init-time handler */ ASSERT(info->app_sigaction != NULL); #endif const char *fmt = "%s %s at PC "PFX"\n" "Received SIG%s at%s pc "PFX" in thread "TIDFMT"\n" "Base: "PFX"\n" "Registers:" #ifdef X86 "eax="PFX" ebx="PFX" ecx="PFX" edx="PFX"\n" "\tesi="PFX" edi="PFX" esp="PFX" ebp="PFX"\n" # ifdef X64 "\tr8 ="PFX" r9 ="PFX" r10="PFX" r11="PFX"\n" "\tr12="PFX" r13="PFX" r14="PFX" r15="PFX"\n" # endif /* X64 */ #elif defined(ARM) # ifndef X64 " r0 ="PFX" r1 ="PFX" r2 ="PFX" r3 ="PFX"\n" "\tr4 ="PFX" r5 ="PFX" r6 ="PFX" r7 ="PFX"\n" "\tr8 ="PFX" r9 ="PFX" r10="PFX" r11="PFX"\n" "\tr12="PFX" r13="PFX" r14="PFX" r15="PFX"\n" # else # error NYI on AArch64 # endif #endif /* X86/ARM */ "\teflags="PFX; #if defined(STATIC_LIBRARY) && defined(LINUX) /* i#2119: if we're invoking an app handler, disable a fatal coredump. */ if (INTERNAL_OPTION(invoke_app_on_crash) && info->app_sigaction[sig] != NULL && IS_RT_FOR_APP(info, sig) && TEST(dumpcore_flag, DYNAMO_OPTION(dumpcore_mask)) && !DYNAMO_OPTION(live_dump)) dumpcore_flag = 0; #endif report_dynamorio_problem(dcontext, dumpcore_flag, pc, (app_pc) sc->SC_FP, fmt, prefix, CRASH_NAME, pc, signame, where, pc, get_thread_id(), get_dynamorio_dll_start(), #ifdef X86 sc->SC_XAX, sc->SC_XBX, sc->SC_XCX, sc->SC_XDX, sc->SC_XSI, sc->SC_XDI, sc->SC_XSP, sc->SC_XBP, # ifdef X64 sc->SC_FIELD(r8), sc->SC_FIELD(r9), sc->SC_FIELD(r10), sc->SC_FIELD(r11), sc->SC_FIELD(r12), sc->SC_FIELD(r13), sc->SC_FIELD(r14), sc->SC_FIELD(r15), # endif /* X86 */ #elif defined(ARM) # ifndef X64 sc->SC_FIELD(arm_r0), sc->SC_FIELD(arm_r1), sc->SC_FIELD(arm_r2), sc->SC_FIELD(arm_r3), sc->SC_FIELD(arm_r4), sc->SC_FIELD(arm_r5), sc->SC_FIELD(arm_r6), sc->SC_FIELD(arm_r7), sc->SC_FIELD(arm_r8), sc->SC_FIELD(arm_r9), sc->SC_FIELD(arm_r10), sc->SC_FIELD(arm_fp), sc->SC_FIELD(arm_ip), sc->SC_FIELD(arm_sp), sc->SC_FIELD(arm_lr), sc->SC_FIELD(arm_pc), # else # error NYI on AArch64 # endif /* X64 */ #endif /* X86/ARM */ sc->SC_XFLAGS); #if defined(STATIC_LIBRARY) && defined(LINUX) /* i#2119: For static DR, the surrounding app's handler may well be * safe to invoke even when DR state is messed up: it's worth a try, as it * likely has useful reporting features for users of the app. * We limit to Linux and RT for simplicity: it can be expanded later if static * library use expands. */ if (INTERNAL_OPTION(invoke_app_on_crash) && info->app_sigaction[sig] != NULL && IS_RT_FOR_APP(info, sig)) { SYSLOG(SYSLOG_WARNING, INVOKING_APP_HANDLER, 2, get_application_name(), get_application_pid()); (*info->app_sigaction[sig]->handler)(sig, &frame->info, ucxt); /* If the app handler didn't terminate, now get a fatal core. */ if (TEST(orig_dumpcore_flag, DYNAMO_OPTION(dumpcore_mask)) && !DYNAMO_OPTION(live_dump)) os_dump_core("post-app-handler attempt at core dump"); } #endif os_terminate(dcontext, TERMINATE_PROCESS); ASSERT_NOT_REACHED(); } static void abort_on_DR_fault(dcontext_t *dcontext, app_pc pc, int sig, sigframe_rt_t *frame, const char *signame, const char *where) { abort_on_fault(dcontext, DUMPCORE_INTERNAL_EXCEPTION, pc, sig, frame, exception_label_core, signame, where); ASSERT_NOT_REACHED(); } /* Returns whether unlinked or mangled syscall. * Restored in receive_pending_signal. */ static bool unlink_fragment_for_signal(dcontext_t *dcontext, fragment_t *f, byte *pc/*interruption pc*/) { /* We only come here if we interrupted a fragment in the cache, * or interrupted transition gencode (i#2019), * which means that this thread's DR state is safe, and so it * should be ok to acquire a lock. xref PR 596069. * * There is a race where if two threads hit a signal in the same * shared fragment, the first could re-link after the second * un-links but before the second exits, and the second could then * execute the syscall, resulting in arbitrary delay prior to * signal delivery. We don't want to allocate global memory, * but we could use a static array of counters (since should * be small # of interrupted shared fragments at any one time) * used as refcounts so we only unlink when all are done. * Not bothering to implement now: going to live w/ chance of * long signal delays. xref PR 596069. */ bool changed = false; bool waslinking = is_couldbelinking(dcontext); if (!waslinking) enter_couldbelinking(dcontext, NULL, false); /* may not be linked if trace_relink or something */ if (TEST(FRAG_COARSE_GRAIN, f->flags)) { /* XXX PR 213040: we don't support unlinking coarse, so we try * not to come here, but for indirect branch and other spots * where we don't yet support translation (since can't fault) * we end up w/ no bound on delivery... */ } else if (TEST(FRAG_LINKED_OUTGOING, f->flags)) { LOG(THREAD, LOG_ASYNCH, 3, "\tunlinking outgoing for interrupted F%d\n", f->id); SHARED_FLAGS_RECURSIVE_LOCK(f->flags, acquire, change_linking_lock); unlink_fragment_outgoing(dcontext, f); SHARED_FLAGS_RECURSIVE_LOCK(f->flags, release, change_linking_lock); changed = true; } else { LOG(THREAD, LOG_ASYNCH, 3, "\toutgoing already unlinked for interrupted F%d\n", f->id); } if (TEST(FRAG_HAS_SYSCALL, f->flags)) { /* Syscalls are signal barriers! * Make sure the next syscall (if any) in f is not executed! * instead go back to dispatch right before the syscall */ /* syscall mangling does a bunch of decodes but only one write, * changing the target of a short jmp, which is atomic * since a one-byte write, so we don't need the change_linking_lock. */ if (mangle_syscall_code(dcontext, f, pc, false/*do not skip exit cti*/)) changed = true; } if (!waslinking) enter_nolinking(dcontext, NULL, false); return changed; } static bool interrupted_inlined_syscall(dcontext_t *dcontext, fragment_t *f, byte *pc/*interruption pc*/) { bool pre_or_post_syscall = false; if (TEST(FRAG_HAS_SYSCALL, f->flags)) { /* PR 596147: if the thread is currently in an inlined * syscall when a signal comes in, we can't delay and bound the * delivery time: we need to deliver now. Should decode * backward and see if syscall. We assume our translation of * the interruption state is fine to re-start: i.e., the syscall * is complete if kernel has pc at post-syscall point, and * kernel set EINTR in eax if necessary. */ /* Interrupted fcache, so ok to alloc memory for decode */ instr_t instr; byte *nxt_pc; instr_init(dcontext, &instr); nxt_pc = decode(dcontext, pc, &instr); if (nxt_pc != NULL && instr_valid(&instr) && instr_is_syscall(&instr)) { /* pre-syscall but post-jmp so can't skip syscall */ pre_or_post_syscall = true; } else { size_t syslen = syscall_instr_length(FRAG_ISA_MODE(f->flags)); instr_reset(dcontext, &instr); nxt_pc = decode(dcontext, pc - syslen, &instr); if (nxt_pc != NULL && instr_valid(&instr) && instr_is_syscall(&instr)) { #if defined(X86) && !defined(MACOS) /* decoding backward so check for exit cti jmp prior * to syscall to ensure no mismatch */ instr_reset(dcontext, &instr); nxt_pc = decode(dcontext, pc - syslen - JMP_LONG_LENGTH, &instr); if (nxt_pc != NULL && instr_valid(&instr) && instr_get_opcode(&instr) == OP_jmp) { /* post-inlined-syscall */ pre_or_post_syscall = true; } #else /* On Mac and ARM we have some TLS spills in between so we just * trust that this is a syscall (esp on ARM w/ aligned instrs). */ pre_or_post_syscall = true; #endif } } instr_free(dcontext, &instr); } return pre_or_post_syscall; } /* i#1145: auto-restart syscalls interrupted by signals */ static bool adjust_syscall_for_restart(dcontext_t *dcontext, thread_sig_info_t *info, int sig, sigcontext_t *sc, fragment_t *f) { byte *pc = (byte *) sc->SC_XIP; instr_t instr; int sys_inst_len; if (sc->IF_X86_ELSE(SC_XAX, SC_R0) != -EINTR) { /* The syscall succeeded, so no reason to interrupt. * Some syscalls succeed on a signal coming in. * E.g., SYS_wait4 on SIGCHLD, or reading from a slow device. */ return false; } /* Don't restart if the app's handler says not to */ if (info->app_sigaction[sig] != NULL && !TEST(SA_RESTART, info->app_sigaction[sig]->flags)) { return false; } /* XXX i#1145: some syscalls are never restarted when interrupted by a signal. * We check those that are simple to distinguish below, but not all are. We have * this under an option so it can be disabled if necessary. */ if (!DYNAMO_OPTION(restart_syscalls)) return false; /* For x86, the kernel has already put -EINTR into eax, so we must * restore the syscall number. We assume no other register or * memory values have been clobbered from their pre-syscall * values. * For ARM, we want the sysnum to determine whether restartable. */ int sysnum = -1; if (f != NULL) { /* Inlined syscall. I'd use find_syscall_num() but we'd need to call * decode_fragment() and tweak find_syscall_num() to handle the skip-syscall * jumps, or grab locks and call recreate_fragment_ilist() -- both are * heavyweight, so we do our own decode loop. * We assume we'll find a mov-imm b/c otherwise we wouldn't have inlined this. */ LOG(THREAD, LOG_ASYNCH, 3, "%s: decoding to find syscall #\n", __FUNCTION__); instr_init(dcontext, &instr); pc = FCACHE_ENTRY_PC(f); do { ptr_int_t val; DOLOG(3, LOG_ASYNCH, { disassemble_with_bytes(dcontext, pc, THREAD); }); instr_reset(dcontext, &instr); pc = decode(dcontext, pc, &instr); if (instr_is_mov_constant(&instr, &val) && opnd_is_reg(instr_get_dst(&instr, 0)) && reg_to_pointer_sized(opnd_get_reg(instr_get_dst(&instr, 0))) == reg_to_pointer_sized(DR_REG_SYSNUM)) { sysnum = (int) val; /* don't break: find last one before syscall */ } } while (pc != NULL && instr_valid(&instr) && !instr_is_syscall(&instr) && pc < FCACHE_ENTRY_PC(f) + f->size); instr_free(dcontext, &instr); ASSERT(DYNAMO_OPTION(ignore_syscalls)); ASSERT(sysnum > -1); } else { /* do_syscall => eax should be in mcontext */ sysnum = (int) MCXT_SYSNUM_REG(get_mcontext(dcontext)); } LOG(THREAD, LOG_ASYNCH, 2, "%s: syscall # is %d\n", __FUNCTION__, sysnum); if (sysnum_is_not_restartable(sysnum)) { LOG(THREAD, LOG_ASYNCH, 2, "%s: syscall is non-restartable\n", __FUNCTION__); return false; } #ifdef X86 sc->SC_SYSNUM_REG = sysnum; #elif defined(AARCHXX) /* We just need to restore the app's arg to the syscall into r0, which * the kernel clobbered with -EINTR. We stored r0 into TLS. */ sc->SC_R0 = (reg_t) get_tls(os_tls_offset(TLS_REG0_SLOT)); LOG(THREAD, LOG_ASYNCH, 2, "%s: restored r0 to "PFX"\n", __FUNCTION__, sc->SC_R0); #else # error NYI #endif /* Now adjust the pc to point at the syscall instruction instead of after it, * so when we resume we'll go back to the syscall. * * XXX: this is a transparency issue: the app might expect a pc after the * syscall. We live with it for now. */ #ifdef ARM dr_isa_mode_t isa_mode, old_mode; if (is_after_syscall_address(dcontext, pc)) { /* We're going to walk back in the fragment, not gencode */ isa_mode = dr_get_isa_mode(dcontext); } else { ASSERT(f != NULL); isa_mode = FRAG_ISA_MODE(f->flags); } dr_set_isa_mode(dcontext, isa_mode, &old_mode); sys_inst_len = (isa_mode == DR_ISA_ARM_THUMB) ? SVC_THUMB_LENGTH : SVC_ARM_LENGTH; #else ASSERT(INT_LENGTH == SYSCALL_LENGTH && INT_LENGTH == SYSENTER_LENGTH); sys_inst_len = INT_LENGTH; #endif if (pc == vsyscall_sysenter_return_pc) { #ifdef X86 sc->SC_XIP = (ptr_uint_t) (vsyscall_syscall_end_pc - sys_inst_len); /* To restart sysenter we must re-copy xsp into xbp, as xbp is * clobbered by the kernel. */ sc->SC_XBP = sc->SC_XSP; #else ASSERT_NOT_REACHED(); #endif } else if (is_after_syscall_address(dcontext, pc)) { /* We're at do_syscall: point at app syscall instr */ sc->SC_XIP = (ptr_uint_t) (dcontext->asynch_target - sys_inst_len); DODEBUG({ instr_init(dcontext, &instr); ASSERT(decode(dcontext, (app_pc) sc->SC_XIP, &instr) != NULL && instr_is_syscall(&instr)); instr_free(dcontext, &instr); }); } else { instr_init(dcontext, &instr); pc = decode(dcontext, pc - sys_inst_len, &instr); if (instr_is_syscall(&instr)) sc->SC_XIP -= sys_inst_len; else ASSERT_NOT_REACHED(); instr_free(dcontext, &instr); } #ifdef ARM dr_set_isa_mode(dcontext, old_mode, NULL); #endif LOG(THREAD, LOG_ASYNCH, 2, "%s: sigreturn pc is now "PFX"\n", __FUNCTION__, sc->SC_XIP); return true; } static void record_pending_signal(dcontext_t *dcontext, int sig, kernel_ucontext_t *ucxt, sigframe_rt_t *frame, bool forged _IF_CLIENT(byte *access_address)) { thread_sig_info_t *info = (thread_sig_info_t *) dcontext->signal_field; os_thread_data_t *ostd = (os_thread_data_t *) dcontext->os_field; sigcontext_t *sc = SIGCXT_FROM_UCXT(ucxt); /* XXX #1615: we need a full ucontext to store pre-xl8 simd values */ sigcontext_t sc_orig; byte *pc = (byte *) sc->SC_XIP; byte *xsp = (byte*) sc->SC_XSP; bool receive_now = false; bool blocked = false; bool handled = false; bool at_syscall = false; sigpending_t *pend; fragment_t *f = NULL; fragment_t wrapper; /* We no longer block SUSPEND_SIGNAL (i#184/PR 450670) or SIGSEGV (i#193/PR 287309). * But we can have re-entrancy issues in this routine if the app uses the same * SUSPEND_SIGNAL, or the nested SIGSEGV needs to be sent to the app. The * latter shouldn't happen unless the app sends SIGSEGV via SYS_kill(). */ if (ostd->processing_signal > 0 || /* If we interrupted receive_pending_signal() we can't prepend a new * pending or delete an old b/c we might mess up the state so we * just drop this one: should only happen for alarm signal */ (info->accessing_sigpending && /* we do want to report a crash in receive_pending_signal() */ (can_always_delay[sig] || is_sys_kill(dcontext, pc, (byte*)sc->SC_XSP, &frame->info)))) { LOG(THREAD, LOG_ASYNCH, 1, "nested signal %d\n", sig); ASSERT(ostd->processing_signal == 0 || sig == SUSPEND_SIGNAL || sig == SIGSEGV); ASSERT(can_always_delay[sig] || is_sys_kill(dcontext, pc, (byte*)sc->SC_XSP, &frame->info)); /* To avoid re-entrant execution of special_heap_alloc() and of * prepending to the pending list we just drop this signal. * FIXME i#194/PR 453996: do better. */ STATS_INC(num_signals_dropped); SYSLOG_INTERNAL_WARNING_ONCE("dropping nested signal"); return; } ostd->processing_signal++; /* no need for atomicity: thread-private */ /* First, check whether blocked, before we restore for sigsuspend (i#1340). */ if (kernel_sigismember(&info->app_sigblocked, sig)) blocked = true; if (info->in_sigsuspend) { /* sigsuspend ends when a signal is received, so restore the * old blocked set */ info->app_sigblocked = info->app_sigblocked_save; info->in_sigsuspend = false; /* update the set to restore to post-signal-delivery */ #ifdef MACOS ucxt->uc_sigmask = *(__darwin_sigset_t *) &info->app_sigblocked; #else ucxt->uc_sigmask = info->app_sigblocked; #endif #ifdef DEBUG if (stats->loglevel >= 3 && (stats->logmask & LOG_ASYNCH) != 0) { LOG(THREAD, LOG_ASYNCH, 3, "after sigsuspend, blocked signals are now:\n"); dump_sigset(dcontext, &info->app_sigblocked); } #endif } if (info->app_sigaction[sig] != NULL && info->app_sigaction[sig]->handler == (handler_t)SIG_IGN /* If a client registered a handler, put this in the queue. * Races between registering, queueing, and delivering are fine. */ IF_CLIENT_INTERFACE(&& !dr_signal_hook_exists())) { LOG(THREAD, LOG_ASYNCH, 3, "record_pending_signal (%d at pc "PFX"): action is SIG_IGN!\n", sig, pc); ostd->processing_signal--; return; } else if (blocked) { /* signal is blocked by app, so just record it, don't receive now */ LOG(THREAD, LOG_ASYNCH, 2, "record_pending_signal(%d at pc "PFX"): signal is currently blocked\n", sig, pc); IF_LINUX(handled = notify_signalfd(dcontext, info, sig, frame)); } else if (safe_is_in_fcache(dcontext, pc, xsp)) { LOG(THREAD, LOG_ASYNCH, 2, "record_pending_signal(%d) from cache pc "PFX"\n", sig, pc); if (forged || can_always_delay[sig]) { /* to make translation easier, want to delay if can until dispatch * unlink cur frag, wait for dispatch */ /* check for coarse first to avoid cost of coarse pclookup */ if (get_fcache_coarse_info(pc) != NULL) { /* PR 213040: we can't unlink coarse. If we fail to translate * we'll switch back to delaying, below. */ if (sig_is_alarm_signal(sig) && info->sigpending[sig] != NULL && info->sigpending[sig]->next != NULL && info->skip_alarm_xl8 > 0) { /* Translating coarse fragments is very expensive so we * avoid doing it when we're having trouble keeping up w/ * the alarm frequency (PR 213040), but we make sure we try * every once in a while to avoid unbounded signal delay */ info->skip_alarm_xl8--; STATS_INC(num_signals_coarse_delayed); } else { if (sig_is_alarm_signal(sig)) info->skip_alarm_xl8 = SKIP_ALARM_XL8_MAX; receive_now = true; LOG(THREAD, LOG_ASYNCH, 2, "signal interrupted coarse fragment so delivering now\n"); } } else { f = fragment_pclookup(dcontext, pc, &wrapper); ASSERT(f != NULL); ASSERT(!TEST(FRAG_COARSE_GRAIN, f->flags)); /* checked above */ LOG(THREAD, LOG_ASYNCH, 2, "\tdelaying until exit F%d\n", f->id); if (interrupted_inlined_syscall(dcontext, f, pc)) { /* PR 596147: if delayable signal arrives after syscall-skipping * jmp, either at syscall or post-syscall, we deliver * immediately, since we can't bound the delay */ receive_now = true; LOG(THREAD, LOG_ASYNCH, 2, "signal interrupted pre/post syscall itself so delivering now\n"); at_syscall = true; } else { /* could get another signal but should be in same fragment */ ASSERT(info->interrupted == NULL || info->interrupted == f); if (unlink_fragment_for_signal(dcontext, f, pc)) { info->interrupted = f; info->interrupted_pc = pc; } else { /* either was unlinked for trace creation, or we got another * signal before exiting cache to handle 1st */ ASSERT(info->interrupted == NULL || info->interrupted == f); } } } } else { /* the signal interrupted code cache => run handler now! */ receive_now = true; LOG(THREAD, LOG_ASYNCH, 2, "\tnot certain can delay so handling now\n"); } } else if (in_generated_routine(dcontext, pc) || /* XXX: should also check fine stubs */ safe_is_in_coarse_stubs(dcontext, pc, xsp)) { /* Assumption: dynamo errors have been caught already inside * the master_signal_handler, thus any error in a generated routine * is an asynch signal that can be delayed */ /* FIXME: dispatch on routine: * if fcache_return, treat as dynamo * if fcache_enter, unlink next frag, treat as dynamo * what if next frag has syscall in it? * if indirect_branch_lookup prior to getting target...?!? */ LOG(THREAD, LOG_ASYNCH, 2, "record_pending_signal(%d) from gen routine or stub "PFX"\n", sig, pc); /* i#1206: the syscall was interrupted, so we can go back to dispatch * and don't need to receive it now (which complicates post-syscall handling) * w/o any extra delay. */ at_syscall = is_after_syscall_address(dcontext, pc); /* This could come from another thread's SYS_kill (via our gen do_syscall) */ DOLOG(1, LOG_ASYNCH, { if (!is_after_syscall_address(dcontext, pc) && !forged && !can_always_delay[sig]) { LOG(THREAD, LOG_ASYNCH, 1, "WARNING: signal %d in gen routine: may cause problems!\n", sig); } }); /* i#2019: for a signal arriving in gencode before entry to a fragment, * we need to unlink the fragment just like for a signal arriving inside * the fragment itself. * Multiple signals should all have the same asynch_target so we should * only need a single info->interrupted. */ if (info->interrupted == NULL && !get_at_syscall(dcontext)) { /* Try to find the target if the signal arrived in the IBL. * We could try to be a lot more precise by hardcoding the IBL * sequence here but that would make the code less maintainable. * Instead we try the registers that hold the target app address. * * FIXME i#2042: we'll still fail if the signal arrives at the * actual jmp* in the hit path b/c the reg holding the target is * restored on the prior instr. * * XXX: better to get this code inside arch/ but we'd have to * convert to an mcontext which seems overkill. */ #ifdef AARCHXX /* The target is in r2 the whole time, w/ or w/o Thumb LSB. */ if (sc->SC_R2 != 0) f = fragment_lookup(dcontext, ENTRY_PC_TO_DECODE_PC(sc->SC_R2)); #elif defined(X86) /* The target is initially in xcx but is then copied to xbx. */ if (sc->SC_XBX != 0) f = fragment_lookup(dcontext, (app_pc)sc->SC_XBX); if (f == NULL && sc->SC_XCX != 0) f = fragment_lookup(dcontext, (app_pc)sc->SC_XCX); #else # error Unsupported arch. #endif /* If in fcache_enter, we stored the next_tag in asynch_target in dispatch. */ if (f == NULL && dcontext->asynch_target != NULL) f = fragment_lookup(dcontext, dcontext->asynch_target); if (f != NULL && !TEST(FRAG_COARSE_GRAIN, f->flags)) { if (unlink_fragment_for_signal(dcontext, f, FCACHE_ENTRY_PC(f))) { info->interrupted = f; info->interrupted_pc = FCACHE_ENTRY_PC(f); } } } } else if (pc == vsyscall_sysenter_return_pc) { LOG(THREAD, LOG_ASYNCH, 2, "record_pending_signal(%d) from vsyscall "PFX"\n", sig, pc); /* i#1206: the syscall was interrupted, so we can go back to dispatch * and don't need to receive it now (which complicates post-syscall handling) */ at_syscall = true; } else { /* the signal interrupted DR itself => do not run handler now! */ LOG(THREAD, LOG_ASYNCH, 2, "record_pending_signal(%d) from DR at pc "PFX"\n", sig, pc); if (!forged && !can_always_delay[sig] && !is_sys_kill(dcontext, pc, (byte*)sc->SC_XSP, &frame->info)) { /* i#195/PR 453964: don't re-execute if will just re-fault. * Our checks for dstack, etc. in master_signal_handler should * have accounted for everything */ ASSERT_NOT_REACHED(); abort_on_DR_fault(dcontext, pc, sig, frame, (sig == SIGSEGV) ? "SEGV" : "other", " unknown"); } } LOG(THREAD, LOG_ASYNCH, 3, "\taction is not SIG_IGN\n"); #if defined(X86) && defined(LINUX) LOG(THREAD, LOG_ASYNCH, 3, "\tretaddr = "PFX"\n", frame->pretcode); /* pretcode has same offs for plain */ #endif if (receive_now) { /* we need to translate sc before we know whether client wants to * suppress, so we need a backup copy */ bool xl8_success; /* i#1145: update the context for an auto-restart syscall * before we make the sc_orig copy or translate. */ if (at_syscall) adjust_syscall_for_restart(dcontext, info, sig, sc, f); sc_orig = *sc; ASSERT(!forged); /* cache the fragment since pclookup is expensive for coarse (i#658) */ f = fragment_pclookup(dcontext, (cache_pc)sc->SC_XIP, &wrapper); xl8_success = translate_sigcontext(dcontext, ucxt, !can_always_delay[sig], f); if (can_always_delay[sig] && !xl8_success) { /* delay: we expect this for coarse fragments if alarm arrives * in middle of ind branch region or sthg (PR 213040) */ LOG(THREAD, LOG_ASYNCH, 2, "signal is in un-translatable spot in coarse fragment: delaying\n"); receive_now = false; } } if (receive_now) { /* N.B.: since we abandon the old context for synchronous signals, * we do not need to mark this fragment as FRAG_CANNOT_DELETE */ #ifdef DEBUG if (stats->loglevel >= 2 && (stats->logmask & LOG_ASYNCH) != 0 && safe_is_in_fcache(dcontext, pc, xsp)) { ASSERT(f != NULL); LOG(THREAD, LOG_ASYNCH, 2, "Got signal at pc "PFX" in this fragment:\n", pc); disassemble_fragment(dcontext, f, false); } #endif LOG(THREAD, LOG_ASYNCH, 2, "Going to receive signal now\n"); /* If we end up executing the default action, we'll go native * since we translated the context. If there's a handler, * we'll copy the context to the app stack and then adjust the * original on our stack so we take over. */ execute_handler_from_cache(dcontext, sig, frame, &sc_orig, f _IF_CLIENT(access_address)); } else if (!handled) { #ifdef CLIENT_INTERFACE /* i#182/PR 449996: must let client act on blocked non-delayable signals to * handle instrumentation faults. Make sure we're at a safe spot: i.e., * only raise for in-cache faults. Checking forged and no-delay * to avoid the in-cache check for delayable signals => safer. */ if (blocked && !forged && !can_always_delay[sig] && safe_is_in_fcache(dcontext, pc, xsp)) { dr_signal_action_t action; /* cache the fragment since pclookup is expensive for coarse (i#658) */ f = fragment_pclookup(dcontext, (cache_pc)sc->SC_XIP, &wrapper); sc_orig = *sc; translate_sigcontext(dcontext, ucxt, true/*shouldn't fail*/, f); action = send_signal_to_client(dcontext, sig, frame, &sc_orig, access_address, true/*blocked*/, f); /* For blocked signal early event we disallow BYPASS (xref i#182/PR 449996) */ CLIENT_ASSERT(action != DR_SIGNAL_BYPASS, "cannot bypass a blocked signal event"); if (!handle_client_action_from_cache(dcontext, sig, action, frame, &sc_orig, true/*blocked*/)) { ostd->processing_signal--; return; } /* restore original (untranslated) sc */ *get_sigcontext_from_rt_frame(frame) = sc_orig; } #endif /* i#196/PR 453847: avoid infinite loop of signals if try to re-execute */ if (blocked && !forged && !can_always_delay[sig] && !is_sys_kill(dcontext, pc, (byte*)sc->SC_XSP, &frame->info)) { ASSERT(default_action[sig] == DEFAULT_TERMINATE || default_action[sig] == DEFAULT_TERMINATE_CORE); LOG(THREAD, LOG_ASYNCH, 1, "blocked fatal signal %d cannot be delayed: terminating\n", sig); sc_orig = *sc; translate_sigcontext(dcontext, ucxt, true/*shouldn't fail*/, NULL); /* the process should be terminated */ execute_default_from_cache(dcontext, sig, frame, &sc_orig); ASSERT_NOT_REACHED(); } /* Happened in DR, do not translate context. Record for later processing * at a safe point with a clean app state. */ if (!blocked || sig >= OFFS_RT || (blocked && info->sigpending[sig] == NULL)) { /* only have 1 pending for blocked non-rt signals */ /* special heap alloc always uses sizeof(sigpending_t) blocks */ pend = special_heap_alloc(info->sigheap); ASSERT(sig > 0 && sig <= MAX_SIGNUM); /* to avoid accumulating signals if we're slow in presence of * a high-rate itimer we only keep 2 alarm signals (PR 596768) */ if (sig_is_alarm_signal(sig)) { if (info->sigpending[sig] != NULL && info->sigpending[sig]->next != NULL) { ASSERT(info->sigpending[sig]->next->next == NULL); /* keep the oldest, replace newer w/ brand-new one, for * more spread-out alarms */ sigpending_t *temp = info->sigpending[sig]; info->sigpending[sig] = temp->next; special_heap_free(info->sigheap, temp); LOG(THREAD, LOG_ASYNCH, 2, "3rd pending alarm %d => dropping 2nd\n", sig); STATS_INC(num_signals_dropped); SYSLOG_INTERNAL_WARNING_ONCE("dropping 3rd pending alarm signal"); } } pend->next = info->sigpending[sig]; info->sigpending[sig] = pend; pend->unblocked = !blocked; /* FIXME: note that for asynchronous signals we don't need to * bother to record exact machine context, even entire frame, * since don't want to pass dynamo pc context to app handler. * only copy frame for synchronous signals? those only * happen while in cache? but for asynch, we would have to * construct our own frame...kind of a pain. */ copy_frame_to_pending(dcontext, sig, frame _IF_CLIENT(access_address)); /* i#1145: check whether we should auto-restart an interrupted syscall */ if (at_syscall) { /* Adjust the pending frame to restart the syscall, if applicable */ sigframe_rt_t *frame = &(info->sigpending[sig]->rt_frame); sigcontext_t *sc_pend = get_sigcontext_from_rt_frame(frame); if (adjust_syscall_for_restart(dcontext, info, sig, sc_pend, f)) { /* We're going to re-start this syscall after we go * back to dispatch, run the post-syscall handler (for -EINTR), * and deliver the signal. We've adjusted the sigcontext * for re-start on the sigreturn, but we need to tell * execute_handler_from_dispatch() to use our sigcontext * and not the mcontext. * A client will see a second set of pre + post handlers for * the restart, which seems reasonable, given the signal in * between. */ info->sigpending[sig]->use_sigcontext = true; } } } else { /* For clients, we document that we do not pass to them * unless we're prepared to deliver to app. We would have * to change our model to pass them non-final-translated * contexts for delayable signals in order to give them * signals as soon as they come in. Xref i#182/PR 449996. */ LOG(THREAD, LOG_ASYNCH, 3, "\tnon-rt signal already in queue, ignoring this one!\n"); } if (!blocked && !dcontext->signals_pending) dcontext->signals_pending = 1; } ostd->processing_signal--; } /* Distinguish SYS_kill-generated from instruction-generated signals. * If sent from another process we can't tell, but if sent from this * thread the interruption point should be our own post-syscall. * FIXME PR 368277: for other threads in same process we should set a flag * and identify them as well. * FIXME: for faults like SIGILL we could examine the interrupted pc * to see whether it is capable of generating such a fault (see code * used in handle_nudge_signal()). */ static bool is_sys_kill(dcontext_t *dcontext, byte *pc, byte *xsp, siginfo_t *info) { #ifndef VMX86_SERVER /* does not properly set si_code */ /* i#133: use si_code to distinguish user-sent signals. * Even 2.2 Linux kernel supports <=0 meaning user-sent (except * SIGIO) so we assume we can rely on it. */ if (info->si_code <= 0) return true; #endif return (is_at_do_syscall(dcontext, pc, xsp) && (dcontext->sys_num == SYS_kill || #ifdef LINUX dcontext->sys_num == SYS_tkill || dcontext->sys_num == SYS_tgkill || dcontext->sys_num == SYS_rt_sigqueueinfo #elif defined (MACOS) dcontext->sys_num == SYS___pthread_kill #endif )); } static byte * compute_memory_target(dcontext_t *dcontext, cache_pc instr_cache_pc, kernel_ucontext_t *uc, siginfo_t *si, bool *write) { sigcontext_t *sc = SIGCXT_FROM_UCXT(uc); byte *target = NULL; instr_t instr; priv_mcontext_t mc; uint memopidx, memoppos, memopsize; opnd_t memop; bool found_target = false; bool in_maps; bool use_allmem = false; uint prot; IF_ARM(dr_isa_mode_t old_mode;) LOG(THREAD, LOG_ALL, 2, "computing memory target for "PFX" causing SIGSEGV, kernel claims it is "PFX"\n", instr_cache_pc, (byte*)si->si_addr); /* ARM's sigcontext_t has a "fault_address" field but it also seems unreliable */ IF_ARM(LOG(THREAD, LOG_ALL, 2, "fault_address: "PFX"\n", sc->fault_address)); /* We used to do a memory query to check if instr_cache_pc is readable, but * now we use TRY/EXCEPT because we don't have the instr length and the OS * query is expensive. If decoding faults, the signal handler will longjmp * out before it calls us recursively. */ instr_init(dcontext, &instr); IF_ARM({ /* Be sure to use the interrupted mode and not the last-dispatch mode */ dr_set_isa_mode(dcontext, get_pc_mode_from_cpsr(sc), &old_mode); }); TRY_EXCEPT(dcontext, { decode(dcontext, instr_cache_pc, &instr); }, { return NULL; /* instr_cache_pc was unreadable */ }); IF_ARM(dr_set_isa_mode(dcontext, old_mode, NULL)); if (!instr_valid(&instr)) { LOG(THREAD, LOG_ALL, 2, "WARNING: got SIGSEGV for invalid instr at cache pc "PFX"\n", instr_cache_pc); ASSERT_NOT_REACHED(); instr_free(dcontext, &instr); return NULL; } ucontext_to_mcontext(&mc, uc); ASSERT(write != NULL); /* i#1009: If si_addr is plausibly one of the memory operands of the * faulting instruction, assume the target was si_addr. If none of the * memops match, fall back to checking page protections, which can be racy. * For si_addr == NULL, we fall back to the protection check because it's * too likely to be a valid memop and we can live with a race on a page that * is typically unmapped. */ if (si->si_code == SEGV_ACCERR && si->si_addr != NULL) { for (memopidx = 0; instr_compute_address_ex_priv(&instr, &mc, memopidx, &target, write, &memoppos); memopidx++) { /* i#1045: check whether operand and si_addr overlap */ memop = *write ? instr_get_dst(&instr, memoppos) : instr_get_src(&instr, memoppos); memopsize = opnd_size_in_bytes(opnd_get_size(memop)); LOG(THREAD, LOG_ALL, 2, "memory operand %u has address "PFX" and size %u\n", memopidx, target, memopsize); if ((byte*)si->si_addr >= target && (byte*)si->si_addr < target + memopsize) { target = (byte*)si->si_addr; found_target = true; break; } } } /* For fcache faults, use all_memory_areas, which is faster but acquires * locks. If it's possible we're in DR, go to the OS to avoid deadlock. */ if (DYNAMO_OPTION(use_all_memory_areas)) { use_allmem = safe_is_in_fcache(dcontext, instr_cache_pc, (byte *)sc->SC_XSP); } if (!found_target) { if (si->si_addr != NULL) { LOG(THREAD, LOG_ALL, 3, "%s: falling back to racy protection checks\n", __FUNCTION__); } /* i#115/PR 394984: consider all memops */ for (memopidx = 0; instr_compute_address_ex_priv(&instr, &mc, memopidx, &target, write, NULL); memopidx++) { if (use_allmem) { in_maps = get_memory_info(target, NULL, NULL, &prot); } else { in_maps = get_memory_info_from_os(target, NULL, NULL, &prot); } if ((!in_maps || !TEST(MEMPROT_READ, prot)) || (*write && !TEST(MEMPROT_WRITE, prot))) { found_target = true; break; } } } if (!found_target) { /* probably an NX fault: how tell whether kernel enforcing? */ in_maps = get_memory_info_from_os(instr_cache_pc, NULL, NULL, &prot); if (!in_maps || !TEST(MEMPROT_EXEC, prot)) { target = instr_cache_pc; found_target = true; } } /* we may still not find target, e.g. for SYS_kill(SIGSEGV) */ if (!found_target) target = NULL; DOLOG(2, LOG_ALL, { LOG(THREAD, LOG_ALL, 2, "For SIGSEGV at cache pc "PFX", computed target %s "PFX"\n", instr_cache_pc, *write ? "write" : "read", target); loginst(dcontext, 2, &instr, "\tfaulting instr"); }); instr_free(dcontext, &instr); return target; } /* If native_state is true, assumes the fault is not in the cache and thus * does not need translation but rather should always be re-executed. */ static bool check_for_modified_code(dcontext_t *dcontext, cache_pc instr_cache_pc, sigcontext_t *sc, byte *target, bool native_state) { /* special case: we expect a seg fault for executable regions * that were writable and marked read-only by us. * have to figure out the target address! * unfortunately the OS doesn't tell us, nor whether it's a write. * FIXME: if sent from SYS_kill(SIGSEGV), the pc will be post-syscall, * and if that post-syscall instr is a write that could have faulted, * how can we tell the difference? */ if (was_executable_area_writable(target)) { /* translate instr_cache_pc to original app pc * DO NOT use translate_sigcontext, don't want to change the * signal frame or else we'll lose control when we try to * return to signal pc! */ app_pc next_pc, translated_pc = NULL; fragment_t *f = NULL; fragment_t wrapper; ASSERT((cache_pc)sc->SC_XIP == instr_cache_pc); if (!native_state) { /* For safe recreation we need to either be couldbelinking or hold * the initexit lock (to keep someone from flushing current * fragment), the initexit lock is easier */ mutex_lock(&thread_initexit_lock); /* cache the fragment since pclookup is expensive for coarse units (i#658) */ f = fragment_pclookup(dcontext, instr_cache_pc, &wrapper); translated_pc = recreate_app_pc(dcontext, instr_cache_pc, f); ASSERT(translated_pc != NULL); mutex_unlock(&thread_initexit_lock); } next_pc = handle_modified_code(dcontext, instr_cache_pc, translated_pc, target, f); if (!native_state) { /* going to exit from middle of fragment (at the write) so will mess up * trace building */ if (is_building_trace(dcontext)) { LOG(THREAD, LOG_ASYNCH, 3, "\tsquashing trace-in-progress\n"); trace_abort(dcontext); } } if (next_pc == NULL) { /* re-execute the write -- just have master_signal_handler return */ return true; } else { ASSERT(!native_state); /* Do not resume execution in cache, go back to dispatch. */ transfer_from_sig_handler_to_fcache_return(dcontext, sc, next_pc, (linkstub_t *) get_selfmod_linkstub()); /* now have master_signal_handler return */ return true; } } return false; } #ifndef HAVE_SIGALTSTACK /* The exact layout of this struct is relied on in master_signal_handler() * in x86.asm. */ struct clone_and_swap_args { byte *stack; byte *tos; }; /* Helper function for swapping handler to dstack */ bool sig_should_swap_stack(struct clone_and_swap_args *args, kernel_ucontext_t *ucxt) { byte *cur_esp; dcontext_t *dcontext = get_thread_private_dcontext(); if (dcontext == NULL) return false; GET_STACK_PTR(cur_esp); if (!is_on_dstack(dcontext, cur_esp)) { sigcontext_t *sc = SIGCXT_FROM_UCXT(ucxt); /* Pass back the proper args to clone_and_swap_stack: we want to * copy to dstack from the tos at the signal interruption point. */ args->stack = dcontext->dstack; /* leave room for fpstate */ args->stack -= signal_frame_extra_size(true); args->stack = (byte *) ALIGN_BACKWARD(args->stack, XSTATE_ALIGNMENT); args->tos = (byte *) sc->SC_XSP; return true; } else return false; } #endif /* Helper that takes over the current thread signaled via SUSPEND_SIGNAL. Kept * separate mostly to keep the priv_mcontext_t allocation out of * master_signal_handler_C. */ static void sig_take_over(kernel_ucontext_t *uc) { priv_mcontext_t mc; ucontext_to_mcontext(&mc, uc); /* We don't want our own blocked signals: we want the app's, stored in the frame. */ os_thread_take_over(&mc, SIGMASK_FROM_UCXT(uc)); ASSERT_NOT_REACHED(); } static bool is_safe_read_ucxt(kernel_ucontext_t *ucxt) { app_pc pc = (app_pc) SIGCXT_FROM_UCXT(ucxt)->SC_XIP; return is_safe_read_pc(pc); } /* the master signal handler * WARNING: behavior varies with different versions of the kernel! * sigaction support was only added with 2.2 */ #ifndef X86_32 /* stub in x86.asm passes our xsp to us */ # ifdef MACOS void master_signal_handler_C(handler_t handler, int style, int sig, siginfo_t *info, kernel_ucontext_t *ucxt, byte *xsp) # else void master_signal_handler_C(int sig, siginfo_t *siginfo, kernel_ucontext_t *ucxt, byte *xsp) # endif #else /* On ia32, adding a parameter disturbs the frame we're trying to capture, so we * add an intermediate frame and read the normal params off the stack directly. */ void master_signal_handler_C(byte *xsp) #endif { sigframe_rt_t *frame = (sigframe_rt_t *) xsp; #ifdef X86_32 /* Read the normal arguments from the frame. */ int sig = frame->sig; siginfo_t *siginfo = frame->pinfo; kernel_ucontext_t *ucxt = frame->puc; #endif /* !X64 */ sigcontext_t *sc = SIGCXT_FROM_UCXT(ucxt); thread_record_t *tr; #ifdef DEBUG uint level = 2; # if !defined(HAVE_MEMINFO) /* avoid logging every single TRY probe fault */ if (!dynamo_initialized) level = 5; # endif #endif bool local; #if defined(MACOS) && !defined(X64) /* The kernel clears fs, so we have to re-instate our selector, if * it was set in the first place. */ if (sc->__ss.__fs != 0) tls_reinstate_selector(sc->__ss.__fs); #endif #ifdef X86 /* i#2089: For is_thread_tls_initialized() we need a safe_read path that does not * do any logging or call get_thread_private_dcontext() as those will recurse. * This path is global so there's no SELF_PROTECT_LOCAL and we also bypass * the ENTERING_DR() for this short path. */ if (sig == SIGSEGV && sc->SC_XIP == (ptr_uint_t)safe_read_tls_magic) { sc->SC_RETURN_REG = 0; sc->SC_XIP = (reg_t) safe_read_tls_magic_recover; return; } else if (sig == SIGSEGV && sc->SC_XIP == (ptr_uint_t)safe_read_tls_self) { sc->SC_RETURN_REG = 0; sc->SC_XIP = (reg_t) safe_read_tls_self_recover; return; } else if (sig == SIGSEGV && sc->SC_XIP == (ptr_uint_t)safe_read_tls_app_self) { sc->SC_RETURN_REG = 0; sc->SC_XIP = (reg_t) safe_read_tls_app_self_recover; return; } #endif dcontext_t *dcontext = get_thread_private_dcontext(); #ifdef MACOS # ifdef X64 ASSERT((YMM_ENABLED() && ucxt->uc_mcsize == sizeof(_STRUCT_MCONTEXT_AVX64)) || (!YMM_ENABLED() && ucxt->uc_mcsize == sizeof(_STRUCT_MCONTEXT64))); # else ASSERT((YMM_ENABLED() && ucxt->uc_mcsize == sizeof(_STRUCT_MCONTEXT_AVX32)) || (!YMM_ENABLED() && ucxt->uc_mcsize == sizeof(_STRUCT_MCONTEXT))); # endif #endif /* i#350: To support safe_read or TRY_EXCEPT without a dcontext, use the * global dcontext * when handling safe_read faults. This lets us pass the check for a * dcontext below and causes us to use the global log. */ if (dcontext == NULL && (sig == SIGSEGV || sig == SIGBUS) && (is_safe_read_ucxt(ucxt) || (!dynamo_initialized && global_try_except.try_except_state != NULL))) { dcontext = GLOBAL_DCONTEXT; } if (dynamo_exited && get_num_threads() > 1 && sig == SIGSEGV) { /* PR 470957: this is almost certainly a race so just squelch it. * We live w/ the risk that it was holding a lock our release-build * exit code needs. */ exit_thread_syscall(1); } /* FIXME: ensure the path for recording a pending signal does not grab any DR locks * that could have been interrupted * e.g., synchronize_dynamic_options grabs the stats_lock! */ if (dcontext == NULL && sig == SUSPEND_SIGNAL) { /* Check for a temporarily-native thread we're synch-ing with. */ tr = thread_lookup(get_sys_thread_id()); if (tr != NULL) dcontext = tr->dcontext; } if (dcontext == NULL || (dcontext != GLOBAL_DCONTEXT && (dcontext->signal_field == NULL || !((thread_sig_info_t*)dcontext->signal_field)->fully_initialized))) { /* FIXME: || !intercept_asynch, or maybe !under_our_control */ /* FIXME i#26: this could be a signal arbitrarily sent to this thread. * We could try to route it to another thread, using a global queue * of pending signals. But what if it was targeted to this thread * via SYS_{tgkill,tkill}? Can we tell the difference, even if * we watch the kill syscalls: could come from another process? */ if (sig_is_alarm_signal(sig)) { /* assuming an alarm during thread exit or init (xref PR 596127, * i#359): suppressing is fine */ } else if (sig == SUSPEND_SIGNAL && dcontext == NULL) { /* We sent SUSPEND_SIGNAL to a thread we don't control (no * dcontext), which means we want to take over. */ ASSERT(!doing_detach); sig_take_over(ucxt); /* no return */ ASSERT_NOT_REACHED(); } else { /* Using global dcontext because dcontext is NULL here. */ DOLOG(1, LOG_ASYNCH, { dump_sigcontext(GLOBAL_DCONTEXT, sc); }); SYSLOG_INTERNAL_ERROR("ERROR: master_signal_handler with no siginfo " "(i#26?): tid=%d, sig=%d", get_sys_thread_id(), sig); } /* see FIXME comments above. * workaround for now: suppressing is better than dying. */ if (can_always_delay[sig]) return; else exit_process_syscall(1); } /* we may be entering dynamo from code cache! */ /* Note that this is unsafe if -single_thread_in_DR => we grab a lock => * hang if signal interrupts DR: but we don't really support that option */ ENTERING_DR(); if (dcontext == GLOBAL_DCONTEXT) { local = false; tr = thread_lookup(get_sys_thread_id()); } else { tr = dcontext->thread_record; local = local_heap_protected(dcontext); if (local) SELF_PROTECT_LOCAL(dcontext, WRITABLE); } /* i#1921: For proper native execution with re-takeover we need to propagate * signals to app handlers while native. For now we do not support re-takeover * and we give up our handlers via signal_remove_handlers(). */ ASSERT(tr == NULL || tr->under_dynamo_control || IS_CLIENT_THREAD(dcontext) || sig == SUSPEND_SIGNAL); LOG(THREAD, LOG_ASYNCH, level, "\nmaster_signal_handler: sig=%d, retaddr="PFX"\n", sig, *((byte **)xsp)); LOG(THREAD, LOG_ASYNCH, level+1, "siginfo: sig = %d, pid = %d, status = %d, errno = %d, si_code = %d\n", siginfo->si_signo, siginfo->si_pid, siginfo->si_status, siginfo->si_errno, siginfo->si_code); DOLOG(level+1, LOG_ASYNCH, { dump_sigcontext(dcontext, sc); }); #if defined(X86_32) && !defined(VMX86_SERVER) && defined(LINUX) /* FIXME case 6700: 2.6.9 (FC3) kernel sets up our frame with a pretcode * of 0x440. This happens if our restorer is unspecified (though 2.6.9 * src code shows setting the restorer to a default value in that case...) * or if we explicitly point at dynamorio_sigreturn. I couldn't figure * out why it kept putting 0x440 there. So we fix the issue w/ this * hardcoded return. * This hack causes vmkernel to kill the process on sigreturn due to * vmkernel's non-standard sigreturn semantics. PR 404712. */ *((byte **)xsp) = (byte *) dynamorio_sigreturn; #endif /* N.B.: * ucontext_t is defined in two different places. The one we get * included is /usr/include/sys/ucontext.h, which would have us * doing this: * void *pc = (void *) ucxt->uc_mcontext.gregs[EIP]; * However, EIP is not defined for us (used to be in older * RedHat version) unless we define __USE_GNU, which we don't want to do * for other reasons, so we'd have to also say: * #define EIP 14 * Instead we go by the ucontext_t definition in * /usr/include/asm/ucontext.h, which has it containing a sigcontext struct, * defined in /usr/include/asm/sigcontext.h. This is the definition used * by the kernel. The two definitions are field-for-field * identical except that the sys one has an fpstate struct at the end -- * but the next field in the frame is an fpstate. The only mystery * is why the rt frame is declared as ucontext instead of sigcontext. * The kernel's version of ucontext must be the asm one! * And the sys one grabs the next field of the frame. * Also note that mcontext_t.fpregs == sigcontext.fpstate is NULL if * floating point operations have not been used (lazy fp state saving). * Also, sigset_t has different sizes according to kernel (8 bytes) vs. * glibc (128 bytes?). */ switch (sig) { case SIGBUS: /* PR 313665: look for DR crashes on unaligned memory or mmap bounds */ case SIGSEGV: { /* Older kernels do NOT fill out the signal-specific fields of siginfo, * except for SIGCHLD. Thus we cannot do this: * void *pc = (void*) siginfo->si_addr; * Thus we must use the third argument, which is a ucontext_t (see above) */ void *pc = (void *) sc->SC_XIP; bool syscall_signal = false; /* signal came from syscall? */ bool is_write = false; byte *target; bool is_DR_exception = false; #ifdef SIDELINE if (dcontext == NULL) { SYSLOG_INTERNAL_ERROR("seg fault in sideline thread -- NULL dcontext!"); ASSERT_NOT_REACHED(); } #endif if (is_safe_read_ucxt(ucxt) || (!dynamo_initialized && global_try_except.try_except_state != NULL) || dcontext->try_except.try_except_state != NULL) { /* handle our own TRY/EXCEPT */ try_except_context_t *try_cxt; #ifdef HAVE_MEMINFO /* our probe produces many of these every run */ /* since we use for safe_*, making a _ONCE */ SYSLOG_INTERNAL_WARNING_ONCE("(1+x) Handling our fault in a TRY at "PFX, pc); #endif LOG(THREAD, LOG_ALL, level, "TRY fault at "PFX"\n", pc); if (TEST(DUMPCORE_TRY_EXCEPT, DYNAMO_OPTION(dumpcore_mask))) os_dump_core("try/except fault"); if (is_safe_read_ucxt(ucxt)) { sc->SC_XIP = (reg_t) safe_read_resume_pc(); /* Break out to log the normal return from the signal handler. */ break; } try_cxt = (dcontext != NULL) ? dcontext->try_except.try_except_state : global_try_except.try_except_state; ASSERT(try_cxt != NULL); /* The exception interception code did an ENTER so we must EXIT here */ EXITING_DR(); /* Since we have no sigreturn we have to restore the mask * manually, just like siglongjmp(). i#226/PR 492568: we rely * on the kernel storing the prior mask in ucxt, so we do not * need to store it on every setjmp. */ /* Verify that there's no scenario where the mask gets changed prior * to a fault inside a try. This relies on dr_setjmp_sigmask() filling * in the mask, which we only bother to do in debug build. */ ASSERT(memcmp(&try_cxt->context.sigmask, &ucxt->uc_sigmask, sizeof(ucxt->uc_sigmask)) == 0); sigprocmask_syscall(SIG_SETMASK, SIGMASK_FROM_UCXT(ucxt), NULL, sizeof(ucxt->uc_sigmask)); DR_LONGJMP(&try_cxt->context, LONGJMP_EXCEPTION); ASSERT_NOT_REACHED(); } target = compute_memory_target(dcontext, pc, ucxt, siginfo, &is_write); #ifdef CLIENT_INTERFACE if (CLIENTS_EXIST() && is_in_client_lib(pc)) { /* i#1354: client might write to a page we made read-only. * If so, handle the fault and re-execute it, if it's safe to do so * (we document these criteria under DR_MEMPROT_PRETEND_WRITE). */ if (is_write && !is_couldbelinking(dcontext) && OWN_NO_LOCKS(dcontext) && check_for_modified_code(dcontext, pc, sc, target, true/*native*/)) break; abort_on_fault(dcontext, DUMPCORE_CLIENT_EXCEPTION, pc, sig, frame, exception_label_client, (sig == SIGSEGV) ? "SEGV" : "BUS", " client library"); ASSERT_NOT_REACHED(); } #endif /* For !HAVE_MEMINFO, we cannot compute the target until * after the try/except check b/c compute_memory_target() * calls get_memory_info_from_os() which does a probe: and the * try/except could be from a probe itself. A try/except that * triggers a stack overflow should recover on the longjmp, so * this order should be fine. */ #ifdef STACK_GUARD_PAGE if (sig == SIGSEGV && is_write && is_stack_overflow(dcontext, target)) { SYSLOG_INTERNAL_CRITICAL(PRODUCT_NAME" stack overflow at pc "PFX, pc); /* options are already synchronized by the SYSLOG */ if (TEST(DUMPCORE_INTERNAL_EXCEPTION, dynamo_options.dumpcore_mask)) os_dump_core("stack overflow"); os_terminate(dcontext, TERMINATE_PROCESS); } #endif /* STACK_GUARD_PAGE */ /* FIXME: share code with Windows callback.c */ /* FIXME PR 205795: in_fcache and is_dynamo_address do grab locks! */ if ((is_on_dstack(dcontext, (byte *)sc->SC_XSP) /* PR 302951: clean call arg processing => pass to app/client. * Rather than call the risky in_fcache we check whereami. */ IF_CLIENT_INTERFACE(&& (dcontext->whereami != WHERE_FCACHE))) || is_on_alt_stack(dcontext, (byte *)sc->SC_XSP) || is_on_initstack((byte *)sc->SC_XSP)) { /* Checks here need to cover everything that record_pending_signal() * thinks is non-fcache, non-gencode: else that routine will kill * process since can't delay or re-execute (i#195/PR 453964). */ is_DR_exception = true; } else if (!safe_is_in_fcache(dcontext, pc, (byte*)sc->SC_XSP) && (in_generated_routine(dcontext, pc) || is_at_do_syscall(dcontext, pc, (byte*)sc->SC_XSP) || is_dynamo_address(pc))) { #ifdef CLIENT_INTERFACE if (!in_generated_routine(dcontext, pc) && !is_at_do_syscall(dcontext, pc, (byte*)sc->SC_XSP)) { /* PR 451074: client needs a chance to handle exceptions in its * own gencode. client_exception_event() won't return if client * wants to re-execute faulting instr. */ dr_signal_action_t action = send_signal_to_client(dcontext, sig, frame, sc, target, false/*!blocked*/, NULL); if (action != DR_SIGNAL_DELIVER && /* for delivery, continue below */ !handle_client_action_from_cache(dcontext, sig, action, frame, sc, false/*!blocked*/)) { /* client handled fault */ break; } } #endif is_DR_exception = true; } if (is_DR_exception) { /* kill(getpid(), SIGSEGV) looks just like a SIGSEGV in the store of eax * to mcontext after the syscall instr in do_syscall -- try to distinguish: */ if (is_sys_kill(dcontext, pc, (byte*)sc->SC_XSP, siginfo)) { LOG(THREAD, LOG_ALL, 2, "assuming SIGSEGV at post-do-syscall is kill, not our write fault\n"); syscall_signal = true; } if (!syscall_signal) { if (check_in_last_thread_vm_area(dcontext, target)) { /* See comments in callback.c as well. * FIXME: try to share code */ SYSLOG_INTERNAL_WARNING("(decode) exception in last area, " "DR pc="PFX", app pc="PFX, pc, target); STATS_INC(num_exceptions_decode); if (is_building_trace(dcontext)) { LOG(THREAD, LOG_ASYNCH, 2, "intercept_exception: " "squashing old trace\n"); trace_abort(dcontext); } /* we do get faults when not building a bb: e.g., * ret_after_call_check does decoding (case 9396) */ if (dcontext->bb_build_info != NULL) { /* must have been building a bb at the time */ bb_build_abort(dcontext, true/*clean vm area*/, true/*unlock*/); } /* Since we have no sigreturn we have to restore the mask manually */ unblock_all_signals(NULL); /* Let's pass it back to the application - memory is unreadable */ if (TEST(DUMPCORE_FORGE_UNREAD_EXEC, DYNAMO_OPTION(dumpcore_mask))) os_dump_core("Warning: Racy app execution (decode unreadable)"); os_forge_exception(target, UNREADABLE_MEMORY_EXECUTION_EXCEPTION); ASSERT_NOT_REACHED(); } else { abort_on_DR_fault(dcontext, pc, sig, frame, (sig == SIGSEGV) ? "SEGV" : "BUS", in_generated_routine(dcontext, pc) ? " generated" : ""); } } } /* if get here, pass the signal to the app */ ASSERT(pc != 0); /* shouldn't get here */ if (sig == SIGSEGV && !syscall_signal/*only for in-cache signals*/) { /* special case: we expect a seg fault for executable regions * that were writable and marked read-only by us. */ if (is_write && check_for_modified_code(dcontext, pc, sc, target, false/*!native*/)) { /* it was our signal, so don't pass to app -- return now */ break; } } /* pass it to the application (or client) */ LOG(THREAD, LOG_ALL, 1, "** Received SIG%s at cache pc "PFX" in thread "TIDFMT"\n", (sig == SIGSEGV) ? "SEGV" : "BUS", pc, get_thread_id()); ASSERT(syscall_signal || safe_is_in_fcache(dcontext, pc, (byte *)sc->SC_XSP)); /* we do not call trace_abort() here since we may need to * translate from a temp private bb (i#376): but all paths * that deliver the signal or redirect will call it */ record_pending_signal(dcontext, sig, ucxt, frame, false _IF_CLIENT(target)); break; } /* PR 212090: the signal we use to suspend threads */ case SUSPEND_SIGNAL: if (handle_suspend_signal(dcontext, ucxt, frame)) { /* i#1921: see comment above */ ASSERT(tr == NULL || tr->under_dynamo_control || IS_CLIENT_THREAD(dcontext)); record_pending_signal(dcontext, sig, ucxt, frame, false _IF_CLIENT(NULL)); } /* else, don't deliver to app */ break; /* i#61/PR 211530: the signal we use for nudges */ case NUDGESIG_SIGNUM: if (handle_nudge_signal(dcontext, siginfo, ucxt)) record_pending_signal(dcontext, sig, ucxt, frame, false _IF_CLIENT(NULL)); /* else, don't deliver to app */ break; case SIGALRM: case SIGVTALRM: case SIGPROF: if (handle_alarm(dcontext, sig, ucxt)) record_pending_signal(dcontext, sig, ucxt, frame, false _IF_CLIENT(NULL)); /* else, don't deliver to app */ break; #ifdef SIDELINE case SIGCHLD: { int status = siginfo->si_status; if (siginfo->si_pid == 0) { /* FIXME: with older versions of linux the sigchld fields of * siginfo are not filled in properly! * This is my attempt to handle that, pid seems to be 0 */ break; } if (status != 0) { LOG(THREAD, LOG_ALL, 0, "*** Child thread died with error %d\n", status); ASSERT_NOT_REACHED(); } break; } #endif default: { record_pending_signal(dcontext, sig, ucxt, frame, false _IF_CLIENT(NULL)); break; } } /* end switch */ LOG(THREAD, LOG_ASYNCH, level, "\tmaster_signal_handler %d returning now\n\n", sig); /* restore protections */ if (local) SELF_PROTECT_LOCAL(dcontext, READONLY); EXITING_DR(); } static bool execute_handler_from_cache(dcontext_t *dcontext, int sig, sigframe_rt_t *our_frame, sigcontext_t *sc_orig, fragment_t *f _IF_CLIENT(byte *access_address)) { thread_sig_info_t *info = (thread_sig_info_t *) dcontext->signal_field; /* we want to modify the sc in DR's frame */ sigcontext_t *sc = get_sigcontext_from_rt_frame(our_frame); kernel_sigset_t blocked; /* Need to get xsp now before get new dcontext. * This is the translated xsp, so we avoid PR 306410 (cleancall arg fault * on dstack => handler run on dstack) that Windows hit. */ byte *xsp = get_sigstack_frame_ptr(dcontext, sig, our_frame/* take xsp from (translated) * interruption point */); #ifdef CLIENT_INTERFACE dr_signal_action_t action = send_signal_to_client(dcontext, sig, our_frame, sc_orig, access_address, false/*not blocked*/, f); if (!handle_client_action_from_cache(dcontext, sig, action, our_frame, sc_orig, false/*!blocked*/)) return false; #else if (info->app_sigaction[sig] == NULL || info->app_sigaction[sig]->handler == (handler_t)SIG_DFL) { LOG(THREAD, LOG_ASYNCH, 3, "\taction is SIG_DFL\n"); if (execute_default_from_cache(dcontext, sig, our_frame, sc_orig)) { /* if we haven't terminated, restore original (untranslated) sc * on request. * XXX i#1615: this doesn't restore SIMD regs, if client translated them! */ *get_sigcontext_from_rt_frame(our_frame) = *sc_orig; } return false; } ASSERT(info->app_sigaction[sig] != NULL && info->app_sigaction[sig]->handler != (handler_t)SIG_IGN && info->app_sigaction[sig]->handler != (handler_t)SIG_DFL); #endif LOG(THREAD, LOG_ASYNCH, 2, "execute_handler_from_cache for signal %d\n", sig); RSTATS_INC(num_signals); /* now that we know it's not a client-involved fault, dump as app fault */ report_app_problem(dcontext, APPFAULT_FAULT, (byte *)sc->SC_XIP, (byte *)sc->SC_FP, "\nSignal %d delivered to application handler.\n", sig); LOG(THREAD, LOG_ASYNCH, 3, "\txsp is "PFX"\n", xsp); /* copy frame to appropriate stack and convert to non-rt if necessary */ copy_frame_to_stack(dcontext, sig, our_frame, (void *)xsp, false/*!pending*/); LOG(THREAD, LOG_ASYNCH, 3, "\tcopied frame from "PFX" to "PFX"\n", our_frame, xsp); /* Because of difficulties determining when/if a signal handler * returns, we do what the kernel does: abandon all of our current * state, copy what we might need to the handler frame if we come back, * and then it's ok if the handler doesn't return. * If it does, we start interpreting afresh when we see sigreturn(). * This routine assumes anything needed to return has been put in the * frame (only needed for signals queued up while in dynamo), and goes * ahead and trashes the current dcontext. */ /* if we were building a trace, kill it */ if (is_building_trace(dcontext)) { LOG(THREAD, LOG_ASYNCH, 3, "\tsquashing trace-in-progress\n"); trace_abort(dcontext); } /* add to set of blocked signals those in sigaction mask */ blocked = info->app_sigaction[sig]->mask; /* SA_NOMASK says whether to block sig itself or not */ if ((info->app_sigaction[sig]->flags & SA_NOMASK) == 0) kernel_sigaddset(&blocked, sig); set_blocked(dcontext, &blocked, false/*relative: OR these in*/); /* Doesn't matter what most app registers are, signal handler doesn't * expect anything except the frame on the stack. We do need to set xsp, * only because if app wants special signal stack we need to point xsp * there. (If no special signal stack, this is a nop.) */ sc->SC_XSP = (ptr_uint_t) xsp; /* Set up args to handler: int sig, siginfo_t *siginfo, kernel_ucontext_t *ucxt */ #ifdef X86_64 sc->SC_XDI = sig; sc->SC_XSI = (reg_t) &((sigframe_rt_t *)xsp)->info; sc->SC_XDX = (reg_t) &((sigframe_rt_t *)xsp)->uc; #elif defined(AARCHXX) sc->SC_R0 = sig; if (IS_RT_FOR_APP(info, sig)) { sc->SC_R1 = (reg_t) &((sigframe_rt_t *)xsp)->info; sc->SC_R2 = (reg_t) &((sigframe_rt_t *)xsp)->uc; } if (sig_has_restorer(info, sig)) sc->SC_LR = (reg_t) info->app_sigaction[sig]->restorer; else sc->SC_LR = (reg_t) dynamorio_sigreturn; # ifndef AARCH64 /* We're going to our fcache_return gencode which uses DEFAULT_ISA_MODE */ set_pc_mode_in_cpsr(sc, DEFAULT_ISA_MODE); # endif #endif /* Set our sigreturn context (NOT for the app: we already copied the * translated context to the app stack) to point to fcache_return! * Then we'll go back through kernel, appear in fcache_return, * and go through dispatch & interp, without messing up DR stack. */ transfer_from_sig_handler_to_fcache_return (dcontext, sc, /* Make sure handler is next thing we execute */ (app_pc) SIGACT_PRIMARY_HANDLER(info->app_sigaction[sig]), (linkstub_t *) get_asynch_linkstub()); if ((info->app_sigaction[sig]->flags & SA_ONESHOT) != 0) { /* clear handler now -- can't delete memory since sigreturn, * others may look at sigaction struct, so we just set to default */ info->app_sigaction[sig]->handler = (handler_t) SIG_DFL; } LOG(THREAD, LOG_ASYNCH, 3, "\tset next_tag to handler "PFX", xsp to "PFX"\n", SIGACT_PRIMARY_HANDLER(info->app_sigaction[sig]), xsp); return true; } static bool execute_handler_from_dispatch(dcontext_t *dcontext, int sig) { thread_sig_info_t *info = (thread_sig_info_t *) dcontext->signal_field; byte *xsp = get_sigstack_frame_ptr(dcontext, sig, NULL); sigframe_rt_t *frame = &(info->sigpending[sig]->rt_frame); priv_mcontext_t *mcontext = get_mcontext(dcontext); sigcontext_t *sc; kernel_ucontext_t *uc; kernel_sigset_t blocked; #ifdef CLIENT_INTERFACE dr_signal_action_t action; #else if (info->app_sigaction[sig] == NULL || info->app_sigaction[sig]->handler == (handler_t)SIG_DFL) { LOG(THREAD, LOG_ASYNCH, 3, "\taction is SIG_DFL\n"); execute_default_from_dispatch(dcontext, sig, frame); return true; } ASSERT(info->app_sigaction[sig] != NULL && info->app_sigaction[sig]->handler != (handler_t)SIG_IGN && info->app_sigaction[sig]->handler != (handler_t)SIG_DFL); #endif LOG(THREAD, LOG_ASYNCH, 2, "execute_handler_from_dispatch for signal %d\n", sig); RSTATS_INC(num_signals); /* modify the rtframe before copying to stack so we can pass final * version to client, and propagate its mods */ uc = get_ucontext_from_rt_frame(frame); sc = SIGCXT_FROM_UCXT(uc); /* Because of difficulties determining when/if a signal handler * returns, we do what the kernel does: abandon all of our current * state, copy what we might need to the handler frame if we come back, * and then it's ok if the handler doesn't return. * If it does, we start interpreting afresh when we see sigreturn(). */ #ifdef DEBUG if (stats->loglevel >= 3 && (stats->logmask & LOG_ASYNCH) != 0) { LOG(THREAD, LOG_ASYNCH, 3, "original sigcontext "PFX":\n", sc); dump_sigcontext(dcontext, sc); } #endif if (info->sigpending[sig]->use_sigcontext) { LOG(THREAD, LOG_ASYNCH, 2, "%s: using sigcontext, not mcontext (syscall restart)\n", __FUNCTION__); } else { /* copy currently-interrupted-context to frame's context, so we can * abandon the currently-interrupted context. */ mcontext_to_ucontext(uc, mcontext); } /* Sigreturn needs the target ISA mode to be set in the T bit in cpsr. * Since we came from dispatch, the post-signal target's mode is in dcontext. */ IF_ARM(set_pc_mode_in_cpsr(sc, dr_get_isa_mode(dcontext))); /* mcontext does not contain fp or mmx or xmm state, which may have * changed since the frame was created (while finishing up interrupted * fragment prior to returning to dispatch). Since DR does not touch * this state except for xmm on x64, we go ahead and copy the * current state into the frame, and then touch up xmm for x64. */ /* FIXME: should this be done for all pending as soon as reach * dispatch? what if get two asynch inside same frag prior to exiting * cache? have issues with fpstate, but also prob with next_tag? FIXME */ /* FIXME: we should clear fpstate for app handler itself as that's * how our own handler is executed. */ #if defined(LINUX) && defined(X86) ASSERT(sc->fpstate != NULL); /* not doing i#641 yet */ save_fpstate(dcontext, frame); #endif /* LINUX && X86 */ #ifdef DEBUG if (stats->loglevel >= 3 && (stats->logmask & LOG_ASYNCH) != 0) { LOG(THREAD, LOG_ASYNCH, 3, "new sigcontext "PFX":\n", sc); dump_sigcontext(dcontext, sc); LOG(THREAD, LOG_ASYNCH, 3, "\n"); } #endif /* FIXME: other state? debug regs? * if no syscall allowed between master_ (when frame created) and * receiving, then don't have to worry about debug regs, etc. * check for syscall when record pending, if it exists, try to * receive in pre_system_call or something? what if ignorable? FIXME! */ if (!info->sigpending[sig]->use_sigcontext) { /* for the pc we want the app pc not the cache pc */ sc->SC_XIP = (ptr_uint_t) dcontext->next_tag; LOG(THREAD, LOG_ASYNCH, 3, "\tset frame's eip to "PFX"\n", sc->SC_XIP); } #ifdef CLIENT_INTERFACE action = send_signal_to_client(dcontext, sig, frame, NULL, info->sigpending[sig]->access_address, false/*not blocked*/, NULL); /* in order to pass to the client, we come all the way here for signals * the app has no handler for */ if (action == DR_SIGNAL_REDIRECT) { /* send_signal_to_client copied mcontext into frame's sc */ ucontext_to_mcontext(get_mcontext(dcontext), uc); dcontext->next_tag = canonicalize_pc_target(dcontext, (app_pc) sc->SC_XIP); if (is_building_trace(dcontext)) { LOG(THREAD, LOG_ASYNCH, 3, "\tsquashing trace-in-progress\n"); trace_abort(dcontext); } IF_ARM(dr_set_isa_mode(dcontext, get_pc_mode_from_cpsr(sc), NULL)); return true; /* don't try another signal */ } else if (action == DR_SIGNAL_SUPPRESS || (info->app_sigaction[sig] != NULL && info->app_sigaction[sig]->handler == (handler_t)SIG_IGN)) { LOG(THREAD, LOG_ASYNCH, 2, "%s: not delivering!\n", (action == DR_SIGNAL_SUPPRESS) ? "client suppressing signal" : "app signal handler is SIG_IGN"); return false; } else if (action == DR_SIGNAL_BYPASS || (info->app_sigaction[sig] == NULL || info->app_sigaction[sig]->handler == (handler_t)SIG_DFL)) { LOG(THREAD, LOG_ASYNCH, 2, "%s: executing default action\n", (action == DR_SIGNAL_BYPASS) ? "client forcing default" : "app signal handler is SIG_DFL"); if (info->sigpending[sig]->use_sigcontext) { /* after the default action we want to go to the sigcontext */ dcontext->next_tag = canonicalize_pc_target(dcontext, (app_pc) sc->SC_XIP); ucontext_to_mcontext(get_mcontext(dcontext), uc); IF_ARM(dr_set_isa_mode(dcontext, get_pc_mode_from_cpsr(sc), NULL)); } execute_default_from_dispatch(dcontext, sig, frame); return true; } CLIENT_ASSERT(action == DR_SIGNAL_DELIVER, "invalid signal event return value"); #endif /* now that we've made all our changes and given the client a * chance to make changes, copy the frame to the appropriate stack * location and convert to non-rt if necessary */ copy_frame_to_stack(dcontext, sig, frame, xsp, true/*pending*/); /* now point at the app's frame */ sc = get_sigcontext_from_app_frame(info, sig, (void *) xsp); ASSERT(info->app_sigaction[sig] != NULL); /* add to set of blocked signals those in sigaction mask */ blocked = info->app_sigaction[sig]->mask; /* SA_NOMASK says whether to block sig itself or not */ if ((info->app_sigaction[sig]->flags & SA_NOMASK) == 0) kernel_sigaddset(&blocked, sig); set_blocked(dcontext, &blocked, false/*relative: OR these in*/); /* if we were building a trace, kill it */ if (is_building_trace(dcontext)) { LOG(THREAD, LOG_ASYNCH, 3, "\tsquashing trace-in-progress\n"); trace_abort(dcontext); } /* Doesn't matter what most app registers are, signal handler doesn't * expect anything except the frame on the stack. We do need to set xsp. */ mcontext->xsp = (ptr_uint_t) xsp; /* Set up args to handler: int sig, siginfo_t *siginfo, kernel_ucontext_t *ucxt */ #ifdef X86_64 mcontext->xdi = sig; mcontext->xsi = (reg_t) &((sigframe_rt_t *)xsp)->info; mcontext->xdx = (reg_t) &((sigframe_rt_t *)xsp)->uc; #elif defined(AARCHXX) mcontext->r0 = sig; if (IS_RT_FOR_APP(info, sig)) { mcontext->r1 = (reg_t) &((sigframe_rt_t *)xsp)->info; mcontext->r2 = (reg_t) &((sigframe_rt_t *)xsp)->uc; } if (sig_has_restorer(info, sig)) mcontext->lr = (reg_t) info->app_sigaction[sig]->restorer; else mcontext->lr = (reg_t) dynamorio_sigreturn; #endif #ifdef X86 /* Clear eflags DF (signal handler should match function entry ABI) */ mcontext->xflags &= ~EFLAGS_DF; #endif /* Make sure handler is next thing we execute */ dcontext->next_tag = canonicalize_pc_target (dcontext, (app_pc) SIGACT_PRIMARY_HANDLER(info->app_sigaction[sig])); if ((info->app_sigaction[sig]->flags & SA_ONESHOT) != 0) { /* clear handler now -- can't delete memory since sigreturn, * others may look at sigaction struct, so we just set to default */ info->app_sigaction[sig]->handler = (handler_t) SIG_DFL; } LOG(THREAD, LOG_ASYNCH, 3, "\tset xsp to "PFX"\n", xsp); return true; } /* The arg to SYS_kill, i.e., the signal number, should be in dcontext->sys_param0 */ static void terminate_via_kill(dcontext_t *dcontext) { ASSERT(dcontext == get_thread_private_dcontext()); /* FIXME PR 541760: there can be multiple thread groups and thus * this may not exit all threads in the address space */ cleanup_and_terminate(dcontext, SYS_kill, /* Pass -pid in case main thread has exited * in which case will get -ESRCH */ IF_VMX86(os_in_vmkernel_userworld() ? -(int)get_process_id() :) get_process_id(), dcontext->sys_param0, true, 0, 0); ASSERT_NOT_REACHED(); } bool is_currently_on_sigaltstack(dcontext_t *dcontext) { thread_sig_info_t *info = (thread_sig_info_t *) dcontext->signal_field; byte *cur_esp; GET_STACK_PTR(cur_esp); return (cur_esp >= (byte *)info->sigstack.ss_sp && cur_esp < (byte *)info->sigstack.ss_sp + info->sigstack.ss_size); } static void terminate_via_kill_from_anywhere(dcontext_t *dcontext, int sig) { dcontext->sys_param0 = sig; /* store arg to SYS_kill */ if (is_currently_on_sigaltstack(dcontext)) { /* We can't clean up our sigstack properly when we're on it * (i#1160) so we terminate on the dstack. */ call_switch_stack(dcontext, dcontext->dstack, (void(*)(void*))terminate_via_kill, NULL/*!initstack */, false/*no return */); } else { terminate_via_kill(dcontext); } ASSERT_NOT_REACHED(); } /* xref os_request_fatal_coredump() */ void os_terminate_via_signal(dcontext_t *dcontext, terminate_flags_t flags, int sig) { if (signal_is_interceptable(sig)) { bool set_action = false; #if defined(STATIC_LIBRARY) && defined(LINUX) if (INTERNAL_OPTION(invoke_app_on_crash)) { /* We come here for asserts. Faults already bypass this routine. */ dcontext_t *my_dc = get_thread_private_dcontext(); if (my_dc != NULL) { thread_sig_info_t *info = (thread_sig_info_t *) my_dc->signal_field; if (info != NULL && info->app_sigaction[sig] != NULL && IS_RT_FOR_APP(info, sig)) { set_action = true; sigaction_syscall(sig, info->app_sigaction[sig], NULL); } } } #endif if (!set_action) { DEBUG_DECLARE(bool res =) set_default_signal_action(sig); ASSERT(res); } } if (TEST(TERMINATE_CLEANUP, flags)) { /* we enter from several different places, so rewind until top-level kstat */ KSTOP_REWIND_UNTIL(thread_measured); ASSERT(dcontext != NULL); dcontext->sys_param0 = sig; /* XXX: the comment in the else below implies some systems have SYS_kill * of SIGSEGV w/ no handler on oneself actually return. * cleanup_and_terminate won't return to us and will use global_do_syscall * to invoke SYS_kill, which in debug will do an inf loop (good!) but * in release will do SYS_exit_group -- oh well, the systems I'm testing * on do an immediate exit. */ terminate_via_kill_from_anywhere(dcontext, sig); } else { /* general clean up is unsafe: just remove .1config file */ config_exit(); dynamorio_syscall(SYS_kill, 2, get_process_id(), sig); /* We try both the SYS_kill and the immediate crash since on some platforms * the SIGKILL is delayed and on others the *-1 is hanging(?): should investigate */ if (sig == SIGSEGV) /* make doubly-sure */ *((int *)PTR_UINT_MINUS_1) = 0; while (true) { /* in case signal delivery is delayed we wait...forever */ os_thread_yield(); } } ASSERT_NOT_REACHED(); } static bool execute_default_action(dcontext_t *dcontext, int sig, sigframe_rt_t *frame, sigcontext_t *sc_orig, bool from_dispatch) { thread_sig_info_t *info = (thread_sig_info_t *) dcontext->signal_field; sigcontext_t *sc = get_sigcontext_from_rt_frame(frame); byte *pc = (byte *) sc->SC_XIP; LOG(THREAD, LOG_ASYNCH, 3, "execute_default_action for signal %d\n", sig); /* should only come here for signals we catch, or signal with ONESHOT * that didn't sigreturn */ ASSERT(info->we_intercept[sig] || (info->app_sigaction[sig]->flags & SA_ONESHOT) != 0); if (info->app_sigaction[sig] != NULL && (info->app_sigaction[sig]->flags & SA_ONESHOT) != 0) { if (!info->we_intercept[sig]) { handler_free(dcontext, info->app_sigaction[sig], sizeof(kernel_sigaction_t)); info->app_sigaction[sig] = NULL; } } /* FIXME PR 205310: we can't always perfectly emulate the default * behavior. To execute the default action, we have to un-register our * handler, if we have one, for signals whose default action is not * ignore or that will just be re-raised upon returning to the * interrupted context -- FIXME: are any of the ignores repeated? * SIGURG? * * If called from execute_handler_from_cache(), our master_signal_handler() * is going to return directly to the translated context: which means we * go native to re-execute the instr, which if it does in fact generate * the signal again means we have a nice transparent core dump. * * If called from execute_handler_from_dispatch(), we need to generate * the signal ourselves. */ if (default_action[sig] != DEFAULT_IGNORE) { DEBUG_DECLARE(bool ok =) set_default_signal_action(sig); ASSERT(ok); /* FIXME: to avoid races w/ shared handlers should set a flag to * prevent another thread from re-enabling. * Perhaps worse: what if this signal arrives for another thread * in the meantime (and the default is not terminate)? */ if (info->shared_app_sigaction) { LOG(THREAD, LOG_ASYNCH, 1, "WARNING: having to install SIG_DFL for thread "TIDFMT", but will be shared!\n", get_thread_id()); } if (default_action[sig] == DEFAULT_TERMINATE || default_action[sig] == DEFAULT_TERMINATE_CORE) { report_app_problem(dcontext, APPFAULT_CRASH, pc, (byte *)sc->SC_FP, "\nSignal %d delivered to application as default action.\n", sig); /* App may call sigaction to set handler SIG_DFL (unnecessary but legal), * in which case DR will put a handler in info->app_sigaction[sig]. * We must clear it, otherwise, signal_thread_exit may cleanup the * handler and set it to SIG_IGN instead. */ if (info->app_sigaction[sig] != NULL) { ASSERT(info->we_intercept[sig]); handler_free(dcontext, info->app_sigaction[sig], sizeof(kernel_sigaction_t)); info->app_sigaction[sig] = NULL; } /* N.B.: we don't have to restore our handler because the * default action is for the process (entire thread group for NPTL) to die! */ if (from_dispatch || can_always_delay[sig] || is_sys_kill(dcontext, pc, (byte*)sc->SC_XSP, &frame->info)) { /* This must have come from SYS_kill rather than raised by * a faulting instruction. Thus we can't go re-execute the * instr in order to re-raise the signal (if from_dispatch, * we delayed and can't re-execute anyway). Instead we * re-generate via SYS_kill. An alternative, if we don't * care about generating a core dump, is to use SYS_exit * and pass the right exit code to indicate the signal * number: that would avoid races w/ the sigaction. * * FIXME: should have app make the syscall to get a more * transparent core dump! */ if (!from_dispatch) KSTOP_NOT_MATCHING_NOT_PROPAGATED(fcache_default); KSTOP_NOT_MATCHING_NOT_PROPAGATED(dispatch_num_exits); if (is_couldbelinking(dcontext)) /* won't be for SYS_kill (i#1159) */ enter_nolinking(dcontext, NULL, false); /* we could be on sigstack so call this version: */ terminate_via_kill_from_anywhere(dcontext, sig); ASSERT_NOT_REACHED(); } else { /* We assume that re-executing the interrupted instr will * re-raise the fault. We could easily be wrong: * xref PR 363811 infinite loop due to memory we * thought was unreadable and thus thought would raise * a signal; xref PR 368277 to improve is_sys_kill(). * FIXME PR 205310: we should check whether we come out of * the cache when we expected to terminate! * * An alternative is to abandon transparent core dumps and * do the same explicit SYS_kill we do for from_dispatch. * That would let us clean up DR as well. * FIXME: currently we do not clean up DR for a synchronous * signal death, but we do for asynch. */ /* i#552: cleanup and raise client exit event */ int instr_sz; thread_sig_info_t *info; /* We are on the sigstack now, so assign it to NULL to avoid being * freed during process exit cleanup */ info = (thread_sig_info_t *)dcontext->signal_field; info->sigstack.ss_sp = NULL; /* We enter from several different places, so rewind until * top-level kstat. */ KSTOP_REWIND_UNTIL(thread_measured); /* We try to raise the same signal in app's context so a correct * coredump can be generated. However, the client might change * the code in a way that the corresponding app code won't * raise the signal, so we first check if the app instr is the * same as instr in the cache, and raise the signal (by return). * Otherwise, we kill the process instead. */ ASSERT(sc_orig != NULL); instr_sz = decode_sizeof(dcontext, (byte *) sc_orig->SC_XIP, NULL _IF_X86_64(NULL)); if (instr_sz != 0 && pc != NULL && /* avoid crash on xl8 failure (i#1699) */ instr_sz == decode_sizeof(dcontext, pc, NULL _IF_X86_64(NULL)) && memcmp(pc, (byte *) sc_orig->SC_XIP, instr_sz) == 0) { /* the app instr matches the cache instr; cleanup and raise the * the signal in the app context */ dynamo_process_exit(); /* we cannot re-enter the cache, which is freed by now */ ASSERT(!from_dispatch); return false; } else { /* mismatch, cleanup and terminate */ dcontext->sys_param0 = sig; terminate_via_kill(dcontext); ASSERT_NOT_REACHED(); } } } else { /* FIXME PR 297033: in order to intercept DEFAULT_STOP / * DEFAULT_CONTINUE signals, we need to set sigcontext to point * to some kind of regain-control routine, so that when our * thread gets to run again we can reset our handler. So far * we have no signals that fall here that we intercept. */ CLIENT_ASSERT(false, "STOP/CONT signals not supported"); } #if defined(DEBUG) && defined(INTERNAL) if (sig == SIGSEGV && !dynamo_exited) { /* pc should be an app pc at this point (it was translated) -- * check for bad cases here */ if (safe_is_in_fcache(dcontext, pc, (byte *)sc->SC_XSP)) { fragment_t wrapper; fragment_t *f; LOG(THREAD, LOG_ALL, 1, "Received SIGSEGV at pc "PFX" in thread "TIDFMT"\n", pc, get_thread_id()); f = fragment_pclookup(dcontext, pc, &wrapper); if (f) disassemble_fragment(dcontext, f, false); ASSERT_NOT_REACHED(); } else if (in_generated_routine(dcontext, pc)) { LOG(THREAD, LOG_ALL, 1, "Received SIGSEGV at generated non-code-cache pc "PFX"\n", pc); ASSERT_NOT_REACHED(); } } #endif } /* now continue at the interruption point and re-raise the signal */ return true; } static bool execute_default_from_cache(dcontext_t *dcontext, int sig, sigframe_rt_t *frame, sigcontext_t *sc_orig) { return execute_default_action(dcontext, sig, frame, sc_orig, false); } static void execute_default_from_dispatch(dcontext_t *dcontext, int sig, sigframe_rt_t *frame) { execute_default_action(dcontext, sig, frame, NULL, true); } void receive_pending_signal(dcontext_t *dcontext) { thread_sig_info_t *info = (thread_sig_info_t *) dcontext->signal_field; sigpending_t *temp; int sig; LOG(THREAD, LOG_ASYNCH, 3, "receive_pending_signal\n"); if (info->interrupted != NULL) { /* i#2066: if we were building a trace, it may already be re-linked */ if (!TEST(FRAG_LINKED_OUTGOING, info->interrupted->flags)) { LOG(THREAD, LOG_ASYNCH, 3, "\tre-linking outgoing for interrupted F%d\n", info->interrupted->id); SHARED_FLAGS_RECURSIVE_LOCK(info->interrupted->flags, acquire, change_linking_lock); link_fragment_outgoing(dcontext, info->interrupted, false); SHARED_FLAGS_RECURSIVE_LOCK(info->interrupted->flags, release, change_linking_lock); } if (TEST(FRAG_HAS_SYSCALL, info->interrupted->flags)) { /* restore syscall (they're a barrier to signals, so signal * handler has cur frag exit before it does a syscall) */ if (info->interrupted_pc != NULL) { mangle_syscall_code(dcontext, info->interrupted, info->interrupted_pc, true/*skip exit cti*/); } } info->interrupted = NULL; info->interrupted_pc = NULL; } /* grab first pending signal * XXX: start with real-time ones? */ /* "lock" the array to prevent a new signal that interrupts this bit of * code from prepended or deleting from the array while we're accessing it */ info->accessing_sigpending = true; /* barrier to prevent compiler from moving the above write below the loop */ __asm__ __volatile__("" : : : "memory"); for (sig = 1; sig <= MAX_SIGNUM; sig++) { if (info->sigpending[sig] != NULL) { bool executing = true; /* We do not re-check whether blocked if it was unblocked at * receive time, to properly handle sigsuspend (i#1340). */ if (!info->sigpending[sig]->unblocked && kernel_sigismember(&info->app_sigblocked, sig)) { LOG(THREAD, LOG_ASYNCH, 3, "\tsignal %d is blocked!\n", sig); continue; } LOG(THREAD, LOG_ASYNCH, 3, "\treceiving signal %d\n", sig); executing = execute_handler_from_dispatch(dcontext, sig); temp = info->sigpending[sig]; info->sigpending[sig] = temp->next; special_heap_free(info->sigheap, temp); /* only one signal at a time! */ if (executing) { /* Make negative so our fcache_enter check makes progress but * our C code still considers there to be pending signals. */ dcontext->signals_pending = -1; break; } } } /* barrier to prevent compiler from moving the below write above the loop */ __asm__ __volatile__("" : : : "memory"); info->accessing_sigpending = false; /* we only clear this on a call to us where we find NO pending signals */ if (sig > MAX_SIGNUM) { LOG(THREAD, LOG_ASYNCH, 3, "\tclearing signals_pending flag\n"); dcontext->signals_pending = 0; } } /* Returns false if should NOT issue syscall. */ bool #ifdef LINUX handle_sigreturn(dcontext_t *dcontext, bool rt) #else handle_sigreturn(dcontext_t *dcontext, void *ucxt_param, int style) #endif { thread_sig_info_t *info = (thread_sig_info_t *) dcontext->signal_field; sigcontext_t *sc = NULL; /* initialize to satisfy Mac clang */ int sig = 0; app_pc next_pc; /* xsp was put in mcontext prior to pre_system_call() */ reg_t xsp = get_mcontext(dcontext)->xsp; #ifdef MACOS bool rt = true; #endif LOG(THREAD, LOG_ASYNCH, 3, "%ssigreturn()\n", rt?"rt_":""); LOG(THREAD, LOG_ASYNCH, 3, "\txsp is "PFX"\n", xsp); #ifdef PROGRAM_SHEPHERDING /* if (!sig_has_restorer, region was never added to exec list, * allowed as pattern only and kicked off at first write via * selfmod detection or otherwise if vsyscall, so no worries * about having to remove it here */ #endif /* get sigframe: it's the top thing on the stack, except the ret * popped off pretcode. * WARNING: handler for tcsh's window_change (SIGWINCH) clobbers its * signal # arg, so don't use frame->sig! (kernel doesn't look at sig * so app can get away with it) */ if (rt) { kernel_ucontext_t *ucxt; #ifdef LINUX sigframe_rt_t *frame = (sigframe_rt_t *) (xsp IF_X86(- sizeof(char*))); /* use si_signo instead of sig, less likely to be clobbered by app */ sig = frame->info.si_signo; # ifdef X86_32 LOG(THREAD, LOG_ASYNCH, 3, "\tsignal was %d (did == param %d)\n", sig, frame->sig); if (frame->sig != sig) LOG(THREAD, LOG_ASYNCH, 1, "WARNING: app sig handler clobbered sig param\n"); # endif sc = get_sigcontext_from_app_frame(info, sig, (void *) frame); ucxt = &frame->uc; #elif defined(MACOS) /* The initial frame fields on the stack are messed up due to * params to handler from tramp, so use params to syscall. * XXX: we don't have signal # though: so we have to rely on app * not clobbering the sig param field. */ sig = *(int*)xsp; LOG(THREAD, LOG_ASYNCH, 3, "\tsignal was %d\n", sig); ucxt = (kernel_ucontext_t *) ucxt_param; if (ucxt == NULL) { /* On Mac the kernel seems to store state on whether the process is * on the altstack, so longjmp calls _sigunaltstack() which issues a * sigreturn syscall telling the kernel about the altstack change, * with a NULL context. */ LOG(THREAD, LOG_ASYNCH, 3, "\tsigunalstack sigreturn: no context\n"); return true; } sc = SIGCXT_FROM_UCXT(ucxt); #endif ASSERT(sig > 0 && sig <= MAX_SIGNUM && IS_RT_FOR_APP(info, sig)); /* FIXME: what if handler called sigaction and requested rt * when itself was non-rt? */ /* discard blocked signals, re-set from prev mask stored in frame */ set_blocked(dcontext, SIGMASK_FROM_UCXT(ucxt), true/*absolute*/); } #ifdef LINUX else { /* FIXME: libc's restorer pops prior to calling sigreturn, I have * no idea why, but kernel asks for xsp-8 not xsp-4...weird! */ kernel_sigset_t prevset; sigframe_plain_t *frame = (sigframe_plain_t *) (xsp IF_X86(-8)); /* We don't trust frame->sig (app sometimes clobbers it), and for * plain frame there's no other place that sig is stored, * so as a hack we added a new frame! * FIXME: this means we won't support nonstandard use of SYS_sigreturn, * e.g., as NtContinue, if frame didn't come from a real signal and so * wasn't copied to stack by us. */ sig = frame->sig_noclobber; LOG(THREAD, LOG_ASYNCH, 3, "\tsignal was %d (did == param %d)\n", sig, IF_X86_ELSE(frame->sig, 0)); # ifdef X86_32 if (frame->sig != sig) LOG(THREAD, LOG_ASYNCH, 1, "WARNING: app sig handler clobbered sig param\n"); # endif ASSERT(sig > 0 && sig <= MAX_SIGNUM && !IS_RT_FOR_APP(info, sig)); sc = get_sigcontext_from_app_frame(info, sig, (void *) frame); /* discard blocked signals, re-set from prev mask stored in frame */ # ifdef AARCH64 ASSERT_NOT_IMPLEMENTED(false); /* FIXME i#1569 */ # else prevset.sig[0] = frame->IF_X86_ELSE(sc.oldmask, uc.uc_mcontext.oldmask); if (_NSIG_WORDS > 1) { memcpy(&prevset.sig[1], &frame->IF_X86_ELSE(extramask, uc.sigset_ex), sizeof(prevset.sig[1])); } # endif set_blocked(dcontext, &prevset, true/*absolute*/); } #endif /* LINUX */ /* Make sure we deliver pending signals that are now unblocked. */ check_signals_pending(dcontext, info); /* We abandoned the previous context, so we need to start * interpreting anew. Regardless of whether we handled the signal * from dispatch or the fcache, we want to go to the context * stored in the frame. So we have the kernel send us to * fcache_return and set up for dispatch to use the frame's * context. */ /* if we were building a trace, kill it */ if (is_building_trace(dcontext)) { LOG(THREAD, LOG_ASYNCH, 3, "\tsquashing trace-in-progress\n"); trace_abort(dcontext); } if ((info->app_sigaction[sig]->flags & SA_ONESHOT) != 0) { ASSERT(info->app_sigaction[sig]->handler == (handler_t) SIG_DFL); if (!info->we_intercept[sig]) { /* let kernel do default independent of us */ handler_free(dcontext, info->app_sigaction[sig], sizeof(kernel_sigaction_t)); info->app_sigaction[sig] = NULL; } } ASSERT(!safe_is_in_fcache(dcontext, (app_pc) sc->SC_XIP, (byte *)sc->SC_XSP)); #ifdef DEBUG if (stats->loglevel >= 3 && (stats->logmask & LOG_ASYNCH) != 0) { LOG(THREAD, LOG_ASYNCH, 3, "returning-to sigcontext "PFX":\n", sc); dump_sigcontext(dcontext, sc); } #endif /* XXX i#1206: if we interrupted a non-ignorable syscall to run the app's * handler, and we set up to restart the syscall, we'll come here with the * translated syscall pc -- thus we can't distinguish from a signal interrupting * the prior app instr. So we can't simply point at do_syscall and call * set_at_syscall -- we have to re-interpret the syscall and re-run the * pre-syscall handler. Hopefully all our pre-syscall handlers can handle that. */ /* set up for dispatch */ /* we have to use a different slot since next_tag ends up holding the do_syscall * entry when entered from dispatch (we're called from pre_syscall, prior to entering cache) */ dcontext->asynch_target = canonicalize_pc_target (dcontext, (app_pc)(sc->SC_XIP IF_ARM(|(TEST(EFLAGS_T, sc->SC_XFLAGS) ? 1 : 0)))); next_pc = dcontext->asynch_target; #ifdef VMX86_SERVER /* PR 404712: kernel only restores gp regs so we do it ourselves and avoid * complexities of kernel's non-linux-like sigreturn semantics */ sig_full_cxt_t sc_full = {sc, NULL}; /* non-ARM so NULL ok */ sigcontext_to_mcontext(get_mcontext(dcontext), &sc_full); #else /* HACK to get eax put into mcontext AFTER do_syscall */ dcontext->next_tag = (app_pc) sc->IF_X86_ELSE(SC_XAX, SC_R0); /* use special linkstub so we know why we came out of the cache */ sc->IF_X86_ELSE(SC_XAX, SC_R0) = (ptr_uint_t) get_asynch_linkstub(); /* set our sigreturn context to point to fcache_return */ /* We don't need PC_AS_JMP_TGT b/c the kernel uses EFLAGS_T for the mode */ sc->SC_XIP = (ptr_uint_t) fcache_return_routine(dcontext); /* if we overlaid inner frame on nested signal, will end up with this * error -- disable in release build since this is often app's fault (stack * too small) * FIXME: how make this transparent? what ends up happening is that we * get a segfault when we start interpreting dispatch, we want to make it * look like whatever would happen to the app... */ ASSERT((app_pc)sc->SC_XIP != next_pc); # ifdef AARCHXX set_stolen_reg_val(get_mcontext(dcontext), get_sigcxt_stolen_reg(sc)); set_sigcxt_stolen_reg(sc, (reg_t) *get_dr_tls_base_addr()); # ifdef AARCH64 /* On entry to the do_syscall gencode, we save X1 into TLS_REG1_SLOT. * Then the sigreturn would redirect the flow to the fcache_return gencode. * In fcache_return it recovers the values of x0 and x1 from TLS_SLOT 0 and 1. */ get_mcontext(dcontext)->r1 = sc->regs[1]; # else /* We're going to our fcache_return gencode which uses DEFAULT_ISA_MODE */ set_pc_mode_in_cpsr(sc, DEFAULT_ISA_MODE); # endif # endif #endif LOG(THREAD, LOG_ASYNCH, 3, "set next tag to "PFX", sc->SC_XIP to "PFX"\n", next_pc, sc->SC_XIP); return IF_VMX86_ELSE(false, true); } bool is_signal_restorer_code(byte *pc, size_t *len) { /* is this a sigreturn pattern placed by kernel on the stack or vsyscall page? * for non-rt frame: * 0x58 popl %eax * 0xb8 <sysnum> movl SYS_sigreturn, %eax * 0xcd 0x80 int 0x80 * for rt frame: * 0xb8 <sysnum> movl SYS_rt_sigreturn, %eax * 0xcd 0x80 int 0x80 */ /* optimized we only need two uint reads, but we have to do * some little-endian byte-order reverses to get the right result */ # define reverse(x) ((((x) & 0xff) << 24) | (((x) & 0xff00) << 8) | \ (((x) & 0xff0000) >> 8) | (((x) & 0xff000000) >> 24)) #ifdef MACOS # define SYS_RT_SIGRET SYS_sigreturn #else # define SYS_RT_SIGRET SYS_rt_sigreturn #endif #ifndef X64 /* 58 b8 s4 s3 s2 s1 cd 80 */ static const uint non_rt_1w = reverse(0x58b80000 | (reverse(SYS_sigreturn) >> 16)); static const uint non_rt_2w = reverse((reverse(SYS_sigreturn) << 16) | 0xcd80); #endif /* b8 s4 s3 s2 s1 cd 80 XX */ static const uint rt_1w = reverse(0xb8000000 | (reverse(SYS_RT_SIGRET) >> 8)); static const uint rt_2w = reverse((reverse(SYS_RT_SIGRET) << 24) | 0x00cd8000); /* test rt first as it's the most common * only 7 bytes here so we ignore the last one (becomes msb since little-endian) */ if (*((uint *)pc) == rt_1w && (*((uint *)(pc+4)) & 0x00ffffff) == rt_2w) { if (len != NULL) *len = 7; return true; } #ifndef X64 if (*((uint *)pc) == non_rt_1w && *((uint *)(pc+4)) == non_rt_2w) { if (len != NULL) *len = 8; return true; } #endif return false; } void os_forge_exception(app_pc target_pc, dr_exception_type_t type) { /* PR 205136: * We want to deliver now, and the caller expects us not to return. * We have two alternatives: * 1) Emulate stack frame, and call transfer_to_dispatch() for delivery. We * may not know how to fill out every field of the frame (cr2, etc.). Plus, * we have problems w/ default actions (PR 205310) but we have to solve * those long-term anyway. We also have to create different frames based on * whether app intercepts via rt or not. * 2) Call SYS_tgkill from a special location that our handler can * recognize and know it's a signal meant for the app and that the * interrupted DR can be discarded. We'd then essentially repeat 1, * but modifying the kernel-generated frame. We'd have to always * intercept SIGILL. * I'm going with #1 for now b/c the common case is simpler. */ dcontext_t *dcontext = get_thread_private_dcontext(); #if defined(LINUX) && defined(X86) thread_sig_info_t *info = (thread_sig_info_t *) dcontext->signal_field; #endif char frame_no_xstate[sizeof(sigframe_rt_t)]; sigframe_rt_t *frame = (sigframe_rt_t *) frame_no_xstate; int sig; where_am_i_t cur_whereami = dcontext->whereami; kernel_ucontext_t *uc = get_ucontext_from_rt_frame(frame); sigcontext_t *sc = SIGCXT_FROM_UCXT(uc); switch (type) { case ILLEGAL_INSTRUCTION_EXCEPTION: sig = SIGILL; break; case UNREADABLE_MEMORY_EXECUTION_EXCEPTION: sig = SIGSEGV; break; case IN_PAGE_ERROR_EXCEPTION: /* fall-through: Windows only */ default: ASSERT_NOT_REACHED(); sig = SIGSEGV; break; } LOG(GLOBAL, LOG_ASYNCH, 1, "os_forge_exception sig=%d\n", sig); /* since we always delay delivery, we always want an rt frame. we'll convert * to a plain frame on delivery. */ memset(frame, 0, sizeof(*frame)); frame->info.si_signo = sig; #ifdef X86_32 frame->sig = sig; frame->pinfo = &frame->info; frame->puc = (void *) &frame->uc; #endif #if defined(LINUX) && defined(X86) /* We use a TLS buffer to avoid too much stack space here. */ sc->fpstate = (struct _fpstate *) get_xstate_buffer(dcontext); #endif mcontext_to_ucontext(uc, get_mcontext(dcontext)); sc->SC_XIP = (reg_t) target_pc; /* We'll fill in fpstate at delivery time. * We fill in segment registers to their current values and assume they won't * change and that these are the right values. * * FIXME i#2095: restore the app's segment register value(s). * * XXX: it seems to work w/o filling in the other state: * I'm leaving cr2 and other fields all zero. * If this gets problematic we could switch to approach #2. */ thread_set_segment_registers(sc); #if defined(X86) && defined(LINUX) if (sig_has_restorer(info, sig)) frame->pretcode = (char *) info->app_sigaction[sig]->restorer; else frame->pretcode = (char *) dynamorio_sigreturn; #endif /* We assume that we do not need to translate the context when forged. * If we did, we'd move this below enter_nolinking() (and update * record_pending_signal() to do the translation). */ record_pending_signal(dcontext, sig, &frame->uc, frame, true/*forged*/ _IF_CLIENT(NULL)); /* For most callers this is not necessary and we only do it to match * the Windows usage model: but for forging from our own handler, * this is good b/c it resets us to the base of dstack. */ /* tell dispatch() why we're coming there */ dcontext->whereami = WHERE_TRAMPOLINE; KSTART(dispatch_num_exits); set_last_exit(dcontext, (linkstub_t *) get_asynch_linkstub()); if (is_couldbelinking(dcontext)) enter_nolinking(dcontext, NULL, false); transfer_to_dispatch(dcontext, get_mcontext(dcontext), cur_whereami != WHERE_FCACHE && cur_whereami != WHERE_SIGNAL_HANDLER /*full_DR_state*/); ASSERT_NOT_REACHED(); } void os_request_fatal_coredump(const char *msg) { /* To enable getting a coredump just make sure that rlimits are * not preventing getting one, e.g. ulimit -c unlimited */ SYSLOG_INTERNAL_ERROR("Crashing the process deliberately for a core dump!"); os_terminate_via_signal(NULL, 0/*no cleanup*/, SIGSEGV); ASSERT_NOT_REACHED(); } void os_request_live_coredump(const char *msg) { #ifdef VMX86_SERVER if (os_in_vmkernel_userworld()) { vmk_request_live_coredump(msg); return; } #endif LOG(GLOBAL, LOG_ASYNCH, 1, "LiveCoreDump unsupported (PR 365105). " "Continuing execution without a core.\n"); return; } void os_dump_core(const char *msg) { /* FIXME Case 3408: fork stack dump crashes on 2.6 kernel, so moving the getchar * ahead to aid in debugging */ if (TEST(DUMPCORE_WAIT_FOR_DEBUGGER, dynamo_options.dumpcore_mask)) { SYSLOG_INTERNAL_ERROR("looping so you can use gdb to attach to pid %s", get_application_pid()); IF_CLIENT_INTERFACE(SYSLOG(SYSLOG_CRITICAL, WAITING_FOR_DEBUGGER, 2, get_application_name(), get_application_pid())); /* getchar() can hit our own vsyscall hook (from PR 212570); typically we * want to attach and not continue anyway, so doing an infinite loop: */ while (true) os_thread_yield(); } if (DYNAMO_OPTION(live_dump)) { os_request_live_coredump(msg); } if (TEST(DUMPCORE_INCLUDE_STACKDUMP, dynamo_options.dumpcore_mask)) { /* fork, dump core, then use gdb to get a stack dump * we can get into an infinite loop if there's a seg fault * in the process of doing this -- so we have a do-once test, * and if it failed we do the no-symbols dr callstack dump */ static bool tried_stackdump = false; if (!tried_stackdump) { tried_stackdump = true; stackdump(); } else { static bool tried_calldump = false; if (!tried_calldump) { tried_calldump = true; dump_dr_callstack(STDERR); } } } if (!DYNAMO_OPTION(live_dump)) { os_request_fatal_coredump(msg); ASSERT_NOT_REACHED(); } } #ifdef RETURN_AFTER_CALL bool at_known_exception(dcontext_t *dcontext, app_pc target_pc, app_pc source_fragment) { /* There is a known exception in signal restorers and the Linux dynamic symbol resoulution */ /* The latter we assume it is the only other recurring known exception, so the first time we pattern match to help make sure it is indeed _dl_runtime_resolve (since with LD_BIND_NOW it will never be called). After that we compare with the known value. */ static app_pc known_exception = 0; thread_sig_info_t *info = (thread_sig_info_t *) dcontext->signal_field; LOG(THREAD, LOG_INTERP, 1, "RCT: testing for KNOWN exception "PFX" "PFX"\n", target_pc, source_fragment); /* Check if this is a signal return. FIXME: we should really get that from the frame itself. Since currently grabbing restorer only when copying a frame, this will work with nested signals only if they all have same restorer (I haven't seen restorers other than the one in libc) */ if (target_pc == info->signal_restorer_retaddr) { LOG(THREAD, LOG_INTERP, 1, "RCT: KNOWN exception this is a signal restorer --ok \n"); STATS_INC(ret_after_call_signal_restorer); return true; } if (source_fragment == known_exception) { LOG(THREAD, LOG_INTERP, 1, "RCT: KNOWN exception again _dl_runtime_resolve --ok\n"); return true; } if (known_exception == 0) { int ret_imm; return at_dl_runtime_resolve_ret(dcontext, source_fragment, &ret_imm); } return false; } #endif /* RETURN_AFTER_CALL */ /*************************************************************************** * ITIMERS * * We support combining an app itimer with a DR itimer for each of the 3 types * (PR 204556). */ static inline uint64 timeval_to_usec(struct timeval *t1) { return ((uint64)(t1->tv_sec))*1000000 + t1->tv_usec; } static inline void usec_to_timeval(uint64 usec, struct timeval *t1) { t1->tv_sec = (long) usec / 1000000; t1->tv_usec = (long) usec % 1000000; } static void init_itimer(dcontext_t *dcontext, bool first) { thread_sig_info_t *info = (thread_sig_info_t *) dcontext->signal_field; ASSERT(info != NULL); ASSERT(!info->shared_itimer); /* else inherit */ LOG(THREAD, LOG_ASYNCH, 2, "thread has private itimers%s\n", os_itimers_thread_shared() ? " (for now)" : ""); if (os_itimers_thread_shared()) { /* we have to allocate now even if no itimer is installed until later, * so that all child threads point to the same data */ info->itimer = (thread_itimer_info_t (*)[NUM_ITIMERS]) global_heap_alloc(sizeof(*info->itimer) HEAPACCT(ACCT_OTHER)); } else { /* for simplicity and parallel w/ shared we allocate proactively */ info->itimer = (thread_itimer_info_t (*)[NUM_ITIMERS]) heap_alloc(dcontext, sizeof(*info->itimer) HEAPACCT(ACCT_OTHER)); } memset(info->itimer, 0, sizeof(*info->itimer)); if (first) { /* see if app has set up an itimer before we were loaded */ struct itimerval prev; int rc; int which; for (which = 0; which < NUM_ITIMERS; which++) { rc = getitimer_syscall(which, &prev); ASSERT(rc == SUCCESS); (*info->itimer)[which].app.interval = timeval_to_usec(&prev.it_interval); (*info->itimer)[which].app.value = timeval_to_usec(&prev.it_value); } } } /* Up to caller to hold lock for shared itimers */ static bool set_actual_itimer(dcontext_t *dcontext, int which, thread_sig_info_t *info, bool enable) { struct itimerval val; int rc; ASSERT(info != NULL && info->itimer != NULL); ASSERT(which >= 0 && which < NUM_ITIMERS); if (enable) { ASSERT(!info->shared_itimer || self_owns_recursive_lock(info->shared_itimer_lock)); usec_to_timeval((*info->itimer)[which].actual.interval, &val.it_interval); usec_to_timeval((*info->itimer)[which].actual.value, &val.it_value); LOG(THREAD, LOG_ASYNCH, 2, "installing itimer %d interval="INT64_FORMAT_STRING ", value="INT64_FORMAT_STRING"\n", which, (*info->itimer)[which].actual.interval, (*info->itimer)[which].actual.value); } else { LOG(THREAD, LOG_ASYNCH, 2, "disabling itimer %d\n", which); memset(&val, 0, sizeof(val)); (*info->itimer)[which].actual.value = 0; (*info->itimer)[which].actual.interval = 0; } rc = setitimer_syscall(which, &val, NULL); return (rc == SUCCESS); } /* Caller should hold lock */ bool itimer_new_settings(dcontext_t *dcontext, int which, bool app_changed) { struct itimerval val; bool res = true; int rc; thread_sig_info_t *info = (thread_sig_info_t *) dcontext->signal_field; ASSERT(info != NULL && info->itimer != NULL); ASSERT(which >= 0 && which < NUM_ITIMERS); ASSERT(!info->shared_itimer || self_owns_recursive_lock(info->shared_itimer_lock)); /* the general strategy is to set the actual value to the smaller, * update the larger on each signal, and when the larger becomes * smaller do a one-time swap for the remaining */ if ((*info->itimer)[which].dr.interval > 0 && ((*info->itimer)[which].app.interval == 0 || (*info->itimer)[which].dr.interval < (*info->itimer)[which].app.interval)) (*info->itimer)[which].actual.interval = (*info->itimer)[which].dr.interval; else (*info->itimer)[which].actual.interval = (*info->itimer)[which].app.interval; if ((*info->itimer)[which].actual.value > 0) { if ((*info->itimer)[which].actual.interval == 0 && (*info->itimer)[which].dr.value == 0 && (*info->itimer)[which].app.value == 0) { (*info->itimer)[which].actual.value = 0; res = set_actual_itimer(dcontext, which, info, false/*disabled*/); } else { /* one of app or us has an in-flight timer which we should not interrupt. * but, we already set the new requested value (for app or us), so we * need to update the actual value so we subtract properly. */ rc = getitimer_syscall(which, &val); ASSERT(rc == SUCCESS); uint64 left = timeval_to_usec(&val.it_value); if (!app_changed && (*info->itimer)[which].actual.value == (*info->itimer)[which].app.value) (*info->itimer)[which].app.value = left; if (app_changed && (*info->itimer)[which].actual.value == (*info->itimer)[which].dr.value) (*info->itimer)[which].dr.value = left; (*info->itimer)[which].actual.value = left; } } else { if ((*info->itimer)[which].dr.value > 0 && ((*info->itimer)[which].app.value == 0 || (*info->itimer)[which].dr.value < (*info->itimer)[which].app.value)) (*info->itimer)[which].actual.value = (*info->itimer)[which].dr.value; else { (*info->itimer)[which].actual.value = (*info->itimer)[which].app.value; } res = set_actual_itimer(dcontext, which, info, true/*enable*/); } return res; } bool set_itimer_callback(dcontext_t *dcontext, int which, uint millisec, void (*func)(dcontext_t *, priv_mcontext_t *), void (*func_api)(dcontext_t *, dr_mcontext_t *)) { thread_sig_info_t *info = (thread_sig_info_t *) dcontext->signal_field; bool rc; if (which < 0 || which >= NUM_ITIMERS) { CLIENT_ASSERT(false, "invalid itimer type"); return false; } if (func == NULL && func_api == NULL && millisec != 0) { CLIENT_ASSERT(false, "invalid function"); return false; } ASSERT(info != NULL && info->itimer != NULL); if (info->shared_itimer) acquire_recursive_lock(info->shared_itimer_lock); (*info->itimer)[which].dr.interval = ((uint64)millisec)*1000; (*info->itimer)[which].dr.value = (*info->itimer)[which].dr.interval; (*info->itimer)[which].cb = func; (*info->itimer)[which].cb_api = func_api; rc = itimer_new_settings(dcontext, which, false/*us*/); if (info->shared_itimer) release_recursive_lock(info->shared_itimer_lock); return rc; } uint get_itimer_frequency(dcontext_t *dcontext, int which) { thread_sig_info_t *info = (thread_sig_info_t *) dcontext->signal_field; uint ms = 0; if (which < 0 || which >= NUM_ITIMERS) { CLIENT_ASSERT(false, "invalid itimer type"); return 0; } ASSERT(info != NULL && info->itimer != NULL); if (info->shared_itimer) acquire_recursive_lock(info->shared_itimer_lock); ms = (*info->itimer)[which].dr.interval / 1000; if (info->shared_itimer) release_recursive_lock(info->shared_itimer_lock); return ms; } static bool handle_alarm(dcontext_t *dcontext, int sig, kernel_ucontext_t *ucxt) { thread_sig_info_t *info = (thread_sig_info_t *) dcontext->signal_field; ASSERT(info != NULL && info->itimer != NULL); int which = 0; bool invoke_cb = false, pass_to_app = false, reset_timer_manually = false; bool should_release_lock = false; /* i#471: suppress alarms coming in after exit */ if (dynamo_exited) return pass_to_app; if (sig == SIGALRM) which = ITIMER_REAL; else if (sig == SIGVTALRM) which = ITIMER_VIRTUAL; else if (sig == SIGPROF) which = ITIMER_PROF; else ASSERT_NOT_REACHED(); LOG(THREAD, LOG_ASYNCH, 2, "received alarm %d @"PFX"\n", which, SIGCXT_FROM_UCXT(ucxt)->SC_XIP); /* This alarm could have interrupted an app thread making an itimer syscall */ if (info->shared_itimer) { #ifdef DEADLOCK_AVOIDANCE /* i#2061: in debug build we can get an alarm while in deadlock handling * code that holds innermost_lock. We just drop such alarms. */ if (OWN_MUTEX(&innermost_lock)) return pass_to_app; #endif if (self_owns_recursive_lock(info->shared_itimer_lock)) { /* What can we do? We just go ahead and hope conflicting writes work out. * We don't re-acquire in case app was in middle of acquiring. */ } else if (try_recursive_lock(info->shared_itimer_lock) || try_recursive_lock(info->shared_itimer_lock)) { should_release_lock = true; } else { /* Heuristic: if fail twice then assume interrupted lock routine. * What can we do? Just continue and hope conflicting writes work out. */ } } if ((*info->itimer)[which].app.value > 0) { /* Alarm could have been on its way when app value changed */ if ((*info->itimer)[which].app.value >= (*info->itimer)[which].actual.value) { (*info->itimer)[which].app.value -= (*info->itimer)[which].actual.value; LOG(THREAD, LOG_ASYNCH, 2, "\tapp value is now %d\n", (*info->itimer)[which].app.value); if ((*info->itimer)[which].app.value == 0) { pass_to_app = true; (*info->itimer)[which].app.value = (*info->itimer)[which].app.interval; } else reset_timer_manually = true; } } if ((*info->itimer)[which].dr.value > 0) { /* Alarm could have been on its way when DR value changed */ if ((*info->itimer)[which].dr.value >= (*info->itimer)[which].actual.value) { (*info->itimer)[which].dr.value -= (*info->itimer)[which].actual.value; LOG(THREAD, LOG_ASYNCH, 2, "\tdr value is now %d\n", (*info->itimer)[which].dr.value); if ((*info->itimer)[which].dr.value == 0) { invoke_cb = true; (*info->itimer)[which].dr.value = (*info->itimer)[which].dr.interval; } else reset_timer_manually = true; } } /* for efficiency we let the kernel reset the value to interval if * there's only one timer */ if (reset_timer_manually) { (*info->itimer)[which].actual.value = 0; itimer_new_settings(dcontext, which, true/*doesn't matter: actual.value==0*/); } else (*info->itimer)[which].actual.value = (*info->itimer)[which].actual.interval; if (invoke_cb) { /* invoke after setting new itimer value */ /* we save stack space by allocating superset dr_mcontext_t */ dr_mcontext_t dmc; dr_mcontext_init(&dmc); void (*cb)(dcontext_t *, priv_mcontext_t *) = (*info->itimer)[which].cb; void (*cb_api)(dcontext_t *, dr_mcontext_t *) = (*info->itimer)[which].cb_api; if (which == ITIMER_VIRTUAL && info->shared_itimer && should_release_lock) { release_recursive_lock(info->shared_itimer_lock); should_release_lock = false; } if (cb != NULL) { priv_mcontext_t *mc = dr_mcontext_as_priv_mcontext(&dmc); ucontext_to_mcontext(mc, ucxt); cb(dcontext, mc); } else { cb_api(dcontext, &dmc); } } if (info->shared_itimer && should_release_lock) release_recursive_lock(info->shared_itimer_lock); return pass_to_app; } /* Starts itimer if stopped, or increases refcount of existing itimer if already * started. It is *not* safe to call this more than once for the same thread, * since it will inflate the refcount and prevent cleanup. */ void start_itimer(dcontext_t *dcontext) { thread_sig_info_t *info = (thread_sig_info_t *) dcontext->signal_field; ASSERT(info != NULL && info->itimer != NULL); bool start = false; if (info->shared_itimer) { acquire_recursive_lock(info->shared_itimer_lock); (*info->shared_itimer_underDR)++; start = (*info->shared_itimer_underDR == 1); } else start = true; if (start) { /* Enable all DR itimers b/c at least one thread in this set of threads * sharing itimers is under DR control */ int which; LOG(THREAD, LOG_ASYNCH, 2, "starting DR itimers from thread "TIDFMT"\n", get_thread_id()); for (which = 0; which < NUM_ITIMERS; which++) { /* May have already been started if there was no stop_itimer() since * init time */ if ((*info->itimer)[which].dr.value == 0 && (*info->itimer)[which].dr.interval > 0) { (*info->itimer)[which].dr.value = (*info->itimer)[which].dr.interval; itimer_new_settings(dcontext, which, false/*!app*/); } } } if (info->shared_itimer) release_recursive_lock(info->shared_itimer_lock); } /* Decrements the itimer refcount, and turns off the itimer once there are no * more threads listening for it. It is not safe to call this more than once on * the same thread. */ void stop_itimer(dcontext_t *dcontext) { thread_sig_info_t *info = (thread_sig_info_t *) dcontext->signal_field; ASSERT(info != NULL && info->itimer != NULL); bool stop = false; if (info->shared_itimer) { acquire_recursive_lock(info->shared_itimer_lock); ASSERT(*info->shared_itimer_underDR > 0); (*info->shared_itimer_underDR)--; stop = (*info->shared_itimer_underDR == 0); } else stop = true; if (stop) { /* Disable all DR itimers b/c this set of threads sharing this * itimer is now completely native */ int which; LOG(THREAD, LOG_ASYNCH, 2, "stopping DR itimers from thread "TIDFMT"\n", get_thread_id()); for (which = 0; which < NUM_ITIMERS; which++) { if ((*info->itimer)[which].dr.value > 0) { (*info->itimer)[which].dr.value = 0; if ((*info->itimer)[which].app.value > 0) { (*info->itimer)[which].actual.interval = (*info->itimer)[which].app.interval; } else set_actual_itimer(dcontext, which, info, false/*disable*/); } } } if (info->shared_itimer) release_recursive_lock(info->shared_itimer_lock); } /* handle app itimer syscalls */ /* handle_pre_alarm also calls this function and passes NULL as prev_timer */ void handle_pre_setitimer(dcontext_t *dcontext, int which, const struct itimerval *new_timer, struct itimerval *prev_timer) { if (new_timer == NULL || which < 0 || which >= NUM_ITIMERS) return; thread_sig_info_t *info = (thread_sig_info_t *) dcontext->signal_field; ASSERT(info != NULL && info->itimer != NULL); struct itimerval val; if (safe_read(new_timer, sizeof(val), &val)) { if (info->shared_itimer) acquire_recursive_lock(info->shared_itimer_lock); /* save a copy in case the syscall fails */ (*info->itimer)[which].app_saved = (*info->itimer)[which].app; (*info->itimer)[which].app.interval = timeval_to_usec(&val.it_interval); (*info->itimer)[which].app.value = timeval_to_usec(&val.it_value); LOG(THREAD, LOG_ASYNCH, 2, "app setitimer type=%d interval="SZFMT" value="SZFMT"\n", which, (*info->itimer)[which].app.interval, (*info->itimer)[which].app.value); itimer_new_settings(dcontext, which, true/*app*/); if (info->shared_itimer) release_recursive_lock(info->shared_itimer_lock); } } void handle_post_setitimer(dcontext_t *dcontext, bool success, int which, const struct itimerval *new_timer, struct itimerval *prev_timer) { if (new_timer == NULL || which < 0 || which >= NUM_ITIMERS) { ASSERT(new_timer == NULL || !success); return; } thread_sig_info_t *info = (thread_sig_info_t *) dcontext->signal_field; ASSERT(info != NULL && info->itimer != NULL); ASSERT(which >= 0 && which < NUM_ITIMERS); if (!success && new_timer != NULL) { if (info->shared_itimer) acquire_recursive_lock(info->shared_itimer_lock); /* restore saved pre-syscall settings */ (*info->itimer)[which].app = (*info->itimer)[which].app_saved; itimer_new_settings(dcontext, which, true/*app*/); if (info->shared_itimer) release_recursive_lock(info->shared_itimer_lock); } if (success && prev_timer != NULL) handle_post_getitimer(dcontext, success, which, prev_timer); } void handle_post_getitimer(dcontext_t *dcontext, bool success, int which, struct itimerval *cur_timer) { thread_sig_info_t *info = (thread_sig_info_t *) dcontext->signal_field; ASSERT(info != NULL && info->itimer != NULL); if (success) { /* write succeeded for kernel but we're user and can have races */ struct timeval val; DEBUG_DECLARE(bool ok;) ASSERT(which >= 0 && which < NUM_ITIMERS); ASSERT(cur_timer != NULL); if (info->shared_itimer) acquire_recursive_lock(info->shared_itimer_lock); usec_to_timeval((*info->itimer)[which].app.interval, &val); IF_DEBUG(ok = ) safe_write_ex(&cur_timer->it_interval, sizeof(val), &val, NULL); ASSERT(ok); if (safe_read(&cur_timer->it_value, sizeof(val), &val)) { /* subtract the difference between last-asked-for value * and current value to reflect elapsed time */ uint64 left = (*info->itimer)[which].app.value - ((*info->itimer)[which].actual.value - timeval_to_usec(&val)); usec_to_timeval(left, &val); IF_DEBUG(ok = ) safe_write_ex(&cur_timer->it_value, sizeof(val), &val, NULL); ASSERT(ok); } else ASSERT_NOT_REACHED(); if (info->shared_itimer) release_recursive_lock(info->shared_itimer_lock); } } /* handle app alarm syscall */ /* alarm uses the same itimer and could be defined in terms of setitimer */ void handle_pre_alarm(dcontext_t *dcontext, unsigned int sec) { struct itimerval val; val.it_interval.tv_usec = 0; val.it_interval.tv_sec = 0; val.it_value.tv_usec = 0; val.it_value.tv_sec = sec; handle_pre_setitimer(dcontext, ITIMER_REAL, &val, NULL); } void handle_post_alarm(dcontext_t *dcontext, bool success, unsigned int sec) { /* alarm is always successful, so do nothing in post */ ASSERT(success); return; } /*************************************************************************** * Internal DR communication */ typedef struct _sig_detach_info_t { KSYNCH_TYPE *detached; byte *sigframe_xsp; #ifdef HAVE_SIGALTSTACK stack_t *app_sigstack; #endif } sig_detach_info_t; /* xsp is only set for X86 */ static void notify_and_jmp_without_stack(KSYNCH_TYPE *notify_var, byte *continuation, byte *xsp) { if (ksynch_kernel_support()) { /* Can't use dstack once we signal so in asm we do: * futex/semaphore = 1; * %xsp = xsp; * dynamorio_condvar_wake_and_jmp(notify_var, continuation); */ #ifdef MACOS ASSERT(sizeof(notify_var->sem) == 4); #endif #ifdef X86 asm("mov %0, %%"ASM_XAX : : "m"(notify_var)); asm("mov %0, %%"ASM_XCX : : "m"(continuation)); asm("mov %0, %%"ASM_XSP : : "m"(xsp)); # ifdef MACOS asm("movl $1,4(%"ASM_XAX")"); asm("jmp _dynamorio_condvar_wake_and_jmp"); # else asm("movl $1,(%"ASM_XAX")"); asm("jmp dynamorio_condvar_wake_and_jmp"); # endif #elif defined(AARCHXX) asm("ldr "ASM_R0", %0" : : "m"(notify_var)); asm("mov "ASM_R1", #1"); asm("str "ASM_R1",["ASM_R0"]"); asm("ldr "ASM_R1", %0" : : "m"(continuation)); asm("b dynamorio_condvar_wake_and_jmp"); #endif } else { ksynch_set_value(notify_var, 1); #ifdef X86 asm("mov %0, %%"ASM_XSP : : "m"(xsp)); asm("mov %0, %%"ASM_XAX : : "m"(continuation)); asm("jmp *%"ASM_XAX); #elif defined(AARCHXX) asm("ldr "ASM_R0", %0" : : "m"(continuation)); asm(ASM_INDJMP" "ASM_R0); #endif /* X86/ARM */ } } /* Go native from detach. This is executed on the app stack. */ static void sig_detach_go_native(sig_detach_info_t *info) { byte *xsp = info->sigframe_xsp; #ifdef HAVE_SIGALTSTACK /* Restore the app signal stack. */ DEBUG_DECLARE(int rc =) sigaltstack_syscall(info->app_sigstack, NULL); ASSERT(rc == 0); #endif #ifdef X86 /* Skip pretcode */ xsp += sizeof(char *); #endif notify_and_jmp_without_stack(info->detached, (byte *)dynamorio_sigreturn, xsp); ASSERT_NOT_REACHED(); } /* Sets this (slave) thread to detach by directly returning from the signal. */ static void sig_detach(dcontext_t *dcontext, sigframe_rt_t *frame, KSYNCH_TYPE *detached) { thread_sig_info_t *info = (thread_sig_info_t *)dcontext->signal_field; byte *xsp; sig_detach_info_t detach_info; LOG(THREAD, LOG_ASYNCH, 1, "%s: detaching\n", __FUNCTION__); /* Update the mask of the signal frame so that the later sigreturn will * restore the app signal mask. */ memcpy(&frame->uc.uc_sigmask, &info->app_sigblocked, sizeof(info->app_sigblocked)); /* Copy the signal frame to the app stack. * XXX: We live with the transparency risk of storing the signal frame on * the app stack: we assume the app stack is writable where we need it to be, * and that we're not clobbering any app data beyond TOS. */ xsp = get_sigstack_frame_ptr(dcontext, SUSPEND_SIGNAL, frame); copy_frame_to_stack(dcontext, SUSPEND_SIGNAL, frame, xsp, false/*!pending*/); #ifdef HAVE_SIGALTSTACK /* Make sure the frame's sigstack reflects the app stack. */ frame = (sigframe_rt_t *) xsp; frame->uc.uc_stack = info->app_sigstack; #endif /* Restore app segment registers. */ os_thread_not_under_dynamo(dcontext); os_tls_thread_exit(dcontext->local_state); #ifdef HAVE_SIGALTSTACK /* We can't restore the app's sigstack here as that will invalidate the * sigstack we're currently on. */ detach_info.app_sigstack = &info->app_sigstack; #endif detach_info.detached = detached; detach_info.sigframe_xsp = xsp; call_switch_stack(&detach_info, xsp, (void(*)(void*))sig_detach_go_native, false/*free_initstack*/, false/*do not return*/); ASSERT_NOT_REACHED(); } /* Returns whether to pass on to app */ static bool handle_suspend_signal(dcontext_t *dcontext, kernel_ucontext_t *ucxt, sigframe_rt_t *frame) { os_thread_data_t *ostd = (os_thread_data_t *) dcontext->os_field; kernel_sigset_t prevmask; sig_full_cxt_t sc_full; ASSERT(ostd != NULL); if (ostd->terminate) { /* PR 297902: exit this thread, without using the dstack */ /* For MacOS, we need a stack as 32-bit syscalls take args on the stack. * We go ahead and use it for x86 too for simpler sysenter return. * We don't have a lot of options: we're terminating, so we go ahead * and use the app stack. */ byte *app_xsp; if (IS_CLIENT_THREAD(dcontext)) app_xsp = (byte *) SIGCXT_FROM_UCXT(ucxt)->SC_XSP; else app_xsp = (byte *) get_mcontext(dcontext)->xsp; LOG(THREAD, LOG_ASYNCH, 2, "handle_suspend_signal: exiting\n"); ASSERT(app_xsp != NULL); notify_and_jmp_without_stack(&ostd->terminated, (byte*)dynamorio_sys_exit, app_xsp); ASSERT_NOT_REACHED(); return false; } if (!doing_detach && is_thread_currently_native(dcontext->thread_record) && !IS_CLIENT_THREAD(dcontext) IF_APP_EXPORTS(&& !dr_api_exit)) { sig_take_over(ucxt); /* no return */ ASSERT_NOT_REACHED(); } /* If suspend_count is 0, we are not trying to suspend this thread * (os_thread_resume() may have already decremented suspend_count to 0, but * os_thread_suspend() will not send a signal until this thread unsets * ostd->suspended, so not having a lock around the suspend_count read is * ok), so pass signal to app. * If we are trying or have already suspended this thread, our own * os_thread_suspend() will not send a 2nd suspend signal until we are * completely resumed, so we can distinguish app uses of SUSPEND_SIGNAL. We * can't have a race between the read and write of suspended_sigcxt b/c * signals are blocked. It's fine to have a race and reorder the app's * signal w/ DR's. */ if (ostd->suspend_count == 0 || ostd->suspended_sigcxt != NULL) return true; /* pass to app */ sig_full_initialize(&sc_full, ucxt); ostd->suspended_sigcxt = &sc_full; /* We're sitting on our sigaltstack w/ all signals blocked. We're * going to stay here but unblock all signals so we don't lose any * delivered while we're waiting. We're at a safe enough point to * re-enter master_signal_handler(). We use a mutex in * thread_{suspend,resume} to prevent our own re-suspension signal * from arriving before we've re-blocked on the resume. */ sigprocmask_syscall(SIG_SETMASK, SIGMASK_FROM_UCXT(ucxt), &prevmask, sizeof(ucxt->uc_sigmask)); LOG(THREAD, LOG_ASYNCH, 2, "handle_suspend_signal: suspended now\n"); /* We cannot use mutexes here as we have interrupted DR at an * arbitrary point! Thus we can't use the event_t routines. * However, the existing synch and check above prevent any * re-entrance here, and our cond vars target just a single thread, * so we can get away w/o a mutex. */ /* Notify os_thread_suspend that it can now return, as this thread is * officially suspended now and is ready for thread_{get,set}_mcontext. */ ASSERT(ksynch_get_value(&ostd->suspended) == 0); ksynch_set_value(&ostd->suspended, 1); ksynch_wake_all(&ostd->suspended); /* i#96/PR 295561: use futex(2) if available */ while (ksynch_get_value(&ostd->wakeup) == 0) { /* Waits only if the wakeup flag is not set as 1. Return value * doesn't matter because the flag will be re-checked. */ ksynch_wait(&ostd->wakeup, 0); if (ksynch_get_value(&ostd->wakeup) == 0) { /* If it still has to wait, give up the cpu. */ os_thread_yield(); } } LOG(THREAD, LOG_ASYNCH, 2, "handle_suspend_signal: awake now\n"); /* re-block so our exit from master_signal_handler is not interrupted */ sigprocmask_syscall(SIG_SETMASK, &prevmask, NULL, sizeof(prevmask)); ostd->suspended_sigcxt = NULL; /* Notify os_thread_resume that it can return now, which (assuming * suspend_count is back to 0) means it's then safe to re-suspend. */ ksynch_set_value(&ostd->suspended, 0); /*reset prior to signalling os_thread_resume*/ ksynch_set_value(&ostd->resumed, 1); ksynch_wake_all(&ostd->resumed); if (ostd->retakeover) { ostd->retakeover = false; sig_take_over(ucxt); /* no return */ ASSERT_NOT_REACHED(); } else if (ostd->do_detach) { ostd->do_detach = false; sig_detach(dcontext, frame, &ostd->detached); /* no return */ ASSERT_NOT_REACHED(); } return false; /* do not pass to app */ } /* PR 206278: for try/except we need to save the signal mask */ void dr_setjmp_sigmask(dr_jmp_buf_t *buf) { /* i#226/PR 492568: we rely on the kernel storing the prior mask in the * signal frame, so we do not need to store it on every setjmp, which * can be a performance hit. */ #ifdef DEBUG sigprocmask_syscall(SIG_SETMASK, NULL, &buf->sigmask, sizeof(buf->sigmask)); #endif } /* i#61/PR 211530: nudge on Linux. * Determines whether this is a nudge signal, and if so queues up a nudge, * or is an app signal. Returns whether to pass the signal on to the app. */ static bool handle_nudge_signal(dcontext_t *dcontext, siginfo_t *siginfo, kernel_ucontext_t *ucxt) { sigcontext_t *sc = SIGCXT_FROM_UCXT(ucxt); nudge_arg_t *arg = (nudge_arg_t *) siginfo; instr_t instr; char buf[MAX_INSTR_LENGTH]; /* Distinguish a nudge from an app signal. An app using libc sigqueue() * will never have its signal mistaken as libc does not expose the siginfo_t * and always passes 0 for si_errno, so we're only worried beyond our * si_code check about an app using a raw syscall that is deliberately * trying to fool us. * While there is a lot of padding space in siginfo_t, the kernel doesn't * copy it through on SYS_rt_sigqueueinfo so we don't have room for any * dedicated magic numbers. The client id could function as a magic * number for client nudges, but I don't think we want to kill the app * if an external nudger types the client id wrong. */ LOG(THREAD, LOG_ASYNCH, 2, "%s: sig=%d code=%d errno=%d\n", __FUNCTION__, siginfo->si_signo, siginfo->si_code, siginfo->si_errno); if (siginfo->si_signo != NUDGESIG_SIGNUM /* PR 477454: remove the IF_NOT_VMX86 once we have nudge-arg support */ IF_NOT_VMX86(|| siginfo->si_code != SI_QUEUE || siginfo->si_errno == 0)) { return true; /* pass to app */ } #if defined(CLIENT_INTERFACE) && !defined(VMX86_SERVER) DODEBUG({ if (TEST(NUDGE_GENERIC(client), arg->nudge_action_mask) && !is_valid_client_id(arg->client_id)) { SYSLOG_INTERNAL_WARNING("received client nudge for invalid id=0x%x", arg->client_id); } }); #endif if (dynamo_exited || !dynamo_initialized || dcontext == NULL) { /* Ignore the nudge: too early, or too late. * Xref Windows handling of such cases in nudge.c: old case 5702, etc. * We do this before the illegal-instr check b/c it's unsafe to decode * if too early or too late. */ SYSLOG_INTERNAL_WARNING("too-early or too-late nudge: ignoring"); return false; /* do not pass to app */ } /* As a further check, try to detect whether this was raised synchronously * from a real illegal instr: though si_code for that should not be * SI_QUEUE. It's possible a nudge happened to come at a bad instr before * it faulted, or maybe the instr after a syscall or other wait spot is * illegal, but we'll live with that risk. */ ASSERT(NUDGESIG_SIGNUM == SIGILL); /* else this check makes no sense */ instr_init(dcontext, &instr); if (safe_read((byte *)sc->SC_XIP, sizeof(buf), buf) && (decode(dcontext, (byte *)buf, &instr) == NULL || /* check for ud2 (xref PR 523161) */ instr_is_undefined(&instr))) { LOG(THREAD, LOG_ASYNCH, 2, "%s: real illegal instr @"PFX"\n", __FUNCTION__, sc->SC_XIP); DOLOG(2, LOG_ASYNCH, { disassemble_with_bytes(dcontext, (byte *)sc->SC_XIP, THREAD); }); instr_free(dcontext, &instr); return true; /* pass to app */ } instr_free(dcontext, &instr); #ifdef VMX86_SERVER /* Treat as a client nudge until we have PR 477454 */ if (siginfo->si_errno == 0) { arg->version = NUDGE_ARG_CURRENT_VERSION; arg->flags = 0; arg->nudge_action_mask = NUDGE_GENERIC(client); arg->client_id = 0; arg->client_arg = 0; } #endif LOG(THREAD, LOG_ASYNCH, 1, "received nudge version=%u flags=0x%x mask=0x%x id=0x%08x arg=0x" ZHEX64_FORMAT_STRING"\n", arg->version, arg->flags, arg->nudge_action_mask, arg->client_id, arg->client_arg); SYSLOG_INTERNAL_INFO("received nudge mask=0x%x id=0x%08x arg=0x"ZHEX64_FORMAT_STRING, arg->nudge_action_mask, arg->client_id, arg->client_arg); /* We need to handle the nudge at a safe, nolinking spot */ if (safe_is_in_fcache(dcontext, (byte *)sc->SC_XIP, (byte*)sc->SC_XSP) && dcontext->interrupted_for_nudge == NULL) { /* We unlink the interrupted fragment and skip any inlined syscalls to * bound the nudge delivery time. If we already unlinked one we assume * that's sufficient. */ fragment_t wrapper; fragment_t *f = fragment_pclookup(dcontext, (byte *)sc->SC_XIP, &wrapper); if (f != NULL) { if (unlink_fragment_for_signal(dcontext, f, (byte *)sc->SC_XIP)) dcontext->interrupted_for_nudge = f; } } /* No lock is needed since thread-private and this signal is blocked now */ nudge_add_pending(dcontext, arg); return false; /* do not pass to app */ }
1
11,037
Convention is "FIXME: i#2144" or "XXX: i#2144"
DynamoRIO-dynamorio
c
@@ -0,0 +1,7 @@ +namespace Datadog.Trace.ClrProfiler.Interfaces +{ + internal interface IHasHttpMethod + { + string GetHttpMethod(); + } +}
1
1
14,659
This should probably be a property instead of a method.
DataDog-dd-trace-dotnet
.cs
@@ -159,10 +159,12 @@ spec: status: phase: Init versionDetails: - current: {{ .CAST.version }} + status: + current: {{ .CAST.version }} + dependentsUpgraded: true + state: RECONCILED desired: {{ .CAST.version }} autoUpgrade: false - dependentsUpgraded: true --- apiVersion: openebs.io/v1alpha1 kind: RunTask
1
/* Copyright 2018 The OpenEBS Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // TODO // Rename this file by removing the version suffix information package v1alpha1 const cstorPoolYamls = ` --- apiVersion: openebs.io/v1alpha1 kind: CASTemplate metadata: name: cstor-pool-create-default spec: defaultConfig: # CstorPoolImage is the container image that executes zpool replication and # communicates with cstor iscsi target - name: CstorPoolImage value: {{env "OPENEBS_IO_CSTOR_POOL_IMAGE" | default "openebs/cstor-pool:latest"}} # CstorPoolExporterImage is the container image that executes zpool and zfs binary # to export various volume and pool metrics - name: CstorPoolExporterImage value: {{env "OPENEBS_IO_CSTOR_POOL_EXPORTER_IMAGE" | default "openebs/m-exporter:latest"}} # CstorPoolMgmtImage runs cstor pool and cstor volume replica related CRUD # operations - name: CstorPoolMgmtImage value: {{env "OPENEBS_IO_CSTOR_POOL_MGMT_IMAGE" | default "openebs/cstor-pool-mgmt:latest"}} # HostPathType is a hostPath volume i.e. mounts a file or directory from the # host node’s filesystem into a Pod. 'DirectoryOrCreate' value ensures # nothing exists at the given path i.e. an empty directory will be created. - name: HostPathType value: DirectoryOrCreate # SparseDir is a hostPath directory where to look for sparse files - name: SparseDir value: {{env "OPENEBS_IO_CSTOR_POOL_SPARSE_DIR" | default "/var/openebs/sparse"}} # RunNamespace is the namespace where namespaced resources related to pool # will be placed - name: RunNamespace value: {{env "OPENEBS_NAMESPACE"}} # ServiceAccountName is the account name assigned to pool management pod # with permissions to view, create, edit, delete required custom resources - name: ServiceAccountName value: {{env "OPENEBS_SERVICE_ACCOUNT"}} # PoolResourceRequests allow you to specify resource requests that need to be available # before scheduling the containers. If not specified, the default is to use the limits # from PoolResourceLimits or the default requests set in the cluster. - name: PoolResourceRequests value: "none" # PoolResourceLimits allow you to set the limits on memory and cpu for pool pods # The resource and limit value should be in the same format as expected by # Kubernetes. Example: #- name: PoolResourceLimits # value: |- # memory: 1Gi - name: PoolResourceLimits value: "none" # AuxResourceRequests allow you to set requests on side cars. Requests have to be specified # in the format expected by Kubernetes - name: AuxResourceRequests value: "none" # AuxResourceLimits allow you to set limits on side cars. Limits have to be specified # in the format expected by Kubernetes - name: AuxResourceLimits value: "none" # ResyncInterval specifies duration after which a controller should # resync the resource status - name: ResyncInterval value: "30" # Toleration allows you to set tolerations for the cstor pool deployments # against the nodes which has been tainted - name: Tolerations value: "none" taskNamespace: {{env "OPENEBS_NAMESPACE"}} run: tasks: # Following are the list of run tasks executed in this order to # create a cstor storage pool - cstor-pool-create-getspc-default - cstor-pool-create-putcstorpoolcr-default - cstor-pool-create-putcstorpooldeployment-default - cstor-pool-create-patchstoragepoolclaim-default --- # This run task get StoragePoolClaim apiVersion: openebs.io/v1alpha1 kind: RunTask metadata: name: cstor-pool-create-getspc-default spec: meta: | id: getspc apiVersion: openebs.io/v1alpha1 kind: StoragePoolClaim action: get objectName: {{.Storagepool.owner}} post: | {{- jsonpath .JsonResult "{.metadata.uid}" | trim | addTo "getspc.objectUID" .TaskResult | noop -}} --- apiVersion: openebs.io/v1alpha1 kind: RunTask metadata: name: cstor-pool-create-putcstorpoolcr-default spec: meta: | apiVersion: openebs.io/v1alpha1 kind: CStorPool action: put id: putcstorpoolcr post: | {{- jsonpath .JsonResult "{.metadata.name}" | trim | addTo "putcstorpoolcr.objectName" .TaskResult | noop -}} {{- jsonpath .JsonResult "{.metadata.uid}" | trim | addTo "putcstorpoolcr.objectUID" .TaskResult | noop -}} {{- jsonpath .JsonResult "{.metadata.labels.kubernetes\\.io/hostname}" | trim | addTo "putcstorpoolcr.nodeName" .TaskResult | noop -}} task: |- {{- $blockDeviceIdList:= toYaml .Storagepool | fromYaml -}} apiVersion: openebs.io/v1alpha1 kind: CStorPool metadata: name: {{$blockDeviceIdList.owner}}-{{randAlphaNum 4 |lower }} labels: openebs.io/storage-pool-claim: {{$blockDeviceIdList.owner}} kubernetes.io/hostname: {{$blockDeviceIdList.nodeName}} openebs.io/version: {{ .CAST.version }} openebs.io/cas-template-name: {{ .CAST.castName }} openebs.io/cas-type: cstor ownerReferences: - apiVersion: openebs.io/v1alpha1 blockOwnerDeletion: true controller: true kind: StoragePoolClaim name: {{$blockDeviceIdList.owner}} uid: {{ .TaskResult.getspc.objectUID }} spec: group: {{- range $k, $v := $blockDeviceIdList.blockDeviceList }} - blockDevice: {{- range $ki, $blockDevice := $v.blockDevice }} - name: {{$blockDevice.name}} inUseByPool: true deviceID: {{$blockDevice.deviceID}} {{- end }} {{- end }} poolSpec: poolType: {{$blockDeviceIdList.poolType}} cacheFile: {{$blockDeviceIdList.poolCacheFile}} overProvisioning: false status: phase: Init versionDetails: current: {{ .CAST.version }} desired: {{ .CAST.version }} autoUpgrade: false dependentsUpgraded: true --- apiVersion: openebs.io/v1alpha1 kind: RunTask metadata: name: cstor-pool-create-putcstorpooldeployment-default spec: meta: | runNamespace: {{.Config.RunNamespace.value}} apiVersion: apps/v1 kind: Deployment action: put id: putcstorpooldeployment post: | {{- jsonpath .JsonResult "{.metadata.name}" | trim | addTo "putcstorpooldeployment.objectName" .TaskResult | noop -}} {{- jsonpath .JsonResult "{.metadata.uid}" | trim | addTo "putcstorpooldeployment.objectUID" .TaskResult | noop -}} task: | {{- $isTolerations := .Config.Tolerations.value | default "none" -}} {{- $tolerationsVal := fromYaml .Config.Tolerations.value -}} {{- $setResourceRequests := .Config.PoolResourceRequests.value | default "none" -}} {{- $resourceRequestsVal := fromYaml .Config.PoolResourceRequests.value -}} {{- $setResourceLimits := .Config.PoolResourceLimits.value | default "none" -}} {{- $resourceLimitsVal := fromYaml .Config.PoolResourceLimits.value -}} {{- $setAuxResourceRequests := .Config.AuxResourceRequests.value | default "none" -}} {{- $auxResourceRequestsVal := fromYaml .Config.AuxResourceRequests.value -}} {{- $setAuxResourceLimits := .Config.AuxResourceLimits.value | default "none" -}} {{- $auxResourceLimitsVal := fromYaml .Config.AuxResourceLimits.value -}} apiVersion: apps/v1 kind: Deployment metadata: name: {{.TaskResult.putcstorpoolcr.objectName}} labels: openebs.io/storage-pool-claim: {{.Storagepool.owner}} openebs.io/cstor-pool: {{.TaskResult.putcstorpoolcr.objectName}} app: cstor-pool openebs.io/version: {{ .CAST.version }} openebs.io/cas-template-name: {{ .CAST.castName }} annotations: openebs.io/monitoring: pool_exporter_prometheus ownerReferences: - apiVersion: openebs.io/v1alpha1 blockOwnerDeletion: true controller: true kind: CStorPool name: {{ .TaskResult.putcstorpoolcr.objectName }} uid: {{ .TaskResult.putcstorpoolcr.objectUID }} spec: strategy: type: Recreate replicas: 1 selector: matchLabels: app: cstor-pool template: metadata: labels: app: cstor-pool openebs.io/storage-pool-claim: {{.Storagepool.owner}} openebs.io/cstor-pool: {{.TaskResult.putcstorpoolcr.objectName}} openebs.io/version: {{ .CAST.version }} annotations: openebs.io/monitoring: pool_exporter_prometheus prometheus.io/path: /metrics prometheus.io/port: "9500" prometheus.io/scrape: "true" spec: serviceAccountName: {{ .Config.ServiceAccountName.value }} nodeSelector: kubernetes.io/hostname: {{.Storagepool.nodeName}} containers: - name: cstor-pool image: {{ .Config.CstorPoolImage.value }} resources: {{- if ne $setResourceLimits "none" }} limits: {{- range $rKey, $rLimit := $resourceLimitsVal }} {{ $rKey }}: {{ $rLimit }} {{- end }} {{- end }} {{- if ne $setResourceRequests "none" }} requests: {{- range $rKey, $rReq := $resourceRequestsVal }} {{ $rKey }}: {{ $rReq }} {{- end }} {{- end }} ports: - containerPort: 12000 protocol: TCP - containerPort: 3233 protocol: TCP - containerPort: 3232 protocol: TCP livenessProbe: exec: command: - /bin/sh - -c - zfs set io.openebs:livenesstimestamp="$(date)" cstor-$OPENEBS_IO_CSTOR_ID failureThreshold: 3 initialDelaySeconds: 300 periodSeconds: 10 timeoutSeconds: 30 securityContext: privileged: true volumeMounts: - name: device mountPath: /dev - name: tmp mountPath: /tmp - name: sparse mountPath: {{ .Config.SparseDir.value }} - name: udev mountPath: /run/udev env: # OPENEBS_IO_CSTOR_ID env has UID of cStorPool CR. - name: OPENEBS_IO_CSTOR_ID value: {{.TaskResult.putcstorpoolcr.objectUID}} # To avoid clash between terminating and restarting pod # in case older zrepl gets deleted faster, we keep initial delay lifecycle: postStart: exec: command: ["/bin/sh", "-c", "sleep 2"] - name: cstor-pool-mgmt image: {{ .Config.CstorPoolMgmtImage.value }} resources: {{- if ne $setAuxResourceRequests "none" }} requests: {{- range $rKey, $rLimit := $auxResourceRequestsVal }} {{ $rKey }}: {{ $rLimit }} {{- end }} {{- end }} {{- if ne $setAuxResourceLimits "none" }} limits: {{- range $rKey, $rLimit := $auxResourceLimitsVal }} {{ $rKey }}: {{ $rLimit }} {{- end }} {{- end }} securityContext: privileged: true volumeMounts: - name: device mountPath: /dev - name: tmp mountPath: /tmp - name: sparse mountPath: {{ .Config.SparseDir.value }} - name: udev mountPath: /run/udev env: # OPENEBS_IO_CSTOR_ID env has UID of cStorPool CR. - name: OPENEBS_IO_CSTOR_ID value: {{.TaskResult.putcstorpoolcr.objectUID}} - name: POD_NAME valueFrom: fieldRef: fieldPath: metadata.name - name: NAMESPACE valueFrom: fieldRef: fieldPath: metadata.namespace - name: RESYNC_INTERVAL value: {{ .Config.ResyncInterval.value }} - name: maya-exporter image: {{ .Config.CstorPoolExporterImage.value }} resources: {{- if ne $setAuxResourceRequests "none" }} requests: {{- range $rKey, $rLimit := $auxResourceRequestsVal }} {{ $rKey }}: {{ $rLimit }} {{- end }} {{- end }} {{- if ne $setAuxResourceLimits "none" }} limits: {{- range $rKey, $rLimit := $auxResourceLimitsVal }} {{ $rKey }}: {{ $rLimit }} {{- end }} {{- end }} command: - maya-exporter args: - "-e=pool" ports: - containerPort: 9500 protocol: TCP securityContext: privileged: true volumeMounts: - mountPath: /dev name: device - mountPath: /tmp name: tmp - mountPath: {{ .Config.SparseDir.value }} name: sparse - mountPath: /run/udev name: udev tolerations: {{- if ne $isTolerations "none" }} {{- range $k, $v := $tolerationsVal }} - {{- range $kk, $vv := $v }} {{ $kk }}: {{ $vv }} {{- end }} {{- end }} {{- end }} volumes: - name: device hostPath: # directory location on host path: /dev # this field is optional type: Directory - name: tmp hostPath: # host dir {{ .Config.SparseDir.value }}/shared-<uid> is # created to avoid clash if two replicas run on same node. path: {{ .Config.SparseDir.value }}/shared-{{.Storagepool.owner}} type: {{ .Config.HostPathType.value }} - name: sparse hostPath: path: {{ .Config.SparseDir.value }} type: {{ .Config.HostPathType.value }} - name: udev hostPath: path: /run/udev type: Directory --- apiVersion: openebs.io/v1alpha1 kind: RunTask metadata: name: cstor-pool-create-patchstoragepoolclaim-default spec: meta: | id: patchstoragepoolclaim apiVersion: openebs.io/v1alpha1 kind: StoragePoolClaim objectName: {{.Storagepool.owner}} action: patch task: |- type: merge pspec: |- status: phase: Online --- ` // CstorPoolArtifacts returns the cstor pool related artifacts corresponding to // latest version func CstorPoolArtifacts() (list artifactList) { list.Items = append(list.Items, ParseArtifactListFromMultipleYamls(cstorPools{})...) return } type cstorPools struct{} // FetchYamls returns all the yamls related to cstor pool in a string // format // // NOTE: // This is an implementation of MultiYamlFetcher func (c cstorPools) FetchYamls() string { return cstorPoolYamls }
1
17,478
do we need to consider setting the `state` as well? If so, lot of changes might be required, like, setting to 'Reconciling' in upgrade code, setting to 'error' or 'reconciled' in volumeReconciler functions.
openebs-maya
go
@@ -3,7 +3,11 @@ module Blacklight::Solr extend ActiveSupport::Concern included do - self.default_processor_chain = [:default_solr_parameters, :add_query_to_solr, :add_facet_fq_to_solr, :add_facetting_to_solr, :add_solr_fields_to_query, :add_paging_to_solr, :add_sorting_to_solr, :add_group_config_to_solr ] + self.default_processor_chain = [ + :default_solr_parameters, :add_query_to_solr, :add_facet_fq_to_solr, + :add_facetting_to_solr, :add_solr_fields_to_query, :add_paging_to_solr, + :add_sorting_to_solr, :add_group_config_to_solr, :add_facet_paging_to_solr + ] end ####
1
module Blacklight::Solr module SearchBuilderBehavior extend ActiveSupport::Concern included do self.default_processor_chain = [:default_solr_parameters, :add_query_to_solr, :add_facet_fq_to_solr, :add_facetting_to_solr, :add_solr_fields_to_query, :add_paging_to_solr, :add_sorting_to_solr, :add_group_config_to_solr ] end #### # Start with general defaults from BL config. Need to use custom # merge to dup values, to avoid later mutating the original by mistake. def default_solr_parameters(solr_parameters) blacklight_config.default_solr_params.each do |key, value| solr_parameters[key] = if value.respond_to? :deep_dup value.deep_dup elsif value.respond_to? :dup and value.duplicable? value.dup else value end end end ## # Take the user-entered query, and put it in the solr params, # including config's "search field" params for current search field. # also include setting spellcheck.q. def add_query_to_solr(solr_parameters) ### # Merge in search field configured values, if present, over-writing general # defaults ### # legacy behavior of user param :qt is passed through, but over-ridden # by actual search field config if present. We might want to remove # this legacy behavior at some point. It does not seem to be currently # rspec'd. solr_parameters[:qt] = blacklight_params[:qt] if blacklight_params[:qt] if search_field solr_parameters[:qt] = search_field.qt solr_parameters.merge!( search_field.solr_parameters) if search_field.solr_parameters end ## # Create Solr 'q' including the user-entered q, prefixed by any # solr LocalParams in config, using solr LocalParams syntax. # http://wiki.apache.org/solr/LocalParams ## if (search_field && hash = search_field.solr_local_parameters) local_params = hash.collect do |key, val| key.to_s + "=" + solr_param_quote(val, :quote => "'") end.join(" ") solr_parameters[:q] = "{!#{local_params}}#{blacklight_params[:q]}" ## # Set Solr spellcheck.q to be original user-entered query, without # our local params, otherwise it'll try and spellcheck the local # params! solr_parameters["spellcheck.q"] ||= blacklight_params[:q] elsif blacklight_params[:q].is_a? Hash q = blacklight_params[:q] solr_parameters[:q] = if q.values.any?(&:blank?) # if any field parameters are empty, exclude _all_ results "{!lucene}NOT *:*" else "{!lucene}" + q.map do |field, values| "#{field}:(#{ Array(values).map { |x| solr_param_quote(x) }.join(" OR ")})" end.join(" AND ") end solr_parameters[:spellcheck] = 'false' elsif blacklight_params[:q] solr_parameters[:q] = blacklight_params[:q] end end ## # Add any existing facet limits, stored in app-level HTTP query # as :f, to solr as appropriate :fq query. def add_facet_fq_to_solr(solr_parameters) # convert a String value into an Array if solr_parameters[:fq].is_a? String solr_parameters[:fq] = [solr_parameters[:fq]] end # :fq, map from :f. if ( blacklight_params[:f]) f_request_params = blacklight_params[:f] f_request_params.each_pair do |facet_field, value_list| Array(value_list).each do |value| next if value.blank? # skip empty strings solr_parameters.append_filter_query facet_value_to_fq_string(facet_field, value) end end end end ## # Add appropriate Solr facetting directives in, including # taking account of our facet paging/'more'. This is not # about solr 'fq', this is about solr facet.* params. def add_facetting_to_solr(solr_parameters) # While not used by BL core behavior, legacy behavior seemed to be # to accept incoming params as "facet.field" or "facets", and add them # on to any existing facet.field sent to Solr. Legacy behavior seemed # to be accepting these incoming params as arrays (in Rails URL with [] # on end), or single values. At least one of these is used by # Stanford for "faux hieararchial facets". if blacklight_params.has_key?("facet.field") || blacklight_params.has_key?("facets") solr_parameters[:"facet.field"].concat( [blacklight_params["facet.field"], blacklight_params["facets"]].flatten.compact ).uniq! end facet_fields_to_include_in_request.each do |field_name, facet| solr_parameters[:facet] ||= true case when facet.pivot solr_parameters.append_facet_pivot with_ex_local_param(facet.ex, facet.pivot.join(",")) when facet.query solr_parameters.append_facet_query facet.query.map { |k, x| with_ex_local_param(facet.ex, x[:fq]) } else solr_parameters.append_facet_fields with_ex_local_param(facet.ex, facet.field) end if facet.sort solr_parameters[:"f.#{facet.field}.facet.sort"] = facet.sort end if facet.solr_params facet.solr_params.each do |k, v| solr_parameters[:"f.#{facet.field}.#{k}"] = v end end # Support facet paging and 'more' # links, by sending a facet.limit one more than what we # want to page at, according to configured facet limits. solr_parameters[:"f.#{facet.field}.facet.limit"] = (facet_limit_for(field_name) + 1) if facet_limit_for(field_name) end end def add_solr_fields_to_query solr_parameters blacklight_config.show_fields.select(&method(:should_add_field_to_request?)).each do |field_name, field| if field.solr_params field.solr_params.each do |k, v| solr_parameters[:"f.#{field.field}.#{k}"] = v end end end blacklight_config.index_fields.select(&method(:should_add_field_to_request?)).each do |field_name, field| if field.highlight solr_parameters[:hl] = true solr_parameters.append_highlight_field field.field end if field.solr_params field.solr_params.each do |k, v| solr_parameters[:"f.#{field.field}.#{k}"] = v end end end end ### # copy paging params from BL app over to solr, changing # app level per_page and page to Solr rows and start. def add_paging_to_solr(solr_params) rows(solr_params[:rows] || 10) if rows.nil? solr_params[:rows] = rows if start != 0 solr_params[:start] = start end end ### # copy sorting params from BL app over to solr def add_sorting_to_solr(solr_parameters) solr_parameters[:sort] = sort unless sort.blank? end # Remove the group parameter if we've faceted on the group field (e.g. for the full results for a group) def add_group_config_to_solr solr_parameters if blacklight_params[:f] and blacklight_params[:f][grouped_key_for_results] solr_parameters[:group] = false end end def with_ex_local_param(ex, value) if ex "{!ex=#{ex}}#{value}" else value end end # Look up facet limit for given facet_field. Will look at config, and # if config is 'true' will look up from Solr @response if available. If # no limit is avaialble, returns nil. Used from #add_facetting_to_solr # to supply f.fieldname.facet.limit values in solr request (no @response # available), and used in display (with @response available) to create # a facet paginator with the right limit. def facet_limit_for(facet_field) facet = blacklight_config.facet_fields[facet_field] return if facet.blank? if facet.limit facet.limit == true ? blacklight_config.default_facet_limit : facet.limit end end ## # A helper method used for generating solr LocalParams, put quotes # around the term unless it's a bare-word. Escape internal quotes # if needed. def solr_param_quote(val, options = {}) options[:quote] ||= '"' unless val =~ /^[a-zA-Z0-9$_\-\^]+$/ val = options[:quote] + # Yes, we need crazy escaping here, to deal with regexp esc too! val.gsub("'", "\\\\\'").gsub('"', "\\\\\"") + options[:quote] end return val end private ## # Convert a facet/value pair into a solr fq parameter def facet_value_to_fq_string(facet_field, value) facet_config = blacklight_config.facet_fields[facet_field] solr_field = facet_config.field if facet_config and not facet_config.query solr_field ||= facet_field local_params = [] local_params << "tag=#{facet_config.tag}" if facet_config and facet_config.tag prefix = "{!#{local_params.join(" ")}}" unless local_params.empty? case when (facet_config and facet_config.query) facet_config.query[value][:fq] when (facet_config and facet_config.date) # in solr 3.2+, this could be replaced by a !term query "#{prefix}#{solr_field}:#{RSolr.solr_escape(value)}" when (value.is_a?(DateTime) or value.is_a?(Time)) "#{prefix}#{solr_field}:#{RSolr.solr_escape(value.utc.strftime("%Y-%m-%dT%H:%M:%SZ"))}" when value.is_a?(Date) # rubocop:disable Rails/Date "#{prefix}#{solr_field}:#{RSolr.solr_escape(value.to_time(:local).strftime("%Y-%m-%dT%H:%M:%SZ"))}" # rubocop:enable Rails/Date when (value.is_a?(TrueClass) or value.is_a?(FalseClass) or value == 'true' or value == 'false'), (value.is_a?(Integer) or (value.to_i.to_s == value if value.respond_to? :to_i)), (value.is_a?(Float) or (value.to_f.to_s == value if value.respond_to? :to_f)) "#{prefix}#{solr_field}:#{RSolr.solr_escape(value.to_s)}" when value.is_a?(Range) "#{prefix}#{solr_field}:[#{value.first} TO #{value.last}]" else "{!raw f=#{solr_field}#{(" " + local_params.join(" ")) unless local_params.empty?}}#{value}" end end ## # The key to use to retrieve the grouped field to display def grouped_key_for_results blacklight_config.index.group end def facet_fields_to_include_in_request blacklight_config.facet_fields.select do |field_name,facet| facet.include_in_request || (facet.include_in_request.nil? && blacklight_config.add_facet_fields_to_solr_request) end end end end
1
5,986
Line is too long. [82/80]
projectblacklight-blacklight
rb
@@ -1,4 +1,5 @@ -// Copyright (c) Microsoft. All rights reserved. +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.Client.Parallel { using System;
1
// Copyright (c) Microsoft. All rights reserved. namespace Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.Client.Parallel { using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.VisualStudio.TestPlatform.ObjectModel; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Engine; /// <summary> /// ParallelProxyExecutionManager that manages parallel execution /// </summary> internal class ParallelProxyExecutionManager : ParallelOperationManager<IProxyExecutionManager>, IParallelProxyExecutionManager { #region TestRunSpecificData private int runCompletedClients = 0; private TestRunCriteria actualTestRunCriteria; private IEnumerator<string> sourceEnumerator; private IEnumerator testCaseListEnumerator; private bool hasSpecificTestsRun = false; private Task lastParallelRunCleanUpTask = null; private IDictionary<IProxyExecutionManager, ITestRunEventsHandler> concurrentManagerHandlerMap; private ITestRunEventsHandler currentRunEventsHandler; private ParallelRunDataAggregator currentRunDataAggregator; #endregion #region Concurrency Keeper Objects /// <summary> /// LockObject to update execution status in parallel /// </summary> private object executionStatusLockObject = new object(); #endregion public ParallelProxyExecutionManager(Func<IProxyExecutionManager> actualProxyManagerCreator, int parallelLevel) : base(actualProxyManagerCreator, parallelLevel, true) { } public ParallelProxyExecutionManager(Func<IProxyExecutionManager> actualProxyManagerCreator, int parallelLevel, bool sharedHosts) : base(actualProxyManagerCreator, parallelLevel, sharedHosts) { } #region IProxyExecutionManager public void Initialize() { this.DoActionOnAllManagers((proxyManager) => proxyManager.Initialize(), doActionsInParallel: true); } public int StartTestRun(TestRunCriteria testRunCriteria, ITestRunEventsHandler eventHandler) { this.hasSpecificTestsRun = testRunCriteria.HasSpecificTests; this.actualTestRunCriteria = testRunCriteria; if (this.hasSpecificTestsRun) { var testCasesBySource = new Dictionary<string, List<TestCase>>(); foreach (var test in testRunCriteria.Tests) { if (!testCasesBySource.ContainsKey(test.Source)) { testCasesBySource.Add(test.Source, new List<TestCase>()); } testCasesBySource[test.Source].Add(test); } // Do not use "Dictionary.ValueCollection.Enumerator" - it becomes undetermenstic once we go out of scope of this method // Use "ToArray" to copy ValueColleciton to a simple array and use it's enumerator // Set the enumerator for parallel yielding of testCases // Whenever a concurrent executor becomes free, it picks up the next set of testCases using this enumerator this.testCaseListEnumerator = testCasesBySource.Values.ToArray().GetEnumerator(); } else { // Set the enumerator for parallel yielding of sources // Whenever a concurrent executor becomes free, it picks up the next source using this enumerator this.sourceEnumerator = testRunCriteria.Sources.GetEnumerator(); } return this.StartTestRunPrivate(eventHandler); } public void Abort() { this.DoActionOnAllManagers((proxyManager) => proxyManager.Abort(), doActionsInParallel: true); } public void Cancel() { this.DoActionOnAllManagers((proxyManager) => proxyManager.Cancel(), doActionsInParallel: true); } public void Close() { this.DoActionOnAllManagers(proxyManager => proxyManager.Close(), doActionsInParallel: true); } #endregion #region IParallelProxyExecutionManager methods /// <summary> /// Handles Partial Run Complete event coming from a specific concurrent proxy exceution manager /// Each concurrent proxy execution manager will signal the parallel execution manager when its complete /// </summary> /// <param name="proxyExecutionManager">Concurrent Execution manager that completed the run</param> /// <param name="testRunCompleteArgs">RunCompleteArgs for the concurrent run</param> /// <param name="lastChunkArgs">LastChunk testresults for the concurrent run</param> /// <param name="runContextAttachments">RunAttachments for the concurrent run</param> /// <param name="executorUris">ExecutorURIs of the adapters involved in executing the tests</param> /// <returns>True if parallel run is complete</returns> public bool HandlePartialRunComplete( IProxyExecutionManager proxyExecutionManager, TestRunCompleteEventArgs testRunCompleteArgs, TestRunChangedEventArgs lastChunkArgs, ICollection<AttachmentSet> runContextAttachments, ICollection<string> executorUris) { var allRunsCompleted = false; if(!this.SharedHosts) { this.concurrentManagerHandlerMap.Remove(proxyExecutionManager); proxyExecutionManager.Close(); proxyExecutionManager = CreateNewConcurrentManager(); var parallelEventsHandler = new ParallelRunEventsHandler( proxyExecutionManager, this.currentRunEventsHandler, this, this.currentRunDataAggregator); this.concurrentManagerHandlerMap.Add(proxyExecutionManager, parallelEventsHandler); } // In Case of Cancel or Abort, no need to trigger run for rest of the data // If there are no more sources/testcases, a parallel executor is truly done with execution if (testRunCompleteArgs.IsAborted || testRunCompleteArgs.IsCanceled || !this.StartTestRunOnConcurrentManager(proxyExecutionManager)) { lock (this.executionStatusLockObject) { // Each concurrent Executor calls this method // So, we need to keep track of total runcomplete calls this.runCompletedClients++; allRunsCompleted = this.runCompletedClients == this.concurrentManagerInstances.Length; } // verify that all executors are done with the execution and there are no more sources/testcases to execute if (allRunsCompleted) { // Reset enumerators this.sourceEnumerator = null; this.testCaseListEnumerator = null; this.currentRunDataAggregator = null; this.currentRunEventsHandler = null; // Dispose concurrent executors // Do not do the cleanuptask in the current thread as we will unncessarily add to execution time this.lastParallelRunCleanUpTask = Task.Run(() => { this.UpdateParallelLevel(0); }); } } return allRunsCompleted; } #endregion #region ParallelOperationManager Methods protected override void DisposeInstance(IProxyExecutionManager managerInstance) { if (managerInstance != null) { try { managerInstance.Close(); } catch (Exception) { // ignore any exceptions } } } #endregion private int StartTestRunPrivate(ITestRunEventsHandler runEventsHandler) { this.currentRunEventsHandler = runEventsHandler; // Cleanup Task for cleaning up the parallel executors except for the default one // We do not do this in Sync so that this task does not add up to execution time if (this.lastParallelRunCleanUpTask != null) { try { this.lastParallelRunCleanUpTask.Wait(); } catch (Exception ex) { // if there is an exception disposing off concurrent executors ignore it if (EqtTrace.IsWarningEnabled) { EqtTrace.Warning("ParallelTestRunnerServiceClient: Exception while invoking an action on DiscoveryManager: {0}", ex); } } this.lastParallelRunCleanUpTask = null; } // Reset the runcomplete data this.runCompletedClients = 0; // One data aggregator per parallel run this.currentRunDataAggregator = new ParallelRunDataAggregator(); this.concurrentManagerHandlerMap = new Dictionary<IProxyExecutionManager, ITestRunEventsHandler>(); for (int i = 0; i < this.concurrentManagerInstances.Length; i++) { var concurrentManager = this.concurrentManagerInstances[i]; var parallelEventsHandler = new ParallelRunEventsHandler( concurrentManager, runEventsHandler, this, this.currentRunDataAggregator); this.concurrentManagerHandlerMap.Add(concurrentManager, parallelEventsHandler); Task.Run(() => this.StartTestRunOnConcurrentManager(concurrentManager)); } return 1; } /// <summary> /// Triggers the execution for the next data object on the concurrent executor /// Each concurrent executor calls this method, once its completed working on previous data /// </summary> /// <param name="proxyExecutionManager">Proxy execution manager instance.</param> /// <returns>True, if execution triggered</returns> private bool StartTestRunOnConcurrentManager(IProxyExecutionManager proxyExecutionManager) { TestRunCriteria testRunCriteria = null; if (!this.hasSpecificTestsRun) { string nextSource = null; if (this.TryFetchNextSource(this.sourceEnumerator, out nextSource)) { EqtTrace.Info("ProxyParallelExecutionManager: Triggering test run for next source: {0}", nextSource); testRunCriteria = new TestRunCriteria(new List<string>() { nextSource }, this.actualTestRunCriteria.FrequencyOfRunStatsChangeEvent, this.actualTestRunCriteria.KeepAlive, this.actualTestRunCriteria.TestRunSettings, this.actualTestRunCriteria.RunStatsChangeEventTimeout, this.actualTestRunCriteria.TestHostLauncher); } } else { List<TestCase> nextSetOfTests = null; if (this.TryFetchNextSource(this.testCaseListEnumerator, out nextSetOfTests)) { EqtTrace.Info("ProxyParallelExecutionManager: Triggering test run for next source: {0}", nextSetOfTests?.FirstOrDefault()?.Source); testRunCriteria = new TestRunCriteria( nextSetOfTests, this.actualTestRunCriteria.FrequencyOfRunStatsChangeEvent, this.actualTestRunCriteria.KeepAlive, this.actualTestRunCriteria.TestRunSettings, this.actualTestRunCriteria.RunStatsChangeEventTimeout, this.actualTestRunCriteria.TestHostLauncher); } } if (testRunCriteria != null) { proxyExecutionManager.StartTestRun(testRunCriteria, this.concurrentManagerHandlerMap[proxyExecutionManager]); } return testRunCriteria != null; } } }
1
11,390
Add blank line below license header.
microsoft-vstest
.cs
@@ -110,9 +110,17 @@ public abstract class BaseMetastoreCatalog implements Catalog { throw new NoSuchTableException("No such table: " + identifier); } - String baseLocation = location != null ? location : defaultWarehouseLocation(identifier); Map<String, String> tableProperties = properties != null ? properties : Maps.newHashMap(); - TableMetadata metadata = TableMetadata.newTableMetadata(schema, spec, baseLocation, tableProperties); + + TableMetadata metadata; + if (ops.current() != null) { + String baseLocation = location != null ? location : ops.current().location(); + metadata = ops.current().buildReplacement(schema, spec, baseLocation, tableProperties); + } else { + String baseLocation = location != null ? location : defaultWarehouseLocation(identifier); + metadata = TableMetadata.newTableMetadata(schema, spec, baseLocation, tableProperties); + } + if (orCreate) { return Transactions.createOrReplaceTableTransaction(identifier.toString(), ops, metadata); } else {
1
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.iceberg; import java.io.IOException; import java.util.Map; import java.util.Set; import org.apache.iceberg.catalog.Catalog; import org.apache.iceberg.catalog.TableIdentifier; import org.apache.iceberg.exceptions.AlreadyExistsException; import org.apache.iceberg.exceptions.CommitFailedException; import org.apache.iceberg.exceptions.NoSuchTableException; import org.apache.iceberg.exceptions.RuntimeIOException; import org.apache.iceberg.io.FileIO; import org.apache.iceberg.relocated.com.google.common.base.Joiner; import org.apache.iceberg.relocated.com.google.common.base.Preconditions; import org.apache.iceberg.relocated.com.google.common.collect.Iterables; import org.apache.iceberg.relocated.com.google.common.collect.MapMaker; import org.apache.iceberg.relocated.com.google.common.collect.Maps; import org.apache.iceberg.relocated.com.google.common.collect.Sets; import org.apache.iceberg.util.Tasks; import org.apache.iceberg.util.ThreadPools; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public abstract class BaseMetastoreCatalog implements Catalog { private static final Logger LOG = LoggerFactory.getLogger(BaseMetastoreCatalog.class); @Override public Table createTable( TableIdentifier identifier, Schema schema, PartitionSpec spec, String location, Map<String, String> properties) { Preconditions.checkArgument(isValidIdentifier(identifier), "Invalid table identifier: %s", identifier); TableOperations ops = newTableOps(identifier); if (ops.current() != null) { throw new AlreadyExistsException("Table already exists: " + identifier); } String baseLocation; if (location != null) { baseLocation = location; } else { baseLocation = defaultWarehouseLocation(identifier); } TableMetadata metadata = TableMetadata.newTableMetadata( schema, spec, baseLocation, properties == null ? Maps.newHashMap() : properties); try { ops.commit(null, metadata); } catch (CommitFailedException ignored) { throw new AlreadyExistsException("Table was created concurrently: " + identifier); } return new BaseTable(ops, fullTableName(name(), identifier)); } @Override public Transaction newCreateTableTransaction( TableIdentifier identifier, Schema schema, PartitionSpec spec, String location, Map<String, String> properties) { Preconditions.checkArgument(isValidIdentifier(identifier), "Invalid table identifier: %s", identifier); TableOperations ops = newTableOps(identifier); if (ops.current() != null) { throw new AlreadyExistsException("Table already exists: " + identifier); } String baseLocation = location != null ? location : defaultWarehouseLocation(identifier); Map<String, String> tableProperties = properties != null ? properties : Maps.newHashMap(); TableMetadata metadata = TableMetadata.newTableMetadata(schema, spec, baseLocation, tableProperties); return Transactions.createTableTransaction(identifier.toString(), ops, metadata); } @Override public Transaction newReplaceTableTransaction( TableIdentifier identifier, Schema schema, PartitionSpec spec, String location, Map<String, String> properties, boolean orCreate) { TableOperations ops = newTableOps(identifier); if (!orCreate && ops.current() == null) { throw new NoSuchTableException("No such table: " + identifier); } String baseLocation = location != null ? location : defaultWarehouseLocation(identifier); Map<String, String> tableProperties = properties != null ? properties : Maps.newHashMap(); TableMetadata metadata = TableMetadata.newTableMetadata(schema, spec, baseLocation, tableProperties); if (orCreate) { return Transactions.createOrReplaceTableTransaction(identifier.toString(), ops, metadata); } else { return Transactions.replaceTableTransaction(identifier.toString(), ops, metadata); } } @Override public Table loadTable(TableIdentifier identifier) { if (isValidIdentifier(identifier)) { TableOperations ops = newTableOps(identifier); if (ops.current() == null) { // the identifier may be valid for both tables and metadata tables if (isValidMetadataIdentifier(identifier)) { return loadMetadataTable(identifier); } throw new NoSuchTableException("Table does not exist: %s", identifier); } return new BaseTable(ops, fullTableName(name(), identifier)); } else if (isValidMetadataIdentifier(identifier)) { return loadMetadataTable(identifier); } else { throw new NoSuchTableException("Invalid table identifier: %s", identifier); } } private Table loadMetadataTable(TableIdentifier identifier) { String name = identifier.name(); MetadataTableType type = MetadataTableType.from(name); if (type != null) { TableIdentifier baseTableIdentifier = TableIdentifier.of(identifier.namespace().levels()); TableOperations ops = newTableOps(baseTableIdentifier); if (ops.current() == null) { throw new NoSuchTableException("Table does not exist: " + baseTableIdentifier); } Table baseTable = new BaseTable(ops, fullTableName(name(), baseTableIdentifier)); switch (type) { case ENTRIES: return new ManifestEntriesTable(ops, baseTable); case FILES: return new DataFilesTable(ops, baseTable); case HISTORY: return new HistoryTable(ops, baseTable); case SNAPSHOTS: return new SnapshotsTable(ops, baseTable); case MANIFESTS: return new ManifestsTable(ops, baseTable); case PARTITIONS: return new PartitionsTable(ops, baseTable); case ALL_DATA_FILES: return new AllDataFilesTable(ops, baseTable); case ALL_MANIFESTS: return new AllManifestsTable(ops, baseTable); case ALL_ENTRIES: return new AllEntriesTable(ops, baseTable); default: throw new NoSuchTableException("Unknown metadata table type: %s for %s", type, baseTableIdentifier); } } else { throw new NoSuchTableException("Table does not exist: " + identifier); } } private boolean isValidMetadataIdentifier(TableIdentifier identifier) { return MetadataTableType.from(identifier.name()) != null && isValidIdentifier(TableIdentifier.of(identifier.namespace().levels())); } protected boolean isValidIdentifier(TableIdentifier tableIdentifier) { // by default allow all identifiers return true; } @Override public String toString() { return getClass().getSimpleName() + "(" + name() + ")"; } protected abstract String name(); protected abstract TableOperations newTableOps(TableIdentifier tableIdentifier); protected abstract String defaultWarehouseLocation(TableIdentifier tableIdentifier); /** * Drops all data and metadata files referenced by TableMetadata. * <p> * This should be called by dropTable implementations to clean up table files once the table has been dropped in the * metastore. * * @param io a FileIO to use for deletes * @param metadata the last valid TableMetadata instance for a dropped table. */ protected static void dropTableData(FileIO io, TableMetadata metadata) { // Reads and deletes are done using Tasks.foreach(...).suppressFailureWhenFinished to complete // as much of the delete work as possible and avoid orphaned data or manifest files. Set<String> manifestListsToDelete = Sets.newHashSet(); Set<ManifestFile> manifestsToDelete = Sets.newHashSet(); for (Snapshot snapshot : metadata.snapshots()) { // add all manifests to the delete set because both data and delete files should be removed Iterables.addAll(manifestsToDelete, snapshot.allManifests()); // add the manifest list to the delete set, if present if (snapshot.manifestListLocation() != null) { manifestListsToDelete.add(snapshot.manifestListLocation()); } } LOG.info("Manifests to delete: {}", Joiner.on(", ").join(manifestsToDelete)); // run all of the deletes deleteFiles(io, manifestsToDelete); Tasks.foreach(Iterables.transform(manifestsToDelete, ManifestFile::path)) .noRetry().suppressFailureWhenFinished() .onFailure((manifest, exc) -> LOG.warn("Delete failed for manifest: {}", manifest, exc)) .run(io::deleteFile); Tasks.foreach(manifestListsToDelete) .noRetry().suppressFailureWhenFinished() .onFailure((list, exc) -> LOG.warn("Delete failed for manifest list: {}", list, exc)) .run(io::deleteFile); Tasks.foreach(metadata.metadataFileLocation()) .noRetry().suppressFailureWhenFinished() .onFailure((list, exc) -> LOG.warn("Delete failed for metadata file: {}", list, exc)) .run(io::deleteFile); } private static void deleteFiles(FileIO io, Set<ManifestFile> allManifests) { // keep track of deleted files in a map that can be cleaned up when memory runs low Map<String, Boolean> deletedFiles = new MapMaker() .concurrencyLevel(ThreadPools.WORKER_THREAD_POOL_SIZE) .weakKeys() .makeMap(); Tasks.foreach(allManifests) .noRetry().suppressFailureWhenFinished() .executeWith(ThreadPools.getWorkerPool()) .onFailure((item, exc) -> LOG.warn("Failed to get deleted files: this may cause orphaned data files", exc)) .run(manifest -> { try (ManifestReader<?> reader = ManifestFiles.open(manifest, io)) { for (ManifestEntry<?> entry : reader.entries()) { // intern the file path because the weak key map uses identity (==) instead of equals String path = entry.file().path().toString().intern(); Boolean alreadyDeleted = deletedFiles.putIfAbsent(path, true); if (alreadyDeleted == null || !alreadyDeleted) { try { io.deleteFile(path); } catch (RuntimeException e) { // this may happen if the map of deleted files gets cleaned up by gc LOG.warn("Delete failed for data file: {}", path, e); } } } } catch (IOException e) { throw new RuntimeIOException(e, "Failed to read manifest file: " + manifest.path()); } }); } protected static String fullTableName(String catalogName, TableIdentifier identifier) { StringBuilder sb = new StringBuilder(); if (catalogName.contains("/") || catalogName.contains(":")) { // use / for URI-like names: thrift://host:port/db.table sb.append(catalogName); if (!catalogName.endsWith("/")) { sb.append("/"); } } else { // use . for non-URI named catalogs: prod.db.table sb.append(catalogName).append("."); } for (String level : identifier.namespace().levels()) { sb.append(level).append("."); } sb.append(identifier.name()); return sb.toString(); } }
1
21,135
I'm not clear on whether this really should be the right behavior. Basically we're saying that a replace table will keep the existing location (as opposed to using defaults). I suspect we don't have create or replace with location semantics, but this is making some assumptions that a replacement is somehow the same as the old. If we were to go with id based pathing convention, this wouldn't work. I don't think this is an issue at this point, but it might make sense to push this down to the location provider.
apache-iceberg
java
@@ -37,8 +37,10 @@ import ( executionpb "go.temporal.io/temporal-proto/execution" tasklistpb "go.temporal.io/temporal-proto/tasklist" + executionproto "github.com/temporalio/temporal/.gen/proto/execution" "github.com/temporalio/temporal/.gen/proto/persistenceblobs" replicationgenpb "github.com/temporalio/temporal/.gen/proto/replication" + "github.com/temporalio/temporal/common" "github.com/temporalio/temporal/common/checksum" "github.com/temporalio/temporal/common/persistence/serialization"
1
// The MIT License // // Copyright (c) 2020 Temporal Technologies Inc. All rights reserved. // // Copyright (c) 2020 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. package persistence import ( "fmt" "net" "strings" "time" "github.com/gogo/protobuf/types" "github.com/pborman/uuid" commonpb "go.temporal.io/temporal-proto/common" eventpb "go.temporal.io/temporal-proto/event" executionpb "go.temporal.io/temporal-proto/execution" tasklistpb "go.temporal.io/temporal-proto/tasklist" "github.com/temporalio/temporal/.gen/proto/persistenceblobs" replicationgenpb "github.com/temporalio/temporal/.gen/proto/replication" "github.com/temporalio/temporal/common" "github.com/temporalio/temporal/common/checksum" "github.com/temporalio/temporal/common/persistence/serialization" "github.com/temporalio/temporal/common/primitives" ) // Namespace status const ( NamespaceStatusRegistered = iota NamespaceStatusDeprecated NamespaceStatusDeleted ) const ( // EventStoreVersion is already deprecated, this is used for forward // compatibility (so that rollback is possible). // TODO we can remove it after fixing all the query templates and when // we decide the compatibility is no longer needed. EventStoreVersion = 2 ) // CreateWorkflowMode workflow creation mode type CreateWorkflowMode int // QueueType is an enum that represents various queue types in persistence type QueueType int // Queue types used in queue table // Use positive numbers for queue type // Negative numbers are reserved for DLQ const ( NamespaceReplicationQueueType QueueType = iota + 1 ) // Create Workflow Execution Mode const ( // Fail if current record exists // Only applicable for CreateWorkflowExecution CreateWorkflowModeBrandNew CreateWorkflowMode = iota // Update current record only if workflow is closed // Only applicable for CreateWorkflowExecution CreateWorkflowModeWorkflowIDReuse // Update current record only if workflow is open // Only applicable for UpdateWorkflowExecution CreateWorkflowModeContinueAsNew // Do not update current record since workflow to // applicable for CreateWorkflowExecution, UpdateWorkflowExecution CreateWorkflowModeZombie ) // UpdateWorkflowMode update mode type UpdateWorkflowMode int // Update Workflow Execution Mode const ( // Update workflow, including current record // NOTE: update on current record is a condition update UpdateWorkflowModeUpdateCurrent UpdateWorkflowMode = iota // Update workflow, without current record // NOTE: current record CANNOT point to the workflow to be updated UpdateWorkflowModeBypassCurrent ) // ConflictResolveWorkflowMode conflict resolve mode type ConflictResolveWorkflowMode int // Conflict Resolve Workflow Mode const ( // Conflict resolve workflow, including current record // NOTE: update on current record is a condition update ConflictResolveWorkflowModeUpdateCurrent ConflictResolveWorkflowMode = iota // Conflict resolve workflow, without current record // NOTE: current record CANNOT point to the workflow to be updated ConflictResolveWorkflowModeBypassCurrent ) // Workflow execution states const ( WorkflowStateCreated = iota WorkflowStateRunning WorkflowStateCompleted WorkflowStateZombie WorkflowStateVoid WorkflowStateCorrupted ) // Transfer task types const ( TransferTaskTypeDecisionTask = iota TransferTaskTypeActivityTask TransferTaskTypeCloseExecution TransferTaskTypeCancelExecution TransferTaskTypeStartChildExecution TransferTaskTypeSignalExecution TransferTaskTypeRecordWorkflowStarted TransferTaskTypeResetWorkflow TransferTaskTypeUpsertWorkflowSearchAttributes ) // Types of replication tasks const ( ReplicationTaskTypeHistory = iota ReplicationTaskTypeSyncActivity ) // Types of timers const ( TaskTypeDecisionTimeout = iota TaskTypeActivityTimeout TaskTypeUserTimer TaskTypeWorkflowRunTimeout TaskTypeDeleteHistoryEvent TaskTypeActivityRetryTimer TaskTypeWorkflowBackoffTimer ) // UnknownNumRowsAffected is returned when the number of rows that an API affected cannot be determined const UnknownNumRowsAffected = -1 // Types of workflow backoff timeout const ( WorkflowBackoffTimeoutTypeRetry = iota WorkflowBackoffTimeoutTypeCron ) const ( // InitialFailoverNotificationVersion is the initial failover version for a namespace InitialFailoverNotificationVersion int64 = 0 // TransferTaskTransferTargetWorkflowID is the the dummy workflow ID for transfer tasks of types // that do not have a target workflow TransferTaskTransferTargetWorkflowID = "20000000-0000-f000-f000-000000000001" // indicate invalid workflow state transition invalidStateTransitionMsg = "unable to change workflow state from %v to %v, status %v" ) const numItemsInGarbageInfo = 3 type ( // InvalidPersistenceRequestError represents invalid request to persistence InvalidPersistenceRequestError struct { Msg string } // CurrentWorkflowConditionFailedError represents a failed conditional update for current workflow record CurrentWorkflowConditionFailedError struct { Msg string } // ConditionFailedError represents a failed conditional update for execution record ConditionFailedError struct { Msg string } // ShardAlreadyExistError is returned when conditionally creating a shard fails ShardAlreadyExistError struct { Msg string } // ShardOwnershipLostError is returned when conditional update fails due to RangeID for the shard ShardOwnershipLostError struct { ShardID int Msg string } // WorkflowExecutionAlreadyStartedError is returned when creating a new workflow failed. WorkflowExecutionAlreadyStartedError struct { Msg string StartRequestID string RunID string State int Status executionpb.WorkflowExecutionStatus LastWriteVersion int64 } // TimeoutError is returned when a write operation fails due to a timeout TimeoutError struct { Msg string } // TransactionSizeLimitError is returned when the transaction size is too large TransactionSizeLimitError struct { Msg string } // ShardInfoWithFailover describes a shard ShardInfoWithFailover struct { *persistenceblobs.ShardInfo TransferFailoverLevels map[string]TransferFailoverLevel // uuid -> TransferFailoverLevel TimerFailoverLevels map[string]TimerFailoverLevel // uuid -> TimerFailoverLevel } // TransferFailoverLevel contains corresponding start / end level TransferFailoverLevel struct { StartTime time.Time MinLevel int64 CurrentLevel int64 MaxLevel int64 NamespaceIDs map[string]struct{} } // TimerFailoverLevel contains namespace IDs and corresponding start / end level TimerFailoverLevel struct { StartTime time.Time MinLevel time.Time CurrentLevel time.Time MaxLevel time.Time NamespaceIDs map[string]struct{} } // WorkflowExecutionInfo describes a workflow execution WorkflowExecutionInfo struct { NamespaceID string WorkflowID string RunID string ParentNamespaceID string ParentWorkflowID string ParentRunID string InitiatedID int64 CompletionEventBatchID int64 CompletionEvent *eventpb.HistoryEvent TaskList string WorkflowTypeName string WorkflowRunTimeout int32 WorkflowExecutionTimeout int32 WorkflowTaskTimeout int32 State int Status executionpb.WorkflowExecutionStatus LastFirstEventID int64 LastEventTaskID int64 NextEventID int64 LastProcessedEvent int64 StartTimestamp time.Time LastUpdatedTimestamp time.Time CreateRequestID string SignalCount int32 DecisionVersion int64 DecisionScheduleID int64 DecisionStartedID int64 DecisionRequestID string DecisionTimeout int32 DecisionAttempt int64 DecisionStartedTimestamp int64 DecisionScheduledTimestamp int64 DecisionOriginalScheduledTimestamp int64 CancelRequested bool CancelRequestID string StickyTaskList string StickyScheduleToStartTimeout int32 ClientLibraryVersion string ClientFeatureVersion string ClientImpl string AutoResetPoints *executionpb.ResetPoints Memo map[string]*commonpb.Payload SearchAttributes map[string]*commonpb.Payload // for retry Attempt int32 HasRetryPolicy bool InitialInterval int32 BackoffCoefficient float64 MaximumInterval int32 WorkflowExpirationTime time.Time MaximumAttempts int32 NonRetriableErrors []string BranchToken []byte // Cron CronSchedule string } // ExecutionStats is the statistics about workflow execution ExecutionStats struct { HistorySize int64 } // ReplicationState represents mutable state information for global namespaces. // This information is used by replication protocol when applying events from remote clusters ReplicationState struct { CurrentVersion int64 StartVersion int64 LastWriteVersion int64 LastWriteEventID int64 LastReplicationInfo map[string]*replicationgenpb.ReplicationInfo } // ReplicationTaskInfoWrapper describes a replication task. ReplicationTaskInfoWrapper struct { *persistenceblobs.ReplicationTaskInfo } // Task is the generic interface for workflow tasks Task interface { GetType() int GetVersion() int64 SetVersion(version int64) GetTaskID() int64 SetTaskID(id int64) GetVisibilityTimestamp() time.Time SetVisibilityTimestamp(timestamp time.Time) } // TaskListKey is the struct used to identity TaskLists TaskListKey struct { NamespaceID primitives.UUID Name string TaskType tasklistpb.TaskListType } // ActivityTask identifies a transfer task for activity ActivityTask struct { VisibilityTimestamp time.Time TaskID int64 NamespaceID string TaskList string ScheduleID int64 Version int64 } // DecisionTask identifies a transfer task for decision DecisionTask struct { VisibilityTimestamp time.Time TaskID int64 NamespaceID string TaskList string ScheduleID int64 Version int64 RecordVisibility bool } // RecordWorkflowStartedTask identifites a transfer task for writing visibility open execution record RecordWorkflowStartedTask struct { VisibilityTimestamp time.Time TaskID int64 Version int64 } // ResetWorkflowTask identifites a transfer task to reset workflow ResetWorkflowTask struct { VisibilityTimestamp time.Time TaskID int64 Version int64 } // CloseExecutionTask identifies a transfer task for deletion of execution CloseExecutionTask struct { VisibilityTimestamp time.Time TaskID int64 Version int64 } // DeleteHistoryEventTask identifies a timer task for deletion of history events of completed execution. DeleteHistoryEventTask struct { VisibilityTimestamp time.Time TaskID int64 Version int64 } // DecisionTimeoutTask identifies a timeout task. DecisionTimeoutTask struct { VisibilityTimestamp time.Time TaskID int64 EventID int64 ScheduleAttempt int64 TimeoutType int Version int64 } // WorkflowTimeoutTask identifies a timeout task. WorkflowTimeoutTask struct { VisibilityTimestamp time.Time TaskID int64 Version int64 } // CancelExecutionTask identifies a transfer task for cancel of execution CancelExecutionTask struct { VisibilityTimestamp time.Time TaskID int64 TargetNamespaceID string TargetWorkflowID string TargetRunID string TargetChildWorkflowOnly bool InitiatedID int64 Version int64 } // SignalExecutionTask identifies a transfer task for signal execution SignalExecutionTask struct { VisibilityTimestamp time.Time TaskID int64 TargetNamespaceID string TargetWorkflowID string TargetRunID string TargetChildWorkflowOnly bool InitiatedID int64 Version int64 } // UpsertWorkflowSearchAttributesTask identifies a transfer task for upsert search attributes UpsertWorkflowSearchAttributesTask struct { VisibilityTimestamp time.Time TaskID int64 // this version is not used by task processing for validation, // instead, the version is used by elastic search Version int64 } // StartChildExecutionTask identifies a transfer task for starting child execution StartChildExecutionTask struct { VisibilityTimestamp time.Time TaskID int64 TargetNamespaceID string TargetWorkflowID string InitiatedID int64 Version int64 } // ActivityTimeoutTask identifies a timeout task. ActivityTimeoutTask struct { VisibilityTimestamp time.Time TaskID int64 TimeoutType int EventID int64 Attempt int64 Version int64 } // UserTimerTask identifies a timeout task. UserTimerTask struct { VisibilityTimestamp time.Time TaskID int64 EventID int64 Version int64 } // ActivityRetryTimerTask to schedule a retry task for activity ActivityRetryTimerTask struct { VisibilityTimestamp time.Time TaskID int64 EventID int64 Version int64 Attempt int32 } // WorkflowBackoffTimerTask to schedule first decision task for retried workflow WorkflowBackoffTimerTask struct { VisibilityTimestamp time.Time TaskID int64 EventID int64 // TODO this attribute is not used? Version int64 TimeoutType int // 0 for retry, 1 for cron. } // HistoryReplicationTask is the replication task created for shipping history replication events to other clusters HistoryReplicationTask struct { VisibilityTimestamp time.Time TaskID int64 FirstEventID int64 NextEventID int64 Version int64 BranchToken []byte NewRunBranchToken []byte // TODO when 2DC is deprecated remove these 2 attributes ResetWorkflow bool LastReplicationInfo map[string]*replicationgenpb.ReplicationInfo } // SyncActivityTask is the replication task created for shipping activity info to other clusters SyncActivityTask struct { VisibilityTimestamp time.Time TaskID int64 Version int64 ScheduledID int64 } // VersionHistoryItem contains the event id and the associated version VersionHistoryItem struct { EventID int64 Version int64 } // VersionHistory provides operations on version history VersionHistory struct { BranchToken []byte Items []*VersionHistoryItem } // VersionHistories contains a set of VersionHistory VersionHistories struct { CurrentVersionHistoryIndex int Histories []*VersionHistory } // WorkflowMutableState indicates workflow related state WorkflowMutableState struct { ActivityInfos map[int64]*ActivityInfo TimerInfos map[string]*persistenceblobs.TimerInfo ChildExecutionInfos map[int64]*ChildExecutionInfo RequestCancelInfos map[int64]*persistenceblobs.RequestCancelInfo SignalInfos map[int64]*persistenceblobs.SignalInfo SignalRequestedIDs map[string]struct{} ExecutionInfo *WorkflowExecutionInfo ExecutionStats *ExecutionStats ReplicationState *ReplicationState BufferedEvents []*eventpb.HistoryEvent VersionHistories *VersionHistories Checksum checksum.Checksum } // ActivityInfo details. ActivityInfo struct { Version int64 ScheduleID int64 ScheduledEventBatchID int64 ScheduledEvent *eventpb.HistoryEvent ScheduledTime time.Time StartedID int64 StartedEvent *eventpb.HistoryEvent StartedTime time.Time NamespaceID string ActivityID string RequestID string Details *commonpb.Payloads ScheduleToStartTimeout int32 ScheduleToCloseTimeout int32 StartToCloseTimeout int32 HeartbeatTimeout int32 CancelRequested bool CancelRequestID int64 LastHeartBeatUpdatedTime time.Time TimerTaskStatus int32 // For retry Attempt int32 StartedIdentity string TaskList string HasRetryPolicy bool InitialInterval int32 BackoffCoefficient float64 MaximumInterval int32 ExpirationTime time.Time MaximumAttempts int32 NonRetriableErrors []string LastFailureReason string LastWorkerIdentity string LastFailureDetails *commonpb.Payloads // Not written to database - This is used only for deduping heartbeat timer creation LastHeartbeatTimeoutVisibilityInSeconds int64 } // ChildExecutionInfo has details for pending child executions. ChildExecutionInfo struct { Version int64 InitiatedID int64 InitiatedEventBatchID int64 InitiatedEvent *eventpb.HistoryEvent StartedID int64 StartedWorkflowID string StartedRunID string StartedEvent *eventpb.HistoryEvent CreateRequestID string Namespace string WorkflowTypeName string ParentClosePolicy commonpb.ParentClosePolicy } // CreateShardRequest is used to create a shard in executions table CreateShardRequest struct { ShardInfo *persistenceblobs.ShardInfo } // GetShardRequest is used to get shard information GetShardRequest struct { ShardID int32 } // GetShardResponse is the response to GetShard GetShardResponse struct { ShardInfo *persistenceblobs.ShardInfo } // UpdateShardRequest is used to update shard information UpdateShardRequest struct { ShardInfo *persistenceblobs.ShardInfo PreviousRangeID int64 } // CreateWorkflowExecutionRequest is used to write a new workflow execution CreateWorkflowExecutionRequest struct { RangeID int64 Mode CreateWorkflowMode PreviousRunID string PreviousLastWriteVersion int64 NewWorkflowSnapshot WorkflowSnapshot } // CreateWorkflowExecutionResponse is the response to CreateWorkflowExecutionRequest CreateWorkflowExecutionResponse struct { } // GetWorkflowExecutionRequest is used to retrieve the info of a workflow execution GetWorkflowExecutionRequest struct { NamespaceID string Execution executionpb.WorkflowExecution } // GetWorkflowExecutionResponse is the response to GetworkflowExecutionRequest GetWorkflowExecutionResponse struct { State *WorkflowMutableState MutableStateStats *MutableStateStats } // GetCurrentExecutionRequest is used to retrieve the current RunId for an execution GetCurrentExecutionRequest struct { NamespaceID string WorkflowID string } // ListConcreteExecutionsRequest is request to ListConcreteExecutions ListConcreteExecutionsRequest struct { PageSize int PageToken []byte } // ListConcreteExecutionsResponse is response to ListConcreteExecutions ListConcreteExecutionsResponse struct { ExecutionInfos []*WorkflowExecutionInfo PageToken []byte } // GetCurrentExecutionResponse is the response to GetCurrentExecution GetCurrentExecutionResponse struct { StartRequestID string RunID string State int Status executionpb.WorkflowExecutionStatus LastWriteVersion int64 } // UpdateWorkflowExecutionRequest is used to update a workflow execution UpdateWorkflowExecutionRequest struct { RangeID int64 Mode UpdateWorkflowMode UpdateWorkflowMutation WorkflowMutation NewWorkflowSnapshot *WorkflowSnapshot Encoding common.EncodingType // optional binary encoding type } // ConflictResolveWorkflowExecutionRequest is used to reset workflow execution state for a single run ConflictResolveWorkflowExecutionRequest struct { RangeID int64 Mode ConflictResolveWorkflowMode // workflow to be resetted ResetWorkflowSnapshot WorkflowSnapshot // maybe new workflow NewWorkflowSnapshot *WorkflowSnapshot // current workflow CurrentWorkflowMutation *WorkflowMutation // TODO deprecate this once nDC migration is completed // basically should use CurrentWorkflowMutation instead CurrentWorkflowCAS *CurrentWorkflowCAS Encoding common.EncodingType // optional binary encoding type } // CurrentWorkflowCAS represent a compare and swap on current record // TODO deprecate this once nDC migration is completed CurrentWorkflowCAS struct { PrevRunID string PrevLastWriteVersion int64 PrevState int } // ResetWorkflowExecutionRequest is used to reset workflow execution state for current run and create new run ResetWorkflowExecutionRequest struct { RangeID int64 // for base run (we need to make sure the baseRun hasn't been deleted after forking) BaseRunID string BaseRunNextEventID int64 // for current workflow record CurrentRunID string CurrentRunNextEventID int64 // for current mutable state CurrentWorkflowMutation *WorkflowMutation // For new mutable state NewWorkflowSnapshot WorkflowSnapshot Encoding common.EncodingType // optional binary encoding type } // WorkflowEvents is used as generic workflow history events transaction container WorkflowEvents struct { NamespaceID string WorkflowID string RunID string BranchToken []byte Events []*eventpb.HistoryEvent } // WorkflowMutation is used as generic workflow execution state mutation WorkflowMutation struct { ExecutionInfo *WorkflowExecutionInfo ExecutionStats *ExecutionStats ReplicationState *ReplicationState VersionHistories *VersionHistories UpsertActivityInfos []*ActivityInfo DeleteActivityInfos []int64 UpsertTimerInfos []*persistenceblobs.TimerInfo DeleteTimerInfos []string UpsertChildExecutionInfos []*ChildExecutionInfo DeleteChildExecutionInfo *int64 UpsertRequestCancelInfos []*persistenceblobs.RequestCancelInfo DeleteRequestCancelInfo *int64 UpsertSignalInfos []*persistenceblobs.SignalInfo DeleteSignalInfo *int64 UpsertSignalRequestedIDs []string DeleteSignalRequestedID string NewBufferedEvents []*eventpb.HistoryEvent ClearBufferedEvents bool TransferTasks []Task ReplicationTasks []Task TimerTasks []Task Condition int64 Checksum checksum.Checksum } // WorkflowSnapshot is used as generic workflow execution state snapshot WorkflowSnapshot struct { ExecutionInfo *WorkflowExecutionInfo ExecutionStats *ExecutionStats ReplicationState *ReplicationState VersionHistories *VersionHistories ActivityInfos []*ActivityInfo TimerInfos []*persistenceblobs.TimerInfo ChildExecutionInfos []*ChildExecutionInfo RequestCancelInfos []*persistenceblobs.RequestCancelInfo SignalInfos []*persistenceblobs.SignalInfo SignalRequestedIDs []string TransferTasks []Task ReplicationTasks []Task TimerTasks []Task Condition int64 Checksum checksum.Checksum } // DeleteWorkflowExecutionRequest is used to delete a workflow execution DeleteWorkflowExecutionRequest struct { NamespaceID string WorkflowID string RunID string } // DeleteCurrentWorkflowExecutionRequest is used to delete the current workflow execution DeleteCurrentWorkflowExecutionRequest struct { NamespaceID string WorkflowID string RunID string } // GetTransferTasksRequest is used to read tasks from the transfer task queue GetTransferTasksRequest struct { ReadLevel int64 MaxReadLevel int64 BatchSize int NextPageToken []byte } // GetTransferTasksResponse is the response to GetTransferTasksRequest GetTransferTasksResponse struct { Tasks []*persistenceblobs.TransferTaskInfo NextPageToken []byte } // GetReplicationTasksRequest is used to read tasks from the replication task queue GetReplicationTasksRequest struct { ReadLevel int64 MaxReadLevel int64 BatchSize int NextPageToken []byte } // GetReplicationTasksResponse is the response to GetReplicationTask GetReplicationTasksResponse struct { Tasks []*persistenceblobs.ReplicationTaskInfo NextPageToken []byte } // CompleteTransferTaskRequest is used to complete a task in the transfer task queue CompleteTransferTaskRequest struct { TaskID int64 } // RangeCompleteTransferTaskRequest is used to complete a range of tasks in the transfer task queue RangeCompleteTransferTaskRequest struct { ExclusiveBeginTaskID int64 InclusiveEndTaskID int64 } // CompleteReplicationTaskRequest is used to complete a task in the replication task queue CompleteReplicationTaskRequest struct { TaskID int64 } // RangeCompleteReplicationTaskRequest is used to complete a range of task in the replication task queue RangeCompleteReplicationTaskRequest struct { InclusiveEndTaskID int64 } // PutReplicationTaskToDLQRequest is used to put a replication task to dlq PutReplicationTaskToDLQRequest struct { SourceClusterName string TaskInfo *persistenceblobs.ReplicationTaskInfo } // GetReplicationTasksFromDLQRequest is used to get replication tasks from dlq GetReplicationTasksFromDLQRequest struct { SourceClusterName string GetReplicationTasksRequest } // DeleteReplicationTaskFromDLQRequest is used to delete replication task from DLQ DeleteReplicationTaskFromDLQRequest struct { SourceClusterName string TaskID int64 } //RangeDeleteReplicationTaskFromDLQRequest is used to delete replication tasks from DLQ RangeDeleteReplicationTaskFromDLQRequest struct { SourceClusterName string ExclusiveBeginTaskID int64 InclusiveEndTaskID int64 } // GetReplicationTasksFromDLQResponse is the response for GetReplicationTasksFromDLQ GetReplicationTasksFromDLQResponse = GetReplicationTasksResponse // RangeCompleteTimerTaskRequest is used to complete a range of tasks in the timer task queue RangeCompleteTimerTaskRequest struct { InclusiveBeginTimestamp time.Time ExclusiveEndTimestamp time.Time } // CompleteTimerTaskRequest is used to complete a task in the timer task queue CompleteTimerTaskRequest struct { VisibilityTimestamp time.Time TaskID int64 } // LeaseTaskListRequest is used to request lease of a task list LeaseTaskListRequest struct { NamespaceID primitives.UUID TaskList string TaskType tasklistpb.TaskListType TaskListKind tasklistpb.TaskListKind RangeID int64 } // LeaseTaskListResponse is response to LeaseTaskListRequest LeaseTaskListResponse struct { TaskListInfo *PersistedTaskListInfo } // UpdateTaskListRequest is used to update task list implementation information UpdateTaskListRequest struct { RangeID int64 TaskListInfo *persistenceblobs.TaskListInfo } // UpdateTaskListResponse is the response to UpdateTaskList UpdateTaskListResponse struct { } // ListTaskListRequest contains the request params needed to invoke ListTaskList API ListTaskListRequest struct { PageSize int PageToken []byte } // ListTaskListResponse is the response from ListTaskList API ListTaskListResponse struct { Items []*PersistedTaskListInfo NextPageToken []byte } // DeleteTaskListRequest contains the request params needed to invoke DeleteTaskList API DeleteTaskListRequest struct { TaskList *TaskListKey RangeID int64 } // CreateTasksRequest is used to create a new task for a workflow execution CreateTasksRequest struct { TaskListInfo *PersistedTaskListInfo Tasks []*persistenceblobs.AllocatedTaskInfo } // CreateTasksResponse is the response to CreateTasksRequest CreateTasksResponse struct { } PersistedTaskListInfo struct { Data *persistenceblobs.TaskListInfo RangeID int64 } // GetTasksRequest is used to retrieve tasks of a task list GetTasksRequest struct { NamespaceID primitives.UUID TaskList string TaskType tasklistpb.TaskListType ReadLevel int64 // range exclusive MaxReadLevel *int64 // optional: range inclusive when specified BatchSize int } // GetTasksResponse is the response to GetTasksRequests GetTasksResponse struct { Tasks []*persistenceblobs.AllocatedTaskInfo } // CompleteTaskRequest is used to complete a task CompleteTaskRequest struct { TaskList *TaskListKey TaskID int64 } // CompleteTasksLessThanRequest contains the request params needed to invoke CompleteTasksLessThan API CompleteTasksLessThanRequest struct { NamespaceID primitives.UUID TaskListName string TaskType tasklistpb.TaskListType TaskID int64 // Tasks less than or equal to this ID will be completed Limit int // Limit on the max number of tasks that can be completed. Required param } // GetTimerIndexTasksRequest is the request for GetTimerIndexTasks // TODO: replace this with an iterator that can configure min and max index. GetTimerIndexTasksRequest struct { MinTimestamp time.Time MaxTimestamp time.Time BatchSize int NextPageToken []byte } // GetTimerIndexTasksResponse is the response for GetTimerIndexTasks GetTimerIndexTasksResponse struct { Timers []*persistenceblobs.TimerTaskInfo NextPageToken []byte } // CreateNamespaceRequest is used to create the namespace CreateNamespaceRequest struct { Namespace *persistenceblobs.NamespaceDetail IsGlobalNamespace bool } // CreateNamespaceResponse is the response for CreateNamespace CreateNamespaceResponse struct { ID primitives.UUID } // GetNamespaceRequest is used to read namespace GetNamespaceRequest struct { ID primitives.UUID Name string } // GetNamespaceResponse is the response for GetNamespace GetNamespaceResponse struct { Namespace *persistenceblobs.NamespaceDetail IsGlobalNamespace bool NotificationVersion int64 } // UpdateNamespaceRequest is used to update namespace UpdateNamespaceRequest struct { Namespace *persistenceblobs.NamespaceDetail NotificationVersion int64 } // DeleteNamespaceRequest is used to delete namespace entry from namespaces table DeleteNamespaceRequest struct { ID primitives.UUID } // DeleteNamespaceByNameRequest is used to delete namespace entry from namespaces_by_name table DeleteNamespaceByNameRequest struct { Name string } // ListNamespacesRequest is used to list namespaces ListNamespacesRequest struct { PageSize int NextPageToken []byte } // ListNamespacesResponse is the response for GetNamespace ListNamespacesResponse struct { Namespaces []*GetNamespaceResponse NextPageToken []byte } // GetMetadataResponse is the response for GetMetadata GetMetadataResponse struct { NotificationVersion int64 } // MutableStateStats is the size stats for MutableState MutableStateStats struct { // Total size of mutable state MutableStateSize int // Breakdown of size into more granular stats ExecutionInfoSize int ActivityInfoSize int TimerInfoSize int ChildInfoSize int SignalInfoSize int BufferedEventsSize int // Item count for various information captured within mutable state ActivityInfoCount int TimerInfoCount int ChildInfoCount int SignalInfoCount int RequestCancelInfoCount int BufferedEventsCount int } // MutableStateUpdateSessionStats is size stats for mutableState updating session MutableStateUpdateSessionStats struct { MutableStateSize int // Total size of mutable state update // Breakdown of mutable state size update for more granular stats ExecutionInfoSize int ActivityInfoSize int TimerInfoSize int ChildInfoSize int SignalInfoSize int BufferedEventsSize int // Item counts in this session update ActivityInfoCount int TimerInfoCount int ChildInfoCount int SignalInfoCount int RequestCancelInfoCount int // Deleted item counts in this session update DeleteActivityInfoCount int DeleteTimerInfoCount int DeleteChildInfoCount int DeleteSignalInfoCount int DeleteRequestCancelInfoCount int } // UpdateWorkflowExecutionResponse is response for UpdateWorkflowExecutionRequest UpdateWorkflowExecutionResponse struct { MutableStateUpdateSessionStats *MutableStateUpdateSessionStats } // AppendHistoryNodesRequest is used to append a batch of history nodes AppendHistoryNodesRequest struct { // true if this is the first append request to the branch IsNewBranch bool // the info for clean up data in background Info string // The branch to be appended BranchToken []byte // The batch of events to be appended. The first eventID will become the nodeID of this batch Events []*eventpb.HistoryEvent // requested TransactionID for this write operation. For the same eventID, the node with larger TransactionID always wins TransactionID int64 // optional binary encoding type Encoding common.EncodingType // The shard to get history node data ShardID *int } // AppendHistoryNodesResponse is a response to AppendHistoryNodesRequest AppendHistoryNodesResponse struct { // the size of the event data that has been appended Size int } // ReadHistoryBranchRequest is used to read a history branch ReadHistoryBranchRequest struct { // The branch to be read BranchToken []byte // Get the history nodes from MinEventID. Inclusive. MinEventID int64 // Get the history nodes upto MaxEventID. Exclusive. MaxEventID int64 // Maximum number of batches of events per page. Not that number of events in a batch >=1, it is not number of events per page. // However for a single page, it is also possible that the returned events is less than PageSize (event zero events) due to stale events. PageSize int // Token to continue reading next page of history append transactions. Pass in empty slice for first page NextPageToken []byte // The shard to get history branch data ShardID *int } // ReadHistoryBranchResponse is the response to ReadHistoryBranchRequest ReadHistoryBranchResponse struct { // History events HistoryEvents []*eventpb.HistoryEvent // Token to read next page if there are more events beyond page size. // Use this to set NextPageToken on ReadHistoryBranchRequest to read the next page. // Empty means we have reached the last page, not need to continue NextPageToken []byte // Size of history read from store Size int // the first_event_id of last loaded batch LastFirstEventID int64 } // ReadHistoryBranchByBatchResponse is the response to ReadHistoryBranchRequest ReadHistoryBranchByBatchResponse struct { // History events by batch History []*eventpb.History // Token to read next page if there are more events beyond page size. // Use this to set NextPageToken on ReadHistoryBranchRequest to read the next page. // Empty means we have reached the last page, not need to continue NextPageToken []byte // Size of history read from store Size int // the first_event_id of last loaded batch LastFirstEventID int64 } // ReadRawHistoryBranchResponse is the response to ReadHistoryBranchRequest ReadRawHistoryBranchResponse struct { // HistoryEventBlobs history event blobs HistoryEventBlobs []*serialization.DataBlob // Token to read next page if there are more events beyond page size. // Use this to set NextPageToken on ReadHistoryBranchRequest to read the next page. // Empty means we have reached the last page, not need to continue NextPageToken []byte // Size of history read from store Size int } // ForkHistoryBranchRequest is used to fork a history branch ForkHistoryBranchRequest struct { // The base branch to fork from ForkBranchToken []byte // The nodeID to fork from, the new branch will start from ( inclusive ), the base branch will stop at(exclusive) // Application must provide a void forking nodeID, it must be a valid nodeID in that branch. A valid nodeID is the firstEventID of a valid batch of events. // And ForkNodeID > 1 because forking from 1 doesn't make any sense. ForkNodeID int64 // the info for clean up data in background Info string // The shard to get history branch data ShardID *int } // ForkHistoryBranchResponse is the response to ForkHistoryBranchRequest ForkHistoryBranchResponse struct { // branchToken to represent the new branch NewBranchToken []byte } // CompleteForkBranchRequest is used to complete forking CompleteForkBranchRequest struct { // the new branch returned from ForkHistoryBranchRequest BranchToken []byte // true means the fork is success, will update the flag, otherwise will delete the new branch Success bool // The shard to update history branch data ShardID *int } // DeleteHistoryBranchRequest is used to remove a history branch DeleteHistoryBranchRequest struct { // branch to be deleted BranchToken []byte // The shard to delete history branch data ShardID *int } // GetHistoryTreeRequest is used to retrieve branch info of a history tree GetHistoryTreeRequest struct { // A UUID of a tree TreeID primitives.UUID // Get data from this shard ShardID *int // optional: can provide treeID via branchToken if treeID is empty BranchToken []byte } // HistoryBranchDetail contains detailed information of a branch HistoryBranchDetail struct { TreeID string BranchID string ForkTime time.Time Info string } // GetHistoryTreeResponse is a response to GetHistoryTreeRequest GetHistoryTreeResponse struct { // all branches of a tree Branches []*persistenceblobs.HistoryBranch } // GetAllHistoryTreeBranchesRequest is a request of GetAllHistoryTreeBranches GetAllHistoryTreeBranchesRequest struct { // pagination token NextPageToken []byte // maximum number of branches returned per page PageSize int } // GetAllHistoryTreeBranchesResponse is a response to GetAllHistoryTreeBranches GetAllHistoryTreeBranchesResponse struct { // pagination token NextPageToken []byte // all branches of all trees Branches []HistoryBranchDetail } // InitializeImmutableClusterMetadataRequest is a request of InitializeImmutableClusterMetadata // These values can only be set a single time upon cluster initialization. InitializeImmutableClusterMetadataRequest struct { persistenceblobs.ImmutableClusterMetadata } // InitializeImmutableClusterMetadataResponse is a request of InitializeImmutableClusterMetadata InitializeImmutableClusterMetadataResponse struct { PersistedImmutableData persistenceblobs.ImmutableClusterMetadata RequestApplied bool } // GetImmutableClusterMetadataResponse is the response to GetImmutableClusterMetadata // These values are set a single time upon cluster initialization. GetImmutableClusterMetadataResponse struct { persistenceblobs.ImmutableClusterMetadata } // GetClusterMembersRequest is the response to GetClusterMembers GetClusterMembersRequest struct { LastHeartbeatWithin time.Duration RPCAddressEquals net.IP HostIDEquals uuid.UUID RoleEquals ServiceType SessionStartedAfter time.Time NextPageToken []byte PageSize int } // GetClusterMembersResponse is the response to GetClusterMembers GetClusterMembersResponse struct { ActiveMembers []*ClusterMember NextPageToken []byte } // ClusterMember is used as a response to GetClusterMembers ClusterMember struct { Role ServiceType HostID uuid.UUID RPCAddress net.IP RPCPort uint16 SessionStart time.Time LastHeartbeat time.Time RecordExpiry time.Time } // UpsertClusterMembershipRequest is the request to UpsertClusterMembership UpsertClusterMembershipRequest struct { Role ServiceType HostID uuid.UUID RPCAddress net.IP RPCPort uint16 SessionStart time.Time RecordExpiry time.Duration } // PruneClusterMembershipRequest is the request to PruneClusterMembership PruneClusterMembershipRequest struct { MaxRecordsPruned int } // Closeable is an interface for any entity that supports a close operation to release resources Closeable interface { Close() } // ShardManager is used to manage all shards ShardManager interface { Closeable GetName() string CreateShard(request *CreateShardRequest) error GetShard(request *GetShardRequest) (*GetShardResponse, error) UpdateShard(request *UpdateShardRequest) error } // ExecutionManager is used to manage workflow executions ExecutionManager interface { Closeable GetName() string GetShardID() int CreateWorkflowExecution(request *CreateWorkflowExecutionRequest) (*CreateWorkflowExecutionResponse, error) GetWorkflowExecution(request *GetWorkflowExecutionRequest) (*GetWorkflowExecutionResponse, error) UpdateWorkflowExecution(request *UpdateWorkflowExecutionRequest) (*UpdateWorkflowExecutionResponse, error) ConflictResolveWorkflowExecution(request *ConflictResolveWorkflowExecutionRequest) error ResetWorkflowExecution(request *ResetWorkflowExecutionRequest) error DeleteWorkflowExecution(request *DeleteWorkflowExecutionRequest) error DeleteCurrentWorkflowExecution(request *DeleteCurrentWorkflowExecutionRequest) error GetCurrentExecution(request *GetCurrentExecutionRequest) (*GetCurrentExecutionResponse, error) // Transfer task related methods GetTransferTasks(request *GetTransferTasksRequest) (*GetTransferTasksResponse, error) CompleteTransferTask(request *CompleteTransferTaskRequest) error RangeCompleteTransferTask(request *RangeCompleteTransferTaskRequest) error // Replication task related methods GetReplicationTasks(request *GetReplicationTasksRequest) (*GetReplicationTasksResponse, error) CompleteReplicationTask(request *CompleteReplicationTaskRequest) error RangeCompleteReplicationTask(request *RangeCompleteReplicationTaskRequest) error PutReplicationTaskToDLQ(request *PutReplicationTaskToDLQRequest) error GetReplicationTasksFromDLQ(request *GetReplicationTasksFromDLQRequest) (*GetReplicationTasksFromDLQResponse, error) DeleteReplicationTaskFromDLQ(request *DeleteReplicationTaskFromDLQRequest) error RangeDeleteReplicationTaskFromDLQ(request *RangeDeleteReplicationTaskFromDLQRequest) error // Timer related methods. GetTimerIndexTasks(request *GetTimerIndexTasksRequest) (*GetTimerIndexTasksResponse, error) CompleteTimerTask(request *CompleteTimerTaskRequest) error RangeCompleteTimerTask(request *RangeCompleteTimerTaskRequest) error // Scan operations ListConcreteExecutions(request *ListConcreteExecutionsRequest) (*ListConcreteExecutionsResponse, error) } // ExecutionManagerFactory creates an instance of ExecutionManager for a given shard ExecutionManagerFactory interface { Closeable NewExecutionManager(shardID int) (ExecutionManager, error) } // TaskManager is used to manage tasks TaskManager interface { Closeable GetName() string LeaseTaskList(request *LeaseTaskListRequest) (*LeaseTaskListResponse, error) UpdateTaskList(request *UpdateTaskListRequest) (*UpdateTaskListResponse, error) ListTaskList(request *ListTaskListRequest) (*ListTaskListResponse, error) DeleteTaskList(request *DeleteTaskListRequest) error CreateTasks(request *CreateTasksRequest) (*CreateTasksResponse, error) GetTasks(request *GetTasksRequest) (*GetTasksResponse, error) CompleteTask(request *CompleteTaskRequest) error // CompleteTasksLessThan completes tasks less than or equal to the given task id // This API takes a limit parameter which specifies the count of maxRows that // can be deleted. This parameter may be ignored by the underlying storage, but // its mandatory to specify it. On success this method returns the number of rows // actually deleted. If the underlying storage doesn't support "limit", all rows // less than or equal to taskID will be deleted. // On success, this method returns: // - number of rows actually deleted, if limit is honored // - UnknownNumRowsDeleted, when all rows below value are deleted CompleteTasksLessThan(request *CompleteTasksLessThanRequest) (int, error) } // HistoryManager is used to manager workflow history events HistoryManager interface { Closeable GetName() string // The below are history V2 APIs // V2 regards history events growing as a tree, decoupled from workflow concepts // For Temporal, treeID is new runID, except for fork(reset), treeID will be the runID that it forks from. // AppendHistoryNodes add(or override) a batch of nodes to a history branch AppendHistoryNodes(request *AppendHistoryNodesRequest) (*AppendHistoryNodesResponse, error) // ReadHistoryBranch returns history node data for a branch ReadHistoryBranch(request *ReadHistoryBranchRequest) (*ReadHistoryBranchResponse, error) // ReadHistoryBranchByBatch returns history node data for a branch ByBatch ReadHistoryBranchByBatch(request *ReadHistoryBranchRequest) (*ReadHistoryBranchByBatchResponse, error) // ReadRawHistoryBranch returns history node raw data for a branch ByBatch // NOTE: this API should only be used by 3+DC ReadRawHistoryBranch(request *ReadHistoryBranchRequest) (*ReadRawHistoryBranchResponse, error) // ForkHistoryBranch forks a new branch from a old branch ForkHistoryBranch(request *ForkHistoryBranchRequest) (*ForkHistoryBranchResponse, error) // DeleteHistoryBranch removes a branch // If this is the last branch to delete, it will also remove the root node DeleteHistoryBranch(request *DeleteHistoryBranchRequest) error // GetHistoryTree returns all branch information of a tree GetHistoryTree(request *GetHistoryTreeRequest) (*GetHistoryTreeResponse, error) // GetAllHistoryTreeBranches returns all branches of all trees GetAllHistoryTreeBranches(request *GetAllHistoryTreeBranchesRequest) (*GetAllHistoryTreeBranchesResponse, error) } // MetadataManager is used to manage metadata CRUD for namespace entities MetadataManager interface { Closeable GetName() string CreateNamespace(request *CreateNamespaceRequest) (*CreateNamespaceResponse, error) GetNamespace(request *GetNamespaceRequest) (*GetNamespaceResponse, error) UpdateNamespace(request *UpdateNamespaceRequest) error DeleteNamespace(request *DeleteNamespaceRequest) error DeleteNamespaceByName(request *DeleteNamespaceByNameRequest) error ListNamespaces(request *ListNamespacesRequest) (*ListNamespacesResponse, error) GetMetadata() (*GetMetadataResponse, error) InitializeSystemNamespaces(currentClusterName string) error } // ClusterMetadataManager is used to manage cluster-wide metadata and configuration ClusterMetadataManager interface { Closeable GetName() string InitializeImmutableClusterMetadata(request *InitializeImmutableClusterMetadataRequest) (*InitializeImmutableClusterMetadataResponse, error) GetImmutableClusterMetadata() (*GetImmutableClusterMetadataResponse, error) GetClusterMembers(request *GetClusterMembersRequest) (*GetClusterMembersResponse, error) UpsertClusterMembership(request *UpsertClusterMembershipRequest) error PruneClusterMembership(request *PruneClusterMembershipRequest) error } ) func (e *InvalidPersistenceRequestError) Error() string { return e.Msg } func (e *CurrentWorkflowConditionFailedError) Error() string { return e.Msg } func (e *ConditionFailedError) Error() string { return e.Msg } func (e *ShardAlreadyExistError) Error() string { return e.Msg } func (e *ShardOwnershipLostError) Error() string { return e.Msg } func (e *WorkflowExecutionAlreadyStartedError) Error() string { return e.Msg } func (e *TimeoutError) Error() string { return e.Msg } func (e *TransactionSizeLimitError) Error() string { return e.Msg } // IsTimeoutError check whether error is TimeoutError func IsTimeoutError(err error) bool { _, ok := err.(*TimeoutError) return ok } // GetType returns the type of the activity task func (a *ActivityTask) GetType() int { return TransferTaskTypeActivityTask } // GetVersion returns the version of the activity task func (a *ActivityTask) GetVersion() int64 { return a.Version } // SetVersion returns the version of the activity task func (a *ActivityTask) SetVersion(version int64) { a.Version = version } // GetTaskID returns the sequence ID of the activity task func (a *ActivityTask) GetTaskID() int64 { return a.TaskID } // SetTaskID sets the sequence ID of the activity task func (a *ActivityTask) SetTaskID(id int64) { a.TaskID = id } // GetVisibilityTimestamp get the visibility timestamp func (a *ActivityTask) GetVisibilityTimestamp() time.Time { return a.VisibilityTimestamp } // SetVisibilityTimestamp set the visibility timestamp func (a *ActivityTask) SetVisibilityTimestamp(timestamp time.Time) { a.VisibilityTimestamp = timestamp } // GetType returns the type of the decision task func (d *DecisionTask) GetType() int { return TransferTaskTypeDecisionTask } // GetVersion returns the version of the decision task func (d *DecisionTask) GetVersion() int64 { return d.Version } // SetVersion returns the version of the decision task func (d *DecisionTask) SetVersion(version int64) { d.Version = version } // GetTaskID returns the sequence ID of the decision task. func (d *DecisionTask) GetTaskID() int64 { return d.TaskID } // SetTaskID sets the sequence ID of the decision task func (d *DecisionTask) SetTaskID(id int64) { d.TaskID = id } // GetVisibilityTimestamp get the visibility timestamp func (d ReplicationTaskInfoWrapper) GetVisibilityTimestamp() *types.Timestamp { return &types.Timestamp{} } // GetVisibilityTimestamp get the visibility timestamp func (d *DecisionTask) GetVisibilityTimestamp() time.Time { return d.VisibilityTimestamp } // SetVisibilityTimestamp set the visibility timestamp func (d *DecisionTask) SetVisibilityTimestamp(timestamp time.Time) { d.VisibilityTimestamp = timestamp } // GetType returns the type of the record workflow started task func (a *RecordWorkflowStartedTask) GetType() int { return TransferTaskTypeRecordWorkflowStarted } // GetVersion returns the version of the record workflow started task func (a *RecordWorkflowStartedTask) GetVersion() int64 { return a.Version } // SetVersion returns the version of the record workflow started task func (a *RecordWorkflowStartedTask) SetVersion(version int64) { a.Version = version } // GetTaskID returns the sequence ID of the record workflow started task func (a *RecordWorkflowStartedTask) GetTaskID() int64 { return a.TaskID } // SetTaskID sets the sequence ID of the record workflow started task func (a *RecordWorkflowStartedTask) SetTaskID(id int64) { a.TaskID = id } // GetVisibilityTimestamp get the visibility timestamp func (a *RecordWorkflowStartedTask) GetVisibilityTimestamp() time.Time { return a.VisibilityTimestamp } // SetVisibilityTimestamp set the visibility timestamp func (a *RecordWorkflowStartedTask) SetVisibilityTimestamp(timestamp time.Time) { a.VisibilityTimestamp = timestamp } // GetType returns the type of the ResetWorkflowTask func (a *ResetWorkflowTask) GetType() int { return TransferTaskTypeResetWorkflow } // GetVersion returns the version of the ResetWorkflowTask func (a *ResetWorkflowTask) GetVersion() int64 { return a.Version } // SetVersion returns the version of the ResetWorkflowTask func (a *ResetWorkflowTask) SetVersion(version int64) { a.Version = version } // GetTaskID returns the sequence ID of the ResetWorkflowTask func (a *ResetWorkflowTask) GetTaskID() int64 { return a.TaskID } // SetTaskID sets the sequence ID of the ResetWorkflowTask func (a *ResetWorkflowTask) SetTaskID(id int64) { a.TaskID = id } // GetVisibilityTimestamp get the visibility timestamp func (a *ResetWorkflowTask) GetVisibilityTimestamp() time.Time { return a.VisibilityTimestamp } // SetVisibilityTimestamp set the visibility timestamp func (a *ResetWorkflowTask) SetVisibilityTimestamp(timestamp time.Time) { a.VisibilityTimestamp = timestamp } // GetType returns the type of the close execution task func (a *CloseExecutionTask) GetType() int { return TransferTaskTypeCloseExecution } // GetVersion returns the version of the close execution task func (a *CloseExecutionTask) GetVersion() int64 { return a.Version } // SetVersion returns the version of the close execution task func (a *CloseExecutionTask) SetVersion(version int64) { a.Version = version } // GetTaskID returns the sequence ID of the close execution task func (a *CloseExecutionTask) GetTaskID() int64 { return a.TaskID } // SetTaskID sets the sequence ID of the close execution task func (a *CloseExecutionTask) SetTaskID(id int64) { a.TaskID = id } // GetVisibilityTimestamp get the visibility timestamp func (a *CloseExecutionTask) GetVisibilityTimestamp() time.Time { return a.VisibilityTimestamp } // SetVisibilityTimestamp set the visibility timestamp func (a *CloseExecutionTask) SetVisibilityTimestamp(timestamp time.Time) { a.VisibilityTimestamp = timestamp } // GetType returns the type of the delete execution task func (a *DeleteHistoryEventTask) GetType() int { return TaskTypeDeleteHistoryEvent } // GetVersion returns the version of the delete execution task func (a *DeleteHistoryEventTask) GetVersion() int64 { return a.Version } // SetVersion returns the version of the delete execution task func (a *DeleteHistoryEventTask) SetVersion(version int64) { a.Version = version } // GetTaskID returns the sequence ID of the delete execution task func (a *DeleteHistoryEventTask) GetTaskID() int64 { return a.TaskID } // SetTaskID sets the sequence ID of the delete execution task func (a *DeleteHistoryEventTask) SetTaskID(id int64) { a.TaskID = id } // GetVisibilityTimestamp get the visibility timestamp func (a *DeleteHistoryEventTask) GetVisibilityTimestamp() time.Time { return a.VisibilityTimestamp } // SetVisibilityTimestamp set the visibility timestamp func (a *DeleteHistoryEventTask) SetVisibilityTimestamp(timestamp time.Time) { a.VisibilityTimestamp = timestamp } // GetType returns the type of the timer task func (d *DecisionTimeoutTask) GetType() int { return TaskTypeDecisionTimeout } // GetVersion returns the version of the timer task func (d *DecisionTimeoutTask) GetVersion() int64 { return d.Version } // SetVersion returns the version of the timer task func (d *DecisionTimeoutTask) SetVersion(version int64) { d.Version = version } // GetTaskID returns the sequence ID. func (d *DecisionTimeoutTask) GetTaskID() int64 { return d.TaskID } // SetTaskID sets the sequence ID. func (d *DecisionTimeoutTask) SetTaskID(id int64) { d.TaskID = id } // GetVisibilityTimestamp gets the visibility time stamp func (d *DecisionTimeoutTask) GetVisibilityTimestamp() time.Time { return d.VisibilityTimestamp } // SetVisibilityTimestamp gets the visibility time stamp func (d *DecisionTimeoutTask) SetVisibilityTimestamp(t time.Time) { d.VisibilityTimestamp = t } // GetType returns the type of the timer task func (a *ActivityTimeoutTask) GetType() int { return TaskTypeActivityTimeout } // GetVersion returns the version of the timer task func (a *ActivityTimeoutTask) GetVersion() int64 { return a.Version } // SetVersion returns the version of the timer task func (a *ActivityTimeoutTask) SetVersion(version int64) { a.Version = version } // GetTaskID returns the sequence ID. func (a *ActivityTimeoutTask) GetTaskID() int64 { return a.TaskID } // SetTaskID sets the sequence ID. func (a *ActivityTimeoutTask) SetTaskID(id int64) { a.TaskID = id } // GetVisibilityTimestamp gets the visibility time stamp func (a *ActivityTimeoutTask) GetVisibilityTimestamp() time.Time { return a.VisibilityTimestamp } // SetVisibilityTimestamp gets the visibility time stamp func (a *ActivityTimeoutTask) SetVisibilityTimestamp(t time.Time) { a.VisibilityTimestamp = t } // GetType returns the type of the timer task func (u *UserTimerTask) GetType() int { return TaskTypeUserTimer } // GetVersion returns the version of the timer task func (u *UserTimerTask) GetVersion() int64 { return u.Version } // SetVersion returns the version of the timer task func (u *UserTimerTask) SetVersion(version int64) { u.Version = version } // GetTaskID returns the sequence ID of the timer task. func (u *UserTimerTask) GetTaskID() int64 { return u.TaskID } // SetTaskID sets the sequence ID of the timer task. func (u *UserTimerTask) SetTaskID(id int64) { u.TaskID = id } // GetVisibilityTimestamp gets the visibility time stamp func (u *UserTimerTask) GetVisibilityTimestamp() time.Time { return u.VisibilityTimestamp } // SetVisibilityTimestamp gets the visibility time stamp func (u *UserTimerTask) SetVisibilityTimestamp(t time.Time) { u.VisibilityTimestamp = t } // GetType returns the type of the retry timer task func (r *ActivityRetryTimerTask) GetType() int { return TaskTypeActivityRetryTimer } // GetVersion returns the version of the retry timer task func (r *ActivityRetryTimerTask) GetVersion() int64 { return r.Version } // SetVersion returns the version of the retry timer task func (r *ActivityRetryTimerTask) SetVersion(version int64) { r.Version = version } // GetTaskID returns the sequence ID. func (r *ActivityRetryTimerTask) GetTaskID() int64 { return r.TaskID } // SetTaskID sets the sequence ID. func (r *ActivityRetryTimerTask) SetTaskID(id int64) { r.TaskID = id } // GetVisibilityTimestamp gets the visibility time stamp func (r *ActivityRetryTimerTask) GetVisibilityTimestamp() time.Time { return r.VisibilityTimestamp } // SetVisibilityTimestamp gets the visibility time stamp func (r *ActivityRetryTimerTask) SetVisibilityTimestamp(t time.Time) { r.VisibilityTimestamp = t } // GetType returns the type of the retry timer task func (r *WorkflowBackoffTimerTask) GetType() int { return TaskTypeWorkflowBackoffTimer } // GetVersion returns the version of the retry timer task func (r *WorkflowBackoffTimerTask) GetVersion() int64 { return r.Version } // SetVersion returns the version of the retry timer task func (r *WorkflowBackoffTimerTask) SetVersion(version int64) { r.Version = version } // GetTaskID returns the sequence ID. func (r *WorkflowBackoffTimerTask) GetTaskID() int64 { return r.TaskID } // SetTaskID sets the sequence ID. func (r *WorkflowBackoffTimerTask) SetTaskID(id int64) { r.TaskID = id } // GetVisibilityTimestamp gets the visibility time stamp func (r *WorkflowBackoffTimerTask) GetVisibilityTimestamp() time.Time { return r.VisibilityTimestamp } // SetVisibilityTimestamp gets the visibility time stamp func (r *WorkflowBackoffTimerTask) SetVisibilityTimestamp(t time.Time) { r.VisibilityTimestamp = t } // GetType returns the type of the timeout task. func (u *WorkflowTimeoutTask) GetType() int { return TaskTypeWorkflowRunTimeout } // GetVersion returns the version of the timeout task func (u *WorkflowTimeoutTask) GetVersion() int64 { return u.Version } // SetVersion returns the version of the timeout task func (u *WorkflowTimeoutTask) SetVersion(version int64) { u.Version = version } // GetTaskID returns the sequence ID of the cancel transfer task. func (u *WorkflowTimeoutTask) GetTaskID() int64 { return u.TaskID } // SetTaskID sets the sequence ID of the cancel transfer task. func (u *WorkflowTimeoutTask) SetTaskID(id int64) { u.TaskID = id } // GetVisibilityTimestamp gets the visibility time stamp func (u *WorkflowTimeoutTask) GetVisibilityTimestamp() time.Time { return u.VisibilityTimestamp } // SetVisibilityTimestamp gets the visibility time stamp func (u *WorkflowTimeoutTask) SetVisibilityTimestamp(t time.Time) { u.VisibilityTimestamp = t } // GetType returns the type of the cancel transfer task func (u *CancelExecutionTask) GetType() int { return TransferTaskTypeCancelExecution } // GetVersion returns the version of the cancel transfer task func (u *CancelExecutionTask) GetVersion() int64 { return u.Version } // SetVersion returns the version of the cancel transfer task func (u *CancelExecutionTask) SetVersion(version int64) { u.Version = version } // GetTaskID returns the sequence ID of the cancel transfer task. func (u *CancelExecutionTask) GetTaskID() int64 { return u.TaskID } // SetTaskID sets the sequence ID of the cancel transfer task. func (u *CancelExecutionTask) SetTaskID(id int64) { u.TaskID = id } // GetVisibilityTimestamp get the visibility timestamp func (u *CancelExecutionTask) GetVisibilityTimestamp() time.Time { return u.VisibilityTimestamp } // SetVisibilityTimestamp set the visibility timestamp func (u *CancelExecutionTask) SetVisibilityTimestamp(timestamp time.Time) { u.VisibilityTimestamp = timestamp } // GetType returns the type of the signal transfer task func (u *SignalExecutionTask) GetType() int { return TransferTaskTypeSignalExecution } // GetVersion returns the version of the signal transfer task func (u *SignalExecutionTask) GetVersion() int64 { return u.Version } // SetVersion returns the version of the signal transfer task func (u *SignalExecutionTask) SetVersion(version int64) { u.Version = version } // GetTaskID returns the sequence ID of the signal transfer task. func (u *SignalExecutionTask) GetTaskID() int64 { return u.TaskID } // SetTaskID sets the sequence ID of the signal transfer task. func (u *SignalExecutionTask) SetTaskID(id int64) { u.TaskID = id } // GetVisibilityTimestamp get the visibility timestamp func (u *SignalExecutionTask) GetVisibilityTimestamp() time.Time { return u.VisibilityTimestamp } // SetVisibilityTimestamp set the visibility timestamp func (u *SignalExecutionTask) SetVisibilityTimestamp(timestamp time.Time) { u.VisibilityTimestamp = timestamp } // GetType returns the type of the upsert search attributes transfer task func (u *UpsertWorkflowSearchAttributesTask) GetType() int { return TransferTaskTypeUpsertWorkflowSearchAttributes } // GetVersion returns the version of the upsert search attributes transfer task func (u *UpsertWorkflowSearchAttributesTask) GetVersion() int64 { return u.Version } // SetVersion returns the version of the upsert search attributes transfer task func (u *UpsertWorkflowSearchAttributesTask) SetVersion(version int64) { u.Version = version } // GetTaskID returns the sequence ID of the signal transfer task. func (u *UpsertWorkflowSearchAttributesTask) GetTaskID() int64 { return u.TaskID } // SetTaskID sets the sequence ID of the signal transfer task. func (u *UpsertWorkflowSearchAttributesTask) SetTaskID(id int64) { u.TaskID = id } // GetVisibilityTimestamp get the visibility timestamp func (u *UpsertWorkflowSearchAttributesTask) GetVisibilityTimestamp() time.Time { return u.VisibilityTimestamp } // SetVisibilityTimestamp set the visibility timestamp func (u *UpsertWorkflowSearchAttributesTask) SetVisibilityTimestamp(timestamp time.Time) { u.VisibilityTimestamp = timestamp } // GetType returns the type of the start child transfer task func (u *StartChildExecutionTask) GetType() int { return TransferTaskTypeStartChildExecution } // GetVersion returns the version of the start child transfer task func (u *StartChildExecutionTask) GetVersion() int64 { return u.Version } // SetVersion returns the version of the start child transfer task func (u *StartChildExecutionTask) SetVersion(version int64) { u.Version = version } // GetTaskID returns the sequence ID of the start child transfer task func (u *StartChildExecutionTask) GetTaskID() int64 { return u.TaskID } // SetTaskID sets the sequence ID of the start child transfer task func (u *StartChildExecutionTask) SetTaskID(id int64) { u.TaskID = id } // GetVisibilityTimestamp get the visibility timestamp func (u *StartChildExecutionTask) GetVisibilityTimestamp() time.Time { return u.VisibilityTimestamp } // SetVisibilityTimestamp set the visibility timestamp func (u *StartChildExecutionTask) SetVisibilityTimestamp(timestamp time.Time) { u.VisibilityTimestamp = timestamp } // GetType returns the type of the history replication task func (a *HistoryReplicationTask) GetType() int { return ReplicationTaskTypeHistory } // GetVersion returns the version of the history replication task func (a *HistoryReplicationTask) GetVersion() int64 { return a.Version } // SetVersion returns the version of the history replication task func (a *HistoryReplicationTask) SetVersion(version int64) { a.Version = version } // GetTaskID returns the sequence ID of the history replication task func (a *HistoryReplicationTask) GetTaskID() int64 { return a.TaskID } // SetTaskID sets the sequence ID of the history replication task func (a *HistoryReplicationTask) SetTaskID(id int64) { a.TaskID = id } // GetVisibilityTimestamp get the visibility timestamp func (a *HistoryReplicationTask) GetVisibilityTimestamp() time.Time { return a.VisibilityTimestamp } // SetVisibilityTimestamp set the visibility timestamp func (a *HistoryReplicationTask) SetVisibilityTimestamp(timestamp time.Time) { a.VisibilityTimestamp = timestamp } // GetType returns the type of the history replication task func (a *SyncActivityTask) GetType() int { return ReplicationTaskTypeSyncActivity } // GetVersion returns the version of the history replication task func (a *SyncActivityTask) GetVersion() int64 { return a.Version } // SetVersion returns the version of the history replication task func (a *SyncActivityTask) SetVersion(version int64) { a.Version = version } // GetTaskID returns the sequence ID of the history replication task func (a *SyncActivityTask) GetTaskID() int64 { return a.TaskID } // SetTaskID sets the sequence ID of the history replication task func (a *SyncActivityTask) SetTaskID(id int64) { a.TaskID = id } // GetVisibilityTimestamp get the visibility timestamp func (a *SyncActivityTask) GetVisibilityTimestamp() time.Time { return a.VisibilityTimestamp } // SetVisibilityTimestamp set the visibility timestamp func (a *SyncActivityTask) SetVisibilityTimestamp(timestamp time.Time) { a.VisibilityTimestamp = timestamp } // DBTimestampToUnixNano converts CQL timestamp to UnixNano func DBTimestampToUnixNano(milliseconds int64) int64 { return milliseconds * 1000 * 1000 // Milliseconds are 10⁻³, nanoseconds are 10⁻⁹, (-3) - (-9) = 6, so multiply by 10⁶ } // UnixNanoToDBTimestamp converts UnixNano to CQL timestamp func UnixNanoToDBTimestamp(timestamp int64) int64 { return timestamp / (1000 * 1000) // Milliseconds are 10⁻³, nanoseconds are 10⁻⁹, (-9) - (-3) = -6, so divide by 10⁶ } // NewHistoryBranchToken return a new branch token func NewHistoryBranchToken(treeID []byte) ([]byte, error) { branchID := uuid.NewRandom() bi := &persistenceblobs.HistoryBranch{ TreeId: treeID, BranchId: branchID, Ancestors: []*persistenceblobs.HistoryBranchRange{}, } datablob, err := serialization.HistoryBranchToBlob(bi) if err != nil { return nil, err } token := datablob.Data return token, nil } // NewHistoryBranchTokenByBranchID return a new branch token with treeID/branchID func NewHistoryBranchTokenByBranchID(treeID, branchID []byte) ([]byte, error) { bi := &persistenceblobs.HistoryBranch{ TreeId: treeID, BranchId: branchID, Ancestors: []*persistenceblobs.HistoryBranchRange{}, } datablob, err := serialization.HistoryBranchToBlob(bi) if err != nil { return nil, err } token := datablob.Data return token, nil } // BuildHistoryGarbageCleanupInfo combine the workflow identity information into a string func BuildHistoryGarbageCleanupInfo(namespaceID, workflowID, runID string) string { return fmt.Sprintf("%v:%v:%v", namespaceID, workflowID, runID) } // SplitHistoryGarbageCleanupInfo returns workflow identity information func SplitHistoryGarbageCleanupInfo(info string) (namespaceID, workflowID, runID string, err error) { ss := strings.Split(info, ":") // workflowID can contain ":" so len(ss) can be greater than 3 if len(ss) < numItemsInGarbageInfo { return "", "", "", fmt.Errorf("not able to split info for %s", info) } namespaceID = ss[0] runID = ss[len(ss)-1] workflowEnd := len(info) - len(runID) - 1 workflowID = info[len(namespaceID)+1 : workflowEnd] return } // NewGetReplicationTasksFromDLQRequest creates a new GetReplicationTasksFromDLQRequest func NewGetReplicationTasksFromDLQRequest( sourceClusterName string, readLevel int64, maxReadLevel int64, batchSize int, nextPageToken []byte, ) *GetReplicationTasksFromDLQRequest { return &GetReplicationTasksFromDLQRequest{ SourceClusterName: sourceClusterName, GetReplicationTasksRequest: GetReplicationTasksRequest{ ReadLevel: readLevel, MaxReadLevel: maxReadLevel, BatchSize: batchSize, NextPageToken: nextPageToken, }, } } func (r *ReplicationState) GenerateVersionProto() *persistenceblobs.ReplicationVersions { return &persistenceblobs.ReplicationVersions{ StartVersion: &types.Int64Value{Value: r.StartVersion}, LastWriteVersion: &types.Int64Value{Value: r.LastWriteVersion}, } } type ServiceType int const ( All ServiceType = iota Frontend History Matching Worker )
1
9,565
Just run a global replacement for all `executionproto`.
temporalio-temporal
go
@@ -111,7 +111,7 @@ class WebDriver(object): def __init__(self, command_executor='http://127.0.0.1:4444/wd/hub', desired_capabilities=None, browser_profile=None, proxy=None, - keep_alive=False, file_detector=None): + keep_alive=False, file_detector=None, options=None): """ Create a new driver that will issue commands using the wire protocol.
1
# Licensed to the Software Freedom Conservancy (SFC) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The SFC licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """The WebDriver implementation.""" import base64 import copy import warnings from contextlib import contextmanager from .command import Command from .webelement import WebElement from .remote_connection import RemoteConnection from .errorhandler import ErrorHandler from .switch_to import SwitchTo from .mobile import Mobile from .file_detector import FileDetector, LocalFileDetector from selenium.common.exceptions import (InvalidArgumentException, WebDriverException) from selenium.webdriver.common.by import By from selenium.webdriver.common.html5.application_cache import ApplicationCache try: str = basestring except NameError: pass _W3C_CAPABILITY_NAMES = frozenset([ 'acceptInsecureCerts', 'browserName', 'browserVersion', 'platformName', 'pageLoadStrategy', 'proxy', 'setWindowRect', 'timeouts', 'unhandledPromptBehavior', ]) _OSS_W3C_CONVERSION = { 'acceptSslCerts': 'acceptInsecureCerts', 'version': 'browserVersion', 'platform': 'platformName' } def _make_w3c_caps(caps): """Makes a W3C alwaysMatch capabilities object. Filters out capability names that are not in the W3C spec. Spec-compliant drivers will reject requests containing unknown capability names. Moves the Firefox profile, if present, from the old location to the new Firefox options object. :Args: - caps - A dictionary of capabilities requested by the caller. """ caps = copy.deepcopy(caps) profile = caps.get('firefox_profile') always_match = {} if caps.get('proxy') and caps['proxy'].get('proxyType'): caps['proxy']['proxyType'] = caps['proxy']['proxyType'].lower() for k, v in caps.items(): if v and k in _OSS_W3C_CONVERSION: always_match[_OSS_W3C_CONVERSION[k]] = v.lower() if k == 'platform' else v if k in _W3C_CAPABILITY_NAMES or ':' in k: always_match[k] = v if profile: moz_opts = always_match.get('moz:firefoxOptions', {}) # If it's already present, assume the caller did that intentionally. if 'profile' not in moz_opts: # Don't mutate the original capabilities. new_opts = copy.deepcopy(moz_opts) new_opts['profile'] = profile always_match['moz:firefoxOptions'] = new_opts return {"firstMatch": [{}], "alwaysMatch": always_match} class WebDriver(object): """ Controls a browser by sending commands to a remote server. This server is expected to be running the WebDriver wire protocol as defined at https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol :Attributes: - session_id - String ID of the browser session started and controlled by this WebDriver. - capabilities - Dictionaty of effective capabilities of this browser session as returned by the remote server. See https://github.com/SeleniumHQ/selenium/wiki/DesiredCapabilities - command_executor - remote_connection.RemoteConnection object used to execute commands. - error_handler - errorhandler.ErrorHandler object used to handle errors. """ _web_element_cls = WebElement def __init__(self, command_executor='http://127.0.0.1:4444/wd/hub', desired_capabilities=None, browser_profile=None, proxy=None, keep_alive=False, file_detector=None): """ Create a new driver that will issue commands using the wire protocol. :Args: - command_executor - Either a string representing URL of the remote server or a custom remote_connection.RemoteConnection object. Defaults to 'http://127.0.0.1:4444/wd/hub'. - desired_capabilities - A dictionary of capabilities to request when starting the browser session. Required parameter. - browser_profile - A selenium.webdriver.firefox.firefox_profile.FirefoxProfile object. Only used if Firefox is requested. Optional. - proxy - A selenium.webdriver.common.proxy.Proxy object. The browser session will be started with given proxy settings, if possible. Optional. - keep_alive - Whether to configure remote_connection.RemoteConnection to use HTTP keep-alive. Defaults to False. - file_detector - Pass custom file detector object during instantiation. If None, then default LocalFileDetector() will be used. """ if desired_capabilities is None: raise WebDriverException("Desired Capabilities can't be None") if not isinstance(desired_capabilities, dict): raise WebDriverException("Desired Capabilities must be a dictionary") if proxy is not None: warnings.warn("Please use FirefoxOptions to set proxy", DeprecationWarning) proxy.add_to_capabilities(desired_capabilities) self.command_executor = command_executor if type(self.command_executor) is bytes or isinstance(self.command_executor, str): self.command_executor = RemoteConnection(command_executor, keep_alive=keep_alive) self._is_remote = True self.session_id = None self.capabilities = {} self.error_handler = ErrorHandler() self.start_client() if browser_profile is not None: warnings.warn("Please use FirefoxOptions to set browser profile", DeprecationWarning) self.start_session(desired_capabilities, browser_profile) self._switch_to = SwitchTo(self) self._mobile = Mobile(self) self.file_detector = file_detector or LocalFileDetector() def __repr__(self): return '<{0.__module__}.{0.__name__} (session="{1}")>'.format( type(self), self.session_id) @contextmanager def file_detector_context(self, file_detector_class, *args, **kwargs): """ Overrides the current file detector (if necessary) in limited context. Ensures the original file detector is set afterwards. Example: with webdriver.file_detector_context(UselessFileDetector): someinput.send_keys('/etc/hosts') :Args: - file_detector_class - Class of the desired file detector. If the class is different from the current file_detector, then the class is instantiated with args and kwargs and used as a file detector during the duration of the context manager. - args - Optional arguments that get passed to the file detector class during instantiation. - kwargs - Keyword arguments, passed the same way as args. """ last_detector = None if not isinstance(self.file_detector, file_detector_class): last_detector = self.file_detector self.file_detector = file_detector_class(*args, **kwargs) try: yield finally: if last_detector is not None: self.file_detector = last_detector @property def mobile(self): return self._mobile @property def name(self): """Returns the name of the underlying browser for this instance. :Usage: - driver.name """ if 'browserName' in self.capabilities: return self.capabilities['browserName'] else: raise KeyError('browserName not specified in session capabilities') def start_client(self): """ Called before starting a new session. This method may be overridden to define custom startup behavior. """ pass def stop_client(self): """ Called after executing a quit command. This method may be overridden to define custom shutdown behavior. """ pass def start_session(self, capabilities, browser_profile=None): """ Creates a new session with the desired capabilities. :Args: - browser_name - The name of the browser to request. - version - Which browser version to request. - platform - Which platform to request the browser on. - javascript_enabled - Whether the new session should support JavaScript. - browser_profile - A selenium.webdriver.firefox.firefox_profile.FirefoxProfile object. Only used if Firefox is requested. """ if not isinstance(capabilities, dict): raise InvalidArgumentException("Capabilities must be a dictionary") if browser_profile: if "moz:firefoxOptions" in capabilities: capabilities["moz:firefoxOptions"]["profile"] = browser_profile.encoded else: capabilities.update({'firefox_profile': browser_profile.encoded}) w3c_caps = _make_w3c_caps(capabilities) parameters = {"capabilities": w3c_caps, "desiredCapabilities": capabilities} response = self.execute(Command.NEW_SESSION, parameters) if 'sessionId' not in response: response = response['value'] self.session_id = response['sessionId'] self.capabilities = response.get('value') # if capabilities is none we are probably speaking to # a W3C endpoint if self.capabilities is None: self.capabilities = response.get('capabilities') # Double check to see if we have a W3C Compliant browser self.w3c = response.get('status') is None def _wrap_value(self, value): if isinstance(value, dict): converted = {} for key, val in value.items(): converted[key] = self._wrap_value(val) return converted elif isinstance(value, self._web_element_cls): return {'ELEMENT': value.id, 'element-6066-11e4-a52e-4f735466cecf': value.id} elif isinstance(value, list): return list(self._wrap_value(item) for item in value) else: return value def create_web_element(self, element_id): """Creates a web element with the specified `element_id`.""" return self._web_element_cls(self, element_id, w3c=self.w3c) def _unwrap_value(self, value): if isinstance(value, dict): if 'ELEMENT' in value or 'element-6066-11e4-a52e-4f735466cecf' in value: wrapped_id = value.get('ELEMENT', None) if wrapped_id: return self.create_web_element(value['ELEMENT']) else: return self.create_web_element(value['element-6066-11e4-a52e-4f735466cecf']) else: for key, val in value.items(): value[key] = self._unwrap_value(val) return value elif isinstance(value, list): return list(self._unwrap_value(item) for item in value) else: return value def execute(self, driver_command, params=None): """ Sends a command to be executed by a command.CommandExecutor. :Args: - driver_command: The name of the command to execute as a string. - params: A dictionary of named parameters to send with the command. :Returns: The command's JSON response loaded into a dictionary object. """ if self.session_id is not None: if not params: params = {'sessionId': self.session_id} elif 'sessionId' not in params: params['sessionId'] = self.session_id params = self._wrap_value(params) response = self.command_executor.execute(driver_command, params) if response: self.error_handler.check_response(response) response['value'] = self._unwrap_value( response.get('value', None)) return response # If the server doesn't send a response, assume the command was # a success return {'success': 0, 'value': None, 'sessionId': self.session_id} def get(self, url): """ Loads a web page in the current browser session. """ self.execute(Command.GET, {'url': url}) @property def title(self): """Returns the title of the current page. :Usage: driver.title """ resp = self.execute(Command.GET_TITLE) return resp['value'] if resp['value'] is not None else "" def find_element_by_id(self, id_): """Finds an element by id. :Args: - id\_ - The id of the element to be found. :Usage: driver.find_element_by_id('foo') """ return self.find_element(by=By.ID, value=id_) def find_elements_by_id(self, id_): """ Finds multiple elements by id. :Args: - id\_ - The id of the elements to be found. :Usage: driver.find_elements_by_id('foo') """ return self.find_elements(by=By.ID, value=id_) def find_element_by_xpath(self, xpath): """ Finds an element by xpath. :Args: - xpath - The xpath locator of the element to find. :Usage: driver.find_element_by_xpath('//div/td[1]') """ return self.find_element(by=By.XPATH, value=xpath) def find_elements_by_xpath(self, xpath): """ Finds multiple elements by xpath. :Args: - xpath - The xpath locator of the elements to be found. :Usage: driver.find_elements_by_xpath("//div[contains(@class, 'foo')]") """ return self.find_elements(by=By.XPATH, value=xpath) def find_element_by_link_text(self, link_text): """ Finds an element by link text. :Args: - link_text: The text of the element to be found. :Usage: driver.find_element_by_link_text('Sign In') """ return self.find_element(by=By.LINK_TEXT, value=link_text) def find_elements_by_link_text(self, text): """ Finds elements by link text. :Args: - link_text: The text of the elements to be found. :Usage: driver.find_elements_by_link_text('Sign In') """ return self.find_elements(by=By.LINK_TEXT, value=text) def find_element_by_partial_link_text(self, link_text): """ Finds an element by a partial match of its link text. :Args: - link_text: The text of the element to partially match on. :Usage: driver.find_element_by_partial_link_text('Sign') """ return self.find_element(by=By.PARTIAL_LINK_TEXT, value=link_text) def find_elements_by_partial_link_text(self, link_text): """ Finds elements by a partial match of their link text. :Args: - link_text: The text of the element to partial match on. :Usage: driver.find_element_by_partial_link_text('Sign') """ return self.find_elements(by=By.PARTIAL_LINK_TEXT, value=link_text) def find_element_by_name(self, name): """ Finds an element by name. :Args: - name: The name of the element to find. :Usage: driver.find_element_by_name('foo') """ return self.find_element(by=By.NAME, value=name) def find_elements_by_name(self, name): """ Finds elements by name. :Args: - name: The name of the elements to find. :Usage: driver.find_elements_by_name('foo') """ return self.find_elements(by=By.NAME, value=name) def find_element_by_tag_name(self, name): """ Finds an element by tag name. :Args: - name: The tag name of the element to find. :Usage: driver.find_element_by_tag_name('foo') """ return self.find_element(by=By.TAG_NAME, value=name) def find_elements_by_tag_name(self, name): """ Finds elements by tag name. :Args: - name: The tag name the use when finding elements. :Usage: driver.find_elements_by_tag_name('foo') """ return self.find_elements(by=By.TAG_NAME, value=name) def find_element_by_class_name(self, name): """ Finds an element by class name. :Args: - name: The class name of the element to find. :Usage: driver.find_element_by_class_name('foo') """ return self.find_element(by=By.CLASS_NAME, value=name) def find_elements_by_class_name(self, name): """ Finds elements by class name. :Args: - name: The class name of the elements to find. :Usage: driver.find_elements_by_class_name('foo') """ return self.find_elements(by=By.CLASS_NAME, value=name) def find_element_by_css_selector(self, css_selector): """ Finds an element by css selector. :Args: - css_selector: The css selector to use when finding elements. :Usage: driver.find_element_by_css_selector('#foo') """ return self.find_element(by=By.CSS_SELECTOR, value=css_selector) def find_elements_by_css_selector(self, css_selector): """ Finds elements by css selector. :Args: - css_selector: The css selector to use when finding elements. :Usage: driver.find_elements_by_css_selector('.foo') """ return self.find_elements(by=By.CSS_SELECTOR, value=css_selector) def execute_script(self, script, *args): """ Synchronously Executes JavaScript in the current window/frame. :Args: - script: The JavaScript to execute. - \*args: Any applicable arguments for your JavaScript. :Usage: driver.execute_script('document.title') """ converted_args = list(args) command = None if self.w3c: command = Command.W3C_EXECUTE_SCRIPT else: command = Command.EXECUTE_SCRIPT return self.execute(command, { 'script': script, 'args': converted_args})['value'] def execute_async_script(self, script, *args): """ Asynchronously Executes JavaScript in the current window/frame. :Args: - script: The JavaScript to execute. - \*args: Any applicable arguments for your JavaScript. :Usage: driver.execute_async_script('document.title') """ converted_args = list(args) if self.w3c: command = Command.W3C_EXECUTE_SCRIPT_ASYNC else: command = Command.EXECUTE_ASYNC_SCRIPT return self.execute(command, { 'script': script, 'args': converted_args})['value'] @property def current_url(self): """ Gets the URL of the current page. :Usage: driver.current_url """ return self.execute(Command.GET_CURRENT_URL)['value'] @property def page_source(self): """ Gets the source of the current page. :Usage: driver.page_source """ return self.execute(Command.GET_PAGE_SOURCE)['value'] def close(self): """ Closes the current window. :Usage: driver.close() """ self.execute(Command.CLOSE) def quit(self): """ Quits the driver and closes every associated window. :Usage: driver.quit() """ try: self.execute(Command.QUIT) finally: self.stop_client() @property def current_window_handle(self): """ Returns the handle of the current window. :Usage: driver.current_window_handle """ if self.w3c: return self.execute(Command.W3C_GET_CURRENT_WINDOW_HANDLE)['value'] else: return self.execute(Command.GET_CURRENT_WINDOW_HANDLE)['value'] @property def window_handles(self): """ Returns the handles of all windows within the current session. :Usage: driver.window_handles """ if self.w3c: return self.execute(Command.W3C_GET_WINDOW_HANDLES)['value'] else: return self.execute(Command.GET_WINDOW_HANDLES)['value'] def maximize_window(self): """ Maximizes the current window that webdriver is using """ command = Command.MAXIMIZE_WINDOW if self.w3c: command = Command.W3C_MAXIMIZE_WINDOW self.execute(command, {"windowHandle": "current"}) @property def switch_to(self): return self._switch_to # Target Locators def switch_to_active_element(self): """ Deprecated use driver.switch_to.active_element """ warnings.warn("use driver.switch_to.active_element instead", DeprecationWarning) return self._switch_to.active_element def switch_to_window(self, window_name): """ Deprecated use driver.switch_to.window """ warnings.warn("use driver.switch_to.window instead", DeprecationWarning) self._switch_to.window(window_name) def switch_to_frame(self, frame_reference): """ Deprecated use driver.switch_to.frame """ warnings.warn("use driver.switch_to.frame instead", DeprecationWarning) self._switch_to.frame(frame_reference) def switch_to_default_content(self): """ Deprecated use driver.switch_to.default_content """ warnings.warn("use driver.switch_to.default_content instead", DeprecationWarning) self._switch_to.default_content() def switch_to_alert(self): """ Deprecated use driver.switch_to.alert """ warnings.warn("use driver.switch_to.alert instead", DeprecationWarning) return self._switch_to.alert # Navigation def back(self): """ Goes one step backward in the browser history. :Usage: driver.back() """ self.execute(Command.GO_BACK) def forward(self): """ Goes one step forward in the browser history. :Usage: driver.forward() """ self.execute(Command.GO_FORWARD) def refresh(self): """ Refreshes the current page. :Usage: driver.refresh() """ self.execute(Command.REFRESH) # Options def get_cookies(self): """ Returns a set of dictionaries, corresponding to cookies visible in the current session. :Usage: driver.get_cookies() """ return self.execute(Command.GET_ALL_COOKIES)['value'] def get_cookie(self, name): """ Get a single cookie by name. Returns the cookie if found, None if not. :Usage: driver.get_cookie('my_cookie') """ cookies = self.get_cookies() for cookie in cookies: if cookie['name'] == name: return cookie return None def delete_cookie(self, name): """ Deletes a single cookie with the given name. :Usage: driver.delete_cookie('my_cookie') """ self.execute(Command.DELETE_COOKIE, {'name': name}) def delete_all_cookies(self): """ Delete all cookies in the scope of the session. :Usage: driver.delete_all_cookies() """ self.execute(Command.DELETE_ALL_COOKIES) def add_cookie(self, cookie_dict): """ Adds a cookie to your current session. :Args: - cookie_dict: A dictionary object, with required keys - "name" and "value"; optional keys - "path", "domain", "secure", "expiry" Usage: driver.add_cookie({'name' : 'foo', 'value' : 'bar'}) driver.add_cookie({'name' : 'foo', 'value' : 'bar', 'path' : '/'}) driver.add_cookie({'name' : 'foo', 'value' : 'bar', 'path' : '/', 'secure':True}) """ self.execute(Command.ADD_COOKIE, {'cookie': cookie_dict}) # Timeouts def implicitly_wait(self, time_to_wait): """ Sets a sticky timeout to implicitly wait for an element to be found, or a command to complete. This method only needs to be called one time per session. To set the timeout for calls to execute_async_script, see set_script_timeout. :Args: - time_to_wait: Amount of time to wait (in seconds) :Usage: driver.implicitly_wait(30) """ if self.w3c: self.execute(Command.SET_TIMEOUTS, { 'implicit': int(float(time_to_wait) * 1000)}) else: self.execute(Command.IMPLICIT_WAIT, { 'ms': float(time_to_wait) * 1000}) def set_script_timeout(self, time_to_wait): """ Set the amount of time that the script should wait during an execute_async_script call before throwing an error. :Args: - time_to_wait: The amount of time to wait (in seconds) :Usage: driver.set_script_timeout(30) """ if self.w3c: self.execute(Command.SET_TIMEOUTS, { 'script': int(float(time_to_wait) * 1000)}) else: self.execute(Command.SET_SCRIPT_TIMEOUT, { 'ms': float(time_to_wait) * 1000}) def set_page_load_timeout(self, time_to_wait): """ Set the amount of time to wait for a page load to complete before throwing an error. :Args: - time_to_wait: The amount of time to wait :Usage: driver.set_page_load_timeout(30) """ try: self.execute(Command.SET_TIMEOUTS, { 'pageLoad': int(float(time_to_wait) * 1000)}) except WebDriverException: self.execute(Command.SET_TIMEOUTS, { 'ms': float(time_to_wait) * 1000, 'type': 'page load'}) def find_element(self, by=By.ID, value=None): """ 'Private' method used by the find_element_by_* methods. :Usage: Use the corresponding find_element_by_* instead of this. :rtype: WebElement """ if self.w3c: if by == By.ID: by = By.CSS_SELECTOR value = '[id="%s"]' % value elif by == By.TAG_NAME: by = By.CSS_SELECTOR elif by == By.CLASS_NAME: by = By.CSS_SELECTOR value = ".%s" % value elif by == By.NAME: by = By.CSS_SELECTOR value = '[name="%s"]' % value return self.execute(Command.FIND_ELEMENT, { 'using': by, 'value': value})['value'] def find_elements(self, by=By.ID, value=None): """ 'Private' method used by the find_elements_by_* methods. :Usage: Use the corresponding find_elements_by_* instead of this. :rtype: list of WebElement """ if self.w3c: if by == By.ID: by = By.CSS_SELECTOR value = '[id="%s"]' % value elif by == By.TAG_NAME: by = By.CSS_SELECTOR elif by == By.CLASS_NAME: by = By.CSS_SELECTOR value = ".%s" % value elif by == By.NAME: by = By.CSS_SELECTOR value = '[name="%s"]' % value # Return empty list if driver returns null # See https://github.com/SeleniumHQ/selenium/issues/4555 return self.execute(Command.FIND_ELEMENTS, { 'using': by, 'value': value})['value'] or [] @property def desired_capabilities(self): """ returns the drivers current desired capabilities being used """ return self.capabilities def get_screenshot_as_file(self, filename): """ Saves a screenshot of the current window to a PNG image file. Returns False if there is any IOError, else returns True. Use full paths in your filename. :Args: - filename: The full path you wish to save your screenshot to. This should end with a `.png` extension. :Usage: driver.get_screenshot_as_file('/Screenshots/foo.png') """ if not filename.lower().endswith('.png'): warnings.warn("name used for saved screenshot does not match file " "type. It should end with a `.png` extension", UserWarning) png = self.get_screenshot_as_png() try: with open(filename, 'wb') as f: f.write(png) except IOError: return False finally: del png return True def save_screenshot(self, filename): """ Saves a screenshot of the current window to a PNG image file. Returns False if there is any IOError, else returns True. Use full paths in your filename. :Args: - filename: The full path you wish to save your screenshot to. This should end with a `.png` extension. :Usage: driver.save_screenshot('/Screenshots/foo.png') """ return self.get_screenshot_as_file(filename) def get_screenshot_as_png(self): """ Gets the screenshot of the current window as a binary data. :Usage: driver.get_screenshot_as_png() """ return base64.b64decode(self.get_screenshot_as_base64().encode('ascii')) def get_screenshot_as_base64(self): """ Gets the screenshot of the current window as a base64 encoded string which is useful in embedded images in HTML. :Usage: driver.get_screenshot_as_base64() """ return self.execute(Command.SCREENSHOT)['value'] def set_window_size(self, width, height, windowHandle='current'): """ Sets the width and height of the current window. (window.resizeTo) :Args: - width: the width in pixels to set the window to - height: the height in pixels to set the window to :Usage: driver.set_window_size(800,600) """ command = Command.SET_WINDOW_SIZE if self.w3c: command = Command.W3C_SET_WINDOW_SIZE self.execute(command, { 'width': int(width), 'height': int(height), 'windowHandle': windowHandle}) def get_window_size(self, windowHandle='current'): """ Gets the width and height of the current window. :Usage: driver.get_window_size() """ command = Command.GET_WINDOW_SIZE if self.w3c: command = Command.W3C_GET_WINDOW_SIZE size = self.execute(command, {'windowHandle': windowHandle}) if size.get('value', None) is not None: return size['value'] else: return size def set_window_position(self, x, y, windowHandle='current'): """ Sets the x,y position of the current window. (window.moveTo) :Args: - x: the x-coordinate in pixels to set the window position - y: the y-coordinate in pixels to set the window position :Usage: driver.set_window_position(0,0) """ if self.w3c: return self.execute(Command.W3C_SET_WINDOW_POSITION, { 'x': int(x), 'y': int(y) }) else: self.execute(Command.SET_WINDOW_POSITION, { 'x': int(x), 'y': int(y), 'windowHandle': windowHandle }) def get_window_position(self, windowHandle='current'): """ Gets the x,y position of the current window. :Usage: driver.get_window_position() """ if self.w3c: return self.execute(Command.W3C_GET_WINDOW_POSITION)['value'] else: return self.execute(Command.GET_WINDOW_POSITION, { 'windowHandle': windowHandle})['value'] def get_window_rect(self): """ Gets the x, y coordinates of the window as well as height and width of the current window. :Usage: driver.get_window_rect() """ return self.execute(Command.GET_WINDOW_RECT)['value'] def set_window_rect(self, x=None, y=None, width=None, height=None): """ Sets the x, y coordinates of the window as well as height and width of the current window. :Usage: driver.set_window_rect(x=10, y=10) driver.set_window_rect(width=100, height=200) driver.set_window_rect(x=10, y=10, width=100, height=200) """ if (x is None and y is None) and (height is None and width is None): raise InvalidArgumentException("x and y or height and width need values") return self.execute(Command.SET_WINDOW_RECT, {"x": x, "y": y, "width": width, "height": height})['value'] @property def file_detector(self): return self._file_detector @file_detector.setter def file_detector(self, detector): """ Set the file detector to be used when sending keyboard input. By default, this is set to a file detector that does nothing. see FileDetector see LocalFileDetector see UselessFileDetector :Args: - detector: The detector to use. Must not be None. """ if detector is None: raise WebDriverException("You may not set a file detector that is null") if not isinstance(detector, FileDetector): raise WebDriverException("Detector has to be instance of FileDetector") self._file_detector = detector @property def orientation(self): """ Gets the current orientation of the device :Usage: orientation = driver.orientation """ return self.execute(Command.GET_SCREEN_ORIENTATION)['value'] @orientation.setter def orientation(self, value): """ Sets the current orientation of the device :Args: - value: orientation to set it to. :Usage: driver.orientation = 'landscape' """ allowed_values = ['LANDSCAPE', 'PORTRAIT'] if value.upper() in allowed_values: self.execute(Command.SET_SCREEN_ORIENTATION, {'orientation': value}) else: raise WebDriverException("You can only set the orientation to 'LANDSCAPE' and 'PORTRAIT'") @property def application_cache(self): """ Returns a ApplicationCache Object to interact with the browser app cache""" return ApplicationCache(self) @property def log_types(self): """ Gets a list of the available log types :Usage: driver.log_types """ return self.execute(Command.GET_AVAILABLE_LOG_TYPES)['value'] def get_log(self, log_type): """ Gets the log for a given log type :Args: - log_type: type of log that which will be returned :Usage: driver.get_log('browser') driver.get_log('driver') driver.get_log('client') driver.get_log('server') """ return self.execute(Command.GET_LOG, {'type': log_type})['value']
1
14,946
@AutomatedTester @davehunt thoughts on a new keyword argument?
SeleniumHQ-selenium
java
@@ -49,6 +49,9 @@ fpga_result opae_ioctl(int fd, int request, ...) case EINVAL: res = FPGA_INVALID_PARAM; break; + case ENOTSUP: + res = FPGA_NOT_SUPPORTED; + break; default: // other errors could be // EBADF - fd is bad file descriptor
1
// Copyright(c) 2017-2018, Intel Corporation // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of Intel Corporation nor the names of its contributors // may be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. /* * opae_ioctl.c */ #include <stddef.h> #include <stdarg.h> #include <sys/ioctl.h> #include <errno.h> #include <opae/fpga.h> #include "common_int.h" #include "opae_ioctl.h" #include "intel-fpga.h" fpga_result opae_ioctl(int fd, int request, ...) { fpga_result res = FPGA_OK; va_list argp; va_start(argp, request); void *msg = va_arg(argp, void *); errno = 0; if (ioctl(fd, request, msg) != 0) { OPAE_MSG("error executing ioctl: %s", strerror(errno)); switch (errno) { case EINVAL: res = FPGA_INVALID_PARAM; break; default: // other errors could be // EBADF - fd is bad file descriptor // EFAULT - argp references an inaccessible // memory area // ENOTTY - fd is not associated with a char. // special device res = FPGA_EXCEPTION; break; } } va_end(argp); return res; } int opae_get_fme_info(int fd, opae_fme_info *info) { ASSERT_NOT_NULL(info); struct fpga_fme_info fme_info = {.argsz = sizeof(fme_info), .flags = 0}; int res = opae_ioctl(fd, FPGA_FME_GET_INFO, &fme_info); if (!res) { info->flags = fme_info.flags; info->capability = fme_info.capability; } return res; } int opae_get_port_info(int fd, opae_port_info *info) { ASSERT_NOT_NULL(info); struct fpga_port_info pinfo = {.argsz = sizeof(pinfo), .flags = 0}; int res = opae_ioctl(fd, FPGA_PORT_GET_INFO, &pinfo); if (!res) { info->flags = pinfo.flags; info->capability = pinfo.capability; info->num_regions = pinfo.num_regions; info->num_umsgs = pinfo.num_umsgs; info->num_uafu_irqs = pinfo.num_uafu_irqs; } return res; } int opae_get_port_region_info(int fd, uint32_t index, opae_port_region_info *info) { ASSERT_NOT_NULL(info); struct fpga_port_region_info rinfo = {.argsz = sizeof(rinfo), .padding = 0, .index = index}; int res = opae_ioctl(fd, FPGA_PORT_GET_REGION_INFO, &rinfo); if (!res) { info->flags = rinfo.flags; info->size = rinfo.size; info->offset = rinfo.offset; } return res; } int opae_port_map(int fd, void *addr, uint64_t len, uint64_t *io_addr) { int res = 0; int req = 0; void *msg = NULL; /* Set ioctl fpga_port_dma_map struct parameters */ struct fpga_port_dma_map dma_map = {.argsz = sizeof(dma_map), .flags = 0, .user_addr = (__u64)addr, .length = (__u64)len, .iova = 0}; ASSERT_NOT_NULL(io_addr); /* Dispatch ioctl command */ req = FPGA_PORT_DMA_MAP; msg = &dma_map; res = opae_ioctl(fd, req, msg); if (!res) { *io_addr = dma_map.iova; } return res; } int opae_port_unmap(int fd, uint64_t io_addr) { /* Set ioctl fpga_port_dma_unmap struct parameters */ struct fpga_port_dma_unmap dma_unmap = { .argsz = sizeof(dma_unmap), .flags = 0, .iova = io_addr}; /* Dispatch ioctl command */ return opae_ioctl(fd, FPGA_PORT_DMA_UNMAP, &dma_unmap); }
1
17,693
Should line 47 be OPAE_ERR?
OPAE-opae-sdk
c
@@ -104,6 +104,8 @@ import ( "gocloud.dev/pubsub/driver" ) +var zeroTime time.Time + // Message contains data to be published. type Message struct { // Body contains the content of the message.
1
// Copyright 2018 The Go Cloud Development Kit Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package pubsub provides an easy and portable way to interact with publish/ // subscribe systems. // // Subpackages contain distinct implementations of pubsub for various providers, // including Cloud and on-prem solutions. For example, "gcppubsub" supports // Google Cloud Pub/Sub. Your application should import one of these // provider-specific subpackages and use its exported functions to get a // *Topic and/or *Subscription; do not use the NewTopic/NewSubscription // functions in this package. For example: // // topic := mempubsub.NewTopic() // err := topic.Send(ctx.Background(), &pubsub.Message{Body: []byte("hi")) // ... // // Then, write your application code using the *Topic/*Subscription types. You // can easily reconfigure your initialization code to choose a different provider. // You can develop your application locally using memblob, or deploy it to // multiple Cloud providers. You may find http://github.com/google/wire useful // for managing your initialization code. // // Alternatively, you can construct a *Topic/*Subscription via a URL and // OpenTopic/OpenSubscription. // See https://godoc.org/gocloud.dev#hdr-URLs for more information. // // // At-most-once and At-least-once Delivery // // Some PubSub systems guarantee that messages received by subscribers but not // acknowledged are delivered again. These at-least-once systems require that // subscribers call an ack function to indicate that they have fully processed a // message. // // In other PubSub systems, a message will be delivered only once, if it is delivered // at all. These at-most-once systems do not need an Ack method. // // This package accommodates both kinds of systems. If your application uses // at-least-once providers, it should always call Message.Ack. If your application // only uses at-most-once providers, it may call Message.Ack, but does not need to. // The constructor for at-most-once-providers will require you to supply a function // to be called whenever the application calls Message.Ack. Common implementations // are: do nothing, on the grounds that you may want to test your at-least-once // system with an at-most-once provider; or panic, so that a system that assumes // at-least-once delivery isn't accidentally paired with an at-most-once provider. // Providers that support both at-most-once and at-least-once semantics will include // an optional ack function in their Options struct. // // // OpenCensus Integration // // OpenCensus supports tracing and metric collection for multiple languages and // backend providers. See https://opencensus.io. // // This API collects OpenCensus traces and metrics for the following methods: // - Topic.Send // - Topic.Shutdown // - Subscription.Receive // - Subscription.Shutdown // - The internal driver methods SendBatch, SendAcks and ReceiveBatch. // All trace and metric names begin with the package import path. // The traces add the method name. // For example, "gocloud.dev/pubsub/Topic.Send". // The metrics are "completed_calls", a count of completed method calls by provider, // method and status (error code); and "latency", a distribution of method latency // by provider and method. // For example, "gocloud.dev/pubsub/latency". // // To enable trace collection in your application, see "Configure Exporter" at // https://opencensus.io/quickstart/go/tracing. // To enable metric collection in your application, see "Exporting stats" at // https://opencensus.io/quickstart/go/metrics. package pubsub // import "gocloud.dev/pubsub" import ( "context" "fmt" "math" "net/url" "reflect" "sync" "time" "unicode/utf8" gax "github.com/googleapis/gax-go" "gocloud.dev/gcerrors" "gocloud.dev/internal/batcher" "gocloud.dev/internal/gcerr" "gocloud.dev/internal/oc" "gocloud.dev/internal/openurl" "gocloud.dev/internal/retry" "gocloud.dev/pubsub/driver" ) // Message contains data to be published. type Message struct { // Body contains the content of the message. Body []byte // Metadata has key/value metadata for the message. Metadata map[string]string // asFunc invokes driver.Message.AsFunc. asFunc func(interface{}) bool // ack is a closure that queues this message for acknowledgement. ack func() // mu guards isAcked in case Ack() is called concurrently. mu sync.Mutex // isAcked tells whether this message has already had its Ack method // called. isAcked bool } // Ack acknowledges the message, telling the server that it does not need to be // sent again to the associated Subscription. It returns immediately, but the // actual ack is sent in the background, and is not guaranteed to succeed. func (m *Message) Ack() { m.mu.Lock() defer m.mu.Unlock() if m.isAcked { panic(fmt.Sprintf("Ack() called twice on message: %+v", m)) } m.ack() m.isAcked = true } // As converts i to provider-specific types. // See https://godoc.org/gocloud.dev#hdr-As for background information, the "As" // examples in this package for examples, and the provider-specific package // documentation for the specific types supported for that provider. // As panics unless it is called on a message obtained from Subscription.Receive. func (m *Message) As(i interface{}) bool { if m.asFunc == nil { panic("As called on a Message that was not obtained from Receive") } return m.asFunc(i) } // Topic publishes messages to all its subscribers. type Topic struct { driver driver.Topic batcher driver.Batcher tracer *oc.Tracer mu sync.Mutex err error // cancel cancels all SendBatch calls. cancel func() } type msgErrChan struct { msg *Message errChan chan error } // Send publishes a message. It only returns after the message has been // sent, or failed to be sent. Send can be called from multiple goroutines // at once. func (t *Topic) Send(ctx context.Context, m *Message) (err error) { ctx = t.tracer.Start(ctx, "Topic.Send") defer func() { t.tracer.End(ctx, err) }() // Check for doneness before we do any work. if err := ctx.Err(); err != nil { return err // Return context errors unwrapped. } t.mu.Lock() err = t.err t.mu.Unlock() if err != nil { return err // t.err wrapped when set } for k, v := range m.Metadata { if !utf8.ValidString(k) { return fmt.Errorf("pubsub.Send: Message.Metadata keys must be valid UTF-8 strings: %q", k) } if !utf8.ValidString(v) { return fmt.Errorf("pubsub.Send: Message.Metadata values must be valid UTF-8 strings: %q", v) } } return t.batcher.Add(ctx, m) } // Shutdown flushes pending message sends and disconnects the Topic. // It only returns after all pending messages have been sent. func (t *Topic) Shutdown(ctx context.Context) (err error) { ctx = t.tracer.Start(ctx, "Topic.Shutdown") defer func() { t.tracer.End(ctx, err) }() t.mu.Lock() t.err = gcerr.Newf(gcerr.FailedPrecondition, nil, "pubsub: Topic closed") t.mu.Unlock() c := make(chan struct{}) go func() { defer close(c) t.batcher.Shutdown() }() select { case <-ctx.Done(): case <-c: } t.cancel() return ctx.Err() } // As converts i to provider-specific types. // See https://godoc.org/gocloud.dev#hdr-As for background information, the "As" // examples in this package for examples, and the provider-specific package // documentation for the specific types supported for that provider. func (t *Topic) As(i interface{}) bool { return t.driver.As(i) } // ErrorAs converts err to provider-specific types. // ErrorAs panics if i is nil or not a pointer. // ErrorAs returns false if err == nil. // See https://godoc.org/gocloud.dev#hdr-As for background information. func (t *Topic) ErrorAs(err error, i interface{}) bool { return gcerr.ErrorAs(err, i, t.driver.ErrorAs) } // NewTopic is for use by provider implementations. var NewTopic = newTopic // defaultBatcher creates a batcher for topics, for use with NewTopic. func defaultBatcher(ctx context.Context, t *Topic, dt driver.Topic) driver.Batcher { const maxHandlers = 1 handler := func(items interface{}) error { ms := items.([]*Message) var dms []*driver.Message for _, m := range ms { dm := &driver.Message{ Body: m.Body, Metadata: m.Metadata, } dms = append(dms, dm) } err := retry.Call(ctx, gax.Backoff{}, t.driver.IsRetryable, func() (err error) { ctx2 := t.tracer.Start(ctx, "driver.Topic.SendBatch") defer func() { t.tracer.End(ctx2, err) }() return dt.SendBatch(ctx2, dms) }) if err != nil { return wrapError(dt, err) } return nil } return batcher.New(reflect.TypeOf(&Message{}), maxHandlers, handler) } // newTopic makes a pubsub.Topic from a driver.Topic. func newTopic(d driver.Topic, newBatcher func(context.Context, *Topic, driver.Topic) driver.Batcher) *Topic { ctx, cancel := context.WithCancel(context.Background()) t := &Topic{ driver: d, tracer: newTracer(d), cancel: cancel, } if newBatcher == nil { newBatcher = defaultBatcher } t.batcher = newBatcher(ctx, t, d) return t } const pkgName = "gocloud.dev/pubsub" var ( latencyMeasure = oc.LatencyMeasure(pkgName) // OpenCensusViews are predefined views for OpenCensus metrics. // The views include counts and latency distributions for API method calls. // See the example at https://godoc.org/go.opencensus.io/stats/view for usage. OpenCensusViews = oc.Views(pkgName, latencyMeasure) ) func newTracer(driver interface{}) *oc.Tracer { return &oc.Tracer{ Package: pkgName, Provider: oc.ProviderName(driver), LatencyMeasure: latencyMeasure, } } // Subscription receives published messages. type Subscription struct { driver driver.Subscription tracer *oc.Tracer // ackBatcher makes batches of acks and sends them to the server. ackBatcher driver.Batcher ackFunc func() // if non-nil, used for Ack cancel func() // for canceling all SendAcks calls fixedBatchSize int // if 0, batch size is computed dynamically via updateBatchSize mu sync.Mutex // protects everything below q []*Message // local queue of messages downloaded from server err error // permanent error waitc chan struct{} // for goroutines waiting on ReceiveBatch runningBatchSize float64 // running number of messages to request via ReceiveBatch lastBatchRecv time.Time // time when the last ReceiveBatch finished lastBatchNumMsgs int // actual number of msgs received in the last ReceiveBatch // Used in tests. preReceiveBatchHook func(maxMessages int) postReceiveBatchHook func(numMessages int) } const ( // The desired duration of a subscription's queue of messages (the messages pulled // and waiting in memory to be doled out to Receive callers). This is how long // it would take to drain the queue at the current processing rate. // The relationship to queue length (number of messages) is // // lengthInMessages = desiredQueueDuration / averageProcessTimePerMessage // // In other words, if it takes 100ms to process a message on average, and we want // 2s worth of queued messages, then we need 2/.1 = 20 messages in the queue. // // If desiredQueueDuration is too small, then there won't be a large enough buffer // of messages to handle fluctuations in processing time, and the queue is likely // to become empty, reducing throughput. If desiredQueueDuration is too large, then // messages will wait in memory for a long time, possibly timing out (that is, // their ack deadline will be exceeded). Those messages could have been handled // by another process receiving from the same subscription. desiredQueueDuration = 2 * time.Second // The initial # of messages to request via ReceiveBatch. initialBatchSize = 1 // The factor by which old batch sizes decay when a new value is added to the // running value. The larger this number, the more weight will be given to the // newest value in preference to older ones. // // The delta based on a single value is capped by the constants below. decay = 0.5 // The maximum growth factor in a single jump. Higher values mean that the // batch size can increase more aggressively. For example, 2.0 means that the // batch size will at most double from one ReceiveBatch call to the next. maxGrowthFactor = 2.0 // Similarly, the maximum shrink factor. Lower values mean that the batch size // can shrink more aggressively. For example; 0.75 means that the batch size // will at most shrink to 75% of what it was before. Note that values less // than (1-decay) will have no effect because the running value can't change // by more than that. maxShrinkFactor = 0.75 // The maximum batch size to request. Setting this too low doesn't allow // drivers to get lots of messages at once; setting it too small risks having // drivers spend a long time in ReceiveBatch trying to achieve it. maxBatchSize = 3000 ) // updateBatchSize updates the # of messages to request in ReceiveBatch based // on the previous batch size and rate of messages being pulled from the queue. // // It returns the number of messages to request in this ReceiveBatch call. // // s.mu must be held. func (s *Subscription) updateBatchSize() int { if s.fixedBatchSize != 0 { return s.fixedBatchSize } if s.lastBatchRecv.IsZero() { // First call, no data yet. s.runningBatchSize = initialBatchSize return initialBatchSize } // Compute how many msgs/sec have been pulled from the queue since our // last batch of messages was received. // Note that there's no guarantee that they have been processed yet. elapsed := time.Since(s.lastBatchRecv) msgsPerSec := float64(s.lastBatchNumMsgs) / elapsed.Seconds() // The "ideal" batch size is how many messages we'd need in the queue to // support desiredQueueDuration at the msgsPerSec rate. idealBatchSize := desiredQueueDuration.Seconds() * msgsPerSec // Move the s.runningBatchSize towards the ideal. // We first combine the previous value and the new value, with weighting // based on decay, and then cap the growth/shrinkage. newBatchSize := s.runningBatchSize*(1-decay) + idealBatchSize*decay if max := s.runningBatchSize * maxGrowthFactor; newBatchSize > max { s.runningBatchSize = max } else if min := s.runningBatchSize * maxShrinkFactor; newBatchSize < min { s.runningBatchSize = min } else { s.runningBatchSize = newBatchSize } s.runningBatchSize = math.Min(s.runningBatchSize, maxBatchSize) // Using Ceil guarantees at least one message. return int(math.Ceil(s.runningBatchSize)) } // Receive receives and returns the next message from the Subscription's queue, // blocking and polling if none are available. This method can be called // concurrently from multiple goroutines. The Ack() method of the returned // Message has to be called once the message has been processed, to prevent it // from being received again. func (s *Subscription) Receive(ctx context.Context) (_ *Message, err error) { ctx = s.tracer.Start(ctx, "Subscription.Receive") defer func() { s.tracer.End(ctx, err) }() s.mu.Lock() defer s.mu.Unlock() for { // The lock is always held here, at the top of the loop. if s.err != nil { // The Subscription is in a permanent error state. Return the error. return nil, s.err // s.err wrapped when set } if len(s.q) > 0 { // At least one message is available. Return it. m := s.q[0] s.q = s.q[1:] // TODO(jba): pre-fetch more messages if the queue gets too small. return m, nil } if s.waitc != nil { // A call to ReceiveBatch is in flight. Wait for it. // TODO(jba): support multiple calls in flight simultaneously. waitc := s.waitc s.mu.Unlock() select { case <-waitc: s.mu.Lock() continue case <-ctx.Done(): s.mu.Lock() return nil, ctx.Err() } } // No messages are available and there are no calls to ReceiveBatch in flight. // Make a call. batchSize := s.updateBatchSize() s.waitc = make(chan struct{}) s.mu.Unlock() // Even though the mutex is unlocked, only one goroutine can be here. // The only way here is if s.waitc was nil. This goroutine just set // s.waitc to non-nil while holding the lock. if s.preReceiveBatchHook != nil { s.preReceiveBatchHook(batchSize) } msgs, err := s.getNextBatch(ctx, batchSize) if s.postReceiveBatchHook != nil { s.postReceiveBatchHook(len(msgs)) } s.mu.Lock() // Update these even if there was an error; the next call to Receive will // try again to get more messages, and updateBatchSize based on 0 messages // proceesed, which is fine. s.lastBatchRecv = time.Now() s.lastBatchNumMsgs = len(msgs) close(s.waitc) s.waitc = nil if err != nil { // This goroutine's call failed, perhaps because its context was done. // Some waiting goroutine will wake up when s.waitc is closed, // go to the top of the loop, and (since s.q is empty and s.waitc is // now nil) will try the RPC for itself. return nil, err } s.q = append(s.q, msgs...) } } // getNextBatch gets the next batch of messages from the server and returns it. func (s *Subscription) getNextBatch(ctx context.Context, nMessages int) ([]*Message, error) { var msgs []*driver.Message err := retry.Call(ctx, gax.Backoff{}, s.driver.IsRetryable, func() error { var err error ctx2 := s.tracer.Start(ctx, "driver.Subscription.ReceiveBatch") defer func() { s.tracer.End(ctx2, err) }() msgs, err = s.driver.ReceiveBatch(ctx2, nMessages) return err }) if err != nil { return nil, wrapError(s.driver, err) } var q []*Message for _, m := range msgs { id := m.AckID m2 := &Message{ Body: m.Body, Metadata: m.Metadata, asFunc: m.AsFunc, } if s.ackFunc == nil { m2.ack = func() { // Ignore the error channel. Errors are dealt with // in the ackBatcher handler. _ = s.ackBatcher.AddNoWait(id) } } else { m2.ack = s.ackFunc } q = append(q, m2) } return q, nil } // Shutdown flushes pending ack sends and disconnects the Subscription. func (s *Subscription) Shutdown(ctx context.Context) (err error) { ctx = s.tracer.Start(ctx, "Subscription.Shutdown") defer func() { s.tracer.End(ctx, err) }() s.mu.Lock() s.err = gcerr.Newf(gcerr.FailedPrecondition, nil, "pubsub: Subscription closed") s.mu.Unlock() c := make(chan struct{}) go func() { defer close(c) s.ackBatcher.Shutdown() }() select { case <-ctx.Done(): case <-c: } s.cancel() return ctx.Err() } // As converts i to provider-specific types. // See https://godoc.org/gocloud.dev#hdr-As for background information, the "As" // examples in this package for examples, and the provider-specific package // documentation for the specific types supported for that provider. func (s *Subscription) As(i interface{}) bool { return s.driver.As(i) } // ErrorAs converts err to provider-specific types. // ErrorAs panics if i is nil or not a pointer. // ErrorAs returns false if err == nil. // See Topic.As for more details. func (s *Subscription) ErrorAs(err error, i interface{}) bool { return gcerr.ErrorAs(err, i, s.driver.ErrorAs) } // NewSubscription is for use by provider implementations. var NewSubscription = newSubscription // newSubscription creates a Subscription from a driver.Subscription // and a function to make a batcher that sends batches of acks to the provider. // If newAckBatcher is nil, a default batcher implementation will be used. // fixedBatchSize should be 0 except in tests, where stability is necessary for // record/replay. func newSubscription(ds driver.Subscription, fixedBatchSize int, newAckBatcher func(context.Context, *Subscription, driver.Subscription) driver.Batcher) *Subscription { ctx, cancel := context.WithCancel(context.Background()) s := &Subscription{ driver: ds, tracer: newTracer(ds), cancel: cancel, fixedBatchSize: fixedBatchSize, } if newAckBatcher == nil { newAckBatcher = defaultAckBatcher } s.ackBatcher = newAckBatcher(ctx, s, ds) s.ackFunc = ds.AckFunc() return s } // defaultAckBatcher creates a batcher for acknowledgements, for use with // NewSubscription. func defaultAckBatcher(ctx context.Context, s *Subscription, ds driver.Subscription) driver.Batcher { const maxHandlers = 1 handler := func(items interface{}) error { ids := items.([]driver.AckID) err := retry.Call(ctx, gax.Backoff{}, s.driver.IsRetryable, func() (err error) { ctx2 := s.tracer.Start(ctx, "driver.Subscription.SendAcks") defer func() { s.tracer.End(ctx2, err) }() return ds.SendAcks(ctx2, ids) }) // Remember a non-retryable error from SendAcks. It will be returned on the // next call to Receive. if err != nil { err = wrapError(s.driver, err) s.mu.Lock() s.err = err s.mu.Unlock() } return err } return batcher.New(reflect.TypeOf([]driver.AckID{}).Elem(), maxHandlers, handler) } type errorCoder interface { ErrorCode(error) gcerrors.ErrorCode } func wrapError(ec errorCoder, err error) error { if gcerr.DoNotWrap(err) { return err } return gcerr.New(ec.ErrorCode(err), err, 2, "pubsub") } // TopicURLOpener represents types than can open Topics based on a URL. // The opener must not modify the URL argument. OpenTopicURL must be safe to // call from multiple goroutines. // // This interface is generally implemented by types in driver packages. type TopicURLOpener interface { OpenTopicURL(ctx context.Context, u *url.URL) (*Topic, error) } // SubscriptionURLOpener represents types than can open Subscriptions based on a URL. // The opener must not modify the URL argument. OpenSubscriptionURL must be safe to // call from multiple goroutines. // // This interface is generally implemented by types in driver packages. type SubscriptionURLOpener interface { OpenSubscriptionURL(ctx context.Context, u *url.URL) (*Subscription, error) } // URLMux is a URL opener multiplexer. It matches the scheme of the URLs // against a set of registered schemes and calls the opener that matches the // URL's scheme. // See https://godoc.org/gocloud.dev#hdr-URLs for more information. // // The zero value is a multiplexer with no registered schemes. type URLMux struct { subscriptionSchemes openurl.SchemeMap topicSchemes openurl.SchemeMap } // RegisterTopic registers the opener with the given scheme. If an opener // already exists for the scheme, RegisterTopic panics. func (mux *URLMux) RegisterTopic(scheme string, opener TopicURLOpener) { mux.topicSchemes.Register("pubsub", "Topic", scheme, opener) } // RegisterSubscription registers the opener with the given scheme. If an opener // already exists for the scheme, RegisterSubscription panics. func (mux *URLMux) RegisterSubscription(scheme string, opener SubscriptionURLOpener) { mux.subscriptionSchemes.Register("pubsub", "Subscription", scheme, opener) } // OpenTopic calls OpenTopicURL with the URL parsed from urlstr. // OpenTopic is safe to call from multiple goroutines. func (mux *URLMux) OpenTopic(ctx context.Context, urlstr string) (*Topic, error) { opener, u, err := mux.topicSchemes.FromString("Topic", urlstr) if err != nil { return nil, err } return opener.(TopicURLOpener).OpenTopicURL(ctx, u) } // OpenSubscription calls OpenSubscriptionURL with the URL parsed from urlstr. // OpenSubscription is safe to call from multiple goroutines. func (mux *URLMux) OpenSubscription(ctx context.Context, urlstr string) (*Subscription, error) { opener, u, err := mux.subscriptionSchemes.FromString("Subscription", urlstr) if err != nil { return nil, err } return opener.(SubscriptionURLOpener).OpenSubscriptionURL(ctx, u) } // OpenTopicURL dispatches the URL to the opener that is registered with the // URL's scheme. OpenTopicURL is safe to call from multiple goroutines. func (mux *URLMux) OpenTopicURL(ctx context.Context, u *url.URL) (*Topic, error) { opener, err := mux.topicSchemes.FromURL("Topic", u) if err != nil { return nil, err } return opener.(TopicURLOpener).OpenTopicURL(ctx, u) } // OpenSubscriptionURL dispatches the URL to the opener that is registered with the // URL's scheme. OpenSubscriptionURL is safe to call from multiple goroutines. func (mux *URLMux) OpenSubscriptionURL(ctx context.Context, u *url.URL) (*Subscription, error) { opener, err := mux.subscriptionSchemes.FromURL("Subscription", u) if err != nil { return nil, err } return opener.(SubscriptionURLOpener).OpenSubscriptionURL(ctx, u) } var defaultURLMux = &URLMux{} // DefaultURLMux returns the URLMux used by OpenTopic and OpenSubscription. // // Driver packages can use this to register their TopicURLOpener and/or // SubscriptionURLOpener on the mux. func DefaultURLMux() *URLMux { return defaultURLMux } // OpenTopic opens the Topic identified by the URL given. // See the URLOpener documentation in provider-specific subpackages for // details on supported URL formats, and https://godoc.org/gocloud.dev#hdr-URLs // for more information. func OpenTopic(ctx context.Context, urlstr string) (*Topic, error) { return defaultURLMux.OpenTopic(ctx, urlstr) } // OpenSubscription opens the Subscription identified by the URL given. // See the URLOpener documentation in provider-specific subpackages for // details on supported URL formats, and https://godoc.org/gocloud.dev#hdr-URLs // for more information. func OpenSubscription(ctx context.Context, urlstr string) (*Subscription, error) { return defaultURLMux.OpenSubscription(ctx, urlstr) }
1
16,056
Not necessary, just write `time.Time{}`
google-go-cloud
go
@@ -499,6 +499,11 @@ def data(readonly=False): SettingValue(typ.Bool(), 'true'), "Whether to show favicons in the tab bar."), + ('tabbar-size', + SettingValue(typ.Int(minval=8), '12'), + "The height of the tabbar in pixels." + "This also controls the size of the favicons."), + ('width', SettingValue(typ.PercOrInt(minperc=0, maxperc=100, minint=1), '20%'),
1
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2014-2015 Florian Bruhin (The Compiler) <[email protected]> # # This file is part of qutebrowser. # # qutebrowser is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # qutebrowser is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with qutebrowser. If not, see <http://www.gnu.org/licenses/>. """Configuration data for config.py. Module attributes: FIRST_COMMENT: The initial comment header to place in the config. SECTION_DESC: A dictionary with descriptions for sections. DATA: A global read-only copy of the default config, an OrderedDict of sections. """ import sys import re import collections from qutebrowser.config import configtypes as typ from qutebrowser.config import sections as sect from qutebrowser.config.value import SettingValue from qutebrowser.utils.qtutils import MAXVALS FIRST_COMMENT = r""" # vim: ft=dosini # Configfile for qutebrowser. # # This configfile is parsed by python's configparser in extended # interpolation mode. The format is very INI-like, so there are # categories like [general] with "key = value"-pairs. # # Note that you shouldn't add your own comments, as this file is # regenerated every time the config is saved. # # Interpolation looks like ${value} or ${section:value} and will be # replaced by the respective value. # # Some settings will expand environment variables. Note that, since # interpolation is run first, you will need to escape the $ char as # described below. # # This is the default config, so if you want to remove anything from # here (as opposed to change/add), for example a key binding, set it to # an empty value. # # You will need to escape the following values: # - # at the start of the line (at the first position of the key) (\#) # - $ in a value ($$) """ SECTION_DESC = { 'general': "General/miscellaneous options.", 'ui': "General options related to the user interface.", 'input': "Options related to input modes.", 'network': "Settings related to the network.", 'completion': "Options related to completion and command history.", 'tabs': "Configuration of the tab bar.", 'storage': "Settings related to cache and storage.", 'content': "Loaded plugins/scripts and allowed actions.", 'hints': "Hinting settings.", 'searchengines': ( "Definitions of search engines which can be used via the address " "bar.\n" "The searchengine named `DEFAULT` is used when " "`general -> auto-search` is true and something else than a URL was " "entered to be opened. Other search engines can be used by prepending " "the search engine name to the search term, e.g. " "`:open google qutebrowser`. The string `{}` will be replaced by the " "search term, use `{{` and `}}` for literal `{`/`}` signs."), 'aliases': ( "Aliases for commands.\n" "By default, no aliases are defined. Example which adds a new command " "`:qtb` to open qutebrowsers website:\n\n" "`qtb = open http://www.qutebrowser.org/`"), 'colors': ( "Colors used in the UI.\n" "A value can be in one of the following format:\n\n" " * `#RGB`/`#RRGGBB`/`#RRRGGGBBB`/`#RRRRGGGGBBBB`\n" " * A SVG color name as specified in http://www.w3.org/TR/SVG/" "types.html#ColorKeywords[the W3C specification].\n" " * transparent (no color)\n" " * `rgb(r, g, b)` / `rgba(r, g, b, a)` (values 0-255 or " "percentages)\n" " * `hsv(h, s, v)` / `hsva(h, s, v, a)` (values 0-255, hue 0-359)\n" " * A gradient as explained in http://doc.qt.io/qt-5/" "stylesheet-reference.html#list-of-property-types[the Qt " "documentation] under ``Gradient''.\n\n" "A *.system value determines the color system to use for color " "interpolation between similarly-named *.start and *.stop entries, " "regardless of how they are defined in the options. " "Valid values are 'rgb', 'hsv', and 'hsl'.\n\n" "The `hints.*` values are a special case as they're real CSS " "colors, not Qt-CSS colors. There, for a gradient, you need to use " "`-webkit-gradient`, see https://www.webkit.org/blog/175/introducing-" "css-gradients/[the WebKit documentation]."), 'fonts': ( "Fonts used for the UI, with optional style/weight/size.\n\n" " * Style: `normal`/`italic`/`oblique`\n" " * Weight: `normal`, `bold`, `100`..`900`\n" " * Size: _number_ `px`/`pt`"), } DEFAULT_FONT_SIZE = '10pt' if sys.platform == 'darwin' else '8pt' def data(readonly=False): """Get the default config data. Return: A {name: section} OrderedDict. """ return collections.OrderedDict([ ('general', sect.KeyValue( ('ignore-case', SettingValue(typ.IgnoreCase(), 'smart'), "Whether to find text on a page case-insensitively."), ('wrap-search', SettingValue(typ.Bool(), 'true'), "Whether to wrap finding text to the top when arriving at the " "end."), ('startpage', SettingValue(typ.List(), 'https://www.duckduckgo.com'), "The default page(s) to open at the start, separated by commas."), ('default-page', SettingValue(typ.FuzzyUrl(), '${startpage}'), "The page to open if :open -t/-b/-w is used without URL. Use " "`about:blank` for a blank page."), ('auto-search', SettingValue(typ.AutoSearch(), 'naive'), "Whether to start a search when something else than a URL is " "entered."), ('auto-save-config', SettingValue(typ.Bool(), 'true'), "Whether to save the config automatically on quit."), ('auto-save-interval', SettingValue(typ.Int(minval=0), '15000'), "How often (in milliseconds) to auto-save config/cookies/etc."), ('editor', SettingValue(typ.ShellCommand(placeholder=True), 'gvim -f "{}"'), "The editor (and arguments) to use for the `open-editor` " "command.\n\n" "Use `{}` for the filename. The value gets split like in a " "shell, so you can use `\"` or `'` to quote arguments."), ('editor-encoding', SettingValue(typ.Encoding(), 'utf-8'), "Encoding to use for editor."), ('private-browsing', SettingValue(typ.Bool(), 'false'), "Do not record visited pages in the history or store web page " "icons."), ('developer-extras', SettingValue(typ.Bool(), 'false'), "Enable extra tools for Web developers.\n\n" "This needs to be enabled for `:inspector` to work and also adds " "an _Inspect_ entry to the context menu."), ('print-element-backgrounds', SettingValue(typ.Bool(), 'true'), "Whether the background color and images are also drawn when the " "page is printed."), ('xss-auditing', SettingValue(typ.Bool(), 'false'), "Whether load requests should be monitored for cross-site " "scripting attempts.\n\n" "Suspicious scripts will be blocked and reported in the " "inspector's JavaScript console. Enabling this feature might " "have an impact on performance."), ('site-specific-quirks', SettingValue(typ.Bool(), 'true'), "Enable workarounds for broken sites."), ('default-encoding', SettingValue(typ.String(none_ok=True), ''), "Default encoding to use for websites.\n\n" "The encoding must be a string describing an encoding such as " "_utf-8_, _iso-8859-1_, etc. If left empty a default value will " "be used."), ('new-instance-open-target', SettingValue(typ.NewInstanceOpenTarget(), 'window'), "How to open links in an existing instance if a new one is " "launched."), ('log-javascript-console', SettingValue(typ.Bool(), 'false'), "Whether to log javascript console messages."), ('save-session', SettingValue(typ.Bool(), 'false'), "Whether to always save the open pages."), ('session-default-name', SettingValue(typ.SessionName(none_ok=True), ''), "The name of the session to save by default, or empty for the " "last loaded session."), readonly=readonly )), ('ui', sect.KeyValue( ('zoom-levels', SettingValue(typ.PercList(minval=0), '25%,33%,50%,67%,75%,90%,100%,110%,125%,150%,175%,' '200%,250%,300%,400%,500%'), "The available zoom levels, separated by commas."), ('default-zoom', SettingValue(typ.Perc(), '100%'), "The default zoom level."), ('downloads-position', SettingValue(typ.VerticalPosition(), 'north'), "Where to show the downloaded files."), ('message-timeout', SettingValue(typ.Int(), '2000'), "Time (in ms) to show messages in the statusbar for."), ('message-unfocused', SettingValue(typ.Bool(), 'false'), "Whether to show messages in unfocused windows."), ('confirm-quit', SettingValue(typ.ConfirmQuit(), 'never'), "Whether to confirm quitting the application."), ('display-statusbar-messages', SettingValue(typ.Bool(), 'false'), "Whether to display javascript statusbar messages."), ('zoom-text-only', SettingValue(typ.Bool(), 'false'), "Whether the zoom factor on a frame applies only to the text or " "to all content."), ('frame-flattening', SettingValue(typ.Bool(), 'false'), "Whether to expand each subframe to its contents.\n\n" "This will flatten all the frames to become one scrollable " "page."), ('user-stylesheet', SettingValue(typ.UserStyleSheet(), '::-webkit-scrollbar { width: 0px; height: 0px; }'), "User stylesheet to use (absolute filename, filename relative to " "the config directory or CSS string). Will expand environment " "variables."), ('css-media-type', SettingValue(typ.String(none_ok=True), ''), "Set the CSS media type."), ('smooth-scrolling', SettingValue(typ.Bool(), 'false'), "Whether to enable smooth scrolling for webpages."), ('remove-finished-downloads', SettingValue(typ.Bool(), 'false'), "Whether to remove finished downloads automatically."), ('hide-statusbar', SettingValue(typ.Bool(), 'false'), "Whether to hide the statusbar unless a message is shown."), ('window-title-format', SettingValue(typ.FormatString(fields=['perc', 'perc_raw', 'title', 'title_sep', 'id']), '{perc}{title}{title_sep}qutebrowser'), "The format to use for the window title. The following " "placeholders are defined:\n\n" "* `{perc}`: The percentage as a string like `[10%]`.\n" "* `{perc_raw}`: The raw percentage, e.g. `10`\n" "* `{title}`: The title of the current web page\n" "* `{title_sep}`: The string ` - ` if a title is set, empty " "otherwise.\n" "* `{id}`: The internal window ID of this window."), ('hide-mouse-cursor', SettingValue(typ.Bool(), 'false'), "Whether to hide the mouse cursor."), ('modal-js-dialog', SettingValue(typ.Bool(), 'false'), "Use standard JavaScript modal dialog for alert() and confirm()"), readonly=readonly )), ('network', sect.KeyValue( ('do-not-track', SettingValue(typ.Bool(), 'true'), "Value to send in the `DNT` header."), ('accept-language', SettingValue(typ.String(none_ok=True), 'en-US,en'), "Value to send in the `accept-language` header."), ('user-agent', SettingValue(typ.UserAgent(none_ok=True), ''), "User agent to send. Empty to send the default."), ('proxy', SettingValue(typ.Proxy(), 'system'), "The proxy to use.\n\n" "In addition to the listed values, you can use a `socks://...` " "or `http://...` URL."), ('proxy-dns-requests', SettingValue(typ.Bool(), 'true'), "Whether to send DNS requests over the configured proxy."), ('ssl-strict', SettingValue(typ.BoolAsk(), 'ask'), "Whether to validate SSL handshakes."), ('dns-prefetch', SettingValue(typ.Bool(), 'true'), "Whether to try to pre-fetch DNS entries to speed up browsing."), readonly=readonly )), ('completion', sect.KeyValue( ('download-path-suggestion', SettingValue(typ.DownloadPathSuggestion(), 'path'), "What to display in the download filename input."), ('timestamp-format', SettingValue(typ.String(none_ok=True), '%Y-%m-%d'), "How to format timestamps (e.g. for history)"), ('show', SettingValue(typ.Bool(), 'true'), "Whether to show the autocompletion window."), ('height', SettingValue(typ.PercOrInt(minperc=0, maxperc=100, minint=1), '50%'), "The height of the completion, in px or as percentage of the " "window."), ('cmd-history-max-items', SettingValue(typ.Int(minval=-1), '100'), "How many commands to save in the command history.\n\n" "0: no history / -1: unlimited"), ('web-history-max-items', SettingValue(typ.Int(minval=-1), '1000'), "How many URLs to show in the web history.\n\n" "0: no history / -1: unlimited"), ('quick-complete', SettingValue(typ.Bool(), 'true'), "Whether to move on to the next part when there's only one " "possible completion left."), ('shrink', SettingValue(typ.Bool(), 'false'), "Whether to shrink the completion to be smaller than the " "configured size if there are no scrollbars."), readonly=readonly )), ('input', sect.KeyValue( ('timeout', SettingValue(typ.Int(minval=0, maxval=MAXVALS['int']), '500'), "Timeout for ambiguous key bindings."), ('partial-timeout', SettingValue(typ.Int(minval=0, maxval=MAXVALS['int']), '1000'), "Timeout for partially typed key bindings."), ('insert-mode-on-plugins', SettingValue(typ.Bool(), 'false'), "Whether to switch to insert mode when clicking flash and other " "plugins."), ('auto-leave-insert-mode', SettingValue(typ.Bool(), 'true'), "Whether to leave insert mode if a non-editable element is " "clicked."), ('auto-insert-mode', SettingValue(typ.Bool(), 'false'), "Whether to automatically enter insert mode if an editable " "element is focused after page load."), ('forward-unbound-keys', SettingValue(typ.ForwardUnboundKeys(), 'auto'), "Whether to forward unbound keys to the webview in normal mode."), ('spatial-navigation', SettingValue(typ.Bool(), 'false'), "Enables or disables the Spatial Navigation feature\n\n" "Spatial navigation consists in the ability to navigate between " "focusable elements in a Web page, such as hyperlinks and form " "controls, by using Left, Right, Up and Down arrow keys. For " "example, if a user presses the Right key, heuristics determine " "whether there is an element he might be trying to reach towards " "the right and which element he probably wants."), ('links-included-in-focus-chain', SettingValue(typ.Bool(), 'true'), "Whether hyperlinks should be included in the keyboard focus " "chain."), ('rocker-gestures', SettingValue(typ.Bool(), 'false'), "Whether to enable Opera-like mouse rocker gestures. This " "disables the context menu."), ('mouse-zoom-divider', SettingValue(typ.Int(minval=1), '512'), "How much to divide the mouse wheel movements to translate them " "into zoom increments."), readonly=readonly )), ('tabs', sect.KeyValue( ('background-tabs', SettingValue(typ.Bool(), 'false'), "Whether to open new tabs (middleclick/ctrl+click) in " "background."), ('select-on-remove', SettingValue(typ.SelectOnRemove(), 'right'), "Which tab to select when the focused tab is removed."), ('new-tab-position', SettingValue(typ.NewTabPosition(), 'right'), "How new tabs are positioned."), ('new-tab-position-explicit', SettingValue(typ.NewTabPosition(), 'last'), "How new tabs opened explicitly are positioned."), ('last-close', SettingValue(typ.LastClose(), 'ignore'), "Behavior when the last tab is closed."), ('hide-auto', SettingValue(typ.Bool(), 'false'), "Hide the tab bar if only one tab is open."), ('hide-always', SettingValue(typ.Bool(), 'false'), "Always hide the tab bar."), ('wrap', SettingValue(typ.Bool(), 'true'), "Whether to wrap when changing tabs."), ('movable', SettingValue(typ.Bool(), 'true'), "Whether tabs should be movable."), ('close-mouse-button', SettingValue(typ.CloseButton(), 'middle'), "On which mouse button to close tabs."), ('position', SettingValue(typ.Position(), 'north'), "The position of the tab bar."), ('show-favicons', SettingValue(typ.Bool(), 'true'), "Whether to show favicons in the tab bar."), ('width', SettingValue(typ.PercOrInt(minperc=0, maxperc=100, minint=1), '20%'), "The width of the tab bar if it's vertical, in px or as " "percentage of the window."), ('indicator-width', SettingValue(typ.Int(minval=0), '3'), "Width of the progress indicator (0 to disable)."), ('indicator-space', SettingValue(typ.Int(minval=0), '3'), "Spacing between tab edge and indicator."), ('tabs-are-windows', SettingValue(typ.Bool(), 'false'), "Whether to open windows instead of tabs."), ('title-format', SettingValue(typ.FormatString( fields=['perc', 'perc_raw', 'title', 'title_sep', 'index', 'id']), '{index}: {title}'), "The format to use for the tab title. The following placeholders " "are defined:\n\n" "* `{perc}`: The percentage as a string like `[10%]`.\n" "* `{perc_raw}`: The raw percentage, e.g. `10`\n" "* `{title}`: The title of the current web page\n" "* `{title_sep}`: The string ` - ` if a title is set, empty " "otherwise.\n" "* `{index}`: The index of this tab.\n" "* `{id}`: The internal tab ID of this tab."), ('mousewheel-tab-switching', SettingValue(typ.Bool(), 'true'), "Switch between tabs using the mouse wheel."), readonly=readonly )), ('storage', sect.KeyValue( ('download-directory', SettingValue(typ.Directory(none_ok=True), ''), "The directory to save downloads to. An empty value selects a " "sensible os-specific default. Will expand environment " "variables."), ('maximum-pages-in-cache', SettingValue( typ.Int(none_ok=True, minval=0, maxval=MAXVALS['int']), ''), "The maximum number of pages to hold in the global memory page " "cache.\n\n" "The Page Cache allows for a nicer user experience when " "navigating forth or back to pages in the forward/back history, " "by pausing and resuming up to _n_ pages.\n\n" "For more information about the feature, please refer to: " "http://webkit.org/blog/427/webkit-page-cache-i-the-basics/"), ('object-cache-capacities', SettingValue( typ.WebKitBytesList(length=3, maxsize=MAXVALS['int']), ''), "The capacities for the global memory cache for dead objects " "such as stylesheets or scripts. Syntax: cacheMinDeadCapacity, " "cacheMaxDead, totalCapacity.\n\n" "The _cacheMinDeadCapacity_ specifies the minimum number of " "bytes that dead objects should consume when the cache is under " "pressure.\n\n" "_cacheMaxDead_ is the maximum number of bytes that dead objects " "should consume when the cache is *not* under pressure.\n\n" "_totalCapacity_ specifies the maximum number of bytes " "that the cache should consume *overall*."), ('offline-storage-default-quota', SettingValue(typ.WebKitBytes(maxsize=MAXVALS['int64']), ''), "Default quota for new offline storage databases."), ('offline-web-application-cache-quota', SettingValue(typ.WebKitBytes(maxsize=MAXVALS['int64']), ''), "Quota for the offline web application cache."), ('offline-storage-database', SettingValue(typ.Bool(), 'true'), "Whether support for the HTML 5 offline storage feature is " "enabled."), ('offline-web-application-storage', SettingValue(typ.Bool(), 'true'), "Whether support for the HTML 5 web application cache feature is " "enabled.\n\n" "An application cache acts like an HTTP cache in some sense. For " "documents that use the application cache via JavaScript, the " "loader engine will first ask the application cache for the " "contents, before hitting the network.\n\n" "The feature is described in details at: " "http://dev.w3.org/html5/spec/Overview.html#appcache"), ('local-storage', SettingValue(typ.Bool(), 'true'), "Whether support for the HTML 5 local storage feature is " "enabled."), ('cache-size', SettingValue(typ.Int(minval=0, maxval=MAXVALS['int64']), '52428800'), "Size of the HTTP network cache."), readonly=readonly )), ('content', sect.KeyValue( ('allow-images', SettingValue(typ.Bool(), 'true'), "Whether images are automatically loaded in web pages."), ('allow-javascript', SettingValue(typ.Bool(), 'true'), "Enables or disables the running of JavaScript programs."), ('allow-plugins', SettingValue(typ.Bool(), 'false'), "Enables or disables plugins in Web pages.\n\n" 'Qt plugins with a mimetype such as "application/x-qt-plugin" ' "are not affected by this setting."), ('webgl', SettingValue(typ.Bool(), 'true'), "Enables or disables WebGL."), ('css-regions', SettingValue(typ.Bool(), 'true'), "Enable or disable support for CSS regions."), ('hyperlink-auditing', SettingValue(typ.Bool(), 'false'), "Enable or disable hyperlink auditing (<a ping>)."), ('geolocation', SettingValue(typ.BoolAsk(), 'ask'), "Allow websites to request geolocations."), ('notifications', SettingValue(typ.BoolAsk(), 'ask'), "Allow websites to show notifications."), #('allow-java', # SettingValue(typ.Bool(), 'true'), # "Enables or disables Java applets. Currently Java applets are " # "not supported"), ('javascript-can-open-windows', SettingValue(typ.Bool(), 'false'), "Whether JavaScript programs can open new windows."), ('javascript-can-close-windows', SettingValue(typ.Bool(), 'false'), "Whether JavaScript programs can close windows."), ('javascript-can-access-clipboard', SettingValue(typ.Bool(), 'false'), "Whether JavaScript programs can read or write to the " "clipboard."), ('ignore-javascript-prompt', SettingValue(typ.Bool(), 'false'), "Whether all javascript prompts should be ignored."), ('ignore-javascript-alert', SettingValue(typ.Bool(), 'false'), "Whether all javascript alerts should be ignored."), ('local-content-can-access-remote-urls', SettingValue(typ.Bool(), 'false'), "Whether locally loaded documents are allowed to access remote " "urls."), ('local-content-can-access-file-urls', SettingValue(typ.Bool(), 'true'), "Whether locally loaded documents are allowed to access other " "local urls."), ('cookies-accept', SettingValue(typ.AcceptCookies(), 'no-3rdparty'), "Control which cookies to accept."), ('cookies-store', SettingValue(typ.Bool(), 'true'), "Whether to store cookies."), ('host-block-lists', SettingValue( typ.UrlList(none_ok=True), 'http://www.malwaredomainlist.com/hostslist/hosts.txt,' 'http://someonewhocares.org/hosts/hosts,' 'http://winhelp2002.mvps.org/hosts.zip,' 'http://malwaredomains.lehigh.edu/files/justdomains.zip,' 'http://pgl.yoyo.org/adservers/serverlist.php?' 'hostformat=hosts&mimetype=plaintext'), "List of URLs of lists which contain hosts to block.\n\n" "The file can be in one of the following formats:\n\n" "- An '/etc/hosts'-like file\n" "- One host per line\n" "- A zip-file of any of the above, with either only one file, or " "a file named 'hosts' (with any extension)."), ('host-blocking-enabled', SettingValue(typ.Bool(), 'true'), "Whether host blocking is enabled."), readonly=readonly )), ('hints', sect.KeyValue( ('border', SettingValue(typ.String(), '1px solid #E3BE23'), "CSS border value for hints."), ('opacity', SettingValue(typ.Float(minval=0.0, maxval=1.0), '0.7'), "Opacity for hints."), ('mode', SettingValue(typ.HintMode(), 'letter'), "Mode to use for hints."), ('chars', SettingValue(typ.String(minlen=2), 'asdfghjkl'), "Chars used for hint strings."), ('min-chars', SettingValue(typ.Int(minval=1), '1'), "Mininum number of chars used for hint strings."), ('scatter', SettingValue(typ.Bool(), 'true'), "Whether to scatter hint key chains (like Vimium) or not (like " "dwb)."), ('uppercase', SettingValue(typ.Bool(), 'false'), "Make chars in hint strings uppercase."), ('auto-follow', SettingValue(typ.Bool(), 'true'), "Whether to auto-follow a hint if there's only one left."), ('next-regexes', SettingValue(typ.RegexList(flags=re.IGNORECASE), r'\bnext\b,\bmore\b,\bnewer\b,\b[>→≫]\b,\b(>>|»)\b,' r'\bcontinue\b'), "A comma-separated list of regexes to use for 'next' links."), ('prev-regexes', SettingValue(typ.RegexList(flags=re.IGNORECASE), r'\bprev(ious)?\b,\bback\b,\bolder\b,\b[<←≪]\b,' r'\b(<<|«)\b'), "A comma-separated list of regexes to use for 'prev' links."), readonly=readonly )), ('searchengines', sect.ValueList( typ.SearchEngineName(), typ.SearchEngineUrl(), ('DEFAULT', 'https://duckduckgo.com/?q={}'), readonly=readonly )), ('aliases', sect.ValueList( typ.String(forbidden=' '), typ.Command(), readonly=readonly )), ('colors', sect.KeyValue( ('completion.fg', SettingValue(typ.QtColor(), 'white'), "Text color of the completion widget."), ('completion.bg', SettingValue(typ.QssColor(), '#333333'), "Background color of the completion widget."), ('completion.alternate-bg', SettingValue(typ.QssColor(), '#444444'), "Alternating background color of the completion widget."), ('completion.category.fg', SettingValue(typ.QtColor(), 'white'), "Foreground color of completion widget category headers."), ('completion.category.bg', SettingValue(typ.QssColor(), 'qlineargradient(x1:0, y1:0, x2:0, ' 'y2:1, stop:0 #888888, stop:1 #505050)'), "Background color of the completion widget category headers."), ('completion.category.border.top', SettingValue(typ.QssColor(), 'black'), "Top border color of the completion widget category headers."), ('completion.category.border.bottom', SettingValue(typ.QssColor(), '${completion.category.border.top}'), "Bottom border color of the completion widget category headers."), ('completion.item.selected.fg', SettingValue(typ.QtColor(), 'black'), "Foreground color of the selected completion item."), ('completion.item.selected.bg', SettingValue(typ.QssColor(), '#e8c000'), "Background color of the selected completion item."), ('completion.item.selected.border.top', SettingValue(typ.QssColor(), '#bbbb00'), "Top border color of the completion widget category headers."), ('completion.item.selected.border.bottom', SettingValue( typ.QssColor(), '${completion.item.selected.border.top}'), "Bottom border color of the selected completion item."), ('completion.match.fg', SettingValue(typ.QssColor(), '#ff4444'), "Foreground color of the matched text in the completion."), ('statusbar.fg', SettingValue(typ.QssColor(), 'white'), "Foreground color of the statusbar."), ('statusbar.bg', SettingValue(typ.QssColor(), 'black'), "Foreground color of the statusbar."), ('statusbar.fg.error', SettingValue(typ.QssColor(), '${statusbar.fg}'), "Foreground color of the statusbar if there was an error."), ('statusbar.bg.error', SettingValue(typ.QssColor(), 'red'), "Background color of the statusbar if there was an error."), ('statusbar.fg.warning', SettingValue(typ.QssColor(), '${statusbar.fg}'), "Foreground color of the statusbar if there is a warning."), ('statusbar.bg.warning', SettingValue(typ.QssColor(), 'darkorange'), "Background color of the statusbar if there is a warning."), ('statusbar.fg.prompt', SettingValue(typ.QssColor(), '${statusbar.fg}'), "Foreground color of the statusbar if there is a prompt."), ('statusbar.bg.prompt', SettingValue(typ.QssColor(), 'darkblue'), "Background color of the statusbar if there is a prompt."), ('statusbar.fg.insert', SettingValue(typ.QssColor(), '${statusbar.fg}'), "Foreground color of the statusbar in insert mode."), ('statusbar.bg.insert', SettingValue(typ.QssColor(), 'darkgreen'), "Background color of the statusbar in insert mode."), ('statusbar.fg.command', SettingValue(typ.QssColor(), '${statusbar.fg}'), "Foreground color of the statusbar in command mode."), ('statusbar.bg.command', SettingValue(typ.QssColor(), '${statusbar.bg}'), "Background color of the statusbar in command mode."), ('statusbar.fg.caret', SettingValue(typ.QssColor(), '${statusbar.fg}'), "Foreground color of the statusbar in caret mode."), ('statusbar.bg.caret', SettingValue(typ.QssColor(), 'purple'), "Background color of the statusbar in caret mode."), ('statusbar.fg.caret-selection', SettingValue(typ.QssColor(), '${statusbar.fg}'), "Foreground color of the statusbar in caret mode with a " "selection"), ('statusbar.bg.caret-selection', SettingValue(typ.QssColor(), '#a12dff'), "Background color of the statusbar in caret mode with a " "selection"), ('statusbar.progress.bg', SettingValue(typ.QssColor(), 'white'), "Background color of the progress bar."), ('statusbar.url.fg', SettingValue(typ.QssColor(), '${statusbar.fg}'), "Default foreground color of the URL in the statusbar."), ('statusbar.url.fg.success', SettingValue(typ.QssColor(), 'lime'), "Foreground color of the URL in the statusbar on successful " "load."), ('statusbar.url.fg.error', SettingValue(typ.QssColor(), 'orange'), "Foreground color of the URL in the statusbar on error."), ('statusbar.url.fg.warn', SettingValue(typ.QssColor(), 'yellow'), "Foreground color of the URL in the statusbar when there's a " "warning."), ('statusbar.url.fg.hover', SettingValue(typ.QssColor(), 'aqua'), "Foreground color of the URL in the statusbar for hovered " "links."), ('tabs.fg.odd', SettingValue(typ.QtColor(), 'white'), "Foreground color of unselected odd tabs."), ('tabs.bg.odd', SettingValue(typ.QtColor(), 'grey'), "Background color of unselected odd tabs."), ('tabs.fg.even', SettingValue(typ.QtColor(), 'white'), "Foreground color of unselected even tabs."), ('tabs.bg.even', SettingValue(typ.QtColor(), 'darkgrey'), "Background color of unselected even tabs."), ('tabs.fg.selected', SettingValue(typ.QtColor(), 'white'), "Foreground color of selected tabs."), ('tabs.bg.selected', SettingValue(typ.QtColor(), 'black'), "Background color of selected tabs."), ('tabs.bg.bar', SettingValue(typ.QtColor(), '#555555'), "Background color of the tab bar."), ('tabs.indicator.start', SettingValue(typ.QtColor(), '#0000aa'), "Color gradient start for the tab indicator."), ('tabs.indicator.stop', SettingValue(typ.QtColor(), '#00aa00'), "Color gradient end for the tab indicator."), ('tabs.indicator.error', SettingValue(typ.QtColor(), '#ff0000'), "Color for the tab indicator on errors.."), ('tabs.indicator.system', SettingValue(typ.ColorSystem(), 'rgb'), "Color gradient interpolation system for the tab indicator."), ('hints.fg', SettingValue(typ.CssColor(), 'black'), "Font color for hints."), ('hints.bg', SettingValue( typ.CssColor(), '-webkit-gradient(linear, left top, ' 'left bottom, color-stop(0%,#FFF785), ' 'color-stop(100%,#FFC542))'), "Background color for hints."), ('hints.fg.match', SettingValue(typ.CssColor(), 'green'), "Font color for the matched part of hints."), ('downloads.bg.bar', SettingValue(typ.QssColor(), 'black'), "Background color for the download bar."), ('downloads.fg.start', SettingValue(typ.QtColor(), 'white'), "Color gradient start for download text."), ('downloads.bg.start', SettingValue(typ.QtColor(), '#0000aa'), "Color gradient start for download backgrounds."), ('downloads.fg.stop', SettingValue(typ.QtColor(), '${downloads.fg.start}'), "Color gradient end for download text."), ('downloads.bg.stop', SettingValue(typ.QtColor(), '#00aa00'), "Color gradient stop for download backgrounds."), ('downloads.fg.system', SettingValue(typ.ColorSystem(), 'rgb'), "Color gradient interpolation system for download text."), ('downloads.bg.system', SettingValue(typ.ColorSystem(), 'rgb'), "Color gradient interpolation system for download backgrounds."), ('downloads.fg.error', SettingValue(typ.QtColor(), 'white'), "Foreground color for downloads with errors."), ('downloads.bg.error', SettingValue(typ.QtColor(), 'red'), "Background color for downloads with errors."), ('webpage.bg', SettingValue(typ.QtColor(none_ok=True), 'white'), "Background color for webpages if unset (or empty to use the " "theme's color)"), readonly=readonly )), ('fonts', sect.KeyValue( ('_monospace', SettingValue(typ.Font(), 'Terminus, Monospace, ' '"DejaVu Sans Mono", Monaco, ' '"Bitstream Vera Sans Mono", "Andale Mono", ' '"Liberation Mono", "Courier New", Courier, ' 'monospace, Fixed, Consolas, Terminal'), "Default monospace fonts."), ('completion', SettingValue(typ.Font(), DEFAULT_FONT_SIZE + ' ${_monospace}'), "Font used in the completion widget."), ('tabbar', SettingValue(typ.QtFont(), DEFAULT_FONT_SIZE + ' ${_monospace}'), "Font used in the tab bar."), ('statusbar', SettingValue(typ.Font(), DEFAULT_FONT_SIZE + ' ${_monospace}'), "Font used in the statusbar."), ('downloads', SettingValue(typ.Font(), DEFAULT_FONT_SIZE + ' ${_monospace}'), "Font used for the downloadbar."), ('hints', SettingValue(typ.Font(), 'bold 12px Monospace'), "Font used for the hints."), ('debug-console', SettingValue(typ.QtFont(), DEFAULT_FONT_SIZE + ' ${_monospace}'), "Font used for the debugging console."), ('web-family-standard', SettingValue(typ.FontFamily(none_ok=True), ''), "Font family for standard fonts."), ('web-family-fixed', SettingValue(typ.FontFamily(none_ok=True), ''), "Font family for fixed fonts."), ('web-family-serif', SettingValue(typ.FontFamily(none_ok=True), ''), "Font family for serif fonts."), ('web-family-sans-serif', SettingValue(typ.FontFamily(none_ok=True), ''), "Font family for sans-serif fonts."), ('web-family-cursive', SettingValue(typ.FontFamily(none_ok=True), ''), "Font family for cursive fonts."), ('web-family-fantasy', SettingValue(typ.FontFamily(none_ok=True), ''), "Font family for fantasy fonts."), ('web-size-minimum', SettingValue( typ.Int(none_ok=True, minval=1, maxval=MAXVALS['int']), ''), "The hard minimum font size."), ('web-size-minimum-logical', SettingValue( typ.Int(none_ok=True, minval=1, maxval=MAXVALS['int']), ''), "The minimum logical font size that is applied when zooming " "out."), ('web-size-default', SettingValue( typ.Int(none_ok=True, minval=1, maxval=MAXVALS['int']), ''), "The default font size for regular text."), ('web-size-default-fixed', SettingValue( typ.Int(none_ok=True, minval=1, maxval=MAXVALS['int']), ''), "The default font size for fixed-pitch text."), readonly=readonly )), ]) DATA = data(readonly=True) KEY_FIRST_COMMENT = """ # vim: ft=conf # # In this config file, qutebrowser's key bindings are configured. # The format looks like this: # # [keymode] # # command # keychain # keychain2 # ... # # All blank lines and lines starting with '#' are ignored. # Inline-comments are not permitted. # # keymode is a comma separated list of modes in which the key binding should be # active. If keymode starts with !, the key binding is active in all modes # except the listed modes. # # For special keys (can't be part of a keychain), enclose them in `<`...`>`. # For modifiers, you can use either `-` or `+` as delimiters, and these names: # # * Control: `Control`, `Ctrl` # * Meta: `Meta`, `Windows`, `Mod4` # * Alt: `Alt`, `Mod1` # * Shift: `Shift` # # For simple keys (no `<>`-signs), a capital letter means the key is pressed # with Shift. For special keys (with `<>`-signs), you need to explicitly add # `Shift-` to match a key pressed with shift. You can bind multiple commands # by separating them with `;;`. """ KEY_SECTION_DESC = { 'all': "Keybindings active in all modes.", 'normal': "Keybindings for normal mode.", 'insert': ( "Keybindings for insert mode.\n" "Since normal keypresses are passed through, only special keys are " "supported in this mode.\n" "Useful hidden commands to map in this section:\n\n" " * `open-editor`: Open a texteditor with the focused field."), 'hint': ( "Keybindings for hint mode.\n" "Since normal keypresses are passed through, only special keys are " "supported in this mode.\n" "Useful hidden commands to map in this section:\n\n" " * `follow-hint`: Follow the currently selected hint."), 'passthrough': ( "Keybindings for passthrough mode.\n" "Since normal keypresses are passed through, only special keys are " "supported in this mode."), 'command': ( "Keybindings for command mode.\n" "Since normal keypresses are passed through, only special keys are " "supported in this mode.\n" "Useful hidden commands to map in this section:\n\n" " * `command-history-prev`: Switch to previous command in history.\n" " * `command-history-next`: Switch to next command in history.\n" " * `completion-item-prev`: Select previous item in completion.\n" " * `completion-item-next`: Select next item in completion.\n" " * `command-accept`: Execute the command currently in the " "commandline."), 'prompt': ( "Keybindings for prompts in the status line.\n" "You can bind normal keys in this mode, but they will be only active " "when a yes/no-prompt is asked. For other prompt modes, you can only " "bind special keys.\n" "Useful hidden commands to map in this section:\n\n" " * `prompt-accept`: Confirm the entered value.\n" " * `prompt-yes`: Answer yes to a yes/no question.\n" " * `prompt-no`: Answer no to a yes/no question."), 'caret': ( ""), } # Keys which are similar to Return and should be bound by default where Return # is bound. RETURN_KEYS = ['<Return>', '<Ctrl-M>', '<Ctrl-J>', '<Shift-Return>', '<Enter>', '<Shift-Enter>'] KEY_DATA = collections.OrderedDict([ ('!normal', collections.OrderedDict([ ('leave-mode', ['<Escape>', '<Ctrl-[>']), ])), ('normal', collections.OrderedDict([ ('search ;; clear-keychain', ['<Escape>']), ('set-cmd-text -s :open', ['o']), ('set-cmd-text :open {url}', ['go']), ('set-cmd-text -s :open -t', ['O']), ('set-cmd-text :open -t {url}', ['gO']), ('set-cmd-text -s :open -b', ['xo']), ('set-cmd-text :open -b {url}', ['xO']), ('set-cmd-text -s :open -w', ['wo']), ('set-cmd-text :open -w {url}', ['wO']), ('open -t', ['ga', '<Ctrl-T>']), ('tab-close', ['d', '<Ctrl-W>']), ('tab-close -o', ['D']), ('tab-only', ['co']), ('tab-focus', ['T']), ('tab-move', ['gm']), ('tab-move -', ['gl']), ('tab-move +', ['gr']), ('tab-next', ['J', 'gt']), ('tab-prev', ['K', 'gT']), ('tab-clone', ['gC']), ('reload', ['r']), ('reload -f', ['R']), ('back', ['H', '<Backspace>']), ('back -t', ['th']), ('back -w', ['wh']), ('forward', ['L']), ('forward -t', ['tl']), ('forward -w', ['wl']), ('fullscreen', ['<F11>']), ('hint', ['f']), ('hint all tab', ['F']), ('hint all window', ['wf']), ('hint all tab-bg', [';b']), ('hint all tab-fg', [';f']), ('hint all hover', [';h']), ('hint images', [';i']), ('hint images tab', [';I']), ('hint images tab-bg', ['.i']), ('hint links fill ":open {hint-url}"', [';o']), ('hint links fill ":open -t {hint-url}"', [';O']), ('hint links fill ":open -b {hint-url}"', ['.o']), ('hint links yank', [';y']), ('hint links yank-primary', [';Y']), ('hint --rapid links tab-bg', [';r']), ('hint --rapid links window', [';R']), ('hint links download', [';d']), ('scroll left', ['h']), ('scroll down', ['j']), ('scroll up', ['k']), ('scroll right', ['l']), ('undo', ['u', '<Ctrl-Shift-T>']), ('scroll-perc 0', ['gg']), ('scroll-perc', ['G']), ('search-next', ['n']), ('search-prev', ['N']), ('enter-mode insert', ['i']), ('enter-mode caret', ['v']), ('yank', ['yy']), ('yank -s', ['yY']), ('yank -t', ['yt']), ('yank -ts', ['yT']), ('yank -d', ['yd']), ('yank -ds', ['yD']), ('paste', ['pp']), ('paste -s', ['pP']), ('paste -t', ['Pp']), ('paste -ts', ['PP']), ('paste -w', ['wp']), ('paste -ws', ['wP']), ('quickmark-save', ['m']), ('set-cmd-text -s :quickmark-load', ['b']), ('set-cmd-text -s :quickmark-load -t', ['B']), ('set-cmd-text -s :quickmark-load -w', ['wb']), ('save', ['sf']), ('set-cmd-text -s :set', ['ss']), ('set-cmd-text -s :set -t', ['sl']), ('set-cmd-text -s :set keybind', ['sk']), ('zoom-out', ['-']), ('zoom-in', ['+']), ('zoom', ['=']), ('navigate prev', ['[[']), ('navigate next', [']]']), ('navigate prev -t', ['{{']), ('navigate next -t', ['}}']), ('navigate up', ['gu']), ('navigate up -t', ['gU']), ('navigate increment', ['<Ctrl-A>']), ('navigate decrement', ['<Ctrl-X>']), ('inspector', ['wi']), ('download', ['gd']), ('download-cancel', ['ad']), ('download-remove --all', ['cd']), ('view-source', ['gf']), ('tab-focus last', ['<Ctrl-Tab>']), ('enter-mode passthrough', ['<Ctrl-V>']), ('quit', ['<Ctrl-Q>']), ('scroll-page 0 1', ['<Ctrl-F>']), ('scroll-page 0 -1', ['<Ctrl-B>']), ('scroll-page 0 0.5', ['<Ctrl-D>']), ('scroll-page 0 -0.5', ['<Ctrl-U>']), ('tab-focus 1', ['<Alt-1>']), ('tab-focus 2', ['<Alt-2>']), ('tab-focus 3', ['<Alt-3>']), ('tab-focus 4', ['<Alt-4>']), ('tab-focus 5', ['<Alt-5>']), ('tab-focus 6', ['<Alt-6>']), ('tab-focus 7', ['<Alt-7>']), ('tab-focus 8', ['<Alt-8>']), ('tab-focus 9', ['<Alt-9>']), ('home', ['<Ctrl-h>']), ('stop', ['<Ctrl-s>']), ('print', ['<Ctrl-Alt-p>']), ('open qute:settings', ['Ss']), ('follow-selected', RETURN_KEYS), ('follow-selected -t', ['<Ctrl-Return>', '<Ctrl-Enter>']), ])), ('insert', collections.OrderedDict([ ('open-editor', ['<Ctrl-E>']), ])), ('hint', collections.OrderedDict([ ('follow-hint', RETURN_KEYS), ('hint --rapid links tab-bg', ['<Ctrl-R>']), ('hint links', ['<Ctrl-F>']), ('hint all tab-bg', ['<Ctrl-B>']), ])), ('passthrough', {}), ('command', collections.OrderedDict([ ('command-history-prev', ['<Ctrl-P>']), ('command-history-next', ['<Ctrl-N>']), ('completion-item-prev', ['<Shift-Tab>', '<Up>']), ('completion-item-next', ['<Tab>', '<Down>']), ('command-accept', RETURN_KEYS), ])), ('prompt', collections.OrderedDict([ ('prompt-accept', RETURN_KEYS), ('prompt-yes', ['y']), ('prompt-no', ['n']), ])), ('command,prompt', collections.OrderedDict([ ('rl-backward-char', ['<Ctrl-B>']), ('rl-forward-char', ['<Ctrl-F>']), ('rl-backward-word', ['<Alt-B>']), ('rl-forward-word', ['<Alt-F>']), ('rl-beginning-of-line', ['<Ctrl-A>']), ('rl-end-of-line', ['<Ctrl-E>']), ('rl-unix-line-discard', ['<Ctrl-U>']), ('rl-kill-line', ['<Ctrl-K>']), ('rl-kill-word', ['<Alt-D>']), ('rl-unix-word-rubout', ['<Ctrl-W>']), ('rl-yank', ['<Ctrl-Y>']), ('rl-delete-char', ['<Ctrl-?>']), ('rl-backward-delete-char', ['<Ctrl-H>']), ])), ('caret', collections.OrderedDict([ ('toggle-selection', ['v', '<Space>']), ('drop-selection', ['<Ctrl-Space>']), ('enter-mode normal', ['c']), ('move-to-next-line', ['j']), ('move-to-prev-line', ['k']), ('move-to-next-char', ['l']), ('move-to-prev-char', ['h']), ('move-to-end-of-word', ['e']), ('move-to-next-word', ['w']), ('move-to-prev-word', ['b']), ('move-to-start-of-next-block', [']']), ('move-to-start-of-prev-block', ['[']), ('move-to-end-of-next-block', ['}']), ('move-to-end-of-prev-block', ['{']), ('move-to-start-of-line', ['0']), ('move-to-end-of-line', ['$']), ('move-to-start-of-document', ['gg']), ('move-to-end-of-document', ['G']), ('yank-selected -p', ['Y']), ('yank-selected', ['y'] + RETURN_KEYS), ('scroll left', ['H']), ('scroll down', ['J']), ('scroll up', ['K']), ('scroll right', ['L']), ])), ]) # A list of (regex, replacement) tuples of changed key commands. CHANGED_KEY_COMMANDS = [ (re.compile(r'^open -([twb]) about:blank$'), r'open -\1'), (re.compile(r'^download-page$'), r'download'), (re.compile(r'^cancel-download$'), r'download-cancel'), (re.compile(r"""^search (''|"")$"""), r'search ;; clear-keychain'), (re.compile(r'^search$'), r'search ;; clear-keychain'), (re.compile(r"""^set-cmd-text ['"](.*) ['"]$"""), r'set-cmd-text -s \1'), (re.compile(r"""^set-cmd-text ['"](.*)['"]$"""), r'set-cmd-text \1'), (re.compile(r"^hint links rapid$"), r'hint --rapid links tab-bg'), (re.compile(r"^hint links rapid-win$"), r'hint --rapid links window'), (re.compile(r'^scroll -50 0$'), r'scroll left'), (re.compile(r'^scroll 0 50$'), r'scroll down'), (re.compile(r'^scroll 0 -50$'), r'scroll up'), (re.compile(r'^scroll 50 0$'), r'scroll right'), (re.compile(r'^scroll ([-\d]+ [-\d]+)$'), r'scroll-px \1'), ]
1
13,185
As these two strings simply get concatenated for the docs, there's a space missing after the dot here.
qutebrowser-qutebrowser
py
@@ -29,6 +29,7 @@ namespace Datadog.Trace.ClrProfiler.CallTarget { if (IntegrationOptions<TIntegration, TTarget>.IsIntegrationEnabled) { + IntegrationOptions<TIntegration, TTarget>.RecordTelemetry(); return BeginMethodHandler<TIntegration, TTarget>.Invoke(instance); }
1
// <copyright file="CallTargetInvoker.cs" company="Datadog"> // Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. // This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. // </copyright> using System; using System.ComponentModel; using System.Runtime.CompilerServices; using Datadog.Trace.ClrProfiler.CallTarget.Handlers; namespace Datadog.Trace.ClrProfiler.CallTarget { /// <summary> /// CallTarget Invoker /// </summary> [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public static class CallTargetInvoker { /// <summary> /// Begin Method Invoker /// </summary> /// <typeparam name="TIntegration">Integration type</typeparam> /// <typeparam name="TTarget">Target type</typeparam> /// <param name="instance">Instance value</param> /// <returns>Call target state</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static CallTargetState BeginMethod<TIntegration, TTarget>(TTarget instance) { if (IntegrationOptions<TIntegration, TTarget>.IsIntegrationEnabled) { return BeginMethodHandler<TIntegration, TTarget>.Invoke(instance); } return CallTargetState.GetDefault(); } /// <summary> /// Begin Method Invoker /// </summary> /// <typeparam name="TIntegration">Integration type</typeparam> /// <typeparam name="TTarget">Target type</typeparam> /// <typeparam name="TArg1">First argument type</typeparam> /// <param name="instance">Instance value</param> /// <param name="arg1">First argument value</param> /// <returns>Call target state</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static CallTargetState BeginMethod<TIntegration, TTarget, TArg1>(TTarget instance, TArg1 arg1) { if (IntegrationOptions<TIntegration, TTarget>.IsIntegrationEnabled) { return BeginMethodHandler<TIntegration, TTarget, TArg1>.Invoke(instance, ref arg1); } return CallTargetState.GetDefault(); } /// <summary> /// Begin Method Invoker /// </summary> /// <typeparam name="TIntegration">Integration type</typeparam> /// <typeparam name="TTarget">Target type</typeparam> /// <typeparam name="TArg1">First argument type</typeparam> /// <typeparam name="TArg2">Second argument type</typeparam> /// <param name="instance">Instance value</param> /// <param name="arg1">First argument value</param> /// <param name="arg2">Second argument value</param> /// <returns>Call target state</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static CallTargetState BeginMethod<TIntegration, TTarget, TArg1, TArg2>(TTarget instance, TArg1 arg1, TArg2 arg2) { if (IntegrationOptions<TIntegration, TTarget>.IsIntegrationEnabled) { return BeginMethodHandler<TIntegration, TTarget, TArg1, TArg2>.Invoke(instance, ref arg1, ref arg2); } return CallTargetState.GetDefault(); } /// <summary> /// Begin Method Invoker /// </summary> /// <typeparam name="TIntegration">Integration type</typeparam> /// <typeparam name="TTarget">Target type</typeparam> /// <typeparam name="TArg1">First argument type</typeparam> /// <typeparam name="TArg2">Second argument type</typeparam> /// <typeparam name="TArg3">Third argument type</typeparam> /// <param name="instance">Instance value</param> /// <param name="arg1">First argument value</param> /// <param name="arg2">Second argument value</param> /// <param name="arg3">Third argument value</param> /// <returns>Call target state</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static CallTargetState BeginMethod<TIntegration, TTarget, TArg1, TArg2, TArg3>(TTarget instance, TArg1 arg1, TArg2 arg2, TArg3 arg3) { if (IntegrationOptions<TIntegration, TTarget>.IsIntegrationEnabled) { return BeginMethodHandler<TIntegration, TTarget, TArg1, TArg2, TArg3>.Invoke(instance, ref arg1, ref arg2, ref arg3); } return CallTargetState.GetDefault(); } /// <summary> /// Begin Method Invoker /// </summary> /// <typeparam name="TIntegration">Integration type</typeparam> /// <typeparam name="TTarget">Target type</typeparam> /// <typeparam name="TArg1">First argument type</typeparam> /// <typeparam name="TArg2">Second argument type</typeparam> /// <typeparam name="TArg3">Third argument type</typeparam> /// <typeparam name="TArg4">Fourth argument type</typeparam> /// <param name="instance">Instance value</param> /// <param name="arg1">First argument value</param> /// <param name="arg2">Second argument value</param> /// <param name="arg3">Third argument value</param> /// <param name="arg4">Fourth argument value</param> /// <returns>Call target state</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static CallTargetState BeginMethod<TIntegration, TTarget, TArg1, TArg2, TArg3, TArg4>(TTarget instance, TArg1 arg1, TArg2 arg2, TArg3 arg3, TArg4 arg4) { if (IntegrationOptions<TIntegration, TTarget>.IsIntegrationEnabled) { return BeginMethodHandler<TIntegration, TTarget, TArg1, TArg2, TArg3, TArg4>.Invoke(instance, ref arg1, ref arg2, ref arg3, ref arg4); } return CallTargetState.GetDefault(); } /// <summary> /// Begin Method Invoker /// </summary> /// <typeparam name="TIntegration">Integration type</typeparam> /// <typeparam name="TTarget">Target type</typeparam> /// <typeparam name="TArg1">First argument type</typeparam> /// <typeparam name="TArg2">Second argument type</typeparam> /// <typeparam name="TArg3">Third argument type</typeparam> /// <typeparam name="TArg4">Fourth argument type</typeparam> /// <typeparam name="TArg5">Fifth argument type</typeparam> /// <param name="instance">Instance value</param> /// <param name="arg1">First argument value</param> /// <param name="arg2">Second argument value</param> /// <param name="arg3">Third argument value</param> /// <param name="arg4">Fourth argument value</param> /// <param name="arg5">Fifth argument value</param> /// <returns>Call target state</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static CallTargetState BeginMethod<TIntegration, TTarget, TArg1, TArg2, TArg3, TArg4, TArg5>(TTarget instance, TArg1 arg1, TArg2 arg2, TArg3 arg3, TArg4 arg4, TArg5 arg5) { if (IntegrationOptions<TIntegration, TTarget>.IsIntegrationEnabled) { return BeginMethodHandler<TIntegration, TTarget, TArg1, TArg2, TArg3, TArg4, TArg5>.Invoke(instance, ref arg1, ref arg2, ref arg3, ref arg4, ref arg5); } return CallTargetState.GetDefault(); } /// <summary> /// Begin Method Invoker /// </summary> /// <typeparam name="TIntegration">Integration type</typeparam> /// <typeparam name="TTarget">Target type</typeparam> /// <typeparam name="TArg1">First argument type</typeparam> /// <typeparam name="TArg2">Second argument type</typeparam> /// <typeparam name="TArg3">Third argument type</typeparam> /// <typeparam name="TArg4">Fourth argument type</typeparam> /// <typeparam name="TArg5">Fifth argument type</typeparam> /// <typeparam name="TArg6">Sixth argument type</typeparam> /// <param name="instance">Instance value</param> /// <param name="arg1">First argument value</param> /// <param name="arg2">Second argument value</param> /// <param name="arg3">Third argument value</param> /// <param name="arg4">Fourth argument value</param> /// <param name="arg5">Fifth argument value</param> /// <param name="arg6">Sixth argument value</param> /// <returns>Call target state</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static CallTargetState BeginMethod<TIntegration, TTarget, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6>(TTarget instance, TArg1 arg1, TArg2 arg2, TArg3 arg3, TArg4 arg4, TArg5 arg5, TArg6 arg6) { if (IntegrationOptions<TIntegration, TTarget>.IsIntegrationEnabled) { return BeginMethodHandler<TIntegration, TTarget, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6>.Invoke(instance, ref arg1, ref arg2, ref arg3, ref arg4, ref arg5, ref arg6); } return CallTargetState.GetDefault(); } /// <summary> /// Begin Method Invoker /// </summary> /// <typeparam name="TIntegration">Integration type</typeparam> /// <typeparam name="TTarget">Target type</typeparam> /// <typeparam name="TArg1">First argument type</typeparam> /// <typeparam name="TArg2">Second argument type</typeparam> /// <typeparam name="TArg3">Third argument type</typeparam> /// <typeparam name="TArg4">Fourth argument type</typeparam> /// <typeparam name="TArg5">Fifth argument type</typeparam> /// <typeparam name="TArg6">Sixth argument type</typeparam> /// <typeparam name="TArg7">Seventh argument type</typeparam> /// <param name="instance">Instance value</param> /// <param name="arg1">First argument value</param> /// <param name="arg2">Second argument value</param> /// <param name="arg3">Third argument value</param> /// <param name="arg4">Fourth argument value</param> /// <param name="arg5">Fifth argument value</param> /// <param name="arg6">Sixth argument value</param> /// <param name="arg7">Seventh argument value</param> /// <returns>Call target state</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static CallTargetState BeginMethod<TIntegration, TTarget, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7>(TTarget instance, TArg1 arg1, TArg2 arg2, TArg3 arg3, TArg4 arg4, TArg5 arg5, TArg6 arg6, TArg7 arg7) { if (IntegrationOptions<TIntegration, TTarget>.IsIntegrationEnabled) { return BeginMethodHandler<TIntegration, TTarget, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7>.Invoke(instance, ref arg1, ref arg2, ref arg3, ref arg4, ref arg5, ref arg6, ref arg7); } return CallTargetState.GetDefault(); } /// <summary> /// Begin Method Invoker /// </summary> /// <typeparam name="TIntegration">Integration type</typeparam> /// <typeparam name="TTarget">Target type</typeparam> /// <typeparam name="TArg1">First argument type</typeparam> /// <typeparam name="TArg2">Second argument type</typeparam> /// <typeparam name="TArg3">Third argument type</typeparam> /// <typeparam name="TArg4">Fourth argument type</typeparam> /// <typeparam name="TArg5">Fifth argument type</typeparam> /// <typeparam name="TArg6">Sixth argument type</typeparam> /// <typeparam name="TArg7">Seventh argument type</typeparam> /// <typeparam name="TArg8">Eighth argument type</typeparam> /// <param name="instance">Instance value</param> /// <param name="arg1">First argument value</param> /// <param name="arg2">Second argument value</param> /// <param name="arg3">Third argument value</param> /// <param name="arg4">Fourth argument value</param> /// <param name="arg5">Fifth argument value</param> /// <param name="arg6">Sixth argument value</param> /// <param name="arg7">Seventh argument value</param> /// <param name="arg8">Eighth argument value</param> /// <returns>Call target state</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static CallTargetState BeginMethod<TIntegration, TTarget, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8>(TTarget instance, TArg1 arg1, TArg2 arg2, TArg3 arg3, TArg4 arg4, TArg5 arg5, TArg6 arg6, TArg7 arg7, TArg8 arg8) { if (IntegrationOptions<TIntegration, TTarget>.IsIntegrationEnabled) { return BeginMethodHandler<TIntegration, TTarget, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8>.Invoke(instance, ref arg1, ref arg2, ref arg3, ref arg4, ref arg5, ref arg6, ref arg7, ref arg8); } return CallTargetState.GetDefault(); } /// <summary> /// Begin Method Invoker /// </summary> /// <typeparam name="TIntegration">Integration type</typeparam> /// <typeparam name="TTarget">Target type</typeparam> /// <typeparam name="TArg1">First argument type</typeparam> /// <param name="instance">Instance value</param> /// <param name="arg1">First argument value</param> /// <returns>Call target state</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static CallTargetState BeginMethod<TIntegration, TTarget, TArg1>(TTarget instance, ref TArg1 arg1) { if (IntegrationOptions<TIntegration, TTarget>.IsIntegrationEnabled) { return BeginMethodHandler<TIntegration, TTarget, TArg1>.Invoke(instance, ref arg1); } return CallTargetState.GetDefault(); } /// <summary> /// Begin Method Invoker /// </summary> /// <typeparam name="TIntegration">Integration type</typeparam> /// <typeparam name="TTarget">Target type</typeparam> /// <typeparam name="TArg1">First argument type</typeparam> /// <typeparam name="TArg2">Second argument type</typeparam> /// <param name="instance">Instance value</param> /// <param name="arg1">First argument value</param> /// <param name="arg2">Second argument value</param> /// <returns>Call target state</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static CallTargetState BeginMethod<TIntegration, TTarget, TArg1, TArg2>(TTarget instance, ref TArg1 arg1, ref TArg2 arg2) { if (IntegrationOptions<TIntegration, TTarget>.IsIntegrationEnabled) { return BeginMethodHandler<TIntegration, TTarget, TArg1, TArg2>.Invoke(instance, ref arg1, ref arg2); } return CallTargetState.GetDefault(); } /// <summary> /// Begin Method Invoker /// </summary> /// <typeparam name="TIntegration">Integration type</typeparam> /// <typeparam name="TTarget">Target type</typeparam> /// <typeparam name="TArg1">First argument type</typeparam> /// <typeparam name="TArg2">Second argument type</typeparam> /// <typeparam name="TArg3">Third argument type</typeparam> /// <param name="instance">Instance value</param> /// <param name="arg1">First argument value</param> /// <param name="arg2">Second argument value</param> /// <param name="arg3">Third argument value</param> /// <returns>Call target state</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static CallTargetState BeginMethod<TIntegration, TTarget, TArg1, TArg2, TArg3>(TTarget instance, ref TArg1 arg1, ref TArg2 arg2, ref TArg3 arg3) { if (IntegrationOptions<TIntegration, TTarget>.IsIntegrationEnabled) { return BeginMethodHandler<TIntegration, TTarget, TArg1, TArg2, TArg3>.Invoke(instance, ref arg1, ref arg2, ref arg3); } return CallTargetState.GetDefault(); } /// <summary> /// Begin Method Invoker /// </summary> /// <typeparam name="TIntegration">Integration type</typeparam> /// <typeparam name="TTarget">Target type</typeparam> /// <typeparam name="TArg1">First argument type</typeparam> /// <typeparam name="TArg2">Second argument type</typeparam> /// <typeparam name="TArg3">Third argument type</typeparam> /// <typeparam name="TArg4">Fourth argument type</typeparam> /// <param name="instance">Instance value</param> /// <param name="arg1">First argument value</param> /// <param name="arg2">Second argument value</param> /// <param name="arg3">Third argument value</param> /// <param name="arg4">Fourth argument value</param> /// <returns>Call target state</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static CallTargetState BeginMethod<TIntegration, TTarget, TArg1, TArg2, TArg3, TArg4>(TTarget instance, ref TArg1 arg1, ref TArg2 arg2, ref TArg3 arg3, ref TArg4 arg4) { if (IntegrationOptions<TIntegration, TTarget>.IsIntegrationEnabled) { return BeginMethodHandler<TIntegration, TTarget, TArg1, TArg2, TArg3, TArg4>.Invoke(instance, ref arg1, ref arg2, ref arg3, ref arg4); } return CallTargetState.GetDefault(); } /// <summary> /// Begin Method Invoker /// </summary> /// <typeparam name="TIntegration">Integration type</typeparam> /// <typeparam name="TTarget">Target type</typeparam> /// <typeparam name="TArg1">First argument type</typeparam> /// <typeparam name="TArg2">Second argument type</typeparam> /// <typeparam name="TArg3">Third argument type</typeparam> /// <typeparam name="TArg4">Fourth argument type</typeparam> /// <typeparam name="TArg5">Fifth argument type</typeparam> /// <param name="instance">Instance value</param> /// <param name="arg1">First argument value</param> /// <param name="arg2">Second argument value</param> /// <param name="arg3">Third argument value</param> /// <param name="arg4">Fourth argument value</param> /// <param name="arg5">Fifth argument value</param> /// <returns>Call target state</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static CallTargetState BeginMethod<TIntegration, TTarget, TArg1, TArg2, TArg3, TArg4, TArg5>(TTarget instance, ref TArg1 arg1, ref TArg2 arg2, ref TArg3 arg3, ref TArg4 arg4, ref TArg5 arg5) { if (IntegrationOptions<TIntegration, TTarget>.IsIntegrationEnabled) { return BeginMethodHandler<TIntegration, TTarget, TArg1, TArg2, TArg3, TArg4, TArg5>.Invoke(instance, ref arg1, ref arg2, ref arg3, ref arg4, ref arg5); } return CallTargetState.GetDefault(); } /// <summary> /// Begin Method Invoker /// </summary> /// <typeparam name="TIntegration">Integration type</typeparam> /// <typeparam name="TTarget">Target type</typeparam> /// <typeparam name="TArg1">First argument type</typeparam> /// <typeparam name="TArg2">Second argument type</typeparam> /// <typeparam name="TArg3">Third argument type</typeparam> /// <typeparam name="TArg4">Fourth argument type</typeparam> /// <typeparam name="TArg5">Fifth argument type</typeparam> /// <typeparam name="TArg6">Sixth argument type</typeparam> /// <param name="instance">Instance value</param> /// <param name="arg1">First argument value</param> /// <param name="arg2">Second argument value</param> /// <param name="arg3">Third argument value</param> /// <param name="arg4">Fourth argument value</param> /// <param name="arg5">Fifth argument value</param> /// <param name="arg6">Sixth argument value</param> /// <returns>Call target state</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static CallTargetState BeginMethod<TIntegration, TTarget, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6>(TTarget instance, ref TArg1 arg1, ref TArg2 arg2, ref TArg3 arg3, ref TArg4 arg4, ref TArg5 arg5, ref TArg6 arg6) { if (IntegrationOptions<TIntegration, TTarget>.IsIntegrationEnabled) { return BeginMethodHandler<TIntegration, TTarget, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6>.Invoke(instance, ref arg1, ref arg2, ref arg3, ref arg4, ref arg5, ref arg6); } return CallTargetState.GetDefault(); } /// <summary> /// Begin Method Invoker /// </summary> /// <typeparam name="TIntegration">Integration type</typeparam> /// <typeparam name="TTarget">Target type</typeparam> /// <typeparam name="TArg1">First argument type</typeparam> /// <typeparam name="TArg2">Second argument type</typeparam> /// <typeparam name="TArg3">Third argument type</typeparam> /// <typeparam name="TArg4">Fourth argument type</typeparam> /// <typeparam name="TArg5">Fifth argument type</typeparam> /// <typeparam name="TArg6">Sixth argument type</typeparam> /// <typeparam name="TArg7">Seventh argument type</typeparam> /// <param name="instance">Instance value</param> /// <param name="arg1">First argument value</param> /// <param name="arg2">Second argument value</param> /// <param name="arg3">Third argument value</param> /// <param name="arg4">Fourth argument value</param> /// <param name="arg5">Fifth argument value</param> /// <param name="arg6">Sixth argument value</param> /// <param name="arg7">Seventh argument value</param> /// <returns>Call target state</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static CallTargetState BeginMethod<TIntegration, TTarget, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7>(TTarget instance, ref TArg1 arg1, ref TArg2 arg2, ref TArg3 arg3, ref TArg4 arg4, ref TArg5 arg5, ref TArg6 arg6, ref TArg7 arg7) { if (IntegrationOptions<TIntegration, TTarget>.IsIntegrationEnabled) { return BeginMethodHandler<TIntegration, TTarget, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7>.Invoke(instance, ref arg1, ref arg2, ref arg3, ref arg4, ref arg5, ref arg6, ref arg7); } return CallTargetState.GetDefault(); } /// <summary> /// Begin Method Invoker /// </summary> /// <typeparam name="TIntegration">Integration type</typeparam> /// <typeparam name="TTarget">Target type</typeparam> /// <typeparam name="TArg1">First argument type</typeparam> /// <typeparam name="TArg2">Second argument type</typeparam> /// <typeparam name="TArg3">Third argument type</typeparam> /// <typeparam name="TArg4">Fourth argument type</typeparam> /// <typeparam name="TArg5">Fifth argument type</typeparam> /// <typeparam name="TArg6">Sixth argument type</typeparam> /// <typeparam name="TArg7">Seventh argument type</typeparam> /// <typeparam name="TArg8">Eighth argument type</typeparam> /// <param name="instance">Instance value</param> /// <param name="arg1">First argument value</param> /// <param name="arg2">Second argument value</param> /// <param name="arg3">Third argument value</param> /// <param name="arg4">Fourth argument value</param> /// <param name="arg5">Fifth argument value</param> /// <param name="arg6">Sixth argument value</param> /// <param name="arg7">Seventh argument value</param> /// <param name="arg8">Eighth argument value</param> /// <returns>Call target state</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static CallTargetState BeginMethod<TIntegration, TTarget, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8>(TTarget instance, ref TArg1 arg1, ref TArg2 arg2, ref TArg3 arg3, ref TArg4 arg4, ref TArg5 arg5, ref TArg6 arg6, ref TArg7 arg7, ref TArg8 arg8) { if (IntegrationOptions<TIntegration, TTarget>.IsIntegrationEnabled) { return BeginMethodHandler<TIntegration, TTarget, TArg1, TArg2, TArg3, TArg4, TArg5, TArg6, TArg7, TArg8>.Invoke(instance, ref arg1, ref arg2, ref arg3, ref arg4, ref arg5, ref arg6, ref arg7, ref arg8); } return CallTargetState.GetDefault(); } /// <summary> /// Begin Method Invoker Slow Path /// </summary> /// <typeparam name="TIntegration">Integration type</typeparam> /// <typeparam name="TTarget">Target type</typeparam> /// <param name="instance">Instance value</param> /// <param name="arguments">Object arguments array</param> /// <returns>Call target state</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static CallTargetState BeginMethod<TIntegration, TTarget>(TTarget instance, object[] arguments) { if (IntegrationOptions<TIntegration, TTarget>.IsIntegrationEnabled) { return BeginMethodSlowHandler<TIntegration, TTarget>.Invoke(instance, arguments); } return CallTargetState.GetDefault(); } /// <summary> /// End Method with Void return value invoker /// </summary> /// <typeparam name="TIntegration">Integration type</typeparam> /// <typeparam name="TTarget">Target type</typeparam> /// <param name="instance">Instance value</param> /// <param name="exception">Exception value</param> /// <param name="state">CallTarget state</param> /// <returns>CallTarget return structure</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static CallTargetReturn EndMethod<TIntegration, TTarget>(TTarget instance, Exception exception, CallTargetState state) { if (IntegrationOptions<TIntegration, TTarget>.IsIntegrationEnabled) { return EndMethodHandler<TIntegration, TTarget>.Invoke(instance, exception, in state); } return CallTargetReturn.GetDefault(); } /// <summary> /// End Method with Return value invoker /// </summary> /// <typeparam name="TIntegration">Integration type</typeparam> /// <typeparam name="TTarget">Target type</typeparam> /// <typeparam name="TReturn">Return type</typeparam> /// <param name="instance">Instance value</param> /// <param name="returnValue">Return value</param> /// <param name="exception">Exception value</param> /// <param name="state">CallTarget state</param> /// <returns>CallTarget return structure</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static CallTargetReturn<TReturn> EndMethod<TIntegration, TTarget, TReturn>(TTarget instance, TReturn returnValue, Exception exception, CallTargetState state) { if (IntegrationOptions<TIntegration, TTarget>.IsIntegrationEnabled) { return EndMethodHandler<TIntegration, TTarget, TReturn>.Invoke(instance, returnValue, exception, in state); } return new CallTargetReturn<TReturn>(returnValue); } /// <summary> /// End Method with Void return value invoker /// </summary> /// <typeparam name="TIntegration">Integration type</typeparam> /// <typeparam name="TTarget">Target type</typeparam> /// <param name="instance">Instance value</param> /// <param name="exception">Exception value</param> /// <param name="state">CallTarget state</param> /// <returns>CallTarget return structure</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static CallTargetReturn EndMethod<TIntegration, TTarget>(TTarget instance, Exception exception, in CallTargetState state) { if (IntegrationOptions<TIntegration, TTarget>.IsIntegrationEnabled) { return EndMethodHandler<TIntegration, TTarget>.Invoke(instance, exception, in state); } return CallTargetReturn.GetDefault(); } /// <summary> /// End Method with Return value invoker /// </summary> /// <typeparam name="TIntegration">Integration type</typeparam> /// <typeparam name="TTarget">Target type</typeparam> /// <typeparam name="TReturn">Return type</typeparam> /// <param name="instance">Instance value</param> /// <param name="returnValue">Return value</param> /// <param name="exception">Exception value</param> /// <param name="state">CallTarget state</param> /// <returns>CallTarget return structure</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static CallTargetReturn<TReturn> EndMethod<TIntegration, TTarget, TReturn>(TTarget instance, TReturn returnValue, Exception exception, in CallTargetState state) { if (IntegrationOptions<TIntegration, TTarget>.IsIntegrationEnabled) { return EndMethodHandler<TIntegration, TTarget, TReturn>.Invoke(instance, returnValue, exception, in state); } return new CallTargetReturn<TReturn>(returnValue); } /// <summary> /// Log integration exception /// </summary> /// <typeparam name="TIntegration">Integration type</typeparam> /// <typeparam name="TTarget">Target type</typeparam> /// <param name="exception">Integration exception instance</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void LogException<TIntegration, TTarget>(Exception exception) { IntegrationOptions<TIntegration, TTarget>.LogException(exception); } /// <summary> /// Gets the default value of a type /// </summary> /// <typeparam name="T">Type to get the default value</typeparam> /// <returns>Default value of T</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static T GetDefaultValue<T>() => default; } }
1
25,682
What about integrations where we don't plug ourselved on OnMethodBegin?
DataDog-dd-trace-dotnet
.cs
@@ -102,7 +102,7 @@ class presence_of_all_elements_located(object): def __call__(self, driver): return _find_elements(driver, self.locator) -class visibility_of_all_elements_located(object): +class visibility_of_any_elements_located(object): """ An expectation for checking that there is at least one element visible on a web page. locator is used to find the element
1
# Licensed to the Software Freedom Conservancy (SFC) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The SFC licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from selenium.common.exceptions import NoSuchElementException from selenium.common.exceptions import NoSuchFrameException from selenium.common.exceptions import StaleElementReferenceException from selenium.common.exceptions import WebDriverException from selenium.common.exceptions import NoAlertPresentException """ * Canned "Expected Conditions" which are generally useful within webdriver * tests. """ class title_is(object): """An expectation for checking the title of a page. title is the expected title, which must be an exact match returns True if the title matches, false otherwise.""" def __init__(self, title): self.title = title def __call__(self, driver): return self.title == driver.title class title_contains(object): """ An expectation for checking that the title contains a case-sensitive substring. title is the fragment of title expected returns True when the title matches, False otherwise """ def __init__(self, title): self.title = title def __call__(self, driver): return self.title in driver.title class presence_of_element_located(object): """ An expectation for checking that an element is present on the DOM of a page. This does not necessarily mean that the element is visible. locator - used to find the element returns the WebElement once it is located """ def __init__(self, locator): self.locator = locator def __call__(self, driver): return _find_element(driver, self.locator) class visibility_of_element_located(object): """ An expectation for checking that an element is present on the DOM of a page and visible. Visibility means that the element is not only displayed but also has a height and width that is greater than 0. locator - used to find the element returns the WebElement once it is located and visible """ def __init__(self, locator): self.locator = locator def __call__(self, driver): try: return _element_if_visible(_find_element(driver, self.locator)) except StaleElementReferenceException: return False class visibility_of(object): """ An expectation for checking that an element, known to be present on the DOM of a page, is visible. Visibility means that the element is not only displayed but also has a height and width that is greater than 0. element is the WebElement returns the (same) WebElement once it is visible """ def __init__(self, element): self.element = element def __call__(self, ignored): return _element_if_visible(self.element) def _element_if_visible(element, visibility=True): return element if element.is_displayed() == visibility else False class presence_of_all_elements_located(object): """ An expectation for checking that there is at least one element present on a web page. locator is used to find the element returns the list of WebElements once they are located """ def __init__(self, locator): self.locator = locator def __call__(self, driver): return _find_elements(driver, self.locator) class visibility_of_all_elements_located(object): """ An expectation for checking that there is at least one element visible on a web page. locator is used to find the element returns the list of WebElements once they are located """ def __init__(self, locator): self.locator = locator def __call__(self, driver): return [element for element in _find_elements(driver, self.locator) if _element_if_visible(element)] class text_to_be_present_in_element(object): """ An expectation for checking if the given text is present in the specified element. locator, text """ def __init__(self, locator, text_): self.locator = locator self.text = text_ def __call__(self, driver): try : element_text = _find_element(driver, self.locator).text return self.text in element_text except StaleElementReferenceException: return False class text_to_be_present_in_element_value(object): """ An expectation for checking if the given text is present in the element's locator, text """ def __init__(self, locator, text_): self.locator = locator self.text = text_ def __call__(self, driver): try: element_text = _find_element(driver, self.locator).get_attribute("value") if element_text: return self.text in element_text else: return False except StaleElementReferenceException: return False class frame_to_be_available_and_switch_to_it(object): """ An expectation for checking whether the given frame is available to switch to. If the frame is available it switches the given driver to the specified frame. """ def __init__(self, locator): self.frame_locator = locator def __call__(self, driver): try: if isinstance(self.frame_locator, tuple): driver.switch_to.frame(_find_element(driver, self.frame_locator)) else: driver.switch_to.frame(self.frame_locator) return True except NoSuchFrameException: return False class invisibility_of_element_located(object): """ An Expectation for checking that an element is either invisible or not present on the DOM. locator used to find the element """ def __init__(self, locator): self.locator = locator def __call__(self, driver): try: return _element_if_visible(_find_element(driver, self.locator), False) except (NoSuchElementException, StaleElementReferenceException): # In the case of NoSuchElement, returns true because the element is # not present in DOM. The try block checks if the element is present # but is invisible. # In the case of StaleElementReference, returns true because stale # element reference implies that element is no longer visible. return True class element_to_be_clickable(object): """ An Expectation for checking an element is visible and enabled such that you can click it.""" def __init__(self, locator): self.locator = locator def __call__(self, driver): element = visibility_of_element_located(self.locator)(driver) if element and element.is_enabled(): return element else: return False class staleness_of(object): """ Wait until an element is no longer attached to the DOM. element is the element to wait for. returns False if the element is still attached to the DOM, true otherwise. """ def __init__(self, element): self.element = element def __call__(self, ignored): try: # Calling any method forces a staleness check self.element.is_enabled() return False except StaleElementReferenceException as expected: return True class element_to_be_selected(object): """ An expectation for checking the selection is selected. element is WebElement object """ def __init__(self, element): self.element = element def __call__(self, ignored): return self.element.is_selected() class element_located_to_be_selected(object): """An expectation for the element to be located is selected. locator is a tuple of (by, path)""" def __init__(self, locator): self.locator = locator def __call__(self, driver): return _find_element(driver, self.locator).is_selected() class element_selection_state_to_be(object): """ An expectation for checking if the given element is selected. element is WebElement object is_selected is a Boolean." """ def __init__(self, element, is_selected): self.element = element self.is_selected = is_selected def __call__(self, ignored): return self.element.is_selected() == self.is_selected class element_located_selection_state_to_be(object): """ An expectation to locate an element and check if the selection state specified is in that state. locator is a tuple of (by, path) is_selected is a boolean """ def __init__(self, locator, is_selected): self.locator = locator self.is_selected = is_selected def __call__(self, driver): try: element = _find_element(driver, self.locator) return element.is_selected() == self.is_selected except StaleElementReferenceException: return False class alert_is_present(object): """ Expect an alert to be present.""" def __init__(self): pass def __call__(self, driver): try: alert = driver.switch_to.alert alert.text return alert except NoAlertPresentException: return False def _find_element(driver, by): """Looks up an element. Logs and re-raises ``WebDriverException`` if thrown.""" try : return driver.find_element(*by) except NoSuchElementException as e: raise e except WebDriverException as e: raise e def _find_elements(driver, by): try : return driver.find_elements(*by) except WebDriverException as e: raise e
1
13,212
shouldn't **call** return a boolean?
SeleniumHQ-selenium
java
@@ -18,12 +18,15 @@ import com.google.api.codegen.SnippetSetRunner; import com.google.api.codegen.viewmodel.FileHeaderView; import com.google.api.codegen.viewmodel.ViewModel; import com.google.api.codegen.viewmodel.testing.MockServiceImplView.Builder; +import com.google.api.tools.framework.model.Interface; import com.google.auto.value.AutoValue; import java.util.List; @AutoValue public abstract class GapicSurfaceTestClassView implements ViewModel { + public abstract Interface service(); + public abstract FileHeaderView fileHeader(); public abstract String name();
1
/* Copyright 2016 Google Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.api.codegen.viewmodel.testing; import com.google.api.codegen.SnippetSetRunner; import com.google.api.codegen.viewmodel.FileHeaderView; import com.google.api.codegen.viewmodel.ViewModel; import com.google.api.codegen.viewmodel.testing.MockServiceImplView.Builder; import com.google.auto.value.AutoValue; import java.util.List; @AutoValue public abstract class GapicSurfaceTestClassView implements ViewModel { public abstract FileHeaderView fileHeader(); public abstract String name(); public abstract String apiClassName(); public abstract String apiSettingsClassName(); public abstract List<MockServiceUsageView> mockServices(); public abstract List<GapicSurfaceTestCaseView> testCases(); @Override public String resourceRoot() { return SnippetSetRunner.SNIPPET_RESOURCE_ROOT; } @Override public abstract String templateFileName(); @Override public abstract String outputPath(); public static Builder newBuilder() { return new AutoValue_GapicSurfaceTestClassView.Builder(); } @AutoValue.Builder public abstract static class Builder { public abstract Builder fileHeader(FileHeaderView val); public abstract Builder name(String val); public abstract Builder apiClassName(String val); public abstract Builder apiSettingsClassName(String val); public abstract Builder mockServices(List<MockServiceUsageView> val); public abstract Builder outputPath(String val); public abstract Builder templateFileName(String val); public abstract Builder testCases(List<GapicSurfaceTestCaseView> val); public abstract GapicSurfaceTestClassView build(); } }
1
19,961
ViewModel classes should not expose any classes from framework.model.
googleapis-gapic-generator
java
@@ -135,9 +135,6 @@ def test_single_required_string_field_config_type(): assert _validate(_single_required_string_config_dict(), {'string_field': 'value'}) == { 'string_field': 'value' } - assert _validate(_single_required_string_config_dict(), {'string_field': None}) == { - 'string_field': None - } with pytest.raises(DagsterEvaluateConfigValueError): _validate(_single_required_string_config_dict(), {})
1
from collections import namedtuple import pytest from dagster import ( ConfigField, DagsterEvaluateConfigValueError, DagsterInvalidDefinitionError, ExecutionContext, Field, PipelineConfigEvaluationError, PipelineContextDefinition, PipelineDefinition, SolidDefinition, execute_pipeline, solid, types, ) from dagster.core.evaluator import ( evaluate_config_value, throwing_evaluate_config_value, DagsterEvaluationErrorReason, ) from dagster.core.types import ( ScopedConfigInfo, ) from dagster.core.definitions import build_config_dict_type def test_noop_config(): assert Field(types.Any) def test_int_field(): config_field = ConfigField.config_dict_field( 'SingleRequiredInt', { 'int_field': Field(types.Int), }, ) assert evaluate_config_value(config_field.dagster_type, { 'int_field': 1 }).value == { 'int_field': 1 } def assert_config_value_success(dagster_type, config_value, expected): result = evaluate_config_value(dagster_type, config_value) assert result.success assert result.value == expected def assert_eval_failure(dagster_type, value): assert not evaluate_config_value(dagster_type, value).success def test_int_fails(): config_field = ConfigField.config_dict_field( 'SingleRequiredInt', { 'int_field': Field(types.Int), } ) assert_eval_failure(config_field.dagster_type, {'int_field': 'fjkdj'}) assert_eval_failure(config_field.dagster_type, {'int_field': True}) def test_default_arg(): config_field = ConfigField.config_dict_field( 'TestDefaultArg', { 'int_field': Field(types.Int, default_value=2, is_optional=True), } ) assert_config_value_success(config_field.dagster_type, {}, {'int_field': 2}) def _single_required_string_config_dict(): return ConfigField.config_dict_field( 'SingleRequiredField', {'string_field': Field(types.String)} ) def _multiple_required_fields_config_dict(): return ConfigField.config_dict_field( 'MultipleRequiredFields', { 'field_one': Field(types.String), 'field_two': Field(types.String), } ) def _single_optional_string_config_dict(): return ConfigField.config_dict_field( 'SingleOptionalString', {'optional_field': Field(types.String, is_optional=True)} ) def _single_optional_string_field_config_dict_with_default(): optional_field_def = Field( types.String, is_optional=True, default_value='some_default', ) return ConfigField.config_dict_field( 'SingleOptionalStringWithDefault', {'optional_field': optional_field_def}, ) def _mixed_required_optional_string_config_dict_with_default(): return ConfigField.config_dict_field( 'MixedRequired', { 'optional_arg': Field( types.String, is_optional=True, default_value='some_default', ), 'required_arg': Field(types.String, is_optional=False), 'optional_arg_no_default': Field(types.String, is_optional=True), } ) def _validate(config_field, value): return throwing_evaluate_config_value(config_field.dagster_type, value) def test_single_required_string_field_config_type(): assert _validate(_single_required_string_config_dict(), {'string_field': 'value'}) == { 'string_field': 'value' } assert _validate(_single_required_string_config_dict(), {'string_field': None}) == { 'string_field': None } with pytest.raises(DagsterEvaluateConfigValueError): _validate(_single_required_string_config_dict(), {}) with pytest.raises(DagsterEvaluateConfigValueError): _validate(_single_required_string_config_dict(), {'extra': 'yup'}) with pytest.raises(DagsterEvaluateConfigValueError): _validate(_single_required_string_config_dict(), {'string_field': 'yupup', 'extra': 'yup'}) with pytest.raises(DagsterEvaluateConfigValueError): _validate(_single_required_string_config_dict(), {'string_field': 1}) def test_multiple_required_fields_passing(): assert _validate( _multiple_required_fields_config_dict(), { 'field_one': 'value_one', 'field_two': 'value_two', }, ) == { 'field_one': 'value_one', 'field_two': 'value_two', } assert _validate( _multiple_required_fields_config_dict(), { 'field_one': 'value_one', 'field_two': None, }, ) == { 'field_one': 'value_one', 'field_two': None, } def test_multiple_required_fields_failing(): with pytest.raises(DagsterEvaluateConfigValueError): _validate(_multiple_required_fields_config_dict(), {}) with pytest.raises(DagsterEvaluateConfigValueError): _validate(_multiple_required_fields_config_dict(), {'field_one': 'yup'}) with pytest.raises(DagsterEvaluateConfigValueError): _validate(_multiple_required_fields_config_dict(), {'field_one': 'yup', 'extra': 'yup'}) with pytest.raises(DagsterEvaluateConfigValueError): _validate( _multiple_required_fields_config_dict(), { 'field_one': 'value_one', 'field_two': 2 } ) def test_single_optional_field_passing(): assert _validate(_single_optional_string_config_dict(), {'optional_field': 'value'}) == { 'optional_field': 'value' } assert _validate(_single_optional_string_config_dict(), {}) == {} assert _validate(_single_optional_string_config_dict(), {'optional_field': None}) == { 'optional_field': None } def test_single_optional_field_failing(): with pytest.raises(DagsterEvaluateConfigValueError): _validate(_single_optional_string_config_dict(), {'optional_field': 1}) with pytest.raises(DagsterEvaluateConfigValueError): _validate(_single_optional_string_config_dict(), {'dlkjfalksdjflksaj': 1}) def test_single_optional_field_passing_with_default(): assert _validate(_single_optional_string_field_config_dict_with_default(), {}) == { 'optional_field': 'some_default' } assert _validate( _single_optional_string_field_config_dict_with_default(), {'optional_field': 'override'} ) == { 'optional_field': 'override' } def test_mixed_args_passing(): assert _validate( _mixed_required_optional_string_config_dict_with_default(), { 'optional_arg': 'value_one', 'required_arg': 'value_two', } ) == { 'optional_arg': 'value_one', 'required_arg': 'value_two', } assert _validate( _mixed_required_optional_string_config_dict_with_default(), { 'required_arg': 'value_two', } ) == { 'optional_arg': 'some_default', 'required_arg': 'value_two', } assert _validate( _mixed_required_optional_string_config_dict_with_default(), { 'required_arg': 'value_two', 'optional_arg_no_default': 'value_three', } ) == { 'optional_arg': 'some_default', 'required_arg': 'value_two', 'optional_arg_no_default': 'value_three', } def _single_nested_config(): return Field( dagster_type=types.ConfigDictionary( 'ParentType', { 'nested': Field( dagster_type=types.ConfigDictionary( 'NestedType', {'int_field': Field(types.Int)}, ) ), } ) ) def _nested_optional_config_with_default(): return Field( dagster_type=types.ConfigDictionary( 'ParentType', { 'nested': Field( dagster_type=types.ConfigDictionary( 'NestedType', {'int_field': Field( types.Int, is_optional=True, default_value=3, )} ) ), } ) ) def _nested_optional_config_with_no_default(): nested_type = types.ConfigDictionary( 'NestedType', { 'int_field': Field( types.Int, is_optional=True, ), }, ) return Field( dagster_type=types.ConfigDictionary( 'ParentType', {'nested': Field(dagster_type=nested_type)}, ) ) def test_single_nested_config(): assert _validate(_single_nested_config(), {'nested': { 'int_field': 2 }}) == { 'nested': { 'int_field': 2 } } def test_single_nested_config_failures(): with pytest.raises(DagsterEvaluateConfigValueError): _validate(_single_nested_config(), {'nested': 'dkjfdk'}) with pytest.raises(DagsterEvaluateConfigValueError): _validate(_single_nested_config(), {'nested': {'int_field': 'dkjfdk'}}) with pytest.raises(DagsterEvaluateConfigValueError): _validate(_single_nested_config(), {'nested': {'int_field': {'too_nested': 'dkjfdk'}}}) def test_nested_optional_with_default(): assert _validate(_nested_optional_config_with_default(), {'nested': { 'int_field': 2 }}) == { 'nested': { 'int_field': 2 } } assert _validate(_nested_optional_config_with_default(), {'nested': {}}) == { 'nested': { 'int_field': 3 } } def test_nested_optional_with_no_default(): assert _validate(_nested_optional_config_with_no_default(), {'nested': { 'int_field': 2 }}) == { 'nested': { 'int_field': 2 } } assert _validate(_nested_optional_config_with_no_default(), {'nested': {}}) == {'nested': {}} CustomStructConfig = namedtuple('CustomStructConfig', 'foo bar') class CustomStructConfigType(types.DagsterCompositeType): def __init__(self): super(CustomStructConfigType, self).__init__( 'CustomStructConfigType', { 'foo': Field(types.String), 'bar': Field(types.Int), }, ) def construct_from_config_value(self, config_value): return CustomStructConfig(**config_value) def test_custom_composite_type(): config_type = CustomStructConfigType() assert throwing_evaluate_config_value(config_type, { 'foo': 'some_string', 'bar': 2 }) == CustomStructConfig( foo='some_string', bar=2 ) with pytest.raises(DagsterEvaluateConfigValueError): assert throwing_evaluate_config_value(config_type, { 'foo': 'some_string', }) with pytest.raises(DagsterEvaluateConfigValueError): assert throwing_evaluate_config_value(config_type, { 'bar': 'some_string', }) with pytest.raises(DagsterEvaluateConfigValueError): assert throwing_evaluate_config_value( config_type, { 'foo': 'some_string', 'bar': 'not_an_int', } ) def single_elem(ddict): return list(ddict.items())[0] def test_build_config_dict_type(): single_cd_type = build_config_dict_type( ['PipelineName', 'SingleField'], {'foo': types.Field(types.String)}, ScopedConfigInfo( pipeline_def_name='pipeline_name', solid_def_name='single_field', ), ) assert isinstance(single_cd_type, types.ConfigDictionary) assert single_cd_type.name == 'PipelineName.SingleField.ConfigDict' assert len(single_cd_type.field_dict) == 1 foo_name, foo_field = single_elem(single_cd_type.field_dict) assert foo_name == 'foo' assert foo_field.dagster_type is types.String def test_build_single_nested(): def _assert_facts(single_nested): assert single_nested.name == 'PipelineName.Solid.SolidName.ConfigDict' assert set(single_nested.field_dict.keys()) == set(['foo', 'nested_dict']) assert single_nested.field_dict['nested_dict'].is_optional is False nested_field_type = single_nested.field_dict['nested_dict'].dagster_type assert isinstance(nested_field_type, types.ConfigDictionary) assert nested_field_type.name == 'PipelineName.Solid.SolidName.NestedDict.ConfigDict' assert nested_field_type.field_name_set == set(['bar']) old_style_config_field = Field( types.ConfigDictionary( 'PipelineName.Solid.SolidName.ConfigDict', { 'foo': types.Field(types.String), 'nested_dict': types.Field( types.ConfigDictionary( 'PipelineName.Solid.SolidName.NestedDict.ConfigDict', { 'bar': types.Field(types.String), }, ), ), }, ), ) _assert_facts(old_style_config_field.dagster_type) single_nested_manual = build_config_dict_type( ['PipelineName', 'Solid', 'SolidName'], { 'foo': types.Field(types.String), 'nested_dict': { 'bar': types.Field(types.String), }, }, ScopedConfigInfo( pipeline_def_name='pipeline_name', solid_def_name='solid_name', ), ) _assert_facts(single_nested_manual) nested_from_config_field = ConfigField.solid_config_dict( 'pipeline_name', 'solid_name', { 'foo': types.Field(types.String), 'nested_dict': { 'bar': types.Field(types.String), }, }, ) _assert_facts(nested_from_config_field.dagster_type) def test_build_double_nested(): double_config_type = ConfigField.context_config_dict( 'some_pipeline', 'some_context', { 'level_one': { 'level_two': { 'field': types.Field(types.String) } } }, ).dagster_type assert double_config_type.name == 'SomePipeline.Context.SomeContext.ConfigDict' level_one_type = double_config_type.field_dict['level_one'].dagster_type assert isinstance(level_one_type, types.ConfigDictionary) assert level_one_type.name == 'SomePipeline.Context.SomeContext.LevelOne.ConfigDict' assert level_one_type.field_name_set == set(['level_two']) level_two_type = level_one_type.field_dict['level_two'].dagster_type assert level_two_type.name == 'SomePipeline.Context.SomeContext.LevelOne.LevelTwo.ConfigDict' assert level_two_type.field_name_set == set(['field']) def test_build_optionality(): optional_test_type = ConfigField.solid_config_dict( 'some_pipeline', 'some_solid', { 'required': { 'value': types.Field(types.String), }, 'optional': { 'value': types.Field(types.String, is_optional=True), } }, ).dagster_type assert optional_test_type.field_dict['required'].is_optional is False assert optional_test_type.field_dict['optional'].is_optional is True def test_wrong_solid_name(): pipeline_def = PipelineDefinition( name='pipeline_wrong_solid_name', solids=[ SolidDefinition( name='some_solid', inputs=[], outputs=[], config_field=ConfigField.solid_config_dict( 'pipeline_wrong_solid_name', 'some_solid', {}, ), transform_fn=lambda *_args: None, ), ], ) env_config = { 'solids': { 'another_name': { 'config': {}, }, }, } with pytest.raises(PipelineConfigEvaluationError) as pe_info: execute_pipeline(pipeline_def, env_config) pe = pe_info.value assert 'Undefined field "another_name" at path root:solids' in str(pe) def fail_me(): assert False return None def test_multiple_context(): pipeline_def = PipelineDefinition( name='pipeline_test_multiple_context', context_definitions={ 'context_one': PipelineContextDefinition(context_fn=lambda *_args: fail_me(), ), 'context_two': PipelineContextDefinition(context_fn=lambda *_args: fail_me(), ), }, solids=[], ) with pytest.raises(PipelineConfigEvaluationError): execute_pipeline( pipeline_def, { 'context': { 'context_one': {}, 'context_two': {}, }, }, ) def test_wrong_context(): pipeline_def = PipelineDefinition( name='pipeline_test_multiple_context', context_definitions={ 'context_one': PipelineContextDefinition(context_fn=lambda *_args: fail_me(), ), 'context_two': PipelineContextDefinition(context_fn=lambda *_args: fail_me(), ), }, solids=[], ) with pytest.raises( PipelineConfigEvaluationError, match='Undefined field "nope" at path root:context', ): execute_pipeline( pipeline_def, { 'context': { 'nope': {}, }, }, ) def test_pipeline_name_mismatch_error(): with pytest.raises(DagsterInvalidDefinitionError, match='wrong pipeline name'): PipelineDefinition( name='pipeline_mismatch_test', solids=[ SolidDefinition( name='some_solid', inputs=[], outputs=[], config_field=ConfigField.solid_config_dict( 'wrong_pipeline', 'some_solid', {}, ), transform_fn=lambda *_args: None, ), ], ) with pytest.raises(DagsterInvalidDefinitionError, match='wrong pipeline name'): PipelineDefinition( name='pipeline_mismatch_test', solids=[], context_definitions={ 'some_context': PipelineContextDefinition( context_fn=lambda *_args: None, config_field=ConfigField.context_config_dict( 'not_a_match', 'some_context', {}, ) ) } ) def test_solid_name_mismatch(): with pytest.raises(DagsterInvalidDefinitionError, match='wrong solid name'): PipelineDefinition( name='solid_name_mismatch', solids=[ SolidDefinition( name='dont_match_me', inputs=[], outputs=[], config_field=ConfigField.solid_config_dict( 'solid_name_mismatch', 'nope', {}, ), transform_fn=lambda *_args: None, ), ], ) with pytest.raises(DagsterInvalidDefinitionError, match='context_config_dict'): PipelineDefinition( name='solid_name_mismatch', solids=[ SolidDefinition( name='dont_match_me', inputs=[], outputs=[], config_field=ConfigField.context_config_dict( 'solid_name_mismatch', 'dont_match_me', {}, ), transform_fn=lambda *_args: None, ), ], ) def test_context_name_mismatch(): with pytest.raises(DagsterInvalidDefinitionError, match='wrong context name'): PipelineDefinition( name='context_name_mismatch', solids=[], context_definitions={ 'test': PipelineContextDefinition( context_fn=lambda *_args: None, config_field=ConfigField.context_config_dict( 'context_name_mismatch', 'nope', {}, ) ) } ) with pytest.raises(DagsterInvalidDefinitionError, match='solid_config_dict'): PipelineDefinition( name='context_name_mismatch', solids=[], context_definitions={ 'test': PipelineContextDefinition( context_fn=lambda *_args: None, config_field=ConfigField.solid_config_dict( 'context_name_mismatch', 'some_solid', {}, ) ) } ) def test_solid_list_config(): value = [1, 2] called = {} def _test_config(info, _inputs): assert info.config == value called['yup'] = True pipeline_def = PipelineDefinition( name='solid_list_config_pipeline', solids=[ SolidDefinition( name='solid_list_config', inputs=[], outputs=[], config_field=Field(types.List(types.Int)), transform_fn=_test_config ), ], ) result = execute_pipeline( pipeline_def, environment={'solids': { 'solid_list_config': { 'config': value } }} ) assert result.success assert called['yup'] def test_two_list_types(): assert PipelineDefinition( name='two_types', solids=[ SolidDefinition( name='two_list_type', inputs=[], outputs=[], config_field=ConfigField.solid_config_dict( 'two_types', 'two_list_type', { 'list_one': types.Field(types.List(types.Int)), 'list_two': types.Field(types.List(types.Int)), }, ), transform_fn=lambda *_args: None, ), ], ) def test_multilevel_default_handling(): @solid(config_field=Field(types.Int, is_optional=True, default_value=234)) def has_default_value(info): assert info.config == 234 pipeline_def = PipelineDefinition( name='multilevel_default_handling', solids=[has_default_value], ) assert execute_pipeline(pipeline_def).success assert execute_pipeline(pipeline_def, environment=None).success assert execute_pipeline(pipeline_def, environment={}).success assert execute_pipeline(pipeline_def, environment={'solids': None}).success assert execute_pipeline(pipeline_def, environment={'solids': {}}).success assert execute_pipeline( pipeline_def, environment={ 'solids': { 'has_default_value': None } }, ).success assert execute_pipeline( pipeline_def, environment={ 'solids': { 'has_default_value': {} } }, ).success assert execute_pipeline( pipeline_def, environment={ 'solids': { 'has_default_value': { 'config': 234 } } }, ).success def test_no_env_missing_required_error_handling(): @solid(config_field=Field(types.Int)) def required_int_solid(_info): pass pipeline_def = PipelineDefinition( name='no_env_missing_required_error', solids=[required_int_solid], ) with pytest.raises(PipelineConfigEvaluationError) as pe_info: execute_pipeline(pipeline_def) assert isinstance(pe_info.value, PipelineConfigEvaluationError) pe = pe_info.value assert len(pe.errors) == 1 mfe = pe.errors[0] assert mfe.reason == DagsterEvaluationErrorReason.MISSING_REQUIRED_FIELD assert len(pe.error_messages) == 1 assert 'Missing required field "solids"' in pe.message assert 'at document config root' in pe.message assert 'Missing required field "solids"' in pe.error_messages[0] def test_root_extra_field(): @solid(config_field=Field(types.Int)) def required_int_solid(_info): pass pipeline_def = PipelineDefinition( name='root_extra_field', solids=[required_int_solid], ) with pytest.raises(PipelineConfigEvaluationError) as pe_info: execute_pipeline( pipeline_def, environment={ 'solids': { 'required_int_solid': { 'config': 948594 } }, 'nope': None, }, ) pe = pe_info.value assert len(pe.errors) == 1 fnd = pe.errors[0] assert fnd.reason == DagsterEvaluationErrorReason.FIELD_NOT_DEFINED assert 'Undefined field "nope"' in pe.message def test_deeper_path(): @solid(config_field=Field(types.Int)) def required_int_solid(_info): pass pipeline_def = PipelineDefinition( name='deeper_path', solids=[required_int_solid], ) with pytest.raises(PipelineConfigEvaluationError) as pe_info: execute_pipeline( pipeline_def, environment={ 'solids': { 'required_int_solid': { 'config': 'asdf', }, }, }, ) pe = pe_info.value assert len(pe.errors) == 1 rtm = pe.errors[0] assert rtm.reason == DagsterEvaluationErrorReason.RUNTIME_TYPE_MISMATCH def test_working_list_path(): called = {} @solid(config_field=Field(types.List(types.Int))) def required_list_int_solid(info): assert info.config == [1, 2] called['yup'] = True pipeline_def = PipelineDefinition( name='list_path', solids=[required_list_int_solid], ) result = execute_pipeline( pipeline_def, environment={ 'solids': { 'required_list_int_solid': { 'config': [1, 2], }, }, }, ) assert result.success assert called['yup'] def test_item_error_list_path(): called = {} @solid(config_field=Field(types.List(types.Int))) def required_list_int_solid(info): assert info.config == [1, 2] called['yup'] = True pipeline_def = PipelineDefinition( name='list_path', solids=[required_list_int_solid], ) with pytest.raises(PipelineConfigEvaluationError) as pe_info: execute_pipeline( pipeline_def, environment={ 'solids': { 'required_list_int_solid': { 'config': [1, 'nope'], }, }, }, ) pe = pe_info.value assert len(pe.errors) == 1 rtm = pe.errors[0] assert rtm.reason == DagsterEvaluationErrorReason.RUNTIME_TYPE_MISMATCH assert 'Type failure at path "root:solids:required_list_int_solid:config[1]"' in str(pe) def test_context_selector_working(): called = {} @solid def check_context(info): assert info.context.resources == 32 called['yup'] = True pipeline_def = PipelineDefinition( name='context_selector_working', solids=[check_context], context_definitions={ 'context_required_int': PipelineContextDefinition( context_fn=lambda info: ExecutionContext(resources=info.config), config_field=types.Field(types.Int), ) } ) result = execute_pipeline( pipeline_def, environment={ 'context': { 'context_required_int': { 'config': 32, }, }, }, ) assert result.success assert called['yup'] def test_context_selector_extra_context(): @solid def check_context(_info): assert False pipeline_def = PipelineDefinition( name='context_selector_extra_context', solids=[check_context], context_definitions={ 'context_required_int': PipelineContextDefinition( context_fn=lambda info: ExecutionContext(resources=info.config), config_field=types.Field(types.Int), ) } ) with pytest.raises(PipelineConfigEvaluationError) as pe_info: execute_pipeline( pipeline_def, environment={ 'context': { 'context_required_int': { 'config': 32, }, 'extra_context': { 'config': None, }, }, }, ) pe = pe_info.value cse = pe.errors[0] assert cse.reason == DagsterEvaluationErrorReason.SELECTOR_FIELD_ERROR assert 'Specified more than one field at path "root:context"' in str(pe) def test_context_selector_wrong_name(): @solid def check_context(_info): assert False pipeline_def = PipelineDefinition( name='context_selector_wrong_name', solids=[check_context], context_definitions={ 'context_required_int': PipelineContextDefinition( context_fn=lambda info: ExecutionContext(resources=info.config), config_field=types.Field(types.Int), ) } ) with pytest.raises(PipelineConfigEvaluationError) as pe_info: execute_pipeline( pipeline_def, environment={ 'context': { 'wrong_name': { 'config': None, }, }, }, ) pe = pe_info.value cse = pe.errors[0] assert cse.reason == DagsterEvaluationErrorReason.FIELD_NOT_DEFINED assert 'Undefined field "wrong_name" at path root:context' in str(pe) def test_context_selector_none_given(): @solid def check_context(_info): assert False pipeline_def = PipelineDefinition( name='context_selector_none_given', solids=[check_context], context_definitions={ 'context_required_int': PipelineContextDefinition( context_fn=lambda info: ExecutionContext(resources=info.config), config_field=types.Field(types.Int), ) } ) with pytest.raises(PipelineConfigEvaluationError) as pe_info: execute_pipeline( pipeline_def, environment={'context': None}, ) pe = pe_info.value cse = pe.errors[0] assert cse.reason == DagsterEvaluationErrorReason.SELECTOR_FIELD_ERROR assert 'You specified no fields at path "root:context"' in str(pe) def test_multilevel_good_error_handling_solids(): @solid(config_field=Field(types.Int)) def good_error_handling(_info): pass pipeline_def = PipelineDefinition( name='multilevel_good_error_handling', solids=[good_error_handling], ) with pytest.raises(PipelineConfigEvaluationError) as pe_info: execute_pipeline(pipeline_def, environment={'solids': None}) pe = pe_info.value assert 'Missing required field "good_error_handling" at path root:solids' in str(pe) def test_multilevel_good_error_handling_solid_name_solids(): @solid(config_field=Field(types.Int)) def good_error_handling(_info): pass pipeline_def = PipelineDefinition( name='multilevel_good_error_handling', solids=[good_error_handling], ) with pytest.raises(PipelineConfigEvaluationError) as pe_info: execute_pipeline(pipeline_def, environment={'solids': {'good_error_handling': {}}}) pe = pe_info.value assert 'Missing required field "config" at path root:solids:good_error_handling' in str(pe) def test_multilevel_good_error_handling_config_solids_name_solids(): @solid(config_field=Field(types.Int)) def good_error_handling(_info): pass pipeline_def = PipelineDefinition( name='multilevel_good_error_handling', solids=[good_error_handling], ) execute_pipeline( pipeline_def, environment={'solids': { 'good_error_handling': { 'config': None } }} )
1
11,827
how would you feel about keeping these tests to be more explicit and having them `assert not _validate...`? or is your view that that is too duplicative of the tests in `test_evaluator.py`?
dagster-io-dagster
py
@@ -21,10 +21,11 @@ test_name "bolt plan run should apply manifest block on remote hosts via winrm" scp_to(bolt, File.join(fixtures, 'example_apply'), "#{dir}/modules/example_apply") end - bolt_command = "bolt plan run example_apply filepath=#{filepath} nodes=winrm_nodes" + bolt_command = "bolt plan run example_apply filepath=#{filepath}" flags = { '--modulepath' => modulepath(File.join(dir, 'modules')), - '--format' => 'json' + '--format' => 'json', + '-t' => "winrm_nodes" } teardown do
1
# frozen_string_literal: true require 'bolt_command_helper' require 'json' test_name "bolt plan run should apply manifest block on remote hosts via winrm" do extend Acceptance::BoltCommandHelper winrm_nodes = select_hosts(roles: ['winrm']) skip_test('no applicable nodes to test on') if winrm_nodes.empty? controller_has_ruby = on(bolt, 'which ruby', accept_all_exit_codes: true).exit_code == 0 skip_test('FIX: apply uses wrong Ruby') if controller_has_ruby && bolt[:roles].include?('winrm') dir = bolt.tmpdir('apply_winrm') fixtures = File.absolute_path('files') filepath = File.join('C:/', SecureRandom.uuid.to_s) step "create plan on bolt controller" do on(bolt, "mkdir -p #{dir}/modules") scp_to(bolt, File.join(fixtures, 'example_apply'), "#{dir}/modules/example_apply") end bolt_command = "bolt plan run example_apply filepath=#{filepath} nodes=winrm_nodes" flags = { '--modulepath' => modulepath(File.join(dir, 'modules')), '--format' => 'json' } teardown do on(winrm_nodes, "rm -rf #{filepath}") end step "execute `bolt plan run noop=true` via WinRM with json output" do result = bolt_command_on(bolt, bolt_command + ' noop=true', flags) assert_equal(0, result.exit_code, "Bolt did not exit with exit code 0") begin json = JSON.parse(result.stdout) rescue JSON::ParserError assert_equal("Output should be JSON", result.string, "Output should be JSON") end winrm_nodes.each do |node| # Verify that node succeeded host = node.hostname result = json.select { |n| n['node'] == host } assert_equal('success', result[0]['status'], "The task did not succeed on #{host}") # Verify that files were not created on the target on(node, "cat #{filepath}/hello.txt", acceptable_exit_codes: [1]) end end step "execute `bolt plan run` via WinRM with json output" do result = bolt_command_on(bolt, bolt_command, flags) assert_equal(0, result.exit_code, "Bolt did not exit with exit code 0") begin json = JSON.parse(result.stdout) rescue JSON::ParserError assert_equal("Output should be JSON", result.string, "Output should be JSON") end winrm_nodes.each do |node| # Verify that node succeeded host = node.hostname result = json.select { |n| n['node'] == host } assert_equal('success', result[0]['status'], "The task did not succeed on #{host}") # Verify the custom type was invoked logs = result[0]['result']['report']['logs'] warnings = logs.select { |l| l['level'] == 'warning' } assert_equal(1, warnings.count) assert_equal('Writing a MOTD!', warnings[0]['message']) # Verify that files were created on the target hello = on(node, "cat #{filepath}/hello.txt") assert_match(/^hi there I'm windows$/, hello.stdout) motd = on(node, "cat #{filepath}/motd") assert_equal("Today's #WordOfTheDay is 'gloss'", motd.stdout) end end step "puppet service should be stopped" do service_command = 'bolt plan run example_apply::puppet_status -n winrm_nodes' flags = { '--modulepath' => modulepath(File.join(dir, 'modules')), '--format' => 'json' } result = bolt_command_on(bolt, service_command, flags) assert_equal(0, result.exit_code, "Bolt did not exit with exit code 0") begin json = JSON.parse(result.stdout) rescue JSON::ParserError assert_equal("Output should be JSON", result.string, "Output should be JSON") end winrm_nodes.each do |node| # Verify that node succeeded host = node.hostname result = json.select { |n| n['node'] == host } assert_equal('success', result[0]['status'], "The task did not succeed on #{host}") assert_equal('stopped', result[0]['result']['status'], "Puppet must be stopped") assert_equal('false', result[0]['result']['enabled'], "Puppet must be disabled") end end end
1
13,783
Why do we use the `winrm_nodes` variable here and not the string `"winrm_nodes"` as we were using before?
puppetlabs-bolt
rb
@@ -1,4 +1,4 @@ -/* Copyright (c) 2018 vesoft inc. All rights reserved. +/* Copyright (c) 2019 vesoft inc. All rights reserved. * * This source code is licensed under Apache 2.0 License, * attached with Common Clause Condition 1.0, found in the LICENSES directory.
1
/* Copyright (c) 2018 vesoft inc. All rights reserved. * * This source code is licensed under Apache 2.0 License, * attached with Common Clause Condition 1.0, found in the LICENSES directory. */ #include "base/Base.h" #include <gtest/gtest.h> #include "base/Cord.h" namespace nebula { TEST(Cord, write) { Cord cord; cord.write("cord", 4).write("-", 1).write("test", 4); EXPECT_EQ(9, cord.size()); EXPECT_EQ(9, cord.str().size()); EXPECT_EQ("cord-test", cord.str()); int64_t iVal = 1234567890L; cord.write(reinterpret_cast<char*>(&iVal), sizeof(int64_t)); EXPECT_EQ(9 + sizeof(int64_t), cord.size()); EXPECT_EQ(9 + sizeof(int64_t), cord.str().size()); iVal = 0; memcpy(reinterpret_cast<char*>(&iVal), cord.str().data() + 9, sizeof(int64_t)); EXPECT_EQ(1234567890L, iVal); } TEST(Cord, multipleBlocks) { Cord cord(128); std::string buf; for (int i = 0; i < 100; i++) { buf.append("Hello World!"); } cord.write(buf.data(), buf.size()); EXPECT_EQ(buf.size(), cord.size()); EXPECT_EQ(buf.size(), cord.str().size()); EXPECT_EQ(buf, cord.str()); } TEST(Cord, byteStream) { Cord cord1; cord1 << static_cast<int8_t>('A') << static_cast<uint8_t>('b') << 'C' << true; EXPECT_EQ(4, cord1.size()); EXPECT_EQ(4, cord1.str().size()); EXPECT_EQ("AbC", cord1.str().substr(0, 3)); bool bVal = false; memcpy(reinterpret_cast<char*>(&bVal), cord1.str().data() + 3, sizeof(bool)); EXPECT_EQ(true, bVal); uint8_t bytes[] = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF}; Cord cord2; cord2 << folly::ByteRange(bytes, sizeof(bytes)); std::string str = cord2.str(); EXPECT_EQ(sizeof(bytes), str.size()); const char* p = str.data(); for (auto i = 0UL; i < str.size(); i++) { EXPECT_EQ(bytes[i], uint8_t(p[i])); } } TEST(Cord, integerStream) { Cord cord; cord << static_cast<int16_t>(16) << static_cast<uint16_t>(0x8080) << static_cast<int32_t>(32) << static_cast<uint32_t>(0xFF00FF00) << static_cast<int64_t>(64) << static_cast<uint64_t>(0xFF11FF22FF33FF44UL); EXPECT_EQ(sizeof(int16_t) + sizeof(uint16_t) + sizeof(int32_t) + sizeof(uint32_t) + sizeof(int64_t) + sizeof(uint64_t), cord.size()); EXPECT_EQ(sizeof(int16_t) + sizeof(uint16_t) + sizeof(int32_t) + sizeof(uint32_t) + sizeof(int64_t) + sizeof(uint64_t), cord.str().size()); int16_t sVal; uint16_t usVal; int32_t iVal; uint32_t uiVal; int64_t lVal; uint64_t ulVal; std::string str = cord.str(); memcpy(reinterpret_cast<char*>(&sVal), str.data(), sizeof(int16_t)); memcpy(reinterpret_cast<char*>(&usVal), str.data() + sizeof(int16_t), sizeof(uint16_t)); memcpy(reinterpret_cast<char*>(&iVal), str.data() + sizeof(int16_t) + sizeof(uint16_t), sizeof(int32_t)); memcpy(reinterpret_cast<char*>(&uiVal), str.data() + sizeof(int16_t) + sizeof(uint16_t) + sizeof(int32_t), sizeof(uint32_t)); memcpy(reinterpret_cast<char*>(&lVal), str.data() + sizeof(int16_t) + sizeof(uint16_t) + sizeof(int32_t) + sizeof(uint32_t), sizeof(int64_t)); memcpy(reinterpret_cast<char*>(&ulVal), str.data() + sizeof(int16_t) + sizeof(uint16_t) + sizeof(int32_t) + sizeof(uint32_t) + sizeof(int64_t), sizeof(uint64_t)); EXPECT_EQ(16, sVal); EXPECT_EQ(0x8080, usVal); EXPECT_EQ(32, iVal); EXPECT_EQ(0xFF00FF00, uiVal); EXPECT_EQ(64, lVal); EXPECT_EQ(0xFF11FF22FF33FF44UL, ulVal); } TEST(Cord, floatStream) { Cord cord; cord << static_cast<float>(1.234) << static_cast<double>(9.876); EXPECT_EQ(sizeof(float) + sizeof(double), cord.size()); EXPECT_EQ(sizeof(float) + sizeof(double), cord.str().size()); float fVal; double dVal; std::string str = cord.str(); memcpy(reinterpret_cast<char*>(&fVal), str.data(), sizeof(float)); memcpy(reinterpret_cast<char*>(&dVal), str.data() + sizeof(float), sizeof(double)); EXPECT_FLOAT_EQ(1.234, fVal); EXPECT_DOUBLE_EQ(9.876, dVal); } TEST(Cord, stringStream) { std::string str1("Hello"); char str2[] = "Beautiful"; std::string str3("World"); Cord cord; cord << str1 << str2 << folly::StringPiece(str3); EXPECT_EQ(str1.size() + strlen(str2) + str3.size(), cord.size()); EXPECT_EQ(str1.size() + strlen(str2) + str3.size(), cord.str().size()); EXPECT_EQ(str1 + str2 + str3, cord.str()); } TEST(Cord, cordStream) { Cord c1; Cord c2; std::string str1("Hello world!"); std::string str2("Welcome to the future!"); c2 << str2; c1 << str1 << c2; EXPECT_EQ(str1.size() + str2.size(), c1.size()); EXPECT_EQ(str1 + str2, c1.str()); } } // namespace nebula int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); folly::init(&argc, &argv, true); google::SetStderrLogging(google::INFO); return RUN_ALL_TESTS(); }
1
22,325
why update Copyright ?
vesoft-inc-nebula
cpp