text,length,is_long_context,metric_val,label_metric "[[cluster-nodes-stats]] === Nodes stats API ++++ Nodes stats ++++ Returns cluster nodes statistics. [[cluster-nodes-stats-api-request]] ==== {api-request-title} `GET /_nodes/stats` + `GET /_nodes//stats` + `GET/_nodes/stats/` + `GET/_nodes//stats/` + `GET /_nodes/stats//` + `GET /_nodes//stats//` [[cluster-nodes-stats-api-desc]] ==== {api-description-title} You can use the cluster nodes stats API to retrieve statistics for nodes in a cluster. All the nodes selective options are explained <>. By default, all stats are returned. You can limit the returned information by using metrics. [[cluster-nodes-stats-api-path-params]] ==== {api-path-parms-title} ``:: (Optional, string) Limits the information returned to the specific metrics. A comma-separated list of the following options: + -- `adaptive_selection`:: Statistics about <>. `breaker`:: Statistics about the field data circuit breaker. `discovery`:: Statistics about the discovery. `fs`:: File system information, data path, free disk space, read/write stats. `http`:: HTTP connection information. `indexing_pressure`:: Statistics about the node's indexing load and related rejections. `indices`:: Indices stats about size, document count, indexing and deletion times, search times, field cache size, merges and flushes. `ingest`:: Statistics about ingest preprocessing. `jvm`:: JVM stats, memory pool information, garbage collection, buffer pools, number of loaded/unloaded classes. `os`:: Operating system stats, load average, mem, swap. `process`:: Process statistics, memory consumption, cpu usage, open file descriptors. `thread_pool`:: Statistics about each thread pool, including current size, queue and rejected tasks. `transport`:: Transport statistics about sent and received bytes in cluster communication. -- ``:: (Optional, string) Limit the information returned for `indices` metric to the specific index metrics. It can be used only if `indices` (or `all`) metric is specified. Supported metrics are: + -- * `completion` * `docs` * `fielddata` * `flush` * `get` * `indexing` * `merge` * `query_cache` * `recovery` * `refresh` * `request_cache` * `search` * `segments` * `store` * `translog` * `warmer` -- include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=node-id] [[cluster-nodes-stats-api-query-params]] ==== {api-query-parms-title} include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=completion-fields] include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=fielddata-fields] include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=fields] include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=groups] include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=level] `types`:: (Optional, string) A comma-separated list of document types for the `indexing` index metric. include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=timeoutparms] include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=include-segment-file-sizes] [role=""child_attributes""] [[cluster-nodes-stats-api-response-body]] ==== {api-response-body-title} `_nodes`:: (object) Contains statistics about the number of nodes selected by the request. + .Properties of `_nodes` [%collapsible%open] ==== `total`:: (integer) Total number of nodes selected by the request. `successful`:: (integer) Number of nodes that responded successfully to the request. `failed`:: (integer) Number of nodes that rejected the request or failed to respond. If this value is not `0`, a reason for the rejection or failure is included in the response. ==== `cluster_name`:: (string) Name of the cluster. Based on the <> setting. `nodes`:: (object) Contains statistics for the nodes selected by the request. + .Properties of `nodes` [%collapsible%open] ==== ``:: (object) Contains statistics for the node. + .Properties of `` [%collapsible%open] ===== `timestamp`:: (integer) Time the node stats were collected for this response. Recorded in milliseconds since the {wikipedia}/Unix_time[Unix Epoch]. `name`:: (string) Human-readable identifier for the node. Based on the <> setting. `transport_address`:: (string) Host and port for the <>, used for internal communication between nodes in a cluster. `host`:: (string) Network host for the node, based on the <> setting. `ip`:: (string) IP address and port for the node. `roles`:: (array of strings) Roles assigned to the node. See <>. `attributes`:: (object) Contains a list of attributes for the node. [[cluster-nodes-stats-api-response-body-indices]] `indices`:: (object) Contains statistics about indices with shards assigned to the node. + .Properties of `indices` [%collapsible%open] ====== `docs`:: (object) Contains statistics about documents across all primary shards assigned to the node. + .Properties of `docs` [%collapsible%open] ======= `count`:: (integer) include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=docs-count] `deleted`:: (integer) include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=docs-deleted] ======= `store`:: (object) Contains statistics about the size of shards assigned to the node. + .Properties of `store` [%collapsible%open] ======= `size`:: (<>) Total size of all shards assigned to the node. `size_in_bytes`:: (integer) Total size, in bytes, of all shards assigned to the node. `reserved`:: (<>) A prediction of how much larger the shard stores on this node will eventually grow due to ongoing peer recoveries, restoring snapshots, and similar activities. A value of `-1b` indicates that this is not available. `reserved_in_bytes`:: (integer) A prediction, in bytes, of how much larger the shard stores on this node will eventually grow due to ongoing peer recoveries, restoring snapshots, and similar activities. A value of `-1` indicates that this is not available. ======= `indexing`:: (object) Contains statistics about indexing operations for the node. + .Properties of `indexing` [%collapsible%open] ======= `index_total`:: (integer) Total number of indexing operations. `index_time`:: (<>) Total time spent performing indexing operations. `index_time_in_millis`:: (integer) Total time in milliseconds spent performing indexing operations. `index_current`:: (integer) Number of indexing operations currently running. `index_failed`:: (integer) Number of failed indexing operations. `delete_total`:: (integer) Total number of deletion operations. `delete_time`:: (<>) Time spent performing deletion operations. `delete_time_in_millis`:: (integer) Time in milliseconds spent performing deletion operations. `delete_current`:: (integer) Number of deletion operations currently running. `noop_update_total`:: (integer) Total number of noop operations. `is_throttled`:: (boolean) Number of times operations were throttled. `throttle_time`:: (<>) Total time spent throttling operations. `throttle_time_in_millis`:: (integer) Total time in milliseconds spent throttling operations. ======= `get`:: (object) Contains statistics about get operations for the node. + .Properties of `get` [%collapsible%open] ======= `total`:: (integer) Total number of get operations. `getTime`:: (<>) Time spent performing get operations. `time_in_millis`:: (integer) Time in milliseconds spent performing get operations. `exists_total`:: (integer) Total number of successful get operations. `exists_time`:: (<>) Time spent performing successful get operations. `exists_time_in_millis`:: (integer) Time in milliseconds spent performing successful get operations. `missing_total`:: (integer) Total number of failed get operations. `missing_time`:: (<>) Time spent performing failed get operations. `missing_time_in_millis`:: (integer) Time in milliseconds spent performing failed get operations. `current`:: (integer) Number of get operations currently running. ======= `search`:: (object) Contains statistics about search operations for the node. + .Properties of `search` [%collapsible%open] ======= `open_contexts`:: (integer) Number of open search contexts. `query_total`:: (integer) Total number of query operations. `query_time`:: (<>) Time spent performing query operations. `query_time_in_millis`:: (integer) Time in milliseconds spent performing query operations. `query_current`:: (integer) Number of query operations currently running. `fetch_total`:: (integer) Total number of fetch operations. `fetch_time`:: (<>) Time spent performing fetch operations. `fetch_time_in_millis`:: (integer) Time in milliseconds spent performing fetch operations. `fetch_current`:: (integer) Number of fetch operations currently running. `scroll_total`:: (integer) Total number of scroll operations. `scroll_time`:: (<>) Time spent performing scroll operations. `scroll_time_in_millis`:: (integer) Time in milliseconds spent performing scroll operations. `scroll_current`:: (integer) Number of scroll operations currently running. `suggest_total`:: (integer) Total number of suggest operations. `suggest_time`:: (<>) Time spent performing suggest operations. `suggest_time_in_millis`:: (integer) Time in milliseconds spent performing suggest operations. `suggest_current`:: (integer) Number of suggest operations currently running. ======= `merges`:: (object) Contains statistics about merge operations for the node. + .Properties of `merges` [%collapsible%open] ======= `current`:: (integer) Number of merge operations currently running. `current_docs`:: (integer) Number of document merges currently running. `current_size`:: (<>) Memory used performing current document merges. `current_size_in_bytes`:: (integer) Memory, in bytes, used performing current document merges. `total`:: (integer) Total number of merge operations. `total_time`:: (<>) Total time spent performing merge operations. `total_time_in_millis`:: (integer) Total time in milliseconds spent performing merge operations. `total_docs`:: (integer) Total number of merged documents. `total_size`:: (<>) Total size of document merges. `total_size_in_bytes`:: (integer) Total size of document merges in bytes. `total_stopped_time`:: (<>) Total time spent stopping merge operations. `total_stopped_time_in_millis`:: (integer) Total time in milliseconds spent stopping merge operations. `total_throttled_time`:: (<>) Total time spent throttling merge operations. `total_throttled_time_in_millis`:: (integer) Total time in milliseconds spent throttling merge operations. `total_auto_throttle`:: (<>) Size of automatically throttled merge operations. `total_auto_throttle_in_bytes`:: (integer) Size, in bytes, of automatically throttled merge operations. ======= `refresh`:: (object) Contains statistics about refresh operations for the node. + .Properties of `refresh` [%collapsible%open] ======= `total`:: (integer) Total number of refresh operations. `total_time`:: (<>) Total time spent performing refresh operations. `total_time_in_millis`:: (integer) Total time in milliseconds spent performing refresh operations. `external_total`:: (integer) Total number of external refresh operations. `external_total_time`:: (<>) Total time spent performing external operations. `external_total_time_in_millis`:: (integer) Total time in milliseconds spent performing external operations. `listeners`:: (integer) Number of refresh listeners. ======= `flush`:: (object) Contains statistics about flush operations for the node. + .Properties of `flush` [%collapsible%open] ======= `total`:: (integer) Number of flush operations. `periodic`:: (integer) Number of flush periodic operations. `total_time`:: (<>) Total time spent performing flush operations. `total_time_in_millis`:: (integer) Total time in milliseconds spent performing flush operations. ======= `warmer`:: (object) Contains statistics about index warming operations for the node. + .Properties of `warmer` [%collapsible%open] ======= `current`:: (integer) Number of active index warmers. `total`:: (integer) Total number of index warmers. `total_time`:: (<>) Total time spent performing index warming operations. `total_time_in_millis`:: (integer) Total time in milliseconds spent performing index warming operations. ======= `query_cache`:: (object) Contains statistics about the query cache across all shards assigned to the node. + .Properties of `query_cache` [%collapsible%open] ======= `memory_size`:: (<>) Total amount of memory used for the query cache across all shards assigned to the node. `memory_size_in_bytes`:: (integer) Total amount of memory, in bytes, used for the query cache across all shards assigned to the node. `total_count`:: (integer) Total count of hits, misses, and cached queries in the query cache. `hit_count`:: (integer) Number of query cache hits. `miss_count`:: (integer) Number of query cache misses. `cache_size`:: (integer) Size, in bytes, of the query cache. `cache_count`:: (integer) Count of queries in the query cache. `evictions`:: (integer) Number of query cache evictions. ======= `fielddata`:: (object) Contains statistics about the field data cache across all shards assigned to the node. + .Properties of `fielddata` [%collapsible%open] ======= `memory_size`:: (<>) Total amount of memory used for the field data cache across all shards assigned to the node. `memory_size_in_bytes`:: (integer) Total amount of memory, in bytes, used for the field data cache across all shards assigned to the node. `evictions`:: (integer) Number of fielddata evictions. ======= `completion`:: (object) Contains statistics about completions across all shards assigned to the node. + .Properties of `completion` [%collapsible%open] ======= `size`:: (<>) Total amount of memory used for completion across all shards assigned to the node. `size_in_bytes`:: (integer) Total amount of memory, in bytes, used for completion across all shards assigned to the node. ======= `segments`:: (object) Contains statistics about segments across all shards assigned to the node. + .Properties of `segments` [%collapsible%open] ======= `count`:: (integer) Number of segments. `memory`:: (<>) Total amount of memory used for segments across all shards assigned to the node. `memory_in_bytes`:: (integer) Total amount of memory, in bytes, used for segments across all shards assigned to the node. `terms_memory`:: (<>) Total amount of memory used for terms across all shards assigned to the node. `terms_memory_in_bytes`:: (integer) Total amount of memory, in bytes, used for terms across all shards assigned to the node. `stored_fields_memory`:: (<>) Total amount of memory used for stored fields across all shards assigned to the node. `stored_fields_memory_in_bytes`:: (integer) Total amount of memory, in bytes, used for stored fields across all shards assigned to the node. `term_vectors_memory`:: (<>) Total amount of memory used for term vectors across all shards assigned to the node. `term_vectors_memory_in_bytes`:: (integer) Total amount of memory, in bytes, used for term vectors across all shards assigned to the node. `norms_memory`:: (<>) Total amount of memory used for normalization factors across all shards assigned to the node. `norms_memory_in_bytes`:: (integer) Total amount of memory, in bytes, used for normalization factors across all shards assigned to the node. `points_memory`:: (<>) Total amount of memory used for points across all shards assigned to the node. `points_memory_in_bytes`:: (integer) Total amount of memory, in bytes, used for points across all shards assigned to the node. `doc_values_memory`:: (<>) Total amount of memory used for doc values across all shards assigned to the node. `doc_values_memory_in_bytes`:: (integer) Total amount of memory, in bytes, used for doc values across all shards assigned to the node. `index_writer_memory`:: (<>) Total amount of memory used by all index writers across all shards assigned to the node. `index_writer_memory_in_bytes`:: (integer) Total amount of memory, in bytes, used by all index writers across all shards assigned to the node. `version_map_memory`:: (<>) Total amount of memory used by all version maps across all shards assigned to the node. `version_map_memory_in_bytes`:: (integer) Total amount of memory, in bytes, used by all version maps across all shards assigned to the node. `fixed_bit_set`:: (<>) Total amount of memory used by fixed bit sets across all shards assigned to the node. + Fixed bit sets are used for nested object field types and type filters for <> fields. `fixed_bit_set_memory_in_bytes`:: (integer) Total amount of memory, in bytes, used by fixed bit sets across all shards assigned to the node. + Fixed bit sets are used for nested object field types and type filters for <> fields. `max_unsafe_auto_id_timestamp`:: (integer) Time of the most recently retried indexing request. Recorded in milliseconds since the {wikipedia}/Unix_time[Unix Epoch]. `file_sizes`:: (object) Contains statistics about the size of the segment file. + .Properties of `file_sizes` [%collapsible%open] ======== `size`:: (<>) Size of the segment file. `size_in_bytes`:: (integer) Size, in bytes, of the segment file. `description`:: (string) Description of the segment file. ======== ======= `translog`:: (object) Contains statistics about transaction log operations for the node. + .Properties of `translog` [%collapsible%open] ======= `operations`:: (integer) Number of transaction log operations. `size`:: (<>) Size of the transaction log. `size_in_bytes`:: (integer) Size, in bytes, of the transaction log. `uncommitted_operations`:: (integer) Number of uncommitted transaction log operations. `uncommitted_size`:: (<>) Size of uncommitted transaction log operations. `uncommitted_size_in_bytes`:: (integer) Size, in bytes, of uncommitted transaction log operations. `earliest_last_modified_age`:: (integer) Earliest last modified age for the transaction log. ======= `request_cache`:: (object) Contains statistics about the request cache across all shards assigned to the node. + .Properties of `request_cache` [%collapsible%open] ======= `memory_size`:: (<>) Memory used by the request cache. `memory_size_in_bytes`:: (integer) Memory, in bytes, used by the request cache. `evictions`:: (integer) Number of request cache operations. `hit_count`:: (integer) Number of request cache hits. `miss_count`:: (integer) Number of request cache misses. ======= `recovery`:: (object) Contains statistics about recovery operations for the node. + .Properties of `recovery` [%collapsible%open] ======= `current_as_source`:: (integer) Number of recoveries that used an index shard as a source. `current_as_target`:: (integer) Number of recoveries that used an index shard as a target. `throttle_time`:: (<>) Time by which recovery operations were delayed due to throttling. `throttle_time_in_millis`:: (integer) Time in milliseconds recovery operations were delayed due to throttling. ======= ====== [[cluster-nodes-stats-api-response-body-os]] `os`:: (object) Contains statistics about the operating system for the node. + .Properties of `os` [%collapsible%open] ====== `timestamp`:: (integer) Last time the operating system statistics were refreshed. Recorded in milliseconds since the {wikipedia}/Unix_time[Unix Epoch]. `cpu`:: (object) Contains statistics about CPU usage for the node. + .Properties of `cpu` [%collapsible%open] ======= `percent`:: (integer) Recent CPU usage for the whole system, or `-1` if not supported. `load_average`:: (object) Contains statistics about load averages on the system. + .Properties of `load_average` [%collapsible%open] ======== `1m`:: (float) One-minute load average on the system (field is not present if one-minute load average is not available). `5m`:: (float) Five-minute load average on the system (field is not present if five-minute load average is not available). `15m`:: (float) Fifteen-minute load average on the system (field is not present if fifteen-minute load average is not available). ======== ======= `mem`:: (object) Contains statistics about memory usage for the node. + .Properties of `mem` [%collapsible%open] ======= `total`:: (<>) Total amount of physical memory. `total_in_bytes`:: (integer) Total amount of physical memory in bytes. `free`:: (<>) Amount of free physical memory. `free_in_bytes`:: (integer) Amount of free physical memory in bytes. `used`:: (<>) Amount of used physical memory. `used_in_bytes`:: (integer) Amount of used physical memory in bytes. `free_percent`:: (integer) Percentage of free memory. `used_percent`:: (integer) Percentage of used memory. ======= `swap`:: (object) Contains statistics about swap space for the node. + .Properties of `swap` [%collapsible%open] ======= `total`:: (<>) Total amount of swap space. `total_in_bytes`:: (integer) Total amount of swap space in bytes. `free`:: (<>) Amount of free swap space. `free_in_bytes`:: (integer) Amount of free swap space in bytes. `used`:: (<>) Amount of used swap space. `used_in_bytes`:: (integer) Amount of used swap space in bytes. ======= `cgroup` (Linux only):: (object) Contains cgroup statistics for the node. + NOTE: For the cgroup stats to be visible, cgroups must be compiled into the kernel, the `cpu` and `cpuacct` cgroup subsystems must be configured and stats must be readable from `/sys/fs/cgroup/cpu` and `/sys/fs/cgroup/cpuacct`. + .Properties of `cgroup` [%collapsible%open] ======= `cpuacct` (Linux only):: (object) Contains statistics about `cpuacct` control group for the node. + .Properties of `cpuacct` [%collapsible%open] ======== `control_group` (Linux only):: (string) The `cpuacct` control group to which the {es} process belongs. `usage_nanos` (Linux only):: (integer) The total CPU time (in nanoseconds) consumed by all tasks in the same cgroup as the {es} process. ======== `cpu` (Linux only):: (object) Contains statistics about `cpu` control group for the node. + .Properties of `cpu` [%collapsible%open] ======== `control_group` (Linux only):: (string) The `cpu` control group to which the {es} process belongs. `cfs_period_micros` (Linux only):: (integer) The period of time (in microseconds) for how regularly all tasks in the same cgroup as the {es} process should have their access to CPU resources reallocated. `cfs_quota_micros` (Linux only):: (integer) The total amount of time (in microseconds) for which all tasks in the same cgroup as the {es} process can run during one period `cfs_period_micros`. `stat` (Linux only):: (object) Contains CPU statistics for the node. + .Properties of `stat` [%collapsible%open] ========= `number_of_elapsed_periods` (Linux only):: (integer) The number of reporting periods (as specified by `cfs_period_micros`) that have elapsed. `number_of_times_throttled` (Linux only):: (integer) The number of times all tasks in the same cgroup as the {es} process have been throttled. `time_throttled_nanos` (Linux only):: (integer) The total amount of time (in nanoseconds) for which all tasks in the same cgroup as the {es} process have been throttled. ========= ======== `memory` (Linux only):: (object) Contains statistics about the `memory` control group for the node. + .Properties of `memory` [%collapsible%open] ======== `control_group` (Linux only):: (string) The `memory` control group to which the {es} process belongs. `limit_in_bytes` (Linux only):: (string) The maximum amount of user memory (including file cache) allowed for all tasks in the same cgroup as the {es} process. This value can be too big to store in a `long`, so is returned as a string so that the value returned can exactly match what the underlying operating system interface returns. Any value that is too large to parse into a `long` almost certainly means no limit has been set for the cgroup. `usage_in_bytes` (Linux only):: (string) The total current memory usage by processes in the cgroup (in bytes) by all tasks in the same cgroup as the {es} process. This value is stored as a string for consistency with `limit_in_bytes`. ======== ======= ====== [[cluster-nodes-stats-api-response-body-process]] `process`:: (object) Contains process statistics for the node. + .Properties of `process` [%collapsible%open] ====== `timestamp`:: (integer) Last time the statistics were refreshed. Recorded in milliseconds since the {wikipedia}/Unix_time[Unix Epoch]. `open_file_descriptors`:: (integer) Number of opened file descriptors associated with the current or `-1` if not supported. `max_file_descriptors`:: (integer) Maximum number of file descriptors allowed on the system, or `-1` if not supported. `cpu`:: (object) Contains CPU statistics for the node. + .Properties of `cpu` [%collapsible%open] ======= `percent`:: (integer) CPU usage in percent, or `-1` if not known at the time the stats are computed. `total`:: (<>) CPU time used by the process on which the Java virtual machine is running. `total_in_millis`:: (integer) CPU time (in milliseconds) used by the process on which the Java virtual machine is running, or `-1` if not supported. ======= `mem`:: (object) Contains virtual memory statistics for the node. + .Properties of `mem` [%collapsible%open] ======= `total_virtual`:: (<>) Size of virtual memory that is guaranteed to be available to the running process. `total_virtual_in_bytes`:: (integer) Size in bytes of virtual memory that is guaranteed to be available to the running process. ======= ====== [[cluster-nodes-stats-api-response-body-jvm]] `jvm`:: (object) Contains Java Virtual Machine (JVM) statistics for the node. + .Properties of `jvm` [%collapsible%open] ====== `timestamp`:: (integer) Last time JVM statistics were refreshed. `uptime`:: (<>) JVM uptime. `uptime_in_millis`:: (integer) JVM uptime in milliseconds. `mem`:: (object) Contains JVM memory usage statistics for the node. + .Properties of `mem` [%collapsible%open] ======= `heap_used`:: (<>) Memory currently in use by the heap. `heap_used_in_bytes`:: (integer) Memory, in bytes, currently in use by the heap. `heap_used_percent`:: (integer) Percentage of memory currently in use by the heap. `heap_committed`:: (<>) Amount of memory available for use by the heap. `heap_committed_in_bytes`:: (integer) Amount of memory, in bytes, available for use by the heap. `heap_max`:: (<>) Maximum amount of memory available for use by the heap. `heap_max_in_bytes`:: (integer) Maximum amount of memory, in bytes, available for use by the heap. `non_heap_used`:: (<>) Non-heap memory used. `non_heap_used_in_bytes`:: (integer) Non-heap memory used, in bytes. `non_heap_committed`:: (<>) Amount of non-heap memory available. `non_heap_committed_in_bytes`:: (integer) Amount of non-heap memory available, in bytes. `pools`:: (object) Contains statistics about heap memory usage for the node. + .Properties of `pools` [%collapsible%open] ======== `young`:: (object) Contains statistics about memory usage by the young generation heap for the node. + .Properties of `young` [%collapsible%open] ========= `used`:: (<>) Memory used by the young generation heap. `used_in_bytes`:: (integer) Memory, in bytes, used by the young generation heap. `max`:: (<>) Maximum amount of memory available for use by the young generation heap. `max_in_bytes`:: (integer) Maximum amount of memory, in bytes, available for use by the young generation heap. `peak_used`:: (<>) Largest amount of memory historically used by the young generation heap. `peak_used_in_bytes`:: (integer) Largest amount of memory, in bytes, historically used by the young generation heap. `peak_max`:: (<>) Largest amount of memory historically used by the young generation heap. `peak_max_in_bytes`:: (integer) Largest amount of memory, in bytes, historically used by the young generation heap. ========= `survivor`:: (object) Contains statistics about memory usage by the survivor space for the node. + .Properties of `survivor` [%collapsible%open] ========= `used`:: (<>) Memory used by the survivor space. `used_in_bytes`:: (integer) Memory, in bytes, used by the survivor space. `max`:: (<>) Maximum amount of memory available for use by the survivor space. `max_in_bytes`:: (integer) Maximum amount of memory, in bytes, available for use by the survivor space. `peak_used`:: (<>) Largest amount of memory historically used by the survivor space. `peak_used_in_bytes`:: (integer) Largest amount of memory, in bytes, historically used by the survivor space. `peak_max`:: (<>) Largest amount of memory historically used by the survivor space. `peak_max_in_bytes`:: (integer) Largest amount of memory, in bytes, historically used by the survivor space. ========= `old`:: (object) Contains statistics about memory usage by the old generation heap for the node. + .Properties of `old` [%collapsible%open] ========= `used`:: (<>) Memory used by the old generation heap. `used_in_bytes`:: (integer) Memory, in bytes, used by the old generation heap. `max`:: (<>) Maximum amount of memory available for use by the old generation heap. `max_in_bytes`:: (integer) Maximum amount of memory, in bytes, available for use by the old generation heap. `peak_used`:: (<>) Largest amount of memory historically used by the old generation heap. `peak_used_in_bytes`:: (integer) Largest amount of memory, in bytes, historically used by the old generation heap. `peak_max`:: (<>) Highest memory limit historically available for use by the old generation heap. `peak_max_in_bytes`:: (integer) Highest memory limit, in bytes, historically available for use by the old generation heap. ========= ======== ======= `threads`:: (object) Contains statistics about JVM thread usage for the node. + .Properties of `threads` [%collapsible%open] ======= `count`:: (integer) Number of active threads in use by JVM. `peak_count`:: (integer) Highest number of threads used by JVM. ======= `gc`:: (object) Contains statistics about JVM garbage collectors for the node. + .Properties of `gc` [%collapsible%open] ======= `collectors`:: (object) Contains statistics about JVM garbage collectors for the node. + .Properties of `collectors` [%collapsible%open] ======== `young`:: (object) Contains statistics about JVM garbage collectors that collect young generation objects for the node. + .Properties of `young` [%collapsible%open] ========= `collection_count`:: (integer) Number of JVM garbage collectors that collect young generation objects. `collection_time`:: (<>) Total time spent by JVM collecting young generation objects. `collection_time_in_millis`:: (integer) Total time in milliseconds spent by JVM collecting young generation objects. ========= `old`:: (object) Contains statistics about JVM garbage collectors that collect old generation objects for the node. + .Properties of `old` [%collapsible%open] ========= `collection_count`:: (integer) Number of JVM garbage collectors that collect old generation objects. `collection_time`:: (<>) Total time spent by JVM collecting old generation objects. `collection_time_in_millis`:: (integer) Total time in milliseconds spent by JVM collecting old generation objects. ========= ======== ======= `buffer_pools`:: (object) Contains statistics about JVM buffer pools for the node. + .Properties of `buffer_pools` [%collapsible%open] ======= `mapped`:: (object) Contains statistics about mapped JVM buffer pools for the node. + .Properties of `mapped` [%collapsible%open] ======== `count`:: (integer) Number of mapped buffer pools. `used`:: (<>) Size of mapped buffer pools. `used_in_bytes`:: (integer) Size, in bytes, of mapped buffer pools. `total_capacity`:: (<>) Total capacity of mapped buffer pools. `total_capacity_in_bytes`:: (integer) Total capacity, in bytes, of mapped buffer pools. ======== `direct`:: (object) Contains statistics about direct JVM buffer pools for the node. + .Properties of `direct` [%collapsible%open] ======== `count`:: (integer) Number of direct buffer pools. `used`:: (<>) Size of direct buffer pools. `used_in_bytes`:: (integer) Size, in bytes, of direct buffer pools. `total_capacity`:: (<>) Total capacity of direct buffer pools. `total_capacity_in_bytes`:: (integer) Total capacity, in bytes, of direct buffer pools. ======== ======= `classes`:: (object) Contains statistics about classes loaded by JVM for the node. + .Properties of `classes` [%collapsible%open] ======= `current_loaded_count`:: (integer) Number of classes currently loaded by JVM. `total_loaded_count`:: (integer) Total number of classes loaded since the JVM started. `total_unloaded_count`:: (integer) Total number of classes unloaded since the JVM started. ======= ====== [[cluster-nodes-stats-api-response-body-threadpool]] `thread_pool`:: (object) Contains thread pool statistics for the node + .Properties of `thread_pool` [%collapsible%open] ====== ``:: (object) Contains statistics about the thread pool for the node. + .Properties of `` [%collapsible%open] ======= `threads`:: (integer) Number of threads in the thread pool. `queue`:: (integer) Number of tasks in queue for the thread pool. `active`:: (integer) Number of active threads in the thread pool. `rejected`:: (integer) Number of tasks rejected by the thread pool executor. `largest`:: (integer) Highest number of active threads in the thread pool. `completed`:: (integer) Number of tasks completed by the thread pool executor. ======= ====== [[cluster-nodes-stats-api-response-body-fs]] `fs`:: (object) Contains file store statistics for the node. + .Properties of `fs` [%collapsible%open] ====== `timestamp`:: (integer) Last time the file stores statistics were refreshed. Recorded in milliseconds since the {wikipedia}/Unix_time[Unix Epoch]. `total`:: (object) Contains statistics for all file stores of the node. + .Properties of `total` [%collapsible%open] ======= `total`:: (<>) Total size of all file stores. `total_in_bytes`:: (integer) Total size (in bytes) of all file stores. `free`:: (<>) Total unallocated disk space in all file stores. `free_in_bytes`:: (integer) Total number of unallocated bytes in all file stores. `available`:: (<>) Total disk space available to this Java virtual machine on all file stores. Depending on OS or process level restrictions, this might appear less than `free`. This is the actual amount of free disk space the {es} node can utilise. `available_in_bytes`:: (integer) Total number of bytes available to this Java virtual machine on all file stores. Depending on OS or process level restrictions, this might appear less than `free_in_bytes`. This is the actual amount of free disk space the {es} node can utilise. ======= `least_usage_estimate`:: (object) Contains statistics for the file store with the least estimated usage. See <> for a list of child parameters. `most_usage_estimate`:: (object) Contains statistics for the file store with the most estimated usage. See <> for a list of child parameters. [[cluster-nodes-stats-fs-data]] `data`:: (array of objects) List of all file stores. + .Properties of `data` [%collapsible%open] ======= `path`:: (string) Path to the file store. `mount`:: (string) Mount point of the file store (ex: /dev/sda2). + NOTE: This parameter is not provided for the `least_usage_estimate` or `most_usage_estimate` file stores. `type`:: (string) Type of the file store (ex: ext4). `total`:: (<>) Total size of the file store. `total_in_bytes`:: (integer) Total size (in bytes) of the file store. `free`:: (<>) Total amount of unallocated disk space in the file store. `free_in_bytes`:: (integer) Total number of unallocated bytes in the file store. `available`:: (<>) Total amount of disk space available to this Java virtual machine on this file store. `available_in_bytes`:: (integer) Total number of bytes available to this Java virtual machine on this file store. ======= `io_stats` (Linux only):: (objects) Contains I/O statistics for the node. + .Properties of `io_stats` [%collapsible%open] ======= `devices` (Linux only):: (array) Array of disk metrics for each device that is backing an {es} data path. These disk metrics are probed periodically and averages between the last probe and the current probe are computed. + .Properties of `devices` [%collapsible%open] ======== `device_name` (Linux only):: (string) The Linux device name. `operations` (Linux only):: (integer) The total number of read and write operations for the device completed since starting {es}. `read_operations` (Linux only):: (integer) The total number of read operations for the device completed since starting {es}. `write_operations` (Linux only):: (integer) The total number of write operations for the device completed since starting {es}. `read_kilobytes` (Linux only):: (integer) The total number of kilobytes read for the device since starting {es}. `write_kilobytes` (Linux only):: (integer) The total number of kilobytes written for the device since starting {es}. ======== `operations` (Linux only):: (integer) The total number of read and write operations across all devices used by {es} completed since starting {es}. `read_operations` (Linux only):: (integer) The total number of read operations for across all devices used by {es} completed since starting {es}. `write_operations` (Linux only):: (integer) The total number of write operations across all devices used by {es} completed since starting {es}. `read_kilobytes` (Linux only):: (integer) The total number of kilobytes read across all devices used by {es} since starting {es}. `write_kilobytes` (Linux only):: (integer) The total number of kilobytes written across all devices used by {es} since starting {es}. ======= ====== [[cluster-nodes-stats-api-response-body-transport]] `transport`:: (object) Contains transport statistics for the node. + .Properties of `transport` [%collapsible%open] ====== `server_open`:: (integer) Number of open TCP connections used for internal communication between nodes. `rx_count`:: (integer) Total number of RX (receive) packets received by the node during internal cluster communication. `rx_size`:: (<>) Size of RX packets received by the node during internal cluster communication. `rx_size_in_bytes`:: (integer) Size, in bytes, of RX packets received by the node during internal cluster communication. `tx_count`:: (integer) Total number of TX (transmit) packets sent by the node during internal cluster communication. `tx_size`:: (<>) Size of TX packets sent by the node during internal cluster communication. `tx_size_in_bytes`:: (integer) Size, in bytes, of TX packets sent by the node during internal cluster communication. ====== [[cluster-nodes-stats-api-response-body-http]] `http`:: (object) Contains http statistics for the node. + .Properties of `http` [%collapsible%open] ====== `current_open`:: (integer) Current number of open HTTP connections for the node. `total_opened`:: (integer) Total number of HTTP connections opened for the node. ====== [[cluster-nodes-stats-api-response-body-breakers]] `breakers`:: (object) Contains circuit breaker statistics for the node. + .Properties of `breakers` [%collapsible%open] ====== ``:: (object) Contains statistics for the circuit breaker. + .Properties of `` [%collapsible%open] ======= `limit_size_in_bytes`:: (integer) Memory limit, in bytes, for the circuit breaker. `limit_size`:: (<>) Memory limit for the circuit breaker. `estimated_size_in_bytes`:: (integer) Estimated memory used, in bytes, for the operation. `estimated_size`:: (<>) Estimated memory used for the operation. `overhead`:: (float) A constant that all estimates for the circuit breaker are multiplied with to calculate a final estimate. `tripped`:: (integer) Total number of times the circuit breaker has been triggered and prevented an out of memory error. ======= ====== [[cluster-nodes-stats-api-response-body-script]] `script`:: (object) Contains script statistics for the node. + .Properties of `script` [%collapsible%open] ====== `compilations`:: (integer) Total number of inline script compilations performed by the node. `cache_evictions`:: (integer) Total number of times the script cache has evicted old data. `compilation_limit_triggered`:: (integer) Total number of times the <> circuit breaker has limited inline script compilations. ====== [[cluster-nodes-stats-api-response-body-discovery]] `discovery`:: (object) Contains node discovery statistics for the node. + .Properties of `discovery` [%collapsible%open] ====== `cluster_state_queue`:: (object) Contains statistics for the cluster state queue of the node. + .Properties of `cluster_state_queue` [%collapsible%open] ======= `total`:: (integer) Total number of cluster states in queue. `pending`:: (integer) Number of pending cluster states in queue. `committed`:: (integer) Number of committed cluster states in queue. ======= `published_cluster_states`:: (object) Contains statistics for the published cluster states of the node. + .Properties of `published_cluster_states` [%collapsible%open] ======= `full_states`:: (integer) Number of published cluster states. `incompatible_diffs`:: (integer) Number of incompatible differences between published cluster states. `compatible_diffs`:: (integer) Number of compatible differences between published cluster states. ======= ====== [[cluster-nodes-stats-api-response-body-ingest]] `ingest`:: (object) Contains ingest statistics for the node. + .Properties of `ingest` [%collapsible%open] ====== `total`:: (object) Contains statistics about ingest operations for the node. + .Properties of `total` [%collapsible%open] ======= `count`:: (integer) Total number of documents ingested during the lifetime of this node. `time`:: (<>) Total time spent preprocessing ingest documents during the lifetime of this node. `time_in_millis`:: (integer) Total time, in milliseconds, spent preprocessing ingest documents during the lifetime of this node. `current`:: (integer) Total number of documents currently being ingested. `failed`:: (integer) Total number of failed ingest operations during the lifetime of this node. ======= `pipelines`:: (object) Contains statistics about ingest pipelines for the node. + .Properties of `pipelines` [%collapsible%open] ======= ``:: (object) Contains statistics about the ingest pipeline. + .Properties of `` [%collapsible%open] ======== `count`:: (integer) Number of documents preprocessed by the ingest pipeline. `time`:: (<>) Total time spent preprocessing documents in the ingest pipeline. `time_in_millis`:: (integer) Total time, in milliseconds, spent preprocessing documents in the ingest pipeline. `failed`:: (integer) Total number of failed operations for the ingest pipeline. `processors`:: (array of objects) Contains statistics for the ingest processors for the ingest pipeline. + .Properties of `processors` [%collapsible%open] ========= ``:: (object) Contains statistics for the ingest processor. + .Properties of `` [%collapsible%open] ========== `count`:: (integer) Number of documents transformed by the processor. `time`:: (<>) Time spent by the processor transforming documents. `time_in_millis`:: (integer) Time, in milliseconds, spent by the processor transforming documents. `current`:: (integer) Number of documents currently being transformed by the processor. `failed`:: (integer) Number of failed operations for the processor. ========== ========= ======== ======= ====== [[cluster-nodes-stats-api-response-body-indexing-pressure]] `indexing_pressure`:: (object) Contains <> statistics for the node. + .Properties of `indexing_pressure` [%collapsible%open] ====== `memory`:: (object) Contains statistics for memory consumption from indexing load. + .Properties of `` [%collapsible%open] ======= `current`:: (object) Contains statistics for current indexing load. + .Properties of `` [%collapsible%open] ======== `combined_coordinating_and_primary`:: (<>) Memory consumed by indexing requests in the coordinating or primary stage. This value is not the sum of coordinating and primary as a node can reuse the coordinating memory if the primary stage is executed locally. `combined_coordinating_and_primary_in_bytes`:: (integer) Memory consumed, in bytes, by indexing requests in the coordinating or primary stage. This value is not the sum of coordinating and primary as a node can reuse the coordinating memory if the primary stage is executed locally. `coordinating`:: (<>) Memory consumed by indexing requests in the coordinating stage. `coordinating_in_bytes`:: (integer) Memory consumed, in bytes, by indexing requests in the coordinating stage. `primary`:: (<>) Memory consumed by indexing requests in the primary stage. `primary_in_bytes`:: (integer) Memory consumed, in bytes, by indexing requests in the primary stage. `replica`:: (<>) Memory consumed by indexing requests in the replica stage. `replica_in_bytes`:: (integer) Memory consumed, in bytes, by indexing requests in the replica stage. `all`:: (<>) Memory consumed by indexing requests in the coordinating, primary, or replica stage. `all_in_bytes`:: (integer) Memory consumed, in bytes, by indexing requests in the coordinating, primary, or replica stage. ======== `total`:: (object) Contains statistics for the cumulative indexing load since the node started. + .Properties of `` [%collapsible%open] ======== `combined_coordinating_and_primary`:: (<>) Memory consumed by indexing requests in the coordinating or primary stage. This value is not the sum of coordinating and primary as a node can reuse the coordinating memory if the primary stage is executed locally. `combined_coordinating_and_primary_in_bytes`:: (integer) Memory consumed, in bytes, by indexing requests in the coordinating or primary stage. This value is not the sum of coordinating and primary as a node can reuse the coordinating memory if the primary stage is executed locally. `coordinating`:: (<>) Memory consumed by indexing requests in the coordinating stage. `coordinating_in_bytes`:: (integer) Memory consumed, in bytes, by indexing requests in the coordinating stage. `primary`:: (<>) Memory consumed by indexing requests in the primary stage. `primary_in_bytes`:: (integer) Memory consumed, in bytes, by indexing requests in the primary stage. `replica`:: (<>) Memory consumed by indexing requests in the replica stage. `replica_in_bytes`:: (integer) Memory consumed, in bytes, by indexing requests in the replica stage. `all`:: (<>) Memory consumed by indexing requests in the coordinating, primary, or replica stage. `all_in_bytes`:: (integer) Memory consumed, in bytes, by indexing requests in the coordinating, primary, or replica stage. `coordinating_rejections`:: (integer) Number of indexing requests rejected in the coordinating stage. `primary_rejections`:: (integer) Number of indexing requests rejected in the primary stage. `replica_rejections`:: (integer) Number of indexing requests rejected in the replica stage. ======== ======= ====== [[cluster-nodes-stats-api-response-body-adaptive-selection]] `adaptive_selection`:: (object) Contains adaptive selection statistics for the node. + .Properties of `adaptive_selection` [%collapsible%open] ====== `outgoing_searches`:: (integer) The number of outstanding search requests from the node these stats are for to the keyed node. `avg_queue_size`:: (integer) The exponentially weighted moving average queue size of search requests on the keyed node. `avg_service_time`:: (<>) The exponentially weighted moving average service time of search requests on the keyed node. `avg_service_time_ns`:: (integer) The exponentially weighted moving average service time, in nanoseconds, of search requests on the keyed node. `avg_response_time`:: (<>) The exponentially weighted moving average response time of search requests on the keyed node. `avg_response_time_ns`:: (integer) The exponentially weighted moving average response time, in nanoseconds, of search requests on the keyed node. `rank`:: (string) The rank of this node; used for shard selection when routing search requests. ====== ===== ==== [[cluster-nodes-stats-api-example]] ==== {api-examples-title} [source,console] -------------------------------------------------- # return just indices GET /_nodes/stats/indices # return just os and process GET /_nodes/stats/os,process # return just process for node with IP address 10.0.0.1 GET /_nodes/10.0.0.1/stats/process -------------------------------------------------- All stats can be explicitly requested via `/_nodes/stats/_all` or `/_nodes/stats?metric=_all`. You can get information about indices stats on `node`, `indices`, or `shards` level. [source,console] -------------------------------------------------- # Fielddata summarized by node GET /_nodes/stats/indices/fielddata?fields=field1,field2 # Fielddata summarized by node and index GET /_nodes/stats/indices/fielddata?level=indices&fields=field1,field2 # Fielddata summarized by node, index, and shard GET /_nodes/stats/indices/fielddata?level=shards&fields=field1,field2 # You can use wildcards for field names GET /_nodes/stats/indices/fielddata?fields=field* -------------------------------------------------- You can get statistics about search groups for searches executed on this node. [source,console] -------------------------------------------------- # All groups with all stats GET /_nodes/stats?groups=_all # Some groups from just the indices stats GET /_nodes/stats/indices?groups=foo,bar -------------------------------------------------- [[cluster-nodes-stats-ingest-ex]] ===== Retrieve ingest statistics only To return only ingest-related node statistics, set the `` path parameter to `ingest` and use the <> query parameter. [source,console] -------------------------------------------------- GET /_nodes/stats/ingest?filter_path=nodes.*.ingest -------------------------------------------------- You can use the `metric` and `filter_path` query parameters to get the same response. [source,console] -------------------------------------------------- GET /_nodes/stats?metric=ingest&filter_path=nodes.*.ingest -------------------------------------------------- To further refine the response, change the `filter_path` value. For example, the following request only returns ingest pipeline statistics. [source,console] -------------------------------------------------- GET /_nodes/stats?metric=ingest&filter_path=nodes.*.ingest.pipelines -------------------------------------------------- ",12239,True,2561.3644551179395,median " CLASS unit_tests DEFINITION FOR TESTING FINAL DURATION SHORT RISK LEVEL HARMLESS . *? *? *? *?unit_Tests *? *?f_Cut *? *?ZZZCL_DATETIME *? *? *? *? *? *? *? *? *? PRIVATE SECTION. METHODS: method_chaining FOR TESTING. METHODS: add FOR TESTING. METHODS: add_days FOR TESTING. METHODS: add_hours FOR TESTING. METHODS: add_minutes FOR TESTING. METHODS: add_months FOR TESTING. METHODS: add_seconds FOR TESTING. METHODS: add_weeks FOR TESTING. METHODS: add_years FOR TESTING. METHODS: as_date FOR TESTING. METHODS: as_iso_timestamp FOR TESTING. METHODS: as_long_timestamp FOR TESTING. METHODS: as_timestamp FOR TESTING. METHODS: begin_of_day FOR TESTING. METHODS: begin_of_month FOR TESTING. METHODS: begin_of_quarter FOR TESTING. METHODS: begin_of_week FOR TESTING. METHODS: begin_of_year FOR TESTING. METHODS: clone FOR TESTING. METHODS: day_of_week FOR TESTING. METHODS: end_of_day FOR TESTING. METHODS: end_of_month FOR TESTING. METHODS: end_of_quarter FOR TESTING. METHODS: end_of_week FOR TESTING. METHODS: end_of_year FOR TESTING. METHODS: from_date FOR TESTING. METHODS: from_iso_timestamp FOR TESTING. METHODS: from_now FOR TESTING. METHODS: from_today FOR TESTING. METHODS: get_dayname FOR TESTING. METHODS: get_day_of_week FOR TESTING. METHODS: get_day_of_year FOR TESTING. METHODS: get_ultimo FOR TESTING. METHODS: get_number_of_days_of_month FOR TESTING. METHODS: get_number_of_days_of_year FOR TESTING. METHODS: is_last_day_of_month FOR TESTING. METHODS: set FOR TESTING. METHODS: subtract FOR TESTING. METHODS: get_quarter FOR TESTING. METHODS: get_iso_week FOR TESTING. METHODS: is_leap_year FOR TESTING. METHODS: is_before FOR TESTING. METHODS: is_before_or_equal FOR TESTING. METHODS: is_after FOR TESTING. METHODS: is_after_or_equal FOR TESTING. METHODS: is_equal FOR TESTING. METHODS: create_list FOR TESTING. METHODS: sub_days FOR TESTING. METHODS: sub_hours FOR TESTING. METHODS: sub_minutes FOR TESTING. METHODS: sub_months FOR TESTING. METHODS: sub_seconds FOR TESTING. METHODS: sub_weeks FOR TESTING. METHODS: sub_years FOR TESTING. METHODS: diff FOR TESTING. ENDCLASS. ""unit_Tests CLASS unit_tests IMPLEMENTATION. METHOD method_chaining. DATA(o_datetime) = zcl_datetime=>from_date( '20210307' ). o_datetime->add_days( 3 )->add_hours( 12 )->add_minutes( 30 )->add_seconds( 45 )->add_weeks( 2 )->add_months( 3 )->add_years( 3 ). DATA(ts) = o_datetime->as_timestamp( ). cl_aunit_assert=>assert_equals( act = ts exp = '20240624123045' msg = 'Method chaining check #01' ). o_datetime->add_days( -3 )->add_hours( -12 )->add_minutes( -30 )->add_seconds( -45 )->add_weeks( -2 )->add_months( -3 )->add_years( -3 ). ts = o_datetime->as_timestamp( ). cl_aunit_assert=>assert_equals( act = ts exp = '20210307000000' msg = 'Method chaining check #02' ). ENDMETHOD. METHOD add. "" ISO Timestamp im Format 2021-01-01T01:01:01+01:00 DATA(o_datetime) = zcl_datetime=>from_date( '20210307' ). o_datetime->add( iv_field = zcl_datetime=>c_fields-day iv_value = 3 ). DATA(ts) = o_datetime->as_timestamp( ). cl_aunit_assert=>assert_equals( act = ts exp = '20210310000000' msg = 'Datum +3 Tage fehlerhaft' ). o_datetime->add( iv_field = zcl_datetime=>c_fields-day iv_value = -5 ). o_datetime->add( iv_field = zcl_datetime=>c_fields-hour iv_value = -3 ). ts = o_datetime->as_timestamp( ). cl_aunit_assert=>assert_equals( act = ts exp = '20210304210000' msg = 'Datum -5 Tage - 3 Stunden fehlerhaft' ). o_datetime->add( iv_field = zcl_datetime=>c_fields-week iv_value = 1 ). o_datetime->add( iv_field = zcl_datetime=>c_fields-hour iv_value = 3 ). ts = o_datetime->as_timestamp( ). cl_aunit_assert=>assert_equals( act = ts exp = '20210312000000' msg = 'Datum +1 Woche +3 Stunden fehlerhaft' ). o_datetime = zcl_datetime=>from_date( iv_date = '20210228' iv_time = zcl_datetime=>c_times-end_of_day ). o_datetime->add( iv_field = zcl_datetime=>c_fields-second iv_value = 1 ). ts = o_datetime->as_timestamp( ). cl_aunit_assert=>assert_equals( act = ts exp = '20210301000000' msg = 'Datum +1 Sekunde fehlerhaft' ). ENDMETHOD. METHOD add_days. DATA(o_datetime) = zcl_datetime=>from_date( '20210307' ). o_datetime->add_days( 5 ). DATA(ts) = o_datetime->as_timestamp( ). cl_aunit_assert=>assert_equals( act = ts exp = '20210312000000' msg = 'Datum +5 Tage fehlerhaft' ). o_datetime->add_days( -12 ). ts = o_datetime->as_timestamp( ). cl_aunit_assert=>assert_equals( act = ts exp = '20210228000000' msg = 'Datum -12 Tage fehlerhaft' ). ENDMETHOD. METHOD add_hours. DATA(o_datetime) = zcl_datetime=>from_date( iv_date = '20210307' iv_time = '060000' ). o_datetime->add_hours( 8 ). DATA(ts) = o_datetime->as_timestamp( ). cl_aunit_assert=>assert_equals( act = ts exp = '20210307140000' msg = 'Add hours check #01' ). o_datetime->add_hours( 16 ). ts = o_datetime->as_timestamp( ). cl_aunit_assert=>assert_equals( act = ts exp = '20210308060000' msg = 'Add hours check #02' ). o_datetime->add_hours( -24 ). ts = o_datetime->as_timestamp( ). cl_aunit_assert=>assert_equals( act = ts exp = '20210307060000' msg = 'Add hours check #03' ). ENDMETHOD. METHOD add_minutes. DATA(o_datetime) = zcl_datetime=>from_date( iv_date = '20210307' iv_time = '060000' ). o_datetime->add_minutes( 8 ). DATA(ts) = o_datetime->as_timestamp( ). cl_aunit_assert=>assert_equals( act = ts exp = '20210307060800' msg = 'Add minutes check #01' ). o_datetime->add_minutes( 52 ). ts = o_datetime->as_timestamp( ). cl_aunit_assert=>assert_equals( act = ts exp = '20210307070000' msg = 'Add minutes check #02' ). o_datetime->add_minutes( 60 * 24 * 2 ). ts = o_datetime->as_timestamp( ). cl_aunit_assert=>assert_equals( act = ts exp = '20210309070000' msg = 'Add minutes check #03' ). o_datetime->add_minutes( -1 * ( 60 * 24 * 3 ) ). o_datetime->add_minutes( -60 ). ts = o_datetime->as_timestamp( ). cl_aunit_assert=>assert_equals( act = ts exp = '20210306060000' msg = 'Add minutes check #04' ). ENDMETHOD. METHOD add_months. DATA(o_datetime) = zcl_datetime=>from_date( '20210131' ). DATA(date) = o_datetime->add_months( 1 )->as_date( ). cl_aunit_assert=>assert_equals( act = date exp = '20210228' msg = 'Add month check #01' ). date = o_datetime->add_months( 36 )->as_date( ). cl_aunit_assert=>assert_equals( act = date exp = '20240228' msg = 'Add month check #02' ). ENDMETHOD. METHOD add_seconds. DATA(o_datetime) = zcl_datetime=>from_date( iv_date = '20210307' iv_time = '060000' ). o_datetime->add_seconds( 8 ). DATA(ts) = o_datetime->as_timestamp( ). cl_aunit_assert=>assert_equals( act = ts exp = '20210307060008' msg = 'Add seconds check #01' ). o_datetime->add_seconds( 52 ). ts = o_datetime->as_timestamp( ). cl_aunit_assert=>assert_equals( act = ts exp = '20210307060100' msg = 'Add seconds check #02' ). o_datetime->add_seconds( 60 * 60 * 24 ). ts = o_datetime->as_timestamp( ). cl_aunit_assert=>assert_equals( act = ts exp = '20210308060100' msg = 'Add seconds check #03' ). o_datetime->add_seconds( -600 ). ts = o_datetime->as_timestamp( ). cl_aunit_assert=>assert_equals( act = ts exp = '20210308055100' msg = 'Add seconds check #04' ). ENDMETHOD. METHOD add_weeks. DATA(o_datetime) = zcl_datetime=>from_date( iv_date = '20210307' ). o_datetime->add_weeks( 1 ). DATA(date) = o_datetime->as_date( ). cl_aunit_assert=>assert_equals( act = date exp = '20210314' msg = 'Add weeks check #01' ). o_datetime->add_weeks( -2 ). date = o_datetime->as_date( ). cl_aunit_assert=>assert_equals( act = date exp = '20210228' msg = 'Add weeks check #02' ). ENDMETHOD. METHOD add_years. DATA(o_datetime) = zcl_datetime=>from_date( iv_date = '20210307' ). o_datetime->add_years( 1 ). DATA(date) = o_datetime->as_date( ). cl_aunit_assert=>assert_equals( act = date exp = '20220307' msg = 'Add years check #01' ). o_datetime->add_years( -2 ). date = o_datetime->as_date( ). cl_aunit_assert=>assert_equals( act = date exp = '20200307' msg = 'Add years check #02' ). ENDMETHOD. METHOD as_date. DATA(o_datetime) = zcl_datetime=>from_date( iv_date = '20210307' ). DATA(date) = o_datetime->as_date( ). cl_aunit_assert=>assert_equals( act = date exp = '20210307' msg = 'As date check #01' ). o_datetime = zcl_datetime=>from_date( iv_date = '20210331' ). date = o_datetime->as_date( ). cl_aunit_assert=>assert_equals( act = date exp = '20210331' msg = 'As date check #02' ). o_datetime = zcl_datetime=>from_date( iv_date = '20210401' ). date = o_datetime->as_date( ). cl_aunit_assert=>assert_equals( act = date exp = '20210401' msg = 'As date check #02' ). ENDMETHOD. METHOD as_iso_timestamp. DATA(o_datetime) = zcl_datetime=>from_timestamp( '20210307093045' ). DATA(iso_timestamp) = o_datetime->as_iso_timestamp( ). cl_aunit_assert=>assert_equals( act = iso_timestamp exp = '2021-03-07T09:30:45Z' msg = 'As ISO timestamp check #01' ). ENDMETHOD. METHOD as_long_timestamp. DATA(o_datetime) = zcl_datetime=>from_timestamp( '20210307093045' ). DATA(long_timestamp) = o_datetime->as_long_timestamp( ). cl_aunit_assert=>assert_equals( act = long_timestamp exp = '20210307093045.0000000' msg = 'As date check #01' ). ENDMETHOD. METHOD as_timestamp. DATA(o_datetime) = zcl_datetime=>from_timestamp( '20210307093045' ). DATA(long_timestamp) = o_datetime->as_long_timestamp( ). cl_aunit_assert=>assert_equals( act = long_timestamp exp = '20210307093045' msg = 'As date check #02' ). ENDMETHOD. METHOD begin_of_day. DATA(o_datetime) = zcl_datetime=>from_date( iv_date = '20210307' iv_time = '235959' ). o_datetime->begin_of_day( ). DATA(ts) = o_datetime->as_timestamp( ). cl_aunit_assert=>assert_equals( act = ts exp = '20210307000000' msg = 'Begin of day check #01' ). ENDMETHOD. METHOD begin_of_month. DATA(o_datetime) = zcl_datetime=>from_date( '20210307' ). o_datetime->begin_of_month( ). DATA(ts) = o_datetime->as_timestamp( ). cl_aunit_assert=>assert_equals( act = ts exp = '20210301000000' msg = 'Begin of month check #01' ). ENDMETHOD. METHOD begin_of_quarter. DATA(o_datetime) = zcl_datetime=>from_date( '20210307' ). o_datetime->begin_of_quarter( ). DATA(ts) = o_datetime->as_timestamp( ). cl_aunit_assert=>assert_equals( act = ts exp = '20210101000000' msg = 'Begin of quarter check #01' ). ENDMETHOD. METHOD begin_of_week. DATA(o_datetime) = zcl_datetime=>from_date( '20210101' ). DATA(date) = o_datetime->begin_of_week( )->as_date( ). cl_aunit_assert=>assert_equals( act = date exp = '20201228' msg = 'Begin of week check #01' ). ENDMETHOD. METHOD begin_of_year. DATA(o_datetime) = zcl_datetime=>from_date( '20210307' ). o_datetime->begin_of_quarter( ). DATA(ts) = o_datetime->as_timestamp( ). cl_aunit_assert=>assert_equals( act = ts exp = '20210101000000' msg = 'Begin of year check #01' ). ENDMETHOD. METHOD clone. DATA(o_this_datetime) = zcl_datetime=>from_now( ). DATA(o_other_datetime) = o_this_datetime->clone( ). IF o_this_datetime = o_other_datetime. cl_aunit_assert=>fail( 'Clone check #01' ). ENDIF. IF NOT o_this_datetime->is_equal( o_other_datetime ). cl_aunit_assert=>fail( 'Clone check #02' ). ENDIF. ENDMETHOD. METHOD day_of_week. DATA(o_datetime) = zcl_datetime=>from_date( '20210307' ). "" Sunday o_datetime->day_of_week( zcl_datetime=>c_day_of_week-wednesday ). DATA(ts) = o_datetime->as_timestamp( ). cl_aunit_assert=>assert_equals( act = ts exp = '20210303000000' msg = 'Day of week check #01' ). o_datetime->day_of_week( zcl_datetime=>c_day_of_week-monday ). ts = o_datetime->as_timestamp( ). cl_aunit_assert=>assert_equals( act = ts exp = '20210301000000' msg = 'Day of week check #02' ). ENDMETHOD. METHOD end_of_day. DATA(o_datetime) = zcl_datetime=>from_date( iv_date = '20210307' iv_time = '120000' ). o_datetime->end_of_day( ). DATA(ts) = o_datetime->as_timestamp( ). cl_aunit_assert=>assert_equals( act = ts exp = '20210307235959' msg = 'End of day check #01' ). ENDMETHOD. METHOD end_of_month. DATA(o_datetime) = zcl_datetime=>from_date( '20200205' ). DATA(ts) = o_datetime->end_of_month( )->as_timestamp( ). cl_aunit_assert=>assert_equals( act = ts exp = '20200229000000' msg = 'End of month check #01' ). o_datetime = zcl_datetime=>from_date( '20210205' ). ts = o_datetime->end_of_month( )->as_timestamp( ). cl_aunit_assert=>assert_equals( act = ts exp = '20210228000000' msg = 'End of month check #02' ). ENDMETHOD. METHOD end_of_quarter. DATA(o_datetime) = zcl_datetime=>from_date( '20210307' ). "" Sunday o_datetime->end_of_quarter( ). DATA(ts) = o_datetime->as_timestamp( ). cl_aunit_assert=>assert_equals( act = ts exp = '20210331000000' msg = 'End of quarter check #01' ). o_datetime->add_days( 1 )->end_of_quarter( ). ts = o_datetime->as_timestamp( ). cl_aunit_assert=>assert_equals( act = ts exp = '20210630000000' msg = 'End of quarter check #02' ). o_datetime->add_days( 1 )->end_of_quarter( ). ts = o_datetime->as_timestamp( ). cl_aunit_assert=>assert_equals( act = ts exp = '20210930000000' msg = 'End of quarter check #03' ). o_datetime->add_days( 1 )->end_of_quarter( ). ts = o_datetime->as_timestamp( ). cl_aunit_assert=>assert_equals( act = ts exp = '20211231000000' msg = 'End of quarter check #04' ). ENDMETHOD. METHOD end_of_week. DATA(o_datetime) = zcl_datetime=>from_date( '20210101' ). DATA(date) = o_datetime->end_of_week( )->as_date( ). cl_aunit_assert=>assert_equals( act = date exp = '20210103' msg = 'End of week check #01' ). o_datetime = zcl_datetime=>from_date( '20210301' ). date = o_datetime->end_of_week( )->as_date( ). cl_aunit_assert=>assert_equals( act = date exp = '20210307' msg = 'End of week check #02' ). ENDMETHOD. METHOD end_of_year. DATA(o_datetime) = zcl_datetime=>from_date( '20210101' ). DATA(date) = o_datetime->end_of_year( )->as_date( ). cl_aunit_assert=>assert_equals( act = date exp = '20211231' msg = 'End of year check #01' ). ENDMETHOD. METHOD from_date. DATA(o_datetime) = zcl_datetime=>from_date( '20210101' ). DATA(date) = o_datetime->as_date( ). cl_aunit_assert=>assert_equals( act = date exp = '20210101' msg = 'From date check #01' ). TRY. o_datetime = zcl_datetime=>from_date( '20210229' ). "" 2021 is a none leap year...29th of february is not a valid date. cl_aunit_assert=>fail( msg = 'From date check #02' ). CATCH cx_parameter_invalid_range ##NO_HANDLER. "" Everything is fine. We had expected an exception. ENDTRY. TRY. o_datetime = zcl_datetime=>from_date( '20200229' ). "" 2021 is a leap year...29th of february is a valid date. CATCH cx_parameter_invalid_range ##NO_HANDLER. cl_aunit_assert=>fail( msg = 'From date check #03' ). "" Everything is fine. We had expected an exception. ENDTRY. TRY. o_datetime = zcl_datetime=>from_date( iv_date = '20200229' iv_time = '243030' ). cl_aunit_assert=>fail( msg = 'From date check #04' ). CATCH cx_parameter_invalid_range ##NO_HANDLER. "" Everything is fine. We had expected an exception. ENDTRY. TRY. o_datetime = zcl_datetime=>from_date( iv_date = '20200229' iv_time = '000000' ). CATCH cx_parameter_invalid_range ##NO_HANDLER. cl_aunit_assert=>fail( msg = 'From date check #05' ). ENDTRY. ENDMETHOD. METHOD from_iso_timestamp. DATA(o_datetime) = zcl_datetime=>from_iso_timestamp( '2020-04-21T18:09:25Z' ). DATA(ts) = o_datetime->as_timestamp( ). cl_aunit_assert=>assert_equals( act = ts exp = '20200421180925' msg = 'From iso timestamp check #01' ). TRY. o_datetime = zcl_datetime=>from_iso_timestamp( '2020-04-21T28:09:25Z' ). "" 28:09:25 is not a valid time... cl_aunit_assert=>fail( msg = 'From iso timestamp check #02' ). CATCH cx_xlf_illegal_argument ##NO_HANDLER. "" Everything is fine. We had expected an exception. ENDTRY. ENDMETHOD. METHOD from_now. DATA(current_date) = sy-datum. DATA(current_time) = sy-uzeit. DATA(o_datetime) = zcl_datetime=>from_now( ). DATA(ts) = o_datetime->as_timestamp( ). DATA(o_dt_reference) = zcl_datetime=>from_timestamp( CONV timestamp( |{ current_date }{ current_time }| ) ). DATA(delta) = abs( o_datetime->diff( iv_field = zcl_datetime=>c_fields-second io_datetime = o_dt_reference ) ). "" Max delta of one second is okay. Be aware that this test fails in debugger "" if you arent fast enough... IF delta > 1. cl_aunit_assert=>fail( msg = 'From now check #01' ). ENDIF. ENDMETHOD. METHOD from_today. DATA(current_date) = sy-datum. DATA(o_datetime) = zcl_datetime=>from_today( ). DATA(date) = o_datetime->as_date( ). IF date NE current_date. cl_aunit_assert=>fail( msg = 'From today check #01' ). ENDIF. ENDMETHOD. METHOD get_dayname. ##TODO. ENDMETHOD. METHOD get_day_of_week. DATA(o_datetime) = zcl_datetime=>from_date( '20210101' ). "" We step throug next 7 day and check the expected day of week. "" Checks are done relative to given date 1st January of 2021 DATA(day_of_week) = o_datetime->get_day_of_week( ). cl_aunit_assert=>assert_equals( act = day_of_week exp = zcl_datetime=>c_day_of_week-friday msg = 'Day of week check #01' ). o_datetime->add_days( 1 ). day_of_week = o_datetime->get_day_of_week( ). cl_aunit_assert=>assert_equals( act = day_of_week exp = zcl_datetime=>c_day_of_week-saturday msg = 'Day of week check #02' ). o_datetime->add_days( 1 ). day_of_week = o_datetime->get_day_of_week( ). cl_aunit_assert=>assert_equals( act = day_of_week exp = zcl_datetime=>c_day_of_week-sunday msg = 'Day of week check #03' ). o_datetime->add_days( 1 ). day_of_week = o_datetime->get_day_of_week( ). cl_aunit_assert=>assert_equals( act = day_of_week exp = zcl_datetime=>c_day_of_week-monday msg = 'Day of week check #04' ). o_datetime->add_days( 1 ). day_of_week = o_datetime->get_day_of_week( ). cl_aunit_assert=>assert_equals( act = day_of_week exp = zcl_datetime=>c_day_of_week-tuesday msg = 'Day of week check #05' ). o_datetime->add_days( 1 ). day_of_week = o_datetime->get_day_of_week( ). cl_aunit_assert=>assert_equals( act = day_of_week exp = zcl_datetime=>c_day_of_week-wednesday msg = 'Day of week check #06' ). o_datetime->add_days( 1 ). day_of_week = o_datetime->get_day_of_week( ). cl_aunit_assert=>assert_equals( act = day_of_week exp = zcl_datetime=>c_day_of_week-thursday msg = 'Day of week check #07' ). o_datetime->add_days( 1 ). day_of_week = o_datetime->get_day_of_week( ). cl_aunit_assert=>assert_equals( act = day_of_week exp = zcl_datetime=>c_day_of_week-friday msg = 'Day of week check #08' ). o_datetime = zcl_datetime=>from_date( '20211231' ). day_of_week = o_datetime->get_day_of_week( ). cl_aunit_assert=>assert_equals( act = day_of_week exp = zcl_datetime=>c_day_of_week-friday msg = 'Day of week check #09' ). ENDMETHOD. METHOD get_ultimo. DATA(o_datetime) = zcl_datetime=>from_date( '20210101' ). DATA(ultimo) = o_datetime->get_ultimo( ). cl_aunit_assert=>assert_equals( act = ultimo exp = '20210131' msg = 'Get last day of month check #01' ). ultimo = o_datetime->add_months( 1 )->get_ultimo( ). cl_aunit_assert=>assert_equals( act = ultimo exp = '20210228' msg = 'Get last day of month check #02' ). ultimo = o_datetime->add_years( -1 )->get_ultimo( ). "" 2020 was a leap year... cl_aunit_assert=>assert_equals( act = ultimo exp = '20200229' msg = 'Get last day of month check #03' ). ENDMETHOD. METHOD get_number_of_days_of_month. "" The result is calculated in the same way. me->get_ultimo( ). ENDMETHOD. METHOD get_number_of_days_of_year. DATA(o_datetime) = zcl_datetime=>from_date( '20210101' ). DATA(number_of_days_of_year) = o_datetime->get_number_of_days_of_year( ). cl_aunit_assert=>assert_equals( act = number_of_days_of_year exp = zcl_datetime=>c_day_of_year-max_days_in_none_leap_year msg = 'Get number of days of year check #01' ). number_of_days_of_year = o_datetime->add_years( -1 )->get_number_of_days_of_year( ). cl_aunit_assert=>assert_equals( act = number_of_days_of_year exp = zcl_datetime=>c_day_of_year-max_days_in_leap_year msg = 'Get number of days of year check #02' ). ENDMETHOD. METHOD is_last_day_of_month. DATA(o_datetime) = zcl_datetime=>from_date( '20210131' ). DATA(fl_last_day_of_month) = o_datetime->is_last_day_of_month( ). cl_aunit_assert=>assert_equals( act = fl_last_day_of_month exp = abap_true msg = 'Is last day of month check #01' ). fl_last_day_of_month = o_datetime->add_days( 1 )->is_last_day_of_month( ). cl_aunit_assert=>assert_equals( act = fl_last_day_of_month exp = abap_false msg = 'Is last day of month check #02' ). ENDMETHOD. METHOD set. DATA(o_datetime) = zcl_datetime=>from_date( '20210131' ). o_datetime->set( iv_field = zcl_datetime=>c_fields-year iv_value = 2020 ). o_datetime->set( iv_field = zcl_datetime=>c_fields-month iv_value = 3 ). o_datetime->set( iv_field = zcl_datetime=>c_fields-day iv_value = 1 ). o_datetime->set( iv_field = zcl_datetime=>c_fields-hour iv_value = 9 ). o_datetime->set( iv_field = zcl_datetime=>c_fields-minute iv_value = 30 ). o_datetime->set( iv_field = zcl_datetime=>c_fields-second iv_value = 45 ). DATA(ts) = o_datetime->as_timestamp( ). cl_aunit_assert=>assert_equals( act = ts exp = '20200301093045' msg = 'Set check #01' ). ENDMETHOD. METHOD subtract. ENDMETHOD. METHOD get_day_of_year. DATA(o_datetime) = zcl_datetime=>from_date( '19900806' ). o_datetime->get_day_of_year( ). ENDMETHOD. METHOD get_quarter. DATA(o_datetime) = zcl_datetime=>from_date( '20210101' ). DATA(quarter) = o_datetime->get_quarter( ). cl_aunit_assert=>assert_equals( act = quarter exp = 1 msg = 'Quarter calc check #01' ). o_datetime->add_months( 3 ). quarter = o_datetime->get_quarter( ). cl_aunit_assert=>assert_equals( act = quarter exp = 2 msg = 'Quarter calc check #02' ). o_datetime->add_months( 3 ). quarter = o_datetime->get_quarter( ). cl_aunit_assert=>assert_equals( act = quarter exp = 3 msg = 'Quarter calc check #03' ). o_datetime->add_months( 3 ). quarter = o_datetime->get_quarter( ). cl_aunit_assert=>assert_equals( act = quarter exp = 4 msg = 'Quarter calc check #04' ). o_datetime->add_months( 3 ). quarter = o_datetime->get_quarter( ). cl_aunit_assert=>assert_equals( act = quarter exp = 1 msg = 'Quarter calc check #05' ). ENDMETHOD. METHOD get_iso_week. DATA(o_datetime) = zcl_datetime=>from_date( '20211231' ). DATA(wa_iso_week) = o_datetime->get_iso_week( ). cl_aunit_assert=>assert_equals( act = wa_iso_week exp = VALUE zcl_datetime=>ty_iso_week( week = 52 year = 2021 day_of_week = zcl_datetime=>c_day_of_week-friday ) msg = 'ISO week check #01' ). o_datetime = zcl_datetime=>from_date( '20210101' ). wa_iso_week = o_datetime->get_iso_week( ). cl_aunit_assert=>assert_equals( act = wa_iso_week exp = VALUE zcl_datetime=>ty_iso_week( week = 53 year = 2020 day_of_week = zcl_datetime=>c_day_of_week-friday ) msg = 'ISO week check #02' ). o_datetime = zcl_datetime=>from_date( '20200104' ). wa_iso_week = o_datetime->get_iso_week( ). cl_aunit_assert=>assert_equals( act = wa_iso_week exp = VALUE zcl_datetime=>ty_iso_week( week = 1 year = 2020 day_of_week = zcl_datetime=>c_day_of_week-saturday ) msg = 'ISO week check #03' ). o_datetime = zcl_datetime=>from_date( '20200229' ). wa_iso_week = o_datetime->get_iso_week( ). cl_aunit_assert=>assert_equals( act = wa_iso_week exp = VALUE zcl_datetime=>ty_iso_week( week = 9 year = 2020 day_of_week = zcl_datetime=>c_day_of_week-saturday ) msg = 'ISO week check #04' ). o_datetime = zcl_datetime=>from_date( '20200106' ). wa_iso_week = o_datetime->get_iso_week( ). cl_aunit_assert=>assert_equals( act = wa_iso_week exp = VALUE zcl_datetime=>ty_iso_week( week = 2 year = 2020 day_of_week = zcl_datetime=>c_day_of_week-monday ) msg = 'ISO week check #05' ). ENDMETHOD. METHOD is_leap_year. DATA(o_datetime) = zcl_datetime=>from_date( '20210101' ). DATA(fl_is_leap_year) = o_datetime->is_leap_year( ). cl_aunit_assert=>assert_equals( act = fl_is_leap_year exp = abap_false msg = 'Leap year check #01' ). o_datetime = zcl_datetime=>from_date( '20200101' ). fl_is_leap_year = o_datetime->is_leap_year( ). cl_aunit_assert=>assert_equals( act = fl_is_leap_year exp = abap_true msg = 'Leap year check #02' ). o_datetime = zcl_datetime=>from_date( '16000101' ). fl_is_leap_year = o_datetime->is_leap_year( ). cl_aunit_assert=>assert_equals( act = fl_is_leap_year exp = abap_true msg = 'Leap year check #03' ). o_datetime = zcl_datetime=>from_date( '19000101' ). fl_is_leap_year = o_datetime->is_leap_year( ). cl_aunit_assert=>assert_equals( act = fl_is_leap_year exp = abap_false msg = 'Leap year check #04' ). ENDMETHOD. METHOD is_before. DATA(o_this) = zcl_datetime=>from_now( ). DATA(o_other) = o_this->clone( )->add_days( -1 ). IF o_other->is_before( o_this ). "" Works as expected... ELSE. cl_aunit_assert=>fail( msg = 'Is before check #01' ). ENDIF. IF o_this->is_before( o_other ). cl_aunit_assert=>fail( msg = 'Is before check #02' ). ELSE. "" Works as expected... ENDIF. o_other = o_this->clone( )->add_seconds( -1 ). IF o_other->is_before( o_this ). cl_aunit_assert=>fail( msg = 'Is before check #03' ). ELSE. "" Works as expected... ENDIF. IF o_this->is_before( o_other ). cl_aunit_assert=>fail( msg = 'Is before check #04' ). ELSE. "" Works as expected... ENDIF. IF o_other->is_before( io_datetime = o_this iv_ignore_time = abap_false ). "" Works as expected... ELSE. cl_aunit_assert=>fail( msg = 'Is before check #05' ). ENDIF. ENDMETHOD. METHOD is_before_or_equal. DATA(o_this) = zcl_datetime=>from_now( ). DATA(o_other) = o_this->clone( ). IF o_other->is_before_or_equal( o_this ). "" Works as expected... ELSE. cl_aunit_assert=>fail( msg = 'Is before or equal check #01' ). ENDIF. o_other->add_seconds( -1 ). IF o_other->is_before_or_equal( o_this ). "" Works as expected... ELSE. cl_aunit_assert=>fail( msg = 'Is before or equal check #02' ). ENDIF. o_other = o_this->clone( )->add_seconds( 1 ). IF o_other->is_before_or_equal( o_this ). "" Works as expected... ELSE. cl_aunit_assert=>fail( msg = 'Is before or equal check #03' ). ENDIF. IF o_other->is_before_or_equal( io_datetime = o_this iV_ignore_time = abap_false ). cl_aunit_assert=>fail( msg = 'Is before or equal check #03' ). ELSE. "" Works as expected... ENDIF. ENDMETHOD. METHOD is_after. DATA(o_this) = zcl_datetime=>from_now( ). DATA(o_other) = o_this->clone( ). IF o_this->is_after( o_other ). cl_aunit_assert=>fail( msg = 'Is after check #01' ). ELSE. "" Works as expected... ENDIF. o_other->add_days( - 1 ). IF o_this->is_after( o_other ). "" Works as expected... ELSE. cl_aunit_assert=>fail( msg = 'Is after check #02' ). ENDIF. o_other = o_this->clone( )->add_seconds( -1 ). IF o_this->is_after( io_datetime = o_other iv_ignore_time = abap_false ). "" Works as expected... ELSE. cl_aunit_assert=>fail( msg = 'Is after check #03' ). ENDIF. o_other = o_this->clone( )->add_seconds( 1 ). IF o_this->is_after( io_datetime = o_other iv_ignore_time = abap_false ). cl_aunit_assert=>fail( msg = 'Is after check #03' ). ELSE. "" Works as expected... ENDIF. ENDMETHOD. METHOD is_after_or_equal. DATA(o_this) = zcl_datetime=>from_now( ). DATA(o_other) = o_this->clone( ). IF o_this->is_after_or_equal( o_other ). "" Works as expected... ELSE. cl_aunit_assert=>fail( msg = 'Is after or equal check #01' ). ENDIF. o_other->add_days( 1 ). IF o_this->is_after_or_equal( o_other ). cl_aunit_assert=>fail( msg = 'Is after or equal check #02' ). ELSE. "" Works as expected... ENDIF. o_other = o_this->clone( ). IF o_this->is_after_or_equal( io_datetime = o_other iv_ignore_time = abap_false ). "" Works as expected... ELSE. cl_aunit_assert=>fail( msg = 'Is after or equal check #03' ). ENDIF. o_other->add_seconds( 1 ). IF o_this->is_after_or_equal( io_datetime = o_other iv_ignore_time = abap_false ). cl_aunit_assert=>fail( msg = 'Is after or equal check #04' ). ELSE. "" Works as expected... ENDIF. o_other = o_this->clone( )->add_seconds( - 1 ). IF o_this->is_after_or_equal( io_datetime = o_other iv_ignore_time = abap_false ). "" Works as expected... ELSE. cl_aunit_assert=>fail( msg = 'Is after or equal check #05' ). ENDIF. ENDMETHOD. METHOD is_equal. DATA(o_this) = zcl_datetime=>from_now( ). DATA(o_other) = o_this->clone( ). IF o_this->is_equal( o_other ). "" Works as expected... ELSE. cl_aunit_assert=>fail( msg = 'Is equal check #01' ). ENDIF. o_other->add_days( 1 ). IF o_this->is_equal( o_other ). cl_aunit_assert=>fail( msg = 'Is equal check #02' ). ELSE. "" Works as expected... ENDIF. o_other = o_this->clone( )->add_seconds( 1 ). IF o_this->is_equal( o_other ). "" Works as expected... ELSE. cl_aunit_assert=>fail( msg = 'Is equal check #03' ). ENDIF. IF o_this->is_equal( io_datetime = o_other iv_ignore_time = abap_false ). cl_aunit_assert=>fail( msg = 'Is equal check #04' ). ELSE. "" Works as expected... ENDIF. ENDMETHOD. METHOD create_list. DATA(o_this) = zcl_datetime=>from_date( '20210307' ). o_this->begin_of_year( )->begin_of_day( ). "" Create a list with all 12 month in a year DATA(t_datetime_list) = zcl_datetime=>create_list( io_start = o_this iv_increment_field = zcl_datetime=>c_fields-month iv_increment_value = 1 iv_num_of_elements = 12 ). cl_aunit_assert=>assert_equals( act = lines( t_datetime_list ) exp = 12 msg = 'Create list check #01' ). cl_aunit_assert=>assert_equals( act = t_datetime_list[ 1 ]-o_datetime->as_date( ) exp = CONV dats( '20210101' ) msg = 'Create list check #02' ). cl_aunit_assert=>assert_equals( act = t_datetime_list[ 2 ]-o_datetime->as_date( ) exp = CONV dats( '20210201' ) msg = 'Create list check #03' ). cl_aunit_assert=>assert_equals( act = t_datetime_list[ 3 ]-o_datetime->as_date( ) exp = CONV dats( '20210301' ) msg = 'Create list check #04' ). cl_aunit_assert=>assert_equals( act = t_datetime_list[ 4 ]-o_datetime->as_date( ) exp = CONV dats( '20210401' ) msg = 'Create list check #05' ). cl_aunit_assert=>assert_equals( act = t_datetime_list[ 5 ]-o_datetime->as_date( ) exp = CONV dats( '20210501' ) msg = 'Create list check #06' ). cl_aunit_assert=>assert_equals( act = t_datetime_list[ 6 ]-o_datetime->as_date( ) exp = CONV dats( '20210601' ) msg = 'Create list check #07' ). cl_aunit_assert=>assert_equals( act = t_datetime_list[ 7 ]-o_datetime->as_date( ) exp = CONV dats( '20210701' ) msg = 'Create list check #08' ). cl_aunit_assert=>assert_equals( act = t_datetime_list[ 8 ]-o_datetime->as_date( ) exp = CONV dats( '20210801' ) msg = 'Create list check #09' ). cl_aunit_assert=>assert_equals( act = t_datetime_list[ 9 ]-o_datetime->as_date( ) exp = CONV dats( '20210901' ) msg = 'Create list check #10' ). cl_aunit_assert=>assert_equals( act = t_datetime_list[ 10 ]-o_datetime->as_date( ) exp = CONV dats( '20211001' ) msg = 'Create list check #11' ). cl_aunit_assert=>assert_equals( act = t_datetime_list[ 11 ]-o_datetime->as_date( ) exp = CONV dats( '20211101' ) msg = 'Create list check #12' ). cl_aunit_assert=>assert_equals( act = t_datetime_list[ 12 ]-o_datetime->as_date( ) exp = CONV dats( '20211201' ) msg = 'Create list check #13' ). "" Creating date list with all 31 days of january t_datetime_list = zcl_datetime=>create_list( io_start = o_this iv_increment_field = zcl_datetime=>c_fields-day iv_increment_value = 1 iv_num_of_elements = 31 ). cl_aunit_assert=>assert_equals( act = lines( t_datetime_list ) exp = 31 msg = 'Create list check #14' ). "" Testing only one sample cl_aunit_assert=>assert_equals( act = t_datetime_list[ 15 ]-o_datetime->as_date( ) exp = CONV dats( '20210115' ) msg = 'Create list check #14' ). ENDMETHOD. METHOD sub_days. DATA(o_datetime) = zcl_datetime=>from_date( '20210307' ). o_datetime->sub_days( 5 ). DATA(ts) = o_datetime->as_timestamp( ). cl_aunit_assert=>assert_equals( act = ts exp = '20210302000000' msg = 'Sub days check #01' ). o_datetime->sub_days( -10 ). ts = o_datetime->as_timestamp( ). cl_aunit_assert=>assert_equals( act = ts exp = '20210312000000' msg = 'Sub days check #02' ). ENDMETHOD. METHOD sub_hours. DATA(o_datetime) = zcl_datetime=>from_date( iv_date = '20210307' iv_time = '060000' ). o_datetime->sub_hours( 8 ). DATA(ts) = o_datetime->as_timestamp( ). cl_aunit_assert=>assert_equals( act = ts exp = '20210306220000' msg = 'Sub hours check #01' ). o_datetime->sub_hours( 16 ). ts = o_datetime->as_timestamp( ). cl_aunit_assert=>assert_equals( act = ts exp = '20210306060000' msg = 'Sub hours check #02' ). o_datetime->sub_hours( -24 ). ts = o_datetime->as_timestamp( ). cl_aunit_assert=>assert_equals( act = ts exp = '20210307060000' msg = 'Sub hours check #03' ). ENDMETHOD. METHOD sub_minutes. DATA(o_datetime) = zcl_datetime=>from_date( iv_date = '20210307' iv_time = '060000' ). o_datetime->sub_minutes( 8 ). DATA(ts) = o_datetime->as_timestamp( ). cl_aunit_assert=>assert_equals( act = ts exp = '20210307055200' msg = 'Sub minutes check #01' ). o_datetime->sub_minutes( 52 ). ts = o_datetime->as_timestamp( ). cl_aunit_assert=>assert_equals( act = ts exp = '20210307050000' msg = 'Sub minutes check #02' ). ENDMETHOD. METHOD sub_months. DATA(o_datetime) = zcl_datetime=>from_date( '20210131' ). DATA(date) = o_datetime->sub_months( 1 )->as_date( ). cl_aunit_assert=>assert_equals( act = date exp = '20201231' msg = 'Sub month check #01' ). date = o_datetime->sub_months( 36 )->as_date( ). cl_aunit_assert=>assert_equals( act = date exp = '20171231' msg = 'Sub month check #02' ). ENDMETHOD. METHOD sub_seconds. DATA(o_datetime) = zcl_datetime=>from_date( iv_date = '20210307' iv_time = '060000' ). o_datetime->sub_seconds( 8 ). DATA(ts) = o_datetime->as_timestamp( ). cl_aunit_assert=>assert_equals( act = ts exp = '20210307055952' msg = 'Sub seconds check #01' ). o_datetime->sub_seconds( 52 ). ts = o_datetime->as_timestamp( ). cl_aunit_assert=>assert_equals( act = ts exp = '20210307055900' msg = 'Sub seconds check #02' ). ENDMETHOD. METHOD sub_weeks. DATA(o_datetime) = zcl_datetime=>from_date( iv_date = '20210307' ). o_datetime->sub_weeks( 1 ). DATA(date) = o_datetime->as_date( ). cl_aunit_assert=>assert_equals( act = date exp = '20210228' msg = 'Sub weeks check #01' ). o_datetime->sub_weeks( -2 ). date = o_datetime->as_date( ). cl_aunit_assert=>assert_equals( act = date exp = '20210314' msg = 'Sub weeks check #02' ). ENDMETHOD. METHOD sub_years. DATA(o_datetime) = zcl_datetime=>from_date( iv_date = '20210307' ). o_datetime->sub_years( 1 ). DATA(date) = o_datetime->as_date( ). cl_aunit_assert=>assert_equals( act = date exp = '20200307' msg = 'Sub years check #01' ). o_datetime->sub_years( -2 ). date = o_datetime->as_date( ). cl_aunit_assert=>assert_equals( act = date exp = '20220307' msg = 'Sub years check #02' ). ENDMETHOD. METHOD diff. DATA(o_this) = zcl_datetime=>from_date( iv_date = '20210307' ). DATA(o_other) = o_this->clone( )->add_hours( 36 ). DATA(diff) = o_this->diff( io_datetime = o_other iv_field = zcl_datetime=>c_fields-day ). cl_aunit_assert=>assert_equals( act = diff exp = CONV zcl_datetime=>ty_diff( '1.5' ) msg = 'Diff check #01' ). diff = o_this->diff( io_datetime = o_other iv_field = zcl_datetime=>c_fields-day iv_round_mode = zcl_datetime=>c_rouding-round_ceiling ). cl_aunit_assert=>assert_equals( act = diff exp = CONV zcl_datetime=>ty_diff( '2' ) msg = 'Diff check #02' ). diff = o_this->diff( io_datetime = o_other iv_field = zcl_datetime=>c_fields-day iv_round_mode = zcl_datetime=>c_rouding-round_down ). cl_aunit_assert=>assert_equals( act = diff exp = CONV zcl_datetime=>ty_diff( '1' ) msg = 'Diff check #02' ). o_other = o_this->clone( )->add_hours( 44 ). diff = o_this->diff( io_datetime = o_other iv_field = zcl_datetime=>c_fields-day ). cl_aunit_assert=>assert_equals( act = diff exp = CONV zcl_datetime=>ty_diff( '1.833333333333333' ) msg = 'Diff check #02' ). o_this = zcl_datetime=>from_date( '20210101' ). o_other = zcl_datetime=>from_date( '20211231' ). diff = o_this->diff( io_datetime = o_other iv_field = zcl_datetime=>c_fields-month ). ENDMETHOD. ENDCLASS. ",12880,True,3144.685192996604,median ":toc: macro toc::[] :idprefix: :idseparator: - ifdef::env-github[] :tip-caption: :bulb: :note-caption: :information_source: :important-caption: :heavy_exclamation_mark: :caution-caption: :fire: :warning-caption: :warning: endif::[] = devon4j adding Custom Functionality Now we have a fully functional blank project. All we have to do now is to create the components and services which will compose our application. First, we are going to develop the views of the app through its components, then we will create the services with the logic, security and back-end connection. == Creating Components [NOTE] ==== You have already learned about creating Components in devon4ng https://github.com/devonfw/jump-the-queue/wiki/devon4ng-components#create-a-new-component[here]. + You can go back and read that section again to refresh your memory. ==== Our app is going to consist of 3 main views: * Login * Register * ViewQueue To navigate between these views/components, we are going to implement routes using the Angular Router. To see our progress, move to the root folder of the `angular` project and run `ng serve -o` again. This will recompile and publish our client app to http://localhost:4200. Angular will keep watching for changes, so whenever we modify the code, the app will automatically reload. === Root Component `app.component.ts` inside `angular/src/app` will be our root component, so we don't have to create a new file yet. We are going to add elements to the root component that will be common no matter what view will be displayed. [NOTE] ==== You have already learned about the Root Component in devon4ng https://github.com/devonfw/jump-the-queue/wiki/devon4ng-components#root-component[here]. + You can go back and read that section again to refresh your memory. ==== This applies to the header element which will be on top of the window and on top of all other components. If you want, you can read more about https://teradata.github.io/covalent/#/layouts[Covalent layouts], which we are going to use a lot from now on, for every view component. [NOTE] ==== You have already learned about Covalent Layouts in devon4ng https://github.com/devonfw/jump-the-queue/wiki/devon4ng-components#teradata-covalent-layouts[here]. + You can go back and read that section again to refresh your memory. ==== We don't really need anything more than a header, so we are going to use the simplest layout for this purpose; the *nav view*. In order to be able to use Covalent and Angular Material we are going to create a core module, which we will import into every other module where we want to use Covalent and Angular Material. First, we create a folder called `shared` in the `angular/src/app` directory. Inside there we are going to create a file called `core.module.ts` and will fill it with the following content: [source, typescript] ---- import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; import { CommonModule } from '@angular/common'; import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { MatAutocompleteModule, MatButtonModule, MatButtonToggleModule, MatCardModule, MatCheckboxModule, MatChipsModule, MatDatepickerModule, MatDialogModule, MatExpansionModule, MatGridListModule, MatIconModule, MatInputModule, MatListModule, MatMenuModule, MatNativeDateModule, MatPaginatorModule, MatProgressBarModule, MatProgressSpinnerModule, MatRadioModule, MatRippleModule, MatSelectModule, MatSidenavModule, MatSliderModule, MatSlideToggleModule, MatSnackBarModule, MatSortModule, MatTableModule, MatTabsModule, MatToolbarModule, MatTooltipModule, } from '@angular/material'; import { CdkTableModule } from '@angular/cdk/table'; import { CovalentChipsModule, CovalentLayoutModule, CovalentExpansionPanelModule, CovalentDataTableModule, CovalentPagingModule, CovalentDialogsModule, CovalentLoadingModule, CovalentMediaModule, CovalentNotificationsModule, CovalentCommonModule, } from '@covalent/core'; @NgModule({ imports: [ RouterModule, BrowserAnimationsModule, MatCardModule, MatButtonModule, MatIconModule, CovalentMediaModule, CovalentLayoutModule, CdkTableModule, ], exports: [ CommonModule, CovalentChipsModule, CovalentLayoutModule, CovalentExpansionPanelModule, CovalentDataTableModule, CovalentPagingModule, CovalentDialogsModule, CovalentLoadingModule, CovalentMediaModule, CovalentNotificationsModule, CovalentCommonModule, CdkTableModule, MatAutocompleteModule, MatButtonModule, MatButtonToggleModule, MatCardModule, MatCheckboxModule, MatChipsModule, MatDatepickerModule, MatDialogModule, MatExpansionModule, MatGridListModule, MatIconModule, MatInputModule, MatListModule, MatMenuModule, MatNativeDateModule, MatPaginatorModule, MatProgressBarModule, MatProgressSpinnerModule, MatRadioModule, MatRippleModule, MatSelectModule, MatSidenavModule, MatSliderModule, MatSlideToggleModule, MatSnackBarModule, MatSortModule, MatTableModule, MatTabsModule, MatToolbarModule, MatTooltipModule, HttpClientModule, ], declarations: [], providers: [ HttpClientModule ], }) export class CoreModule {} ---- [NOTE] ==== This `CoreModule` has almost every module of the different components for *Angular Material* and *Covalent Teradata*. If you decide to use a component that is not included yet, you need to add the corresponding module here. ==== Remember that we need to import this `CoreModule` module into the `AppModule` and inside every module of the different components that use *Angular Material* and *Covalent Teradata*. If a component does not have a module, it will be imported in the `AppModule` and hence automatically have the `CoreModule`. Our `app.module.ts` should have the following content: [source, typescript] ---- import { BrowserModule } from '@angular/platform-browser'; import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; // Application components and services import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { CoreModule } from './shared/core.module'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule, CoreModule, ], providers: [ ], bootstrap: [AppComponent], schemas: [ CUSTOM_ELEMENTS_SCHEMA ] }) export class AppModule { } ---- [NOTE] ==== Even if we setup module correctly the html file can give us this red flag: ""If 'td-layout' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message."" To solve this we add ""schemas: [ CUSTOM_ELEMENTS_SCHEMA ]"" insde the @NgModule of all the afected modules. ==== [NOTE] ==== Remember this step because you will have to repeat it for every other component from Teradata you use in your app. ==== Now we can use this layout, so let's implement it in `app.component.html`. Use the following code: [source, html] ----
Jump The Queue

app works!

---- [NOTE] ==== You have already learned about Toolbars in devon4ng https://github.com/devonfw/jump-the-queue/wiki/devon4ng-components#toolbars[here]. + You can go back and read that section again to refresh your memory. ==== [NOTE] ==== You have already learned about Toolbars in devon4ng https://github.com/devonfw/jump-the-queue/wiki/devon4ng-components#toolbars[here]. + You can go back and read that section again to refresh your memory. ==== Once this is done, our app should have a header and ""app works!"" should appear in the body of the page: image::images/devon4ng/3.BuildYourOwn/root_header.jpg[Root Header, 250] To go a step further, we have to modify the body of the root component because it should be the *output of the router*. Now it's time to prepare the routing system. First, we need to create a component to show as default which will be our access view. We will modify it later. Stop `ng serve` and run: ---- ng generate component form-login ---- It will add a folder to our project with all the files needed for a component. Now we can move on to the router task again. Run `ng serve` again to continue the development. Let's create a module that navigates between components when the Router checks for routes. The file `app-routing.module.ts` was created automatically when we chose to include Angular Routing during project creation and we only need to modify it now: [source, typescript] ---- import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { FormLoginComponent } from './form-login/form-login.component'; const appRoutes: Routes = [ { path: 'FormLogin', component: FormLoginComponent}, // Redirect if url path is /FormLogin. { path: '**', redirectTo: '/FormLogin', pathMatch: 'full' } // Redirect if url path do not match any other route. ]; @NgModule({ imports: [ RouterModule.forRoot( appRoutes, { enableTracing: true }, // <-- debugging purposes only ), ], exports: [RouterModule], }) export class AppRoutingModule {} ---- [NOTE] ==== You have already learned about Routing in devon4ng https://github.com/devonfw/jump-the-queue/wiki/devon4ng-components#routing[here]. + You can go back and read that section again to refresh your memory. ==== Finally, we remove the `

app works!

` from `app.component.html` and replace it with a `` tag. The final result of our root component will look like this: image::images/devon4ng/3.BuildYourOwn/root_router.jpg[Root Router, 250] As you can see, now the body content is the HTML of `FormLoginComponent`. This is because we told the Router to redirect to formlogin when the path is `/FormLogin`, but also, redirect to it by default if any of the other routes match the given path. For now we are going to leave the header like this. In the future we will separate it into another component inside a layout folder. === LoginForm Component As we have already created this component from the section before, let's move on to building the template of the login view. First, we need to add the Covalent Layout and the card to the file `form-login.component.html`: [source, html] ---- Login ---- This will add a grey background to the view and a card on top of it with the title ""Login"" now that we have the basic structure of the view. Now we are going to add this image: image::images/devon4ng/3.BuildYourOwn/jumptheq.png[JumpTheQueue Logo Image, 250] In order to have it available, save it in the following path of the project: `angular/src/assets/images/` and name it `jumptheq.png`. The final code with the form added will look like this: [source, html] ---- ---- This code will give us as a result similar to this: image::images/devon4ng/3.BuildYourOwn/formlogin.png[Form Login, 250] This is going to be the container for the login. + Now we will continue with the second component: Login. === Login Component Our first step will be to create the component in the exact same way we created the `FormLogin` component but this time we are going to generate it in a new folder called components inside formlogin. Putting every child component inside that folder will allow us to keep a good and clear structure. In order to do this, we use the command: ---- ng generate component form-login/components/login ---- After _Angular/CLI_ has finished generating the component, we have to create two modules, one for the form-login and one for the login: 1.- We create a new file called `login-module.ts` in the login root: [source, typescript] ---- import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; import { CommonModule } from '@angular/common'; import { CoreModule } from 'src/app/shared/core.module'; import { LoginComponent } from './login.component'; @NgModule({ imports: [CommonModule, CoreModule], providers: [], declarations: [LoginComponent], exports: [LoginComponent], schemas: [ CUSTOM_ELEMENTS_SCHEMA ] }) export class LoginModule {} ---- 2.- We create a new file called `form-login-module.ts` in the form-login root: [source, typescript] ---- import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormLoginComponent } from './form-login.component'; import { CoreModule } from '../shared/core.module'; import { LoginModule } from './components/login/login-module'; @NgModule({ imports: [CommonModule, CoreModule, LoginModule], providers: [], declarations: [FormLoginComponent], exports: [FormLoginComponent], schemas: [ CUSTOM_ELEMENTS_SCHEMA ] }) export class FormLoginModule {} ---- As you can see, the `LoginModule` is already added to the `FormLoginModule`. Once this is done, we need to remove the `FormLoginComponent` and the `LoginComponent` from the `declarations` since they are already declared in their own modules. Then add the `FormLoginModule`. This will be done inside `AppModule`: [source, typescript] ---- ... import { FormLoginModule } from './form-login/form-login-module'; ... declarations: [ AppComponent, ] imports: [ BrowserModule, FormLoginModule, CoreModule, AppRoutingModule ] ... ---- [NOTE] ==== This is done so the `form-login` (container/wrapper) and the `login` stay separated allowing us to reuse the login without having the card around in other views. ==== After this, we modify the `login.component.html` and add the form: [source, typescript] ----
---- [NOTE] ==== You have already learned about Forms in devon4ng https://github.com/devonfw/jump-the-queue/wiki/devon4ng-components#forms[here]. + You can go back and read that section again to refresh your memory. ==== This form contains two input containers from Material. The containers enclose the input with the properties listed above. We also need to add a button to send the information and redirect to the `QueueViewer` or show an error if something went wrong in the process. But for the moment, as we neither have another component nor the auth service yet, we will implement the button visually, as well as the validator to disable it if the form is not correct. We will tackle the on-click-event later. As a last step we will add this component to the `form-login-component.html`: [source, html] ---- ---- Now you should see something like this: image::images/devon4ng/3.BuildYourOwn/login.png[JumpTheQueue Login Screen, 250] With two components already created, we need to use the router to navigate between them. Following the application flow of events, we are going to add a _navigate_ function to the register button. When we press it, we will be redirected to our future register component. === Register Component First, we are going to generate the register component via: ---- ng generate component register` ---- This will create our component so we can start working on it. Turning back to `login.component.html` we have to modify these lines of code: [source, html] ----
... ... ---- Two events were added. First, when we submit the form, the method `submitLogin()` is going to be called. Second, when the user clicks the button `(click)` will send an event to the function `onRegisterClick()`. This function should be inside `login.component.ts` which is going to be created now: [source, typescript] ---- ... import { Router } from '@angular/router'; ... constructor(private router: Router) { } ... onRegisterClick(): void { this.router.navigate(['Register']); } submitLogin(): void { } ---- We need to inject an instance of the Router object and declare it with the name _router_ in order to use it in the code, as we did with `onRegisterClick()`. Doing this will use the navigate function and redirect to the next view. In our case, it will redirect using the route we are going to define in `app.routing.module.ts`: [source, typescript] ---- ... import { RegisterComponent } from './register/register.component'; ... const appRoutes: Routes = [ { path: 'FormLogin', component: FormLoginComponent}, // Redirect if url path is /FormLogin. { path: 'Register', component: RegisterComponent}, // Redirect if url path is /Register. { path: '**', redirectTo: '/FormLogin', pathMatch: 'full' } // Redirect if url path do not match any other route. ]; ... ---- [NOTE] ==== You have already learned about Dependency Injection in devon4ng https://github.com/devonfw/jump-the-queue/wiki/devon4ng-services#dependency-injection[here]. + You can go back and read that section again to refresh your memory. ==== Now we are going to imitate the `login` to shape our `register.component.html`: [source, html] ----
Accept Terms And conditions
I want to receive notifications
---- Now that we have a minimum of navigation flow inside our application, we are going to generate our first service using the command: ---- ng generate service register/services/register ---- This will create a folder ""services"" inside ""register"" and create the service itself. Services are where we keep the logic that connects to our database and fetches data which is going to be used by our `component.ts`. In order to use the service, we are going to create some interface models. Let's create a folder called `backendModels` inside ""shared"" and inside this folder a file called `interfaces.ts` in which we are going to add the model interfaces that will match our backend: [source, typescript] ---- export class Visitor { id?: number; username: string; name: string; password: string; phoneNumber: string; acceptedCommercial: boolean; acceptedTerms: boolean; userType: boolean; } export class VisitorArray { content: Visitor[]; } ---- [NOTE] ==== You have already learned about creating new services in devon4ng https://github.com/devonfw/jump-the-queue/wiki/devon4ng-services#create-a-new-service[here]. + You can go back and read that section again to refresh your memory. ==== If we take a closer look, we can see that id has a `?` behind it. This indicates that the id is optional. [NOTE] ==== At this point we are going to assume that you have finished the https://github.com/devonfw/jump-the-queue/wiki/build-devon4j-application[devon4j] part of this tutorial, or have at least downloaded the project and have the back end running locally on http://localhost:8081. ==== After doing this, we are going to add an environment variable with our base-URL for the REST services. This way we won't have to change every URL when we switch to production. Inside `environments/environment.ts` we add: [source, typescript] ---- export const environment: {production: boolean, baseUrlRestServices: string} = { production: false, baseUrlRestServices: 'http://localhost:8081/jumpthequeue/services/rest' }; ---- Now in the service, we are going to add a `registerVisitor` method. To call the server in this method we are going to inject the Angular `HttpClient` class from `@angular/common/http`. This class is the standard used by Angular to perform HTTP calls. The register call demands a `Visitor` model which we created in the `interfaces` file. We are going to build a POST call and send the information to the proper URL of the server service. The call will return an observable: [source, typescript] ---- import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Visitor} from 'src/app/shared/backendModels/interfaces'; import { Observable } from 'rxjs'; import { environment } from 'src/environments/environment'; @Injectable({ providedIn: 'root' }) export class RegisterService { private baseUrl = environment.baseUrlRestServices; constructor(private http: HttpClient) { } registerVisitor(visitor: Visitor): Observable { return this.http.post(`${this.baseUrl}` + '/visitormanagement/v1/visitor', visitor); } } ---- This method will send our model to the backend and return an Observable that we will use on the `component.ts`. [NOTE] ==== You have already learned about Observables and RxJs in devon4ng https://github.com/devonfw/jump-the-queue/wiki/devon4ng-services#server-communication[here]. + You can go back and read that section again to refresh your memory. ==== Now we are going to modify `register.component.ts` to call this service: [source, typescript] ---- import { Component, OnInit } from '@angular/core'; import { RegisterService } from './services/register.service'; import { Visitor } from '../shared/backendModels/interfaces'; import { Router } from '@angular/router'; import { MatSnackBar } from '@angular/material/snack-bar'; @Component({ selector: 'app-register', templateUrl: './register.component.html', styleUrls: ['./register.component.scss'] }) export class RegisterComponent implements OnInit { constructor(private registerService: RegisterService, private router: Router, public snackBar: MatSnackBar) { } submitRegister(formValue): void { const visitor: Visitor = new Visitor(); visitor.username = formValue.username; visitor.name = formValue.name; visitor.phoneNumber = formValue.phoneNumber; visitor.password = formValue.password; visitor.acceptedCommercial = formValue.acceptedCommercial; visitor.acceptedTerms = formValue.acceptedTerms; visitor.userType = false; this.registerService.registerVisitor(visitor).subscribe( (visitorResult: Visitor) => console.log(JSON.stringify(visitorResult)), // When call is received (err) => this.snackBar.open(err.error.message, 'OK', { duration: 5000, }), // When theres an error ); } ngOnInit() { } } ---- In this file we injected `RegisterService` and `Router` to use them. Then, inside the method `submitRegister`, we created a visitor that we are going to pass to the service. We called the service method `registerVisitor`, we passed the visitor and we subscribed to the `Observable`, which we returned from the service. This subscription allows us to control three things: . What to do when the data is received. . What to do when there's an error. . What to do when the call is complete. Finally, we modify the `register.component.html` to send the form values to the method: [source, html] ---- ...
... ---- image::images/devon4ng/3.BuildYourOwn/register.png[Register Page, 250] Using the method and taking a look at the browser console, we should see the visitor model being returned. == Creating Services Now that we registered a `Visitor`, it's time to create 3 important services: - AuthService - AuthGuardService - LoginService The `AuthService` will be the one that contains the login info, the `AuthGuardService` will check if a user is authorized to use a component (via the `canActivate` method), and the `LoginService` will be used to fill the `AuthService`. [NOTE] ==== To keep this tutorial simple, we are going to perform the password check client side. *THIS IS NOT CORRECT!* Usually, you would send the username and password to the backend, check that the values are correct, and create a corresponding token which you would pass in the header and use it inside the `AuthService` -- checking with some interceptors that the token is both in the `AuthService` and in the request. ==== === Login, Auth and AuthGuard Services We are going to create the 3 services via `ng generate service `: . `LoginService` via: + `ng generate service form-login/components/login/services/login` . `Auth` service via: + `ng generate service core/authentication/auth` . `AuthGuard` service via: + `ng generate service core/authentication/auth-guard` After generating the services, we are going to start modifying the interfaces. Inside `angular/src/app/shared/backendModels/interfaces` we are going to add `Role`, `FilterVisitor`, `Pageable` and a `Sort` interface: [source, typescript] ---- ... export class FilterVisitor { pageable: Pageable; username?: string; password?: string; } export class Pageable { pageSize: number; pageNumber: number; sort: Sort[]; } export class Sort { property: string; direction: string; } export class Role { name: string; permission: number; } ---- [NOTE] ==== As you can see, we added a `Pageable`, since a lot of the search methods in the backend are using `SearchCriterias`. These need pageables which specify a `paseSize` and `pageNumber`. Also, we can see that in this case `FilterVisitor` uses a pageable and adds parameters as a filter (`username` and `password`), which are optional. ==== Then we are going to create a `config.ts` file inside the root (`angular/app`). We are going to use that file to set up default config variables, for example: role names with their permission number, default pagination settings etc. For now we are just adding the roles: [source, typescript] ---- export const config: any = { roles: [ { name: 'VISITOR', permission: 0 }, { name: 'BOSS', permission: 1 }, ], }; ---- After that, we are going to modify the `auth.service.ts`: [source, typescript] ---- import { Injectable } from '@angular/core'; import { find } from 'lodash'; import { Role } from 'src/app/shared/backendModels/interfaces'; import { config } from 'src/app/config'; @Injectable({ providedIn: 'root' }) export class AuthService { private logged = false; private user = ''; private userId = 0; private currentRole = 'NONE'; private token: string; public isLogged(): boolean { return this.logged; } public setLogged(login: boolean): void { this.logged = login; } public getUser(): string { return this.user; } public setUser(username: string): void { this.user = username; } public getUserId(): number { return this.userId; } public setUserId(userId: number): void { this.userId = userId; } public getToken(): string { return this.token; } public setToken(token: string): void { this.token = token; } public setRole(role: string): void { this.currentRole = role; } public getPermission(roleName: string): number { const role: Role = find(config.roles, { name: roleName }); return role.permission; } public isPermited(userRole: string): boolean { return ( this.getPermission(this.currentRole) === this.getPermission(userRole) ); } } ---- We will use this service to fill it with information from the logged-in user once the user logs in. This will allow us to check the information of the logged-in user in any way necessary. [NOTE] ==== You have already learned about Authentication in devon4ng https://github.com/devonfw/jump-the-queue/wiki/devon4ng-services#authentication[here]. + You can go back and read that section again to refresh your memory. ==== Now we are going to use this class to fill the `auth-guard.service.ts`: [source, typescript] ---- import { Injectable } from '@angular/core'; import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot, } from '@angular/router'; import { AuthService } from './auth.service'; @Injectable({ providedIn: 'root' }) export class AuthGuardService implements CanActivate { constructor( private authService: AuthService, private router: Router, ) {} canActivate( route: ActivatedRouteSnapshot, state: RouterStateSnapshot, ): boolean { if (this.authService.isLogged() && this.authService.isPermited('VISITOR')) { // If its logged in and its role is visitor return true; } if (!this.authService.isLogged()) { // if its not logged in console.log('Error login'); } if (this.router.url === '/') { // if the router is the app route this.router.navigate(['/login']); } return false; } } ---- This service will be slightly different because we have to implement an interface called `CanActivate`. It has a method called `canActivate()` returning a boolean. This method will be called when navigating to a specified route, and -- depending on the return value of this implemented method -- the navigation will proceed or be rejected. [NOTE] ==== You have already learned about Guards in devon4ng https://github.com/devonfw/jump-the-queue/wiki/devon4ng-services#guards[here]. + You can go back and read that section again to refresh your memory. ==== Once this is done, the last step is to fill the `login.service.ts`. In this case, there's going to be three methods: . `getVisitorByUsername(username: string)`: + A method that recovers a single user corresponding to the email. . `login(username: string, password: string)`: + A method, which is going to use the previous method, to check that the username and password match the form input and then fill the `AuthService`. . `logout()`: + This is going to be used to reset the `AuthService` and log out the user. Also, we see the first use of `pipe` and `map`: + `pipe` allows us to execute a chain of functions, then `map` allows us to return the single visitor instead of all the parameters that the server will send us. [source, typescript] ---- import { map, tap } from 'rxjs/operators'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { Visitor, FilterVisitor, Pageable } from 'src/app/shared/backendModels/interfaces'; import { HttpClient } from '@angular/common/http'; import { environment } from 'src/environments/environment'; import { AuthService } from 'src/app/core/authentication/auth.service'; import { Router } from '@angular/router'; import { MatSnackBar } from '@angular/material/snack-bar'; @Injectable({ providedIn: 'root' }) export class LoginService { private baseUrl = environment.baseUrlRestServices; constructor(private router: Router, private http: HttpClient, private authService: AuthService, public snackBar: MatSnackBar) { } getVisitorByUsername(username: string): Observable { const filters: FilterVisitor = new FilterVisitor(); const pageable: Pageable = new Pageable(); pageable.pageNumber = 0; pageable.pageSize = 1; pageable.sort= []; filters.username = username; filters.pageable = pageable; return this.http.post(`${this.baseUrl}` + '/visitormanagement/v1/visitor/search', filters) .pipe( map(visitors => visitors.content[0]), ); } login(username: string, password: string): void { // Checks if given username and password are the ones aved in the database this.getVisitorByUsername(username).subscribe( (visitorFound) => { if (visitorFound.username === username && visitorFound.password === password) { this.authService.setUserId(visitorFound.id); this.authService.setLogged(true); this.authService.setUser(visitorFound.username); if (visitorFound.userType === false) { this.authService.setRole('VISITOR'); this.router.navigate(['ViewQueue']); } else { this.authService.setLogged(false); this.snackBar.open('access error', 'OK', { duration: 2000, }); } } else { this.snackBar.open('access error', 'OK', { duration: 2000, }); } }, (err: any) => { this.snackBar.open('access error', 'OK', { duration: 2000, }); }, ); } logout(): void { this.authService.setLogged(false); this.authService.setUser(''); this.authService.setUserId(0); this.router.navigate(['FormLogin']); } } ---- If you remember the devon4j tutorial, we used `Criteria` in order to filter and to search the DB. The `Criteria` require a pageable and you can add extra parameters to get specific results. In `getVisitorByUsername()` you can see the creation of a `FilterVisitor` corresponding to the `Criteria` in the backend. This `FilterVisitor` gets a `Pageable` and a `username` and will return a single result as soon as the POST call is performed. That's why we return the first page and only a single result. [NOTE] ==== For the tutorial we are only considering the visitor side of the application. That's why we `setLogged(false)` if it's `userType === true` (BOSS side). ==== Then we add to the `login-module.ts` and `LoginService`: [source, typescript] ---- ... import { LoginService } from './services/login.service'; @NgModule({ ... providers: [LoginService], ... }) ... ---- After that, we are going to add the `AuthGuard` and the `Auth` into the `shared/core-module.ts`. This will allow us to employ these two services when importing the core module avoiding having to provide these services in every component: [source, typescript] ---- ... providers: [ HttpClientModule, AuthService, AuthGuardService, ], ... ---- You need to import these modules as well, as shown earlier. Finally, we modify the `login.component.html` to send the form values to the `login.component.ts` like we did with the register form. Afterwards, we are going to modify the `register.components.ts`: When the visitor registers, we can log him in automatically to avoid any nuisances. Let's start with the `login.component.html`: [source, html] ---- ... ... ---- As you can see, in the form we just added, the values to the `ngSubmit` allow us to call the method `submitLogin()` within the logic, sending the `loginForm.form.values` which are the form's input values. In the next step we are going to modify the `login.components.ts`, adding the `submitLogin()` method. This method calls the `LoginService`, providing the service with the necessary values received from the form (i.e. the `loginFormValues`). [source, typescript] ---- ... import { LoginService } from './services/login.service'; ... export class LoginComponent implements OnInit { ... constructor(private router: Router, private loginService: LoginService) { } ... submitLogin(loginFormValues): void { this.loginService.login(loginFormValues.username, loginFormValues.password); } } ---- Finally, in the `register.components.ts` we are going to inject the `LoginService` and use it to login the visitor after registering him. This will also send the user to the `ViewQueue`, which we will create and secure later in the tutorial. [source, typescript] ---- import { LoginService } from '../form-login/components/login/services/login.service'; ... constructor(private registerService: RegisterService, private router: Router, public snackBar: MatSnackBar, private loginService: LoginService) { } ... submitRegister(formValue): void { ... this.registerService.registerVisitor(visitor).subscribe( (visitorResult: Visitor) => { this.loginService.login(visitorResult.username, visitorResult.password); }, ... ); } ... ---- == Finishing Touches Now we only need to generate two more components (`header` and `view-queue`) and services (`AccessCodeService` and `QueueService`) in order to finish the implementation of our _JumpTheQueue_ app. === Separating Header from Layout By separating the header on top of the page from the layout, we enable the reuse of this component and reach a better separation of concerns across our application. To do this, we are going to generate a new component inside `angular/src/app/layout/header` via: ---- ng generate component layout/header ---- Now we are going to add it to the main view `app.component.html`: [source, html] ---- ...
... ---- After adding the component to the header view (`app-header`), we are going to modify the HTML of the component (`header.component.html`) and the logic of the component (`header.component.ts`). As a first step, we are going to modify the HTML, adding an icon as a button, which checks whether or not the user is logged in via `*ngIf` by calling the auth service's `isLogged()` method. This will make the icon appear only if the user is logged in: [source, html] ---- Jump The Queue ---- In the header logic (`header.component.ts`) we are simply going to inject the `AuthService` and `LoginService`, then we are going call `logout()` from `LoginService` in the `OnClickLogout()`. Finally, the `AuthService` is needed because it's being used by the HTML template to control if the user is logged in with `isLogged()`: [source, typescript] ---- ... constructor(private authService: AuthService, private loginService: LoginService) { } ... onClickLogout(): void { this.loginService.logout(); } ... ---- Separating components will allow us to keep the code clean and easy to work with. === ViewQueue Component For the last view, we are going to learn how to use our Observables on the HTML template directly without having to `subscribe()` to them. First, we are going to generate the component via: ---- ng generate component view-queue ---- After that, we are going to include the component in the `app-routing.module.ts`, also adding the guard, to only allow users that are `VISITOR` to see the component. It is important to insert the following code before `{ path: '**', redirectTo: '/FormLogin', pathMatch: 'full' }`: [source, typescript] ---- ... const appRoutes: Routes = [ ... { path: 'ViewQueue', component: ViewQueueComponent, canActivate: [AuthGuardService]}, // Redirect if url path is /ViewQueue, check if canActivate() with the AuthGuardService. ... ]; ... ---- Now in order to make this view work, we are going to do these things: . Add the `Queue` and `AccessCode` interface in our `angular/src/app/shared/backendModels/interfaces` and their corresponding filters. . Generate the `QueueService` and `AccessCodeService` and add the necessary methods. . Modify the `view-queue.component.html`. . Modify the logic of the component `view-queue.component.ts`. First, we are going to add the necessary interfaces. We modify `angular/src/app/shared/backendModels/interfaces.ts` and add the `FilterQueue`, `Queue`, `FilterAccessCode`, `AccessCode`, `QueueArray` and `AccessCodeArray`. These are going to be necessary in order to communicate with the backend. [source, typescript] ---- ... export class FilterAccessCode { pageable: Pageable; visitorId?: Number; endTime?: string; } export class FilterQueue { pageable: Pageable; active: boolean; } export class AccessCode { id?: number; ticketNumber: string; creationTime: string; startTime?: string; endTime?: string; visitorId: number; queueId: number; content: any; } export class Queue { id?: number; name: string; logo: string; currentNumber: string; attentionTime: string; minAttentionTime: string; active: boolean; customers: number; content: any; } export class QueueArray { content: Queue[]; } export class AccessCodeArray { content: [{ accessCode: AccessCode }]; } ... ---- === AccessCode and Queue Services After this is done, we are going to generate the `AccessCodeService` and the `QueueService`: ---- ng generate service view-queue/services/Queue ng generate service view-queue/services/AccessCode ---- Once this is done, we are going to modify them and add the necessary methods: - For the `AccessCodeService` we are going to need a full CRUD: [source, typescript] ---- import { Injectable } from '@angular/core'; import { AuthService } from 'src/app/core/authentication/auth.service'; import { Router } from '@angular/router'; import { HttpClient } from '@angular/common/http'; import { AccessCode, Pageable, FilterAccessCode } from 'src/app/shared/backendModels/interfaces'; import { Observable } from 'rxjs'; import { environment } from 'src/environments/environment'; import { map } from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) export class AccessCodeService { private baseUrl = environment.baseUrlRestServices; constructor(private router: Router, private http: HttpClient, private authService: AuthService) { } getCurrentlyAttendedAccessCode(): Observable { const filters: FilterAccessCode = new FilterAccessCode(); const pageable: Pageable = new Pageable(); filters.endTime = null; pageable.pageNumber = 0; pageable.pageSize = 1; filters.pageable = pageable; return this.http.post(`${this.baseUrl}` + '/accesscodemanagement/v1/accesscode/cto/search', filters) .pipe( map(accesscodes => { if (!accesscodes.content[0]) { // if theres no response it means theres noone in the queue return null; } else { if (accesscodes.content[0].accessCode.startTime != null) { // if start time is not null it means that hes being attended return accesscodes.content[0].accessCode; } else { // noone being attended return null; } } }), ); } getVisitorAccessCode(visitorId: number): Observable { const filters: FilterAccessCode = new FilterAccessCode(); const pageable: Pageable = new Pageable(); pageable.pageNumber = 0; pageable.pageSize = 1; filters.visitorId = visitorId; filters.pageable = pageable; return this.http.post(`${this.baseUrl}` + '/accesscodemanagement/v1/accesscode/cto/search', filters) .pipe( map(accesscodes => { if (accesscodes.content[0]) { return accesscodes.content[0].accessCode; } else { return null; } }), ); } deleteAccessCode(codeAccessId: number) { this.http.delete(`${this.baseUrl}` + '/accesscodemanagement/v1/accesscode/' + codeAccessId + '/').subscribe(); } saveAccessCode(visitorId: number, queueId: number) { const accessCode: AccessCode = new AccessCode(); accessCode.visitorId = visitorId; accessCode.queueId = queueId; return this.http.post(`${this.baseUrl}` + '/accesscodemanagement/v1/accesscode/', accessCode); } } ---- In the methods `getCurrentlyAttendedAccessCode` and `getVisitorAccessCode` we can see the use of `Pageable` and `FilterAccessCode` to match the `Criteria` in the backend like we explained in previous steps. In this case, the `getVisitorAccessCode` method will be used to see if the visitor has an `AccessCode` and the `getCurrentlyAttendedAccessCode` is going to recover the first `AccessCode` of the queue. - For the `QueueService` we are only going to need to find the active queue: [source, typescript] ---- import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Router } from '@angular/router'; import { Observable } from 'rxjs'; import { Queue, FilterQueue, Pageable } from 'src/app/shared/backendModels/interfaces'; import { environment } from 'src/environments/environment'; import { map } from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) export class QueueService { private baseUrl = environment.baseUrlRestServices; constructor(private router: Router, private http: HttpClient) { } getActiveQueue(): Observable { const filters: FilterQueue = new FilterQueue(); filters.active = true; const pageable: Pageable = new Pageable(); pageable.pageNumber = 0; pageable.pageSize = 1; pageable.sort = []; filters.pageable = pageable; return this.http.post(`${this.baseUrl}` + '/queuemanagement/v1/queue/search', filters) .pipe( map(queues => queues.content[0]), ); } } ---- Now we are going to create the template `view-queue.component.html` (which will use this data) and we will also introduce a new concept: ""_async pipes in templates_"". [source, html] ----

Your Number:

{{data.accessCodeVisitor.ticketNumber}}

Currently estimate time: 10:00:00

Currently Being Attended:

{{data.accessCodeAttended?.ticketNumber}}

The queue is not active try again later

---- If you watch closely, the starting `td-layout` has an `*ngIf` inside it. This `*ngIf` allows us to asynchronously pipe the observables that we will asign in the next steps. This solution avoids having to use `subscribe()` (as it subscribes automatically) and -- as a result -- we dont have to worry about where to `unsubscribe()` from the observables. In this HTML, we give `*ngif` another use: We use it to hide certain panels. Using `accessCodeVisitor`, we hide the ticket number panel and the ""leave the queue""-button and show the button to join the queue. On the contrary we can hide the ticket number and the ""leave the queue""-button and only show the ""join the queue""-button. [NOTE] ==== In this case, since we are using HTTP and the calls are finite, there wouldn't be any problems if you dont `unsubscribe()` from their corresponding observables. However, if -- for example -- we use an observable to keep track of an input and `subscribe()` to it but not controlling the `unsubscribe()` method, the app could end up containing a memory leak. This is because -- everytime we visit the component with the input -- it is going to create another subscription without unsubscribing from the last one. ==== Finally, to adapt the async pipe, the `ngOnInit()` method inside `view-queue.component.ts` now does not subscribe to the observable. In its place, we equal the queuers variable directly to the observable, so we can load it using `*ngIf`. [source, typescript] ---- import { Component, OnInit } from '@angular/core'; import { AccessCode, Queue } from '../shared/backendModels/interfaces'; import { Observable, timer } from 'rxjs'; import { AccessCodeService } from './services/access-code.service'; import { switchMap } from 'rxjs/operators'; import { AuthService } from '../core/authentication/auth.service'; import { QueueService } from './services/queue.service'; @Component({ selector: 'app-view-queue', templateUrl: './view-queue.component.html', styleUrls: ['./view-queue.component.scss'] }) export class ViewQueueComponent implements OnInit { accessCodeAttended$: Observable; accessCodeVisitor$: Observable; queue$: Observable; constructor(private accessCodeService: AccessCodeService, private queueService: QueueService, private authService: AuthService) { } ngOnInit() { // Every minute we are going to update accessCodeAttended$ starting instantly this.accessCodeAttended$ = timer(0, 60000).pipe( // we switchMap and give it the value necesary from the accessCodeService switchMap(() => { return this.accessCodeService.getCurrentlyAttendedAccessCode(); }) ); this.accessCodeVisitor$ = this.accessCodeService.getVisitorAccessCode(this.authService.getUserId()); this.queue$ = this.queueService.getActiveQueue(); } onJoinQueue(queueId: number): void { this.accessCodeVisitor$ = this.accessCodeService.saveAccessCode(this.authService.getUserId(), queueId); } onLeaveQueue(accessCodeId: number): void { this.accessCodeService.deleteAccessCode(accessCodeId); this.accessCodeVisitor$ = null; } } ---- In this last component we assign the `Observables` when the component is initiated. After that, when clicking the ""join the queue""-button, we assign a new `Observable` called `AccessCode` to the `accessCodeVisitor$`. Finally, when we leave the queue, we delete the `AccessCode` and set the `accessCodeVisitor` to null. Since we are using an async pipe, everytime we modify the status of the `Observables`, they are going to update the template. image::images/devon4ng/3.BuildYourOwn/withCodeAccess.png[Queue Page with Access Code, 250] image::images/devon4ng/3.BuildYourOwn/withoutCodeAccess.png[Queue Page without Access Code, 250] This is all on how to build your own devon4ng application. Now it's up to you to add features, change styles and do everything you can imagine doing with this app. As a final step to complete the tutorial, however, we are going to run the app outside of our local machine by deploying it. ''' *Next Chapter*: link:devon4ng-deployment.asciidoc[Deploy your devon4ng App] ",12303,False,2101.9947550440793,median "// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include ""ash/login/ui/login_auth_user_view.h"" #include #include #include #include ""ash/login/login_screen_controller.h"" #include ""ash/login/resources/grit/login_resources.h"" #include ""ash/login/ui/arrow_button_view.h"" #include ""ash/login/ui/horizontal_image_sequence_animation_decoder.h"" #include ""ash/login/ui/lock_screen.h"" #include ""ash/login/ui/login_display_style.h"" #include ""ash/login/ui/login_password_view.h"" #include ""ash/login/ui/login_pin_input_view.h"" #include ""ash/login/ui/login_pin_view.h"" #include ""ash/login/ui/login_user_view.h"" #include ""ash/login/ui/non_accessible_view.h"" #include ""ash/login/ui/pin_keyboard_animation.h"" #include ""ash/login/ui/pin_request_view.h"" #include ""ash/login/ui/system_label_button.h"" #include ""ash/login/ui/views_utils.h"" #include ""ash/public/cpp/login_constants.h"" #include ""ash/resources/vector_icons/vector_icons.h"" #include ""ash/session/session_controller_impl.h"" #include ""ash/shell.h"" #include ""ash/strings/grit/ash_strings.h"" #include ""ash/style/ash_color_provider.h"" #include ""ash/system/model/clock_model.h"" #include ""ash/system/model/system_tray_model.h"" #include ""ash/system/night_light/time_of_day.h"" #include ""ash/wallpaper/wallpaper_controller_impl.h"" #include ""base/bind.h"" #include ""base/i18n/time_formatting.h"" #include ""base/memory/ptr_util.h"" #include ""base/strings/utf_string_conversions.h"" #include ""base/time/time.h"" #include ""base/timer/timer.h"" #include ""components/user_manager/user.h"" #include ""ui/accessibility/ax_enums.mojom.h"" #include ""ui/accessibility/ax_node_data.h"" #include ""ui/base/l10n/l10n_util.h"" #include ""ui/base/resource/resource_bundle.h"" #include ""ui/compositor/callback_layer_animation_observer.h"" #include ""ui/compositor/layer_animation_sequence.h"" #include ""ui/compositor/layer_animator.h"" #include ""ui/compositor/scoped_layer_animation_settings.h"" #include ""ui/gfx/color_analysis.h"" #include ""ui/gfx/geometry/size.h"" #include ""ui/gfx/interpolated_transform.h"" #include ""ui/gfx/paint_vector_icon.h"" #include ""ui/gfx/vector_icon_types.h"" #include ""ui/views/background.h"" #include ""ui/views/border.h"" #include ""ui/views/controls/button/md_text_button.h"" #include ""ui/views/controls/highlight_path_generator.h"" #include ""ui/views/controls/label.h"" #include ""ui/views/layout/box_layout.h"" #include ""ui/views/layout/fill_layout.h"" #include ""ui/views/layout/flex_layout.h"" #include ""ui/views/layout/grid_layout.h"" #include ""ui/views/style/typography.h"" #include ""ui/views/view.h"" namespace ash { namespace { constexpr const char kLoginAuthUserViewClassName[] = ""LoginAuthUserView""; // Distance between the user view (ie, the icon and name) and other elements const int kDistanceBetweenUserViewAndPasswordDp = 24; const int kDistanceBetweenUserViewAndPinInputDp = 32; const int kDistanceBetweenUserViewAndOnlineSigninDp = 24; const int kDistanceBetweenUserViewAndChallengeResponseDp = 32; // Distance between the password textfield and the the pin keyboard. const int kDistanceBetweenPasswordFieldAndPinKeyboardDp = 16; // Height of button used for switching between pin and password authentication. const int kPinPasswordToggleButtonHeight = 32; const int kPinPasswordToggleButtonPaddingTop = 24; // Distance from the end of pin keyboard to the bottom of the big user view. const int kDistanceFromPinKeyboardToBigUserViewBottomDp = 50; // Distance from the top of the user view to the user icon. constexpr int kDistanceFromTopOfBigUserViewToUserIconDp = 24; // Date time format containing only the day of the week, for example: ""Tuesday"". constexpr char kDayOfWeekOnlyTimeFormat[] = ""EEEE""; constexpr int kFingerprintIconSizeDp = 28; constexpr int kResetToDefaultIconDelayMs = 1300; constexpr base::TimeDelta kResetToDefaultMessageDelayMs = base::TimeDelta::FromMilliseconds(3000); constexpr int kFingerprintIconTopSpacingDp = 20; constexpr int kSpacingBetweenFingerprintIconAndLabelDp = 15; constexpr int kFingerprintViewWidthDp = 204; constexpr int kDistanceBetweenPasswordFieldAndFingerprintViewDp = 90; constexpr int kFingerprintFailedAnimationDurationMs = 700; constexpr int kFingerprintFailedAnimationNumFrames = 45; constexpr base::TimeDelta kChallengeResponseResetAfterFailureDelay = base::TimeDelta::FromSeconds(5); constexpr int kChallengeResponseArrowSizeDp = 48; constexpr int kSpacingBetweenChallengeResponseArrowAndIconDp = 100; constexpr int kSpacingBetweenChallengeResponseIconAndLabelDp = 15; constexpr int kChallengeResponseIconSizeDp = 28; constexpr int kDistanceBetweenPwdFieldAndChallengeResponseViewDp = 0; constexpr int kDisabledAuthMessageVerticalBorderDp = 16; constexpr int kDisabledAuthMessageHorizontalBorderDp = 16; constexpr int kDisabledAuthMessageChildrenSpacingDp = 4; constexpr int kDisabledAuthMessageTimeWidthDp = 204; constexpr int kDisabledAuthMessageMultiprofileWidthDp = 304; constexpr int kDisabledAuthMessageHeightDp = 98; constexpr int kDisabledAuthMessageIconSizeDp = 24; constexpr int kDisabledAuthMessageTitleFontSizeDeltaDp = 3; constexpr int kDisabledAuthMessageContentsFontSizeDeltaDp = -1; constexpr int kDisabledAuthMessageRoundedCornerRadiusDp = 8; constexpr int kLockedTpmMessageVerticalBorderDp = 16; constexpr int kLockedTpmMessageHorizontalBorderDp = 16; constexpr int kLockedTpmMessageChildrenSpacingDp = 4; constexpr int kLockedTpmMessageWidthDp = 360; constexpr int kLockedTpmMessageHeightDp = 108; constexpr int kLockedTpmMessageIconSizeDp = 24; constexpr int kLockedTpmMessageDeltaDp = 0; constexpr int kLockedTpmMessageRoundedCornerRadiusDp = 8; constexpr int kNonEmptyWidthDp = 1; gfx::Size SizeFromHeight(int height) { return gfx::Size(kNonEmptyWidthDp, height); } // Returns an observer that will hide |view| when it fires. The observer will // delete itself after firing (by returning true). Make sure to call // |observer->SetActive()| after attaching it. ui::CallbackLayerAnimationObserver* BuildObserverToHideView(views::View* view) { return new ui::CallbackLayerAnimationObserver(base::BindRepeating( [](views::View* view, const ui::CallbackLayerAnimationObserver& observer) { // Don't hide the view if the animation is aborted, as |view| may no // longer be valid. if (observer.aborted_count()) return true; view->SetVisible(false); return true; }, view)); } ui::CallbackLayerAnimationObserver* BuildObserverToNotifyA11yLocationChanged( views::View* view) { return new ui::CallbackLayerAnimationObserver(base::BindRepeating( [](views::View* view, const ui::CallbackLayerAnimationObserver& observer) { // Don't notify a11y event if the animation is aborted, as |view| may no // longer be valid. if (observer.aborted_count()) return true; view->NotifyAccessibilityEvent(ax::mojom::Event::kLocationChanged, false /*send_native_event*/); return true; }, view)); } ui::CallbackLayerAnimationObserver* BuildObserverToNotifyA11yLocationChanged( LoginPinView* view) { return new ui::CallbackLayerAnimationObserver(base::BindRepeating( [](LoginPinView* view, const ui::CallbackLayerAnimationObserver& observer) { // Don't notify a11y event if the animation is aborted, as |view| may no // longer be valid. if (observer.aborted_count()) return true; view->NotifyAccessibilityLocationChanged(); return true; }, view)); } // Clears the password for the given |LoginPasswordView| instance, hides it, and // then deletes itself. class ClearPasswordAndHideAnimationObserver : public ui::ImplicitAnimationObserver { public: explicit ClearPasswordAndHideAnimationObserver(LoginPasswordView* view) : password_view_(view) {} ~ClearPasswordAndHideAnimationObserver() override = default; // ui::ImplicitAnimationObserver: void OnImplicitAnimationsCompleted() override { password_view_->Reset(); password_view_->SetVisible(false); delete this; } private: LoginPasswordView* const password_view_; DISALLOW_COPY_AND_ASSIGN(ClearPasswordAndHideAnimationObserver); }; // The label shown below the fingerprint icon. class FingerprintLabel : public views::Label { public: FingerprintLabel() { SetSubpixelRenderingEnabled(false); SetAutoColorReadabilityEnabled(false); SetEnabledColor(AshColorProvider::Get()->GetContentLayerColor( AshColorProvider::ContentLayerType::kTextColorSecondary)); SetMultiLine(true); SetTextBasedOnState(FingerprintState::AVAILABLE_DEFAULT, false /*can_use_pin*/); } void SetTextBasedOnAuthAttempt(bool success) { SetText(l10n_util::GetStringUTF16( success ? IDS_ASH_LOGIN_FINGERPRINT_UNLOCK_AUTH_SUCCESS : IDS_ASH_LOGIN_FINGERPRINT_UNLOCK_AUTH_FAILED)); SetAccessibleName(l10n_util::GetStringUTF16( success ? IDS_ASH_LOGIN_FINGERPRINT_UNLOCK_ACCESSIBLE_AUTH_SUCCESS : IDS_ASH_LOGIN_FINGERPRINT_UNLOCK_ACCESSIBLE_AUTH_FAILED)); } void SetTextBasedOnState(FingerprintState state, bool can_use_pin) { auto get_displayed_id = [&]() { switch (state) { case FingerprintState::UNAVAILABLE: case FingerprintState::AVAILABLE_DEFAULT: return IDS_ASH_LOGIN_FINGERPRINT_UNLOCK_AVAILABLE; case FingerprintState::AVAILABLE_WITH_TOUCH_SENSOR_WARNING: return IDS_ASH_LOGIN_FINGERPRINT_UNLOCK_TOUCH_SENSOR; case FingerprintState::DISABLED_FROM_ATTEMPTS: return IDS_ASH_LOGIN_FINGERPRINT_UNLOCK_DISABLED_FROM_ATTEMPTS; case FingerprintState::DISABLED_FROM_TIMEOUT: if (can_use_pin) return IDS_ASH_LOGIN_FINGERPRINT_UNLOCK_PIN_OR_PASSWORD_REQUIRED; return IDS_ASH_LOGIN_FINGERPRINT_UNLOCK_PASSWORD_REQUIRED; } NOTREACHED(); }; auto get_accessible_id = [&]() { if (state == FingerprintState::DISABLED_FROM_ATTEMPTS) return IDS_ASH_LOGIN_FINGERPRINT_UNLOCK_ACCESSIBLE_AUTH_DISABLED_FROM_ATTEMPTS; return get_displayed_id(); }; SetText(l10n_util::GetStringUTF16(get_displayed_id())); SetAccessibleName(l10n_util::GetStringUTF16(get_accessible_id())); } // views::View: void GetAccessibleNodeData(ui::AXNodeData* node_data) override { node_data->role = ax::mojom::Role::kStaticText; node_data->SetName(accessible_name_); } private: void SetAccessibleName(const base::string16& name) { accessible_name_ = name; NotifyAccessibilityEvent(ax::mojom::Event::kTextChanged, true /*send_native_event*/); } base::string16 accessible_name_; DISALLOW_COPY_AND_ASSIGN(FingerprintLabel); }; // The content needed to render the disabled auth message view. struct LockScreenMessage { base::string16 title; base::string16 content; const gfx::VectorIcon* icon; }; // Returns the message used when the device was locked due to a time window // limit. LockScreenMessage GetWindowLimitMessage(const base::Time& unlock_time, bool use_24hour_clock) { LockScreenMessage message; message.title = l10n_util::GetStringUTF16(IDS_ASH_LOGIN_TIME_FOR_BED_MESSAGE); base::Time local_midnight = base::Time::Now().LocalMidnight(); base::string16 time_to_display; if (use_24hour_clock) { time_to_display = base::TimeFormatTimeOfDayWithHourClockType( unlock_time, base::k24HourClock, base::kDropAmPm); } else { time_to_display = base::TimeFormatTimeOfDayWithHourClockType( unlock_time, base::k12HourClock, base::kKeepAmPm); } if (unlock_time < local_midnight + base::TimeDelta::FromDays(1)) { // Unlock time is today. message.content = l10n_util::GetStringFUTF16( IDS_ASH_LOGIN_COME_BACK_MESSAGE, time_to_display); } else if (unlock_time < local_midnight + base::TimeDelta::FromDays(2)) { // Unlock time is tomorrow. message.content = l10n_util::GetStringFUTF16( IDS_ASH_LOGIN_COME_BACK_TOMORROW_MESSAGE, time_to_display); } else { message.content = l10n_util::GetStringFUTF16( IDS_ASH_LOGIN_COME_BACK_DAY_OF_WEEK_MESSAGE, base::TimeFormatWithPattern(unlock_time, kDayOfWeekOnlyTimeFormat), time_to_display); } message.icon = &kLockScreenTimeLimitMoonIcon; return message; } // Returns the message used when the device was locked due to a time usage // limit. LockScreenMessage GetUsageLimitMessage(const base::TimeDelta& used_time) { LockScreenMessage message; // 1 minute is used instead of 0, because the device is used for a few // milliseconds before locking. if (used_time < base::TimeDelta::FromMinutes(1)) { // The device was locked all day. message.title = l10n_util::GetStringUTF16(IDS_ASH_LOGIN_TAKE_BREAK_MESSAGE); message.content = l10n_util::GetStringUTF16(IDS_ASH_LOGIN_LOCKED_ALL_DAY_MESSAGE); } else { // The usage limit is over. message.title = l10n_util::GetStringUTF16(IDS_ASH_LOGIN_TIME_IS_UP_MESSAGE); // TODO(933973): Stop displaying the hours part of the string when duration // is less than 1 hour. Example: change ""0 hours, 7 minutes"" to ""7 minutes"". base::string16 used_time_string; if (!base::TimeDurationFormat( used_time, base::DurationFormatWidth::DURATION_WIDTH_WIDE, &used_time_string)) { LOG(ERROR) << ""Failed to generate time duration string.""; return message; } message.content = l10n_util::GetStringFUTF16( IDS_ASH_LOGIN_SCREEN_TIME_USED_MESSAGE, used_time_string); } message.icon = &kLockScreenTimeLimitTimerIcon; return message; } // Returns the message used when the device was locked due to a time limit // override. LockScreenMessage GetOverrideMessage() { LockScreenMessage message; message.title = l10n_util::GetStringUTF16(IDS_ASH_LOGIN_TIME_FOR_A_BREAK_MESSAGE); message.content = l10n_util::GetStringUTF16(IDS_ASH_LOGIN_MANUAL_LOCK_MESSAGE); message.icon = &kLockScreenTimeLimitLockIcon; return message; } LockScreenMessage GetLockScreenMessage(AuthDisabledReason lock_reason, const base::Time& unlock_time, const base::TimeDelta& used_time, bool use_24hour_clock) { switch (lock_reason) { case AuthDisabledReason::kTimeWindowLimit: return GetWindowLimitMessage(unlock_time, use_24hour_clock); case AuthDisabledReason::kTimeUsageLimit: return GetUsageLimitMessage(used_time); case AuthDisabledReason::kTimeLimitOverride: return GetOverrideMessage(); default: NOTREACHED(); } } } // namespace // Consists of fingerprint icon view and a label. class LoginAuthUserView::FingerprintView : public views::View { public: FingerprintView() { SetPaintToLayer(); layer()->SetFillsBoundsOpaquely(false); SetBorder(views::CreateEmptyBorder(kFingerprintIconTopSpacingDp, 0, 0, 0)); auto* layout = SetLayoutManager(std::make_unique( views::BoxLayout::Orientation::kVertical, gfx::Insets(), kSpacingBetweenFingerprintIconAndLabelDp)); layout->set_main_axis_alignment( views::BoxLayout::MainAxisAlignment::kCenter); icon_ = new AnimatedRoundedImageView( gfx::Size(kFingerprintIconSizeDp, kFingerprintIconSizeDp), 0 /*corner_radius*/); icon_->SetImage(gfx::CreateVectorIcon( kLockScreenFingerprintIcon, kFingerprintIconSizeDp, AshColorProvider::Get()->GetContentLayerColor( AshColorProvider::ContentLayerType::kIconColorPrimary))); AddChildView(icon_); label_ = new FingerprintLabel(); AddChildView(label_); DisplayCurrentState(); } ~FingerprintView() override = default; void SetState(FingerprintState state) { if (state_ == state) return; reset_state_.Stop(); state_ = state; DisplayCurrentState(); if (ShouldFireChromeVoxAlert(state)) FireAlert(); } void SetCanUsePin(bool value) { if (can_use_pin_ == value) return; can_use_pin_ = value; label_->SetTextBasedOnState(state_, can_use_pin_); } void NotifyFingerprintAuthResult(bool success) { reset_state_.Stop(); label_->SetTextBasedOnAuthAttempt(success); if (success) { icon_->SetImage(gfx::CreateVectorIcon( kLockScreenFingerprintSuccessIcon, kFingerprintIconSizeDp, AshColorProvider::Get()->GetContentLayerColor( AshColorProvider::ContentLayerType::kIconColorPositive))); } else { SetIcon(FingerprintState::DISABLED_FROM_ATTEMPTS); // base::Unretained is safe because reset_state_ is owned by |this|. reset_state_.Start( FROM_HERE, base::TimeDelta::FromMilliseconds(kResetToDefaultIconDelayMs), base::BindOnce(&FingerprintView::DisplayCurrentState, base::Unretained(this))); FireAlert(); } } // views::View: gfx::Size CalculatePreferredSize() const override { gfx::Size size = views::View::CalculatePreferredSize(); size.set_width(kFingerprintViewWidthDp); return size; } // views::View: void OnGestureEvent(ui::GestureEvent* event) override { if (event->type() != ui::ET_GESTURE_TAP) return; if (state_ == FingerprintState::AVAILABLE_DEFAULT || state_ == FingerprintState::AVAILABLE_WITH_TOUCH_SENSOR_WARNING) { SetState(FingerprintState::AVAILABLE_WITH_TOUCH_SENSOR_WARNING); reset_state_.Start( FROM_HERE, kResetToDefaultMessageDelayMs, base::BindOnce(&FingerprintView::SetState, base::Unretained(this), FingerprintState::AVAILABLE_DEFAULT)); } } private: void DisplayCurrentState() { SetVisible(state_ != FingerprintState::UNAVAILABLE); SetIcon(state_); label_->SetTextBasedOnState(state_, can_use_pin_); } void FireAlert() { label_->NotifyAccessibilityEvent(ax::mojom::Event::kAlert, true /*send_native_event*/); } void SetIcon(FingerprintState state) { const SkColor icon_color = AshColorProvider::Get()->GetContentLayerColor( AshColorProvider::ContentLayerType::kIconColorPrimary); const SkColor color = state == FingerprintState::AVAILABLE_DEFAULT || state == FingerprintState::AVAILABLE_WITH_TOUCH_SENSOR_WARNING ? icon_color : AshColorProvider::Get()->GetDisabledColor(icon_color); switch (state) { case FingerprintState::UNAVAILABLE: case FingerprintState::AVAILABLE_DEFAULT: case FingerprintState::AVAILABLE_WITH_TOUCH_SENSOR_WARNING: case FingerprintState::DISABLED_FROM_TIMEOUT: icon_->SetImage(gfx::CreateVectorIcon(kLockScreenFingerprintIcon, kFingerprintIconSizeDp, color)); break; case FingerprintState::DISABLED_FROM_ATTEMPTS: icon_->SetAnimationDecoder( std::make_unique( *ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed( IDR_LOGIN_FINGERPRINT_UNLOCK_SPINNER), base::TimeDelta::FromMilliseconds( kFingerprintFailedAnimationDurationMs), kFingerprintFailedAnimationNumFrames), AnimatedRoundedImageView::Playback::kSingle); break; } } bool ShouldFireChromeVoxAlert(FingerprintState state) { return state == FingerprintState::DISABLED_FROM_ATTEMPTS || state == FingerprintState::DISABLED_FROM_TIMEOUT; } FingerprintLabel* label_ = nullptr; AnimatedRoundedImageView* icon_ = nullptr; base::OneShotTimer reset_state_; FingerprintState state_ = FingerprintState::AVAILABLE_DEFAULT; // Affects DISABLED_FROM_TIMEOUT message. bool can_use_pin_ = false; DISALLOW_COPY_AND_ASSIGN(FingerprintView); }; // Consists of challenge-response icon view and a label. class LoginAuthUserView::ChallengeResponseView : public views::View { public: enum class State { kInitial, kAuthenticating, kFailure }; explicit ChallengeResponseView(base::RepeatingClosure on_start_tap) : on_start_tap_(std::move(on_start_tap)) { SetPaintToLayer(); layer()->SetFillsBoundsOpaquely(false); auto* layout = SetLayoutManager(std::make_unique( views::BoxLayout::Orientation::kVertical)); layout->set_cross_axis_alignment( views::BoxLayout::CrossAxisAlignment::kCenter); auto arrow_button_view = std::make_unique( base::BindRepeating(&ChallengeResponseView::ArrowButtonPressed, base::Unretained(this)), kChallengeResponseArrowSizeDp); arrow_button_view->SetInstallFocusRingOnFocus(true); views::InstallCircleHighlightPathGenerator(arrow_button_view.get()); arrow_button_ = AddChildView(std::move(arrow_button_view)); arrow_button_->SetAccessibleName(l10n_util::GetStringUTF16( IDS_ASH_LOGIN_START_SMART_CARD_AUTH_BUTTON_ACCESSIBLE_NAME)); arrow_to_icon_spacer_ = AddChildView(std::make_unique()); arrow_to_icon_spacer_->SetPreferredSize( gfx::Size(0, kSpacingBetweenChallengeResponseArrowAndIconDp)); icon_ = AddChildView(std::make_unique()); icon_->SetImage(GetImageForIcon()); auto* icon_to_label_spacer = AddChildView(std::make_unique()); icon_to_label_spacer->SetPreferredSize( gfx::Size(0, kSpacingBetweenChallengeResponseIconAndLabelDp)); label_ = AddChildView(std::make_unique( GetTextForLabel(), views::style::CONTEXT_LABEL, views::style::STYLE_PRIMARY)); label_->SetAutoColorReadabilityEnabled(false); label_->SetEnabledColor(AshColorProvider::Get()->GetContentLayerColor( AshColorProvider::ContentLayerType::kTextColorSecondary)); label_->SetSubpixelRenderingEnabled(false); label_->SetFontList(views::Label::GetDefaultFontList().Derive( /*size_delta=*/1, gfx::Font::FontStyle::ITALIC, gfx::Font::Weight::NORMAL)); } ~ChallengeResponseView() override = default; void SetState(State state) { if (state_ == state) return; state_ = state; reset_state_timer_.Stop(); if (state == State::kFailure) { reset_state_timer_.Start( FROM_HERE, kChallengeResponseResetAfterFailureDelay, base::BindOnce(&ChallengeResponseView::SetState, base::Unretained(this), State::kInitial)); } arrow_button_->EnableLoadingAnimation(state == State::kAuthenticating); icon_->SetImage(GetImageForIcon()); label_->SetText(GetTextForLabel()); if (state == State::kFailure) { label_->NotifyAccessibilityEvent(ax::mojom::Event::kAlert, /*send_native_event=*/true); } Layout(); } void RequestFocus() override { arrow_button_->RequestFocus(); } views::Button* GetButtonForTesting() { return arrow_button_; } views::Label* GetLabelForTesting() { return label_; } private: gfx::ImageSkia GetImageForIcon() const { switch (state_) { case State::kInitial: case State::kAuthenticating: return gfx::CreateVectorIcon( kLockScreenSmartCardIcon, kChallengeResponseIconSizeDp, AshColorProvider::Get()->GetContentLayerColor( AshColorProvider::ContentLayerType::kIconColorPrimary)); case State::kFailure: return gfx::CreateVectorIcon( kLockScreenSmartCardFailureIcon, kChallengeResponseIconSizeDp, AshColorProvider::Get()->GetContentLayerColor( AshColorProvider::ContentLayerType::kIconColorAlert)); } } base::string16 GetTextForLabel() const { switch (state_) { case State::kInitial: case State::kAuthenticating: return l10n_util::GetStringUTF16( IDS_ASH_LOGIN_SMART_CARD_SIGN_IN_MESSAGE); case State::kFailure: return l10n_util::GetStringUTF16( IDS_ASH_LOGIN_SMART_CARD_SIGN_IN_FAILURE_MESSAGE); } } void ArrowButtonPressed() { // Ignore further clicks while handling the previous one. if (state_ != State::kAuthenticating) on_start_tap_.Run(); } base::RepeatingClosure on_start_tap_; State state_ = State::kInitial; ArrowButtonView* arrow_button_ = nullptr; NonAccessibleView* arrow_to_icon_spacer_ = nullptr; views::ImageView* icon_ = nullptr; views::Label* label_ = nullptr; base::OneShotTimer reset_state_timer_; DISALLOW_COPY_AND_ASSIGN(ChallengeResponseView); }; // The message shown to user when the auth method is |AUTH_DISABLED|. class LoginAuthUserView::DisabledAuthMessageView : public views::View { public: class ASH_EXPORT TestApi { public: explicit TestApi(DisabledAuthMessageView* view) : view_(view) {} ~TestApi() = default; const base::string16& GetDisabledAuthMessageContent() const { return view_->message_contents_->GetText(); } private: DisabledAuthMessageView* const view_; }; // If the reason of disabled auth is multiprofile policy, then we can already // set the text and message. Otherwise, in case of disabled auth because of // time limit exceeded on child account, we wait for SetAuthDisabledMessage to // be called. DisabledAuthMessageView(bool shown_because_of_multiprofile_policy, MultiProfileUserBehavior multiprofile_policy) : shown_because_of_multiprofile_policy_( shown_because_of_multiprofile_policy) { SetLayoutManager(std::make_unique( views::BoxLayout::Orientation::kVertical, gfx::Insets(kDisabledAuthMessageVerticalBorderDp, kDisabledAuthMessageHorizontalBorderDp), kDisabledAuthMessageChildrenSpacingDp)); SetPaintToLayer(); layer()->SetFillsBoundsOpaquely(false); SetPreferredSize(gfx::Size(shown_because_of_multiprofile_policy ? kDisabledAuthMessageMultiprofileWidthDp : kDisabledAuthMessageTimeWidthDp, kDisabledAuthMessageHeightDp)); SetFocusBehavior(FocusBehavior::ALWAYS); if (!shown_because_of_multiprofile_policy) { message_icon_ = new views::ImageView(); message_icon_->SetPreferredSize(gfx::Size( kDisabledAuthMessageIconSizeDp, kDisabledAuthMessageIconSizeDp)); message_icon_->SetImage(gfx::CreateVectorIcon( kLockScreenTimeLimitMoonIcon, kDisabledAuthMessageIconSizeDp, AshColorProvider::Get()->GetContentLayerColor( AshColorProvider::ContentLayerType::kIconColorPrimary))); AddChildView(message_icon_); } auto decorate_label = [](views::Label* label) { label->SetSubpixelRenderingEnabled(false); label->SetAutoColorReadabilityEnabled(false); label->SetEnabledColor(AshColorProvider::Get()->GetContentLayerColor( AshColorProvider::ContentLayerType::kTextColorPrimary)); label->SetFocusBehavior(FocusBehavior::ALWAYS); }; message_title_ = new views::Label(base::string16(), views::style::CONTEXT_LABEL, views::style::STYLE_PRIMARY); message_title_->SetFontList( gfx::FontList().Derive(kDisabledAuthMessageTitleFontSizeDeltaDp, gfx::Font::NORMAL, gfx::Font::Weight::MEDIUM)); decorate_label(message_title_); AddChildView(message_title_); message_contents_ = new views::Label(base::string16(), views::style::CONTEXT_LABEL, views::style::STYLE_PRIMARY); message_contents_->SetFontList( gfx::FontList().Derive(kDisabledAuthMessageContentsFontSizeDeltaDp, gfx::Font::NORMAL, gfx::Font::Weight::NORMAL)); decorate_label(message_contents_); message_contents_->SetMultiLine(true); AddChildView(message_contents_); if (shown_because_of_multiprofile_policy) { message_title_->SetText(l10n_util::GetStringUTF16( IDS_ASH_LOGIN_MULTI_PROFILES_RESTRICTED_POLICY_TITLE)); switch (multiprofile_policy) { case MultiProfileUserBehavior::PRIMARY_ONLY: message_contents_->SetText(l10n_util::GetStringUTF16( IDS_ASH_LOGIN_MULTI_PROFILES_PRIMARY_ONLY_POLICY_MSG)); break; case MultiProfileUserBehavior::NOT_ALLOWED: message_contents_->SetText(l10n_util::GetStringUTF16( IDS_ASH_LOGIN_MULTI_PROFILES_NOT_ALLOWED_POLICY_MSG)); break; case MultiProfileUserBehavior::OWNER_PRIMARY_ONLY: message_contents_->SetText(l10n_util::GetStringUTF16( IDS_ASH_LOGIN_MULTI_PROFILES_OWNER_PRIMARY_ONLY_MSG)); break; default: NOTREACHED(); } } } ~DisabledAuthMessageView() override = default; // Set the parameters needed to render the message. void SetAuthDisabledMessage(const AuthDisabledData& auth_disabled_data, bool use_24hour_clock) { // Do not do anything if message is already shown. if (shown_because_of_multiprofile_policy_) return; LockScreenMessage message = GetLockScreenMessage( auth_disabled_data.reason, auth_disabled_data.auth_reenabled_time, auth_disabled_data.device_used_time, use_24hour_clock); message_icon_->SetImage(gfx::CreateVectorIcon( *message.icon, kDisabledAuthMessageIconSizeDp, AshColorProvider::Get()->GetContentLayerColor( AshColorProvider::ContentLayerType::kIconColorPrimary))); message_title_->SetText(message.title); message_contents_->SetText(message.content); Layout(); } // views::View: void OnPaint(gfx::Canvas* canvas) override { views::View::OnPaint(canvas); cc::PaintFlags flags; flags.setStyle(cc::PaintFlags::kFill_Style); flags.setColor( PinRequestView::GetChildUserDialogColor(false /*using blur*/)); canvas->DrawRoundRect(GetContentsBounds(), kDisabledAuthMessageRoundedCornerRadiusDp, flags); } void RequestFocus() override { message_title_->RequestFocus(); } private: views::Label* message_title_; views::Label* message_contents_; views::ImageView* message_icon_; // Used in case a child account has triggered the disabled auth message // because of time limit exceeded while it also has disabled auth by // multiprofile policy. bool shown_because_of_multiprofile_policy_ = false; DISALLOW_COPY_AND_ASSIGN(DisabledAuthMessageView); }; // The message shown to user when TPM is locked. class LoginAuthUserView::LockedTpmMessageView : public views::View { public: LockedTpmMessageView() { SetLayoutManager(std::make_unique( views::BoxLayout::Orientation::kVertical, gfx::Insets(kLockedTpmMessageVerticalBorderDp, kLockedTpmMessageHorizontalBorderDp), kLockedTpmMessageChildrenSpacingDp)); SetPaintToLayer(); layer()->SetFillsBoundsOpaquely(false); SetPreferredSize( gfx::Size(kLockedTpmMessageWidthDp, kLockedTpmMessageHeightDp)); SetFocusBehavior(FocusBehavior::ALWAYS); auto message_icon = std::make_unique(); message_icon->SetPreferredSize( gfx::Size(kLockedTpmMessageIconSizeDp, kLockedTpmMessageIconSizeDp)); message_icon->SetImage(gfx::CreateVectorIcon( kLockScreenAlertIcon, AshColorProvider::Get()->GetContentLayerColor( AshColorProvider::ContentLayerType::kIconColorPrimary))); message_icon_ = AddChildView(std::move(message_icon)); message_warning_ = CreateLabel(); message_description_ = CreateLabel(); // Set content. base::string16 message_description = l10n_util::GetStringUTF16( IDS_ASH_LOGIN_POD_TPM_LOCKED_ISSUE_DESCRIPTION); message_description_->SetText(message_description); } LockedTpmMessageView(const LockedTpmMessageView&) = delete; LockedTpmMessageView& operator=(const LockedTpmMessageView&) = delete; ~LockedTpmMessageView() override = default; // Set the parameters needed to render the message. void SetRemainingTime(base::TimeDelta time_left) { base::string16 time_left_message; if (base::TimeDurationFormatWithSeconds( time_left, base::DurationFormatWidth::DURATION_WIDTH_WIDE, &time_left_message)) { base::string16 message_warning = l10n_util::GetStringFUTF16( IDS_ASH_LOGIN_POD_TPM_LOCKED_ISSUE_WARNING, time_left_message); message_warning_->SetText(message_warning); if (time_left.InMinutes() != prev_time_left_.InMinutes()) { message_warning_->NotifyAccessibilityEvent( ax::mojom::Event::kTextChanged, true); } prev_time_left_ = time_left; } } // views::View: void OnPaint(gfx::Canvas* canvas) override { views::View::OnPaint(canvas); cc::PaintFlags flags; flags.setStyle(cc::PaintFlags::kFill_Style); flags.setColor( PinRequestView::GetChildUserDialogColor(false /*using blur*/)); canvas->DrawRoundRect(GetContentsBounds(), kLockedTpmMessageRoundedCornerRadiusDp, flags); } void RequestFocus() override { message_warning_->RequestFocus(); } private: views::Label* CreateLabel() { auto label = std::make_unique(base::string16(), views::style::CONTEXT_LABEL, views::style::STYLE_PRIMARY); label->SetFontList(gfx::FontList().Derive(kLockedTpmMessageDeltaDp, gfx::Font::NORMAL, gfx::Font::Weight::NORMAL)); label->SetSubpixelRenderingEnabled(false); label->SetAutoColorReadabilityEnabled(false); label->SetEnabledColor(AshColorProvider::Get()->GetContentLayerColor( AshColorProvider::ContentLayerType::kTextColorPrimary)); label->SetFocusBehavior(FocusBehavior::ALWAYS); label->SetMultiLine(true); return AddChildView(std::move(label)); } base::TimeDelta prev_time_left_; views::Label* message_warning_; views::Label* message_description_; views::ImageView* message_icon_; }; LoginAuthUserView::AuthMethodsMetadata::AuthMethodsMetadata() = default; LoginAuthUserView::AuthMethodsMetadata::~AuthMethodsMetadata() = default; LoginAuthUserView::AuthMethodsMetadata::AuthMethodsMetadata( const AuthMethodsMetadata&) = default; struct LoginAuthUserView::UiState { explicit UiState(const LoginAuthUserView* view) { has_password = view->ShouldShowPasswordField(); has_pin_input = view->ShouldShowPinInputField(); has_pinpad = view->ShouldShowPinPad(); has_toggle = view->ShouldShowToggle(); has_fingerprint = view->HasAuthMethod(LoginAuthUserView::AUTH_FINGERPRINT); has_challenge_response = view->HasAuthMethod(LoginAuthUserView::AUTH_CHALLENGE_RESPONSE); auth_disabled = view->HasAuthMethod(LoginAuthUserView::AUTH_DISABLED); tpm_is_locked = view->HasAuthMethod(LoginAuthUserView::AUTH_DISABLED_TPM_LOCKED); force_online_sign_in = view->HasAuthMethod(LoginAuthUserView::AUTH_ONLINE_SIGN_IN); non_pin_y_start_in_screen = view->GetBoundsInScreen().y(); pin_start_in_screen = view->pin_view_->GetBoundsInScreen().origin(); } bool has_password = false; bool has_pin_input = false; bool has_pinpad = false; bool has_toggle = false; bool has_fingerprint = false; bool has_challenge_response = false; bool auth_disabled = false; bool tpm_is_locked = false; bool force_online_sign_in = false; // Used for this view's animation in `ApplyAnimationPostLayout`. int non_pin_y_start_in_screen = 0; gfx::Point pin_start_in_screen; }; LoginAuthUserView::TestApi::TestApi(LoginAuthUserView* view) : view_(view) {} LoginAuthUserView::TestApi::~TestApi() = default; LoginUserView* LoginAuthUserView::TestApi::user_view() const { return view_->user_view_; } LoginPasswordView* LoginAuthUserView::TestApi::password_view() const { return view_->password_view_; } LoginPinView* LoginAuthUserView::TestApi::pin_view() const { return view_->pin_view_; } LoginPinInputView* LoginAuthUserView::TestApi::pin_input_view() const { return view_->pin_input_view_; } views::Button* LoginAuthUserView::TestApi::pin_password_toggle() const { return view_->pin_password_toggle_; } views::Button* LoginAuthUserView::TestApi::online_sign_in_message() const { return view_->online_sign_in_message_; } views::View* LoginAuthUserView::TestApi::disabled_auth_message() const { return view_->disabled_auth_message_; } views::Button* LoginAuthUserView::TestApi::challenge_response_button() { return view_->challenge_response_view_->GetButtonForTesting(); } views::Label* LoginAuthUserView::TestApi::challenge_response_label() { return view_->challenge_response_view_->GetLabelForTesting(); } bool LoginAuthUserView::TestApi::HasAuthMethod(AuthMethods auth_method) const { return view_->HasAuthMethod(auth_method); } const base::string16& LoginAuthUserView::TestApi::GetDisabledAuthMessageContent() const { return LoginAuthUserView::DisabledAuthMessageView::TestApi( view_->disabled_auth_message_) .GetDisabledAuthMessageContent(); } LoginAuthUserView::Callbacks::Callbacks() = default; LoginAuthUserView::Callbacks::Callbacks(const Callbacks& other) = default; LoginAuthUserView::Callbacks::~Callbacks() = default; LoginAuthUserView::LoginAuthUserView(const LoginUserInfo& user, const Callbacks& callbacks) : NonAccessibleView(kLoginAuthUserViewClassName), on_auth_(callbacks.on_auth), on_tap_(callbacks.on_tap) { DCHECK(callbacks.on_auth); DCHECK(callbacks.on_tap); DCHECK(callbacks.on_remove_warning_shown); DCHECK(callbacks.on_remove); DCHECK(callbacks.on_easy_unlock_icon_hovered); DCHECK_NE(user.basic_user_info.type, user_manager::USER_TYPE_PUBLIC_ACCOUNT); // Build child views. auto user_view = std::make_unique( LoginDisplayStyle::kLarge, true /*show_dropdown*/, base::BindRepeating(&LoginAuthUserView::OnUserViewTap, base::Unretained(this)), callbacks.on_remove_warning_shown, callbacks.on_remove); user_view_ = user_view.get(); const LoginPalette palette = CreateDefaultLoginPalette(); auto password_view = std::make_unique(palette); password_view_ = password_view.get(); password_view->SetPaintToLayer(); // Needed for opacity animation. password_view->layer()->SetFillsBoundsOpaquely(false); password_view_->SetDisplayPasswordButtonVisible( user.show_display_password_button); password_view->Init( base::BindRepeating(&LoginAuthUserView::OnAuthSubmit, base::Unretained(this)), base::BindRepeating(&LoginAuthUserView::OnPasswordTextChanged, base::Unretained(this)), callbacks.on_easy_unlock_icon_hovered, callbacks.on_easy_unlock_icon_tapped); auto pin_input_view = std::make_unique(palette); pin_input_view_ = pin_input_view.get(); pin_input_view->Init(base::BindRepeating(&LoginAuthUserView::OnAuthSubmit, base::Unretained(this)), base::BindRepeating(&LoginAuthUserView::OnPinTextChanged, base::Unretained(this))); auto toggle_container = std::make_unique(); toggle_container->SetLayoutManager(std::make_unique( views::BoxLayout::Orientation::kVertical, gfx::Insets(kPinPasswordToggleButtonPaddingTop, 0, 0, 0))); pin_password_toggle_ = toggle_container->AddChildView(std::make_unique( base::BindRepeating(&LoginAuthUserView::OnSwitchButtonClicked, base::Unretained(this)), GetPinPasswordToggleText(), SystemLabelButton::DisplayType::DEFAULT, /*multiline*/ false)); pin_password_toggle_->SetMaxSize( gfx::Size(/*ignored*/ 0, kPinPasswordToggleButtonHeight)); auto pin_view = std::make_unique( LoginPinView::Style::kAlphanumeric, palette, base::BindRepeating(&LoginAuthUserView::OnPinPadInsertDigit, base::Unretained(this)), base::BindRepeating(&LoginAuthUserView::OnPinPadBackspace, base::Unretained(this))); pin_view_ = pin_view.get(); DCHECK(pin_view_->layer()); auto padding_below_password_view = std::make_unique(); padding_below_password_view->SetPreferredSize(gfx::Size( kNonEmptyWidthDp, kDistanceBetweenPasswordFieldAndPinKeyboardDp)); padding_below_password_view_ = padding_below_password_view.get(); auto padding_below_user_view = std::make_unique(); padding_below_user_view->SetPreferredSize( gfx::Size(kNonEmptyWidthDp, kDistanceBetweenUserViewAndPasswordDp)); padding_below_user_view_ = padding_below_user_view.get(); base::string16 button_message = l10n_util::GetStringUTF16(IDS_ASH_LOGIN_SIGN_IN_REQUIRED_MESSAGE); if (user.is_signed_in) { button_message = l10n_util::GetStringUTF16(IDS_ASH_LOCK_SCREEN_VERIFY_ACCOUNT_MESSAGE); } bool is_login_secondary = Shell::Get()->session_controller()->GetSessionState() == session_manager::SessionState::LOGIN_SECONDARY; auto online_sign_in_button = std::make_unique( base::BindRepeating(&LoginAuthUserView::OnOnlineSignInMessageTap, base::Unretained(this)), button_message, SystemLabelButton::DisplayType::ALERT_WITH_ICON, /*multiline*/ false); // Disable online sign-in on secondary login screen as there is no OOBE there. online_sign_in_button->SetEnabled(!is_login_secondary); online_sign_in_message_ = online_sign_in_button.get(); bool shown_because_of_multiprofile_policy = !user.is_multiprofile_allowed && is_login_secondary; auto disabled_auth_message = std::make_unique( shown_because_of_multiprofile_policy, user.multiprofile_policy); disabled_auth_message_ = disabled_auth_message.get(); auto locked_tpm_message_view = std::make_unique(); locked_tpm_message_view_ = locked_tpm_message_view.get(); auto fingerprint_view = std::make_unique(); fingerprint_view_ = fingerprint_view.get(); auto challenge_response_view = std::make_unique(base::BindRepeating( &LoginAuthUserView::AttemptAuthenticateWithChallengeResponse, weak_factory_.GetWeakPtr())); challenge_response_view_ = challenge_response_view.get(); SetPaintToLayer(ui::LayerType::LAYER_NOT_DRAWN); // Build layout. auto wrapped_password_view = login_views_utils::WrapViewForPreferredSize(std::move(password_view)); auto wrapped_online_sign_in_message_view = login_views_utils::WrapViewForPreferredSize( std::move(online_sign_in_button)); auto wrapped_disabled_auth_message_view = login_views_utils::WrapViewForPreferredSize( std::move(disabled_auth_message)); auto wrapped_locked_tpm_message_view = login_views_utils::WrapViewForPreferredSize( std::move(locked_tpm_message_view)); auto wrapped_user_view = login_views_utils::WrapViewForPreferredSize(std::move(user_view)); auto wrapped_pin_view = login_views_utils::WrapViewForPreferredSize(std::move(pin_view)); auto wrapped_pin_input_view = login_views_utils::WrapViewForPreferredSize(std::move(pin_input_view)); auto wrapped_pin_password_toggle_view = login_views_utils::WrapViewForPreferredSize(std::move(toggle_container)); auto wrapped_fingerprint_view = login_views_utils::WrapViewForPreferredSize(std::move(fingerprint_view)); auto wrapped_challenge_response_view = login_views_utils::WrapViewForPreferredSize( std::move(challenge_response_view)); auto wrapped_padding_below_password_view = login_views_utils::WrapViewForPreferredSize( std::move(padding_below_password_view)); auto wrapped_padding_below_user_view = login_views_utils::WrapViewForPreferredSize( std::move(padding_below_user_view)); // Add views in tabbing order; they are rendered in a different order below. views::View* wrapped_password_view_ptr = AddChildView(std::move(wrapped_password_view)); views::View* wrapped_online_sign_in_message_view_ptr = AddChildView(std::move(wrapped_online_sign_in_message_view)); views::View* wrapped_disabled_auth_message_view_ptr = AddChildView(std::move(wrapped_disabled_auth_message_view)); views::View* wrapped_locked_tpm_message_view_ptr = AddChildView(std::move(wrapped_locked_tpm_message_view)); views::View* wrapped_pin_input_view_ptr = AddChildView(std::move(wrapped_pin_input_view)); views::View* wrapped_pin_view_ptr = AddChildView(std::move(wrapped_pin_view)); views::View* wrapped_pin_password_toggle_view_ptr = AddChildView(std::move(wrapped_pin_password_toggle_view)); views::View* wrapped_fingerprint_view_ptr = AddChildView(std::move(wrapped_fingerprint_view)); views::View* wrapped_challenge_response_view_ptr = AddChildView(std::move(wrapped_challenge_response_view)); views::View* wrapped_user_view_ptr = AddChildView(std::move(wrapped_user_view)); views::View* wrapped_padding_below_password_view_ptr = AddChildView(std::move(wrapped_padding_below_password_view)); views::View* wrapped_padding_below_user_view_ptr = AddChildView(std::move(wrapped_padding_below_user_view)); // Use views::GridLayout instead of views::BoxLayout because views::BoxLayout // lays out children according to the view->children order. views::GridLayout* grid_layout = SetLayoutManager(std::make_unique()); views::ColumnSet* column_set = grid_layout->AddColumnSet(0); column_set->AddColumn(views::GridLayout::CENTER, views::GridLayout::LEADING, 0 /*resize_percent*/, views::GridLayout::ColumnSize::kUsePreferred, 0 /*fixed_width*/, 0 /*min_width*/); auto add_view = [&](views::View* view) { grid_layout->StartRow(0 /*vertical_resize*/, 0 /*column_set_id*/); grid_layout->AddExistingView(view); }; auto add_padding = [&](int amount) { grid_layout->AddPaddingRow(0 /*vertical_resize*/, amount /*size*/); }; // Add views in rendering order. add_padding(kDistanceFromTopOfBigUserViewToUserIconDp); add_view(wrapped_user_view_ptr); add_view(wrapped_padding_below_user_view_ptr); add_view(wrapped_locked_tpm_message_view_ptr); add_view(wrapped_password_view_ptr); add_view(wrapped_online_sign_in_message_view_ptr); add_view(wrapped_disabled_auth_message_view_ptr); add_view(wrapped_pin_input_view_ptr); add_view(wrapped_padding_below_password_view_ptr); add_view(wrapped_pin_view_ptr); add_view(wrapped_pin_password_toggle_view_ptr); add_view(wrapped_fingerprint_view_ptr); add_view(wrapped_challenge_response_view_ptr); add_padding(kDistanceFromPinKeyboardToBigUserViewBottomDp); // Update authentication UI. CaptureStateForAnimationPreLayout(); SetAuthMethods(auth_methods_); ApplyAnimationPostLayout(/*animate*/ false); user_view_->UpdateForUser(user, /*animate*/ false); } LoginAuthUserView::~LoginAuthUserView() = default; void LoginAuthUserView::SetAuthMethods( uint32_t auth_methods, const AuthMethodsMetadata& auth_metadata) { // It is an error to call this method without storing the previous state. DCHECK(previous_state_); // Apply changes and determine the new state of input fields. auth_methods_ = static_cast(auth_methods); auth_metadata_ = auth_metadata; UpdateInputFieldMode(); const UiState current_state{this}; online_sign_in_message_->SetVisible(current_state.force_online_sign_in); disabled_auth_message_->SetVisible(current_state.auth_disabled); locked_tpm_message_view_->SetVisible(current_state.tpm_is_locked); if (current_state.tpm_is_locked && auth_metadata.time_until_tpm_unlock.has_value()) locked_tpm_message_view_->SetRemainingTime( auth_metadata.time_until_tpm_unlock.value()); // Adjust the PIN keyboard visibility before the password textfield's one, so // that when both are about to be hidden the focus doesn't jump to the ""1"" // keyboard button, causing unexpected accessibility effects. pin_view_->SetVisible(current_state.has_pinpad); password_view_->SetEnabled(current_state.has_password); password_view_->SetEnabledOnEmptyPassword(HasAuthMethod(AUTH_TAP)); password_view_->SetFocusEnabledForTextfield(current_state.has_password); password_view_->SetVisible(current_state.has_password); password_view_->layer()->SetOpacity(current_state.has_password ? 1 : 0); pin_input_view_->UpdateLength(auth_metadata_.autosubmit_pin_length); pin_input_view_->SetAuthenticateWithEmptyPinOnReturnKey( HasAuthMethod(AUTH_TAP)); pin_input_view_->SetVisible(current_state.has_pin_input); pin_password_toggle_->SetVisible(current_state.has_toggle); pin_password_toggle_->SetText(GetPinPasswordToggleText()); fingerprint_view_->SetVisible(current_state.has_fingerprint); fingerprint_view_->SetCanUsePin(HasAuthMethod(AUTH_PIN)); challenge_response_view_->SetVisible(current_state.has_challenge_response); padding_below_user_view_->SetPreferredSize(GetPaddingBelowUserView()); padding_below_password_view_->SetPreferredSize(GetPaddingBelowPasswordView()); password_view_->SetPlaceholderText(GetPasswordViewPlaceholder()); const std::string& user_display_email = current_user().basic_user_info.display_email; password_view_->SetAccessibleName(l10n_util::GetStringFUTF16( IDS_ASH_LOGIN_POD_PASSWORD_FIELD_ACCESSIBLE_NAME, base::UTF8ToUTF16(user_display_email))); // Only the active auth user view has authentication methods. If that is the // case, then render the user view as if it was always focused, since clicking // on it will not do anything (such as swapping users). user_view_->SetForceOpaque(auth_methods_ != AUTH_NONE); user_view_->SetTapEnabled(auth_methods_ == AUTH_NONE); UpdateFocus(); PreferredSizeChanged(); } void LoginAuthUserView::SetEasyUnlockIcon( EasyUnlockIconId id, const base::string16& accessibility_label) { password_view_->SetEasyUnlockIcon(id, accessibility_label); const std::string& user_display_email = current_user().basic_user_info.display_email; if (id == EasyUnlockIconId::UNLOCKED) { password_view_->SetAccessibleName(l10n_util::GetStringFUTF16( IDS_ASH_LOGIN_POD_AUTH_TAP_PASSWORD_FIELD_ACCESSIBLE_NAME, base::UTF8ToUTF16(user_display_email))); } else { password_view_->SetAccessibleName(l10n_util::GetStringFUTF16( IDS_ASH_LOGIN_POD_PASSWORD_FIELD_ACCESSIBLE_NAME, base::UTF8ToUTF16(user_display_email))); } } void LoginAuthUserView::CaptureStateForAnimationPreLayout() { auto stop_animation = [](views::View* view) { if (view->layer()->GetAnimator()->is_animating()) view->layer()->GetAnimator()->StopAnimating(); }; // Stop any running animation scheduled in ApplyAnimationPostLayout. stop_animation(this); stop_animation(password_view_); stop_animation(pin_view_); stop_animation(fingerprint_view_); stop_animation(challenge_response_view_); stop_animation(pin_password_toggle_); DCHECK(!previous_state_); previous_state_ = std::make_unique(this); } void LoginAuthUserView::ApplyAnimationPostLayout(bool animate) { DCHECK(previous_state_); // Release the previous state if no animation should be performed. if (!animate) { previous_state_.reset(); return; } const UiState current_state{this}; //////// // Animate the user info (ie, icon, name) up or down the screen. { int non_pin_y_end_in_screen = GetBoundsInScreen().y(); // Transform the layer so the user view renders where it used to be. This // requires a y offset. // Note: Doing this animation via ui::ScopedLayerAnimationSettings works, // but it seems that the timing gets slightly out of sync with the PIN // animation. auto move_to_center = std::make_unique( gfx::PointF(0, previous_state_->non_pin_y_start_in_screen - non_pin_y_end_in_screen), gfx::PointF()); auto transition = ui::LayerAnimationElement::CreateInterpolatedTransformElement( std::move(move_to_center), base::TimeDelta::FromMilliseconds( login_constants::kChangeUserAnimationDurationMs)); transition->set_tween_type(gfx::Tween::Type::FAST_OUT_SLOW_IN); auto* sequence = new ui::LayerAnimationSequence(std::move(transition)); auto* observer = BuildObserverToNotifyA11yLocationChanged(this); sequence->AddObserver(observer); observer->SetActive(); layer()->GetAnimator()->StartAnimation(sequence); } //////// // Fade the password view if it is being hidden or shown. if (current_state.has_password != previous_state_->has_password) { float opacity_start = 0, opacity_end = 1; if (!current_state.has_password) std::swap(opacity_start, opacity_end); password_view_->layer()->SetOpacity(opacity_start); { ui::ScopedLayerAnimationSettings settings( password_view_->layer()->GetAnimator()); settings.SetTransitionDuration(base::TimeDelta::FromMilliseconds( login_constants::kChangeUserAnimationDurationMs)); settings.SetTweenType(gfx::Tween::Type::FAST_OUT_SLOW_IN); if (previous_state_->has_password && !current_state.has_password) { settings.AddObserver( new ClearPasswordAndHideAnimationObserver(password_view_)); } password_view_->layer()->SetOpacity(opacity_end); } } //////// // Fade the pin/pwd toggle if its being hidden or shown. if (previous_state_->has_toggle != current_state.has_toggle) { float opacity_start = 0, opacity_end = 1; if (!current_state.has_toggle) std::swap(opacity_start, opacity_end); pin_password_toggle_->layer()->SetOpacity(opacity_start); { ui::ScopedLayerAnimationSettings settings( pin_password_toggle_->layer()->GetAnimator()); settings.SetTransitionDuration(base::TimeDelta::FromMilliseconds( login_constants::kChangeUserAnimationDurationMs)); settings.SetTweenType(gfx::Tween::Type::FAST_OUT_SLOW_IN); pin_password_toggle_->layer()->SetOpacity(opacity_end); } } //////// // Grow/shrink the PIN keyboard if it is being hidden or shown. if (previous_state_->has_pinpad != current_state.has_pinpad) { if (!current_state.has_pinpad) { gfx::Point pin_end_in_screen = pin_view_->GetBoundsInScreen().origin(); gfx::Rect pin_bounds = pin_view_->bounds(); pin_bounds.set_x(previous_state_->pin_start_in_screen.x() - pin_end_in_screen.x()); pin_bounds.set_y(previous_state_->pin_start_in_screen.y() - pin_end_in_screen.y()); // Since PIN is disabled, the previous Layout() hid the PIN keyboard. // We need to redisplay it where it used to be. // pin_view_->SetVisible(true); pin_view_->SetBoundsRect(pin_bounds); } auto transition = std::make_unique( current_state.has_pinpad /*grow*/, pin_view_->height(), // TODO(https://crbug.com/955119): Implement proper animation. base::TimeDelta::FromMilliseconds( login_constants::kChangeUserAnimationDurationMs / 2.0f), gfx::Tween::FAST_OUT_SLOW_IN); auto* sequence = new ui::LayerAnimationSequence(std::move(transition)); // Hide the PIN keyboard after animation if needed. if (!current_state.has_pinpad) { auto* observer = BuildObserverToHideView(pin_view_); sequence->AddObserver(observer); observer->SetActive(); } auto* observer = BuildObserverToNotifyA11yLocationChanged(pin_view_); sequence->AddObserver(observer); observer->SetActive(); pin_view_->layer()->GetAnimator()->ScheduleAnimation(sequence); } //////// // Fade the fingerprint view if it is being hidden or shown. if (previous_state_->has_fingerprint != current_state.has_fingerprint) { float opacity_start = 0, opacity_end = 1; if (!current_state.has_fingerprint) std::swap(opacity_start, opacity_end); fingerprint_view_->layer()->SetOpacity(opacity_start); { ui::ScopedLayerAnimationSettings settings( fingerprint_view_->layer()->GetAnimator()); settings.SetTransitionDuration(base::TimeDelta::FromMilliseconds( login_constants::kChangeUserAnimationDurationMs)); settings.SetTweenType(gfx::Tween::Type::FAST_OUT_SLOW_IN); fingerprint_view_->layer()->SetOpacity(opacity_end); } } //////// // Fade the challenge response (Smart Card) if it is being hidden or shown. if (previous_state_->has_challenge_response != current_state.has_challenge_response) { float opacity_start = 0, opacity_end = 1; if (!current_state.has_challenge_response) std::swap(opacity_start, opacity_end); challenge_response_view_->layer()->SetOpacity(opacity_start); { ui::ScopedLayerAnimationSettings settings( challenge_response_view_->layer()->GetAnimator()); settings.SetTransitionDuration(base::TimeDelta::FromMilliseconds( login_constants::kChangeUserAnimationDurationMs)); settings.SetTweenType(gfx::Tween::Type::FAST_OUT_SLOW_IN); challenge_response_view_->layer()->SetOpacity(opacity_end); } } previous_state_.reset(); } void LoginAuthUserView::UpdateForUser(const LoginUserInfo& user) { const bool user_changed = current_user().basic_user_info.account_id != user.basic_user_info.account_id; user_view_->UpdateForUser(user, true /*animate*/); if (user_changed) { password_view_->Reset(); password_view_->SetDisplayPasswordButtonVisible( user.show_display_password_button); } online_sign_in_message_->SetText( l10n_util::GetStringUTF16(IDS_ASH_LOGIN_SIGN_IN_REQUIRED_MESSAGE)); } void LoginAuthUserView::SetFingerprintState(FingerprintState state) { fingerprint_view_->SetState(state); } void LoginAuthUserView::NotifyFingerprintAuthResult(bool success) { fingerprint_view_->NotifyFingerprintAuthResult(success); } void LoginAuthUserView::SetAuthDisabledMessage( const AuthDisabledData& auth_disabled_data) { disabled_auth_message_->SetAuthDisabledMessage( auth_disabled_data, current_user().use_24hour_clock); Layout(); } const LoginUserInfo& LoginAuthUserView::current_user() const { return user_view_->current_user(); } views::View* LoginAuthUserView::GetActiveInputView() { if (input_field_mode_ == InputFieldMode::PIN_WITH_TOGGLE) return pin_input_view_; return password_view_; } gfx::Size LoginAuthUserView::CalculatePreferredSize() const { gfx::Size size = views::View::CalculatePreferredSize(); // Make sure we are at least as big as the user view. If we do not do this the // view will be below minimum size when no auth methods are displayed. size.SetToMax(user_view_->GetPreferredSize()); return size; } void LoginAuthUserView::RequestFocus() { if (input_field_mode_ == InputFieldMode::PIN_WITH_TOGGLE) pin_input_view_->RequestFocus(); else password_view_->RequestFocus(); } void LoginAuthUserView::OnAuthSubmit(const base::string16& password) { // Pressing enter when the password field is empty and tap-to-unlock is // enabled should attempt unlock. if (HasAuthMethod(AUTH_TAP) && password.empty()) { Shell::Get()->login_screen_controller()->AuthenticateUserWithEasyUnlock( current_user().basic_user_info.account_id); return; } password_view_->SetReadOnly(true); pin_input_view_->SetReadOnly(true); Shell::Get()->login_screen_controller()->AuthenticateUserWithPasswordOrPin( current_user().basic_user_info.account_id, base::UTF16ToUTF8(password), ShouldAuthenticateWithPin(), base::BindOnce(&LoginAuthUserView::OnAuthComplete, weak_factory_.GetWeakPtr())); } void LoginAuthUserView::OnAuthComplete(base::Optional auth_success) { // Clear the password only if auth fails. Make sure to keep the password view // disabled even if auth succeededs, as if the user submits a password while // animating the next lock screen will not work as expected. See // https://crbug.com/808486. if (!auth_success.has_value() || !auth_success.value()) { password_view_->Reset(); password_view_->SetReadOnly(false); pin_input_view_->Reset(); pin_input_view_->SetReadOnly(false); } on_auth_.Run(auth_success.value(), /*display_error_messages=*/true); } void LoginAuthUserView::OnChallengeResponseAuthComplete( base::Optional auth_success) { if (!auth_success.has_value() || !auth_success.value()) { password_view_->Reset(); password_view_->SetReadOnly(false); // If the user canceled the PIN request during ChallengeResponse, // ChallengeResponse will fail with an unknown error. Since this is // expected, we do not show this error. if (Shell::Get() ->login_screen_controller() ->GetSecurityTokenPinRequestCanceled()) { challenge_response_view_->SetState( ChallengeResponseView::State::kInitial); } else { challenge_response_view_->SetState( ChallengeResponseView::State::kFailure); } } on_auth_.Run(auth_success.value_or(false), /*display_error_messages=*/false); } void LoginAuthUserView::OnUserViewTap() { if (HasAuthMethod(AUTH_TAP)) { Shell::Get()->login_screen_controller()->AuthenticateUserWithEasyUnlock( current_user().basic_user_info.account_id); } else if (HasAuthMethod(AUTH_ONLINE_SIGN_IN)) { // Tapping anywhere in the user view is the same with tapping the message. OnOnlineSignInMessageTap(); } else { on_tap_.Run(); } } void LoginAuthUserView::OnOnlineSignInMessageTap() { // Do not show on secondary login screen as there is no OOBE there. if (Shell::Get()->session_controller()->GetSessionState() == session_manager::SessionState::LOGIN_SECONDARY) { return; } Shell::Get()->login_screen_controller()->ShowGaiaSignin( current_user().basic_user_info.account_id); } void LoginAuthUserView::OnPinPadBackspace() { DCHECK(pin_input_view_); DCHECK(password_view_); if (input_field_mode_ == InputFieldMode::PIN_WITH_TOGGLE) pin_input_view_->Backspace(); else password_view_->Backspace(); } void LoginAuthUserView::OnPinPadInsertDigit(int digit) { DCHECK(pin_input_view_); DCHECK(password_view_); if (input_field_mode_ == InputFieldMode::PIN_WITH_TOGGLE) pin_input_view_->InsertDigit(digit); else password_view_->InsertNumber(digit); } void LoginAuthUserView::OnPasswordTextChanged(bool is_empty) { DCHECK(pin_view_); if (input_field_mode_ != InputFieldMode::PIN_WITH_TOGGLE) pin_view_->OnPasswordTextChanged(is_empty); } void LoginAuthUserView::OnPinTextChanged(bool is_empty) { DCHECK(pin_view_); if (input_field_mode_ == InputFieldMode::PIN_WITH_TOGGLE) pin_view_->OnPasswordTextChanged(is_empty); } bool LoginAuthUserView::HasAuthMethod(AuthMethods auth_method) const { return (auth_methods_ & auth_method) != 0; } bool LoginAuthUserView::ShouldAuthenticateWithPin() const { return input_field_mode_ == InputFieldMode::PIN_AND_PASSWORD || input_field_mode_ == InputFieldMode::PIN_WITH_TOGGLE; } void LoginAuthUserView::AttemptAuthenticateWithChallengeResponse() { challenge_response_view_->SetState( ChallengeResponseView::State::kAuthenticating); Shell::Get() ->login_screen_controller() ->AuthenticateUserWithChallengeResponse( current_user().basic_user_info.account_id, base::BindOnce(&LoginAuthUserView::OnChallengeResponseAuthComplete, weak_factory_.GetWeakPtr())); } void LoginAuthUserView::UpdateFocus() { DCHECK(previous_state_); const UiState current_state{this}; if (current_state.tpm_is_locked) { locked_tpm_message_view_->RequestFocus(); return; } // All further states are exclusive. if (current_state.auth_disabled) disabled_auth_message_->RequestFocus(); if (current_state.has_challenge_response) challenge_response_view_->RequestFocus(); if (current_state.has_password && !previous_state_->has_password) password_view_->RequestFocus(); if (current_state.has_pin_input) pin_input_view_->RequestFocus(); // Tapping the user view will trigger the online sign-in flow when // |force_online_sign_in| is true. if (current_state.force_online_sign_in) user_view_->RequestFocus(); } void LoginAuthUserView::OnSwitchButtonClicked() { // Ignore events from the switch button if no longer present. if (input_field_mode_ != InputFieldMode::PIN_WITH_TOGGLE && input_field_mode_ != InputFieldMode::PWD_WITH_TOGGLE) { return; } // Clear both input fields. password_view_->Reset(); pin_input_view_->Reset(); // Cache the current state of the UI. CaptureStateForAnimationPreLayout(); // Same auth methods, but the input field mode has changed. input_field_mode_ = (input_field_mode_ == InputFieldMode::PIN_WITH_TOGGLE) ? InputFieldMode::PWD_WITH_TOGGLE : InputFieldMode::PIN_WITH_TOGGLE; SetAuthMethods(auth_methods_, auth_metadata_); // Layout and animate. Layout(); ApplyAnimationPostLayout(/*animate*/ true); } void LoginAuthUserView::UpdateInputFieldMode() { // There isn't an input field when any of the following is true: // - Challenge response is active (Smart Card) // - Online sign in message shown // - Disabled message shown // - No password auth available if (HasAuthMethod(AUTH_CHALLENGE_RESPONSE) || HasAuthMethod(AUTH_ONLINE_SIGN_IN) || HasAuthMethod(AUTH_DISABLED) || !HasAuthMethod(AUTH_PASSWORD)) { input_field_mode_ = InputFieldMode::NONE; return; } if (!HasAuthMethod(AUTH_PIN)) { input_field_mode_ = InputFieldMode::PASSWORD_ONLY; return; } // Default to combined password/pin if autosubmit is disabled. const int pin_length = auth_metadata_.autosubmit_pin_length; if (!LoginPinInputView::IsAutosubmitSupported(pin_length)) { input_field_mode_ = InputFieldMode::PIN_AND_PASSWORD; return; } // Defaults to PIN + switch button if not showing the switch button already. if (input_field_mode_ != InputFieldMode::PIN_WITH_TOGGLE && input_field_mode_ != InputFieldMode::PWD_WITH_TOGGLE) { input_field_mode_ = InputFieldMode::PIN_WITH_TOGGLE; return; } } bool LoginAuthUserView::ShouldShowPinPad() const { if (auth_metadata_.virtual_keyboard_visible) return false; switch (input_field_mode_) { case InputFieldMode::NONE: return false; case InputFieldMode::PASSWORD_ONLY: case InputFieldMode::PWD_WITH_TOGGLE: return auth_metadata_.show_pinpad_for_pw; case InputFieldMode::PIN_AND_PASSWORD: case InputFieldMode::PIN_WITH_TOGGLE: return true; } } bool LoginAuthUserView::ShouldShowPasswordField() const { return input_field_mode_ == InputFieldMode::PASSWORD_ONLY || input_field_mode_ == InputFieldMode::PIN_AND_PASSWORD || input_field_mode_ == InputFieldMode::PWD_WITH_TOGGLE; } bool LoginAuthUserView::ShouldShowPinInputField() const { return input_field_mode_ == InputFieldMode::PIN_WITH_TOGGLE; } bool LoginAuthUserView::ShouldShowToggle() const { return input_field_mode_ == InputFieldMode::PIN_WITH_TOGGLE || input_field_mode_ == InputFieldMode::PWD_WITH_TOGGLE; } gfx::Size LoginAuthUserView::GetPaddingBelowUserView() const { const UiState state{this}; if (state.has_password) return SizeFromHeight(kDistanceBetweenUserViewAndPasswordDp); if (state.has_pin_input) return SizeFromHeight(kDistanceBetweenUserViewAndPinInputDp); if (state.force_online_sign_in) return SizeFromHeight(kDistanceBetweenUserViewAndOnlineSigninDp); if (state.has_challenge_response) return SizeFromHeight(kDistanceBetweenUserViewAndChallengeResponseDp); return SizeFromHeight(0); } gfx::Size LoginAuthUserView::GetPaddingBelowPasswordView() const { const UiState state{this}; if (state.has_pinpad) return SizeFromHeight(kDistanceBetweenPasswordFieldAndPinKeyboardDp); if (state.has_fingerprint) return SizeFromHeight(kDistanceBetweenPasswordFieldAndFingerprintViewDp); if (state.has_challenge_response) return SizeFromHeight(kDistanceBetweenPwdFieldAndChallengeResponseViewDp); return SizeFromHeight(0); } base::string16 LoginAuthUserView::GetPinPasswordToggleText() { if (input_field_mode_ == InputFieldMode::PWD_WITH_TOGGLE) return l10n_util::GetStringUTF16(IDS_ASH_LOGIN_SWITCH_TO_PIN); else return l10n_util::GetStringUTF16(IDS_ASH_LOGIN_SWITCH_TO_PASSWORD); } base::string16 LoginAuthUserView::GetPasswordViewPlaceholder() const { // Note: |AUTH_TAP| must have higher priority than |AUTH_PIN| when // determining the placeholder. if (HasAuthMethod(AUTH_TAP)) return l10n_util::GetStringUTF16( IDS_ASH_LOGIN_POD_PASSWORD_TAP_PLACEHOLDER); if (input_field_mode_ == InputFieldMode::PIN_AND_PASSWORD) return l10n_util::GetStringUTF16( IDS_ASH_LOGIN_POD_PASSWORD_PIN_PLACEHOLDER); return l10n_util::GetStringUTF16(IDS_ASH_LOGIN_POD_PASSWORD_PLACEHOLDER); } } // namespace ash ",16232,True,2799.8098347798605,median "CLASS zcl_abapgit_object_fugr DEFINITION PUBLIC INHERITING FROM zcl_abapgit_objects_program FINAL. PUBLIC SECTION. INTERFACES zif_abapgit_object. ALIASES mo_files FOR zif_abapgit_object~mo_files. PROTECTED SECTION. PRIVATE SECTION. TYPES: ty_rs38l_incl_tt TYPE STANDARD TABLE OF rs38l_incl WITH DEFAULT KEY . TYPES: BEGIN OF ty_function, funcname TYPE rs38l_fnam, global_flag TYPE rs38l-global, remote_call TYPE rs38l-remote, update_task TYPE rs38l-utask, short_text TYPE tftit-stext, remote_basxml TYPE rs38l-basxml_enabled, import TYPE STANDARD TABLE OF rsimp WITH DEFAULT KEY, changing TYPE STANDARD TABLE OF rscha WITH DEFAULT KEY, export TYPE STANDARD TABLE OF rsexp WITH DEFAULT KEY, tables TYPE STANDARD TABLE OF rstbl WITH DEFAULT KEY, exception TYPE STANDARD TABLE OF rsexc WITH DEFAULT KEY, documentation TYPE STANDARD TABLE OF rsfdo WITH DEFAULT KEY, exception_classes TYPE abap_bool, END OF ty_function . TYPES: ty_function_tt TYPE STANDARD TABLE OF ty_function WITH DEFAULT KEY . TYPES: ty_sobj_name_tt TYPE STANDARD TABLE OF sobj_name WITH DEFAULT KEY . TYPES: BEGIN OF ty_tpool_i18n, language TYPE langu, textpool TYPE zif_abapgit_definitions=>ty_tpool_tt, END OF ty_tpool_i18n . TYPES: tt_tpool_i18n TYPE STANDARD TABLE OF ty_tpool_i18n . METHODS check_rfc_parameters IMPORTING !is_function TYPE ty_function RAISING zcx_abapgit_exception . METHODS update_where_used IMPORTING !it_includes TYPE ty_sobj_name_tt . METHODS main_name RETURNING VALUE(rv_program) TYPE program RAISING zcx_abapgit_exception . METHODS functions RETURNING VALUE(rt_functab) TYPE ty_rs38l_incl_tt RAISING zcx_abapgit_exception . METHODS includes RETURNING VALUE(rt_includes) TYPE ty_sobj_name_tt RAISING zcx_abapgit_exception . METHODS serialize_functions RETURNING VALUE(rt_functions) TYPE ty_function_tt RAISING zcx_abapgit_exception . METHODS deserialize_functions IMPORTING !it_functions TYPE ty_function_tt !ii_log TYPE REF TO zif_abapgit_log RAISING zcx_abapgit_exception . METHODS serialize_xml IMPORTING !io_xml TYPE REF TO zcl_abapgit_xml_output RAISING zcx_abapgit_exception . METHODS deserialize_xml IMPORTING !io_xml TYPE REF TO zcl_abapgit_xml_input !iv_package TYPE devclass RAISING zcx_abapgit_exception . METHODS serialize_includes RAISING zcx_abapgit_exception . METHODS deserialize_includes IMPORTING !io_xml TYPE REF TO zcl_abapgit_xml_input !iv_package TYPE devclass !ii_log TYPE REF TO zif_abapgit_log RAISING zcx_abapgit_exception . METHODS are_exceptions_class_based IMPORTING !iv_function_name TYPE rs38l_fnam RETURNING VALUE(rv_return) TYPE abap_bool RAISING zcx_abapgit_exception . METHODS is_function_group_locked RETURNING VALUE(rv_is_functions_group_locked) TYPE abap_bool RAISING zcx_abapgit_exception . METHODS is_any_include_locked RETURNING VALUE(rv_is_any_include_locked) TYPE abap_bool RAISING zcx_abapgit_exception . METHODS is_any_function_module_locked RETURNING VALUE(rv_any_function_module_locked) TYPE abap_bool RAISING zcx_abapgit_exception . METHODS get_abap_version IMPORTING !io_xml TYPE REF TO zcl_abapgit_xml_input RETURNING VALUE(rv_abap_version) TYPE progdir-uccheck RAISING zcx_abapgit_exception . METHODS update_func_group_short_text IMPORTING !iv_group TYPE rs38l-area !iv_short_text TYPE tftit-stext . METHODS serialize_texts IMPORTING !iv_prog_name TYPE programm !io_xml TYPE REF TO zcl_abapgit_xml_output RAISING zcx_abapgit_exception . METHODS deserialize_texts IMPORTING !iv_prog_name TYPE programm !io_xml TYPE REF TO zcl_abapgit_xml_input RAISING zcx_abapgit_exception . ENDCLASS. CLASS ZCL_ABAPGIT_OBJECT_FUGR IMPLEMENTATION. METHOD are_exceptions_class_based. DATA: lt_dokumentation TYPE TABLE OF funct, lt_exception_list TYPE TABLE OF rsexc, lt_export_parameter TYPE TABLE OF rsexp, lt_import_parameter TYPE TABLE OF rsimp, lt_tables_parameter TYPE TABLE OF rstbl. CALL FUNCTION 'FUNCTION_IMPORT_DOKU' EXPORTING funcname = iv_function_name IMPORTING exception_class = rv_return TABLES dokumentation = lt_dokumentation exception_list = lt_exception_list export_parameter = lt_export_parameter import_parameter = lt_import_parameter tables_parameter = lt_tables_parameter EXCEPTIONS error_message = 1 function_not_found = 2 invalid_name = 3 OTHERS = 4. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'Error from FUNCTION_IMPORT_DOKU' ). ENDIF. ENDMETHOD. METHOD check_rfc_parameters. * function module RS_FUNCTIONMODULE_INSERT does the same deep down, but the right error * message is not returned to the user, this is a workaround to give a proper error * message to the user DATA: ls_parameter TYPE rsfbpara, lt_fupa TYPE rsfb_param, ls_fupa LIKE LINE OF lt_fupa. IF is_function-remote_call = 'R'. cl_fb_parameter_conversion=>convert_parameter_old_to_fupa( EXPORTING functionname = is_function-funcname import = is_function-import export = is_function-export change = is_function-changing tables = is_function-tables except = is_function-exception IMPORTING fupararef = lt_fupa ). LOOP AT lt_fupa INTO ls_fupa WHERE paramtype = 'I' OR paramtype = 'E' OR paramtype = 'C' OR paramtype = 'T'. cl_fb_parameter_conversion=>convert_intern_to_extern( EXPORTING parameter_db = ls_fupa IMPORTING parameter_vis = ls_parameter ). CALL FUNCTION 'RS_FB_CHECK_PARAMETER_REMOTE' EXPORTING parameter = ls_parameter basxml_enabled = is_function-remote_basxml EXCEPTIONS not_remote_compatible = 1 OTHERS = 2. IF sy-subrc <> 0. zcx_abapgit_exception=>raise_t100( ). ENDIF. ENDLOOP. ENDIF. ENDMETHOD. METHOD deserialize_functions. DATA: lv_include TYPE rs38l-include, lv_area TYPE rs38l-area, lv_group TYPE rs38l-area, lv_namespace TYPE rs38l-namespace, lt_source TYPE TABLE OF abaptxt255, lv_msg TYPE string, lx_error TYPE REF TO zcx_abapgit_exception, lv_corrnum TYPE e070use-ordernum. FIELD-SYMBOLS: LIKE LINE OF it_functions. lv_corrnum = zcl_abapgit_default_transport=>get_instance( )->get( )-ordernum. LOOP AT it_functions ASSIGNING . lt_source = mo_files->read_abap( iv_extra = -funcname ). lv_area = ms_item-obj_name. CALL FUNCTION 'FUNCTION_INCLUDE_SPLIT' EXPORTING complete_area = lv_area IMPORTING namespace = lv_namespace group = lv_group EXCEPTIONS OTHERS = 12. IF sy-subrc <> 0. MESSAGE ID sy-msgid TYPE 'S' NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4 INTO lv_msg. ii_log->add_error( iv_msg = |Function module { -funcname }: { lv_msg }| is_item = ms_item ). CONTINUE. ""with next function module ENDIF. CALL FUNCTION 'FUNCTION_EXISTS' EXPORTING funcname = -funcname IMPORTING include = lv_include EXCEPTIONS function_not_exist = 1. IF sy-subrc = 0. * delete the function module to make sure the parameters are updated * havent found a nice way to update the paramters CALL FUNCTION 'FUNCTION_DELETE' EXPORTING funcname = -funcname suppress_success_message = abap_true EXCEPTIONS error_message = 1 OTHERS = 2. IF sy-subrc <> 0. MESSAGE ID sy-msgid TYPE 'S' NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4 INTO lv_msg. ii_log->add_error( iv_msg = |Function module { -funcname }: { lv_msg }| is_item = ms_item ). CONTINUE. ""with next function module ENDIF. ENDIF. TRY. check_rfc_parameters( ). CATCH zcx_abapgit_exception INTO lx_error. ii_log->add_error( iv_msg = |Function module { -funcname }: { lx_error->get_text( ) }| is_item = ms_item ). CONTINUE. ""with next function module ENDTRY. CALL FUNCTION 'RS_FUNCTIONMODULE_INSERT' EXPORTING funcname = -funcname function_pool = lv_group interface_global = -global_flag remote_call = -remote_call short_text = -short_text update_task = -update_task exception_class = -exception_classes namespace = lv_namespace remote_basxml_supported = -remote_basxml corrnum = lv_corrnum IMPORTING function_include = lv_include TABLES import_parameter = -import export_parameter = -export tables_parameter = -tables changing_parameter = -changing exception_list = -exception parameter_docu = -documentation EXCEPTIONS double_task = 1 error_message = 2 function_already_exists = 3 invalid_function_pool = 4 invalid_name = 5 too_many_functions = 6 no_modify_permission = 7 no_show_permission = 8 enqueue_system_failure = 9 canceled_in_corr = 10 OTHERS = 11. IF sy-subrc <> 0. MESSAGE ID sy-msgid TYPE 'S' NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4 INTO lv_msg. ii_log->add_error( iv_msg = |Function module { -funcname }: { lv_msg }| is_item = ms_item ). CONTINUE. ""with next function module ENDIF. INSERT REPORT lv_include FROM lt_source. ii_log->add_success( iv_msg = |Function module { -funcname } imported| is_item = ms_item ). ENDLOOP. ENDMETHOD. METHOD deserialize_includes. DATA: lo_xml TYPE REF TO zcl_abapgit_xml_input, ls_progdir TYPE ty_progdir, lt_includes TYPE ty_sobj_name_tt, lt_tpool TYPE textpool_table, lt_tpool_ext TYPE zif_abapgit_definitions=>ty_tpool_tt, lt_source TYPE TABLE OF abaptxt255, lx_exc TYPE REF TO zcx_abapgit_exception. FIELD-SYMBOLS: LIKE LINE OF lt_includes. tadir_insert( iv_package ). io_xml->read( EXPORTING iv_name = 'INCLUDES' CHANGING cg_data = lt_includes ). LOOP AT lt_includes ASSIGNING . ""ignore simple transformation includes (as long as they remain in existing repositories) IF strlen( ) = 33 AND +30(3) = 'XTI'. ii_log->add_warning( iv_msg = |Simple Transformation include { } ignored| is_item = ms_item ). CONTINUE. ENDIF. TRY. lt_source = mo_files->read_abap( iv_extra = ). lo_xml = mo_files->read_xml( ). lo_xml->read( EXPORTING iv_name = 'PROGDIR' CHANGING cg_data = ls_progdir ). lo_xml->read( EXPORTING iv_name = 'TPOOL' CHANGING cg_data = lt_tpool_ext ). lt_tpool = read_tpool( lt_tpool_ext ). deserialize_program( is_progdir = ls_progdir it_source = lt_source it_tpool = lt_tpool iv_package = iv_package ). deserialize_textpool( iv_program = it_tpool = lt_tpool iv_is_include = abap_true ). ii_log->add_success( iv_msg = |Include { ls_progdir-name } imported| is_item = ms_item ). CATCH zcx_abapgit_exception INTO lx_exc. ii_log->add_exception( ix_exc = lx_exc is_item = ms_item ). CONTINUE. ENDTRY. ENDLOOP. ENDMETHOD. METHOD deserialize_texts. DATA: lt_tpool_i18n TYPE tt_tpool_i18n, lt_tpool TYPE textpool_table. FIELD-SYMBOLS LIKE LINE OF lt_tpool_i18n. io_xml->read( EXPORTING iv_name = 'I18N_TPOOL' CHANGING cg_data = lt_tpool_i18n ). LOOP AT lt_tpool_i18n ASSIGNING . lt_tpool = read_tpool( -textpool ). deserialize_textpool( iv_program = iv_prog_name iv_language = -language it_tpool = lt_tpool ). ENDLOOP. ENDMETHOD. METHOD deserialize_xml. DATA: lv_complete TYPE rs38l-area, lv_namespace TYPE rs38l-namespace, lv_areat TYPE tlibt-areat, lv_stext TYPE tftit-stext, lv_group TYPE rs38l-area, lv_abap_version TYPE trdir-uccheck, lv_corrnum TYPE e070use-ordernum. lv_abap_version = get_abap_version( io_xml ). lv_complete = ms_item-obj_name. CALL FUNCTION 'FUNCTION_INCLUDE_SPLIT' EXPORTING complete_area = lv_complete IMPORTING namespace = lv_namespace group = lv_group EXCEPTIONS include_not_exists = 1 group_not_exists = 2 no_selections = 3 no_function_include = 4 no_function_pool = 5 delimiter_wrong_position = 6 no_customer_function_group = 7 no_customer_function_include = 8 reserved_name_customer = 9 namespace_too_long = 10 area_length_error = 11 OTHERS = 12. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'error from FUNCTION_INCLUDE_SPLIT' ). ENDIF. io_xml->read( EXPORTING iv_name = 'AREAT' CHANGING cg_data = lv_areat ). lv_stext = lv_areat. lv_corrnum = zcl_abapgit_default_transport=>get_instance( )->get( )-ordernum. CALL FUNCTION 'RS_FUNCTION_POOL_INSERT' EXPORTING function_pool = lv_group short_text = lv_stext namespace = lv_namespace devclass = iv_package unicode_checks = lv_abap_version corrnum = lv_corrnum suppress_corr_check = abap_false EXCEPTIONS name_already_exists = 1 name_not_correct = 2 function_already_exists = 3 invalid_function_pool = 4 invalid_name = 5 too_many_functions = 6 no_modify_permission = 7 no_show_permission = 8 enqueue_system_failure = 9 canceled_in_corr = 10 undefined_error = 11 OTHERS = 12. CASE sy-subrc. WHEN 0. "" Everything is ok WHEN 1 OR 3. "" If the function group exists we need to manually update the short text update_func_group_short_text( iv_group = lv_group iv_short_text = lv_stext ). WHEN OTHERS. zcx_abapgit_exception=>raise( |error from RS_FUNCTION_POOL_INSERT, code: { sy-subrc }| ). ENDCASE. ENDMETHOD. METHOD functions. DATA: lv_area TYPE rs38l-area. lv_area = ms_item-obj_name. CALL FUNCTION 'RS_FUNCTION_POOL_CONTENTS' EXPORTING function_pool = lv_area TABLES functab = rt_functab EXCEPTIONS function_pool_not_found = 1 OTHERS = 2. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'Error from RS_FUNCTION_POOL_CONTENTS' ). ENDIF. SORT rt_functab BY funcname ASCENDING. DELETE ADJACENT DUPLICATES FROM rt_functab COMPARING funcname. ENDMETHOD. METHOD get_abap_version. DATA: lt_includes TYPE ty_sobj_name_tt, ls_progdir TYPE ty_progdir, lo_xml TYPE REF TO zcl_abapgit_xml_input. FIELD-SYMBOLS: LIKE LINE OF lt_includes. io_xml->read( EXPORTING iv_name = 'INCLUDES' CHANGING cg_data = lt_includes ). LOOP AT lt_includes ASSIGNING . lo_xml = mo_files->read_xml( ). lo_xml->read( EXPORTING iv_name = 'PROGDIR' CHANGING cg_data = ls_progdir ). IF ls_progdir-uccheck IS INITIAL. CONTINUE. ELSEIF rv_abap_version IS INITIAL. rv_abap_version = ls_progdir-uccheck. CONTINUE. ELSEIF rv_abap_version <> ls_progdir-uccheck. *** All includes need to have the same ABAP language version zcx_abapgit_exception=>raise( 'different ABAP Language Versions' ). ENDIF. ENDLOOP. IF rv_abap_version IS INITIAL. rv_abap_version = 'X'. ENDIF. ENDMETHOD. METHOD includes. TYPES: BEGIN OF ty_reposrc, progname TYPE reposrc-progname, cnam TYPE reposrc-cnam, END OF ty_reposrc. DATA: lt_reposrc TYPE STANDARD TABLE OF ty_reposrc WITH DEFAULT KEY, ls_reposrc LIKE LINE OF lt_reposrc, lv_program TYPE program, lv_maintviewname LIKE LINE OF rt_includes, lv_offset_ns TYPE i, lv_tabix LIKE sy-tabix, lt_functab TYPE ty_rs38l_incl_tt, lt_tadir_includes TYPE HASHED TABLE OF objname WITH UNIQUE KEY table_line. FIELD-SYMBOLS: LIKE LINE OF rt_includes, LIKE LINE OF lt_functab. lv_program = main_name( ). lt_functab = functions( ). CALL FUNCTION 'RS_GET_ALL_INCLUDES' EXPORTING program = lv_program * WITH_RESERVED_INCLUDES = * WITH_CLASS_INCLUDES = ' ' hmm, todo TABLES includetab = rt_includes EXCEPTIONS not_existent = 1 no_program = 2 OTHERS = 3. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'Error from RS_GET_ALL_INCLUDES' ). ENDIF. LOOP AT lt_functab ASSIGNING . DELETE TABLE rt_includes FROM -include. ENDLOOP. * handle generated maintenance views IF ms_item-obj_name(1) <> '/'. ""FGroup name does not contain a namespace lv_maintviewname = |L{ ms_item-obj_name }T00|. ELSE. ""FGroup name contains a namespace lv_offset_ns = find( val = ms_item-obj_name+1 sub = '/' ). lv_offset_ns = lv_offset_ns + 2. lv_maintviewname = |{ ms_item-obj_name(lv_offset_ns) }L{ ms_item-obj_name+lv_offset_ns }T00|. ENDIF. READ TABLE rt_includes WITH KEY table_line = lv_maintviewname TRANSPORTING NO FIELDS. IF sy-subrc <> 0. APPEND lv_maintviewname TO rt_includes. ENDIF. IF lines( rt_includes ) > 0. "" check which includes have their own tadir entry "" these includes might reside in a different package or might be shared between multiple function groups "" or other programs and are hence no part of the to serialized FUGR object "" they will be handled as individual objects when serializing their package "" in addition, referenced XTI includes referencing (simple) transformations must be ignored SELECT obj_name INTO TABLE lt_tadir_includes FROM tadir FOR ALL ENTRIES IN rt_includes WHERE pgmid = 'R3TR' AND object = 'PROG' AND obj_name = rt_includes-table_line. LOOP AT rt_includes ASSIGNING . "" skip autogenerated includes from Table Maintenance Generator IF CP 'LSVIM*'. DELETE rt_includes INDEX sy-tabix. CONTINUE. ENDIF. READ TABLE lt_tadir_includes WITH KEY table_line = TRANSPORTING NO FIELDS. IF sy-subrc = 0. DELETE rt_includes. CONTINUE. ENDIF. IF strlen( ) = 33 AND +30(3) = 'XTI'. ""ignore referenced (simple) transformation includes DELETE rt_includes. CONTINUE. ENDIF. ENDLOOP. SELECT progname cnam FROM reposrc INTO TABLE lt_reposrc FOR ALL ENTRIES IN rt_includes WHERE progname = rt_includes-table_line AND r3state = 'A'. SORT lt_reposrc BY progname ASCENDING. ENDIF. LOOP AT rt_includes ASSIGNING . lv_tabix = sy-tabix. * make sure the include exists READ TABLE lt_reposrc INTO ls_reposrc WITH KEY progname = BINARY SEARCH. IF sy-subrc <> 0. DELETE rt_includes INDEX lv_tabix. ENDIF. ENDLOOP. APPEND lv_program TO rt_includes. ENDMETHOD. METHOD is_any_function_module_locked. DATA: lt_functions TYPE ty_rs38l_incl_tt. FIELD-SYMBOLS: TYPE rs38l_incl. TRY. lt_functions = functions( ). CATCH zcx_abapgit_exception. RETURN. ENDTRY. LOOP AT lt_functions ASSIGNING . IF exists_a_lock_entry_for( iv_lock_object = 'ESFUNCTION' iv_argument = |{ -funcname }| ) = abap_true. rv_any_function_module_locked = abap_true. EXIT. ENDIF. ENDLOOP. ENDMETHOD. METHOD is_any_include_locked. DATA: lt_includes TYPE ty_sobj_name_tt. FIELD-SYMBOLS: TYPE sobj_name. TRY. lt_includes = includes( ). CATCH zcx_abapgit_exception. RETURN. ENDTRY. LOOP AT lt_includes ASSIGNING . IF exists_a_lock_entry_for( iv_lock_object = 'ESRDIRE' iv_argument = |{ }| ) = abap_true. rv_is_any_include_locked = abap_true. EXIT. ENDIF. ENDLOOP. ENDMETHOD. METHOD is_function_group_locked. DATA: lv_object TYPE eqegraarg. lv_object = |FG{ ms_item-obj_name }|. OVERLAY lv_object WITH ' '. lv_object = lv_object && '*'. rv_is_functions_group_locked = exists_a_lock_entry_for( iv_lock_object = 'EEUDB' iv_argument = lv_object ). ENDMETHOD. METHOD main_name. DATA: lv_area TYPE rs38l-area, lv_namespace TYPE rs38l-namespace, lv_group TYPE rs38l-area. lv_area = ms_item-obj_name. CALL FUNCTION 'FUNCTION_INCLUDE_SPLIT' EXPORTING complete_area = lv_area IMPORTING namespace = lv_namespace group = lv_group EXCEPTIONS include_not_exists = 1 group_not_exists = 2 no_selections = 3 no_function_include = 4 no_function_pool = 5 delimiter_wrong_position = 6 no_customer_function_group = 7 no_customer_function_include = 8 reserved_name_customer = 9 namespace_too_long = 10 area_length_error = 11 OTHERS = 12. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'Error from FUNCTION_INCLUDE_SPLIT' ). ENDIF. CONCATENATE lv_namespace 'SAPL' lv_group INTO rv_program. ENDMETHOD. METHOD serialize_functions. DATA: lt_source TYPE TABLE OF rssource, lt_functab TYPE ty_rs38l_incl_tt, lt_new_source TYPE rsfb_source, ls_function LIKE LINE OF rt_functions. FIELD-SYMBOLS: LIKE LINE OF lt_functab, TYPE LINE OF ty_function-documentation. lt_functab = functions( ). LOOP AT lt_functab ASSIGNING . * fm RPY_FUNCTIONMODULE_READ does not support source code * lines longer than 72 characters CLEAR ls_function. MOVE-CORRESPONDING TO ls_function. CLEAR lt_new_source. CLEAR lt_source. CALL FUNCTION 'RPY_FUNCTIONMODULE_READ_NEW' EXPORTING functionname = -funcname IMPORTING global_flag = ls_function-global_flag remote_call = ls_function-remote_call update_task = ls_function-update_task short_text = ls_function-short_text remote_basxml_supported = ls_function-remote_basxml TABLES import_parameter = ls_function-import changing_parameter = ls_function-changing export_parameter = ls_function-export tables_parameter = ls_function-tables exception_list = ls_function-exception documentation = ls_function-documentation source = lt_source CHANGING new_source = lt_new_source EXCEPTIONS error_message = 1 function_not_found = 2 invalid_name = 3 OTHERS = 4. IF sy-subrc = 2. CONTINUE. ELSEIF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'Error from RPY_FUNCTIONMODULE_READ_NEW' ). ENDIF. LOOP AT ls_function-documentation ASSIGNING . CLEAR -index. ENDLOOP. ls_function-exception_classes = are_exceptions_class_based( -funcname ). APPEND ls_function TO rt_functions. IF NOT lt_new_source IS INITIAL. mo_files->add_abap( iv_extra = -funcname it_abap = lt_new_source ). ELSE. mo_files->add_abap( iv_extra = -funcname it_abap = lt_source ). ENDIF. ENDLOOP. ENDMETHOD. METHOD serialize_includes. DATA: lt_includes TYPE ty_sobj_name_tt. FIELD-SYMBOLS: LIKE LINE OF lt_includes. lt_includes = includes( ). LOOP AT lt_includes ASSIGNING . * todo, filename is not correct, a include can be used in several programs serialize_program( is_item = ms_item io_files = mo_files iv_program = iv_extra = ). ENDLOOP. ENDMETHOD. METHOD serialize_texts. DATA: lt_tpool_i18n TYPE tt_tpool_i18n, lt_tpool TYPE textpool_table. FIELD-SYMBOLS LIKE LINE OF lt_tpool_i18n. IF io_xml->i18n_params( )-serialize_master_lang_only = abap_true. RETURN. ENDIF. "" Table d010tinf stores info. on languages in which program is maintained "" Select all active translations of program texts "" Skip master language - it was already serialized SELECT DISTINCT language INTO CORRESPONDING FIELDS OF TABLE lt_tpool_i18n FROM d010tinf WHERE r3state = 'A' AND prog = iv_prog_name AND language <> mv_language ##TOO_MANY_ITAB_FIELDS. SORT lt_tpool_i18n BY language ASCENDING. LOOP AT lt_tpool_i18n ASSIGNING . READ TEXTPOOL iv_prog_name LANGUAGE -language INTO lt_tpool. -textpool = add_tpool( lt_tpool ). ENDLOOP. IF lines( lt_tpool_i18n ) > 0. io_xml->add( iv_name = 'I18N_TPOOL' ig_data = lt_tpool_i18n ). ENDIF. ENDMETHOD. METHOD serialize_xml. DATA: lt_includes TYPE ty_sobj_name_tt, lv_areat TYPE tlibt-areat. SELECT SINGLE areat INTO lv_areat FROM tlibt WHERE spras = mv_language AND area = ms_item-obj_name. ""#EC CI_GENBUFF ""#EC CI_SUBRC lt_includes = includes( ). io_xml->add( iv_name = 'AREAT' ig_data = lv_areat ). io_xml->add( iv_name = 'INCLUDES' ig_data = lt_includes ). ENDMETHOD. METHOD update_func_group_short_text. "" We update the short text directly. "" SE80 does the same in "" Program SAPLSEUF / LSEUFF07 "" FORM GROUP_CHANGE UPDATE tlibt SET areat = iv_short_text WHERE spras = mv_language AND area = iv_group. ENDMETHOD. METHOD update_where_used. * make extra sure the where-used list is updated after deletion * Experienced some problems with the T00 include * this method just tries to update everything DATA: lv_include LIKE LINE OF it_includes, lo_cross TYPE REF TO cl_wb_crossreference. LOOP AT it_includes INTO lv_include. CREATE OBJECT lo_cross EXPORTING p_name = lv_include p_include = lv_include. lo_cross->index_actualize( ). ENDLOOP. ENDMETHOD. METHOD zif_abapgit_object~changed_by. TYPES: BEGIN OF ty_stamps, user TYPE xubname, date TYPE d, time TYPE t, END OF ty_stamps. DATA: lt_stamps TYPE STANDARD TABLE OF ty_stamps WITH DEFAULT KEY, lv_program TYPE program, lt_includes TYPE ty_sobj_name_tt. FIELD-SYMBOLS: LIKE LINE OF lt_stamps, LIKE LINE OF lt_includes. lv_program = main_name( ). CALL FUNCTION 'RS_GET_ALL_INCLUDES' EXPORTING program = lv_program TABLES includetab = lt_includes EXCEPTIONS not_existent = 1 no_program = 2 OTHERS = 3. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'Error from RS_GET_ALL_INCLUDES' ). ENDIF. SELECT unam AS user udat AS date utime AS time FROM reposrc APPENDING CORRESPONDING FIELDS OF TABLE lt_stamps WHERE progname = lv_program AND r3state = 'A'. ""#EC CI_SUBRC LOOP AT lt_includes ASSIGNING . SELECT unam AS user udat AS date utime AS time FROM reposrc APPENDING CORRESPONDING FIELDS OF TABLE lt_stamps WHERE progname = AND r3state = 'A'. ""#EC CI_SUBRC ENDLOOP. SELECT unam AS user udat AS date utime AS time FROM repotext "" Program text pool APPENDING CORRESPONDING FIELDS OF TABLE lt_stamps WHERE progname = lv_program AND r3state = 'A'. ""#EC CI_SUBRC SELECT vautor AS user vdatum AS date vzeit AS time FROM eudb "" GUI APPENDING CORRESPONDING FIELDS OF TABLE lt_stamps WHERE relid = 'CU' AND name = lv_program AND srtf2 = 0 ##TOO_MANY_ITAB_FIELDS. * Screens: username not stored in D020S database table SORT lt_stamps BY date DESCENDING time DESCENDING. READ TABLE lt_stamps INDEX 1 ASSIGNING . IF sy-subrc = 0. rv_user = -user. ELSE. rv_user = c_user_unknown. ENDIF. ENDMETHOD. METHOD zif_abapgit_object~delete. DATA: lv_area TYPE rs38l-area, lt_includes TYPE ty_sobj_name_tt, lv_corrnum TYPE e070use-ordernum. lt_includes = includes( ). lv_area = ms_item-obj_name. lv_corrnum = zcl_abapgit_default_transport=>get_instance( )->get( )-ordernum. CALL FUNCTION 'RS_FUNCTION_POOL_DELETE' EXPORTING area = lv_area suppress_popups = abap_true skip_progress_ind = abap_true corrnum = lv_corrnum EXCEPTIONS canceled_in_corr = 1 enqueue_system_failure = 2 function_exist = 3 not_executed = 4 no_modify_permission = 5 no_show_permission = 6 permission_failure = 7 pool_not_exist = 8 cancelled = 9 OTHERS = 10. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'error from RS_FUNCTION_POOL_DELETE' ). ENDIF. update_where_used( lt_includes ). ENDMETHOD. METHOD zif_abapgit_object~deserialize. DATA: lv_program_name TYPE programm, lt_functions TYPE ty_function_tt, lt_dynpros TYPE ty_dynpro_tt, ls_cua TYPE ty_cua. deserialize_xml( io_xml = io_xml iv_package = iv_package ). io_xml->read( EXPORTING iv_name = 'FUNCTIONS' CHANGING cg_data = lt_functions ). deserialize_functions( it_functions = lt_functions ii_log = ii_log ). deserialize_includes( io_xml = io_xml iv_package = iv_package ii_log = ii_log ). lv_program_name = main_name( ). deserialize_texts( iv_prog_name = lv_program_name io_xml = io_xml ). io_xml->read( EXPORTING iv_name = 'DYNPROS' CHANGING cg_data = lt_dynpros ). deserialize_dynpros( lt_dynpros ). io_xml->read( EXPORTING iv_name = 'CUA' CHANGING cg_data = ls_cua ). deserialize_cua( iv_program_name = lv_program_name is_cua = ls_cua ). ENDMETHOD. METHOD zif_abapgit_object~exists. DATA: lv_pool TYPE tlibg-area. lv_pool = ms_item-obj_name. CALL FUNCTION 'RS_FUNCTION_POOL_EXISTS' EXPORTING function_pool = lv_pool EXCEPTIONS pool_not_exists = 1. rv_bool = boolc( sy-subrc <> 1 ). ENDMETHOD. METHOD zif_abapgit_object~get_comparator. RETURN. ENDMETHOD. METHOD zif_abapgit_object~get_deserialize_steps. APPEND zif_abapgit_object=>gc_step_id-abap TO rt_steps. ENDMETHOD. METHOD zif_abapgit_object~get_metadata. rs_metadata = get_metadata( ). ENDMETHOD. METHOD zif_abapgit_object~is_active. rv_active = is_active( ). ENDMETHOD. METHOD zif_abapgit_object~is_locked. DATA: lv_program TYPE program. lv_program = main_name( ). IF is_function_group_locked( ) = abap_true OR is_any_include_locked( ) = abap_true OR is_any_function_module_locked( ) = abap_true OR is_any_dynpro_locked( lv_program ) = abap_true OR is_cua_locked( lv_program ) = abap_true OR is_text_locked( lv_program ) = abap_true. rv_is_locked = abap_true. ENDIF. ENDMETHOD. METHOD zif_abapgit_object~jump. CALL FUNCTION 'RS_TOOL_ACCESS' EXPORTING operation = 'SHOW' object_name = ms_item-obj_name object_type = 'FUGR' in_new_window = abap_true. ENDMETHOD. METHOD zif_abapgit_object~serialize. * function group SEUF * function group SIFP * function group SUNI DATA: lt_functions TYPE ty_function_tt, ls_progdir TYPE ty_progdir, lv_program_name TYPE programm, lt_dynpros TYPE ty_dynpro_tt, ls_cua TYPE ty_cua. IF zif_abapgit_object~exists( ) = abap_false. RETURN. ENDIF. serialize_xml( io_xml ). lt_functions = serialize_functions( ). io_xml->add( iv_name = 'FUNCTIONS' ig_data = lt_functions ). serialize_includes( ). lv_program_name = main_name( ). ls_progdir = read_progdir( lv_program_name ). serialize_texts( iv_prog_name = lv_program_name io_xml = io_xml ). IF ls_progdir-subc = 'F'. lt_dynpros = serialize_dynpros( lv_program_name ). io_xml->add( iv_name = 'DYNPROS' ig_data = lt_dynpros ). ls_cua = serialize_cua( lv_program_name ). io_xml->add( iv_name = 'CUA' ig_data = ls_cua ). ENDIF. ENDMETHOD. ENDCLASS. ",9231,False,1880.1414151067568,median "/*************************************************************************/ /* particles_material.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* 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 ""particles_material.h"" Mutex ParticlesMaterial::material_mutex; SelfList::List *ParticlesMaterial::dirty_materials = nullptr; Map ParticlesMaterial::shader_map; ParticlesMaterial::ShaderNames *ParticlesMaterial::shader_names = nullptr; void ParticlesMaterial::init_shaders() { dirty_materials = memnew(SelfList::List); shader_names = memnew(ShaderNames); shader_names->direction = ""direction""; shader_names->spread = ""spread""; shader_names->flatness = ""flatness""; shader_names->initial_linear_velocity = ""initial_linear_velocity""; shader_names->initial_angle = ""initial_angle""; shader_names->angular_velocity = ""angular_velocity""; shader_names->orbit_velocity = ""orbit_velocity""; shader_names->linear_accel = ""linear_accel""; shader_names->radial_accel = ""radial_accel""; shader_names->tangent_accel = ""tangent_accel""; shader_names->damping = ""damping""; shader_names->scale = ""scale""; shader_names->hue_variation = ""hue_variation""; shader_names->anim_speed = ""anim_speed""; shader_names->anim_offset = ""anim_offset""; shader_names->initial_linear_velocity_random = ""initial_linear_velocity_random""; shader_names->initial_angle_random = ""initial_angle_random""; shader_names->angular_velocity_random = ""angular_velocity_random""; shader_names->orbit_velocity_random = ""orbit_velocity_random""; shader_names->linear_accel_random = ""linear_accel_random""; shader_names->radial_accel_random = ""radial_accel_random""; shader_names->tangent_accel_random = ""tangent_accel_random""; shader_names->damping_random = ""damping_random""; shader_names->scale_random = ""scale_random""; shader_names->hue_variation_random = ""hue_variation_random""; shader_names->anim_speed_random = ""anim_speed_random""; shader_names->anim_offset_random = ""anim_offset_random""; shader_names->angle_texture = ""angle_texture""; shader_names->angular_velocity_texture = ""angular_velocity_texture""; shader_names->orbit_velocity_texture = ""orbit_velocity_texture""; shader_names->linear_accel_texture = ""linear_accel_texture""; shader_names->radial_accel_texture = ""radial_accel_texture""; shader_names->tangent_accel_texture = ""tangent_accel_texture""; shader_names->damping_texture = ""damping_texture""; shader_names->scale_texture = ""scale_texture""; shader_names->hue_variation_texture = ""hue_variation_texture""; shader_names->anim_speed_texture = ""anim_speed_texture""; shader_names->anim_offset_texture = ""anim_offset_texture""; shader_names->color = ""color_value""; shader_names->color_ramp = ""color_ramp""; shader_names->emission_sphere_radius = ""emission_sphere_radius""; shader_names->emission_box_extents = ""emission_box_extents""; shader_names->emission_texture_point_count = ""emission_texture_point_count""; shader_names->emission_texture_points = ""emission_texture_points""; shader_names->emission_texture_normal = ""emission_texture_normal""; shader_names->emission_texture_color = ""emission_texture_color""; shader_names->trail_divisor = ""trail_divisor""; shader_names->trail_size_modifier = ""trail_size_modifier""; shader_names->trail_color_modifier = ""trail_color_modifier""; shader_names->gravity = ""gravity""; shader_names->lifetime_randomness = ""lifetime_randomness""; } void ParticlesMaterial::finish_shaders() { memdelete(dirty_materials); dirty_materials = nullptr; memdelete(shader_names); } void ParticlesMaterial::_update_shader() { dirty_materials->remove(&element); MaterialKey mk = _compute_key(); if (mk.key == current_key.key) return; //no update required in the end if (shader_map.has(current_key)) { shader_map[current_key].users--; if (shader_map[current_key].users == 0) { //deallocate shader, as it's no longer in use RS::get_singleton()->free(shader_map[current_key].shader); shader_map.erase(current_key); } } current_key = mk; if (shader_map.has(mk)) { RS::get_singleton()->material_set_shader(_get_material(), shader_map[mk].shader); shader_map[mk].users++; return; } //must create a shader! String code = ""shader_type particles;\\n""; code += ""uniform vec3 direction;\\n""; code += ""uniform float spread;\\n""; code += ""uniform float flatness;\\n""; code += ""uniform float initial_linear_velocity;\\n""; code += ""uniform float initial_angle;\\n""; code += ""uniform float angular_velocity;\\n""; code += ""uniform float orbit_velocity;\\n""; code += ""uniform float linear_accel;\\n""; code += ""uniform float radial_accel;\\n""; code += ""uniform float tangent_accel;\\n""; code += ""uniform float damping;\\n""; code += ""uniform float scale;\\n""; code += ""uniform float hue_variation;\\n""; code += ""uniform float anim_speed;\\n""; code += ""uniform float anim_offset;\\n""; code += ""uniform float initial_linear_velocity_random;\\n""; code += ""uniform float initial_angle_random;\\n""; code += ""uniform float angular_velocity_random;\\n""; code += ""uniform float orbit_velocity_random;\\n""; code += ""uniform float linear_accel_random;\\n""; code += ""uniform float radial_accel_random;\\n""; code += ""uniform float tangent_accel_random;\\n""; code += ""uniform float damping_random;\\n""; code += ""uniform float scale_random;\\n""; code += ""uniform float hue_variation_random;\\n""; code += ""uniform float anim_speed_random;\\n""; code += ""uniform float anim_offset_random;\\n""; code += ""uniform float lifetime_randomness;\\n""; switch (emission_shape) { case EMISSION_SHAPE_POINT: { //do none } break; case EMISSION_SHAPE_SPHERE: { code += ""uniform float emission_sphere_radius;\\n""; } break; case EMISSION_SHAPE_BOX: { code += ""uniform vec3 emission_box_extents;\\n""; } break; case EMISSION_SHAPE_DIRECTED_POINTS: { code += ""uniform sampler2D emission_texture_normal : hint_black;\\n""; [[fallthrough]]; } case EMISSION_SHAPE_POINTS: { code += ""uniform sampler2D emission_texture_points : hint_black;\\n""; code += ""uniform int emission_texture_point_count;\\n""; if (emission_color_texture.is_valid()) { code += ""uniform sampler2D emission_texture_color : hint_white;\\n""; } } break; case EMISSION_SHAPE_MAX: { // Max value for validity check. break; } } code += ""uniform vec4 color_value : hint_color;\\n""; code += ""uniform int trail_divisor;\\n""; code += ""uniform vec3 gravity;\\n""; if (color_ramp.is_valid()) code += ""uniform sampler2D color_ramp;\\n""; if (tex_parameters[PARAM_INITIAL_LINEAR_VELOCITY].is_valid()) code += ""uniform sampler2D linear_velocity_texture;\\n""; if (tex_parameters[PARAM_ORBIT_VELOCITY].is_valid()) code += ""uniform sampler2D orbit_velocity_texture;\\n""; if (tex_parameters[PARAM_ANGULAR_VELOCITY].is_valid()) code += ""uniform sampler2D angular_velocity_texture;\\n""; if (tex_parameters[PARAM_LINEAR_ACCEL].is_valid()) code += ""uniform sampler2D linear_accel_texture;\\n""; if (tex_parameters[PARAM_RADIAL_ACCEL].is_valid()) code += ""uniform sampler2D radial_accel_texture;\\n""; if (tex_parameters[PARAM_TANGENTIAL_ACCEL].is_valid()) code += ""uniform sampler2D tangent_accel_texture;\\n""; if (tex_parameters[PARAM_DAMPING].is_valid()) code += ""uniform sampler2D damping_texture;\\n""; if (tex_parameters[PARAM_ANGLE].is_valid()) code += ""uniform sampler2D angle_texture;\\n""; if (tex_parameters[PARAM_SCALE].is_valid()) code += ""uniform sampler2D scale_texture;\\n""; if (tex_parameters[PARAM_HUE_VARIATION].is_valid()) code += ""uniform sampler2D hue_variation_texture;\\n""; if (tex_parameters[PARAM_ANIM_SPEED].is_valid()) code += ""uniform sampler2D anim_speed_texture;\\n""; if (tex_parameters[PARAM_ANIM_OFFSET].is_valid()) code += ""uniform sampler2D anim_offset_texture;\\n""; if (trail_size_modifier.is_valid()) { code += ""uniform sampler2D trail_size_modifier;\\n""; } if (trail_color_modifier.is_valid()) { code += ""uniform sampler2D trail_color_modifier;\\n""; } //need a random function code += ""\\n\\n""; code += ""float rand_from_seed(inout uint seed) {\\n""; code += "" int k;\\n""; code += "" int s = int(seed);\\n""; code += "" if (s == 0)\\n""; code += "" s = 305420679;\\n""; code += "" k = s / 127773;\\n""; code += "" s = 16807 * (s - k * 127773) - 2836 * k;\\n""; code += "" if (s < 0)\\n""; code += "" s += 2147483647;\\n""; code += "" seed = uint(s);\\n""; code += "" return float(seed % uint(65536)) / 65535.0;\\n""; code += ""}\\n""; code += ""\\n""; code += ""float rand_from_seed_m1_p1(inout uint seed) {\\n""; code += "" return rand_from_seed(seed) * 2.0 - 1.0;\\n""; code += ""}\\n""; code += ""\\n""; //improve seed quality code += ""uint hash(uint x) {\\n""; code += "" x = ((x >> uint(16)) ^ x) * uint(73244475);\\n""; code += "" x = ((x >> uint(16)) ^ x) * uint(73244475);\\n""; code += "" x = (x >> uint(16)) ^ x;\\n""; code += "" return x;\\n""; code += ""}\\n""; code += ""\\n""; code += ""void vertex() {\\n""; code += "" uint base_number = NUMBER / uint(trail_divisor);\\n""; code += "" uint alt_seed = hash(base_number + uint(1) + RANDOM_SEED);\\n""; code += "" float angle_rand = rand_from_seed(alt_seed);\\n""; code += "" float scale_rand = rand_from_seed(alt_seed);\\n""; code += "" float hue_rot_rand = rand_from_seed(alt_seed);\\n""; code += "" float anim_offset_rand = rand_from_seed(alt_seed);\\n""; code += "" float pi = 3.14159;\\n""; code += "" float degree_to_rad = pi / 180.0;\\n""; code += ""\\n""; if (emission_shape == EMISSION_SHAPE_POINTS || emission_shape == EMISSION_SHAPE_DIRECTED_POINTS) { code += "" int point = min(emission_texture_point_count - 1, int(rand_from_seed(alt_seed) * float(emission_texture_point_count)));\\n""; code += "" ivec2 emission_tex_size = textureSize(emission_texture_points, 0);\\n""; code += "" ivec2 emission_tex_ofs = ivec2(point % emission_tex_size.x, point / emission_tex_size.x);\\n""; } code += "" bool restart = false;\\n""; code += "" if (CUSTOM.y > CUSTOM.w) {\\n""; code += "" restart = true;\\n""; code += "" }\\n\\n""; code += "" if (RESTART || restart) {\\n""; if (tex_parameters[PARAM_INITIAL_LINEAR_VELOCITY].is_valid()) code += "" float tex_linear_velocity = textureLod(linear_velocity_texture, vec2(0.0, 0.0), 0.0).r;\\n""; else code += "" float tex_linear_velocity = 0.0;\\n""; if (tex_parameters[PARAM_ANGLE].is_valid()) code += "" float tex_angle = textureLod(angle_texture, vec2(0.0, 0.0), 0.0).r;\\n""; else code += "" float tex_angle = 0.0;\\n""; if (tex_parameters[PARAM_ANIM_OFFSET].is_valid()) code += "" float tex_anim_offset = textureLod(anim_offset_texture, vec2(0.0, 0.0), 0.0).r;\\n""; else code += "" float tex_anim_offset = 0.0;\\n""; code += "" float spread_rad = spread * degree_to_rad;\\n""; if (flags[FLAG_DISABLE_Z]) { code += "" float angle1_rad = rand_from_seed_m1_p1(alt_seed) * spread_rad;\\n""; code += "" angle1_rad += direction.x != 0.0 ? atan(direction.y, direction.x) : sign(direction.y) * (pi / 2.0);\\n""; code += "" vec3 rot = vec3(cos(angle1_rad), sin(angle1_rad), 0.0);\\n""; code += "" VELOCITY = rot * initial_linear_velocity * mix(1.0, rand_from_seed(alt_seed), initial_linear_velocity_random);\\n""; } else { //initiate velocity spread in 3D code += "" float angle1_rad = rand_from_seed_m1_p1(alt_seed) * spread_rad;\\n""; code += "" float angle2_rad = rand_from_seed_m1_p1(alt_seed) * spread_rad * (1.0 - flatness);\\n""; code += "" angle1_rad += direction.z != 0.0 ? atan(direction.x, direction.z) : sign(direction.x) * (pi / 2.0);\\n""; code += "" angle2_rad += direction.z != 0.0 ? atan(direction.y, abs(direction.z)) : (direction.x != 0.0 ? atan(direction.y, abs(direction.x)) : sign(direction.y) * (pi / 2.0));\\n""; code += "" vec3 direction_xz = vec3(sin(angle1_rad), 0.0, cos(angle1_rad));\\n""; code += "" vec3 direction_yz = vec3(0.0, sin(angle2_rad), cos(angle2_rad));\\n""; code += "" direction_yz.z = direction_yz.z / max(0.0001,sqrt(abs(direction_yz.z))); // better uniform distribution\\n""; code += "" vec3 vec_direction = vec3(direction_xz.x * direction_yz.z, direction_yz.y, direction_xz.z * direction_yz.z);\\n""; code += "" vec_direction = normalize(vec_direction);\\n""; code += "" VELOCITY = vec_direction * initial_linear_velocity * mix(1.0, rand_from_seed(alt_seed), initial_linear_velocity_random);\\n""; } code += "" float base_angle = (initial_angle + tex_angle) * mix(1.0, angle_rand, initial_angle_random);\\n""; code += "" CUSTOM.x = base_angle * degree_to_rad;\\n""; // angle code += "" CUSTOM.y = 0.0;\\n""; // phase code += "" CUSTOM.w = (1.0 - lifetime_randomness * rand_from_seed(alt_seed));\\n""; code += "" CUSTOM.z = (anim_offset + tex_anim_offset) * mix(1.0, anim_offset_rand, anim_offset_random);\\n""; // animation offset (0-1) switch (emission_shape) { case EMISSION_SHAPE_POINT: { //do none } break; case EMISSION_SHAPE_SPHERE: { code += "" float s = rand_from_seed(alt_seed) * 2.0 - 1.0;\\n""; code += "" float t = rand_from_seed(alt_seed) * 2.0 * pi;\\n""; code += "" float radius = emission_sphere_radius * sqrt(1.0 - s * s);\\n""; code += "" TRANSFORM[3].xyz = vec3(radius * cos(t), radius * sin(t), emission_sphere_radius * s);\\n""; } break; case EMISSION_SHAPE_BOX: { code += "" TRANSFORM[3].xyz = vec3(rand_from_seed(alt_seed) * 2.0 - 1.0, rand_from_seed(alt_seed) * 2.0 - 1.0, rand_from_seed(alt_seed) * 2.0 - 1.0) * emission_box_extents;\\n""; } break; case EMISSION_SHAPE_POINTS: case EMISSION_SHAPE_DIRECTED_POINTS: { code += "" TRANSFORM[3].xyz = texelFetch(emission_texture_points, emission_tex_ofs, 0).xyz;\\n""; if (emission_shape == EMISSION_SHAPE_DIRECTED_POINTS) { if (flags[FLAG_DISABLE_Z]) { code += "" mat2 rotm;""; code += "" rotm[0] = texelFetch(emission_texture_normal, emission_tex_ofs, 0).xy;\\n""; code += "" rotm[1] = rotm[0].yx * vec2(1.0, -1.0);\\n""; code += "" VELOCITY.xy = rotm * VELOCITY.xy;\\n""; } else { code += "" vec3 normal = texelFetch(emission_texture_normal, emission_tex_ofs, 0).xyz;\\n""; code += "" vec3 v0 = abs(normal.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(0.0, 1.0, 0.0);\\n""; code += "" vec3 tangent = normalize(cross(v0, normal));\\n""; code += "" vec3 bitangent = normalize(cross(tangent, normal));\\n""; code += "" VELOCITY = mat3(tangent, bitangent, normal) * VELOCITY;\\n""; } } } break; case EMISSION_SHAPE_MAX: { // Max value for validity check. break; } } code += "" VELOCITY = (EMISSION_TRANSFORM * vec4(VELOCITY, 0.0)).xyz;\\n""; code += "" TRANSFORM = EMISSION_TRANSFORM * TRANSFORM;\\n""; if (flags[FLAG_DISABLE_Z]) { code += "" VELOCITY.z = 0.0;\\n""; code += "" TRANSFORM[3].z = 0.0;\\n""; } code += "" } else {\\n""; code += "" CUSTOM.y += DELTA / LIFETIME;\\n""; if (tex_parameters[PARAM_INITIAL_LINEAR_VELOCITY].is_valid()) code += "" float tex_linear_velocity = textureLod(linear_velocity_texture, vec2(CUSTOM.y, 0.0), 0.0).r;\\n""; else code += "" float tex_linear_velocity = 0.0;\\n""; if (flags[FLAG_DISABLE_Z]) { if (tex_parameters[PARAM_ORBIT_VELOCITY].is_valid()) code += "" float tex_orbit_velocity = textureLod(orbit_velocity_texture, vec2(CUSTOM.y, 0.0), 0.0).r;\\n""; else code += "" float tex_orbit_velocity = 0.0;\\n""; } if (tex_parameters[PARAM_ANGULAR_VELOCITY].is_valid()) code += "" float tex_angular_velocity = textureLod(angular_velocity_texture, vec2(CUSTOM.y, 0.0), 0.0).r;\\n""; else code += "" float tex_angular_velocity = 0.0;\\n""; if (tex_parameters[PARAM_LINEAR_ACCEL].is_valid()) code += "" float tex_linear_accel = textureLod(linear_accel_texture, vec2(CUSTOM.y, 0.0), 0.0).r;\\n""; else code += "" float tex_linear_accel = 0.0;\\n""; if (tex_parameters[PARAM_RADIAL_ACCEL].is_valid()) code += "" float tex_radial_accel = textureLod(radial_accel_texture, vec2(CUSTOM.y, 0.0), 0.0).r;\\n""; else code += "" float tex_radial_accel = 0.0;\\n""; if (tex_parameters[PARAM_TANGENTIAL_ACCEL].is_valid()) code += "" float tex_tangent_accel = textureLod(tangent_accel_texture, vec2(CUSTOM.y, 0.0), 0.0).r;\\n""; else code += "" float tex_tangent_accel = 0.0;\\n""; if (tex_parameters[PARAM_DAMPING].is_valid()) code += "" float tex_damping = textureLod(damping_texture, vec2(CUSTOM.y, 0.0), 0.0).r;\\n""; else code += "" float tex_damping = 0.0;\\n""; if (tex_parameters[PARAM_ANGLE].is_valid()) code += "" float tex_angle = textureLod(angle_texture, vec2(CUSTOM.y, 0.0), 0.0).r;\\n""; else code += "" float tex_angle = 0.0;\\n""; if (tex_parameters[PARAM_ANIM_SPEED].is_valid()) code += "" float tex_anim_speed = textureLod(anim_speed_texture, vec2(CUSTOM.y, 0.0), 0.0).r;\\n""; else code += "" float tex_anim_speed = 0.0;\\n""; if (tex_parameters[PARAM_ANIM_OFFSET].is_valid()) code += "" float tex_anim_offset = textureLod(anim_offset_texture, vec2(CUSTOM.y, 0.0), 0.0).r;\\n""; else code += "" float tex_anim_offset = 0.0;\\n""; code += "" vec3 force = gravity;\\n""; code += "" vec3 pos = TRANSFORM[3].xyz;\\n""; if (flags[FLAG_DISABLE_Z]) { code += "" pos.z = 0.0;\\n""; } code += "" // apply linear acceleration\\n""; code += "" force += length(VELOCITY) > 0.0 ? normalize(VELOCITY) * (linear_accel + tex_linear_accel) * mix(1.0, rand_from_seed(alt_seed), linear_accel_random) : vec3(0.0);\\n""; code += "" // apply radial acceleration\\n""; code += "" vec3 org = EMISSION_TRANSFORM[3].xyz;\\n""; code += "" vec3 diff = pos - org;\\n""; code += "" force += length(diff) > 0.0 ? normalize(diff) * (radial_accel + tex_radial_accel) * mix(1.0, rand_from_seed(alt_seed), radial_accel_random) : vec3(0.0);\\n""; code += "" // apply tangential acceleration;\\n""; if (flags[FLAG_DISABLE_Z]) { code += "" force += length(diff.yx) > 0.0 ? vec3(normalize(diff.yx * vec2(-1.0, 1.0)), 0.0) * ((tangent_accel + tex_tangent_accel) * mix(1.0, rand_from_seed(alt_seed), tangent_accel_random)) : vec3(0.0);\\n""; } else { code += "" vec3 crossDiff = cross(normalize(diff), normalize(gravity));\\n""; code += "" force += length(crossDiff) > 0.0 ? normalize(crossDiff) * ((tangent_accel + tex_tangent_accel) * mix(1.0, rand_from_seed(alt_seed), tangent_accel_random)) : vec3(0.0);\\n""; } code += "" // apply attractor forces\\n""; code += "" VELOCITY += force * DELTA;\\n""; code += "" // orbit velocity\\n""; if (flags[FLAG_DISABLE_Z]) { code += "" float orbit_amount = (orbit_velocity + tex_orbit_velocity) * mix(1.0, rand_from_seed(alt_seed), orbit_velocity_random);\\n""; code += "" if (orbit_amount != 0.0) {\\n""; code += "" float ang = orbit_amount * DELTA * pi * 2.0;\\n""; code += "" mat2 rot = mat2(vec2(cos(ang), -sin(ang)), vec2(sin(ang), cos(ang)));\\n""; code += "" TRANSFORM[3].xy -= diff.xy;\\n""; code += "" TRANSFORM[3].xy += rot * diff.xy;\\n""; code += "" }\\n""; } if (tex_parameters[PARAM_INITIAL_LINEAR_VELOCITY].is_valid()) { code += "" VELOCITY = normalize(VELOCITY) * tex_linear_velocity;\\n""; } code += "" if (damping + tex_damping > 0.0) {\\n""; code += "" float v = length(VELOCITY);\\n""; code += "" float damp = (damping + tex_damping) * mix(1.0, rand_from_seed(alt_seed), damping_random);\\n""; code += "" v -= damp * DELTA;\\n""; code += "" if (v < 0.0) {\\n""; code += "" VELOCITY = vec3(0.0);\\n""; code += "" } else {\\n""; code += "" VELOCITY = normalize(VELOCITY) * v;\\n""; code += "" }\\n""; code += "" }\\n""; code += "" float base_angle = (initial_angle + tex_angle) * mix(1.0, angle_rand, initial_angle_random);\\n""; code += "" base_angle += CUSTOM.y * LIFETIME * (angular_velocity + tex_angular_velocity) * mix(1.0, rand_from_seed(alt_seed) * 2.0 - 1.0, angular_velocity_random);\\n""; code += "" CUSTOM.x = base_angle * degree_to_rad;\\n""; // angle code += "" CUSTOM.z = (anim_offset + tex_anim_offset) * mix(1.0, anim_offset_rand, anim_offset_random) + CUSTOM.y * (anim_speed + tex_anim_speed) * mix(1.0, rand_from_seed(alt_seed), anim_speed_random);\\n""; // angle code += "" }\\n""; // apply color // apply hue rotation if (tex_parameters[PARAM_SCALE].is_valid()) code += "" float tex_scale = textureLod(scale_texture, vec2(CUSTOM.y, 0.0), 0.0).r;\\n""; else code += "" float tex_scale = 1.0;\\n""; if (tex_parameters[PARAM_HUE_VARIATION].is_valid()) code += "" float tex_hue_variation = textureLod(hue_variation_texture, vec2(CUSTOM.y, 0.0), 0.0).r;\\n""; else code += "" float tex_hue_variation = 0.0;\\n""; code += "" float hue_rot_angle = (hue_variation + tex_hue_variation) * pi * 2.0 * mix(1.0, hue_rot_rand * 2.0 - 1.0, hue_variation_random);\\n""; code += "" float hue_rot_c = cos(hue_rot_angle);\\n""; code += "" float hue_rot_s = sin(hue_rot_angle);\\n""; code += "" mat4 hue_rot_mat = mat4(vec4(0.299, 0.587, 0.114, 0.0),\\n""; code += "" vec4(0.299, 0.587, 0.114, 0.0),\\n""; code += "" vec4(0.299, 0.587, 0.114, 0.0),\\n""; code += "" vec4(0.000, 0.000, 0.000, 1.0)) +\\n""; code += "" mat4(vec4(0.701, -0.587, -0.114, 0.0),\\n""; code += "" vec4(-0.299, 0.413, -0.114, 0.0),\\n""; code += "" vec4(-0.300, -0.588, 0.886, 0.0),\\n""; code += "" vec4(0.000, 0.000, 0.000, 0.0)) * hue_rot_c +\\n""; code += "" mat4(vec4(0.168, 0.330, -0.497, 0.0),\\n""; code += "" vec4(-0.328, 0.035, 0.292, 0.0),\\n""; code += "" vec4(1.250, -1.050, -0.203, 0.0),\\n""; code += "" vec4(0.000, 0.000, 0.000, 0.0)) * hue_rot_s;\\n""; if (color_ramp.is_valid()) { code += "" COLOR = hue_rot_mat * textureLod(color_ramp, vec2(CUSTOM.y, 0.0), 0.0);\\n""; } else { code += "" COLOR = hue_rot_mat * color_value;\\n""; } if (emission_color_texture.is_valid() && (emission_shape == EMISSION_SHAPE_POINTS || emission_shape == EMISSION_SHAPE_DIRECTED_POINTS)) { code += "" COLOR *= texelFetch(emission_texture_color, emission_tex_ofs, 0);\\n""; } if (trail_color_modifier.is_valid()) { code += "" if (trail_divisor > 1) {\\n""; code += "" COLOR *= textureLod(trail_color_modifier, vec2(float(int(NUMBER) % trail_divisor) / float(trail_divisor - 1), 0.0), 0.0);\\n""; code += "" }\\n""; } code += ""\\n""; if (flags[FLAG_DISABLE_Z]) { if (flags[FLAG_ALIGN_Y_TO_VELOCITY]) { code += "" if (length(VELOCITY) > 0.0) {\\n""; code += "" TRANSFORM[1].xyz = normalize(VELOCITY);\\n""; code += "" } else {\\n""; code += "" TRANSFORM[1].xyz = normalize(TRANSFORM[1].xyz);\\n""; code += "" }\\n""; code += "" TRANSFORM[0].xyz = normalize(cross(TRANSFORM[1].xyz, TRANSFORM[2].xyz));\\n""; code += "" TRANSFORM[2] = vec4(0.0, 0.0, 1.0, 0.0);\\n""; } else { code += "" TRANSFORM[0] = vec4(cos(CUSTOM.x), -sin(CUSTOM.x), 0.0, 0.0);\\n""; code += "" TRANSFORM[1] = vec4(sin(CUSTOM.x), cos(CUSTOM.x), 0.0, 0.0);\\n""; code += "" TRANSFORM[2] = vec4(0.0, 0.0, 1.0, 0.0);\\n""; } } else { // orient particle Y towards velocity if (flags[FLAG_ALIGN_Y_TO_VELOCITY]) { code += "" if (length(VELOCITY) > 0.0) {\\n""; code += "" TRANSFORM[1].xyz = normalize(VELOCITY);\\n""; code += "" } else {\\n""; code += "" TRANSFORM[1].xyz = normalize(TRANSFORM[1].xyz);\\n""; code += "" }\\n""; code += "" if (TRANSFORM[1].xyz == normalize(TRANSFORM[0].xyz)) {\\n""; code += "" TRANSFORM[0].xyz = normalize(cross(normalize(TRANSFORM[1].xyz), normalize(TRANSFORM[2].xyz)));\\n""; code += "" TRANSFORM[2].xyz = normalize(cross(normalize(TRANSFORM[0].xyz), normalize(TRANSFORM[1].xyz)));\\n""; code += "" } else {\\n""; code += "" TRANSFORM[2].xyz = normalize(cross(normalize(TRANSFORM[0].xyz), normalize(TRANSFORM[1].xyz)));\\n""; code += "" TRANSFORM[0].xyz = normalize(cross(normalize(TRANSFORM[1].xyz), normalize(TRANSFORM[2].xyz)));\\n""; code += "" }\\n""; } else { code += "" TRANSFORM[0].xyz = normalize(TRANSFORM[0].xyz);\\n""; code += "" TRANSFORM[1].xyz = normalize(TRANSFORM[1].xyz);\\n""; code += "" TRANSFORM[2].xyz = normalize(TRANSFORM[2].xyz);\\n""; } // turn particle by rotation in Y if (flags[FLAG_ROTATE_Y]) { code += "" TRANSFORM = TRANSFORM * mat4(vec4(cos(CUSTOM.x), 0.0, -sin(CUSTOM.x), 0.0), vec4(0.0, 1.0, 0.0, 0.0), vec4(sin(CUSTOM.x), 0.0, cos(CUSTOM.x), 0.0), vec4(0.0, 0.0, 0.0, 1.0));\\n""; } } //scale by scale code += "" float base_scale = tex_scale * mix(scale, 1.0, scale_random * scale_rand);\\n""; code += "" if (base_scale < 0.000001) {\\n""; code += "" base_scale = 0.000001;\\n""; code += "" }\\n""; if (trail_size_modifier.is_valid()) { code += "" if (trail_divisor > 1) {\\n""; code += "" base_scale *= textureLod(trail_size_modifier, vec2(float(int(NUMBER) % trail_divisor) / float(trail_divisor - 1), 0.0), 0.0).r;\\n""; code += "" }\\n""; } code += "" TRANSFORM[0].xyz *= base_scale;\\n""; code += "" TRANSFORM[1].xyz *= base_scale;\\n""; code += "" TRANSFORM[2].xyz *= base_scale;\\n""; if (flags[FLAG_DISABLE_Z]) { code += "" VELOCITY.z = 0.0;\\n""; code += "" TRANSFORM[3].z = 0.0;\\n""; } code += "" if (CUSTOM.y > CUSTOM.w) {""; code += "" ACTIVE = false;\\n""; code += "" }\\n""; code += ""}\\n""; code += ""\\n""; ShaderData shader_data; shader_data.shader = RS::get_singleton()->shader_create(); shader_data.users = 1; RS::get_singleton()->shader_set_code(shader_data.shader, code); shader_map[mk] = shader_data; RS::get_singleton()->material_set_shader(_get_material(), shader_data.shader); } void ParticlesMaterial::flush_changes() { MutexLock lock(material_mutex); while (dirty_materials->first()) { dirty_materials->first()->self()->_update_shader(); } } void ParticlesMaterial::_queue_shader_change() { MutexLock lock(material_mutex); if (!element.in_list()) { dirty_materials->add(&element); } } bool ParticlesMaterial::_is_shader_dirty() const { MutexLock lock(material_mutex); return element.in_list(); } void ParticlesMaterial::set_direction(Vector3 p_direction) { direction = p_direction; RenderingServer::get_singleton()->material_set_param(_get_material(), shader_names->direction, direction); } Vector3 ParticlesMaterial::get_direction() const { return direction; } void ParticlesMaterial::set_spread(float p_spread) { spread = p_spread; RenderingServer::get_singleton()->material_set_param(_get_material(), shader_names->spread, p_spread); } float ParticlesMaterial::get_spread() const { return spread; } void ParticlesMaterial::set_flatness(float p_flatness) { flatness = p_flatness; RenderingServer::get_singleton()->material_set_param(_get_material(), shader_names->flatness, p_flatness); } float ParticlesMaterial::get_flatness() const { return flatness; } void ParticlesMaterial::set_param(Parameter p_param, float p_value) { ERR_FAIL_INDEX(p_param, PARAM_MAX); parameters[p_param] = p_value; switch (p_param) { case PARAM_INITIAL_LINEAR_VELOCITY: { RenderingServer::get_singleton()->material_set_param(_get_material(), shader_names->initial_linear_velocity, p_value); } break; case PARAM_ANGULAR_VELOCITY: { RenderingServer::get_singleton()->material_set_param(_get_material(), shader_names->angular_velocity, p_value); } break; case PARAM_ORBIT_VELOCITY: { RenderingServer::get_singleton()->material_set_param(_get_material(), shader_names->orbit_velocity, p_value); } break; case PARAM_LINEAR_ACCEL: { RenderingServer::get_singleton()->material_set_param(_get_material(), shader_names->linear_accel, p_value); } break; case PARAM_RADIAL_ACCEL: { RenderingServer::get_singleton()->material_set_param(_get_material(), shader_names->radial_accel, p_value); } break; case PARAM_TANGENTIAL_ACCEL: { RenderingServer::get_singleton()->material_set_param(_get_material(), shader_names->tangent_accel, p_value); } break; case PARAM_DAMPING: { RenderingServer::get_singleton()->material_set_param(_get_material(), shader_names->damping, p_value); } break; case PARAM_ANGLE: { RenderingServer::get_singleton()->material_set_param(_get_material(), shader_names->initial_angle, p_value); } break; case PARAM_SCALE: { RenderingServer::get_singleton()->material_set_param(_get_material(), shader_names->scale, p_value); } break; case PARAM_HUE_VARIATION: { RenderingServer::get_singleton()->material_set_param(_get_material(), shader_names->hue_variation, p_value); } break; case PARAM_ANIM_SPEED: { RenderingServer::get_singleton()->material_set_param(_get_material(), shader_names->anim_speed, p_value); } break; case PARAM_ANIM_OFFSET: { RenderingServer::get_singleton()->material_set_param(_get_material(), shader_names->anim_offset, p_value); } break; case PARAM_MAX: break; // Can't happen, but silences warning } } float ParticlesMaterial::get_param(Parameter p_param) const { ERR_FAIL_INDEX_V(p_param, PARAM_MAX, 0); return parameters[p_param]; } void ParticlesMaterial::set_param_randomness(Parameter p_param, float p_value) { ERR_FAIL_INDEX(p_param, PARAM_MAX); randomness[p_param] = p_value; switch (p_param) { case PARAM_INITIAL_LINEAR_VELOCITY: { RenderingServer::get_singleton()->material_set_param(_get_material(), shader_names->initial_linear_velocity_random, p_value); } break; case PARAM_ANGULAR_VELOCITY: { RenderingServer::get_singleton()->material_set_param(_get_material(), shader_names->angular_velocity_random, p_value); } break; case PARAM_ORBIT_VELOCITY: { RenderingServer::get_singleton()->material_set_param(_get_material(), shader_names->orbit_velocity_random, p_value); } break; case PARAM_LINEAR_ACCEL: { RenderingServer::get_singleton()->material_set_param(_get_material(), shader_names->linear_accel_random, p_value); } break; case PARAM_RADIAL_ACCEL: { RenderingServer::get_singleton()->material_set_param(_get_material(), shader_names->radial_accel_random, p_value); } break; case PARAM_TANGENTIAL_ACCEL: { RenderingServer::get_singleton()->material_set_param(_get_material(), shader_names->tangent_accel_random, p_value); } break; case PARAM_DAMPING: { RenderingServer::get_singleton()->material_set_param(_get_material(), shader_names->damping_random, p_value); } break; case PARAM_ANGLE: { RenderingServer::get_singleton()->material_set_param(_get_material(), shader_names->initial_angle_random, p_value); } break; case PARAM_SCALE: { RenderingServer::get_singleton()->material_set_param(_get_material(), shader_names->scale_random, p_value); } break; case PARAM_HUE_VARIATION: { RenderingServer::get_singleton()->material_set_param(_get_material(), shader_names->hue_variation_random, p_value); } break; case PARAM_ANIM_SPEED: { RenderingServer::get_singleton()->material_set_param(_get_material(), shader_names->anim_speed_random, p_value); } break; case PARAM_ANIM_OFFSET: { RenderingServer::get_singleton()->material_set_param(_get_material(), shader_names->anim_offset_random, p_value); } break; case PARAM_MAX: break; // Can't happen, but silences warning } } float ParticlesMaterial::get_param_randomness(Parameter p_param) const { ERR_FAIL_INDEX_V(p_param, PARAM_MAX, 0); return randomness[p_param]; } static void _adjust_curve_range(const Ref &p_texture, float p_min, float p_max) { Ref curve_tex = p_texture; if (!curve_tex.is_valid()) return; curve_tex->ensure_default_setup(p_min, p_max); } void ParticlesMaterial::set_param_texture(Parameter p_param, const Ref &p_texture) { ERR_FAIL_INDEX(p_param, PARAM_MAX); tex_parameters[p_param] = p_texture; switch (p_param) { case PARAM_INITIAL_LINEAR_VELOCITY: { //do none for this one } break; case PARAM_ANGULAR_VELOCITY: { RenderingServer::get_singleton()->material_set_param(_get_material(), shader_names->angular_velocity_texture, p_texture); _adjust_curve_range(p_texture, -360, 360); } break; case PARAM_ORBIT_VELOCITY: { RenderingServer::get_singleton()->material_set_param(_get_material(), shader_names->orbit_velocity_texture, p_texture); _adjust_curve_range(p_texture, -500, 500); } break; case PARAM_LINEAR_ACCEL: { RenderingServer::get_singleton()->material_set_param(_get_material(), shader_names->linear_accel_texture, p_texture); _adjust_curve_range(p_texture, -200, 200); } break; case PARAM_RADIAL_ACCEL: { RenderingServer::get_singleton()->material_set_param(_get_material(), shader_names->radial_accel_texture, p_texture); _adjust_curve_range(p_texture, -200, 200); } break; case PARAM_TANGENTIAL_ACCEL: { RenderingServer::get_singleton()->material_set_param(_get_material(), shader_names->tangent_accel_texture, p_texture); _adjust_curve_range(p_texture, -200, 200); } break; case PARAM_DAMPING: { RenderingServer::get_singleton()->material_set_param(_get_material(), shader_names->damping_texture, p_texture); _adjust_curve_range(p_texture, 0, 100); } break; case PARAM_ANGLE: { RenderingServer::get_singleton()->material_set_param(_get_material(), shader_names->angle_texture, p_texture); _adjust_curve_range(p_texture, -360, 360); } break; case PARAM_SCALE: { RenderingServer::get_singleton()->material_set_param(_get_material(), shader_names->scale_texture, p_texture); _adjust_curve_range(p_texture, 0, 1); } break; case PARAM_HUE_VARIATION: { RenderingServer::get_singleton()->material_set_param(_get_material(), shader_names->hue_variation_texture, p_texture); _adjust_curve_range(p_texture, -1, 1); } break; case PARAM_ANIM_SPEED: { RenderingServer::get_singleton()->material_set_param(_get_material(), shader_names->anim_speed_texture, p_texture); _adjust_curve_range(p_texture, 0, 200); } break; case PARAM_ANIM_OFFSET: { RenderingServer::get_singleton()->material_set_param(_get_material(), shader_names->anim_offset_texture, p_texture); } break; case PARAM_MAX: break; // Can't happen, but silences warning } _queue_shader_change(); } Ref ParticlesMaterial::get_param_texture(Parameter p_param) const { ERR_FAIL_INDEX_V(p_param, PARAM_MAX, Ref()); return tex_parameters[p_param]; } void ParticlesMaterial::set_color(const Color &p_color) { RenderingServer::get_singleton()->material_set_param(_get_material(), shader_names->color, p_color); color = p_color; } Color ParticlesMaterial::get_color() const { return color; } void ParticlesMaterial::set_color_ramp(const Ref &p_texture) { color_ramp = p_texture; RenderingServer::get_singleton()->material_set_param(_get_material(), shader_names->color_ramp, p_texture); _queue_shader_change(); _change_notify(); } Ref ParticlesMaterial::get_color_ramp() const { return color_ramp; } void ParticlesMaterial::set_flag(Flags p_flag, bool p_enable) { ERR_FAIL_INDEX(p_flag, FLAG_MAX); flags[p_flag] = p_enable; _queue_shader_change(); if (p_flag == FLAG_DISABLE_Z) { _change_notify(); } } bool ParticlesMaterial::get_flag(Flags p_flag) const { ERR_FAIL_INDEX_V(p_flag, FLAG_MAX, false); return flags[p_flag]; } void ParticlesMaterial::set_emission_shape(EmissionShape p_shape) { ERR_FAIL_INDEX(p_shape, EMISSION_SHAPE_MAX); emission_shape = p_shape; _change_notify(); _queue_shader_change(); } void ParticlesMaterial::set_emission_sphere_radius(float p_radius) { emission_sphere_radius = p_radius; RenderingServer::get_singleton()->material_set_param(_get_material(), shader_names->emission_sphere_radius, p_radius); } void ParticlesMaterial::set_emission_box_extents(Vector3 p_extents) { emission_box_extents = p_extents; RenderingServer::get_singleton()->material_set_param(_get_material(), shader_names->emission_box_extents, p_extents); } void ParticlesMaterial::set_emission_point_texture(const Ref &p_points) { emission_point_texture = p_points; RenderingServer::get_singleton()->material_set_param(_get_material(), shader_names->emission_texture_points, p_points); } void ParticlesMaterial::set_emission_normal_texture(const Ref &p_normals) { emission_normal_texture = p_normals; RenderingServer::get_singleton()->material_set_param(_get_material(), shader_names->emission_texture_normal, p_normals); } void ParticlesMaterial::set_emission_color_texture(const Ref &p_colors) { emission_color_texture = p_colors; RenderingServer::get_singleton()->material_set_param(_get_material(), shader_names->emission_texture_color, p_colors); _queue_shader_change(); } void ParticlesMaterial::set_emission_point_count(int p_count) { emission_point_count = p_count; RenderingServer::get_singleton()->material_set_param(_get_material(), shader_names->emission_texture_point_count, p_count); } ParticlesMaterial::EmissionShape ParticlesMaterial::get_emission_shape() const { return emission_shape; } float ParticlesMaterial::get_emission_sphere_radius() const { return emission_sphere_radius; } Vector3 ParticlesMaterial::get_emission_box_extents() const { return emission_box_extents; } Ref ParticlesMaterial::get_emission_point_texture() const { return emission_point_texture; } Ref ParticlesMaterial::get_emission_normal_texture() const { return emission_normal_texture; } Ref ParticlesMaterial::get_emission_color_texture() const { return emission_color_texture; } int ParticlesMaterial::get_emission_point_count() const { return emission_point_count; } void ParticlesMaterial::set_trail_divisor(int p_divisor) { trail_divisor = p_divisor; RenderingServer::get_singleton()->material_set_param(_get_material(), shader_names->trail_divisor, p_divisor); } int ParticlesMaterial::get_trail_divisor() const { return trail_divisor; } void ParticlesMaterial::set_trail_size_modifier(const Ref &p_trail_size_modifier) { trail_size_modifier = p_trail_size_modifier; Ref curve = trail_size_modifier; if (curve.is_valid()) { curve->ensure_default_setup(); } RenderingServer::get_singleton()->material_set_param(_get_material(), shader_names->trail_size_modifier, curve); _queue_shader_change(); } Ref ParticlesMaterial::get_trail_size_modifier() const { return trail_size_modifier; } void ParticlesMaterial::set_trail_color_modifier(const Ref &p_trail_color_modifier) { trail_color_modifier = p_trail_color_modifier; RenderingServer::get_singleton()->material_set_param(_get_material(), shader_names->trail_color_modifier, p_trail_color_modifier); _queue_shader_change(); } Ref ParticlesMaterial::get_trail_color_modifier() const { return trail_color_modifier; } void ParticlesMaterial::set_gravity(const Vector3 &p_gravity) { gravity = p_gravity; Vector3 gset = gravity; if (gset == Vector3()) { gset = Vector3(0, -0.000001, 0); //as gravity is used as upvector in some calculations } RenderingServer::get_singleton()->material_set_param(_get_material(), shader_names->gravity, gset); } Vector3 ParticlesMaterial::get_gravity() const { return gravity; } void ParticlesMaterial::set_lifetime_randomness(float p_lifetime) { lifetime_randomness = p_lifetime; RenderingServer::get_singleton()->material_set_param(_get_material(), shader_names->lifetime_randomness, lifetime_randomness); } float ParticlesMaterial::get_lifetime_randomness() const { return lifetime_randomness; } RID ParticlesMaterial::get_shader_rid() const { ERR_FAIL_COND_V(!shader_map.has(current_key), RID()); return shader_map[current_key].shader; } void ParticlesMaterial::_validate_property(PropertyInfo &property) const { if (property.name == ""color"" && color_ramp.is_valid()) { property.usage = 0; } if (property.name == ""emission_sphere_radius"" && emission_shape != EMISSION_SHAPE_SPHERE) { property.usage = 0; } if (property.name == ""emission_box_extents"" && emission_shape != EMISSION_SHAPE_BOX) { property.usage = 0; } if ((property.name == ""emission_point_texture"" || property.name == ""emission_color_texture"") && (emission_shape < EMISSION_SHAPE_POINTS)) { property.usage = 0; } if (property.name == ""emission_normal_texture"" && emission_shape != EMISSION_SHAPE_DIRECTED_POINTS) { property.usage = 0; } if (property.name == ""emission_point_count"" && (emission_shape != EMISSION_SHAPE_POINTS && emission_shape != EMISSION_SHAPE_DIRECTED_POINTS)) { property.usage = 0; } if (property.name.begins_with(""orbit_"") && !flags[FLAG_DISABLE_Z]) { property.usage = 0; } } Shader::Mode ParticlesMaterial::get_shader_mode() const { return Shader::MODE_PARTICLES; } void ParticlesMaterial::_bind_methods() { ClassDB::bind_method(D_METHOD(""set_direction"", ""degrees""), &ParticlesMaterial::set_direction); ClassDB::bind_method(D_METHOD(""get_direction""), &ParticlesMaterial::get_direction); ClassDB::bind_method(D_METHOD(""set_spread"", ""degrees""), &ParticlesMaterial::set_spread); ClassDB::bind_method(D_METHOD(""get_spread""), &ParticlesMaterial::get_spread); ClassDB::bind_method(D_METHOD(""set_flatness"", ""amount""), &ParticlesMaterial::set_flatness); ClassDB::bind_method(D_METHOD(""get_flatness""), &ParticlesMaterial::get_flatness); ClassDB::bind_method(D_METHOD(""set_param"", ""param"", ""value""), &ParticlesMaterial::set_param); ClassDB::bind_method(D_METHOD(""get_param"", ""param""), &ParticlesMaterial::get_param); ClassDB::bind_method(D_METHOD(""set_param_randomness"", ""param"", ""randomness""), &ParticlesMaterial::set_param_randomness); ClassDB::bind_method(D_METHOD(""get_param_randomness"", ""param""), &ParticlesMaterial::get_param_randomness); ClassDB::bind_method(D_METHOD(""set_param_texture"", ""param"", ""texture""), &ParticlesMaterial::set_param_texture); ClassDB::bind_method(D_METHOD(""get_param_texture"", ""param""), &ParticlesMaterial::get_param_texture); ClassDB::bind_method(D_METHOD(""set_color"", ""color""), &ParticlesMaterial::set_color); ClassDB::bind_method(D_METHOD(""get_color""), &ParticlesMaterial::get_color); ClassDB::bind_method(D_METHOD(""set_color_ramp"", ""ramp""), &ParticlesMaterial::set_color_ramp); ClassDB::bind_method(D_METHOD(""get_color_ramp""), &ParticlesMaterial::get_color_ramp); ClassDB::bind_method(D_METHOD(""set_flag"", ""flag"", ""enable""), &ParticlesMaterial::set_flag); ClassDB::bind_method(D_METHOD(""get_flag"", ""flag""), &ParticlesMaterial::get_flag); ClassDB::bind_method(D_METHOD(""set_emission_shape"", ""shape""), &ParticlesMaterial::set_emission_shape); ClassDB::bind_method(D_METHOD(""get_emission_shape""), &ParticlesMaterial::get_emission_shape); ClassDB::bind_method(D_METHOD(""set_emission_sphere_radius"", ""radius""), &ParticlesMaterial::set_emission_sphere_radius); ClassDB::bind_method(D_METHOD(""get_emission_sphere_radius""), &ParticlesMaterial::get_emission_sphere_radius); ClassDB::bind_method(D_METHOD(""set_emission_box_extents"", ""extents""), &ParticlesMaterial::set_emission_box_extents); ClassDB::bind_method(D_METHOD(""get_emission_box_extents""), &ParticlesMaterial::get_emission_box_extents); ClassDB::bind_method(D_METHOD(""set_emission_point_texture"", ""texture""), &ParticlesMaterial::set_emission_point_texture); ClassDB::bind_method(D_METHOD(""get_emission_point_texture""), &ParticlesMaterial::get_emission_point_texture); ClassDB::bind_method(D_METHOD(""set_emission_normal_texture"", ""texture""), &ParticlesMaterial::set_emission_normal_texture); ClassDB::bind_method(D_METHOD(""get_emission_normal_texture""), &ParticlesMaterial::get_emission_normal_texture); ClassDB::bind_method(D_METHOD(""set_emission_color_texture"", ""texture""), &ParticlesMaterial::set_emission_color_texture); ClassDB::bind_method(D_METHOD(""get_emission_color_texture""), &ParticlesMaterial::get_emission_color_texture); ClassDB::bind_method(D_METHOD(""set_emission_point_count"", ""point_count""), &ParticlesMaterial::set_emission_point_count); ClassDB::bind_method(D_METHOD(""get_emission_point_count""), &ParticlesMaterial::get_emission_point_count); ClassDB::bind_method(D_METHOD(""set_trail_divisor"", ""divisor""), &ParticlesMaterial::set_trail_divisor); ClassDB::bind_method(D_METHOD(""get_trail_divisor""), &ParticlesMaterial::get_trail_divisor); ClassDB::bind_method(D_METHOD(""set_trail_size_modifier"", ""texture""), &ParticlesMaterial::set_trail_size_modifier); ClassDB::bind_method(D_METHOD(""get_trail_size_modifier""), &ParticlesMaterial::get_trail_size_modifier); ClassDB::bind_method(D_METHOD(""set_trail_color_modifier"", ""texture""), &ParticlesMaterial::set_trail_color_modifier); ClassDB::bind_method(D_METHOD(""get_trail_color_modifier""), &ParticlesMaterial::get_trail_color_modifier); ClassDB::bind_method(D_METHOD(""get_gravity""), &ParticlesMaterial::get_gravity); ClassDB::bind_method(D_METHOD(""set_gravity"", ""accel_vec""), &ParticlesMaterial::set_gravity); ClassDB::bind_method(D_METHOD(""set_lifetime_randomness"", ""randomness""), &ParticlesMaterial::set_lifetime_randomness); ClassDB::bind_method(D_METHOD(""get_lifetime_randomness""), &ParticlesMaterial::get_lifetime_randomness); ADD_GROUP(""Time"", """"); ADD_PROPERTY(PropertyInfo(Variant::FLOAT, ""lifetime_randomness"", PROPERTY_HINT_RANGE, ""0,1,0.01""), ""set_lifetime_randomness"", ""get_lifetime_randomness""); ADD_GROUP(""Trail"", ""trail_""); ADD_PROPERTY(PropertyInfo(Variant::INT, ""trail_divisor"", PROPERTY_HINT_RANGE, ""1,1000000,1""), ""set_trail_divisor"", ""get_trail_divisor""); ADD_PROPERTY(PropertyInfo(Variant::OBJECT, ""trail_size_modifier"", PROPERTY_HINT_RESOURCE_TYPE, ""CurveTexture""), ""set_trail_size_modifier"", ""get_trail_size_modifier""); ADD_PROPERTY(PropertyInfo(Variant::OBJECT, ""trail_color_modifier"", PROPERTY_HINT_RESOURCE_TYPE, ""GradientTexture""), ""set_trail_color_modifier"", ""get_trail_color_modifier""); ADD_GROUP(""Emission Shape"", ""emission_""); ADD_PROPERTY(PropertyInfo(Variant::INT, ""emission_shape"", PROPERTY_HINT_ENUM, ""Point,Sphere,Box,Points,Directed Points""), ""set_emission_shape"", ""get_emission_shape""); ADD_PROPERTY(PropertyInfo(Variant::FLOAT, ""emission_sphere_radius"", PROPERTY_HINT_RANGE, ""0.01,128,0.01,or_greater""), ""set_emission_sphere_radius"", ""get_emission_sphere_radius""); ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, ""emission_box_extents""), ""set_emission_box_extents"", ""get_emission_box_extents""); ADD_PROPERTY(PropertyInfo(Variant::OBJECT, ""emission_point_texture"", PROPERTY_HINT_RESOURCE_TYPE, ""Texture2D""), ""set_emission_point_texture"", ""get_emission_point_texture""); ADD_PROPERTY(PropertyInfo(Variant::OBJECT, ""emission_normal_texture"", PROPERTY_HINT_RESOURCE_TYPE, ""Texture2D""), ""set_emission_normal_texture"", ""get_emission_normal_texture""); ADD_PROPERTY(PropertyInfo(Variant::OBJECT, ""emission_color_texture"", PROPERTY_HINT_RESOURCE_TYPE, ""Texture2D""), ""set_emission_color_texture"", ""get_emission_color_texture""); ADD_PROPERTY(PropertyInfo(Variant::INT, ""emission_point_count"", PROPERTY_HINT_RANGE, ""0,1000000,1""), ""set_emission_point_count"", ""get_emission_point_count""); ADD_GROUP(""Flags"", ""flag_""); ADD_PROPERTYI(PropertyInfo(Variant::BOOL, ""flag_align_y""), ""set_flag"", ""get_flag"", FLAG_ALIGN_Y_TO_VELOCITY); ADD_PROPERTYI(PropertyInfo(Variant::BOOL, ""flag_rotate_y""), ""set_flag"", ""get_flag"", FLAG_ROTATE_Y); ADD_PROPERTYI(PropertyInfo(Variant::BOOL, ""flag_disable_z""), ""set_flag"", ""get_flag"", FLAG_DISABLE_Z); ADD_GROUP(""Direction"", """"); ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, ""direction""), ""set_direction"", ""get_direction""); ADD_PROPERTY(PropertyInfo(Variant::FLOAT, ""spread"", PROPERTY_HINT_RANGE, ""0,180,0.01""), ""set_spread"", ""get_spread""); ADD_PROPERTY(PropertyInfo(Variant::FLOAT, ""flatness"", PROPERTY_HINT_RANGE, ""0,1,0.01""), ""set_flatness"", ""get_flatness""); ADD_GROUP(""Gravity"", """"); ADD_PROPERTY(PropertyInfo(Variant::VECTOR3, ""gravity""), ""set_gravity"", ""get_gravity""); ADD_GROUP(""Initial Velocity"", ""initial_""); ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, ""initial_velocity"", PROPERTY_HINT_RANGE, ""0,1000,0.01,or_lesser,or_greater""), ""set_param"", ""get_param"", PARAM_INITIAL_LINEAR_VELOCITY); ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, ""initial_velocity_random"", PROPERTY_HINT_RANGE, ""0,1,0.01""), ""set_param_randomness"", ""get_param_randomness"", PARAM_INITIAL_LINEAR_VELOCITY); ADD_GROUP(""Angular Velocity"", ""angular_""); ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, ""angular_velocity"", PROPERTY_HINT_RANGE, ""-720,720,0.01,or_lesser,or_greater""), ""set_param"", ""get_param"", PARAM_ANGULAR_VELOCITY); ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, ""angular_velocity_random"", PROPERTY_HINT_RANGE, ""0,1,0.01""), ""set_param_randomness"", ""get_param_randomness"", PARAM_ANGULAR_VELOCITY); ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, ""angular_velocity_curve"", PROPERTY_HINT_RESOURCE_TYPE, ""CurveTexture""), ""set_param_texture"", ""get_param_texture"", PARAM_ANGULAR_VELOCITY); ADD_GROUP(""Orbit Velocity"", ""orbit_""); ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, ""orbit_velocity"", PROPERTY_HINT_RANGE, ""-1000,1000,0.01,or_lesser,or_greater""), ""set_param"", ""get_param"", PARAM_ORBIT_VELOCITY); ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, ""orbit_velocity_random"", PROPERTY_HINT_RANGE, ""0,1,0.01""), ""set_param_randomness"", ""get_param_randomness"", PARAM_ORBIT_VELOCITY); ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, ""orbit_velocity_curve"", PROPERTY_HINT_RESOURCE_TYPE, ""CurveTexture""), ""set_param_texture"", ""get_param_texture"", PARAM_ORBIT_VELOCITY); ADD_GROUP(""Linear Accel"", ""linear_""); ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, ""linear_accel"", PROPERTY_HINT_RANGE, ""-100,100,0.01,or_lesser,or_greater""), ""set_param"", ""get_param"", PARAM_LINEAR_ACCEL); ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, ""linear_accel_random"", PROPERTY_HINT_RANGE, ""0,1,0.01""), ""set_param_randomness"", ""get_param_randomness"", PARAM_LINEAR_ACCEL); ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, ""linear_accel_curve"", PROPERTY_HINT_RESOURCE_TYPE, ""CurveTexture""), ""set_param_texture"", ""get_param_texture"", PARAM_LINEAR_ACCEL); ADD_GROUP(""Radial Accel"", ""radial_""); ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, ""radial_accel"", PROPERTY_HINT_RANGE, ""-100,100,0.01,or_lesser,or_greater""), ""set_param"", ""get_param"", PARAM_RADIAL_ACCEL); ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, ""radial_accel_random"", PROPERTY_HINT_RANGE, ""0,1,0.01""), ""set_param_randomness"", ""get_param_randomness"", PARAM_RADIAL_ACCEL); ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, ""radial_accel_curve"", PROPERTY_HINT_RESOURCE_TYPE, ""CurveTexture""), ""set_param_texture"", ""get_param_texture"", PARAM_RADIAL_ACCEL); ADD_GROUP(""Tangential Accel"", ""tangential_""); ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, ""tangential_accel"", PROPERTY_HINT_RANGE, ""-100,100,0.01,or_lesser,or_greater""), ""set_param"", ""get_param"", PARAM_TANGENTIAL_ACCEL); ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, ""tangential_accel_random"", PROPERTY_HINT_RANGE, ""0,1,0.01""), ""set_param_randomness"", ""get_param_randomness"", PARAM_TANGENTIAL_ACCEL); ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, ""tangential_accel_curve"", PROPERTY_HINT_RESOURCE_TYPE, ""CurveTexture""), ""set_param_texture"", ""get_param_texture"", PARAM_TANGENTIAL_ACCEL); ADD_GROUP(""Damping"", """"); ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, ""damping"", PROPERTY_HINT_RANGE, ""0,100,0.01,or_greater""), ""set_param"", ""get_param"", PARAM_DAMPING); ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, ""damping_random"", PROPERTY_HINT_RANGE, ""0,1,0.01""), ""set_param_randomness"", ""get_param_randomness"", PARAM_DAMPING); ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, ""damping_curve"", PROPERTY_HINT_RESOURCE_TYPE, ""CurveTexture""), ""set_param_texture"", ""get_param_texture"", PARAM_DAMPING); ADD_GROUP(""Angle"", """"); ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, ""angle"", PROPERTY_HINT_RANGE, ""-720,720,0.1,or_lesser,or_greater""), ""set_param"", ""get_param"", PARAM_ANGLE); ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, ""angle_random"", PROPERTY_HINT_RANGE, ""0,1,0.01""), ""set_param_randomness"", ""get_param_randomness"", PARAM_ANGLE); ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, ""angle_curve"", PROPERTY_HINT_RESOURCE_TYPE, ""CurveTexture""), ""set_param_texture"", ""get_param_texture"", PARAM_ANGLE); ADD_GROUP(""Scale"", """"); ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, ""scale"", PROPERTY_HINT_RANGE, ""0,1000,0.01,or_greater""), ""set_param"", ""get_param"", PARAM_SCALE); ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, ""scale_random"", PROPERTY_HINT_RANGE, ""0,1,0.01""), ""set_param_randomness"", ""get_param_randomness"", PARAM_SCALE); ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, ""scale_curve"", PROPERTY_HINT_RESOURCE_TYPE, ""CurveTexture""), ""set_param_texture"", ""get_param_texture"", PARAM_SCALE); ADD_GROUP(""Color"", """"); ADD_PROPERTY(PropertyInfo(Variant::COLOR, ""color""), ""set_color"", ""get_color""); ADD_PROPERTY(PropertyInfo(Variant::OBJECT, ""color_ramp"", PROPERTY_HINT_RESOURCE_TYPE, ""GradientTexture""), ""set_color_ramp"", ""get_color_ramp""); ADD_GROUP(""Hue Variation"", ""hue_""); ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, ""hue_variation"", PROPERTY_HINT_RANGE, ""-1,1,0.01""), ""set_param"", ""get_param"", PARAM_HUE_VARIATION); ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, ""hue_variation_random"", PROPERTY_HINT_RANGE, ""0,1,0.01""), ""set_param_randomness"", ""get_param_randomness"", PARAM_HUE_VARIATION); ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, ""hue_variation_curve"", PROPERTY_HINT_RESOURCE_TYPE, ""CurveTexture""), ""set_param_texture"", ""get_param_texture"", PARAM_HUE_VARIATION); ADD_GROUP(""Animation"", ""anim_""); ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, ""anim_speed"", PROPERTY_HINT_RANGE, ""0,128,0.01,or_greater""), ""set_param"", ""get_param"", PARAM_ANIM_SPEED); ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, ""anim_speed_random"", PROPERTY_HINT_RANGE, ""0,1,0.01""), ""set_param_randomness"", ""get_param_randomness"", PARAM_ANIM_SPEED); ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, ""anim_speed_curve"", PROPERTY_HINT_RESOURCE_TYPE, ""CurveTexture""), ""set_param_texture"", ""get_param_texture"", PARAM_ANIM_SPEED); ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, ""anim_offset"", PROPERTY_HINT_RANGE, ""0,1,0.01""), ""set_param"", ""get_param"", PARAM_ANIM_OFFSET); ADD_PROPERTYI(PropertyInfo(Variant::FLOAT, ""anim_offset_random"", PROPERTY_HINT_RANGE, ""0,1,0.01""), ""set_param_randomness"", ""get_param_randomness"", PARAM_ANIM_OFFSET); ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, ""anim_offset_curve"", PROPERTY_HINT_RESOURCE_TYPE, ""CurveTexture""), ""set_param_texture"", ""get_param_texture"", PARAM_ANIM_OFFSET); BIND_ENUM_CONSTANT(PARAM_INITIAL_LINEAR_VELOCITY); BIND_ENUM_CONSTANT(PARAM_ANGULAR_VELOCITY); BIND_ENUM_CONSTANT(PARAM_ORBIT_VELOCITY); BIND_ENUM_CONSTANT(PARAM_LINEAR_ACCEL); BIND_ENUM_CONSTANT(PARAM_RADIAL_ACCEL); BIND_ENUM_CONSTANT(PARAM_TANGENTIAL_ACCEL); BIND_ENUM_CONSTANT(PARAM_DAMPING); BIND_ENUM_CONSTANT(PARAM_ANGLE); BIND_ENUM_CONSTANT(PARAM_SCALE); BIND_ENUM_CONSTANT(PARAM_HUE_VARIATION); BIND_ENUM_CONSTANT(PARAM_ANIM_SPEED); BIND_ENUM_CONSTANT(PARAM_ANIM_OFFSET); BIND_ENUM_CONSTANT(PARAM_MAX); BIND_ENUM_CONSTANT(FLAG_ALIGN_Y_TO_VELOCITY); BIND_ENUM_CONSTANT(FLAG_ROTATE_Y); BIND_ENUM_CONSTANT(FLAG_DISABLE_Z); BIND_ENUM_CONSTANT(FLAG_MAX); BIND_ENUM_CONSTANT(EMISSION_SHAPE_POINT); BIND_ENUM_CONSTANT(EMISSION_SHAPE_SPHERE); BIND_ENUM_CONSTANT(EMISSION_SHAPE_BOX); BIND_ENUM_CONSTANT(EMISSION_SHAPE_POINTS); BIND_ENUM_CONSTANT(EMISSION_SHAPE_DIRECTED_POINTS); BIND_ENUM_CONSTANT(EMISSION_SHAPE_MAX); } ParticlesMaterial::ParticlesMaterial() : element(this) { set_direction(Vector3(1, 0, 0)); set_spread(45); set_flatness(0); set_param(PARAM_INITIAL_LINEAR_VELOCITY, 0); set_param(PARAM_ANGULAR_VELOCITY, 0); set_param(PARAM_ORBIT_VELOCITY, 0); set_param(PARAM_LINEAR_ACCEL, 0); set_param(PARAM_RADIAL_ACCEL, 0); set_param(PARAM_TANGENTIAL_ACCEL, 0); set_param(PARAM_DAMPING, 0); set_param(PARAM_ANGLE, 0); set_param(PARAM_SCALE, 1); set_param(PARAM_HUE_VARIATION, 0); set_param(PARAM_ANIM_SPEED, 0); set_param(PARAM_ANIM_OFFSET, 0); set_emission_shape(EMISSION_SHAPE_POINT); set_emission_sphere_radius(1); set_emission_box_extents(Vector3(1, 1, 1)); set_trail_divisor(1); set_gravity(Vector3(0, -9.8, 0)); set_lifetime_randomness(0); emission_point_count = 1; for (int i = 0; i < PARAM_MAX; i++) { set_param_randomness(Parameter(i), 0); } for (int i = 0; i < FLAG_MAX; i++) { flags[i] = false; } set_color(Color(1, 1, 1, 1)); current_key.key = 0; current_key.invalid_key = 1; _queue_shader_change(); } ParticlesMaterial::~ParticlesMaterial() { MutexLock lock(material_mutex); if (shader_map.has(current_key)) { shader_map[current_key].users--; if (shader_map[current_key].users == 0) { //deallocate shader, as it's no longer in use RS::get_singleton()->free(shader_map[current_key].shader); shader_map.erase(current_key); } RS::get_singleton()->material_set_shader(_get_material(), RID()); } } ",16132,True,2721.843310573885,median "class ZCL_EXCEL_SHEET_SETUP definition public final create public . public section. *""* public components of class ZCL_EXCEL_SHEET_SETUP *""* do not include other source files here!!! type-pools ABAP . data BLACK_AND_WHITE type FLAG . data CELL_COMMENTS type STRINGVAL . data COPIES type INT2 . constants C_BREAK_COLUMN type ZEXCEL_BREAK value 2. ""#EC NOTEXT constants C_BREAK_NONE type ZEXCEL_BREAK value 0. ""#EC NOTEXT constants C_BREAK_ROW type ZEXCEL_BREAK value 1. ""#EC NOTEXT constants C_CC_AS_DISPLAYED type STRING value 'asDisplayed'. ""#EC NOTEXT constants C_CC_AT_END type STRING value 'atEnd'. ""#EC NOTEXT constants C_CC_NONE type STRING value 'none'. ""#EC NOTEXT constants C_ORD_DOWNTHENOVER type STRING value 'downThenOver'. ""#EC NOTEXT constants C_ORD_OVERTHENDOWN type STRING value 'overThenDown'. ""#EC NOTEXT constants C_ORIENTATION_DEFAULT type ZEXCEL_SHEET_ORIENATATION value 'default'. ""#EC NOTEXT constants C_ORIENTATION_LANDSCAPE type ZEXCEL_SHEET_ORIENATATION value 'landscape'. ""#EC NOTEXT constants C_ORIENTATION_PORTRAIT type ZEXCEL_SHEET_ORIENATATION value 'portrait'. ""#EC NOTEXT constants C_PAPERSIZE_6_3_4_ENVELOPE type ZEXCEL_SHEET_PAPER_SIZE value 38. ""#EC NOTEXT constants C_PAPERSIZE_A2_PAPER type ZEXCEL_SHEET_PAPER_SIZE value 64. ""#EC NOTEXT constants C_PAPERSIZE_A3 type ZEXCEL_SHEET_PAPER_SIZE value 8. ""#EC NOTEXT constants C_PAPERSIZE_A3_EXTRA_PAPER type ZEXCEL_SHEET_PAPER_SIZE value 61. ""#EC NOTEXT constants C_PAPERSIZE_A3_EXTRA_TV_PAPER type ZEXCEL_SHEET_PAPER_SIZE value 66. ""#EC NOTEXT constants C_PAPERSIZE_A3_TV_PAPER type ZEXCEL_SHEET_PAPER_SIZE value 65. ""#EC NOTEXT constants C_PAPERSIZE_A4 type ZEXCEL_SHEET_PAPER_SIZE value 9. ""#EC NOTEXT constants C_PAPERSIZE_A4_EXTRA_PAPER type ZEXCEL_SHEET_PAPER_SIZE value 51. ""#EC NOTEXT constants C_PAPERSIZE_A4_PLUS_PAPER type ZEXCEL_SHEET_PAPER_SIZE value 58. ""#EC NOTEXT constants C_PAPERSIZE_A4_SMALL type ZEXCEL_SHEET_PAPER_SIZE value 10. ""#EC NOTEXT constants C_PAPERSIZE_A4_TV_PAPER type ZEXCEL_SHEET_PAPER_SIZE value 53. ""#EC NOTEXT constants C_PAPERSIZE_A5 type ZEXCEL_SHEET_PAPER_SIZE value 11. ""#EC NOTEXT constants C_PAPERSIZE_A5_EXTRA_PAPER type ZEXCEL_SHEET_PAPER_SIZE value 62. ""#EC NOTEXT constants C_PAPERSIZE_A5_TV_PAPER type ZEXCEL_SHEET_PAPER_SIZE value 59. ""#EC NOTEXT constants C_PAPERSIZE_B4 type ZEXCEL_SHEET_PAPER_SIZE value 12. ""#EC NOTEXT constants C_PAPERSIZE_B4_ENVELOPE type ZEXCEL_SHEET_PAPER_SIZE value 33. ""#EC NOTEXT constants C_PAPERSIZE_B5 type ZEXCEL_SHEET_PAPER_SIZE value 13. ""#EC NOTEXT constants C_PAPERSIZE_B5_ENVELOPE type ZEXCEL_SHEET_PAPER_SIZE value 34. ""#EC NOTEXT constants C_PAPERSIZE_B6_ENVELOPE type ZEXCEL_SHEET_PAPER_SIZE value 35. ""#EC NOTEXT constants C_PAPERSIZE_C type ZEXCEL_SHEET_PAPER_SIZE value 24. ""#EC NOTEXT constants C_PAPERSIZE_C3_ENVELOPE type ZEXCEL_SHEET_PAPER_SIZE value 29. ""#EC NOTEXT constants C_PAPERSIZE_C4_ENVELOPE type ZEXCEL_SHEET_PAPER_SIZE value 30. ""#EC NOTEXT constants C_PAPERSIZE_C5_ENVELOPE type ZEXCEL_SHEET_PAPER_SIZE value 28. ""#EC NOTEXT constants C_PAPERSIZE_C65_ENVELOPE type ZEXCEL_SHEET_PAPER_SIZE value 32. ""#EC NOTEXT constants C_PAPERSIZE_C6_ENVELOPE type ZEXCEL_SHEET_PAPER_SIZE value 31. ""#EC NOTEXT constants C_PAPERSIZE_D type ZEXCEL_SHEET_PAPER_SIZE value 25. ""#EC NOTEXT constants C_PAPERSIZE_DE_LEG_FANFOLD type ZEXCEL_SHEET_PAPER_SIZE value 41. ""#EC NOTEXT constants C_PAPERSIZE_DE_STD_FANFOLD type ZEXCEL_SHEET_PAPER_SIZE value 40. ""#EC NOTEXT constants C_PAPERSIZE_DL_ENVELOPE type ZEXCEL_SHEET_PAPER_SIZE value 27. ""#EC NOTEXT constants C_PAPERSIZE_E type ZEXCEL_SHEET_PAPER_SIZE value 26. ""#EC NOTEXT constants C_PAPERSIZE_EXECUTIVE type ZEXCEL_SHEET_PAPER_SIZE value 7. ""#EC NOTEXT constants C_PAPERSIZE_FOLIO type ZEXCEL_SHEET_PAPER_SIZE value 14. ""#EC NOTEXT constants C_PAPERSIZE_INVITE_ENVELOPE type ZEXCEL_SHEET_PAPER_SIZE value 47. ""#EC NOTEXT constants C_PAPERSIZE_ISO_B4 type ZEXCEL_SHEET_PAPER_SIZE value 42. ""#EC NOTEXT constants C_PAPERSIZE_ISO_B5_EXTRA_PAPER type ZEXCEL_SHEET_PAPER_SIZE value 63. ""#EC NOTEXT constants C_PAPERSIZE_ITALY_ENVELOPE type ZEXCEL_SHEET_PAPER_SIZE value 36. ""#EC NOTEXT constants C_PAPERSIZE_JIS_B5_TV_PAPER type ZEXCEL_SHEET_PAPER_SIZE value 60. ""#EC NOTEXT constants C_PAPERSIZE_JPN_DBL_POSTCARD type ZEXCEL_SHEET_PAPER_SIZE value 43. ""#EC NOTEXT constants C_PAPERSIZE_LEDGER type ZEXCEL_SHEET_PAPER_SIZE value 4. ""#EC NOTEXT constants C_PAPERSIZE_LEGAL type ZEXCEL_SHEET_PAPER_SIZE value 5. ""#EC NOTEXT constants C_PAPERSIZE_LEGAL_EXTRA_PAPER type ZEXCEL_SHEET_PAPER_SIZE value 49. ""#EC NOTEXT constants C_PAPERSIZE_LETTER type ZEXCEL_SHEET_PAPER_SIZE value 1. ""#EC NOTEXT constants C_PAPERSIZE_LETTER_EXTRA_PAPER type ZEXCEL_SHEET_PAPER_SIZE value 48. ""#EC NOTEXT constants C_PAPERSIZE_LETTER_EXTV_PAPER type ZEXCEL_SHEET_PAPER_SIZE value 54. ""#EC NOTEXT constants C_PAPERSIZE_LETTER_PLUS_PAPER type ZEXCEL_SHEET_PAPER_SIZE value 57. ""#EC NOTEXT constants C_PAPERSIZE_LETTER_SMALL type ZEXCEL_SHEET_PAPER_SIZE value 2. ""#EC NOTEXT constants C_PAPERSIZE_LETTER_TV_PAPER type ZEXCEL_SHEET_PAPER_SIZE value 52. ""#EC NOTEXT constants C_PAPERSIZE_MONARCH_ENVELOPE type ZEXCEL_SHEET_PAPER_SIZE value 37. ""#EC NOTEXT constants C_PAPERSIZE_NO10_ENVELOPE type ZEXCEL_SHEET_PAPER_SIZE value 20. ""#EC NOTEXT constants C_PAPERSIZE_NO11_ENVELOPE type ZEXCEL_SHEET_PAPER_SIZE value 21. ""#EC NOTEXT constants C_PAPERSIZE_NO12_ENVELOPE type ZEXCEL_SHEET_PAPER_SIZE value 22. ""#EC NOTEXT constants C_PAPERSIZE_NO14_ENVELOPE type ZEXCEL_SHEET_PAPER_SIZE value 23. ""#EC NOTEXT constants C_PAPERSIZE_NO9_ENVELOPE type ZEXCEL_SHEET_PAPER_SIZE value 19. ""#EC NOTEXT constants C_PAPERSIZE_NOTE type ZEXCEL_SHEET_PAPER_SIZE value 18. ""#EC NOTEXT constants C_PAPERSIZE_QUARTO type ZEXCEL_SHEET_PAPER_SIZE value 15. ""#EC NOTEXT constants C_PAPERSIZE_STANDARD_1 type ZEXCEL_SHEET_PAPER_SIZE value 16. ""#EC NOTEXT constants C_PAPERSIZE_STANDARD_2 type ZEXCEL_SHEET_PAPER_SIZE value 17. ""#EC NOTEXT constants C_PAPERSIZE_STANDARD_PAPER_1 type ZEXCEL_SHEET_PAPER_SIZE value 44. ""#EC NOTEXT constants C_PAPERSIZE_STANDARD_PAPER_2 type ZEXCEL_SHEET_PAPER_SIZE value 45. ""#EC NOTEXT constants C_PAPERSIZE_STANDARD_PAPER_3 type ZEXCEL_SHEET_PAPER_SIZE value 46. ""#EC NOTEXT constants C_PAPERSIZE_STATEMENT type ZEXCEL_SHEET_PAPER_SIZE value 6. ""#EC NOTEXT constants C_PAPERSIZE_SUPERA_A4_PAPER type ZEXCEL_SHEET_PAPER_SIZE value 55. ""#EC NOTEXT constants C_PAPERSIZE_SUPERB_A3_PAPER type ZEXCEL_SHEET_PAPER_SIZE value 56. ""#EC NOTEXT constants C_PAPERSIZE_TABLOID type ZEXCEL_SHEET_PAPER_SIZE value 3. ""#EC NOTEXT constants C_PAPERSIZE_TABL_EXTRA_PAPER type ZEXCEL_SHEET_PAPER_SIZE value 50. ""#EC NOTEXT constants C_PAPERSIZE_US_STD_FANFOLD type ZEXCEL_SHEET_PAPER_SIZE value 39. ""#EC NOTEXT constants C_PE_BLANK type STRING value 'blank'. ""#EC NOTEXT constants C_PE_DASH type STRING value 'dash'. ""#EC NOTEXT constants C_PE_DISPLAYED type STRING value 'displayed'. ""#EC NOTEXT constants C_PE_NA type STRING value 'NA'. ""#EC NOTEXT data DIFF_ODDEVEN_HEADERFOOTER type FLAG . data DRAFT type FLAG . data ERRORS type STRINGVAL . data EVEN_FOOTER type ZEXCEL_S_WORKSHEET_HEAD_FOOT . data EVEN_HEADER type ZEXCEL_S_WORKSHEET_HEAD_FOOT . data FIRST_PAGE_NUMBER type INT2 . data FIT_TO_HEIGHT type INT2 . data FIT_TO_PAGE type FLAG . data FIT_TO_WIDTH type INT2 . data HORIZONTAL_CENTERED type FLAG . data HORIZONTAL_DPI type INT2 . data MARGIN_BOTTOM type ZEXCEL_DEC_8_2 . data MARGIN_FOOTER type ZEXCEL_DEC_8_2 . data MARGIN_HEADER type ZEXCEL_DEC_8_2 . data MARGIN_LEFT type ZEXCEL_DEC_8_2 . data MARGIN_RIGHT type ZEXCEL_DEC_8_2 . data MARGIN_TOP type ZEXCEL_DEC_8_2 . data ODD_FOOTER type ZEXCEL_S_WORKSHEET_HEAD_FOOT . data ODD_HEADER type ZEXCEL_S_WORKSHEET_HEAD_FOOT . data ORIENTATION type ZEXCEL_SHEET_ORIENATATION . data PAGE_ORDER type STRING . data PAPER_HEIGHT type STRING . data PAPER_SIZE type INT2 . data PAPER_WIDTH type STRING . data SCALE type INT2 . data USE_FIRST_PAGE_NUM type FLAG . data USE_PRINTER_DEFAULTS type FLAG . data VERTICAL_CENTERED type FLAG . data VERTICAL_DPI type INT2 . methods CONSTRUCTOR . methods SET_PAGE_MARGINS importing !IP_BOTTOM type FLOAT optional !IP_FOOTER type FLOAT optional !IP_HEADER type FLOAT optional !IP_LEFT type FLOAT optional !IP_RIGHT type FLOAT optional !IP_TOP type FLOAT optional !IP_UNIT type CSEQUENCE default 'in' . methods SET_HEADER_FOOTER importing !IP_ODD_HEADER type ZEXCEL_S_WORKSHEET_HEAD_FOOT optional !IP_ODD_FOOTER type ZEXCEL_S_WORKSHEET_HEAD_FOOT optional !IP_EVEN_HEADER type ZEXCEL_S_WORKSHEET_HEAD_FOOT optional !IP_EVEN_FOOTER type ZEXCEL_S_WORKSHEET_HEAD_FOOT optional . methods GET_HEADER_FOOTER_STRING exporting !EP_ODD_HEADER type STRING !EP_ODD_FOOTER type STRING !EP_EVEN_HEADER type STRING !EP_EVEN_FOOTER type STRING . protected section. *""* protected components of class ZCL_EXCEL_SHEET_SETUP *""* do not include other source files here!!! methods PROCESS_HEADER_FOOTER importing !IP_HEADER type ZEXCEL_S_WORKSHEET_HEAD_FOOT !IP_SIDE type STRING returning value(RV_PROCESSED_STRING) type STRING . private section. *""* private components of class ZCL_EXCEL_SHEET_SETUP *""* do not include other source files here!!! ENDCLASS. CLASS ZCL_EXCEL_SHEET_SETUP IMPLEMENTATION. method CONSTRUCTOR. orientation = me->c_orientation_default. * default margins margin_bottom = '0.75'. margin_footer = '0.3'. margin_header = '0.3'. margin_left = '0.7'. margin_right = '0.7'. margin_top = '0.75'. * clear page settings CLEAR: black_and_white, cell_comments, copies, draft, errors, first_page_number, fit_to_page, fit_to_height, fit_to_width, horizontal_dpi, orientation, page_order, paper_height, paper_size, paper_width, scale, use_first_page_num, use_printer_defaults, vertical_dpi. endmethod. method GET_HEADER_FOOTER_STRING. * ---------------------------------------------------------------------- DATA: lc_marker_left(2) TYPE c VALUE '&L' , lc_marker_right(2) TYPE c VALUE '&R' , lc_marker_center(2) TYPE c VALUE '&C' , lv_value TYPE string . * ---------------------------------------------------------------------- IF ep_odd_header IS SUPPLIED. IF me->odd_header-left_value IS NOT INITIAL. lv_value = me->process_header_footer( ip_header = me->odd_header ip_side = 'LEFT' ). CONCATENATE lc_marker_left lv_value INTO ep_odd_header. ENDIF. IF me->odd_header-center_value IS NOT INITIAL. lv_value = me->process_header_footer( ip_header = me->odd_header ip_side = 'CENTER' ). CONCATENATE ep_odd_header lc_marker_center lv_value INTO ep_odd_header. ENDIF. IF me->odd_header-right_value IS NOT INITIAL. lv_value = me->process_header_footer( ip_header = me->odd_header ip_side = 'RIGHT' ). CONCATENATE ep_odd_header lc_marker_right lv_value INTO ep_odd_header. ENDIF. ENDIF. * ---------------------------------------------------------------------- IF ep_odd_footer IS SUPPLIED. IF me->odd_footer-left_value IS NOT INITIAL. lv_value = me->process_header_footer( ip_header = me->odd_footer ip_side = 'LEFT' ). CONCATENATE lc_marker_left lv_value INTO ep_odd_footer. ENDIF. IF me->odd_footer-center_value IS NOT INITIAL. lv_value = me->process_header_footer( ip_header = me->odd_footer ip_side = 'CENTER' ). CONCATENATE ep_odd_footer lc_marker_center lv_value INTO ep_odd_footer. ENDIF. IF me->odd_footer-right_value IS NOT INITIAL. lv_value = me->process_header_footer( ip_header = me->odd_footer ip_side = 'RIGHT' ). CONCATENATE ep_odd_footer lc_marker_right lv_value INTO ep_odd_footer. ENDIF. ENDIF. * ---------------------------------------------------------------------- IF ep_even_header IS SUPPLIED. IF me->even_header-left_value IS NOT INITIAL. lv_value = me->process_header_footer( ip_header = me->even_header ip_side = 'LEFT' ). CONCATENATE lc_marker_left lv_value INTO ep_even_header. ENDIF. IF me->even_header-center_value IS NOT INITIAL. lv_value = me->process_header_footer( ip_header = me->even_header ip_side = 'CENTER' ). CONCATENATE ep_even_header lc_marker_center lv_value INTO ep_even_header. ENDIF. IF me->even_header-right_value IS NOT INITIAL. lv_value = me->process_header_footer( ip_header = me->even_header ip_side = 'RIGHT' ). CONCATENATE ep_even_header lc_marker_right lv_value INTO ep_even_header. ENDIF. ENDIF. * ---------------------------------------------------------------------- IF ep_even_footer IS SUPPLIED. IF me->even_footer-left_value IS NOT INITIAL. lv_value = me->process_header_footer( ip_header = me->even_footer ip_side = 'LEFT' ). CONCATENATE lc_marker_left lv_value INTO ep_even_footer. ENDIF. IF me->even_footer-center_value IS NOT INITIAL. lv_value = me->process_header_footer( ip_header = me->even_footer ip_side = 'CENTER' ). CONCATENATE ep_even_footer lc_marker_center lv_value INTO ep_even_footer. ENDIF. IF me->even_footer-right_value IS NOT INITIAL. lv_value = me->process_header_footer( ip_header = me->even_footer ip_side = 'RIGHT' ). CONCATENATE ep_even_footer lc_marker_right lv_value INTO ep_even_footer. ENDIF. ENDIF. * ---------------------------------------------------------------------- endmethod. method PROCESS_HEADER_FOOTER. * ---------------------------------------------------------------------- * Only Basic font/text formatting possible: * Bold (yes / no), Font Type, Font Size DATA: lv_fname(12) TYPE c , lv_string TYPE string . FIELD-SYMBOLS: TYPE string , TYPE zexcel_s_style_font . * ---------------------------------------------------------------------- CONCATENATE ip_side '_VALUE' INTO lv_fname. ASSIGN COMPONENT lv_fname OF STRUCTURE ip_header TO . CONCATENATE ip_side '_FONT' INTO lv_fname. ASSIGN COMPONENT lv_fname OF STRUCTURE ip_header TO . IF IS ASSIGNED AND IS ASSIGNED. IF -name IS NOT INITIAL. CONCATENATE '&""' -name ',' INTO rv_processed_string. ELSE. rv_processed_string = '&""-,'. ENDIF. IF -bold = abap_true. CONCATENATE rv_processed_string 'Bold""' INTO rv_processed_string. ELSE. CONCATENATE rv_processed_string 'Standard""' INTO rv_processed_string. ENDIF. IF -size IS NOT INITIAL. lv_string = -size. CONCATENATE rv_processed_string '&' lv_string INTO rv_processed_string. ENDIF. CONCATENATE rv_processed_string INTO rv_processed_string. ENDIF. * ---------------------------------------------------------------------- endmethod. method SET_HEADER_FOOTER. * Only Basic font/text formatting possible: * Bold (yes / no), Font Type, Font Size * * usefull placeholders, which can be used in header/footer value strings * '&P' - page number * '&N' - total number of pages * '&D' - Date * '&T' - Time * '&F' - File Name * '&Z' - Path * '&A' - Sheet name * new line via class constant CL_ABAP_CHAR_UTILITIES=>newline * * Example Value String 'page &P of &N' * * DO NOT USE &L , &C or &R which automatically created as position markers me->odd_header = ip_odd_header. me->odd_footer = ip_odd_footer. me->even_header = ip_even_header. me->even_footer = ip_even_footer. IF me->even_header IS NOT INITIAL OR me->even_footer IS NOT INITIAL. me->diff_oddeven_headerfooter = abap_true. ENDIF. endmethod. method SET_PAGE_MARGINS. DATA: lv_coef TYPE f, lv_unit TYPE string. lv_unit = ip_unit. TRANSLATE lv_unit TO UPPER CASE. CASE lv_unit. WHEN 'IN'. lv_coef = 1. WHEN 'CM'. lv_coef = '0.393700787'. WHEN 'MM'. lv_coef = '0.0393700787'. ENDCASE. IF ip_bottom IS SUPPLIED. margin_bottom = lv_coef * ip_bottom. ENDIF. IF ip_footer IS SUPPLIED. margin_footer = lv_coef * ip_footer. ENDIF. IF ip_header IS SUPPLIED. margin_header = lv_coef * ip_header. ENDIF. IF ip_left IS SUPPLIED. margin_left = lv_coef * ip_left. ENDIF. IF ip_right IS SUPPLIED. margin_right = lv_coef * ip_right. ENDIF. IF ip_top IS SUPPLIED. margin_top = lv_coef * ip_top. ENDIF. endmethod. ENDCLASS. ",4813,False,847.6669590732046,median "/*************************************************************************/ /* tween.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* 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 ""tween.h"" void Tween::_add_pending_command(StringName p_key, const Variant &p_arg1, const Variant &p_arg2, const Variant &p_arg3, const Variant &p_arg4, const Variant &p_arg5, const Variant &p_arg6, const Variant &p_arg7, const Variant &p_arg8, const Variant &p_arg9, const Variant &p_arg10) { // Add a new pending command and reference it pending_commands.push_back(PendingCommand()); PendingCommand &cmd = pending_commands.back()->get(); // Update the command with the target key cmd.key = p_key; // Determine command argument count int &count = cmd.args; if (p_arg10.get_type() != Variant::NIL) { count = 10; } else if (p_arg9.get_type() != Variant::NIL) { count = 9; } else if (p_arg8.get_type() != Variant::NIL) { count = 8; } else if (p_arg7.get_type() != Variant::NIL) { count = 7; } else if (p_arg6.get_type() != Variant::NIL) { count = 6; } else if (p_arg5.get_type() != Variant::NIL) { count = 5; } else if (p_arg4.get_type() != Variant::NIL) { count = 4; } else if (p_arg3.get_type() != Variant::NIL) { count = 3; } else if (p_arg2.get_type() != Variant::NIL) { count = 2; } else if (p_arg1.get_type() != Variant::NIL) { count = 1; } else { count = 0; } // Add the specified arguments to the command if (count > 0) { cmd.arg[0] = p_arg1; } if (count > 1) { cmd.arg[1] = p_arg2; } if (count > 2) { cmd.arg[2] = p_arg3; } if (count > 3) { cmd.arg[3] = p_arg4; } if (count > 4) { cmd.arg[4] = p_arg5; } if (count > 5) { cmd.arg[5] = p_arg6; } if (count > 6) { cmd.arg[6] = p_arg7; } if (count > 7) { cmd.arg[7] = p_arg8; } if (count > 8) { cmd.arg[8] = p_arg9; } if (count > 9) { cmd.arg[9] = p_arg10; } } void Tween::_process_pending_commands() { // For each pending command... for (List::Element *E = pending_commands.front(); E; E = E->next()) { // Get the command PendingCommand &cmd = E->get(); Callable::CallError err; // Grab all of the arguments for the command Variant *arg[10] = { &cmd.arg[0], &cmd.arg[1], &cmd.arg[2], &cmd.arg[3], &cmd.arg[4], &cmd.arg[5], &cmd.arg[6], &cmd.arg[7], &cmd.arg[8], &cmd.arg[9], }; // Execute the command (and retrieve any errors) this->call(cmd.key, (const Variant **)arg, cmd.args, err); } // Clear the pending commands pending_commands.clear(); } bool Tween::_set(const StringName &p_name, const Variant &p_value) { // Set the correct attribute based on the given name String name = p_name; if (name == ""playback/speed"" || name == ""speed"") { // Backwards compatibility set_speed_scale(p_value); return true; } else if (name == ""playback/active"") { set_active(p_value); return true; } else if (name == ""playback/repeat"") { set_repeat(p_value); return true; } return false; } bool Tween::_get(const StringName &p_name, Variant &r_ret) const { // Get the correct attribute based on the given name String name = p_name; if (name == ""playback/speed"") { // Backwards compatibility r_ret = speed_scale; return true; } else if (name == ""playback/active"") { r_ret = is_active(); return true; } else if (name == ""playback/repeat"") { r_ret = is_repeat(); return true; } return false; } void Tween::_get_property_list(List *p_list) const { // Add the property info for the Tween object p_list->push_back(PropertyInfo(Variant::BOOL, ""playback/active"", PROPERTY_HINT_NONE, """")); p_list->push_back(PropertyInfo(Variant::BOOL, ""playback/repeat"", PROPERTY_HINT_NONE, """")); p_list->push_back(PropertyInfo(Variant::FLOAT, ""playback/speed"", PROPERTY_HINT_RANGE, ""-64,64,0.01"")); } void Tween::_notification(int p_what) { // What notification did we receive? switch (p_what) { case NOTIFICATION_ENTER_TREE: { // Are we not already active? if (!is_active()) { // Make sure that a previous process state was not saved // Only process if ""processing"" is set set_physics_process_internal(false); set_process_internal(false); } } break; case NOTIFICATION_READY: { // Do nothing } break; case NOTIFICATION_INTERNAL_PROCESS: { // Are we processing during physics time? if (tween_process_mode == TWEEN_PROCESS_PHYSICS) { // Do nothing since we aren't aligned with physics when we should be break; } // Should we update? if (is_active()) { // Update the tweens _tween_process(get_process_delta_time()); } } break; case NOTIFICATION_INTERNAL_PHYSICS_PROCESS: { // Are we processing during 'regular' time? if (tween_process_mode == TWEEN_PROCESS_IDLE) { // Do nothing since we would only process during idle time break; } // Should we update? if (is_active()) { // Update the tweens _tween_process(get_physics_process_delta_time()); } } break; case NOTIFICATION_EXIT_TREE: { // We've left the tree. Stop all tweens stop_all(); } break; } } void Tween::_bind_methods() { // Bind getters and setters ClassDB::bind_method(D_METHOD(""is_active""), &Tween::is_active); ClassDB::bind_method(D_METHOD(""set_active"", ""active""), &Tween::set_active); ClassDB::bind_method(D_METHOD(""is_repeat""), &Tween::is_repeat); ClassDB::bind_method(D_METHOD(""set_repeat"", ""repeat""), &Tween::set_repeat); ClassDB::bind_method(D_METHOD(""set_speed_scale"", ""speed""), &Tween::set_speed_scale); ClassDB::bind_method(D_METHOD(""get_speed_scale""), &Tween::get_speed_scale); ClassDB::bind_method(D_METHOD(""set_tween_process_mode"", ""mode""), &Tween::set_tween_process_mode); ClassDB::bind_method(D_METHOD(""get_tween_process_mode""), &Tween::get_tween_process_mode); // Bind the various Tween control methods ClassDB::bind_method(D_METHOD(""start""), &Tween::start); ClassDB::bind_method(D_METHOD(""reset"", ""object"", ""key""), &Tween::reset, DEFVAL("""")); ClassDB::bind_method(D_METHOD(""reset_all""), &Tween::reset_all); ClassDB::bind_method(D_METHOD(""stop"", ""object"", ""key""), &Tween::stop, DEFVAL("""")); ClassDB::bind_method(D_METHOD(""stop_all""), &Tween::stop_all); ClassDB::bind_method(D_METHOD(""resume"", ""object"", ""key""), &Tween::resume, DEFVAL("""")); ClassDB::bind_method(D_METHOD(""resume_all""), &Tween::resume_all); ClassDB::bind_method(D_METHOD(""remove"", ""object"", ""key""), &Tween::remove, DEFVAL("""")); ClassDB::bind_method(D_METHOD(""_remove_by_uid"", ""uid""), &Tween::_remove_by_uid); ClassDB::bind_method(D_METHOD(""remove_all""), &Tween::remove_all); ClassDB::bind_method(D_METHOD(""seek"", ""time""), &Tween::seek); ClassDB::bind_method(D_METHOD(""tell""), &Tween::tell); ClassDB::bind_method(D_METHOD(""get_runtime""), &Tween::get_runtime); // Bind interpolation and follow methods ClassDB::bind_method(D_METHOD(""interpolate_property"", ""object"", ""property"", ""initial_val"", ""final_val"", ""duration"", ""trans_type"", ""ease_type"", ""delay""), &Tween::interpolate_property, DEFVAL(TRANS_LINEAR), DEFVAL(EASE_IN_OUT), DEFVAL(0)); ClassDB::bind_method(D_METHOD(""interpolate_method"", ""object"", ""method"", ""initial_val"", ""final_val"", ""duration"", ""trans_type"", ""ease_type"", ""delay""), &Tween::interpolate_method, DEFVAL(TRANS_LINEAR), DEFVAL(EASE_IN_OUT), DEFVAL(0)); ClassDB::bind_method(D_METHOD(""interpolate_callback"", ""object"", ""duration"", ""callback"", ""arg1"", ""arg2"", ""arg3"", ""arg4"", ""arg5""), &Tween::interpolate_callback, DEFVAL(Variant()), DEFVAL(Variant()), DEFVAL(Variant()), DEFVAL(Variant()), DEFVAL(Variant())); ClassDB::bind_method(D_METHOD(""interpolate_deferred_callback"", ""object"", ""duration"", ""callback"", ""arg1"", ""arg2"", ""arg3"", ""arg4"", ""arg5""), &Tween::interpolate_deferred_callback, DEFVAL(Variant()), DEFVAL(Variant()), DEFVAL(Variant()), DEFVAL(Variant()), DEFVAL(Variant())); ClassDB::bind_method(D_METHOD(""follow_property"", ""object"", ""property"", ""initial_val"", ""target"", ""target_property"", ""duration"", ""trans_type"", ""ease_type"", ""delay""), &Tween::follow_property, DEFVAL(TRANS_LINEAR), DEFVAL(EASE_IN_OUT), DEFVAL(0)); ClassDB::bind_method(D_METHOD(""follow_method"", ""object"", ""method"", ""initial_val"", ""target"", ""target_method"", ""duration"", ""trans_type"", ""ease_type"", ""delay""), &Tween::follow_method, DEFVAL(TRANS_LINEAR), DEFVAL(EASE_IN_OUT), DEFVAL(0)); ClassDB::bind_method(D_METHOD(""targeting_property"", ""object"", ""property"", ""initial"", ""initial_val"", ""final_val"", ""duration"", ""trans_type"", ""ease_type"", ""delay""), &Tween::targeting_property, DEFVAL(TRANS_LINEAR), DEFVAL(EASE_IN_OUT), DEFVAL(0)); ClassDB::bind_method(D_METHOD(""targeting_method"", ""object"", ""method"", ""initial"", ""initial_method"", ""final_val"", ""duration"", ""trans_type"", ""ease_type"", ""delay""), &Tween::targeting_method, DEFVAL(TRANS_LINEAR), DEFVAL(EASE_IN_OUT), DEFVAL(0)); // Add the Tween signals ADD_SIGNAL(MethodInfo(""tween_started"", PropertyInfo(Variant::OBJECT, ""object""), PropertyInfo(Variant::NODE_PATH, ""key""))); ADD_SIGNAL(MethodInfo(""tween_step"", PropertyInfo(Variant::OBJECT, ""object""), PropertyInfo(Variant::NODE_PATH, ""key""), PropertyInfo(Variant::FLOAT, ""elapsed""), PropertyInfo(Variant::OBJECT, ""value""))); ADD_SIGNAL(MethodInfo(""tween_completed"", PropertyInfo(Variant::OBJECT, ""object""), PropertyInfo(Variant::NODE_PATH, ""key""))); ADD_SIGNAL(MethodInfo(""tween_all_completed"")); // Add the properties and tie them to the getters and setters ADD_PROPERTY(PropertyInfo(Variant::BOOL, ""repeat""), ""set_repeat"", ""is_repeat""); ADD_PROPERTY(PropertyInfo(Variant::INT, ""playback_process_mode"", PROPERTY_HINT_ENUM, ""Physics,Idle""), ""set_tween_process_mode"", ""get_tween_process_mode""); ADD_PROPERTY(PropertyInfo(Variant::FLOAT, ""playback_speed"", PROPERTY_HINT_RANGE, ""-64,64,0.01""), ""set_speed_scale"", ""get_speed_scale""); // Bind Idle vs Physics process BIND_ENUM_CONSTANT(TWEEN_PROCESS_PHYSICS); BIND_ENUM_CONSTANT(TWEEN_PROCESS_IDLE); // Bind the Transition type constants BIND_ENUM_CONSTANT(TRANS_LINEAR); BIND_ENUM_CONSTANT(TRANS_SINE); BIND_ENUM_CONSTANT(TRANS_QUINT); BIND_ENUM_CONSTANT(TRANS_QUART); BIND_ENUM_CONSTANT(TRANS_QUAD); BIND_ENUM_CONSTANT(TRANS_EXPO); BIND_ENUM_CONSTANT(TRANS_ELASTIC); BIND_ENUM_CONSTANT(TRANS_CUBIC); BIND_ENUM_CONSTANT(TRANS_CIRC); BIND_ENUM_CONSTANT(TRANS_BOUNCE); BIND_ENUM_CONSTANT(TRANS_BACK); // Bind the easing constants BIND_ENUM_CONSTANT(EASE_IN); BIND_ENUM_CONSTANT(EASE_OUT); BIND_ENUM_CONSTANT(EASE_IN_OUT); BIND_ENUM_CONSTANT(EASE_OUT_IN); } Variant Tween::_get_initial_val(const InterpolateData &p_data) const { // What type of data are we interpolating? switch (p_data.type) { case INTER_PROPERTY: case INTER_METHOD: case FOLLOW_PROPERTY: case FOLLOW_METHOD: // Simply use the given initial value return p_data.initial_val; case TARGETING_PROPERTY: case TARGETING_METHOD: { // Get the object that is being targeted Object *object = ObjectDB::get_instance(p_data.target_id); ERR_FAIL_COND_V(object == nullptr, p_data.initial_val); // Are we targeting a property or a method? Variant initial_val; if (p_data.type == TARGETING_PROPERTY) { // Get the property from the target object bool valid = false; initial_val = object->get_indexed(p_data.target_key, &valid); ERR_FAIL_COND_V(!valid, p_data.initial_val); } else { // Call the method and get the initial value from it Callable::CallError error; initial_val = object->call(p_data.target_key[0], nullptr, 0, error); ERR_FAIL_COND_V(error.error != Callable::CallError::CALL_OK, p_data.initial_val); } return initial_val; } case INTER_CALLBACK: // Callback does not have a special initial value break; } // If we've made it here, just return the delta value as the initial value return p_data.delta_val; } Variant Tween::_get_final_val(const InterpolateData &p_data) const { switch (p_data.type) { case FOLLOW_PROPERTY: case FOLLOW_METHOD: { // Get the object that is being followed Object *target = ObjectDB::get_instance(p_data.target_id); ERR_FAIL_COND_V(target == nullptr, p_data.initial_val); // We want to figure out the final value Variant final_val; if (p_data.type == FOLLOW_PROPERTY) { // Read the property as-is bool valid = false; final_val = target->get_indexed(p_data.target_key, &valid); ERR_FAIL_COND_V(!valid, p_data.initial_val); } else { // We're looking at a method. Call the method on the target object Callable::CallError error; final_val = target->call(p_data.target_key[0], nullptr, 0, error); ERR_FAIL_COND_V(error.error != Callable::CallError::CALL_OK, p_data.initial_val); } // If we're looking at an INT value, instead convert it to a FLOAT // This is better for interpolation if (final_val.get_type() == Variant::INT) { final_val = final_val.operator real_t(); } return final_val; } default: { // If we're not following a final value/method, use the final value from the data return p_data.final_val; } } } Variant &Tween::_get_delta_val(InterpolateData &p_data) { // What kind of data are we interpolating? switch (p_data.type) { case INTER_PROPERTY: case INTER_METHOD: // Simply return the given delta value return p_data.delta_val; case FOLLOW_PROPERTY: case FOLLOW_METHOD: { // We're following an object, so grab that instance Object *target = ObjectDB::get_instance(p_data.target_id); ERR_FAIL_COND_V(target == nullptr, p_data.initial_val); // We want to figure out the final value Variant final_val; if (p_data.type == FOLLOW_PROPERTY) { // Read the property as-is bool valid = false; final_val = target->get_indexed(p_data.target_key, &valid); ERR_FAIL_COND_V(!valid, p_data.initial_val); } else { // We're looking at a method. Call the method on the target object Callable::CallError error; final_val = target->call(p_data.target_key[0], nullptr, 0, error); ERR_FAIL_COND_V(error.error != Callable::CallError::CALL_OK, p_data.initial_val); } // If we're looking at an INT value, instead convert it to a FLOAT // This is better for interpolation if (final_val.get_type() == Variant::INT) { final_val = final_val.operator real_t(); } // Calculate the delta based on the initial value and the final value _calc_delta_val(p_data.initial_val, final_val, p_data.delta_val); return p_data.delta_val; } case TARGETING_PROPERTY: case TARGETING_METHOD: { // Grab the initial value from the data to calculate delta Variant initial_val = _get_initial_val(p_data); // If we're looking at an INT value, instead convert it to a FLOAT // This is better for interpolation if (initial_val.get_type() == Variant::INT) { initial_val = initial_val.operator real_t(); } // Calculate the delta based on the initial value and the final value _calc_delta_val(initial_val, p_data.final_val, p_data.delta_val); return p_data.delta_val; } case INTER_CALLBACK: // Callbacks have no special delta break; } // If we've made it here, use the initial value as the delta return p_data.initial_val; } Variant Tween::_run_equation(InterpolateData &p_data) { // Get the initial and delta values from the data Variant initial_val = _get_initial_val(p_data); Variant &delta_val = _get_delta_val(p_data); Variant result; #define APPLY_EQUATION(element) \\ r.element = _run_equation(p_data.trans_type, p_data.ease_type, p_data.elapsed - p_data.delay, i.element, d.element, p_data.duration); // What type of data are we interpolating? switch (initial_val.get_type()) { case Variant::BOOL: // Run the boolean specific equation (checking if it is at least 0.5) result = (_run_equation(p_data.trans_type, p_data.ease_type, p_data.elapsed - p_data.delay, initial_val, delta_val, p_data.duration)) >= 0.5; break; case Variant::INT: // Run the integer specific equation result = (int)_run_equation(p_data.trans_type, p_data.ease_type, p_data.elapsed - p_data.delay, (int)initial_val, (int)delta_val, p_data.duration); break; case Variant::FLOAT: // Run the FLOAT specific equation result = _run_equation(p_data.trans_type, p_data.ease_type, p_data.elapsed - p_data.delay, (real_t)initial_val, (real_t)delta_val, p_data.duration); break; case Variant::VECTOR2: { // Get vectors for initial and delta values Vector2 i = initial_val; Vector2 d = delta_val; Vector2 r; // Execute the equation and mutate the r vector // This uses the custom APPLY_EQUATION macro defined above APPLY_EQUATION(x); APPLY_EQUATION(y); result = r; } break; case Variant::RECT2: { // Get the Rect2 for initial and delta value Rect2 i = initial_val; Rect2 d = delta_val; Rect2 r; // Execute the equation for the position and size of Rect2 APPLY_EQUATION(position.x); APPLY_EQUATION(position.y); APPLY_EQUATION(size.x); APPLY_EQUATION(size.y); result = r; } break; case Variant::VECTOR3: { // Get vectors for initial and delta values Vector3 i = initial_val; Vector3 d = delta_val; Vector3 r; // Execute the equation and mutate the r vector // This uses the custom APPLY_EQUATION macro defined above APPLY_EQUATION(x); APPLY_EQUATION(y); APPLY_EQUATION(z); result = r; } break; case Variant::TRANSFORM2D: { // Get the transforms for initial and delta values Transform2D i = initial_val; Transform2D d = delta_val; Transform2D r; // Execute the equation on the transforms and mutate the r transform // This uses the custom APPLY_EQUATION macro defined above APPLY_EQUATION(elements[0][0]); APPLY_EQUATION(elements[0][1]); APPLY_EQUATION(elements[1][0]); APPLY_EQUATION(elements[1][1]); APPLY_EQUATION(elements[2][0]); APPLY_EQUATION(elements[2][1]); result = r; } break; case Variant::QUAT: { // Get the quaternian for the initial and delta values Quat i = initial_val; Quat d = delta_val; Quat r; // Execute the equation on the quaternian values and mutate the r quaternian // This uses the custom APPLY_EQUATION macro defined above APPLY_EQUATION(x); APPLY_EQUATION(y); APPLY_EQUATION(z); APPLY_EQUATION(w); result = r; } break; case Variant::AABB: { // Get the AABB's for the initial and delta values AABB i = initial_val; AABB d = delta_val; AABB r; // Execute the equation for the position and size of the AABB's and mutate the r AABB // This uses the custom APPLY_EQUATION macro defined above APPLY_EQUATION(position.x); APPLY_EQUATION(position.y); APPLY_EQUATION(position.z); APPLY_EQUATION(size.x); APPLY_EQUATION(size.y); APPLY_EQUATION(size.z); result = r; } break; case Variant::BASIS: { // Get the basis for initial and delta values Basis i = initial_val; Basis d = delta_val; Basis r; // Execute the equation on all the basis and mutate the r basis // This uses the custom APPLY_EQUATION macro defined above APPLY_EQUATION(elements[0][0]); APPLY_EQUATION(elements[0][1]); APPLY_EQUATION(elements[0][2]); APPLY_EQUATION(elements[1][0]); APPLY_EQUATION(elements[1][1]); APPLY_EQUATION(elements[1][2]); APPLY_EQUATION(elements[2][0]); APPLY_EQUATION(elements[2][1]); APPLY_EQUATION(elements[2][2]); result = r; } break; case Variant::TRANSFORM: { // Get the transforms for the initial and delta values Transform i = initial_val; Transform d = delta_val; Transform r; // Execute the equation for each of the transforms and their origin and mutate the r transform // This uses the custom APPLY_EQUATION macro defined above APPLY_EQUATION(basis.elements[0][0]); APPLY_EQUATION(basis.elements[0][1]); APPLY_EQUATION(basis.elements[0][2]); APPLY_EQUATION(basis.elements[1][0]); APPLY_EQUATION(basis.elements[1][1]); APPLY_EQUATION(basis.elements[1][2]); APPLY_EQUATION(basis.elements[2][0]); APPLY_EQUATION(basis.elements[2][1]); APPLY_EQUATION(basis.elements[2][2]); APPLY_EQUATION(origin.x); APPLY_EQUATION(origin.y); APPLY_EQUATION(origin.z); result = r; } break; case Variant::COLOR: { // Get the Color for initial and delta value Color i = initial_val; Color d = delta_val; Color r; // Apply the equation on the Color RGBA, and mutate the r color // This uses the custom APPLY_EQUATION macro defined above APPLY_EQUATION(r); APPLY_EQUATION(g); APPLY_EQUATION(b); APPLY_EQUATION(a); result = r; } break; default: { // If unknown, just return the initial value result = initial_val; } break; }; #undef APPLY_EQUATION // Return the result that was computed return result; } bool Tween::_apply_tween_value(InterpolateData &p_data, Variant &value) { // Get the object we want to apply the new value to Object *object = ObjectDB::get_instance(p_data.id); ERR_FAIL_COND_V(object == nullptr, false); // What kind of data are we mutating? switch (p_data.type) { case INTER_PROPERTY: case FOLLOW_PROPERTY: case TARGETING_PROPERTY: { // Simply set the property on the object bool valid = false; object->set_indexed(p_data.key, value, &valid); return valid; } case INTER_METHOD: case FOLLOW_METHOD: case TARGETING_METHOD: { // We want to call the method on the target object Callable::CallError error; // Do we have a non-nil value passed in? if (value.get_type() != Variant::NIL) { // Pass it as an argument to the function call Variant *arg[1] = { &value }; object->call(p_data.key[0], (const Variant **)arg, 1, error); } else { // Don't pass any argument object->call(p_data.key[0], nullptr, 0, error); } // Did we get an error from the function call? return error.error == Callable::CallError::CALL_OK; } case INTER_CALLBACK: // Nothing to apply for a callback break; }; // No issues found! return true; } void Tween::_tween_process(float p_delta) { // Process all of the pending commands _process_pending_commands(); // If the scale is 0, make no progress on the tweens if (speed_scale == 0) { return; } // Update the delta and whether we are pending an update p_delta *= speed_scale; pending_update++; // Are we repeating the interpolations? if (repeat) { // For each interpolation... bool repeats_finished = true; for (List::Element *E = interpolates.front(); E; E = E->next()) { // Get the data from it InterpolateData &data = E->get(); // Is not finished? if (!data.finish) { // We aren't finished yet, no need to check the rest repeats_finished = false; break; } } // If we are all finished, we can reset all of the tweens if (repeats_finished) { reset_all(); } } // Are all of the tweens complete? int any_unfinished = 0; // For each tween we wish to interpolate... for (List::Element *E = interpolates.front(); E; E = E->next()) { // Get the data from it InterpolateData &data = E->get(); // Is the data not active or already finished? No need to go any further if (!data.active || data.finish) { continue; } // Track if we hit one that isn't finished yet any_unfinished++; // Get the target object for this interpolation Object *object = ObjectDB::get_instance(data.id); if (object == nullptr) { continue; } // Are we still delaying this tween? bool prev_delaying = data.elapsed <= data.delay; data.elapsed += p_delta; if (data.elapsed < data.delay) { continue; } else if (prev_delaying) { // We can apply the tween's value to the data and emit that the tween has started _apply_tween_value(data, data.initial_val); emit_signal(""tween_started"", object, NodePath(Vector(), data.key, false)); } // Are we at the end of the tween? if (data.elapsed > (data.delay + data.duration)) { // Set the elapsed time to the end and mark this one as finished data.elapsed = data.delay + data.duration; data.finish = true; } // Are we interpolating a callback? if (data.type == INTER_CALLBACK) { // Is the tween completed? if (data.finish) { // Are we calling this callback deferred or immediately? if (data.call_deferred) { // Run the deferred function callback, applying the correct number of arguments switch (data.args) { case 0: object->call_deferred(data.key[0]); break; case 1: object->call_deferred(data.key[0], data.arg[0]); break; case 2: object->call_deferred(data.key[0], data.arg[0], data.arg[1]); break; case 3: object->call_deferred(data.key[0], data.arg[0], data.arg[1], data.arg[2]); break; case 4: object->call_deferred(data.key[0], data.arg[0], data.arg[1], data.arg[2], data.arg[3]); break; case 5: object->call_deferred(data.key[0], data.arg[0], data.arg[1], data.arg[2], data.arg[3], data.arg[4]); break; } } else { // Call the function directly with the arguments Callable::CallError error; Variant *arg[5] = { &data.arg[0], &data.arg[1], &data.arg[2], &data.arg[3], &data.arg[4], }; object->call(data.key[0], (const Variant **)arg, data.args, error); } } } else { // We can apply the value directly Variant result = _run_equation(data); _apply_tween_value(data, result); // Emit that the tween has taken a step emit_signal(""tween_step"", object, NodePath(Vector(), data.key, false), data.elapsed, result); } // Is the tween now finished? if (data.finish) { // Set it to the final value directly Variant final_val = _get_final_val(data); _apply_tween_value(data, final_val); // Mark the tween as completed and emit the signal data.elapsed = 0; emit_signal(""tween_completed"", object, NodePath(Vector(), data.key, false)); // If we are not repeating the tween, remove it if (!repeat) { call_deferred(""_remove_by_uid"", data.uid); any_unfinished--; } } } // One less update left to go pending_update--; // If all tweens are completed, we no longer need to be active if (any_unfinished == 0) { set_active(false); emit_signal(""tween_all_completed""); } } void Tween::set_tween_process_mode(TweenProcessMode p_mode) { tween_process_mode = p_mode; } Tween::TweenProcessMode Tween::get_tween_process_mode() const { return tween_process_mode; } bool Tween::is_active() const { return is_processing_internal() || is_physics_processing_internal(); } void Tween::set_active(bool p_active) { // Do nothing if it's the same active mode that we currently are if (is_active() == p_active) { return; } // Depending on physics or idle, set processing switch (tween_process_mode) { case TWEEN_PROCESS_IDLE: set_process_internal(p_active); break; case TWEEN_PROCESS_PHYSICS: set_physics_process_internal(p_active); break; } } bool Tween::is_repeat() const { return repeat; } void Tween::set_repeat(bool p_repeat) { repeat = p_repeat; } void Tween::set_speed_scale(float p_speed) { speed_scale = p_speed; } float Tween::get_speed_scale() const { return speed_scale; } void Tween::start() { ERR_FAIL_COND_MSG(!is_inside_tree(), ""Tween was not added to the SceneTree!""); // Are there any pending updates? if (pending_update != 0) { // Start the tweens after deferring call_deferred(""start""); return; } // We want to be activated set_active(true); } void Tween::reset(Object *p_object, StringName p_key) { // Find all interpolations that use the same object and target string pending_update++; for (List::Element *E = interpolates.front(); E; E = E->next()) { // Get the target object InterpolateData &data = E->get(); Object *object = ObjectDB::get_instance(data.id); if (object == nullptr) { continue; } // Do we have the correct object and key? if (object == p_object && (data.concatenated_key == p_key || p_key == """")) { // Reset the tween to the initial state data.elapsed = 0; data.finish = false; // Also apply the initial state if there isn't a delay if (data.delay == 0) { _apply_tween_value(data, data.initial_val); } } } pending_update--; } void Tween::reset_all() { // Go through all interpolations pending_update++; for (List::Element *E = interpolates.front(); E; E = E->next()) { // Get the target data and set it back to the initial state InterpolateData &data = E->get(); data.elapsed = 0; data.finish = false; // If there isn't a delay, apply the value to the object if (data.delay == 0) { _apply_tween_value(data, data.initial_val); } } pending_update--; } void Tween::stop(Object *p_object, StringName p_key) { // Find the tween that has the given target object and string key pending_update++; for (List::Element *E = interpolates.front(); E; E = E->next()) { // Get the object the tween is targeting InterpolateData &data = E->get(); Object *object = ObjectDB::get_instance(data.id); if (object == nullptr) { continue; } // Is this the correct object and does it have the given key? if (object == p_object && (data.concatenated_key == p_key || p_key == """")) { // Disable the tween data.active = false; } } pending_update--; } void Tween::stop_all() { // We no longer need to be active since all tweens have been stopped set_active(false); // For each interpolation... pending_update++; for (List::Element *E = interpolates.front(); E; E = E->next()) { // Simply set it inactive InterpolateData &data = E->get(); data.active = false; } pending_update--; } void Tween::resume(Object *p_object, StringName p_key) { // We need to be activated // TODO: What if no tween is found?? set_active(true); // Find the tween that uses the given target object and string key pending_update++; for (List::Element *E = interpolates.front(); E; E = E->next()) { // Grab the object InterpolateData &data = E->get(); Object *object = ObjectDB::get_instance(data.id); if (object == nullptr) { continue; } // If the object and string key match, activate it if (object == p_object && (data.concatenated_key == p_key || p_key == """")) { data.active = true; } } pending_update--; } void Tween::resume_all() { // Set ourselves active so we can process tweens // TODO: What if there are no tweens? We get set to active for no reason! set_active(true); // For each interpolation... pending_update++; for (List::Element *E = interpolates.front(); E; E = E->next()) { // Simply grab it and set it to active InterpolateData &data = E->get(); data.active = true; } pending_update--; } void Tween::remove(Object *p_object, StringName p_key) { // If we are still updating, call this function again later if (pending_update != 0) { call_deferred(""remove"", p_object, p_key); return; } // For each interpolation... List::Element *> for_removal; for (List::Element *E = interpolates.front(); E; E = E->next()) { // Get the target object InterpolateData &data = E->get(); Object *object = ObjectDB::get_instance(data.id); if (object == nullptr) { continue; } // If the target object and string key match, queue it for removal if (object == p_object && (data.concatenated_key == p_key || p_key == """")) { for_removal.push_back(E); } } // For each interpolation we wish to remove... for (List::Element *>::Element *E = for_removal.front(); E; E = E->next()) { // Erase it interpolates.erase(E->get()); } } void Tween::_remove_by_uid(int uid) { // If we are still updating, call this function again later if (pending_update != 0) { call_deferred(""_remove_by_uid"", uid); return; } // Find the interpolation that matches the given UID for (List::Element *E = interpolates.front(); E; E = E->next()) { if (uid == E->get().uid) { // It matches, erase it and stop looking E->erase(); break; } } } void Tween::_push_interpolate_data(InterpolateData &p_data) { pending_update++; // Add the new interpolation p_data.uid = ++uid; interpolates.push_back(p_data); pending_update--; } void Tween::remove_all() { // If we are still updating, call this function again later if (pending_update != 0) { call_deferred(""remove_all""); return; } // We no longer need to be active set_active(false); // Clear out all interpolations and reset the uid interpolates.clear(); uid = 0; } void Tween::seek(real_t p_time) { // Go through each interpolation... pending_update++; for (List::Element *E = interpolates.front(); E; E = E->next()) { // Get the target data InterpolateData &data = E->get(); // Update the elapsed data to be set to the target time data.elapsed = p_time; // Are we at the end? if (data.elapsed < data.delay) { // There is still time left to go data.finish = false; continue; } else if (data.elapsed >= (data.delay + data.duration)) { // We are past the end of it, set the elapsed time to the end and mark as finished data.elapsed = (data.delay + data.duration); data.finish = true; } else { // We are not finished with this interpolation yet data.finish = false; } // If we are a callback, do nothing special if (data.type == INTER_CALLBACK) { continue; } // Run the equation on the data and apply the value Variant result = _run_equation(data); _apply_tween_value(data, result); } pending_update--; } real_t Tween::tell() const { // We want to grab the position of the furthest along tween pending_update++; real_t pos = 0; // For each interpolation... for (const List::Element *E = interpolates.front(); E; E = E->next()) { // Get the data and figure out if it's position is further along than the previous ones const InterpolateData &data = E->get(); if (data.elapsed > pos) { // Save it if so pos = data.elapsed; } } pending_update--; return pos; } real_t Tween::get_runtime() const { // If the tween isn't moving, it'll last forever if (speed_scale == 0) { return INFINITY; } pending_update++; // For each interpolation... real_t runtime = 0; for (const List::Element *E = interpolates.front(); E; E = E->next()) { // Get the tween data and see if it's runtime is greater than the previous tweens const InterpolateData &data = E->get(); real_t t = data.delay + data.duration; if (t > runtime) { // This is the longest running tween runtime = t; } } pending_update--; // Adjust the runtime for the current speed scale return runtime / speed_scale; } bool Tween::_calc_delta_val(const Variant &p_initial_val, const Variant &p_final_val, Variant &p_delta_val) { // Get the initial, final, and delta values const Variant &initial_val = p_initial_val; const Variant &final_val = p_final_val; Variant &delta_val = p_delta_val; // What kind of data are we interpolating? switch (initial_val.get_type()) { case Variant::BOOL: // We'll treat booleans just like integers case Variant::INT: // Compute the integer delta delta_val = (int)final_val - (int)initial_val; break; case Variant::FLOAT: // Convert to FLOAT and find the delta delta_val = (real_t)final_val - (real_t)initial_val; break; case Variant::VECTOR2: // Convert to Vectors and find the delta delta_val = final_val.operator Vector2() - initial_val.operator Vector2(); break; case Variant::RECT2: { // Build a new Rect2 and use the new position and sizes to make a delta Rect2 i = initial_val; Rect2 f = final_val; delta_val = Rect2(f.position - i.position, f.size - i.size); } break; case Variant::VECTOR3: // Convert to Vectors and find the delta delta_val = final_val.operator Vector3() - initial_val.operator Vector3(); break; case Variant::TRANSFORM2D: { // Build a new transform which is the difference between the initial and final values Transform2D i = initial_val; Transform2D f = final_val; Transform2D d = Transform2D(); d[0][0] = f.elements[0][0] - i.elements[0][0]; d[0][1] = f.elements[0][1] - i.elements[0][1]; d[1][0] = f.elements[1][0] - i.elements[1][0]; d[1][1] = f.elements[1][1] - i.elements[1][1]; d[2][0] = f.elements[2][0] - i.elements[2][0]; d[2][1] = f.elements[2][1] - i.elements[2][1]; delta_val = d; } break; case Variant::QUAT: // Convert to quaternianls and find the delta delta_val = final_val.operator Quat() - initial_val.operator Quat(); break; case Variant::AABB: { // Build a new AABB and use the new position and sizes to make a delta AABB i = initial_val; AABB f = final_val; delta_val = AABB(f.position - i.position, f.size - i.size); } break; case Variant::BASIS: { // Build a new basis which is the delta between the initial and final values Basis i = initial_val; Basis f = final_val; delta_val = Basis(f.elements[0][0] - i.elements[0][0], f.elements[0][1] - i.elements[0][1], f.elements[0][2] - i.elements[0][2], f.elements[1][0] - i.elements[1][0], f.elements[1][1] - i.elements[1][1], f.elements[1][2] - i.elements[1][2], f.elements[2][0] - i.elements[2][0], f.elements[2][1] - i.elements[2][1], f.elements[2][2] - i.elements[2][2]); } break; case Variant::TRANSFORM: { // Build a new transform which is the difference between the initial and final values Transform i = initial_val; Transform f = final_val; Transform d; d.set(f.basis.elements[0][0] - i.basis.elements[0][0], f.basis.elements[0][1] - i.basis.elements[0][1], f.basis.elements[0][2] - i.basis.elements[0][2], f.basis.elements[1][0] - i.basis.elements[1][0], f.basis.elements[1][1] - i.basis.elements[1][1], f.basis.elements[1][2] - i.basis.elements[1][2], f.basis.elements[2][0] - i.basis.elements[2][0], f.basis.elements[2][1] - i.basis.elements[2][1], f.basis.elements[2][2] - i.basis.elements[2][2], f.origin.x - i.origin.x, f.origin.y - i.origin.y, f.origin.z - i.origin.z); delta_val = d; } break; case Variant::COLOR: { // Make a new color which is the difference between each the color's RGBA attributes Color i = initial_val; Color f = final_val; delta_val = Color(f.r - i.r, f.g - i.g, f.b - i.b, f.a - i.a); } break; default: { static Variant::Type supported_types[] = { Variant::BOOL, Variant::INT, Variant::FLOAT, Variant::VECTOR2, Variant::RECT2, Variant::VECTOR3, Variant::TRANSFORM2D, Variant::QUAT, Variant::AABB, Variant::BASIS, Variant::TRANSFORM, Variant::COLOR, }; int length = *(&supported_types + 1) - supported_types; String error_msg = ""Invalid parameter type. Supported types are: ""; for (int i = 0; i < length; i++) { if (i != 0) { error_msg += "", ""; } error_msg += Variant::get_type_name(supported_types[i]); } error_msg += "".""; ERR_PRINT(error_msg); return false; } }; return true; } void Tween::_build_interpolation(InterpolateType p_interpolation_type, Object *p_object, NodePath *p_property, StringName *p_method, Variant p_initial_val, Variant p_final_val, real_t p_duration, TransitionType p_trans_type, EaseType p_ease_type, real_t p_delay) { // TODO: Add initialization+implementation for remaining interpolation types // TODO: Fix this method's organization to take advantage of the type // Make a new interpolation data InterpolateData data; data.active = true; data.type = p_interpolation_type; data.finish = false; data.elapsed = 0; // Validate and apply interpolation data // Give it the object ERR_FAIL_COND_MSG(p_object == nullptr, ""Invalid object provided to Tween.""); data.id = p_object->get_instance_id(); // Validate the initial and final values ERR_FAIL_COND_MSG(p_initial_val.get_type() != p_final_val.get_type(), ""Initial value type '"" + Variant::get_type_name(p_initial_val.get_type()) + ""' does not match final value type '"" + Variant::get_type_name(p_final_val.get_type()) + ""'.""); data.initial_val = p_initial_val; data.final_val = p_final_val; // Check the Duration ERR_FAIL_COND_MSG(p_duration < 0, ""Only non-negative duration values allowed in Tweens.""); data.duration = p_duration; // Tween Delay ERR_FAIL_COND_MSG(p_delay < 0, ""Only non-negative delay values allowed in Tweens.""); data.delay = p_delay; // Transition type ERR_FAIL_COND_MSG(p_trans_type < 0 || p_trans_type >= TRANS_COUNT, ""Invalid transition type provided to Tween.""); data.trans_type = p_trans_type; // Easing type ERR_FAIL_COND_MSG(p_ease_type < 0 || p_ease_type >= EASE_COUNT, ""Invalid easing type provided to Tween.""); data.ease_type = p_ease_type; // Is the property defined? if (p_property) { // Check that the object actually contains the given property bool prop_valid = false; p_object->get_indexed(p_property->get_subnames(), &prop_valid); ERR_FAIL_COND_MSG(!prop_valid, ""Tween target object has no property named: "" + p_property->get_concatenated_subnames() + "".""); data.key = p_property->get_subnames(); data.concatenated_key = p_property->get_concatenated_subnames(); } // Is the method defined? if (p_method) { // Does the object even have the requested method? ERR_FAIL_COND_MSG(!p_object->has_method(*p_method), ""Tween target object has no method named: "" + *p_method + "".""); data.key.push_back(*p_method); data.concatenated_key = *p_method; } // Is there not a valid delta? if (!_calc_delta_val(data.initial_val, data.final_val, data.delta_val)) { return; } // Add this interpolation to the total _push_interpolate_data(data); } void Tween::interpolate_property(Object *p_object, NodePath p_property, Variant p_initial_val, Variant p_final_val, real_t p_duration, TransitionType p_trans_type, EaseType p_ease_type, real_t p_delay) { // If we are busy updating, call this function again later if (pending_update != 0) { _add_pending_command(""interpolate_property"", p_object, p_property, p_initial_val, p_final_val, p_duration, p_trans_type, p_ease_type, p_delay); return; } // Get the property from the node path p_property = p_property.get_as_property_path(); // If no initial value given, grab the initial value from the object // TODO: Is this documented? This is very useful and removes a lot of clutter from tweens! if (p_initial_val.get_type() == Variant::NIL) { p_initial_val = p_object->get_indexed(p_property.get_subnames()); } // Convert any integers into REALs as they are better for interpolation if (p_initial_val.get_type() == Variant::INT) { p_initial_val = p_initial_val.operator real_t(); } if (p_final_val.get_type() == Variant::INT) { p_final_val = p_final_val.operator real_t(); } // Build the interpolation data _build_interpolation(INTER_PROPERTY, p_object, &p_property, nullptr, p_initial_val, p_final_val, p_duration, p_trans_type, p_ease_type, p_delay); } void Tween::interpolate_method(Object *p_object, StringName p_method, Variant p_initial_val, Variant p_final_val, real_t p_duration, TransitionType p_trans_type, EaseType p_ease_type, real_t p_delay) { // If we are busy updating, call this function again later if (pending_update != 0) { _add_pending_command(""interpolate_method"", p_object, p_method, p_initial_val, p_final_val, p_duration, p_trans_type, p_ease_type, p_delay); return; } // Convert any integers into REALs as they are better for interpolation if (p_initial_val.get_type() == Variant::INT) { p_initial_val = p_initial_val.operator real_t(); } if (p_final_val.get_type() == Variant::INT) { p_final_val = p_final_val.operator real_t(); } // Build the interpolation data _build_interpolation(INTER_METHOD, p_object, nullptr, &p_method, p_initial_val, p_final_val, p_duration, p_trans_type, p_ease_type, p_delay); } void Tween::interpolate_callback(Object *p_object, real_t p_duration, String p_callback, VARIANT_ARG_DECLARE) { // If we are already updating, call this function again later if (pending_update != 0) { _add_pending_command(""interpolate_callback"", p_object, p_duration, p_callback, p_arg1, p_arg2, p_arg3, p_arg4, p_arg5); return; } // Check that the target object is valid ERR_FAIL_COND(p_object == nullptr); // Duration cannot be negative ERR_FAIL_COND(p_duration < 0); // Check whether the object even has the callback ERR_FAIL_COND_MSG(!p_object->has_method(p_callback), ""Object has no callback named: "" + p_callback + "".""); // Build a new InterpolationData InterpolateData data; data.active = true; data.type = INTER_CALLBACK; data.finish = false; data.call_deferred = false; data.elapsed = 0; // Give the data it's configuration data.id = p_object->get_instance_id(); data.key.push_back(p_callback); data.concatenated_key = p_callback; data.duration = p_duration; data.delay = 0; // Add arguments to the interpolation int args = 0; if (p_arg5.get_type() != Variant::NIL) { args = 5; } else if (p_arg4.get_type() != Variant::NIL) { args = 4; } else if (p_arg3.get_type() != Variant::NIL) { args = 3; } else if (p_arg2.get_type() != Variant::NIL) { args = 2; } else if (p_arg1.get_type() != Variant::NIL) { args = 1; } else { args = 0; } data.args = args; data.arg[0] = p_arg1; data.arg[1] = p_arg2; data.arg[2] = p_arg3; data.arg[3] = p_arg4; data.arg[4] = p_arg5; // Add the new interpolation _push_interpolate_data(data); } void Tween::interpolate_deferred_callback(Object *p_object, real_t p_duration, String p_callback, VARIANT_ARG_DECLARE) { // If we are already updating, call this function again later if (pending_update != 0) { _add_pending_command(""interpolate_deferred_callback"", p_object, p_duration, p_callback, p_arg1, p_arg2, p_arg3, p_arg4, p_arg5); return; } // Check that the target object is valid ERR_FAIL_COND(p_object == nullptr); // No negative durations allowed ERR_FAIL_COND(p_duration < 0); // Confirm the callback exists on the object ERR_FAIL_COND_MSG(!p_object->has_method(p_callback), ""Object has no callback named: "" + p_callback + "".""); // Create a new InterpolateData for the callback InterpolateData data; data.active = true; data.type = INTER_CALLBACK; data.finish = false; data.call_deferred = true; data.elapsed = 0; // Give the data it's configuration data.id = p_object->get_instance_id(); data.key.push_back(p_callback); data.concatenated_key = p_callback; data.duration = p_duration; data.delay = 0; // Collect arguments for the callback int args = 0; if (p_arg5.get_type() != Variant::NIL) { args = 5; } else if (p_arg4.get_type() != Variant::NIL) { args = 4; } else if (p_arg3.get_type() != Variant::NIL) { args = 3; } else if (p_arg2.get_type() != Variant::NIL) { args = 2; } else if (p_arg1.get_type() != Variant::NIL) { args = 1; } else { args = 0; } data.args = args; data.arg[0] = p_arg1; data.arg[1] = p_arg2; data.arg[2] = p_arg3; data.arg[3] = p_arg4; data.arg[4] = p_arg5; // Add the new interpolation _push_interpolate_data(data); } void Tween::follow_property(Object *p_object, NodePath p_property, Variant p_initial_val, Object *p_target, NodePath p_target_property, real_t p_duration, TransitionType p_trans_type, EaseType p_ease_type, real_t p_delay) { // If we are already updating, call this function again later if (pending_update != 0) { _add_pending_command(""follow_property"", p_object, p_property, p_initial_val, p_target, p_target_property, p_duration, p_trans_type, p_ease_type, p_delay); return; } // Get the two properties from their paths p_property = p_property.get_as_property_path(); p_target_property = p_target_property.get_as_property_path(); // If no initial value is given, grab it from the source object // TODO: Is this documented? It's really helpful for decluttering tweens if (p_initial_val.get_type() == Variant::NIL) { p_initial_val = p_object->get_indexed(p_property.get_subnames()); } // Convert initial INT values to FLOAT as they are better for interpolation if (p_initial_val.get_type() == Variant::INT) { p_initial_val = p_initial_val.operator real_t(); } // Confirm the source and target objects are valid ERR_FAIL_COND(p_object == nullptr); ERR_FAIL_COND(p_target == nullptr); // No negative durations ERR_FAIL_COND(p_duration < 0); // Ensure transition and easing types are valid ERR_FAIL_COND(p_trans_type < 0 || p_trans_type >= TRANS_COUNT); ERR_FAIL_COND(p_ease_type < 0 || p_ease_type >= EASE_COUNT); // No negative delays ERR_FAIL_COND(p_delay < 0); // Confirm the source and target objects have the desired properties bool prop_valid = false; p_object->get_indexed(p_property.get_subnames(), &prop_valid); ERR_FAIL_COND(!prop_valid); bool target_prop_valid = false; Variant target_val = p_target->get_indexed(p_target_property.get_subnames(), &target_prop_valid); ERR_FAIL_COND(!target_prop_valid); // Convert target INT to FLOAT since it is better for interpolation if (target_val.get_type() == Variant::INT) { target_val = target_val.operator real_t(); } // Verify that the target value and initial value are the same type ERR_FAIL_COND(target_val.get_type() != p_initial_val.get_type()); // Create a new InterpolateData InterpolateData data; data.active = true; data.type = FOLLOW_PROPERTY; data.finish = false; data.elapsed = 0; // Give the InterpolateData it's configuration data.id = p_object->get_instance_id(); data.key = p_property.get_subnames(); data.concatenated_key = p_property.get_concatenated_subnames(); data.initial_val = p_initial_val; data.target_id = p_target->get_instance_id(); data.target_key = p_target_property.get_subnames(); data.duration = p_duration; data.trans_type = p_trans_type; data.ease_type = p_ease_type; data.delay = p_delay; // Add the interpolation _push_interpolate_data(data); } void Tween::follow_method(Object *p_object, StringName p_method, Variant p_initial_val, Object *p_target, StringName p_target_method, real_t p_duration, TransitionType p_trans_type, EaseType p_ease_type, real_t p_delay) { // If we are currently updating, call this function again later if (pending_update != 0) { _add_pending_command(""follow_method"", p_object, p_method, p_initial_val, p_target, p_target_method, p_duration, p_trans_type, p_ease_type, p_delay); return; } // Convert initial INT values to FLOAT as they are better for interpolation if (p_initial_val.get_type() == Variant::INT) { p_initial_val = p_initial_val.operator real_t(); } // Verify the source and target objects are valid ERR_FAIL_COND(p_object == nullptr); ERR_FAIL_COND(p_target == nullptr); // No negative durations ERR_FAIL_COND(p_duration < 0); // Ensure that the transition and ease types are valid ERR_FAIL_COND(p_trans_type < 0 || p_trans_type >= TRANS_COUNT); ERR_FAIL_COND(p_ease_type < 0 || p_ease_type >= EASE_COUNT); // No negative delays ERR_FAIL_COND(p_delay < 0); // Confirm both objects have the target methods ERR_FAIL_COND_MSG(!p_object->has_method(p_method), ""Object has no method named: "" + p_method + "".""); ERR_FAIL_COND_MSG(!p_target->has_method(p_target_method), ""Target has no method named: "" + p_target_method + "".""); // Call the method to get the target value Callable::CallError error; Variant target_val = p_target->call(p_target_method, nullptr, 0, error); ERR_FAIL_COND(error.error != Callable::CallError::CALL_OK); // Convert target INT values to FLOAT as they are better for interpolation if (target_val.get_type() == Variant::INT) { target_val = target_val.operator real_t(); } ERR_FAIL_COND(target_val.get_type() != p_initial_val.get_type()); // Make the new InterpolateData for the method follow InterpolateData data; data.active = true; data.type = FOLLOW_METHOD; data.finish = false; data.elapsed = 0; // Give the data it's configuration data.id = p_object->get_instance_id(); data.key.push_back(p_method); data.concatenated_key = p_method; data.initial_val = p_initial_val; data.target_id = p_target->get_instance_id(); data.target_key.push_back(p_target_method); data.duration = p_duration; data.trans_type = p_trans_type; data.ease_type = p_ease_type; data.delay = p_delay; // Add the new interpolation _push_interpolate_data(data); } void Tween::targeting_property(Object *p_object, NodePath p_property, Object *p_initial, NodePath p_initial_property, Variant p_final_val, real_t p_duration, TransitionType p_trans_type, EaseType p_ease_type, real_t p_delay) { // If we are currently updating, call this function again later if (pending_update != 0) { _add_pending_command(""targeting_property"", p_object, p_property, p_initial, p_initial_property, p_final_val, p_duration, p_trans_type, p_ease_type, p_delay); return; } // Grab the target property and the target property p_property = p_property.get_as_property_path(); p_initial_property = p_initial_property.get_as_property_path(); // Convert the initial INT values to FLOAT as they are better for Interpolation if (p_final_val.get_type() == Variant::INT) { p_final_val = p_final_val.operator real_t(); } // Verify both objects are valid ERR_FAIL_COND(p_object == nullptr); ERR_FAIL_COND(p_initial == nullptr); // No negative durations ERR_FAIL_COND(p_duration < 0); // Ensure transition and easing types are valid ERR_FAIL_COND(p_trans_type < 0 || p_trans_type >= TRANS_COUNT); ERR_FAIL_COND(p_ease_type < 0 || p_ease_type >= EASE_COUNT); // No negative delays ERR_FAIL_COND(p_delay < 0); // Ensure the initial and target properties exist on their objects bool prop_valid = false; p_object->get_indexed(p_property.get_subnames(), &prop_valid); ERR_FAIL_COND(!prop_valid); bool initial_prop_valid = false; Variant initial_val = p_initial->get_indexed(p_initial_property.get_subnames(), &initial_prop_valid); ERR_FAIL_COND(!initial_prop_valid); // Convert the initial INT value to FLOAT as it is better for interpolation if (initial_val.get_type() == Variant::INT) { initial_val = initial_val.operator real_t(); } ERR_FAIL_COND(initial_val.get_type() != p_final_val.get_type()); // Build the InterpolateData object InterpolateData data; data.active = true; data.type = TARGETING_PROPERTY; data.finish = false; data.elapsed = 0; // Give the data it's configuration data.id = p_object->get_instance_id(); data.key = p_property.get_subnames(); data.concatenated_key = p_property.get_concatenated_subnames(); data.target_id = p_initial->get_instance_id(); data.target_key = p_initial_property.get_subnames(); data.initial_val = initial_val; data.final_val = p_final_val; data.duration = p_duration; data.trans_type = p_trans_type; data.ease_type = p_ease_type; data.delay = p_delay; // Ensure there is a valid delta if (!_calc_delta_val(data.initial_val, data.final_val, data.delta_val)) { return; } // Add the interpolation _push_interpolate_data(data); } void Tween::targeting_method(Object *p_object, StringName p_method, Object *p_initial, StringName p_initial_method, Variant p_final_val, real_t p_duration, TransitionType p_trans_type, EaseType p_ease_type, real_t p_delay) { // If we are currently updating, call this function again later if (pending_update != 0) { _add_pending_command(""targeting_method"", p_object, p_method, p_initial, p_initial_method, p_final_val, p_duration, p_trans_type, p_ease_type, p_delay); return; } // Convert final INT values to FLOAT as they are better for interpolation if (p_final_val.get_type() == Variant::INT) { p_final_val = p_final_val.operator real_t(); } // Make sure the given objects are valid ERR_FAIL_COND(p_object == nullptr); ERR_FAIL_COND(p_initial == nullptr); // No negative durations ERR_FAIL_COND(p_duration < 0); // Ensure transition and easing types are valid ERR_FAIL_COND(p_trans_type < 0 || p_trans_type >= TRANS_COUNT); ERR_FAIL_COND(p_ease_type < 0 || p_ease_type >= EASE_COUNT); // No negative delays ERR_FAIL_COND(p_delay < 0); // Make sure both objects have the given method ERR_FAIL_COND_MSG(!p_object->has_method(p_method), ""Object has no method named: "" + p_method + "".""); ERR_FAIL_COND_MSG(!p_initial->has_method(p_initial_method), ""Initial Object has no method named: "" + p_initial_method + "".""); // Call the method to get the initial value Callable::CallError error; Variant initial_val = p_initial->call(p_initial_method, nullptr, 0, error); ERR_FAIL_COND(error.error != Callable::CallError::CALL_OK); // Convert initial INT values to FLOAT as they aer better for interpolation if (initial_val.get_type() == Variant::INT) { initial_val = initial_val.operator real_t(); } ERR_FAIL_COND(initial_val.get_type() != p_final_val.get_type()); // Build the new InterpolateData object InterpolateData data; data.active = true; data.type = TARGETING_METHOD; data.finish = false; data.elapsed = 0; // Configure the data data.id = p_object->get_instance_id(); data.key.push_back(p_method); data.concatenated_key = p_method; data.target_id = p_initial->get_instance_id(); data.target_key.push_back(p_initial_method); data.initial_val = initial_val; data.final_val = p_final_val; data.duration = p_duration; data.trans_type = p_trans_type; data.ease_type = p_ease_type; data.delay = p_delay; // Ensure there is a valid delta if (!_calc_delta_val(data.initial_val, data.final_val, data.delta_val)) { return; } // Add the interpolation _push_interpolate_data(data); } Tween::Tween() { // Initialize tween attributes tween_process_mode = TWEEN_PROCESS_IDLE; repeat = false; speed_scale = 1; pending_update = 0; uid = 0; } Tween::~Tween() { } ",16142,True,2819.1693446187105,median "[[salesforce-component]] = Salesforce Component :page-source: components/camel-salesforce/camel-salesforce-component/src/main/docs/salesforce-component.adoc *Available as of Camel version 2.12* This component supports producer and consumer endpoints to communicate with Salesforce using Java DTOs. + There is a companion maven plugin Camel Salesforce Plugin that generates these DTOs (see further below). Maven users will need to add the following dependency to their `pom.xml` for this component: [source,xml] ---- org.apache.camel camel-salesforce x.x.x ---- NOTE: Developers wishing to contribute to the component are instructed to look at the https://github.com/apache/camel/tree/master/components/camel-salesforce/camel-salesforce-component/README.md[README.md] file on instructions on how to get started and setup your environment for running integration tests. == Authenticating to Salesforce The component supports three OAuth authentication flows: * https://help.salesforce.com/articleView?id=remoteaccess_oauth_username_password_flow.htm[OAuth 2.0 Username-Password Flow] * https://help.salesforce.com/articleView?id=remoteaccess_oauth_refresh_token_flow.htm[OAuth 2.0 Refresh Token Flow] * https://help.salesforce.com/articleView?id=remoteaccess_oauth_jwt_flow.htm[OAuth 2.0 JWT Bearer Token Flow] For each of the flow different set of properties needs to be set: .Properties to set for each authentication flow |=== | Property | Where to find it on Salesforce | Flow | clientId | Connected App, Consumer Key | All flows | clientSecret | Connected App, Consumer Secret | Username-Password, Refresh Token | userName | Salesforce user username | Username-Password, JWT Bearer Token | password | Salesforce user password | Username-Password | refreshToken | From OAuth flow callback | Refresh Token | keystore | Connected App, Digital Certificate | JWT Bearer Token |=== The component auto determines what flow you're trying to configure, to be remove ambiguity set the `authenticationType` property. NOTE: Using Username-Password Flow in production is not encouraged. NOTE: The certificate used in JWT Bearer Token Flow can be a selfsigned certificate. The KeyStore holding the certificate and the private key must contain only single certificate-private key entry. == URI format When used as a consumer, receiving streaming events, the URI scheme is: [source,java] ---- salesforce:topic?options ---- When used as a producer, invoking the Salesforce REST APIs, the URI scheme is: [source,java] ---- salesforce:operationName?options ---- You can append query options to the URI in the following format, `?option=value&option=value&...` == Passing in Salesforce headers and fetching Salesforce response headers There is support to pass https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/headers.htm[Salesforce headers] via inbound message headers, header names that start with `Sforce` or `x-sfdc` on the Camel message will be passed on in the request, and response headers that start with `Sforce` will be present in the outbound message headers. For example to fetch API limits you can specify: [source,java] ---- // in your Camel route set the header before Salesforce endpoint //... .setHeader(""Sforce-Limit-Info"", constant(""api-usage"")) .to(""salesforce:getGlobalObjects"") .to(myProcessor); // myProcessor will receive `Sforce-Limit-Info` header on the outbound // message class MyProcessor implements Processor { public void process(Exchange exchange) throws Exception { Message in = exchange.getIn(); String apiLimits = in.getHeader(""Sforce-Limit-Info"", String.class); } } ---- == Supported Salesforce APIs The component supports the following Salesforce APIs Producer endpoints can use the following APIs. Most of the APIs process one record at a time, the Query API can retrieve multiple Records. === Rest API You can use the following for `operationName`: * getVersions - Gets supported Salesforce REST API versions * getResources - Gets available Salesforce REST Resource endpoints * getGlobalObjects - Gets metadata for all available SObject types * getBasicInfo - Gets basic metadata for a specific SObject type * getDescription - Gets comprehensive metadata for a specific SObject type * getSObject - Gets an SObject using its Salesforce Id * createSObject - Creates an SObject * updateSObject - Updates an SObject using Id * deleteSObject - Deletes an SObject using Id * getSObjectWithId - Gets an SObject using an external (user defined) id field * upsertSObject - Updates or inserts an SObject using an external id * deleteSObjectWithId - Deletes an SObject using an external id * query - Runs a Salesforce SOQL query * queryMore - Retrieves more results (in case of large number of results) using result link returned from the 'query' API * search - Runs a Salesforce SOSL query * limits - fetching organization API usage limits * recent - fetching recent items * approval - submit a record or records (batch) for approval process * approvals - fetch a list of all approval processes * composite - submit up to 25 possibly related REST requests and receive individual responses * composite-tree - create up to 200 records with parent-child relationships (up to 5 levels) in one go * composite-batch - submit a composition of requests in batch * queryAll - Runs a SOQL query. It returns the results that are deleted because of a merge or delete. Also returns the information about archived Task and Event records. * getBlobField - Retrieves the specified blob field from an individual record. * apexCall - Executes a user defined APEX REST API call. For example, the following producer endpoint uses the upsertSObject API, with the sObjectIdName parameter specifying 'Name' as the external id field. The request message body should be an SObject DTO generated using the maven plugin. The response message will either be `null` if an existing record was updated, or `CreateSObjectResult` with an id of the new record, or a list of errors while creating the new object. [source,java] ---- ...to(""salesforce:upsertSObject?sObjectIdName=Name"")... ---- === Rest Bulk API Producer endpoints can use the following APIs. All Job data formats, i.e. xml, csv, zip/xml, and zip/csv are supported. + The request and response have to be marshalled/unmarshalled by the route. Usually the request will be some stream source like a CSV file, + and the response may also be saved to a file to be correlated with the request. You can use the following for `operationName`: * createJob - Creates a Salesforce Bulk Job * getJob - Gets a Job using its Salesforce Id * closeJob - Closes a Job * abortJob - Aborts a Job * createBatch - Submits a Batch within a Bulk Job * getBatch - Gets a Batch using Id * getAllBatches - Gets all Batches for a Bulk Job Id * getRequest - Gets Request data (XML/CSV) for a Batch * getResults - Gets the results of the Batch when its complete * createBatchQuery - Creates a Batch from an SOQL query * getQueryResultIds - Gets a list of Result Ids for a Batch Query * getQueryResult - Gets results for a Result Id * getRecentReports - Gets up to 200 of the reports you most recently viewed by sending a GET request to the Report List resource. * getReportDescription - Retrieves the report, report type, and related metadata for a report, either in a tabular or summary or matrix format. * executeSyncReport - Runs a report synchronously with or without changing filters and returns the latest summary data. * executeAsyncReport - Runs an instance of a report asynchronously with or without filters and returns the summary data with or without details. * getReportInstances - Returns a list of instances for a report that you requested to be run asynchronously. Each item in the list is treated as a separate instance of the report. * getReportResults: Contains the results of running a report. For example, the following producer endpoint uses the createBatch API to create a Job Batch. The in message must contain a body that can be converted into an `InputStream` (usually UTF-8 CSV or XML content from a file, etc.) and header fields 'jobId' for the Job and 'contentType' for the Job content type, which can be XML, CSV, ZIP_XML or ZIP_CSV. The put message body will contain `BatchInfo` on success, or throw a `SalesforceException` on error. [source,java] ---- ...to(""salesforce:createBatchJob"").. ---- === Rest Streaming API Consumer endpoints can use the following syntax for streaming endpoints to receive Salesforce notifications on create/update. To create and subscribe to a topic [source,java] ---- from(""salesforce:CamelTestTopic?notifyForFields=ALL¬ifyForOperations=ALL&sObjectName=Merchandise__c&updateTopic=true&sObjectQuery=SELECT Id, Name FROM Merchandise__c"")... ---- To subscribe to an existing topic [source,java] ---- from(""salesforce:CamelTestTopic&sObjectName=Merchandise__c"")... ---- === Platform events To emit a platform event use `createSObject` operation. And set the message body can be JSON string or InputStream with key-value data -- in that case `sObjectName` needs to be set to the API name of the event, or a class that extends from AbstractDTOBase with the appropriate class name for the event. For example using a DTO: [source,java] ---- class Order_Event__e extends AbstractDTOBase { @JsonProperty(""OrderNumber"") private String orderNumber; // ... other properties and getters/setters } from(""timer:tick"") .process(exchange -> { final Message in = exchange.getIn(); String orderNumber = ""ORD"" + String.valueOf(in.getHeader(Exchange.TIMER_COUNTER)); Order_Event__e event = new Order_Event__e(); event.setOrderNumber(orderNumber); in.setBody(event); }) .to(""salesforce:createSObject""); ---- Or using JSON event data: [source,java] ---- from(""timer:tick"") .process(exchange -> { final Message in = exchange.getIn(); String orderNumber = ""ORD"" + String.valueOf(in.getHeader(Exchange.TIMER_COUNTER)); in.setBody(""{\\""OrderNumber\\"":\\"""" + orderNumber + ""\\""}""); }) .to(""salesforce:createSObject?sObjectName=Order_Event__e""); ---- To receive platform events use the consumer endpoint with the API name of the platform event prefixed with `event/` (or `/event/`), e.g.: `salesforce:events/Order_Event__e`. Processor consuming from that endpoint will receive either `org.apache.camel.component.salesforce.api.dto.PlatformEvent` object or `org.cometd.bayeux.Message` in the body depending on the `rawPayload` being `false` or `true` respectively. For example, in the simplest form to consume one event: [source,java] ---- PlatformEvent event = consumer.receiveBody(""salesforce:event/Order_Event__e"", PlatformEvent.class); ---- === Change data capture events On the one hand, Salesforce could be configured to emit notifications for record changes of select objects. On the other hand, the Camel Salesforce component could react to such notifications, allowing for instance to https://trailhead.salesforce.com/en/content/learn/modules/change-data-capture/understand-change-data-capture[synchronize those changes into an external system]. The notifications of interest could be specified in the `from(""salesforce:XXX"")` clause of a Camel route via the subscription channel, e.g: [source,java] ---- from(""salesforce:data/ChangeEvents?replayId=-1"").log(""being notified of all change events"") from(""salesforce:data/AccountChangeEvent?replayId=-1"").log(""being notified of change events for Account records"") from(""salesforce:data/Employee__ChangeEvent?replayId=-1"").log(""being notified of change events for Employee__c custom object"") ---- The received message contains either `java.util.Map` or `org.cometd.bayeux.Message` in the body depending on the `rawPayload` being `false` or `true` respectively. The `CamelSalesforceChangeType` header could be valued to one of `CREATE`, `UPDATE`, `DELETE` or `UNDELETE`. More details about how to use the Camel Salesforce component change data capture capabilities could be found in the https://github.com/apache/camel/tree/master/components/camel-salesforce/camel-salesforce-component/src/test/java/org/apache/camel/component/salesforce/ChangeEventsConsumerIntegrationTest.java[ChangeEventsConsumerIntegrationTest]. The https://developer.salesforce.com/docs/atlas.en-us.change_data_capture.meta/change_data_capture/cdc_intro.htm[Salesforce developer guide] is a good fit to better know the subtleties of implementing a change data capture integration application. The dynamic nature of change event body fields, high level replication steps as well as security considerations could be of interest. == Examples === Uploading a document to a ContentWorkspace Create the ContentVersion in Java, using a Processor instance: [source,java] ---- public class ContentProcessor implements Processor { public void process(Exchange exchange) throws Exception { Message message = exchange.getIn(); ContentVersion cv = new ContentVersion(); ContentWorkspace cw = getWorkspace(exchange); cv.setFirstPublishLocationId(cw.getId()); cv.setTitle(""test document""); cv.setPathOnClient(""test_doc.html""); byte[] document = message.getBody(byte[].class); ObjectMapper mapper = new ObjectMapper(); String enc = mapper.convertValue(document, String.class); cv.setVersionDataUrl(enc); message.setBody(cv); } protected ContentWorkspace getWorkSpace(Exchange exchange) { // Look up the content workspace somehow, maybe use enrich() to add it to a // header that can be extracted here .... } } ---- Give the output from the processor to the Salesforce component: [source,java] ---- from(""file:///home/camel/library"") .to(new ContentProcessor()) // convert bytes from the file into a ContentVersion SObject // for the salesforce component .to(""salesforce:createSObject""); ---- == Using Salesforce Limits API With `salesforce:limits` operation you can fetch of API limits from Salesforce and then act upon that data received. The result of `salesforce:limits` operation is mapped to `org.apache.camel.component.salesforce.api.dto.Limits` class and can be used in a custom processors or expressions. For instance, consider that you need to limit the API usage of Salesforce so that 10% of daily API requests is left for other routes. The body of output message contains an instance of `org.apache.camel.component.salesforce.api.dto.Limits` object that can be used in conjunction with Content Based Router and Content Based Router and xref:spel-language.adoc[Spring Expression Language (SpEL)] to choose when to perform queries. Notice how multiplying `1.0` with the integer value held in `body.dailyApiRequests.remaining` makes the expression evaluate as with floating point arithmetic, without it - it would end up making integral division which would result with either `0` (some API limits consumed) or `1` (no API limits consumed). [source,java] ---- from(""direct:querySalesforce"") .to(""salesforce:limits"") .choice() .when(spel(""#{1.0 * body.dailyApiRequests.remaining / body.dailyApiRequests.max < 0.1}"")) .to(""salesforce:query?..."") .otherwise() .setBody(constant(""Used up Salesforce API limits, leaving 10% for critical routes"")) .endChoice() ---- == Working with approvals All the properties are named exactly the same as in the Salesforce REST API prefixed with `approval.`. You can set approval properties by setting `approval.PropertyName` of the Endpoint these will be used as template -- meaning that any property not present in either body or header will be taken from the Endpoint configuration. Or you can set the approval template on the Endpoint by assigning `approval` property to a reference onto a bean in the Registry. You can also provide header values using the same `approval.PropertyName` in the incoming message headers. And finally body can contain one `AprovalRequest` or an `Iterable` of `ApprovalRequest` objects to process as a batch. The important thing to remember is the priority of the values specified in these three mechanisms: . value in body takes precedence before any other . value in message header takes precedence before template value . value in template is set if no other value in header or body was given For example to send one record for approval using values in headers use: Given a route: [source,java] ---- from(""direct:example1"")// .setHeader(""approval.ContextId"", simple(""${body['contextId']}"")) .setHeader(""approval.NextApproverIds"", simple(""${body['nextApproverIds']}"")) .to(""salesforce:approval?""// + ""approval.actionType=Submit""// + ""&approval.comments=this is a test""// + ""&approval.processDefinitionNameOrId=Test_Account_Process""// + ""&approval.skipEntryCriteria=true""); ---- You could send a record for approval using: [source,java] ---- final Map body = new HashMap<>(); body.put(""contextId"", accountIds.iterator().next()); body.put(""nextApproverIds"", userId); final ApprovalResult result = template.requestBody(""direct:example1"", body, ApprovalResult.class); ---- == Using Salesforce Recent Items API To fetch the recent items use `salesforce:recent` operation. This operation returns an `java.util.List` of `org.apache.camel.component.salesforce.api.dto.RecentItem` objects (`List`) that in turn contain the `Id`, `Name` and `Attributes` (with `type` and `url` properties). You can limit the number of returned items by specifying `limit` parameter set to maximum number of records to return. For example: [source,java] ---- from(""direct:fetchRecentItems"") to(""salesforce:recent"") .split().body() .log(""${body.name} at ${body.attributes.url}""); ---- == Using Salesforce Composite API to submit SObject tree To create up to 200 records including parent-child relationships use `salesforce:composite-tree` operation. This requires an instance of `org.apache.camel.component.salesforce.api.dto.composite.SObjectTree` in the input message and returns the same tree of objects in the output message. The `org.apache.camel.component.salesforce.api.dto.AbstractSObjectBase` instances within the tree get updated with the identifier values (`Id` property) or their corresponding `org.apache.camel.component.salesforce.api.dto.composite.SObjectNode` is populated with `errors` on failure. Note that for some records operation can succeed and for some it can fail -- so you need to manually check for errors. Easiest way to use this functionality is to use the DTOs generated by the `camel-salesforce-maven-plugin`, but you also have the option of customizing the references that identify the each object in the tree, for instance primary keys from your database. Lets look at an example: [source,java] ---- Account account = ... Contact president = ... Contact marketing = ... Account anotherAccount = ... Contact sales = ... Asset someAsset = ... // build the tree SObjectTree request = new SObjectTree(); request.addObject(account).addChildren(president, marketing); request.addObject(anotherAccount).addChild(sales).addChild(someAsset); final SObjectTree response = template.requestBody(""salesforce:composite-tree"", tree, SObjectTree.class); final Map> result = response.allNodes() .collect(Collectors.groupingBy(SObjectNode::hasErrors)); final List withErrors = result.get(true); final List succeeded = result.get(false); final String firstId = succeeded.get(0).getId(); ---- == Using Salesforce Composite API to submit multiple requests in a batch The Composite API batch operation (`composite-batch`) allows you to accumulate multiple requests in a batch and then submit them in one go, saving the round trip cost of multiple individual requests. Each response is then received in a list of responses with the order preserved, so that the n-th requests response is in the n-th place of the response. NOTE: The results can vary from API to API so the result of the request is given as a `java.lang.Object`. In most cases the result will be a `java.util.Map` with string keys and values or other `java.util.Map` as value. Requests made in JSON format hold some type information (i.e. it is known what values are strings and what values are numbers), so in general those will be more type friendly. Note that the responses will vary between XML and JSON, this is due to the responses from Salesforce API being different. So be careful if you switch between formats without changing the response handling code. Lets look at an example: [source,java] ---- final String acountId = ... final SObjectBatch batch = new SObjectBatch(""38.0""); final Account updates = new Account(); updates.setName(""NewName""); batch.addUpdate(""Account"", accountId, updates); final Account newAccount = new Account(); newAccount.setName(""Account created from Composite batch API""); batch.addCreate(newAccount); batch.addGet(""Account"", accountId, ""Name"", ""BillingPostalCode""); batch.addDelete(""Account"", accountId); final SObjectBatchResponse response = template.requestBody(""salesforce:composite-batch?format=JSON"", batch, SObjectBatchResponse.class); boolean hasErrors = response.hasErrors(); // if any of the requests has resulted in either 4xx or 5xx HTTP status final List results = response.getResults(); // results of three operations sent in batch final SObjectBatchResult updateResult = results.get(0); // update result final int updateStatus = updateResult.getStatusCode(); // probably 204 final Object updateResultData = updateResult.getResult(); // probably null final SObjectBatchResult createResult = results.get(1); // create result @SuppressWarnings(""unchecked"") final Map createData = (Map) createResult.getResult(); final String newAccountId = createData.get(""id""); // id of the new account, this is for JSON, for XML it would be createData.get(""Result"").get(""id"") final SObjectBatchResult retrieveResult = results.get(2); // retrieve result @SuppressWarnings(""unchecked"") final Map retrieveData = (Map) retrieveResult.getResult(); final String accountName = retrieveData.get(""Name""); // Name of the retrieved account, this is for JSON, for XML it would be createData.get(""Account"").get(""Name"") final String accountBillingPostalCode = retrieveData.get(""BillingPostalCode""); // Name of the retrieved account, this is for JSON, for XML it would be createData.get(""Account"").get(""BillingPostalCode"") final SObjectBatchResult deleteResult = results.get(3); // delete result final int updateStatus = deleteResult.getStatusCode(); // probably 204 final Object updateResultData = deleteResult.getResult(); // probably null ---- == Using Salesforce Composite API to submit multiple chained requests The `composite` operation allows submitting up to 25 requests that can be chained together, for instance identifier generated in previous request can be used in subsequent request. Individual requests and responses are linked with the provided _reference_. NOTE: Composite API supports only JSON payloads. NOTE: As with the batch API the results can vary from API to API so the result of the request is given as a `java.lang.Object`. In most cases the result will be a `java.util.Map` with string keys and values or other `java.util.Map` as value. Requests made in JSON format hold some type information (i.e. it is known what values are strings and what values are numbers), so in general those will be more type friendly. Lets look at an example: [source,java] ---- SObjectComposite composite = new SObjectComposite(""38.0"", true); // first insert operation via an external id final Account updateAccount = new TestAccount(); updateAccount.setName(""Salesforce""); updateAccount.setBillingStreet(""Landmark @ 1 Market Street""); updateAccount.setBillingCity(""San Francisco""); updateAccount.setBillingState(""California""); updateAccount.setIndustry(Account_IndustryEnum.TECHNOLOGY); composite.addUpdate(""Account"", ""001xx000003DIpcAAG"", updateAccount, ""UpdatedAccount""); final Contact newContact = new TestContact(); newContact.setLastName(""John Doe""); newContact.setPhone(""1234567890""); composite.addCreate(newContact, ""NewContact""); final AccountContactJunction__c junction = new AccountContactJunction__c(); junction.setAccount__c(""001xx000003DIpcAAG""); junction.setContactId__c(""@{NewContact.id}""); composite.addCreate(junction, ""JunctionRecord""); final SObjectCompositeResponse response = template.requestBody(""salesforce:composite?format=JSON"", composite, SObjectCompositeResponse.class); final List results = response.getCompositeResponse(); final SObjectCompositeResult accountUpdateResult = results.stream().filter(r -> ""UpdatedAccount"".equals(r.getReferenceId())).findFirst().get() final int statusCode = accountUpdateResult.getHttpStatusCode(); // should be 200 final Map accountUpdateBody = accountUpdateResult.getBody(); final SObjectCompositeResult contactCreationResult = results.stream().filter(r -> ""JunctionRecord"".equals(r.getReferenceId())).findFirst().get() ---- == Sending null values to salesforce By default, SObject fields with null values are not sent to salesforce. In order to send null values to salesforce, use the `fieldsToNull` property, as follows: [source,java] ---- accountSObject.getFieldsToNull().add(""Site""); ---- == Generating SOQL query strings `org.apache.camel.component.salesforce.api.utils.QueryHelper` contains helper methods to generate SOQL queries. For instance to fetch all custom fields from _Account_ SObject you can simply generate the SOQL SELECT by invoking: [source,java] ---- String allCustomFieldsQuery = QueryHelper.queryToFetchFilteredFieldsOf(new Account(), SObjectField::isCustom); ---- == Camel Salesforce Maven Plugin This Maven plugin generates DTOs for the Camel. For obvious security reasons it is recommended that the clientId, clientSecret, userName and password fields be not set in the pom.xml. The plugin should be configured for the rest of the properties, and can be executed using the following command: [source,java] ---- mvn camel-salesforce:generate -DcamelSalesforce.clientId= -DcamelSalesforce.clientSecret= \\ -DcamelSalesforce.userName= -DcamelSalesforce.password= ---- The generated DTOs use Jackson and XStream annotations. All Salesforce field types are supported. Date and time fields are mapped to `java.time.ZonedDateTime` by default, and picklist fields are mapped to generated Java Enumerations. Please refer to https://github.com/apache/camel/tree/master/components/camel-salesforce/camel-salesforce-maven-plugin[README.md] for details on how to generate the DTO. == Options // component options: START The Salesforce component supports 31 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *authenticationType* (security) | Explicit authentication method to be used, one of USERNAME_PASSWORD, REFRESH_TOKEN or JWT. Salesforce component can auto-determine the authentication method to use from the properties set, set this property to eliminate any ambiguity. | | AuthenticationType | *loginConfig* (security) | All authentication configuration in one nested bean, all properties set there can be set directly on the component as well | | SalesforceLoginConfig | *instanceUrl* (security) | URL of the Salesforce instance used after authentication, by default received from Salesforce on successful authentication | | String | *loginUrl* (security) | *Required* URL of the Salesforce instance used for authentication, by default set to \\https://login.salesforce.com | https://login.salesforce.com | String | *clientId* (security) | *Required* OAuth Consumer Key of the connected app configured in the Salesforce instance setup. Typically a connected app needs to be configured but one can be provided by installing a package. | | String | *clientSecret* (security) | OAuth Consumer Secret of the connected app configured in the Salesforce instance setup. | | String | *keystore* (security) | KeyStore parameters to use in OAuth JWT flow. The KeyStore should contain only one entry with private key and certificate. Salesforce does not verify the certificate chain, so this can easily be a selfsigned certificate. Make sure that you upload the certificate to the corresponding connected app. | | KeyStoreParameters | *refreshToken* (security) | Refresh token already obtained in the refresh token OAuth flow. One needs to setup a web application and configure a callback URL to receive the refresh token, or configure using the builtin callback at \\https://login.salesforce.com/services/oauth2/success or \\https://test.salesforce.com/services/oauth2/success and then retrive the refresh_token from the URL at the end of the flow. Note that in development organizations Salesforce allows hosting the callback web application at localhost. | | String | *userName* (security) | Username used in OAuth flow to gain access to access token. It's easy to get started with password OAuth flow, but in general one should avoid it as it is deemed less secure than other flows. | | String | *password* (security) | Password used in OAuth flow to gain access to access token. It's easy to get started with password OAuth flow, but in general one should avoid it as it is deemed less secure than other flows. Make sure that you append security token to the end of the password if using one. | | String | *lazyLogin* (security) | If set to true prevents the component from authenticating to Salesforce with the start of the component. You would generally set this to the (default) false and authenticate early and be immediately aware of any authentication issues. | false | boolean | *config* (common) | Global endpoint configuration - use to set values that are common to all endpoints | | SalesforceEndpointConfig | *httpClientProperties* (common) | Used to set any properties that can be configured on the underlying HTTP client. Have a look at properties of SalesforceHttpClient and the Jetty HttpClient for all available options. | | Map | *longPollingTransport Properties* (common) | Used to set any properties that can be configured on the LongPollingTransport used by the BayeuxClient (CometD) used by the streaming api | | Map | *sslContextParameters* (security) | SSL parameters to use, see SSLContextParameters class for all available options. | | SSLContextParameters | *useGlobalSslContext Parameters* (security) | Enable usage of global SSL context parameters | false | boolean | *httpClientIdleTimeout* (common) | Timeout used by the HttpClient when waiting for response from the Salesforce server. | 10000 | long | *httpClientConnection Timeout* (common) | Connection timeout used by the HttpClient when connecting to the Salesforce server. | 60000 | long | *httpProxyHost* (proxy) | Hostname of the HTTP proxy server to use. | | String | *httpProxyPort* (proxy) | Port number of the HTTP proxy server to use. | | Integer | *httpProxyUsername* (security) | Username to use to authenticate against the HTTP proxy server. | | String | *httpProxyPassword* (security) | Password to use to authenticate against the HTTP proxy server. | | String | *isHttpProxySocks4* (proxy) | If set to true the configures the HTTP proxy to use as a SOCKS4 proxy. | false | boolean | *isHttpProxySecure* (security) | If set to false disables the use of TLS when accessing the HTTP proxy. | true | boolean | *httpProxyIncluded Addresses* (proxy) | A list of addresses for which HTTP proxy server should be used. | | Set | *httpProxyExcluded Addresses* (proxy) | A list of addresses for which HTTP proxy server should not be used. | | Set | *httpProxyAuthUri* (security) | Used in authentication against the HTTP proxy server, needs to match the URI of the proxy server in order for the httpProxyUsername and httpProxyPassword to be used for authentication. | | String | *httpProxyRealm* (security) | Realm of the proxy server, used in preemptive Basic/Digest authentication methods against the HTTP proxy server. | | String | *httpProxyUseDigest Auth* (security) | If set to true Digest authentication will be used when authenticating to the HTTP proxy,otherwise Basic authorization method will be used | false | boolean | *packages* (common) | In what packages are the generated DTO classes. Typically the classes would be generated using camel-salesforce-maven-plugin. Set it if using the generated DTOs to gain the benefit of using short SObject names in parameters/header values. | | String[] | *basicPropertyBinding* (advanced) | Whether the component should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities | false | boolean |=== // component options: END // endpoint options: START The Salesforce endpoint is configured using URI syntax: ---- salesforce:operationName:topicName ---- with the following path and query parameters: === Path Parameters (2 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *operationName* | The operation to use | | OperationName | *topicName* | The name of the topic/channel to use | | String |=== === Query Parameters (45 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *apexMethod* (common) | APEX method name | | String | *apexQueryParams* (common) | Query params for APEX method | | Map | *apexUrl* (common) | APEX method URL | | String | *apiVersion* (common) | Salesforce API version, defaults to SalesforceEndpointConfig.DEFAULT_VERSION | | String | *backoffIncrement* (common) | Backoff interval increment for Streaming connection restart attempts for failures beyond CometD auto-reconnect. | | long | *batchId* (common) | Bulk API Batch ID | | String | *contentType* (common) | Bulk API content type, one of XML, CSV, ZIP_XML, ZIP_CSV | | ContentType | *defaultReplayId* (common) | Default replayId setting if no value is found in initialReplayIdMap | | Long | *format* (common) | Payload format to use for Salesforce API calls, either JSON or XML, defaults to JSON | | PayloadFormat | *httpClient* (common) | Custom Jetty Http Client to use to connect to Salesforce. | | SalesforceHttpClient | *includeDetails* (common) | Include details in Salesforce1 Analytics report, defaults to false. | | Boolean | *initialReplayIdMap* (common) | Replay IDs to start from per channel name. | | Map | *instanceId* (common) | Salesforce1 Analytics report execution instance ID | | String | *jobId* (common) | Bulk API Job ID | | String | *limit* (common) | Limit on number of returned records. Applicable to some of the API, check the Salesforce documentation. | | Integer | *maxBackoff* (common) | Maximum backoff interval for Streaming connection restart attempts for failures beyond CometD auto-reconnect. | | long | *notFoundBehaviour* (common) | Sets the behaviour of 404 not found status received from Salesforce API. Should the body be set to NULL NotFoundBehaviour#NULL or should a exception be signaled on the exchange NotFoundBehaviour#EXCEPTION - the default. | | NotFoundBehaviour | *notifyForFields* (common) | Notify for fields, options are ALL, REFERENCED, SELECT, WHERE | | NotifyForFieldsEnum | *notifyForOperationCreate* (common) | Notify for create operation, defaults to false (API version = 29.0) | | Boolean | *notifyForOperationDelete* (common) | Notify for delete operation, defaults to false (API version = 29.0) | | Boolean | *notifyForOperations* (common) | Notify for operations, options are ALL, CREATE, EXTENDED, UPDATE (API version 29.0) | | NotifyForOperationsEnum | *notifyForOperationUndelete* (common) | Notify for un-delete operation, defaults to false (API version = 29.0) | | Boolean | *notifyForOperationUpdate* (common) | Notify for update operation, defaults to false (API version = 29.0) | | Boolean | *objectMapper* (common) | Custom Jackson ObjectMapper to use when serializing/deserializing Salesforce objects. | | ObjectMapper | *rawPayload* (common) | Use raw payload String for request and response (either JSON or XML depending on format), instead of DTOs, false by default | false | boolean | *reportId* (common) | Salesforce1 Analytics report Id | | String | *reportMetadata* (common) | Salesforce1 Analytics report metadata for filtering | | ReportMetadata | *resultId* (common) | Bulk API Result ID | | String | *sObjectBlobFieldName* (common) | SObject blob field name | | String | *sObjectClass* (common) | Fully qualified SObject class name, usually generated using camel-salesforce-maven-plugin | | String | *sObjectFields* (common) | SObject fields to retrieve | | String | *sObjectId* (common) | SObject ID if required by API | | String | *sObjectIdName* (common) | SObject external ID field name | | String | *sObjectIdValue* (common) | SObject external ID field value | | String | *sObjectName* (common) | SObject name if required or supported by API | | String | *sObjectQuery* (common) | Salesforce SOQL query string | | String | *sObjectSearch* (common) | Salesforce SOSL search string | | String | *updateTopic* (common) | Whether to update an existing Push Topic when using the Streaming API, defaults to false | false | boolean | *bridgeErrorHandler* (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | *replayId* (consumer) | The replayId value to use when subscribing | | Long | *exceptionHandler* (consumer) | To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored. | | ExceptionHandler | *exchangePattern* (consumer) | Sets the exchange pattern when the consumer creates an exchange. | | ExchangePattern | *lazyStartProducer* (producer) | Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel's routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | *basicPropertyBinding* (advanced) | Whether the endpoint should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities | false | boolean | *synchronous* (advanced) | Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported). | false | boolean |=== // endpoint options: END // spring-boot-auto-configure options: START == Spring Boot Auto-Configuration When using Spring Boot make sure to use the following Maven dependency to have support for auto configuration: [source,xml] ---- org.apache.camel camel-salesforce-starter x.x.x ---- The component supports 86 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *camel.component.salesforce.authentication-type* | Explicit authentication method to be used, one of USERNAME_PASSWORD, REFRESH_TOKEN or JWT. Salesforce component can auto-determine the authentication method to use from the properties set, set this property to eliminate any ambiguity. | | AuthenticationType | *camel.component.salesforce.basic-property-binding* | Whether the component should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities | false | Boolean | *camel.component.salesforce.client-id* | OAuth Consumer Key of the connected app configured in the Salesforce instance setup. Typically a connected app needs to be configured but one can be provided by installing a package. | | String | *camel.component.salesforce.client-secret* | OAuth Consumer Secret of the connected app configured in the Salesforce instance setup. | | String | *camel.component.salesforce.config.apex-method* | APEX method name | | String | *camel.component.salesforce.config.apex-query-params* | Query params for APEX method | | Map | *camel.component.salesforce.config.apex-url* | APEX method URL | | String | *camel.component.salesforce.config.api-version* | Salesforce API version, defaults to SalesforceEndpointConfig.DEFAULT_VERSION | | String | *camel.component.salesforce.config.approval* | The approval request for Approval API. | | ApprovalRequest | *camel.component.salesforce.config.approval-action-type* | Represents the kind of action to take: Submit, Approve, or Reject. | | ApprovalRequest$Action | *camel.component.salesforce.config.approval-comments* | The comment to add to the history step associated with this request. | | String | *camel.component.salesforce.config.approval-context-actor-id* | The ID of the submitter who’s requesting the approval record. | | String | *camel.component.salesforce.config.approval-context-id* | The ID of the item that is being acted upon. | | String | *camel.component.salesforce.config.approval-next-approver-ids* | If the process requires specification of the next approval, the ID of the user to be assigned the next request. | | List | *camel.component.salesforce.config.approval-process-definition-name-or-id* | The developer name or ID of the process definition. | | String | *camel.component.salesforce.config.approval-skip-entry-criteria* | Determines whether to evaluate the entry criteria for the process (true) or not (false) if the process definition name or ID isn’t null. If the process definition name or ID isn’t specified, this argument is ignored, and standard evaluation is followed based on process order. By default, the entry criteria isn’t skipped if it’s not set by this request. | | Boolean | *camel.component.salesforce.config.backoff-increment* | Backoff interval increment for Streaming connection restart attempts for failures beyond CometD auto-reconnect. | | Long | *camel.component.salesforce.config.batch-id* | Bulk API Batch ID | | String | *camel.component.salesforce.config.content-type* | Bulk API content type, one of XML, CSV, ZIP_XML, ZIP_CSV | | ContentType | *camel.component.salesforce.config.default-replay-id* | Default replayId setting if no value is found in {@link #initialReplayIdMap} | | Long | *camel.component.salesforce.config.format* | Payload format to use for Salesforce API calls, either JSON or XML, defaults to JSON | | PayloadFormat | *camel.component.salesforce.config.http-client* | Custom Jetty Http Client to use to connect to Salesforce. | | SalesforceHttpClient | *camel.component.salesforce.config.include-details* | Include details in Salesforce1 Analytics report, defaults to false. | | Boolean | *camel.component.salesforce.config.initial-replay-id-map* | Replay IDs to start from per channel name. | | Map | *camel.component.salesforce.config.instance-id* | Salesforce1 Analytics report execution instance ID | | String | *camel.component.salesforce.config.job-id* | Bulk API Job ID | | String | *camel.component.salesforce.config.limit* | Limit on number of returned records. Applicable to some of the API, check the Salesforce documentation. | | Integer | *camel.component.salesforce.config.max-backoff* | Maximum backoff interval for Streaming connection restart attempts for failures beyond CometD auto-reconnect. | | Long | *camel.component.salesforce.config.not-found-behaviour* | Sets the behaviour of 404 not found status received from Salesforce API. Should the body be set to NULL {@link NotFoundBehaviour#NULL} or should a exception be signaled on the exchange {@link NotFoundBehaviour#EXCEPTION} - the default. | | NotFoundBehaviour | *camel.component.salesforce.config.notify-for-fields* | Notify for fields, options are ALL, REFERENCED, SELECT, WHERE | | NotifyForFieldsEnum | *camel.component.salesforce.config.notify-for-operation-create* | Notify for create operation, defaults to false (API version >= 29.0) | | Boolean | *camel.component.salesforce.config.notify-for-operation-delete* | Notify for delete operation, defaults to false (API version >= 29.0) | | Boolean | *camel.component.salesforce.config.notify-for-operation-undelete* | Notify for un-delete operation, defaults to false (API version >= 29.0) | | Boolean | *camel.component.salesforce.config.notify-for-operation-update* | Notify for update operation, defaults to false (API version >= 29.0) | | Boolean | *camel.component.salesforce.config.notify-for-operations* | Notify for operations, options are ALL, CREATE, EXTENDED, UPDATE (API version < 29.0) | | NotifyForOperationsEnum | *camel.component.salesforce.config.object-mapper* | Custom Jackson ObjectMapper to use when serializing/deserializing Salesforce objects. | | ObjectMapper | *camel.component.salesforce.config.raw-payload* | Use raw payload {@link String} for request and response (either JSON or XML depending on {@code format}), instead of DTOs, false by default | false | Boolean | *camel.component.salesforce.config.report-id* | Salesforce1 Analytics report Id | | String | *camel.component.salesforce.config.report-metadata* | Salesforce1 Analytics report metadata for filtering | | ReportMetadata | *camel.component.salesforce.config.result-id* | Bulk API Result ID | | String | *camel.component.salesforce.config.s-object-blob-field-name* | SObject blob field name | | String | *camel.component.salesforce.config.s-object-class* | Fully qualified SObject class name, usually generated using camel-salesforce-maven-plugin | | String | *camel.component.salesforce.config.s-object-fields* | SObject fields to retrieve | | String | *camel.component.salesforce.config.s-object-id* | SObject ID if required by API | | String | *camel.component.salesforce.config.s-object-id-name* | SObject external ID field name | | String | *camel.component.salesforce.config.s-object-id-value* | SObject external ID field value | | String | *camel.component.salesforce.config.s-object-name* | SObject name if required or supported by API | | String | *camel.component.salesforce.config.s-object-query* | Salesforce SOQL query string | | String | *camel.component.salesforce.config.s-object-search* | Salesforce SOSL search string | | String | *camel.component.salesforce.config.update-topic* | Whether to update an existing Push Topic when using the Streaming API, defaults to false | false | Boolean | *camel.component.salesforce.enabled* | Enable salesforce component | true | Boolean | *camel.component.salesforce.http-client-connection-timeout* | Connection timeout used by the HttpClient when connecting to the Salesforce server. | 60000 | Long | *camel.component.salesforce.http-client-idle-timeout* | Timeout used by the HttpClient when waiting for response from the Salesforce server. | 10000 | Long | *camel.component.salesforce.http-client-properties* | Used to set any properties that can be configured on the underlying HTTP client. Have a look at properties of SalesforceHttpClient and the Jetty HttpClient for all available options. | | Map | *camel.component.salesforce.http-proxy-auth-uri* | Used in authentication against the HTTP proxy server, needs to match the URI of the proxy server in order for the httpProxyUsername and httpProxyPassword to be used for authentication. | | String | *camel.component.salesforce.http-proxy-excluded-addresses* | A list of addresses for which HTTP proxy server should not be used. | | Set | *camel.component.salesforce.http-proxy-host* | Hostname of the HTTP proxy server to use. | | String | *camel.component.salesforce.http-proxy-included-addresses* | A list of addresses for which HTTP proxy server should be used. | | Set | *camel.component.salesforce.http-proxy-password* | Password to use to authenticate against the HTTP proxy server. | | String | *camel.component.salesforce.http-proxy-port* | Port number of the HTTP proxy server to use. | | Integer | *camel.component.salesforce.http-proxy-realm* | Realm of the proxy server, used in preemptive Basic/Digest authentication methods against the HTTP proxy server. | | String | *camel.component.salesforce.http-proxy-use-digest-auth* | If set to true Digest authentication will be used when authenticating to the HTTP proxy,otherwise Basic authorization method will be used | false | Boolean | *camel.component.salesforce.http-proxy-username* | Username to use to authenticate against the HTTP proxy server. | | String | *camel.component.salesforce.instance-url* | URL of the Salesforce instance used after authentication, by default received from Salesforce on successful authentication | | String | *camel.component.salesforce.is-http-proxy-secure* | If set to false disables the use of TLS when accessing the HTTP proxy. | true | Boolean | *camel.component.salesforce.is-http-proxy-socks4* | If set to true the configures the HTTP proxy to use as a SOCKS4 proxy. | false | Boolean | *camel.component.salesforce.keystore* | KeyStore parameters to use in OAuth JWT flow. The KeyStore should contain only one entry with private key and certificate. Salesforce does not verify the certificate chain, so this can easily be a selfsigned certificate. Make sure that you upload the certificate to the corresponding connected app. The option is a org.apache.camel.support.jsse.KeyStoreParameters type. | | String | *camel.component.salesforce.lazy-login* | If set to true prevents the component from authenticating to Salesforce with the start of the component. You would generally set this to the (default) false and authenticate early and be immediately aware of any authentication issues. | false | Boolean | *camel.component.salesforce.login-config.client-id* | Salesforce connected application Consumer Key | | String | *camel.component.salesforce.login-config.client-secret* | Salesforce connected application Consumer Secret | | String | *camel.component.salesforce.login-config.instance-url* | Configuration object for Salesforce login properties | | String | *camel.component.salesforce.login-config.keystore* | Keystore parameters for keystore containing certificate and private key needed for OAuth 2.0 JWT Bearer Token Flow. | | KeyStoreParameters | *camel.component.salesforce.login-config.lazy-login* | Flag to enable/disable lazy OAuth, default is false. When enabled, OAuth token retrieval or generation is not done until the first API call | false | Boolean | *camel.component.salesforce.login-config.login-url* | Salesforce login URL, defaults to \\https://login.salesforce.com | https://login.salesforce.com | String | *camel.component.salesforce.login-config.password* | Salesforce account password | | String | *camel.component.salesforce.login-config.refresh-token* | Salesforce connected application Consumer token | | String | *camel.component.salesforce.login-config.type* | Salesforce connected application Consumer token | | AuthenticationType | *camel.component.salesforce.login-config.user-name* | Salesforce account user name | | String | *camel.component.salesforce.login-url* | URL of the Salesforce instance used for authentication, by default set to \\https://login.salesforce.com | https://login.salesforce.com | String | *camel.component.salesforce.long-polling-transport-properties* | Used to set any properties that can be configured on the LongPollingTransport used by the BayeuxClient (CometD) used by the streaming api | | Map | *camel.component.salesforce.packages* | In what packages are the generated DTO classes. Typically the classes would be generated using camel-salesforce-maven-plugin. Set it if using the generated DTOs to gain the benefit of using short SObject names in parameters/header values. | | String[] | *camel.component.salesforce.password* | Password used in OAuth flow to gain access to access token. It's easy to get started with password OAuth flow, but in general one should avoid it as it is deemed less secure than other flows. Make sure that you append security token to the end of the password if using one. | | String | *camel.component.salesforce.refresh-token* | Refresh token already obtained in the refresh token OAuth flow. One needs to setup a web application and configure a callback URL to receive the refresh token, or configure using the builtin callback at \\https://login.salesforce.com/services/oauth2/success or \\https://test.salesforce.com/services/oauth2/success and then retrive the refresh_token from the URL at the end of the flow. Note that in development organizations Salesforce allows hosting the callback web application at localhost. | | String | *camel.component.salesforce.ssl-context-parameters* | SSL parameters to use, see SSLContextParameters class for all available options. The option is a org.apache.camel.support.jsse.SSLContextParameters type. | | String | *camel.component.salesforce.use-global-ssl-context-parameters* | Enable usage of global SSL context parameters | false | Boolean | *camel.component.salesforce.user-name* | Username used in OAuth flow to gain access to access token. It's easy to get started with password OAuth flow, but in general one should avoid it as it is deemed less secure than other flows. | | String |=== // spring-boot-auto-configure options: END ",12158,False,2156.007867465547,median "=== 9 Manía ==== Notas clínicas .Afecto Expresiones de vida media corta reflejas de contingencias emocionales momentáneas. .Humor Emociones sostenidas sentidas interiormente .Humor patológico Desproporcionado al estresor o a la situación concurrente, no responde a continentación, mantenido por semanas / meses / años, juicio alterado por severa influencia del humor. Endoreactivo: demasiado intenso, disregulación permanente dada por (1) la facilidad con que se alcanza un intenso estado de humor ante un estrés y (2) persiste autónomamente cuando el estresor cesa. ==== Encare Motivos de consulta: traído por terceros (trastorno de conductas basales o complejas y pragmatismos), complicación medicolegal, abandono de medicación. ===== En suma Paciente de sexo X, con AF de trastornos afectivos o sus equivalentes (alcoholismo), con AP de episodios de humor en más (y/o en menos), con tratamientos que (mantuvo / abandonó), con (buena/mala) adaptación pragmática interepisódica, que es traído (por terceros, en general no por cuenta propia) a la consulta por alteraciones de conducta / alteración de CB / pragmatismos con un cuadro centrado en el humor que pasamos a analizar. ===== Agrupación sindromática ====== Síndrome de exaltación del humor Centra el cuadro clínico, de X tiempo de evolución (en general desarrollo rápido en 1-2 semanas), que se presenta luego de icon:paperclip[] (60% tienen como antecedente algún estresor psicosocial), en el que se aprecia una aceleración de los procesos psíquicos, evidenciado por los elemento que se detallan. .Humor Central en el cuadro. Humor predominantemente expansivo y exaltado, que pareciera optimista, pero de tonalidad inestable y oscilante y que puede llegar a colérico, eufórico e irritable, con una tendencia a dominar el encuentro y ridiculizar al entrevistador, con elementos eróticos, con una afectividad que se presenta lábil, con oscilaciones, con llantos y risas. Puede presentar un síndrome de ansiedad que reconocemos como parte integrante de este cuadro del humor (puede describirse aparte si la magnitud lo permite). .Presentación Un acortamiento del espacio interpersonal, confianza excesiva, el paciente es invasivo, nos tutea, nos toca, nos interrumpe, usa un tono de voz alta, tiende a dominar la entrevista, está inquieto, alegre, canta, baila, grita, desinhibido, se desnuda, porte desprolijo o desaliñado, facies animado, alegre o furioso, habla sin cesar, está en continuo movimiento y parece no cansarse. .Mímica y gestualidad Aumentadas, congreuentes con las oscilaciones del humor. .Actitud Inadecuada, lúdica, expansiva. .Cognición Se distrae fácilmente por estímulos periféricos, tiene dificultad para fijar la atención voluntaria y espontánea en algo en particular (hipoprosexia), con alteraciones de la memoria reciente, con dificultades para reconstruir el pasado reciente, pero con una exaltación de la memoria lejana. En general está BOTE (puede no estar por falta de atención). Carencia de insight. Sin conciencia de morbidez. .Pensamiento Forma: lenguaje con logorrea, un flujo del habla incontrolable, excesivo, que invade y domina la conversación. Un curso acelerado, con verborrea, configurando una taquipsiquia, acompañada de una fuga de ideas, pues el paciente comienza un relato que no concluye para pasar de inmediato a otro diferente mediante la asociación por asonancia, es decir una asociación superficial y efímera de ideas que se presenta por lo tanto como un pensamiento no finalista. La taquipsiquia y la fuga de ideas (o fuga de temas) dan cuenta de la exaltación del ser psíquico en su totalidad. Contenido: reconocemos ideas sobrevaloradas, exageradas, condicionadas afectivamente, comprensibles en la vida del paciente, pero no compartibles, con calor afectivo, de las cuales puede no tener una verdadera convicción, son fugaces, admiten críticas, enmarcadas en un entorno lúdico, parecen delirantes pero tienen menor intensidad. Centradas en grandiosidad, omnipotencia e hiperoptimismo. icon:sticky-note[] Si las ideas exceden lo sobrevalorado icon:arrow-right[] Síndrome delirante. .Psicomotricidad Se presenta exaltada, no puede estar quieto, con necesidad imperiosa de actividad, volcado al ambiente, camina, cambia las cosas de lugar, canta, baila, se sienta, se levanta, con un actitud lúdica, pero que es improductiva, estéril y sin cansancio físico proporcional, con menor necesidad de dormir. Llega a realizar estos actos sin finalidad, desordenados. Toma elementos del ambiente. .Conductual En las conductas basales destacamos adelgazamiento, disminución de la necesidad de dormir, anorexia o hiperorexia con polidipsia y polifagia (pueden ser prodromos). En los pragmatismos destacamos la esterilidad e la hiperactividad con deterioro laboral, social y familiar (pobre juicio social), hipersexualidad con riesgo de ETS, llamadas excesivas inadecuadas. En las conductas complejas: agresividad, derroche, malos negocios, prodigalidad, compromiso excesivo en actividades placenteras, consumo de sustancias/OH (dentro y fuera del episodio actual), juegos de azar, casamiento impulsivo, actos con repercusión medicolegal. ====== Síndrome delirante / síndrome de alteración del pensamiento En ocasiones las ideas dejan de ser sobrevaloradas para ser delirantes. En este caso son ideas mórbidas, permanentes, incompartibles, irreductibles a la lógica, con defensa con convicción y con generación de conductas. .Formal Curso acelerado, asociación de ideas rápida y superficial, asociaciones frágiles, flujo continuo de frases rápidas, mal hilvanadas. Salta de un tema a otro (idea a otra) constituyendo una taquipsiquia con fuga de ideas que traduce la exaltación del ser psíquico en su totalidad. Esta hiperactividad de los procesos psíquicos leva a una incapacidad de fijarse en una idea concreta con fijación a estímulos irrelevantes. Esta ""volatilidad"" es responsable de trastornos en atención (voluntaria y espontánea), memoria y orientación. .Contenido * Temática: megalomaníaca (capacidades especiales, identidad grandiosa, riqueza, misión especial), mística, filiatoria, erótica, persecutoria, de envidia. * Mecanismo: principalmente intuitivo, pero puede ser imaginativo, interpretativo, alucinatorio. * Sistematización: mala sistematización: con escaso orden, coherencia y claridad. * Conductas: le genera conductas (compras, gastos, sexo, violencia, robos, consumo de sustancias, alcohol). Se configura un delirio móvil, cambiante, desorganizado. * Congruencia: puede ser congruente o incongruente con el estado de ánimo expansivo. ====== Síndrome de ansiedad-angustia Ansiedad masiva, invasiva, desestructurante e incompartible, por lo que la catalogamos como ansiedad psicótica. ====== Síndrome de alteración de la conciencia Evidenciado por la imposibilidad del paciente de adaptar el campo fenomenológico de la conciencia al momento presente, lo que configura para la Teoría Organodinámica de Ey una desestructuración de conciencia de primer grado o nivel ético-temporal. Carece de conciencia mórbida. No presentifica el encuentro con el médico psiquiatra. Dificultad para reconstruir el pasado inmediato con alteración de la atención espontánea y voluntaria, dejándose llevar por estímulos ambientales. ====== Síndrome somático Evidenciado por las repercusiones de los cambios de apetito y sueño, así como de las conductas (consumo de sustancias, exposición a clima adverso). Destacar elementos metabólicos (adelgazamiento, deshidratación, hipertermina), neurológicos y endocrinológicos relevantes. ====== Síndrome depresivo Puede darse en retrospectiva (ver encare correspondiente) o bien con elementos depresivos dentro del cuadro actual (en ese caso, puede que haya que plantear episodio mixto). ===== Personalidad y nivel ====== Nivel icon:paste[] Nivel en diferido. ====== Personalidad Lo evaluaremos luego de remitido el cuadro actual. ===== Diagnóstico positivo ====== Nosografía clásica icon:paste[] Psicosis. icon:paste[] Psicosis aguda .Crisis de manía Por presentar una exaltación del humor como elemento central del cuadro clínico, del que se destaca la fuga de ideas, la exaltación psicomotriz con actitud lúdica e hiperactividad desordenada (y en caso de presentarlas destacar las ideas deliroides o delirantes), que ha repercutido negativamente en los desempeños y funcionamiento vital. .Forma clínica Las diferentes formas clínicas son un continuum dinámico, según fluctuaciones de superficialización o pofundización de la alteración de conciencia. * Manía franca (simple o aguda): es el cuadro clásico. Carece de delirio y alucinaciones. Pero como la imaginación está exaltada puede darse, en las formas con más desestructuración de la conciencia, ideas de convicción subdelirantes o fabulatorias, como un delirio en estado naciente que no se consolida dada la gran hiperactividad y aceleración de los procesos mentales. * Manía delirante: al desestructurarse la conciencia más profundamente se pasa a esta forma clínica. En ella se reconoce un delirio, una ""experiencia delirante"", aunque no de las características de la ""experiencia delirante primaria"" de la PDA. Este es cambiante, móvil, mínimamente sistematizado. Es un delirio verbalizado más que vivido (como en las PDA). * Furor maníaco: es el grado máximo de exaltación psicomotriz. Se presenta como una exaltación de la expresión principalmente motora, con oscurecimiento de la conciencia. Puede haber rechazo del alimento y signos orgánicos graves de agotamiento, deshidratación e hipertermia. * Estados mixtos: en todo episodio coexisten elementos maníacos y depresivos, pero en ocasiones esta mezcla es un rasgo principal del cuadro. * Hipomanía: caracterizada por la fuga de temas (la idea llega a desarrollarse o formar un tema), un humor jovial, eufórico, hiperactivo, con múltiples inciativas y proyectos que no llegan a finalizar, prodigalidad, hipersexualidad. Menor deterioro funcional. * Manía confusa: desorientación TE, alteraciones mnésicas, trastornos del pensamiento. .Diagnóstico nosológico Este acceso maníaco se inscribe en una enfermedad crónica, de manifestación episódica: Psicosis Maníaco-Depresiva. Esta se define por la presencia de uno o más episodios de manía, generalmente acompañado por uno o más episodios depresivos, en el contexto de antecedentes personales y familiares destacados. ====== Según sistemas de clasificación (DSM IV) .Diagnóstico del episodio Episodio maníaco A. Período diferenciado de estado de ánimo anormalmente y persistentemente elevado, expansivo o irritable, de al menos 1 semana de duración (o cualquier duración si se hospitaliza). B. Al menos 3 de estos síntomas: megalomanía, insomnio, verborrea, fuga de ideas, distraibilidad, hiperactividad, humor lúdico. C. Malestar o deterioro clínicamente significativo D. No cumple criterios para episodio mixto E. Se excluye cuadro provocado por sustancias, enfermedad médica, tratamiento farmacológico, trastorno por déficit atencional con hiperactividad, EDM con irritabilidad. Especificadores del episodio * Gravedad: leve, moderado, grave, con/sin síntomas psicóticos. * Curso: en curso, remisión parcial / total. * Síntomas psicóticos: congruentes / no congruentes con el estado de ánimo. * Síntomas catatónicos. * Inicio: inicio en postparto. Episodio Hipomaníaco Requiere: A y B: igual que manía, pero duración de al menos 4 días + A. Igual que manía B. Igual que manía C. Cambio con respecto a humor habitual + D. Cambio observable por terceros + E. Sin alteración importante de pragmatismos + F. Descartar sustancias, medicamentos, enfermedad médica. Episodio Mixto Requiere: A. Se cumplen criterios para episodio maníaco y para episodio depresivo mayor casi cada día x 1 período mayor a 1 semana + B. Alteración de pragmatismos + C. Descartar sustancias, enfermedad médica. Episodio Depresivo Ver encares de depresión .Diagnóstico nosológico Trastorno Bipolar I • Requiere: al menos 1 episodio maníaco o mixto (previo o actual). • Especificar: último episodio + especificadores del último episodio. • Especificadores de curso longitudinal: recuperación interepisódica (si/no), patrón estacional (si/no), ciclos rápidos (si/no). Tipos: • TB I episodio maníaco único • TB I episodio más reciente X (hipomaníaco, maníaco, mixto, depresivo) Trastorno Bipolar II • Requiere: al menos 1 episodio hipomaníaco + historia de uno o más episodios depresivos (SIN historia de episodios maníacos o mixtos). • Especificar: último episodio + especificadores de curso longitudinal. • Trastorno ciclotímico • Requiere: A. historia de 2 años de varios episodios hipomaníacos + episodios depresivos que no cumplen criterios de EDM + B. Nunca asintomático x más de 2 meses + C. Dos primeros años sin EDM, episodio maníaco o mixto (si aparecen luego de los 2 años, codifican los 2 trastornos) + D. Descartar esquizoafectivo, esquizofrenia, esquizofreniforme, trastorno delirante + E. Descartar sustancias, enfermedad médica + F. Alteración de pragmatismos. Especificadores del trastorno Curso: . ciclos rápidos (al menos 4 episodios en 12 meses, 15-20% de los bipolares) . con/sin patrón estacional . con/sin recuperación interepisódica total. Promotores del ciclado: * Hipotiroidismo subclínico * Sustancias/alcohol * Alteraciones del ciclo sueño/vigilia * Fármacos: antidepresivos, corticoides * Lesiones cerebrales ===== Diagnóstico diferencial ====== Del episodio .Con otras psicosis agudas . Manía secundaria a causa orgánica: si el cuadro se presenta a edad tardía, con trastorno de conciencia, desorientación, UISP, primer episodio, elementos atípicos: .. Causa: tóxica: anfetaminas, cocaína, alcohol, intoxicación o abstinencia. .. Fármacos: antidepresivos, corticoides. .. Endocrinológicas: hipertiroidismo, Cushing, encefalopatía hepática. .. Neurológica: epilepsia parcial compleja, esclerosis múltiple, corea, tumores, TEC. .. Infeccionsa: neurosífilis, HIV .. Metabólica .. Neoplasias: páncreas, pulmón .. Autoinmune. . PDA / Trastorno psicótico breve: tienen cosas en común (episodio agudo, desestructuración de conciencia y afectos, delirio, experiencia sensible y actual), pero con diferencias (predominio del humor exaltado y de la fuga de ideas, con actitud lúdica, ideas delirantes secundarias al trastorno del ánimo, AF, AP), le falta elementos (delirio polimorfo, alteración de conciencia más profunda, de tipo oniroide). . Confusión mental: tiene cosas en común (desestructuración de conciencia). En contra: menor profundidad de la desestructuración, delirio onírico en la confusión, falta de perplejidad, conservación de la orientación temporoespacial. No pensamos que este cuadro sea icon:paperclip[], por los AF, los AP de episodios maníacos y melancólicos y por el abandono de medicación determinando cuadros similares. Por la paraclínica descartaremos algunas de estas causas. ====== Del trastorno .Con psicosis crónicas En el joven se pueden ver debut clínico de Esquizofrenia o de un Trastorno Esquizoafectivo con un episodio maníaco. A factor: deterioro en el curso evolutivo, el hipopragmatismo o el corte existencial, el delirio incongruente con el estado de ánimo. En contra: prima la alteración del humor por sobre la del pensamiento, no elementos del Síndrome Disociativo-Discordante, por los AF y los AP. .Demencias En el paciente añoso se puede ver el debut clínico de un cuadro Demencial, alejándonos los AF y AP, la ausencia de causa orgánica y la falta de un deterioro global cognitivo. .Trastorno de la personalidad Tanto DD como comorbilidad. ===== Diagnóstico etiopatogénico y psicopatológico Destacar elementos del cuadro clínico del paciente en particular, agregando observaciones teóricas SOBRE el cuadro clínico. ====== Diagnóstico etiopatogénico Se plantea una causa multifactorial. Existen múltiples niveles complementarios e integrativos de comprensión e intento de explicación de esta enfermedad. La vía final es la interacción estrés-diátesis. .Comprensión biológica . Genética: hay una carga genética predisponente, dada la frecuencia de AF de trastornos afectivos, alcoholismo, IAE, comprobándose asociaciones con algunos cromosomas específicos. Pero la concordancia entre gemelos no es del 100%, por lo cual no es un factor determinante. . Constitucional: desde las descripciones clásicas se plantea la asociación con el biotipo pícnico (Kretschmer), lo cual se ve reforzado por la constatación de una mayor prevalencia de alteraciones metabólicas. . Hipótesis catecolaminérgica: involucra los neurotransmisores dopamina y noradrenalina, planteada en 1965 por Bunney y Davis. . Hipótesis serotinérgica: planteada por Coppen y Lappin en 1969. Cambios primarios en los sistemas monoaminérgicos y cambios en la modulación realizada por el sistema serotoninérgico. Existiría una disregulación en estas vías. . Existiría una alteración de la carga alostérica al estrés, es decir la capacidad de conservar la estabilidad. Sería una enfermedad de la respuesta, del retorno a la normalidad. . Se postula la existencia de un fenómeno de kindling límbico-amigdalino-prefrontal: en los sucesivos episodios, el desencadenante exógeno es menor y finalmente el fenómeno adquiere autonomía de las causas externas. . Se detectan también cambios neuroendócrinos en: CRH, RCRH, VSP, ACTH, cortisol. Una causa frecuente de descompensación es el abandono de medicación. .Comprensión psicológica Puede encontrarse dificultad para superar pérdidas y para adaptarse a situaciones nuevas. Sobre un terreno de vulnerabilidad actúan factores psicosociales: pérdidas, dificultades interpersonales. Hay etapas vitales con mayor riesgo de síntomas afectivos: adolescencia, embarazo, puerperio, climaterio, menopausia, envejecimineto, duelo. .Comprensión social Estresores sociales como factor exterior sobre la vulnerabilidad de base. Pérdida de roles laborales, pérdida de posición social. ====== Diagnóstico psicopatológico Para Binswanger se trata de una modalidad regresiva global con modificación de la estructura temporal de la vida psíquica, con desencadenamiento de los impulsos. Para la Teoría Organodinámica de Ey de la desestructuración de conciencia (el Ser Consciente), el maníaco presenta una desestructuración del orden del cuerpo mental en su nivel ético-temporal (de 1° grado). Etico por la incapacidad de postergar la realización de los deseos y temporal por la estrechez del presente en un punto virtual siempre renovado y sin trascendencia, con distensión, laxitud, relajamiento de la continuidad histórica del individuo. Determina una pérdida de la capacidad de adaptación a las exigencias del aquí y ahora. Comporta un aspecto negativo (regresivo o deficitario) y aspecto positivo, de liberación de instancias inferiores. Para los psicoanalistas se trata de una regresión a las etapas infantiles del desarrollo psicosexual, anteriores a toda frustración exterior. Las pulsiones se liberan, especialmente las pregenitales. En este sentido, sería lo contrario del melancólico, pues el maníaco se precipita a la satisfacción inmediata de las pulsiones como una forma de escapar de la angustia. Sus mecanismos de defensa son la negación de la pérdida de objeto (mal manejo de una pérdida) y la omnipotencia ante la melancolía (en todo maníaco hay un fondo nuclear melancólico). ===== Paraclínica El diagnóstico es clínico. La paraclínica está destinada a realizar una valoración general del paciente, descartar diagnósticos diferenciales y con miras a los diferentes recursos terapéuticos de los que disponemos. Lo solicitaremos desde un punto de vista integral: biológico, psicológico y social. Solicitaremos la historia clínica previa o su resumen para objetivar los antecedentes clínicos y de recursos terapéuticos. En caso que sea necesario se pedirá información al juez o a la policía. ====== Biológico .Valoración general Realizaremos una anamnesis médica general al paciente y terceros. Un examen físico completo con énfasis en el aspecto neurológico (con el paciente sedado, si corresponde), buscando elementos de organicidad que nos pongan en la pista de una patología reversible determinante de la expresión clínica actual. En particular buscaremos elementos de hipertensión endocraneana (fondo de ojo), estigmas de UISP, focos infecciosos. Solicitaremos exámenes de valoración general: . Metabólica: glicemia, perfil lipídico (para establecer línea de base ante el eventual uso de fármacos con repercusión metabólica). . Hematológica: hemograma . Renal: función renal . Infecciosa: HIV, VDRL y si la situación clínica lo determina: HVB, HVC . Hepática: funcional y enzimograma hepático . Tóxica: screening de sustancias psicoactivas en orina Si es pertinente: test de embarazo. Si es clínicamente necesario: TAC, consulta con neurólogo, enzimograma cardíaco (cocaína). Se solicitarán consultas con especialistas según hallazgos. .Con miras a posibles tratamientos Litio: examen de orina, función renal (contraindicado en insuficiencia renal), función tiroidea (por comorbilidad, por factor causal y como línea de base por efecto secundario del litio), test de embarazo (el litio es teratogénico), ionograma (hiponatremia aumenta probabilidades de intoxicación por litio), hemograma (litio da leucocitosis), ECG (por efectos sobre la conducción cardíaca). Descartar estados que lleven a balance negativo de Na (dieta hiposódica, diuréticos) ya que en su eliminación, el LI se intercambia por Na a nivel renal y un déficit de este ion puede llevar a un aumento de la litemia con el consiguiente riesgo de intoxicación. ECT: ECG y consulta con cardiólogo para descartar IAM reciente o arritmias ventriculares graves que contraindicarían su realización). Rx Tx (para descartar aneurisma de aorta). Fondo de ojo/TAC: para descartar hipertensión endocraneana. En algunos casos puede plantearse la realización de EEG. En pacientes añosos y según el caso clínico puede solicitarse una evaluación del estado cognitivo basal. TIP: Contraindicaciones de ECT: IAM reciente, arritmias inestables, aneurisma de aorta, PEIC con HTEC. Carbamazepina: hemograma (por ser depresor de la médula ósea, contraindicado en caso de citopenia), funcional y enzimograma hepático (por determinar movilización enzimática y potencial toxicidad hepática). Acido valproico: funcional y enzimograma hepático, hemograma. ====== Psicológico Será diferido hasta superada la agudeza del cuadro actual, salvo la existencia de dudas diagnósticas. Realizaremos entrevistas para evaluar las características propias del paciente y sus capacidades para en un futuro integrarse a grupos de psicoterapia. Realizaremos tests de personalidad proyectivos (Rorscharch y TAT) y no proyectivos (Minessota), que nos informarán sobre los mecanismos de defensa, integridad yoica, manejo de la agresividad y rasgos de personalidad. Realizaremos test de nivel, si hay dudas. La realización de tests no es imprescindible y no retrasará el inicio del tratamiento. ====== Social Realizaremos entrevistas con familiares a los efectos de valorar: red de soporte y vínculos, características de los tratamientos previos y sus resultados, funcionamiento premórbido e intercrítico, antededentes de corte existencial, inventario de eventos vitales, valorar medio socio-económico-cultural. Informaremos a la familia sobre los diagnósticos positivos y diferenciales, las dudas, los tratamientos disponibles, sus riesgos y beneficios y nuestra opinión sobre lo mejor para este paciente en este momento. La información será transmitida siempre con un objetivo de psicoeducación. Pediremos consentimiento informado por la posibilidad de ECT. ===== Tratamiento El tratamiento será dinámico, adaptado constantemente a la evolución clínica y a la aparición de complicaciones, integrado por recursos farmacológicos, psicológicos y sociales. . Objetivos inmediatos: remitir rápidamente el cuadro actual, descartar causa orgánica, prevenir complicaciones. . Objetivos mediatos: compensar la enfermedad de fondo, prevenir futuras recaídas, prolongar los períodos de remisión, reinsertar al paciente en su mejor nivel de funcionamiento. Lo internaremos en sala de patología aguda de hospital psiquiátrico por: gran exaltación, presencia de un delirio, agresividad, ansiedad, riesgo suicida, alteración de las conductas basales, carencia de continencia familiar. Lo ideal es internarlo en sala individual, en un entorno con poca estimulación, sin elementos de riesgo (ventanas, espejos), con asistencia de enfermería especializada las 24 horas y acompañante continentador a permanencia. Límites claros y firmes. Evitar interacciones provocativas. La internación será en sala de hospital general si reconocemos una causa determinante orgánica tratable y reversible que necesite de medios asistenciales más complejos. Será dentro de lo posible con su consentimiento, pero debemos hacerla aún de forma compulsiva, evaluando riesgo/beneficio. La internación es una medida de protección del paciente y de terceros. De esta forma lograremos: continentar al paciente calmando su sufrimiento psíquico, tratar su excitación / ansiedad / delirio, acortar la duración de la crisis actual, mejorando el pronóstico; ajustar la medicación; proteger al paciente y terceros de las posibles complicaciones medicolegales, vigilar fugas e IAEs, descartar causa orgánica. Se llevará adelante por un equipo interdisciplinario. Indicaremos controles de enfermería especializada. Permitiremos visitas de figuras continentadoras. Realizaremos adecuado aporte nutricional. Se verificará la toma de medicación. ====== Farmacológico .Tratamiento del episodio Tratamiento de la fase aguda, busca la remisión de síntomas específicos. Depende de la situación clínica: 1. Manía típica (eufórica) sin síntomas psicóticos: Litio (o Divalproato) icon:arrow-right[] + benzodiacepina icon:arrow-right[] + Antipsicótico atípico icon:arrow-right[] DVP + Litio icon:arrow-right[] Cambiar de antipsicótico icon:arrow-right[] DVP + Li + CBZ icon:arrow-right[] ECT 2. Manía mixta (disfórica): Divalproato icon:arrow-right[] mismo esquema que manía típica. 3. Hipomanía: mismo esquema que manía eufórica (con menos énfasis en el uso de antipsicóticos). 4. Manía con síntomas psicóticos: Divalproato (o Litio) + AAP (o CAP) icon:arrow-right[] cambiar AAP o + BZD icon:arrow-right[] DVP + LI icon:arrow-right[] cambiar AAP o AAP + CAP icon:arrow-right[] ECT icon:arrow-right[] DVP + LI + CBZ (o agregar Clozapina) 5. Manía en paciente con ciclado rápido: DVP icon:arrow-right[] DVP + (LI o CBZ) icon:arrow-right[] + AAP icon:arrow-right[] DVP + LI + CBZ icon:arrow-right[] Clozapina icon:arrow-right[] Lamotrigina icon:arrow-right[] Gabapentina icon:arrow-right[] ECT 6. Depresión en bipolar (no psicótica - no ciclos rápidos) sin medicación previa moderado: Li icon:arrow-right[] +AD 7. Depresión en bipolar (no psicótica - no ciclos rápidos) sin medicación previa severo: LI (o DVP) + AD icon:arrow-right[] LI + DVP. 8. Si estaba con estabilizador: maximizar estabilizador como primer paso icon:arrow-right[] Li + DVP icon:arrow-right[] + AD o Lamotrigina icon:arrow-right[] + AD si no tenía (o cambiarlo). 9. Si hay refractariedad en la depresión: ECT icon:arrow-right[] T3 icon:arrow-right[] Otros estabilizadores icon:arrow-right[] Clozapina o estimulante o fototerapia. 10. Episodio depresivo psicótico: igual pauta, con más énfasis en antipsicóticos atípicos (ECT a cualquier altura del algoritmo). 11. Depresión en paciente con ciclado rápido: DVP icon:arrow-right[] + (Li o CBZ o Lamotrigina) icon:arrow-right[] + AD icon:arrow-right[] cambio de AD icon:arrow-right[] T3/T4 o AAP icon:arrow-right[] Gabapentina o Clozapina o Fototerapia -> ECT. TIP: Regla general: LIT en manía típica, DVL en el resto (por se de más fácil manejo). icon:notes-medical[] Ansiedad y angustia Inicialmente usaremos benzodiacepinas, como el Lorazepam (del cual contamos con presentación parenteral de ser necesario). Iniciamos con dosis de 2 a 4 mg i/m o v/o según la clínica, cada 6-8 horas. Una alternativa es el uso de Clonazepam a dosis de 2 a 4 mg c/8-12 horas, pudiendo llegar a 12 mg/día (con efecto sobre la disforia y la impulsividad). Ambos fármacos actúan sobre receptores GABA. icon:notes-medical[] Excitación psicomotriz De nos ser suficiente con la benzodiacepina, utlizaremos antipsicóticos sedativos, sustityéndola o como complemento. Indicaremos Levomepromazina 25 mg i/m c/8 horas con un posible refuerzo de dosis nocturno (50 mg H 20) evaluando el pasaje a v/o, atentos a los efectos anticolinérgicos e hipotensión postural. icon:notes-medical[] Delirio Escenario 1: vía IM. Indicaremos neurolépticos incisivos antidelirantes del grupo de las butirofenonas, como el Haloperidol, que actúa bloqueando los receptores dopaminérgicos D2 córtico-mesolímbicos, comenzando con dosis de 5 mg i/m horas 8 y 20 a fin de lograr la seguridad en la toma de medicación y niveles terapéuticos adecuados en los sitios de acción. Destacamos además el efecto antimaníaco de esta medicación además de la acción sobre la excitación y los síntomas psicóticos. La dosis y la vía se ajustarán según respuesta clínica. El Haloperidol puede elevarse a dosis de 15-20 mg/día si la evaluación clínica lo indica. Pasaremos la totalidad de la dosis a la noche, en lo posible. Estaremos atentos a la aparición de efectos secundarios de los neurolépticos. En caso de un paciente de riesgo (varón, menor de 35 años, AF de Enfermedad de Parkinson), indicaremos Biperideno de forma preventiva a dosis de 2 mg H 8 y H14 por v/o por vía i/m. Las formas de liberación prolongada se pueden dar solamente en la mañana. De aparecer distonía aguda, acatisia, síntomas extrapiramidales (rigidez, rueda dentada, bradiquinesia, temblor) comenzaremos con Biperideno, evaluando la posibilidad de disminuir las dosis del antispsicótico (y/o concentrar la dosis en la noche) y discontinuándolo en un plazo de 3 meses si la evolución lo permite. Mantendremos el Haloperidol i/m de 3 a 5 días y pasaremos luego a v/o según disminuya la exaltación y el delirio. Debemos retirarlo completamente lo antes posible por riesgo de viraje hacia la depresión, con aumento de frecuencia de crisis y reducción de períodos intercríticos. Debemos considerar además que los paciente con trastornos afectivos tienen también mayor riesgo de presentar disquinesias tardías. Escenario 2: VO Consideramos de elección el uso de antipsicóticos atípicos por la menor incidencia de efectos secundarios. Solo en caso de que se requiera medicación intramuscular, usaremos Haloperidol i/m que pasaremos luego a vía oral. Olanzapina (primera línea, con o sin síntomas psicóticos): iniciando con 5 mg/día en toma única, aumentando a 10 si hay buena tolerancia, pudiendo aumentar hasta 20 mg/día. Propiedades como antipsicótico y como estabilizador del humor. Risperidona: comenzamos con 2 mg/día v/o en 2 tomas, aumentando hasta 4.5 mg/día en 2 tomas. Luego 1 semana puede administrarse en una única toma nocturna. Máximo: 6 mg/día (dosis más altas aumentan el riesgo de efectos secundarios). icon:notes-medical[] Insomnio De persistir el insomnio a pesar de los ansiolíticos, indicaremos Midazolam i/m, o si la situación lo permite, Flunitrazepam 2 mg v/o a la noche. La restauración de un ciclo sueño-vigilia normal es fundamental para la recuperación clínica. icon:bolt[] ECT Si en 10-15 días no obtenemos mejoría (disminución de exaltación, disminución de entrega a la experiencia maníaca) evaluaremos las posibles causas y consideraremos el aumento de la dosis de los fármacos y evaluaremos la realización de ECT, para lo cual solicitaremos consentimiento informado a familiar. La ECT se considera de primera línea en caso de afectación severa de conductas basales (rechazo de alimentos), repercusión general, mal estado general y cuando los fármacos están contraindicados por algún motivo. El mecanismo de acción de la ECT es desconocido. Indicaremos una serie inicial de 8 a 10 sesiones, una día por medio, realizadas con asistencia de anestesista, psiquiatra y enfermería especializada, bajo monitoreo ECG y EEG. Descartaremos previamente elementos que la contraindiquen, como se especificó en el apartado Paraclínica. Puede ser necesario la suspensión de benzodiacepinas en las horas previas dado que éstas aumentan el umbral convulsivo (se puede sustituir por Levomepromazina). La dosis de litio de la mañana se postergará por mayor riesgo de confusión mental y amnesia post ECT. .Tratamiento de la enfermedad de fondo El tratamiento de la fase aguda será seguido de un tratamiento de continuación (4-12 meses) donde se busca mantener el control del episodio actual y se comienza la fase de prevenir o atenuar futuros episodios. icon:pills[] Litio De primera elección en manías típicas (sin estados mixtos, sin ciclado rápido, sin abuso de sustancias). Indicaremos desde el inicio del tratamiento. Pese a su latencia de 8-10 días proporciona un efecto antimaníaco más específico, además de ser estabilizador del humor y profiláctico de recidivas. Comenzaremos con 300 mg v/o c/8 horas, con las comidas, probando tolerancia, ya que al inicio son frecuentes los trastornos digestivos leves que, al igual que la sintomatología neurológica inespecífica (letargia, fatiga, debilidad muscular y temblor fino distal), polidpsia y poliuria, son todos fenómenos reversibles y transitorios. Indicaremos abundantes líquidos v/o. Estaremos atentos a la aparición de estos síntomas. Controlaremos la aparición de signos incipientes de toxicidad: ataxia, temblor grueso, disartria, fasciculaciones. WARNING: Atentos a los signos de intoxicación por litio (ATeGDiF): ataxia, temblor grueso, disartria, fasciculaciones Si el paciente es añoso, o con problemas renales, o sensible a efectos secundarios: comenzar con 150 mg v/o c/8. Probablemente lleguemos a un rango de dosis de 900 a 1800 mg). La posología en 1 o 2 tomas diarias no modifica la eficacia y puede minimizar algunos efectos adversos, además de favorecer el cumplimiento con el tratamiento. A los 5-7 días (tiempo en que se tarda en llegar al estado de meseta) realizaremos la primera litemia (12 horas luego de la última toma, por la variación pico-valle) y según ella iremos ajustando la dosis hasta llegar al rango terapéutico establecido de 0.8-1.2 mEq/l (según el paciente aprox 900-1800 mg/día). La litemia se repetirá semanalmente el primer mes y luego mensual durante el primer semestre. La dosis se ajustará según concentraciones séricas y cuadro clínico. El nivel plasmático depende de muchos factores, entre ellos: masa corporal, filtrado glomerular e idiosincrasia farmacológica individual. Para la crisis de manía se postula un rango terapéutico de 1.0 a 1.2 mEq/l y para la profilaxis 0.8 a 1.0 mEq/l. El litio no actúa en el espacio sináptico sino intracelularmente, en los sistemas de proteína G y segundos mensajeros. Por eso la latencia de hasta 3 semanas para el inicio de los efectos terapéuticos. Las litemias se realizarán cada 3 meses o más seguido si hay efectos tóxicos o incumplimiento del tratamiento. Se realizará una función renal evaluando creatininemia cada 6 meses y ante cambios de dosis, de respuesta terapéutica o ante sospecha de falla renal. Se realizará ECG cuando sea necesario, pero solo una arritmia grave determina la suspensión del Litio. Se realizará TSH cada 6 mees si hay clínica de disfunción tiroidea. En paciente con ciclado rápido, se postula que el litio tiene menor eficacia, presentando mejor respuesta a Acido Valproico o Carbamazepina. La disfunción tiroidea puede ser un factor predisponente para el ciclado rápido WARNING: Poner predictores de buena respuesta al litio (ej. AF afectivos). icon:pills[] Acido Valproico Actúa sobre la neurotransmisión GABA. Se plantea una dosis inicial de 250 mg c/12 horas (probando tolerancia, sobre todo por efecto gastrointestinales), que se aumentará hasta dosis máxima de 20 mg/kg/día (en 2 o 3 tomas) o concentraciones plasmáticas de 50 a 125 mcg/ml. Se logra una meseta plasmática al cabo de 2 semanas. El efecto puede tener una latencia de 3 semanas. Precaución en pacientes con AP de disfunción hepática. No dar en embarazo o lactancia. Alta unión a proteínas. Ajustar dosis en insuficiencia renal y hepática, en ancianos, coagulopatías, dislipemias severas, desnutrición. Aumenta los niveles de AAS, fenitoina, carbamazepina, warfarina, diazepam, lorazepam, amitriptilina. Efectos secundarios: intolerancia digestiva, sedación, astenia, rash cutáneo, leucopenia y plaquetopenia benignas, alopecia, temblor. Puede haber como efecto idiosincrático: insuficiencia hepática y agranulocitosis. Es más eficaz en los episodios mixtos que en la manía clásica. TIP: Las presentaciones de divalproato de sodio tienen mejor tolerancia gástrica. Tienen una cobertura entérica por lo que no es recomendable partir el comprimido. Precaución: trombocitopenia, insuficiencia hepática. Realizaremos la valoración paraclínica descrita previo a su uso. icon:pills[] Carbamazepina Generalmente como coadyuvante de otro estabilizador del humor. Dosis iniciales de 200 mg v/o c/12 horas que se aumentará hasta 1200-1400 mg/día. con control de función hepática y hematológica. Se plantea lograr una concentración terapéutica de 4-12 mcg/ml de plasma. TIP: Predictores de respuesta a antivonvulsivantes: ciclado rápido, episodio mixto, pobre respuesta a litio, manía secundaria, comorbilidad con abuso de sustancias. ====== Psicológico Haremos entrevistas diarias con el paciente, con el objetivo de: crear un vínculo terapéutico cálido y continentador, evaluar la evolución y las oscilaciones diarias, investigar y reforzar los aspectos sanos, evaluar el factor desencadenante si lo hubiera, evaluar factores de vulnerabilidad para próximos episodios, darle referencias de realidad sin confrontarlo. Se fomentará la alianza terapéutica. A mediano plazo, la terapia de grupo puede ser útil para abordar el incumplimiento con el tratamiento, la adaptación a una enfermedad crónica, la regulación de la autoestima y los problemas conyugales / sociales que puede acarrear la enfermedad. ====== Social Entrevistas reiteradas con familiares con fines de psicoeducación sobre el diagnóstico y tratamiento instituido, los pronósticos y su relación con la adherencia al tratamiento, la importancia de los controles y afianzar el vínculo como aliado terapéutico. Evaluaremos el impacto de la patología en la autoestima del paciente. Facilitaremos el acceso a biblioterapia. Contactaremos a la familiar con grupos de psicoeducación de familiares de pacientes bipolares (en especial grupos que sigan el modelo propuesto por Colom y Vieta). El familiar es un aliado en la evitación del abandono del tratamiento y en la detección de signos precoces de descompensación, que llevan a la consulta precoz. Se evaluarán las condiciones laborales evitando turnos rotativos, favoreciendo la estabilidad en el ciclo sueño-vigilia. Mujer en edad genital activa: derivar a planificación familiar (potencial teratogénico de algunos fármacos, aumento de posibilidades de descompensaciones vinculadas a ciclos reproductivos). ====== Alta hospitalaria Dependerá de la respuesta al tratamiento. Se dará al haber: remisión de sintomatología psicótica, aparición de crítica, normalización de las conductas basales y el autocuidado, adquisición de conceptos básicos de psicoeducación, compromiso con el paciente y la familia en el control evolutivo en policlínica. Se retirarán, en la medida de lo posible los fármacos que no sean necesarios. A largo plazo lo ideal es la monoterapia con estabilizadores del humor. Sabemos que esto no siempre es posible que en general se recurre a una combinación de fármacos a las mismas dosis con las que se obtuvo la mejoría (ver esquema previo con secuencia de uso de fármacos de 1a, 2a y 3a linea). Es fundamental el seguimiento para el control evolutivo, el cumplimiento con el tratamiento, la dosificación de fármacos en sangre (si corresponde). WARNING: Poner control de fármacos según CANMAT ===== Evolución y pronóstico ====== Evolución Estamos ante una enfermedad crónica de manifestación episódica, estando el pronóstico supeditado al subtipo clínico, la respuesta y adhesión al tratamiento, el funcionamiento psicosocial y la presencia de estresores. Sin tratamiento evoluciona hacia el aumento de la frecuencia de las crisis, con períodos libres de síntomas más cortos, con crisis más intensas y prolongadas y con refractariedad a la terapéutica profiláctica. Espontáneamente una crisis de manía remite al cabo de 3 a 6 meses y una de melancolía al cabo de 8 a 12 meses. Con tratamiento adecuado y adherencia al mismo, se logra en un alto porcentaje de pacientes la remisión de las crisis, prolongación de períodos intercríticos, disminución de la frecuencia de las crisis, las crisis que ocurren son de menor duración y de menor intensidad, con menor necesidad de internaciones y de medicación, con menor repercusión psicológica individual, de pareja y familiar, menor compromiso laboral y en los estudios. ====== Pronóstico Pronóstico psiquiátrico inmediato: bueno con el tratamiento instituido. Pronóstico vital inmediato: supeditado a la exclusión de patologías orgánicos, al riesgo de IAE, autolesiones, conductas de riesgo y heteroagresividad. Pronóstico psiquiátrico alejado: sujeto a la adhesión al tratamiento. Pronóstico vital alejado: sujeto a descompensaciones con conductas de riesgo; agresividad UISP, alcoholismo, sexualidad (HIV, VDRL, HVB, HVC). Comorbilidad médica (insuficiencia renal, enfermedades cardíacas). Se considera refractario a un tratamiento si no ha habido respuesta significativa luego de 12 semanas de niveles terapéuticos en sangre. A mayor edad, tienden a disminuir los períodos intercríticos, con mayor frecuencia y duración de las crisis (kindling). De tratarse de una mujer en edad genital activa: control de natalidad y anticoncepción con ginecólogo. Suicidio: en el trastorno bipolar bipolar hay 30 veces más riesgo que en la población generl. Se registra un 15 % de suicidio consumado. Elementos de mal pronóstico * Presencia de comorbilidad (deterioro cognitivo, consumo de sustancias) * Alta frecuencia de episodios * Estresores ambientales / psicosociales ===== En suma Hemos visto un paciente de sexo X, de X años de edad, con un MSEC X, con AF de X, con AP de X, que consulta por X síntomas, en quien diagnosticamos un Trastorno Bipolar de tipo I / II, de características X. con un episodio actualX, con características X, en comorbilidad con X. Hemos planteado diagnósticos diferenciales con X, hemos estudiado con X, y hemos tratado con X. Planteamos una evolución buena con el tratamiento indicado, dependiendo el pronóstico a largo plazo de la adherencia al tratamiento. ",12204,False,2176.0088200185546,median "--- title: Бүлэг 18. Аюулгүй байдлын үйл явцад аудит хийх нь part: хэсэг III. Системийн Удирдлага prev: books/handbook/mac next: books/handbook/disks --- [[audit]] = Аюулгүй байдлын үйл явцад аудит хийх нь :doctype: book :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :sectnumoffset: 18 :partnums: :source-highlighter: rouge :experimental: :images-path: books/handbook/audit/ ifdef::env-beastie[] ifdef::backend-html5[] :imagesdir: ../../../../images/{images-path} endif::[] ifndef::book[] include::shared/authors.adoc[] include::shared/mirrors.adoc[] include::shared/releases.adoc[] include::shared/attributes/attributes-{{% lang %}}.adoc[] include::shared/{{% lang %}}/teams.adoc[] include::shared/{{% lang %}}/mailing-lists.adoc[] include::shared/{{% lang %}}/urls.adoc[] toc::[] endif::[] ifdef::backend-pdf,backend-epub3[] include::../../../../../shared/asciidoctor.adoc[] endif::[] endif::[] ifndef::env-beastie[] toc::[] include::../../../../../shared/asciidoctor.adoc[] endif::[] [[audit-synopsis]] == Ерөнхий агуулга FreeBSD үйлдлийн системд нягт-боловсруулсан, аюулгүй байдлын үйл явцад аудит хийх дэмжлэг орсон байгаа. Үйл явцад аудит хийх нь нэвтрэн оролтууд, тохиргооны өөрчлөлтүүд, болон файл болон сүлжээний хандалт зэрэг төрөл бүрийн аюулгүй байдлын холбогдолтой системийн үйл явцуудын хянаж бүртгэсэн бичлэгийг найдвартай, нягт-боловсруулсан, ба тохируулах боломжтойгоор хийх боломжийг бүрдүүлдэг. Эдгээр хянаж бүртгэсэн бичлэгүүд нь системийг шууд хянах, халдлага илрүүлэх, болон халдлагын дараах анализ хийхэд үнэлж баршгүй байж болох юм. FreeBSD Sun(TM)-ий гаргасан BSM API болон файлын хэлбэрийг шийдлээ болгосон бөгөөд Sun(TM)-ий Solaris болон Apple(R)-ийн Mac OS(R) X-ийн аудит шийдлүүдтэй харилцан ажиллах боломжтой. Энэ бүлэг нь үйл явцыг аудит хийхийг тохируулах болон суулгах тал дээр анхаарна. Энд аудитийн бодлогуудын талаар тайлбарлах бөгөөд аудитийн тохиргооны жишээг бас харж болно. Энэ бүлгийг уншсаны дараа, та дараах зүйлсийг мэдэх болно: * Үйл явцыг аудит хийх гэж юу вэ болон яаж ажилладаг талаар. * Хэрэглэгчид болон процессуудын үйл явцыг аудит хийхийг FreeBSD дээр яаж тохируулах талаар. * Аудитийн мөрийг аудит багасгах болон хянах хэрэгслүүдээр хэрхэн шалгах талаар. Энэ бүлгийг уншихаасаа өмнө, та дараах зүйлсийг мэдэх шаардлагатай: * UNIX(R) болон FreeBSD-ийн үндсийг ойлгох (crossref:basics[basics,Юниксийн үндэс]). * Цөмийг тохируулах/хөрвүүлэх үндэстэй танилцах (crossref:kernelconfig[kernelconfig,FreeBSD цөмийг тохируулах нь]). * Аюулгүй байдлын талаар болон түүний FreeBSD -тэй хэрхэн холбогддог талаар ойлголттой байх (crossref:security[security,Аюулгүй байдал]). [WARNING] ==== Аудит хэрэгсэл нь зарим нэг хязгаарлагдмал боломжуудтай бөгөөд тэдгээрээс дурдвал бүх аюулгүй байдлын холбогдолтой системийн үйл явцуудыг аудит хийх боломжгүй, X11 дээр үндэслэгдсэн дэлгэцийн менежерүүд болон гуравдагч дэмонууд зэрэг зарим нэвтрэх механизмууд хэрэглэгчийн нэвтрэх сессийг аудит хийх тохиргоог буруу хийдэг зэрэг болно. Аюулгүй байдлын үйл явцыг аудит хийх хэрэгсэл нь системийн ажиллагааны маш дэлгэрэнгүй бичлэгүүдийг үүсгэх чадвартай: нарийвчилсан тохиргоо хийгдсэн завгүй системд мөр бичлэгийн файлын өгөгдөл тохиргооноос хамааран зарим тохиолдолд гигабайтаас ч илүү асар их болох боломжтой. Администраторууд их хэмжээний аудит хийх тохиргоотой холбоотой дискний хэмжээний шаардлагыг тооцох ёстой. Жишээ нь, аудит бичиж байгаа файлын систем дүүрэх нөхцөлд өөр бусад файлын системүүдэд хамааралгүйгээр файлын системийг [.filename]#/var/audit# модонд зориулах нь магадгүй зохимжтой байж болох юм. ==== [[audit-inline-glossary]] == Энэ бүлгийн түлхүүр ухагдахуунууд Энэ бүлгийг уншихаас өмнө аудиттай холбоотой цөөн түлхүүр ухагдахуунуудыг тайлбарлах шаардлагатай: * _үйл явц_: Аудит хийх боломжтой үйл явц гэдэг нь аудит дэд системийн тусламжтайгаар хянаж бүртгэх боломжтой дурын үйл явцыг хэлнэ. Аюулгүй байдалтай холбоотой үйл явцуудын жишээнүүдэд файлын үүсгэлт, сүлжээний холболтыг босгох, эсвэл хэрэглэгчийн нэвтрэлтийг дурдаж болно. Үйл явцууд нь нэг бол жинхэнэ хэрэглэгч хүртэл мөрдөн гаргаж болох ""шинж чанарлаг"", эсвэл тэгж болохооргүй ""шинж чанарлаг бус "" байна. ""Шинж чанарлаг бус"" үйл явцуудын жишээнүүд гэвэл нууц үгийн буруу оролдлогууд гэх мэт нэвтрэн орох процессийн жинхэнэ эсэхийг шалгахаас өмнөх үеийн дурын үйл явцуудыг хэлж болно. * _ангилал_: Үйл явцын ангиллууд гэдэг нь холбоотой үйл явцууд бүхий хэсэг бүлгүүдийн нэр бөгөөд эдгээр нь сонголтын илэрхийллүүдэд хэрэглэгддэг. Энгийн ашиглагддаг үйл явцуудын ангиллуудад ""файл үүсгэлт"" (fc), ""ажиллуулах"" (ex) мөн ""нэвтрэх_гарах"" (lo) зэрэг орно. * _бичлэг_: Бичлэг гэдэг нь аюулгүй байдлын үйл явцыг тайлбарласан аудитийн хянан бүртгэсэн оруулга юм. Бичлэгүүд нь үйл явцын төрлийн бичлэг, субьектийн (хэрэглэгч) үйлдэл хийж байгаа тухай мэдээлэл, огноо болон цагийн мэдээлэл, дурын нэмэлт өгөгдлүүд болон обьектуудын мэдээлэл, амжилт эсвэл уналтын нөхцөлүүдийг агуулдаг. * _мөр_: Аудитийн мөр буюу хянан бүртгэлийн файл нь аюулгүй байдлын үйл явцуудыг тайлбарласан аудит бичлэгүүдийн сериэс тогтоно. Ерөнхийдөө мөрүүд нь үйл явцуудын биелж дууссан цагийн дагуу он цагийн дарааллаар байрладаг. Зөвхөн жинхэнэ процессууд аудитийн мөрд бичлэг нэмэх эрхтэй байдаг. * _сонголтын илэрхийлэл_: Сонголтын илэрхийлэл нь угтваруудын жагсаалт болон үйл явцтай тохирох аудитийн үйл явцын ангиллын нэрсээс тогтох мөр юм. * _урьдчилсан сонголт_: Энэ нь администраторын сонирхох боломж бүхий үйл явцууд, сонирхлыг татахгүй байгаа үйл явц зэргийг тайлбарласан аудитийн бичлэгүүдийг үүсгэхээс зайлсхийх зорилготойгоор ялгасан системийн процесс юм. Урьдчилсан тохиргоо нь аль хэрэглэгчийн хувьд үйл явцуудын аль ангиллуудыг таних болон жинхэнэ болон жинхэнэ биш процессуудад хамаарах глобал тохиргоонуудын сонголтын илэрхийллүүдийн серийг ашигладаг. * _хураангуйлалт_: Энэ нь байгаа аудитийн мөрнүүдээс аль бичлэгүүдийг хадгалалт, хэвлэлт болон анализ хийхээр сонгосон процесс юм. Үүний нэгэн адил аудит мөрөөс хэрэггүй аудит бичлэгүүдийг устгах процесс бас хамаарна. Хураангуйлалтыг ашиглаад администраторууд аудит өгөгдлийн хадгалалтын бодлогуудыг боловсруулах боломжтой юм. Жишээ нь, дэлгэрэнгүй аудитийн мөрнүүд нэг сарын хугацаанд хадгалагдаад дараагаар нь тэдгээр мөрнүүдийг архивын зорилгоор зөвхөн нэвтрэлтийн мэдээллийг үлдээн багасгаж болох юм. [[audit-install]] == Аудит хийх дэмжлэг суулгах нь Үйл явцыг Аудит хийх хэрэглэгчийн талбарын дэмжлэг үндсэн FreeBSD үйлдлийн системд орсон байгаа. Үйл явцыг Аудит хийх дэмжлэг анхдагчаар эмхэтгэгдэн орсон боловч яг энэ боломжийг дэмжихийн тулд дараах мөрийг цөмд оруулан хөрвүүлсэн байх шаардлагатай: [.programlisting] .... options AUDIT .... crossref:kernelconfig[kernelconfig,FreeBSD цөмийг тохируулах нь] -д тайлбарласан ердийн процессийн дагуу цөмийг дахин хөрвүүлж суулгана. Аудит идэвхжсэн цөм бүтээгдэж суулгагдаад систем дахин ачаалсны дараа дараах мөрийг man:rc.conf[5] -д нэмж аудит дэмонг идэвхжүүлнэ: [.programlisting] .... auditd_enable=""YES"" .... Тэгээд системийг дахин ачаалах замаар эсвэл гараар аудит дэмонг ажиллуулах замаар аудит дэмжлэгийг эхлүүлэх ёстой: [.programlisting] .... service auditd start .... [[audit-config]] == Аудитийн тохиргоо Аюулгүй байдлын аудитийн тохиргооны бүх файлуудыг [.filename]#/etc/security# дотроос олж болно. Дараах файлууд аудит дэмон эхлэхээс өмнө байх ёстой: * [.filename]#audit_class# - Аудитийн ангиллуудын тодорхойлолтуудыг агуулна. * [.filename]#audit_control# - Анхдагч аудитийн ангиллууд, аудитийн хянан бүртгэлтийн эзлэхүүнд үлдээх хамгийн бага дискний зай, хамгийн их аудитийн мөрийн хэмжээ гэх зэрэг аудит дэд системийн шинж чанарыг хянана. * [.filename]#audit_event# - Системийн аудит үйл явцуудын тайлбарууд, нэрс болон үйл явц болгон аль ангилалд хамаарах жагсаалт. * [.filename]#audit_user# - Нэвтрэн орох үеийн глобал анхдагчуудаас бүрдсэн зөвхөн хэрэглэгчид хамааралтай аудитийн шаардлагууд * [.filename]#audit_warn# - Аудитийн бичлэгүүдийн зай хангалтгүй болох эсвэл аудитийн мөрийн файл дахин эргэсэн зэрэг зайлшгүй шаардлагатай тохиолдолд анхааруулах мэдээллүүдийг үүсгэдэг өөрчлөх боломж бүхий auditd-ийн ашигладаг бүрхүүлийн скрипт. [WARNING] ==== Тохиргоон дахь алдаанууд үйл явцуудын буруу хянан бүртгэлд хүргэж болзошгүй тул аудитийн тохиргооны файлуудыг засварлах болон ажиллагааг хангахдаа заавал болгоомжтой байх шаардлагатай. ==== === Үйл явц сонголтын илэрхийллүүд Сонголтын илэрхийллүүд нь аль үйл явцуудыг аудит хийх ёстойг тодорхойлох аудитийн тохиргооны хэд хэдэн газар ашиглагддаг. Илэрхийллүүд нь тохирох үйл явцын ангиллуудын жагсаалтаас бүрдэх ба эдгээр тус бүр нь тохирох бичлэгүүдийг хүлээн авах ёстой юу эсвэл орхих ёстой юу гэдгийг харуулсан угтвартайгаас гадна оруулга нь амжилттай эсвэл амжилтгүй үйлдлүүдтэй тохирох ёстойг харуулах боломж бас байна. Сонголтын илэрхийллүүд нь зүүнээс баруун тийш биелэгддэг бөгөөд хоёр илэрхийллийг нэг дээр нь нөгөөг нь нэмж нийлүүлдэг. Дараах жагсаалт нь [.filename]#audit_class#-д байгаа анхдагч үйл явцын ангиллуудаас тогтоно: * `all` - _all_ - Бүх үйл явцын ангиллуудыг тааруулах(match). * `ad` - _administrative_ - Удирдлагын үйлдлүүд систем дээр бүхэлдээ гүйцэтгэгдэнэ. * `ap` - _application_ - Програмын тодорхойлсон үйлдэл. * `cl` - _file close_ - `close` системийн дуудлагыг аудит хийх. * `ex` - _exec_ - Програмын ажиллагааг аудит хийх. Тушаалын мөрийн нэмэлт өгөгдлүүд болон орчны хувьсагчуудыг `argv` ба `envv` параметрүүдийг ашиглан `policy` тохиргоонд тохиргоо хийн man:audit_control[5] -ийн тусламжтайгаар хянадаг. * `fa` - _file attribute access_ - man:stat[1], man:pathconf[2] болон бусад адил үйл явцуудын обьектийн шинж чанаруудад хандсан хандалтыг аудит хийх. * `fc` - _file create_ - Үр дүнд нь файл үүсдэг үйл явцуудыг аудит хийх. * `fd` - _file delete_ - Файлыг устгадаг үйл явцуудыг аудит хийх. * `fm` - _file attribute modify_ - man:chown[8], man:chflags[1], man:flock[2] зэрэг файлын шинж чанарын өөрчлөлт гарч байгаа үйл явцуудыг аудит хийх. * `fr` - _file read_ - Өгөгдөл уншигдаж байгаа, мөн файлуудыг уншихаар нээсэн зэрэг үйл явцуудыг аудит хийх. * `fw` - _file write_ - Өгөгдөл бичигдэж байгаа, мөн файлд бичсэн эсвэл файл өөрчлөгдсөн зэрэг үйл явцуудыг аудит хийх. * `io` - _ioctl_ - man:ioctl[2] системийн дуудлагын хэрэглээг аудит хийх. * `ip` - _ipc_ - POSIX хоолойнууд болон System V IPC үйлдлүүд зэрэг Процесс-Хоорондох Холбооны төрөл бүрийн хэлбэрүүдийг аудит хийх. * `lo` - _login_logout_ - Систем дээр болж байгаа man:login[1] ба man:logout[1] үйл явцуудыг аудит хийх. * `na` - _non attributable_ - Шинж чанаргүй үйл явцуудыг аудит хийх. * `no` - _invalid class_ - Аудит бус үйл явцуудыг тааруулах(match). * `nt` - _network_ - man:connect[2] ба man:accept[2] зэрэг сүлжээний үйлдлүүдтэй холбоотой үйл явцуудыг аудит хийх. * `ot` - _other_ - Бусад үйл явцуудыг аудит хийх. * `pc` - _process_ - man:exec[3] ба man:exit[3] зэрэг процессийн үйлдлүүдийг аудит хийх. Эдгээр аудит үйл явцын ангиллуудыг [.filename]#audit_class# болон [.filename]#audit_event# тохиргооны файлуудыг өөрчилснөөр өөрчилж болно. Жагсаалтад байгаа аудитийн ангилал бүр амжилттай/амжилтгүй үйлдлүүдийг таарсан эсэхийг болон ангилал ба төрлийн хувьд таарч байгааг нэмж байгаа эсвэл устгаж байгааг харуулсан угтвартай байна. * (none) Үйл явцын амжилттай болон амжилтгүйг аудит хийх. * `+` Энэ ангилал дахь амжилттай үйл явцуудыг аудит хийх. * `-` Энэ ангилал дахь амжилтгүй үйл явцуудыг аудит хийх. * `^` Энэ ангилал дахь амжилттай, амжилтгүй аль нь ч биш үйл явцуудыг аудит хийх. * `^+` Энэ ангилал дахь амжилттай үйл явцуудыг аудит хийхгүй. * `^-` Энэ ангилал дахь амжилтгүй үйл явцуудыг аудит хийхгүй. Дараах сонголтын мөр амжилттай ба амжилтгүй нэвтрэлт/гаралтын үйл явцуудаас гадна зөвхөн амжилттай ажиллуулсныг сонгож байна: [.programlisting] .... lo,+ex .... === Тохиргооны файлууд Аудит системийг тохируулахдаа ихэнх тохиолдолд администраторууд зөвхөн хоёр файлыг өөрчлөх хэрэгтэй: [.filename]#audit_control# болон [.filename]#audit_user#. Эхнийх нь системийн дагуух аудит өмчүүд болон бодлогуудыг хянадаг; хоёр дахь нь хэрэглэгчийн аудитийг нарийн тохируулахад ашиглагддаг. [[audit-auditcontrol]] ==== [.filename]#audit_control# файл [.filename]#audit_control# файл нь аудит дэд системийн хувьд анхдагч утгуудын тоог тодорхойлно. Энэ файлын дотор бид дараах зүйлсийг харна: [.programlisting] .... dir:/var/audit flags:lo minfree:20 naflags:lo policy:cnt filesz:0 .... `dir` тохиргоо нь аудит бүртгэлүүдийг хадгалах нэг болон хэд хэдэн санг заахад хэрэглэгдэнэ. Хэрэв нэгээс их сан байгаа бол бичигдсэн дарааллаараа ашиглагдана. Файлын систем дүүрсэн тохиолдолд аудит дэд систем болон бусад дэд системүүд бие биедээ нөлөөлж болзошгүй учир аудит бүртгэлүүдийг тусгайлан зориулсан файлын систем дээр хадгалахаар аудит системийг ихэвчлэн тохируулдаг. `flags` талбар нь системийн дагуух шинж чанар бүхий үйл явцуудад зориулсан анхдагч урьдчилан сонголтын багийг тодорхойлдог. Дээрх жишээн дээр бүх хэрэглэгчийн хувьд амжилттай болон амжилтгүй нэвтрэлт болон гаралтын үйл явцууд аудит хийгдэж байна. `minfree` тохиргоо нь аудит мөр хадгалагдах файлын системийн хувьд хамгийн бага чөлөөт зайны хувийг тодорхойлдог. Энэ тогтоосон хэмжээнээс илүү гарахад анхааруулга үүсгэгддэг. Дээрх жишээ хамгийн бага чөлөөт зайг 20 хувиар тогтоожээ. `naflags` тохиргоо нь нэвтрэн оролтын процесс болон системийн дэмонууд зэрэг шинж чанаргүй үйл явцуудыг аудит хийх аудитийн ангиллуудыг тодорхойлдог. `policy` тохиргоо нь таслалаар тусгаарлагдсан, аудитийн зан авирын төрөл бүрийн шинж чанарыг хянах бодлогын тугуудын жагсаалтыг тодорхойлдог. Анхдагч `cnt` туг нь аудит амжилтгүй болсон ч гэсэн систем ажиллагаагаа үргэлжлүүлэхийг заадаг (энэ туг зайлшгүй шаардлагатай). Өөр нэг байнга ашиглагддаг туг бол `argv` бөгөөд энэ нь man:execve[2] системийн дуудлагад орж байгаа тушаалын мөрийн нэмэлт өгөгдлүүдийг тушаалын ажиллагааг аудит хийхийн хэсэг болох боломж олгодог. `filesz` тохиргоо нь мөрийн файл автоматаар төгсөх болон эргэхээс өмнөх аудит мөрийн файлын хамгийн их хэмжээг байтаар тодорхойлдог. Анхдагч утга нь 0 байх ба автоматаар эргүүлэхийг хориглосон байна. Хэрэв хүссэн файлын хэмжээ тэгээс ялгаатай ба 512k -аас бага бол түүнийг орхиж бүртгэлийн мэдээлэл үүсгэнэ. [[audit-audituser]] ==== [.filename]#audit_user# файл [.filename]#audit_user# файл нь зарим нэг хэрэглэгчдэд зориулсан аудитийн шаардлагуудыг администраторууд тодорхойлохыг зөвшөөрдөг. Мөр болгон хэрэглэгчид зориулсан аудитийг хийхийг хоёр талбараар тохируулдаг: нэг дэх нь хэрэглэгчийн хувьд үргэлж аудит хийх шаардлагатай нэг хэсэг үйл явцуудыг тодорхойлдог `alwaysaudit` талбар ба хоёр дахь нь `neveraudit` талбар бөгөөд хэрэглэгчийн хувьд хэзээ ч аудит хийх шаардлагагүй нэг хэсэг үйл явцуудыг тодорхойлдог. Дараах жишээн дээр [.filename]#audit_user# файл нь нэвтрэлт/гаралтын үйл явцууд, `root` хэрэглэгчийн амжилттай тушаалын ажиллагаа, файл үүсгэлт ба `www` хэрэглэгчийн амжилттай тушаалын ажиллагааг аудит хийж байна. Хэрэв дээрх жишээ [.filename]#audit_control# файлтай цуг ашиглагдвал `root`-ийн `lo` оруулга нь давхардах бөгөөд `www` хэрэглэгчийн нэвтрэлт/гаралтын үйл явцууд бас аудит хийгдэнэ. [.programlisting] .... root:lo,+ex:no www:fc,+ex:no .... [[audit-administration]] == Аудит дэд системийг удирдах нь === Аудит мөрүүдийг харах нь Аудит мөрүүд нь BSM хоёртын хэлбэрээр хадгалагддаг бөгөөд өөрчлөх болон текст уруу хөрвүүлэхэд тусгай хэрэгслүүд ашиглах шаардлагатай. man:praudit[1] тушаал нь мөрийн файлуудыг хялбар текст хэлбэрт хөрвүүлдэг; man:auditreduce[1] тушаал нь аудит мөрийн файлыг шинжлэх, архивлах эсвэл хэвлэх зорилгоор багасгахад ашиглагддаг. `auditreduce` нь үйл явцын төрөл, үйл явцын ангилал, үйл явцын хэрэглэгч, огноо эсвэл цаг, файлын зам эсвэл обьектийн үйлдэл үзүүлсэн зэрэг төрөл бүрийн сонголтын параметрүүдийг дэмждэг. Жишээ нь `praudit` хэрэгсэл нь заасан аудит бүртгэлийн бүх агуулгыг жирийн текстээр харуулна: [source,shell] .... # praudit /var/audit/AUDITFILE .... [.filename]#AUDITFILE# нь харуулах аудит бүртгэл юм. Аудит мөрүүд нь токенуудаас бүтэх аудит бичлэгүүдийн цувралаас тогтох бөгөөд `praudit` нь мөр болгонд нэгийг дараалуулан хэвлэнэ. Токен бүр аудит бичлэгийн толгойг агуулсан `header` эсвэл нэрийн хайлтаас гарсан файлын замыг агуулсан `path` зэрэг тусгай төрлийн байна. Дараах жишээ нь `execve` үйл явцыг харуулж байна: [.programlisting] .... header,133,10,execve(2),0,Mon Sep 25 15:58:03 2006, + 384 msec exec arg,finger,doug path,/usr/bin/finger attribute,555,root,wheel,90,24918,104944 subject,robert,root,wheel,root,wheel,38439,38032,42086,128.232.9.100 return,success,0 trailer,133 .... Энэхүү аудит нь амжилттай `execve` дуудлагыг илэрхийлж байгаа бөгөөд түүнд `finger doug` тушаал ажиллажээ. Нэмэлт өгөгдлийн токен нь цөм уруу бүрхүүлээс гарч боловсруулагдсан тушаалын мөрийг агуулна. `path` буюу замын токен нь цөмийн хайсан ажиллах файлын замыг агуулна. `attribute` буюу шинж чанарын токен нь хоёртын файлыг тайлбарлах ба тухайлбал програм setuid эсэхийг тодорхойлоход ашиглагдах файлын горимыг агуулна. `subject` буюу субьект токен нь субьект процессийг тайлбарлах бөгөөд аудит хэрэглэгчийн ID, идэвхитэй хэрэглэгчийн ID ба бүлгийн ID, жинхэнэ хэрэглэгчийн ID ба бүлгийн ID, процессийн ID, сессийн ID, портын ID болон нэвтрэлтийн хаяг гэсэн дарааллаар хадгална. Аудит хэрэглэгчийн ID ба жинхэнэ хэрэглэгчийн ID нь ялгаатайг анхаарах хэрэгтэй: `robert` гэдэг хэрэглэгч энэ тушаалыг ажиллуулахаасаа өмнө `root` бүртгэл уруу шилжсэн бөгөөд энэ нь эхний шалгуулсан хэрэглэгчийг ашиглан аудит хийгдсэн байна. Төгсгөлд нь `return` буюу буцах токен нь амжилттай ажиллагааг харуулж `trailer` нь бичлэгийг төгсгөнө. `praudit` нь бас XML гаралтын хэлбэрийг дэмждэг бөгөөд үүнийг `-x` нэмэлт өгөгдлийг ашиглан сонгож болдог. === Аудитийн мөрүүдийг багасгах нь Аудит бүртгэлүүд нь маш их байж болно, администратор зарим хэрэглэгчтэй холбоотой бичлэгүүд зэрэг хэсэг бичлэгүүдийг ашиглахын тулд шилж сонгохыг магадгүй хүснэ: [source,shell] .... # auditreduce -u trhodes /var/audit/AUDITFILE | praudit .... Энэ нь [.filename]#AUDITFILE# файлд хадгалагдсан `trhodes` хэрэглэгчийн бүх аудитийн бичлэгүүдийг сонгож байна. === Аудит хянах эрхүүдийг томилох нь `audit` бүлгийн гишүүд [.filename]#/var/audit# дахь аудит мөрүүдийг унших эрхтэй; анхандаа энэ бүлэг нь хоосон байх бөгөөд тэгэхээр зөвхөн `root` хэрэглэгч аудит мөрүүдийг уншиж чадна. Аудит хянах эрхүүдийг хэрэглэгчдэд томилохын тулд хэрэглэгчдийг `audit` бүлэгт нэмж болно. Аудитийн бүртгэлийн агуулгыг хянах чадвар нь хэрэглэгчид болон процессуудын үйл хөдлөлийн дотоод уруу нэлээн гүнзгий ханддаг учир аудит хянах эрхүүдийг томилохдоо болгоомжтой хийхийг зөвлөж байна. === Аудит хоолойнуудыг шууд монитор хийх нь Аудит хоолойнууд нь төхөөрөмжийн файлын систем дахь клон хийгдсэн псевдо төхөөрөмжүүд бөгөөд програмыг шууд явж байгаа аудит бичлэгийн урсгалд холбох боломж олгоно. Энэ нь голчлон халдлага илрүүлэх болон систем монитор хийх програмуудын зохиогчдын сонирхлыг татдаг. Гэхдээ администраторуудын хувьд аудитийн хоолойны төхөөрөмж нь аудитийн мөрийн файлын эзэмшил эсвэл үйл явцын урсгалыг зогсоох, бүртгэл эргүүлэх зэрэг асуудлуудтай холбогдолгүйгээр шууд монитор хийх эвтэйхэн боломжийг бүрдүүлдэг. Шууд явж байгаа аудитийн үйл явцын урсгалыг хянахдаа дараах тушаалын мөрийг ашиглана: [source,shell] .... # praudit /dev/auditpipe .... Анхандаа аудитийн хоолойны төхөөрөмжийн цэгүүдэд зөвхөн `root` хэрэглэгч хандах эрхтэй байдаг. `audit` бүлгийн хэрэглэгчид хандах боломжтой болгохын тулд `devfs` дүрмийг [.filename]#devfs.rules# -д нэмнэ: [.programlisting] .... add path 'auditpipe*' mode 0440 group audit .... devfs файлын системийг тохируулах талаар дэлгэрэнгүй мэдээллийг man:devfs.rules[5] -ээс харна уу. [WARNING] ==== Аудитийн үйл явцын буцааж өгөх давталтуудыг үүсгэх нь хялбар бөгөөд аудит үйл явц бүрийн үзэлт нь олон аудитийн үйл явцуудыг үүсгэхэд хүргэнэ. Жишээ нь, хэрэв сүлжээний бүх I/O аудит хийгдсэн бөгөөд man:praudit[1] нь SSH сессээс ажилласан бол үйл явц бүр хэвлэгдэхэд өөр үйл явцыг бас үүсгэх учраас үргэлжилсэн аудитийн үйл явцууд их хэмжээгээр үүсэх болно. Энэ асуудлыг бий болгохгүйн тулд нарийн тохируулаагүй I/O аудит хийх сессээс `praudit`-ийг аудитийн хоолойны төхөөрөмж дээр ажиллуулахыг зөвлөж байна. ==== === Аудит мөрийн файлуудыг эргүүлэх нь Аудит мөрүүд нь зөвхөн цөмөөр бичигдэх бөгөөд auditd аудит дэмоноор удирдагддаг. Администраторууд аудит бүртгэлүүдийг шууд эргүүлэхдээ man:newsyslog.conf[5] эсвэл бусад хэрэгслүүдийг ашиглан хийх ёсгүй юм. Харин `audit` удирдах хэрэгслийг ашиглан аудитийг унтраах, аудит системийг дахин тохируулах, болон бүртгэлийг эргүүлэх үйлдлүүдийг хийх боломжтой байдаг. Дараах тушаал аудит дэмонг шинэ аудит бүртгэл үүсгэж цөмийг шинэ бүртгэл уруу шилжихийг дохино. Хуучин бүртгэл нь төгсөж нэр нь өөрчлөгдөх бөгөөд дараагаар түүнтэй администратор ажиллах боломж бүрдэнэ. [source,shell] .... # audit -n .... [WARNING] ==== Хэрэв auditd дэмон ажиллахгүй байгаа бол энэ тушаал нь амжилтгүй болох бөгөөд алдааны мэдээлэл үүсгэнэ. ==== Дараах мөрийг [.filename]#/etc/crontab# -д нэмснээр man:cron[8] -оос арван хоёр цаг тутам эргүүлэх болно: [.programlisting] .... 0 */12 * * * root /usr/sbin/audit -n .... Шинэ [.filename]#/etc/crontab# -ийг хадгалсны дараа өөрчлөлт үйлчилж эхлэх болно. Файлын хэмжээн дээр тулгуурласан аудитийн мөрийн файлыг автоматаар эргүүлэх нь man:audit_control[5] дахь `filesz` тохиргоогоор хийгдэх боломжтой бөгөөд гарын авлагын энэ бүлгийн тохиргооны файлуудын хэсэгт тайлбарласан болно. === Аудит мөрүүдийг шахах нь Аудит мөрийн файлууд асар их болох тусам мөрүүдийг аудит дэмоноор хаалгасны дараа шахах эсвэл архивлах нь зүйтэй юм. [.filename]#audit_warn# скрипт нь аудитийн мөрүүдийг эргүүлэх үеийн цэвэр төгсгөл зэрэг төрөл бүрийн аудиттай холбоотой үйл явцуудад зориулан өөрчилсөн үйлдлүүдийг гүйцэтгэхэд ашиглагдана. Жишээ нь хаагдах үед аудит мөрүүдийг шахах дараах кодыг [.filename]#audit_warn# скриптэд нэмж болно: [.programlisting] .... # # Compress audit trail files on close. # if [ ""$1"" = closefile ]; then gzip -9 $2 fi .... Бусад архивлах идэвхүүдэд мөрийн файлуудыг төв сервер уруу хуулах, хуучин мөрийн файлуудыг устгах эсвэл хэрэггүй бичлэгүүдийг хасч аудит мөрийг багасгах зэрэг орж болно. Аудит мөрийн файлууд цэвэрхэн дууссан тохиолдолд скрипт ажиллана, тэгэхээр буруу унтраасны дараа дуусаагүй мөрүүд дээр ажиллахгүй. ",12439,True,2674.574359152609,median "[[flowableApps]] == Flowable applications Flowable provides several ui web applications to demonstrate and leverage the functionality provided by the Flowable project: * Flowable IDM: an Identity Management application that provides single sign-on authentication functionality for all the Flowable UI applications, and, for users with the IDM administrative privilege, it also provides functionality to manage users, groups and privileges. * Flowable Modeler: an application that allows users with modeler privileges to model processes, forms, decision tables and application definitions. * Flowable Task: a runtime task application that provides functionality to start process instances, edit task forms, complete tasks and query on tasks and process instances. * Flowable Admin: an administrative application that allows users with admin privilege to query the BPMN, DMN, form and content engines and provides several options to change process instances, tasks, jobs and so on. The admin application connects to the engines through the REST API that is deployed together with the Flowable Task app and the Flowable REST app. The Flowable IDM is required for all other apps to enable authentication. The WAR files for each app can be deployed to the same servlet container (such as Apache Tomcat), but can also be deployed on different servlet containers. Because the same cookie is used for authentication with each app, the apps need to run on the same domain. Flowable also provides the `flowable-rest.war` which contains the Flowable REST API. More about this can be read in the <> chapter. The apps are Spring Boot 2.0 based, which means that that the WAR files are actually executable and can be run as a normal standalone applications. See https://docs.spring.io/spring-boot/docs/current/reference/html/build-tool-plugins-maven-plugin.html#build-tool-plugins-maven-packaging[The Executable Jar Format] in the Spring Boot reference documentation. [[uiAppInstallation]] === Flowable UI Applications installation As mentioned before, all four UI apps can be deployed together on the same Tomcat server, and to get started this is probably the easiest approach. You can choose to only install the Modeler app, for example, but make sure the Flowable IDM app is always running/deployed as well. For this installation guide we'll describe the installation of all four apps to a Tomcat server. 1. Download a recent stable version of link:$$http://tomcat.apache.org$$[Apache Tomcat]. 2. Download the latest stable link:$$http://www.flowable.org/downloads.html$$[Flowable 6 version]. 3. Copy the flowable-admin.war, flowable-idm.war, flowable-modeler.war and flowable-task.war files from the Flowable distribution __wars__ folder to the Tomcat webapps folder. 4. Startup the Tomcat server by running the bin/startup.sh (Mac OS and Linux) or bin/startup.bat (Windows) script. 5. Open a web browser and go to link:$$http://localhost:8080/flowable-modeler$$[http://localhost:8080/flowable-modeler]. All Flowable UI apps should now be running with an H2 in-memory database and the following login screen should be shown in your web browser: image::images/flowable_idm_login_screen.png[align=""center""] By default, the Flowable IDM application will create an admin user that has privileges to all the Flowable UI apps. You can login with admin/test and the browser should redirect to the Flowable Modeler application: image::images/flowable_modeler_startup_screen.png[align=""center""] Since the UI apps are Spring Boot executable apps it is possible to run them as standalone applications without the need of an application server. Starting single application looks like: ``` java -jar flowable-idm.war ``` Usually, you will want to change the default H2 in-memory database configuration to a MySQL or Postgres (or other persistent database) configuration. You can do this per app by changing the application.properties file in the _WEB-INF/classes/_ directory of each app. However, it is easier to use the Spring Boot https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html[Externalized Configuration]. An example configuration can be found on link:$$https://github.com/flowable/flowable-engine/blob/master/modules/flowable-ui-task/flowable-ui-task-app/src/main/resources/flowable-default.properties$$[Github] To change the default configuration to MySQL the following changes are needed to the properties file: [source,linenums] ---- spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://127.0.0.1:3306/flowable?characterEncoding=UTF-8 spring.datasource.username=flowable spring.datasource.password=flowable ---- This configuration will expect a flowable database to be present in the MySQL server and the UI apps will automatically generate the necessary database tables. For Postgres the following changes are necessary: [source,linenums] ---- spring.datasource.driver-class-name=org.postgresql.Driver spring.datasource.url=jdbc:postgresql://localhost:5432/flowable spring.datasource.username=flowable spring.datasource.password=flowable ---- In addition to changing the configuration, make sure the database driver is available on the classpath. Again, you could do this for every web application separately by adding the driver JAR file to the WEB-INF/lib folder, but you can also copy the JAR file once to the Tomcat lib folder. For MySQL and Postgres the database drivers can be downloaded from: * MySQL: link:$$https://dev.mysql.com/downloads/connector/j$$[https://dev.mysql.com/downloads/connector/j] * Postgres: link:$$https://jdbc.postgresql.org/$$[https://jdbc.postgresql.org/] When running the apps as standalone applications the database driver can be added by using the `loader.path` property. ``` java -Dloader.path=/location/to/your/driverfolder -jar flowable-idm.war ``` See the https://docs.spring.io/spring-boot/docs/current/reference/html/executable-jar.html#executable-jar-property-launcher-features[`PropertiesLauncher` Features] in the Spring Boot reference documentation for more information. === Flowable UI Applications Configurations As the Flowable UI apps are Spring Boot applications you can use all the properties Spring Boot provides. In order to provide custom configuration for the apps have a look at the https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html[Externalized Configuration] section of the Spring Boot documentation. [TIP] ----- You can also use YAML based properties. ----- .Common UI App Properties [cols=""4*"",options=""header""] |=============== |Property name |Old Property |Default value |Description |flowable.common.app.idm-url |idm.app.url |- |The URL to the IDM application, used for the user info and token info REST GET calls. It's also used as a fallback for the redirect url to the login page in the UI apps. |flowable.common.app.idm-redirect-url |idm.app.redirect.url |- |The redirect URL to the IDM application, used for the login redirect when the cookie isn't set or is invalid. |flowable.common.app.redirect-on-auth-success |app.redirect.url.on.authsuccess |- |The URL to which the redirect should occur after a successful authentication. |flowable.common.app.role-prefix |- |ROLE_ |The default role prefix that needs to be used by Spring Security. |flowable.common.app.tenant-id |- |- |The static tenant id used for the DefaultTenantProvider. The modeler app uses this to determine under which tenant id to store and publish models. When not provided, empty or only contains whitespace it defaults to the user's tenant id if available otherwise it uses no tenant id. |flowable.common.app.cache-login-tokens.max-age |cache.login-tokens.max.age |30 |The max age in seconds after which the entry should be invalidated. |flowable.common.app.cache-login-tokens.max-size |cache.login-tokens.max.size |2048 |The maximum number of entries that the cache should contain. |flowable.common.app.cache-login-users.max-age |cache.login-users.max.age |30 |The max age in seconds after which the entry should be invalidated. |flowable.common.app.cache-login-users.max-size |cache.login-users.max.size |2048 |The maximum number of entries that the cache should contain. |flowable.common.app.cache-users.max-age |cache.users.max.age |30 |The max age in seconds after which the entry should be invalidated. |flowable.common.app.cache-users.max-size |cache.users.max.size |2048 |The maximum number of entries that the cache should contain. |flowable.common.app.idm-admin.password |idm.admin.password |- |The password used for executing the REST calls (with basic auth) to the IDM REST services. Default is test. |flowable.common.app.idm-admin.user |idm.admin.user |admin |The username used for executing the REST calls (with basic auth) to the IDM REST services. Default is admin |flowable.rest.app.authentication-mode |rest.authentication.mode |verify-privilege |Configures the way user credentials are verified when doing a REST API call: 'any-user' : the user needs to exist and the password need to match. Any user is allowed to do the call (this is the pre 6.3.0 behavior) 'verify-privilege' : the user needs to exist, the password needs to match and the user needs to have the 'rest-api' privilege If nothing set, defaults to 'verify-privilege' |=============== Some of the old properties have been moved to be managed by the Flowable Spring Boot starter (or Spring Boot itself) .Old properties managed by the Flowable Spring Boot Starter [cols=""4*"",options=""header""] |=============== |Property name |Old Property |Default value |Description |flowable.async-executor-activate |engine.process.asyncexecutor.activate |true |Whether the async executor should be activated. |flowable.database-schema-update |engine.process.schema.update |true |The strategy that should be used for the database schema. |flowable.history-level |engine.process.history.level |- |The history level that needs to be used. |flowable.process.servlet.name |flowable.rest-api-servlet-name |Flowable BPMN Rest API |The name of the Process servlet. |flowable.process.servlet.path |flowable.rest-api-mapping |/process-api |The context path for the Process rest servlet. |flowable.content.storage.create-root |contentstorage.fs.create-root |true |If the root folder doesn't exist, should it be created? |flowable.content.storage.root-folder |contentstorage.fs.root-folder |- |Root folder location where content files will be stored, for example, task attachments or form file uploads. |flowable.idm.enabled |flowable.db-identity-used |true |Whether the idm engine needs to be started. |flowable.idm.password-encoder |security.passwordencoder |- |The type of the password encoder that needs to be used. |flowable.idm.ldap.base-dn |ldap.basedn |- |The base 'distinguished name' (DN) from which the searches for users and groups are started. Use 'user-base-dn' or 'group-base-dn' when needing to differentiate between user and group base DN. |flowable.idm.ldap.enabled |ldap.enabled |false |Whether to enable LDAP IDM Service. |flowable.idm.ldap.password |ldap.password |- |The password that is used to connect to the LDAP system. |flowable.idm.ldap.port |ldap.port |-1 |The port on which the LDAP system is running. |flowable.idm.ldap.server |ldap.server |- |The server host on which the LDAP system can be reached. For example 'ldap://localhost'. |flowable.idm.ldap.user |ldap.user |- |The user id that is used to connect to the LDAP system. |flowable.idm.ldap.attribute.email |ldap.attribute.email |- |Name of the attribute that matches the user email. This property is used when looking for an 'org.flowable.idm.api.User' object and the mapping between the LDAP object and the Flowable 'org.flowable.idm.api.User' object is done. |flowable.idm.ldap.attribute.first-name |ldap.attribute.firstname |- |Name of the attribute that matches the user first name. This property is used when looking for a 'org.flowable.idm.api.User' object and the mapping between the LDAP object and the Flowable 'org.flowable.idm.api.User' object is done. |flowable.idm.ldap.attribute.group-id |ldap.attribute.groupid |- |Name of the attribute that matches the group id. This property is used when looking for a 'org.flowable.idm.api.Group' object and the mapping between the LDAP object and the Flowable 'org.flowable.idm.api.Group' object is done. |flowable.idm.ldap.attribute.group-name |ldap.attribute.groupname |- |Name of the attribute that matches the group name. This property is used when looking for a 'org.flowable.idm.api.Group' object and the mapping between the LDAP object and the Flowable 'org.flowable.idm.api.Group' object is done. |flowable.idm.ldap.attribute.last-name |ldap.attribute.lastname |- |Name of the attribute that matches the user last name. This property is used when looking for a 'org.flowable.idm.api.User' object and the mapping between the LDAP object and the Flowable 'org.flowable.idm.api.User' object is done. |flowable.idm.ldap.attribute.user-id |ldap.attribute.userid |- |Name of the attribute that matches the user id. This property is used when looking for a 'org.flowable.idm.api.User' object and the mapping between the LDAP object and the Flowable 'org.flowable.idm.api.User' object is done. This property is optional and is only needed if searching for 'org.flowable.idm.api.User' objects using the Flowable API. |flowable.idm.ldap.cache.group-size |ldap.cache.groupsize |-1 |Allows to set the size of the 'org.flowable.ldap.LDAPGroupCache'. This is an LRU cache that caches groups for users and thus avoids hitting the LDAP system each time the groups of a user needs to be known. The cache will not be instantiated if the value is less then zero. By default set to -1, so no caching is done. Note that the group cache is instantiated on the 'org.flowable.ldap.LDAPIdentityServiceImpl'. As such, if you have a custom implementation of the 'org.flowable.ldap.LDAPIdentityServiceImpl', do not forget to add the group cache functionality. |flowable.idm.ldap.query.all-groups |ldap.query.groupall |- |The query that is executed when searching for all groups. |flowable.idm.ldap.query.all-users |ldap.query.userall |- |The query that is executed when searching for all users. |flowable.idm.ldap.query.groups-for-user |ldap.query.groupsforuser |- |The query that is executed when searching for the groups of a specific user. For example: `(&(objectClass=groupOfUniqueNames)(uniqueMember={0}))` Here, all the objects in LDAP with the class 'groupOfUniqueNames' and where the provided DN is a 'uniqueMember' are returned. As shown in the example, the user id is injected by the typical {@link java.text.MessageFormat}, ie by using _{0}_ If setting the query alone is insufficient for your specific LDAP setup, you can alternatively plug in a different `org.flowable.ldap.LDAPQueryBuilder`, which allows for more customization than only the query. |flowable.idm.ldap.query.user-by-full-name-like |ldap.query.userbyname |- |The query that is executed when searching for a user by full name. For example: `(&(objectClass=inetOrgPerson)(\\|({0}=**{1}**)({2}={3})))` Here, all the objects in LDAP with the class 'inetOrgPerson' and who have the matching first name or last name will be returned Several things will be injected in the expression: {0} : the first name attribute {1} : the search text {2} : the last name attribute {3} : the search text If setting the query alone is insufficient for your specific LDAP setup, you can alternatively plug in a different 'org.flowable.ldap.LDAPQueryBuilder', which allows for more customization than only the query. |flowable.idm.ldap.query.user-by-id |ldap.query.userbyid |- |The query that is executed when searching for a user by userId. For example: `(&(objectClass=inetOrgPerson)(uid={0}))` Here, all the objects in LDAP with the class 'inetOrgPerson' and who have the matching 'uid' attribute value will be returned. As shown in the example, the user id is injected by the typical {@link java.text.MessageFormat}, ie by using _{0}_ If setting the query alone is insufficient for your specific LDAP setup, you can alternatively plug in a different 'org.flowable.ldap.LDAPQueryBuilder', which allows for more customization than only the query. |flowable.mail.server.host |email.host |localhost |The host of the mail server. |flowable.mail.server.password |email.password |- |The password for the mail server authentication. |flowable.mail.server.port |email.port |1025 |The port of the mail server. |flowable.mail.server.use-ssl |email.use-ssl |false |Sets whether SSL/TLS encryption should be enabled for the SMTP transport upon connection (SMTPS/POPS). |flowable.mail.server.use-tls |email.use-tls |false |Set or disable the STARTTLS encryption. |flowable.mail.server.username |email.username |- |The username that needs to be used for the mail server authentication. If empty no authentication would be used. |flowable.process.definition-cache-limit |flowable.process-definitions.cache.max |-1 |The maximum amount of process definitions available in the process definition cache. Per default it is -1 (all process definitions). |=============== .Old properties managed by Spring Boot [cols=""4*"",options=""header""] |=============== |Property name |Old Property |Default value |Description |spring.datasource.driver-class-name |datasource.driver |- |Fully qualified name of the JDBC driver. Auto-detected based on the URL by default. |spring.datasource.jndi-name |datasource.jndi.name |- |JNDI location of the datasource. Class, url, username & password are ignored when set. |spring.datasource.password |datasource.password |- |Login password of the database. |spring.datasource.url |datasource.url |- |JDBC URL of the database. |spring.datasource.username |datasource.username |- |Login username of the database. |spring.datasource.hikari.connection-test-query |datasource.preferred-test-query |- |The SQL query to be executed to test the validity of connections. |spring.datasource.hikari.connection-timeout |datasource.connection.timeout |- |The maximum number of milliseconds that a client will wait for a connection from the pool. If this time is exceeded without a connection becoming available, a SQLException will be thrown when getting a connection. |spring.datasource.hikari.idle-timeout |datasource.connection.idletimeout |- |The maximum amount of time (in milliseconds) that a connection is allowed to sit idle in the pool. Whether a connection is retired as idle or not is subject to a maximum variation of +30 seconds, and average variation of +15 seconds. A connection will never be retired as idle before this timeout. A value of 0 means that idle connections are never removed from the pool. |spring.datasource.hikari.max-lifetime |datasource.connection.maxlifetime |- |This property controls the maximum lifetime of a connection in the pool. When a connection reaches this timeout, even if recently used, it will be retired from the pool. An in-use connection will never be retired, only when it is idle will it be removed. |spring.datasource.hikari.maximum-pool-size |datasource.connection.maxpoolsize |- |The property controls the maximum size that the pool is allowed to reach, including both idle and in-use connections. Basically this value will determine the maximum number of actual connections to the database backend. When the pool reaches this size, and no idle connections are available, calls to getConnection() will block for up to connectionTimeout milliseconds before timing out. |spring.datasource.hikari.minimum-idle |datasource.connection.minidle |- |The property controls the minimum number of idle connections that HikariCP tries to maintain in the pool, including both idle and in-use connections. If the idle connections dip below this value, HikariCP will make a best effort to restore them quickly and efficiently. |spring.servlet.multipart.max-file-size |file.upload.max.size |10MB |Max file size. Values can use the suffixes ""MB"" or ""KB"" to indicate megabytes or kilobytes, respectively. |=============== .Not used old properties [cols=""2*"",options=""header""] |=============== |Old property |Description |datasource.jndi.resource-ref |Spring Boot does not support configuring JNDI resourceRef. Use entire resource reference in the name. |email.use-credentials |In case you don't want to use credentials, set the password and user to empty. |=============== [[flowableIDMApp]] === Flowable IDM application The Flowable IDM application is used by all other three Flowable web applications for authentication and authorization and is therefore required to be available when you want to run the Modeler, Task or Admin application. The Flowable IDM application is a simple identity management application and is targeted at providing single sign-on capabilities to the Flowable web applications, including providing a central place to define users, groups and privileges. The IDM application boots the IDM engine at startup and will create the identity tables as defined in the IDM engine in the datasource defined in the properties configuration. When the Flowable IDM application is deployed and started, it will check if there's a user available in the ACT_ID_USER table, and if not it will use the `flowable.common.app.idm-admin.user` property to create a new default admin user in this table. It will also add all available privileges in the Flowable project to the newly created admin user: * access-idm: provides the privilege to manage users, groups and privileges * access-admin: allows the user to login to the Flowable Admin application, manage the Flowable engines and access the Actuator endpoints of all the applications * access-modeler: enables access to the Flowable Modeler application * access-task: provides the privilege to login to the Flowable Task application * access-rest-api: allows the user to do call the REST API. Otherwise a 403 (forbidden) http status will be returned. Note that _flowable.rest.app.authentication-mode_ nees to be set to _verify-privilege_, which is the default. When logging in to link:$$http://localhost:8080/flowable-idm$$[http://localhost:8080/flowable-idm] with admin/test for the first time the following user overview screen is shown: image::images/flowable_idm_startup_screen.png[align=""center""] In this screen users can be added, removed and updated. The groups section can be used to create, delete and update groups. In the group details view you can also add and remove users to and from the group. The privilege screen allows you to add and remove privileges from users and groups: image::images/flowable_idm_privilege_screen.png[align=""center""] There's no option to define new privileges yet, but you can add and remove users and groups for the existing four privileges. This are the IDM UI App specific properties. .IDM UI App Properties [cols=""4*"",options=""header""] |=============== |Property name |Old Property |Default value |Description |flowable.idm.app.bootstrap |idm.bootstrap.enabled |true |Whether the IDM App needs to be bootstrapped. |flowable.idm.app.rest-enabled |rest.idm-app.enabled |true |Enables the REST API (this is not the REST api used by the UI, but an api that's available over basic auth authentication). |flowable.idm.app.admin.email |admin.email |- |The email of the admin user. |flowable.idm.app.admin.first-name |admin.firstname |- |The first name of the admin user. |flowable.idm.app.admin.last-name |admin.lastname |- |The last name of the admin user. |flowable.idm.app.admin.password |admin.password |- |The password for the admin user. |flowable.idm.app.admin.user-id |admin.userid |- |The id of the admin user. |flowable.idm.app.security.remember-me-key |security.rememberme.key |testKey |The hash key that is used by Spring Security to hash the password values in the applications. Make sure that you change the value of this property. |flowable.idm.app.security.user-validity-period |cache.users.recheck.period |30000 |How long should a user be cached before invalidating it in the cache for the cacheable CustomUserDetailsService. |flowable.idm.app.security.cookie.domain |security.cookie.domain |- |The domain for the cookie. |flowable.idm.app.security.cookie.max-age |security.cookie.max-age |2678400 |The max age of the security cookie in seconds. Default is 31 days. |flowable.idm.app.security.cookie.refresh-age |security.cookie.refresh-age |86400 |The refresh age of the cookie in seconds. Default is 1 day. |=============== In addition to the default identity tables, the IDM application can also be configured to use an LDAP server. To connect to a LDAP server, additional properties in the application.properties file (or any other way of configuring the application) are needed: [source,linenums] ---- # # LDAP # flowable.idm.ldap.enabled=true flowable.idm.ldap.server=ldap://localhost flowable.idm.ldap.port=10389 flowable.idm.ldap.user=uid=admin, ou=system flowable.idm.ldap.password=secret flowable.idm.ldap.base-dn=o=flowable flowable.idm.ldap.query.user-by-id=(&(objectClass=inetOrgPerson)(uid={0})) flowable.idm.ldap.query.user-by-full-name-like=(&(objectClass=inetOrgPerson)(|({0}=*{1}*)({2}=*{3}*))) flowable.idm.ldap.query.all-users=(objectClass=inetOrgPerson) flowable.idm.ldap.query.groups-for-user=(&(objectClass=groupOfUniqueNames)(uniqueMember={0})) flowable.idm.ldap.query.all-groups=(objectClass=groupOfUniqueNames) flowable.idm.ldap.query.group-by-id=(&(objectClass=groupOfUniqueNames)(uniqueId={0})) flowable.idm.ldap.attribute.user-id=uid flowable.idm.ldap.attribute.first-name=cn flowable.idm.ldap.attribute.last-name=sn flowable.idm.ldap.attribute.group-id=cn flowable.idm.ldap.attribute.group-name=cn flowable.idm.ldap.cache.group-size=10000 flowable.idm.ldap.cache.group-expiration=180000 ---- When the `flowable.idm.ldap.enabled` property is set to true, the IDM app will expect the other LDAP properties to have been filled-in. In this example configuration the server configuration + LDAP queries for the Apache Directory Server are provided. For other LDAP servers, like Active Directory, other configuration values are needed. When LDAP is configured, authentication and group retrieval for a user will be done through the LDAP server. Only privileges will still be retrieved from the Flowable identity tables. So make sure each LDAP user has the correct privileges defined in the IDM application. If the IDM application is booted with LDAP configuration the bootstrap logic will check if there are already privileges present in the Flowable identity tables. If there are no privileges (only when booting the first time), the 4 default privileges will be created and the `flowable.idm.app.admin.user-id` property value (from application.properties or configured in the environment) will be used as the user id to get all 4 privileges. So make sure that the `flowable.idm.app.admin.user-id` property value is set to a valid LDAP user, otherwise nobody will be able to login to any of the Flowable UI apps. [[flowableModelerApp]] === Flowable Modeler application The Flowable Modeler application can be used to model BPMN processes, DMN decision table, Form definitions and create app definitions. The BPMN modeler uses the same Oryx and Angular foundation as in Flowable 5, but the functionality has now been moved into a separate Modeler application. When using the Flowable Modeler application, make sure the Flowable IDM application is deployed and running as well (for authentication and authorization purposes). When you login to the Modeler application (link:$$http://localhost:8080/flowable-modeler$$[http://localhost:8080/flowable-modeler]) with your user (or the default admin/test user), you will see the process overview screen. From here you can start creating new BPMN process models by clicking on the Create Process or Import Process button. image::images/flowable_modeler_createmodel_popup.png[align=""center"", width=""600""] When creating a process model (but also any other model), it's important to think carefully about the model key value. The model key is a unique identifier for the model across the full model repository. If you choose a model key that already exists in the model repository, an error message is shown and the model is not saved. After creating the model with the popup, the BPMN modeling canvas is shown. The BPMN editor is very similar to the Flowable 5 BPMN editor that was part of the Explorer application. All BPMN elements supported by the Flowable engine are available to be used in the design of a process model. image::images/flowable_modeler_design_screen.png[align=""center""] The BPMN editor is divided into 4 parts: * Palette: the palette of BPMN elements available to design a process model * Toolbar: actions to change the model canvas, such as zooming, layout and saving a model * Model canvas: the modeling canvas on which to drag and drop BPMN elements and design the process model * Properties panel: the properties for the main process model if no element is select and otherwise the properties of the selected BPMN element For a User task element there's a _Referenced form_ property in the properties panel. If you select this property, a popup is opened where you can select a form definition from the repository or create a new form. When creating a new form, a similar create dialog to the process model create dialog is presented. After filling in the name and form model key, the form editor is opened. image::images/flowable_modeler_formdesign_screen.png[align=""center""] Form fields can be dragged from the form palette on to the form canvas. In this example, a name textfield, two date fields and a remarks multiline textfield are added to the form canvas. When editing a form field, the label, id, required status and placeholder can be filled in. image::images/flowable_modeler_editfield_popup.png[align=""center"", width=""600""] The id field is an important value, because a process variable will be created with the form field value using the id property value. When filling in the label property, the id property is automatically filled. If needed, you can also provide the id property value yourself by checking the override id checkbox. After saving the form model and closing the form editor, you are automatically navigated back to the process model (when the form editor was opened via the BPMN editor). When selecting the User task element again and clicking on the _Referenced form_ property you will see that the newly created form definition is now attached to the User task. When clicking on the _Form_ tab in the header of the Modeler application, all form definitions available in the model repository are shown. image::images/flowable_modeler_formoverview_screen.png[align=""center""] You can preview every form definition by opening the details view of a form definition. In the details view, the form name, key and description can be edited and the history of form models is available. You can also duplicate the form definition to create a new form definition with the same form fields. Now let's open the vacation request process model in the BPMN editor again and add a Script task to the process model, that will calculate the number of days between the vacation start and end dates. Click on the _Script format_ property and fill in a value of _groovy_ to instruct the Flowable engine to use the Groovy scripting engine. Now click on the _Script_ property and fill in the script that calculates the number of days. image::images/flowable_modeler_script_popup.png[align=""center"", width=""600""] Now we have a _amountOfVacationDays_ process variable we can add a Decision task to the process model. A decision task can be used to execute a DMN decision table in the Flowable DMN engine. Through the _Decision table reference_ property, a new decision table model can be created and the DMN editor is opened. image::images/flowable_modeler_dmneditor_screen.png[align=""center""] The DMN editor provides a table editor with input columns, where input conditions can be defined with the process variables available in the process context, and output columns, where output variable values can be defined. In this very simple example there's one input column using the _amountOfVacationDays_ variable that checks if it's less than 10 or higher or equal to 10. When the amount of days is less than 10, an output variable _managerApprovalNeeded_ is returned with value false, and otherwise a value of true is returned. You can define multiple input columns and have multiple input conditions per rule. It's also possible to leave an input column empty, which means that it's evaluated to true for that part of the rule. You can define one or multiple output variables. Another important part of the DMN decision table definition is the hit policy. Currently, Flowable supports the First and Any hit policy. With the First hit policy, when the first rule is found that evaluates to true the DMN execution will stop and its output variables are returned. For the Any hit policy, all rules will be executed and the output variables for the last rule that evaluates to true are returned. When the DMN editor is saved and closed, the Modeler application navigates back to the BPMN editor and the newly created DMN decision table is now attached to the Decision task. The decision task will be generated in the BPMN XML like; [source,xml,linenums] ---- ---- With the _managerApprovalNeeded_ variable available in the process instance context, we can now create an exclusive gateway with a sequence flow condition that evaluates the calculated value of the DMN Engine. image::images/flowable_modeler_sequenceflowcondition_popup.png[align=""center"", width=""500""] The full BPMN process model now looks like this: image::images/flowable_modeler_vacationrequest_screen.png[align=""center""] With the process model completed, we can now create an app definition that combines one or more process models with all their associated models (for example, decision tables and form definitions) into a single artifact. An app definition can be exported as a BAR file (zip format) that can be deployed on the Flowable engine. When creating a vacation request app definition, the app editor will look something like the screen below. image::images/flowable_modeler_appeditor_screen.png[align=""center""] In the app editor, an icon and a theme color can be selected that will be used in the Flowable Task application to show the application in the dashboard. The important step is to add the vacation request process model, and by selecting the process model, automatically include any form definitions and DMN decision tables. image::images/flowable_modeler_modelselection_popup.png[align=""center""] A process model can be selected by clicking on the model thumbnail. When one or more models are selected, you can close the popup, save the app definition and close it. When navigating to the details view of the newly created vacation request app definition, the following details screen is shown: image::images/flowable_modeler_appdetails_screen.png[align=""center""] From this view, you can download the app definition in two different formats. The first download button (with the arrow pointing downwards) can be used to download the app definition with the JSON model files for each included model. This makes it easy to share app definitions between different Flowable Modeler applications. The second download button (with the arrow point to upper right) will provide a BAR file of the app definition models, which can be deployed on the Flowable engine. In the BAR file, only the deployable artifacts are included, such as the BPMN 2.0 XML file and the DMN XML file, and not the JSON model files. All files in a BAR file deployed on a Flowable engine are stored in the database, so therefore only the deployable files are included. From the app definition details view, you can also _Publish_ the app definition directly to the Flowable engine. The Flowable Modeler uses the URL defined in the application.properties file with the _flowable.modeler.app.deployment-api-url_ property key. By default, the deployment URL is configured so the app definition will be deployed on the Flowable Task application when it's running. However, this can be changed to use the Flowable REST application, for example. Make sure the Flowable Task application is running and click on the _Publish_ button. The app definition is now deployed as a BAR file to the Flowable Task application. This are the Modeler UI App specific properties. .Modeler UI App Properties [cols=""4*"",options=""header""] |=============== |Property name |Old Property |Default value |Description |flowable.modeler.app.data-source-prefix |datasource.prefix |- |The prefix for the database tables. |flowable.modeler.app.deployment-api-url |deployment.api.url |http://localhost:8080/flowable-task/app-api |The root URI to the REST services of the Flowable engine, used by the Flowable Modeler application to deploy the application definition BAR file to the engine. Default url for the Flowable Task application is http://localhost:8080/flowable-task/app-api |flowable.modeler.app.rest-enabled |rest.modeler-app.enabled |true |Enables the REST API (this is not the REST api used by the UI, but an api that's available over basic auth authentication). |=============== [[flowableTaskApp]] === Flowable Task application The Flowable Task application is the runtime application of the Flowable project and includes the Flowable BPMN, DMN, Form and Content engines by default. With the Flowable Task application, new process instances can be started, tasks can be completed, task forms can be rendered and so on. In the previous section, the vacation request app definition was deployed on the Flowable Task application REST API, and through that deployed on the Flowable engine. If you look in the Flowable database, you can see a new deployment entry has been added to the ACT_RE_DEPLOYMENT table for the BPMN Engine. Also, new entries haven been created in the ACT_DMN_DEPLOYMENT and ACT_FO_FORM_DEPLOYMENT tables for the DMN and Form engines. On the dashboard on link:$$http://localhost:8080/flowable-task$$[http://localhost:8080/flowable-task], you can see a vacation request app in addition to the default Task app, and any other apps that have been deployed to the Flowable engine already. image::images/flowable_task_dashboard_screen.png[align=""center""] When clicking on the vacation request app, the task list for the logged-in user is shown (which is probably empty for now). image::images/flowable_task_tasklist_screen.png[align=""center""] When clicking on the _Processes_ tab you can choose to start a new process instance by clicking on the _Start a process_ button. The list of available process definitions within the context of this app definition is now displayed. In the general Task app this works in a similar way, but in the Task app, all process definitions deployed on the Flowable engine are shown. After selecting the vacation request process definition, the _Start process_ button can be clicked to start a new vacation request process instance. The Flowable Task application automatically navigates to the process instance details view. You can see the _Provide vacation information_ task is active and, for example, comments can be added and the process instance state can be shown diagrammatically using the _Show diagram_ button. image::images/flowable_task_processdetails_screen.png[align=""center""] When navigating to the task list, you can also see the _Provide vacation information_ task listed there as well. The task details are shown in this view, with the vacation info form being rendered. You can also switch to the details view by clicking on the _Show details_ button. In the details view, comments can be added, users can involved in the task and attachments can be added to the task. You can also change the due date and the assignee of a task. image::images/flowable_task_taskdetails_screen.png[align=""center""] Let's fill in the form and complete the task. First, select a start date and end date that have more than 10 days in between, so we can validate that a _Manager approval_ task is being generated. After filling in the vacation info form and clicking the _Complete_ button, the Flowable task app navigates directly to the _Manager approval_ task view. When you also complete this task (without a task form), the process instance is completed. When navigating to the _Processes_ tab and clicking on the _Showing running processes_ section, you can select an option to show completed process instances. The list of completed process instances is now shown and when clicking on the just completed vacation request process you can see the two completed tasks. image::images/flowable_task_processhistory_screen.png[align=""center""] The completed form of each task is stored in the ACT_FO_FORM_INSTANCE table of the Flowable Form engine. So it's possible to look at the values of each completed form when you navigate to the completed task. image::images/flowable_task_completedform_screen.png[align=""center""] Make sure to switch back to showing running processes instead of the completed ones, otherwise you won't see newly started process instances. You can also filter tasks in the task list view. There are options to search on the name of a task, the task state, only tasks for a specific process definition and change the assignment filter. image::images/flowable_task_taskfilter_screen.png[align=""center"", width=""400""] By default, the assignment filter is set to _Tasks where I am involved_. This doesn't show the tasks where you are a candidate, such as tasks that are available to a specific candidate group before they are assigned to a specific person. To show candidate tasks you can select the _Tasks where I am one of the candidates_ assignment filter option. This are the Task UI App specific properties. .Task UI App Properties [cols=""4*"",options=""header""] |=============== |Property name |Old Property |Default value |Description |flowable.experimental.debugger.enabled |debugger.enabled |false |Whether the process debugger should be enabled. |flowable.task.app.rest-enabled |rest.task-app.enabled |true |Enables the REST API (this is not the REST api used by the UI, but an api that's available over basic auth authentication). |flowable.form-field-validation-enabled | |false |Enable form field validation after form submission on the engine side. |=============== [[flowableAdminApp]] === Flowable Admin application The fourth UI application the Flowable project provides is the Flowable Admin application. This application provides ways to, for example, query deployments in the BPMN, DMN and Form Engines, but also shows the active state of a process instance with its active tasks and process variables. It also provides actions to assign a task to a different assignee and to complete an active task. The Flowable Admin application uses the REST API to communicate with the Flowable engines. By default, it is configured to connect to the Flowable Task REST API, but you can easily change this to use the Flowable REST app REST API instead. When going to link:$$http://localhost:8080/flowable-admin$$[http://localhost:8080/flowable-admin], the configuration screen is shown (which is also available by clicking on the arrow at the top right near the Flowable logo). image:images/flowable_admin_configuration_screen.png[align=""center""] For each engine, the REST endpoint can be configured with the basic authentication values. The configuration is done per engine, because it's possible to, for example, deploy the DMN Engine on a separate server from the BPMN Engine. When the configuration is defined with the correct values, the _Process Engine_ can be selected to administer the Flowable BPMN engine. By default, the deployments of the Flowable BPMN engine are shown. image::images/flowable_admin_deployments_screen.png[align=""center""] You can filter the deployments based on name and tenant identifier. In this view, it's also possible to deploy a new BPMN XML file or BAR file to the Flowable engine. When clicking on one of the deployments, the deployment details view is shown. image::images/flowable_admin_deploymentdetails_screen.png[align=""center""] More details of a deployment are shown here and also the process definitions that are part of this deployment on which you click to get more details. It's also possible to delete a deployment here. When you want to delete a deployed app definition, this is also the way to delete the app definition from the Flowable Task app dashboard. When clicking on one of the process definitions, the process definition details view is shown. image::images/flowable_admin_processdefinitiondetails_screen.png[align=""center""] In the process definition details view, the first page of process instances is shown, together with optional decision table definitions and form definitions that are used in the process definition. For the vacation request process definition, there's one connected decision table and one connected form definition. Clicking on the decision table definition navigates the Flowable Admin application to the DMN engine. You can always navigate back to the Process engine by clicking on the _Parent Deployment ID_ link. In addition to the deployments and definitions, you can also query on process instances, tasks, jobs and event subscriptions in the Process engine. The views all work in a similar way to what's already been described. This are the Admin UI App specific properties .Admin UI App Properties [cols=""4*"",options=""header""] |=============== |Property name |Old Property |Default value |Description |flowable.admin.app.data-source-prefix |datasource.prefix | |The prefix for the database tables. |flowable.admin.app.security.encryption.credentials-i-v-spec |security.encryption.credentials-i-v-spec |- |The string that needs to be used to create an IvParameterSpec object using it's the bytes. |flowable.admin.app.security.encryption.credentials-secret-spec |security.encryption.credentials-secret-spec |- |The string that needs to be used to create a SecretKeySpec using it's bytes. |flowable.admin.app.security.preemptive-basic-authentication | |false |Perform a preemptive basic authentication when issuing requests to the flowable REST API. **NB:** This is an experimental property and might be removed without notice. |=============== In addition to these properties, the Flowable admin application has a few more properties. The full content of the properties file can be viewed on {sc-flowable-ui-admin}/flowable-ui-admin-app/src/main/resources/application.properties[Github]. The additional properties are mainly used for defining the initial values for the REST endpoints for the different engines. The Admin application uses the initial values to make a connection to the Flowable engines, but the values can be overridden in the Admin application configuration view and these values are stored in the __ACT\\_ADM\\_SERVER\\_CONFIG__ table. An example of the BPMN Engine REST properties is shown below: [source,linenums] ---- flowable.admin.app.server-config.process.name=Flowable Process app flowable.admin.app.server-config.process.description=Flowable Process REST config flowable.admin.app.server-config.process.server-address=http://localhost flowable.admin.app.server-config.process.port=8080 flowable.admin.app.server-config.process.context-root=flowable-task flowable.admin.app.server-config.process.rest-root=process-api flowable.admin.app.server-config.process.user-name=admin flowable.admin.app.server-config.process.password=test ---- These values can be used when the Flowable Task app (with all the Flowable engines included) is managed by the Flowable Admin application. .Admin UI App Properties managed by Spring Boot [cols=""2*"",options=""header""] |=============== |Old property |Description |message.reloading.enabled |Using Spring Boot MessageSourceAutoConfiguration. Set the duration with `spring.messages.cache-duration`. |=============== === Internationalization The Flowable UI apps support internationalization (i18n). The project maintains the English translations. It is however possible to provide your own translation files in order to support other languages. The link:$$https://github.com/angular-translate/angular-translate[Angular Translate] library tries to load a specific translation file based on the browser's locale located in the _i18n_ folder (present in each UI module). When a matching translation file cannot be loaded the framework will fallback to the English translation. Mapping multiple browser locale keys to specific translations additional configuration can be provided (located in the Angular app config); [source,linenums] ---- // Initialize angular-translate $translateProvider.useStaticFilesLoader({ prefix: './i18n/', suffix: '.json' }) /* This can be used to map multiple browser language keys to a angular translate language key. */ // .registerAvailableLanguageKeys(['en'], { // 'en-*': 'en' // }) .useCookieStorage() .useSanitizeValueStrategy('sanitizeParameters') .uniformLanguageTag('bcp47') .determinePreferredLanguage(); ---- For example; your browser is configured for English (United States) and provides the language key _en-US_. Without the mapping Angular Translate will try to fetch the corresponding translation file _en-US.json_. (If this is not available it will fallback to 'en' and load the _en.json_ translation file) By uncommenting the _.registerAvailableLanguageKeys_ block you can map _en-US_ (and all other _en_ language keys) to the _en.json_ language file. === Production ready endpoints The https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-endpoints.html[Production ready endpoints] from Spring Boot are present for all applications. To have an overview of all the available Endpoints have a look at the https://docs.spring.io/spring-boot/docs/current/actuator-api/html/[Actuator Web API Documentation]. This properties are set per default: [source,linenums] ----- # Expose all actuator endpoints to the web # They are exposed, but only authenticated users can see /info and /health abd users with access-admin can see the others management.endpoints.web.exposure.include=* # Full health details should only be displayed when a user is authorized management.endpoint.health.show-details=when_authorized # Only users with role access-admin can access full health details management.endpoint.health.roles=access-admin ----- The security is configured in such way that the `info` and `health` endpoint are exposed to all authenticated users. Full details of the `health` endpoint can only be seen by users with the privilege `access-admin`. In case you want to change that you need to configure `management.endpoint.health.show-details`. All the rest of the endpoints are accessing only to users with the `access-admin` privilege. [[custom-bean-deployment]] === Custom bean deployment There are multiple ways of providing custom beans to the Flowable applications. [[custom-bean-deployment-spring-boot-auto]] ==== Using Spring Boot auto configuration The Flowable applications are Spring Boot 2 applications. Which means that normal Spring Boot auto configuration can be used to make the beans to Flowable. This can be done in the following manner ``` package com.your.own.package.configuration; @Configuration @AutoConfigureOrder(Ordered.LOWEST_PRECEDENCE) // Makes sure that this configuration will be processed last by Spring Boot @ConditionalOnBean(type = ""org.flowable.engine.ProcessEngine"") // The configuration will only be used when the ProcessEngine bean is present public class YourOwnConfiguration { @Configuration @ComponentScan (""com.your.own.package.beans"") public static class ComponentScanConfiguration { // This class is needed in order to conditionally perform the component scan (i.e. when the ProcessEngine bean is present) // It is an optional class, in case you don't need component scanning then you don't need to do this } @Bean public CustomBean customBean() { // create your bean } @Bean public EngineConfigurationConfigurer customProcessEngineConfigurationConfigurer() { return engineConfiguration -> { // You can use this to add extra configuration to the process engine } } } ``` Note that when using Spring Boot the configuration class can be under your own package and not under some Flowable package. In order to make this class an auto configuration class a file named `spring.factories` should be created in the `META-INF` folder of your jar. In this file you should add ``` org.springframework.boot.autoconfigure.EnableAutoConfiguration=\\ com.your.own.package.configuration.YourOwnCustomConfiguration ``` In order to use this approach you would need to include your jar in the `WEB-INF/lib` folder of the exploded war. Placing this jar in the lib folder of the servlet container (e.g. Tomcat) is not going to work due to the way Spring proxies the `@Configuration` classes. [[custom-bean-deployment-component-scan]] ==== Component scan Another way to provide custom Spring beans to the Flowable engine is to put them under a certain package and have the Flowable application component scan that package. Based on the used application this package is different: * `org.flowable.rest.app` for the `flowable-rest.war` * `org.flowable.ui.task.application` for the `flowable-task.war` The custom beans can be located in a single JAR and this jar should be present on the classpath when the applications are starting up. Depending where there JAR is placed, the lib folder of the servlet container (e.g. Tomcat) or the `WEB-INF/lib` folder of the exploded war, there are different possibilities. When using the lib folder of the servlet container then the created classes should be self contained, i.e. they should only use classes from within the jar. You can use any of the Spring `@Component` annotations (with the exception of `@Configuration`). The reason for not being able to use `@Configuration` classes is the fact that each configuration class is proxied by Spring with the help of the `ConfigurationClassPostProcessor`. However, the classloader loading the `@Configuration` class does not have access to the needed classes by Spring. When including the jar in the `WEB-INF/lib` folder of the exploded war then `@Configuration` classes and dependencies to other jars is possible. [[custom-bean-deployment-own-spring-boot]] ==== Creating your own Spring Boot application This approach is the most flexible and most powerful approach of all. In order to follow this approach have a look at the <> section of this documentation.",12254,False,2066.6261771612344,median "// Automatically generated by 'openshift-apidocs-gen'. Do not edit. :_content-type: ASSEMBLY [id=""job-batch-v1""] = Job [batch/v1] ifdef::product-title[] include::modules/common-attributes.adoc[] endif::[] toc::[] Description:: + -- Job represents the configuration of a single job. -- Type:: `object` == Specification [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `apiVersion` | `string` | APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources | `kind` | `string` | Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds | `metadata` | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta[`ObjectMeta`] | Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata | `spec` | `object` | JobSpec describes how the job execution will look like. | `status` | `object` | JobStatus represents the current state of a Job. |=== === .spec Description:: + -- JobSpec describes how the job execution will look like. -- Type:: `object` Required:: - `template` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `activeDeadlineSeconds` | `integer` | Specifies the duration in seconds relative to the startTime that the job may be continuously active before the system tries to terminate it; value must be positive integer. If a Job is suspended (at creation or through an update), this timer will effectively be stopped and reset when the Job is resumed again. | `backoffLimit` | `integer` | Specifies the number of retries before marking this job failed. Defaults to 6 | `completionMode` | `string` | CompletionMode specifies how Pod completions are tracked. It can be `NonIndexed` (default) or `Indexed`. `NonIndexed` means that the Job is considered complete when there have been .spec.completions successfully completed Pods. Each Pod completion is homologous to each other. `Indexed` means that the Pods of a Job get an associated completion index from 0 to (.spec.completions - 1), available in the annotation batch.kubernetes.io/job-completion-index. The Job is considered complete when there is one successfully completed Pod for each index. When value is `Indexed`, .spec.completions must be specified and `.spec.parallelism` must be less than or equal to 10^5. In addition, The Pod name takes the form `$(job-name)-$(index)-$(random-string)`, the Pod hostname takes the form `$(job-name)-$(index)`. This field is beta-level. More completion modes can be added in the future. If the Job controller observes a mode that it doesn't recognize, the controller skips updates for the Job. | `completions` | `integer` | Specifies the desired number of successfully finished pods the job should be run with. Setting to nil means that the success of any pod signals the success of all pods, and allows parallelism to have any positive value. Setting to 1 means that parallelism is limited to 1 and the success of that pod signals the success of the job. More info: https://kubernetes.io/docs/concepts/workloads/controllers/jobs-run-to-completion/ | `manualSelector` | `boolean` | manualSelector controls generation of pod labels and pod selectors. Leave `manualSelector` unset unless you are certain what you are doing. When false or unset, the system pick labels unique to this job and appends those labels to the pod template. When true, the user is responsible for picking unique labels and specifying the selector. Failure to pick a unique label may cause this and other jobs to not function correctly. However, You may see `manualSelector=true` in jobs that were created with the old `extensions/v1beta1` API. More info: https://kubernetes.io/docs/concepts/workloads/controllers/jobs-run-to-completion/#specifying-your-own-pod-selector | `parallelism` | `integer` | Specifies the maximum desired number of pods the job should run at any given time. The actual number of pods running in steady state will be less than this number when ((.spec.completions - .status.successful) < .spec.parallelism), i.e. when the work left to do is less than max parallelism. More info: https://kubernetes.io/docs/concepts/workloads/controllers/jobs-run-to-completion/ | `selector` | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.LabelSelector[`LabelSelector`] | A label query over pods that should match the pod count. Normally, the system sets this field for you. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors | `suspend` | `boolean` | Suspend specifies whether the Job controller should create Pods or not. If a Job is created with suspend set to true, no Pods are created by the Job controller. If a Job is suspended after creation (i.e. the flag goes from false to true), the Job controller will delete all active Pods associated with this Job. Users must design their workload to gracefully handle this. Suspending a Job will reset the StartTime field of the Job, effectively resetting the ActiveDeadlineSeconds timer too. Defaults to false. This field is beta-level, gated by SuspendJob feature flag (enabled by default). | `template` | xref:../objects/index.adoc#io.k8s.api.core.v1.PodTemplateSpec[`PodTemplateSpec`] | Describes the pod that will be created when executing a job. More info: https://kubernetes.io/docs/concepts/workloads/controllers/jobs-run-to-completion/ | `ttlSecondsAfterFinished` | `integer` | ttlSecondsAfterFinished limits the lifetime of a Job that has finished execution (either Complete or Failed). If this field is set, ttlSecondsAfterFinished after the Job finishes, it is eligible to be automatically deleted. When the Job is being deleted, its lifecycle guarantees (e.g. finalizers) will be honored. If this field is unset, the Job won't be automatically deleted. If this field is set to zero, the Job becomes eligible to be deleted immediately after it finishes. This field is alpha-level and is only honored by servers that enable the TTLAfterFinished feature. |=== === .status Description:: + -- JobStatus represents the current state of a Job. -- Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `active` | `integer` | The number of actively running pods. | `completedIndexes` | `string` | CompletedIndexes holds the completed indexes when .spec.completionMode = ""Indexed"" in a text format. The indexes are represented as decimal integers separated by commas. The numbers are listed in increasing order. Three or more consecutive numbers are compressed and represented by the first and last element of the series, separated by a hyphen. For example, if the completed indexes are 1, 3, 4, 5 and 7, they are represented as ""1,3-5,7"". | `completionTime` | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.Time[`Time`] | Represents time when the job was completed. It is not guaranteed to be set in happens-before order across separate operations. It is represented in RFC3339 form and is in UTC. The completion time is only set when the job finishes successfully. | `conditions` | `array` | The latest available observations of an object's current state. When a Job fails, one of the conditions will have type ""Failed"" and status true. When a Job is suspended, one of the conditions will have type ""Suspended"" and status true; when the Job is resumed, the status of this condition will become false. When a Job is completed, one of the conditions will have type ""Complete"" and status true. More info: https://kubernetes.io/docs/concepts/workloads/controllers/jobs-run-to-completion/ | `conditions[]` | `object` | JobCondition describes current state of a job. | `failed` | `integer` | The number of pods which reached phase Failed. | `startTime` | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.Time[`Time`] | Represents time when the job controller started processing a job. When a Job is created in the suspended state, this field is not set until the first time it is resumed. This field is reset every time a Job is resumed from suspension. It is represented in RFC3339 form and is in UTC. | `succeeded` | `integer` | The number of pods which reached phase Succeeded. | `uncountedTerminatedPods` | `object` | UncountedTerminatedPods holds UIDs of Pods that have terminated but haven't been accounted in Job status counters. |=== === .status.conditions Description:: + -- The latest available observations of an object's current state. When a Job fails, one of the conditions will have type ""Failed"" and status true. When a Job is suspended, one of the conditions will have type ""Suspended"" and status true; when the Job is resumed, the status of this condition will become false. When a Job is completed, one of the conditions will have type ""Complete"" and status true. More info: https://kubernetes.io/docs/concepts/workloads/controllers/jobs-run-to-completion/ -- Type:: `array` === .status.conditions[] Description:: + -- JobCondition describes current state of a job. -- Type:: `object` Required:: - `type` - `status` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `lastProbeTime` | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.Time[`Time`] | Last time the condition was checked. | `lastTransitionTime` | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.Time[`Time`] | Last time the condition transit from one status to another. | `message` | `string` | Human readable message indicating details about last transition. | `reason` | `string` | (brief) reason for the condition's last transition. | `status` | `string` | Status of the condition, one of True, False, Unknown. | `type` | `string` | Type of job condition, Complete or Failed. |=== === .status.uncountedTerminatedPods Description:: + -- UncountedTerminatedPods holds UIDs of Pods that have terminated but haven't been accounted in Job status counters. -- Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `failed` | `array (string)` | Failed holds UIDs of failed Pods. | `succeeded` | `array (string)` | Succeeded holds UIDs of succeeded Pods. |=== == API endpoints The following API endpoints are available: * `/apis/batch/v1/jobs` - `GET`: list or watch objects of kind Job * `/apis/batch/v1/watch/jobs` - `GET`: watch individual changes to a list of Job. deprecated: use the 'watch' parameter with a list operation instead. * `/apis/batch/v1/namespaces/{namespace}/jobs` - `DELETE`: delete collection of Job - `GET`: list or watch objects of kind Job - `POST`: create a Job * `/apis/batch/v1/watch/namespaces/{namespace}/jobs` - `GET`: watch individual changes to a list of Job. deprecated: use the 'watch' parameter with a list operation instead. * `/apis/batch/v1/namespaces/{namespace}/jobs/{name}` - `DELETE`: delete a Job - `GET`: read the specified Job - `PATCH`: partially update the specified Job - `PUT`: replace the specified Job * `/apis/batch/v1/watch/namespaces/{namespace}/jobs/{name}` - `GET`: watch changes to an object of kind Job. deprecated: use the 'watch' parameter with a list operation instead, filtered to a single item with the 'fieldSelector' parameter. * `/apis/batch/v1/namespaces/{namespace}/jobs/{name}/status` - `GET`: read status of the specified Job - `PATCH`: partially update status of the specified Job - `PUT`: replace status of the specified Job === /apis/batch/v1/jobs .Global query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `allowWatchBookmarks` | `boolean` | allowWatchBookmarks requests watch events with type "BOOKMARK". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. | `continue` | `string` | The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the "next key". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. | `fieldSelector` | `string` | A selector to restrict the list of returned objects by their fields. Defaults to everything. | `labelSelector` | `string` | A selector to restrict the list of returned objects by their labels. Defaults to everything. | `limit` | `integer` | limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. | `pretty` | `string` | If 'true', then the output is pretty printed. | `resourceVersion` | `string` | resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `resourceVersionMatch` | `string` | resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `timeoutSeconds` | `integer` | Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. | `watch` | `boolean` | Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== HTTP method:: `GET` Description:: list or watch objects of kind Job .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#io.k8s.api.batch.v1.JobList[`JobList`] schema | 401 - Unauthorized | Empty |=== === /apis/batch/v1/watch/jobs .Global query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `allowWatchBookmarks` | `boolean` | allowWatchBookmarks requests watch events with type "BOOKMARK". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. | `continue` | `string` | The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the "next key". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. | `fieldSelector` | `string` | A selector to restrict the list of returned objects by their fields. Defaults to everything. | `labelSelector` | `string` | A selector to restrict the list of returned objects by their labels. Defaults to everything. | `limit` | `integer` | limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. | `pretty` | `string` | If 'true', then the output is pretty printed. | `resourceVersion` | `string` | resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `resourceVersionMatch` | `string` | resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `timeoutSeconds` | `integer` | Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. | `watch` | `boolean` | Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== HTTP method:: `GET` Description:: watch individual changes to a list of Job. deprecated: use the 'watch' parameter with a list operation instead. .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.WatchEvent[`WatchEvent`] schema | 401 - Unauthorized | Empty |=== === /apis/batch/v1/namespaces/{namespace}/jobs .Global path parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `namespace` | `string` | object name and auth scope, such as for teams and projects |=== .Global query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `pretty` | `string` | If 'true', then the output is pretty printed. |=== HTTP method:: `DELETE` Description:: delete collection of Job .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `continue` | `string` | The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the "next key". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldSelector` | `string` | A selector to restrict the list of returned objects by their fields. Defaults to everything. | `gracePeriodSeconds` | `integer` | The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. | `labelSelector` | `string` | A selector to restrict the list of returned objects by their labels. Defaults to everything. | `limit` | `integer` | limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. | `orphanDependents` | `boolean` | Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the "orphan" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. | `propagationPolicy` | `string` | Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. | `resourceVersion` | `string` | resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `resourceVersionMatch` | `string` | resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `timeoutSeconds` | `integer` | Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.DeleteOptions[`DeleteOptions`] schema | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.Status[`Status`] schema | 401 - Unauthorized | Empty |=== HTTP method:: `GET` Description:: list or watch objects of kind Job .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `allowWatchBookmarks` | `boolean` | allowWatchBookmarks requests watch events with type "BOOKMARK". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. | `continue` | `string` | The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the "next key". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. | `fieldSelector` | `string` | A selector to restrict the list of returned objects by their fields. Defaults to everything. | `labelSelector` | `string` | A selector to restrict the list of returned objects by their labels. Defaults to everything. | `limit` | `integer` | limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. | `resourceVersion` | `string` | resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `resourceVersionMatch` | `string` | resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `timeoutSeconds` | `integer` | Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. | `watch` | `boolean` | Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#io.k8s.api.batch.v1.JobList[`JobList`] schema | 401 - Unauthorized | Empty |=== HTTP method:: `POST` Description:: create a Job .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldManager` | `string` | fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../workloads_apis/job-batch-v1.adoc#job-batch-v1[`Job`] schema | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../workloads_apis/job-batch-v1.adoc#job-batch-v1[`Job`] schema | 201 - Created | xref:../workloads_apis/job-batch-v1.adoc#job-batch-v1[`Job`] schema | 202 - Accepted | xref:../workloads_apis/job-batch-v1.adoc#job-batch-v1[`Job`] schema | 401 - Unauthorized | Empty |=== === /apis/batch/v1/watch/namespaces/{namespace}/jobs .Global path parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `namespace` | `string` | object name and auth scope, such as for teams and projects |=== .Global query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `allowWatchBookmarks` | `boolean` | allowWatchBookmarks requests watch events with type "BOOKMARK". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. | `continue` | `string` | The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the "next key". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. | `fieldSelector` | `string` | A selector to restrict the list of returned objects by their fields. Defaults to everything. | `labelSelector` | `string` | A selector to restrict the list of returned objects by their labels. Defaults to everything. | `limit` | `integer` | limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. | `pretty` | `string` | If 'true', then the output is pretty printed. | `resourceVersion` | `string` | resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `resourceVersionMatch` | `string` | resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `timeoutSeconds` | `integer` | Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. | `watch` | `boolean` | Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== HTTP method:: `GET` Description:: watch individual changes to a list of Job. deprecated: use the 'watch' parameter with a list operation instead. .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.WatchEvent[`WatchEvent`] schema | 401 - Unauthorized | Empty |=== === /apis/batch/v1/namespaces/{namespace}/jobs/{name} .Global path parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `name` | `string` | name of the Job | `namespace` | `string` | object name and auth scope, such as for teams and projects |=== .Global query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `pretty` | `string` | If 'true', then the output is pretty printed. |=== HTTP method:: `DELETE` Description:: delete a Job .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `gracePeriodSeconds` | `integer` | The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. | `orphanDependents` | `boolean` | Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the "orphan" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. | `propagationPolicy` | `string` | Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.DeleteOptions[`DeleteOptions`] schema | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.Status[`Status`] schema | 202 - Accepted | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.Status[`Status`] schema | 401 - Unauthorized | Empty |=== HTTP method:: `GET` Description:: read the specified Job .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../workloads_apis/job-batch-v1.adoc#job-batch-v1[`Job`] schema | 401 - Unauthorized | Empty |=== HTTP method:: `PATCH` Description:: partially update the specified Job .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldManager` | `string` | fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). | `force` | `boolean` | Force is going to "force" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.Patch[`Patch`] schema | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../workloads_apis/job-batch-v1.adoc#job-batch-v1[`Job`] schema | 201 - Created | xref:../workloads_apis/job-batch-v1.adoc#job-batch-v1[`Job`] schema | 401 - Unauthorized | Empty |=== HTTP method:: `PUT` Description:: replace the specified Job .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldManager` | `string` | fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../workloads_apis/job-batch-v1.adoc#job-batch-v1[`Job`] schema | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../workloads_apis/job-batch-v1.adoc#job-batch-v1[`Job`] schema | 201 - Created | xref:../workloads_apis/job-batch-v1.adoc#job-batch-v1[`Job`] schema | 401 - Unauthorized | Empty |=== === /apis/batch/v1/watch/namespaces/{namespace}/jobs/{name} .Global path parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `name` | `string` | name of the Job | `namespace` | `string` | object name and auth scope, such as for teams and projects |=== .Global query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `allowWatchBookmarks` | `boolean` | allowWatchBookmarks requests watch events with type "BOOKMARK". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. | `continue` | `string` | The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the "next key". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. | `fieldSelector` | `string` | A selector to restrict the list of returned objects by their fields. Defaults to everything. | `labelSelector` | `string` | A selector to restrict the list of returned objects by their labels. Defaults to everything. | `limit` | `integer` | limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. | `pretty` | `string` | If 'true', then the output is pretty printed. | `resourceVersion` | `string` | resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `resourceVersionMatch` | `string` | resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `timeoutSeconds` | `integer` | Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. | `watch` | `boolean` | Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== HTTP method:: `GET` Description:: watch changes to an object of kind Job. deprecated: use the 'watch' parameter with a list operation instead, filtered to a single item with the 'fieldSelector' parameter. .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.WatchEvent[`WatchEvent`] schema | 401 - Unauthorized | Empty |=== === /apis/batch/v1/namespaces/{namespace}/jobs/{name}/status .Global path parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `name` | `string` | name of the Job | `namespace` | `string` | object name and auth scope, such as for teams and projects |=== .Global query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `pretty` | `string` | If 'true', then the output is pretty printed. |=== HTTP method:: `GET` Description:: read status of the specified Job .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../workloads_apis/job-batch-v1.adoc#job-batch-v1[`Job`] schema | 401 - Unauthorized | Empty |=== HTTP method:: `PATCH` Description:: partially update status of the specified Job .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldManager` | `string` | fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch). | `force` | `boolean` | Force is going to "force" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../objects/index.adoc#io.k8s.apimachinery.pkg.apis.meta.v1.Patch[`Patch`] schema | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../workloads_apis/job-batch-v1.adoc#job-batch-v1[`Job`] schema | 201 - Created | xref:../workloads_apis/job-batch-v1.adoc#job-batch-v1[`Job`] schema | 401 - Unauthorized | Empty |=== HTTP method:: `PUT` Description:: replace status of the specified Job .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldManager` | `string` | fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../workloads_apis/job-batch-v1.adoc#job-batch-v1[`Job`] schema | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../workloads_apis/job-batch-v1.adoc#job-batch-v1[`Job`] schema | 201 - Created | xref:../workloads_apis/job-batch-v1.adoc#job-batch-v1[`Job`] schema | 401 - Unauthorized | Empty |=== ",12430,True,2975.2382983442762,median "[[install-config-install-advanced-install]] = Advanced Installation {product-author} {product-version} :data-uri: :icons: :experimental: :toc: macro :toc-title: :prewrap!: toc::[] == Overview A reference configuration implemented using http://www.ansible.com[Ansible] playbooks is available as the _advanced installation_ method for installing a {product-title} cluster. Familiarity with Ansible is assumed, however you can use this configuration as a reference to create your own implementation using the configuration management tool of your choosing. [IMPORTANT] ==== While RHEL Atomic Host is supported for running containerized {product-title} services, the advanced installation method utilizes Ansible, which is not available in RHEL Atomic Host, and must therefore be run from ifdef::openshift-enterprise[] a RHEL 7 system. endif::[] ifdef::openshift-origin[] a supported version of Fedora, CentOS, or RHEL. endif::[] The host initiating the installation does not need to be intended for inclusion in the {product-title} cluster, but it can be. ==== ifdef::openshift-enterprise[] Alternatively, you can use the xref:quick_install.adoc#install-config-install-quick-install[quick installation] method if you prefer an interactive installation experience. endif::[] [NOTE] ==== To install {product-title} as a stand-alone registry, see xref:../../install_config/install/stand_alone_registry.adoc#install-config-installing-stand-alone-registry[Installing a Stand-alone Registry]. ==== [[advanced-before-you-begin]] == Before You Begin Before installing {product-title}, you must first see the xref:../../install_config/install/prerequisites.adoc#install-config-install-prerequisites[Prerequisites] topic to prepare your hosts, which includes verifying system and environment requirements per component type and properly installing and configuring Docker. It also includes installing Ansible version 2.2.0 or later, as the advanced installation method is based on Ansible playbooks and as such requires directly invoking Ansible. If you are interested in installing {product-title} using the containerized method (optional for RHEL but required for RHEL Atomic Host), see xref:../../install_config/install/rpm_vs_containerized.adoc#install-config-install-rpm-vs-containerized[Installing on Containerized Hosts] to ensure that you understand the differences between these methods, then return to this topic to continue. For large-scale installs, including suggestions for optimizing install time, see the xref:../../scaling_performance/install_practices.adoc#scaling-performance-install-best-practices[Scaling and Performance Guide]. After following the instructions in the xref:../../install_config/install/prerequisites.adoc#install-config-install-prerequisites[Prerequisites] topic and deciding between the RPM and containerized methods, you can continue in this topic to xref:configuring-ansible[Configuring Ansible]. [[configuring-ansible]] == Configuring Ansible The *_/etc/ansible/hosts_* file is Ansible's inventory file for the playbook to use during the installation. The inventory file describes the configuration for your {product-title} cluster. You must replace the default contents of the file with your desired configuration. The following sections describe commonly-used variables to set in your inventory file during an advanced installation, followed by example inventory files you can use as a starting point for your installation. The examples describe various environment topographies, including xref:multiple-masters[using multiple masters for high availability]. You can choose an example that matches your requirements, modify it to match your own environment, and use it as your inventory file when xref:running-the-advanced-installation[running the advanced installation]. [[configuring-host-variables]] === Configuring Host Variables To assign environment variables to hosts during the Ansible installation, indicate the desired variables in the *_/etc/ansible/hosts_* file after the host entry in the *[masters]* or *[nodes]* sections. For example: ---- [masters] ec2-52-6-179-239.compute-1.amazonaws.com openshift_public_hostname=ose3-master.public.example.com ---- The following table describes variables for use with the Ansible installer that can be assigned to individual host entries: [[advanced-host-variables]] .Host Variables [options=""header""] |=== |Variable |Purpose |`*openshift_hostname*` |This variable overrides the internal cluster host name for the system. Use this when the system's default IP address does not resolve to the system host name. |`*openshift_public_hostname*` |This variable overrides the system's public host name. Use this for cloud installations, or for hosts on networks using a network address translation (NAT). |`*openshift_ip*` |This variable overrides the cluster internal IP address for the system. Use this when using an interface that is not configured with the default route. |`*openshift_public_ip*` |This variable overrides the system's public IP address. Use this for cloud installations, or for hosts on networks using a network address translation (NAT). |`*containerized*` |If set to *true*, containerized {product-title} services are run on the target master and node hosts instead of installed using RPM packages. If set to *false* or unset, the default RPM method is used. RHEL Atomic Host requires the containerized method, and is automatically selected for you based on the detection of the *_/run/ostree-booted_* file. See xref:../../install_config/install/rpm_vs_containerized.adoc#install-config-install-rpm-vs-containerized[Installing on Containerized Hosts] for more details. ifdef::openshift-enterprise[] Containerized installations are supported starting in {product-title} 3.1.1. endif::[] |`*openshift_node_labels*` |This variable adds labels to nodes during installation. See xref:configuring-node-host-labels[Configuring Node Host Labels] for more details. |`*openshift_node_kubelet_args*` |This variable is used to configure `kubeletArguments` on nodes, such as arguments used in xref:../../admin_guide/garbage_collection.adoc#admin-guide-garbage-collection[container and image garbage collection], and to xref:../../admin_guide/manage_nodes.adoc#configuring-node-resources[specify resources per node]. `kubeletArguments` are key value pairs that are passed directly to the Kubelet that match the http://kubernetes.io/v1.1/docs/admin/kubelet.html[Kubelet's command line arguments]. `kubeletArguments` are not migrated or validated and may become invalid if used. These values override other settings in node configuration which may cause invalid configurations. Example usage: *{'image-gc-high-threshold': ['90'],'image-gc-low-threshold': ['80']}*. |`*openshift_hosted_router_selector*` |Default node selector for automatically deploying router pods. See xref:configuring-node-host-labels[Configuring Node Host Labels] for details. |`*openshift_registry_selector*` |Default node selector for automatically deploying registry pods. See xref:configuring-node-host-labels[Configuring Node Host Labels] for details. |`*openshift_docker_options*` |This variable configures additional Docker options within *_/etc/sysconfig/docker_*, such as options used in xref:../../install_config/install/host_preparation.adoc#managing-docker-container-logs[Managing Container Logs]. Example usage: *""--log-driver json-file --log-opt max-size=1M --log-opt max-file=3""*. |=== [[configuring-cluster-variables]] === Configuring Cluster Variables To assign environment variables during the Ansible install that apply more globally to your {product-title} cluster overall, indicate the desired variables in the *_/etc/ansible/hosts_* file on separate, single lines within the *[OSEv3:vars]* section. For example: ---- [OSEv3:vars] openshift_master_identity_providers=[{'name': 'htpasswd_auth', 'login': 'true', 'challenge': 'true', 'kind': 'HTPasswdPasswordIdentityProvider', 'filename': '/etc/origin/master/htpasswd'}] openshift_master_default_subdomain=apps.test.example.com ---- The following table describes variables for use with the Ansible installer that can be assigned cluster-wide: [[cluster-variables-table]] .Cluster Variables [options=""header""] |=== |Variable |Purpose |`*ansible_ssh_user*` |This variable sets the SSH user for the installer to use and defaults to *root*. This user should allow SSH-based authentication xref:host_preparation.adoc#ensuring-host-access[without requiring a password]. If using SSH key-based authentication, then the key should be managed by an SSH agent. |`*ansible_become*` |If `*ansible_ssh_user*` is not *root*, this variable must be set to *true* and the user must be configured for passwordless *sudo*. |`*debug_level*` a|This variable sets which INFO messages are logged to the `systemd-journald.service`. Set one of the following: * `0` to log errors and warnings only * `2` to log normal information (This is the default level.) * `4` to log debugging-level information * `6` to log API-level debugging information (request / response) * `8` to log body-level API debugging information For more information on debug log levels, see xref:../../install_config/master_node_configuration.adoc#master-node-config-logging-levels[Configuring Logging Levels]. |`*containerized*` |If set to *true*, containerized {product-title} services are run on all target master and node hosts in the cluster instead of installed using RPM packages. If set to *false* or unset, the default RPM method is used. RHEL Atomic Host requires the containerized method, and is automatically selected for you based on the detection of the *_/run/ostree-booted_* file. See xref:../../install_config/install/rpm_vs_containerized.adoc#install-config-install-rpm-vs-containerized[Installing on Containerized Hosts] for more details. ifdef::openshift-enterprise[] Containerized installations are supported starting in {product-title} 3.1.1. endif::[] |`*openshift_master_cluster_hostname*` |This variable overrides the host name for the cluster, which defaults to the host name of the master. |`*openshift_master_cluster_public_hostname*` |This variable overrides the public host name for the cluster, which defaults to the host name of the master. |`*openshift_master_cluster_method*` |Optional. This variable defines the HA method when deploying multiple masters. Supports the `native` method. See xref:multiple-masters[Multiple Masters] for more information. |`*openshift_rolling_restart_mode*` |This variable enables rolling restarts of HA masters (i.e., masters are taken down one at a time) when xref:../upgrading/automated_upgrades.adoc#running-the-upgrade-playbook-directly[running the upgrade playbook directly]. It defaults to `services`, which allows rolling restarts of services on the masters. It can instead be set to `system`, which enables rolling, full system restarts and also works for single master clusters. |`*os_sdn_network_plugin_name*` |This variable configures which xref:../../architecture/additional_concepts/sdn.adoc#architecture-additional-concepts-sdn[OpenShift SDN plug-in] to use for the pod network, which defaults to *redhat/openshift-ovs-subnet* for the standard SDN plug-in. Set the variable to *redhat/openshift-ovs-multitenant* to use the multitenant plug-in. |`*openshift_master_identity_providers*` |This variable overrides the xref:../../install_config/configuring_authentication.adoc#install-config-configuring-authentication[identity provider], which defaults to xref:../../install_config/configuring_authentication.adoc#DenyAllPasswordIdentityProvider[Deny All]. |`*openshift_master_named_certificates*` .2+.^|These variables are used to configure xref:../../install_config/certificate_customization.adoc#install-config-certificate-customization[custom certificates] which are deployed as part of the installation. See xref:advanced-install-custom-certificates[Configuring Custom Certificates] for more information. |`*openshift_master_overwrite_named_certificates*` |`*openshift_master_session_name*` .4+.^|These variables override defaults for xref:../../install_config/configuring_authentication.adoc#session-options[session options] in the OAuth configuration. See xref:advanced-install-session-options[Configuring Session Options] for more information. |`*openshift_master_session_max_seconds*` |`*openshift_master_session_auth_secrets*` |`*openshift_master_session_encryption_secrets*` |`*openshift_master_portal_net*` |This variable configures the subnet in which xref:../../architecture/core_concepts/pods_and_services.adoc#services[services] will be created within the xref:../../architecture/additional_concepts/sdn.adoc#architecture-additional-concepts-sdn[{product-title} SDN]. This network block should be private and must not conflict with any existing network blocks in your infrastructure to which pods, nodes, or the master may require access to, or the installation will fail. Defaults to *172.30.0.0/16*, and *cannot* be re-configured after deployment. If changing from the default, avoid *172.16.0.0/16*, which the *docker0* network bridge uses by default, or modify the *docker0* network. |`*openshift_master_default_subdomain*` |This variable overrides the default subdomain to use for exposed xref:../../architecture/core_concepts/routes.adoc#architecture-core-concepts-routes[routes]. |`*openshift_node_proxy_mode*` |This variable specifies the xref:../../architecture/core_concepts/pods_and_services.adoc#service-proxy-mode[service proxy mode] to use: either *iptables* for the default, pure-*iptables* implementation, or *userspace* for the user space proxy. |`*osm_default_node_selector*` |This variable overrides the node selector that projects will use by default when placing pods. |`*osm_cluster_network_cidr*` | This variable overrides the xref:../../architecture/additional_concepts/sdn.adoc#sdn-design-on-masters[SDN cluster network] CIDR block. This is the network from which pod IPs are assigned. This network block should be a private block and must not conflict with existing network blocks in your infrastructure to which pods, nodes, or the master may require access. Defaults to *10.128.0.0/14* and *cannot* be arbitrarily re-configured after deployment, although certain changes to it can be made in the xref:../configuring_sdn.adoc#configuring-the-pod-network-on-masters[SDN master configuration]. |`*osm_host_subnet_length*` |This variable specifies the size of the per host subnet allocated for pod IPs by xref:../../architecture/additional_concepts/sdn.adoc#sdn-design-on-masters[{product-title} SDN]. Defaults to *9* which means that a subnet of size /23 is allocated to each host; for example, given the default 10.128.0.0/14 cluster network, this will allocate 10.128.0.0/23, 10.128.2.0/23, 10.128.4.0/23, and so on. This *cannot* be re-configured after deployment. |`*openshift_use_flannel*` |This variable enables *flannel* as an alternative networking layer instead of the default SDN. If enabling *flannel*, disable the default SDN with the *openshift_use_openshift_sdn* variable. For more information, see xref:../configuring_sdn.adoc#using-flannel[Using Flannel]. |`*openshift_docker_additional_registries*` |{product-title} adds the specified additional registry or registries to the Docker configuration. |`*openshift_docker_insecure_registries*` |{product-title} adds the specified additional insecure registry or registries to the Docker configuration. |`*openshift_docker_blocked_registries*` |{product-title} adds the specified blocked registry or registries to the Docker configuration. |`*openshift_hosted_metrics_public_url*` |This variable sets the host name for integration with the metrics console. The default is `*https://hawkular-metrics.{{openshift_master_default_subdomain}}/hawkular/metrics*` If you alter this variable, ensure the host name is accessible via your router. |=== [[advanced-install-configuring-registry-location]] === Configuring a Registry Location If you are using an image registry other than the default at `registry.access.redhat.com`, specify the desired registry within the *_/etc/ansible/hosts_* file. ---- oreg_url=example.com/openshift3/ose-${component}:${version} openshift_examples_modify_imagestreams=true ---- .Registry Variables [options=""header""] |=== |Variable |Purpose |`*oreg_url*` |Set to the alternate image location. Necessary if you are not using the default registry at `registry.access.redhat.com`. |`*openshift_examples_modify_imagestreams*` |Set to `true` if pointing to a registry other than the default. Modifies the image stream location to the value of `*oreg_url*`. |=== [[advanced-install-configuring-global-proxy]] === Configuring Global Proxy Options If your hosts require use of a HTTP or HTTPS proxy in order to connect to external hosts, there are many components that must be configured to use the proxy, including masters, Docker, and builds. Node services only connect to the master API requiring no external access and therefore do not need to be configured to use a proxy. In order to simplify this configuration, the following Ansible variables can be specified at a cluster or host level to apply these settings uniformly across your environment. [NOTE] ==== See xref:../../install_config/build_defaults_overrides.adoc#install-config-build-defaults-overrides[Configuring Global Build Defaults and Overrides] for more information on how the proxy environment is defined for builds. ==== .Cluster Proxy Variables [options=""header""] |=== |Variable |Purpose |`*openshift_http_proxy*` |This variable specifies the `*HTTP_PROXY*` environment variable for masters and the Docker daemon. |`*openshift_https_proxy*` |This variable specifices the `*HTTPS_PROXY*` environment variable for masters and the Docker daemon. |`*openshift_no_proxy*` |This variable is used to set the `*NO_PROXY*` environment variable for masters and the Docker daemon. This value should be set to a comma separated list of host names or wildcard host names that should not use the defined proxy. This list will be augmented with the list of all defined {product-title} host names by default. |`*openshift_generate_no_proxy_hosts*` |This boolean variable specifies whether or not the names of all defined OpenShift hosts and `pass:[*.cluster.local]` should be automatically appended to the `*NO_PROXY*` list. Defaults to *true*; set it to *false* to override this option. |`*openshift_builddefaults_http_proxy*` |This variable defines the `*HTTP_PROXY*` environment variable inserted into builds using the `*BuildDefaults*` admission controller. If `*openshift_http_proxy*` is set, this variable will inherit that value; you only need to set this if you want your builds to use a different value. |`*openshift_builddefaults_https_proxy*` |This variable defines the `*HTTPS_PROXY*` environment variable inserted into builds using the `*BuildDefaults*` admission controller. If `*openshift_https_proxy*` is set, this variable will inherit that value; you only need to set this if you want your builds to use a different value. |`*openshift_builddefaults_no_proxy*` |This variable defines the `*NO_PROXY*` environment variable inserted into builds using the `*BuildDefaults*` admission controller. If `*openshift_no_proxy*` is set, this variable will inherit that value; you only need to set this if you want your builds to use a different value. |`*openshift_builddefaults_git_http_proxy*` |This variable defines the HTTP proxy used by `git clone` operations during a build, defined using the `*BuildDefaults*` admission controller. If `*openshift_builddefaults_http_proxy*` is set, this variable will inherit that value; you only need to set this if you want your `git clone` operations to use a different value. |`*openshift_builddefaults_git_https_proxy*` |This variable defines the HTTPS proxy used by `git clone` operations during a build, defined using the `*BuildDefaults*` admission controller. If `*openshift_builddefaults_https_proxy*` is set, this variable will inherit that value; you only need to set this if you want your `git clone` operations to use a different value. |=== [[configuring-node-host-labels]] === Configuring Node Host Labels You can assign xref:../../architecture/core_concepts/pods_and_services.adoc#labels[labels] to node hosts during the Ansible install by configuring the *_/etc/ansible/hosts_* file. Labels are useful for determining the placement of pods onto nodes using the xref:../../admin_guide/scheduler.adoc#configurable-predicates[scheduler]. Other than *region=infra* (discussed below), the actual label names and values are arbitrary and can be assigned however you see fit per your cluster's requirements. To assign labels to a node host during an Ansible install, use the `*openshift_node_labels*` variable with the desired labels added to the desired node host entry in the *[nodes]* section. In the following example, labels are set for a region called *primary* and a zone called *east*: ---- [nodes] node1.example.com openshift_node_labels=""{'region': 'primary', 'zone': 'east'}"" ---- The `*openshift_router_selector*` and `*openshift_registry_selector*` Ansible settings are set to *region=infra* by default: ---- # default selectors for router and registry services # openshift_router_selector='region=infra' # openshift_registry_selector='region=infra' ---- The default router and registry will be automatically deployed if nodes exist that match the selector settings above. For example: ---- [nodes] node1.example.com openshift_node_labels=""{'region':'infra','zone':'default'}"" ---- [IMPORTANT] ==== The registry and router are only able to run on node hosts with the 'region=infra' label. Ensure that at least one node host in your {product-title} environment has the 'region=infra' label. ==== [[marking-masters-as-unschedulable-nodes]] === Marking Masters as Unschedulable Nodes Any hosts you designate as masters during the installation process should also be configured as nodes by adding them to the *[nodes]* section so that the masters are configured as part of the xref:../../architecture/additional_concepts/networking.adoc#openshift-sdn[{product-title} SDN]. However, in order to ensure that your masters are not burdened with running pods, you can make them xref:../../admin_guide/manage_nodes.adoc#marking-nodes-as-unschedulable-or-schedulable[unschedulable] by adding the `*openshift_schedulable=false*` option any node that is also a master. For example: ---- [nodes] master.example.com openshift_node_labels=""{'region':'infra','zone':'default'}"" openshift_schedulable=false ---- [[advanced-install-session-options]] === Configuring Session Options xref:../../install_config/configuring_authentication.adoc#session-options[Session options] in the OAuth configuration are configurable in the inventory file. By default, Ansible populates a `*sessionSecretsFile*` with generated authentication and encryption secrets so that sessions generated by one master can be decoded by the others. The default location is *_/etc/origin/master/session-secrets.yaml_*, and this file will only be re-created if deleted on all masters. You can set the session name and maximum number of seconds with `*openshift_master_session_name*` and `*openshift_master_session_max_seconds*`: ---- openshift_master_session_name=ssn openshift_master_session_max_seconds=3600 ---- If provided, `*openshift_master_session_auth_secrets*` and `*openshift_master_encryption_secrets*` must be equal length. For `*openshift_master_session_auth_secrets*`, used to authenticate sessions using HMAC, it is recommended to use secrets with 32 or 64 bytes: ---- openshift_master_session_auth_secrets=['DONT+USE+THIS+SECRET+b4NV+pmZNSO'] ---- For `*openshift_master_encryption_secrets*`, used to encrypt sessions, secrets must be 16, 24, or 32 characters long, to select AES-128, AES-192, or AES-256: ---- openshift_master_session_encryption_secrets=['DONT+USE+THIS+SECRET+b4NV+pmZNSO'] ---- [[advanced-install-custom-certificates]] === Configuring Custom Certificates xref:../../install_config/certificate_customization.adoc#install-config-certificate-customization[Custom serving certificates] for the public host names of the {product-title} API and xref:../../architecture/infrastructure_components/web_console.adoc#architecture-infrastructure-components-web-console[web console] can be deployed during an advanced installation and are configurable in the inventory file. [NOTE] ==== Custom certificates should only be configured for the host name associated with the `*publicMasterURL*` which can be set using `*openshift_master_cluster_public_hostname*`. Using a custom serving certificate for the host name associated with the `*masterURL*` (*`openshift_master_cluster_hostname`*) will result in TLS errors as infrastructure components will attempt to contact the master API using the internal `*masterURL*` host. ==== Certificate and key file paths can be configured using the `*openshift_master_named_certificates*` cluster variable: ---- openshift_master_named_certificates=[{""certfile"": ""/path/to/custom1.crt"", ""keyfile"": ""/path/to/custom1.key""}] ---- File paths must be local to the system where Ansible will be run. Certificates are copied to master hosts and are deployed within the *_/etc/origin/master/named_certificates/_* directory. Ansible detects a certificate's `Common Name` and `Subject Alternative Names`. Detected names can be overridden by providing the `*""names""*` key when setting `*openshift_master_named_certificates*`: ---- openshift_master_named_certificates=[{""certfile"": ""/path/to/custom1.crt"", ""keyfile"": ""/path/to/custom1.key"", ""names"": [""public-master-host.com""]}] ---- Certificates configured using `*openshift_master_named_certificates*` are cached on masters, meaning that each additional Ansible run with a different set of certificates results in all previously deployed certificates remaining in place on master hosts and within the master configuration file. If you would like `*openshift_master_named_certificates*` to be overwritten with the provided value (or no value), specify the `*openshift_master_overwrite_named_certificates*` cluster variable: ---- openshift_master_overwrite_named_certificates=true ---- For a more complete example, consider the following cluster variables in an inventory file: ---- openshift_master_cluster_method=native openshift_master_cluster_hostname=lb.openshift.com openshift_master_cluster_public_hostname=custom.openshift.com ---- To overwrite the certificates on a subsequent Ansible run, you could set the following: ---- openshift_master_named_certificates=[{""certfile"": ""/root/STAR.openshift.com.crt"", ""keyfile"": ""/root/STAR.openshift.com.key"", ""names"": [""custom.openshift.com""]}] openshift_master_overwrite_named_certificates=true ---- [[advanced-install-cluster-metrics]] == Configuring Cluster Metrics Cluster metrics are not set to automatically deploy by default. Set the following to enable cluster metrics when using the advanced install: ---- [OSEv3:vars] openshift_hosted_metrics_deploy=true ---- === Metrics Storage The `*openshift_metrics_cassandra_storage_type*` variable must be set in order to use persistent storage. If `*openshift_metrics_cassandra_storage_type*` is not set, then cluster metrics data is stored in an `EmptyDir` volume, which will be deleted when the Cassandra pod terminates. There are three options for enabling cluster metrics storage when using the advanced install: *Option A - NFS Host Group* When the following variables are set, an NFS volume is created during an advanced install with path *_/_* on the host within the `[nfs]` host group. For example, the volume path using these options would be *_/exports/metrics_*: ---- [OSEv3:vars] openshift_hosted_metrics_storage_kind=nfs openshift_hosted_metrics_storage_access_modes=['ReadWriteOnce'] openshift_hosted_metrics_storage_nfs_directory=/exports openshift_hosted_metrics_storage_nfs_options='*(rw,root_squash)' openshift_hosted_metrics_storage_volume_name=metrics openshift_hosted_metrics_storage_volume_size=10Gi ---- *Option B - External NFS Host* To use an external NFS volume, one must already exist with a path of *_/_* on the storage host. ---- [OSEv3:vars] openshift_hosted_metrics_storage_kind=nfs openshift_hosted_metrics_storage_access_modes=['ReadWriteOnce'] openshift_hosted_metrics_storage_host=nfs.example.com openshift_hosted_metrics_storage_nfs_directory=/exports openshift_hosted_metrics_storage_volume_name=metrics openshift_hosted_metrics_storage_volume_size=10Gi ---- The remote volume path using the following options would be *_nfs.example.com:/exports/metrics_*. *Option C - Dynamic* Use the following variable if your {product-title} environment supports dynamic volume provisioning for your cloud platform: ---- [OSEv3:vars] #openshift_metrics_cassandra_storage_type=dynamic ---- [[advanced-install-cluster-logging]] == Configuring Cluster Logging Cluster logging is not set to automatically deploy by default. Set the following to enable cluster logging when using the advanced installation method: ---- [OSEv3:vars] openshift_hosted_logging_deploy=true ---- [[advanced-installation-logging-storage]] === Logging Storage The `openshift_hosted_logging_storage_kind` variable must be set in order to use persistent storage. If `openshift_hosted_logging_storage_kind` is not set, then cluster logging data is stored in an `emptyDir` volume, which will be deleted when the Elasticsearch pod terminates. There are three options for enabling cluster logging storage when using the advanced install: *Option A - NFS Host Group* When the following variables are set, an NFS volume is created during an advanced install with path *_/_* on the host within the `[nfs]` host group. For example, the volume path using these options would be *_/exports/logging_*: ---- [OSEv3:vars] openshift_hosted_logging_storage_kind=nfs openshift_hosted_logging_storage_access_modes=['ReadWriteOnce'] openshift_hosted_logging_storage_nfs_directory=/exports openshift_hosted_logging_storage_nfs_options='*(rw,root_squash)' openshift_hosted_logging_storage_volume_name=logging openshift_hosted_logging_storage_volume_size=10Gi ---- *Option B - External NFS Host* To use an external NFS volume, one must already exist with a path of *_/_* on the storage host. ---- [OSEv3:vars] openshift_hosted_logging_storage_kind=nfs openshift_hosted_logging_storage_access_modes=['ReadWriteOnce'] openshift_hosted_logging_storage_host=nfs.example.com openshift_hosted_logging_storage_nfs_directory=/exports openshift_hosted_logging_storage_volume_name=logging openshift_hosted_logging_storage_volume_size=10Gi ---- The remote volume path using the following options would be *_nfs.example.com:/exports/logging_*. *Option C - Dynamic* Use the following variable if your {product-title} environment supports dynamic volume provisioning for your cloud platform: ---- [OSEv3:vars] #openshift_hosted_logging_storage_kind=dynamic ---- [[single-master]] == Single Master Examples You can configure an environment with a single master and multiple nodes, and either a single or multiple number of external *etcd* hosts. [NOTE] ==== Moving from a single master cluster to multiple masters after installation is not supported. ==== [[single-master-multi-node-ai]] *Single Master and Multiple Nodes* The following table describes an example environment for a single xref:../../architecture/infrastructure_components/kubernetes_infrastructure.adoc#master[master] (with *etcd* on the same host) and two xref:../../architecture/infrastructure_components/kubernetes_infrastructure.adoc#node[nodes]: [options=""header""] |=== |Host Name |Infrastructure Component to Install |*master.example.com* |Master and node |*master.example.com* |etcd |*node1.example.com* .2+.^|Node |*node2.example.com* |=== You can see these example hosts present in the *[masters]* and *[nodes]* sections of the following example inventory file: .Single Master and Multiple Nodes Inventory File ---- # Create an OSEv3 group that contains the masters and nodes groups [OSEv3:children] masters nodes # Set variables common for all OSEv3 hosts [OSEv3:vars] # SSH user, this user should allow ssh based auth without requiring a password ansible_ssh_user=root # If ansible_ssh_user is not root, ansible_become must be set to true #ansible_become=true ifdef::openshift-enterprise[] deployment_type=openshift-enterprise endif::[] ifdef::openshift-origin[] deployment_type=origin endif::[] # uncomment the following to enable htpasswd authentication; defaults to DenyAllPasswordIdentityProvider #openshift_master_identity_providers=[{'name': 'htpasswd_auth', 'login': 'true', 'challenge': 'true', 'kind': 'HTPasswdPasswordIdentityProvider', 'filename': '/etc/origin/master/htpasswd'}] # host group for masters [masters] master.example.com # host group for etcd [etcd] master.example.com # host group for nodes, includes region info [nodes] master.example.com openshift_node_labels=""{'region': 'infra', 'zone': 'default'}"" node1.example.com openshift_node_labels=""{'region': 'primary', 'zone': 'east'}"" node2.example.com openshift_node_labels=""{'region': 'primary', 'zone': 'west'}"" ---- To use this example, modify the file to match your environment and specifications, and save it as *_/etc/ansible/hosts_*. [[single-master-multi-etcd-multi-node-ai]] *Single Master, Multiple etcd, and Multiple Nodes* The following table describes an example environment for a single xref:../../architecture/infrastructure_components/kubernetes_infrastructure.adoc#master[master], three xref:../../architecture/infrastructure_components/kubernetes_infrastructure.adoc#master[*etcd*] hosts, and two xref:../../architecture/infrastructure_components/kubernetes_infrastructure.adoc#node[nodes]: [options=""header""] |=== |Host Name |Infrastructure Component to Install |*master.example.com* |Master and node |*etcd1.example.com* .3+.^|*etcd* |*etcd2.example.com* |*etcd3.example.com* |*node1.example.com* .2+.^|Node |*node2.example.com* |=== [NOTE] ==== When specifying multiple *etcd* hosts, external *etcd* is installed and configured. Clustering of {product-title}'s embedded *etcd* is not supported. ==== You can see these example hosts present in the *[masters]*, *[nodes]*, and *[etcd]* sections of the following example inventory file: .Single Master, Multiple etcd, and Multiple Nodes Inventory File ---- # Create an OSEv3 group that contains the masters, nodes, and etcd groups [OSEv3:children] masters nodes etcd # Set variables common for all OSEv3 hosts [OSEv3:vars] ansible_ssh_user=root ifdef::openshift-enterprise[] deployment_type=openshift-enterprise endif::[] ifdef::openshift-origin[] deployment_type=origin endif::[] # uncomment the following to enable htpasswd authentication; defaults to DenyAllPasswordIdentityProvider #openshift_master_identity_providers=[{'name': 'htpasswd_auth', 'login': 'true', 'challenge': 'true', 'kind': 'HTPasswdPasswordIdentityProvider', 'filename': '/etc/origin/master/htpasswd'}] # host group for masters [masters] master.example.com # host group for etcd [etcd] etcd1.example.com etcd2.example.com etcd3.example.com # host group for nodes, includes region info [nodes] master.example.com openshift_node_labels=""{'region': 'infra', 'zone': 'default'}"" node1.example.com openshift_node_labels=""{'region': 'primary', 'zone': 'east'}"" node2.example.com openshift_node_labels=""{'region': 'primary', 'zone': 'west'}"" ---- To use this example, modify the file to match your environment and specifications, and save it as *_/etc/ansible/hosts_*. [[multiple-masters]] == Multiple Masters Examples You can configure an environment with multiple masters, multiple *etcd* hosts, and multiple nodes. Configuring xref:../../architecture/infrastructure_components/kubernetes_infrastructure.adoc#high-availability-masters[multiple masters for high availability] (HA) ensures that the cluster has no single point of failure. [NOTE] ==== Moving from a single master cluster to multiple masters after installation is not supported. ==== When configuring multiple masters, the advanced installation supports the following high availability (HA) method: [cols=""1,5""] |=== |`native` |Leverages the native HA master capabilities built into {product-title} and can be combined with any load balancing solution. If a host is defined in the *[lb]* section of the inventory file, Ansible installs and configures HAProxy automatically as the load balancing solution. If no host is defined, it is assumed you have pre-configured a load balancing solution of your choice to balance the master API (port 8443) on all master hosts. |=== For your pre-configured load balancing solution, you must have: * A pre-created load balancer VIP configured for SSL passthrough. * A domain name for VIP registered in DNS. ** The domain name will become the value of both `openshift_master_cluster_public_hostname` and `openshift_master_cluster_hostname` in the {product-title} installer. See link:https://github.com/redhat-cop/openshift-playbooks/blob/master/playbooks/installation/load_balancing.adoc[External Load Balancer Integrations] for more information. [NOTE] ==== For more on the high availability master architecture, see xref:../../architecture/infrastructure_components/kubernetes_infrastructure.adoc#master[Kubernetes Infrastructure]. ==== Note the following when using the `native` HA method: - The advanced installation method does not currently support multiple HAProxy load balancers in an active-passive setup. See the https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/Load_Balancer_Administration/ch-lvs-overview-VSA.html[Load Balancer Administration documentation] for post-installation amendments. - In a HAProxy setup, controller manager servers run as standalone processes. They elect their active leader with a lease stored in *etcd*. The lease expires after 30 seconds by default. If a failure happens on an active controller server, it will take up to this number of seconds to elect another leader. The interval can be configured with the `*osm_controller_lease_ttl*` variable. To configure multiple masters, refer to the following section. [[multi-masters-using-native-ha-ai]] *Multiple Masters with Multiple etcd, and Using Native HA* The following describes an example environment for three xref:../../architecture/infrastructure_components/kubernetes_infrastructure.adoc#master[masters], one HAProxy load balancer, three xref:../../architecture/infrastructure_components/kubernetes_infrastructure.adoc#master[*etcd*] hosts, and two xref:../../architecture/infrastructure_components/kubernetes_infrastructure.adoc#node[nodes] using the `native` HA method: [options=""header""] |=== |Host Name |Infrastructure Component to Install |*master1.example.com* .3+.^|Master (clustered using native HA) and node |*master2.example.com* |*master3.example.com* |*lb.example.com* |HAProxy to load balance API master endpoints |*etcd1.example.com* .3+.^|*etcd* |*etcd2.example.com* |*etcd3.example.com* |*node1.example.com* .2+.^|Node |*node2.example.com* |=== [NOTE] ==== When specifying multiple *etcd* hosts, external *etcd* is installed and configured. Clustering of {product-title}'s embedded *etcd* is not supported. ==== You can see these example hosts present in the *[masters]*, *[etcd]*, *[lb]*, and *[nodes]* sections of the following example inventory file: .Multiple Masters Using HAProxy Inventory File ==== ---- # Create an OSEv3 group that contains the master, nodes, etcd, and lb groups. # The lb group lets Ansible configure HAProxy as the load balancing solution. # Comment lb out if your load balancer is pre-configured. [OSEv3:children] masters nodes etcd lb # Set variables common for all OSEv3 hosts [OSEv3:vars] ansible_ssh_user=root ifdef::openshift-enterprise[] deployment_type=openshift-enterprise endif::[] ifdef::openshift-origin[] deployment_type=origin endif::[] # Uncomment the following to enable htpasswd authentication; defaults to # DenyAllPasswordIdentityProvider. #openshift_master_identity_providers=[{'name': 'htpasswd_auth', 'login': 'true', 'challenge': 'true', 'kind': 'HTPasswdPasswordIdentityProvider', 'filename': '/etc/origin/master/htpasswd'}] # Native high availbility cluster method with optional load balancer. # If no lb group is defined installer assumes that a load balancer has # been preconfigured. For installation the value of # openshift_master_cluster_hostname must resolve to the load balancer # or to one or all of the masters defined in the inventory if no load # balancer is present. openshift_master_cluster_method=native openshift_master_cluster_hostname=openshift-cluster.example.com openshift_master_cluster_public_hostname=openshift-cluster.example.com # apply updated node defaults openshift_node_kubelet_args={'pods-per-core': ['10'], 'max-pods': ['250'], 'image-gc-high-threshold': ['90'], 'image-gc-low-threshold': ['80']} # override the default controller lease ttl #osm_controller_lease_ttl=30 # enable ntp on masters to ensure proper failover openshift_clock_enabled=true # host group for masters [masters] master1.example.com master2.example.com master3.example.com # host group for etcd [etcd] etcd1.example.com etcd2.example.com etcd3.example.com # Specify load balancer host [lb] lb.example.com # host group for nodes, includes region info [nodes] master[1:3].example.com openshift_node_labels=""{'region': 'infra', 'zone': 'default'}"" node1.example.com openshift_node_labels=""{'region': 'primary', 'zone': 'east'}"" node2.example.com openshift_node_labels=""{'region': 'primary', 'zone': 'west'}"" ---- ==== To use this example, modify the file to match your environment and specifications, and save it as *_/etc/ansible/hosts_*. [[multi-masters-singel-etcd-using-native-ha]] *Multiple Masters with Master and etcd on the Same Host, and Using Native HA* The following describes an example environment for three xref:../../architecture/infrastructure_components/kubernetes_infrastructure.adoc#master[masters] with xref:../../architecture/infrastructure_components/kubernetes_infrastructure.adoc#master[*etcd*] on each host, one HAProxy load balancer, and two xref:../../architecture/infrastructure_components/kubernetes_infrastructure.adoc#node[nodes] using the `native` HA method: [options=""header""] |=== |Host Name |Infrastructure Component to Install |*master1.example.com* .3+.^|Master (clustered using native HA) and node with etcd on each host |*master2.example.com* |*master3.example.com* |*lb.example.com* |HAProxy to load balance API master endpoints |*node1.example.com* .2+.^|Node |*node2.example.com* |=== You can see these example hosts present in the *[masters]*, *[etcd]*, *[lb]*, and *[nodes]* sections of the following example inventory file: ==== ---- # Create an OSEv3 group that contains the master, nodes, etcd, and lb groups. # The lb group lets Ansible configure HAProxy as the load balancing solution. # Comment lb out if your load balancer is pre-configured. [OSEv3:children] masters nodes etcd lb # Set variables common for all OSEv3 hosts [OSEv3:vars] ansible_ssh_user=root deployment_type=openshift-enterprise # Uncomment the following to enable htpasswd authentication; defaults to # DenyAllPasswordIdentityProvider. #openshift_master_identity_providers=[{'name': 'htpasswd_auth', 'login': 'true', 'challenge': 'true', 'kind': 'HTPasswdPasswordIdentityProvider', 'filename': '/etc/origin/master/htpasswd'}] # Native high availbility cluster method with optional load balancer. # If no lb group is defined installer assumes that a load balancer has # been preconfigured. For installation the value of # openshift_master_cluster_hostname must resolve to the load balancer # or to one or all of the masters defined in the inventory if no load # balancer is present. openshift_master_cluster_method=native openshift_master_cluster_hostname=openshift-cluster.example.com openshift_master_cluster_public_hostname=openshift-cluster.example.com # override the default controller lease ttl #osm_controller_lease_ttl=30 # host group for masters [masters] master1.example.com master2.example.com master3.example.com # host group for etcd [etcd] master1.example.com master2.example.com master3.example.com # Specify load balancer host [lb] lb.example.com # host group for nodes, includes region info [nodes] master[1:3].example.com openshift_node_labels=""{'region': 'infra', 'zone': 'default'}"" node1.example.com openshift_node_labels=""{'region': 'primary', 'zone': 'east'}"" node2.example.com openshift_node_labels=""{'region': 'primary', 'zone': 'west'}"" ---- ==== To use this example, modify the file to match your environment and specifications, and save it as *_/etc/ansible/hosts_*. [[running-the-advanced-installation]] == Running the Advanced Installation After you have xref:configuring-ansible[configured Ansible] by defining an inventory file in *_/etc/ansible/hosts_*, you can run the advanced installation using the following playbook: ---- ifdef::openshift-enterprise[] # ansible-playbook /usr/share/ansible/openshift-ansible/playbooks/byo/config.yml endif::[] ifdef::openshift-origin[] # ansible-playbook ~/openshift-ansible/playbooks/byo/config.yml endif::[] ---- If for any reason the installation fails, before re-running the installer, see xref:installer-known-issues[Known Issues] to check for any specific instructions or workarounds. [[advanced-verifying-the-installation]] == Verifying the Installation // tag::verifying-the-installation[] After the installation completes: . Verify that the master is started and nodes are registered and reporting in *Ready* status. *On the master host*, run the following as root: ---- # oc get nodes NAME STATUS AGE master.example.com Ready,SchedulingDisabled 165d node1.example.com Ready 165d node2.example.com Ready 165d ---- To verify that the web console is installed correctly, use the master host name and the console port number to access the console with a web browser. For example, for a master host with a hostname of `master.openshift.com` and using the default port of `8443`, the web console would be found at: ---- https://master.openshift.com:8443/console ---- Now that the install has been verified, run the following command on each master and node host to add the *atomic-openshift* packages back to the list of yum excludes on the host: ---- # atomic-openshift-excluder exclude ---- // end::verifying-the-installation[] [NOTE] ==== The default port for the console is `8443`. If this was changed during the installation, the port can be found at *openshift_master_console_port* in the *_/etc/ansible/hosts_* file. ==== *Multiple etcd Hosts* If you installed multiple *etcd* hosts: . On a master host, verify the *etcd* cluster health, substituting for the FQDNs of your *etcd* hosts in the following: + ---- # etcdctl -C \\ https://etcd1.example.com:2379,https://etcd2.example.com:2379,https://etcd3.example.com:2379 \\ --ca-file=/etc/origin/master/master.etcd-ca.crt \\ --cert-file=/etc/origin/master/master.etcd-client.crt \\ --key-file=/etc/origin/master/master.etcd-client.key cluster-health ---- . Also verify the member list is correct: + ---- # etcdctl -C \\ https://etcd1.example.com:2379,https://etcd2.example.com:2379,https://etcd3.example.com:2379 \\ --ca-file=/etc/origin/master/master.etcd-ca.crt \\ --cert-file=/etc/origin/master/master.etcd-client.crt \\ --key-file=/etc/origin/master/master.etcd-client.key member list ---- *Multiple Masters Using HAProxy* If you installed multiple masters using HAProxy as a load balancer, browse to the following URL according to your *[lb]* section definition and check HAProxy's status: ---- http://:9000 ---- You can verify your installation by consulting the https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/Load_Balancer_Administration/ch-haproxy-setup-VSA.html[HAProxy Configuration documentation]. [[uninstalling-advanced]] == Uninstalling {product-title} You can uninstall {product-title} hosts in your cluster by running the *_uninstall.yml_* playbook. This playbook deletes {product-title} content installed by Ansible, including: - Configuration - Containers - Default templates and image streams - Images - RPM packages The playbook will delete content for any hosts defined in the inventory file that you specify when running the playbook. If you want to uninstall {product-title} across all hosts in your cluster, run the playbook using the inventory file you used when installing {product-title} initially or ran most recently: ---- ifdef::openshift-enterprise[] # ansible-playbook [-i /path/to/file] \\ /usr/share/ansible/openshift-ansible/playbooks/adhoc/uninstall.yml endif::[] ifdef::openshift-origin[] # ansible-playbook [-i /path/to/file] \\ ~/openshift-ansible/playbooks/adhoc/uninstall.yml endif::[] ---- [[uninstalling-nodes-advanced]] === Uninstalling Nodes You can also uninstall node components from specific hosts using the *_uninstall.yml_* playbook while leaving the remaining hosts and cluster alone: [WARNING] ==== This method should only be used when attempting to uninstall specific node hosts and not for specific masters or etcd hosts, which would require further configuration changes within the cluster. ==== . First follow the steps in xref:../../admin_guide/manage_nodes.adoc#deleting-nodes[Deleting Nodes] to remove the node object from the cluster, then continue with the remaining steps in this procedure. . Create a different inventory file that only references those hosts. For example, to only delete content from one node: + ---- [OSEv3:children] nodes <1> [OSEv3:vars] ansible_ssh_user=root ifdef::openshift-enterprise[] deployment_type=openshift-enterprise endif::[] ifdef::openshift-origin[] deployment_type=origin endif::[] [nodes] node3.example.com openshift_node_labels=""{'region': 'primary', 'zone': 'west'}"" <2> ---- <1> Only include the sections that pertain to the hosts you are interested in uninstalling. <2> Only include hosts that you want to uninstall. . Specify that new inventory file using the `-i` option when running the *_uninstall.yml_* playbook: + ---- ifdef::openshift-enterprise[] # ansible-playbook -i /path/to/new/file \\ /usr/share/ansible/openshift-ansible/playbooks/adhoc/uninstall.yml endif::[] ifdef::openshift-origin[] # ansible-playbook -i /path/to/new/file \\ ~/openshift-ansible/playbooks/adhoc/uninstall.yml endif::[] ---- When the playbook completes, all {product-title} content should be removed from any specified hosts. [[installer-known-issues]] == Known Issues The following are known issues for specified installation configurations. *Multiple Masters* - On failover, it is possible for the controller manager to overcorrect, which causes the system to run more pods than what was intended. However, this is a transient event and the system does correct itself over time. See https://github.com/kubernetes/kubernetes/issues/10030 for details. - On failure of the Ansible installer, you must start from a clean operating system installation. If you are using virtual machines, start from a fresh image. If you are using bare metal machines, run the following on all hosts: + ---- # yum -y remove openshift openshift-* etcd docker docker-common # rm -rf /etc/origin /var/lib/openshift /etc/etcd \\ /var/lib/etcd /etc/sysconfig/atomic-openshift* /etc/sysconfig/docker* \\ /root/.kube/config /etc/ansible/facts.d /usr/share/openshift ---- == What's Next? Now that you have a working {product-title} instance, you can: - xref:../../install_config/configuring_authentication.adoc#install-config-configuring-authentication[Configure authentication]; by default, authentication is set to ifdef::openshift-enterprise[] xref:../../install_config/configuring_authentication.adoc#DenyAllPasswordIdentityProvider[Deny All]. endif::[] ifdef::openshift-origin[] xref:../../install_config/configuring_authentication.adoc#AllowAllPasswordIdentityProvider[Allow All]. endif::[] - Deploy an xref:../registry/index.adoc#install-config-registry-overview[integrated Docker registry]. - Deploy a xref:../router/index.adoc#install-config-router-overview[router]. ifdef::openshift-origin[] - xref:../../install_config/imagestreams_templates.adoc#install-config-imagestreams-templates[Populate your {product-title} installation] with a useful set of Red Hat-provided image streams and templates. endif::[] ",12514,False,2237.8403577821464,median "/*============================================================================= Boost.Wave: A Standard compliant C++ preprocessor library http://www.boost.org/ Copyright (c) 2001 by Andrei Alexandrescu. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ // This code is taken from: // Andrei Alexandrescu, Generic: A Policy-Based basic_string // Implementation. http://www.cuj.com/documents/s=7994/cujcexp1906alexandr/ // // #HK030306: // - Moved into the namespace boost::wave::util // - Added a bunch of missing typename(s) // - Integrated with boost config // - Added a missing header include // - Added special constructors and operator= to allow CowString to be // a real COW-string (removed unnecessary data copying) // - Fixed a string terminating bug in append // // #HK040109: // - Incorporated the changes from Andrei's latest version of this class #ifndef FLEX_STRING_INC_ #define FLEX_STRING_INC_ /* //////////////////////////////////////////////////////////////////////////////// template class StoragePolicy { typedef E value_type; typedef @ iterator; typedef @ const_iterator; typedef A allocator_type; typedef @ size_type; StoragePolicy(const StoragePolicy& s); StoragePolicy(const A&); StoragePolicy(const E* s, size_type len, const A&); StoragePolicy(size_type len, E c, const A&); ~StoragePolicy(); iterator begin(); const_iterator begin() const; iterator end(); const_iterator end() const; size_type size() const; size_type max_size() const; size_type capacity() const; void reserve(size_type res_arg); void append(const E* s, size_type sz); template void append(InputIterator b, InputIterator e); void resize(size_type newSize, E fill); void swap(StoragePolicy& rhs); const E* c_str() const; const E* data() const; A get_allocator() const; }; //////////////////////////////////////////////////////////////////////////////// */ #include #include #include #include #include #include #include #include #include #include #include /////////////////////////////////////////////////////////////////////////////// namespace boost { namespace wave { namespace util { namespace flex_string_details { template inline void pod_fill(Pod* b, Pod* e, T c) { switch ((e - b) & 7) { case 0: while (b != e) { *b = c; ++b; case 7: *b = c; ++b; case 6: *b = c; ++b; case 5: *b = c; ++b; case 4: *b = c; ++b; case 3: *b = c; ++b; case 2: *b = c; ++b; case 1: *b = c; ++b; } } } template inline void pod_move(const Pod* b, const Pod* e, Pod* d) { using namespace std; memmove(d, b, (e - b) * sizeof(*b)); } template inline Pod* pod_copy(const Pod* b, const Pod* e, Pod* d) { const std::size_t s = e - b; using namespace std; memcpy(d, b, s * sizeof(*b)); return d + s; } template struct get_unsigned { typedef T result; }; template <> struct get_unsigned { typedef unsigned char result; }; template <> struct get_unsigned { typedef unsigned char result; }; template <> struct get_unsigned { typedef unsigned short int result; }; template <> struct get_unsigned { typedef unsigned int result; }; template <> struct get_unsigned { typedef unsigned long int result; }; enum Shallow {}; } template class mallocator { public: typedef T value_type; typedef value_type* pointer; typedef const value_type* const_pointer; typedef value_type& reference; typedef const value_type& const_reference; typedef std::size_t size_type; //typedef unsigned int size_type; //typedef std::ptrdiff_t difference_type; typedef int difference_type; template struct rebind { typedef mallocator other; }; mallocator() {} mallocator(const mallocator&) {} //template //mallocator(const mallocator&) {} ~mallocator() {} pointer address(reference x) const { return &x; } const_pointer address(const_reference x) const { return x; } pointer allocate(size_type n, const_pointer = 0) { using namespace std; void* p = malloc(n * sizeof(T)); if (!p) throw bad_alloc(); return static_cast(p); } void deallocate(pointer p, size_type) { using namespace std; free(p); } size_type max_size() const { return static_cast(-1) / sizeof(T); } void construct(pointer p, const value_type& x) { new(p) value_type(x); } void destroy(pointer p) { p->~value_type(); } private: void operator=(const mallocator&); }; template<> class mallocator { typedef void value_type; typedef void* pointer; typedef const void* const_pointer; template struct rebind { typedef mallocator other; }; }; template inline bool operator==(const mallocator&, const mallocator&) { return true; } template inline bool operator!=(const mallocator&, const mallocator&) { return false; } template typename Allocator::pointer Reallocate( Allocator& alloc, typename Allocator::pointer p, typename Allocator::size_type oldObjCount, typename Allocator::size_type newObjCount, void*) { // @@@ not implemented return NULL; } template typename Allocator::pointer Reallocate( Allocator& alloc, typename Allocator::pointer p, typename Allocator::size_type oldObjCount, typename Allocator::size_type newObjCount, mallocator*) { // @@@ not implemented return NULL; } //////////////////////////////////////////////////////////////////////////////// // class template SimpleStringStorage // Allocates memory with malloc //////////////////////////////////////////////////////////////////////////////// template > class SimpleStringStorage { // The ""public"" below exists because MSVC can't do template typedefs public: struct Data { Data() : pEnd_(buffer_), pEndOfMem_(buffer_) { buffer_[0] = E(0); } E* pEnd_; E* pEndOfMem_; E buffer_[1]; }; static const Data emptyString_; typedef typename A::size_type size_type; private: Data* pData_; void Init(size_type size, size_type capacity) { BOOST_ASSERT(size <= capacity); if (capacity == 0) { pData_ = const_cast(&emptyString_); } else { // 11-17-2000: comment added: // No need to allocate (capacity + 1) to // accomodate the terminating 0, because Data already // has one one character in there pData_ = static_cast( malloc(sizeof(Data) + capacity * sizeof(E))); if (!pData_) throw std::bad_alloc(); pData_->pEnd_ = pData_->buffer_ + size; pData_->pEndOfMem_ = pData_->buffer_ + capacity; } } private: // Warning - this doesn't initialize pData_. Used in reserve() SimpleStringStorage() { } public: typedef E value_type; typedef E* iterator; typedef const E* const_iterator; typedef A allocator_type; SimpleStringStorage(const SimpleStringStorage& rhs) { const size_type sz = rhs.size(); Init(sz, sz); if (sz) flex_string_details::pod_copy(rhs.begin(), rhs.end(), begin()); } SimpleStringStorage(const SimpleStringStorage& s, flex_string_details::Shallow) : pData_(s.pData_) { } SimpleStringStorage(const A&) { pData_ = const_cast(&emptyString_); } SimpleStringStorage(const E* s, size_type len, const A&) { Init(len, len); flex_string_details::pod_copy(s, s + len, begin()); } SimpleStringStorage(size_type len, E c, const A&) { Init(len, len); flex_string_details::pod_fill(begin(), end(), c); } SimpleStringStorage& operator=(const SimpleStringStorage& rhs) { const size_type sz = rhs.size(); reserve(sz); flex_string_details::pod_copy(&*rhs.begin(), &*rhs.end(), begin()); pData_->pEnd_ = &*begin() + sz; return *this; } ~SimpleStringStorage() { BOOST_ASSERT(begin() <= end()); if (pData_ != &emptyString_) free(pData_); } iterator begin() { return pData_->buffer_; } const_iterator begin() const { return pData_->buffer_; } iterator end() { return pData_->pEnd_; } const_iterator end() const { return pData_->pEnd_; } size_type size() const { return pData_->pEnd_ - pData_->buffer_; } size_type max_size() const { return std::size_t(-1) / sizeof(E) - sizeof(Data) - 1; } size_type capacity() const { return pData_->pEndOfMem_ - pData_->buffer_; } void reserve(size_type res_arg) { if (res_arg <= capacity()) { // @@@ insert shrinkage here if you wish return; } if (pData_ == &emptyString_) { Init(0, res_arg); } else { const size_type sz = size(); void* p = realloc(pData_, sizeof(Data) + res_arg * sizeof(E)); if (!p) throw std::bad_alloc(); if (p != pData_) { pData_ = static_cast(p); pData_->pEnd_ = pData_->buffer_ + sz; } pData_->pEndOfMem_ = pData_->buffer_ + res_arg; } } void append(const E* s, size_type sz) { const size_type neededCapacity = size() + sz; if (capacity() < neededCapacity) { const iterator b = begin(); static std::less_equal le; if (le(b, s) && le(s, end())) { // aliased const size_type offset = s - b; reserve(neededCapacity); s = begin() + offset; } else { reserve(neededCapacity); } } flex_string_details::pod_copy(s, s + sz, end()); pData_->pEnd_ += sz; } template void append(InputIterator b, InputIterator e) { // @@@ todo: optimize this depending on iterator type for (; b != e; ++b) { *this += *b; } } void resize(size_type newSize, E fill) { const int delta = int(newSize - size()); if (delta == 0) return; if (delta > 0) { if (newSize > capacity()) { reserve(newSize); } E* e = &*end(); flex_string_details::pod_fill(e, e + delta, fill); } pData_->pEnd_ = pData_->buffer_ + newSize; } void swap(SimpleStringStorage& rhs) { std::swap(pData_, rhs.pData_); } const E* c_str() const { if (pData_ != &emptyString_) *pData_->pEnd_ = E(); return pData_->buffer_; } const E* data() const { return pData_->buffer_; } A get_allocator() const { return A(); } }; template const typename SimpleStringStorage::Data SimpleStringStorage::emptyString_ = typename SimpleStringStorage::Data(); //{ // const_cast(SimpleStringStorage::emptyString_.buffer_), // const_cast(SimpleStringStorage::emptyString_.buffer_), // { E() } //}; //////////////////////////////////////////////////////////////////////////////// // class template AllocatorStringStorage // Allocates with your allocator // Takes advantage of the Empty Base Optimization if available //////////////////////////////////////////////////////////////////////////////// template > class AllocatorStringStorage : public A { typedef typename A::size_type size_type; typedef typename SimpleStringStorage::Data Data; void* Alloc(size_type sz, const void* p = 0) { return A::allocate(1 + (sz - 1) / sizeof(E), static_cast(p)); } void* Realloc(void* p, size_type oldSz, size_type newSz) { void* r = Alloc(newSz); flex_string_details::pod_copy(p, p + Min(oldSz, newSz), r); Free(p, oldSz); return r; } void Free(void* p, size_type sz) { A::deallocate(static_cast(p), sz); } Data* pData_; void Init(size_type size, size_type cap) { BOOST_ASSERT(size <= cap); if (cap == 0) { pData_ = const_cast( &SimpleStringStorage::emptyString_); } else { pData_ = static_cast(Alloc( cap * sizeof(E) + sizeof(Data))); pData_->pEnd_ = pData_->buffer_ + size; pData_->pEndOfMem_ = pData_->buffer_ + cap; } } public: typedef E value_type; typedef A allocator_type; typedef typename A::pointer iterator; typedef typename A::const_pointer const_iterator; AllocatorStringStorage(const AllocatorStringStorage& rhs) : A(rhs.get_allocator()) { const size_type sz = rhs.size(); Init(sz, sz); if (sz) flex_string_details::pod_copy(rhs.begin(), rhs.end(), begin()); } AllocatorStringStorage(const AllocatorStringStorage& s, flex_string_details::Shallow) : A(s.get_allocator()) { pData_ = s.pData_; } AllocatorStringStorage(const A& a) : A(a) { pData_ = const_cast( &SimpleStringStorage::emptyString_); } AllocatorStringStorage(const E* s, size_type len, const A& a) : A(a) { Init(len, len); flex_string_details::pod_copy(s, s + len, begin()); } AllocatorStringStorage(size_type len, E c, const A& a) : A(a) { Init(len, len); flex_string_details::pod_fill(&*begin(), &*end(), c); } AllocatorStringStorage& operator=(const AllocatorStringStorage& rhs) { const size_type sz = rhs.size(); reserve(sz); flex_string_details::pod_copy(&*rhs.begin(), &*rhs.end(), begin()); pData_->pEnd_ = &*begin() + rhs.size(); return *this; } ~AllocatorStringStorage() { if (capacity()) { Free(pData_, sizeof(Data) + capacity() * sizeof(E)); } } iterator begin() { return pData_->buffer_; } const_iterator begin() const { return pData_->buffer_; } iterator end() { return pData_->pEnd_; } const_iterator end() const { return pData_->pEnd_; } size_type size() const { return size_type(end() - begin()); } size_type max_size() const { return A::max_size(); } size_type capacity() const { return size_type(pData_->pEndOfMem_ - pData_->buffer_); } void resize(size_type n, E c) { reserve(n); iterator newEnd = begin() + n; iterator oldEnd = end(); if (newEnd > oldEnd) { // Copy the characters flex_string_details::pod_fill(oldEnd, newEnd, c); } if (capacity()) pData_->pEnd_ = newEnd; } void reserve(size_type res_arg) { if (res_arg <= capacity()) { // @@@ shrink to fit here return; } A& myAlloc = *this; AllocatorStringStorage newStr(myAlloc); newStr.Init(size(), res_arg); flex_string_details::pod_copy(begin(), end(), newStr.begin()); swap(newStr); } void append(const E* s, size_type sz) { const size_type neededCapacity = size() + sz; if (capacity() < neededCapacity) { const iterator b = begin(); static std::less_equal le; if (le(b, s) && le(s, end())) { // aliased const size_type offset = s - b; reserve(neededCapacity); s = begin() + offset; } else { reserve(neededCapacity); } } flex_string_details::pod_copy(s, s + sz, end()); pData_->pEnd_ += sz; } void swap(AllocatorStringStorage& rhs) { // @@@ The following line is commented due to a bug in MSVC //std::swap(lhsAlloc, rhsAlloc); std::swap(pData_, rhs.pData_); } const E* c_str() const { if (pData_ != &SimpleStringStorage::emptyString_) { *pData_->pEnd_ = E(); } return &*begin(); } const E* data() const { return &*begin(); } A get_allocator() const { return *this; } }; //////////////////////////////////////////////////////////////////////////////// // class template VectorStringStorage // Uses std::vector // Takes advantage of the Empty Base Optimization if available //////////////////////////////////////////////////////////////////////////////// template > class VectorStringStorage : protected std::vector { typedef std::vector base; public: // protected: typedef E value_type; typedef typename base::iterator iterator; typedef typename base::const_iterator const_iterator; typedef A allocator_type; typedef typename A::size_type size_type; VectorStringStorage(const VectorStringStorage& s) : base(s) { } VectorStringStorage(const A& a) : base(1, E(), a) { } VectorStringStorage(const E* s, size_type len, const A& a) : base(a) { base::reserve(len + 1); base::insert(base::end(), s, s + len); // Terminating zero base::insert(base::end(), E()); } VectorStringStorage(size_type len, E c, const A& a) : base(len + 1, c, a) { // Terminating zero base::back() = E(); } VectorStringStorage& operator=(const VectorStringStorage& rhs) { base& v = *this; v = rhs; return *this; } iterator begin() { return base::begin(); } const_iterator begin() const { return base::begin(); } iterator end() { return base::end() - 1; } const_iterator end() const { return base::end() - 1; } size_type size() const { return base::size() - 1; } size_type max_size() const { return base::max_size() - 1; } size_type capacity() const { return base::capacity() - 1; } void reserve(size_type res_arg) { BOOST_ASSERT(res_arg < max_size()); base::reserve(res_arg + 1); } void append(const E* s, size_type sz) { // Check for aliasing because std::vector doesn't do it. static std::less_equal le; if (!base::empty()) { const E* start = &base::front(); if (le(start, s) && le(s, start + size())) { // aliased const size_type offset = s - start; reserve(size() + sz); s = &base::front() + offset; } } base::insert(end(), s, s + sz); } template void append(InputIterator b, InputIterator e) { base::insert(end(), b, e); } void resize(size_type n, E c) { base::reserve(n + 1); base::back() = c; base::resize(n + 1, c); base::back() = E(); } void swap(VectorStringStorage& rhs) { base::swap(rhs); } const E* c_str() const { return &*begin(); } const E* data() const { return &*begin(); } A get_allocator() const { return base::get_allocator(); } }; //////////////////////////////////////////////////////////////////////////////// // class template SmallStringOpt // Builds the small string optimization over any other storage //////////////////////////////////////////////////////////////////////////////// template class SmallStringOpt { public: typedef typename Storage::value_type value_type; typedef value_type* iterator; typedef const value_type* const_iterator; typedef typename Storage::allocator_type allocator_type; typedef typename allocator_type::size_type size_type; private: enum { temp1 = threshold * sizeof(value_type) > sizeof(Storage) ? threshold * sizeof(value_type) : sizeof(Storage) }; enum { temp2 = temp1 > sizeof(Align) ? temp1 : sizeof(Align) }; public: enum { maxSmallString = (temp2 + sizeof(value_type) - 1) / sizeof(value_type) }; private: enum { magic = maxSmallString + 1 }; union { mutable value_type buf_[maxSmallString + 1]; Align align_; }; Storage& GetStorage() { BOOST_ASSERT(buf_[maxSmallString] == magic); Storage* p = reinterpret_cast(&buf_[0]); return *p; } const Storage& GetStorage() const { BOOST_ASSERT(buf_[maxSmallString] == magic); const Storage *p = reinterpret_cast(&buf_[0]); return *p; } bool Small() const { return buf_[maxSmallString] != magic; } public: SmallStringOpt(const SmallStringOpt& s) { if (s.Small()) { flex_string_details::pod_copy( s.buf_, s.buf_ + s.size(), buf_); } else { new(buf_) Storage(s.GetStorage()); } buf_[maxSmallString] = s.buf_[maxSmallString]; } SmallStringOpt(const allocator_type&) { buf_[maxSmallString] = maxSmallString; } SmallStringOpt(const value_type* s, size_type len, const allocator_type& a) { if (len <= maxSmallString) { flex_string_details::pod_copy(s, s + len, buf_); buf_[maxSmallString] = value_type(maxSmallString - len); } else { new(buf_) Storage(s, len, a); buf_[maxSmallString] = magic; } } SmallStringOpt(size_type len, value_type c, const allocator_type& a) { if (len <= maxSmallString) { flex_string_details::pod_fill(buf_, buf_ + len, c); buf_[maxSmallString] = value_type(maxSmallString - len); } else { new(buf_) Storage(len, c, a); buf_[maxSmallString] = magic; } } SmallStringOpt& operator=(const SmallStringOpt& rhs) { reserve(rhs.size()); resize(0, 0); append(rhs.data(), rhs.size()); return *this; } ~SmallStringOpt() { if (!Small()) GetStorage().~Storage(); } iterator begin() { if (Small()) return buf_; return &*GetStorage().begin(); } const_iterator begin() const { if (Small()) return buf_; return &*GetStorage().begin(); } iterator end() { if (Small()) return buf_ + maxSmallString - buf_[maxSmallString]; return &*GetStorage().end(); } const_iterator end() const { if (Small()) return buf_ + maxSmallString - buf_[maxSmallString]; return &*GetStorage().end(); } size_type size() const { BOOST_ASSERT(!Small() || maxSmallString >= buf_[maxSmallString]); return Small() ? maxSmallString - buf_[maxSmallString] : GetStorage().size(); } size_type max_size() const { return get_allocator().max_size(); } size_type capacity() const { return Small() ? maxSmallString : GetStorage().capacity(); } void reserve(size_type res_arg) { if (Small()) { if (res_arg <= maxSmallString) return; SmallStringOpt temp(*this); this->~SmallStringOpt(); new(buf_) Storage(temp.data(), temp.size(), temp.get_allocator()); buf_[maxSmallString] = magic; GetStorage().reserve(res_arg); } else { GetStorage().reserve(res_arg); } BOOST_ASSERT(capacity() >= res_arg); } void append(const value_type* s, size_type sz) { if (!Small()) { GetStorage().append(s, sz); } else { // append to a small string const size_type neededCapacity = maxSmallString - buf_[maxSmallString] + sz; if (maxSmallString < neededCapacity) { // need to change storage strategy allocator_type alloc; Storage temp(alloc); temp.reserve(neededCapacity); temp.append(buf_, maxSmallString - buf_[maxSmallString]); temp.append(s, sz); buf_[maxSmallString] = magic; new(buf_) Storage(temp.get_allocator()); GetStorage().swap(temp); } else { flex_string_details::pod_move(s, s + sz, buf_ + maxSmallString - buf_[maxSmallString]); buf_[maxSmallString] -= value_type(sz); } } } template void append(InputIterator b, InputIterator e) { // @@@ todo: optimize this depending on iterator type for (; b != e; ++b) { *this += *b; } } void resize(size_type n, value_type c) { if (Small()) { if (n > maxSmallString) { // Small string resized to big string SmallStringOpt temp(*this); // can't throw // 11-17-2001: correct exception safety bug Storage newString(temp.data(), temp.size(), temp.get_allocator()); newString.resize(n, c); // We make the reasonable assumption that an empty Storage // constructor won't throw this->~SmallStringOpt(); new(&buf_[0]) Storage(temp.get_allocator()); buf_[maxSmallString] = value_type(magic); GetStorage().swap(newString); } else { // Small string resized to small string // 11-17-2001: bug fix: terminating zero not copied size_type toFill = n > size() ? n - size() : 0; flex_string_details::pod_fill(end(), end() + toFill, c); buf_[maxSmallString] = value_type(maxSmallString - n); } } else { if (n > maxSmallString) { // Big string resized to big string GetStorage().resize(n, c); } else { // Big string resized to small string // 11-17=2001: bug fix in the BOOST_ASSERTion below BOOST_ASSERT(capacity() > n); SmallStringOpt newObj(data(), n, get_allocator()); newObj.swap(*this); } } } void swap(SmallStringOpt& rhs) { if (Small()) { if (rhs.Small()) { // Small swapped with small std::swap_ranges(buf_, buf_ + maxSmallString + 1, rhs.buf_); } else { // Small swapped with big // Make a copy of myself - can't throw SmallStringOpt temp(*this); // Nuke myself this->~SmallStringOpt(); // Make an empty storage for myself (likely won't throw) new(buf_) Storage(0, value_type(), rhs.get_allocator()); buf_[maxSmallString] = magic; // Recurse to this same function swap(rhs); // Nuke rhs rhs.~SmallStringOpt(); // Build the new small string into rhs new(&rhs) SmallStringOpt(temp); } } else { if (rhs.Small()) { // Big swapped with small // Already implemented, recurse with reversed args rhs.swap(*this); } else { // Big swapped with big GetStorage().swap(rhs.GetStorage()); } } } const value_type* c_str() const { if (!Small()) return GetStorage().c_str(); buf_[maxSmallString - buf_[maxSmallString]] = value_type(); return buf_; } const value_type* data() const { return Small() ? buf_ : GetStorage().data(); } allocator_type get_allocator() const { return allocator_type(); } }; //////////////////////////////////////////////////////////////////////////////// // class template CowString // Implements Copy on Write over any storage //////////////////////////////////////////////////////////////////////////////// template < typename Storage, typename Align = BOOST_DEDUCED_TYPENAME Storage::value_type* > class CowString { typedef typename Storage::value_type E; typedef typename flex_string_details::get_unsigned::result RefCountType; public: typedef E value_type; typedef typename Storage::iterator iterator; typedef typename Storage::const_iterator const_iterator; typedef typename Storage::allocator_type allocator_type; typedef typename allocator_type::size_type size_type; private: union { mutable char buf_[sizeof(Storage)]; Align align_; }; Storage& Data() const { return *reinterpret_cast(buf_); } RefCountType GetRefs() const { const Storage& d = Data(); BOOST_ASSERT(d.size() > 0); BOOST_ASSERT(static_cast(*d.begin()) != 0); return *d.begin(); } RefCountType& Refs() { Storage& d = Data(); BOOST_ASSERT(d.size() > 0); return reinterpret_cast(*d.begin()); } void MakeUnique() const { BOOST_ASSERT(GetRefs() >= 1); if (GetRefs() == 1) return; union { char buf_[sizeof(Storage)]; Align align_; } temp; new(buf_) Storage( *new(temp.buf_) Storage(Data()), flex_string_details::Shallow()); *Data().begin() = 1; } public: CowString(const CowString& s) { if (s.GetRefs() == (std::numeric_limits::max)()) { // must make a brand new copy new(buf_) Storage(s.Data()); // non shallow Refs() = 1; } else { new(buf_) Storage(s.Data(), flex_string_details::Shallow()); ++Refs(); } BOOST_ASSERT(Data().size() > 0); } CowString(const allocator_type& a) { new(buf_) Storage(1, 1, a); } CowString(const E* s, size_type len, const allocator_type& a) { // Warning - MSVC's debugger has trouble tracing through the code below. // It seems to be a const-correctness issue // new(buf_) Storage(a); Data().reserve(len + 1); Data().resize(1, 1); Data().append(s, len); } CowString(size_type len, E c, const allocator_type& a) { new(buf_) Storage(len + 1, c, a); Refs() = 1; } CowString& operator=(const CowString& rhs) { // CowString(rhs).swap(*this); if (--Refs() == 0) Data().~Storage(); if (rhs.GetRefs() == (std::numeric_limits::max)()) { // must make a brand new copy new(buf_) Storage(rhs.Data()); // non shallow Refs() = 1; } else { new(buf_) Storage(rhs.Data(), flex_string_details::Shallow()); ++Refs(); } BOOST_ASSERT(Data().size() > 0); return *this; } ~CowString() { BOOST_ASSERT(Data().size() > 0); if (--Refs() == 0) Data().~Storage(); } iterator begin() { BOOST_ASSERT(Data().size() > 0); MakeUnique(); return Data().begin() + 1; } const_iterator begin() const { BOOST_ASSERT(Data().size() > 0); return Data().begin() + 1; } iterator end() { MakeUnique(); return Data().end(); } const_iterator end() const { return Data().end(); } size_type size() const { BOOST_ASSERT(Data().size() > 0); return Data().size() - 1; } size_type max_size() const { BOOST_ASSERT(Data().max_size() > 0); return Data().max_size() - 1; } size_type capacity() const { BOOST_ASSERT(Data().capacity() > 0); return Data().capacity() - 1; } void resize(size_type n, E c) { BOOST_ASSERT(Data().size() > 0); MakeUnique(); Data().resize(n + 1, c); } void append(const E* s, size_type sz) { MakeUnique(); Data().append(s, sz); } template void append(InputIterator b, InputIterator e) { MakeUnique(); // @@@ todo: optimize this depending on iterator type for (; b != e; ++b) { *this += *b; } } void reserve(size_type res_arg) { if (capacity() > res_arg) return; MakeUnique(); Data().reserve(res_arg + 1); } void swap(CowString& rhs) { Data().swap(rhs.Data()); } const E* c_str() const { BOOST_ASSERT(Data().size() > 0); return Data().c_str() + 1; } const E* data() const { BOOST_ASSERT(Data().size() > 0); return Data().data() + 1; } allocator_type get_allocator() const { return Data().get_allocator(); } }; //////////////////////////////////////////////////////////////////////////////// // class template flex_string // a std::basic_string compatible implementation // Uses a Storage policy //////////////////////////////////////////////////////////////////////////////// template , class A = std::allocator, class Storage = AllocatorStringStorage > class flex_string : private Storage { #if defined(THROW_ON_ENFORCE) template static void Enforce(bool condition, Exception*, const char* msg) { if (!condition) throw Exception(msg); } #else template static inline void Enforce(bool condition, Exception*, const char* msg) { BOOST_ASSERT(condition && msg); } #endif // defined(THROW_ON_ENFORCE) bool Sane() const { return begin() <= end() && empty() == (size() == 0) && empty() == (begin() == end()) && size() <= max_size() && capacity() <= max_size() && size() <= capacity(); } struct Invariant; friend struct Invariant; struct Invariant { Invariant(const flex_string& s) : s_(s) { BOOST_ASSERT(s_.Sane()); } ~Invariant() { BOOST_ASSERT(s_.Sane()); } private: const flex_string& s_; }; public: // types typedef T traits_type; typedef typename traits_type::char_type value_type; typedef A allocator_type; typedef typename A::size_type size_type; typedef typename A::difference_type difference_type; typedef typename A::reference reference; typedef typename A::const_reference const_reference; typedef typename A::pointer pointer; typedef typename A::const_pointer const_pointer; typedef typename Storage::iterator iterator; typedef typename Storage::const_iterator const_iterator; typedef boost::reverse_iterator reverse_iterator; typedef boost::reverse_iterator const_reverse_iterator; static const size_type npos; // = size_type(-1) private: static size_type Min(size_type lhs, size_type rhs) { return lhs < rhs ? lhs : rhs; } public: // 21.3.1 construct/copy/destroy explicit flex_string(const A& a = A()) : Storage(a) {} flex_string(const flex_string& str) : Storage(str) { } flex_string(const flex_string& str, size_type pos, size_type n = npos, const A& a = A()) : Storage(a) { Enforce(pos <= str.size(), (std::out_of_range*)0, """"); assign(str, pos, n); } flex_string(const value_type* s, const A& a = A()) : Storage(s, traits_type::length(s), a) {} flex_string(const value_type* s, size_type n, const A& a = A()) : Storage(s, n, a) {} flex_string(size_type n, value_type c, const A& a = A()) : Storage(n, c, a) {} template flex_string(InputIterator begin, InputIterator end, const A& a = A()) : Storage(a) { assign(begin, end); } ~flex_string() {} flex_string& operator=(const flex_string& str) { if (this != &str) { Storage& s = *this; s = str; } return *this; } flex_string& operator=(const value_type* s) { assign(s); return *this; } flex_string& operator=(value_type c) { assign(1, c); return *this; } // 21.3.2 iterators: iterator begin() { return Storage::begin(); } const_iterator begin() const { return Storage::begin(); } iterator end() { return Storage::end(); } const_iterator end() const { return Storage::end(); } reverse_iterator rbegin() { return reverse_iterator(end()); } const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); } reverse_iterator rend() { return reverse_iterator(begin()); } const_reverse_iterator rend() const { return const_reverse_iterator(begin()); } // 21.3.3 capacity: size_type size() const { return Storage::size(); } size_type length() const { return size(); } size_type max_size() const { return Storage::max_size(); } void resize(size_type n, value_type c) { Storage::resize(n, c); } void resize(size_type n) { resize(n, value_type()); } size_type capacity() const { return Storage::capacity(); } void reserve(size_type res_arg = 0) { Enforce(res_arg <= max_size(), (std::length_error*)0, """"); Storage::reserve(res_arg); } void clear() { resize(0); } bool empty() const { return size() == 0; } // 21.3.4 element access: const_reference operator[](size_type pos) const { return *(begin() + pos); } reference operator[](size_type pos) { return *(begin() + pos); } const_reference at(size_type n) const { Enforce(n < size(), (std::out_of_range*)0, """"); return (*this)[n]; } reference at(size_type n) { Enforce(n < size(), (std::out_of_range*)0, """"); return (*this)[n]; } // 21.3.5 modifiers: flex_string& operator+=(const flex_string& str) { return append(str); } flex_string& operator+=(const value_type* s) { return append(s); } flex_string& operator+=(value_type c) { const size_type cap = capacity(); if (size() == cap) { reserve(cap << 1u); } resize(size() + 1, c); return *this; } flex_string& append(const flex_string& str) { return append(str, 0, npos); } flex_string& append(const flex_string& str, size_type pos, size_type n) { const size_type sz = str.size(); Enforce(pos <= sz, (std::out_of_range*)0, """"); return append(str.c_str() + pos, Min(n, sz - pos)); } flex_string& append(const value_type* s, size_type n) { Storage::append(s, n); return *this; } flex_string& append(const value_type* s) { return append(s, traits_type::length(s)); } flex_string& append(size_type n, value_type c) { resize(size() + n, c); return *this; } /* template flex_string& append(InputIterator first, InputIterator last) { for (; first != last; ++first) *this += E(*first); return *this; } */ void push_back(value_type c) { *this += c; } flex_string& assign(const flex_string& str) { if (&str == this) return *this; replace(0, size(), &*str.begin(), str.size()); return *this; } flex_string& assign(const flex_string& str, size_type pos, size_type n) { Enforce(pos <= str.size(), (std::out_of_range*)0, """"); return assign(str.data() + pos, Min(n, str.size() - pos)); } flex_string& assign(const value_type* s, size_type n) { if (size() >= n) { flex_string_details::pod_move(s, s + n, &*begin()); resize(n, value_type()); } else { flex_string_details::pod_move(s, s + size(), &*begin()); Storage::append(s + size(), n - size()); } return *this; } flex_string& assign(const value_type* s) { return assign(s, traits_type::length(s)); } flex_string& assign(size_type n, value_type c) { return replace(begin(), end(), n, c); } template flex_string& assign(InputIterator first, InputIterator last) { return replace(begin(), end(), first, last); } flex_string& insert(size_type pos1, const flex_string& str) { return insert(pos1, str, 0, npos); } flex_string& insert(size_type pos1, const flex_string& str, size_type pos2, size_type n) { return replace(pos1, 0, str, pos2, n); } flex_string& insert(size_type pos, const value_type* s, size_type n) { return replace(pos, 0, s, n); } flex_string& insert(size_type pos, const value_type* s) { return insert(pos, s, traits_type::length(s)); } flex_string& insert(size_type pos, size_type n, value_type c) { return replace(pos, 0, n, c); } iterator insert(iterator p, value_type c = value_type()) { const size_type pos = p - begin(); insert(pos, &c, 1); return begin() + pos; } void insert(iterator p, size_type n, value_type c) { insert(p - begin(), n, c); } template void insert(iterator p, InputIterator first, InputIterator last) { replace(p, p, first, last); } flex_string& erase(size_type pos = 0, size_type n = npos) { return replace(pos, Min(n, size() - pos), 0, value_type()); } iterator erase(iterator position) { const size_type pos(position - begin()); erase(pos, 1); return begin() + pos; } iterator erase(iterator first, iterator last) { const size_type pos(first - begin()); erase(pos, last - first); return begin() + pos; } // @@@ replace flex_string& replace(size_type pos1, size_type n1, const flex_string& str) { return replace(pos1, n1, str, 0, npos); } flex_string& replace(size_type pos1, size_type n1, const flex_string& str, size_type pos2, size_type n2) { Enforce(pos1 <= length() && pos2 <= str.length(), (std::out_of_range*)0, """"); return replace(pos1, n1, &*str.begin() + pos2, Min(n2, str.length() - pos2)); } flex_string& replace(const size_type d, size_type n1, const value_type* s1, const size_type n2) { using namespace flex_string_details; Enforce(d <= size(), (std::out_of_range*)0, """"); if (d + n1 > size()) n1 = size() - d; const int delta = int(n2 - n1); static const std::less_equal le = std::less_equal(); const bool aliased = le(&*begin(), s1) && le(s1, &*end()); if (delta > 0) { if (capacity() < size() + delta) { // realloc the string if (aliased) { const size_type offset = s1 - &*begin(); reserve(size() + delta); s1 = &*begin() + offset; } else { reserve(size() + delta); } } const value_type* s2 = s1 + n2; value_type* d1 = &*begin() + d; value_type* d2 = d1 + n1; const int tailLen = int(&*end() - d2); if (delta <= tailLen) { value_type* oldEnd = &*end(); // simple case Storage::append(oldEnd - delta, delta); pod_move(d2, d2 + (tailLen - delta), d2 + delta); if (le(d2, s1)) { if (aliased) { pod_copy(s1 + delta, s2 + delta, d1); } else { pod_copy(s1, s2, d1); } } else { // d2 > s1 if (le(d2, s2)) { BOOST_ASSERT(aliased); pod_move(s1, d2, d1); pod_move(d2 + delta, s2 + delta, d1 + (d2 - s1)); } else { pod_move(s1, s2, d1); } } } else { const size_type sz = delta - tailLen; Storage::append(s2 - sz, sz); Storage::append(d2, tailLen); pod_move(s1, s2 - (delta - tailLen), d1); } } else { pod_move(s1, s1 + n2, &*begin() + d); pod_move(&*begin() + d + n1, &*end(), &*begin() + d + n1 + delta); resize(size() + delta); } return *this; } flex_string& replace(size_type pos, size_type n1, const value_type* s) { return replace(pos, n1, s, traits_type::length(s)); } flex_string& replace(size_type pos, size_type n1, size_type n2, value_type c) { if (pos + n1 > size()) n1 = size() - pos; const size_type oldSize = size(); if (pos + n2 > oldSize) { resize(pos + n2, c); Storage::append(&*begin() + pos + n1, oldSize - pos - n1); flex_string_details::pod_fill(&*begin() + pos, &*begin() + oldSize, c); } else { if (n2 > n1) { const size_type delta = n2 - n1; Storage::append(&*begin() + oldSize - delta, delta); flex_string_details::pod_move( &*begin() + pos + n1, &*begin() + oldSize - delta, &*begin() + pos + n2); } else { flex_string_details::pod_move(&*begin() + pos + n1, &*end(), &*begin() + pos + n2); resize(oldSize - (n1 - n2)); } flex_string_details::pod_fill(&*begin() + pos, &*begin() + pos + n2, c); } return *this; } flex_string& replace(iterator i1, iterator i2, const flex_string& str) { return replace(i1, i2, str.c_str(), str.length()); } flex_string& replace(iterator i1, iterator i2, const value_type* s, size_type n) { return replace(i1 - begin(), i2 - i1, s, n); } flex_string& replace(iterator i1, iterator i2, const value_type* s) { return replace(i1, i2, s, traits_type::length(s)); } flex_string& replace(iterator i1, iterator i2, size_type n, value_type c) { return replace(i1 - begin(), i2 - i1, n, c); } private: template class Selector {}; // template struct SameType // { // enum { result = false }; // }; // // template struct SameType // { // enum { result = true }; // }; template flex_string& ReplaceImpl(iterator i1, iterator i2, ReallyAnIntegral n, ReallyAnIntegral c, Selector<1>) { return replace(i1, i2, static_cast(n), static_cast(c)); } template flex_string& ReplaceImpl(iterator i1, iterator i2, InputIterator b, InputIterator e, Selector<0>) { BOOST_ASSERT(false); return *this; } public: template flex_string& replace(iterator i1, iterator i2, InputIterator j1, InputIterator j2) { return ReplaceImpl(i1, i2, j1, j2, Selector::is_specialized>()); } size_type copy(value_type* s, size_type n, size_type pos = 0) const { Enforce(pos <= size(), (std::out_of_range*)0, """"); n = Min(n, size() - pos); flex_string_details::pod_copy( &*begin() + pos, &*begin() + pos + n, s); return n; } void swap(flex_string& rhs) { Storage& srhs = rhs; this->Storage::swap(srhs); } // 21.3.6 string operations: const value_type* c_str() const { return Storage::c_str(); } const value_type* data() const { return Storage::data(); } allocator_type get_allocator() const { return Storage::get_allocator(); } size_type find(const flex_string& str, size_type pos = 0) const { return find(str.data(), pos, str.length()); } size_type find (const value_type* s, size_type pos, size_type n) const { for (; pos <= size(); ++pos) { if (traits_type::compare(&*begin() + pos, s, n) == 0) { return pos; } } return npos; } size_type find (const value_type* s, size_type pos = 0) const { return find(s, pos, traits_type::length(s)); } size_type find (value_type c, size_type pos = 0) const { return find(&c, pos, 1); } size_type rfind(const flex_string& str, size_type pos = npos) const { return rfind(str.c_str(), pos, str.length()); } size_type rfind(const value_type* s, size_type pos, size_type n) const { if (n > length()) return npos; pos = Min(pos, length() - n); if (n == 0) return pos; const_iterator i(begin() + pos); for (; ; --i) { if (traits_type::eq(*i, *s) && traits_type::compare(&*i, s, n) == 0) { return i - begin(); } if (i == begin()) break; } return npos; } size_type rfind(const value_type* s, size_type pos = npos) const { return rfind(s, pos, traits_type::length(s)); } size_type rfind(value_type c, size_type pos = npos) const { return rfind(&c, pos, 1); } size_type find_first_of(const flex_string& str, size_type pos = 0) const { return find_first_of(str.c_str(), pos, str.length()); } size_type find_first_of(const value_type* s, size_type pos, size_type n) const { if (pos > length() || n == 0) return npos; const_iterator i(begin() + pos), finish(end()); for (; i != finish; ++i) { if (traits_type::find(s, n, *i) != 0) { return i - begin(); } } return npos; } size_type find_first_of(const value_type* s, size_type pos = 0) const { return find_first_of(s, pos, traits_type::length(s)); } size_type find_first_of(value_type c, size_type pos = 0) const { return find_first_of(&c, pos, 1); } size_type find_last_of (const flex_string& str, size_type pos = npos) const { return find_last_of(str.c_str(), pos, str.length()); } size_type find_last_of (const value_type* s, size_type pos, size_type n) const { if (!empty() && n > 0) { pos = Min(pos, length() - 1); const_iterator i(begin() + pos); for (;; --i) { if (traits_type::find(s, n, *i) != 0) { return i - begin(); } if (i == begin()) break; } } return npos; } size_type find_last_of (const value_type* s, size_type pos = npos) const { return find_last_of(s, pos, traits_type::length(s)); } size_type find_last_of (value_type c, size_type pos = npos) const { return find_last_of(&c, pos, 1); } size_type find_first_not_of(const flex_string& str, size_type pos = 0) const { return find_first_not_of(str.data(), pos, str.size()); } size_type find_first_not_of(const value_type* s, size_type pos, size_type n) const { if (pos < length()) { const_iterator i(begin() + pos), finish(end()); for (; i != finish; ++i) { if (traits_type::find(s, n, *i) == 0) { return i - begin(); } } } return npos; } size_type find_first_not_of(const value_type* s, size_type pos = 0) const { return find_first_not_of(s, pos, traits_type::length(s)); } size_type find_first_not_of(value_type c, size_type pos = 0) const { return find_first_not_of(&c, pos, 1); } size_type find_last_not_of(const flex_string& str, size_type pos = npos) const { return find_last_not_of(str.c_str(), pos, str.length()); } size_type find_last_not_of(const value_type* s, size_type pos, size_type n) const { if (!empty()) { pos = Min(pos, size() - 1); const_iterator i(begin() + pos); for (;; --i) { if (traits_type::find(s, n, *i) == 0) { return i - begin(); } if (i == begin()) break; } } return npos; } size_type find_last_not_of(const value_type* s, size_type pos = npos) const { return find_last_not_of(s, pos, traits_type::length(s)); } size_type find_last_not_of (value_type c, size_type pos = npos) const { return find_last_not_of(&c, pos, 1); } flex_string substr(size_type pos = 0, size_type n = npos) const { Enforce(pos <= size(), (std::out_of_range*)0, """"); return flex_string(data() + pos, Min(n, size() - pos)); } std::ptrdiff_t compare(const flex_string& str) const { return compare(0, size(), str.data(), str.length()); } std::ptrdiff_t compare(size_type pos1, size_type n1, const flex_string& str) const { return compare(pos1, n1, str.data(), str.size()); } std::ptrdiff_t compare(size_type pos1, size_type n1, const value_type* s, size_type n2 = npos) const { Enforce(pos1 <= size(), (std::out_of_range*)0, """"); n1 = Min(size() - pos1, n1); const std::ptrdiff_t result = traits_type::compare(data() + pos1, s, Min(n1, n2)); return (result != 0) ? result : int(n1 - n2); } std::ptrdiff_t compare(size_type pos1, size_type n1, const flex_string& str, size_type pos2, size_type n2) const { Enforce(pos2 <= str.size(), (std::out_of_range*)0, """"); return compare(pos1, n1, str.data() + pos2, Min(n2, str.size() - pos2)); } std::ptrdiff_t compare(const value_type* s) const { return compare(0, size(), s, traits_type::length(s)); } }; // non-member functions template flex_string operator+(const flex_string& lhs, const flex_string& rhs) { flex_string result; result.reserve(lhs.size() + rhs.size()); result.append(lhs); result.append(rhs); return result; } template flex_string operator+(const typename flex_string::value_type* lhs, const flex_string& rhs) { flex_string result; const typename flex_string::size_type len = flex_string::traits_type::length(lhs); result.reserve(len + rhs.size()); result.append(lhs, len); result.append(rhs); return result; } template flex_string operator+( typename flex_string::value_type lhs, const flex_string& rhs) { flex_string result; result.reserve(1 + rhs.size()); result.push_back(lhs); result.append(rhs); return result; } template flex_string operator+(const flex_string& lhs, const typename flex_string::value_type* rhs) { typedef typename flex_string::size_type size_type; typedef typename flex_string::traits_type traits_type; flex_string result; const size_type len = traits_type::length(rhs); result.reserve(lhs.size() + len); result.append(lhs); result.append(rhs, len); return result; } template flex_string operator+(const flex_string& lhs, typename flex_string::value_type rhs) { flex_string result; result.reserve(lhs.size() + 1); result.append(lhs); result.push_back(rhs); return result; } template bool operator==(const flex_string& lhs, const flex_string& rhs) { return lhs.compare(rhs) == 0; } template bool operator==(const typename flex_string::value_type* lhs, const flex_string& rhs) { return rhs == lhs; } template bool operator==(const flex_string& lhs, const typename flex_string::value_type* rhs) { return lhs.compare(rhs) == 0; } template bool operator!=(const flex_string& lhs, const flex_string& rhs) { return !(lhs == rhs); } template bool operator!=(const typename flex_string::value_type* lhs, const flex_string& rhs) { return !(lhs == rhs); } template bool operator!=(const flex_string& lhs, const typename flex_string::value_type* rhs) { return !(lhs == rhs); } template bool operator<(const flex_string& lhs, const flex_string& rhs) { return lhs.compare(rhs) < 0; } template bool operator<(const flex_string& lhs, const typename flex_string::value_type* rhs) { return lhs.compare(rhs) < 0; } template bool operator<(const typename flex_string::value_type* lhs, const flex_string& rhs) { return rhs.compare(lhs) > 0; } template bool operator>(const flex_string& lhs, const flex_string& rhs) { return rhs < lhs; } template bool operator>(const flex_string& lhs, const typename flex_string::value_type* rhs) { return rhs < lhs; } template bool operator>(const typename flex_string::value_type* lhs, const flex_string& rhs) { return rhs < lhs; } template bool operator<=(const flex_string& lhs, const flex_string& rhs) { return !(rhs < lhs); } template bool operator<=(const flex_string& lhs, const typename flex_string::value_type* rhs) { return !(rhs < lhs); } template bool operator<=(const typename flex_string::value_type* lhs, const flex_string& rhs) { return !(rhs < lhs); } template bool operator>=(const flex_string& lhs, const flex_string& rhs) { return !(lhs < rhs); } template bool operator>=(const flex_string& lhs, const typename flex_string::value_type* rhs) { return !(lhs < rhs); } template bool operator>=(const typename flex_string::value_type* lhs, const flex_string& rhs) { return !(lhs < rhs); } // subclause 21.3.7.8: //void swap(flex_string& lhs, flex_string& rhs); // to do template std::basic_istream::value_type, typename flex_string::traits_type>& operator>>( std::basic_istream::value_type, typename flex_string::traits_type>& is, flex_string& str); template std::basic_ostream::value_type, typename flex_string::traits_type>& operator<<( std::basic_ostream::value_type, typename flex_string::traits_type>& os, const flex_string& str) { return os << str.c_str(); } template std::basic_istream::value_type, typename flex_string::traits_type>& getline( std::basic_istream::value_type, typename flex_string::traits_type>& is, flex_string& str, typename flex_string::value_type delim); template std::basic_istream::value_type, typename flex_string::traits_type>& getline( std::basic_istream::value_type, typename flex_string::traits_type>& is, flex_string& str); template const typename flex_string::size_type flex_string::npos = (typename flex_string::size_type)(-1); /////////////////////////////////////////////////////////////////////////////// } // namespace util } // namespace wave } // namespace boost #endif // FLEX_STRING_INC_ ",16158,True,3036.986121089042,median "// Copyright (c) 2011-present, Facebook, Inc. All rights reserved. // This source code is licensed under both the GPLv2 (found in the // COPYING file in the root directory) and Apache 2.0 License // (found in the LICENSE.Apache file in the root directory). #ifndef ROCKSDB_LITE #include ""utilities/blob_db/blob_db_impl.h"" #include #include #include #include #include ""db/db_impl.h"" #include ""db/write_batch_internal.h"" #include ""monitoring/instrumented_mutex.h"" #include ""monitoring/statistics.h"" #include ""rocksdb/convenience.h"" #include ""rocksdb/env.h"" #include ""rocksdb/iterator.h"" #include ""rocksdb/utilities/stackable_db.h"" #include ""rocksdb/utilities/transaction.h"" #include ""table/block.h"" #include ""table/block_based_table_builder.h"" #include ""table/block_builder.h"" #include ""table/meta_blocks.h"" #include ""util/cast_util.h"" #include ""util/crc32c.h"" #include ""util/file_reader_writer.h"" #include ""util/filename.h"" #include ""util/logging.h"" #include ""util/mutexlock.h"" #include ""util/random.h"" #include ""util/stop_watch.h"" #include ""util/sync_point.h"" #include ""util/timer_queue.h"" #include ""utilities/blob_db/blob_compaction_filter.h"" #include ""utilities/blob_db/blob_db_iterator.h"" #include ""utilities/blob_db/blob_db_listener.h"" #include ""utilities/blob_db/blob_index.h"" namespace { int kBlockBasedTableVersionFormat = 2; } // end namespace namespace rocksdb { namespace blob_db { WalFilter::WalProcessingOption BlobReconcileWalFilter::LogRecordFound( unsigned long long /*log_number*/, const std::string& /*log_file_name*/, const WriteBatch& /*batch*/, WriteBatch* /*new_batch*/, bool* /*batch_changed*/) { return WalFilter::WalProcessingOption::kContinueProcessing; } bool BlobFileComparator::operator()( const std::shared_ptr& lhs, const std::shared_ptr& rhs) const { return lhs->BlobFileNumber() > rhs->BlobFileNumber(); } bool BlobFileComparatorTTL::operator()( const std::shared_ptr& lhs, const std::shared_ptr& rhs) const { assert(lhs->HasTTL() && rhs->HasTTL()); if (lhs->expiration_range_.first < rhs->expiration_range_.first) { return true; } if (lhs->expiration_range_.first > rhs->expiration_range_.first) { return false; } return lhs->BlobFileNumber() < rhs->BlobFileNumber(); } BlobDBImpl::BlobDBImpl(const std::string& dbname, const BlobDBOptions& blob_db_options, const DBOptions& db_options, const ColumnFamilyOptions& cf_options) : BlobDB(), dbname_(dbname), db_impl_(nullptr), env_(db_options.env), bdb_options_(blob_db_options), db_options_(db_options), cf_options_(cf_options), env_options_(db_options), statistics_(db_options_.statistics.get()), next_file_number_(1), epoch_of_(0), closed_(true), open_file_count_(0), total_blob_size_(0), live_sst_size_(0), fifo_eviction_seq_(0), evict_expiration_up_to_(0), debug_level_(0) { blob_dir_ = (bdb_options_.path_relative) ? dbname + ""/"" + bdb_options_.blob_dir : bdb_options_.blob_dir; env_options_.bytes_per_sync = blob_db_options.bytes_per_sync; } BlobDBImpl::~BlobDBImpl() { // CancelAllBackgroundWork(db_, true); Status s __attribute__((__unused__)) = Close(); assert(s.ok()); } Status BlobDBImpl::Close() { if (closed_) { return Status::OK(); } closed_ = true; // Close base DB before BlobDBImpl destructs to stop event listener and // compaction filter call. Status s = db_->Close(); // delete db_ anyway even if close failed. delete db_; // Reset pointers to avoid StackableDB delete the pointer again. db_ = nullptr; db_impl_ = nullptr; if (!s.ok()) { return s; } s = SyncBlobFiles(); return s; } BlobDBOptions BlobDBImpl::GetBlobDBOptions() const { return bdb_options_; } Status BlobDBImpl::Open(std::vector* handles) { assert(handles != nullptr); assert(db_ == nullptr); if (blob_dir_.empty()) { return Status::NotSupported(""No blob directory in options""); } if (cf_options_.compaction_filter != nullptr || cf_options_.compaction_filter_factory != nullptr) { return Status::NotSupported(""Blob DB doesn't support compaction filter.""); } Status s; // Create info log. if (db_options_.info_log == nullptr) { s = CreateLoggerFromOptions(dbname_, db_options_, &db_options_.info_log); if (!s.ok()) { return s; } } ROCKS_LOG_INFO(db_options_.info_log, ""Opening BlobDB...""); // Open blob directory. s = env_->CreateDirIfMissing(blob_dir_); if (!s.ok()) { ROCKS_LOG_ERROR(db_options_.info_log, ""Failed to create blob_dir %s, status: %s"", blob_dir_.c_str(), s.ToString().c_str()); } s = env_->NewDirectory(blob_dir_, &dir_ent_); if (!s.ok()) { ROCKS_LOG_ERROR(db_options_.info_log, ""Failed to open blob_dir %s, status: %s"", blob_dir_.c_str(), s.ToString().c_str()); return s; } // Open blob files. s = OpenAllBlobFiles(); if (!s.ok()) { return s; } // Update options db_options_.listeners.push_back(std::make_shared(this)); cf_options_.compaction_filter_factory.reset( new BlobIndexCompactionFilterFactory(this, env_, statistics_)); // Open base db. ColumnFamilyDescriptor cf_descriptor(kDefaultColumnFamilyName, cf_options_); s = DB::Open(db_options_, dbname_, {cf_descriptor}, handles, &db_); if (!s.ok()) { return s; } db_impl_ = static_cast_with_check(db_->GetRootDB()); UpdateLiveSSTSize(); // Start background jobs. if (!bdb_options_.disable_background_tasks) { StartBackgroundTasks(); } ROCKS_LOG_INFO(db_options_.info_log, ""BlobDB pointer %p"", this); bdb_options_.Dump(db_options_.info_log.get()); closed_ = false; return s; } void BlobDBImpl::StartBackgroundTasks() { // store a call to a member function and object tqueue_.add( kReclaimOpenFilesPeriodMillisecs, std::bind(&BlobDBImpl::ReclaimOpenFiles, this, std::placeholders::_1)); tqueue_.add(static_cast( bdb_options_.garbage_collection_interval_secs * 1000), std::bind(&BlobDBImpl::RunGC, this, std::placeholders::_1)); tqueue_.add( kDeleteObsoleteFilesPeriodMillisecs, std::bind(&BlobDBImpl::DeleteObsoleteFiles, this, std::placeholders::_1)); tqueue_.add(kSanityCheckPeriodMillisecs, std::bind(&BlobDBImpl::SanityCheck, this, std::placeholders::_1)); tqueue_.add( kEvictExpiredFilesPeriodMillisecs, std::bind(&BlobDBImpl::EvictExpiredFiles, this, std::placeholders::_1)); } Status BlobDBImpl::GetAllBlobFiles(std::set* file_numbers) { assert(file_numbers != nullptr); std::vector all_files; Status s = env_->GetChildren(blob_dir_, &all_files); if (!s.ok()) { ROCKS_LOG_ERROR(db_options_.info_log, ""Failed to get list of blob files, status: %s"", s.ToString().c_str()); return s; } for (const auto& file_name : all_files) { uint64_t file_number; FileType type; bool success = ParseFileName(file_name, &file_number, &type); if (success && type == kBlobFile) { file_numbers->insert(file_number); } else { ROCKS_LOG_WARN(db_options_.info_log, ""Skipping file in blob directory: %s"", file_name.c_str()); } } return s; } Status BlobDBImpl::OpenAllBlobFiles() { std::set file_numbers; Status s = GetAllBlobFiles(&file_numbers); if (!s.ok()) { return s; } if (!file_numbers.empty()) { next_file_number_.store(*file_numbers.rbegin() + 1); } std::string blob_file_list; std::string obsolete_file_list; for (auto& file_number : file_numbers) { std::shared_ptr blob_file = std::make_shared( this, blob_dir_, file_number, db_options_.info_log.get()); blob_file->MarkImmutable(); // Read file header and footer Status read_metadata_status = blob_file->ReadMetadata(env_, env_options_); if (read_metadata_status.IsCorruption()) { // Remove incomplete file. ObsoleteBlobFile(blob_file, 0 /*obsolete_seq*/, false /*update_size*/); if (!obsolete_file_list.empty()) { obsolete_file_list.append("", ""); } obsolete_file_list.append(ToString(file_number)); continue; } else if (!read_metadata_status.ok()) { ROCKS_LOG_ERROR(db_options_.info_log, ""Unable to read metadata of blob file % "" PRIu64 "", status: '%s'"", file_number, read_metadata_status.ToString().c_str()); return read_metadata_status; } total_blob_size_ += blob_file->GetFileSize(); blob_files_[file_number] = blob_file; if (!blob_file_list.empty()) { blob_file_list.append("", ""); } blob_file_list.append(ToString(file_number)); } ROCKS_LOG_INFO(db_options_.info_log, ""Found %"" ROCKSDB_PRIszt "" blob files: %s"", blob_files_.size(), blob_file_list.c_str()); ROCKS_LOG_INFO(db_options_.info_log, ""Found %"" ROCKSDB_PRIszt "" incomplete or corrupted blob files: %s"", obsolete_files_.size(), obsolete_file_list.c_str()); return s; } void BlobDBImpl::CloseRandomAccessLocked( const std::shared_ptr& bfile) { bfile->CloseRandomAccessLocked(); open_file_count_--; } Status BlobDBImpl::GetBlobFileReader( const std::shared_ptr& blob_file, std::shared_ptr* reader) { assert(reader != nullptr); bool fresh_open = false; Status s = blob_file->GetReader(env_, env_options_, reader, &fresh_open); if (s.ok() && fresh_open) { assert(*reader != nullptr); open_file_count_++; } return s; } std::shared_ptr BlobDBImpl::NewBlobFile(const std::string& reason) { uint64_t file_num = next_file_number_++; auto bfile = std::make_shared(this, blob_dir_, file_num, db_options_.info_log.get()); ROCKS_LOG_DEBUG(db_options_.info_log, ""New blob file created: %s reason='%s'"", bfile->PathName().c_str(), reason.c_str()); LogFlush(db_options_.info_log); return bfile; } Status BlobDBImpl::CreateWriterLocked(const std::shared_ptr& bfile) { std::string fpath(bfile->PathName()); std::unique_ptr wfile; Status s = env_->ReopenWritableFile(fpath, &wfile, env_options_); if (!s.ok()) { ROCKS_LOG_ERROR(db_options_.info_log, ""Failed to open blob file for write: %s status: '%s'"" "" exists: '%s'"", fpath.c_str(), s.ToString().c_str(), env_->FileExists(fpath).ToString().c_str()); return s; } std::unique_ptr fwriter; fwriter.reset(new WritableFileWriter(std::move(wfile), fpath, env_options_)); uint64_t boffset = bfile->GetFileSize(); if (debug_level_ >= 2 && boffset) { ROCKS_LOG_DEBUG(db_options_.info_log, ""Open blob file: %s with offset: %d"", fpath.c_str(), boffset); } Writer::ElemType et = Writer::kEtNone; if (bfile->file_size_ == BlobLogHeader::kSize) { et = Writer::kEtFileHdr; } else if (bfile->file_size_ > BlobLogHeader::kSize) { et = Writer::kEtRecord; } else if (bfile->file_size_) { ROCKS_LOG_WARN(db_options_.info_log, ""Open blob file: %s with wrong size: %d"", fpath.c_str(), boffset); return Status::Corruption(""Invalid blob file size""); } bfile->log_writer_ = std::make_shared( std::move(fwriter), env_, statistics_, bfile->file_number_, bdb_options_.bytes_per_sync, db_options_.use_fsync, boffset); bfile->log_writer_->last_elem_type_ = et; return s; } std::shared_ptr BlobDBImpl::FindBlobFileLocked( uint64_t expiration) const { if (open_ttl_files_.empty()) { return nullptr; } std::shared_ptr tmp = std::make_shared(); tmp->SetHasTTL(true); tmp->expiration_range_ = std::make_pair(expiration, 0); tmp->file_number_ = std::numeric_limits::max(); auto citr = open_ttl_files_.equal_range(tmp); if (citr.first == open_ttl_files_.end()) { assert(citr.second == open_ttl_files_.end()); std::shared_ptr check = *(open_ttl_files_.rbegin()); return (check->expiration_range_.second <= expiration) ? nullptr : check; } if (citr.first != citr.second) { return *(citr.first); } auto finditr = citr.second; if (finditr != open_ttl_files_.begin()) { --finditr; } bool b2 = (*finditr)->expiration_range_.second <= expiration; bool b1 = (*finditr)->expiration_range_.first > expiration; return (b1 || b2) ? nullptr : (*finditr); } std::shared_ptr BlobDBImpl::CheckOrCreateWriterLocked( const std::shared_ptr& bfile) { std::shared_ptr writer = bfile->GetWriter(); if (writer) return writer; Status s = CreateWriterLocked(bfile); if (!s.ok()) return nullptr; writer = bfile->GetWriter(); return writer; } std::shared_ptr BlobDBImpl::SelectBlobFile() { { ReadLock rl(&mutex_); if (open_non_ttl_file_ != nullptr) { return open_non_ttl_file_; } } // CHECK again WriteLock wl(&mutex_); if (open_non_ttl_file_ != nullptr) { return open_non_ttl_file_; } std::shared_ptr bfile = NewBlobFile(""SelectBlobFile""); assert(bfile); // file not visible, hence no lock std::shared_ptr writer = CheckOrCreateWriterLocked(bfile); if (!writer) { ROCKS_LOG_ERROR(db_options_.info_log, ""Failed to get writer from blob file: %s"", bfile->PathName().c_str()); return nullptr; } bfile->file_size_ = BlobLogHeader::kSize; bfile->header_.compression = bdb_options_.compression; bfile->header_.has_ttl = false; bfile->header_.column_family_id = reinterpret_cast(DefaultColumnFamily())->GetID(); bfile->header_valid_ = true; bfile->SetColumnFamilyId(bfile->header_.column_family_id); bfile->SetHasTTL(false); bfile->SetCompression(bdb_options_.compression); Status s = writer->WriteHeader(bfile->header_); if (!s.ok()) { ROCKS_LOG_ERROR(db_options_.info_log, ""Failed to write header to new blob file: %s"" "" status: '%s'"", bfile->PathName().c_str(), s.ToString().c_str()); return nullptr; } blob_files_.insert(std::make_pair(bfile->BlobFileNumber(), bfile)); open_non_ttl_file_ = bfile; total_blob_size_ += BlobLogHeader::kSize; return bfile; } std::shared_ptr BlobDBImpl::SelectBlobFileTTL(uint64_t expiration) { assert(expiration != kNoExpiration); uint64_t epoch_read = 0; std::shared_ptr bfile; { ReadLock rl(&mutex_); bfile = FindBlobFileLocked(expiration); epoch_read = epoch_of_.load(); } if (bfile) { assert(!bfile->Immutable()); return bfile; } uint64_t exp_low = (expiration / bdb_options_.ttl_range_secs) * bdb_options_.ttl_range_secs; uint64_t exp_high = exp_low + bdb_options_.ttl_range_secs; ExpirationRange expiration_range = std::make_pair(exp_low, exp_high); bfile = NewBlobFile(""SelectBlobFileTTL""); assert(bfile); ROCKS_LOG_INFO(db_options_.info_log, ""New blob file TTL range: %s %d %d"", bfile->PathName().c_str(), exp_low, exp_high); LogFlush(db_options_.info_log); // we don't need to take lock as no other thread is seeing bfile yet std::shared_ptr writer = CheckOrCreateWriterLocked(bfile); if (!writer) { ROCKS_LOG_ERROR(db_options_.info_log, ""Failed to get writer from blob file with TTL: %s"", bfile->PathName().c_str()); return nullptr; } bfile->header_.expiration_range = expiration_range; bfile->header_.compression = bdb_options_.compression; bfile->header_.has_ttl = true; bfile->header_.column_family_id = reinterpret_cast(DefaultColumnFamily())->GetID(); ; bfile->header_valid_ = true; bfile->SetColumnFamilyId(bfile->header_.column_family_id); bfile->SetHasTTL(true); bfile->SetCompression(bdb_options_.compression); bfile->file_size_ = BlobLogHeader::kSize; // set the first value of the range, since that is // concrete at this time. also necessary to add to open_ttl_files_ bfile->expiration_range_ = expiration_range; WriteLock wl(&mutex_); // in case the epoch has shifted in the interim, then check // check condition again - should be rare. if (epoch_of_.load() != epoch_read) { auto bfile2 = FindBlobFileLocked(expiration); if (bfile2) return bfile2; } Status s = writer->WriteHeader(bfile->header_); if (!s.ok()) { ROCKS_LOG_ERROR(db_options_.info_log, ""Failed to write header to new blob file: %s"" "" status: '%s'"", bfile->PathName().c_str(), s.ToString().c_str()); return nullptr; } blob_files_.insert(std::make_pair(bfile->BlobFileNumber(), bfile)); open_ttl_files_.insert(bfile); total_blob_size_ += BlobLogHeader::kSize; epoch_of_++; return bfile; } class BlobDBImpl::BlobInserter : public WriteBatch::Handler { private: const WriteOptions& options_; BlobDBImpl* blob_db_impl_; uint32_t default_cf_id_; WriteBatch batch_; public: BlobInserter(const WriteOptions& options, BlobDBImpl* blob_db_impl, uint32_t default_cf_id) : options_(options), blob_db_impl_(blob_db_impl), default_cf_id_(default_cf_id) {} WriteBatch* batch() { return &batch_; } virtual Status PutCF(uint32_t column_family_id, const Slice& key, const Slice& value) override { if (column_family_id != default_cf_id_) { return Status::NotSupported( ""Blob DB doesn't support non-default column family.""); } Status s = blob_db_impl_->PutBlobValue(options_, key, value, kNoExpiration, &batch_); return s; } virtual Status DeleteCF(uint32_t column_family_id, const Slice& key) override { if (column_family_id != default_cf_id_) { return Status::NotSupported( ""Blob DB doesn't support non-default column family.""); } Status s = WriteBatchInternal::Delete(&batch_, column_family_id, key); return s; } virtual Status DeleteRange(uint32_t column_family_id, const Slice& begin_key, const Slice& end_key) { if (column_family_id != default_cf_id_) { return Status::NotSupported( ""Blob DB doesn't support non-default column family.""); } Status s = WriteBatchInternal::DeleteRange(&batch_, column_family_id, begin_key, end_key); return s; } virtual Status SingleDeleteCF(uint32_t /*column_family_id*/, const Slice& /*key*/) override { return Status::NotSupported(""Not supported operation in blob db.""); } virtual Status MergeCF(uint32_t /*column_family_id*/, const Slice& /*key*/, const Slice& /*value*/) override { return Status::NotSupported(""Not supported operation in blob db.""); } virtual void LogData(const Slice& blob) override { batch_.PutLogData(blob); } }; Status BlobDBImpl::Write(const WriteOptions& options, WriteBatch* updates) { StopWatch write_sw(env_, statistics_, BLOB_DB_WRITE_MICROS); RecordTick(statistics_, BLOB_DB_NUM_WRITE); uint32_t default_cf_id = reinterpret_cast(DefaultColumnFamily())->GetID(); Status s; BlobInserter blob_inserter(options, this, default_cf_id); { // Release write_mutex_ before DB write to avoid race condition with // flush begin listener, which also require write_mutex_ to sync // blob files. MutexLock l(&write_mutex_); s = updates->Iterate(&blob_inserter); } if (!s.ok()) { return s; } return db_->Write(options, blob_inserter.batch()); } Status BlobDBImpl::Put(const WriteOptions& options, const Slice& key, const Slice& value) { return PutUntil(options, key, value, kNoExpiration); } Status BlobDBImpl::PutWithTTL(const WriteOptions& options, const Slice& key, const Slice& value, uint64_t ttl) { uint64_t now = EpochNow(); uint64_t expiration = kNoExpiration - now > ttl ? now + ttl : kNoExpiration; return PutUntil(options, key, value, expiration); } Status BlobDBImpl::PutUntil(const WriteOptions& options, const Slice& key, const Slice& value, uint64_t expiration) { StopWatch write_sw(env_, statistics_, BLOB_DB_WRITE_MICROS); RecordTick(statistics_, BLOB_DB_NUM_PUT); TEST_SYNC_POINT(""BlobDBImpl::PutUntil:Start""); Status s; WriteBatch batch; { // Release write_mutex_ before DB write to avoid race condition with // flush begin listener, which also require write_mutex_ to sync // blob files. MutexLock l(&write_mutex_); s = PutBlobValue(options, key, value, expiration, &batch); } if (s.ok()) { s = db_->Write(options, &batch); } TEST_SYNC_POINT(""BlobDBImpl::PutUntil:Finish""); return s; } Status BlobDBImpl::PutBlobValue(const WriteOptions& /*options*/, const Slice& key, const Slice& value, uint64_t expiration, WriteBatch* batch) { write_mutex_.AssertHeld(); Status s; std::string index_entry; uint32_t column_family_id = reinterpret_cast(DefaultColumnFamily())->GetID(); if (value.size() < bdb_options_.min_blob_size) { if (expiration == kNoExpiration) { // Put as normal value s = batch->Put(key, value); RecordTick(statistics_, BLOB_DB_WRITE_INLINED); } else { // Inlined with TTL BlobIndex::EncodeInlinedTTL(&index_entry, expiration, value); s = WriteBatchInternal::PutBlobIndex(batch, column_family_id, key, index_entry); RecordTick(statistics_, BLOB_DB_WRITE_INLINED_TTL); } } else { std::string compression_output; Slice value_compressed = GetCompressedSlice(value, &compression_output); std::string headerbuf; Writer::ConstructBlobHeader(&headerbuf, key, value_compressed, expiration); // Check DB size limit before selecting blob file to // Since CheckSizeAndEvictBlobFiles() can close blob files, it needs to be // done before calling SelectBlobFile(). s = CheckSizeAndEvictBlobFiles(headerbuf.size() + key.size() + value_compressed.size()); if (!s.ok()) { return s; } std::shared_ptr bfile = (expiration != kNoExpiration) ? SelectBlobFileTTL(expiration) : SelectBlobFile(); assert(bfile != nullptr); assert(bfile->compression() == bdb_options_.compression); s = AppendBlob(bfile, headerbuf, key, value_compressed, expiration, &index_entry); if (expiration == kNoExpiration) { RecordTick(statistics_, BLOB_DB_WRITE_BLOB); } else { RecordTick(statistics_, BLOB_DB_WRITE_BLOB_TTL); } if (s.ok()) { if (expiration != kNoExpiration) { bfile->ExtendExpirationRange(expiration); } s = CloseBlobFileIfNeeded(bfile); if (s.ok()) { s = WriteBatchInternal::PutBlobIndex(batch, column_family_id, key, index_entry); } } else { ROCKS_LOG_ERROR(db_options_.info_log, ""Failed to append blob to FILE: %s: KEY: %s VALSZ: %d"" "" status: '%s' blob_file: '%s'"", bfile->PathName().c_str(), key.ToString().c_str(), value.size(), s.ToString().c_str(), bfile->DumpState().c_str()); } } RecordTick(statistics_, BLOB_DB_NUM_KEYS_WRITTEN); RecordTick(statistics_, BLOB_DB_BYTES_WRITTEN, key.size() + value.size()); MeasureTime(statistics_, BLOB_DB_KEY_SIZE, key.size()); MeasureTime(statistics_, BLOB_DB_VALUE_SIZE, value.size()); return s; } Slice BlobDBImpl::GetCompressedSlice(const Slice& raw, std::string* compression_output) const { if (bdb_options_.compression == kNoCompression) { return raw; } StopWatch compression_sw(env_, statistics_, BLOB_DB_COMPRESSION_MICROS); CompressionType ct = bdb_options_.compression; CompressionContext compression_ctx(ct); CompressBlock(raw, compression_ctx, &ct, kBlockBasedTableVersionFormat, compression_output); return *compression_output; } void BlobDBImpl::GetCompactionContext(BlobCompactionContext* context) { ReadLock l(&mutex_); context->next_file_number = next_file_number_.load(); context->current_blob_files.clear(); for (auto& p : blob_files_) { context->current_blob_files.insert(p.first); } context->fifo_eviction_seq = fifo_eviction_seq_; context->evict_expiration_up_to = evict_expiration_up_to_; } void BlobDBImpl::UpdateLiveSSTSize() { uint64_t live_sst_size = 0; bool ok = GetIntProperty(DB::Properties::kLiveSstFilesSize, &live_sst_size); if (ok) { live_sst_size_.store(live_sst_size); ROCKS_LOG_INFO(db_options_.info_log, ""Updated total SST file size: %"" PRIu64 "" bytes."", live_sst_size); } else { ROCKS_LOG_ERROR( db_options_.info_log, ""Failed to update total SST file size after flush or compaction.""); } { // Trigger FIFO eviction if needed. MutexLock l(&write_mutex_); Status s = CheckSizeAndEvictBlobFiles(0, true /*force*/); if (s.IsNoSpace()) { ROCKS_LOG_WARN(db_options_.info_log, ""DB grow out-of-space after SST size updated. Current live"" "" SST size: %"" PRIu64 "" , current blob files size: %"" PRIu64 ""."", live_sst_size_.load(), total_blob_size_.load()); } } } Status BlobDBImpl::CheckSizeAndEvictBlobFiles(uint64_t blob_size, bool force_evict) { write_mutex_.AssertHeld(); uint64_t live_sst_size = live_sst_size_.load(); if (bdb_options_.max_db_size == 0 || live_sst_size + total_blob_size_.load() + blob_size <= bdb_options_.max_db_size) { return Status::OK(); } if (bdb_options_.is_fifo == false || (!force_evict && live_sst_size + blob_size > bdb_options_.max_db_size)) { // FIFO eviction is disabled, or no space to insert new blob even we evict // all blob files. return Status::NoSpace( ""Write failed, as writing it would exceed max_db_size limit.""); } std::vector> candidate_files; CopyBlobFiles(&candidate_files); std::sort(candidate_files.begin(), candidate_files.end(), BlobFileComparator()); fifo_eviction_seq_ = GetLatestSequenceNumber(); WriteLock l(&mutex_); while (!candidate_files.empty() && live_sst_size + total_blob_size_.load() + blob_size > bdb_options_.max_db_size) { std::shared_ptr blob_file = candidate_files.back(); candidate_files.pop_back(); WriteLock file_lock(&blob_file->mutex_); if (blob_file->Obsolete()) { // File already obsoleted by someone else. continue; } // FIFO eviction can evict open blob files. if (!blob_file->Immutable()) { Status s = CloseBlobFile(blob_file, false /*need_lock*/); if (!s.ok()) { return s; } } assert(blob_file->Immutable()); auto expiration_range = blob_file->GetExpirationRange(); ROCKS_LOG_INFO(db_options_.info_log, ""Evict oldest blob file since DB out of space. Current "" ""live SST file size: %"" PRIu64 "", total blob size: %"" PRIu64 "", max db size: %"" PRIu64 "", evicted blob file #%"" PRIu64 ""."", live_sst_size, total_blob_size_.load(), bdb_options_.max_db_size, blob_file->BlobFileNumber()); ObsoleteBlobFile(blob_file, fifo_eviction_seq_, true /*update_size*/); evict_expiration_up_to_ = expiration_range.first; RecordTick(statistics_, BLOB_DB_FIFO_NUM_FILES_EVICTED); RecordTick(statistics_, BLOB_DB_FIFO_NUM_KEYS_EVICTED, blob_file->BlobCount()); RecordTick(statistics_, BLOB_DB_FIFO_BYTES_EVICTED, blob_file->GetFileSize()); TEST_SYNC_POINT(""BlobDBImpl::EvictOldestBlobFile:Evicted""); } if (live_sst_size + total_blob_size_.load() + blob_size > bdb_options_.max_db_size) { return Status::NoSpace( ""Write failed, as writing it would exceed max_db_size limit.""); } return Status::OK(); } Status BlobDBImpl::AppendBlob(const std::shared_ptr& bfile, const std::string& headerbuf, const Slice& key, const Slice& value, uint64_t expiration, std::string* index_entry) { Status s; uint64_t blob_offset = 0; uint64_t key_offset = 0; { WriteLock lockbfile_w(&bfile->mutex_); std::shared_ptr writer = CheckOrCreateWriterLocked(bfile); if (!writer) { return Status::IOError(""Failed to create blob writer""); } // write the blob to the blob log. s = writer->EmitPhysicalRecord(headerbuf, key, value, &key_offset, &blob_offset); } if (!s.ok()) { ROCKS_LOG_ERROR(db_options_.info_log, ""Invalid status in AppendBlob: %s status: '%s'"", bfile->PathName().c_str(), s.ToString().c_str()); return s; } // increment blob count bfile->blob_count_++; uint64_t size_put = headerbuf.size() + key.size() + value.size(); bfile->file_size_ += size_put; total_blob_size_ += size_put; if (expiration == kNoExpiration) { BlobIndex::EncodeBlob(index_entry, bfile->BlobFileNumber(), blob_offset, value.size(), bdb_options_.compression); } else { BlobIndex::EncodeBlobTTL(index_entry, expiration, bfile->BlobFileNumber(), blob_offset, value.size(), bdb_options_.compression); } return s; } std::vector BlobDBImpl::MultiGet( const ReadOptions& read_options, const std::vector& keys, std::vector* values) { StopWatch multiget_sw(env_, statistics_, BLOB_DB_MULTIGET_MICROS); RecordTick(statistics_, BLOB_DB_NUM_MULTIGET); // Get a snapshot to avoid blob file get deleted between we // fetch and index entry and reading from the file. ReadOptions ro(read_options); bool snapshot_created = SetSnapshotIfNeeded(&ro); std::vector statuses; statuses.reserve(keys.size()); values->clear(); values->reserve(keys.size()); PinnableSlice value; for (size_t i = 0; i < keys.size(); i++) { statuses.push_back(Get(ro, DefaultColumnFamily(), keys[i], &value)); values->push_back(value.ToString()); value.Reset(); } if (snapshot_created) { db_->ReleaseSnapshot(ro.snapshot); } return statuses; } bool BlobDBImpl::SetSnapshotIfNeeded(ReadOptions* read_options) { assert(read_options != nullptr); if (read_options->snapshot != nullptr) { return false; } read_options->snapshot = db_->GetSnapshot(); return true; } Status BlobDBImpl::GetBlobValue(const Slice& key, const Slice& index_entry, PinnableSlice* value, uint64_t* expiration) { assert(value != nullptr); BlobIndex blob_index; Status s = blob_index.DecodeFrom(index_entry); if (!s.ok()) { return s; } if (blob_index.HasTTL() && blob_index.expiration() <= EpochNow()) { return Status::NotFound(""Key expired""); } if (expiration != nullptr) { if (blob_index.HasTTL()) { *expiration = blob_index.expiration(); } else { *expiration = kNoExpiration; } } if (blob_index.IsInlined()) { // TODO(yiwu): If index_entry is a PinnableSlice, we can also pin the same // memory buffer to avoid extra copy. value->PinSelf(blob_index.value()); return Status::OK(); } if (blob_index.size() == 0) { value->PinSelf(""""); return Status::OK(); } // offset has to have certain min, as we will read CRC // later from the Blob Header, which needs to be also a // valid offset. if (blob_index.offset() < (BlobLogHeader::kSize + BlobLogRecord::kHeaderSize + key.size())) { if (debug_level_ >= 2) { ROCKS_LOG_ERROR(db_options_.info_log, ""Invalid blob index file_number: %"" PRIu64 "" blob_offset: %"" PRIu64 "" blob_size: %"" PRIu64 "" key: %s"", blob_index.file_number(), blob_index.offset(), blob_index.size(), key.data()); } return Status::NotFound(""Invalid blob offset""); } std::shared_ptr bfile; { ReadLock rl(&mutex_); auto hitr = blob_files_.find(blob_index.file_number()); // file was deleted if (hitr == blob_files_.end()) { return Status::NotFound(""Blob Not Found as blob file missing""); } bfile = hitr->second; } if (blob_index.size() == 0 && value != nullptr) { value->PinSelf(""""); return Status::OK(); } // takes locks when called std::shared_ptr reader; s = GetBlobFileReader(bfile, &reader); if (!s.ok()) { return s; } assert(blob_index.offset() > key.size() + sizeof(uint32_t)); uint64_t record_offset = blob_index.offset() - key.size() - sizeof(uint32_t); uint64_t record_size = sizeof(uint32_t) + key.size() + blob_index.size(); // Allocate the buffer. This is safe in C++11 std::string buffer_str(static_cast(record_size), static_cast(0)); char* buffer = &buffer_str[0]; // A partial blob record contain checksum, key and value. Slice blob_record; { StopWatch read_sw(env_, statistics_, BLOB_DB_BLOB_FILE_READ_MICROS); s = reader->Read(record_offset, static_cast(record_size), &blob_record, buffer); RecordTick(statistics_, BLOB_DB_BLOB_FILE_BYTES_READ, blob_record.size()); } if (!s.ok()) { ROCKS_LOG_DEBUG(db_options_.info_log, ""Failed to read blob from blob file %"" PRIu64 "", blob_offset: %"" PRIu64 "", blob_size: %"" PRIu64 "", key_size: "" PRIu64 "", read "" PRIu64 "" bytes, status: '%s'"", bfile->BlobFileNumber(), blob_index.offset(), blob_index.size(), key.size(), s.ToString().c_str()); return s; } if (blob_record.size() != record_size) { ROCKS_LOG_DEBUG(db_options_.info_log, ""Failed to read blob from blob file %"" PRIu64 "", blob_offset: %"" PRIu64 "", blob_size: %"" PRIu64 "", key_size: "" PRIu64 "", read "" PRIu64 "" bytes, status: '%s'"", bfile->BlobFileNumber(), blob_index.offset(), blob_index.size(), key.size(), s.ToString().c_str()); return Status::Corruption(""Failed to retrieve blob from blob index.""); } Slice crc_slice(blob_record.data(), sizeof(uint32_t)); Slice blob_value(blob_record.data() + sizeof(uint32_t) + key.size(), static_cast(blob_index.size())); uint32_t crc_exp; if (!GetFixed32(&crc_slice, &crc_exp)) { ROCKS_LOG_DEBUG(db_options_.info_log, ""Unable to decode CRC from blob file %"" PRIu64 "", blob_offset: %"" PRIu64 "", blob_size: %"" PRIu64 "", key size: %"" PRIu64 "", status: '%s'"", bfile->BlobFileNumber(), blob_index.offset(), blob_index.size(), key.size(), s.ToString().c_str()); return Status::Corruption(""Unable to decode checksum.""); } uint32_t crc = crc32c::Value(blob_record.data() + sizeof(uint32_t), blob_record.size() - sizeof(uint32_t)); crc = crc32c::Mask(crc); // Adjust for storage if (crc != crc_exp) { if (debug_level_ >= 2) { ROCKS_LOG_ERROR(db_options_.info_log, ""Blob crc mismatch file: %s blob_offset: %"" PRIu64 "" blob_size: %"" PRIu64 "" key: %s status: '%s'"", bfile->PathName().c_str(), blob_index.offset(), blob_index.size(), key.data(), s.ToString().c_str()); } return Status::Corruption(""Corruption. Blob CRC mismatch""); } if (bfile->compression() == kNoCompression) { value->PinSelf(blob_value); } else { BlockContents contents; auto cfh = reinterpret_cast(DefaultColumnFamily()); { StopWatch decompression_sw(env_, statistics_, BLOB_DB_DECOMPRESSION_MICROS); UncompressionContext uncompression_ctx(bfile->compression()); s = UncompressBlockContentsForCompressionType( uncompression_ctx, blob_value.data(), blob_value.size(), &contents, kBlockBasedTableVersionFormat, *(cfh->cfd()->ioptions())); } value->PinSelf(contents.data); } return s; } Status BlobDBImpl::Get(const ReadOptions& read_options, ColumnFamilyHandle* column_family, const Slice& key, PinnableSlice* value) { return Get(read_options, column_family, key, value, nullptr /*expiration*/); } Status BlobDBImpl::Get(const ReadOptions& read_options, ColumnFamilyHandle* column_family, const Slice& key, PinnableSlice* value, uint64_t* expiration) { StopWatch get_sw(env_, statistics_, BLOB_DB_GET_MICROS); RecordTick(statistics_, BLOB_DB_NUM_GET); return GetImpl(read_options, column_family, key, value, expiration); } Status BlobDBImpl::GetImpl(const ReadOptions& read_options, ColumnFamilyHandle* column_family, const Slice& key, PinnableSlice* value, uint64_t* expiration) { if (column_family != DefaultColumnFamily()) { return Status::NotSupported( ""Blob DB doesn't support non-default column family.""); } // Get a snapshot to avoid blob file get deleted between we // fetch and index entry and reading from the file. // TODO(yiwu): For Get() retry if file not found would be a simpler strategy. ReadOptions ro(read_options); bool snapshot_created = SetSnapshotIfNeeded(&ro); PinnableSlice index_entry; Status s; bool is_blob_index = false; s = db_impl_->GetImpl(ro, column_family, key, &index_entry, nullptr /*value_found*/, nullptr /*read_callback*/, &is_blob_index); TEST_SYNC_POINT(""BlobDBImpl::Get:AfterIndexEntryGet:1""); TEST_SYNC_POINT(""BlobDBImpl::Get:AfterIndexEntryGet:2""); if (expiration != nullptr) { *expiration = kNoExpiration; } RecordTick(statistics_, BLOB_DB_NUM_KEYS_READ); if (s.ok()) { if (is_blob_index) { s = GetBlobValue(key, index_entry, value, expiration); } else { // The index entry is the value itself in this case. value->PinSelf(index_entry); } RecordTick(statistics_, BLOB_DB_BYTES_READ, value->size()); } if (snapshot_created) { db_->ReleaseSnapshot(ro.snapshot); } return s; } std::pair BlobDBImpl::SanityCheck(bool aborted) { if (aborted) { return std::make_pair(false, -1); } ROCKS_LOG_INFO(db_options_.info_log, ""Starting Sanity Check""); ROCKS_LOG_INFO(db_options_.info_log, ""Number of files %"" PRIu64, blob_files_.size()); ROCKS_LOG_INFO(db_options_.info_log, ""Number of open files %"" PRIu64, open_ttl_files_.size()); for (auto bfile : open_ttl_files_) { assert(!bfile->Immutable()); } uint64_t now = EpochNow(); for (auto blob_file_pair : blob_files_) { auto blob_file = blob_file_pair.second; char buf[1000]; int pos = snprintf(buf, sizeof(buf), ""Blob file %"" PRIu64 "", size %"" PRIu64 "", blob count %"" PRIu64 "", immutable %d"", blob_file->BlobFileNumber(), blob_file->GetFileSize(), blob_file->BlobCount(), blob_file->Immutable()); if (blob_file->HasTTL()) { auto expiration_range = blob_file->GetExpirationRange(); pos += snprintf(buf + pos, sizeof(buf) - pos, "", expiration range (%"" PRIu64 "", %"" PRIu64 "")"", expiration_range.first, expiration_range.second); if (!blob_file->Obsolete()) { pos += snprintf(buf + pos, sizeof(buf) - pos, "", expire in %"" PRIu64 "" seconds"", expiration_range.second - now); } } if (blob_file->Obsolete()) { pos += snprintf(buf + pos, sizeof(buf) - pos, "", obsolete at %"" PRIu64, blob_file->GetObsoleteSequence()); } snprintf(buf + pos, sizeof(buf) - pos, "".""); ROCKS_LOG_INFO(db_options_.info_log, ""%s"", buf); } // reschedule return std::make_pair(true, -1); } Status BlobDBImpl::CloseBlobFile(std::shared_ptr bfile, bool need_lock) { assert(bfile != nullptr); write_mutex_.AssertHeld(); Status s; ROCKS_LOG_INFO(db_options_.info_log, ""Closing blob file %"" PRIu64 "". Path: %s"", bfile->BlobFileNumber(), bfile->PathName().c_str()); { std::unique_ptr lock; if (need_lock) { lock.reset(new WriteLock(&mutex_)); } if (bfile->HasTTL()) { size_t erased __attribute__((__unused__)); erased = open_ttl_files_.erase(bfile); } else if (bfile == open_non_ttl_file_) { open_non_ttl_file_ = nullptr; } } if (!bfile->closed_.load()) { std::unique_ptr file_lock; if (need_lock) { file_lock.reset(new WriteLock(&bfile->mutex_)); } s = bfile->WriteFooterAndCloseLocked(); } if (s.ok()) { total_blob_size_ += BlobLogFooter::kSize; } else { ROCKS_LOG_ERROR(db_options_.info_log, ""Failed to close blob file %"" PRIu64 ""with error: %s"", bfile->BlobFileNumber(), s.ToString().c_str()); } return s; } Status BlobDBImpl::CloseBlobFileIfNeeded(std::shared_ptr& bfile) { // atomic read if (bfile->GetFileSize() < bdb_options_.blob_file_size) { return Status::OK(); } return CloseBlobFile(bfile); } void BlobDBImpl::ObsoleteBlobFile(std::shared_ptr blob_file, SequenceNumber obsolete_seq, bool update_size) { // Should hold write lock of mutex_ or during DB open. blob_file->MarkObsolete(obsolete_seq); obsolete_files_.push_back(blob_file); assert(total_blob_size_.load() >= blob_file->GetFileSize()); if (update_size) { total_blob_size_ -= blob_file->GetFileSize(); } } bool BlobDBImpl::VisibleToActiveSnapshot( const std::shared_ptr& bfile) { assert(bfile->Obsolete()); // We check whether the oldest snapshot is no less than the last sequence // by the time the blob file become obsolete. If so, the blob file is not // visible to all existing snapshots. // // If we keep track of the earliest sequence of the keys in the blob file, // we could instead check if there's a snapshot falls in range // [earliest_sequence, obsolete_sequence). But doing so will make the // implementation more complicated. SequenceNumber obsolete_sequence = bfile->GetObsoleteSequence(); SequenceNumber oldest_snapshot = kMaxSequenceNumber; { // Need to lock DBImpl mutex before access snapshot list. InstrumentedMutexLock l(db_impl_->mutex()); auto& snapshots = db_impl_->snapshots(); if (!snapshots.empty()) { oldest_snapshot = snapshots.oldest()->GetSequenceNumber(); } } bool visible = oldest_snapshot < obsolete_sequence; if (visible) { ROCKS_LOG_INFO(db_options_.info_log, ""Obsolete blob file %"" PRIu64 "" (obsolete at %"" PRIu64 "") visible to oldest snapshot %"" PRIu64 ""."", bfile->BlobFileNumber(), obsolete_sequence, oldest_snapshot); } return visible; } std::pair BlobDBImpl::EvictExpiredFiles(bool aborted) { if (aborted) { return std::make_pair(false, -1); } std::vector> process_files; uint64_t now = EpochNow(); { ReadLock rl(&mutex_); for (auto p : blob_files_) { auto& blob_file = p.second; ReadLock file_lock(&blob_file->mutex_); if (blob_file->HasTTL() && !blob_file->Obsolete() && blob_file->GetExpirationRange().second <= now) { process_files.push_back(blob_file); } } } SequenceNumber seq = GetLatestSequenceNumber(); { MutexLock l(&write_mutex_); for (auto& blob_file : process_files) { WriteLock file_lock(&blob_file->mutex_); if (!blob_file->Immutable()) { CloseBlobFile(blob_file, false /*need_lock*/); } // Need to double check if the file is obsolete. if (!blob_file->Obsolete()) { ObsoleteBlobFile(blob_file, seq, true /*update_size*/); } } } return std::make_pair(true, -1); } Status BlobDBImpl::SyncBlobFiles() { MutexLock l(&write_mutex_); std::vector> process_files; { ReadLock rl(&mutex_); for (auto fitr : open_ttl_files_) { process_files.push_back(fitr); } if (open_non_ttl_file_ != nullptr) { process_files.push_back(open_non_ttl_file_); } } Status s; for (auto& blob_file : process_files) { s = blob_file->Fsync(); if (!s.ok()) { ROCKS_LOG_ERROR(db_options_.info_log, ""Failed to sync blob file %"" PRIu64 "", status: %s"", blob_file->BlobFileNumber(), s.ToString().c_str()); return s; } } s = dir_ent_->Fsync(); if (!s.ok()) { ROCKS_LOG_ERROR(db_options_.info_log, ""Failed to sync blob directory, status: %s"", s.ToString().c_str()); } return s; } std::pair BlobDBImpl::ReclaimOpenFiles(bool aborted) { if (aborted) return std::make_pair(false, -1); if (open_file_count_.load() < kOpenFilesTrigger) { return std::make_pair(true, -1); } // in the future, we should sort by last_access_ // instead of closing every file ReadLock rl(&mutex_); for (auto const& ent : blob_files_) { auto bfile = ent.second; if (bfile->last_access_.load() == -1) continue; WriteLock lockbfile_w(&bfile->mutex_); CloseRandomAccessLocked(bfile); } return std::make_pair(true, -1); } // Write callback for garbage collection to check if key has been updated // since last read. Similar to how OptimisticTransaction works. See inline // comment in GCFileAndUpdateLSM(). class BlobDBImpl::GarbageCollectionWriteCallback : public WriteCallback { public: GarbageCollectionWriteCallback(ColumnFamilyData* cfd, const Slice& key, SequenceNumber upper_bound) : cfd_(cfd), key_(key), upper_bound_(upper_bound) {} virtual Status Callback(DB* db) override { auto* db_impl = reinterpret_cast(db); auto* sv = db_impl->GetAndRefSuperVersion(cfd_); SequenceNumber latest_seq = 0; bool found_record_for_key = false; bool is_blob_index = false; Status s = db_impl->GetLatestSequenceForKey( sv, key_, false /*cache_only*/, &latest_seq, &found_record_for_key, &is_blob_index); db_impl->ReturnAndCleanupSuperVersion(cfd_, sv); if (!s.ok() && !s.IsNotFound()) { // Error. assert(!s.IsBusy()); return s; } if (s.IsNotFound()) { assert(!found_record_for_key); return Status::Busy(""Key deleted""); } assert(found_record_for_key); assert(is_blob_index); if (latest_seq > upper_bound_) { return Status::Busy(""Key overwritten""); } return s; } virtual bool AllowWriteBatching() override { return false; } private: ColumnFamilyData* cfd_; // Key to check Slice key_; // Upper bound of sequence number to proceed. SequenceNumber upper_bound_; }; // iterate over the blobs sequentially and check if the blob sequence number // is the latest. If it is the latest, preserve it, otherwise delete it // if it is TTL based, and the TTL has expired, then // we can blow the entity if the key is still the latest or the Key is not // found // WHAT HAPPENS IF THE KEY HAS BEEN OVERRIDEN. Then we can drop the blob // without doing anything if the earliest snapshot is not // referring to that sequence number, i.e. it is later than the sequence number // of the new key // // if it is not TTL based, then we can blow the key if the key has been // DELETED in the LSM Status BlobDBImpl::GCFileAndUpdateLSM(const std::shared_ptr& bfptr, GCStats* gc_stats) { StopWatch gc_sw(env_, statistics_, BLOB_DB_GC_MICROS); uint64_t now = EpochNow(); std::shared_ptr reader = bfptr->OpenRandomAccessReader(env_, db_options_, env_options_); if (!reader) { ROCKS_LOG_ERROR(db_options_.info_log, ""File sequential reader could not be opened"", bfptr->PathName().c_str()); return Status::IOError(""failed to create sequential reader""); } BlobLogHeader header; Status s = reader->ReadHeader(&header); if (!s.ok()) { ROCKS_LOG_ERROR(db_options_.info_log, ""Failure to read header for blob-file %s"", bfptr->PathName().c_str()); return s; } auto* cfh = db_impl_->GetColumnFamilyHandleUnlocked(bfptr->column_family_id()); auto* cfd = reinterpret_cast(cfh)->cfd(); auto column_family_id = cfd->GetID(); bool has_ttl = header.has_ttl; // this reads the key but skips the blob Reader::ReadLevel shallow = Reader::kReadHeaderKey; bool file_expired = has_ttl && now >= bfptr->GetExpirationRange().second; if (!file_expired) { // read the blob because you have to write it back to new file shallow = Reader::kReadHeaderKeyBlob; } BlobLogRecord record; std::shared_ptr newfile; std::shared_ptr new_writer; uint64_t blob_offset = 0; while (true) { assert(s.ok()); // Read the next blob record. Status read_record_status = reader->ReadRecord(&record, shallow, &blob_offset); // Exit if we reach the end of blob file. // TODO(yiwu): properly handle ReadRecord error. if (!read_record_status.ok()) { break; } gc_stats->blob_count++; // Similar to OptimisticTransaction, we obtain latest_seq from // base DB, which is guaranteed to be no smaller than the sequence of // current key. We use a WriteCallback on write to check the key sequence // on write. If the key sequence is larger than latest_seq, we know // a new versions is inserted and the old blob can be disgard. // // We cannot use OptimisticTransaction because we need to pass // is_blob_index flag to GetImpl. SequenceNumber latest_seq = GetLatestSequenceNumber(); bool is_blob_index = false; PinnableSlice index_entry; Status get_status = db_impl_->GetImpl( ReadOptions(), cfh, record.key, &index_entry, nullptr /*value_found*/, nullptr /*read_callback*/, &is_blob_index); TEST_SYNC_POINT(""BlobDBImpl::GCFileAndUpdateLSM:AfterGetFromBaseDB""); if (!get_status.ok() && !get_status.IsNotFound()) { // error s = get_status; ROCKS_LOG_ERROR(db_options_.info_log, ""Error while getting index entry: %s"", s.ToString().c_str()); break; } if (get_status.IsNotFound() || !is_blob_index) { // Either the key is deleted or updated with a newer version whish is // inlined in LSM. gc_stats->num_keys_overwritten++; gc_stats->bytes_overwritten += record.record_size(); continue; } BlobIndex blob_index; s = blob_index.DecodeFrom(index_entry); if (!s.ok()) { ROCKS_LOG_ERROR(db_options_.info_log, ""Error while decoding index entry: %s"", s.ToString().c_str()); break; } if (blob_index.IsInlined() || blob_index.file_number() != bfptr->BlobFileNumber() || blob_index.offset() != blob_offset) { // Key has been overwritten. Drop the blob record. gc_stats->num_keys_overwritten++; gc_stats->bytes_overwritten += record.record_size(); continue; } GarbageCollectionWriteCallback callback(cfd, record.key, latest_seq); // If key has expired, remove it from base DB. // TODO(yiwu): Blob indexes will be remove by BlobIndexCompactionFilter. // We can just drop the blob record. if (file_expired || (has_ttl && now >= record.expiration)) { gc_stats->num_keys_expired++; gc_stats->bytes_expired += record.record_size(); TEST_SYNC_POINT(""BlobDBImpl::GCFileAndUpdateLSM:BeforeDelete""); WriteBatch delete_batch; Status delete_status = delete_batch.Delete(record.key); if (delete_status.ok()) { delete_status = db_impl_->WriteWithCallback(WriteOptions(), &delete_batch, &callback); } if (!delete_status.ok() && !delete_status.IsBusy()) { // We hit an error. s = delete_status; ROCKS_LOG_ERROR(db_options_.info_log, ""Error while deleting expired key: %s"", s.ToString().c_str()); break; } // Continue to next blob record or retry. continue; } // Relocate the blob record to new file. if (!newfile) { // new file std::string reason(""GC of ""); reason += bfptr->PathName(); newfile = NewBlobFile(reason); new_writer = CheckOrCreateWriterLocked(newfile); // Can't use header beyond this point newfile->header_ = std::move(header); newfile->header_valid_ = true; newfile->file_size_ = BlobLogHeader::kSize; newfile->SetColumnFamilyId(bfptr->column_family_id()); newfile->SetHasTTL(bfptr->HasTTL()); newfile->SetCompression(bfptr->compression()); newfile->expiration_range_ = bfptr->expiration_range_; s = new_writer->WriteHeader(newfile->header_); if (!s.ok()) { ROCKS_LOG_ERROR(db_options_.info_log, ""File: %s - header writing failed"", newfile->PathName().c_str()); break; } // We don't add the file to open_ttl_files_ or open_non_ttl_files_, to // avoid user writes writing to the file, and avoid // EvictExpiredFiles close the file by mistake. WriteLock wl(&mutex_); blob_files_.insert(std::make_pair(newfile->BlobFileNumber(), newfile)); } std::string new_index_entry; uint64_t new_blob_offset = 0; uint64_t new_key_offset = 0; // write the blob to the blob log. s = new_writer->AddRecord(record.key, record.value, record.expiration, &new_key_offset, &new_blob_offset); BlobIndex::EncodeBlob(&new_index_entry, newfile->BlobFileNumber(), new_blob_offset, record.value.size(), bdb_options_.compression); newfile->blob_count_++; newfile->file_size_ += BlobLogRecord::kHeaderSize + record.key.size() + record.value.size(); TEST_SYNC_POINT(""BlobDBImpl::GCFileAndUpdateLSM:BeforeRelocate""); WriteBatch rewrite_batch; Status rewrite_status = WriteBatchInternal::PutBlobIndex( &rewrite_batch, column_family_id, record.key, new_index_entry); if (rewrite_status.ok()) { rewrite_status = db_impl_->WriteWithCallback(WriteOptions(), &rewrite_batch, &callback); } if (rewrite_status.ok()) { gc_stats->num_keys_relocated++; gc_stats->bytes_relocated += record.record_size(); } else if (rewrite_status.IsBusy()) { // The key is overwritten in the meanwhile. Drop the blob record. gc_stats->num_keys_overwritten++; gc_stats->bytes_overwritten += record.record_size(); } else { // We hit an error. s = rewrite_status; ROCKS_LOG_ERROR(db_options_.info_log, ""Error while relocating key: %s"", s.ToString().c_str()); break; } } // end of ReadRecord loop { WriteLock wl(&mutex_); ObsoleteBlobFile(bfptr, GetLatestSequenceNumber(), true /*update_size*/); } ROCKS_LOG_INFO( db_options_.info_log, ""%s blob file %"" PRIu64 "". Total blob records: %"" PRIu64 "", expired: %"" PRIu64 "" keys/%"" PRIu64 "" bytes, updated or deleted by user: %"" PRIu64 "" keys/%"" PRIu64 "" bytes, rewrite to new file: %"" PRIu64 "" keys/%"" PRIu64 "" bytes."", s.ok() ? ""Successfully garbage collected"" : ""Failed to garbage collect"", bfptr->BlobFileNumber(), gc_stats->blob_count, gc_stats->num_keys_expired, gc_stats->bytes_expired, gc_stats->num_keys_overwritten, gc_stats->bytes_overwritten, gc_stats->num_keys_relocated, gc_stats->bytes_relocated); RecordTick(statistics_, BLOB_DB_GC_NUM_FILES); RecordTick(statistics_, BLOB_DB_GC_NUM_KEYS_OVERWRITTEN, gc_stats->num_keys_overwritten); RecordTick(statistics_, BLOB_DB_GC_NUM_KEYS_EXPIRED, gc_stats->num_keys_expired); RecordTick(statistics_, BLOB_DB_GC_BYTES_OVERWRITTEN, gc_stats->bytes_overwritten); RecordTick(statistics_, BLOB_DB_GC_BYTES_EXPIRED, gc_stats->bytes_expired); if (newfile != nullptr) { { MutexLock l(&write_mutex_); CloseBlobFile(newfile); } total_blob_size_ += newfile->file_size_; ROCKS_LOG_INFO(db_options_.info_log, ""New blob file %"" PRIu64 ""."", newfile->BlobFileNumber()); RecordTick(statistics_, BLOB_DB_GC_NUM_NEW_FILES); RecordTick(statistics_, BLOB_DB_GC_NUM_KEYS_RELOCATED, gc_stats->num_keys_relocated); RecordTick(statistics_, BLOB_DB_GC_BYTES_RELOCATED, gc_stats->bytes_relocated); } if (!s.ok()) { RecordTick(statistics_, BLOB_DB_GC_FAILURES); } return s; } std::pair BlobDBImpl::DeleteObsoleteFiles(bool aborted) { if (aborted) { return std::make_pair(false, -1); } MutexLock delete_file_lock(&delete_file_mutex_); if (disable_file_deletions_ > 0) { return std::make_pair(true, -1); } std::list> tobsolete; { WriteLock wl(&mutex_); if (obsolete_files_.empty()) { return std::make_pair(true, -1); } tobsolete.swap(obsolete_files_); } bool file_deleted = false; for (auto iter = tobsolete.begin(); iter != tobsolete.end();) { auto bfile = *iter; { ReadLock lockbfile_r(&bfile->mutex_); if (VisibleToActiveSnapshot(bfile)) { ROCKS_LOG_INFO(db_options_.info_log, ""Could not delete file due to snapshot failure %s"", bfile->PathName().c_str()); ++iter; continue; } } ROCKS_LOG_INFO(db_options_.info_log, ""Will delete file due to snapshot success %s"", bfile->PathName().c_str()); blob_files_.erase(bfile->BlobFileNumber()); Status s = env_->DeleteFile(bfile->PathName()); if (!s.ok()) { ROCKS_LOG_ERROR(db_options_.info_log, ""File failed to be deleted as obsolete %s"", bfile->PathName().c_str()); ++iter; continue; } file_deleted = true; ROCKS_LOG_INFO(db_options_.info_log, ""File deleted as obsolete from blob dir %s"", bfile->PathName().c_str()); iter = tobsolete.erase(iter); } // directory change. Fsync if (file_deleted) { Status s = dir_ent_->Fsync(); if (!s.ok()) { ROCKS_LOG_ERROR(db_options_.info_log, ""Failed to sync dir %s: %s"", blob_dir_.c_str(), s.ToString().c_str()); } } // put files back into obsolete if for some reason, delete failed if (!tobsolete.empty()) { WriteLock wl(&mutex_); for (auto bfile : tobsolete) { obsolete_files_.push_front(bfile); } } return std::make_pair(!aborted, -1); } void BlobDBImpl::CopyBlobFiles( std::vector>* bfiles_copy) { ReadLock rl(&mutex_); for (auto const& p : blob_files_) { bfiles_copy->push_back(p.second); } } std::pair BlobDBImpl::RunGC(bool aborted) { if (aborted) { return std::make_pair(false, -1); } // TODO(yiwu): Garbage collection implementation. // reschedule return std::make_pair(true, -1); } Iterator* BlobDBImpl::NewIterator(const ReadOptions& read_options) { auto* cfd = reinterpret_cast(DefaultColumnFamily())->cfd(); // Get a snapshot to avoid blob file get deleted between we // fetch and index entry and reading from the file. ManagedSnapshot* own_snapshot = nullptr; const Snapshot* snapshot = read_options.snapshot; if (snapshot == nullptr) { own_snapshot = new ManagedSnapshot(db_); snapshot = own_snapshot->snapshot(); } auto* iter = db_impl_->NewIteratorImpl( read_options, cfd, snapshot->GetSequenceNumber(), nullptr /*read_callback*/, true /*allow_blob*/); return new BlobDBIterator(own_snapshot, iter, this, env_, statistics_); } Status DestroyBlobDB(const std::string& dbname, const Options& options, const BlobDBOptions& bdb_options) { const ImmutableDBOptions soptions(SanitizeOptions(dbname, options)); Env* env = soptions.env; Status status; std::string blobdir; blobdir = (bdb_options.path_relative) ? dbname + ""/"" + bdb_options.blob_dir : bdb_options.blob_dir; std::vector filenames; env->GetChildren(blobdir, &filenames); for (const auto& f : filenames) { uint64_t number; FileType type; if (ParseFileName(f, &number, &type) && type == kBlobFile) { Status del = env->DeleteFile(blobdir + ""/"" + f); if (status.ok() && !del.ok()) { status = del; } } } env->DeleteDir(blobdir); Status destroy = DestroyDB(dbname, options); if (status.ok() && !destroy.ok()) { status = destroy; } return status; } #ifndef NDEBUG Status BlobDBImpl::TEST_GetBlobValue(const Slice& key, const Slice& index_entry, PinnableSlice* value) { return GetBlobValue(key, index_entry, value); } std::vector> BlobDBImpl::TEST_GetBlobFiles() const { ReadLock l(&mutex_); std::vector> blob_files; for (auto& p : blob_files_) { blob_files.emplace_back(p.second); } return blob_files; } std::vector> BlobDBImpl::TEST_GetObsoleteFiles() const { ReadLock l(&mutex_); std::vector> obsolete_files; for (auto& bfile : obsolete_files_) { obsolete_files.emplace_back(bfile); } return obsolete_files; } void BlobDBImpl::TEST_DeleteObsoleteFiles() { DeleteObsoleteFiles(false /*abort*/); } Status BlobDBImpl::TEST_CloseBlobFile(std::shared_ptr& bfile) { MutexLock l(&write_mutex_); return CloseBlobFile(bfile); } void BlobDBImpl::TEST_ObsoleteBlobFile(std::shared_ptr& blob_file, SequenceNumber obsolete_seq, bool update_size) { return ObsoleteBlobFile(blob_file, obsolete_seq, update_size); } Status BlobDBImpl::TEST_GCFileAndUpdateLSM(std::shared_ptr& bfile, GCStats* gc_stats) { return GCFileAndUpdateLSM(bfile, gc_stats); } void BlobDBImpl::TEST_RunGC() { RunGC(false /*abort*/); } void BlobDBImpl::TEST_EvictExpiredFiles() { EvictExpiredFiles(false /*abort*/); } uint64_t BlobDBImpl::TEST_live_sst_size() { return live_sst_size_.load(); } #endif // !NDEBUG } // namespace blob_db } // namespace rocksdb #endif // ROCKSDB_LITE ",16157,True,3129.963254815383,median "//// DO NOT EDIT THIS FILE. IT WAS GENERATED. Manual changes to this file will be lost when it is generated again. Edit the files in the src/main/asciidoc/ directory instead. //// :jdkversion: 1.8 :github-tag: master :github-repo: spring-cloud/spring-cloud-stream-binder-rabbit :github-raw: https://raw.githubusercontent.com/{github-repo}/{github-tag} :github-code: https://github.com/{github-repo}/tree/{github-tag} image::https://circleci.com/gh/spring-cloud/spring-cloud-stream-binder-rabbit.svg?style=svg[""CircleCI"", link=""https://circleci.com/gh/spring-cloud/spring-cloud-stream-binder-rabbit""] image::https://codecov.io/gh/spring-cloud/spring-cloud-stream-binder-rabbit/branch/{github-tag}/graph/badge.svg[""codecov"", link=""https://codecov.io/gh/spring-cloud/spring-cloud-stream-binder-rabbit""] image::https://badges.gitter.im/spring-cloud/spring-cloud-stream-binder-rabbit.svg[Gitter, link=""https://gitter.im/spring-cloud/spring-cloud-stream-binder-rabbit?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge""] // ====================================================================================== //= Overview [partintro] -- This guide describes the RabbitMQ implementation of the Spring Cloud Stream Binder. It contains information about its design, usage and configuration options, as well as information on how the Stream Cloud Stream concepts map into RabbitMQ specific constructs. -- == Usage To use the RabbitMQ binder, you can add it to your Spring Cloud Stream application, by using the following Maven coordinates: [source,xml] ---- org.springframework.cloud spring-cloud-stream-binder-rabbit ---- Alternatively, you can use the Spring Cloud Stream RabbitMQ Starter, as follows: [source,xml] ---- org.springframework.cloud spring-cloud-starter-stream-rabbit ---- == RabbitMQ Binder Overview The following simplified diagram shows how the RabbitMQ binder operates: .RabbitMQ Binder image::{github-raw}/docs/src/main/asciidoc/images/rabbit-binder.png[width=300,scaledwidth=""50%""] By default, the RabbitMQ Binder implementation maps each destination to a `TopicExchange`. For each consumer group, a `Queue` is bound to that `TopicExchange`. Each consumer instance has a corresponding RabbitMQ `Consumer` instance for its group's `Queue`. For partitioned producers and consumers, the queues are suffixed with the partition index and use the partition index as the routing key. For anonymous consumers (those with no `group` property), an auto-delete queue (with a randomized unique name) is used. By using the optional `autoBindDlq` option, you can configure the binder to create and configure dead-letter queues (DLQs) (and a dead-letter exchange `DLX`, as well as routing infrastructure). By default, the dead letter queue has the name of the destination, appended with `.dlq`. If retry is enabled (`maxAttempts > 1`), failed messages are delivered to the DLQ after retries are exhausted. If retry is disabled (`maxAttempts = 1`), you should set `requeueRejected` to `false` (the default) so that failed messages are routed to the DLQ, instead of being re-queued. In addition, `republishToDlq` causes the binder to publish a failed message to the DLQ (instead of rejecting it). This feature lets additional information (such as the stack trace in the `x-exception-stacktrace` header) be added to the message in headers. See the <> for information about truncated stack traces. This option does not need retry enabled. You can republish a failed message after just one attempt. Starting with version 1.2, you can configure the delivery mode of republished messages. See the <>. If the stream listener throws an `ImmediateAcknowledgeAmqpException`, the DLQ is bypassed and the message simply discarded. Starting with version 2.1, this is true regardless of the setting of `republishToDlq`; previously it was only the case when `republishToDlq` was `false`. IMPORTANT: Setting `requeueRejected` to `true` (with `republishToDlq=false` ) causes the message to be re-queued and redelivered continually, which is likely not what you want unless the reason for the failure is transient. In general, you should enable retry within the binder by setting `maxAttempts` to greater than one or by setting `republishToDlq` to `true`. See <> for more information about these properties. The framework does not provide any standard mechanism to consume dead-letter messages (or to re-route them back to the primary queue). Some options are described in <>. NOTE: When multiple RabbitMQ binders are used in a Spring Cloud Stream application, it is important to disable 'RabbitAutoConfiguration' to avoid the same configuration from `RabbitAutoConfiguration` being applied to the two binders. You can exclude the class by using the `@SpringBootApplication` annotation. Starting with version 2.0, the `RabbitMessageChannelBinder` sets the `RabbitTemplate.userPublisherConnection` property to `true` so that the non-transactional producers avoid deadlocks on consumers, which can happen if cached connections are blocked because of a https://www.rabbitmq.com/memory.html[memory alarm] on the broker. NOTE: Currently, a `multiplex` consumer (a single consumer listening to multiple queues) is only supported for message-driven conssumers; polled consumers can only retrieve messages from a single queue. == Configuration Options This section contains settings specific to the RabbitMQ Binder and bound channels. For general binding configuration options and properties, see the https://cloud.spring.io/spring-cloud-static/spring-cloud-stream/current/reference/html/spring-cloud-stream.html#_configuration_options[Spring Cloud Stream core documentation]. [[rabbit-binder-properties]] === RabbitMQ Binder Properties By default, the RabbitMQ binder uses Spring Boot's `ConnectionFactory`. Conseuqently, it supports all Spring Boot configuration options for RabbitMQ. (For reference, see the https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#common-application-properties[Spring Boot documentation]). RabbitMQ configuration options use the `spring.rabbitmq` prefix. In addition to Spring Boot options, the RabbitMQ binder supports the following properties: spring.cloud.stream.rabbit.binder.adminAddresses:: A comma-separated list of RabbitMQ management plugin URLs. Only used when `nodes` contains more than one entry. Each entry in this list must have a corresponding entry in `spring.rabbitmq.addresses`. Only needed if you use a RabbitMQ cluster and wish to consume from the node that hosts the queue. See https://docs.spring.io/spring-amqp/reference/html/_reference.html#queue-affinity[Queue Affinity and the LocalizedQueueConnectionFactory] for more information. + Default: empty. spring.cloud.stream.rabbit.binder.nodes:: A comma-separated list of RabbitMQ node names. When more than one entry, used to locate the server address where a queue is located. Each entry in this list must have a corresponding entry in `spring.rabbitmq.addresses`. Only needed if you use a RabbitMQ cluster and wish to consume from the node that hosts the queue. See https://docs.spring.io/spring-amqp/reference/html/_reference.html#queue-affinity[Queue Affinity and the LocalizedQueueConnectionFactory] for more information. + Default: empty. spring.cloud.stream.rabbit.binder.compressionLevel:: The compression level for compressed bindings. See `java.util.zip.Deflater`. + Default: `1` (BEST_LEVEL). spring.cloud.stream.binder.connection-name-prefix:: A connection name prefix used to name the connection(s) created by this binder. The name is this prefix followed by `#n`, where `n` increments each time a new connection is opened. + Default: none (Spring AMQP default). === RabbitMQ Consumer Properties The following properties are available for Rabbit consumers only and must be prefixed with `spring.cloud.stream.rabbit.bindings..consumer.`. However if the same set of properties needs to be applied to most bindings, to avoid repetition, Spring Cloud Stream supports setting values for all channels, in the format of `spring.cloud.stream.rabbit.default.=`. Also, keep in mind that binding specific property will override its equivalent in the default. acknowledgeMode:: The acknowledge mode. + Default: `AUTO`. anonymousGroupPrefix:: When the binding has no `group` property, an anonymous, auto-delete queue is bound to the destination exchange. The default naming stragegy for such queues results in a queue named `anonymous.`. Set this property to change the prefix to something other than the default. + Default: `anonymous.`. autoBindDlq:: Whether to automatically declare the DLQ and bind it to the binder DLX. + Default: `false`. bindingRoutingKey:: The routing key with which to bind the queue to the exchange (if `bindQueue` is `true`). Can be multiple keys - see `bindingRoutingKeyDelimiter`. For partitioned destinations, `-` is appended to each key. + Default: `#`. bindingRoutingKeyDelimiter:: When this is not null, 'bindingRoutingKey' is considered to be a list of keys delimited by this value; often a comma is used. + Default: `null`. bindQueue:: Whether to declare the queue and bind it to the destination exchange. Set it to `false` if you have set up your own infrastructure and have previously created and bound the queue. + Default: `true`. consumerTagPrefix:: Used to create the consumer tag(s); will be appended by `#n` where `n` increments for each consumer created. Example: `${spring.application.name}-${spring.cloud.stream.bindings.input.group}-${spring.cloud.stream.instance-index}`. + Default: none - the broker will generate random consumer tags. containerType:: Select the type of listener container to be used. See https://docs.spring.io/spring-amqp/reference/html/_reference.html#choose-container[Choosing a Container] in the Spring AMQP documentation for more information. + Default: `simple` deadLetterQueueName:: The name of the DLQ + Default: `prefix+destination.dlq` deadLetterExchange:: A DLX to assign to the queue. Relevant only if `autoBindDlq` is `true`. + Default: 'prefix+DLX' deadLetterExchangeType:: The type of the DLX to assign to the queue. Relevant only if `autoBindDlq` is `true`. + Default: 'direct' deadLetterRoutingKey:: A dead letter routing key to assign to the queue. Relevant only if `autoBindDlq` is `true`. + Default: `destination` declareDlx:: Whether to declare the dead letter exchange for the destination. Relevant only if `autoBindDlq` is `true`. Set to `false` if you have a pre-configured DLX. + Default: `true`. declareExchange:: Whether to declare the exchange for the destination. + Default: `true`. delayedExchange:: Whether to declare the exchange as a `Delayed Message Exchange`. Requires the delayed message exchange plugin on the broker. The `x-delayed-type` argument is set to the `exchangeType`. + Default: `false`. dlqBindingArguments:: Arguments applied when binding the dlq to the dead letter exchange; used with `headers` `deadLetterExchangeType` to specify headers to match on. For example `...dlqBindingArguments.x-match=any`, `...dlqBindingArguments.someHeader=someValue`. + Default: empty dlqDeadLetterExchange:: If a DLQ is declared, a DLX to assign to that queue. + Default: `none` dlqDeadLetterRoutingKey:: If a DLQ is declared, a dead letter routing key to assign to that queue. + Default: `none` dlqExpires:: How long before an unused dead letter queue is deleted (in milliseconds). + Default: `no expiration` dlqLazy:: Declare the dead letter queue with the `x-queue-mode=lazy` argument. See https://www.rabbitmq.com/lazy-queues.html[""`Lazy Queues`""]. Consider using a policy instead of this setting, because using a policy allows changing the setting without deleting the queue. + Default: `false`. dlqMaxLength:: Maximum number of messages in the dead letter queue. + Default: `no limit` dlqMaxLengthBytes:: Maximum number of total bytes in the dead letter queue from all messages. + Default: `no limit` dlqMaxPriority:: Maximum priority of messages in the dead letter queue (0-255). + Default: `none` dlqOverflowBehavior:: Action to take when `dlqMaxLength` or `dlqMaxLengthBytes` is exceeded; currently `drop-head` or `reject-publish` but refer to the RabbitMQ documentation. + Default: `none` dlqQuorum.deliveryLimit:: When `quorum.enabled=true`, set a delivery limit after which the message is dropped or dead-lettered. + Default: none - broker default will apply. dlqQuorum.enabled:: When true, create a quorum dead letter queue instead of a classic queue. + Default: false dlqQuorum.initialQuorumSize:: When `quorum.enabled=true`, set the initial quorum size. + Default: none - broker default will apply. dlqSingleActiveConsumer:: Set to true to set the `x-single-active-consumer` queue property to true. + Default: `false` dlqTtl:: Default time to live to apply to the dead letter queue when declared (in milliseconds). + Default: `no limit` durableSubscription:: Whether the subscription should be durable. Only effective if `group` is also set. + Default: `true`. exchangeAutoDelete:: If `declareExchange` is true, whether the exchange should be auto-deleted (that is, removed after the last queue is removed). + Default: `true`. exchangeDurable:: If `declareExchange` is true, whether the exchange should be durable (that is, it survives broker restart). + Default: `true`. exchangeType:: The exchange type: `direct`, `fanout`, `headers` or `topic` for non-partitioned destinations and `direct`, headers or `topic` for partitioned destinations. + Default: `topic`. exclusive:: Whether to create an exclusive consumer. Concurrency should be 1 when this is `true`. Often used when strict ordering is required but enabling a hot standby instance to take over after a failure. See `recoveryInterval`, which controls how often a standby instance attempts to consume. Consider using `singleActiveConsumer` instead when using RabbitMQ 3.8 or later. + Default: `false`. expires:: How long before an unused queue is deleted (in milliseconds). + Default: `no expiration` failedDeclarationRetryInterval:: The interval (in milliseconds) between attempts to consume from a queue if it is missing. + Default: 5000 [[spring-cloud-stream-rabbit-frame-max-headroom]] frameMaxHeadroom:: The number of bytes to reserve for other headers when adding the stack trace to a DLQ message header. All headers must fit within the `frame_max` size configured on the broker. Stack traces can be large; if the size plus this property exceeds `frame_max` then the stack trace will be truncated. A WARN log will be written; consider increasing the `frame_max` or reducing the stack trace by catching the exception and throwing one with a smaller stack trace. + Default: 20000 headerPatterns:: Patterns for headers to be mapped from inbound messages. + Default: `['*']` (all headers). lazy:: Declare the queue with the `x-queue-mode=lazy` argument. See https://www.rabbitmq.com/lazy-queues.html[""`Lazy Queues`""]. Consider using a policy instead of this setting, because using a policy allows changing the setting without deleting the queue. + Default: `false`. maxConcurrency:: The maximum number of consumers. Not supported when the `containerType` is `direct`. + Default: `1`. maxLength:: The maximum number of messages in the queue. + Default: `no limit` maxLengthBytes:: The maximum number of total bytes in the queue from all messages. + Default: `no limit` maxPriority:: The maximum priority of messages in the queue (0-255). + Default: `none` missingQueuesFatal:: When the queue cannot be found, whether to treat the condition as fatal and stop the listener container. Defaults to `false` so that the container keeps trying to consume from the queue -- for example, when using a cluster and the node hosting a non-HA queue is down. + Default: `false` overflowBehavior:: Action to take when `maxLength` or `maxLengthBytes` is exceeded; currently `drop-head` or `reject-publish` but refer to the RabbitMQ documentation. + Default: `none` prefetch:: Prefetch count. + Default: `1`. prefix:: A prefix to be added to the name of the `destination` and queues. + Default: """". queueBindingArguments:: Arguments applied when binding the queue to the exchange; used with `headers` `exchangeType` to specify headers to match on. For example `...queueBindingArguments.x-match=any`, `...queueBindingArguments.someHeader=someValue`. + Default: empty queueDeclarationRetries:: The number of times to retry consuming from a queue if it is missing. Relevant only when `missingQueuesFatal` is `true`. Otherwise, the container keeps retrying indefinitely. Not supported when the `containerType` is `direct`. + Default: `3` queueNameGroupOnly:: When true, consume from a queue with a name equal to the `group`. Otherwise the queue name is `destination.group`. This is useful, for example, when using Spring Cloud Stream to consume from an existing RabbitMQ queue. + Default: false. quorum.deliveryLimit:: When `quorum.enabled=true`, set a delivery limit after which the message is dropped or dead-lettered. + Default: none - broker default will apply. quorum.enabled:: When true, create a quorum queue instead of a classic queue. + Default: false quorum.initialQuorumSize:: When `quorum.enabled=true`, set the initial quorum size. + Default: none - broker default will apply. recoveryInterval:: The interval between connection recovery attempts, in milliseconds. + Default: `5000`. requeueRejected:: Whether delivery failures should be re-queued when retry is disabled or `republishToDlq` is `false`. + Default: `false`. [[spring-cloud-stream-rabbit-republish-delivery-mode]] republishDeliveryMode:: When `republishToDlq` is `true`, specifies the delivery mode of the republished message. + Default: `DeliveryMode.PERSISTENT` republishToDlq:: By default, messages that fail after retries are exhausted are rejected. If a dead-letter queue (DLQ) is configured, RabbitMQ routes the failed message (unchanged) to the DLQ. If set to `true`, the binder republishs failed messages to the DLQ with additional headers, including the exception message and stack trace from the cause of the final failure. Also see the <>. + Default: `true` singleActiveConsumer:: Set to true to set the `x-single-active-consumer` queue property to true. + Default: `false` transacted:: Whether to use transacted channels. + Default: `false`. ttl:: Default time to live to apply to the queue when declared (in milliseconds). + Default: `no limit` txSize:: The number of deliveries between acks. Not supported when the `containerType` is `direct`. + Default: `1`. === Advanced Listener Container Configuration To set listener container properties that are not exposed as binder or binding properties, add a single bean of type `ListenerContainerCustomizer` to the application context. The binder and binding properties will be set and then the customizer will be called. The customizer (`configure()` method) is provided with the queue name as well as the consumer group as arguments. === Advanced Queue/Exchange/Binding Configuration From time to time, the RabbitMQ team add new features that are enabled by setting some argument when declaring, for example, a queue. Generally, such features are enabled in the binder by adding appropriate properties, but this may not be immediately available in a current version. Starting with version 3.0.1, you can now add `DeclarableCustomizer` bean(s) to the application context to modify a `Declarable` (`Queue`, `Exchange` or `Binding`) just before the declaration is performed. This allows you to add arguments that are not currently directly supported by the binder. [[rabbit-receiving-batch]] === Receiving Batched Messages With the RabbitMQ binder, there are two types of batches handled by consumer bindings: ==== Batches Created by Producers Normally, if a producer binding has `batch-enabled=true` (see <>), or a message is created by a `BatchingRabbitTemplate`, elements of the batch are returned as individual calls to the listener method. Starting with version 3.0, any such batch can be presented as a `List` to the listener method if `spring.cloud.stream.bindings..consumer.batch-mode` is set to `true`. ==== Consumer-side Batching Starting with version 3.1, the consumer can be configured to assemble multiple inbound messages into a batch which is presented to the application as a `List` of converted payloads. The following simple application demonstrates how to use this technique: ==== [source, properties] ---- spring.cloud.stream.bindings.input-in-0.group=someGroup spring.cloud.stream.bindings.input-in-0.consumer.batch-mode=true spring.cloud.stream.rabbit.bindings.input-in-0.consumer.enable-batching=true spring.cloud.stream.rabbit.bindings.input-in-0.consumer.batch-size=10 spring.cloud.stream.rabbit.bindings.input-in-0.consumer.receive-timeout=200 ---- ==== ==== [source, java] ---- @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Bean Consumer> input() { return list -> { System.out.println(""Received "" + list.size()); list.forEach(thing -> { System.out.println(thing); // ... }); }; } @Bean public ApplicationRunner runner(RabbitTemplate template) { return args -> { template.convertAndSend(""input-in-0.someGroup"", ""{\\""field\\"":\\""value1\\""}""); template.convertAndSend(""input-in-0.someGroup"", ""{\\""field\\"":\\""value2\\""}""); }; } public static class Thing { private String field; public Thing() { } public Thing(String field) { this.field = field; } public String getField() { return this.field; } public void setField(String field) { this.field = field; } @Override public String toString() { return ""Thing [field="" + this.field + ""]""; } } } ---- ==== ==== [source] ---- Received 2 Thing [field=value1] Thing [field=value2] ---- ==== The number of messages in a batch is specified by the `batch-size` and `receive-timeout` properties; if the `receive-timeout` elapses with no new messages, a ""short"" batch is delivered. IMPORTANT: Consumer-side batching is only supported with `container-type=simple` (the default). If you wish to examine headers of consumer-side batched messages, you should consume `Message>`; the headers are a `List>` in a header `AmqpInboundChannelAdapter.CONSOLIDATED_HEADERS`, with the headers for each payload element in the corresponding index. Again, here is a simple example: ==== [source, java] ---- @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Bean Consumer>> input() { return msg -> { List things = msg.getPayload(); System.out.println(""Received "" + things.size()); @SuppressWarnings(""unchecked"") List> headers = (List>) msg.getHeaders().get(AmqpInboundChannelAdapter.CONSOLIDATED_HEADERS); for (int i = 0; i < things.size(); i++) { System.out.println(things.get(i) + "" myHeader="" + headers.get(i).get(""myHeader"")); // ... } }; } @Bean public ApplicationRunner runner(RabbitTemplate template) { return args -> { template.convertAndSend(""input-in-0.someGroup"", ""{\\""field\\"":\\""value1\\""}"", msg -> { msg.getMessageProperties().setHeader(""myHeader"", ""headerValue1""); return msg; }); template.convertAndSend(""input-in-0.someGroup"", ""{\\""field\\"":\\""value2\\""}"", msg -> { msg.getMessageProperties().setHeader(""myHeader"", ""headerValue2""); return msg; }); }; } public static class Thing { private String field; public Thing() { } public Thing(String field) { this.field = field; } public String getfield() { return this.field; } public void setfield(String field) { this.field = field; } @Override public String toString() { return ""Thing [field="" + this.field + ""]""; } } } ---- ==== ==== [source] ---- Received 2 Thing [field=value1] myHeader=headerValue1 Thing [field=value2] myHeader=headerValue2 ---- ==== [[rabbit-prod-props]] === Rabbit Producer Properties The following properties are available for Rabbit producers only and must be prefixed with `spring.cloud.stream.rabbit.bindings..producer.`. However if the same set of properties needs to be applied to most bindings, to avoid repetition, Spring Cloud Stream supports setting values for all channels, in the format of `spring.cloud.stream.rabbit.default.=`. Also, keep in mind that binding specific property will override its equivalent in the default. autoBindDlq:: Whether to automatically declare the DLQ and bind it to the binder DLX. + Default: `false`. batchingEnabled:: Whether to enable message batching by producers. Messages are batched into one message according to the following properties (described in the next three entries in this list): 'batchSize', `batchBufferLimit`, and `batchTimeout`. See https://docs.spring.io/spring-amqp//reference/html/_reference.html#template-batching[Batching] for more information. Also see <>. + Default: `false`. batchSize:: The number of messages to buffer when batching is enabled. + Default: `100`. batchBufferLimit:: The maximum buffer size when batching is enabled. + Default: `10000`. batchTimeout:: The batch timeout when batching is enabled. + Default: `5000`. bindingRoutingKey:: The routing key with which to bind the queue to the exchange (if `bindQueue` is `true`). Can be multiple keys - see `bindingRoutingKeyDelimiter`. For partitioned destinations, `-n` is appended to each key. Only applies if `requiredGroups` are provided and then only to those groups. + Default: `#`. bindingRoutingKeyDelimiter:: When this is not null, 'bindingRoutingKey' is considered to be a list of keys delimited by this value; often a comma is used. Only applies if `requiredGroups` are provided and then only to those groups. + Default: `null`. bindQueue:: Whether to declare the queue and bind it to the destination exchange. Set it to `false` if you have set up your own infrastructure and have previously created and bound the queue. Only applies if `requiredGroups` are provided and then only to those groups. + Default: `true`. compress:: Whether data should be compressed when sent. + Default: `false`. confirmAckChannel:: When `errorChannelEnabled` is true, a channel to which to send positive delivery acknowledgments (aka publisher confirms). If the channel does not exist, a `DirectChannel` is registered with this name. The connection factory must be configured to enable publisher confirms. Mutually exclusive with `useConfirmHeader`. + Default: `nullChannel` (acks are discarded). deadLetterQueueName:: The name of the DLQ Only applies if `requiredGroups` are provided and then only to those groups. + Default: `prefix+destination.dlq` deadLetterExchange:: A DLX to assign to the queue. Relevant only when `autoBindDlq` is `true`. Applies only when `requiredGroups` are provided and then only to those groups. + Default: 'prefix+DLX' deadLetterExchangeType:: The type of the DLX to assign to the queue. Relevant only if `autoBindDlq` is `true`. Applies only when `requiredGroups` are provided and then only to those groups. + Default: 'direct' deadLetterRoutingKey:: A dead letter routing key to assign to the queue. Relevant only when `autoBindDlq` is `true`. Applies only when `requiredGroups` are provided and then only to those groups. + Default: `destination` declareDlx:: Whether to declare the dead letter exchange for the destination. Relevant only if `autoBindDlq` is `true`. Set to `false` if you have a pre-configured DLX. Applies only when `requiredGroups` are provided and then only to those groups. + Default: `true`. declareExchange:: Whether to declare the exchange for the destination. + Default: `true`. delayExpression:: A SpEL expression to evaluate the delay to apply to the message (`x-delay` header). It has no effect if the exchange is not a delayed message exchange. + Default: No `x-delay` header is set. delayedExchange:: Whether to declare the exchange as a `Delayed Message Exchange`. Requires the delayed message exchange plugin on the broker. The `x-delayed-type` argument is set to the `exchangeType`. + Default: `false`. deliveryMode:: The delivery mode. + Default: `PERSISTENT`. dlqBindingArguments:: Arguments applied when binding the dlq to the dead letter exchange; used with `headers` `deadLetterExchangeType` to specify headers to match on. For example `...dlqBindingArguments.x-match=any`, `...dlqBindingArguments.someHeader=someValue`. Applies only when `requiredGroups` are provided and then only to those groups. + Default: empty dlqDeadLetterExchange:: When a DLQ is declared, a DLX to assign to that queue. Applies only if `requiredGroups` are provided and then only to those groups. + Default: `none` dlqDeadLetterRoutingKey:: When a DLQ is declared, a dead letter routing key to assign to that queue. Applies only when `requiredGroups` are provided and then only to those groups. + Default: `none` dlqExpires:: How long (in milliseconds) before an unused dead letter queue is deleted. Applies only when `requiredGroups` are provided and then only to those groups. + Default: `no expiration` dlqLazy:: Declare the dead letter queue with the `x-queue-mode=lazy` argument. See https://www.rabbitmq.com/lazy-queues.html[""`Lazy Queues`""]. Consider using a policy instead of this setting, because using a policy allows changing the setting without deleting the queue. Applies only when `requiredGroups` are provided and then only to those groups. + dlqMaxLength:: Maximum number of messages in the dead letter queue. Applies only if `requiredGroups` are provided and then only to those groups. + Default: `no limit` dlqMaxLengthBytes:: Maximum number of total bytes in the dead letter queue from all messages. Applies only when `requiredGroups` are provided and then only to those groups. + Default: `no limit` dlqMaxPriority:: Maximum priority of messages in the dead letter queue (0-255) Applies only when `requiredGroups` are provided and then only to those groups. + Default: `none` dlqQuorum.deliveryLimit:: When `quorum.enabled=true`, set a delivery limit after which the message is dropped or dead-lettered. Applies only when `requiredGroups` are provided and then only to those groups. + Default: none - broker default will apply. dlqQuorum.enabled:: When true, create a quorum dead letter queue instead of a classic queue. Applies only when `requiredGroups` are provided and then only to those groups. + Default: false dlqQuorum.initialQuorumSize:: When `quorum.enabled=true`, set the initial quorum size. Applies only when `requiredGroups` are provided and then only to those groups. + Default: none - broker default will apply. dlqSingleActiveConsumer:: Set to true to set the `x-single-active-consumer` queue property to true. Applies only when `requiredGroups` are provided and then only to those groups. + Default: `false` dlqTtl:: Default time (in milliseconds) to live to apply to the dead letter queue when declared. Applies only when `requiredGroups` are provided and then only to those groups. + Default: `no limit` exchangeAutoDelete:: If `declareExchange` is `true`, whether the exchange should be auto-delete (it is removed after the last queue is removed). + Default: `true`. exchangeDurable:: If `declareExchange` is `true`, whether the exchange should be durable (survives broker restart). + Default: `true`. exchangeType:: The exchange type: `direct`, `fanout`, `headers` or `topic` for non-partitioned destinations and `direct`, `headers` or `topic` for partitioned destinations. + Default: `topic`. expires:: How long (in milliseconds) before an unused queue is deleted. Applies only when `requiredGroups` are provided and then only to those groups. + Default: `no expiration` headerPatterns:: Patterns for headers to be mapped to outbound messages. + Default: `['*']` (all headers). lazy:: Declare the queue with the `x-queue-mode=lazy` argument. See https://www.rabbitmq.com/lazy-queues.html[""`Lazy Queues`""]. Consider using a policy instead of this setting, because using a policy allows changing the setting without deleting the queue. Applies only when `requiredGroups` are provided and then only to those groups. + Default: `false`. maxLength:: Maximum number of messages in the queue. Applies only when `requiredGroups` are provided and then only to those groups. + Default: `no limit` maxLengthBytes:: Maximum number of total bytes in the queue from all messages. Only applies if `requiredGroups` are provided and then only to those groups. + Default: `no limit` maxPriority:: Maximum priority of messages in the queue (0-255). Only applies if `requiredGroups` are provided and then only to those groups. + Default: `none` prefix:: A prefix to be added to the name of the `destination` exchange. + Default: """". queueBindingArguments:: Arguments applied when binding the queue to the exchange; used with `headers` `exchangeType` to specify headers to match on. For example `...queueBindingArguments.x-match=any`, `...queueBindingArguments.someHeader=someValue`. Applies only when `requiredGroups` are provided and then only to those groups. + Default: empty queueNameGroupOnly:: When `true`, consume from a queue with a name equal to the `group`. Otherwise the queue name is `destination.group`. This is useful, for example, when using Spring Cloud Stream to consume from an existing RabbitMQ queue. Applies only when `requiredGroups` are provided and then only to those groups. + Default: false. quorum.deliveryLimit:: When `quorum.enabled=true`, set a delivery limit after which the message is dropped or dead-lettered. Applies only when `requiredGroups` are provided and then only to those groups. + Default: none - broker default will apply. quorum.enabled:: When true, create a quorum queue instead of a classic queue. Applies only when `requiredGroups` are provided and then only to those groups. + Default: false quorum.initialQuorumSize:: When `quorum.enabled=true`, set the initial quorum size. Applies only when `requiredGroups` are provided and then only to those groups. + Default: none - broker default will apply. routingKeyExpression:: A SpEL expression to determine the routing key to use when publishing messages. For a fixed routing key, use a literal expression, such as `routingKeyExpression='my.routingKey'` in a properties file or `routingKeyExpression: '''my.routingKey'''` in a YAML file. + Default: `destination` or `destination-` for partitioned destinations. singleActiveConsumer:: Set to true to set the `x-single-active-consumer` queue property to true. Applies only when `requiredGroups` are provided and then only to those groups. + Default: `false` transacted:: Whether to use transacted channels. + Default: `false`. ttl:: Default time (in milliseconds) to live to apply to the queue when declared. Applies only when `requiredGroups` are provided and then only to those groups. + Default: `no limit` useConfirmHeader:: See <>. Mutually exclusive with `confirmAckChannel`. + NOTE: In the case of RabbitMQ, content type headers can be set by external applications. Spring Cloud Stream supports them as part of an extended internal protocol used for any type of transport -- including transports, such as Kafka (prior to 0.11), that do not natively support headers. [[publisher-confirms]] === Publisher Confirms There are two mechanisms to get the result of publishing a message; in each case, the connection factory must have `publisherConfirmType` set `ConfirmType.CORRELATED`. The ""legacy"" mechanism is to set the `confirmAckChannel` to the bean name of a message channel from which you can retrieve the confirmations asynchronously; negative acks are sent to the error channel (if enabled) - see <>. The preferred mechanism, added in version 3.1 is to use a correlation data header and wait for the result via its `Future` property. This is particularly useful with a batch listener because you can send multiple messages before waiting for the result. To use this technique, set the `useConfirmHeader` property to true The following simple application is an example of using this technique: ==== [source, properties] ---- spring.cloud.stream.bindings.input-in-0.group=someGroup spring.cloud.stream.bindings.input-in-0.consumer.batch-mode=true spring.cloud.stream.source=output spring.cloud.stream.bindings.output-out-0.producer.error-channel-enabled=true spring.cloud.stream.rabbit.bindings.output-out-0.producer.useConfirmHeader=true spring.cloud.stream.rabbit.bindings.input-in-0.consumer.auto-bind-dlq=true spring.cloud.stream.rabbit.bindings.input-in-0.consumer.batch-size=10 spring.rabbitmq.publisher-confirm-type=correlated spring.rabbitmq.publisher-returns=true ---- ==== ==== [source, java] ---- @SpringBootApplication public class Application { private static final Logger log = LoggerFactory.getLogger(Application.class); public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Autowired private StreamBridge bridge; @Bean Consumer> input() { return list -> { List results = new ArrayList<>(); list.forEach(str -> { log.info(""Received: "" + str); MyCorrelationData corr = new MyCorrelationData(UUID.randomUUID().toString(), str); results.add(corr); this.bridge.send(""output-out-0"", MessageBuilder.withPayload(str.toUpperCase()) .setHeader(AmqpHeaders.PUBLISH_CONFIRM_CORRELATION, corr) .build()); }); results.forEach(correlation -> { try { Confirm confirm = correlation.getFuture().get(10, TimeUnit.SECONDS); log.info(confirm + "" for "" + correlation.getPayload()); if (correlation.getReturnedMessage() != null) { log.error(""Message for "" + correlation.getPayload() + "" was returned ""); // try to re-publish, send a DLQ, etc } } catch (InterruptedException e) { Thread.currentThread().interrupt(); e.printStackTrace(); } catch (ExecutionException | TimeoutException e) { e.printStackTrace(); } }); }; } @Bean public ApplicationRunner runner(BatchingRabbitTemplate template) { return args -> IntStream.range(0, 10).forEach(i -> template.convertAndSend(""input-in-0"", ""input-in-0.rbgh303"", ""foo"" + i)); } @Bean public BatchingRabbitTemplate template(CachingConnectionFactory cf, TaskScheduler taskScheduler) { BatchingStrategy batchingStrategy = new SimpleBatchingStrategy(10, 1000000, 1000); return new BatchingRabbitTemplate(cf, batchingStrategy, taskScheduler); } } class MyCorrelationData extends CorrelationData { private final String payload; MyCorrelationData(String id, String payload) { super(id); this.payload = payload; } public String getPayload() { return this.payload; } } ---- ==== As you can see, we send each message and then await for the publication results. If the messages can't be routed, then correlation data is populated with the returned message before the future is completed. IMPORTANT: The correlation data must be provided with a unique `id` so that the framework can perform the correlation. You cannot set both `useConfirmHeader` and `confirmAckChannel` but you can still receive returned messages in the error channel when `useConfirmHeader` is true, but using the correlation header is more convenient. == Using Existing Queues/Exchanges By default, the binder will automatically provision a topic exchange with the name being derived from the value of the destination binding property ``. The destination defaults to the binding name, if not provided. When binding a consumer, a queue will automatically be provisioned with the name `.` (if a `group` binding property is specified), or an anonymous, auto-delete queue when there is no `group`. The queue will be bound to the exchange with the ""match-all"" wildcard routing key (`#`) for a non-partitioned binding or `-` for a partitioned binding. The prefix is an empty `String` by default. If an output binding is specified with `requiredGroups`, a queue/binding will be provisioned for each group. There are a number of rabbit-specific binding properties that allow you to modify this default behavior. If you have an existing exchange/queue that you wish to use, you can completely disable automatic provisioning as follows, assuming the exchange is named `myExchange` and the queue is named `myQueue`: * `spring.cloud.stream.bindings..destination=myExhange` * `spring.cloud.stream.bindings..group=myQueue` * `spring.cloud.stream.rabbit.bindings..consumer.bindQueue=false` * `spring.cloud.stream.rabbit.bindings..consumer.declareExchange=false` * `spring.cloud.stream.rabbit.bindings..consumer.queueNameGroupOnly=true` If you want the binder to provision the queue/exchange, but you want to do it using something other than the defaults discussed here, use the following properties. Refer to the property documentation above for more information. * `spring.cloud.stream.rabbit.bindings..consumer.bindingRoutingKey=myRoutingKey` * `spring.cloud.stream.rabbit.bindings..consumer.exchangeType=` * `spring.cloud.stream.rabbit.bindings..producer.routingKeyExpression='myRoutingKey'` There are similar properties used when declaring a dead-letter exchange/queue, when `autoBindDlq` is `true`. == Retry With the RabbitMQ Binder When retry is enabled within the binder, the listener container thread is suspended for any back off periods that are configured. This might be important when strict ordering is required with a single consumer. However, for other use cases, it prevents other messages from being processed on that thread. An alternative to using binder retry is to set up dead lettering with time to live on the dead-letter queue (DLQ) as well as dead-letter configuration on the DLQ itself. See ""`<>`"" for more information about the properties discussed here. You can use the following example configuration to enable this feature: * Set `autoBindDlq` to `true`. The binder create a DLQ. Optionally, you can specify a name in `deadLetterQueueName`. * Set `dlqTtl` to the back off time you want to wait between redeliveries. * Set the `dlqDeadLetterExchange` to the default exchange. Expired messages from the DLQ are routed to the original queue, because the default `deadLetterRoutingKey` is the queue name (`destination.group`). Setting to the default exchange is achieved by setting the property with no value, as shown in the next example. To force a message to be dead-lettered, either throw an `AmqpRejectAndDontRequeueException` or set `requeueRejected` to `false` (the default) and throw any exception. The loop continue without end, which is fine for transient problems, but you may want to give up after some number of attempts. Fortunately, RabbitMQ provides the `x-death` header, which lets you determine how many cycles have occurred. To acknowledge a message after giving up, throw an `ImmediateAcknowledgeAmqpException`. === Putting it All Together The following configuration creates an exchange `myDestination` with queue `myDestination.consumerGroup` bound to a topic exchange with a wildcard routing key `#`: [source] --- spring.cloud.stream.bindings.input.destination=myDestination spring.cloud.stream.bindings.input.group=consumerGroup #disable binder retries spring.cloud.stream.bindings.input.consumer.max-attempts=1 #dlx/dlq setup spring.cloud.stream.rabbit.bindings.input.consumer.auto-bind-dlq=true spring.cloud.stream.rabbit.bindings.input.consumer.dlq-ttl=5000 spring.cloud.stream.rabbit.bindings.input.consumer.dlq-dead-letter-exchange= --- This configuration creates a DLQ bound to a direct exchange (`DLX`) with a routing key of `myDestination.consumerGroup`. When messages are rejected, they are routed to the DLQ. After 5 seconds, the message expires and is routed to the original queue by using the queue name as the routing key, as shown in the following example: .Spring Boot application [source, java] ---- @SpringBootApplication @EnableBinding(Sink.class) public class XDeathApplication { public static void main(String[] args) { SpringApplication.run(XDeathApplication.class, args); } @StreamListener(Sink.INPUT) public void listen(String in, @Header(name = ""x-death"", required = false) Map death) { if (death != null && death.get(""count"").equals(3L)) { // giving up - don't send to DLX throw new ImmediateAcknowledgeAmqpException(""Failed after 4 attempts""); } throw new AmqpRejectAndDontRequeueException(""failed""); } } ---- Notice that the count property in the `x-death` header is a `Long`. [[rabbit-error-channels]] == Error Channels Starting with version 1.3, the binder unconditionally sends exceptions to an error channel for each consumer destination and can also be configured to send async producer send failures to an error channel. See ""`<>`"" for more information. RabbitMQ has two types of send failures: * Returned messages, * Negatively acknowledged https://www.rabbitmq.com/confirms.html[Publisher Confirms]. The latter is rare. According to the RabbitMQ documentation ""[A nack] will only be delivered if an internal error occurs in the Erlang process responsible for a queue."". You can also get a negative acknowledgment if you publish to a bounded queue with `reject-publish` queue overflow behavior. As well as enabling producer error channels (as described in ""`<>`""), the RabbitMQ binder only sends messages to the channels if the connection factory is appropriately configured, as follows: * `ccf.setPublisherConfirms(true);` * `ccf.setPublisherReturns(true);` When using Spring Boot configuration for the connection factory, set the following properties: * `spring.rabbitmq.publisher-confirms` * `spring.rabbitmq.publisher-returns` The payload of the `ErrorMessage` for a returned message is a `ReturnedAmqpMessageException` with the following properties: * `failedMessage`: The spring-messaging `Message` that failed to be sent. * `amqpMessage`: The raw spring-amqp `Message`. * `replyCode`: An integer value indicating the reason for the failure (for example, 312 - No route). * `replyText`: A text value indicating the reason for the failure (for example, `NO_ROUTE`). * `exchange`: The exchange to which the message was published. * `routingKey`: The routing key used when the message was published. Also see <> for an alternative mechanism to receive returned messages. For negatively acknowledged confirmations, the payload is a `NackedAmqpMessageException` with the following properties: * `failedMessage`: The spring-messaging `Message` that failed to be sent. * `nackReason`: A reason (if available -- you may need to examine the broker logs for more information). There is no automatic handling of these exceptions (such as sending to a <>). You can consume these exceptions with your own Spring Integration flow. = Appendices [appendix] [[building]] == Building :jdkversion: 1.8 === Basic Compile and Test To build the source you will need to install JDK {jdkversion}. The build uses the Maven wrapper so you don't have to install a specific version of Maven. To enable the tests, you should have RabbitMQ server running on localhost and the default port (5672) before building. The main build command is ---- $ ./mvnw clean install ---- You can also add '-DskipTests' if you like, to avoid running the tests. NOTE: You can also install Maven (>=3.3.3) yourself and run the `mvn` command in place of `./mvnw` in the examples below. If you do that you also might need to add `-P spring` if your local Maven settings do not contain repository declarations for spring pre-release artifacts. NOTE: Be aware that you might need to increase the amount of memory available to Maven by setting a `MAVEN_OPTS` environment variable with a value like `-Xmx512m -XX:MaxPermSize=128m`. We try to cover this in the `.mvn` configuration, so if you find you have to do it to make a build succeed, please raise a ticket to get the settings added to source control. The projects that require middleware generally include a `docker-compose.yml`, so consider using https://compose.docker.io/[Docker Compose] to run the middeware servers in Docker containers. === Documentation There is a ""docs"" profile that will generate documentation. `./mvnw clean package -Pdocs -DskipTests` The reference documentation can then be found in `docs/target/contents/reference`. === Working with the code If you don't have an IDE preference we would recommend that you use https://www.springsource.com/developer/sts[Spring Tools Suite] or https://eclipse.org[Eclipse] when working with the code. We use the https://eclipse.org/m2e/[m2eclipe] eclipse plugin for maven support. Other IDEs and tools should also work without issue. ==== Importing into eclipse with m2eclipse We recommend the https://eclipse.org/m2e/[m2eclipe] eclipse plugin when working with eclipse. If you don't already have m2eclipse installed it is available from the ""eclipse marketplace"". Unfortunately m2e does not yet support Maven 3.3, so once the projects are imported into Eclipse you will also need to tell m2eclipse to use the `.settings.xml` file for the projects. If you do not do this you may see many different errors related to the POMs in the projects. Open your Eclipse preferences, expand the Maven preferences, and select User Settings. In the User Settings field click Browse and navigate to the Spring Cloud project you imported selecting the `.settings.xml` file in that project. Click Apply and then OK to save the preference changes. NOTE: Alternatively you can copy the repository settings from https://github.com/spring-cloud/spring-cloud-build/blob/master/.settings.xml[`.settings.xml`] into your own `~/.m2/settings.xml`. ==== Importing into eclipse without m2eclipse If you prefer not to use m2eclipse you can generate eclipse project metadata using the following command: [indent=0] ---- $ ./mvnw eclipse:eclipse ---- The generated eclipse projects can be imported by selecting `import existing projects` from the `file` menu. [[contributing]] == Contributing Spring Cloud is released under the non-restrictive Apache 2.0 license, and follows a very standard Github development process, using Github tracker for issues and merging pull requests into master. If you want to contribute even something trivial please do not hesitate, but follow the guidelines below. === Sign the Contributor License Agreement Before we accept a non-trivial patch or pull request we will need you to sign the https://support.springsource.com/spring_committer_signup[contributor's agreement]. Signing the contributor's agreement does not grant anyone commit rights to the main repository, but it does mean that we can accept your contributions, and you will get an author credit if we do. Active contributors might be asked to join the core team, and given the ability to merge pull requests. === Code Conventions and Housekeeping None of these is essential for a pull request, but they will all help. They can also be added after the original pull request but before a merge. * Use the Spring Framework code format conventions. If you use Eclipse you can import formatter settings using the `eclipse-code-formatter.xml` file from the https://github.com/spring-cloud/build/tree/master/eclipse-coding-conventions.xml[Spring Cloud Build] project. If using IntelliJ, you can use the https://plugins.jetbrains.com/plugin/6546[Eclipse Code Formatter Plugin] to import the same file. * Make sure all new `.java` files to have a simple Javadoc class comment with at least an `@author` tag identifying you, and preferably at least a paragraph on what the class is for. * Add the ASF license header comment to all new `.java` files (copy from existing files in the project) * Add yourself as an `@author` to the .java files that you modify substantially (more than cosmetic changes). * Add some Javadocs and, if you change the namespace, some XSD doc elements. * A few unit tests would help a lot as well -- someone has to do it. * If no-one else is using your branch, please rebase it against the current master (or other target branch in the main project). * When writing a commit message please follow https://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html[these conventions], if you are fixing an existing issue please add `Fixes gh-XXXX` at the end of the commit message (where XXXX is the issue number). // ====================================================================================== ",12120,False,2226.0891653891367,median "= v1.Role {product-author} {product-version} :data-uri: :icons: :toc: macro :toc-title: :toclevels: 2 toc::[] == Description [%hardbreaks] Role is a namespaced, logical grouping of PolicyRules that can be referenced as a unit by a RoleBinding. == Object Schema Expand or mouse-over a field for more information about it. ++++
apiVersion:
kind:
metadata:
annotations:
[string]:
clusterName:
creationTimestamp:
deletionGracePeriodSeconds:
deletionTimestamp:
finalizers:
- [string]:
generateName:
generation:
:
pending:
- name:
result:
apiVersion:
code:
details:
causes:
- field:
message:
reason:
group:
kind:
name:
retryAfterSeconds:
uid:
kind:
message:
metadata:
continue:
resourceVersion:
selfLink:
reason:
status:
labels:
[string]:
name:
namespace:
ownerReferences:
- apiVersion:
blockOwnerDeletion:
controller:
kind:
name:
uid:
resourceVersion:
selfLink:
uid:
rules:
- apiGroups:
- - [string]:
nonResourceURLs:
- [string]:
resourceNames:
- [string]:
resources:
- [string]:
verbs:
- [string]:
++++ == Operations [[Post-apis-rbac.authorization.k8s.io-v1-namespaces-namespace-roles]] === Create a Role in a namespace Create a Role ==== HTTP request ---- POST /apis/rbac.authorization.k8s.io/v1/namespaces/$NAMESPACE/roles HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json' { ""kind"": ""Role"", ""apiVersion"": ""rbac.authorization.k8s.io/v1"", ... } ---- ==== Curl request ---- $ curl -k \\ -X POST \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json' \\ https://$ENDPOINT/apis/rbac.authorization.k8s.io/v1/namespaces/$NAMESPACE/roles <<'EOF' { ""kind"": ""Role"", ""apiVersion"": ""rbac.authorization.k8s.io/v1"", ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1.Role |=== ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.Role |201 Created|v1.Role |202 Accepted|v1.Role |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Get-apis-rbac.authorization.k8s.io-v1-namespaces-namespace-roles-name]] === Get a Role in a namespace Read the specified Role ==== HTTP request ---- GET /apis/rbac.authorization.k8s.io/v1/namespaces/$NAMESPACE/roles/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/rbac.authorization.k8s.io/v1/namespaces/$NAMESPACE/roles/$NAME ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the Role |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.Role |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Get-apis-rbac.authorization.k8s.io-v1-roles]] === Get all Roles List or watch objects of kind Role ==== HTTP request ---- GET /apis/rbac.authorization.k8s.io/v1/roles HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/rbac.authorization.k8s.io/v1/roles ---- ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |pretty|If 'true', then the output is pretty printed. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.RoleList |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf * application/json;stream=watch * application/vnd.kubernetes.protobuf;stream=watch [[Get-apis-rbac.authorization.k8s.io-v1-namespaces-namespace-roles]] === Get all Roles in a namespace List or watch objects of kind Role ==== HTTP request ---- GET /apis/rbac.authorization.k8s.io/v1/namespaces/$NAMESPACE/roles HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/rbac.authorization.k8s.io/v1/namespaces/$NAMESPACE/roles ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.RoleList |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf * application/json;stream=watch * application/vnd.kubernetes.protobuf;stream=watch [[Get-apis-rbac.authorization.k8s.io-v1-watch-namespaces-namespace-roles-name]] === Watch a Role in a namespace Watch changes to an object of kind Role ==== HTTP request ---- GET /apis/rbac.authorization.k8s.io/v1/watch/namespaces/$NAMESPACE/roles/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/rbac.authorization.k8s.io/v1/watch/namespaces/$NAMESPACE/roles/$NAME ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the Role |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |pretty|If 'true', then the output is pretty printed. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.WatchEvent |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf * application/json;stream=watch * application/vnd.kubernetes.protobuf;stream=watch [[Get-apis-rbac.authorization.k8s.io-v1-watch-roles]] === Watch all Roles Watch individual changes to a list of Role ==== HTTP request ---- GET /apis/rbac.authorization.k8s.io/v1/watch/roles HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/rbac.authorization.k8s.io/v1/watch/roles ---- ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |pretty|If 'true', then the output is pretty printed. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.WatchEvent |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf * application/json;stream=watch * application/vnd.kubernetes.protobuf;stream=watch [[Get-apis-rbac.authorization.k8s.io-v1-watch-namespaces-namespace-roles]] === Watch all Roles in a namespace Watch individual changes to a list of Role ==== HTTP request ---- GET /apis/rbac.authorization.k8s.io/v1/watch/namespaces/$NAMESPACE/roles HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/rbac.authorization.k8s.io/v1/watch/namespaces/$NAMESPACE/roles ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |pretty|If 'true', then the output is pretty printed. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.WatchEvent |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf * application/json;stream=watch * application/vnd.kubernetes.protobuf;stream=watch [[Put-apis-rbac.authorization.k8s.io-v1-namespaces-namespace-roles-name]] === Update a Role in a namespace Replace the specified Role ==== HTTP request ---- PUT /apis/rbac.authorization.k8s.io/v1/namespaces/$NAMESPACE/roles/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json' { ""kind"": ""Role"", ""apiVersion"": ""rbac.authorization.k8s.io/v1"", ... } ---- ==== Curl request ---- $ curl -k \\ -X PUT \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json' \\ https://$ENDPOINT/apis/rbac.authorization.k8s.io/v1/namespaces/$NAMESPACE/roles/$NAME <<'EOF' { ""kind"": ""Role"", ""apiVersion"": ""rbac.authorization.k8s.io/v1"", ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1.Role |=== ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the Role |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.Role |201 Created|v1.Role |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Patch-apis-rbac.authorization.k8s.io-v1-namespaces-namespace-roles-name]] === Patch a Role in a namespace Partially update the specified Role ==== HTTP request ---- PATCH /apis/rbac.authorization.k8s.io/v1/namespaces/$NAMESPACE/roles/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json-patch+json' { ... } ---- ==== Curl request ---- $ curl -k \\ -X PATCH \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json-patch+json' \\ https://$ENDPOINT/apis/rbac.authorization.k8s.io/v1/namespaces/$NAMESPACE/roles/$NAME <<'EOF' { ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1.Patch |=== ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the Role |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.Role |401 Unauthorized| |=== ==== Consumes * application/json-patch+json * application/merge-patch+json * application/strategic-merge-patch+json ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Delete-apis-rbac.authorization.k8s.io-v1-namespaces-namespace-roles-name]] === Delete a Role in a namespace Delete a Role ==== HTTP request ---- DELETE /apis/rbac.authorization.k8s.io/v1/namespaces/$NAMESPACE/roles/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json' { ... } ---- ==== Curl request ---- $ curl -k \\ -X DELETE \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json' \\ https://$ENDPOINT/apis/rbac.authorization.k8s.io/v1/namespaces/$NAMESPACE/roles/$NAME <<'EOF' { ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1.DeleteOptions |=== ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the Role |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |gracePeriodSeconds|The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. |orphanDependents|Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the ""orphan"" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. |propagationPolicy|Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.Status |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Delete-apis-rbac.authorization.k8s.io-v1-namespaces-namespace-roles]] === Delete all Roles in a namespace Delete collection of Role ==== HTTP request ---- DELETE /apis/rbac.authorization.k8s.io/v1/namespaces/$NAMESPACE/roles HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -X DELETE \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/rbac.authorization.k8s.io/v1/namespaces/$NAMESPACE/roles ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |namespace|object name and auth scope, such as for teams and projects |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.Status |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf ",12177,False,2344.906771723636,median "/****************************************************************************** * srengobj.cpp * This file contains the implementation of the CSrEngine class. * This implements ISpSREngine and ISpObjectWithToken. * This is the main recognition object * * Copyright (c) Microsoft Corporation. All rights reserved. ******************************************************************************/ #include ""stdafx.h"" #include ""sreng.h"" #include ""srengobj.h"" #include ""SpHelper.h"" #ifndef _WIN32_WCE #include ""shfolder.h"" #endif static const WCHAR DICT_WORD[] = L""Blah""; // This is the default word the sample engine uses for dictation static const WCHAR ALT_WORD[] = L""Alt""; // This is the default word used for alternates /**************************************************************************** * CSrEngine::FinalConstruct * *---------------------------* * Description: * The ATL FinalConstruct method. Called after the standard C++ constructor * Return: * S_OK * FAILED(hr) *****************************************************************************/ HRESULT CSrEngine::FinalConstruct() { SPDBG_FUNC(""Sample Engine - FINALCONSTRUCT""); HRESULT hr = S_OK; // This event is used to indicate when space is available for data to be given to the recognition thread m_hQueueHasRoom = ::CreateEvent(NULL, TRUE, TRUE, NULL); m_FrameQueue.SetSpaceAvailEvent(m_hQueueHasRoom); // Create a thread control which will be used for the recognition thread CComPtr cpTaskMgr; hr = cpTaskMgr.CoCreateInstance(CLSID_SpResourceManager); if (SUCCEEDED(hr)) { hr = cpTaskMgr->CreateThreadControl(this, this, THREAD_PRIORITY_NORMAL, &m_cpDecoderThread); } if(SUCCEEDED(hr)) { // Create the SAPI lexicon which holds user and app pronounciations hr = m_cpLexicon.CoCreateInstance(CLSID_SpLexicon); } return hr; } /**************************************************************************** * CSrEngine::FinalRelease * *---------------------------* * Description: * The ATL FinalRelease method. Clean up any resources not automatically destructed. * Return: * S_OK *****************************************************************************/ HRESULT CSrEngine::FinalRelease() { SPDBG_FUNC(""Sample Engine - FINALRELEASE""); ::CloseHandle(m_hQueueHasRoom); return S_OK; } /**************************************************************************** * CSrEngine::SetObjectToken * *---------------------------* * Description: * This method is called by SAPI immediately after the engine is created. * It can be used to get registry information specific to this engine. * The engine can recover from the token file paths stored there during installation. * The engine also can recover user set defaults for accuracy, rejection etc. * Also could have different engines sharing the same code base (CLSID) but having different registry info * e.g. if engine supports different languages * Return: * S_OK * FAILED(hr) *****************************************************************************/ STDMETHODIMP CSrEngine::SetObjectToken(ISpObjectToken * pToken) { SPDBG_FUNC(""Sample Engine - SETOBJECTTOKEN""); HRESULT hr = S_OK; // Helper function that copies the token reference. hr = SpGenericSetObjectToken(pToken, m_cpEngineObjectToken); if(FAILED(hr)) { return hr; } // Read attribute information from the token in the registry CComPtr cpAttribKey; hr = pToken->OpenKey(L""Attributes"", &cpAttribKey); if(SUCCEEDED(hr)) { WCHAR *psz = NULL; hr = cpAttribKey->GetStringValue(L""Desktop"", &psz); ::CoTaskMemFree(psz); if(SUCCEEDED(hr)) { // This instance of the engine is for doing desktop recognition } else if(hr == SPERR_NOT_FOUND) { hr = cpAttribKey->GetStringValue(L""Telephony"", &psz); ::CoTaskMemFree(psz); if(SUCCEEDED(hr)) { // This instance of the engine is for doing telephony recognition } } } // Read what language is set in the registry if(SUCCEEDED(hr)) { WCHAR *pszLangID = NULL; hr = cpAttribKey->GetStringValue(L""Language"", &pszLangID); if(SUCCEEDED(hr)) { // We could use this language id in recognition. } else if(hr == SPERR_NOT_FOUND) { pszLangID = L""409""; // Default language (US English) hr = S_OK; } m_LangID = (unsigned short)wcstol(pszLangID, NULL, 16); ::CoTaskMemFree(pszLangID); } // Read data-file location WCHAR *pszPath = NULL; // Looks for the file path stored in the registry hr = pToken->GetStorageFileName(CLSID_SampleSREngine, L""SampleEngDataFile"", NULL, 0, &pszPath); // Could now load engine data-files from this given path ::CoTaskMemFree(pszPath); return hr; } /**************************************************************************** * CSrEngine::GetObjectToken * *---------------------------* * Description: * This method is called if SAPI wants to find which object token this engine is using * Return: * S_OK * FAILED(hr) *****************************************************************************/ STDMETHODIMP CSrEngine::GetObjectToken(ISpObjectToken ** ppToken) { SPDBG_FUNC(""Sample Engine - GETOBJECTTOKEN""); // Generic helper function return SpGenericGetObjectToken(ppToken, m_cpEngineObjectToken); } /**************************************************************************** * CSrEngine::SetSite * *---------------------------* * Description: * This is called to give the engine a reference to the ISpSREngineSite. * The engine uses this to call back to SAPI. * Return: * S_OK *****************************************************************************/ STDMETHODIMP CSrEngine::SetSite(ISpSREngineSite *pSite) { m_cpSite = pSite; return S_OK; } /**************************************************************************** * CSrEngine::SetRecoProfile * *---------------------------* * Description: * The RecoProfile is an object token holding information on the current * user and enrollment session. The engine can store whatever information here * it likes. It should store this in a key under the RecoProfile key named with the engine class id. * Return: * S_OK * FAILED(hr) *****************************************************************************/ STDMETHODIMP CSrEngine::SetRecoProfile(ISpObjectToken *pProfile) { SPDBG_FUNC(""Sample Engine - SETRECOPROFILE""); // First find if our engine already has info in this profile HRESULT hr = S_OK; WCHAR *pszCLSID, *pszPath = NULL; CComPtr dataKey; m_cpUserObjectToken = pProfile; hr = ::StringFromCLSID(CLSID_SampleSREngine, &pszCLSID); if(FAILED(hr)) { return hr; } hr = pProfile->OpenKey(pszCLSID, &dataKey); if(hr == SPERR_NOT_FOUND) { // We haven't seen this user profile before, so create a new registry key to hold info for it hr = pProfile->CreateKey(pszCLSID, &dataKey); // Now we can set some default values if(SUCCEEDED(hr)) { hr = dataKey->SetStringValue(L""GENDER"", L""UNKNOWN""); } if(SUCCEEDED(hr)) { hr = dataKey->SetStringValue(L""AGE"", L""UNKNOWN""); } // Now we can create some temporary file storage (e.g. for trained models) if(SUCCEEDED(hr)) { hr = pProfile->GetStorageFileName(CLSID_SampleSREngine, L""SampleEngTrainingFile"", NULL, CSIDL_FLAG_CREATE | CSIDL_LOCAL_APPDATA, &pszPath); } // Now we request a UI for user training (or properties - SPDUI_RecoProfileProperties) // The engine cannot directly create UI it must request it. hr = AddEventString(SPEI_REQUEST_UI, 0, SPDUI_UserTraining); } else if(SUCCEEDED(hr)) { // We've already seen this profile so read values WCHAR *pszGender = NULL, *pszAge = NULL; hr = dataKey->GetStringValue(L""GENDER"", &pszGender); if(SUCCEEDED(hr)) { hr = dataKey->GetStringValue(L""AGE"", &pszAge); } // Now we could read training file if(SUCCEEDED(hr)) { hr = pProfile->GetStorageFileName(CLSID_SampleSREngine, L""SampleEngTrainingFile"", NULL, 0, &pszPath); } ::CoTaskMemFree(pszGender); ::CoTaskMemFree(pszAge); } ::CoTaskMemFree(pszPath); ::CoTaskMemFree(pszCLSID); return hr; } /**************************************************************************** * CSrEngine::OnCreateRecoContext * *---------------------------* * Description: * This method is called each time a new reco context is created in * an application using this engine. * This sample engine does not strictly need info about reco contexts * but for reference we will a keep list of them. * Return: * S_OK * FAILED(hr) *****************************************************************************/ STDMETHODIMP CSrEngine::OnCreateRecoContext(SPRECOCONTEXTHANDLE hSapiContext, void ** ppvDrvCtxt) { SPDBG_FUNC(""Sample Engine - CREATERECOCONTEXT""); CContext * pContext = new CContext(hSapiContext); // Store a reference to the CContext structure *ppvDrvCtxt = pContext; m_ContextList.InsertHead(pContext); return S_OK; } /**************************************************************************** * CSrEngine::OnDeleteRecoContext * *---------------------------* * Description: * This method is called each time a reco context is deleted. * Return: * S_OK *****************************************************************************/ STDMETHODIMP CSrEngine::OnDeleteRecoContext(void * pvDrvCtxt) { SPDBG_FUNC(""Sample Engine - DELETERECOCONTEXT""); CContext * pContext = (CContext *) pvDrvCtxt; m_ContextList.Remove(pContext); delete pContext; return S_OK; } /**************************************************************************** * CSrEngine::OnCreateGrammar * *---------------------------* * Description: * This method is called each time a new reco grammar is created in * an application using this engine. * We keep a list of grammars - storing a pointer to the list entry in ppvEngineGrammar. * Return: * S_OK *****************************************************************************/ STDMETHODIMP CSrEngine::OnCreateGrammar(void * pvEngineRecoContext, SPGRAMMARHANDLE hSapiGrammar, void ** ppvEngineGrammar) { SPDBG_FUNC(""Sample Engine - ONCREATEGRAMMAR""); // Each grammar will be associated with a context CContext * pContext = (CContext *) pvEngineRecoContext; SPDBG_ASSERT(m_ContextList.Find(pContext->m_hSapiContext)); // Keep a list of grammars CDrvGrammar * pGrammar = new CDrvGrammar(hSapiGrammar); // Store a reference to the CDrvGrammar structure *ppvEngineGrammar = pGrammar; m_GrammarList.InsertHead(pGrammar); return S_OK; } /**************************************************************************** * CSrEngine::OnDeleteGrammar * *---------------------------* * Description: * This method is called each time a reco grammar is deleted. * Return: * S_OK *****************************************************************************/ STDMETHODIMP CSrEngine::OnDeleteGrammar(void * pvDrvGrammar) { SPDBG_FUNC(""Sample Engine - ONDELETEGRAMMAR""); CDrvGrammar * pGrammar = (CDrvGrammar *)pvDrvGrammar; m_GrammarList.Remove(pGrammar); delete pGrammar; return S_OK; } /**************************************************************************** * CSrEngine::WordNotify * *---------------------------* * Description: * This method is called by SAPI to inform the engine of the words in * command & control (C&C) grammars. When words are added or removed (e.g. by * the application loading or unloading grammars) this method is called. * Here we examine the word text, see if it has an associated pronunciation, * and see if there is a pronunciation in the lexicon. * Return: * S_OK * FAILED(hr) *****************************************************************************/ STDMETHODIMP CSrEngine::WordNotify(SPCFGNOTIFY Action, ULONG cWords, const SPWORDENTRY * pWords) { SPDBG_FUNC(""Sample Engine - WORDNOTIFY""); HRESULT hr = S_OK; ULONG i; WCHAR *wordPron; switch(Action){ case SPCFGN_ADD: SPWORDENTRY WordEntry; for(i = 0; SUCCEEDED(hr) && i < cWords; i++) { WordEntry = pWords[i]; hr = m_cpSite->GetWordInfo(&WordEntry, SPWIO_WANT_TEXT); if(SUCCEEDED(hr) && WordEntry.aPhoneId) { // Word entry contains a specific pronounciation from CFG // Engine should use this in recognition wordPron = new WCHAR[wcslen(WordEntry.aPhoneId)]; wcscpy(wordPron, WordEntry.aPhoneId); ::CoTaskMemFree((void*)WordEntry.aPhoneId); } else { // See if word is in lexicon SPWORDPRONUNCIATIONLIST PronList; PronList.pFirstWordPronunciation = 0; PronList.pvBuffer = 0; PronList.ulSize = 0; hr = m_cpLexicon->GetPronunciations(WordEntry.pszLexicalForm, eLEXTYPE_APP | eLEXTYPE_USER, pWords[i].LangID, &PronList); if(SUCCEEDED(hr)) { // Pronounciation(s) found in SAPI lexicon // Engines should use these prons in recognition and also language and POS info // For sample just copy first pron wordPron = new WCHAR[wcslen(PronList.pFirstWordPronunciation->szPronunciation)]; wcscpy(wordPron, PronList.pFirstWordPronunciation->szPronunciation); ::CoTaskMemFree(PronList.pvBuffer); } else if(hr == SPERR_NOT_IN_LEX) { // No pronunciation present in SAPI lexicon. // Engine should generate its own pronounciation or fail // Here we generate a default NULL pronunciation wordPron = NULL; hr = S_OK; } else { break; // Unexpected error - break; } // Associate the pronunciation information with the SAPI word handle so it can be recovered later // An engine can store any arbitrary pointer with each word. hr = m_cpSite->SetWordClientContext(WordEntry.hWord, wordPron); } if (SUCCEEDED(hr)) { // When calling GetWordInfo SAPI allocates the strings which we must free ::CoTaskMemFree((void*)WordEntry.pszDisplayText); ::CoTaskMemFree((void*)WordEntry.pszLexicalForm); } } break; case SPCFGN_REMOVE: for(i = 0; i < cWords; i++) { WordEntry = pWords[i]; // Client context already on word entry wordPron = (WCHAR *) WordEntry.pvClientContext; if(wordPron) { delete wordPron; } } break; } return hr; } /**************************************************************************** * CSrEngine::RuleNotify * *---------------------------* * Description: * This method is called by SAPI to inform the engine of the rules in * command & control grammars. The order or actions of CFG grammars is of this form: * WordNotify(SPCFGN_ADD) - add words * RuleNotify(SPCFGN_ADD) - add rules * RuleNotify(SPCFGN_ACTIVATE) - activate rules to indicate they are to be used for recognition * RuleNotify(SPCFGN_INVALIDATE) - if a rule gets edited by the app then this is called * RuleNotify(SPCFGN_DEACTIVE) - deactivate rules * RuleNotify(SPCFGN_REMOVE) - remove rules * WordNotify(SPCFGN_REMOVE) - remove words * * The engine can call GetRuleInfo to find the initial state in the rule, and * then GetStateInfo to find the information about subsequent states and transitions in the rule. * If a rule is edited then SPCFGN_INVALIDATE is called to indicate rule has changed so the engine * must reparse the rule information. * * The engine can obtain all the information about the rule either before or during recognition. * In this sample engine we just keep a list of rules initially and then wait * until we want to generate a result and then find a random path through the rule. * * Return: * S_OK *****************************************************************************/ STDMETHODIMP CSrEngine::RuleNotify(SPCFGNOTIFY Action, ULONG cRules, const SPRULEENTRY * pRules) { SPDBG_FUNC(""Sample Engine - RULENOTIFY""); ULONG i; CRuleEntry *pRuleEntry; switch (Action) { case SPCFGN_ADD: for (i = 0; i < cRules; i++) { // Obtain information on the rule and store in a CRuleEntry structure pRuleEntry = new CRuleEntry; pRuleEntry->m_hRule = pRules[i].hRule; pRuleEntry->m_fTopLevel = (pRules[i].Attributes & SPRAF_TopLevel); pRuleEntry->m_fActive = (pRules[i].Attributes & SPRAF_Active); // Keep a list of rules m_RuleList.InsertHead(pRuleEntry); // Engine can store information associated with rule handle if desired m_cpSite->SetRuleClientContext(pRules[i].hRule, (void *)pRuleEntry); } break; case SPCFGN_REMOVE: for (i = 0; i < cRules; i++) { pRuleEntry = m_RuleList.Find(pRules[i].hRule); SPDBG_ASSERT(pRuleEntry); // The rule must have been added before being removed m_RuleList.Remove(pRuleEntry); delete pRuleEntry; } break; case SPCFGN_ACTIVATE: for (i = 0; i < cRules; i++) { pRuleEntry = m_RuleList.Find(pRules[i].hRule); // Only top-level rules can be activated SPDBG_ASSERT(pRuleEntry && !pRuleEntry->m_fActive && pRuleEntry->m_fTopLevel); pRuleEntry->m_fActive = TRUE; } break; case SPCFGN_DEACTIVATE: for (i = 0; i < cRules; i++) { pRuleEntry = m_RuleList.Find(pRules[i].hRule); SPDBG_ASSERT(pRuleEntry && pRuleEntry->m_fActive && pRuleEntry->m_fTopLevel); pRuleEntry->m_fActive = FALSE; } break; case SPCFGN_INVALIDATE: for (i = 0; i < cRules; i++) { pRuleEntry = m_RuleList.Find(pRules[i].hRule); SPDBG_ASSERT(pRuleEntry); pRuleEntry->m_fTopLevel = (pRules[i].Attributes & SPRAF_TopLevel); pRuleEntry->m_fActive = (pRules[i].Attributes & SPRAF_Active); // Don't need to do anything here as we don't start parsing the rule until recognition time } break; } return S_OK; } /**************************************************************************** * CSrEngine::LoadSLM * *---------------------------* * Description: * Called when SAPI wants the engine to load a dictaion language model (SLM). * For each reco gramar one dictation as well as C&C rules can be loaded. * Return: * S_OK *****************************************************************************/ STDMETHODIMP CSrEngine::LoadSLM(void * pvEngineGrammar, const WCHAR * pszTopicName) { SPDBG_FUNC(""Sample Engine - LOADSLM""); if (pszTopicName) { // Engines should load the named language model - e.g. Spelling using // this parameter. If NULL load the default dictation model. // Since just a sample ignore this parameter. } // pvEngineGrammar is the pointer ppvEngineGrammar we set in OnCreateGrammar // Use this to find out on which grammar the SLM is being asked for. CDrvGrammar * pGrammar = (CDrvGrammar *)pvEngineGrammar; pGrammar->m_SLMLoaded = TRUE; return S_OK; } /**************************************************************************** * CSrEngine::UnloadSLM * *---------------------------* * Description: * Called when SAPI wants the engine to delete an SLM. * Return: * S_OK *****************************************************************************/ STDMETHODIMP CSrEngine::UnloadSLM(void *pvEngineGrammar) { SPDBG_FUNC(""Sample Engine - UNLOADSLM""); CDrvGrammar * pGrammar = (CDrvGrammar *)pvEngineGrammar; pGrammar->m_SLMLoaded = FALSE; return S_OK; } /**************************************************************************** * CSrEngine::SetSLMState * *---------------------------* * Description: * Called to activate or deactivate an SLM for recognition. * NewState is either SPRS_ACTIVE or SPRS_INACTIVE. * Return: * S_OK *****************************************************************************/ HRESULT CSrEngine::SetSLMState(void * pvDrvGrammar, SPRULESTATE NewState) { SPDBG_FUNC(""Sample Engine - SETSLMSTATE""); // pvDrvGrammar is the pointer ppvEngineGrammar we set in OnCreateGrammar CDrvGrammar * pGrammar = (CDrvGrammar *)pvDrvGrammar; if (NewState != SPRS_INACTIVE) { pGrammar->m_SLMActive = TRUE; } else { pGrammar->m_SLMActive = FALSE; } return S_OK; } /**************************************************************************** * CSrEngine::SetWordSequenceData * *---------------------------* * Description: * If the app submits a text buffer to SAPI this method is called. * The text buffer supplied here can either be used in CFGs with the text buffer transition, * or in dictation to supply information to the engine about the prior text visible on screen. * This sample engine is just using the text buffer with the text buffer transition. * Return: * S_OK *****************************************************************************/ STDMETHODIMP CSrEngine::SetWordSequenceData(void *pvEngineGrammar, const WCHAR *pText, ULONG cchText, const SPTEXTSELECTIONINFO *pInfo) { SPDBG_FUNC(""Sample Engine - SETWORDSEQUENCE""); //For each grammar object going to be released, SAPI would call SetWordSequenceData(NULL, 0, NULL). // Recover the data we have associated with this grammar. CDrvGrammar * pGrammar = (CDrvGrammar*)pvEngineGrammar; // Delete previous grammar text buffer if(pGrammar->m_pWordSequenceText) { delete pGrammar->m_pWordSequenceText; } // Make a copy of the text data if(cchText) { pGrammar->m_pWordSequenceText = new WCHAR[cchText]; memcpy((void *)pGrammar->m_pWordSequenceText, pText, sizeof(WCHAR) * cchText); pGrammar->m_cchText = cchText; } else { pGrammar->m_pWordSequenceText = NULL; pGrammar->m_cchText = NULL; } // Engines can use the SPTEXTSELECTIONINFO to determine which // parts of the text buffer are visible on screen and / or selected. // This sample engine is using the active text selection only. SetTextSelection(pvEngineGrammar, pInfo); return S_OK; } /**************************************************************************** * CSrEngine::SetTextSelection * *---------------------------* * Description: * This method tells engines if the SPTEXTSELECTIONINFO structure * has been updated. This sample engine is using only fields ulStartActiveOffset and cchActiveChars of SPTEXTSELECTIONINFO. * Return: * S_OK *****************************************************************************/ STDMETHODIMP CSrEngine::SetTextSelection(void * pvEngineGrammar, const SPTEXTSELECTIONINFO * pInfo) { SPDBG_FUNC(""Sample Engine - SETTEXTSELECTION""); // Recover the data we have associated with this grammar. CDrvGrammar * pGrammar = (CDrvGrammar*)pvEngineGrammar; if (pGrammar->m_pInfo) { delete pGrammar->m_pInfo; } if (pInfo) { pGrammar->m_pInfo = new SPTEXTSELECTIONINFO(*pInfo); } else { pGrammar->m_pInfo = NULL; } return S_OK; } /**************************************************************************** * CSrEngine::IsPronounceable * *---------------------------* * Description: * Engines should return whether it has or will be able to * generate a pronounciation for this word. * In this sample engine, this is always true. * Return: * S_OK *****************************************************************************/ STDMETHODIMP CSrEngine::IsPronounceable(void * pDrvGrammar, const WCHAR * pszWord, SPWORDPRONOUNCEABLE * pWordPronounceable) { SPDBG_FUNC(""Sample Engine - ISPRONOUNCEABLE""); *pWordPronounceable = SPWP_KNOWN_WORD_PRONOUNCEABLE; return S_OK; } /**************************************************************************** * CSrEngine::SetAdaptationData * *---------------------------* * Description: * This method can be used by the app to give text data to the engine * for language model adaptation etc. This method can only be called * by the app after if has received an SPEI_ADAPTATION event. Since * we never fire that event this method should never be called. * Return: * E_UNEXPECTED *****************************************************************************/ STDMETHODIMP CSrEngine::SetAdaptationData(void * pvEngineCtxtCookie, const WCHAR *pAdaptationData, const ULONG cch) { SPDBG_FUNC(""Sample Engine - SETADAPTATIONDATA""); SPDBG_ASSERT(0); // This method should never be called return E_UNEXPECTED; } /**************************************************************************** * CSrEngine::AddEvent * *---------------------------* * Description: * Internal helper method to send an event to SAPI. * Return: * S_OK * FAILED(hr) *****************************************************************************/ HRESULT CSrEngine::AddEvent(SPEVENTENUM eEventId, ULONGLONG ullStreamPos, WPARAM wParam, LPARAM lParam) { SPDBG_FUNC(""Sample Engine - AddEvent""); HRESULT hr = S_OK; SPEVENT Event; Event.eEventId = eEventId; Event.elParamType = SPET_LPARAM_IS_UNDEFINED; Event.ulStreamNum = 0; // Always set this to zero - SAPI fills this in Event.ullAudioStreamOffset = ullStreamPos; Event.wParam = wParam; Event.lParam = lParam; hr = m_cpSite->AddEvent(&Event, NULL); return hr; } /**************************************************************************** * CSrEngine::AddEventString * *---------------------------* * Description: * Internal helper method to send an event with a string LParam to SAPI. * Request UI is the only event in the sample to need this. * Return: * S_OK * FAILED(hr) *****************************************************************************/ HRESULT CSrEngine::AddEventString(SPEVENTENUM eEventId, ULONGLONG ullStreamPos, const WCHAR * psz, WPARAM wParam) { SPDBG_FUNC(""Sample Engine - AddEventString""); HRESULT hr = S_OK; SPEVENT Event; Event.eEventId = eEventId; Event.elParamType = SPET_LPARAM_IS_STRING; Event.ulStreamNum = 0; // Always set this to zero - SAPI fills this in Event.ullAudioStreamOffset = ullStreamPos; Event.wParam = wParam; Event.lParam = (LPARAM)psz; hr = m_cpSite->AddEvent(&Event, NULL); return hr; } #define BLOCKSIZE 220 // 1/100 of a second /**************************************************************************** * CSrEngine::RecognizeStream * *---------------------------* * Description: * This is the method that SAPI calls for recognition to take place. * Engines must only return from this method after they have read all the data * and completed all the recognition they are going to do on this stream. * Thus this method is giving a thread to the engine to do recognition on, * and engines may create additional threads. * * In this sample we constantly read data using this thread, and then perform * very basic speech detection and pass data to a recognizer thread, which * generates hypotheses and results. * * Parameters: * * - REFGUID rguidFormatId - this is the GUID of the input audio format * - const WAVEFORMATEX * pWaveFormatEx - this is the extended wav format information of the audio format * - HANDLE hRequestSync - this Win32 event is used to indicate that there are pending tasks * and the engine should call Synchronize() for SAPI to process these. * - HANDLE hDataAvailable - this Win32 event is used to tell the engine that data is available to be read. * The frequency this is set can be controlled by the SetBufferNotifySize method. * - HANDLE hExit - this Win32 event indicates the engine is being closed down and should exit immediately. * - BOOL fNewAudioStream - this indicates this is a new input stream * e.g. the app has done a new SetInput call rather than just restarting the previous stream. * - BOOL fRealTimeAudio - this indicates the input is from a real-time ISpAudio stream, rather than, say, a file * - ISpObjectToken * pAudioObjectToken - this is the object token representing the audio input device * the engine may want to query this. * * Return: * S_OK * FAILED(hr) *****************************************************************************/ STDMETHODIMP CSrEngine::RecognizeStream(REFGUID rguidFormatId, const WAVEFORMATEX * pWaveFormatEx, HANDLE hRequestSync, HANDLE hDataAvailable, HANDLE hExit, BOOL fNewAudioStream, BOOL fRealTimeAudio, ISpObjectToken * pAudioObjectToken) { SPDBG_FUNC(""Sample Engine - RECOGNIZESTREAM""); HRESULT hr = S_OK; m_hRequestSync = hRequestSync; // Start the recognition thread hr = m_cpDecoderThread->StartThread(0, NULL); if (SUCCEEDED(hr)) { const HANDLE aWait[] = { hExit, m_hQueueHasRoom }; while (TRUE) // sit in this loop until there is no more data { // The Read method is used to read data. This will block until the required // amount of data is available. If the stream has ended either a fail code // will be returned or the amount read will be less than the amount asked for. // To see how much data is available to be read without blocking the DataAvailable // method can be used or hDataAvailable event. BYTE aData[BLOCKSIZE]; ULONG cbRead; hr = m_cpSite->Read(aData, sizeof(aData), &cbRead); if (hr != S_OK || cbRead < sizeof(aData)) { break; } // Decide if the frame of data is noise or silence with a simple level detector BOOL bNoiseDetected = FALSE; SHORT * pBuffer = (SHORT *)aData; for (ULONG i = 0; i < cbRead; i += 2, pBuffer++) { if (*pBuffer < (SHORT)-3000 || *pBuffer > (SHORT)3000) { bNoiseDetected = TRUE; break; } } // If there no space on the frame queue then wait BOOL bBlock = m_FrameQueue.IsFull(); if(bBlock) { // Wait for space to appear on the queue to be passed to the recognizer. // Real engines should not wait - the data reading should be as real-time as possible // Also detect if the hExit event is set to indicate we should stop processing. if (::WaitForMultipleObjects(sp_countof(aWait), aWait, FALSE, INFINITE) == WAIT_OBJECT_0) { break; } } // Add the frame to the queue and notify the decoder thread m_FrameQueue.InsertTail(bNoiseDetected); m_cpDecoderThread->Notify(); } // Once we've stopped reading data we must wait for the recognizer thread to finish // All processing must be done before returning from the RecognizeStream method. m_cpDecoderThread->WaitForThreadDone(TRUE, &hr, 30 * 1000); } m_hRequestSync = NULL; SPDBG_REPORT_ON_FAIL( hr ); return hr; } /**************************************************************************** * CSrEngine::ThreadProc * *-----------------------* * Description: * This is the main thread for the recognition process. * This hExitThreadEvent indicates this thread should complete, * and the hNotifyEvent indicates the RecognizeStream thread is notifying * that data is available for processing. The m_hRequestSync indicates * SAPI is requesting the engine should call Synchronize. * * Return: * S_OK *****************************************************************************/ STDMETHODIMP CSrEngine::ThreadProc(void *, HANDLE hExitThreadEvent, HANDLE hNotifyEvent, HWND hwndWorker, volatile const BOOL * pfContinueProcessing) { SPDBG_FUNC(""Sample Engine - Recognition ThreadProc""); HRESULT hr = S_OK; const HANDLE aWait[] = { hExitThreadEvent, hNotifyEvent, m_hRequestSync }; ULONG block = 0; ULONG silenceafternoise = 0; DWORD waitres; m_bSoundStarted = FALSE; m_bPhraseStarted = FALSE; m_cBlahBlah = 0; m_ullStart = 0; m_ullEnd = 0; while (*pfContinueProcessing) // sit in this loop until exit { ULONG cEvents = sp_countof(aWait); // Respond to the request sync event only if speech not detected, // as we don't want to allow grammar changes during recognition. // However always respond after several seconds. if(m_bPhraseStarted && (block - m_ullStart / BLOCKSIZE) < 5 * 100) { --cEvents; } waitres = ::WaitForMultipleObjects(cEvents, aWait, FALSE, INFINITE); switch (waitres) { case WAIT_OBJECT_0: // Exit thread break; case WAIT_OBJECT_0 + 1: // Notify (data is available) // Engines should regularly call UpdateRecoPos to indicate how far through the // stream they have recognized. m_cpSite->UpdateRecoPos((ULONGLONG)block * BLOCKSIZE); if (m_ullStart == 0 && !m_bPhraseStarted) { // Engines should also call Synchronize to indicate they are ready // to be notified about grammar changes and other tasks. Within Synchronize // if grammars have changed WordNotify, RuleNotify etc. will be called before Synchronize returns. // Here Synchronize is called only if processing silence, not speech // to avoid having to deal with grammar changes during recognition. m_cpSite->Synchronize((ULONGLONG)block * BLOCKSIZE); // A return code of S_FALSE from synchronize means the engine can stop recognizing // This engine ignores this. } while (m_FrameQueue.HasData()) { BOOL bNoise = m_FrameQueue.RemoveHead(); block++; // Update the position in stream if (bNoise) { // Found some speech - update start and end positions silenceafternoise = 0; if (m_ullStart == 0) { m_ullStart = (ULONGLONG)block * BLOCKSIZE; } m_ullEnd = (ULONGLONG)block * BLOCKSIZE; _CheckRecognition(); // this will generate hypotheses and events } else { // Found some silence silenceafternoise++; if (silenceafternoise > 50) { if (m_bSoundStarted) { // We've heard 1/2 sec of silence since the last noise, so send the // final recognition if we had previously started a phrase if (m_bPhraseStarted) { _NotifyRecognition(FALSE, m_cBlahBlah); } AddEvent(SPEI_SOUND_END, m_ullEnd); // send the sound end event m_bSoundStarted = FALSE; m_bPhraseStarted = FALSE; } m_ullStart = 0; m_ullEnd = 0; } } //--- Generate random interference start at 20 seconds into the stream // and saying it's gone at 22 seconds if (block % (100 * 30) == 20 * 100) { const SPINTERFERENCE rgspi[] = { SPINTERFERENCE_NOISE, SPINTERFERENCE_NOSIGNAL, SPINTERFERENCE_TOOLOUD, SPINTERFERENCE_TOOQUIET }; AddEvent(SPEI_INTERFERENCE, block*BLOCKSIZE, 0, rgspi[rand() % 4]); } else if (block % (100 * 30) == 22 * 100) { AddEvent(SPEI_INTERFERENCE, block*BLOCKSIZE, 0, SPINTERFERENCE_NONE); } // Ask for UI at 10 seconds into the stream // and cancel request one second later else if (block == 10 * 100) { AddEventString(SPEI_REQUEST_UI, block * BLOCKSIZE, SPDUI_UserTraining); } else if (block == 11 * 100) // Cancle the UI request at 11 seconds into the stream { AddEventString(SPEI_REQUEST_UI, block * BLOCKSIZE, NULL); } } break; case WAIT_OBJECT_0 + 2: // SAPI has explicitly requested we call Synchronize hr = m_cpSite->Synchronize((ULONGLONG)block * BLOCKSIZE); // Once synchronize is called the engine cannot fire events prior to that stream position // so update the stored stream start position m_ullStart = block * BLOCKSIZE; if(m_ullEnd < m_ullStart) { m_ullEnd = m_ullStart; } break; default: SPDBG_ASSERT(FALSE); // Something strange! break; } } // Before exiting we must make sure every phrase start has been paired with a recognition, // and that every sound start event has a corresponding sound end. if (m_bPhraseStarted) { _NotifyRecognition(FALSE, m_cBlahBlah); } if (m_bSoundStarted) { AddEvent(SPEI_SOUND_END, m_ullEnd); } return S_OK; } /**************************************************************************** * CSrEngine::_CheckRecognition * *---------------------------* * Description: * This internal method decides when to fire sound start events, * phrase start events and hypotheses. *****************************************************************************/ void CSrEngine::_CheckRecognition() { SPDBG_FUNC(""Sample Engine - _NotifyRecognition""); ULONG duration, blahs; if (m_ullEnd > m_ullStart) { duration = (ULONG)(m_ullEnd - m_ullStart); if (duration >= BLOCKSIZE * 100 * 1 / 8) { if (!m_bSoundStarted) { // Heard something that was longer than 1/8th second, so do sound start AddEvent(SPEI_SOUND_START, m_ullStart); m_bSoundStarted = TRUE; m_cBlahBlah = 0; } if (duration >= BLOCKSIZE * 100 * 1 / 4) { // Heard something that was longer than 1/4 second, so do phrase start // and then generate a hypothesis every 1/4 second after that. blahs = duration / (BLOCKSIZE * 100 * 1 / 4); if (blahs != m_cBlahBlah) { m_cBlahBlah = blahs; if (!m_bPhraseStarted) { m_bPhraseStarted = TRUE; AddEvent(SPEI_PHRASE_START, m_ullStart); } _NotifyRecognition(TRUE, blahs); } } } } } /**************************************************************************** * CSrEngine::_NotifyRecognition * *-------------------------------* * Description: * This internal method is used to generate a recognition result. The contents * are random since we don't actually know how to recognize anything.* ****************************************************************************/ void CSrEngine::_NotifyRecognition( BOOL fHypothesis, ULONG nWords ) { SPDBG_FUNC(""Sample Engine - _NotifyRecognition""); HRESULT hr = S_OK; // First count the active CFG rules ULONG cActiveCFGRules = 0; CRuleEntry * pRule = m_RuleList.GetHead(); for(; pRule; pRule = m_RuleList.GetNext(pRule)) { if( pRule->m_fActive ) { cActiveCFGRules++; } } // Then count all the grammars with active dictation ULONG cActiveSLM = 0; CDrvGrammar * pGram = m_GrammarList.GetHead(); for(; pGram; pGram = m_GrammarList.GetNext(pGram)) { if(pGram->m_SLMActive) { cActiveSLM++; } } // If both CFG and dictation are active, randomly do one or the other if(cActiveCFGRules && cActiveSLM) { if(rand() % 2) { cActiveSLM = 0; } else { cActiveCFGRules = 0; } } //--- Compose reco result info SPRECORESULTINFO Result; memset(&Result, 0, sizeof(SPRECORESULTINFO)); Result.cbSize = sizeof(SPRECORESULTINFO); Result.fHypothesis = fHypothesis; Result.ullStreamPosStart = m_ullStart; Result.ullStreamPosEnd = m_ullEnd; if( cActiveCFGRules ) { // Generate a CFG result phrase hr = WalkCFGRule(&Result, cActiveCFGRules, fHypothesis, nWords, m_ullStart, (ULONG)(m_ullEnd - m_ullStart)); if( SUCCEEDED(hr) ) { // Pass the results info to SAPI hr = m_cpSite->Recognition(&Result); // Cleanup any memory allocated for alternates and release phrases for(ULONG i = 0; i < Result.ulNumAlts; i++) { Result.aPhraseAlts[i].pPhrase->Release(); } Result.pPhrase->Release(); delete[] Result.aPhraseAlts; } } else if(cActiveSLM) { // Generate a dictation result phrase hr = WalkSLM(&Result, cActiveSLM, nWords, m_ullStart, (ULONG)(m_ullEnd - m_ullStart)); if( SUCCEEDED(hr) ) { // Pass the results info to SAPI hr = m_cpSite->Recognition(&Result); // Release the result phrase Result.pPhrase->Release(); delete[] Result.pvEngineData; } } else if(!fHypothesis) { // No rules were active - return a false recognition // RecognizeStream can still be called if no rules are active // - the engine is free to do anything it wants with the speech data. Result.eResultType = SPRT_FALSE_RECOGNITION; hr = m_cpSite->Recognition(&Result); } } /**************************************************************************** * CSrEngine::CreatePhraseFromRule * *---------------------------------* * Description: * This method is used to produce the result phrase for a CFG result. * It selects a random path through an active rule, and * then calls ParseFromTransition to generate an ISpPhraseBuilder object. * * Return: * S_OK * FAIL(hr) ****************************************************************************/ HRESULT CSrEngine::CreatePhraseFromRule( CRuleEntry * pRule, BOOL fHypothesis, ULONGLONG ullAudioPos, ULONG ulAudioSize, ISpPhraseBuilder** ppPhrase ) { HRESULT hr = S_OK; SPRULEENTRY RuleInfo; RuleInfo.hRule = pRule->m_hRule; hr = m_cpSite->GetRuleInfo(&RuleInfo, SPRIO_NONE); if( SUCCEEDED(hr) ) { SPPATHENTRY Path[200]; // Note: Limit of 200 transitions in grammar! ULONG cTrans; // Recursively generate random path hr = RecurseWalk(RuleInfo.hInitialState, Path, &cTrans); //Fill in the audio offset and audio size for each element in the path, while each element has equal size and silence in between if (cTrans) { ULONG ulInterval = ulAudioSize/cTrans; for (ULONG ul = 0; ul < cTrans; ul++) { Path[ul].elem.ulAudioStreamOffset = ul * ulInterval; Path[ul].elem.ulAudioSizeBytes = ulInterval/2; } } if (SUCCEEDED(hr)) { // generate a SPPARSEINFO structure SPPARSEINFO ParseInfo; memset(&ParseInfo, 0, sizeof(ParseInfo)); ParseInfo.cbSize = sizeof(SPPARSEINFO); ParseInfo.hRule = pRule->m_hRule; ParseInfo.ullAudioStreamPosition = ullAudioPos; ParseInfo.ulAudioSize = ulAudioSize; ParseInfo.cTransitions = cTrans; ParseInfo.pPath = Path; ParseInfo.fHypothesis = fHypothesis; ParseInfo.SREngineID = CLSID_SampleSREngine; ParseInfo.ulSREnginePrivateDataSize = 0; ParseInfo.pSREnginePrivateData = NULL; // Generate a phrase object from the parse info. hr = m_cpSite->ParseFromTransitions(&ParseInfo, ppPhrase ); if(SUCCEEDED(hr)) { // delete any allocated memory for(ULONG i = 0; i < cTrans; i++) { if(Path[i].elem.pszDisplayText) { delete const_cast(Path[i].elem.pszDisplayText); } } } } } return hr; } /**************************************************************************** * CSrEngine::FindRule * *---------------------* * Description: * This method is used to locate an active rule in the rule list by index * ****************************************************************************/ CRuleEntry* CSrEngine::FindRule( ULONG ulRuleIndex ) { CRuleEntry * pRule = m_RuleList.GetHead(); ULONG ulRule = 0; while( pRule ) { if( pRule->m_fActive && ( ulRule++ == ulRuleIndex ) ) { break; } pRule = m_RuleList.GetNext( pRule ); } SPDBG_ASSERT(pRule && pRule->m_fActive); return pRule; } /**************************************************************************** * CSrEngine::NextRuleAlt * *------------------------* * Description: * This method is used to locate a rule alternate in the rule list * ****************************************************************************/ CRuleEntry* CSrEngine::NextRuleAlt( CRuleEntry * pPriRule, CRuleEntry * pLastRule ) { CRuleEntry * pRule = (pLastRule)?(pLastRule):(m_RuleList.GetHead()); for(; pRule; pRule = m_RuleList.GetNext(pRule)) { if( pRule->m_fActive && ( m_cpSite->IsAlternate( pPriRule->m_hRule, pRule->m_hRule ) == S_OK ) ) { break; } } return pRule; } /**************************************************************************** * CSrEngine::WalkCFGRule * *------------------------* * Description: * This method is used to produce the results information for a CFG result. * It creates a result phrase and then some alternates phrases. * Return: * S_OK * FAILED(hr) ****************************************************************************/ HRESULT CSrEngine::WalkCFGRule( SPRECORESULTINFO * pResult, ULONG cRulesActive, BOOL fHypothesis, ULONG nWords, ULONGLONG ullAudioPos, ULONG ulAudioSize) { HRESULT hr = E_FAIL; CRuleEntry * pPriRule = NULL; pResult->ulSizeEngineData = 0; pResult->pvEngineData = NULL; pResult->eResultType = SPRT_CFG; pResult->hGrammar = NULL; while (hr == E_FAIL) { // Randomly pick a rule and locate it in the list pPriRule = FindRule( rand() % cRulesActive ); // Create a phrase from the rule hr = CreatePhraseFromRule( pPriRule, fHypothesis, ullAudioPos, ulAudioSize, &pResult->pPhrase ); // E_FAIL means the random path generated came to a dead end. Most likely an empty // dynamic rule. We are not allowed to recognize through empty rules. // Hence we choose another random toplevel rule and try again until we succeed. } if (hr != S_OK) { SPDBG_ASSERT(FALSE); } // Get the phrase info SPPHRASE* pPriPhraseInfo = NULL; if( SUCCEEDED( hr ) ) { hr = pResult->pPhrase->GetPhrase( &pPriPhraseInfo ); } // Ask the site how many alternates to generate ULONG ulNumAlts = 0; if( SUCCEEDED( hr ) ) { hr = m_cpSite->GetMaxAlternates( pPriRule->m_hRule, &ulNumAlts ); } // Randomly create some alternates if( SUCCEEDED( hr ) && ulNumAlts ) { pResult->aPhraseAlts = new SPPHRASEALT[ulNumAlts]; if( pResult->aPhraseAlts ) { memset( pResult->aPhraseAlts, 0, ulNumAlts * sizeof(SPPHRASEALT) ); CRuleEntry * pAltRule = NULL; for( ULONG i = 0; SUCCEEDED( hr ) && (i < ulNumAlts); ++i ) { // Try to find an alternate rule pAltRule = NextRuleAlt( pPriRule, pAltRule ); if( !pAltRule ) { ulNumAlts = i; break; } // Create an alternate phrase from the rule hr = CreatePhraseFromRule( pAltRule, fHypothesis, ullAudioPos, ulAudioSize, &pResult->aPhraseAlts[i].pPhrase ); // Get the alternate phrase info SPPHRASE* pAltPhraseInfo = NULL; if( SUCCEEDED( hr ) ) { hr = pResult->aPhraseAlts[i].pPhrase->GetPhrase( &pAltPhraseInfo ); } if( SUCCEEDED( hr ) ) { ++pResult->ulNumAlts; // Fill out relationship info pResult->aPhraseAlts[i].cElementsInParent = pPriPhraseInfo->Rule.ulCountOfElements; pResult->aPhraseAlts[i].cElementsInAlternate = pAltPhraseInfo->Rule.ulCountOfElements; // Point to some extra data for testing static BYTE AltData[] = { 0xED, 0xED, 0xED, 0xED }; pResult->aPhraseAlts[i].pvAltExtra = &AltData; pResult->aPhraseAlts[i].cbAltExtra = sp_countof( AltData ); } if( pAltPhraseInfo ) { ::CoTaskMemFree( pAltPhraseInfo ); } } } else { E_OUTOFMEMORY; } } // Cleanup main phrase information if( pPriPhraseInfo ) { ::CoTaskMemFree( pPriPhraseInfo ); } // Cleanup on failure if( FAILED( hr ) ) { if( pResult->pPhrase ) { pResult->pPhrase->Release(); pResult->pPhrase = NULL; } for( ULONG i = 0; i < pResult->ulNumAlts; ++i ) { pResult->aPhraseAlts[i].pPhrase->Release(); pResult->aPhraseAlts[i].pPhrase = NULL; } pResult->ulNumAlts = 0; delete[] pResult->aPhraseAlts; pResult->aPhraseAlts = NULL; } return hr; } /**************************************************************************** * CSrEngine::WalkSLM * *---------------------------* * Description: * This method is used to produce the results information for a dictation result. * It creates a result phrase, and then serializes some alternates information * that the CSrEngineAlternates object uses to generate alternates. * Return: * S_OK * FAILED(hr) *****************************************************************************/ HRESULT CSrEngine::WalkSLM(SPRECORESULTINFO * pResult, ULONG cSLMActive, ULONG nWords, ULONGLONG ullAudioPos, ULONG ulAudioSize) { HRESULT hr = S_OK; // If several dictation grammars are active pick one at random ULONG ulGramIndex = rand() % cSLMActive; CDrvGrammar * pGram = m_GrammarList.GetHead(); ULONG nGram = 0; for(; pGram; pGram = m_GrammarList.GetNext(pGram)) { if(pGram->m_SLMActive) { if(nGram == ulGramIndex) { break; } nGram++; } } SPDBG_ASSERT(pGram && pGram->m_SLMActive); // create and fill SPPHRASE structure SPPHRASE phrase; memset(&phrase, 0, sizeof(SPPHRASE)); phrase.cbSize = sizeof(SPPHRASE); phrase.LangID = m_LangID; phrase.ullAudioStreamPosition = ullAudioPos; phrase.ulAudioSizeBytes = ulAudioSize; phrase.SREngineID = CLSID_SampleSREngine; // allocate elements ULONG cb = nWords * sizeof(SPPHRASEELEMENT); SPPHRASEELEMENT* pElements = (SPPHRASEELEMENT *)_alloca(cb); memset(pElements, 0, cb); // fill in word info into elements for (ULONG n = 0; n < nWords; n++) { ULONG ulInterval = ulAudioSize/nWords; pElements[n].bDisplayAttributes = SPAF_ONE_TRAILING_SPACE; pElements[n].pszDisplayText = DICT_WORD; pElements[n].ulAudioStreamOffset = n * ulInterval; pElements[n].ulAudioSizeBytes = ulInterval/2; } // add elements to phrase phrase.Rule.ulCountOfElements = nWords; phrase.pElements = pElements; // make phrase builder and add phrase info CComPtr cpBuilder; hr = cpBuilder.CoCreateInstance(CLSID_SpPhraseBuilder); if (SUCCEEDED(hr)) { hr = cpBuilder->InitFromPhrase(&phrase); } if (SUCCEEDED(hr)) { // Store alternates string in extra engine data // We just serialize an equal number of copies of ALT_WORD as DICT_WORD. // Engines can store any information (e.g. serialized lattice) here. pResult->ulSizeEngineData = sizeof(ALT_WORD) * nWords; pResult->pvEngineData = new WCHAR[(sizeof(ALT_WORD) / sizeof(WCHAR )) * nWords]; if (pResult->pvEngineData == NULL) { hr = E_OUTOFMEMORY; } } if (SUCCEEDED(hr)) { WCHAR *pC = (WCHAR *)pResult->pvEngineData; for(ULONG i = 0; i < nWords; i++) { wcscpy(pC,ALT_WORD); pC += wcslen(ALT_WORD); *pC = L' '; pC++; } *(--pC) = '\\0'; pResult->eResultType = SPRT_SLM; pResult->hGrammar = pGram->m_hSapiGrammar; } if (SUCCEEDED(hr)) { pResult->pPhrase = cpBuilder.Detach(); } else { delete[] pResult->pvEngineData; pResult->pvEngineData = NULL; pResult->ulSizeEngineData = 0; } return hr; } /**************************************************************************** * CSrEngine::WalkTextBuffer * *---------------------------* * Description: * This is called when RecurseWalk hits a text-buffer transition. * At such a transition the engine should try to recognize any sequence * of words from the active text selection the app has supplied. * Any word can be the start word and then recognition can continue to * the next \\0 end of sentence marker or at the end of the active text selection. * In this sample we pick a random string of words from the buffer. * Return: * S_OK * FAILED(hr) *****************************************************************************/ HRESULT CSrEngine::WalkTextBuffer(void* pvGrammarCookie, SPPATHENTRY * pPath, SPTRANSITIONID hId, ULONG * pcTrans) { HRESULT hr = S_OK; // Check if text buffer present CDrvGrammar * pGrammar = (CDrvGrammar *) pvGrammarCookie; SPDBG_ASSERT(pGrammar->m_pWordSequenceText && pGrammar->m_cchText >= 2); //m_cchText counts the trailing ""/0/0"" *pcTrans = 0; // Count sentences ULONG nPhrase = 0; const WCHAR *cPhrase; ULONG ulStartActiveOffset = 0; //The default value with text selection ULONG cchActiveChars = pGrammar->m_cchText - 2; //The default value with text selection ULONG ccChars = 0; if (pGrammar->m_pInfo) { ulStartActiveOffset = pGrammar->m_pInfo->ulStartActiveOffset; cchActiveChars = pGrammar->m_pInfo->cchActiveChars; } for (cPhrase = pGrammar->m_pWordSequenceText + ulStartActiveOffset; ccChars < cchActiveChars && (*cPhrase != L'\\0' || *(cPhrase + 1) != '\\0'); ccChars++, cPhrase++) { if(*cPhrase != L'\\0' && *(cPhrase + 1) == L'\\0') { nPhrase++; } } SPDBG_ASSERT(nPhrase); // Randomly pick a sentence between the first active sentence and the last active sentence nPhrase = rand() % nPhrase; //nPhrase would be 0 index ULONG nP = 0; for(cPhrase = pGrammar->m_pWordSequenceText + ulStartActiveOffset; nP != nPhrase; cPhrase++) { if(*cPhrase == L'\\0') { nP++; } } // Count words in sentence ULONG nWord = 1; const WCHAR *cWord; for(cWord = cPhrase; *cWord != L'\\0' && ULONG(cWord - pGrammar->m_pWordSequenceText) < ulStartActiveOffset + cchActiveChars; cWord++) { if(iswspace(*cWord)) { while(*(cWord+1) && iswspace(*(cWord+1)) && ULONG(cWord - pGrammar->m_pWordSequenceText) < ulStartActiveOffset + cchActiveChars - 1) {cWord++;} nWord++; } } // Pick entry and exit word ULONG startWord = rand() % nWord; ULONG countWord = rand() % (nWord - startWord) + 1; // Find the entry word for(nWord = 0, cWord = cPhrase; nWord != startWord; cWord++) { if(iswspace(*cWord)) { while(*(cWord+1) && iswspace(*(cWord+1)) && ULONG(cWord - pGrammar->m_pWordSequenceText) < ulStartActiveOffset + cchActiveChars - 1) {cWord++;} nWord++; } } // Build paths to end word const WCHAR *cW = cWord; for(nWord = 0; nWord != countWord; cWord++) { if(*cWord == L'\\0' || iswspace(*cWord) || ULONG(cWord - pGrammar->m_pWordSequenceText) == ulStartActiveOffset + cchActiveChars) { // Build a path entry pPath->hTransition = hId; memset(&pPath->elem, 0, sizeof(pPath->elem)); pPath->elem.bDisplayAttributes = SPAF_ONE_TRAILING_SPACE; WCHAR *pszWord = new WCHAR[cWord - cW + 1]; wcsncpy(pszWord, cW, cWord - cW); pszWord[cWord - cW] = '\\0'; pPath->elem.pszDisplayText = pszWord; pPath++; (*pcTrans)++; while(*(cWord+1) && iswspace(*(cWord+1)) && ULONG(cWord - pGrammar->m_pWordSequenceText) < ulStartActiveOffset + cchActiveChars - 1) {cWord++;} cW = cWord + 1; // first char of next word nWord++; } } return hr; } /**************************************************************************** * CSrEngine::RecurseWalk * *----------------------* * Description: * This method produces a random path through an active CFG. If the path contains * a rule reference transition RecurseWalk is recursively called to produce a path though * sub-rules. The result is an array of SPPATHENTRY elements containing the transitions. * * The initial state in each rule is obtained by calling GetRuleInfo. Then for each * state GetStateInfo can be called. This gives an array of SPTRANSITION entries * the contain information on the type of transition, the transition id and * the next state the transition goes to. The transition id is the main information * included in the SPPATHENTRY. Only for word transitions are SPPATHENTRY created, * as this is all that is required by ParseFromTransitions. * * Return: * S_OK * FAILED(hr) ****************************************************************************/ HRESULT CSrEngine::RecurseWalk(SPSTATEHANDLE hState, SPPATHENTRY * pPath, ULONG * pcTrans) { HRESULT hr = S_OK; CSpStateInfo StateInfo; *pcTrans = 0; while (SUCCEEDED(hr) && hState) { ULONG cTrans; hr = m_cpSite->GetStateInfo(hState, &StateInfo); if (SUCCEEDED(hr)) { // Now randomly decide which transition to take. ULONG cTransInState = StateInfo.cEpsilons + StateInfo.cWords + StateInfo.cRules + StateInfo.cSpecialTransitions; if (cTransInState == 0) { // This path is a dead-end. Most likely this is due to an empty dynamic rule. hr = E_FAIL; break; } SPTRANSITIONENTRY * pTransEntry = StateInfo.pTransitions + (rand() % cTransInState); switch(pTransEntry->Type) { case SPTRANSEPSILON: // Epsilon transition - don't need to create a path entry // Advance to the next state. break; case SPTRANSRULE: // Rule transition - we recursively descend into the rule and add onto the path array hr = RecurseWalk(pTransEntry->hRuleInitialState, pPath, &cTrans); *pcTrans += cTrans; pPath += cTrans; break; case SPTRANSWORD: case SPTRANSWILDCARD: // For a word transition we complete an SPPATHENTRY structure with the transition id. // A wildcard transition indicates the engine should match against any speech, so we do the same thing. pPath->hTransition = pTransEntry->ID; memset(&pPath->elem, 0, sizeof(pPath->elem)); pPath->elem.bDisplayAttributes = SPAF_ONE_TRAILING_SPACE; pPath++; (*pcTrans)++; break; case SPTRANSTEXTBUF: // Text Buffer transition - produce a path from WalkTextBuffer hr = WalkTextBuffer(pTransEntry->pvGrammarCookie, pPath, pTransEntry->ID, &cTrans); *pcTrans += cTrans; pPath += cTrans; break; case SPTRANSDICTATION: // Dictation transition - indicating the recognizer should do dictation at // this point in the grammar. We generate the DICT_WORD as a path entry. // The word text is indicated by setting pszDisplayText, which otherwise can be left NULL. pPath->hTransition = pTransEntry->ID; memset(&pPath->elem, 0, sizeof(pPath->elem)); pPath->elem.bDisplayAttributes = SPAF_ONE_TRAILING_SPACE; WCHAR *pszWord = new WCHAR[wcslen(DICT_WORD) + 1]; wcscpy(pszWord, DICT_WORD); pPath->elem.pszDisplayText = pszWord; pPath++; (*pcTrans)++; break; } // Move to the next state - a transition to NULL indicates the end of the rule. hState = pTransEntry->hNextState; } } return hr; } /**************************************************************************** * CSrEngine::GetInputAudioFormat * *---------------------------* * Description: * This method is called for SAPI to find what audio formats the engine * can support for recognition. * Audio formats a represented by a GUID and an optional WAVEFORMATEX * structure for wav file formats. This method may be called * either with pSourceFormatId and pSourceWaveFormatEx NULL, in which * case the engine should return its most preferred format. It may also * be called with these set, in which case the engine should return * that format if it can support or the closest it can. * * If the engines returned format is incompatible with the input audio * object format SAPI will try and create a format convertor to convert the audio * * Return: * S_OK * FAILED(hr) *****************************************************************************/ STDMETHODIMP CSrEngine::GetInputAudioFormat(const GUID * pSourceFormatId, const WAVEFORMATEX * pSourceWaveFormatEx, GUID * pDesiredFormatId, WAVEFORMATEX ** ppCoMemDesiredWFEX) { SPDBG_FUNC( ""Sample Engine - GETINPUTAUDIOFORMAT"" ); // Helper function which fills in the sample engine desired format (PCM 11kHz Mono). return SpConvertStreamFormatEnum(SPSF_11kHz16BitMono, pDesiredFormatId, ppCoMemDesiredWFEX); } /***************************************************************************** * CSrEngine::SetPropertyNum * *---------------------* * Description: * The following methods are used for the app to send and receive * real-time attribute information to the engine. This differs from the * ISpObjectWithToken mechanism which is used to query static registry information. * If the app tries to set or query an attribute the engine should return * okay if it supports that attribute and S_FALSE if it does not. * In this method the app is trying to set a numeric property value. * Return: * S_FALSE *****************************************************************************/ STDMETHODIMP CSrEngine:: SetPropertyNum( SPPROPSRC eSrc, PVOID pvSrcObj, const WCHAR* pName, LONG lValue ) { SPDBG_FUNC( ""Sample Engine - SETPROPERTYNUM"" ); HRESULT hr = S_OK; hr = S_FALSE; // We don't support any properties return hr; } /***************************************************************************** * CSrEngine::GetPropertyNum * *---------------------* * Description: * In this method the app is trying to get a numeric property value. *****************************************************************************/ STDMETHODIMP CSrEngine:: GetPropertyNum( SPPROPSRC eSrc, PVOID pvSrcObj, const WCHAR* pName, LONG * plValue ) { SPDBG_FUNC( ""Sample Engine - GETPROPERTYNUM"" ); HRESULT hr = S_OK; hr = S_FALSE; *plValue = 0; return hr; } /***************************************************************************** * CSrEngine::SetPropertyString * *----------------------* * Description: * In this method the app is trying to set a string property value. *****************************************************************************/ STDMETHODIMP CSrEngine:: SetPropertyString( SPPROPSRC eSrc, PVOID pvSrcObj, const WCHAR* pName, const WCHAR* pValue ) { SPDBG_FUNC( ""Sample Engine - SETPROPERTYSTRING"" ); HRESULT hr = S_OK; hr = S_FALSE; return hr; } /***************************************************************************** * CSrEngine::GetPropertyString * *----------------------* * Description: * In this method the app is trying to get a string property value. *****************************************************************************/ STDMETHODIMP CSrEngine:: GetPropertyString( SPPROPSRC eSrc, PVOID pvSrcObj, const WCHAR* pName, WCHAR** ppCoMemValue ) { SPDBG_FUNC( ""Sample Engine - GETPROPERTYSTRING"" ); HRESULT hr = S_OK; hr = S_FALSE; *ppCoMemValue = NULL; return hr; } /**************************************************************************** * CSrEngine::PrivateCall * *---------------------------* * Description: * This method is used for a reco extension to send private, engine-specific information * to an engine it knows about. The app QI's off the reco context for a private * interface, and SAPI creates the engine' extension object (in this case CSampleSRExtension). * The app can then call methods on this interface. If the extension object wants to * communicate with the engine it calls CallEngine. The data from that call is then * passed to this method on the engine. * * Similarly the alternates class and UI class can also use this mechanism to * communicate with their main engine class. * * The single buffer is in/out. This call can update the buffer, and the updated buffer * will be returned to the caller of _ISpPrivateEngineCall::CallEngine(). To return * variable size buffers, use _ISpPrivateEngineCall::CallEngineEx() and * ISpSREngine::PrivateCallEx(). * * Return: * S_OK *****************************************************************************/ STDMETHODIMP CSrEngine::PrivateCall(void * pvEngineContext, void * pCallFrame, ULONG ulCallFrameSize) { SPDBG_FUNC( ""Sample Engine - PRIVATECALL"" ); // Just an example - do nothing here return S_OK; } /**************************************************************************** * CSrEngine::PrivateCallEx * *--------------------------* * Description: * This method is similar to PrivateCall except that the call frame is an * input only parameter. This function should CoTaskMemAlloc a response block * and return it in *ppvCoMemResponse. You must also return the size of the * allocated block (in bytes) in *pcbResponse. * * While this is slightly more work than CallEngine/PrivateCall, it allows for * variable size responses, which could be more efficent in some cases. * * Returns: * S_OK * *****************************************************************************/ STDMETHODIMP CSrEngine::PrivateCallEx(void * pvEngineContext, const void * pInCallFrame, ULONG ulCallFrameSize, void ** ppvCoMemResponse, ULONG * pcbResponse) { SPDBG_FUNC(""SampleEngine - PrivateCallEx""); HRESULT hr = S_OK; *ppvCoMemResponse = NULL; *pcbResponse = 0; return hr; } ",16256,True,2562.0384551995858,median "// \\file hkl_datatypes.cpp #include #include // Clipper #include using clipper::Message; using clipper::Message_fatal; using clipper::Message_warn; #include ""csymlib.h"" // CCP4 symmetry stuff #include ""rotation.hh"" #include ""hkl_datatypes.hh"" #include ""scala_util.hh"" #include ""range.hh"" #include ""matvec_utils.hh"" #include ""string_util.hh"" #include ""hkl_symmetry.hh"" namespace scala { //-------------------------------------------------------------- //------------------------------------------------------------ std::string Chiral_as_string(const Chirality& chiral) { if (chiral == UNKNOWN) return ""UNKNOWN""; if (chiral == CHIRAL) return ""CHIRAL""; if (chiral == NONCHIRAL) return ""NONCHIRAL""; if (chiral == CENTROSYMMETRIC) return ""CENTROSYMMETRIC""; return """"; } //-------------------------------------------------------------- // Orientation things // DVect3 SpindleToPrincipleAxes(const DMat33& DUB) // Returns angles in degrees between principle reciprocal axes a*, b*, c* // and the rotation spindle (along z). Angles in range 0 - 90 degress // On entry: // DUB is setting matrix [D][U][B] { DVect3 angles; DVect3 spindle(0.0,0.0,1.0); // spindle along z for (int i=0;i<3;++i) { DVect3 axis(0.0,0.0,0.0); axis[i] = 1.0; // a*, b*, c* angles[i] = clipper::Util::rad2d(acos (std::abs(clipper::Vec3<>::dot(spindle, (DUB * axis).unit())))); } return angles; } //-------------------------------------------------------------- int SmallestComponent(const DVect3& v) // Returns index of smallest component of vector { int ismall = 0; // EK: renamed due to Windows clash double min = +1.0e30; for (int i=0;i<3;++i) { if (v[i] < min) { ismall = i; min = v[i]; } } return ismall; } //-------------------------------------------------------------- std::string FormatSpindleToPrincipleAxes(const DMat33& DUB) // Format closest reciprocal axis to spindle { DVect3 angles = SpindleToPrincipleAxes(DUB); int ismall = SmallestComponent(angles); // EK: renamed due to Windows clash std::string axis; if (ismall == 0) {axis = ""a*"";} else if (ismall == 1) {axis = ""b*"";} else if (ismall == 2) {axis = ""c*"";} return axis+"" (angle ""+clipper::String(angles[ismall],6,3)+ "" degrees)""; } //-------------------------------------------------------------- int ClosestPrincipleAxisToSpindle(const DMat33& DUB) // 0,1,2 for h,k,l { DVect3 angles = SpindleToPrincipleAxes(DUB); return SmallestComponent(angles); } //-------------------------------------------------------------- ReindexOp::ReindexOp(const std::string& Operator) // Construct from string eg ""2h+k,k,l"" { float rt44[10][4][4]; // Allocate excess space in case of error int Noper = CSym::symfr_driver(Operator.c_str(), rt44); if (Noper != 1) Message::message(Message_fatal (""ReindexOp: syntax error in operator; ""+Operator)); Mat33 H; Vec3 v; for (int i=0;i<3;i++) { for (int j=0;j<3;j++) // We want the transpose of the matrix since reindex operator H // applies to index h such that h'T = hT H {H(j,i) = rt44[0][i][j];} v[i] = rt44[0][i][3]; } rot() = H; trn() = v; } //-------------------------------------------------------------- std::string ReindexOp::as_hkl() const { std::string st = MVutil::FormatReindex_as_hkl(*this); return st; } //-------------------------------------------------------------- std::string ReindexOp::as_hkl_XML() const { std::string st = MVutil::FormatReindex_as_hkl(*this); return """"+st+""""; } //-------------------------------------------------------------- std::string ReindexOp::as_matrix() const // Rotation only! { std::string fmat = "" h' = ( h k l ) (""; for (int i=0;i<3;i++) { if (i > 0) fmat += "" (""; for (int j=0;j<3;j++) { fmat += "" ""+String(rot()(i,j),7,4); } fmat += "" )\\n""; } return fmat; } //-------------------------------------------------------------- std::string ReindexOp::as_XML() const { std::string fmat = """"; for (int i=0;i<3;i++) { if (i > 0) fmat += "" ""; for (int j=0;j<3;j++) { fmat += "" ""+String(rot()(i,j),6,4); } fmat += ""\\n""; } fmat += "" \\n""; return fmat; } //-------------------------------------------------------------- bool operator < (const ReindexOp& a,const ReindexOp& b) // Sort on deviation, putting identity before anything else { if (MVutil::is_rtop_ident(a)) return true; if (MVutil::is_rtop_ident(b)) return false; return a.deviation < b.deviation; } //-------------------------------------------------------------- bool ReindexOp::equals(const ReindexOp& b, const double& tol) const { return (rot().equals(b.rot(), tol) && trn().equals(b.trn(), tol)); } //-------------------------------------------------------------- void ReindexOp::FindSimplest(const SpaceGroup& symm) // Apply symmetry operators to reindex operator H and choose the simplest // Criteria for ""simplest"" // 1) identity // 2) smallest sum of absolute value of all elements // 3) minimum number of negatives // cf. AlternativeBases::SimplestOp // // h'T = hT [H] reindex hiT = hT [Ri] symmetry // [H'] = [Ri] [H] where [Ri] is the reciprocal space symmetry operator { Mat33 H = rot(); // initial reindex Mat33 Hbest = H; // initial reindex Mat33 Imat = Mat33::identity(); // identity matrix const double TOL = 0.001; // tolerance double besttot = 10000000.; // sum of absolute value of all elements int minneg = 100000; // minimum number of negatives int kbest = -1; for (int isym=0;isym Ht = H * symm.symop(isym).rot().inverse(); if (Ht.equals(Imat, TOL)) { rot() = Imat; //^ // std::cout << ""*** FindSimplest: identity with symop "" << isym << ""\\n"" // << symm.symop(isym).rot().inverse().format() << ""\\n""; //^- return; // always accept identity operation if found } double total = 0.0; // total int nneg = 0; // number of negatives for (int i=0;i<3;i++) for (int j=0;j<3;j++) { total += std::abs(Ht(i,j)); if (Ht(i,j) < 0.0) nneg += 1; } if (total < besttot-TOL) { besttot = total; minneg = nneg; Hbest = Ht; kbest = isym; } else if (Close(total, besttot, TOL)) { if (nneg < minneg) { besttot = total; minneg = nneg; Hbest = Ht; kbest = isym; } } //^ // std::cout << ""\\n\\nFindSimplest: symop "" << isym << ""\\n"" // << symm.symop(isym).rot().inverse().format() // << ""\\n\\nReindex:\\n"" << Ht.format() // << "" total "" << total << "" nneg "" << nneg // << ""\\n""; //^- } rot() = Hbest; //^ // std::cout << ""\\n***FindSimplest: best reindex "" << as_hkl() << "" with symop "" << kbest << ""\\n"" // << symm.symop(kbest).rot().inverse().format() << ""\\n\\n""; //^- } //-------------------------------------------------------------- //! change basis of symmetry operator clipper::Symop ReindexOp::Symop(const clipper::Symop& symop) const { // S' = H^-1 S H // t' = H^-1 t clipper::Mat33 HR = rot(); clipper::RTop Sp(HR.inverse()*symop.rot()*HR, HR.inverse() * symop.trn()); return clipper::Symop(Sp); } //-------------------------------------------------------------- bool operator == (const ReindexOp& a,const ReindexOp& b) { return a.equals(b); } //-------------------------------------------------------------- bool operator != (const ReindexOp& a,const ReindexOp& b) { return !(a.equals(b)); } //-------------------------------------------------------------- ReindexOp operator * (const ReindexOp& a,const ReindexOp& b) { return ReindexOp(RTop(a) * RTop(b)); } //-------------------------------------------------------------- ReindexOp operator * (const RTop& a,const ReindexOp& b) { return ReindexOp(a * b); } //-------------------------------------------------------------- ReindexOp operator * (const ReindexOp& a,const RTop& b) { return ReindexOp(a * b); } //-------------------------------------------------------------- Vec3 operator * (const Vec3 v, const ReindexOp& R) // vT . R { return v*R.rot() + R.trn(); } //-------------------------------------------------------------- //-------------------------------------------------------------- /*! Construct and initialise a metric tensor, given a set of real or reciprocal cell parameters. \\param a Length of \\b a axis in Angstroms or reciprocal Angstroms. \\param b Length of \\b b axis in Angstroms or reciprocal Angstroms. \\param c Length of \\b c axis in Angstroms or reciprocal Angstroms. \\param alph Angle between \\b b and \\b c in degrees. \\param beta Angle between \\b a and \\b c in degrees. \\param gamm Angle between \\b a and \\b b in degrees. */ // from Clipper with extensions // Note that the off-diagonal elements are stored doubled so that they can be used // directly to multiply vectors MetricTensor::MetricTensor( const ftype& a, const ftype& b, const ftype& c, const ftype& alph, const ftype& beta, const ftype& gamm ) { double degtorad = atan(1.0)/45.0; m00 = a*a; m11 = b*b; m22 = c*c; m01 = 2.0*a*b*cos(gamm*degtorad); m02 = 2.0*a*c*cos(beta*degtorad); m12 = 2.0*b*c*cos(alph*degtorad); } //-------------------------------------------------------------- MetricTensor::MetricTensor(const std::vector cell) { double degtorad = atan(1.0)/45.0; m00 = cell[0]*cell[0]; m11 = cell[1]*cell[1]; m22 = cell[2]*cell[2]; m01 = 2.0*cell[0]*cell[1]*cos(cell[5]*degtorad); m02 = 2.0*cell[0]*cell[2]*cos(cell[4]*degtorad); m12 = 2.0*cell[1]*cell[2]*cos(cell[3]*degtorad); } //-------------------------------------------------------------- MetricTensor::MetricTensor(const Mat33 MetricMatrix) // Constructor from full matrix - no check on equality of // off-diagonal elements, just add them together to store // 2 * a.b etc { m00 = MetricMatrix(0,0); m11 = MetricMatrix(1,1); m22 = MetricMatrix(2,2); m01 = MetricMatrix(0,1) + MetricMatrix(1,0); m02 = MetricMatrix(0,2) + MetricMatrix(2,0); m12 = MetricMatrix(1,2) + MetricMatrix(2,1); } //-------------------------------------------------------------- std::vector MetricTensor::cell() const // Return unit cell dimensions (real or reciprocal) // Angles in degrees { double degtorad = atan(1.0)/45.0; std::vector cell(6); cell[0] = sqrt(m00); cell[1] = sqrt(m11); cell[2] = sqrt(m22); cell[3] = acos(0.5 * m12 / (cell[1] * cell[2]))/degtorad; cell[4] = acos(0.5 * m02 / (cell[2] * cell[0]))/degtorad; cell[5] = acos(0.5 * m01 / (cell[0] * cell[1]))/degtorad; return cell; } //-------------------------------------------------------------- MetricTensor MetricTensor::inverse() const { // Mat33 MetricMatrix = matrix(); return MetricTensor((*this).matrix().inverse()); } //-------------------------------------------------------------- Mat33 MetricTensor::matrix() const { return Mat33(m00, 0.5*m01, 0.5*m02, 0.5*m01, m11, 0.5*m12, 0.5*m02, 0.5*m12, m22); } //-------------------------------------------------------------- String MetricTensor::format() const { return ""m00="" + String(m00) + "" m11="" + String(m11) + "" m22="" + String(m22) + "" m01="" + String(m01) + "" m02="" + String(m02) + "" m12="" + String(m12); } //-------------------------------------------------------------- Scell::Scell(const std::vector& real_cell) // Construct Scell object from vector cell { init(real_cell); } //-------------------------------------------------------------- Scell::Scell(const float* cell) // Construct Scell object from float array cell { std::vector real_cell(cell, &cell[6]); init(real_cell); } //-------------------------------------------------------------- Scell::Scell(const clipper::Cell& ccell) // Construct Scell object from clipper::Cell { std::vector real_cell(6); real_cell[0] = ccell.a(); real_cell[1] = ccell.b(); real_cell[2] = ccell.c(); real_cell[3] = ccell.alpha_deg(); real_cell[4] = ccell.beta_deg(); real_cell[5] = ccell.gamma_deg(); init(real_cell); } //-------------------------------------------------------------- Scell::Scell(const double& a,const double& b,const double& c, const double& alpha, const double& beta, const double& gamma) // Construct Scell object from real cell { std::vector real_cell(6); real_cell[0] = a; real_cell[1] = b; real_cell[2] = c; real_cell[3] = alpha; real_cell[4] = beta; real_cell[5] = gamma; init(real_cell); } //-------------------------------------------------------------- Scell::Scell(const MetricTensor& metric_tensor, const bool real) // Construct from real or reciprocal metric tensor { if (real) { // real cell init(metric_tensor.cell()); } else { // reciprocal cell init(metric_tensor.inverse().cell()); } } //-------------------------------------------------------------- // Construct cell class from real cell // derive reciprocal cell and orthogonalisation matrix B void Scell::init(const std::vector& real_cell) { double degtorad = atan(1.0)/45.0; cell_.resize(6); rec_cell_.resize(6); for (int i=0;i<6;i++) cell_[i] = real_cell[i]; // Real metric tensor metric_tensor_ = MetricTensor(cell_); // Reciprocal metric tensor recip_metric_tensor_ = metric_tensor_.inverse(); // Reciprocal cell rec_cell_ = recip_metric_tensor_.cell(); // Orthogonalisation matrix (A**-1) // Reciprocal cell double as = rec_cell_[0]; // a* double bs = rec_cell_[1]; // b* double cs = rec_cell_[2]; // c* // double cas = cos(rec_cell_[3]*degtorad); // cos(alpha*) double cbs = cos(rec_cell_[4]*degtorad); // cos(beta*) double cgs = cos(rec_cell_[5]*degtorad); // cos(gamma*) // double sas = sin(rec_cell_[3]*degtorad); // sin(alpha*) double sbs = sin(rec_cell_[4]*degtorad); // sin(beta*) double sgs = sin(rec_cell_[5]*degtorad); // sin(gamma*) double cc = cell_[2]; double ca = cos(cell_[3]*degtorad); Bmat_ = Mat33(as, bs*cgs, cs*cbs, 0., bs*sgs, -cs*sbs*ca, 0., 0., 1.0/cc); } //-------------------------------------------------------------- std::string Scell::formatPrint(const bool& newline) const { std::string s; for (int i = 0; i < 6; ++i) s += FormatOutput::logTabPrintf(0, ""%7.2f "", cell_[i]); if (newline) s += ""\\n""; return s; } //-------------------------------------------------------------- void Scell::dump() const { std::cout << ""\\n\\n Real cell: ""; for (int i = 0; i < 6; ++i) std::cout << cell_[i] << "" ""; std::cout << std::endl; std::cout << ""Reciprocal cell: ""; for (int i = 0; i < 6; ++i) std::cout << rec_cell_[i] << "" ""; std::cout << std::endl; std::cout << ""RealMetricTensor:\\n"" << metric_tensor_.format() << ""\\n""; std::cout << ""RecipMetricTensor:\\n"" << recip_metric_tensor_.format() << ""\\n""; std::cout << ""Bmat:\\n"" << Bmat_.format() << ""\\n""; } //-------------------------------------------------------------- Scell Scell::change_basis(const ReindexOp& reindex_op) const { // H reindex operator (ignores translations) // B current orthogonalisation matrix // new (UB)' = B H(T)^-1 Mat33 UBp = Bmat_ * reindex_op.transpose().inverse(); // Reciprocal metric tensor = (UB)'(T) (UB)' // construct new cell object from reciprocal metric tensor return Scell(UBp.transpose() * UBp, false); } //-------------------------------------------------------------- std::string Scell::format(const int w, const int p) const { return FormatCell(cell_,w,p); } //-------------------------------------------------------------- std::string Scell::xml() const { std::string line = ""\\n""; line += "" ""+clipper::String(cell_[0],7,4)+""\\n""; line += "" ""+clipper::String(cell_[1],7,4)+""\\n""; line += "" ""+clipper::String(cell_[2],7,4)+""\\n""; line += "" ""+clipper::String(cell_[3],7,4)+""\\n""; line += "" ""+clipper::String(cell_[4],7,4)+""\\n""; line += "" ""+clipper::String(cell_[5],7,4)+""\\n""; line += ""\\n""; return line; } //-------------------------------------------------------------- double Scell::Volume() const { double degtorad = atan(1.0)/45.0; double a = cell_[0]; double b = cell_[1]; double c = cell_[2]; double alpha = cell_[3] * degtorad; double beta = cell_[4] * degtorad; double gamma = cell_[5] * degtorad; double vol = a * b * c * sqrt( 2.0*cos(alpha)*cos(beta)*cos(gamma) - cos(alpha)*cos(alpha) - cos( beta)*cos( beta) - cos(gamma)*cos(gamma) + 1.0 ); return vol; } //-------------------------------------------------------------- // Return true if all angles are within Tol of given test values bool Scell::AngleTest(const double& AlphaTest, const double& BetaTest, const double& GammaTest, const double Tol) const { if (Close(cell_[3], AlphaTest, Tol)) if (Close(cell_[4], BetaTest, Tol)) if (Close(cell_[5], GammaTest, Tol)) return true; return false; } //-------------------------------------------------------------- // Returns true if cells agree within ""tolerance"" bool Scell::equals(const Scell& other, const double& tolA, const double& tolD) const { bool OK = true; for (int i=0;i<3;i++) {if (!Close(cell_[i], other.cell_[i], tolA)) OK = false;} for (int i=3;i<6;i++) {if (!Close(cell_[i], other.cell_[i], tolD)) OK = false;} return OK; } //-------------------------------------------------------------- // Returns true if cells agree within ""tolerance"" bool Scell::equalsTol(const Scell& other, const double& AngularTolerance) const { // Very rough: convert angular tolerance to ""length"" using // average cell edge // double edge = Max(Max(test_cell[0], test_cell[1]), test_cell[2]); double edge = 0.333 * (cell_[0] + cell_[1] + cell_[2]); double max_diff = clipper::Util::d2rad(AngularTolerance) * edge; return equals(other, max_diff, AngularTolerance); } //-------------------------------------------------------------- bool Scell::null() const // Returns true if any value is close to zero { Dtype tol = 0.1; for (int i=0;i<6;i++) { if (std::abs(cell_[i]) < tol) return true; } return false; } //-------------------------------------------------------------- /*! If the ""difference"" between cells is greater than half the resolution, then a reflection may be mapped on to the next reflection in the other cell */ double Scell::Difference(const Scell& other) const // ""difference"" between two cells in A, maximum allowed distance // algorithm from clipper::Cell::equals // Even Kevin doesn't understand this, though presumably V^1/3 is an // average cell length { double s = 0.0; for (int j=0;j<3;++j) { for (int i=0;i<3;++i) { s += (Bmat_(i,j) - other.Bmat_(i,j))*(Bmat_(i,j) - other.Bmat_(i,j)); }} // sum of squares of orthogonalisation matrix differences // Average cell volume double vav = (Volume() + other.Volume())*0.5; double v43 = pow(vav, 1.333333); // V^4/3 // std::cout << ""\\nScell::Difference "" << s // << "" "" << Volume()<< "" "" << other.Volume() << ""\\n""; //^ return sqrt(v43 * s); } //-------------------------------------------------------------- //! Construct from list of cells UnitCellSet::UnitCellSet(const std::vector& Cells) :cells(Cells) { averagecell = Average(); // average all cells } //-------------------------------------------------------------- //! Initialise from list of cells void UnitCellSet::init(const std::vector& Cells) { cells = Cells; averagecell = Average(); // average all cells } //-------------------------------------------------------------- void UnitCellSet::AddCell(const Scell& Cell) { cells.push_back(Cell); averagecell = Average(); // average all cells } //-------------------------------------------------------------- Scell UnitCellSet::Average(const int& idxexclude) const // Average list of cells // if idxexclude >= 0, exclude entry with this index, < 0 include all { int nc = cells.size(); ASSERT (idxexclude < nc); if (idxexclude >= 0) nc--; if (nc <= 0) {return Scell();} else if (nc == 1) { int j = (idxexclude+1)%2; // 1 or 0 return cells[j]; } // We have 2 or more,average std::vector sumcell(6,0.0); for (size_t k=0; k UnitCellSet::Deviations() const { std::vector dv(Number(), 0.0); if (Number() <= 1) return dv; Scell cell; for (int i=0;i dv = Deviations(); for (size_t i=0;i UnitCellSet::RmsD() const { std::vector dv(6, 0.0); if (Number() <= 1) return dv; std::vector rms(6); for (int i=0;i cv = cells[i].UnitCell(); for (int j=0;j<6;++j) { rms[j].Add(cv[j]); } } for (int j=0;j<6;++j) { dv[j] = rms[j].SD(); } return dv; } //-------------------------------------------------------------- // Change basis: new h' = h * reindex_op // return false if indices are non-integral // reindex_op may include translations bool Hkl::change_basis(Hkl& Newhkl, const ReindexOp& reindex_op) const { Vec3 vh(*this); Vec3 v = vh * reindex_op; Newhkl = Hkl(Nint(v[0]), Nint(v[1]), Nint(v[2])); bool OK = true; for (int i=0;i<3;i++) { if (std::abs(v[i]-double(Newhkl[i])) > 0.05) OK = false; } return OK; } //-------------------------------------------------------------- Hkl Hkl::change_basis(const ReindexOp& reindex_op) const // reindex_op may include translations { Vec3 vh(*this); Vec3 v = vh * reindex_op; return Hkl(Nint(v[0]), Nint(v[1]), Nint(v[2])); } //-------------------------------------------------------------- std::string Hkl::format() const { return ""HKL = (""+String(h())+"",""+String(k())+"",""+String(l())+"")""; } //-------------------------------------------------------------- int Hkl::code() const // encode hkl triple as integer (not guaranteed unique) { return (((*this)[0] & 0x3FF) << 20) | (((*this)[1] & 0x3FF) << 10) | (((*this)[2] & 0x3FF)); } //-------------------------------------------------------------- Hkl HklDecode(const int& kode) // decode integer as hkl triple { int h = (kode << 2) >> 22; int k = (kode << 12) >> 22; int l = (kode << 22) >> 22; return Hkl(h,k,l); } //-------------------------------------------------------------- bool Hkl::IsGeneral() const { if (h()==0 || k()==0 || l()==0) return false; if ((h()==k()) || (k()==l()) || (l()==h())) return false; return true; } //-------------------------------------------------------------- void PxdName::update(const PxdName& NewPxd) // Replace elements by any non-blank elements in NewPxd { if (NewPxd.pname() != """") { pname_ = NewPxd.pname(); } if (NewPxd.xname() != """") { xname_ = NewPxd.xname(); } if (NewPxd.dname() != """") { dname_ = NewPxd.dname(); } } //-------------------------------------------------------------- std::string PxdName::formatPrint() const { int lm = Max(pname_.size(), xname_.size()); lm = Max(lm, int(dname_.size())); lm++; int lpn = Max(lm, int(pname_.size()+1)); int lxn = Max(lm, int(xname_.size()+1)); int ldn = Max(lm, int(dname_.size()+1)); return FormatOutput::logTab(2, StringUtil::PadString(""Project: ""+pname_, lpn)+ StringUtil::PadString("" Crystal: ""+xname_, lxn)+ StringUtil::PadString("" Dataset: ""+dname_, ldn)); } //-------------------------------------------------------------- std::string PxdName::format() const { return pname_ + ""/"" + xname_ + ""/"" + dname_; } //-------------------------------------------------------------- Xdataset::Xdataset(const PxdName& pxdname, const Scell& cell, const float& wavel, const int& setid) : pxdname_(pxdname), setid_(setid), cell_(cell), wavel_(wavel) { allcells_.AddCell(cell); allwavel_.push_back(wavel); } //-------------------------------------------------------------- void Xdataset::add_batch(const int& batch_num) { batches.push_back(batch_num); } //-------------------------------------------------------------- void Xdataset::AddRunIndex(const int& RunIndex) { run_index_list.push_back(RunIndex); } //-------------------------------------------------------------- void Xdataset::AddCellWavelength(const Scell& newcell, const float& wavel) //! add in another cell and wavelength { allcells_.AddCell(newcell); allwavel_.push_back(wavel); AverageCellWavelength(); } //-------------------------------------------------------------- std::string Xdataset::formatPrint() const { std::string s = FormatOutput::logTab(1,""\\n * Dataset information *\\n""); s += pxdname_.formatPrint(); s += FormatOutput::logTabPrintf(1,""Unit cell: ""); s += cell_.formatPrint(); s += FormatOutput::logTabPrintf(1, ""Wavelength: %8.5f\\n"", wavel_); s += FormatOutput::logTabPrintf(1,""Runs: ""); for (size_t i=0;i cells = allcells_.Cells(); // cells // differences from mean of others std::vector dv = allcells_.Deviations(); for (int i=0;i::cross(e1, e2).unit(); } spindle = e1; // phi/omega scan scala::Rotation D; if (batchinfo.ngonax == 1) { // Single axis, e1 D = scala::Rotation(e1, dtm[0]); } else { if (batchinfo.jsaxs == 1) { // Omega scan D = scala::Rotation(scala::Euler_explicit (e1, clipper::Util::d2rad(dtm[0]), e2, clipper::Util::d2rad(dtm[1]), e3, clipper::Util::d2rad(dtm[2]))); phiscan = false; } else if (batchinfo.jsaxs == 3) { // Phi scan // datum [D] = [Phi0] D = scala::Rotation(scala::Euler_explicit (e1, 0.0, e2, 0.0, e3, clipper::Util::d2rad(dtm[2]))); phiscan = true; spindle = e3; // phi/omega scan // E1E2 = [Omega][Chi/Kappa] E1E2 = scala::Rotation(scala::Euler_explicit (e1, clipper::Util::d2rad(dtm[0]), e2, clipper::Util::d2rad(dtm[1]), e3, 0.0)).matrix(); } } // ""Missetting"" angles [A] = [PhiXYZ][U] DMat33 A = U; if (batchinfo.misflg > 0) { DVect3 x(1.0,0.0,0.0); DVect3 y(0.0,1.0,0.0); DVect3 z(0.0,0.0,1.0); scala::Rotation PhiXYZ(scala::Euler_explicit (x, clipper::Util::d2rad(batchinfo.phixyz[0][0]), y, clipper::Util::d2rad(batchinfo.phixyz[0][1]), z, clipper::Util::d2rad(batchinfo.phixyz[0][2]))); A = PhiXYZ.matrix() * U; U = A; } A = Q * A; // transform to frame // Store [D][PhiXYZ][U] DU = D.matrix() * A; // [D][U][B] ([B] in is A^-1) DUB = DU * bcell.Bmat(); } // end if valid_Umat float phirange = batchinfo.phiend - batchinfo.phistt; valid_phi = true; if (std::abs(phirange) < tolerance) valid_phi = false; float timerange = batchinfo.time2 - batchinfo.time1; valid_time = +1; if (std::abs(timerange) < tolerance) { valid_time = 0; // Substitute phi if (valid_phi) { timerange = phirange; batchinfo.time1 = batchinfo.phistt; batchinfo.time2 = batchinfo.phiend; valid_time = -1; } } if (batchinfo.phirange > tolerance) { // phirange is explicitly in file, check phi2 modulo 360 if (std::abs(phirange - batchinfo.phirange) > tolerance) { double dif = batchinfo.phistt+batchinfo.phirange-batchinfo.phiend; if (std::abs(fmod(dif,360.0)) > tolerance) { Message::message(Message_warn( ""Inconsistent rotation information in header for batch ""+ clipper::String(batchinfo.num)+ ""\\n Phi1: ""+clipper::String(batchinfo.phistt)+ "" Phi2: ""+clipper::String(batchinfo.phiend)+ "" DelPhi: ""+clipper::String(batchinfo.phirange))); } else // Fix up phi end if off by multiple of 360 {batchinfo.phiend = batchinfo.phistt + batchinfo.phirange;} } } } // Batch constructor //-------------------------------------------------------------- void Batch::change_basis(const ReindexOp& reindex_op) // change cell and orientation matrix for change of basis { // Check for valid cell if (valid_cell) { Scell bcell(batchinfo.cell); // New cell Scell newcell = bcell.change_basis(reindex_op); for (int i=0;i<6;i++) batchinfo.cell[i] = newcell[i]; // Check for valid orientation if (valid_Umat) { // Rotate crystal orientation DMat33 U = MVutil::SetCMat33(batchinfo.umat); // U' = U * B * H(T)^-1 * B'^-1 DMat33 RU = U * bcell.Bmat() * reindex_op.transpose().inverse() * newcell.Bmat().inverse(); for (int i=0;i<3;i++) { for(int j=0;j<3;j++) { batchinfo.umat[j*3+i] = RU(i,j);}} // Update DU' = DU * U^-1 * U' DU = DU * U.inverse() * RU; // [D][U][B] DUB = DU * bcell.Bmat(); } } } //-------------------------------------------------------------- void Batch::print() const // Can't do this to ""Output"" object { CMtz::MtzPrintBatchHeader(&batchinfo); } //-------------------------------------------------------------- void Batch::SetCellConstraint(const std::vector& lbcell) { for (int i=0;i<6;i++) batchinfo.lbcell[i] = lbcell[i]; } //-------------------------------------------------------------- void Batch::SetCell(const Scell& newcell) { for (int i=0;i<6;i++) batchinfo.cell[i] = newcell[i]; valid_cell = true; bcell = newcell; } //-------------------------------------------------------------- void Batch::OffsetPhi(const float& Phioffset) // offset stored phi1, phi2 to allow to 360deg wrap-around { phioffset = Phioffset; batchinfo.phistt += phioffset; batchinfo.phiend += phioffset; } //-------------------------------------------------------------- void Batch::OffsetTime(const float& Timeoffset) // offset stored time1, time2 to allow to 360deg wrap-around // if copied from Phi { timeoffset = Timeoffset; batchinfo.time1 += timeoffset; batchinfo.time2 += timeoffset; } //-------------------------------------------------------------- void Batch::SetRunIndex(const int& RunIndex) { run_index= RunIndex; } //-------------------------------------------------------------- // offset batch number void Batch::OffsetNum(const int& Offset) { batchinfo.num += Offset; offset = Offset; // and store it } //-------------------------------------------------------------- // Orientation information: // x = [R] [D] [U] [B] h // where h = (h k l) // [B] orthogonalisation matrix from unit cell // [U] orientation matrix // Two cases for rotation: // 1) rotation is about the outer goniostat axis e1 // (a) single axis Phi around e1 // [R] = [Phi] [D] = [Phi0], often = [I] // (b) 3-axis goniostat, spindle rotation by omega around e1 // [R] = [Omega] [D] = [Chi/Kappa][Phi] // 2) 3-axis goniostat, spindle rotation by phi around e3 // [R] = [Omega][Chi/Kappa][Phi] [D] = [Phi0] // = [E1E2] [Phi] (phi varying) // // Transformation operations: // four useful reference frames // (a) reciprocal lattice indices h // (b) camera frame (Ewald sphere frame) // s(r) = x = [R][D][U][B]h // (c) zero rotation angle frame (phi/omega = 0) // s(r0) = [D][U][B]h = [R]^-1 s(r) // (d) polar orthogonalised crystal frame to put a defined // reciprocal lattice axis ~ along z // s(pole) = [P][B]h // = [P][DU]^-1 s(r0) // [P] is a cyclic permutation matrix (so [P]^-1 = [P]transpose) // // NB in the following FtoF rountines, all vectors (apart from hkl) are // in dimensionless reciprocal lattice units (ir s(r), s(r0), s(pole) //-------------------------------------------------------------- DVect3 Batch::HtoSr(const Hkl& hkl, const float& phi) const // reciprocal lattice index h -> s(r) = [R][D][U][B]h camera frame { DVect3 hl; // lambda * hkl for (int i=0;i<3;++i) { hl[i] = batchinfo.alambd * hkl[i]; } // spindle rotation [Phi] // for single axis or omega scan [R] = [Phi] DMat33 R = scala::Rotation (spindle, clipper::Util::d2rad(phi)).matrix(); if (phiscan) { // 3-axis Phi scan, [R] = [E1E2][Phi] R = E1E2 * R; } return R * DUB * hl; } //-------------------------------------------------------------- DVect3 Batch::HtoSr0(const Hkl& hkl) const // reciprocal lattice index h -> s(r0) = [D][U][B]h zero rotation angle frame { DVect3 hl; // lambda * hkl for (int i=0;i<3;++i) { hl[i] = batchinfo.alambd * hkl[i]; } return DUB * hl; } //-------------------------------------------------------------- DVect3 Batch::SrtoSr0(const DVect3& sr, const float& phi) const // camera frame s(r) -> s(r0) = [R]^-1 s(r) zero rotation angle frame { // spindle rotation [Phi] // for single axis or omega scan [R] = [Phi] DMat33 R = scala::Rotation (spindle, clipper::Util::d2rad(phi)).matrix(); if (phiscan) { // 3-axis Phi scan, [R] = [E1E2][Phi] R = E1E2 * R; } return R.transpose() * sr; } //-------------------------------------------------------------- DVect3 Batch::Sr0toP(const DVect3& sr0) const // zero rotation angle frame s(r0) -> polar orthogonalised crystal frame // s(pole) = [P] [DU]^-1 s(r0) { return PDUinv * sr0; } //-------------------------------------------------------------- void Batch::SetPole(const int& Pole) { pole = Pole; if (pole < 0) { // Unspecified ABSORPTION pole, choose closest reciprocal axis // numbered 1,2,3 pole = SmallestComponent(SpindleToPrincipleAxes(DUB)) + 1; } // Generate permutation matrix P for this batch to put pole along z // polar orthogonal crystal frame x(polar) = [P] [B] h if (pole != 0) { DMat33 P(0,0,0,0,0,0,0,0,0); int l = pole-1; // pole = 1,2,3 P(2, l) = 1.0; // z axis P(0,++l%3) = 1.0; // x axis P(1,++l%3) = 1.0; // y axis PDUinv = (DU * P).inverse(); } } //-------------------------------------------------------------- //! Return range of detector pixel coordinates std::vector > Batch::DetectorCoordinateRange() const { std::vector lims(2); std::vector > xylims(2); lims[0] = batchinfo.detlm[0][0][0]; // XDET lims[1] = batchinfo.detlm[0][0][1]; xylims[0] = lims; lims[0] = batchinfo.detlm[0][1][0]; // YDET lims[1] = batchinfo.detlm[0][1][1]; xylims[1] = lims; return xylims; } //-------------------------------------------------------------- std::string Batch::SpindleToPrincipleAxis() const { return FormatSpindleToPrincipleAxes(DUB); } //-------------------------------------------------------------- std::string Batch::format() const // formatted version // (most of this copied from cmtzlib.c CMtz::MtzPrintBatchHeader) { std::string s = ""Orientation data for batch ""+clipper::String(num())+"" ""; if (batchinfo.ldtype == 1) { s += ""oscillation (2D) data\\n\\n""; } else if (batchinfo.ldtype == 2) { s += ""area detector (3D) data\\n\\n""; } else if (batchinfo.ldtype == 3) { s += ""Laue data\\n\\n""; } else { s += ""unknown data type\\n\\n""; } s += "" Crystal number ...................""+clipper::String(batchinfo.ncryst)+ ""\\n Associated dataset ID ............""+clipper::String(batchinfo.nbsetid)+ ""\\n Cell dimensions ..................""+FormatCell(cell())+""\\n""; s += "" Cell fix flags ...................""; for (int i=0;i<6;++i) { s += clipper::String(batchinfo.lbcell[i],7); } std::string s2; if (!batchinfo.misflg) { s += ""\\n Orientation matrix U .............""; s2 = ""\\n (including setting angles) ""; } else { s += ""\\n Standard orientation matrix [U] ..""; s2 = ""\\n ""; } for (int i=0;i<3;++i) {for (int j=0;j<3;++j) { s += FormatOutput::logTabPrintf(0,""%10.4f"",U(i,j)); } if (i<2) {s += s2;} s2 = ""\\n ""; } s += ""\\n""; if (batchinfo.misflg == 1) { s += FormatOutput::logTabPrintf(0,"" %s %6.2f %6.2f %6.2f\\n"", ""Missetting angles PhiX PhiY PhiZ.."", batchinfo.phixyz[0][0],batchinfo.phixyz[0][1],batchinfo.phixyz[0][2]); } else if (batchinfo.misflg > 1) { s += FormatOutput::logTabPrintf(0,"" %s %6.2f %6.2f %6.2f %6.2f %6.2f %6.2f\\n"", ""Missetting angles PhiX PhiY PhiZ.."", batchinfo.phixyz[0][0],batchinfo.phixyz[0][1],batchinfo.phixyz[0][2], batchinfo.phixyz[1][0],batchinfo.phixyz[1][1],batchinfo.phixyz[1][2]); } std::string axis(""none""); if (batchinfo.jumpax == 1) axis = ""a*""; if (batchinfo.jumpax == 2) axis = ""b*""; if (batchinfo.jumpax == 3) axis = ""c*""; s += FormatOutput::logTabPrintf(0,"" %s%s%s %s\\n"", ""Reciprocal axis nearest "",batchinfo.gonlab[0],"".."",axis.c_str()); if (!batchinfo.lcrflg) { s += FormatOutput::logTabPrintf(0,"" %s %6.3f \\n"", ""Mosaicity ........................"",batchinfo.crydat[0]); } else { s += FormatOutput::logTabPrintf(0,"" %s %6.3f %6.3f \\n"", ""Mosaicity (horizontal, vertical).."",batchinfo.crydat[0],batchinfo.crydat[1]); } s += FormatOutput::logTabPrintf(0,"" Datum goniostat angles (degrees)..""); for (int i = 0; i < batchinfo.ngonax; ++i) s += FormatOutput::logTabPrintf(0,"" %8.3f"",batchinfo.datum[i]); s += FormatOutput::logTabPrintf(0,""\\n""); if (batchinfo.jsaxs > 0 && batchinfo.jsaxs <= batchinfo.ngonax) s += FormatOutput::logTabPrintf(0,"" %s %s \\n"", ""Scan axis ........................"",batchinfo.gonlab[batchinfo.jsaxs-1]); s += FormatOutput::logTabPrintf(0,"" %s %8.3f %8.3f \\n %s %8.3f \\n %s %8.2f %8.2f \\n"", ""Start & stop Phi angles (degrees)."", batchinfo.phistt,batchinfo.phiend, ""Range of Phi angles (degrees)....."",batchinfo.phirange, ""Start & stop time (minutes)......."",batchinfo.time1,batchinfo.time2); if (batchinfo.nbscal == 4) { s += FormatOutput::logTabPrintf(0,"" %s %9.4f %9.4f \\n %s %9.4f %9.4f \\n"", "" Batch scale & SD ................."",batchinfo.bscale,batchinfo.sdbscale, "" Batch B-factor & SD .............."",batchinfo.bbfac,batchinfo.sdbfac); } s += FormatOutput::logTabPrintf(0,"" %s \\n %s %7d \\n %s %s %s %9.4f %9.4f %9.4f \\n %s %s %s %9.4f %9.4f %9.4f \\n %s %s %s %9.4f %9.4f %9.4f \\n"", "" Crystal goniostat information :-"", "" Number of goniostat axes.........."",batchinfo.ngonax, "" Goniostat vectors....."", batchinfo.gonlab[0],""...."",batchinfo.e1[0],batchinfo.e1[1],batchinfo.e1[2], "" ....."",batchinfo.gonlab[1],""...."",batchinfo.e2[0],batchinfo.e2[1],batchinfo.e2[2], "" ....."",batchinfo.gonlab[2],""...."",batchinfo.e3[0],batchinfo.e3[1],batchinfo.e3[2]); s += FormatOutput::logTabPrintf(0, "" %s \\n %s%9.4f %9.4f %9.4f \\n %s%9.4f %9.4f %9.4f \\n"", "" Beam information :-"", "" Idealized X-ray beam vector......."", batchinfo.source[0],batchinfo.source[1],batchinfo.source[2], "" X-ray beam vector with tilts......"", batchinfo.so[0],batchinfo.so[1],batchinfo.so[2]); if (batchinfo.lbmflg == 0) { s += FormatOutput::logTabPrintf(0,"" %s %9.5f %9.5f \\n"", "" Wavelength and dispersion ........"",batchinfo.alambd,batchinfo.delamb); } else if (batchinfo.lbmflg == 1) { s += FormatOutput::logTabPrintf(0,"" %s %9.5f %9.5f %9.5f \\n %s %7.3f %7.3f \\n"", "" Wavelength and dispersion ........"",batchinfo.alambd,batchinfo.delamb,batchinfo.delcor, "" Divergence ......................."",batchinfo.divhd,batchinfo.divvd); } s += FormatOutput::logTabPrintf(0,"" Detector information :-\\n Number of detectors...............%7d \\n"",batchinfo.ndet); s += FormatOutput::logTabPrintf(0,"" %s%9.3f\\n%s%9.3f\\n%s%7.1f%7.1f%7.1f%7.1f\\n"", "" Crystal to Detector distance (mm)."",batchinfo.dx[0], "" Detector swing angle.............."",batchinfo.theta[0], "" Pixel limits on detector.........."", batchinfo.detlm[0][0][0],batchinfo.detlm[0][0][1],batchinfo.detlm[0][1][0],batchinfo.detlm[0][1][1]); return s; } //-------------------------------------------------------------- // For sorting on batch number bool operator < (const Batch& a,const Batch& b) { return (a.batchinfo.num < b.batchinfo.num); } //-------------------------------------------------------------- bool in_datasets(const int& setid, const std::vector& datasets, int& idataset) // Return true if dataset setid is in datasets list // & return dataset index idataset (-1 if not) // If setid == 0, assign to first dataset { if (setid <= 0) { idataset = 0; return true; } for (size_t k = 0; k < datasets.size(); ++k) { if (setid == datasets[k].setid()) { idataset = k; return true; } } idataset = -1; return false; } //-------------------------------------------------------------- BatchSelection::BatchSelection() {clear();} //-------------------------------------------------------------- void BatchSelection::clear() { batchlist.clear(); fileseries_list.clear(); batchranges.clear(); fileseries_range.clear(); flaglist.clear(); } //-------------------------------------------------------------- void BatchSelection::AddBatch(const int& batch, const int& fileSeriesList) // Add in one batch to selection { batchlist.push_back(batch); fileseries_list.push_back(fileSeriesList); } //-------------------------------------------------------------- void BatchSelection::AddRange(const int& batch1, const int& batch2, const int& fileSeriesList, const int& flag) // Add in batch range to selection { batchranges.push_back(IntRange(batch1,batch2)); fileseries_range.push_back(fileSeriesList); flaglist.push_back(flag); } //-------------------------------------------------------------- bool BatchSelection::InSelection(const int& batch, const int& fileSeriesTest) const { return (FindInSelection(batch, fileSeriesTest) >= 0); } //-------------------------------------------------------------- int BatchSelection::FindInSelection(const int& batch, const int& fileSeriesTest) const // Return index in list if in selection, for given file series, else -1 // Two possibilities for selection: // 1) Specified selection on final numbering, ie from sole file or // after renumbering of 2nd or subsequent file, fileSeriesList == 0, // only test if fileSeriesTest == 0 // // 2) Specified selection on original file numbering from 2nd or // subsequent file, fileSeriesList > 0, only test if // fileSeriesTest > 0 { for (size_t i=0;i 0 && fileseries_list[i] == fileSeriesTest) { // original numbering if (batch == batchlist[i]) return int(i); } } for (size_t i=0;i 0 && fileseries_range[i] == fileSeriesTest) { // original numbering if (batchranges[i].InRange(batch)) return int(i); } } // not in range or not tested return -1; } //-------------------------------------------------------------- //! return numerical flag for batch, = -1 if not in list int BatchSelection::FlagNumber(const int& batch) { int i; if (batchlist.size() > 0) { Message::message(Message_fatal (""BatchSelection::FlagNumber not valid for batch list, only for batch range"")); } if ((i = FindInSelection(batch, 0)) >= 0) { return flaglist[i]; } else { return -1; } } //-------------------------------------------------------------- //! return list of unique numerical flags specified std::vector BatchSelection::UniqueFlags() const { std::vector uniqueflags; for (size_t i=0;i 0) { if (std::find(uniqueflags.begin(), uniqueflags.end(), flaglist[i]) != uniqueflags.end()) {continue;} // skip if already in unique list } uniqueflags.push_back(flaglist[i]); } return uniqueflags; } //-------------------------------------------------------------- //! return list of batch ranges for specified flag, all ranges if flag < 0 std::vector BatchSelection::BatchRanges(const int& flag) { ASSERT (batchranges.size() == flaglist.size()); if (flag < 0) return batchranges; std::vector bsel; for (size_t i=0;i NumFileSeries) { Message::message(Message_fatal (""Batch selection specifies file[series] ""+ clipper::String(fileseries_list[i],3)+ "" which does not exist"")); } } for (size_t i=0;i NumFileSeries) { Message::message(Message_fatal (""Batch selection specifies file[series] ""+ clipper::String(fileseries_range[i],3)+ "" which does not exist"")); } } } //-------------------------------------------------------------- } // end namespace scala // end hkl_datatypes.cpp ",16191,True,2687.6829293548562,median "*&---------------------------------------------------------------------* *& Report ZANGRY_BIRDS *& Just for fun *&---------------------------------------------------------------------* *& *& *&---------------------------------------------------------------------* REPORT zangry_birds. DATA: lo_excel TYPE REF TO zcl_excel, lo_excel_writer TYPE REF TO zif_excel_writer, lo_worksheet TYPE REF TO zcl_excel_worksheet, lo_border_light TYPE REF TO zcl_excel_style_border, lo_style_color0 TYPE REF TO zcl_excel_style, lo_style_color1 TYPE REF TO zcl_excel_style, lo_style_color2 TYPE REF TO zcl_excel_style, lo_style_color3 TYPE REF TO zcl_excel_style, lo_style_color4 TYPE REF TO zcl_excel_style, lo_style_color5 TYPE REF TO zcl_excel_style, lo_style_color6 TYPE REF TO zcl_excel_style, lo_style_color7 TYPE REF TO zcl_excel_style, lo_style_credit TYPE REF TO zcl_excel_style, lo_style_link TYPE REF TO zcl_excel_style, lo_column_dimension TYPE REF TO zcl_excel_worksheet_columndime, lo_row_dimension TYPE REF TO zcl_excel_worksheet_rowdimensi, lo_hyperlink TYPE REF TO zcl_excel_hyperlink. DATA: lv_style_color0_guid TYPE zexcel_cell_style, lv_style_color1_guid TYPE zexcel_cell_style, lv_style_color2_guid TYPE zexcel_cell_style, lv_style_color3_guid TYPE zexcel_cell_style, lv_style_color4_guid TYPE zexcel_cell_style, lv_style_color5_guid TYPE zexcel_cell_style, lv_style_color6_guid TYPE zexcel_cell_style, lv_style_color7_guid TYPE zexcel_cell_style, lv_style_credit_guid TYPE zexcel_cell_style, lv_style_link_guid TYPE zexcel_cell_style, lv_style TYPE zexcel_cell_style. DATA: lv_col_str TYPE zexcel_cell_column_alpha, lv_row TYPE i, lv_col TYPE i, lt_mapper TYPE TABLE OF zexcel_cell_style, ls_mapper TYPE zexcel_cell_style. DATA: lv_file TYPE xstring, lv_bytecount TYPE i, lt_file_tab TYPE solix_tab. DATA: lv_full_path TYPE string, lv_workdir TYPE string, lv_file_separator TYPE c. CONSTANTS: lv_default_file_name TYPE string VALUE 'angry_birds.xlsx'. PARAMETERS: p_path TYPE zexcel_export_dir. AT SELECTION-SCREEN ON VALUE-REQUEST FOR p_path. lv_workdir = p_path. cl_gui_frontend_services=>directory_browse( EXPORTING initial_folder = lv_workdir CHANGING selected_folder = lv_workdir ). p_path = lv_workdir. INITIALIZATION. cl_gui_frontend_services=>get_sapgui_workdir( CHANGING sapworkdir = lv_workdir ). cl_gui_cfw=>flush( ). p_path = lv_workdir. START-OF-SELECTION. IF p_path IS INITIAL. p_path = lv_workdir. ENDIF. cl_gui_frontend_services=>get_file_separator( CHANGING file_separator = lv_file_separator ). CONCATENATE p_path lv_file_separator lv_default_file_name INTO lv_full_path. "" Creates active sheet CREATE OBJECT lo_excel. CREATE OBJECT lo_border_light. lo_border_light->border_color-rgb = zcl_excel_style_color=>c_white. lo_border_light->border_style = zcl_excel_style_border=>c_border_thin. "" Create color white lo_style_color0 = lo_excel->add_new_style( ). lo_style_color0->fill->filltype = zcl_excel_style_fill=>c_fill_solid. lo_style_color0->fill->fgcolor-rgb = 'FFFFFFFF'. lo_style_color0->borders->allborders = lo_border_light. lv_style_color0_guid = lo_style_color0->get_guid( ). "" Create color black lo_style_color1 = lo_excel->add_new_style( ). lo_style_color1->fill->filltype = zcl_excel_style_fill=>c_fill_solid. lo_style_color1->fill->fgcolor-rgb = 'FF252525'. lo_style_color1->borders->allborders = lo_border_light. lv_style_color1_guid = lo_style_color1->get_guid( ). "" Create color dark green lo_style_color2 = lo_excel->add_new_style( ). lo_style_color2->fill->filltype = zcl_excel_style_fill=>c_fill_solid. lo_style_color2->fill->fgcolor-rgb = 'FF75913A'. lo_style_color2->borders->allborders = lo_border_light. lv_style_color2_guid = lo_style_color2->get_guid( ). "" Create color light green lo_style_color3 = lo_excel->add_new_style( ). lo_style_color3->fill->filltype = zcl_excel_style_fill=>c_fill_solid. lo_style_color3->fill->fgcolor-rgb = 'FF9DFB73'. lo_style_color3->borders->allborders = lo_border_light. lv_style_color3_guid = lo_style_color3->get_guid( ). "" Create color green lo_style_color4 = lo_excel->add_new_style( ). lo_style_color4->fill->filltype = zcl_excel_style_fill=>c_fill_solid. lo_style_color4->fill->fgcolor-rgb = 'FF92CF56'. lo_style_color4->borders->allborders = lo_border_light. lv_style_color4_guid = lo_style_color4->get_guid( ). "" Create color 2dark green lo_style_color5 = lo_excel->add_new_style( ). lo_style_color5->fill->filltype = zcl_excel_style_fill=>c_fill_solid. lo_style_color5->fill->fgcolor-rgb = 'FF506228'. lo_style_color5->borders->allborders = lo_border_light. lv_style_color5_guid = lo_style_color5->get_guid( ). "" Create color yellow lo_style_color6 = lo_excel->add_new_style( ). lo_style_color6->fill->filltype = zcl_excel_style_fill=>c_fill_solid. lo_style_color6->fill->fgcolor-rgb = 'FFC3E224'. lo_style_color6->borders->allborders = lo_border_light. lv_style_color6_guid = lo_style_color6->get_guid( ). "" Create color yellow lo_style_color7 = lo_excel->add_new_style( ). lo_style_color7->fill->filltype = zcl_excel_style_fill=>c_fill_solid. lo_style_color7->fill->fgcolor-rgb = 'FFB3C14F'. lo_style_color7->borders->allborders = lo_border_light. lv_style_color7_guid = lo_style_color7->get_guid( ). "" Credits lo_style_credit = lo_excel->add_new_style( ). lo_style_credit->alignment->horizontal = zcl_excel_style_alignment=>c_horizontal_center. lo_style_credit->alignment->vertical = zcl_excel_style_alignment=>c_vertical_center. lo_style_credit->font->size = 20. lv_style_credit_guid = lo_style_credit->get_guid( ). "" Link lo_style_link = lo_excel->add_new_style( ). lo_style_link->alignment->horizontal = zcl_excel_style_alignment=>c_horizontal_center. lo_style_link->alignment->vertical = zcl_excel_style_alignment=>c_vertical_center. * lo_style_link->font->size = 20. lv_style_link_guid = lo_style_link->get_guid( ). "" Create image map "" line 2 DO 30 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. APPEND INITIAL LINE TO lt_mapper. "" escape "" line 3 DO 28 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 5 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. APPEND INITIAL LINE TO lt_mapper. "" escape "" line 4 DO 27 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 4 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. APPEND INITIAL LINE TO lt_mapper. "" escape "" line 5 DO 9 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 15 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 6 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. APPEND INITIAL LINE TO lt_mapper. "" escape "" line 6 DO 7 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 6 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 13 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 4 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. APPEND INITIAL LINE TO lt_mapper. "" escape "" line 7 DO 6 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 5 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 11 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 5 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. APPEND INITIAL LINE TO lt_mapper. "" escape "" line 8 DO 5 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 3 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 9 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 6 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. APPEND INITIAL LINE TO lt_mapper. "" escape "" line 9 DO 5 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 3 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 9 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 4 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. APPEND INITIAL LINE TO lt_mapper. "" escape "" line 10 DO 4 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 6 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 9 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 4 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. APPEND INITIAL LINE TO lt_mapper. "" escape "" line 11 DO 4 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 7 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 9 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 4 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. APPEND INITIAL LINE TO lt_mapper. "" escape "" line 12 DO 4 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 4 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 4 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 4 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 3 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. APPEND INITIAL LINE TO lt_mapper. "" escape "" line 13 DO 5 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 4 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 3 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 3 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 8 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 3 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 3 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. APPEND INITIAL LINE TO lt_mapper. "" escape "" line 14 DO 5 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 4 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 3 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 12 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 3 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. APPEND INITIAL LINE TO lt_mapper. "" escape "" line 15 DO 6 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 3 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 3 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 8 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 4 TIMES. APPEND lv_style_color4_guid TO lt_mapper. ENDDO. DO 3 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. APPEND INITIAL LINE TO lt_mapper. "" escape "" line 16 DO 7 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 7 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color4_guid TO lt_mapper. ENDDO. DO 5 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 3 TIMES. APPEND lv_style_color4_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 3 TIMES. APPEND lv_style_color4_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. APPEND INITIAL LINE TO lt_mapper. "" escape "" line 17 DO 8 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 6 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color4_guid TO lt_mapper. ENDDO. DO 13 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color4_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. APPEND INITIAL LINE TO lt_mapper. "" escape "" line 18 DO 6 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 23 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color4_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 3 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. APPEND INITIAL LINE TO lt_mapper. "" escape "" line 19 DO 5 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 3 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 27 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. APPEND INITIAL LINE TO lt_mapper. "" escape "" line 20 DO 5 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 23 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 3 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 3 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. APPEND INITIAL LINE TO lt_mapper. "" escape "" line 21 DO 4 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 19 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. APPEND INITIAL LINE TO lt_mapper. "" escape "" line 22 DO 4 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 4 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 17 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 3 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 3 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. APPEND INITIAL LINE TO lt_mapper. "" escape "" line 23 DO 4 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 17 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 8 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. APPEND INITIAL LINE TO lt_mapper. "" escape "" line 24 DO 4 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color4_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color5_guid TO lt_mapper. ENDDO. DO 10 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 3 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 9 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 3 TIMES. APPEND lv_style_color5_guid TO lt_mapper. ENDDO. DO 3 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. APPEND INITIAL LINE TO lt_mapper. "" escape "" line 25 DO 3 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color4_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 3 TIMES. APPEND lv_style_color5_guid TO lt_mapper. ENDDO. DO 6 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 8 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 6 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color5_guid TO lt_mapper. ENDDO. DO 3 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color5_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. APPEND INITIAL LINE TO lt_mapper. "" escape "" line 26 DO 3 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color4_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color5_guid TO lt_mapper. ENDDO. DO 3 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color5_guid TO lt_mapper. ENDDO. DO 4 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 4 TIMES. APPEND lv_style_color7_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color6_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color7_guid TO lt_mapper. ENDDO. DO 3 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 3 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color5_guid TO lt_mapper. ENDDO. DO 4 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color5_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. APPEND INITIAL LINE TO lt_mapper. "" escape "" line 27 DO 3 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color4_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color5_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color5_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 4 TIMES. APPEND lv_style_color7_guid TO lt_mapper. ENDDO. DO 4 TIMES. APPEND lv_style_color6_guid TO lt_mapper. ENDDO. DO 3 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color5_guid TO lt_mapper. ENDDO. DO 3 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color5_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. APPEND INITIAL LINE TO lt_mapper. "" escape "" line 28 DO 3 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color4_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color5_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color5_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 3 TIMES. APPEND lv_style_color7_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color5_guid TO lt_mapper. ENDDO. DO 3 TIMES. APPEND lv_style_color7_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color5_guid TO lt_mapper. ENDDO. DO 3 TIMES. APPEND lv_style_color6_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color7_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color5_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color5_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. APPEND INITIAL LINE TO lt_mapper. "" escape "" line 29 DO 3 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color4_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color5_guid TO lt_mapper. ENDDO. DO 3 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color5_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 3 TIMES. APPEND lv_style_color7_guid TO lt_mapper. ENDDO. DO 3 TIMES. APPEND lv_style_color5_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color7_guid TO lt_mapper. ENDDO. DO 3 TIMES. APPEND lv_style_color5_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color7_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color5_guid TO lt_mapper. ENDDO. DO 5 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color5_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. APPEND INITIAL LINE TO lt_mapper. "" escape "" line 30 DO 3 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color4_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color5_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color5_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 4 TIMES. APPEND lv_style_color7_guid TO lt_mapper. ENDDO. DO 3 TIMES. APPEND lv_style_color5_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color7_guid TO lt_mapper. ENDDO. DO 3 TIMES. APPEND lv_style_color5_guid TO lt_mapper. ENDDO. DO 3 TIMES. APPEND lv_style_color7_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color5_guid TO lt_mapper. ENDDO. DO 4 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color5_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. APPEND INITIAL LINE TO lt_mapper. "" escape "" line 31 DO 3 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color4_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 3 TIMES. APPEND lv_style_color5_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 4 TIMES. APPEND lv_style_color7_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color5_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color7_guid TO lt_mapper. ENDDO. DO 3 TIMES. APPEND lv_style_color5_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color7_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color5_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color5_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 3 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. APPEND INITIAL LINE TO lt_mapper. "" escape "" line 32 DO 3 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 8 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 9 TIMES. APPEND lv_style_color7_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 4 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 3 TIMES. APPEND lv_style_color5_guid TO lt_mapper. ENDDO. DO 3 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 3 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. APPEND INITIAL LINE TO lt_mapper. "" escape "" line 33 DO 3 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 3 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 9 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 3 TIMES. APPEND lv_style_color7_guid TO lt_mapper. ENDDO. DO 3 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color7_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 9 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. APPEND INITIAL LINE TO lt_mapper. "" escape "" line 34 DO 3 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 3 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 9 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 9 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 10 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. APPEND INITIAL LINE TO lt_mapper. "" escape "" line 35 DO 4 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 9 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 6 TIMES. APPEND lv_style_color7_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 11 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. APPEND INITIAL LINE TO lt_mapper. "" escape "" line 36 DO 4 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 10 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 3 TIMES. APPEND lv_style_color7_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 11 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. APPEND INITIAL LINE TO lt_mapper. "" escape "" line 37 DO 5 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 10 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color7_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 11 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 3 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. APPEND INITIAL LINE TO lt_mapper. "" escape "" line 38 DO 6 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 10 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 3 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 11 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 3 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. APPEND INITIAL LINE TO lt_mapper. "" escape "" line 39 DO 7 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 3 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 22 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 1 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 3 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. APPEND INITIAL LINE TO lt_mapper. "" escape "" line 40 DO 7 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 3 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 4 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 17 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 3 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 3 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. APPEND INITIAL LINE TO lt_mapper. "" escape "" line 41 DO 8 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 3 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 4 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 15 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 4 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. APPEND INITIAL LINE TO lt_mapper. "" escape "" line 42 DO 9 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 5 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 6 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 9 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 2 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 4 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. APPEND INITIAL LINE TO lt_mapper. "" escape "" line 43 DO 11 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 6 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 4 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 5 TIMES. APPEND lv_style_color3_guid TO lt_mapper. ENDDO. DO 7 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. APPEND INITIAL LINE TO lt_mapper. "" escape "" line 44 DO 13 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 6 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. DO 4 TIMES. APPEND lv_style_color2_guid TO lt_mapper. ENDDO. DO 8 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. APPEND INITIAL LINE TO lt_mapper. "" escape "" line 45 DO 16 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 13 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. APPEND INITIAL LINE TO lt_mapper. "" escape "" line 46 DO 18 TIMES. APPEND lv_style_color0_guid TO lt_mapper. ENDDO. DO 8 TIMES. APPEND lv_style_color1_guid TO lt_mapper. ENDDO. APPEND INITIAL LINE TO lt_mapper. "" escape "" Get active sheet lo_worksheet = lo_excel->get_active_worksheet( ). lo_worksheet->set_title( ip_title = 'Angry Birds' ). lv_row = 1. lv_col = 1. LOOP AT lt_mapper INTO ls_mapper. lv_col_str = zcl_excel_common=>convert_column2alpha( lv_col ). IF ls_mapper IS INITIAL. lo_row_dimension = lo_worksheet->get_row_dimension( ip_row = lv_row ). lo_row_dimension->set_row_height( ip_row_height = 8 ). lv_col = 1. lv_row = lv_row + 1. CONTINUE. ENDIF. lo_worksheet->set_cell( ip_column = lv_col_str ip_row = lv_row ip_value = space ip_style = ls_mapper ). lv_col = lv_col + 1. lo_column_dimension = lo_worksheet->get_column_dimension( ip_column = lv_col_str ). lo_column_dimension->set_width( ip_width = 2 ). ENDLOOP. lo_worksheet->set_show_gridlines( i_show_gridlines = abap_false ). lo_worksheet->set_cell( ip_column = 'AP' ip_row = 15 ip_value = 'Created with abap2xlsx' ip_style = lv_style_credit_guid ). lo_hyperlink = zcl_excel_hyperlink=>create_external_link( iv_url = 'http://www.abap2xlsx.org' ). lo_worksheet->set_cell( ip_column = 'AP' ip_row = 24 ip_value = 'http://www.abap2xlsx.org' ip_style = lv_style_link_guid ip_hyperlink = lo_hyperlink ). lo_column_dimension = lo_worksheet->get_column_dimension( ip_column = 'AP' ). lo_column_dimension->set_auto_size( ip_auto_size = abap_true ). lo_worksheet->set_merge( ip_row = 15 ip_column_start = 'AP' ip_row_to = 22 ip_column_end = 'AR' ). lo_worksheet->set_merge( ip_row = 24 ip_column_start = 'AP' ip_row_to = 26 ip_column_end = 'AR' ). CREATE OBJECT lo_excel_writer TYPE zcl_excel_writer_2007. lv_file = lo_excel_writer->write_file( lo_excel ). "" Convert to binary CALL FUNCTION 'SCMS_XSTRING_TO_BINARY' EXPORTING buffer = lv_file IMPORTING output_length = lv_bytecount TABLES binary_tab = lt_file_tab. * "" This method is only available on AS ABAP > 6.40 * lt_file_tab = cl_bcs_convert=>xstring_to_solix( iv_xstring = lv_file ). * lv_bytecount = xstrlen( lv_file ). "" Save the file cl_gui_frontend_services=>gui_download( EXPORTING bin_filesize = lv_bytecount filename = lv_full_path filetype = 'BIN' CHANGING data_tab = lt_file_tab ). ",13117,True,4588.197709901321,median "// // basic_socket.hpp // ~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef BOOST_ASIO_BASIC_SOCKET_HPP #define BOOST_ASIO_BASIC_SOCKET_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include #include #include #include #include #include #include #include #include #include #include #include #if defined(BOOST_ASIO_WINDOWS_RUNTIME) # include #elif defined(BOOST_ASIO_HAS_IOCP) # include #else # include #endif #if defined(BOOST_ASIO_HAS_MOVE) # include #endif // defined(BOOST_ASIO_HAS_MOVE) #include namespace boost { namespace asio { #if !defined(BOOST_ASIO_BASIC_SOCKET_FWD_DECL) #define BOOST_ASIO_BASIC_SOCKET_FWD_DECL // Forward declaration with defaulted arguments. template class basic_socket; #endif // !defined(BOOST_ASIO_BASIC_SOCKET_FWD_DECL) /// Provides socket functionality. /** * The basic_socket class template provides functionality that is common to both * stream-oriented and datagram-oriented sockets. * * @par Thread Safety * @e Distinct @e objects: Safe.@n * @e Shared @e objects: Unsafe. */ template class basic_socket : public socket_base { public: /// The type of the executor associated with the object. typedef Executor executor_type; /// Rebinds the socket type to another executor. template struct rebind_executor { /// The socket type when rebound to the specified executor. typedef basic_socket other; }; /// The native representation of a socket. #if defined(GENERATING_DOCUMENTATION) typedef implementation_defined native_handle_type; #elif defined(BOOST_ASIO_WINDOWS_RUNTIME) typedef typename detail::null_socket_service< Protocol>::native_handle_type native_handle_type; #elif defined(BOOST_ASIO_HAS_IOCP) typedef typename detail::win_iocp_socket_service< Protocol>::native_handle_type native_handle_type; #else typedef typename detail::reactive_socket_service< Protocol>::native_handle_type native_handle_type; #endif /// The protocol type. typedef Protocol protocol_type; /// The endpoint type. typedef typename Protocol::endpoint endpoint_type; #if !defined(BOOST_ASIO_NO_EXTENSIONS) /// A basic_socket is always the lowest layer. typedef basic_socket lowest_layer_type; #endif // !defined(BOOST_ASIO_NO_EXTENSIONS) /// Construct a basic_socket without opening it. /** * This constructor creates a socket without opening it. * * @param ex The I/O executor that the socket will use, by default, to * dispatch handlers for any asynchronous operations performed on the socket. */ explicit basic_socket(const executor_type& ex) : impl_(ex) { } /// Construct a basic_socket without opening it. /** * This constructor creates a socket without opening it. * * @param context An execution context which provides the I/O executor that * the socket will use, by default, to dispatch handlers for any asynchronous * operations performed on the socket. */ template explicit basic_socket(ExecutionContext& context, typename enable_if< is_convertible::value >::type* = 0) : impl_(context) { } /// Construct and open a basic_socket. /** * This constructor creates and opens a socket. * * @param ex The I/O executor that the socket will use, by default, to * dispatch handlers for any asynchronous operations performed on the socket. * * @param protocol An object specifying protocol parameters to be used. * * @throws boost::system::system_error Thrown on failure. */ basic_socket(const executor_type& ex, const protocol_type& protocol) : impl_(ex) { boost::system::error_code ec; impl_.get_service().open(impl_.get_implementation(), protocol, ec); boost::asio::detail::throw_error(ec, ""open""); } /// Construct and open a basic_socket. /** * This constructor creates and opens a socket. * * @param context An execution context which provides the I/O executor that * the socket will use, by default, to dispatch handlers for any asynchronous * operations performed on the socket. * * @param protocol An object specifying protocol parameters to be used. * * @throws boost::system::system_error Thrown on failure. */ template basic_socket(ExecutionContext& context, const protocol_type& protocol, typename enable_if< is_convertible::value >::type* = 0) : impl_(context) { boost::system::error_code ec; impl_.get_service().open(impl_.get_implementation(), protocol, ec); boost::asio::detail::throw_error(ec, ""open""); } /// Construct a basic_socket, opening it and binding it to the given local /// endpoint. /** * This constructor creates a socket and automatically opens it bound to the * specified endpoint on the local machine. The protocol used is the protocol * associated with the given endpoint. * * @param ex The I/O executor that the socket will use, by default, to * dispatch handlers for any asynchronous operations performed on the socket. * * @param endpoint An endpoint on the local machine to which the socket will * be bound. * * @throws boost::system::system_error Thrown on failure. */ basic_socket(const executor_type& ex, const endpoint_type& endpoint) : impl_(ex) { boost::system::error_code ec; const protocol_type protocol = endpoint.protocol(); impl_.get_service().open(impl_.get_implementation(), protocol, ec); boost::asio::detail::throw_error(ec, ""open""); impl_.get_service().bind(impl_.get_implementation(), endpoint, ec); boost::asio::detail::throw_error(ec, ""bind""); } /// Construct a basic_socket, opening it and binding it to the given local /// endpoint. /** * This constructor creates a socket and automatically opens it bound to the * specified endpoint on the local machine. The protocol used is the protocol * associated with the given endpoint. * * @param context An execution context which provides the I/O executor that * the socket will use, by default, to dispatch handlers for any asynchronous * operations performed on the socket. * * @param endpoint An endpoint on the local machine to which the socket will * be bound. * * @throws boost::system::system_error Thrown on failure. */ template basic_socket(ExecutionContext& context, const endpoint_type& endpoint, typename enable_if< is_convertible::value >::type* = 0) : impl_(context) { boost::system::error_code ec; const protocol_type protocol = endpoint.protocol(); impl_.get_service().open(impl_.get_implementation(), protocol, ec); boost::asio::detail::throw_error(ec, ""open""); impl_.get_service().bind(impl_.get_implementation(), endpoint, ec); boost::asio::detail::throw_error(ec, ""bind""); } /// Construct a basic_socket on an existing native socket. /** * This constructor creates a socket object to hold an existing native socket. * * @param ex The I/O executor that the socket will use, by default, to * dispatch handlers for any asynchronous operations performed on the socket. * * @param protocol An object specifying protocol parameters to be used. * * @param native_socket A native socket. * * @throws boost::system::system_error Thrown on failure. */ basic_socket(const executor_type& ex, const protocol_type& protocol, const native_handle_type& native_socket) : impl_(ex) { boost::system::error_code ec; impl_.get_service().assign(impl_.get_implementation(), protocol, native_socket, ec); boost::asio::detail::throw_error(ec, ""assign""); } /// Construct a basic_socket on an existing native socket. /** * This constructor creates a socket object to hold an existing native socket. * * @param context An execution context which provides the I/O executor that * the socket will use, by default, to dispatch handlers for any asynchronous * operations performed on the socket. * * @param protocol An object specifying protocol parameters to be used. * * @param native_socket A native socket. * * @throws boost::system::system_error Thrown on failure. */ template basic_socket(ExecutionContext& context, const protocol_type& protocol, const native_handle_type& native_socket, typename enable_if< is_convertible::value >::type* = 0) : impl_(context) { boost::system::error_code ec; impl_.get_service().assign(impl_.get_implementation(), protocol, native_socket, ec); boost::asio::detail::throw_error(ec, ""assign""); } #if defined(BOOST_ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) /// Move-construct a basic_socket from another. /** * This constructor moves a socket from one object to another. * * @param other The other basic_socket object from which the move will * occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_socket(const executor_type&) constructor. */ basic_socket(basic_socket&& other) BOOST_ASIO_NOEXCEPT : impl_(std::move(other.impl_)) { } /// Move-assign a basic_socket from another. /** * This assignment operator moves a socket from one object to another. * * @param other The other basic_socket object from which the move will * occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_socket(const executor_type&) constructor. */ basic_socket& operator=(basic_socket&& other) { impl_ = std::move(other.impl_); return *this; } // All sockets have access to each other's implementations. template friend class basic_socket; /// Move-construct a basic_socket from a socket of another protocol type. /** * This constructor moves a socket from one object to another. * * @param other The other basic_socket object from which the move will * occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_socket(const executor_type&) constructor. */ template basic_socket(basic_socket&& other, typename enable_if< is_convertible::value && is_convertible::value >::type* = 0) : impl_(std::move(other.impl_)) { } /// Move-assign a basic_socket from a socket of another protocol type. /** * This assignment operator moves a socket from one object to another. * * @param other The other basic_socket object from which the move will * occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_socket(const executor_type&) constructor. */ template typename enable_if< is_convertible::value && is_convertible::value, basic_socket& >::type operator=(basic_socket && other) { basic_socket tmp(std::move(other)); impl_ = std::move(tmp.impl_); return *this; } #endif // defined(BOOST_ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) /// Get the executor associated with the object. executor_type get_executor() BOOST_ASIO_NOEXCEPT { return impl_.get_executor(); } #if !defined(BOOST_ASIO_NO_EXTENSIONS) /// Get a reference to the lowest layer. /** * This function returns a reference to the lowest layer in a stack of * layers. Since a basic_socket cannot contain any further layers, it simply * returns a reference to itself. * * @return A reference to the lowest layer in the stack of layers. Ownership * is not transferred to the caller. */ lowest_layer_type& lowest_layer() { return *this; } /// Get a const reference to the lowest layer. /** * This function returns a const reference to the lowest layer in a stack of * layers. Since a basic_socket cannot contain any further layers, it simply * returns a reference to itself. * * @return A const reference to the lowest layer in the stack of layers. * Ownership is not transferred to the caller. */ const lowest_layer_type& lowest_layer() const { return *this; } #endif // !defined(BOOST_ASIO_NO_EXTENSIONS) /// Open the socket using the specified protocol. /** * This function opens the socket so that it will use the specified protocol. * * @param protocol An object specifying protocol parameters to be used. * * @throws boost::system::system_error Thrown on failure. * * @par Example * @code * boost::asio::ip::tcp::socket socket(my_context); * socket.open(boost::asio::ip::tcp::v4()); * @endcode */ void open(const protocol_type& protocol = protocol_type()) { boost::system::error_code ec; impl_.get_service().open(impl_.get_implementation(), protocol, ec); boost::asio::detail::throw_error(ec, ""open""); } /// Open the socket using the specified protocol. /** * This function opens the socket so that it will use the specified protocol. * * @param protocol An object specifying which protocol is to be used. * * @param ec Set to indicate what error occurred, if any. * * @par Example * @code * boost::asio::ip::tcp::socket socket(my_context); * boost::system::error_code ec; * socket.open(boost::asio::ip::tcp::v4(), ec); * if (ec) * { * // An error occurred. * } * @endcode */ BOOST_ASIO_SYNC_OP_VOID open(const protocol_type& protocol, boost::system::error_code& ec) { impl_.get_service().open(impl_.get_implementation(), protocol, ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Assign an existing native socket to the socket. /* * This function opens the socket to hold an existing native socket. * * @param protocol An object specifying which protocol is to be used. * * @param native_socket A native socket. * * @throws boost::system::system_error Thrown on failure. */ void assign(const protocol_type& protocol, const native_handle_type& native_socket) { boost::system::error_code ec; impl_.get_service().assign(impl_.get_implementation(), protocol, native_socket, ec); boost::asio::detail::throw_error(ec, ""assign""); } /// Assign an existing native socket to the socket. /* * This function opens the socket to hold an existing native socket. * * @param protocol An object specifying which protocol is to be used. * * @param native_socket A native socket. * * @param ec Set to indicate what error occurred, if any. */ BOOST_ASIO_SYNC_OP_VOID assign(const protocol_type& protocol, const native_handle_type& native_socket, boost::system::error_code& ec) { impl_.get_service().assign(impl_.get_implementation(), protocol, native_socket, ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Determine whether the socket is open. bool is_open() const { return impl_.get_service().is_open(impl_.get_implementation()); } /// Close the socket. /** * This function is used to close the socket. Any asynchronous send, receive * or connect operations will be cancelled immediately, and will complete * with the boost::asio::error::operation_aborted error. * * @throws boost::system::system_error Thrown on failure. Note that, even if * the function indicates an error, the underlying descriptor is closed. * * @note For portable behaviour with respect to graceful closure of a * connected socket, call shutdown() before closing the socket. */ void close() { boost::system::error_code ec; impl_.get_service().close(impl_.get_implementation(), ec); boost::asio::detail::throw_error(ec, ""close""); } /// Close the socket. /** * This function is used to close the socket. Any asynchronous send, receive * or connect operations will be cancelled immediately, and will complete * with the boost::asio::error::operation_aborted error. * * @param ec Set to indicate what error occurred, if any. Note that, even if * the function indicates an error, the underlying descriptor is closed. * * @par Example * @code * boost::asio::ip::tcp::socket socket(my_context); * ... * boost::system::error_code ec; * socket.close(ec); * if (ec) * { * // An error occurred. * } * @endcode * * @note For portable behaviour with respect to graceful closure of a * connected socket, call shutdown() before closing the socket. */ BOOST_ASIO_SYNC_OP_VOID close(boost::system::error_code& ec) { impl_.get_service().close(impl_.get_implementation(), ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Release ownership of the underlying native socket. /** * This function causes all outstanding asynchronous connect, send and receive * operations to finish immediately, and the handlers for cancelled operations * will be passed the boost::asio::error::operation_aborted error. Ownership * of the native socket is then transferred to the caller. * * @throws boost::system::system_error Thrown on failure. * * @note This function is unsupported on Windows versions prior to Windows * 8.1, and will fail with boost::asio::error::operation_not_supported on * these platforms. */ #if defined(BOOST_ASIO_MSVC) && (BOOST_ASIO_MSVC >= 1400) \\ && (!defined(_WIN32_WINNT) || _WIN32_WINNT < 0x0603) __declspec(deprecated(""This function always fails with "" ""operation_not_supported when used on Windows versions "" ""prior to Windows 8.1."")) #endif native_handle_type release() { boost::system::error_code ec; native_handle_type s = impl_.get_service().release( impl_.get_implementation(), ec); boost::asio::detail::throw_error(ec, ""release""); return s; } /// Release ownership of the underlying native socket. /** * This function causes all outstanding asynchronous connect, send and receive * operations to finish immediately, and the handlers for cancelled operations * will be passed the boost::asio::error::operation_aborted error. Ownership * of the native socket is then transferred to the caller. * * @param ec Set to indicate what error occurred, if any. * * @note This function is unsupported on Windows versions prior to Windows * 8.1, and will fail with boost::asio::error::operation_not_supported on * these platforms. */ #if defined(BOOST_ASIO_MSVC) && (BOOST_ASIO_MSVC >= 1400) \\ && (!defined(_WIN32_WINNT) || _WIN32_WINNT < 0x0603) __declspec(deprecated(""This function always fails with "" ""operation_not_supported when used on Windows versions "" ""prior to Windows 8.1."")) #endif native_handle_type release(boost::system::error_code& ec) { return impl_.get_service().release(impl_.get_implementation(), ec); } /// Get the native socket representation. /** * This function may be used to obtain the underlying representation of the * socket. This is intended to allow access to native socket functionality * that is not otherwise provided. */ native_handle_type native_handle() { return impl_.get_service().native_handle(impl_.get_implementation()); } /// Cancel all asynchronous operations associated with the socket. /** * This function causes all outstanding asynchronous connect, send and receive * operations to finish immediately, and the handlers for cancelled operations * will be passed the boost::asio::error::operation_aborted error. * * @throws boost::system::system_error Thrown on failure. * * @note Calls to cancel() will always fail with * boost::asio::error::operation_not_supported when run on Windows XP, Windows * Server 2003, and earlier versions of Windows, unless * BOOST_ASIO_ENABLE_CANCELIO is defined. However, the CancelIo function has * two issues that should be considered before enabling its use: * * @li It will only cancel asynchronous operations that were initiated in the * current thread. * * @li It can appear to complete without error, but the request to cancel the * unfinished operations may be silently ignored by the operating system. * Whether it works or not seems to depend on the drivers that are installed. * * For portable cancellation, consider using one of the following * alternatives: * * @li Disable asio's I/O completion port backend by defining * BOOST_ASIO_DISABLE_IOCP. * * @li Use the close() function to simultaneously cancel the outstanding * operations and close the socket. * * When running on Windows Vista, Windows Server 2008, and later, the * CancelIoEx function is always used. This function does not have the * problems described above. */ #if defined(BOOST_ASIO_MSVC) && (BOOST_ASIO_MSVC >= 1400) \\ && (!defined(_WIN32_WINNT) || _WIN32_WINNT < 0x0600) \\ && !defined(BOOST_ASIO_ENABLE_CANCELIO) __declspec(deprecated(""By default, this function always fails with "" ""operation_not_supported when used on Windows XP, Windows Server 2003, "" ""or earlier. Consult documentation for details."")) #endif void cancel() { boost::system::error_code ec; impl_.get_service().cancel(impl_.get_implementation(), ec); boost::asio::detail::throw_error(ec, ""cancel""); } /// Cancel all asynchronous operations associated with the socket. /** * This function causes all outstanding asynchronous connect, send and receive * operations to finish immediately, and the handlers for cancelled operations * will be passed the boost::asio::error::operation_aborted error. * * @param ec Set to indicate what error occurred, if any. * * @note Calls to cancel() will always fail with * boost::asio::error::operation_not_supported when run on Windows XP, Windows * Server 2003, and earlier versions of Windows, unless * BOOST_ASIO_ENABLE_CANCELIO is defined. However, the CancelIo function has * two issues that should be considered before enabling its use: * * @li It will only cancel asynchronous operations that were initiated in the * current thread. * * @li It can appear to complete without error, but the request to cancel the * unfinished operations may be silently ignored by the operating system. * Whether it works or not seems to depend on the drivers that are installed. * * For portable cancellation, consider using one of the following * alternatives: * * @li Disable asio's I/O completion port backend by defining * BOOST_ASIO_DISABLE_IOCP. * * @li Use the close() function to simultaneously cancel the outstanding * operations and close the socket. * * When running on Windows Vista, Windows Server 2008, and later, the * CancelIoEx function is always used. This function does not have the * problems described above. */ #if defined(BOOST_ASIO_MSVC) && (BOOST_ASIO_MSVC >= 1400) \\ && (!defined(_WIN32_WINNT) || _WIN32_WINNT < 0x0600) \\ && !defined(BOOST_ASIO_ENABLE_CANCELIO) __declspec(deprecated(""By default, this function always fails with "" ""operation_not_supported when used on Windows XP, Windows Server 2003, "" ""or earlier. Consult documentation for details."")) #endif BOOST_ASIO_SYNC_OP_VOID cancel(boost::system::error_code& ec) { impl_.get_service().cancel(impl_.get_implementation(), ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Determine whether the socket is at the out-of-band data mark. /** * This function is used to check whether the socket input is currently * positioned at the out-of-band data mark. * * @return A bool indicating whether the socket is at the out-of-band data * mark. * * @throws boost::system::system_error Thrown on failure. */ bool at_mark() const { boost::system::error_code ec; bool b = impl_.get_service().at_mark(impl_.get_implementation(), ec); boost::asio::detail::throw_error(ec, ""at_mark""); return b; } /// Determine whether the socket is at the out-of-band data mark. /** * This function is used to check whether the socket input is currently * positioned at the out-of-band data mark. * * @param ec Set to indicate what error occurred, if any. * * @return A bool indicating whether the socket is at the out-of-band data * mark. */ bool at_mark(boost::system::error_code& ec) const { return impl_.get_service().at_mark(impl_.get_implementation(), ec); } /// Determine the number of bytes available for reading. /** * This function is used to determine the number of bytes that may be read * without blocking. * * @return The number of bytes that may be read without blocking, or 0 if an * error occurs. * * @throws boost::system::system_error Thrown on failure. */ std::size_t available() const { boost::system::error_code ec; std::size_t s = impl_.get_service().available( impl_.get_implementation(), ec); boost::asio::detail::throw_error(ec, ""available""); return s; } /// Determine the number of bytes available for reading. /** * This function is used to determine the number of bytes that may be read * without blocking. * * @param ec Set to indicate what error occurred, if any. * * @return The number of bytes that may be read without blocking, or 0 if an * error occurs. */ std::size_t available(boost::system::error_code& ec) const { return impl_.get_service().available(impl_.get_implementation(), ec); } /// Bind the socket to the given local endpoint. /** * This function binds the socket to the specified endpoint on the local * machine. * * @param endpoint An endpoint on the local machine to which the socket will * be bound. * * @throws boost::system::system_error Thrown on failure. * * @par Example * @code * boost::asio::ip::tcp::socket socket(my_context); * socket.open(boost::asio::ip::tcp::v4()); * socket.bind(boost::asio::ip::tcp::endpoint( * boost::asio::ip::tcp::v4(), 12345)); * @endcode */ void bind(const endpoint_type& endpoint) { boost::system::error_code ec; impl_.get_service().bind(impl_.get_implementation(), endpoint, ec); boost::asio::detail::throw_error(ec, ""bind""); } /// Bind the socket to the given local endpoint. /** * This function binds the socket to the specified endpoint on the local * machine. * * @param endpoint An endpoint on the local machine to which the socket will * be bound. * * @param ec Set to indicate what error occurred, if any. * * @par Example * @code * boost::asio::ip::tcp::socket socket(my_context); * socket.open(boost::asio::ip::tcp::v4()); * boost::system::error_code ec; * socket.bind(boost::asio::ip::tcp::endpoint( * boost::asio::ip::tcp::v4(), 12345), ec); * if (ec) * { * // An error occurred. * } * @endcode */ BOOST_ASIO_SYNC_OP_VOID bind(const endpoint_type& endpoint, boost::system::error_code& ec) { impl_.get_service().bind(impl_.get_implementation(), endpoint, ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Connect the socket to the specified endpoint. /** * This function is used to connect a socket to the specified remote endpoint. * The function call will block until the connection is successfully made or * an error occurs. * * The socket is automatically opened if it is not already open. If the * connect fails, and the socket was automatically opened, the socket is * not returned to the closed state. * * @param peer_endpoint The remote endpoint to which the socket will be * connected. * * @throws boost::system::system_error Thrown on failure. * * @par Example * @code * boost::asio::ip::tcp::socket socket(my_context); * boost::asio::ip::tcp::endpoint endpoint( * boost::asio::ip::address::from_string(""1.2.3.4""), 12345); * socket.connect(endpoint); * @endcode */ void connect(const endpoint_type& peer_endpoint) { boost::system::error_code ec; if (!is_open()) { impl_.get_service().open(impl_.get_implementation(), peer_endpoint.protocol(), ec); boost::asio::detail::throw_error(ec, ""connect""); } impl_.get_service().connect(impl_.get_implementation(), peer_endpoint, ec); boost::asio::detail::throw_error(ec, ""connect""); } /// Connect the socket to the specified endpoint. /** * This function is used to connect a socket to the specified remote endpoint. * The function call will block until the connection is successfully made or * an error occurs. * * The socket is automatically opened if it is not already open. If the * connect fails, and the socket was automatically opened, the socket is * not returned to the closed state. * * @param peer_endpoint The remote endpoint to which the socket will be * connected. * * @param ec Set to indicate what error occurred, if any. * * @par Example * @code * boost::asio::ip::tcp::socket socket(my_context); * boost::asio::ip::tcp::endpoint endpoint( * boost::asio::ip::address::from_string(""1.2.3.4""), 12345); * boost::system::error_code ec; * socket.connect(endpoint, ec); * if (ec) * { * // An error occurred. * } * @endcode */ BOOST_ASIO_SYNC_OP_VOID connect(const endpoint_type& peer_endpoint, boost::system::error_code& ec) { if (!is_open()) { impl_.get_service().open(impl_.get_implementation(), peer_endpoint.protocol(), ec); if (ec) { BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } } impl_.get_service().connect(impl_.get_implementation(), peer_endpoint, ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Start an asynchronous connect. /** * This function is used to asynchronously connect a socket to the specified * remote endpoint. The function call always returns immediately. * * The socket is automatically opened if it is not already open. If the * connect fails, and the socket was automatically opened, the socket is * not returned to the closed state. * * @param peer_endpoint The remote endpoint to which the socket will be * connected. Copies will be made of the endpoint object as required. * * @param handler The handler to be called when the connection operation * completes. Copies will be made of the handler as required. The function * signature of the handler must be: * @code void handler( * const boost::system::error_code& error // Result of operation * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the handler will not be invoked from within this function. On * immediate completion, invocation of the handler will be performed in a * manner equivalent to using boost::asio::post(). * * @par Example * @code * void connect_handler(const boost::system::error_code& error) * { * if (!error) * { * // Connect succeeded. * } * } * * ... * * boost::asio::ip::tcp::socket socket(my_context); * boost::asio::ip::tcp::endpoint endpoint( * boost::asio::ip::address::from_string(""1.2.3.4""), 12345); * socket.async_connect(endpoint, connect_handler); * @endcode */ template < BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::error_code)) ConnectHandler BOOST_ASIO_DEFAULT_COMPLETION_TOKEN_TYPE(executor_type)> BOOST_ASIO_INITFN_AUTO_RESULT_TYPE(ConnectHandler, void (boost::system::error_code)) async_connect(const endpoint_type& peer_endpoint, BOOST_ASIO_MOVE_ARG(ConnectHandler) handler BOOST_ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) { boost::system::error_code open_ec; if (!is_open()) { const protocol_type protocol = peer_endpoint.protocol(); impl_.get_service().open(impl_.get_implementation(), protocol, open_ec); } return async_initiate( initiate_async_connect(this), handler, peer_endpoint, open_ec); } /// Set an option on the socket. /** * This function is used to set an option on the socket. * * @param option The new option value to be set on the socket. * * @throws boost::system::system_error Thrown on failure. * * @sa SettableSocketOption @n * boost::asio::socket_base::broadcast @n * boost::asio::socket_base::do_not_route @n * boost::asio::socket_base::keep_alive @n * boost::asio::socket_base::linger @n * boost::asio::socket_base::receive_buffer_size @n * boost::asio::socket_base::receive_low_watermark @n * boost::asio::socket_base::reuse_address @n * boost::asio::socket_base::send_buffer_size @n * boost::asio::socket_base::send_low_watermark @n * boost::asio::ip::multicast::join_group @n * boost::asio::ip::multicast::leave_group @n * boost::asio::ip::multicast::enable_loopback @n * boost::asio::ip::multicast::outbound_interface @n * boost::asio::ip::multicast::hops @n * boost::asio::ip::tcp::no_delay * * @par Example * Setting the IPPROTO_TCP/TCP_NODELAY option: * @code * boost::asio::ip::tcp::socket socket(my_context); * ... * boost::asio::ip::tcp::no_delay option(true); * socket.set_option(option); * @endcode */ template void set_option(const SettableSocketOption& option) { boost::system::error_code ec; impl_.get_service().set_option(impl_.get_implementation(), option, ec); boost::asio::detail::throw_error(ec, ""set_option""); } /// Set an option on the socket. /** * This function is used to set an option on the socket. * * @param option The new option value to be set on the socket. * * @param ec Set to indicate what error occurred, if any. * * @sa SettableSocketOption @n * boost::asio::socket_base::broadcast @n * boost::asio::socket_base::do_not_route @n * boost::asio::socket_base::keep_alive @n * boost::asio::socket_base::linger @n * boost::asio::socket_base::receive_buffer_size @n * boost::asio::socket_base::receive_low_watermark @n * boost::asio::socket_base::reuse_address @n * boost::asio::socket_base::send_buffer_size @n * boost::asio::socket_base::send_low_watermark @n * boost::asio::ip::multicast::join_group @n * boost::asio::ip::multicast::leave_group @n * boost::asio::ip::multicast::enable_loopback @n * boost::asio::ip::multicast::outbound_interface @n * boost::asio::ip::multicast::hops @n * boost::asio::ip::tcp::no_delay * * @par Example * Setting the IPPROTO_TCP/TCP_NODELAY option: * @code * boost::asio::ip::tcp::socket socket(my_context); * ... * boost::asio::ip::tcp::no_delay option(true); * boost::system::error_code ec; * socket.set_option(option, ec); * if (ec) * { * // An error occurred. * } * @endcode */ template BOOST_ASIO_SYNC_OP_VOID set_option(const SettableSocketOption& option, boost::system::error_code& ec) { impl_.get_service().set_option(impl_.get_implementation(), option, ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Get an option from the socket. /** * This function is used to get the current value of an option on the socket. * * @param option The option value to be obtained from the socket. * * @throws boost::system::system_error Thrown on failure. * * @sa GettableSocketOption @n * boost::asio::socket_base::broadcast @n * boost::asio::socket_base::do_not_route @n * boost::asio::socket_base::keep_alive @n * boost::asio::socket_base::linger @n * boost::asio::socket_base::receive_buffer_size @n * boost::asio::socket_base::receive_low_watermark @n * boost::asio::socket_base::reuse_address @n * boost::asio::socket_base::send_buffer_size @n * boost::asio::socket_base::send_low_watermark @n * boost::asio::ip::multicast::join_group @n * boost::asio::ip::multicast::leave_group @n * boost::asio::ip::multicast::enable_loopback @n * boost::asio::ip::multicast::outbound_interface @n * boost::asio::ip::multicast::hops @n * boost::asio::ip::tcp::no_delay * * @par Example * Getting the value of the SOL_SOCKET/SO_KEEPALIVE option: * @code * boost::asio::ip::tcp::socket socket(my_context); * ... * boost::asio::ip::tcp::socket::keep_alive option; * socket.get_option(option); * bool is_set = option.value(); * @endcode */ template void get_option(GettableSocketOption& option) const { boost::system::error_code ec; impl_.get_service().get_option(impl_.get_implementation(), option, ec); boost::asio::detail::throw_error(ec, ""get_option""); } /// Get an option from the socket. /** * This function is used to get the current value of an option on the socket. * * @param option The option value to be obtained from the socket. * * @param ec Set to indicate what error occurred, if any. * * @sa GettableSocketOption @n * boost::asio::socket_base::broadcast @n * boost::asio::socket_base::do_not_route @n * boost::asio::socket_base::keep_alive @n * boost::asio::socket_base::linger @n * boost::asio::socket_base::receive_buffer_size @n * boost::asio::socket_base::receive_low_watermark @n * boost::asio::socket_base::reuse_address @n * boost::asio::socket_base::send_buffer_size @n * boost::asio::socket_base::send_low_watermark @n * boost::asio::ip::multicast::join_group @n * boost::asio::ip::multicast::leave_group @n * boost::asio::ip::multicast::enable_loopback @n * boost::asio::ip::multicast::outbound_interface @n * boost::asio::ip::multicast::hops @n * boost::asio::ip::tcp::no_delay * * @par Example * Getting the value of the SOL_SOCKET/SO_KEEPALIVE option: * @code * boost::asio::ip::tcp::socket socket(my_context); * ... * boost::asio::ip::tcp::socket::keep_alive option; * boost::system::error_code ec; * socket.get_option(option, ec); * if (ec) * { * // An error occurred. * } * bool is_set = option.value(); * @endcode */ template BOOST_ASIO_SYNC_OP_VOID get_option(GettableSocketOption& option, boost::system::error_code& ec) const { impl_.get_service().get_option(impl_.get_implementation(), option, ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Perform an IO control command on the socket. /** * This function is used to execute an IO control command on the socket. * * @param command The IO control command to be performed on the socket. * * @throws boost::system::system_error Thrown on failure. * * @sa IoControlCommand @n * boost::asio::socket_base::bytes_readable @n * boost::asio::socket_base::non_blocking_io * * @par Example * Getting the number of bytes ready to read: * @code * boost::asio::ip::tcp::socket socket(my_context); * ... * boost::asio::ip::tcp::socket::bytes_readable command; * socket.io_control(command); * std::size_t bytes_readable = command.get(); * @endcode */ template void io_control(IoControlCommand& command) { boost::system::error_code ec; impl_.get_service().io_control(impl_.get_implementation(), command, ec); boost::asio::detail::throw_error(ec, ""io_control""); } /// Perform an IO control command on the socket. /** * This function is used to execute an IO control command on the socket. * * @param command The IO control command to be performed on the socket. * * @param ec Set to indicate what error occurred, if any. * * @sa IoControlCommand @n * boost::asio::socket_base::bytes_readable @n * boost::asio::socket_base::non_blocking_io * * @par Example * Getting the number of bytes ready to read: * @code * boost::asio::ip::tcp::socket socket(my_context); * ... * boost::asio::ip::tcp::socket::bytes_readable command; * boost::system::error_code ec; * socket.io_control(command, ec); * if (ec) * { * // An error occurred. * } * std::size_t bytes_readable = command.get(); * @endcode */ template BOOST_ASIO_SYNC_OP_VOID io_control(IoControlCommand& command, boost::system::error_code& ec) { impl_.get_service().io_control(impl_.get_implementation(), command, ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Gets the non-blocking mode of the socket. /** * @returns @c true if the socket's synchronous operations will fail with * boost::asio::error::would_block if they are unable to perform the requested * operation immediately. If @c false, synchronous operations will block * until complete. * * @note The non-blocking mode has no effect on the behaviour of asynchronous * operations. Asynchronous operations will never fail with the error * boost::asio::error::would_block. */ bool non_blocking() const { return impl_.get_service().non_blocking(impl_.get_implementation()); } /// Sets the non-blocking mode of the socket. /** * @param mode If @c true, the socket's synchronous operations will fail with * boost::asio::error::would_block if they are unable to perform the requested * operation immediately. If @c false, synchronous operations will block * until complete. * * @throws boost::system::system_error Thrown on failure. * * @note The non-blocking mode has no effect on the behaviour of asynchronous * operations. Asynchronous operations will never fail with the error * boost::asio::error::would_block. */ void non_blocking(bool mode) { boost::system::error_code ec; impl_.get_service().non_blocking(impl_.get_implementation(), mode, ec); boost::asio::detail::throw_error(ec, ""non_blocking""); } /// Sets the non-blocking mode of the socket. /** * @param mode If @c true, the socket's synchronous operations will fail with * boost::asio::error::would_block if they are unable to perform the requested * operation immediately. If @c false, synchronous operations will block * until complete. * * @param ec Set to indicate what error occurred, if any. * * @note The non-blocking mode has no effect on the behaviour of asynchronous * operations. Asynchronous operations will never fail with the error * boost::asio::error::would_block. */ BOOST_ASIO_SYNC_OP_VOID non_blocking( bool mode, boost::system::error_code& ec) { impl_.get_service().non_blocking(impl_.get_implementation(), mode, ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Gets the non-blocking mode of the native socket implementation. /** * This function is used to retrieve the non-blocking mode of the underlying * native socket. This mode has no effect on the behaviour of the socket * object's synchronous operations. * * @returns @c true if the underlying socket is in non-blocking mode and * direct system calls may fail with boost::asio::error::would_block (or the * equivalent system error). * * @note The current non-blocking mode is cached by the socket object. * Consequently, the return value may be incorrect if the non-blocking mode * was set directly on the native socket. * * @par Example * This function is intended to allow the encapsulation of arbitrary * non-blocking system calls as asynchronous operations, in a way that is * transparent to the user of the socket object. The following example * illustrates how Linux's @c sendfile system call might be encapsulated: * @code template * struct sendfile_op * { * tcp::socket& sock_; * int fd_; * Handler handler_; * off_t offset_; * std::size_t total_bytes_transferred_; * * // Function call operator meeting WriteHandler requirements. * // Used as the handler for the async_write_some operation. * void operator()(boost::system::error_code ec, std::size_t) * { * // Put the underlying socket into non-blocking mode. * if (!ec) * if (!sock_.native_non_blocking()) * sock_.native_non_blocking(true, ec); * * if (!ec) * { * for (;;) * { * // Try the system call. * errno = 0; * int n = ::sendfile(sock_.native_handle(), fd_, &offset_, 65536); * ec = boost::system::error_code(n < 0 ? errno : 0, * boost::asio::error::get_system_category()); * total_bytes_transferred_ += ec ? 0 : n; * * // Retry operation immediately if interrupted by signal. * if (ec == boost::asio::error::interrupted) * continue; * * // Check if we need to run the operation again. * if (ec == boost::asio::error::would_block * || ec == boost::asio::error::try_again) * { * // We have to wait for the socket to become ready again. * sock_.async_wait(tcp::socket::wait_write, *this); * return; * } * * if (ec || n == 0) * { * // An error occurred, or we have reached the end of the file. * // Either way we must exit the loop so we can call the handler. * break; * } * * // Loop around to try calling sendfile again. * } * } * * // Pass result back to user's handler. * handler_(ec, total_bytes_transferred_); * } * }; * * template * void async_sendfile(tcp::socket& sock, int fd, Handler h) * { * sendfile_op op = { sock, fd, h, 0, 0 }; * sock.async_wait(tcp::socket::wait_write, op); * } @endcode */ bool native_non_blocking() const { return impl_.get_service().native_non_blocking(impl_.get_implementation()); } /// Sets the non-blocking mode of the native socket implementation. /** * This function is used to modify the non-blocking mode of the underlying * native socket. It has no effect on the behaviour of the socket object's * synchronous operations. * * @param mode If @c true, the underlying socket is put into non-blocking * mode and direct system calls may fail with boost::asio::error::would_block * (or the equivalent system error). * * @throws boost::system::system_error Thrown on failure. If the @c mode is * @c false, but the current value of @c non_blocking() is @c true, this * function fails with boost::asio::error::invalid_argument, as the * combination does not make sense. * * @par Example * This function is intended to allow the encapsulation of arbitrary * non-blocking system calls as asynchronous operations, in a way that is * transparent to the user of the socket object. The following example * illustrates how Linux's @c sendfile system call might be encapsulated: * @code template * struct sendfile_op * { * tcp::socket& sock_; * int fd_; * Handler handler_; * off_t offset_; * std::size_t total_bytes_transferred_; * * // Function call operator meeting WriteHandler requirements. * // Used as the handler for the async_write_some operation. * void operator()(boost::system::error_code ec, std::size_t) * { * // Put the underlying socket into non-blocking mode. * if (!ec) * if (!sock_.native_non_blocking()) * sock_.native_non_blocking(true, ec); * * if (!ec) * { * for (;;) * { * // Try the system call. * errno = 0; * int n = ::sendfile(sock_.native_handle(), fd_, &offset_, 65536); * ec = boost::system::error_code(n < 0 ? errno : 0, * boost::asio::error::get_system_category()); * total_bytes_transferred_ += ec ? 0 : n; * * // Retry operation immediately if interrupted by signal. * if (ec == boost::asio::error::interrupted) * continue; * * // Check if we need to run the operation again. * if (ec == boost::asio::error::would_block * || ec == boost::asio::error::try_again) * { * // We have to wait for the socket to become ready again. * sock_.async_wait(tcp::socket::wait_write, *this); * return; * } * * if (ec || n == 0) * { * // An error occurred, or we have reached the end of the file. * // Either way we must exit the loop so we can call the handler. * break; * } * * // Loop around to try calling sendfile again. * } * } * * // Pass result back to user's handler. * handler_(ec, total_bytes_transferred_); * } * }; * * template * void async_sendfile(tcp::socket& sock, int fd, Handler h) * { * sendfile_op op = { sock, fd, h, 0, 0 }; * sock.async_wait(tcp::socket::wait_write, op); * } @endcode */ void native_non_blocking(bool mode) { boost::system::error_code ec; impl_.get_service().native_non_blocking( impl_.get_implementation(), mode, ec); boost::asio::detail::throw_error(ec, ""native_non_blocking""); } /// Sets the non-blocking mode of the native socket implementation. /** * This function is used to modify the non-blocking mode of the underlying * native socket. It has no effect on the behaviour of the socket object's * synchronous operations. * * @param mode If @c true, the underlying socket is put into non-blocking * mode and direct system calls may fail with boost::asio::error::would_block * (or the equivalent system error). * * @param ec Set to indicate what error occurred, if any. If the @c mode is * @c false, but the current value of @c non_blocking() is @c true, this * function fails with boost::asio::error::invalid_argument, as the * combination does not make sense. * * @par Example * This function is intended to allow the encapsulation of arbitrary * non-blocking system calls as asynchronous operations, in a way that is * transparent to the user of the socket object. The following example * illustrates how Linux's @c sendfile system call might be encapsulated: * @code template * struct sendfile_op * { * tcp::socket& sock_; * int fd_; * Handler handler_; * off_t offset_; * std::size_t total_bytes_transferred_; * * // Function call operator meeting WriteHandler requirements. * // Used as the handler for the async_write_some operation. * void operator()(boost::system::error_code ec, std::size_t) * { * // Put the underlying socket into non-blocking mode. * if (!ec) * if (!sock_.native_non_blocking()) * sock_.native_non_blocking(true, ec); * * if (!ec) * { * for (;;) * { * // Try the system call. * errno = 0; * int n = ::sendfile(sock_.native_handle(), fd_, &offset_, 65536); * ec = boost::system::error_code(n < 0 ? errno : 0, * boost::asio::error::get_system_category()); * total_bytes_transferred_ += ec ? 0 : n; * * // Retry operation immediately if interrupted by signal. * if (ec == boost::asio::error::interrupted) * continue; * * // Check if we need to run the operation again. * if (ec == boost::asio::error::would_block * || ec == boost::asio::error::try_again) * { * // We have to wait for the socket to become ready again. * sock_.async_wait(tcp::socket::wait_write, *this); * return; * } * * if (ec || n == 0) * { * // An error occurred, or we have reached the end of the file. * // Either way we must exit the loop so we can call the handler. * break; * } * * // Loop around to try calling sendfile again. * } * } * * // Pass result back to user's handler. * handler_(ec, total_bytes_transferred_); * } * }; * * template * void async_sendfile(tcp::socket& sock, int fd, Handler h) * { * sendfile_op op = { sock, fd, h, 0, 0 }; * sock.async_wait(tcp::socket::wait_write, op); * } @endcode */ BOOST_ASIO_SYNC_OP_VOID native_non_blocking( bool mode, boost::system::error_code& ec) { impl_.get_service().native_non_blocking( impl_.get_implementation(), mode, ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Get the local endpoint of the socket. /** * This function is used to obtain the locally bound endpoint of the socket. * * @returns An object that represents the local endpoint of the socket. * * @throws boost::system::system_error Thrown on failure. * * @par Example * @code * boost::asio::ip::tcp::socket socket(my_context); * ... * boost::asio::ip::tcp::endpoint endpoint = socket.local_endpoint(); * @endcode */ endpoint_type local_endpoint() const { boost::system::error_code ec; endpoint_type ep = impl_.get_service().local_endpoint( impl_.get_implementation(), ec); boost::asio::detail::throw_error(ec, ""local_endpoint""); return ep; } /// Get the local endpoint of the socket. /** * This function is used to obtain the locally bound endpoint of the socket. * * @param ec Set to indicate what error occurred, if any. * * @returns An object that represents the local endpoint of the socket. * Returns a default-constructed endpoint object if an error occurred. * * @par Example * @code * boost::asio::ip::tcp::socket socket(my_context); * ... * boost::system::error_code ec; * boost::asio::ip::tcp::endpoint endpoint = socket.local_endpoint(ec); * if (ec) * { * // An error occurred. * } * @endcode */ endpoint_type local_endpoint(boost::system::error_code& ec) const { return impl_.get_service().local_endpoint(impl_.get_implementation(), ec); } /// Get the remote endpoint of the socket. /** * This function is used to obtain the remote endpoint of the socket. * * @returns An object that represents the remote endpoint of the socket. * * @throws boost::system::system_error Thrown on failure. * * @par Example * @code * boost::asio::ip::tcp::socket socket(my_context); * ... * boost::asio::ip::tcp::endpoint endpoint = socket.remote_endpoint(); * @endcode */ endpoint_type remote_endpoint() const { boost::system::error_code ec; endpoint_type ep = impl_.get_service().remote_endpoint( impl_.get_implementation(), ec); boost::asio::detail::throw_error(ec, ""remote_endpoint""); return ep; } /// Get the remote endpoint of the socket. /** * This function is used to obtain the remote endpoint of the socket. * * @param ec Set to indicate what error occurred, if any. * * @returns An object that represents the remote endpoint of the socket. * Returns a default-constructed endpoint object if an error occurred. * * @par Example * @code * boost::asio::ip::tcp::socket socket(my_context); * ... * boost::system::error_code ec; * boost::asio::ip::tcp::endpoint endpoint = socket.remote_endpoint(ec); * if (ec) * { * // An error occurred. * } * @endcode */ endpoint_type remote_endpoint(boost::system::error_code& ec) const { return impl_.get_service().remote_endpoint(impl_.get_implementation(), ec); } /// Disable sends or receives on the socket. /** * This function is used to disable send operations, receive operations, or * both. * * @param what Determines what types of operation will no longer be allowed. * * @throws boost::system::system_error Thrown on failure. * * @par Example * Shutting down the send side of the socket: * @code * boost::asio::ip::tcp::socket socket(my_context); * ... * socket.shutdown(boost::asio::ip::tcp::socket::shutdown_send); * @endcode */ void shutdown(shutdown_type what) { boost::system::error_code ec; impl_.get_service().shutdown(impl_.get_implementation(), what, ec); boost::asio::detail::throw_error(ec, ""shutdown""); } /// Disable sends or receives on the socket. /** * This function is used to disable send operations, receive operations, or * both. * * @param what Determines what types of operation will no longer be allowed. * * @param ec Set to indicate what error occurred, if any. * * @par Example * Shutting down the send side of the socket: * @code * boost::asio::ip::tcp::socket socket(my_context); * ... * boost::system::error_code ec; * socket.shutdown(boost::asio::ip::tcp::socket::shutdown_send, ec); * if (ec) * { * // An error occurred. * } * @endcode */ BOOST_ASIO_SYNC_OP_VOID shutdown(shutdown_type what, boost::system::error_code& ec) { impl_.get_service().shutdown(impl_.get_implementation(), what, ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Wait for the socket to become ready to read, ready to write, or to have /// pending error conditions. /** * This function is used to perform a blocking wait for a socket to enter * a ready to read, write or error condition state. * * @param w Specifies the desired socket state. * * @par Example * Waiting for a socket to become readable. * @code * boost::asio::ip::tcp::socket socket(my_context); * ... * socket.wait(boost::asio::ip::tcp::socket::wait_read); * @endcode */ void wait(wait_type w) { boost::system::error_code ec; impl_.get_service().wait(impl_.get_implementation(), w, ec); boost::asio::detail::throw_error(ec, ""wait""); } /// Wait for the socket to become ready to read, ready to write, or to have /// pending error conditions. /** * This function is used to perform a blocking wait for a socket to enter * a ready to read, write or error condition state. * * @param w Specifies the desired socket state. * * @param ec Set to indicate what error occurred, if any. * * @par Example * Waiting for a socket to become readable. * @code * boost::asio::ip::tcp::socket socket(my_context); * ... * boost::system::error_code ec; * socket.wait(boost::asio::ip::tcp::socket::wait_read, ec); * @endcode */ BOOST_ASIO_SYNC_OP_VOID wait(wait_type w, boost::system::error_code& ec) { impl_.get_service().wait(impl_.get_implementation(), w, ec); BOOST_ASIO_SYNC_OP_VOID_RETURN(ec); } /// Asynchronously wait for the socket to become ready to read, ready to /// write, or to have pending error conditions. /** * This function is used to perform an asynchronous wait for a socket to enter * a ready to read, write or error condition state. * * @param w Specifies the desired socket state. * * @param handler The handler to be called when the wait operation completes. * Copies will be made of the handler as required. The function signature of * the handler must be: * @code void handler( * const boost::system::error_code& error // Result of operation * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the handler will not be invoked from within this function. On * immediate completion, invocation of the handler will be performed in a * manner equivalent to using boost::asio::post(). * * @par Example * @code * void wait_handler(const boost::system::error_code& error) * { * if (!error) * { * // Wait succeeded. * } * } * * ... * * boost::asio::ip::tcp::socket socket(my_context); * ... * socket.async_wait(boost::asio::ip::tcp::socket::wait_read, wait_handler); * @endcode */ template < BOOST_ASIO_COMPLETION_TOKEN_FOR(void (boost::system::error_code)) WaitHandler BOOST_ASIO_DEFAULT_COMPLETION_TOKEN_TYPE(executor_type)> BOOST_ASIO_INITFN_AUTO_RESULT_TYPE(WaitHandler, void (boost::system::error_code)) async_wait(wait_type w, BOOST_ASIO_MOVE_ARG(WaitHandler) handler BOOST_ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) { return async_initiate( initiate_async_wait(this), handler, w); } protected: /// Protected destructor to prevent deletion through this type. /** * This function destroys the socket, cancelling any outstanding asynchronous * operations associated with the socket as if by calling @c cancel. */ ~basic_socket() { } #if defined(BOOST_ASIO_WINDOWS_RUNTIME) detail::io_object_impl< detail::null_socket_service, Executor> impl_; #elif defined(BOOST_ASIO_HAS_IOCP) detail::io_object_impl< detail::win_iocp_socket_service, Executor> impl_; #else detail::io_object_impl< detail::reactive_socket_service, Executor> impl_; #endif private: // Disallow copying and assignment. basic_socket(const basic_socket&) BOOST_ASIO_DELETED; basic_socket& operator=(const basic_socket&) BOOST_ASIO_DELETED; class initiate_async_connect { public: typedef Executor executor_type; explicit initiate_async_connect(basic_socket* self) : self_(self) { } executor_type get_executor() const BOOST_ASIO_NOEXCEPT { return self_->get_executor(); } template void operator()(BOOST_ASIO_MOVE_ARG(ConnectHandler) handler, const endpoint_type& peer_endpoint, const boost::system::error_code& open_ec) const { // If you get an error on the following line it means that your handler // does not meet the documented type requirements for a ConnectHandler. BOOST_ASIO_CONNECT_HANDLER_CHECK(ConnectHandler, handler) type_check; if (open_ec) { boost::asio::post(self_->impl_.get_executor(), boost::asio::detail::bind_handler( BOOST_ASIO_MOVE_CAST(ConnectHandler)(handler), open_ec)); } else { detail::non_const_lvalue handler2(handler); self_->impl_.get_service().async_connect( self_->impl_.get_implementation(), peer_endpoint, handler2.value, self_->impl_.get_executor()); } } private: basic_socket* self_; }; class initiate_async_wait { public: typedef Executor executor_type; explicit initiate_async_wait(basic_socket* self) : self_(self) { } executor_type get_executor() const BOOST_ASIO_NOEXCEPT { return self_->get_executor(); } template void operator()(BOOST_ASIO_MOVE_ARG(WaitHandler) handler, wait_type w) const { // If you get an error on the following line it means that your handler // does not meet the documented type requirements for a WaitHandler. BOOST_ASIO_WAIT_HANDLER_CHECK(WaitHandler, handler) type_check; detail::non_const_lvalue handler2(handler); self_->impl_.get_service().async_wait( self_->impl_.get_implementation(), w, handler2.value, self_->impl_.get_executor()); } private: basic_socket* self_; }; }; } // namespace asio } // namespace boost #include #endif // BOOST_ASIO_BASIC_SOCKET_HPP ",16377,True,3386.952007852941,median "/*************************************************************************/ /* tile_map_editor_plugin.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */ /* */ /* 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 ""tile_map_editor_plugin.h"" #include ""canvas_item_editor_plugin.h"" #include ""core/math/math_funcs.h"" #include ""core/os/input.h"" #include ""core/os/keyboard.h"" #include ""editor/editor_scale.h"" #include ""editor/editor_settings.h"" #include ""scene/gui/split_container.h"" void TileMapEditor::_notification(int p_what) { switch (p_what) { case NOTIFICATION_PROCESS: { if (bucket_queue.size()) { CanvasItemEditor::get_singleton()->update_viewport(); } } break; case EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED: { bool new_show_tile_info = EditorSettings::get_singleton()->get(""editors/tile_map/show_tile_info_on_hover""); if (new_show_tile_info != show_tile_info) { show_tile_info = new_show_tile_info; tile_info->set_visible(show_tile_info); } if (is_visible_in_tree()) { _update_palette(); } } // fallthrough case NOTIFICATION_ENTER_TREE: { rotate_left_button->set_icon(get_icon(""Rotate270"", ""EditorIcons"")); rotate_right_button->set_icon(get_icon(""Rotate90"", ""EditorIcons"")); flip_horizontal_button->set_icon(get_icon(""MirrorX"", ""EditorIcons"")); flip_vertical_button->set_icon(get_icon(""MirrorY"", ""EditorIcons"")); clear_transform_button->set_icon(get_icon(""Clear"", ""EditorIcons"")); search_box->set_right_icon(get_icon(""Search"", ""EditorIcons"")); search_box->set_clear_button_enabled(true); PopupMenu *p = options->get_popup(); p->set_item_icon(p->get_item_index(OPTION_PAINTING), get_icon(""Edit"", ""EditorIcons"")); p->set_item_icon(p->get_item_index(OPTION_PICK_TILE), get_icon(""ColorPick"", ""EditorIcons"")); p->set_item_icon(p->get_item_index(OPTION_SELECT), get_icon(""ActionCopy"", ""EditorIcons"")); p->set_item_icon(p->get_item_index(OPTION_CUT), get_icon(""ActionCut"", ""EditorIcons"")); p->set_item_icon(p->get_item_index(OPTION_COPY), get_icon(""Duplicate"", ""EditorIcons"")); p->set_item_icon(p->get_item_index(OPTION_ERASE_SELECTION), get_icon(""Remove"", ""EditorIcons"")); } break; } } void TileMapEditor::_menu_option(int p_option) { switch (p_option) { case OPTION_PAINTING: { // NOTE: We do not set tool = TOOL_PAINTING as this begins painting // immediately without pressing the left mouse button first tool = TOOL_NONE; CanvasItemEditor::get_singleton()->update_viewport(); } break; case OPTION_BUCKET: { tool = TOOL_BUCKET; CanvasItemEditor::get_singleton()->update_viewport(); } break; case OPTION_PICK_TILE: { tool = TOOL_PICKING; CanvasItemEditor::get_singleton()->update_viewport(); } break; case OPTION_SELECT: { tool = TOOL_SELECTING; selection_active = false; CanvasItemEditor::get_singleton()->update_viewport(); } break; case OPTION_COPY: { _update_copydata(); if (selection_active) { tool = TOOL_PASTING; CanvasItemEditor::get_singleton()->update_viewport(); } } break; case OPTION_ERASE_SELECTION: { if (!selection_active) return; _start_undo(TTR(""Erase Selection"")); _erase_selection(); _finish_undo(); selection_active = false; copydata.clear(); CanvasItemEditor::get_singleton()->update_viewport(); } break; case OPTION_FIX_INVALID: { undo_redo->create_action(TTR(""Fix Invalid Tiles"")); undo_redo->add_undo_method(node, ""set"", ""tile_data"", node->get(""tile_data"")); node->fix_invalid_tiles(); undo_redo->add_do_method(node, ""set"", ""tile_data"", node->get(""tile_data"")); undo_redo->commit_action(); } break; case OPTION_CUT: { if (selection_active) { _update_copydata(); _start_undo(TTR(""Cut Selection"")); _erase_selection(); _finish_undo(); selection_active = false; tool = TOOL_PASTING; CanvasItemEditor::get_singleton()->update_viewport(); } } break; } } void TileMapEditor::_palette_selected(int index) { _update_palette(); } void TileMapEditor::_palette_multi_selected(int index, bool selected) { _update_palette(); } void TileMapEditor::_canvas_mouse_enter() { mouse_over = true; CanvasItemEditor::get_singleton()->update_viewport(); } void TileMapEditor::_canvas_mouse_exit() { mouse_over = false; CanvasItemEditor::get_singleton()->update_viewport(); } Vector TileMapEditor::get_selected_tiles() const { Vector items = palette->get_selected_items(); if (items.size() == 0) { items.push_back(TileMap::INVALID_CELL); return items; } for (int i = items.size() - 1; i >= 0; i--) { items.write[i] = palette->get_item_metadata(items[i]); } return items; } void TileMapEditor::set_selected_tiles(Vector p_tiles) { palette->unselect_all(); for (int i = p_tiles.size() - 1; i >= 0; i--) { int idx = palette->find_metadata(p_tiles[i]); if (idx >= 0) { palette->select(idx, false); } } palette->ensure_current_is_visible(); } void TileMapEditor::_create_set_cell_undo(const Vector2 &p_vec, const CellOp &p_cell_old, const CellOp &p_cell_new) { Dictionary cell_old; Dictionary cell_new; cell_old[""id""] = p_cell_old.idx; cell_old[""flip_h""] = p_cell_old.xf; cell_old[""flip_y""] = p_cell_old.yf; cell_old[""transpose""] = p_cell_old.tr; cell_old[""auto_coord""] = p_cell_old.ac; cell_new[""id""] = p_cell_new.idx; cell_new[""flip_h""] = p_cell_new.xf; cell_new[""flip_y""] = p_cell_new.yf; cell_new[""transpose""] = p_cell_new.tr; cell_new[""auto_coord""] = p_cell_new.ac; undo_redo->add_undo_method(node, ""_set_celld"", p_vec, cell_old); undo_redo->add_do_method(node, ""_set_celld"", p_vec, cell_new); } void TileMapEditor::_start_undo(const String &p_action) { undo_data.clear(); undo_redo->create_action(p_action); } void TileMapEditor::_finish_undo() { if (undo_data.size()) { for (Map::Element *E = undo_data.front(); E; E = E->next()) { _create_set_cell_undo(E->key(), E->get(), _get_op_from_cell(E->key())); } undo_data.clear(); } undo_redo->commit_action(); } void TileMapEditor::_set_cell(const Point2i &p_pos, Vector p_values, bool p_flip_h, bool p_flip_v, bool p_transpose, const Point2i p_autotile_coord) { ERR_FAIL_COND(!node); if (p_values.size() == 0) return; int p_value = p_values[Math::rand() % p_values.size()]; int prev_val = node->get_cell(p_pos.x, p_pos.y); bool prev_flip_h = node->is_cell_x_flipped(p_pos.x, p_pos.y); bool prev_flip_v = node->is_cell_y_flipped(p_pos.x, p_pos.y); bool prev_transpose = node->is_cell_transposed(p_pos.x, p_pos.y); Vector2 prev_position = node->get_cell_autotile_coord(p_pos.x, p_pos.y); Vector2 position; int current = manual_palette->get_current(); if (current != -1) { position = manual_palette->get_item_metadata(current); } else { // if there is no manual tile selected, that either means that // autotiling is enabled, or the given tile is not autotiling. Either // way, the coordinate of the tile does not matter, so assigning it to // the coordinate of the existing tile works fine. position = prev_position; } if (p_value == prev_val && p_flip_h == prev_flip_h && p_flip_v == prev_flip_v && p_transpose == prev_transpose && prev_position == position) return; //check that it's actually different for (int y = p_pos.y - 1; y <= p_pos.y + 1; y++) { for (int x = p_pos.x - 1; x <= p_pos.x + 1; x++) { Point2i p = Point2i(x, y); if (!undo_data.has(p)) { undo_data[p] = _get_op_from_cell(p); } } } node->set_cell(p_pos.x, p_pos.y, p_value, p_flip_h, p_flip_v, p_transpose, p_autotile_coord); if (manual_autotile || (p_value != -1 && node->get_tileset()->tile_get_tile_mode(p_value) == TileSet::ATLAS_TILE)) { if (current != -1) { node->set_cell_autotile_coord(p_pos.x, p_pos.y, position); } } else { // manually placing tiles should not update bitmasks if (tool != TOOL_PASTING) { node->update_bitmask_area(Point2(p_pos)); } } } void TileMapEditor::_manual_toggled(bool p_enabled) { manual_autotile = p_enabled; _update_palette(); } void TileMapEditor::_text_entered(const String &p_text) { canvas_item_editor_viewport->grab_focus(); } void TileMapEditor::_text_changed(const String &p_text) { _update_palette(); } void TileMapEditor::_sbox_input(const Ref &p_ie) { Ref k = p_ie; if (k.is_valid() && (k->get_scancode() == KEY_UP || k->get_scancode() == KEY_DOWN || k->get_scancode() == KEY_PAGEUP || k->get_scancode() == KEY_PAGEDOWN)) { palette->call(""_gui_input"", k); search_box->accept_event(); } } // Implementation detail of TileMapEditor::_update_palette(); // in modern C++ this could have been inside its body namespace { struct _PaletteEntry { int id; String name; bool operator<(const _PaletteEntry &p_rhs) const { return name < p_rhs.name; } }; } // namespace void TileMapEditor::_update_palette() { if (!node) return; // Update the clear button clear_transform_button->set_disabled(!flip_h && !flip_v && !transpose); // Update the palette Vector selected = get_selected_tiles(); palette->clear(); manual_palette->clear(); manual_palette->hide(); Ref tileset = node->get_tileset(); if (tileset.is_null()) return; List tiles; tileset->get_tile_list(&tiles); if (tiles.empty()) return; float min_size = EDITOR_DEF(""editors/tile_map/preview_size"", 64); min_size *= EDSCALE; int hseparation = EDITOR_DEF(""editors/tile_map/palette_item_hseparation"", 8); bool show_tile_names = bool(EDITOR_DEF(""editors/tile_map/show_tile_names"", true)); bool show_tile_ids = bool(EDITOR_DEF(""editors/tile_map/show_tile_ids"", false)); bool sort_by_name = bool(EDITOR_DEF(""editors/tile_map/sort_tiles_by_name"", true)); palette->add_constant_override(""hseparation"", hseparation * EDSCALE); palette->add_constant_override(""vseparation"", 8 * EDSCALE); palette->set_fixed_icon_size(Size2(min_size, min_size)); palette->set_fixed_column_width(min_size * MAX(size_slider->get_value(), 1)); palette->set_same_column_width(true); manual_palette->set_fixed_icon_size(Size2(min_size, min_size)); manual_palette->set_same_column_width(true); String filter = search_box->get_text().strip_edges(); Vector<_PaletteEntry> entries; for (List::Element *E = tiles.front(); E; E = E->next()) { String name = tileset->tile_get_name(E->get()); if (name != """") { if (show_tile_ids) { if (sort_by_name) { name = name + "" - "" + itos(E->get()); } else { name = itos(E->get()) + "" - "" + name; } } } else { name = ""#"" + itos(E->get()); } if (filter != """" && !filter.is_subsequence_ofi(name)) continue; const _PaletteEntry entry = { E->get(), name }; entries.push_back(entry); } if (sort_by_name) { entries.sort(); } for (int i = 0; i < entries.size(); i++) { if (show_tile_names) { palette->add_item(entries[i].name); } else { palette->add_item(String()); } Ref tex = tileset->tile_get_texture(entries[i].id); if (tex.is_valid()) { Rect2 region = tileset->tile_get_region(entries[i].id); if (tileset->tile_get_tile_mode(entries[i].id) == TileSet::AUTO_TILE || tileset->tile_get_tile_mode(entries[i].id) == TileSet::ATLAS_TILE) { int spacing = tileset->autotile_get_spacing(entries[i].id); region.size = tileset->autotile_get_size(entries[i].id); region.position += (region.size + Vector2(spacing, spacing)) * tileset->autotile_get_icon_coordinate(entries[i].id); } // Transpose and flip palette->set_item_icon_transposed(palette->get_item_count() - 1, transpose); if (flip_h) { region.size.x = -region.size.x; } if (flip_v) { region.size.y = -region.size.y; } // Set region if (region.size != Size2()) palette->set_item_icon_region(palette->get_item_count() - 1, region); // Set icon palette->set_item_icon(palette->get_item_count() - 1, tex); // Modulation Color color = tileset->tile_get_modulate(entries[i].id); palette->set_item_icon_modulate(palette->get_item_count() - 1, color); } palette->set_item_metadata(palette->get_item_count() - 1, entries[i].id); } int sel_tile = selected.get(0); if (selected.get(0) != TileMap::INVALID_CELL) { set_selected_tiles(selected); sel_tile = selected.get(Math::rand() % selected.size()); } else { palette->select(0); } if (sel_tile != TileMap::INVALID_CELL) { if ((manual_autotile && tileset->tile_get_tile_mode(sel_tile) == TileSet::AUTO_TILE) || tileset->tile_get_tile_mode(sel_tile) == TileSet::ATLAS_TILE) { const Map &tiles2 = tileset->autotile_get_bitmask_map(sel_tile); Vector entries2; for (const Map::Element *E = tiles2.front(); E; E = E->next()) { entries2.push_back(E->key()); } entries2.sort(); Ref tex = tileset->tile_get_texture(sel_tile); for (int i = 0; i < entries2.size(); i++) { manual_palette->add_item(String()); if (tex.is_valid()) { Rect2 region = tileset->tile_get_region(sel_tile); int spacing = tileset->autotile_get_spacing(sel_tile); region.size = tileset->autotile_get_size(sel_tile); // !! region.position += (region.size + Vector2(spacing, spacing)) * entries2[i]; if (!region.has_no_area()) manual_palette->set_item_icon_region(manual_palette->get_item_count() - 1, region); manual_palette->set_item_icon(manual_palette->get_item_count() - 1, tex); } manual_palette->set_item_metadata(manual_palette->get_item_count() - 1, entries2[i]); } } } if (manual_palette->get_item_count() > 0) { // Only show the manual palette if at least tile exists in it int selected2 = manual_palette->get_current(); if (selected2 == -1) selected2 = 0; manual_palette->set_current(selected2); manual_palette->show(); } if (sel_tile != TileMap::INVALID_CELL && tileset->tile_get_tile_mode(sel_tile) == TileSet::AUTO_TILE) { manual_button->show(); } else { manual_button->hide(); } } void TileMapEditor::_pick_tile(const Point2 &p_pos) { int id = node->get_cell(p_pos.x, p_pos.y); if (id == TileMap::INVALID_CELL) return; if (search_box->get_text().strip_edges() != """") { search_box->set_text(""""); _update_palette(); } Vector selected; selected.push_back(id); set_selected_tiles(selected); flip_h = node->is_cell_x_flipped(p_pos.x, p_pos.y); flip_v = node->is_cell_y_flipped(p_pos.x, p_pos.y); transpose = node->is_cell_transposed(p_pos.x, p_pos.y); autotile_coord = node->get_cell_autotile_coord(p_pos.x, p_pos.y); _update_palette(); CanvasItemEditor::get_singleton()->update_viewport(); } PoolVector TileMapEditor::_bucket_fill(const Point2i &p_start, bool erase, bool preview) { int prev_id = node->get_cell(p_start.x, p_start.y); Vector ids; ids.push_back(TileMap::INVALID_CELL); if (!erase) { ids = get_selected_tiles(); if (ids.size() == 0 || ids[0] == TileMap::INVALID_CELL) return PoolVector(); } else if (prev_id == TileMap::INVALID_CELL) { return PoolVector(); } if (ids.size() == 1 && ids[0] == prev_id) { // Same ID, nothing to change return PoolVector(); } Rect2i r = node->get_used_rect(); int area = r.get_area(); if (preview) { // Test if we can re-use the result from preview bucket fill bool invalidate_cache = false; // Area changed if (r != bucket_cache_rect) _clear_bucket_cache(); // Cache grid is not initialized if (bucket_cache_visited == 0) { bucket_cache_visited = new bool[area]; invalidate_cache = true; } // Tile ID changed or position wasn't visited by the previous fill int loc = (p_start.x - r.position.x) + (p_start.y - r.position.y) * r.get_size().x; if (prev_id != bucket_cache_tile || !bucket_cache_visited[loc]) { invalidate_cache = true; } if (invalidate_cache) { for (int i = 0; i < area; ++i) bucket_cache_visited[i] = false; bucket_cache = PoolVector(); bucket_cache_tile = prev_id; bucket_cache_rect = r; bucket_queue.clear(); } } PoolVector points; Vector non_preview_cache; int count = 0; int limit = 0; if (preview) { limit = 1024; } else { bucket_queue.clear(); } bucket_queue.push_back(p_start); while (bucket_queue.size()) { Point2i n = bucket_queue.front()->get(); bucket_queue.pop_front(); if (!r.has_point(n)) continue; if (node->get_cell(n.x, n.y) == prev_id) { if (preview) { int loc = (n.x - r.position.x) + (n.y - r.position.y) * r.get_size().x; if (bucket_cache_visited[loc]) continue; bucket_cache_visited[loc] = true; bucket_cache.push_back(n); } else { if (non_preview_cache.find(n) >= 0) continue; points.push_back(n); non_preview_cache.push_back(n); } bucket_queue.push_back(Point2i(n.x, n.y + 1)); bucket_queue.push_back(Point2i(n.x, n.y - 1)); bucket_queue.push_back(Point2i(n.x + 1, n.y)); bucket_queue.push_back(Point2i(n.x - 1, n.y)); count++; } if (limit > 0 && count >= limit) { break; } } return preview ? bucket_cache : points; } void TileMapEditor::_fill_points(const PoolVector p_points, const Dictionary &p_op) { int len = p_points.size(); PoolVector::Read pr = p_points.read(); Vector ids = p_op[""id""]; bool xf = p_op[""flip_h""]; bool yf = p_op[""flip_v""]; bool tr = p_op[""transpose""]; for (int i = 0; i < len; i++) { _set_cell(pr[i], ids, xf, yf, tr); node->make_bitmask_area_dirty(pr[i]); } node->update_dirty_bitmask(); } void TileMapEditor::_erase_points(const PoolVector p_points) { int len = p_points.size(); PoolVector::Read pr = p_points.read(); for (int i = 0; i < len; i++) { _set_cell(pr[i], invalid_cell); } } void TileMapEditor::_select(const Point2i &p_from, const Point2i &p_to) { Point2i begin = p_from; Point2i end = p_to; if (begin.x > end.x) { SWAP(begin.x, end.x); } if (begin.y > end.y) { SWAP(begin.y, end.y); } rectangle.position = begin; rectangle.size = end - begin; CanvasItemEditor::get_singleton()->update_viewport(); } void TileMapEditor::_erase_selection() { if (!selection_active) return; for (int i = rectangle.position.y; i <= rectangle.position.y + rectangle.size.y; i++) { for (int j = rectangle.position.x; j <= rectangle.position.x + rectangle.size.x; j++) { _set_cell(Point2i(j, i), invalid_cell, false, false, false); } } } void TileMapEditor::_draw_cell(Control *p_viewport, int p_cell, const Point2i &p_point, bool p_flip_h, bool p_flip_v, bool p_transpose, const Point2i p_autotile_coord, const Transform2D &p_xform) { Ref t = node->get_tileset()->tile_get_texture(p_cell); if (t.is_null()) return; Vector2 tile_ofs = node->get_tileset()->tile_get_texture_offset(p_cell); Rect2 r = node->get_tileset()->tile_get_region(p_cell); if (node->get_tileset()->tile_get_tile_mode(p_cell) == TileSet::AUTO_TILE || node->get_tileset()->tile_get_tile_mode(p_cell) == TileSet::ATLAS_TILE) { Vector2 offset; int selected = manual_palette->get_current(); if ((manual_autotile || node->get_tileset()->tile_get_tile_mode(p_cell) == TileSet::ATLAS_TILE) && selected != -1) { offset = manual_palette->get_item_metadata(selected); } else { if (tool != TOOL_PASTING) { offset = node->get_tileset()->autotile_get_icon_coordinate(p_cell); } else { offset = p_autotile_coord; } } int spacing = node->get_tileset()->autotile_get_spacing(p_cell); r.size = node->get_tileset()->autotile_get_size(p_cell); r.position += (r.size + Vector2(spacing, spacing)) * offset; } Size2 sc = p_xform.get_scale(); Rect2 rect = Rect2(); rect.position = node->map_to_world(p_point) + node->get_cell_draw_offset(); if (r.has_no_area()) { rect.size = t->get_size(); } else { rect.size = r.size; } if (rect.size.y > rect.size.x) { if ((p_flip_h && (p_flip_v || p_transpose)) || (p_flip_v && !p_transpose)) tile_ofs.y += rect.size.y - rect.size.x; } else if (rect.size.y < rect.size.x) { if ((p_flip_v && (p_flip_h || p_transpose)) || (p_flip_h && !p_transpose)) tile_ofs.x += rect.size.x - rect.size.y; } if (p_transpose) { SWAP(tile_ofs.x, tile_ofs.y); } if (p_flip_h) { sc.x *= -1.0; tile_ofs.x *= -1.0; } if (p_flip_v) { sc.y *= -1.0; tile_ofs.y *= -1.0; } if (node->get_tile_origin() == TileMap::TILE_ORIGIN_TOP_LEFT) { rect.position += tile_ofs; } else if (node->get_tile_origin() == TileMap::TILE_ORIGIN_BOTTOM_LEFT) { Size2 cell_size = node->get_cell_size(); rect.position += tile_ofs; if (p_transpose) { if (p_flip_h) rect.position.x -= cell_size.x; else rect.position.x += cell_size.x; } else { if (p_flip_v) rect.position.y -= cell_size.y; else rect.position.y += cell_size.y; } } else if (node->get_tile_origin() == TileMap::TILE_ORIGIN_CENTER) { Size2 cell_size = node->get_cell_size(); rect.position += tile_ofs; if (p_flip_h) rect.position.x -= cell_size.x / 2; else rect.position.x += cell_size.x / 2; if (p_flip_v) rect.position.y -= cell_size.y / 2; else rect.position.y += cell_size.y / 2; } rect.position = p_xform.xform(rect.position); rect.size *= sc; Color modulate = node->get_tileset()->tile_get_modulate(p_cell); modulate.a = 0.5; if (r.has_no_area()) p_viewport->draw_texture_rect(t, rect, false, modulate, p_transpose); else p_viewport->draw_texture_rect_region(t, rect, r, modulate, p_transpose); } void TileMapEditor::_draw_fill_preview(Control *p_viewport, int p_cell, const Point2i &p_point, bool p_flip_h, bool p_flip_v, bool p_transpose, const Point2i p_autotile_coord, const Transform2D &p_xform) { PoolVector points = _bucket_fill(p_point, false, true); PoolVector::Read pr = points.read(); int len = points.size(); for (int i = 0; i < len; ++i) { _draw_cell(p_viewport, p_cell, pr[i], p_flip_h, p_flip_v, p_transpose, p_autotile_coord, p_xform); } } void TileMapEditor::_clear_bucket_cache() { if (bucket_cache_visited) { delete[] bucket_cache_visited; bucket_cache_visited = 0; } } void TileMapEditor::_update_copydata() { copydata.clear(); if (!selection_active) return; for (int i = rectangle.position.y; i <= rectangle.position.y + rectangle.size.y; i++) { for (int j = rectangle.position.x; j <= rectangle.position.x + rectangle.size.x; j++) { TileData tcd; tcd.cell = node->get_cell(j, i); if (tcd.cell != TileMap::INVALID_CELL) { tcd.pos = Point2i(j, i); tcd.flip_h = node->is_cell_x_flipped(j, i); tcd.flip_v = node->is_cell_y_flipped(j, i); tcd.transpose = node->is_cell_transposed(j, i); tcd.autotile_coord = node->get_cell_autotile_coord(j, i); } copydata.push_back(tcd); } } } static inline Vector line(int x0, int x1, int y0, int y1) { Vector points; float dx = ABS(x1 - x0); float dy = ABS(y1 - y0); int x = x0; int y = y0; int sx = x0 > x1 ? -1 : 1; int sy = y0 > y1 ? -1 : 1; if (dx > dy) { float err = dx / 2; for (; x != x1; x += sx) { points.push_back(Vector2(x, y)); err -= dy; if (err < 0) { y += sy; err += dx; } } } else { float err = dy / 2; for (; y != y1; y += sy) { points.push_back(Vector2(x, y)); err -= dx; if (err < 0) { x += sx; err += dy; } } } points.push_back(Vector2(x, y)); return points; } bool TileMapEditor::forward_gui_input(const Ref &p_event) { if (!node || !node->get_tileset().is_valid() || !node->is_visible_in_tree()) return false; Transform2D xform = CanvasItemEditor::get_singleton()->get_canvas_transform() * node->get_global_transform(); Transform2D xform_inv = xform.affine_inverse(); Ref mb = p_event; if (mb.is_valid()) { if (mb->get_button_index() == BUTTON_LEFT) { if (mb->is_pressed()) { if (Input::get_singleton()->is_key_pressed(KEY_SPACE)) return false; //drag if (tool == TOOL_NONE) { if (mb->get_shift()) { #ifdef APPLE_STYLE_KEYS if (mb->get_command()) #else if (mb->get_control()) #endif tool = TOOL_RECTANGLE_PAINT; else tool = TOOL_LINE_PAINT; selection_active = false; rectangle_begin = over_tile; return true; } #ifdef APPLE_STYLE_KEYS if (mb->get_command()) { #else if (mb->get_control()) { #endif tool = TOOL_PICKING; _pick_tile(over_tile); return true; } tool = TOOL_PAINTING; } if (tool == TOOL_PAINTING) { Vector ids = get_selected_tiles(); if (ids.size() > 0 && ids[0] != TileMap::INVALID_CELL) { tool = TOOL_PAINTING; _start_undo(TTR(""Paint TileMap"")); } } else if (tool == TOOL_PICKING) { _pick_tile(over_tile); } else if (tool == TOOL_SELECTING) { selection_active = true; rectangle_begin = over_tile; } return true; } else { // Mousebutton was released if (tool != TOOL_NONE) { if (tool == TOOL_PAINTING) { Vector ids = get_selected_tiles(); if (ids.size() > 0 && ids[0] != TileMap::INVALID_CELL) { _set_cell(over_tile, ids, flip_h, flip_v, transpose); _finish_undo(); paint_undo.clear(); } } else if (tool == TOOL_LINE_PAINT) { Vector ids = get_selected_tiles(); if (ids.size() > 0 && ids[0] != TileMap::INVALID_CELL) { _start_undo(TTR(""Line Draw"")); for (Map::Element *E = paint_undo.front(); E; E = E->next()) { _set_cell(E->key(), ids, flip_h, flip_v, transpose); } _finish_undo(); paint_undo.clear(); CanvasItemEditor::get_singleton()->update_viewport(); } } else if (tool == TOOL_RECTANGLE_PAINT) { Vector ids = get_selected_tiles(); if (ids.size() > 0 && ids[0] != TileMap::INVALID_CELL) { _start_undo(TTR(""Rectangle Paint"")); for (int i = rectangle.position.y; i <= rectangle.position.y + rectangle.size.y; i++) { for (int j = rectangle.position.x; j <= rectangle.position.x + rectangle.size.x; j++) { _set_cell(Point2i(j, i), ids, flip_h, flip_v, transpose); } } _finish_undo(); CanvasItemEditor::get_singleton()->update_viewport(); } } else if (tool == TOOL_PASTING) { Point2 ofs = over_tile - rectangle.position; Vector ids; _start_undo(TTR(""Paste"")); ids.push_back(0); for (List::Element *E = copydata.front(); E; E = E->next()) { ids.write[0] = E->get().cell; _set_cell(E->get().pos + ofs, ids, E->get().flip_h, E->get().flip_v, E->get().transpose, E->get().autotile_coord); } _finish_undo(); CanvasItemEditor::get_singleton()->update_viewport(); return true; // We want to keep the Pasting tool } else if (tool == TOOL_SELECTING) { CanvasItemEditor::get_singleton()->update_viewport(); } else if (tool == TOOL_BUCKET) { PoolVector points = _bucket_fill(over_tile); if (points.size() == 0) return false; _start_undo(TTR(""Bucket Fill"")); Dictionary op; op[""id""] = get_selected_tiles(); op[""flip_h""] = flip_h; op[""flip_v""] = flip_v; op[""transpose""] = transpose; _fill_points(points, op); _finish_undo(); // We want to keep the bucket-tool active return true; } tool = TOOL_NONE; return true; } } } else if (mb->get_button_index() == BUTTON_RIGHT) { if (mb->is_pressed()) { if (tool == TOOL_SELECTING || selection_active) { tool = TOOL_NONE; selection_active = false; CanvasItemEditor::get_singleton()->update_viewport(); return true; } if (tool == TOOL_PASTING) { tool = TOOL_NONE; copydata.clear(); CanvasItemEditor::get_singleton()->update_viewport(); return true; } if (tool == TOOL_NONE) { paint_undo.clear(); Point2 local = node->world_to_map(xform_inv.xform(mb->get_position())); _start_undo(TTR(""Erase TileMap"")); if (mb->get_shift()) { #ifdef APPLE_STYLE_KEYS if (mb->get_command()) #else if (mb->get_control()) #endif tool = TOOL_RECTANGLE_ERASE; else tool = TOOL_LINE_ERASE; selection_active = false; rectangle_begin = local; } else { tool = TOOL_ERASING; _set_cell(local, invalid_cell); } return true; } } else { if (tool == TOOL_ERASING || tool == TOOL_RECTANGLE_ERASE || tool == TOOL_LINE_ERASE) { _finish_undo(); if (tool == TOOL_RECTANGLE_ERASE || tool == TOOL_LINE_ERASE) { CanvasItemEditor::get_singleton()->update_viewport(); } tool = TOOL_NONE; return true; } else if (tool == TOOL_BUCKET) { Vector ids; ids.push_back(node->get_cell(over_tile.x, over_tile.y)); Dictionary pop; pop[""id""] = ids; pop[""flip_h""] = node->is_cell_x_flipped(over_tile.x, over_tile.y); pop[""flip_v""] = node->is_cell_y_flipped(over_tile.x, over_tile.y); pop[""transpose""] = node->is_cell_transposed(over_tile.x, over_tile.y); PoolVector points = _bucket_fill(over_tile, true); if (points.size() == 0) return false; undo_redo->create_action(TTR(""Bucket Fill"")); undo_redo->add_do_method(this, ""_erase_points"", points); undo_redo->add_undo_method(this, ""_fill_points"", points, pop); undo_redo->commit_action(); } } } } Ref mm = p_event; if (mm.is_valid()) { Point2i new_over_tile = node->world_to_map(xform_inv.xform(mm->get_position())); Point2i old_over_tile = over_tile; if (new_over_tile != over_tile) { over_tile = new_over_tile; CanvasItemEditor::get_singleton()->update_viewport(); } if (show_tile_info) { int tile_under = node->get_cell(over_tile.x, over_tile.y); String tile_name = ""none""; if (node->get_tileset()->has_tile(tile_under)) tile_name = node->get_tileset()->tile_get_name(tile_under); tile_info->set_text(String::num(over_tile.x) + "", "" + String::num(over_tile.y) + "" ["" + tile_name + ""]""); } if (tool == TOOL_PAINTING) { // Paint using bresenham line to prevent holes in painting if the user moves fast Vector points = line(old_over_tile.x, over_tile.x, old_over_tile.y, over_tile.y); Vector ids = get_selected_tiles(); for (int i = 0; i < points.size(); ++i) { Point2i pos = points[i]; if (!paint_undo.has(pos)) { paint_undo[pos] = _get_op_from_cell(pos); } _set_cell(pos, ids, flip_h, flip_v, transpose); } return true; } if (tool == TOOL_ERASING) { // erase using bresenham line to prevent holes in painting if the user moves fast Vector points = line(old_over_tile.x, over_tile.x, old_over_tile.y, over_tile.y); for (int i = 0; i < points.size(); ++i) { Point2i pos = points[i]; _set_cell(pos, invalid_cell); } return true; } if (tool == TOOL_SELECTING) { _select(rectangle_begin, over_tile); return true; } if (tool == TOOL_LINE_PAINT || tool == TOOL_LINE_ERASE) { Vector ids = get_selected_tiles(); Vector tmp_cell; bool erasing = (tool == TOOL_LINE_ERASE); tmp_cell.push_back(0); if (erasing && paint_undo.size()) { for (Map::Element *E = paint_undo.front(); E; E = E->next()) { tmp_cell.write[0] = E->get().idx; _set_cell(E->key(), tmp_cell, E->get().xf, E->get().yf, E->get().tr); } } paint_undo.clear(); if (ids.size() > 0 && ids[0] != TileMap::INVALID_CELL) { Vector points = line(rectangle_begin.x, over_tile.x, rectangle_begin.y, over_tile.y); for (int i = 0; i < points.size(); i++) { paint_undo[points[i]] = _get_op_from_cell(points[i]); if (erasing) _set_cell(points[i], invalid_cell); } CanvasItemEditor::get_singleton()->update_viewport(); } return true; } if (tool == TOOL_RECTANGLE_PAINT || tool == TOOL_RECTANGLE_ERASE) { Vector tmp_cell; tmp_cell.push_back(0); _select(rectangle_begin, over_tile); if (tool == TOOL_RECTANGLE_ERASE) { if (paint_undo.size()) { for (Map::Element *E = paint_undo.front(); E; E = E->next()) { tmp_cell.write[0] = E->get().idx; _set_cell(E->key(), tmp_cell, E->get().xf, E->get().yf, E->get().tr); } } paint_undo.clear(); for (int i = rectangle.position.y; i <= rectangle.position.y + rectangle.size.y; i++) { for (int j = rectangle.position.x; j <= rectangle.position.x + rectangle.size.x; j++) { Point2i tile = Point2i(j, i); paint_undo[tile] = _get_op_from_cell(tile); _set_cell(tile, invalid_cell); } } } return true; } if (tool == TOOL_PICKING && Input::get_singleton()->is_mouse_button_pressed(BUTTON_LEFT)) { _pick_tile(over_tile); return true; } } Ref k = p_event; if (k.is_valid() && k->is_pressed()) { if (k->get_scancode() == KEY_ESCAPE) { if (tool == TOOL_PASTING) copydata.clear(); else if (tool == TOOL_SELECTING || selection_active) selection_active = false; tool = TOOL_NONE; CanvasItemEditor::get_singleton()->update_viewport(); return true; } if (!mouse_over) { // Editor shortcuts should not fire if mouse not in viewport return false; } if (ED_IS_SHORTCUT(""tile_map_editor/paint_tile"", p_event)) { // NOTE: We do not set tool = TOOL_PAINTING as this begins painting // immediately without pressing the left mouse button first tool = TOOL_NONE; CanvasItemEditor::get_singleton()->update_viewport(); return true; } if (ED_IS_SHORTCUT(""tile_map_editor/bucket_fill"", p_event)) { tool = TOOL_BUCKET; CanvasItemEditor::get_singleton()->update_viewport(); return true; } if (ED_IS_SHORTCUT(""tile_map_editor/erase_selection"", p_event)) { _menu_option(OPTION_ERASE_SELECTION); return true; } if (ED_IS_SHORTCUT(""tile_map_editor/select"", p_event)) { tool = TOOL_SELECTING; selection_active = false; CanvasItemEditor::get_singleton()->update_viewport(); return true; } if (ED_IS_SHORTCUT(""tile_map_editor/copy_selection"", p_event)) { _update_copydata(); if (selection_active) { tool = TOOL_PASTING; CanvasItemEditor::get_singleton()->update_viewport(); return true; } } if (ED_IS_SHORTCUT(""tile_map_editor/cut_selection"", p_event)) { if (selection_active) { _update_copydata(); _start_undo(TTR(""Cut Selection"")); _erase_selection(); _finish_undo(); selection_active = false; tool = TOOL_PASTING; CanvasItemEditor::get_singleton()->update_viewport(); return true; } } if (ED_IS_SHORTCUT(""tile_map_editor/find_tile"", p_event)) { search_box->select_all(); search_box->grab_focus(); return true; } if (ED_IS_SHORTCUT(""tile_map_editor/mirror_x"", p_event)) { flip_h = !flip_h; _update_palette(); CanvasItemEditor::get_singleton()->update_viewport(); return true; } if (ED_IS_SHORTCUT(""tile_map_editor/mirror_y"", p_event)) { flip_v = !flip_v; _update_palette(); CanvasItemEditor::get_singleton()->update_viewport(); return true; } if (ED_IS_SHORTCUT(""tile_map_editor/transpose"", p_event)) { transpose = !transpose; _update_palette(); CanvasItemEditor::get_singleton()->update_viewport(); return true; } } return false; } void TileMapEditor::forward_canvas_draw_over_viewport(Control *p_overlay) { if (!node) return; Transform2D cell_xf = node->get_cell_transform(); Transform2D xform = CanvasItemEditor::get_singleton()->get_canvas_transform() * node->get_global_transform(); Transform2D xform_inv = xform.affine_inverse(); Size2 screen_size = p_overlay->get_size(); { Rect2 aabb; aabb.position = node->world_to_map(xform_inv.xform(Vector2())); aabb.expand_to(node->world_to_map(xform_inv.xform(Vector2(0, screen_size.height)))); aabb.expand_to(node->world_to_map(xform_inv.xform(Vector2(screen_size.width, 0)))); aabb.expand_to(node->world_to_map(xform_inv.xform(screen_size))); Rect2i si = aabb.grow(1.0); if (node->get_half_offset() != TileMap::HALF_OFFSET_X) { int max_lines = 2000; //avoid crash if size too smal for (int i = (si.position.x) - 1; i <= (si.position.x + si.size.x); i++) { Vector2 from = xform.xform(node->map_to_world(Vector2(i, si.position.y))); Vector2 to = xform.xform(node->map_to_world(Vector2(i, si.position.y + si.size.y + 1))); Color col = i == 0 ? Color(1, 0.8, 0.2, 0.5) : Color(1, 0.3, 0.1, 0.2); p_overlay->draw_line(from, to, col, 1); if (max_lines-- == 0) break; } } else { int max_lines = 10000; //avoid crash if size too smal for (int i = (si.position.x) - 1; i <= (si.position.x + si.size.x); i++) { for (int j = (si.position.y) - 1; j <= (si.position.y + si.size.y); j++) { Vector2 ofs; if (ABS(j) & 1) { ofs = cell_xf[0] * 0.5; } Vector2 from = xform.xform(node->map_to_world(Vector2(i, j), true) + ofs); Vector2 to = xform.xform(node->map_to_world(Vector2(i, j + 1), true) + ofs); Color col = i == 0 ? Color(1, 0.8, 0.2, 0.5) : Color(1, 0.3, 0.1, 0.2); p_overlay->draw_line(from, to, col, 1); if (max_lines-- == 0) break; } } } int max_lines = 10000; //avoid crash if size too smal if (node->get_half_offset() != TileMap::HALF_OFFSET_Y) { for (int i = (si.position.y) - 1; i <= (si.position.y + si.size.y); i++) { Vector2 from = xform.xform(node->map_to_world(Vector2(si.position.x, i))); Vector2 to = xform.xform(node->map_to_world(Vector2(si.position.x + si.size.x + 1, i))); Color col = i == 0 ? Color(1, 0.8, 0.2, 0.5) : Color(1, 0.3, 0.1, 0.2); p_overlay->draw_line(from, to, col, 1); if (max_lines-- == 0) break; } } else { for (int i = (si.position.y) - 1; i <= (si.position.y + si.size.y); i++) { for (int j = (si.position.x) - 1; j <= (si.position.x + si.size.x); j++) { Vector2 ofs; if (ABS(j) & 1) { ofs = cell_xf[1] * 0.5; } Vector2 from = xform.xform(node->map_to_world(Vector2(j, i), true) + ofs); Vector2 to = xform.xform(node->map_to_world(Vector2(j + 1, i), true) + ofs); Color col = i == 0 ? Color(1, 0.8, 0.2, 0.5) : Color(1, 0.3, 0.1, 0.2); p_overlay->draw_line(from, to, col, 1); if (max_lines-- == 0) break; } } } } if (selection_active) { Vector points; points.push_back(xform.xform(node->map_to_world((rectangle.position)))); points.push_back(xform.xform(node->map_to_world((rectangle.position + Point2(rectangle.size.x + 1, 0))))); points.push_back(xform.xform(node->map_to_world((rectangle.position + Point2(rectangle.size.x + 1, rectangle.size.y + 1))))); points.push_back(xform.xform(node->map_to_world((rectangle.position + Point2(0, rectangle.size.y + 1))))); p_overlay->draw_colored_polygon(points, Color(0.2, 0.8, 1, 0.4)); } if (mouse_over) { Vector2 endpoints[4] = { node->map_to_world(over_tile, true), node->map_to_world((over_tile + Point2(1, 0)), true), node->map_to_world((over_tile + Point2(1, 1)), true), node->map_to_world((over_tile + Point2(0, 1)), true) }; for (int i = 0; i < 4; i++) { if (node->get_half_offset() == TileMap::HALF_OFFSET_X && ABS(over_tile.y) & 1) endpoints[i] += cell_xf[0] * 0.5; if (node->get_half_offset() == TileMap::HALF_OFFSET_Y && ABS(over_tile.x) & 1) endpoints[i] += cell_xf[1] * 0.5; endpoints[i] = xform.xform(endpoints[i]); } Color col; if (node->get_cell(over_tile.x, over_tile.y) != TileMap::INVALID_CELL) col = Color(0.2, 0.8, 1.0, 0.8); else col = Color(1.0, 0.4, 0.2, 0.8); for (int i = 0; i < 4; i++) p_overlay->draw_line(endpoints[i], endpoints[(i + 1) % 4], col, 2); bool bucket_preview = EditorSettings::get_singleton()->get(""editors/tile_map/bucket_fill_preview""); if (tool == TOOL_SELECTING || tool == TOOL_PICKING || !bucket_preview) { return; } if (tool == TOOL_LINE_PAINT) { if (paint_undo.empty()) return; Vector ids = get_selected_tiles(); if (ids.size() == 1 && ids[0] == TileMap::INVALID_CELL) return; for (Map::Element *E = paint_undo.front(); E; E = E->next()) { _draw_cell(p_overlay, ids[0], E->key(), flip_h, flip_v, transpose, autotile_coord, xform); } } else if (tool == TOOL_RECTANGLE_PAINT) { Vector ids = get_selected_tiles(); if (ids.size() == 1 && ids[0] == TileMap::INVALID_CELL) return; for (int i = rectangle.position.y; i <= rectangle.position.y + rectangle.size.y; i++) { for (int j = rectangle.position.x; j <= rectangle.position.x + rectangle.size.x; j++) { _draw_cell(p_overlay, ids[0], Point2i(j, i), flip_h, flip_v, transpose, autotile_coord, xform); } } } else if (tool == TOOL_PASTING) { if (copydata.empty()) return; Ref ts = node->get_tileset(); if (ts.is_null()) return; Point2 ofs = over_tile - rectangle.position; for (List::Element *E = copydata.front(); E; E = E->next()) { if (!ts->has_tile(E->get().cell)) continue; TileData tcd = E->get(); _draw_cell(p_overlay, tcd.cell, tcd.pos + ofs, tcd.flip_h, tcd.flip_v, tcd.transpose, tcd.autotile_coord, xform); } Rect2i duplicate = rectangle; duplicate.position = over_tile; Vector points; points.push_back(xform.xform(node->map_to_world(duplicate.position))); points.push_back(xform.xform(node->map_to_world((duplicate.position + Point2(duplicate.size.x + 1, 0))))); points.push_back(xform.xform(node->map_to_world((duplicate.position + Point2(duplicate.size.x + 1, duplicate.size.y + 1))))); points.push_back(xform.xform(node->map_to_world((duplicate.position + Point2(0, duplicate.size.y + 1))))); p_overlay->draw_colored_polygon(points, Color(0.2, 1.0, 0.8, 0.2)); } else if (tool == TOOL_BUCKET) { Vector tiles = get_selected_tiles(); _draw_fill_preview(p_overlay, tiles[0], over_tile, flip_h, flip_v, transpose, autotile_coord, xform); } else { Vector st = get_selected_tiles(); if (st.size() == 1 && st[0] == TileMap::INVALID_CELL) return; _draw_cell(p_overlay, st[0], over_tile, flip_h, flip_v, transpose, autotile_coord, xform); } } } void TileMapEditor::edit(Node *p_tile_map) { search_box->set_text(""""); if (!canvas_item_editor_viewport) { canvas_item_editor_viewport = CanvasItemEditor::get_singleton()->get_viewport_control(); } if (node) node->disconnect(""settings_changed"", this, ""_tileset_settings_changed""); if (p_tile_map) { node = Object::cast_to(p_tile_map); if (!canvas_item_editor_viewport->is_connected(""mouse_entered"", this, ""_canvas_mouse_enter"")) canvas_item_editor_viewport->connect(""mouse_entered"", this, ""_canvas_mouse_enter""); if (!canvas_item_editor_viewport->is_connected(""mouse_exited"", this, ""_canvas_mouse_exit"")) canvas_item_editor_viewport->connect(""mouse_exited"", this, ""_canvas_mouse_exit""); _update_palette(); } else { node = NULL; if (canvas_item_editor_viewport->is_connected(""mouse_entered"", this, ""_canvas_mouse_enter"")) canvas_item_editor_viewport->disconnect(""mouse_entered"", this, ""_canvas_mouse_enter""); if (canvas_item_editor_viewport->is_connected(""mouse_exited"", this, ""_canvas_mouse_exit"")) canvas_item_editor_viewport->disconnect(""mouse_exited"", this, ""_canvas_mouse_exit""); _update_palette(); } if (node) node->connect(""settings_changed"", this, ""_tileset_settings_changed""); _clear_bucket_cache(); } void TileMapEditor::_tileset_settings_changed() { _update_palette(); CanvasItemEditor::get_singleton()->update_viewport(); } void TileMapEditor::_icon_size_changed(float p_value) { if (node) { palette->set_icon_scale(p_value); manual_palette->set_icon_scale(p_value); _update_palette(); } } void TileMapEditor::_bind_methods() { ClassDB::bind_method(D_METHOD(""_manual_toggled""), &TileMapEditor::_manual_toggled); ClassDB::bind_method(D_METHOD(""_text_entered""), &TileMapEditor::_text_entered); ClassDB::bind_method(D_METHOD(""_text_changed""), &TileMapEditor::_text_changed); ClassDB::bind_method(D_METHOD(""_sbox_input""), &TileMapEditor::_sbox_input); ClassDB::bind_method(D_METHOD(""_menu_option""), &TileMapEditor::_menu_option); ClassDB::bind_method(D_METHOD(""_canvas_mouse_enter""), &TileMapEditor::_canvas_mouse_enter); ClassDB::bind_method(D_METHOD(""_canvas_mouse_exit""), &TileMapEditor::_canvas_mouse_exit); ClassDB::bind_method(D_METHOD(""_tileset_settings_changed""), &TileMapEditor::_tileset_settings_changed); ClassDB::bind_method(D_METHOD(""_rotate""), &TileMapEditor::_rotate); ClassDB::bind_method(D_METHOD(""_flip_horizontal""), &TileMapEditor::_flip_horizontal); ClassDB::bind_method(D_METHOD(""_flip_vertical""), &TileMapEditor::_flip_vertical); ClassDB::bind_method(D_METHOD(""_clear_transform""), &TileMapEditor::_clear_transform); ClassDB::bind_method(D_METHOD(""_palette_selected""), &TileMapEditor::_palette_selected); ClassDB::bind_method(D_METHOD(""_palette_multi_selected""), &TileMapEditor::_palette_multi_selected); ClassDB::bind_method(D_METHOD(""_fill_points""), &TileMapEditor::_fill_points); ClassDB::bind_method(D_METHOD(""_erase_points""), &TileMapEditor::_erase_points); ClassDB::bind_method(D_METHOD(""_icon_size_changed""), &TileMapEditor::_icon_size_changed); } TileMapEditor::CellOp TileMapEditor::_get_op_from_cell(const Point2i &p_pos) { CellOp op; op.idx = node->get_cell(p_pos.x, p_pos.y); if (op.idx != TileMap::INVALID_CELL) { if (node->is_cell_x_flipped(p_pos.x, p_pos.y)) op.xf = true; if (node->is_cell_y_flipped(p_pos.x, p_pos.y)) op.yf = true; if (node->is_cell_transposed(p_pos.x, p_pos.y)) op.tr = true; op.ac = node->get_cell_autotile_coord(p_pos.x, p_pos.y); } return op; } void TileMapEditor::_rotate(int steps) { const bool normal_rotation_matrix[][3] = { { false, false, false }, { true, true, false }, { false, true, true }, { true, false, true } }; const bool mirrored_rotation_matrix[][3] = { { false, true, false }, { true, true, true }, { false, false, true }, { true, false, false } }; if (transpose ^ flip_h ^ flip_v) { // Odd number of flags activated = mirrored rotation for (int i = 0; i < 4; i++) { if (transpose == mirrored_rotation_matrix[i][0] && flip_h == mirrored_rotation_matrix[i][1] && flip_v == mirrored_rotation_matrix[i][2]) { int new_id = Math::wrapi(i + steps, 0, 4); transpose = mirrored_rotation_matrix[new_id][0]; flip_h = mirrored_rotation_matrix[new_id][1]; flip_v = mirrored_rotation_matrix[new_id][2]; break; } } } else { // Even number of flags activated = normal rotation for (int i = 0; i < 4; i++) { if (transpose == normal_rotation_matrix[i][0] && flip_h == normal_rotation_matrix[i][1] && flip_v == normal_rotation_matrix[i][2]) { int new_id = Math::wrapi(i + steps, 0, 4); transpose = normal_rotation_matrix[new_id][0]; flip_h = normal_rotation_matrix[new_id][1]; flip_v = normal_rotation_matrix[new_id][2]; break; } } } _update_palette(); } void TileMapEditor::_flip_horizontal() { flip_h = !flip_h; _update_palette(); } void TileMapEditor::_flip_vertical() { flip_v = !flip_v; _update_palette(); } void TileMapEditor::_clear_transform() { transpose = false; flip_h = false; flip_v = false; _update_palette(); } TileMapEditor::TileMapEditor(EditorNode *p_editor) { node = NULL; manual_autotile = false; manual_position = Vector2(0, 0); canvas_item_editor_viewport = NULL; editor = p_editor; undo_redo = editor->get_undo_redo(); tool = TOOL_NONE; selection_active = false; mouse_over = false; show_tile_info = true; flip_h = false; flip_v = false; transpose = false; bucket_cache_tile = -1; bucket_cache_visited = 0; invalid_cell.resize(1); invalid_cell.write[0] = TileMap::INVALID_CELL; ED_SHORTCUT(""tile_map_editor/erase_selection"", TTR(""Erase Selection""), KEY_DELETE); ED_SHORTCUT(""tile_map_editor/find_tile"", TTR(""Find Tile""), KEY_MASK_CMD + KEY_F); ED_SHORTCUT(""tile_map_editor/transpose"", TTR(""Transpose""), KEY_T); ED_SHORTCUT(""tile_map_editor/mirror_x"", TTR(""Mirror X""), KEY_A); ED_SHORTCUT(""tile_map_editor/mirror_y"", TTR(""Mirror Y""), KEY_S); HBoxContainer *tool_hb = memnew(HBoxContainer); add_child(tool_hb); manual_button = memnew(CheckBox); manual_button->set_text(""Disable Autotile""); manual_button->connect(""toggled"", this, ""_manual_toggled""); add_child(manual_button); search_box = memnew(LineEdit); search_box->set_h_size_flags(SIZE_EXPAND_FILL); search_box->connect(""text_entered"", this, ""_text_entered""); search_box->connect(""text_changed"", this, ""_text_changed""); search_box->connect(""gui_input"", this, ""_sbox_input""); add_child(search_box); size_slider = memnew(HSlider); size_slider->set_h_size_flags(SIZE_EXPAND_FILL); size_slider->set_min(0.1f); size_slider->set_max(4.0f); size_slider->set_step(0.1f); size_slider->set_value(1.0f); size_slider->connect(""value_changed"", this, ""_icon_size_changed""); add_child(size_slider); int mw = EDITOR_DEF(""editors/tile_map/palette_min_width"", 80); VSplitContainer *palette_container = memnew(VSplitContainer); palette_container->set_v_size_flags(SIZE_EXPAND_FILL); palette_container->set_custom_minimum_size(Size2(mw, 0)); add_child(palette_container); // Add tile palette palette = memnew(ItemList); palette->set_h_size_flags(SIZE_EXPAND_FILL); palette->set_v_size_flags(SIZE_EXPAND_FILL); palette->set_max_columns(0); palette->set_icon_mode(ItemList::ICON_MODE_TOP); palette->set_max_text_lines(2); palette->set_select_mode(ItemList::SELECT_MULTI); palette->connect(""item_selected"", this, ""_palette_selected""); palette->connect(""multi_selected"", this, ""_palette_multi_selected""); palette_container->add_child(palette); // Add autotile override palette manual_palette = memnew(ItemList); manual_palette->set_h_size_flags(SIZE_EXPAND_FILL); manual_palette->set_v_size_flags(SIZE_EXPAND_FILL); manual_palette->set_max_columns(0); manual_palette->set_icon_mode(ItemList::ICON_MODE_TOP); manual_palette->set_max_text_lines(2); manual_palette->hide(); palette_container->add_child(manual_palette); // Add menu items toolbar = memnew(HBoxContainer); toolbar->set_h_size_flags(SIZE_EXPAND_FILL); toolbar->set_alignment(BoxContainer::ALIGN_END); toolbar->hide(); CanvasItemEditor::get_singleton()->add_control_to_menu_panel(toolbar); // Tile position tile_info = memnew(Label); toolbar->add_child(tile_info); options = memnew(MenuButton); options->set_text(""TileMap""); options->set_icon(EditorNode::get_singleton()->get_gui_base()->get_icon(""TileMap"", ""EditorIcons"")); options->set_process_unhandled_key_input(false); PopupMenu *p = options->get_popup(); p->add_shortcut(ED_SHORTCUT(""tile_map_editor/paint_tile"", TTR(""Paint Tile""), KEY_P), OPTION_PAINTING); p->add_shortcut(ED_SHORTCUT(""tile_map_editor/bucket_fill"", TTR(""Bucket Fill""), KEY_G), OPTION_BUCKET); p->add_separator(); p->add_item(TTR(""Pick Tile""), OPTION_PICK_TILE, KEY_CONTROL); p->add_separator(); p->add_shortcut(ED_SHORTCUT(""tile_map_editor/select"", TTR(""Select""), KEY_MASK_CMD + KEY_B), OPTION_SELECT); p->add_shortcut(ED_SHORTCUT(""tile_map_editor/cut_selection"", TTR(""Cut Selection""), KEY_MASK_CMD + KEY_X), OPTION_CUT); p->add_shortcut(ED_SHORTCUT(""tile_map_editor/copy_selection"", TTR(""Copy Selection""), KEY_MASK_CMD + KEY_C), OPTION_COPY); p->add_shortcut(ED_GET_SHORTCUT(""tile_map_editor/erase_selection""), OPTION_ERASE_SELECTION); p->add_separator(); p->add_item(TTR(""Fix Invalid Tiles""), OPTION_FIX_INVALID); p->connect(""id_pressed"", this, ""_menu_option""); toolbar->add_child(options); rotate_left_button = memnew(ToolButton); rotate_left_button->set_tooltip(TTR(""Rotate left"")); rotate_left_button->set_focus_mode(FOCUS_NONE); rotate_left_button->connect(""pressed"", this, ""_rotate"", varray(-1)); tool_hb->add_child(rotate_left_button); rotate_right_button = memnew(ToolButton); rotate_right_button->set_tooltip(TTR(""Rotate right"")); rotate_right_button->set_focus_mode(FOCUS_NONE); rotate_right_button->connect(""pressed"", this, ""_rotate"", varray(1)); tool_hb->add_child(rotate_right_button); flip_horizontal_button = memnew(ToolButton); flip_horizontal_button->set_tooltip(TTR(""Flip horizontally"")); flip_horizontal_button->set_focus_mode(FOCUS_NONE); flip_horizontal_button->connect(""pressed"", this, ""_flip_horizontal""); tool_hb->add_child(flip_horizontal_button); flip_vertical_button = memnew(ToolButton); flip_vertical_button->set_tooltip(TTR(""Flip vertically"")); flip_vertical_button->set_focus_mode(FOCUS_NONE); flip_vertical_button->connect(""pressed"", this, ""_flip_vertical""); tool_hb->add_child(flip_vertical_button); clear_transform_button = memnew(ToolButton); clear_transform_button->set_tooltip(TTR(""Clear transform"")); clear_transform_button->set_focus_mode(FOCUS_NONE); clear_transform_button->connect(""pressed"", this, ""_clear_transform""); tool_hb->add_child(clear_transform_button); clear_transform_button->set_disabled(true); } TileMapEditor::~TileMapEditor() { _clear_bucket_cache(); copydata.clear(); } /////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////// void TileMapEditorPlugin::_notification(int p_what) { if (p_what == EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED) { switch ((int)EditorSettings::get_singleton()->get(""editors/tile_map/editor_side"")) { case 0: { // Left. CanvasItemEditor::get_singleton()->get_palette_split()->move_child(tile_map_editor, 0); } break; case 1: { // Right. CanvasItemEditor::get_singleton()->get_palette_split()->move_child(tile_map_editor, 1); } break; } } } void TileMapEditorPlugin::edit(Object *p_object) { tile_map_editor->edit(Object::cast_to(p_object)); } bool TileMapEditorPlugin::handles(Object *p_object) const { return p_object->is_class(""TileMap""); } void TileMapEditorPlugin::make_visible(bool p_visible) { if (p_visible) { tile_map_editor->show(); tile_map_editor->get_toolbar()->show(); } else { tile_map_editor->hide(); tile_map_editor->get_toolbar()->hide(); tile_map_editor->edit(NULL); } } TileMapEditorPlugin::TileMapEditorPlugin(EditorNode *p_node) { EDITOR_DEF(""editors/tile_map/preview_size"", 64); EDITOR_DEF(""editors/tile_map/palette_item_hseparation"", 8); EDITOR_DEF(""editors/tile_map/show_tile_names"", true); EDITOR_DEF(""editors/tile_map/show_tile_ids"", false); EDITOR_DEF(""editors/tile_map/sort_tiles_by_name"", true); EDITOR_DEF(""editors/tile_map/bucket_fill_preview"", true); EDITOR_DEF(""editors/tile_map/show_tile_info_on_hover"", true); EDITOR_DEF(""editors/tile_map/editor_side"", 1); EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::INT, ""editors/tile_map/editor_side"", PROPERTY_HINT_ENUM, ""Left,Right"")); tile_map_editor = memnew(TileMapEditor(p_node)); switch ((int)EditorSettings::get_singleton()->get(""editors/tile_map/editor_side"")) { case 0: { // Left. add_control_to_container(CONTAINER_CANVAS_EDITOR_SIDE_LEFT, tile_map_editor); } break; case 1: { // Right. add_control_to_container(CONTAINER_CANVAS_EDITOR_SIDE_RIGHT, tile_map_editor); } break; } tile_map_editor->hide(); } TileMapEditorPlugin::~TileMapEditorPlugin() { } ",16282,True,3124.2562639269922,median "// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //***************************************************************************** // CorHost.cpp // // Implementation for the meta data dispenser code. // //***************************************************************************** #include ""common.h"" #include ""mscoree.h"" #include ""corhost.h"" #include ""excep.h"" #include ""threads.h"" #include ""jitinterface.h"" #include ""eeconfig.h"" #include ""dbginterface.h"" #include ""ceemain.h"" #include ""hosting.h"" #include ""eepolicy.h"" #include ""clrex.h"" #include ""comcallablewrapper.h"" #include ""invokeutil.h"" #include ""appdomain.inl"" #include ""vars.hpp"" #include ""comdelegate.h"" #include ""dllimportcallback.h"" #include ""eventtrace.h"" #include ""win32threadpool.h"" #include ""eventtrace.h"" #include ""finalizerthread.h"" #include ""threadsuspend.h"" #ifndef FEATURE_PAL #include ""dwreport.h"" #endif // !FEATURE_PAL #include ""stringarraylist.h"" #ifdef FEATURE_PERFTRACING #include ""eventpipe.h"" #endif // FEATURE_PERFTRACING #ifdef FEATURE_COMINTEROP #include ""winrttypenameconverter.h"" #endif GVAL_IMPL_INIT(DWORD, g_fHostConfig, 0); #ifndef __GNUC__ EXTERN_C __declspec(thread) ThreadLocalInfo gCurrentThreadInfo; #else // !__GNUC__ EXTERN_C __thread ThreadLocalInfo gCurrentThreadInfo; #endif // !__GNUC__ #ifndef FEATURE_PAL EXTERN_C UINT32 _tls_index; #else // FEATURE_PAL UINT32 _tls_index = 0; #endif // FEATURE_PAL #ifndef DACCESS_COMPILE extern void STDMETHODCALLTYPE EEShutDown(BOOL fIsDllUnloading); extern HRESULT STDAPICALLTYPE CoInitializeEE(DWORD fFlags); extern void PrintToStdOutA(const char *pszString); extern void PrintToStdOutW(const WCHAR *pwzString); extern BOOL g_fEEHostedStartup; //*************************************************************************** ULONG CorRuntimeHostBase::m_Version = 0; #endif // !DAC typedef DPTR(CONNID) PTR_CONNID; // Keep track connection id and name #ifndef DACCESS_COMPILE // *** ICorRuntimeHost methods *** CorHost2::CorHost2() : m_fFirstToLoadCLR(FALSE), m_fStarted(FALSE), m_fAppDomainCreated(FALSE) { LIMITED_METHOD_CONTRACT; } static DangerousNonHostedSpinLock lockOnlyOneToInvokeStart; STDMETHODIMP CorHost2::Start() { CONTRACTL { NOTHROW; GC_TRIGGERS; ENTRY_POINT; }CONTRACTL_END; HRESULT hr; BEGIN_ENTRYPOINT_NOTHROW; // Ensure that only one thread at a time gets in here DangerousNonHostedSpinLockHolder lockHolder(&lockOnlyOneToInvokeStart); // To provide the complete semantic of Start/Stop in context of a given host, we check m_fStarted and let // them invoke the Start only if they have not already. Likewise, they can invoke the Stop method // only if they have invoked Start prior to that. // // This prevents a host from invoking Stop twice and hitting the refCount to zero, when another // host is using the CLR, as CLR instance sharing across hosts is a scenario for CoreCLR. if (g_fEEStarted) { hr = S_OK; // CoreCLR is already running - but was Start already invoked by this host? if (m_fStarted) { // This host had already invoked the Start method - return them an error hr = HOST_E_INVALIDOPERATION; } else { // Increment the global (and dynamic) refCount... FastInterlockIncrement(&m_RefCount); // And set our flag that this host has invoked the Start... m_fStarted = TRUE; } } else { // Using managed C++ libraries, its possible that when the runtime is already running, // MC++ will use CorBindToRuntimeEx to make callbacks into specific appdomain of its // choice. Now, CorBindToRuntimeEx results in CorHost2::CreateObject being invoked // that will set runtime hosted flag ""g_fHostConfig |= CLRHOSTED"". // // For the case when managed code started without CLR hosting and MC++ does a // CorBindToRuntimeEx, setting the CLR hosted flag is incorrect. // // Thus, before we attempt to start the runtime, we save the status of it being // already running or not. Next, if we are able to successfully start the runtime // and ONLY if it was not started earlier will we set the hosted flag below. if (!g_fEEStarted) { g_fHostConfig |= CLRHOSTED; } hr = CorRuntimeHostBase::Start(); if (SUCCEEDED(hr)) { // Set our flag that this host invoked the Start method. m_fStarted = TRUE; // And they also loaded the CoreCLR DLL in the memory (for this version). // This is a special flag as the host that has got this flag set will be allowed // to repeatedly invoke Stop method (without corresponding Start method invocations). // This is to support scenarios like that of Office where they need to bring down // the CLR at any cost. // // So, if you want to do that, just make sure you are the first host to load the // specific version of CLR in memory AND start it. m_fFirstToLoadCLR = TRUE; FastInterlockIncrement(&m_RefCount); } } END_ENTRYPOINT_NOTHROW; return hr; } // Starts the runtime. This is equivalent to CoInitializeEE(); HRESULT CorRuntimeHostBase::Start() { CONTRACTL { NOTHROW; DISABLED(GC_TRIGGERS); ENTRY_POINT; } CONTRACTL_END; HRESULT hr = S_OK; BEGIN_ENTRYPOINT_NOTHROW; { m_Started = TRUE; #ifdef FEATURE_EVENT_TRACE g_fEEHostedStartup = TRUE; #endif // FEATURE_EVENT_TRACE hr = InitializeEE(COINITEE_DEFAULT); } END_ENTRYPOINT_NOTHROW; return hr; } HRESULT CorHost2::Stop() { CONTRACTL { NOTHROW; ENTRY_POINT; // We're bringing the EE down, so no point in probing if (GetThread()) {GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);} } CONTRACTL_END; if (!g_fEEStarted) { return E_UNEXPECTED; } HRESULT hr=S_OK; BEGIN_ENTRYPOINT_NOTHROW; // Is this host eligible to invoke the Stop method? if ((!m_fStarted) && (!m_fFirstToLoadCLR)) { // Well - since this host never invoked Start, it is not eligible to invoke Stop. // Semantically, for such a host, CLR is not available in the process. The only // exception to this condition is the host that first loaded this version of the // CLR and invoked Start method. For details, refer to comments in CorHost2::Start implementation. hr = HOST_E_CLRNOTAVAILABLE; } else { while (TRUE) { LONG refCount = m_RefCount; if (refCount == 0) { hr = HOST_E_CLRNOTAVAILABLE; break; } else if (FastInterlockCompareExchange(&m_RefCount, refCount - 1, refCount) == refCount) { // Indicate that we have got a Stop for a corresponding Start call from the // Host. Semantically, CoreCLR has stopped for them. m_fStarted = FALSE; if (refCount > 1) { hr=S_FALSE; break; } else { break; } } } } END_ENTRYPOINT_NOTHROW; return hr; } HRESULT CorHost2::GetCurrentAppDomainId(DWORD *pdwAppDomainId) { CONTRACTL { NOTHROW; GC_NOTRIGGER; ENTRY_POINT; } CONTRACTL_END; // No point going further if the runtime is not running... // We use CanRunManagedCode() instead of IsRuntimeActive() because this allows us // to specify test using the form that does not trigger a GC. if (!(g_fEEStarted && CanRunManagedCode(LoaderLockCheck::None))) { return HOST_E_CLRNOTAVAILABLE; } HRESULT hr = S_OK; BEGIN_ENTRYPOINT_NOTHROW; if(pdwAppDomainId == NULL) { hr = E_POINTER; } else { Thread *pThread = GetThread(); if (!pThread) { hr = E_UNEXPECTED; } else { *pdwAppDomainId = SystemDomain::GetCurrentDomain()->GetId().m_dwId; } } END_ENTRYPOINT_NOTHROW; return hr; } HRESULT CorHost2::ExecuteApplication(LPCWSTR pwzAppFullName, DWORD dwManifestPaths, LPCWSTR *ppwzManifestPaths, DWORD dwActivationData, LPCWSTR *ppwzActivationData, int *pReturnValue) { return E_NOTIMPL; } /* * This method processes the arguments sent to the host which are then used * to invoke the main method. * Note - * [0] - points to the assemblyName that has been sent by the host. * The rest are the arguments sent to the assembly. * Also note, this might not always return the exact same identity as the cmdLine * used to invoke the method. * * For example :- * ActualCmdLine - Foo arg1 arg2. * (Host1) - Full_path_to_Foo arg1 arg2 */ void SetCommandLineArgs(LPCWSTR pwzAssemblyPath, int argc, LPCWSTR* argv) { CONTRACTL { THROWS; GC_TRIGGERS; MODE_COOPERATIVE; } CONTRACTL_END; // Send the command line to EventPipe. #ifdef FEATURE_PERFTRACING EventPipe::SaveCommandLine(pwzAssemblyPath, argc, argv); #endif // FEATURE_PERFTRACING // Send the command line to System.Environment. struct _gc { PTRARRAYREF cmdLineArgs; } gc; ZeroMemory(&gc, sizeof(gc)); GCPROTECT_BEGIN(gc); gc.cmdLineArgs = (PTRARRAYREF)AllocateObjectArray(argc + 1 /* arg[0] should be the exe name*/, g_pStringClass); OBJECTREF orAssemblyPath = StringObject::NewString(pwzAssemblyPath); gc.cmdLineArgs->SetAt(0, orAssemblyPath); for (int i = 0; i < argc; ++i) { OBJECTREF argument = StringObject::NewString(argv[i]); gc.cmdLineArgs->SetAt(i + 1, argument); } MethodDescCallSite setCmdLineArgs(METHOD__ENVIRONMENT__SET_COMMAND_LINE_ARGS); ARG_SLOT args[] = { ObjToArgSlot(gc.cmdLineArgs), }; setCmdLineArgs.Call(args); GCPROTECT_END(); } HRESULT CorHost2::ExecuteAssembly(DWORD dwAppDomainId, LPCWSTR pwzAssemblyPath, int argc, LPCWSTR* argv, DWORD *pReturnValue) { CONTRACTL { THROWS; // Throws...as we do not want it to swallow the managed exception ENTRY_POINT; } CONTRACTL_END; // This is currently supported in default domain only if (dwAppDomainId != DefaultADID) return HOST_E_INVALIDOPERATION; // No point going further if the runtime is not running... if (!IsRuntimeActive()) { return HOST_E_CLRNOTAVAILABLE; } if(!pwzAssemblyPath) return E_POINTER; if(argc < 0) { return E_INVALIDARG; } if(argc > 0 && argv == NULL) { return E_INVALIDARG; } HRESULT hr = S_OK; AppDomain *pCurDomain = SystemDomain::GetCurrentDomain(); Thread *pThread = GetThread(); if (pThread == NULL) { pThread = SetupThreadNoThrow(&hr); if (pThread == NULL) { goto ErrExit; } } if(pCurDomain->GetId().m_dwId != DefaultADID) { return HOST_E_INVALIDOPERATION; } INSTALL_UNHANDLED_MANAGED_EXCEPTION_TRAP; INSTALL_UNWIND_AND_CONTINUE_HANDLER; _ASSERTE (!pThread->PreemptiveGCDisabled()); Assembly *pAssembly = AssemblySpec::LoadAssembly(pwzAssemblyPath); #if defined(FEATURE_MULTICOREJIT) pCurDomain->GetMulticoreJitManager().AutoStartProfile(pCurDomain); #endif // defined(FEATURE_MULTICOREJIT) { GCX_COOP(); // Here we call the managed method that gets the cmdLineArgs array. SetCommandLineArgs(pwzAssemblyPath, argc, argv); PTRARRAYREF arguments = NULL; GCPROTECT_BEGIN(arguments); arguments = (PTRARRAYREF)AllocateObjectArray(argc, g_pStringClass); for (int i = 0; i < argc; ++i) { STRINGREF argument = StringObject::NewString(argv[i]); arguments->SetAt(i, argument); } DWORD retval = pAssembly->ExecuteMainMethod(&arguments, TRUE /* waitForOtherThreads */); if (pReturnValue) { *pReturnValue = retval; } GCPROTECT_END(); } UNINSTALL_UNWIND_AND_CONTINUE_HANDLER; UNINSTALL_UNHANDLED_MANAGED_EXCEPTION_TRAP; ErrExit: return hr; } HRESULT CorHost2::ExecuteInDefaultAppDomain(LPCWSTR pwzAssemblyPath, LPCWSTR pwzTypeName, LPCWSTR pwzMethodName, LPCWSTR pwzArgument, DWORD *pReturnValue) { CONTRACTL { NOTHROW; ENTRY_POINT; } CONTRACTL_END; // No point going further if the runtime is not running... if (!IsRuntimeActive()) { return HOST_E_CLRNOTAVAILABLE; } if(! (pwzAssemblyPath && pwzTypeName && pwzMethodName) ) return E_POINTER; HRESULT hr = S_OK; BEGIN_ENTRYPOINT_NOTHROW; Thread *pThread = GetThread(); if (pThread == NULL) { pThread = SetupThreadNoThrow(&hr); if (pThread == NULL) { goto ErrExit; } } _ASSERTE (!pThread->PreemptiveGCDisabled()); _ASSERTE (SystemDomain::GetCurrentDomain()->GetId().m_dwId == DefaultADID); INSTALL_UNHANDLED_MANAGED_EXCEPTION_TRAP; INSTALL_UNWIND_AND_CONTINUE_HANDLER; EX_TRY { Assembly *pAssembly = AssemblySpec::LoadAssembly(pwzAssemblyPath); SString szTypeName(pwzTypeName); StackScratchBuffer buff1; const char* szTypeNameUTF8 = szTypeName.GetUTF8(buff1); MethodTable *pMT = ClassLoader::LoadTypeByNameThrowing(pAssembly, NULL, szTypeNameUTF8).AsMethodTable(); SString szMethodName(pwzMethodName); StackScratchBuffer buff; const char* szMethodNameUTF8 = szMethodName.GetUTF8(buff); MethodDesc *pMethodMD = MemberLoader::FindMethod(pMT, szMethodNameUTF8, &gsig_SM_Str_RetInt); if (!pMethodMD) { hr = COR_E_MISSINGMETHOD; } else { GCX_COOP(); MethodDescCallSite method(pMethodMD); STRINGREF sref = NULL; GCPROTECT_BEGIN(sref); if (pwzArgument) sref = StringObject::NewString(pwzArgument); ARG_SLOT MethodArgs[] = { ObjToArgSlot(sref) }; DWORD retval = method.Call_RetI4(MethodArgs); if (pReturnValue) { *pReturnValue = retval; } GCPROTECT_END(); } } EX_CATCH_HRESULT(hr); UNINSTALL_UNWIND_AND_CONTINUE_HANDLER; UNINSTALL_UNHANDLED_MANAGED_EXCEPTION_TRAP; ErrExit: END_ENTRYPOINT_NOTHROW; return hr; } HRESULT ExecuteInAppDomainHelper(FExecuteInAppDomainCallback pCallback, void * cookie) { STATIC_CONTRACT_THROWS; return pCallback(cookie); } HRESULT CorHost2::ExecuteInAppDomain(DWORD dwAppDomainId, FExecuteInAppDomainCallback pCallback, void * cookie) { // No point going further if the runtime is not running... if (!IsRuntimeActive()) { return HOST_E_CLRNOTAVAILABLE; } // Moved this here since no point validating the pointer // if the basic checks [above] fail if( pCallback == NULL) return E_POINTER; CONTRACTL { NOTHROW; if (GetThread()) {GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);} ENTRY_POINT; // This is called by a host. } CONTRACTL_END; HRESULT hr = S_OK; BEGIN_ENTRYPOINT_NOTHROW; BEGIN_EXTERNAL_ENTRYPOINT(&hr); GCX_COOP_THREAD_EXISTS(GET_THREAD()); ENTER_DOMAIN_ID(ADID(dwAppDomainId)) { // We are calling an unmanaged function pointer, either an unmanaged function, or a marshaled out delegate. // The thread should be in preemptive mode. GCX_PREEMP(); hr=ExecuteInAppDomainHelper (pCallback, cookie); } END_DOMAIN_TRANSITION; END_EXTERNAL_ENTRYPOINT; END_ENTRYPOINT_NOTHROW; return hr; } #define EMPTY_STRING_TO_NULL(s) {if(s && s[0] == 0) {s=NULL;};} HRESULT CorHost2::_CreateAppDomain( LPCWSTR wszFriendlyName, DWORD dwFlags, LPCWSTR wszAppDomainManagerAssemblyName, LPCWSTR wszAppDomainManagerTypeName, int nProperties, LPCWSTR* pPropertyNames, LPCWSTR* pPropertyValues, DWORD* pAppDomainID) { CONTRACTL { NOTHROW; if (GetThread()) {GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);} ENTRY_POINT; // This is called by a host. } CONTRACTL_END; HRESULT hr=S_OK; //cannot call the function more than once when single appDomain is allowed if (m_fAppDomainCreated) { return HOST_E_INVALIDOPERATION; } //normalize empty strings EMPTY_STRING_TO_NULL(wszFriendlyName); EMPTY_STRING_TO_NULL(wszAppDomainManagerAssemblyName); EMPTY_STRING_TO_NULL(wszAppDomainManagerTypeName); if (pAppDomainID==NULL) return E_POINTER; if (!m_fStarted) return HOST_E_INVALIDOPERATION; if (wszFriendlyName == NULL) return E_INVALIDARG; if ((wszAppDomainManagerAssemblyName != NULL) || (wszAppDomainManagerTypeName != NULL)) return E_INVALIDARG; BEGIN_ENTRYPOINT_NOTHROW; BEGIN_EXTERNAL_ENTRYPOINT(&hr); AppDomain* pDomain = SystemDomain::System()->DefaultDomain(); pDomain->SetFriendlyName(wszFriendlyName); ETW::LoaderLog::DomainLoad(pDomain, (LPWSTR)wszFriendlyName); if (dwFlags & APPDOMAIN_IGNORE_UNHANDLED_EXCEPTIONS) pDomain->SetIgnoreUnhandledExceptions(); if (dwFlags & APPDOMAIN_FORCE_TRIVIAL_WAIT_OPERATIONS) pDomain->SetForceTrivialWaitOperations(); pDomain->CreateFusionContext(); { GCX_COOP(); MethodDescCallSite setup(METHOD__APPCONTEXT__SETUP); ARG_SLOT args[3]; args[0] = PtrToArgSlot(pPropertyNames); args[1] = PtrToArgSlot(pPropertyValues); args[2] = PtrToArgSlot(nProperties); setup.Call(args); } LPCWSTR pwzNativeDllSearchDirectories = NULL; LPCWSTR pwzTrustedPlatformAssemblies = NULL; LPCWSTR pwzPlatformResourceRoots = NULL; LPCWSTR pwzAppPaths = NULL; LPCWSTR pwzAppNiPaths = NULL; #ifdef FEATURE_COMINTEROP LPCWSTR pwzAppLocalWinMD = NULL; #endif for (int i = 0; i < nProperties; i++) { if (wcscmp(pPropertyNames[i], W(""NATIVE_DLL_SEARCH_DIRECTORIES"")) == 0) { pwzNativeDllSearchDirectories = pPropertyValues[i]; } else if (wcscmp(pPropertyNames[i], W(""TRUSTED_PLATFORM_ASSEMBLIES"")) == 0) { pwzTrustedPlatformAssemblies = pPropertyValues[i]; } else if (wcscmp(pPropertyNames[i], W(""PLATFORM_RESOURCE_ROOTS"")) == 0) { pwzPlatformResourceRoots = pPropertyValues[i]; } else if (wcscmp(pPropertyNames[i], W(""APP_PATHS"")) == 0) { pwzAppPaths = pPropertyValues[i]; } else if (wcscmp(pPropertyNames[i], W(""APP_NI_PATHS"")) == 0) { pwzAppNiPaths = pPropertyValues[i]; } #ifdef FEATURE_COMINTEROP else if (wcscmp(pPropertyNames[i], W(""APP_LOCAL_WINMETADATA"")) == 0) { pwzAppLocalWinMD = pPropertyValues[i]; } #endif } pDomain->SetNativeDllSearchDirectories(pwzNativeDllSearchDirectories); { SString sTrustedPlatformAssemblies(pwzTrustedPlatformAssemblies); SString sPlatformResourceRoots(pwzPlatformResourceRoots); SString sAppPaths(pwzAppPaths); SString sAppNiPaths(pwzAppNiPaths); CLRPrivBinderCoreCLR *pBinder = pDomain->GetTPABinderContext(); _ASSERTE(pBinder != NULL); IfFailThrow(pBinder->SetupBindingPaths( sTrustedPlatformAssemblies, sPlatformResourceRoots, sAppPaths, sAppNiPaths)); } #ifdef FEATURE_COMINTEROP if (WinRTSupported()) { pDomain->SetWinrtApplicationContext(pwzAppLocalWinMD); } #endif *pAppDomainID=pDomain->GetId().m_dwId; m_fAppDomainCreated = TRUE; END_EXTERNAL_ENTRYPOINT; END_ENTRYPOINT_NOTHROW; return hr; } HRESULT CorHost2::_CreateDelegate( DWORD appDomainID, LPCWSTR wszAssemblyName, LPCWSTR wszClassName, LPCWSTR wszMethodName, INT_PTR* fnPtr) { CONTRACTL { NOTHROW; if (GetThread()) {GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);} ENTRY_POINT; // This is called by a host. } CONTRACTL_END; HRESULT hr=S_OK; EMPTY_STRING_TO_NULL(wszAssemblyName); EMPTY_STRING_TO_NULL(wszClassName); EMPTY_STRING_TO_NULL(wszMethodName); if (fnPtr == NULL) return E_POINTER; *fnPtr = NULL; if(wszAssemblyName == NULL) return E_INVALIDARG; if(wszClassName == NULL) return E_INVALIDARG; if(wszMethodName == NULL) return E_INVALIDARG; BEGIN_ENTRYPOINT_NOTHROW; BEGIN_EXTERNAL_ENTRYPOINT(&hr); GCX_COOP_THREAD_EXISTS(GET_THREAD()); MAKE_UTF8PTR_FROMWIDE(szAssemblyName, wszAssemblyName); MAKE_UTF8PTR_FROMWIDE(szClassName, wszClassName); MAKE_UTF8PTR_FROMWIDE(szMethodName, wszMethodName); ADID id; id.m_dwId=appDomainID; ENTER_DOMAIN_ID(id) GCX_PREEMP(); AssemblySpec spec; spec.Init(szAssemblyName); Assembly* pAsm=spec.LoadAssembly(FILE_ACTIVE); TypeHandle th=pAsm->GetLoader()->LoadTypeByNameThrowing(pAsm,NULL,szClassName); MethodDesc* pMD=NULL; if (!th.IsTypeDesc()) { pMD = MemberLoader::FindMethodByName(th.GetMethodTable(), szMethodName, MemberLoader::FM_Unique); if (pMD == NULL) { // try again without the FM_Unique flag (error path) pMD = MemberLoader::FindMethodByName(th.GetMethodTable(), szMethodName, MemberLoader::FM_Default); if (pMD != NULL) { // the method exists but is overloaded ThrowHR(COR_E_AMBIGUOUSMATCH); } } } if (pMD==NULL || !pMD->IsStatic() || pMD->ContainsGenericVariables()) ThrowHR(COR_E_MISSINGMETHOD); UMEntryThunk *pUMEntryThunk = pMD->GetLoaderAllocator()->GetUMEntryThunkCache()->GetUMEntryThunk(pMD); *fnPtr = (INT_PTR)pUMEntryThunk->GetCode(); END_DOMAIN_TRANSITION; END_EXTERNAL_ENTRYPOINT; END_ENTRYPOINT_NOTHROW; return hr; } HRESULT CorHost2::CreateAppDomainWithManager( LPCWSTR wszFriendlyName, DWORD dwFlags, LPCWSTR wszAppDomainManagerAssemblyName, LPCWSTR wszAppDomainManagerTypeName, int nProperties, LPCWSTR* pPropertyNames, LPCWSTR* pPropertyValues, DWORD* pAppDomainID) { WRAPPER_NO_CONTRACT; return _CreateAppDomain( wszFriendlyName, dwFlags, wszAppDomainManagerAssemblyName, wszAppDomainManagerTypeName, nProperties, pPropertyNames, pPropertyValues, pAppDomainID); } HRESULT CorHost2::CreateDelegate( DWORD appDomainID, LPCWSTR wszAssemblyName, LPCWSTR wszClassName, LPCWSTR wszMethodName, INT_PTR* fnPtr) { WRAPPER_NO_CONTRACT; return _CreateDelegate(appDomainID, wszAssemblyName, wszClassName, wszMethodName, fnPtr); } HRESULT CorHost2::Authenticate(ULONGLONG authKey) { CONTRACTL { NOTHROW; if (GetThread()) {GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);} ENTRY_POINT; // This is called by a host. } CONTRACTL_END; // Host authentication was used by Silverlight. It is no longer relevant for CoreCLR. return S_OK; } HRESULT CorHost2::RegisterMacEHPort() { CONTRACTL { NOTHROW; if (GetThread()) {GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);} ENTRY_POINT; // This is called by a host. } CONTRACTL_END; return S_OK; } HRESULT CorHost2::SetStartupFlags(STARTUP_FLAGS flag) { CONTRACTL { NOTHROW; if (GetThread()) {GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);} ENTRY_POINT; // This is called by a host. } CONTRACTL_END; if (g_fEEStarted) { return HOST_E_INVALIDOPERATION; } m_dwStartupFlags = flag; return S_OK; } #endif //!DACCESS_COMPILE #ifndef DACCESS_COMPILE SVAL_IMPL(STARTUP_FLAGS, CorHost2, m_dwStartupFlags = STARTUP_CONCURRENT_GC); #else SVAL_IMPL(STARTUP_FLAGS, CorHost2, m_dwStartupFlags); #endif STARTUP_FLAGS CorHost2::GetStartupFlags() { return m_dwStartupFlags; } #ifndef DACCESS_COMPILE extern ""C"" DLLEXPORT HRESULT GetCLRRuntimeHost(REFIID riid, IUnknown **ppUnk) { WRAPPER_NO_CONTRACT; return CorHost2::CreateObject(riid, (void**)ppUnk); } STDMETHODIMP CorHost2::UnloadAppDomain(DWORD dwDomainId, BOOL fWaitUntilDone) { return UnloadAppDomain2(dwDomainId, fWaitUntilDone, nullptr); } STDMETHODIMP CorHost2::UnloadAppDomain2(DWORD dwDomainId, BOOL fWaitUntilDone, int *pLatchedExitCode) { WRAPPER_NO_CONTRACT; if (!m_fStarted) return HOST_E_INVALIDOPERATION; if (!g_fEEStarted) { return HOST_E_CLRNOTAVAILABLE; } if(!m_fAppDomainCreated) { return HOST_E_INVALIDOPERATION; } HRESULT hr=S_OK; BEGIN_ENTRYPOINT_NOTHROW; if (!m_fFirstToLoadCLR) { _ASSERTE(!""Not reachable""); hr = HOST_E_CLRNOTAVAILABLE; } else { LONG refCount = m_RefCount; if (refCount == 0) { hr = HOST_E_CLRNOTAVAILABLE; } else if (1 == refCount) { // Stop coreclr on unload. EEShutDown(FALSE); } else { _ASSERTE(!""Not reachable""); hr = S_FALSE; } } END_ENTRYPOINT_NOTHROW; if (pLatchedExitCode) { *pLatchedExitCode = GetLatchedExitCode(); } return hr; } HRESULT CorRuntimeHostBase::UnloadAppDomain(DWORD dwDomainId, BOOL fWaitUntilDone) { return UnloadAppDomain2(dwDomainId, fWaitUntilDone, nullptr); } HRESULT CorRuntimeHostBase::UnloadAppDomain2(DWORD dwDomainId, BOOL fWaitUntilDone, int *pLatchedExitCode) { CONTRACTL { NOTHROW; GC_TRIGGERS; MODE_ANY; FORBID_FAULT; // Unloading domains cannot fail due to OOM ENTRY_POINT; } CONTRACTL_END; return COR_E_CANNOTUNLOADAPPDOMAIN; } //***************************************************************************** // Fiber Methods //***************************************************************************** HRESULT CorRuntimeHostBase::LocksHeldByLogicalThread(DWORD *pCount) { if (!pCount) return E_POINTER; CONTRACTL { NOTHROW; GC_NOTRIGGER; ENTRY_POINT; } CONTRACTL_END; BEGIN_ENTRYPOINT_NOTHROW; Thread* pThread = GetThread(); if (pThread == NULL) *pCount = 0; else *pCount = pThread->m_dwLockCount; END_ENTRYPOINT_NOTHROW; return S_OK; } //***************************************************************************** // ICorConfiguration //***************************************************************************** //***************************************************************************** // IUnknown //***************************************************************************** ULONG CorRuntimeHostBase::AddRef() { CONTRACTL { WRAPPER(THROWS); WRAPPER(GC_TRIGGERS); } CONTRACTL_END; return InterlockedIncrement(&m_cRef); } ULONG CorHost2::Release() { LIMITED_METHOD_CONTRACT; ULONG cRef = InterlockedDecrement(&m_cRef); if (!cRef) { delete this; } return (cRef); } HRESULT CorHost2::QueryInterface(REFIID riid, void **ppUnk) { if (!ppUnk) return E_POINTER; CONTRACTL { NOTHROW; GC_NOTRIGGER; } CONTRACTL_END; if (ppUnk == NULL) { return E_POINTER; } *ppUnk = 0; // Deliberately do NOT hand out ICorConfiguration. They must explicitly call // GetConfiguration to obtain that interface. if (riid == IID_IUnknown) { *ppUnk = static_cast(static_cast(this)); } else if (riid == IID_ICLRRuntimeHost) { *ppUnk = static_cast(this); } else if (riid == IID_ICLRRuntimeHost2) { ULONG version = 2; if (m_Version == 0) FastInterlockCompareExchange((LONG*)&m_Version, version, 0); *ppUnk = static_cast(this); } else if (riid == IID_ICLRRuntimeHost4) { ULONG version = 4; if (m_Version == 0) FastInterlockCompareExchange((LONG*)&m_Version, version, 0); *ppUnk = static_cast(this); } #ifndef FEATURE_PAL else if (riid == IID_IPrivateManagedExceptionReporting) { *ppUnk = static_cast(this); } #endif // !FEATURE_PAL else return (E_NOINTERFACE); AddRef(); return (S_OK); } #ifndef FEATURE_PAL HRESULT CorHost2::GetBucketParametersForCurrentException(BucketParameters *pParams) { CONTRACTL { NOTHROW; GC_NOTRIGGER; } CONTRACTL_END; HRESULT hr = S_OK; BEGIN_ENTRYPOINT_NOTHROW; // To avoid confusion, clear the buckets. memset(pParams, 0, sizeof(BucketParameters)); // Defer to Watson helper. hr = ::GetBucketParametersForCurrentException(pParams); END_ENTRYPOINT_NOTHROW; return hr; } #endif // !FEATURE_PAL HRESULT CorHost2::CreateObject(REFIID riid, void **ppUnk) { CONTRACTL { NOTHROW; GC_NOTRIGGER; } CONTRACTL_END; HRESULT hr = S_OK; CorHost2 *pCorHost = new (nothrow) CorHost2(); if (!pCorHost) { hr = E_OUTOFMEMORY; } else { hr = pCorHost->QueryInterface(riid, ppUnk); if (FAILED(hr)) delete pCorHost; } return (hr); } //----------------------------------------------------------------------------- // MapFile - Maps a file into the runtime in a non-standard way //----------------------------------------------------------------------------- static PEImage *MapFileHelper(HANDLE hFile) { CONTRACTL { THROWS; GC_TRIGGERS; MODE_ANY; } CONTRACTL_END; GCX_PREEMP(); HandleHolder hFileMap(WszCreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL)); if (hFileMap == NULL) ThrowLastError(); CLRMapViewHolder base(CLRMapViewOfFile(hFileMap, FILE_MAP_READ, 0, 0, 0)); if (base == NULL) ThrowLastError(); DWORD dwSize = SafeGetFileSize(hFile, NULL); if (dwSize == 0xffffffff && GetLastError() != NOERROR) { ThrowLastError(); } PEImageHolder pImage(PEImage::LoadFlat(base, dwSize)); return pImage.Extract(); } HRESULT CorRuntimeHostBase::MapFile(HANDLE hFile, HMODULE* phHandle) { CONTRACTL { NOTHROW; GC_TRIGGERS; MODE_PREEMPTIVE; ENTRY_POINT; } CONTRACTL_END; HRESULT hr; BEGIN_ENTRYPOINT_NOTHROW; BEGIN_EXTERNAL_ENTRYPOINT(&hr) { *phHandle = (HMODULE) (MapFileHelper(hFile)->GetLoadedLayout()->GetBase()); } END_EXTERNAL_ENTRYPOINT; END_ENTRYPOINT_NOTHROW; return hr; } LONG CorHost2::m_RefCount = 0; static Volatile fOneOnly = 0; /////////////////////////////////////////////////////////////////////////////// // ICLRRuntimeHost::SetHostControl /////////////////////////////////////////////////////////////////////////////// HRESULT CorHost2::SetHostControl(IHostControl* pHostControl) { return E_NOTIMPL; } /////////////////////////////////////////////////////////////////////////////// // ICLRRuntimeHost::GetCLRControl HRESULT CorHost2::GetCLRControl(ICLRControl** pCLRControl) { return E_NOTIMPL; } void GetProcessMemoryLoad(LPMEMORYSTATUSEX pMSEX) { CONTRACTL { NOTHROW; GC_NOTRIGGER; } CONTRACTL_END; pMSEX->dwLength = sizeof(MEMORYSTATUSEX); BOOL fRet = GlobalMemoryStatusEx(pMSEX); _ASSERTE (fRet); } // This is the instance that exposes interfaces out to all the other DLLs of the CLR // so they can use our services for TLS, synchronization, memory allocation, etc. static BYTE g_CEEInstance[sizeof(CExecutionEngine)]; static Volatile g_pCEE = NULL; PTLS_CALLBACK_FUNCTION CExecutionEngine::Callbacks[MAX_PREDEFINED_TLS_SLOT]; extern ""C"" IExecutionEngine * __stdcall IEE() { LIMITED_METHOD_CONTRACT; // Unfortunately,we can't probe here. The probing system requires the // use of TLS, and in order to initialize TLS we need to call IEE. //BEGIN_ENTRYPOINT_VOIDRET; // The following code does NOT contain a race condition. The following code is BY DESIGN. // The issue is that we can have two separate threads inside this if statement, both of which are // initializing the g_CEEInstance variable (and subsequently updating g_pCEE). This works fine, // and will not cause an inconsistent state due to the fact that CExecutionEngine has no // local variables. If multiple threads make it inside this if statement, it will copy the same // bytes over g_CEEInstance and there will not be a time when there is an inconsistent state. if ( !g_pCEE ) { // Create a local copy on the stack and then copy it over to the static instance. // This avoids race conditions caused by multiple initializations of vtable in the constructor CExecutionEngine local; memcpy(&g_CEEInstance, (void*)&local, sizeof(CExecutionEngine)); g_pCEE = (IExecutionEngine*)(CExecutionEngine*)&g_CEEInstance; } //END_ENTRYPOINT_VOIDRET; return g_pCEE; } HRESULT STDMETHODCALLTYPE CExecutionEngine::QueryInterface(REFIID id, void **pInterface) { LIMITED_METHOD_CONTRACT; if (!pInterface) return E_POINTER; *pInterface = NULL; //CANNOTTHROWCOMPLUSEXCEPTION(); if (id == IID_IExecutionEngine) *pInterface = (IExecutionEngine *)this; else if (id == IID_IEEMemoryManager) *pInterface = (IEEMemoryManager *)this; else if (id == IID_IUnknown) *pInterface = (IUnknown *)(IExecutionEngine *)this; else return E_NOINTERFACE; AddRef(); return S_OK; } // HRESULT STDMETHODCALLTYPE CExecutionEngine::QueryInterface() ULONG STDMETHODCALLTYPE CExecutionEngine::AddRef() { LIMITED_METHOD_CONTRACT; return 1; } ULONG STDMETHODCALLTYPE CExecutionEngine::Release() { LIMITED_METHOD_CONTRACT; return 1; } struct ClrTlsInfo { void* data[MAX_PREDEFINED_TLS_SLOT]; }; #define DataToClrTlsInfo(a) ((ClrTlsInfo*)a) void** CExecutionEngine::GetTlsData() { LIMITED_METHOD_CONTRACT; return gCurrentThreadInfo.m_EETlsData; } BOOL CExecutionEngine::SetTlsData (void** ppTlsInfo) { LIMITED_METHOD_CONTRACT; gCurrentThreadInfo.m_EETlsData = ppTlsInfo; return TRUE; } //--------------------------------------------------------------------------------------- // // Returns the current logical thread's data block (ClrTlsInfo::data). // // Arguments: // slot - Index of the slot that is about to be requested // force - If the data block does not exist yet, create it as a side-effect // // Return Value: // NULL, if the data block did not exist yet for the current thread and force was FALSE. // A pointer to the data block, otherwise. // // Notes: // If the underlying OS does not support fiber mode, the data block is stored in TLS. // If the underlying OS does support fiber mode, it is primarily stored in FLS, // and cached in TLS so that we can use our generated optimized TLS accessors. // // TLS support for the other DLLs of the CLR operates quite differently in hosted // and unhosted scenarios. void **CExecutionEngine::CheckThreadState(DWORD slot, BOOL force) { STATIC_CONTRACT_GC_NOTRIGGER; STATIC_CONTRACT_THROWS; STATIC_CONTRACT_MODE_ANY; STATIC_CONTRACT_CANNOT_TAKE_LOCK; // @TODO: Decide on an exception strategy for all the DLLs of the CLR, and then // enable all the exceptions out of this method. // Treat as a runtime assertion, since the invariant spans many DLLs. _ASSERTE(slot < MAX_PREDEFINED_TLS_SLOT); // if (slot >= MAX_PREDEFINED_TLS_SLOT) // COMPlusThrow(kArgumentOutOfRangeException); void** pTlsData = CExecutionEngine::GetTlsData(); BOOL fInTls = (pTlsData != NULL); ClrTlsInfo *pTlsInfo = DataToClrTlsInfo(pTlsData); if (pTlsInfo == 0 && force) { #undef HeapAlloc #undef GetProcessHeap // !!! Contract uses our TLS support. Contract may be used before our host support is set up. // !!! To better support contract, we call into OS for memory allocation. pTlsInfo = (ClrTlsInfo*) ::HeapAlloc(GetProcessHeap(),0,sizeof(ClrTlsInfo)); #define GetProcessHeap() Dont_Use_GetProcessHeap() #define HeapAlloc(hHeap, dwFlags, dwBytes) Dont_Use_HeapAlloc(hHeap, dwFlags, dwBytes) if (pTlsInfo == NULL) { goto LError; } memset (pTlsInfo, 0, sizeof(ClrTlsInfo)); } if (!fInTls && pTlsInfo) { if (!CExecutionEngine::SetTlsData(pTlsInfo->data)) { goto LError; } } return pTlsInfo?pTlsInfo->data:NULL; LError: if (pTlsInfo) { #undef HeapFree #undef GetProcessHeap ::HeapFree(GetProcessHeap(), 0, pTlsInfo); #define GetProcessHeap() Dont_Use_GetProcessHeap() #define HeapFree(hHeap, dwFlags, lpMem) Dont_Use_HeapFree(hHeap, dwFlags, lpMem) } // If this is for the stack probe, and we failed to allocate memory for it, we won't // put in a guard page. if (slot == TlsIdx_ClrDebugState) return NULL; ThrowOutOfMemory(); } void **CExecutionEngine::CheckThreadStateNoCreate(DWORD slot #ifdef _DEBUG , BOOL fForDestruction #endif // _DEBUG ) { STATIC_CONTRACT_GC_NOTRIGGER; STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_MODE_ANY; // !!! This function is called during Thread::SwitchIn and SwitchOut // !!! It is extremely important that while executing this function, we will not // !!! cause fiber switch. This means we can not allocate memory, lock, etc... // Treat as a runtime assertion, since the invariant spans many DLLs. _ASSERTE(slot < MAX_PREDEFINED_TLS_SLOT); void **pTlsData = CExecutionEngine::GetTlsData(); ClrTlsInfo *pTlsInfo = DataToClrTlsInfo(pTlsData); return pTlsInfo?pTlsInfo->data:NULL; } // Note: Sampling profilers also use this function to initialize TLS for a unmanaged // sampling thread so that initialization can be done in advance to avoid deadlocks. // See ProfToEEInterfaceImpl::InitializeCurrentThread for more details. void CExecutionEngine::SetupTLSForThread(Thread *pThread) { STATIC_CONTRACT_THROWS; STATIC_CONTRACT_GC_NOTRIGGER; STATIC_CONTRACT_MODE_ANY; #ifdef STRESS_LOG if (StressLog::StressLogOn(~0u, 0)) { StressLog::CreateThreadStressLog(); } #endif void **pTlsData; pTlsData = CheckThreadState(0); PREFIX_ASSUME(pTlsData != NULL); #ifdef ENABLE_CONTRACTS // Profilers need the side effect of GetClrDebugState() to perform initialization // in advance to avoid deadlocks. Refer to ProfToEEInterfaceImpl::InitializeCurrentThread ClrDebugState *pDebugState = ::GetClrDebugState(); if (pThread) pThread->m_pClrDebugState = pDebugState; #endif } static void ThreadDetachingHelper(PTLS_CALLBACK_FUNCTION callback, void* pData) { // Do not use contract. We are freeing TLS blocks. STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_GC_NOTRIGGER; STATIC_CONTRACT_MODE_ANY; callback(pData); } // Called here from a thread detach or from destruction of a Thread object. In // the detach case, we get our info from TLS. In the destruct case, it comes from // the object we are destructing. void CExecutionEngine::ThreadDetaching(void ** pTlsData) { // Can not cause memory allocation during thread detach, so no real contracts. STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_GC_NOTRIGGER; STATIC_CONTRACT_MODE_ANY; // This function may be called twice: // 1. When a physical thread dies, our DLL_THREAD_DETACH calls this function with pTlsData = NULL // 2. When a fiber is destroyed, or OS calls FlsCallback after DLL_THREAD_DETACH process. // We will null the FLS and TLS entry if it matches the deleted one. if (pTlsData) { DeleteTLS (pTlsData); } } void CExecutionEngine::DeleteTLS(void ** pTlsData) { // Can not cause memory allocation during thread detach, so no real contracts. STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_GC_NOTRIGGER; STATIC_CONTRACT_MODE_ANY; if (CExecutionEngine::GetTlsData() == NULL) { // We have not allocated TlsData yet. return; } PREFIX_ASSUME(pTlsData != NULL); ClrTlsInfo *pTlsInfo = DataToClrTlsInfo(pTlsData); BOOL fNeed; do { fNeed = FALSE; for (int i=0; idata[i] != 0) { void* pData = pTlsInfo->data[i]; pTlsInfo->data[i] = 0; ThreadDetachingHelper(Callbacks[i], pData); fNeed = TRUE; } } } while (fNeed); if (pTlsInfo->data[TlsIdx_StressLog] != 0) { #ifdef STRESS_LOG StressLog::ThreadDetach((ThreadStressLog *)pTlsInfo->data[TlsIdx_StressLog]); #else _ASSERTE (!""should not have StressLog""); #endif } if (Callbacks[TlsIdx_ClrDebugState] != 0 && pTlsInfo->data[TlsIdx_ClrDebugState] != 0) { void* pData = pTlsInfo->data[TlsIdx_ClrDebugState]; pTlsInfo->data[TlsIdx_ClrDebugState] = 0; ThreadDetachingHelper(Callbacks[TlsIdx_ClrDebugState], pData); } // NULL TLS and FLS entry so that we don't double free. // We may get two callback here on thread death // 1. From EEDllMain // 2. From OS callback on FLS destruction if (CExecutionEngine::GetTlsData() == pTlsData) { CExecutionEngine::SetTlsData(0); } #undef HeapFree #undef GetProcessHeap ::HeapFree (GetProcessHeap(),0,pTlsInfo); #define HeapFree(hHeap, dwFlags, lpMem) Dont_Use_HeapFree(hHeap, dwFlags, lpMem) #define GetProcessHeap() Dont_Use_GetProcessHeap() } #ifdef ENABLE_CONTRACTS_IMPL // Fls callback to deallocate ClrDebugState when our FLS block goes away. void FreeClrDebugState(LPVOID pTlsData); #endif VOID STDMETHODCALLTYPE CExecutionEngine::TLS_AssociateCallback(DWORD slot, PTLS_CALLBACK_FUNCTION callback) { WRAPPER_NO_CONTRACT; CheckThreadState(slot); // They can toggle between a callback and no callback. But anything else looks like // confusion on their part. // // (TlsIdx_ClrDebugState associates its callback from utilcode.lib - which can be replicated. But // all the callbacks are equally good.) _ASSERTE(slot == TlsIdx_ClrDebugState || Callbacks[slot] == 0 || Callbacks[slot] == callback || callback == 0); if (slot == TlsIdx_ClrDebugState) { #ifdef ENABLE_CONTRACTS_IMPL // ClrDebugState is shared among many dlls. Some dll, like perfcounter.dll, may be unloaded. // We force the callback function to be in mscorwks.dll. Callbacks[slot] = FreeClrDebugState; #else _ASSERTE (!""should not get here""); #endif } else Callbacks[slot] = callback; } LPVOID* STDMETHODCALLTYPE CExecutionEngine::TLS_GetDataBlock() { STATIC_CONTRACT_GC_NOTRIGGER; STATIC_CONTRACT_THROWS; STATIC_CONTRACT_MODE_ANY; STATIC_CONTRACT_CANNOT_TAKE_LOCK; return CExecutionEngine::GetTlsData(); } LPVOID STDMETHODCALLTYPE CExecutionEngine::TLS_GetValue(DWORD slot) { WRAPPER_NO_CONTRACT; return EETlsGetValue(slot); } BOOL STDMETHODCALLTYPE CExecutionEngine::TLS_CheckValue(DWORD slot, LPVOID * pValue) { WRAPPER_NO_CONTRACT; return EETlsCheckValue(slot, pValue); } VOID STDMETHODCALLTYPE CExecutionEngine::TLS_SetValue(DWORD slot, LPVOID pData) { WRAPPER_NO_CONTRACT; EETlsSetValue(slot,pData); } VOID STDMETHODCALLTYPE CExecutionEngine::TLS_ThreadDetaching() { WRAPPER_NO_CONTRACT; CExecutionEngine::ThreadDetaching(NULL); } CRITSEC_COOKIE STDMETHODCALLTYPE CExecutionEngine::CreateLock(LPCSTR szTag, LPCSTR level, CrstFlags flags) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_ANY; ENTRY_POINT; } CONTRACTL_END; CRITSEC_COOKIE cookie = NULL; BEGIN_ENTRYPOINT_VOIDRET; cookie = ::EECreateCriticalSection(*(CrstType*)&level, flags); END_ENTRYPOINT_VOIDRET; return cookie; } void STDMETHODCALLTYPE CExecutionEngine::DestroyLock(CRITSEC_COOKIE cookie) { WRAPPER_NO_CONTRACT; ::EEDeleteCriticalSection(cookie); } void STDMETHODCALLTYPE CExecutionEngine::AcquireLock(CRITSEC_COOKIE cookie) { WRAPPER_NO_CONTRACT; ::EEEnterCriticalSection(cookie); } void STDMETHODCALLTYPE CExecutionEngine::ReleaseLock(CRITSEC_COOKIE cookie) { WRAPPER_NO_CONTRACT; ::EELeaveCriticalSection(cookie); } // Locking routines supplied by the EE to the other DLLs of the CLR. In a _DEBUG // build of the EE, we poison the Crst as a poor man's attempt to do some argument // validation. #define POISON_BITS 3 static inline EVENT_COOKIE CLREventToCookie(CLREvent * pEvent) { LIMITED_METHOD_CONTRACT; _ASSERTE((((uintptr_t) pEvent) & POISON_BITS) == 0); #ifdef _DEBUG pEvent = (CLREvent *) (((uintptr_t) pEvent) | POISON_BITS); #endif return (EVENT_COOKIE) pEvent; } static inline CLREvent *CookieToCLREvent(EVENT_COOKIE cookie) { LIMITED_METHOD_CONTRACT; _ASSERTE((((uintptr_t) cookie) & POISON_BITS) == POISON_BITS); #ifdef _DEBUG if (cookie) { cookie = (EVENT_COOKIE) (((uintptr_t) cookie) & ~POISON_BITS); } #endif return (CLREvent *) cookie; } EVENT_COOKIE STDMETHODCALLTYPE CExecutionEngine::CreateAutoEvent(BOOL bInitialState) { CONTRACTL { THROWS; MODE_ANY; GC_NOTRIGGER; ENTRY_POINT; } CONTRACTL_END; EVENT_COOKIE event = NULL; BEGIN_ENTRYPOINT_THROWS; NewHolder pEvent(new CLREvent()); pEvent->CreateAutoEvent(bInitialState); event = CLREventToCookie(pEvent); pEvent.SuppressRelease(); END_ENTRYPOINT_THROWS; return event; } EVENT_COOKIE STDMETHODCALLTYPE CExecutionEngine::CreateManualEvent(BOOL bInitialState) { CONTRACTL { THROWS; MODE_ANY; GC_NOTRIGGER; ENTRY_POINT; } CONTRACTL_END; EVENT_COOKIE event = NULL; BEGIN_ENTRYPOINT_THROWS; NewHolder pEvent(new CLREvent()); pEvent->CreateManualEvent(bInitialState); event = CLREventToCookie(pEvent); pEvent.SuppressRelease(); END_ENTRYPOINT_THROWS; return event; } void STDMETHODCALLTYPE CExecutionEngine::CloseEvent(EVENT_COOKIE event) { WRAPPER_NO_CONTRACT; if (event) { CLREvent *pEvent = CookieToCLREvent(event); pEvent->CloseEvent(); delete pEvent; } } BOOL STDMETHODCALLTYPE CExecutionEngine::ClrSetEvent(EVENT_COOKIE event) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; if (event) { CLREvent *pEvent = CookieToCLREvent(event); return pEvent->Set(); } return FALSE; } BOOL STDMETHODCALLTYPE CExecutionEngine::ClrResetEvent(EVENT_COOKIE event) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; if (event) { CLREvent *pEvent = CookieToCLREvent(event); return pEvent->Reset(); } return FALSE; } DWORD STDMETHODCALLTYPE CExecutionEngine::WaitForEvent(EVENT_COOKIE event, DWORD dwMilliseconds, BOOL bAlertable) { WRAPPER_NO_CONTRACT; if (event) { CLREvent *pEvent = CookieToCLREvent(event); return pEvent->Wait(dwMilliseconds,bAlertable); } if (GetThread() && bAlertable) ThrowHR(E_INVALIDARG); return WAIT_FAILED; } DWORD STDMETHODCALLTYPE CExecutionEngine::WaitForSingleObject(HANDLE handle, DWORD dwMilliseconds) { STATIC_CONTRACT_WRAPPER; return ::WaitForSingleObject(handle,dwMilliseconds); } static inline SEMAPHORE_COOKIE CLRSemaphoreToCookie(CLRSemaphore * pSemaphore) { LIMITED_METHOD_CONTRACT; _ASSERTE((((uintptr_t) pSemaphore) & POISON_BITS) == 0); #ifdef _DEBUG pSemaphore = (CLRSemaphore *) (((uintptr_t) pSemaphore) | POISON_BITS); #endif return (SEMAPHORE_COOKIE) pSemaphore; } static inline CLRSemaphore *CookieToCLRSemaphore(SEMAPHORE_COOKIE cookie) { LIMITED_METHOD_CONTRACT; _ASSERTE((((uintptr_t) cookie) & POISON_BITS) == POISON_BITS); #ifdef _DEBUG if (cookie) { cookie = (SEMAPHORE_COOKIE) (((uintptr_t) cookie) & ~POISON_BITS); } #endif return (CLRSemaphore *) cookie; } SEMAPHORE_COOKIE STDMETHODCALLTYPE CExecutionEngine::ClrCreateSemaphore(DWORD dwInitial, DWORD dwMax) { CONTRACTL { THROWS; MODE_ANY; GC_NOTRIGGER; } CONTRACTL_END; NewHolder pSemaphore(new CLRSemaphore()); pSemaphore->Create(dwInitial, dwMax); SEMAPHORE_COOKIE ret = CLRSemaphoreToCookie(pSemaphore);; pSemaphore.SuppressRelease(); return ret; } void STDMETHODCALLTYPE CExecutionEngine::ClrCloseSemaphore(SEMAPHORE_COOKIE semaphore) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; CLRSemaphore *pSemaphore = CookieToCLRSemaphore(semaphore); pSemaphore->Close(); delete pSemaphore; } BOOL STDMETHODCALLTYPE CExecutionEngine::ClrReleaseSemaphore(SEMAPHORE_COOKIE semaphore, LONG lReleaseCount, LONG *lpPreviousCount) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; CLRSemaphore *pSemaphore = CookieToCLRSemaphore(semaphore); return pSemaphore->Release(lReleaseCount,lpPreviousCount); } DWORD STDMETHODCALLTYPE CExecutionEngine::ClrWaitForSemaphore(SEMAPHORE_COOKIE semaphore, DWORD dwMilliseconds, BOOL bAlertable) { WRAPPER_NO_CONTRACT; CLRSemaphore *pSemaphore = CookieToCLRSemaphore(semaphore); return pSemaphore->Wait(dwMilliseconds,bAlertable); } static inline MUTEX_COOKIE CLRMutexToCookie(CLRMutex * pMutex) { LIMITED_METHOD_CONTRACT; _ASSERTE((((uintptr_t) pMutex) & POISON_BITS) == 0); #ifdef _DEBUG pMutex = (CLRMutex *) (((uintptr_t) pMutex) | POISON_BITS); #endif return (MUTEX_COOKIE) pMutex; } static inline CLRMutex *CookieToCLRMutex(MUTEX_COOKIE cookie) { LIMITED_METHOD_CONTRACT; _ASSERTE((((uintptr_t) cookie) & POISON_BITS) == POISON_BITS); #ifdef _DEBUG if (cookie) { cookie = (MUTEX_COOKIE) (((uintptr_t) cookie) & ~POISON_BITS); } #endif return (CLRMutex *) cookie; } MUTEX_COOKIE STDMETHODCALLTYPE CExecutionEngine::ClrCreateMutex(LPSECURITY_ATTRIBUTES lpMutexAttributes, BOOL bInitialOwner, LPCTSTR lpName) { CONTRACTL { NOTHROW; MODE_ANY; GC_NOTRIGGER; } CONTRACTL_END; MUTEX_COOKIE mutex = 0; CLRMutex *pMutex = new (nothrow) CLRMutex(); if (pMutex) { EX_TRY { pMutex->Create(lpMutexAttributes, bInitialOwner, lpName); mutex = CLRMutexToCookie(pMutex); } EX_CATCH { delete pMutex; } EX_END_CATCH(SwallowAllExceptions); } return mutex; } void STDMETHODCALLTYPE CExecutionEngine::ClrCloseMutex(MUTEX_COOKIE mutex) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; CLRMutex *pMutex = CookieToCLRMutex(mutex); pMutex->Close(); delete pMutex; } BOOL STDMETHODCALLTYPE CExecutionEngine::ClrReleaseMutex(MUTEX_COOKIE mutex) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; CLRMutex *pMutex = CookieToCLRMutex(mutex); return pMutex->Release(); } DWORD STDMETHODCALLTYPE CExecutionEngine::ClrWaitForMutex(MUTEX_COOKIE mutex, DWORD dwMilliseconds, BOOL bAlertable) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; CLRMutex *pMutex = CookieToCLRMutex(mutex); return pMutex->Wait(dwMilliseconds,bAlertable); } #undef ClrSleepEx DWORD STDMETHODCALLTYPE CExecutionEngine::ClrSleepEx(DWORD dwMilliseconds, BOOL bAlertable) { WRAPPER_NO_CONTRACT; return EESleepEx(dwMilliseconds,bAlertable); } #define ClrSleepEx EESleepEx #undef ClrAllocationDisallowed BOOL STDMETHODCALLTYPE CExecutionEngine::ClrAllocationDisallowed() { WRAPPER_NO_CONTRACT; return EEAllocationDisallowed(); } #define ClrAllocationDisallowed EEAllocationDisallowed #undef ClrVirtualAlloc LPVOID STDMETHODCALLTYPE CExecutionEngine::ClrVirtualAlloc(LPVOID lpAddress, SIZE_T dwSize, DWORD flAllocationType, DWORD flProtect) { WRAPPER_NO_CONTRACT; return EEVirtualAlloc(lpAddress, dwSize, flAllocationType, flProtect); } #define ClrVirtualAlloc EEVirtualAlloc #undef ClrVirtualFree BOOL STDMETHODCALLTYPE CExecutionEngine::ClrVirtualFree(LPVOID lpAddress, SIZE_T dwSize, DWORD dwFreeType) { WRAPPER_NO_CONTRACT; return EEVirtualFree(lpAddress, dwSize, dwFreeType); } #define ClrVirtualFree EEVirtualFree #undef ClrVirtualQuery SIZE_T STDMETHODCALLTYPE CExecutionEngine::ClrVirtualQuery(LPCVOID lpAddress, PMEMORY_BASIC_INFORMATION lpBuffer, SIZE_T dwLength) { WRAPPER_NO_CONTRACT; return EEVirtualQuery(lpAddress, lpBuffer, dwLength); } #define ClrVirtualQuery EEVirtualQuery #if defined(_DEBUG) && !defined(FEATURE_PAL) static VolatilePtr s_pStartOfUEFSection = NULL; static VolatilePtr s_pEndOfUEFSectionBoundary = NULL; static Volatile s_dwProtection = 0; #endif // _DEBUG && !FEATURE_PAL #undef ClrVirtualProtect BOOL STDMETHODCALLTYPE CExecutionEngine::ClrVirtualProtect(LPVOID lpAddress, SIZE_T dwSize, DWORD flNewProtect, PDWORD lpflOldProtect) { WRAPPER_NO_CONTRACT; // Get the UEF installation details - we will use these to validate // that the calls to ClrVirtualProtect are not going to affect the UEF. // // The OS UEF invocation mechanism was updated. When a UEF is setup,the OS captures // the following details about it: // 1) Protection of the pages in which the UEF lives // 2) The size of the region in which the UEF lives // 3) The region's Allocation Base // // The OS verifies details surrounding the UEF before invocation. For security reasons // the page protection cannot change between SetUnhandledExceptionFilter and invocation. // // Prior to this change, the UEF lived in a common section of code_Seg, along with // JIT_PatchedCode. Thus, their pages have the same protection, they live // in the same region (and thus, its size is the same). // // In EEStartupHelper, when we setup the UEF and then invoke InitJitHelpers1 and InitJitHelpers2, // they perform some optimizations that result in the memory page protection being changed. When // the UEF is to be invoked, the OS does the check on the UEF's cached details against the current // memory pages. This check used to fail when on 64bit retail builds when JIT_PatchedCode was // aligned after the UEF with a different memory page protection (post the optimizations by InitJitHelpers). // Thus, the UEF was never invoked. // // To circumvent this, we put the UEF in its own section in the code segment so that any modifications // to memory pages will not affect the UEF details that the OS cached. This is done in Excep.cpp // using the ""#pragma code_seg"" directives. // // Below, we double check that: // // 1) the address being protected does not lie in the region of of the UEF. // 2) the section after UEF is not having the same memory protection as UEF section. // // We assert if either of the two conditions above are true. #if defined(_DEBUG) && !defined(FEATURE_PAL) // We do this check in debug/checked builds only // Do we have the UEF details? if (s_pEndOfUEFSectionBoundary.Load() == NULL) { // Get reference to MSCORWKS image in memory... PEDecoder pe(g_pMSCorEE); // Find the UEF section from the image IMAGE_SECTION_HEADER* pUEFSection = pe.FindSection(CLR_UEF_SECTION_NAME); _ASSERTE(pUEFSection != NULL); if (pUEFSection) { // We got our section - get the start of the section BYTE* pStartOfUEFSection = static_cast(pe.GetBase())+pUEFSection->VirtualAddress; s_pStartOfUEFSection = pStartOfUEFSection; // Now we need the protection attributes for the memory region in which the // UEF section is... MEMORY_BASIC_INFORMATION uefInfo; if (ClrVirtualQuery(pStartOfUEFSection, &uefInfo, sizeof(uefInfo)) != 0) { // Calculate how many pages does the UEF section take to get to the start of the // next section. We dont calculate this as // // pStartOfUEFSection + uefInfo.RegionSize // // because the section following UEF will also be included in the region size // if it has the same protection as the UEF section. DWORD dwUEFSectionPageCount = ((pUEFSection->Misc.VirtualSize + GetOsPageSize() - 1)/GetOsPageSize()); BYTE* pAddressOfFollowingSection = pStartOfUEFSection + (GetOsPageSize() * dwUEFSectionPageCount); // Ensure that the section following us is having different memory protection MEMORY_BASIC_INFORMATION nextSectionInfo; _ASSERTE(ClrVirtualQuery(pAddressOfFollowingSection, &nextSectionInfo, sizeof(nextSectionInfo)) != 0); _ASSERTE(nextSectionInfo.Protect != uefInfo.Protect); // save the memory protection details s_dwProtection = uefInfo.Protect; // Get the end of the UEF section BYTE* pEndOfUEFSectionBoundary = pAddressOfFollowingSection - 1; // Set the end of UEF section boundary FastInterlockExchangePointer(s_pEndOfUEFSectionBoundary.GetPointer(), pEndOfUEFSectionBoundary); } else { _ASSERTE(!""Unable to get UEF Details!""); } } } if (s_pEndOfUEFSectionBoundary.Load() != NULL) { // Is the protection being changed? if (flNewProtect != s_dwProtection) { // Is the target address NOT affecting the UEF ? Possible cases: // 1) Starts and ends before the UEF start // 2) Starts after the UEF start void* pEndOfRangeAddr = static_cast(lpAddress)+dwSize-1; _ASSERTE_MSG(((pEndOfRangeAddr < s_pStartOfUEFSection.Load()) || (lpAddress > s_pEndOfUEFSectionBoundary.Load())), ""Do not virtual protect the section in which UEF lives!""); } } #endif // _DEBUG && !FEATURE_PAL return EEVirtualProtect(lpAddress, dwSize, flNewProtect, lpflOldProtect); } #define ClrVirtualProtect EEVirtualProtect #undef ClrGetProcessHeap HANDLE STDMETHODCALLTYPE CExecutionEngine::ClrGetProcessHeap() { WRAPPER_NO_CONTRACT; return EEGetProcessHeap(); } #define ClrGetProcessHeap EEGetProcessHeap #undef ClrGetProcessExecutableHeap HANDLE STDMETHODCALLTYPE CExecutionEngine::ClrGetProcessExecutableHeap() { WRAPPER_NO_CONTRACT; return EEGetProcessExecutableHeap(); } #define ClrGetProcessExecutableHeap EEGetProcessExecutableHeap #undef ClrHeapCreate HANDLE STDMETHODCALLTYPE CExecutionEngine::ClrHeapCreate(DWORD flOptions, SIZE_T dwInitialSize, SIZE_T dwMaximumSize) { WRAPPER_NO_CONTRACT; return EEHeapCreate(flOptions, dwInitialSize, dwMaximumSize); } #define ClrHeapCreate EEHeapCreate #undef ClrHeapDestroy BOOL STDMETHODCALLTYPE CExecutionEngine::ClrHeapDestroy(HANDLE hHeap) { WRAPPER_NO_CONTRACT; return EEHeapDestroy(hHeap); } #define ClrHeapDestroy EEHeapDestroy #undef ClrHeapAlloc LPVOID STDMETHODCALLTYPE CExecutionEngine::ClrHeapAlloc(HANDLE hHeap, DWORD dwFlags, SIZE_T dwBytes) { WRAPPER_NO_CONTRACT; return EEHeapAlloc(hHeap, dwFlags, dwBytes); } #define ClrHeapAlloc EEHeapAlloc #undef ClrHeapFree BOOL STDMETHODCALLTYPE CExecutionEngine::ClrHeapFree(HANDLE hHeap, DWORD dwFlags, LPVOID lpMem) { WRAPPER_NO_CONTRACT; return EEHeapFree(hHeap, dwFlags, lpMem); } #define ClrHeapFree EEHeapFree #undef ClrHeapValidate BOOL STDMETHODCALLTYPE CExecutionEngine::ClrHeapValidate(HANDLE hHeap, DWORD dwFlags, LPCVOID lpMem) { WRAPPER_NO_CONTRACT; return EEHeapValidate(hHeap, dwFlags, lpMem); } #define ClrHeapValidate EEHeapValidate //------------------------------------------------------------------------------ // Helper function to get an exception object from outside the exception. In // the CLR, it may be from the Thread object. Non-CLR users have no thread object, // and it will do nothing. void CExecutionEngine::GetLastThrownObjectExceptionFromThread(void **ppvException) { WRAPPER_NO_CONTRACT; // Cast to our real type. Exception **ppException = reinterpret_cast(ppvException); // Try to get a better message. GetLastThrownObjectExceptionFromThread_Internal(ppException); } // HRESULT CExecutionEngine::GetLastThrownObjectExceptionFromThread() LocaleID RuntimeGetFileSystemLocale() { return PEImage::GetFileSystemLocale(); }; HRESULT CorHost2::DllGetActivationFactory(DWORD appDomainID, LPCWSTR wszTypeName, IActivationFactory ** factory) { #ifdef FEATURE_COMINTEROP_WINRT_MANAGED_ACTIVATION // WinRT activation currently supported in default domain only if (appDomainID != DefaultADID) return HOST_E_INVALIDOPERATION; HRESULT hr = S_OK; Thread *pThread = GetThread(); if (pThread == NULL) { pThread = SetupThreadNoThrow(&hr); if (pThread == NULL) { return hr; } } if(SystemDomain::GetCurrentDomain()->GetId().m_dwId != DefaultADID) { return HOST_E_INVALIDOPERATION; } return DllGetActivationFactoryImpl(NULL, wszTypeName, NULL, factory); #else return E_NOTIMPL; #endif } #ifdef FEATURE_COMINTEROP_WINRT_MANAGED_ACTIVATION HRESULT STDMETHODCALLTYPE DllGetActivationFactoryImpl(LPCWSTR wszAssemblyName, LPCWSTR wszTypeName, LPCWSTR wszCodeBase, IActivationFactory ** factory) { CONTRACTL { DISABLED(NOTHROW); GC_TRIGGERS; MODE_ANY; ENTRY_POINT; } CONTRACTL_END; HRESULT hr = S_OK; BEGIN_ENTRYPOINT_NOTHROW; AppDomain* pDomain = SystemDomain::System()->DefaultDomain(); _ASSERTE(pDomain); BEGIN_EXTERNAL_ENTRYPOINT(&hr); { GCX_COOP(); bool bIsPrimitive; TypeHandle typeHandle = WinRTTypeNameConverter::GetManagedTypeFromWinRTTypeName(wszTypeName, &bIsPrimitive); if (!bIsPrimitive && !typeHandle.IsNull() && !typeHandle.IsTypeDesc() && typeHandle.AsMethodTable()->IsExportedToWinRT()) { struct _gc { OBJECTREF type; } gc; memset(&gc, 0, sizeof(gc)); IActivationFactory* activationFactory; GCPROTECT_BEGIN(gc); gc.type = typeHandle.GetManagedClassObject(); MethodDescCallSite mdcs(METHOD__WINDOWSRUNTIMEMARSHAL__GET_ACTIVATION_FACTORY_FOR_TYPE); ARG_SLOT args[1] = { ObjToArgSlot(gc.type) }; activationFactory = (IActivationFactory*)mdcs.Call_RetLPVOID(args); *factory = activationFactory; GCPROTECT_END(); } else { hr = COR_E_TYPELOAD; } } END_EXTERNAL_ENTRYPOINT; END_ENTRYPOINT_NOTHROW; return hr; } #endif // !FEATURE_COMINTEROP_MANAGED_ACTIVATION #endif // !DACCESS_COMPILE ",16170,True,2716.4603020249374,median "CLASS zcl_abapgit_gui_chunk_lib DEFINITION PUBLIC FINAL CREATE PUBLIC . PUBLIC SECTION. TYPES: BEGIN OF ty_event_signature, method TYPE string, name TYPE string, END OF ty_event_signature . CLASS-METHODS class_constructor . CLASS-METHODS render_error IMPORTING !ix_error TYPE REF TO zcx_abapgit_exception OPTIONAL !iv_error TYPE string OPTIONAL !iv_extra_style TYPE string OPTIONAL RETURNING VALUE(ri_html) TYPE REF TO zif_abapgit_html . CLASS-METHODS render_repo_top IMPORTING !io_repo TYPE REF TO zcl_abapgit_repo !iv_show_package TYPE abap_bool DEFAULT abap_true !iv_show_branch TYPE abap_bool DEFAULT abap_true !iv_show_commit TYPE abap_bool DEFAULT abap_true !iv_show_edit TYPE abap_bool DEFAULT abap_false !iv_interactive_branch TYPE abap_bool DEFAULT abap_false !io_news TYPE REF TO zcl_abapgit_news OPTIONAL RETURNING VALUE(ri_html) TYPE REF TO zif_abapgit_html RAISING zcx_abapgit_exception . CLASS-METHODS render_item_state IMPORTING !iv_lstate TYPE char1 !iv_rstate TYPE char1 RETURNING VALUE(rv_html) TYPE string . CLASS-METHODS render_js_error_banner RETURNING VALUE(ri_html) TYPE REF TO zif_abapgit_html RAISING zcx_abapgit_exception . CLASS-METHODS render_news IMPORTING !io_news TYPE REF TO zcl_abapgit_news RETURNING VALUE(ri_html) TYPE REF TO zif_abapgit_html RAISING zcx_abapgit_exception . CLASS-METHODS render_commit_popup IMPORTING !iv_content TYPE csequence !iv_id TYPE csequence RETURNING VALUE(ri_html) TYPE REF TO zif_abapgit_html RAISING zcx_abapgit_exception . CLASS-METHODS render_error_message_box IMPORTING !ix_error TYPE REF TO zcx_abapgit_exception RETURNING VALUE(ri_html) TYPE REF TO zif_abapgit_html . CLASS-METHODS render_order_by_header_cells IMPORTING !it_col_spec TYPE zif_abapgit_definitions=>ty_col_spec_tt !iv_order_by TYPE string !iv_order_descending TYPE abap_bool RETURNING VALUE(ri_html) TYPE REF TO zif_abapgit_html . CLASS-METHODS render_warning_banner IMPORTING !iv_text TYPE string RETURNING VALUE(ri_html) TYPE REF TO zif_abapgit_html . CLASS-METHODS render_infopanel IMPORTING !iv_div_id TYPE string !iv_title TYPE string !iv_hide TYPE abap_bool DEFAULT abap_true !iv_hint TYPE string OPTIONAL !iv_scrollable TYPE abap_bool DEFAULT abap_true !io_content TYPE REF TO zif_abapgit_html RETURNING VALUE(ri_html) TYPE REF TO zif_abapgit_html RAISING zcx_abapgit_exception . CLASS-METHODS render_event_as_form IMPORTING !is_event TYPE ty_event_signature RETURNING VALUE(ri_html) TYPE REF TO zif_abapgit_html . CLASS-METHODS render_repo_palette IMPORTING iv_action TYPE string iv_only_favorites TYPE abap_bool RETURNING VALUE(ri_html) TYPE REF TO zif_abapgit_html RAISING zcx_abapgit_exception . CLASS-METHODS advanced_submenu RETURNING VALUE(ro_menu) TYPE REF TO zcl_abapgit_html_toolbar . CLASS-METHODS help_submenu RETURNING VALUE(ro_menu) TYPE REF TO zcl_abapgit_html_toolbar . CLASS-METHODS back_toolbar RETURNING VALUE(ro_menu) TYPE REF TO zcl_abapgit_html_toolbar . CLASS-METHODS settings_toolbar IMPORTING !iv_act TYPE string RETURNING VALUE(ro_menu) TYPE REF TO zcl_abapgit_html_toolbar . CLASS-METHODS settings_repo_toolbar IMPORTING !iv_key TYPE zif_abapgit_persistence=>ty_repo-key !iv_act TYPE string RETURNING VALUE(ro_menu) TYPE REF TO zcl_abapgit_html_toolbar . CLASS-METHODS render_branch_name IMPORTING !iv_branch TYPE string OPTIONAL !iv_repo_key TYPE zif_abapgit_persistence=>ty_value OPTIONAL !io_repo TYPE REF TO zcl_abapgit_repo_online OPTIONAL !iv_interactive TYPE abap_bool DEFAULT abap_true RETURNING VALUE(ri_html) TYPE REF TO zif_abapgit_html RAISING zcx_abapgit_exception . CLASS-METHODS render_package_name IMPORTING !iv_package TYPE devclass !iv_interactive TYPE abap_bool DEFAULT abap_true !iv_suppress_title TYPE abap_bool DEFAULT abap_false RETURNING VALUE(ri_html) TYPE REF TO zif_abapgit_html RAISING zcx_abapgit_exception . CLASS-METHODS render_user_name IMPORTING !iv_username TYPE xubname !iv_interactive TYPE abap_bool DEFAULT abap_true !iv_icon_only TYPE abap_bool DEFAULT abap_false !iv_suppress_title TYPE abap_bool DEFAULT abap_false RETURNING VALUE(ri_html) TYPE REF TO zif_abapgit_html RAISING zcx_abapgit_exception . CLASS-METHODS render_transport IMPORTING !iv_transport TYPE trkorr !iv_interactive TYPE abap_bool DEFAULT abap_true !iv_icon_only TYPE abap_bool DEFAULT abap_false RETURNING VALUE(ri_html) TYPE REF TO zif_abapgit_html RAISING zcx_abapgit_exception . CLASS-METHODS render_sci_result IMPORTING ii_html TYPE REF TO zif_abapgit_html iv_sci_result TYPE zif_abapgit_definitions=>ty_sci_result. PROTECTED SECTION. CLASS-METHODS render_repo_top_commit_hash IMPORTING !ii_html TYPE REF TO zif_abapgit_html !io_repo_online TYPE REF TO zcl_abapgit_repo_online RAISING zcx_abapgit_exception . PRIVATE SECTION. CLASS-DATA gv_time_zone TYPE timezone . CLASS-METHODS get_t100_text IMPORTING !iv_msgid TYPE scx_t100key-msgid !iv_msgno TYPE scx_t100key-msgno RETURNING VALUE(rv_text) TYPE string . CLASS-METHODS normalize_program_name IMPORTING !iv_program_name TYPE sy-repid RETURNING VALUE(rv_normalized_program_name) TYPE string . ENDCLASS. CLASS zcl_abapgit_gui_chunk_lib IMPLEMENTATION. METHOD advanced_submenu. DATA: li_gui_functions TYPE REF TO zif_abapgit_gui_functions, lv_supports_ie_devtools TYPE abap_bool. li_gui_functions = zcl_abapgit_ui_factory=>get_gui_functions( ). lv_supports_ie_devtools = li_gui_functions->is_sapgui_for_windows( ). CREATE OBJECT ro_menu. ro_menu->add( iv_txt = 'Database Utility' iv_act = zif_abapgit_definitions=>c_action-go_db )->add( iv_txt = 'Package to ZIP' iv_act = zif_abapgit_definitions=>c_action-zip_package )->add( iv_txt = 'Transport to ZIP' iv_act = zif_abapgit_definitions=>c_action-zip_transport )->add( iv_txt = 'Object to Files' iv_act = zif_abapgit_definitions=>c_action-zip_object )->add( iv_txt = 'Debug Info' iv_act = zif_abapgit_definitions=>c_action-go_debuginfo ). IF lv_supports_ie_devtools = abap_true. ro_menu->add( iv_txt = 'Open IE DevTools' iv_act = zif_abapgit_definitions=>c_action-ie_devtools ). ENDIF. ENDMETHOD. METHOD back_toolbar. CREATE OBJECT ro_menu EXPORTING iv_id = 'toolbar-back'. ro_menu->add( iv_txt = 'Back' iv_act = zif_abapgit_definitions=>c_action-go_back ). ENDMETHOD. METHOD class_constructor. CALL FUNCTION 'GET_SYSTEM_TIMEZONE' IMPORTING timezone = gv_time_zone EXCEPTIONS customizing_missing = 1 OTHERS = 2. ASSERT sy-subrc = 0. ENDMETHOD. METHOD get_t100_text. SELECT SINGLE text FROM t100 INTO rv_text WHERE arbgb = iv_msgid AND msgnr = iv_msgno AND sprsl = sy-langu. ENDMETHOD. METHOD help_submenu. CREATE OBJECT ro_menu. ro_menu->add( iv_txt = 'Tutorial' iv_act = zif_abapgit_definitions=>c_action-go_tutorial )->add( iv_txt = 'Documentation' iv_act = zif_abapgit_definitions=>c_action-documentation )->add( iv_txt = 'Explore' iv_act = zif_abapgit_definitions=>c_action-go_explore )->add( iv_txt = 'Changelog' iv_act = zif_abapgit_definitions=>c_action-changelog ). ENDMETHOD. METHOD normalize_program_name. rv_normalized_program_name = substring_before( val = iv_program_name regex = `(=+CP)?$` ). ENDMETHOD. METHOD render_branch_name. DATA: lv_key TYPE string, lv_branch TYPE string, lv_selected_commit TYPE string, lv_commit_short_sha TYPE string, lv_text TYPE string, lv_class TYPE string. IF iv_repo_key IS NOT INITIAL. lv_key = iv_repo_key. ELSEIF io_repo IS BOUND. lv_key = io_repo->get_key( ). ELSE. zcx_abapgit_exception=>raise( 'Either iv_repo_key or io_repo must be supplied' ). ENDIF. IF iv_branch IS NOT INITIAL. lv_branch = iv_branch. lv_text = zcl_abapgit_git_branch_list=>get_display_name( lv_branch ). ELSEIF io_repo IS BOUND. lv_selected_commit = io_repo->get_selected_commit( ). IF lv_selected_commit IS NOT INITIAL. ""Convert to short commit. Example: (ae623b9...) lv_commit_short_sha = lv_selected_commit+0(7). lv_text = |({ lv_commit_short_sha }...)|. ELSE. lv_branch = io_repo->get_selected_branch( ). lv_text = zcl_abapgit_git_branch_list=>get_display_name( lv_branch ). ENDIF. ELSE. zcx_abapgit_exception=>raise( 'Either iv_branch or io_repo must be supplied' ). ENDIF. IF zcl_abapgit_git_branch_list=>get_type( lv_branch ) = zif_abapgit_definitions=>c_git_branch_type-branch. lv_class = 'branch branch_branch'. ELSE. lv_class = 'branch'. ENDIF. CREATE OBJECT ri_html TYPE zcl_abapgit_html. ri_html->add( || ). ri_html->add_icon( iv_name = 'code-branch/grey70' iv_hint = 'Current branch' ). IF iv_interactive = abap_true. ri_html->add_a( iv_act = |{ zif_abapgit_definitions=>c_action-git_branch_switch }?key={ lv_key }| iv_txt = lv_text ). ELSE. ri_html->add( lv_text ). ENDIF. ri_html->add( '' ). ENDMETHOD. METHOD render_commit_popup. CREATE OBJECT ri_html TYPE zcl_abapgit_html. ri_html->add( '
    ' ). ri_html->add( |
  • | && |{ iv_content }| && |
  • | ). ri_html->add( '
' ). ri_html = render_infopanel( iv_div_id = |{ iv_id }| iv_title = 'Commit details' iv_hide = abap_true iv_scrollable = abap_false io_content = ri_html ). ENDMETHOD. METHOD render_error. DATA lv_error TYPE string. DATA lv_class TYPE string VALUE 'panel error center'. IF iv_extra_style IS NOT INITIAL. lv_class = lv_class && ` ` && iv_extra_style. ENDIF. CREATE OBJECT ri_html TYPE zcl_abapgit_html. IF ix_error IS BOUND. lv_error = ix_error->get_text( ). ELSE. lv_error = iv_error. ENDIF. ri_html->add( |
| ). ri_html->add( |{ ri_html->icon( 'exclamation-circle/red' ) } { lv_error }| ). ri_html->add( '
' ). ENDMETHOD. METHOD render_error_message_box. DATA: lv_error_text TYPE string, lv_longtext TYPE string, lv_program_name TYPE sy-repid, lv_title TYPE string, lv_text TYPE string. CREATE OBJECT ri_html TYPE zcl_abapgit_html. lv_error_text = ix_error->get_text( ). lv_longtext = ix_error->if_message~get_longtext( abap_true ). REPLACE FIRST OCCURRENCE OF REGEX |({ zcx_abapgit_exception=>c_section_text-cause }{ cl_abap_char_utilities=>newline })| IN lv_longtext WITH |

$1

|. REPLACE FIRST OCCURRENCE OF REGEX |({ zcx_abapgit_exception=>c_section_text-system_response }{ cl_abap_char_utilities=>newline })| IN lv_longtext WITH |

$1

|. REPLACE FIRST OCCURRENCE OF REGEX |({ zcx_abapgit_exception=>c_section_text-what_to_do }{ cl_abap_char_utilities=>newline })| IN lv_longtext WITH |

$1

|. REPLACE FIRST OCCURRENCE OF REGEX |({ zcx_abapgit_exception=>c_section_text-sys_admin }{ cl_abap_char_utilities=>newline })| IN lv_longtext WITH |

$1

|. ri_html->add( |
| ). ri_html->add( |{ ri_html->icon( 'exclamation-circle/red' ) } { lv_error_text }| ). ri_html->add( |
| ). ri_html->add_a( iv_txt = `❌` iv_act = `toggleDisplay('message')` iv_class = `close-btn` iv_typ = zif_abapgit_html=>c_action_type-onclick ). ri_html->add( |
| ). ri_html->add( |
| ). IF ix_error->if_t100_message~t100key-msgid IS NOT INITIAL. lv_title = get_t100_text( iv_msgid = ix_error->if_t100_message~t100key-msgid iv_msgno = ix_error->if_t100_message~t100key-msgno ). lv_text = |Message ({ ix_error->if_t100_message~t100key-msgid }/{ ix_error->if_t100_message~t100key-msgno })|. ri_html->add_a( iv_txt = lv_text iv_typ = zif_abapgit_html=>c_action_type-sapevent iv_act = zif_abapgit_definitions=>c_action-goto_message iv_title = lv_title iv_id = `a_goto_message` ). ENDIF. ix_error->get_source_position( IMPORTING program_name = lv_program_name ). lv_title = normalize_program_name( lv_program_name ). ri_html->add_a( iv_txt = `Goto source` iv_act = zif_abapgit_definitions=>c_action-goto_source iv_typ = zif_abapgit_html=>c_action_type-sapevent iv_title = lv_title iv_id = `a_goto_source` ). ri_html->add_a( iv_txt = `Callstack` iv_act = zif_abapgit_definitions=>c_action-show_callstack iv_typ = zif_abapgit_html=>c_action_type-sapevent iv_id = `a_callstack` ). ri_html->add( |
| ). ri_html->add( |
| ). ri_html->add( |{ lv_longtext }| ). ri_html->add( |
| ). ri_html->add( |
| ). ENDMETHOD. METHOD render_event_as_form. CREATE OBJECT ri_html TYPE zcl_abapgit_html. ri_html->add( || ). ENDMETHOD. METHOD render_infopanel. DATA lv_display TYPE string. DATA lv_class TYPE string. CREATE OBJECT ri_html TYPE zcl_abapgit_html. IF iv_hide = abap_true. "" Initially hide lv_display = 'display:none'. ENDIF. lv_class = 'info-panel'. IF iv_scrollable = abap_false. "" Initially hide lv_class = lv_class && ' info-panel-fixed'. ENDIF. ri_html->add( |
| ). ri_html->add( |
{ iv_title }| && '
' && ri_html->a( iv_txt = '❌' iv_typ = zif_abapgit_html=>c_action_type-onclick iv_act = |toggleDisplay('{ iv_div_id }')| iv_class = 'close-btn' ) && '
' ). IF iv_hint IS NOT INITIAL. ri_html->add( '
' && ri_html->icon( iv_name = 'exclamation-triangle' iv_class = 'pad-right' ) && iv_hint && '
' ). ENDIF. ri_html->add( |
| ). ri_html->add( io_content ). ri_html->add( '
' ). ri_html->add( '
' ). ENDMETHOD. METHOD render_item_state. DATA: lv_system TYPE string. FIELD-SYMBOLS TYPE char1. rv_html = ''. DO 2 TIMES. CASE sy-index. WHEN 1. ASSIGN iv_lstate TO . lv_system = 'Local:'. WHEN 2. ASSIGN iv_rstate TO . lv_system = 'Remote:'. ENDCASE. CASE . WHEN zif_abapgit_definitions=>c_state-unchanged. ""None or unchanged IF iv_lstate = zif_abapgit_definitions=>c_state-added OR iv_rstate = zif_abapgit_definitions=>c_state-added. rv_html = rv_html && |X|. ELSE. rv_html = rv_html && | |. ENDIF. WHEN zif_abapgit_definitions=>c_state-modified. ""Changed rv_html = rv_html && |M|. WHEN zif_abapgit_definitions=>c_state-added. ""Added new rv_html = rv_html && |A|. WHEN zif_abapgit_definitions=>c_state-mixed. ""Multiple changes (multifile) rv_html = rv_html && |■|. WHEN zif_abapgit_definitions=>c_state-deleted. ""Deleted rv_html = rv_html && |D|. ENDCASE. ENDDO. rv_html = rv_html && ''. ENDMETHOD. METHOD render_js_error_banner. CREATE OBJECT ri_html TYPE zcl_abapgit_html. ri_html->add( '
' ). ri_html->add( |{ ri_html->icon( 'exclamation-triangle/red' ) }| && ' If this does not disappear soon,' && ' then there is a JS init error, please log an issue' ). ri_html->add( '
' ). ENDMETHOD. METHOD render_news. DATA: lv_text TYPE string, lv_hint TYPE string, lv_ul TYPE abap_bool, lt_log TYPE zcl_abapgit_news=>ty_logs. FIELD-SYMBOLS: LIKE LINE OF lt_log. CREATE OBJECT ri_html TYPE zcl_abapgit_html. IF io_news IS NOT BOUND OR io_news->has_news( ) = abap_false. RETURN. ENDIF. lt_log = io_news->get_log( ). "" Render news LOOP AT lt_log ASSIGNING . IF -is_header = abap_true. IF -pos_to_cur > 0. lv_text = -text && 'update'. ELSEIF -pos_to_cur = 0. lv_text = -text && 'current'. ELSE. "" < 0 lv_text = -text. ENDIF. IF lv_ul = abap_true. ri_html->add( || ). ENDIF. ri_html->add( |

{ lv_text }

| ). ri_html->add( |
    | ). lv_ul = abap_true. ELSE. -text = escape( val = -text format = cl_abap_format=>e_html_text ). ri_html->add( |
  • { -text }
  • | ). ENDIF. ENDLOOP. IF lv_ul = abap_true. ri_html->add( |
| ). ENDIF. "" Wrap IF io_news->has_important( ) = abap_true. lv_hint = 'Please note changes marked with ""!""'. ENDIF. ri_html = render_infopanel( iv_div_id = 'news' iv_title = 'Announcement of the latest changes' iv_hint = lv_hint iv_hide = boolc( io_news->has_unseen( ) = abap_false ) io_content = ri_html ). ENDMETHOD. METHOD render_order_by_header_cells. DATA: lv_tmp TYPE string, lv_disp_name TYPE string. FIELD-SYMBOLS LIKE LINE OF it_col_spec. CREATE OBJECT ri_html TYPE zcl_abapgit_html. LOOP AT it_col_spec ASSIGNING . "" e.g. Created at [{ gv_time_zone }] lv_tmp = '-css_class IS NOT INITIAL. lv_tmp = lv_tmp && | class=""{ -css_class }""|. ENDIF. lv_tmp = lv_tmp && '>'. IF -display_name IS NOT INITIAL. lv_disp_name = -display_name. IF -add_tz = abap_true. lv_disp_name = lv_disp_name && | [{ gv_time_zone }]|. ENDIF. IF -tech_name = iv_order_by. IF iv_order_descending = abap_true. lv_tmp = lv_tmp && ri_html->a( iv_txt = lv_disp_name iv_act = |{ zif_abapgit_definitions=>c_action-direction }?direction=ASCENDING| iv_title = -title ). ELSE. lv_tmp = lv_tmp && ri_html->a( iv_txt = lv_disp_name iv_act = |{ zif_abapgit_definitions=>c_action-direction }?direction=DESCENDING| iv_title = -title ). ENDIF. ELSEIF -allow_order_by = abap_true. lv_tmp = lv_tmp && ri_html->a( iv_txt = lv_disp_name iv_act = |{ zif_abapgit_definitions=>c_action-change_order_by }?orderBy={ -tech_name }| iv_title = -title ). ELSE. lv_tmp = lv_tmp && lv_disp_name. ENDIF. ENDIF. IF -tech_name = iv_order_by AND iv_order_by IS NOT INITIAL. IF iv_order_descending = abap_true. lv_tmp = lv_tmp && | ▾|. "" arrow down ELSE. lv_tmp = lv_tmp && | ▴|. "" arrow up ENDIF. ENDIF. lv_tmp = lv_tmp && ''. ri_html->add( lv_tmp ). ENDLOOP. ENDMETHOD. METHOD render_package_name. DATA: lv_obj_name TYPE tadir-obj_name, lv_jump TYPE string, lv_title TYPE string. CREATE OBJECT ri_html TYPE zcl_abapgit_html. IF iv_package IS INITIAL. RETURN. ENDIF. IF iv_suppress_title = abap_false. SELECT SINGLE ctext FROM tdevct INTO lv_title WHERE devclass = iv_package AND spras = sy-langu ##SUBRC_OK. ENDIF. lv_obj_name = iv_package. lv_jump = zcl_abapgit_html_action_utils=>jump_encode( iv_obj_type = 'DEVC' iv_obj_name = lv_obj_name ). ri_html->add( || ). ri_html->add_icon( iv_name = 'box/grey70' iv_hint = 'SAP package' ). IF iv_interactive = abap_true. ri_html->add_a( iv_act = |{ zif_abapgit_definitions=>c_action-jump }?{ lv_jump }| iv_title = lv_title iv_txt = |{ iv_package }| ). ELSE. ri_html->add( iv_package ). ENDIF. ri_html->add( '' ). ENDMETHOD. METHOD render_repo_palette. DATA lt_repo_obj_list TYPE zif_abapgit_repo_srv=>ty_repo_list. DATA lt_repo_list TYPE zif_abapgit_persistence=>ty_repos. DATA lv_repo_json TYPE string. DATA lv_size TYPE i. DATA ls_repo_data LIKE LINE OF lt_repo_list. FIELD-SYMBOLS: LIKE LINE OF lt_repo_list, LIKE LINE OF lt_repo_obj_list. IF iv_only_favorites = abap_true. lt_repo_obj_list = zcl_abapgit_repo_srv=>get_instance( )->list_favorites( ). ELSE. lt_repo_obj_list = zcl_abapgit_repo_srv=>get_instance( )->list( ). ENDIF. LOOP AT lt_repo_obj_list ASSIGNING . ls_repo_data = ->ms_data. ls_repo_data-local_settings-display_name = ->get_name( ). APPEND ls_repo_data TO lt_repo_list. ENDLOOP. lv_size = lines( lt_repo_list ). SORT lt_repo_list BY local_settings-display_name AS TEXT. CREATE OBJECT ri_html TYPE zcl_abapgit_html. ri_html->add( 'var repoCatalog = [' ). "" Maybe separate this into another method if needed in more places LOOP AT lt_repo_list ASSIGNING . lv_repo_json = |\\{ key: ""{ -key }"", isOffline: ""{ -offline }"", displayName: ""{ -local_settings-display_name }"" \\}|. IF sy-tabix < lv_size. lv_repo_json = lv_repo_json && ','. ENDIF. ri_html->add( lv_repo_json ). ENDLOOP. ri_html->add( '];' ). ri_html->add( |var gGoRepoPalette = new CommandPalette(createRepoCatalogEnumerator(repoCatalog, ""{ iv_action }""), \\{| ). ri_html->add( ' toggleKey: ""F2"",' ). ri_html->add( ' hotkeyDescription: ""Go to repo ...""' ). ri_html->add( '});' ). ENDMETHOD. METHOD render_repo_top. DATA: lo_repo_online TYPE REF TO zcl_abapgit_repo_online, lo_pback TYPE REF TO zcl_abapgit_persist_background, lx_error TYPE REF TO zcx_abapgit_exception, lv_hint TYPE string, lv_icon TYPE string. CREATE OBJECT ri_html TYPE zcl_abapgit_html. CREATE OBJECT lo_pback. IF io_repo->is_offline( ) = abap_true. lv_icon = 'plug/darkgrey'. lv_hint = 'Offline Repository'. ELSE. lv_icon = 'cloud-upload-alt/blue'. lv_hint = 'On-line Repository'. ENDIF. ri_html->add( '' ). ri_html->add( '' ). ri_html->add( '' ). ri_html->add( '
' ). "" Repo type and name ri_html->add_icon( iv_name = lv_icon iv_hint = lv_hint ). ri_html->add( |{ io_repo->get_name( ) }| ). IF io_repo->is_offline( ) = abap_false. lo_repo_online ?= io_repo. ri_html->add_a( iv_txt = lo_repo_online->get_url( ) iv_act = |{ zif_abapgit_definitions=>c_action-url }?url=| && |{ lo_repo_online->get_url( ) }| iv_class = |url| ). ENDIF. IF iv_show_edit = abap_true. ri_html->add_a( iv_txt = ri_html->icon( iv_name = 'edit-solid' iv_class = 'pad-sides' iv_hint = 'Change Remote' ) iv_act = |{ zif_abapgit_definitions=>c_action-repo_remote_settings }?| && |key={ io_repo->get_key( ) }| iv_class = |url| ). ENDIF. IF io_repo->is_offline( ) = abap_false. lo_repo_online ?= io_repo. ri_html->add_a( iv_txt = ri_html->icon( iv_name = 'copy-solid' iv_class = 'pad-sides' iv_hint = 'Copy URL to Clipboard' ) iv_act = |{ zif_abapgit_definitions=>c_action-clipboard }| && |?clipboard={ lo_repo_online->get_url( ) }| iv_class = |url| ). ENDIF. IF io_repo->is_offline( ) = abap_false AND iv_show_commit = abap_true. TRY. render_repo_top_commit_hash( ii_html = ri_html io_repo_online = lo_repo_online ). CATCH zcx_abapgit_exception INTO lx_error. "" In case of missing or wrong credentials, show message in status bar lv_hint = lx_error->get_text( ). IF lv_hint CS 'credentials'. MESSAGE lv_hint TYPE 'S' DISPLAY LIKE 'E'. ENDIF. ENDTRY. ENDIF. "" News IF io_news IS BOUND AND io_news->has_news( ) = abap_true. IF io_news->has_updates( ) = abap_true. lv_icon = 'arrow-circle-up/warning'. ELSE. lv_icon = 'arrow-circle-up'. ENDIF. ri_html->add_a( iv_act = |toggleDisplay('news')| iv_typ = zif_abapgit_html=>c_action_type-onclick iv_txt = ri_html->icon( iv_name = lv_icon iv_class = 'pad-sides' iv_hint = 'Display Changelog' ) iv_class = |url| ). ENDIF. ri_html->add( '' ). "" Fav IF abap_true = zcl_abapgit_persistence_user=>get_instance( )->is_favorite_repo( io_repo->get_key( ) ). lv_icon = 'star/blue'. ELSE. lv_icon = 'star/grey'. ENDIF. ri_html->add_a( iv_act = |{ zif_abapgit_definitions=>c_action-repo_toggle_fav }?key={ io_repo->get_key( ) }| iv_txt = ri_html->icon( iv_name = lv_icon iv_class = 'pad-sides' iv_hint = 'Toggle Favorite' ) ). "" BG IF lo_pback->exists( io_repo->get_key( ) ) = abap_true. ri_html->add( 'BG' ). ENDIF. "" Write protect IF io_repo->get_local_settings( )-write_protected = abap_true. ri_html->add_icon( iv_name = 'lock/grey70' iv_hint = 'Locked from Pulls' ). ENDIF. "" Branch IF io_repo->is_offline( ) = abap_false. lo_repo_online ?= io_repo. IF iv_show_branch = abap_true. ri_html->add( render_branch_name( io_repo = lo_repo_online iv_interactive = iv_interactive_branch ) ). ENDIF. ENDIF. "" Package IF iv_show_package = abap_true. ri_html->add( render_package_name( io_repo->get_package( ) ) ). ENDIF. ri_html->add( '
' ). ENDMETHOD. METHOD render_repo_top_commit_hash. DATA: lv_commit_hash TYPE zif_abapgit_definitions=>ty_sha1, lv_commit_short_hash TYPE zif_abapgit_definitions=>ty_sha1, lv_display_url TYPE zif_abapgit_persistence=>ty_repo-url, lo_url TYPE REF TO zcl_abapgit_git_url, lv_icon_commit TYPE string. lv_commit_hash = io_repo_online->get_current_remote( ). lv_commit_short_hash = lv_commit_hash(7). lv_icon_commit = ii_html->icon( iv_name = 'code-commit' iv_class = 'pad-sides' iv_hint = 'Commit' ). CREATE OBJECT lo_url. TRY. lv_display_url = lo_url->get_commit_display_url( io_repo_online ). ii_html->add_a( iv_txt = |{ lv_icon_commit }{ lv_commit_short_hash }| iv_act = |{ zif_abapgit_definitions=>c_action-url }?url={ lv_display_url }| iv_title = 'Commit' iv_class = |url| ). CATCH zcx_abapgit_exception. ii_html->add( |{ lv_icon_commit }{ lv_commit_short_hash }| ). ENDTRY. ENDMETHOD. METHOD render_sci_result. DATA lv_icon TYPE string. lv_icon = ii_html->icon( iv_name = 'bug-solid' iv_hint = 'Code inspector result' ). CASE iv_sci_result. WHEN zif_abapgit_definitions=>c_sci_result-passed. ii_html->add( |{ lv_icon }PASSED| ). WHEN zif_abapgit_definitions=>c_sci_result-failed. ii_html->add( |{ lv_icon }FAILED| ). WHEN zif_abapgit_definitions=>c_sci_result-warning. ii_html->add( |{ lv_icon }WARN| ). WHEN OTHERS. "" Including NO_RUN RETURN. ENDCASE. ENDMETHOD. METHOD render_transport. DATA: lv_title TYPE string, lv_jump TYPE string. CREATE OBJECT ri_html TYPE zcl_abapgit_html. IF iv_transport IS INITIAL. RETURN. ENDIF. SELECT SINGLE as4text FROM e07t INTO lv_title WHERE trkorr = iv_transport AND langu = sy-langu ##SUBRC_OK. lv_jump = |{ zif_abapgit_definitions=>c_action-jump_transport }?transport={ iv_transport }|. IF iv_icon_only = abap_true. ri_html->add_a( iv_act = lv_jump iv_title = |Transport { iv_transport }| iv_txt = zcl_abapgit_html=>icon( 'truck-solid/darkgrey' ) ). ELSE. ri_html->add( || ). ri_html->add_icon( iv_name = 'truck-solid/grey70' iv_hint = 'Transport' ). IF iv_interactive = abap_true. ri_html->add_a( iv_act = lv_jump iv_title = lv_title iv_txt = |{ iv_transport }| ). ELSE. ri_html->add( iv_transport ). ENDIF. ri_html->add( '' ). ENDIF. ENDMETHOD. METHOD render_user_name. DATA: ls_user_address TYPE addr3_val, lv_title TYPE string, lv_jump TYPE string. CREATE OBJECT ri_html TYPE zcl_abapgit_html. IF iv_username IS INITIAL. RETURN. ENDIF. IF iv_username <> zcl_abapgit_objects_super=>c_user_unknown AND iv_suppress_title = abap_false. CALL FUNCTION 'SUSR_USER_ADDRESS_READ' EXPORTING user_name = iv_username IMPORTING user_address = ls_user_address EXCEPTIONS user_address_not_found = 1 OTHERS = 2. IF sy-subrc = 0. lv_title = ls_user_address-name_text. ENDIF. ENDIF. lv_jump = |{ zif_abapgit_definitions=>c_action-jump_user }?user={ iv_username }|. IF iv_icon_only = abap_true. ri_html->add_a( iv_act = lv_jump iv_title = lv_title iv_txt = zcl_abapgit_html=>icon( 'user-solid/darkgrey' ) ). ELSE. ri_html->add( || ). ri_html->add_icon( iv_name = 'user-solid/grey70' iv_hint = 'User name' ). IF iv_interactive = abap_true AND iv_username <> zcl_abapgit_objects_super=>c_user_unknown. ri_html->add_a( iv_act = lv_jump iv_title = lv_title iv_txt = |{ iv_username }| ). ELSE. ri_html->add( iv_username ). ENDIF. ri_html->add( '' ). ENDIF. ENDMETHOD. METHOD render_warning_banner. CREATE OBJECT ri_html TYPE zcl_abapgit_html. ri_html->add( '
' ). ri_html->add( |{ ri_html->icon( 'exclamation-triangle/yellow' ) } { iv_text }| ). ri_html->add( '
' ). ENDMETHOD. METHOD settings_repo_toolbar. CREATE OBJECT ro_menu EXPORTING iv_id = 'toolbar-repo-settings'. ro_menu->add( iv_txt = 'Repository' iv_act = |{ zif_abapgit_definitions=>c_action-repo_settings }?key={ iv_key }| iv_cur = boolc( iv_act = zif_abapgit_definitions=>c_action-repo_settings ) )->add( iv_txt = 'Local' iv_act = |{ zif_abapgit_definitions=>c_action-repo_local_settings }?key={ iv_key }| iv_cur = boolc( iv_act = zif_abapgit_definitions=>c_action-repo_local_settings ) )->add( iv_txt = 'Remote' iv_act = |{ zif_abapgit_definitions=>c_action-repo_remote_settings }?key={ iv_key }| iv_cur = boolc( iv_act = zif_abapgit_definitions=>c_action-repo_remote_settings ) )->add( iv_txt = 'Background' iv_act = |{ zif_abapgit_definitions=>c_action-repo_background }?key={ iv_key }| iv_cur = boolc( iv_act = zif_abapgit_definitions=>c_action-repo_background ) )->add( iv_txt = 'Stats' iv_act = |{ zif_abapgit_definitions=>c_action-repo_infos }?key={ iv_key }| iv_cur = boolc( iv_act = zif_abapgit_definitions=>c_action-repo_infos ) ). ENDMETHOD. METHOD settings_toolbar. CREATE OBJECT ro_menu EXPORTING iv_id = 'toolbar-settings'. ro_menu->add( iv_txt = 'Global' iv_act = zif_abapgit_definitions=>c_action-go_settings iv_cur = boolc( iv_act = zif_abapgit_definitions=>c_action-go_settings ) )->add( iv_txt = 'Personal' iv_act = zif_abapgit_definitions=>c_action-go_settings_personal iv_cur = boolc( iv_act = zif_abapgit_definitions=>c_action-go_settings_personal ) ). ENDMETHOD. ENDCLASS. ",9597,False,2107.26081571938,median "[[netty4-component]] == Netty4 Component *Available as of Camel version 2.14* The *netty4* component in Camel is a socket communication component, based on the http://netty.io/[Netty] project version 4. + Netty is a NIO client server framework which enables quick and easy development of networkServerInitializerFactory applications such as protocol servers and clients. + Netty greatly simplifies and streamlines network programming such as TCP and UDP socket server. This camel component supports both producer and consumer endpoints. The Netty component has several options and allows fine-grained control of a number of TCP/UDP communication parameters (buffer sizes, keepAlives, tcpNoDelay, etc) and facilitates both In-Only and In-Out communication on a Camel route. Maven users will need to add the following dependency to their `pom.xml` for this component: [source,xml] ---- org.apache.camel camel-netty4 x.x.x ---- === URI format The URI scheme for a netty component is as follows [source,text] ---- netty4:tcp://localhost:99999[?options] netty4:udp://remotehost:99999/[?options] ---- This component supports producer and consumer endpoints for both TCP and UDP. You can append query options to the URI in the following format, `?option=value&option=value&...` === Options // component options: START The Netty4 component supports 5 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *maximumPoolSize* (advanced) | The thread pool size for the EventExecutorGroup if its in use. The default value is 16. | 16 | int | *configuration* (advanced) | To use the NettyConfiguration as configuration when creating endpoints. | | NettyConfiguration | *executorService* (advanced) | To use the given EventExecutorGroup. | | EventExecutorGroup | *useGlobalSslContext Parameters* (security) | Enable usage of global SSL context parameters. | false | boolean | *resolveProperty Placeholders* (advanced) | Whether the component should resolve property placeholders on itself when starting. Only properties which are of String type can use property placeholders. | true | boolean |=== // component options: END // endpoint options: START The Netty4 endpoint is configured using URI syntax: ---- netty4:protocol:host:port ---- with the following path and query parameters: ==== Path Parameters (3 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *protocol* | *Required* The protocol to use which can be tcp or udp. | | String | *host* | *Required* The hostname. For the consumer the hostname is localhost or 0.0.0.0. For the producer the hostname is the remote host to connect to | | String | *port* | *Required* The host port number | | int |=== ==== Query Parameters (72 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *disconnect* (common) | Whether or not to disconnect(close) from Netty Channel right after use. Can be used for both consumer and producer. | false | boolean | *keepAlive* (common) | Setting to ensure socket is not closed due to inactivity | true | boolean | *reuseAddress* (common) | Setting to facilitate socket multiplexing | true | boolean | *reuseChannel* (common) | This option allows producers and consumers (in client mode) to reuse the same Netty Channel for the lifecycle of processing the Exchange. This is useful if you need to call a server multiple times in a Camel route and want to use the same network connection. When using this, the channel is not returned to the connection pool until the Exchange is done; or disconnected if the disconnect option is set to true. The reused Channel is stored on the Exchange as an exchange property with the key link NettyConstantsNETTY_CHANNEL which allows you to obtain the channel during routing and use it as well. | false | boolean | *sync* (common) | Setting to set endpoint as one-way or request-response | true | boolean | *tcpNoDelay* (common) | Setting to improve TCP protocol performance | true | boolean | *bridgeErrorHandler* (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | *broadcast* (consumer) | Setting to choose Multicast over UDP | false | boolean | *clientMode* (consumer) | If the clientMode is true, netty consumer will connect the address as a TCP client. | false | boolean | *reconnect* (consumer) | Used only in clientMode in consumer, the consumer will attempt to reconnect on disconnection if this is enabled | true | boolean | *reconnectInterval* (consumer) | Used if reconnect and clientMode is enabled. The interval in milli seconds to attempt reconnection | 10000 | int | *backlog* (consumer) | Allows to configure a backlog for netty consumer (server). Note the backlog is just a best effort depending on the OS. Setting this option to a value such as 200, 500 or 1000, tells the TCP stack how long the accept queue can be If this option is not configured, then the backlog depends on OS setting. | | int | *bossCount* (consumer) | When netty works on nio mode, it uses default bossCount parameter from Netty, which is 1. User can use this operation to override the default bossCount from Netty | 1 | int | *bossGroup* (consumer) | Set the BossGroup which could be used for handling the new connection of the server side across the NettyEndpoint | | EventLoopGroup | *disconnectOnNoReply* (consumer) | If sync is enabled then this option dictates NettyConsumer if it should disconnect where there is no reply to send back. | true | boolean | *exceptionHandler* (consumer) | To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this options is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored. | | ExceptionHandler | *exchangePattern* (consumer) | Sets the exchange pattern when the consumer creates an exchange. | | ExchangePattern | *nettyServerBootstrapFactory* (consumer) | To use a custom NettyServerBootstrapFactory | | NettyServerBootstrap Factory | *networkInterface* (consumer) | When using UDP then this option can be used to specify a network interface by its name, such as eth0 to join a multicast group. | | String | *noReplyLogLevel* (consumer) | If sync is enabled this option dictates NettyConsumer which logging level to use when logging a there is no reply to send back. | WARN | LoggingLevel | *serverClosedChannel ExceptionCaughtLogLevel* (consumer) | If the server (NettyConsumer) catches an java.nio.channels.ClosedChannelException then its logged using this logging level. This is used to avoid logging the closed channel exceptions, as clients can disconnect abruptly and then cause a flood of closed exceptions in the Netty server. | DEBUG | LoggingLevel | *serverExceptionCaughtLog Level* (consumer) | If the server (NettyConsumer) catches an exception then its logged using this logging level. | WARN | LoggingLevel | *serverInitializerFactory* (consumer) | To use a custom ServerInitializerFactory | | ServerInitializer Factory | *usingExecutorService* (consumer) | Whether to use ordered thread pool, to ensure events are processed orderly on the same channel. | true | boolean | *connectTimeout* (producer) | Time to wait for a socket connection to be available. Value is in milliseconds. | 10000 | int | *requestTimeout* (producer) | Allows to use a timeout for the Netty producer when calling a remote server. By default no timeout is in use. The value is in milli seconds, so eg 30000 is 30 seconds. The requestTimeout is using Netty's ReadTimeoutHandler to trigger the timeout. | | long | *clientInitializerFactory* (producer) | To use a custom ClientInitializerFactory | | ClientInitializer Factory | *correlationManager* (producer) | To use a custom correlation manager to manage how request and reply messages are mapped when using request/reply with the netty producer. This should only be used if you have a way to map requests together with replies such as if there is correlation ids in both the request and reply messages. This can be used if you want to multiplex concurrent messages on the same channel (aka connection) in netty. When doing this you must have a way to correlate the request and reply messages so you can store the right reply on the inflight Camel Exchange before its continued routed. We recommend extending the TimeoutCorrelationManagerSupport when you build custom correlation managers. This provides support for timeout and other complexities you otherwise would need to implement as well. See also the producerPoolEnabled option for more details. | | NettyCamelState CorrelationManager | *lazyChannelCreation* (producer) | Channels can be lazily created to avoid exceptions, if the remote server is not up and running when the Camel producer is started. | true | boolean | *producerPoolEnabled* (producer) | Whether producer pool is enabled or not. Important: If you turn this off then a single shared connection is used for the producer, also if you are doing request/reply. That means there is a potential issue with interleaved responses if replies comes back out-of-order. Therefore you need to have a correlation id in both the request and reply messages so you can properly correlate the replies to the Camel callback that is responsible for continue processing the message in Camel. To do this you need to implement NettyCamelStateCorrelationManager as correlation manager and configure it via the correlationManager option. See also the correlationManager option for more details. | true | boolean | *producerPoolMaxActive* (producer) | Sets the cap on the number of objects that can be allocated by the pool (checked out to clients, or idle awaiting checkout) at a given time. Use a negative value for no limit. | -1 | int | *producerPoolMaxIdle* (producer) | Sets the cap on the number of idle instances in the pool. | 100 | int | *producerPoolMinEvictable Idle* (producer) | Sets the minimum amount of time (value in millis) an object may sit idle in the pool before it is eligible for eviction by the idle object evictor. | 300000 | long | *producerPoolMinIdle* (producer) | Sets the minimum number of instances allowed in the producer pool before the evictor thread (if active) spawns new objects. | | int | *udpConnectionlessSending* (producer) | This option supports connection less udp sending which is a real fire and forget. A connected udp send receive the PortUnreachableException if no one is listen on the receiving port. | false | boolean | *useByteBuf* (producer) | If the useByteBuf is true, netty producer will turn the message body into ByteBuf before sending it out. | false | boolean | *allowSerializedHeaders* (advanced) | Only used for TCP when transferExchange is true. When set to true, serializable objects in headers and properties will be added to the exchange. Otherwise Camel will exclude any non-serializable objects and log it at WARN level. | false | boolean | *bootstrapConfiguration* (advanced) | To use a custom configured NettyServerBootstrapConfiguration for configuring this endpoint. | | NettyServerBootstrap Configuration | *channelGroup* (advanced) | To use a explicit ChannelGroup. | | ChannelGroup | *nativeTransport* (advanced) | Whether to use native transport instead of NIO. Native transport takes advantage of the host operating system and is only supported on some platforms. You need to add the netty JAR for the host operating system you are using. See more details at: http://netty.io/wiki/native-transports.html | false | boolean | *options* (advanced) | Allows to configure additional netty options using option. as prefix. For example option.child.keepAlive=false to set the netty option child.keepAlive=false. See the Netty documentation for possible options that can be used. | | Map | *receiveBufferSize* (advanced) | The TCP/UDP buffer sizes to be used during inbound communication. Size is bytes. | 65536 | int | *receiveBufferSizePredictor* (advanced) | Configures the buffer size predictor. See details at Jetty documentation and this mail thread. | | int | *sendBufferSize* (advanced) | The TCP/UDP buffer sizes to be used during outbound communication. Size is bytes. | 65536 | int | *synchronous* (advanced) | Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported). | false | boolean | *transferExchange* (advanced) | Only used for TCP. You can transfer the exchange over the wire instead of just the body. The following fields are transferred: In body, Out body, fault body, In headers, Out headers, fault headers, exchange properties, exchange exception. This requires that the objects are serializable. Camel will exclude any non-serializable objects and log it at WARN level. | false | boolean | *udpByteArrayCodec* (advanced) | For UDP only. If enabled the using byte array codec instead of Java serialization protocol. | false | boolean | *workerCount* (advanced) | When netty works on nio mode, it uses default workerCount parameter from Netty, which is cpu_core_threads x 2. User can use this operation to override the default workerCount from Netty. | | int | *workerGroup* (advanced) | To use a explicit EventLoopGroup as the boss thread pool. For example to share a thread pool with multiple consumers or producers. By default each consumer or producer has their own worker pool with 2 x cpu count core threads. | | EventLoopGroup | *allowDefaultCodec* (codec) | The netty component installs a default codec if both, encoder/deocder is null and textline is false. Setting allowDefaultCodec to false prevents the netty component from installing a default codec as the first element in the filter chain. | true | boolean | *autoAppendDelimiter* (codec) | Whether or not to auto append missing end delimiter when sending using the textline codec. | true | boolean | *decoder* (codec) | *Deprecated* A custom ChannelHandler class that can be used to perform special marshalling of inbound payloads. | | ChannelHandler | *decoderMaxLineLength* (codec) | The max line length to use for the textline codec. | 1024 | int | *decoders* (codec) | A list of decoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with so Camel knows it should lookup. | | String | *delimiter* (codec) | The delimiter to use for the textline codec. Possible values are LINE and NULL. | LINE | TextLineDelimiter | *encoder* (codec) | *Deprecated* A custom ChannelHandler class that can be used to perform special marshalling of outbound payloads. | | ChannelHandler | *encoders* (codec) | A list of encoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with so Camel knows it should lookup. | | String | *encoding* (codec) | The encoding (a charset name) to use for the textline codec. If not provided, Camel will use the JVM default Charset. | | String | *textline* (codec) | Only used for TCP. If no codec is specified, you can use this flag to indicate a text line based codec; if not specified or the value is false, then Object Serialization is assumed over TCP. | false | boolean | *enabledProtocols* (security) | Which protocols to enable when using SSL | TLSv1,TLSv1.1,TLSv1.2 | String | *keyStoreFile* (security) | Client side certificate keystore to be used for encryption | | File | *keyStoreFormat* (security) | Keystore format to be used for payload encryption. Defaults to JKS if not set | | String | *keyStoreResource* (security) | Client side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with classpath:, file:, or http: to load the resource from different systems. | | String | *needClientAuth* (security) | Configures whether the server needs client authentication when using SSL. | false | boolean | *passphrase* (security) | Password setting to use in order to encrypt/decrypt payloads sent using SSH | | String | *securityProvider* (security) | Security provider to be used for payload encryption. Defaults to SunX509 if not set. | | String | *ssl* (security) | Setting to specify whether SSL encryption is applied to this endpoint | false | boolean | *sslClientCertHeaders* (security) | When enabled and in SSL mode, then the Netty consumer will enrich the Camel Message with headers having information about the client certificate such as subject name, issuer name, serial number, and the valid date range. | false | boolean | *sslContextParameters* (security) | To configure security using SSLContextParameters | | SSLContextParameters | *sslHandler* (security) | Reference to a class that could be used to return an SSL Handler | | SslHandler | *trustStoreFile* (security) | Server side certificate keystore to be used for encryption | | File | *trustStoreResource* (security) | Server side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with classpath:, file:, or http: to load the resource from different systems. | | String |=== // endpoint options: END // spring-boot-auto-configure options: START === Spring Boot Auto-Configuration The component supports 77 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *camel.component.netty4.configuration.allow-default-codec* | The netty component installs a default codec if both, encoder/deocder is null and textline is false. Setting allowDefaultCodec to false prevents the netty component from installing a default codec as the first element in the filter chain. | true | Boolean | *camel.component.netty4.configuration.allow-serialized-headers* | Only used for TCP when transferExchange is true. When set to true, serializable objects in headers and properties will be added to the exchange. Otherwise Camel will exclude any non-serializable objects and log it at WARN level. | false | Boolean | *camel.component.netty4.configuration.auto-append-delimiter* | Whether or not to auto append missing end delimiter when sending using the textline codec. | true | Boolean | *camel.component.netty4.configuration.backlog* | Allows to configure a backlog for netty consumer (server). Note the backlog is just a best effort depending on the OS. Setting this option to a value such as 200, 500 or 1000, tells the TCP stack how long the accept queue can be If this option is not configured, then the backlog depends on OS setting. | | Integer | *camel.component.netty4.configuration.boss-count* | When netty works on nio mode, it uses default bossCount parameter from Netty, which is 1. User can use this operation to override the default bossCount from Netty | 1 | Integer | *camel.component.netty4.configuration.boss-group* | Set the BossGroup which could be used for handling the new connection of the server side across the NettyEndpoint | | EventLoopGroup | *camel.component.netty4.configuration.broadcast* | Setting to choose Multicast over UDP | false | Boolean | *camel.component.netty4.configuration.channel-group* | To use a explicit ChannelGroup. | | ChannelGroup | *camel.component.netty4.configuration.client-initializer-factory* | To use a custom ClientInitializerFactory | | ClientInitializer Factory | *camel.component.netty4.configuration.client-mode* | If the clientMode is true, netty consumer will connect the address as a TCP client. | false | Boolean | *camel.component.netty4.configuration.client-pipeline-factory* | @deprecated use #setClientInitializerFactory | | ClientInitializer Factory | *camel.component.netty4.configuration.connect-timeout* | Time to wait for a socket connection to be available. Value is in milliseconds. | 10000 | Integer | *camel.component.netty4.configuration.correlation-manager* | To use a custom correlation manager to manage how request and reply messages are mapped when using request/reply with the netty producer. This should only be used if you have a way to map requests together with replies such as if there is correlation ids in both the request and reply messages. This can be used if you want to multiplex concurrent messages on the same channel (aka connection) in netty. When doing this you must have a way to correlate the request and reply messages so you can store the right reply on the inflight Camel Exchange before its continued routed. We recommend extending the TimeoutCorrelationManagerSupport when you build custom correlation managers. This provides support for timeout and other complexities you otherwise would need to implement as well. See also the producerPoolEnabled option for more details. | | NettyCamelState CorrelationManager | *camel.component.netty4.configuration.decoder* | A custom ChannelHandler class that can be used to perform special marshalling of inbound payloads. | | ChannelHandler | *camel.component.netty4.configuration.decoder-max-line-length* | The max line length to use for the textline codec. | 1024 | Integer | *camel.component.netty4.configuration.decoders* | A list of decoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with so Camel knows it should lookup. | | List | *camel.component.netty4.configuration.delimiter* | The delimiter to use for the textline codec. Possible values are LINE and NULL. | | TextLineDelimiter | *camel.component.netty4.configuration.disconnect* | Whether or not to disconnect(close) from Netty Channel right after use. Can be used for both consumer and producer. | false | Boolean | *camel.component.netty4.configuration.disconnect-on-no-reply* | If sync is enabled then this option dictates NettyConsumer if it should disconnect where there is no reply to send back. | true | Boolean | *camel.component.netty4.configuration.enabled-protocols* | Which protocols to enable when using SSL | TLSv1,TLSv1.1,TLSv1.2 | String | *camel.component.netty4.configuration.encoder* | A custom ChannelHandler class that can be used to perform special marshalling of outbound payloads. | | ChannelHandler | *camel.component.netty4.configuration.encoders* | A list of encoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with so Camel knows it should lookup. | | List | *camel.component.netty4.configuration.encoding* | The encoding (a charset name) to use for the textline codec. If not provided, Camel will use the JVM default Charset. | | String | *camel.component.netty4.configuration.host* | The hostname. For the consumer the hostname is localhost or 0.0.0.0. For the producer the hostname is the remote host to connect to | | String | *camel.component.netty4.configuration.keep-alive* | Setting to ensure socket is not closed due to inactivity | true | Boolean | *camel.component.netty4.configuration.key-store-file* | Client side certificate keystore to be used for encryption | | File | *camel.component.netty4.configuration.key-store-format* | Keystore format to be used for payload encryption. Defaults to JKS if not set | | String | *camel.component.netty4.configuration.key-store-resource* | Client side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with classpath:, file:, or http: to load the resource from different systems. | | String | *camel.component.netty4.configuration.lazy-channel-creation* | Channels can be lazily created to avoid exceptions, if the remote server is not up and running when the Camel producer is started. | true | Boolean | *camel.component.netty4.configuration.native-transport* | Whether to use native transport instead of NIO. Native transport takes advantage of the host operating system and is only supported on some platforms. You need to add the netty JAR for the host operating system you are using. See more details at: http://netty.io/wiki/native-transports.html | false | Boolean | *camel.component.netty4.configuration.need-client-auth* | Configures whether the server needs client authentication when using SSL. | false | Boolean | *camel.component.netty4.configuration.netty-server-bootstrap-factory* | To use a custom NettyServerBootstrapFactory | | NettyServerBootstrap Factory | *camel.component.netty4.configuration.network-interface* | When using UDP then this option can be used to specify a network interface by its name, such as eth0 to join a multicast group. | | String | *camel.component.netty4.configuration.no-reply-log-level* | If sync is enabled this option dictates NettyConsumer which logging level to use when logging a there is no reply to send back. | | LoggingLevel | *camel.component.netty4.configuration.options* | Allows to configure additional netty options using option. as prefix. For example option.child.keepAlive=false to set the netty option child.keepAlive=false. See the Netty documentation for possible options that can be used. | | Map | *camel.component.netty4.configuration.passphrase* | Password setting to use in order to encrypt/decrypt payloads sent using SSH | | String | *camel.component.netty4.configuration.port* | The host port number | | Integer | *camel.component.netty4.configuration.producer-pool-enabled* | Whether producer pool is enabled or not. Important: If you turn this off then a single shared connection is used for the producer, also if you are doing request/reply. That means there is a potential issue with interleaved responses if replies comes back out-of-order. Therefore you need to have a correlation id in both the request and reply messages so you can properly correlate the replies to the Camel callback that is responsible for continue processing the message in Camel. To do this you need to implement NettyCamelStateCorrelationManager as correlation manager and configure it via the correlationManager option. See also the correlationManager option for more details. | true | Boolean | *camel.component.netty4.configuration.producer-pool-max-active* | Sets the cap on the number of objects that can be allocated by the pool (checked out to clients, or idle awaiting checkout) at a given time. Use a negative value for no limit. | -1 | Integer | *camel.component.netty4.configuration.producer-pool-max-idle* | Sets the cap on the number of idle instances in the pool. | 100 | Integer | *camel.component.netty4.configuration.producer-pool-min-evictable-idle* | Sets the minimum amount of time (value in millis) an object may sit idle in the pool before it is eligible for eviction by the idle object evictor. | 300000 | Long | *camel.component.netty4.configuration.producer-pool-min-idle* | Sets the minimum number of instances allowed in the producer pool before the evictor thread (if active) spawns new objects. | | Integer | *camel.component.netty4.configuration.protocol* | The protocol to use which can be tcp or udp. | | String | *camel.component.netty4.configuration.receive-buffer-size* | The TCP/UDP buffer sizes to be used during inbound communication. Size is bytes. | 65536 | Integer | *camel.component.netty4.configuration.receive-buffer-size-predictor* | Configures the buffer size predictor. See details at Jetty documentation and this mail thread. | | Integer | *camel.component.netty4.configuration.reconnect* | Used only in clientMode in consumer, the consumer will attempt to reconnect on disconnection if this is enabled | true | Boolean | *camel.component.netty4.configuration.reconnect-interval* | Used if reconnect and clientMode is enabled. The interval in milli seconds to attempt reconnection | 10000 | Integer | *camel.component.netty4.configuration.request-timeout* | Allows to use a timeout for the Netty producer when calling a remote server. By default no timeout is in use. The value is in milli seconds, so eg 30000 is 30 seconds. The requestTimeout is using Netty's ReadTimeoutHandler to trigger the timeout. | | Long | *camel.component.netty4.configuration.reuse-address* | Setting to facilitate socket multiplexing | true | Boolean | *camel.component.netty4.configuration.reuse-channel* | This option allows producers and consumers (in client mode) to reuse the same Netty Channel for the lifecycle of processing the Exchange. This is useful if you need to call a server multiple times in a Camel route and want to use the same network connection. When using this, the channel is not returned to the connection pool until the Exchange is done; or disconnected if the disconnect option is set to true. The reused Channel is stored on the Exchange as an exchange property with the key link NettyConstantsNETTY_CHANNEL which allows you to obtain the channel during routing and use it as well. | false | Boolean | *camel.component.netty4.configuration.security-provider* | Security provider to be used for payload encryption. Defaults to SunX509 if not set. | | String | *camel.component.netty4.configuration.send-buffer-size* | The TCP/UDP buffer sizes to be used during outbound communication. Size is bytes. | 65536 | Integer | *camel.component.netty4.configuration.server-closed-channel-exception-caught-log-level* | If the server (NettyConsumer) catches an java.nio.channels.ClosedChannelException then its logged using this logging level. This is used to avoid logging the closed channel exceptions, as clients can disconnect abruptly and then cause a flood of closed exceptions in the Netty server. | | LoggingLevel | *camel.component.netty4.configuration.server-exception-caught-log-level* | If the server (NettyConsumer) catches an exception then its logged using this logging level. | | LoggingLevel | *camel.component.netty4.configuration.server-initializer-factory* | To use a custom ServerInitializerFactory | | ServerInitializer Factory | *camel.component.netty4.configuration.server-pipeline-factory* | @deprecated use #setServerInitializerFactory | | ServerInitializer Factory | *camel.component.netty4.configuration.ssl* | Setting to specify whether SSL encryption is applied to this endpoint | false | Boolean | *camel.component.netty4.configuration.ssl-client-cert-headers* | When enabled and in SSL mode, then the Netty consumer will enrich the Camel Message with headers having information about the client certificate such as subject name, issuer name, serial number, and the valid date range. | false | Boolean | *camel.component.netty4.configuration.ssl-context-parameters* | To configure security using SSLContextParameters | | SSLContextParameters | *camel.component.netty4.configuration.ssl-handler* | Reference to a class that could be used to return an SSL Handler | | SslHandler | *camel.component.netty4.configuration.sync* | Setting to set endpoint as one-way or request-response | true | Boolean | *camel.component.netty4.configuration.tcp-no-delay* | Setting to improve TCP protocol performance | true | Boolean | *camel.component.netty4.configuration.textline* | Only used for TCP. If no codec is specified, you can use this flag to indicate a text line based codec; if not specified or the value is false, then Object Serialization is assumed over TCP. | false | Boolean | *camel.component.netty4.configuration.transfer-exchange* | Only used for TCP. You can transfer the exchange over the wire instead of just the body. The following fields are transferred: In body, Out body, fault body, In headers, Out headers, fault headers, exchange properties, exchange exception. This requires that the objects are serializable. Camel will exclude any non-serializable objects and log it at WARN level. | false | Boolean | *camel.component.netty4.configuration.trust-store-file* | Server side certificate keystore to be used for encryption | | File | *camel.component.netty4.configuration.trust-store-resource* | Server side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with classpath:, file:, or http: to load the resource from different systems. | | String | *camel.component.netty4.configuration.udp-byte-array-codec* | For UDP only. If enabled the using byte array codec instead of Java serialization protocol. | false | Boolean | *camel.component.netty4.configuration.udp-connectionless-sending* | This option supports connection less udp sending which is a real fire and forget. A connected udp send receive the PortUnreachableException if no one is listen on the receiving port. | false | Boolean | *camel.component.netty4.configuration.use-byte-buf* | If the useByteBuf is true, netty producer will turn the message body into ByteBuf before sending it out. | false | Boolean | *camel.component.netty4.configuration.using-executor-service* | Whether to use ordered thread pool, to ensure events are processed orderly on the same channel. | true | Boolean | *camel.component.netty4.configuration.worker-count* | When netty works on nio mode, it uses default workerCount parameter from Netty, which is cpu_core_threads x 2. User can use this operation to override the default workerCount from Netty. | | Integer | *camel.component.netty4.configuration.worker-group* | To use a explicit EventLoopGroup as the boss thread pool. For example to share a thread pool with multiple consumers or producers. By default each consumer or producer has their own worker pool with 2 x cpu count core threads. | | EventLoopGroup | *camel.component.netty4.enabled* | Enable netty4 component | true | Boolean | *camel.component.netty4.executor-service* | To use the given EventExecutorGroup. The option is a io.netty.util.concurrent.EventExecutorGroup type. | | String | *camel.component.netty4.maximum-pool-size* | The thread pool size for the EventExecutorGroup if its in use. The default value is 16. | 16 | Integer | *camel.component.netty4.resolve-property-placeholders* | Whether the component should resolve property placeholders on itself when starting. Only properties which are of String type can use property placeholders. | true | Boolean | *camel.component.netty4.use-global-ssl-context-parameters* | Enable usage of global SSL context parameters. | false | Boolean |=== // spring-boot-auto-configure options: END === Registry based Options Codec Handlers and SSL Keystores can be enlisted in the Registry, such as in the Spring XML file. The values that could be passed in, are the following: [width=""100%"",cols=""10%,90%"",options=""header"",] |=== |Name |Description |`passphrase` |password setting to use in order to encrypt/decrypt payloads sent using SSH |`keyStoreFormat` |keystore format to be used for payload encryption. Defaults to ""JKS"" if not set |`securityProvider` |Security provider to be used for payload encryption. Defaults to ""SunX509"" if not set. |`keyStoreFile` |*deprecated:* Client side certificate keystore to be used for encryption |`trustStoreFile` |*deprecated:* Server side certificate keystore to be used for encryption |`keyStoreResource` |*Camel 2.11.1:* Client side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with `""classpath:""`, `""file:""`, or `""http:""` to load the resource from different systems. |`trustStoreResource` |*Camel 2.11.1:* Server side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with `""classpath:""`, `""file:""`, or `""http:""` to load the resource from different systems. |`sslHandler` |Reference to a class that could be used to return an SSL Handler |`encoder` |A custom `ChannelHandler` class that can be used to perform special marshalling of outbound payloads. Must override io.netty.channel.ChannelInboundHandlerAdapter. |`encoders` |A list of encoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. |`decoder` |A custom `ChannelHandler` class that can be used to perform special marshalling of inbound payloads. Must override io.netty.channel.ChannelOutboundHandlerAdapter. |`decoders` |A list of decoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. |=== NOTE: Read below about using non shareable encoders/decoders. ==== Using non shareable encoders or decoders If your encoders or decoders are not shareable (e.g. they don't have the @Shareable class annotation), then your encoder/decoder must implement the `org.apache.camel.component.netty.ChannelHandlerFactory` interface, and return a new instance in the `newChannelHandler` method. This is to ensure the encoder/decoder can safely be used. If this is not the case, then the Netty component will log a WARN when an endpoint is created. The Netty component offers a `org.apache.camel.component.netty.ChannelHandlerFactories` factory class, that has a number of commonly used methods. === Sending Messages to/from a Netty endpoint ==== Netty Producer In Producer mode, the component provides the ability to send payloads to a socket endpoint using either TCP or UDP protocols (with optional SSL support). The producer mode supports both one-way and request-response based operations. ==== Netty Consumer In Consumer mode, the component provides the ability to: * listen on a specified socket using either TCP or UDP protocols (with optional SSL support), * receive requests on the socket using text/xml, binary and serialized object based payloads and * send them along on a route as message exchanges. The consumer mode supports both one-way and request-response based operations. === Examples ==== A UDP Netty endpoint using Request-Reply and serialized object payload [source,java] ---- RouteBuilder builder = new RouteBuilder() { public void configure() { from(""netty4:udp://localhost:5155?sync=true"") .process(new Processor() { public void process(Exchange exchange) throws Exception { Poetry poetry = (Poetry) exchange.getIn().getBody(); poetry.setPoet(""Dr. Sarojini Naidu""); exchange.getOut().setBody(poetry); } } } }; ---- ==== A TCP based Netty consumer endpoint using One-way communication [source,java] ---- RouteBuilder builder = new RouteBuilder() { public void configure() { from(""netty4:tcp://localhost:5150"") .to(""mock:result""); } }; ---- ==== An SSL/TCP based Netty consumer endpoint using Request-Reply communication [[Netty4-UsingtheJSSEConfigurationUtility]] Using the JSSE Configuration Utility As of Camel 2.9, the Netty component supports SSL/TLS configuration through the link:camel-configuration-utilities.html[Camel JSSE Configuration Utility].  This utility greatly decreases the amount of component specific code you need to write and is configurable at the endpoint and component levels.  The following examples demonstrate how to use the utility with the Netty component. [[Netty4-Programmaticconfigurationofthecomponent]] Programmatic configuration of the component [source,java] ---- KeyStoreParameters ksp = new KeyStoreParameters(); ksp.setResource(""/users/home/server/keystore.jks""); ksp.setPassword(""keystorePassword""); KeyManagersParameters kmp = new KeyManagersParameters(); kmp.setKeyStore(ksp); kmp.setKeyPassword(""keyPassword""); SSLContextParameters scp = new SSLContextParameters(); scp.setKeyManagers(kmp); NettyComponent nettyComponent = getContext().getComponent(""netty4"", NettyComponent.class); nettyComponent.setSslContextParameters(scp); ---- [[Netty4-SpringDSLbasedconfigurationofendpoint]] Spring DSL based configuration of endpoint [source,xml] ---- ... ... ... ... ---- [[Netty4-UsingBasicSSL/TLSconfigurationontheJettyComponent]] Using Basic SSL/TLS configuration on the Jetty Component [source,java] ---- JndiRegistry registry = new JndiRegistry(createJndiContext()); registry.bind(""password"", ""changeit""); registry.bind(""ksf"", new File(""src/test/resources/keystore.jks"")); registry.bind(""tsf"", new File(""src/test/resources/keystore.jks"")); context.createRegistry(registry); context.addRoutes(new RouteBuilder() { public void configure() { String netty_ssl_endpoint = ""netty4:tcp://localhost:5150?sync=true&ssl=true&passphrase=#password"" + ""&keyStoreFile=#ksf&trustStoreFile=#tsf""; String return_string = ""When You Go Home, Tell Them Of Us And Say,"" + ""For Your Tomorrow, We Gave Our Today.""; from(netty_ssl_endpoint) .process(new Processor() { public void process(Exchange exchange) throws Exception { exchange.getOut().setBody(return_string); } } } }); ---- [[Netty4-GettingaccesstoSSLSessionandtheclientcertificate]] Getting access to SSLSession and the client certificate You can get access to the `javax.net.ssl.SSLSession` if you eg need to get details about the client certificate. When `ssl=true` then the <> component will store the `SSLSession` as a header on the Camel Message as shown below: [source,java] ---- SSLSession session = exchange.getIn().getHeader(NettyConstants.NETTY_SSL_SESSION, SSLSession.class); // get the first certificate which is client certificate javax.security.cert.X509Certificate cert = session.getPeerCertificateChain()[0]; Principal principal = cert.getSubjectDN(); ---- Remember to set `needClientAuth=true` to authenticate the client, otherwise `SSLSession` cannot access information about the client certificate, and you may get an exception `javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated`. You may also get this exception if the client certificate is expired or not valid etc. TIP: The option `sslClientCertHeaders` can be set to `true` which then enriches the Camel Message with headers having details about the client certificate. For example the subject name is readily available in the header `CamelNettySSLClientCertSubjectName`. ==== Using Multiple Codecs In certain cases it may be necessary to add chains of encoders and decoders to the netty pipeline. To add multpile codecs to a camel netty endpoint the 'encoders' and 'decoders' uri parameters should be used. Like the 'encoder' and 'decoder' parameters they are used to supply references (lists of ChannelUpstreamHandlers and ChannelDownstreamHandlers) that should be added to the pipeline. Note that if encoders is specified then the encoder param will be ignored, similarly for decoders and the decoder param. NOTE: Read further above about using non shareable encoders/decoders. The lists of codecs need to be added to the Camel's registry so they can be resolved when the endpoint is created. [source,java] ---- ChannelHandlerFactory lengthDecoder = ChannelHandlerFactories.newLengthFieldBasedFrameDecoder(1048576, 0, 4, 0, 4); StringDecoder stringDecoder = new StringDecoder(); registry.bind(""length-decoder"", lengthDecoder); registry.bind(""string-decoder"", stringDecoder); LengthFieldPrepender lengthEncoder = new LengthFieldPrepender(4); StringEncoder stringEncoder = new StringEncoder(); registry.bind(""length-encoder"", lengthEncoder); registry.bind(""string-encoder"", stringEncoder); List decoders = new ArrayList(); decoders.add(lengthDecoder); decoders.add(stringDecoder); List encoders = new ArrayList(); encoders.add(lengthEncoder); encoders.add(stringEncoder); registry.bind(""encoders"", encoders); registry.bind(""decoders"", decoders); ---- Spring's native collections support can be used to specify the codec lists in an application context [source,xml] ---- ---- The bean names can then be used in netty endpoint definitions either as a comma separated list or contained in a List e.g. [source,java] ---- from(""direct:multiple-codec"").to(""netty4:tcp://localhost:{{port}}?encoders=#encoders&sync=false""); from(""netty4:tcp://localhost:{{port}}?decoders=#length-decoder,#string-decoder&sync=false"").to(""mock:multiple-codec""); ---- or via XML. [source,xml] ---- ---- === Closing Channel When Complete When acting as a server you sometimes want to close the channel when, for example, a client conversion is finished. + You can do this by simply setting the endpoint option `disconnect=true`. However you can also instruct Camel on a per message basis as follows. + To instruct Camel to close the channel, you should add a header with the key `CamelNettyCloseChannelWhenComplete` set to a boolean `true` value. + For instance, the example below will close the channel after it has written the bye message back to the client: [source,java] ---- from(""netty4:tcp://localhost:8080"").process(new Processor() { public void process(Exchange exchange) throws Exception { String body = exchange.getIn().getBody(String.class); exchange.getOut().setBody(""Bye "" + body); // some condition which determines if we should close if (close) { exchange.getOut().setHeader(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, true); } } }); ---- [[Netty4-Addingcustomchannelpipelinefactoriestogaincompletecontroloveracreatedpipeline]] Adding custom channel pipeline factories to gain complete control over a created pipeline === Custom pipeline Custom channel pipelines provide complete control to the user over the handler/interceptor chain by inserting custom handler(s), encoder(s) & decoder(s) without having to specify them in the Netty Endpoint URL in a very simple way. In order to add a custom pipeline, a custom channel pipeline factory must be created and registered with the context via the context registry (JNDIRegistry, or the camel-spring ApplicationContextRegistry etc). A custom pipeline factory must be constructed as follows * A Producer linked channel pipeline factory must extend the abstract class `ClientPipelineFactory`. * A Consumer linked channel pipeline factory must extend the abstract class `ServerInitializerFactory`. * The classes should override the initChannel() method in order to insert custom handler(s), encoder(s) and decoder(s). Not overriding the `initChannel()` method creates a pipeline with no handlers, encoders or decoders wired to the pipeline. The example below shows how ServerInitializerFactory factory may be created ==== Using custom pipeline factory [source,java] ---- public class SampleServerInitializerFactory extends ServerInitializerFactory { private int maxLineSize = 1024; protected void initChannel(Channel ch) throws Exception { ChannelPipeline channelPipeline = ch.pipeline(); channelPipeline.addLast(""encoder-SD"", new StringEncoder(CharsetUtil.UTF_8)); channelPipeline.addLast(""decoder-DELIM"", new DelimiterBasedFrameDecoder(maxLineSize, true, Delimiters.lineDelimiter())); channelPipeline.addLast(""decoder-SD"", new StringDecoder(CharsetUtil.UTF_8)); // here we add the default Camel ServerChannelHandler for the consumer, to allow Camel to route the message etc. channelPipeline.addLast(""handler"", new ServerChannelHandler(consumer)); } } ---- The custom channel pipeline factory can then be added to the registry and instantiated/utilized on a camel route in the following way [source,java] ---- Registry registry = camelContext.getRegistry(); ServerInitializerFactory factory = new TestServerInitializerFactory(); registry.bind(""spf"", factory); context.addRoutes(new RouteBuilder() { public void configure() { String netty_ssl_endpoint = ""netty4:tcp://localhost:5150?serverInitializerFactory=#spf"" String return_string = ""When You Go Home, Tell Them Of Us And Say,"" + ""For Your Tomorrow, We Gave Our Today.""; from(netty_ssl_endpoint) .process(new Processor() { public void process(Exchange exchange) throws Exception { exchange.getOut().setBody(return_string); } } } }); ---- === Reusing Netty boss and worker thread pools Netty has two kind of thread pools: boss and worker. By default each Netty consumer and producer has their private thread pools. If you want to reuse these thread pools among multiple consumers or producers then the thread pools must be created and enlisted in the Registry. For example using Spring XML we can create a shared worker thread pool using the `NettyWorkerPoolBuilder` with 2 worker threads as shown below: [source,xml] ---- ---- TIP: For boss thread pool there is a `org.apache.camel.component.netty4.NettyServerBossPoolBuilder` builder for Netty consumers, and a `org.apache.camel.component.netty4.NettyClientBossPoolBuilder` for the Netty producers. Then in the Camel routes we can refer to this worker pools by configuring the `workerPool` option in the https://cwiki.apache.org/confluence/pages/createpage.action?spaceKey=CAMEL&title=URI&linkCreation=true&fromPageId=45877614[URI] as shown below: [source,xml] ---- ... ---- And if we have another route we can refer to the shared worker pool: [source,xml] ---- ... ---- and so forth. === Multiplexing concurrent messages over a single connection with request/reply When using Netty for request/reply messaging via the netty producer then by default each message is sent via a non-shared connection (pooled). This ensures that replies are automatic being able to map to the correct request thread for further routing in Camel. In other words correlation between request/reply messages happens out-of-the-box because the replies comes back on the same connection that was used for sending the request; and this connection is not shared with others. When the response comes back, the connection is returned back to the connection pool, where it can be reused by others. However if you want to multiplex concurrent request/responses on a single shared connection, then you need to turn off the connection pooling by setting `producerPoolEnabled=false`. Now this means there is a potential issue with interleaved responses if replies comes back out-of-order. Therefore you need to have a correlation id in both the request and reply messages so you can properly correlate the replies to the Camel callback that is responsible for continue processing the message in Camel. To do this you need to implement `NettyCamelStateCorrelationManager` as correlation manager and configure it via the `correlationManager=#myManager` option. NOTE: We recommend extending the `TimeoutCorrelationManagerSupport` when you build custom correlation managers. This provides support for timeout and other complexities you otherwise would need to implement as well. You can find an example with the Apache Camel source code in the examples directory under the `camel-example-netty-custom-correlation` directory. === See Also * <> * <> ",12443,False,2324.210416361285,median "CLASS zcl_abapgit_objects DEFINITION PUBLIC CREATE PUBLIC . PUBLIC SECTION. TYPES: ty_types_tt TYPE SORTED TABLE OF tadir-object WITH UNIQUE KEY table_line . TYPES: BEGIN OF ty_serialization, files TYPE zif_abapgit_definitions=>ty_files_tt, item TYPE zif_abapgit_definitions=>ty_item, END OF ty_serialization . CLASS-METHODS serialize IMPORTING !is_item TYPE zif_abapgit_definitions=>ty_item !iv_language TYPE spras !iv_main_language_only TYPE abap_bool DEFAULT abap_false !it_translation_langs TYPE zif_abapgit_definitions=>ty_languages OPTIONAL RETURNING VALUE(rs_files_and_item) TYPE ty_serialization RAISING zcx_abapgit_exception . CLASS-METHODS deserialize IMPORTING !io_repo TYPE REF TO zcl_abapgit_repo !is_checks TYPE zif_abapgit_definitions=>ty_deserialize_checks !ii_log TYPE REF TO zif_abapgit_log RETURNING VALUE(rt_accessed_files) TYPE zif_abapgit_definitions=>ty_file_signatures_tt RAISING zcx_abapgit_exception . CLASS-METHODS deserialize_checks IMPORTING !io_repo TYPE REF TO zcl_abapgit_repo RETURNING VALUE(rs_checks) TYPE zif_abapgit_definitions=>ty_deserialize_checks RAISING zcx_abapgit_exception . CLASS-METHODS delete IMPORTING !it_tadir TYPE zif_abapgit_definitions=>ty_tadir_tt !is_checks TYPE zif_abapgit_definitions=>ty_delete_checks OPTIONAL !ii_log TYPE REF TO zif_abapgit_log OPTIONAL RAISING zcx_abapgit_exception . CLASS-METHODS jump IMPORTING !is_item TYPE zif_abapgit_definitions=>ty_item !iv_line_number TYPE i OPTIONAL !iv_sub_obj_name TYPE zif_abapgit_definitions=>ty_item-obj_name OPTIONAL !iv_sub_obj_type TYPE zif_abapgit_definitions=>ty_item-obj_type OPTIONAL RAISING zcx_abapgit_exception . CLASS-METHODS changed_by IMPORTING !is_item TYPE zif_abapgit_definitions=>ty_item RETURNING VALUE(rv_user) TYPE xubname . CLASS-METHODS is_supported IMPORTING !is_item TYPE zif_abapgit_definitions=>ty_item !iv_native_only TYPE abap_bool DEFAULT abap_false RETURNING VALUE(rv_bool) TYPE abap_bool . CLASS-METHODS is_type_supported IMPORTING !iv_obj_type TYPE zif_abapgit_definitions=>ty_item-obj_type RETURNING VALUE(rv_bool) TYPE abap_bool . CLASS-METHODS exists IMPORTING !is_item TYPE zif_abapgit_definitions=>ty_item RETURNING VALUE(rv_bool) TYPE abap_bool . CLASS-METHODS supported_list RETURNING VALUE(rt_types) TYPE ty_types_tt . CLASS-METHODS is_active IMPORTING !is_item TYPE zif_abapgit_definitions=>ty_item RETURNING VALUE(rv_active) TYPE abap_bool RAISING zcx_abapgit_exception . PROTECTED SECTION. PRIVATE SECTION. TYPES: BEGIN OF ty_obj_serializer_item, item TYPE zif_abapgit_definitions=>ty_item, metadata TYPE zif_abapgit_definitions=>ty_metadata, END OF ty_obj_serializer_item . TYPES: ty_obj_serializer_map TYPE SORTED TABLE OF ty_obj_serializer_item WITH UNIQUE KEY item . CLASS-DATA gt_obj_serializer_map TYPE ty_obj_serializer_map . CLASS-DATA gt_supported_obj_types TYPE ty_types_tt . CLASS-METHODS check_duplicates IMPORTING !it_files TYPE zif_abapgit_definitions=>ty_files_tt RAISING zcx_abapgit_exception . CLASS-METHODS class_name IMPORTING !is_item TYPE zif_abapgit_definitions=>ty_item RETURNING VALUE(rv_class_name) TYPE string . CLASS-METHODS update_package_tree IMPORTING !iv_package TYPE devclass . CLASS-METHODS delete_object IMPORTING !iv_package TYPE devclass !is_item TYPE zif_abapgit_definitions=>ty_item RAISING zcx_abapgit_exception . CLASS-METHODS compare_remote_to_local IMPORTING !ii_object TYPE REF TO zif_abapgit_object !it_remote TYPE zif_abapgit_definitions=>ty_files_tt !is_result TYPE zif_abapgit_definitions=>ty_result !ii_log TYPE REF TO zif_abapgit_log RAISING zcx_abapgit_exception . CLASS-METHODS deserialize_objects IMPORTING !is_step TYPE zif_abapgit_objects=>ty_step_data !ii_log TYPE REF TO zif_abapgit_log CHANGING !ct_files TYPE zif_abapgit_definitions=>ty_file_signatures_tt RAISING zcx_abapgit_exception . CLASS-METHODS check_objects_locked IMPORTING !iv_language TYPE spras !it_items TYPE zif_abapgit_definitions=>ty_items_tt RAISING zcx_abapgit_exception . CLASS-METHODS create_object IMPORTING !is_item TYPE zif_abapgit_definitions=>ty_item !iv_language TYPE spras !is_metadata TYPE zif_abapgit_definitions=>ty_metadata OPTIONAL !iv_native_only TYPE abap_bool DEFAULT abap_false RETURNING VALUE(ri_obj) TYPE REF TO zif_abapgit_object RAISING zcx_abapgit_exception . CLASS-METHODS map_tadir_to_items IMPORTING !it_tadir TYPE zif_abapgit_definitions=>ty_tadir_tt RETURNING VALUE(rt_items) TYPE zif_abapgit_definitions=>ty_items_tt . CLASS-METHODS map_results_to_items IMPORTING !it_results TYPE zif_abapgit_definitions=>ty_results_tt RETURNING VALUE(rt_items) TYPE zif_abapgit_definitions=>ty_items_tt . CLASS-METHODS get_deserialize_steps RETURNING VALUE(rt_steps) TYPE zif_abapgit_objects=>ty_step_data_tt . CLASS-METHODS check_main_package IMPORTING !iv_package TYPE devclass !iv_obj_type TYPE tadir-object RAISING zcx_abapgit_exception . CLASS-METHODS change_package_assignments IMPORTING !is_item TYPE zif_abapgit_definitions=>ty_item !ii_log TYPE REF TO zif_abapgit_log. ENDCLASS. CLASS zcl_abapgit_objects IMPLEMENTATION. METHOD changed_by. DATA: li_obj TYPE REF TO zif_abapgit_object. "" For unsupported objects, return empty string IF is_type_supported( is_item-obj_type ) = abap_false. RETURN. ENDIF. TRY. li_obj = create_object( is_item = is_item iv_language = zif_abapgit_definitions=>c_english ). rv_user = li_obj->changed_by( ). CATCH zcx_abapgit_exception ##NO_HANDLER. "" Ignore errors ENDTRY. IF rv_user IS INITIAL. "" Eg. "".abapgit.xml"" file rv_user = zcl_abapgit_objects_super=>c_user_unknown. ENDIF. ENDMETHOD. METHOD change_package_assignments. CALL FUNCTION 'TR_TADIR_INTERFACE' EXPORTING wi_tadir_pgmid = 'R3TR' wi_tadir_object = is_item-obj_type wi_tadir_obj_name = is_item-obj_name wi_tadir_devclass = is_item-devclass wi_test_modus = abap_false EXCEPTIONS OTHERS = 1. IF sy-subrc = 0. ii_log->add_success( iv_msg = |Object { is_item-obj_name } assigned to package { is_item-devclass }| is_item = is_item ). ELSE. ii_log->add_error( iv_msg = |Package change of object { is_item-obj_name } failed| is_item = is_item ). ENDIF. ENDMETHOD. METHOD check_duplicates. DATA: lt_files TYPE zif_abapgit_definitions=>ty_files_tt, lv_path TYPE string, lv_filename TYPE string, lt_duplicates TYPE STANDARD TABLE OF string WITH DEFAULT KEY, lv_duplicates LIKE LINE OF lt_duplicates, lv_all_duplicates TYPE string. FIELD-SYMBOLS: LIKE LINE OF it_files. lt_files = it_files. SORT lt_files BY path ASCENDING filename ASCENDING. LOOP AT lt_files ASSIGNING . IF lv_path = -path AND lv_filename = -filename. CONCATENATE -path -filename INTO lv_duplicates. APPEND lv_duplicates TO lt_duplicates. ENDIF. lv_path = -path. lv_filename = -filename. ENDLOOP. IF lt_duplicates IS NOT INITIAL. CONCATENATE LINES OF lt_duplicates INTO lv_all_duplicates SEPARATED BY `, `. zcx_abapgit_exception=>raise( |Duplicates: { lv_all_duplicates }| ). ENDIF. ENDMETHOD. METHOD check_main_package. "" check package restrictions, closed package, descriptive or "" functional package cl_pak_object_types=>check_object_type( EXPORTING i_working_mode = 'I' i_package_name = iv_package i_pgmid = 'R3TR' i_object_type = iv_obj_type EXCEPTIONS wrong_object_type = 1 package_not_extensible = 2 package_not_loaded = 3 OTHERS = 4 ). CASE sy-subrc. WHEN 0. RETURN. WHEN 2. zcx_abapgit_exception=>raise( |Object type { iv_obj_type } not allowed for package { iv_package }| ). WHEN OTHERS. zcx_abapgit_exception=>raise_t100( ). ENDCASE. ENDMETHOD. METHOD check_objects_locked. DATA: li_obj TYPE REF TO zif_abapgit_object. FIELD-SYMBOLS: LIKE LINE OF it_items. LOOP AT it_items ASSIGNING . "" You should remember that we ignore not supported objects here, "" because otherwise the process aborts which is not desired IF is_type_supported( -obj_type ) = abap_false. CONTINUE. ENDIF. li_obj = create_object( is_item = iv_language = iv_language ). IF li_obj->is_locked( ) = abap_true. zcx_abapgit_exception=>raise( |Object { -obj_type } { -obj_name } | && |is locked. Action not possible.| ). ENDIF. ENDLOOP. ENDMETHOD. METHOD class_name. CONCATENATE 'ZCL_ABAPGIT_OBJECT_' is_item-obj_type INTO rv_class_name. ENDMETHOD. METHOD compare_remote_to_local. * this method is used for comparing local with remote objects * before pull, this is useful eg. when overwriting a TABL object. * only the main XML file is used for comparison DATA: ls_remote_file TYPE zif_abapgit_definitions=>ty_file, li_remote_version TYPE REF TO zif_abapgit_xml_input, lv_count TYPE i, ls_result TYPE zif_abapgit_comparator=>ty_result, lv_answer TYPE string, li_comparator TYPE REF TO zif_abapgit_comparator, lv_gui_is_available TYPE abap_bool, ls_item TYPE zif_abapgit_definitions=>ty_item. FIND ALL OCCURRENCES OF '.' IN is_result-filename MATCH COUNT lv_count. IF is_result-filename CS '.XML' AND lv_count = 2. IF ii_object->exists( ) = abap_false. RETURN. ENDIF. READ TABLE it_remote WITH KEY file COMPONENTS filename = is_result-filename INTO ls_remote_file. IF sy-subrc <> 0. ""if file does not exist in remote, we don't need to validate RETURN. ENDIF. li_comparator = ii_object->get_comparator( ). IF NOT li_comparator IS BOUND. RETURN. ENDIF. CREATE OBJECT li_remote_version TYPE zcl_abapgit_xml_input EXPORTING iv_xml = zcl_abapgit_convert=>xstring_to_string_utf8( ls_remote_file-data ) iv_filename = ls_remote_file-filename. ls_result = li_comparator->compare( ii_remote = li_remote_version ii_log = ii_log ). IF ls_result-text IS INITIAL. RETURN. ENDIF. ""log comparison result ls_item-obj_type = is_result-obj_type. ls_item-obj_name = is_result-obj_name. ii_log->add_warning( iv_msg = ls_result-text is_item = ls_item ). ""continue or abort? lv_gui_is_available = zcl_abapgit_ui_factory=>get_gui_functions( )->gui_is_available( ). IF lv_gui_is_available = abap_true. CALL FUNCTION 'POPUP_TO_CONFIRM' EXPORTING titlebar = 'Warning' text_question = ls_result-text text_button_1 = 'Abort' icon_button_1 = 'ICON_CANCEL' text_button_2 = 'Pull anyway' icon_button_2 = 'ICON_OKAY' default_button = '2' display_cancel_button = abap_false IMPORTING answer = lv_answer EXCEPTIONS text_not_found = 1 OTHERS = 2. IF sy-subrc <> 0 OR lv_answer = 1. zcx_abapgit_exception=>raise( |Deserialization for object { is_result-obj_name } | & |(type { is_result-obj_type }) aborted by user| ). ENDIF. ELSE. zcx_abapgit_exception=>raise( |Deserialization for object { is_result-obj_name } | & |(type { is_result-obj_type }) aborted, user descision required| ). ENDIF. ENDIF. ENDMETHOD. METHOD create_object. DATA: lv_message TYPE string, lv_class_name TYPE string, ls_obj_serializer_map LIKE LINE OF gt_obj_serializer_map. READ TABLE gt_obj_serializer_map INTO ls_obj_serializer_map WITH KEY item = is_item. IF sy-subrc = 0. lv_class_name = ls_obj_serializer_map-metadata-class. ELSEIF is_metadata IS NOT INITIAL. * Metadata is provided only on deserialization * Once this has been triggered, the same deserializer shall be used * for subsequent processes. * Thus, buffer the metadata afterwards ls_obj_serializer_map-item = is_item. ls_obj_serializer_map-metadata = is_metadata. INSERT ls_obj_serializer_map INTO TABLE gt_obj_serializer_map. lv_class_name = is_metadata-class. ELSE. lv_class_name = class_name( is_item ). ENDIF. REPLACE FIRST OCCURRENCE OF 'LCL' IN lv_class_name WITH 'ZCL_ABAPGIT'. TRY. CREATE OBJECT ri_obj TYPE (lv_class_name) EXPORTING is_item = is_item iv_language = iv_language. CATCH cx_sy_create_object_error. lv_message = |Object type { is_item-obj_type } is not supported by this system|. IF iv_native_only = abap_false. TRY. "" 2nd step, try looking for plugins CREATE OBJECT ri_obj TYPE zcl_abapgit_objects_bridge EXPORTING is_item = is_item. CATCH cx_sy_create_object_error. zcx_abapgit_exception=>raise( lv_message ). ENDTRY. ELSE. "" No native support? -> fail zcx_abapgit_exception=>raise( lv_message ). ENDIF. ENDTRY. ENDMETHOD. METHOD delete. DATA: ls_item TYPE zif_abapgit_definitions=>ty_item, li_progress TYPE REF TO zif_abapgit_progress, lt_tadir LIKE it_tadir, lt_deleted LIKE it_tadir, lt_items TYPE zif_abapgit_definitions=>ty_items_tt, lx_error TYPE REF TO zcx_abapgit_exception, lv_count TYPE i. FIELD-SYMBOLS: LIKE LINE OF it_tadir. lt_tadir = it_tadir. IF is_checks-transport-required = abap_true. zcl_abapgit_default_transport=>get_instance( )->set( is_checks-transport-transport ). ENDIF. TRY. zcl_abapgit_dependencies=>resolve( CHANGING ct_tadir = lt_tadir ). li_progress = zcl_abapgit_progress=>get_instance( lines( lt_tadir ) ). lt_items = map_tadir_to_items( lt_tadir ). check_objects_locked( iv_language = zif_abapgit_definitions=>c_english it_items = lt_items ). CATCH zcx_abapgit_exception INTO lx_error. zcl_abapgit_default_transport=>get_instance( )->reset( ). RAISE EXCEPTION lx_error. ENDTRY. lv_count = 1. DO. CLEAR lt_deleted. LOOP AT lt_tadir ASSIGNING . li_progress->show( iv_current = lv_count iv_text = |Delete { -obj_name }| ). CLEAR ls_item. ls_item-obj_type = -object. ls_item-obj_name = -obj_name. TRY. delete_object( iv_package = -devclass is_item = ls_item ). INSERT INTO TABLE lt_deleted. DELETE lt_tadir. lv_count = lv_count + 1. "" make sure to save object deletions COMMIT WORK. CATCH zcx_abapgit_exception INTO lx_error. IF ii_log IS BOUND. ii_log->add_exception( ix_exc = lx_error is_item = ls_item ). ii_log->add_error( iv_msg = |Deletion of object { ls_item-obj_name } failed| is_item = ls_item ). ENDIF. ENDTRY. ENDLOOP. "" Exit if done or nothing else was deleted IF lines( lt_tadir ) = 0 OR lines( lt_deleted ) = 0. EXIT. ENDIF. ENDDO. zcl_abapgit_default_transport=>get_instance( )->reset( ). IF lx_error IS BOUND AND lines( lt_tadir ) > 0. zcx_abapgit_exception=>raise( 'Error during uninstall. Check the log.' ). ENDIF. li_progress->off( ). ENDMETHOD. METHOD delete_object. DATA: li_obj TYPE REF TO zif_abapgit_object. "" Nothing to do for unsupported objects IF is_type_supported( is_item-obj_type ) = abap_false. RETURN. ENDIF. li_obj = create_object( is_item = is_item iv_language = zif_abapgit_definitions=>c_english ). li_obj->delete( iv_package ). IF li_obj->get_metadata( )-delete_tadir = abap_true. CALL FUNCTION 'TR_TADIR_INTERFACE' EXPORTING wi_delete_tadir_entry = abap_true wi_tadir_pgmid = 'R3TR' wi_tadir_object = is_item-obj_type wi_tadir_obj_name = is_item-obj_name wi_test_modus = abap_false EXCEPTIONS OTHERS = 1 ##FM_SUBRC_OK. "" We deliberately ignore the subrc, because throwing an exception would "" break the deletion of lots of object types. On the other hand we have "" to catch the exceptions because otherwise messages would directly be issued "" by the function module and change the control flow. Thus breaking the "" deletion of TOBJ and other object types. "" TODO: This is not very clean and has to be improved in the future. See PR 2741. ENDIF. ENDMETHOD. METHOD deserialize. DATA: ls_item TYPE zif_abapgit_definitions=>ty_item, li_obj TYPE REF TO zif_abapgit_object, lt_remote TYPE zif_abapgit_definitions=>ty_files_tt, lv_package TYPE devclass, lo_files TYPE REF TO zcl_abapgit_objects_files, lo_xml TYPE REF TO zif_abapgit_xml_input, lt_results TYPE zif_abapgit_definitions=>ty_results_tt, li_progress TYPE REF TO zif_abapgit_progress, lv_path TYPE string, lt_items TYPE zif_abapgit_definitions=>ty_items_tt, lt_steps_id TYPE zif_abapgit_definitions=>ty_deserialization_step_tt, lt_steps TYPE zif_abapgit_objects=>ty_step_data_tt, lx_exc TYPE REF TO zcx_abapgit_exception. DATA: lo_folder_logic TYPE REF TO zcl_abapgit_folder_logic. FIELD-SYMBOLS: TYPE zif_abapgit_definitions=>ty_result, TYPE LINE OF zif_abapgit_definitions=>ty_deserialization_step_tt, TYPE LINE OF zif_abapgit_objects=>ty_step_data_tt, TYPE LINE OF zif_abapgit_objects=>ty_deserialization_tt. lt_steps = get_deserialize_steps( ). lv_package = io_repo->get_package( ). IF is_checks-transport-required = abap_true. zcl_abapgit_default_transport=>get_instance( )->set( is_checks-transport-transport ). ENDIF. zcl_abapgit_objects_activation=>clear( ). lt_remote = io_repo->get_files_remote( ). lt_results = zcl_abapgit_file_deserialize=>get_results( io_repo = io_repo ii_log = ii_log ). zcl_abapgit_objects_check=>checks_adjust( EXPORTING io_repo = io_repo is_checks = is_checks CHANGING ct_results = lt_results ). li_progress = zcl_abapgit_progress=>get_instance( lines( lt_results ) ). lt_items = map_results_to_items( lt_results ). check_objects_locked( iv_language = io_repo->get_dot_abapgit( )->get_main_language( ) it_items = lt_items ). lo_folder_logic = zcl_abapgit_folder_logic=>get_instance( ). LOOP AT lt_results ASSIGNING . li_progress->show( iv_current = sy-tabix iv_text = |Deserialize { -obj_name }| ). CLEAR ls_item. ls_item-obj_type = -obj_type. ls_item-obj_name = -obj_name. ""error handling & logging added TRY. "" If package does not exist yet, it will be created with this call lv_package = lo_folder_logic->path_to_package( iv_top = io_repo->get_package( ) io_dot = io_repo->get_dot_abapgit( ) iv_path = -path ). check_main_package( iv_package = lv_package iv_obj_type = ls_item-obj_type ). IF ls_item-obj_type = 'DEVC'. "" Packages have the same filename across different folders. The path needs to be supplied "" to find the correct file. lv_path = -path. ENDIF. IF -packmove = abap_true. "" Move object to new package ls_item-devclass = lv_package. change_package_assignments( is_item = ls_item ii_log = ii_log ). "" No other changes required CONTINUE. ENDIF. "" Create or update object CREATE OBJECT lo_files EXPORTING is_item = ls_item iv_path = lv_path. lo_files->set_files( lt_remote ). ""analyze XML in order to instantiate the proper serializer lo_xml = lo_files->read_xml( ). li_obj = create_object( is_item = ls_item iv_language = io_repo->get_dot_abapgit( )->get_main_language( ) is_metadata = lo_xml->get_metadata( ) ). compare_remote_to_local( ii_object = li_obj it_remote = lt_remote is_result = ii_log = ii_log ). li_obj->mo_files = lo_files. ""get required steps for deserialize the object lt_steps_id = li_obj->get_deserialize_steps( ). LOOP AT lt_steps_id ASSIGNING . READ TABLE lt_steps WITH KEY step_id = ASSIGNING . ASSERT sy-subrc = 0. IF -is_ddic = abap_true AND li_obj->get_metadata( )-ddic = abap_false. "" DDIC only for DDIC objects zcx_abapgit_exception=>raise( |Step { } is only for DDIC objects| ). ENDIF. APPEND INITIAL LINE TO -objects ASSIGNING . -item = ls_item. -obj = li_obj. -xml = lo_xml. -package = lv_package. ENDLOOP. CLEAR: lv_path, lv_package. CATCH zcx_abapgit_exception INTO lx_exc. ii_log->add_exception( ix_exc = lx_exc is_item = ls_item ). ii_log->add_error( iv_msg = |Import of object { ls_item-obj_name } failed| is_item = ls_item ). ""object should not be part of any deserialization step CONTINUE. ENDTRY. ENDLOOP. ""run deserialize for all steps and it's objects SORT lt_steps BY order. LOOP AT lt_steps ASSIGNING . deserialize_objects( EXPORTING is_step = ii_log = ii_log CHANGING ct_files = rt_accessed_files ). ENDLOOP. update_package_tree( io_repo->get_package( ) ). SORT rt_accessed_files BY path ASCENDING filename ASCENDING. DELETE ADJACENT DUPLICATES FROM rt_accessed_files. "" Just in case zcl_abapgit_default_transport=>get_instance( )->reset( ). li_progress->off( ). ENDMETHOD. METHOD deserialize_checks. rs_checks = zcl_abapgit_objects_check=>deserialize_checks( io_repo ). ENDMETHOD. METHOD deserialize_objects. DATA: li_progress TYPE REF TO zif_abapgit_progress, li_exit TYPE REF TO zif_abapgit_exit, lx_exc TYPE REF TO zcx_abapgit_exception. FIELD-SYMBOLS: LIKE LINE OF is_step-objects. zcl_abapgit_objects_activation=>clear( ). li_progress = zcl_abapgit_progress=>get_instance( lines( is_step-objects ) ). LOOP AT is_step-objects ASSIGNING . li_progress->show( iv_current = sy-tabix iv_text = |Deserialize { is_step-descr } - { -item-obj_name }| ). TRY. -obj->deserialize( iv_package = -package io_xml = -xml iv_step = is_step-step_id ii_log = ii_log ). APPEND LINES OF -obj->mo_files->get_accessed_files( ) TO ct_files. ii_log->add_success( iv_msg = |Object { -item-obj_name } imported| is_item = -item ). CATCH zcx_abapgit_exception INTO lx_exc. ii_log->add_exception( ix_exc = lx_exc is_item = -item ). ii_log->add_error( iv_msg = |Import of object { -item-obj_name } failed| is_item = -item ). ENDTRY. ENDLOOP. CASE is_step-step_id. WHEN zif_abapgit_object=>gc_step_id-ddic. zcl_abapgit_objects_activation=>activate( is_step-is_ddic ). WHEN zif_abapgit_object=>gc_step_id-abap. zcl_abapgit_objects_activation=>activate( is_step-is_ddic ). WHEN zif_abapgit_object=>gc_step_id-late. "" late can have both DDIC (like TABL with REF TO) and non-DDIC objects zcl_abapgit_objects_activation=>activate( abap_true ). zcl_abapgit_objects_activation=>activate( abap_false ). ENDCASE. * Call postprocessing li_exit = zcl_abapgit_exit=>get_instance( ). li_exit->deserialize_postprocess( is_step = is_step ii_log = ii_log ). ENDMETHOD. METHOD exists. DATA: li_obj TYPE REF TO zif_abapgit_object. "" For unsupported objects, assume object exists IF is_type_supported( is_item-obj_type ) = abap_false. rv_bool = abap_true. RETURN. ENDIF. TRY. li_obj = create_object( is_item = is_item iv_language = zif_abapgit_definitions=>c_english ). rv_bool = li_obj->exists( ). CATCH zcx_abapgit_exception. "" Ignore errors and assume the object exists rv_bool = abap_true. ENDTRY. ENDMETHOD. METHOD get_deserialize_steps. FIELD-SYMBOLS: TYPE LINE OF zif_abapgit_objects=>ty_step_data_tt. APPEND INITIAL LINE TO rt_steps ASSIGNING . -step_id = zif_abapgit_object=>gc_step_id-ddic. -descr = 'Import DDIC objects'. -is_ddic = abap_true. -syntax_check = abap_false. -order = 1. APPEND INITIAL LINE TO rt_steps ASSIGNING . -step_id = zif_abapgit_object=>gc_step_id-abap. -descr = 'Import objects main'. -is_ddic = abap_false. -syntax_check = abap_false. -order = 2. APPEND INITIAL LINE TO rt_steps ASSIGNING . -step_id = zif_abapgit_object=>gc_step_id-late. -descr = 'Import late objects'. -is_ddic = abap_false. -syntax_check = abap_true. -order = 3. ENDMETHOD. METHOD is_active. DATA: li_obj TYPE REF TO zif_abapgit_object. "" For unsupported objects, assume active state IF is_type_supported( is_item-obj_type ) = abap_false. rv_active = abap_true. RETURN. ENDIF. TRY. li_obj = create_object( is_item = is_item iv_language = zif_abapgit_definitions=>c_english ). rv_active = li_obj->is_active( ). CATCH cx_sy_dyn_call_illegal_method cx_sy_ref_is_initial zcx_abapgit_exception. "" Ignore errors and assume active state rv_active = abap_true. ENDTRY. ENDMETHOD. METHOD is_supported. TRY. create_object( is_item = is_item iv_language = zif_abapgit_definitions=>c_english iv_native_only = iv_native_only ). rv_bool = abap_true. CATCH zcx_abapgit_exception. rv_bool = abap_false. ENDTRY. ENDMETHOD. METHOD is_type_supported. "" If necessary, initialize list IF gt_supported_obj_types IS INITIAL. supported_list( ). ENDIF. READ TABLE gt_supported_obj_types TRANSPORTING NO FIELDS WITH TABLE KEY table_line = iv_obj_type. rv_bool = boolc( sy-subrc = 0 ). ENDMETHOD. METHOD jump. DATA: li_obj TYPE REF TO zif_abapgit_object, lv_exit TYPE abap_bool. "" Nothing to do for unsupported objects IF is_type_supported( is_item-obj_type ) = abap_false. zcx_abapgit_exception=>raise( |Object type { is_item-obj_type } is not supported by this system| ). ENDIF. "" Nothing to do if object does not exist li_obj = create_object( is_item = is_item iv_language = zif_abapgit_definitions=>c_english ). IF li_obj->exists( ) = abap_false. zcx_abapgit_exception=>raise( |Object { is_item-obj_type } { is_item-obj_name } doesn't exist| ). ENDIF. "" Open object in new window lv_exit = zcl_abapgit_ui_factory=>get_gui_jumper( )->jump( is_item = is_item iv_sub_obj_name = iv_sub_obj_name iv_sub_obj_type = iv_sub_obj_type iv_line_number = iv_line_number ). "" If all fails, try object-specific handler IF lv_exit IS INITIAL. li_obj->jump( ). ENDIF. ENDMETHOD. METHOD map_results_to_items. DATA: ls_item LIKE LINE OF rt_items. FIELD-SYMBOLS: TYPE zif_abapgit_definitions=>ty_result. LOOP AT it_results ASSIGNING . ls_item-devclass = -package. ls_item-obj_type = -obj_type. ls_item-obj_name = -obj_name. INSERT ls_item INTO TABLE rt_items. ENDLOOP. ENDMETHOD. METHOD map_tadir_to_items. DATA: ls_item LIKE LINE OF rt_items. FIELD-SYMBOLS: TYPE zif_abapgit_definitions=>ty_tadir. LOOP AT it_tadir ASSIGNING . ls_item-devclass = -devclass. ls_item-obj_type = -object. ls_item-obj_name = -obj_name. INSERT ls_item INTO TABLE rt_items. ENDLOOP. ENDMETHOD. METHOD serialize. DATA: li_obj TYPE REF TO zif_abapgit_object, li_xml TYPE REF TO zif_abapgit_xml_output, lo_files TYPE REF TO zcl_abapgit_objects_files, ls_i18n_params TYPE zif_abapgit_definitions=>ty_i18n_params. FIELD-SYMBOLS: LIKE LINE OF rs_files_and_item-files. rs_files_and_item-item = is_item. IF is_type_supported( rs_files_and_item-item-obj_type ) = abap_false. zcx_abapgit_exception=>raise( |Object type ignored, not supported: { rs_files_and_item-item-obj_type }-{ rs_files_and_item-item-obj_name }| ). ENDIF. CREATE OBJECT lo_files EXPORTING is_item = rs_files_and_item-item. li_obj = create_object( is_item = rs_files_and_item-item iv_language = iv_language ). li_obj->mo_files = lo_files. CREATE OBJECT li_xml TYPE zcl_abapgit_xml_output. ls_i18n_params-main_language = iv_language. ls_i18n_params-main_language_only = iv_main_language_only. ls_i18n_params-translation_languages = it_translation_langs. li_xml->i18n_params( ls_i18n_params ). li_obj->serialize( li_xml ). lo_files->add_xml( ii_xml = li_xml is_metadata = li_obj->get_metadata( ) ). rs_files_and_item-files = lo_files->get_files( ). check_duplicates( rs_files_and_item-files ). rs_files_and_item-item-inactive = boolc( li_obj->is_active( ) = abap_false ). LOOP AT rs_files_and_item-files ASSIGNING . -sha1 = zcl_abapgit_hash=>sha1_blob( -data ). ENDLOOP. ENDMETHOD. METHOD supported_list. DATA: lt_objects TYPE STANDARD TABLE OF ko100, ls_item TYPE zif_abapgit_definitions=>ty_item. FIELD-SYMBOLS LIKE LINE OF lt_objects. IF gt_supported_obj_types IS NOT INITIAL. rt_types = gt_supported_obj_types. RETURN. ENDIF. CALL FUNCTION 'TR_OBJECT_TABLE' TABLES wt_object_text = lt_objects EXCEPTIONS OTHERS = 1 ##FM_SUBRC_OK. LOOP AT lt_objects ASSIGNING WHERE pgmid = 'R3TR'. ls_item-obj_type = -object. IF is_supported( ls_item ) = abap_true. INSERT -object INTO TABLE rt_types. ENDIF. ENDLOOP. gt_supported_obj_types = rt_types. ENDMETHOD. METHOD update_package_tree. DATA: lt_packages TYPE zif_abapgit_sap_package=>ty_devclass_tt, lv_package LIKE LINE OF lt_packages, lv_tree TYPE dirtree-tname. lt_packages = zcl_abapgit_factory=>get_sap_package( iv_package )->list_subpackages( ). APPEND iv_package TO lt_packages. LOOP AT lt_packages INTO lv_package. * update package tree for SE80 lv_tree = 'EU_' && lv_package. CALL FUNCTION 'WB_TREE_ACTUALIZE' EXPORTING tree_name = lv_tree without_crossreference = abap_true with_tcode_index = abap_true. ENDLOOP. ENDMETHOD. ENDCLASS. ",8654,False,1993.0307892532162,median "/************************************************************************** * Copyright(c) 1998-2016, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided ""as is"" without express or implied warranty. * **************************************************************************/ #include #include #include #include #include #include #include #include #include #include #include #include #include ""AliParticleContainer.h"" #include ""AliClusterContainer.h"" #include ""AliTrackContainer.h"" #include ""AliCentrality.h"" #include ""AliVCluster.h"" #include ""AliVParticle.h"" #include ""AliVTrack.h"" #include ""AliLog.h"" #include ""AliEMCALGeometry.h"" #include ""AliEMCALGeoParams.h"" #include ""AliESDtrack.h"" #include ""AliAODTrack.h"" #include ""AliAODMCParticle.h"" #include ""AliMCParticleContainer.h"" #include ""AliEmcalJet.h"" #include ""AliJetContainer.h"" #include ""AliMCEvent.h"" #include ""AliGenPythiaEventHeader.h"" #include ""AliAODMCHeader.h"" #include ""AliPHOSGeometry.h"" #include ""AliOADBContainer.h"" #include ""AliAnalysisTaskPWGJEQA.h"" using std::cout; using std::endl; /// \\cond CLASSIMP ClassImp(AliAnalysisTaskPWGJEQA); /// \\endcond //________________________________________________________________________ /// Default constructor for ROOT I/O purposes AliAnalysisTaskPWGJEQA::AliAnalysisTaskPWGJEQA() : AliAnalysisTaskEmcalJet(""AliAnalysisTaskPWGJEQA"", kTRUE), fUseAliEventCuts(kTRUE), fEventCuts(0), fEventCutList(0), fUseManualEventCuts(kFALSE), fCellEnergyCut(0.05), fMaxPt(250), fNTotTracks(0), fLeadingTrack(), fDoTrackQA(kTRUE), fDoCaloQA(kTRUE), fDoJetQA(kTRUE), fDoEventQA(kTRUE), fGeneratorLevelName(), fDetectorLevelName(), fMCGeneratorIndex(-1), fRejectOutlierEvents(kFALSE), fIsPtHard(kFALSE), fGeneratorLevel(0), fDetectorLevel(0), fNPtHistBins(0), fPtHistBins(0), fNEtaHistBins(0), fEtaHistBins(0), fNPhiHistBins(0), fPhiHistBins(0), fNCentHistBins(0), fCentHistBins(0), fNPtRelDiffHistBins(0), fPtRelDiffHistBins(0), fNPtResHistBins(0), fPtResHistBins(0), fNIntegerHistBins(0), fIntegerHistBins(0), fPHOSGeo(nullptr), fHistManager(""AliAnalysisTaskPWGJEQA"") { // Default constructor. memset(fNTotClusters, 0, sizeof(Int_t)*3); SetMakeGeneralHistograms(kTRUE); GenerateHistoBins(); } //________________________________________________________________________ /// Standard named constructor /// /// \\param name Name of the task AliAnalysisTaskPWGJEQA::AliAnalysisTaskPWGJEQA(const char *name) : AliAnalysisTaskEmcalJet(name, kTRUE), fUseAliEventCuts(kTRUE), fEventCuts(0), fEventCutList(0), fUseManualEventCuts(kFALSE), fCellEnergyCut(0.05), fMaxPt(250), fNTotTracks(0), fLeadingTrack(), fDoTrackQA(kTRUE), fDoCaloQA(kTRUE), fDoJetQA(kTRUE), fDoEventQA(kTRUE), fGeneratorLevelName(), fDetectorLevelName(), fMCGeneratorIndex(-1), fRejectOutlierEvents(kFALSE), fIsPtHard(kFALSE), fGeneratorLevel(0), fDetectorLevel(0), fNPtHistBins(0), fPtHistBins(0), fNEtaHistBins(0), fEtaHistBins(0), fNPhiHistBins(0), fPhiHistBins(0), fNCentHistBins(0), fCentHistBins(0), fNPtRelDiffHistBins(0), fPtRelDiffHistBins(0), fNPtResHistBins(0), fPtResHistBins(0), fNIntegerHistBins(0), fIntegerHistBins(0), fPHOSGeo(nullptr), fHistManager(name) { // Standard memset(fNTotClusters, 0, sizeof(Int_t)*3); SetMakeGeneralHistograms(kTRUE); GenerateHistoBins(); } //________________________________________________________________________ AliAnalysisTaskPWGJEQA::~AliAnalysisTaskPWGJEQA() { // Destructor } //________________________________________________________________________ void AliAnalysisTaskPWGJEQA::UserCreateOutputObjects() { // Create histograms AliAnalysisTaskEmcalJet::UserCreateOutputObjects(); // Intialize AliEventCuts if (fUseAliEventCuts) { fEventCutList = new TList(); fEventCutList ->SetOwner(); fEventCutList ->SetName(""EventCutOutput""); fEventCuts.OverrideAutomaticTriggerSelection(fOffTrigger); if(fUseManualEventCuts==1) { fEventCuts.SetManualMode(); fEventCuts.fMC = MCEvent(); //before was= false if(fForceBeamType != kpp) { fEventCuts.SetupLHC15o(); fEventCuts.fUseVariablesCorrelationCuts = true; } else if(fForceBeamType == kpp) { fEventCuts.SetupRun2pp(); //no other cuts known so far } else { printf(""No implementation of manuel event cuts for pPb yet!""); } } fEventCuts.AddQAplotsToList(fEventCutList); fOutput->Add(fEventCutList); } // Set track container pointers fDetectorLevel = GetTrackContainer(fDetectorLevelName); fGeneratorLevel = GetMCParticleContainer(fGeneratorLevelName); // Allocate histograms for tracks, cells, clusters, jets if (fDoTrackQA) AllocateTrackHistograms(); if (fDoCaloQA) AllocateCellHistograms(); if (fDoCaloQA) AllocateClusterHistograms(); if (fDoJetQA) AllocateJetHistograms(); if (fDoEventQA) AllocateEventQAHistograms(); TIter next(fHistManager.GetListOfHistograms()); TObject* obj = 0; while ((obj = next())) { fOutput->Add(obj); } PostData(1, fOutput); // Post data for ALL output slots >0 here, to get at least an empty histogram } //________________________________________________________________________ void AliAnalysisTaskPWGJEQA::AllocateTrackHistograms() { AllocateDetectorLevelTHnSparse(); if (fGeneratorLevel) { AllocateGeneratorLevelTHnSparse(); AllocateMatchedParticlesTHnSparse(); } } //________________________________________________________________________ void AliAnalysisTaskPWGJEQA::AllocateCellHistograms() { TString histname; TString title; if (!fCaloCellsName.IsNull()) { histname = TString::Format(""%s/fHistCellEnergy"", fCaloCellsName.Data()); title = histname + "";#it{E}_{cell} (GeV);counts""; fHistManager.CreateTH1(histname.Data(), title.Data(), 500,0, 100); histname = TString::Format(""%s/fProfCellAbsIdEnergy"", fCaloCellsName.Data()); title = histname + "";cell absId;<#it{E}_{cell}> (GeV)""; fHistManager.CreateTProfile(histname.Data(), title.Data(), 18000,0,18000); histname = TString::Format(""%s/fHistCellTime"", fCaloCellsName.Data()); title = histname + "";#it{t}_{cell} (s);counts""; fHistManager.CreateTH1(histname.Data(), title.Data(), 500,-3e-6, 3e-6); histname = TString::Format(""%s/fProfCellAbsIdTime"", fCaloCellsName.Data()); title = histname + "";cell absId;<#it{t}_{cell}> (s)""; fHistManager.CreateTProfile(histname.Data(), title.Data(), 18000,0,18000); histname = TString::Format(""%s/fHistCellEvsTime"", fCaloCellsName.Data()); title = histname + "";<#it{t}_{cell}> (s);<#it{E}_{cell}> (GeV)""; fHistManager.CreateTH2(histname.Data(), title.Data(), 1000, -1e-6, 1e-6, 200, 0, 100); } } //________________________________________________________________________ void AliAnalysisTaskPWGJEQA::AllocateClusterHistograms() { AliEmcalContainer* cont = 0; TString histname; TString title; Int_t nPtBins = 2*fMaxPt; TIter nextClusColl(&fClusterCollArray); while ((cont = static_cast(nextClusColl()))) { histname = TString::Format(""%s/fHistClusterRejectionReason"", cont->GetArrayName().Data()); title = histname + "";Rejection reason;#it{E}_{clus} (GeV/);counts""; TH2* hist = fHistManager.CreateTH2(histname.Data(), title.Data(), 32, 0, 32, 50, 0, 250); SetRejectionReasonLabels(hist->GetXaxis()); histname = TString::Format(""%s/hPhosNCellsVsEnergy"", cont->GetArrayName().Data()); title = histname + "";N cells;#it{E}_{clus} (GeV/);counts""; fHistManager.CreateTH2(histname.Data(), title.Data(), 40, 0, 40, nPtBins, 0, fMaxPt); histname = TString::Format(""%s/hPhosM02VsEnergy"", cont->GetArrayName().Data()); title = histname + "";M02;#it{E}_{clus} (GeV/);counts""; fHistManager.CreateTH2(histname.Data(), title.Data(), 100, 0, 20, nPtBins, 0, fMaxPt); histname = TString::Format(""%s/hPhosCellIdVsEnergy"", cont->GetArrayName().Data()); title = histname + "";Cell ID;#it{E}_{clus} (GeV/);counts""; fHistManager.CreateTH2(histname.Data(), title.Data(), 20000, 0, 20000, nPtBins, 0, fMaxPt); const Int_t nEmcalSM = 20; for (Int_t sm = 0; sm < nEmcalSM; sm++) { histname = TString::Format(""%s/BySM/hEmcalClusEnergy_SM%d"", cont->GetArrayName().Data(), sm); title = histname + "";#it{E}_{cluster} (GeV);counts""; fHistManager.CreateTH1(histname.Data(), title.Data(), nPtBins, 0, fMaxPt); } for (Int_t sm = 1; sm < 5; sm++) { histname = TString::Format(""%s/BySM/hPhosClusEnergy_SM%d"", cont->GetArrayName().Data(), sm); title = histname + "";#it{E}_{cluster} (GeV);counts""; fHistManager.CreateTH1(histname.Data(), title.Data(), nPtBins, 0, fMaxPt); } // Cluster THnSparse Int_t dim = 0; TString title[20]; Int_t nbins[20] = {0}; Double_t min[30] = {0.}; Double_t max[30] = {0.}; Double_t *binEdges[20] = {0}; if (fForceBeamType != AliAnalysisTaskEmcal::kpp) { title[dim] = ""Centrality %""; nbins[dim] = fNCentHistBins; binEdges[dim] = fCentHistBins; min[dim] = fCentHistBins[0]; max[dim] = fCentHistBins[fNCentHistBins]; dim++; } title[dim] = ""#it{E}_{clus} (GeV)""; nbins[dim] = fNPtHistBins; binEdges[dim] = fPtHistBins; min[dim] = fPtHistBins[0]; max[dim] = fPtHistBins[fNPtHistBins]; dim++; title[dim] = ""#eta""; nbins[dim] = fNEtaHistBins; binEdges[dim] = fEtaHistBins; min[dim] = fEtaHistBins[0]; max[dim] = fEtaHistBins[fNEtaHistBins]; dim++; title[dim] = ""#phi""; nbins[dim] = fNPhiHistBins; binEdges[dim] = fPhiHistBins; min[dim] = fPhiHistBins[0]; max[dim] = fPhiHistBins[fNPhiHistBins]; dim++; title[dim] = ""cluster type""; nbins[dim] = 3; binEdges[dim] = fIntegerHistBins; min[dim] = fIntegerHistBins[0]; max[dim] = fIntegerHistBins[3]; dim++; TString thnname = TString::Format(""%s/clusterObservables"", cont->GetArrayName().Data()); THnSparse* hn = fHistManager.CreateTHnSparse(thnname.Data(), thnname.Data(), dim, nbins, min, max); for (Int_t i = 0; i < dim; i++) { hn->GetAxis(i)->SetTitle(title[i]); hn->SetBinEdges(i, binEdges[i]); } } } //________________________________________________________________________ void AliAnalysisTaskPWGJEQA::AllocateJetHistograms() { AliJetContainer* jets = 0; TIter nextJetColl(&fJetCollArray); while ((jets = static_cast(nextJetColl()))) { // Allocate THnSparse TString axisTitle[30]= {""""}; Int_t nbins[30] = {0}; Double_t min[30] = {0.}; Double_t max[30] = {0.}; Double_t *binEdges[20] = {0}; Int_t dim = 0; if (fForceBeamType != kpp) { axisTitle[dim] = ""Centrality (%)""; nbins[dim] = fNCentHistBins; binEdges[dim] = fCentHistBins; min[dim] = fCentHistBins[0]; max[dim] = fCentHistBins[fNCentHistBins]; dim++; } axisTitle[dim] = ""#eta_{jet}""; nbins[dim] = fNEtaHistBins; binEdges[dim] = fEtaHistBins; min[dim] = fEtaHistBins[0]; max[dim] = fEtaHistBins[fNEtaHistBins]; dim++; axisTitle[dim] = ""#phi_{jet} (rad)""; nbins[dim] = fNPhiHistBins; binEdges[dim] = fPhiHistBins; min[dim] = fPhiHistBins[0]; max[dim] = fPhiHistBins[fNPhiHistBins]; dim++; axisTitle[dim] = ""#it{p}_{T} (GeV/#it{c})""; nbins[dim] = TMath::CeilNint(fMaxPt/3); min[dim] = 0; max[dim] = fMaxPt; binEdges[dim] = GenerateFixedBinArray(nbins[dim], min[dim], max[dim]); dim++; if (fForceBeamType != kpp) { axisTitle[dim] = ""#it{p}_{T}^{corr} (GeV/#it{c})""; nbins[dim] = TMath::CeilNint(fMaxPt/3); min[dim] = -fMaxPt/2 + 25; max[dim] = fMaxPt/2 + 25; binEdges[dim] = GenerateFixedBinArray(nbins[dim], min[dim], max[dim]); dim++; } axisTitle[dim] = ""#it{p}_{T,particle}^{leading} (GeV/#it{c})""; nbins[dim] = fMaxPt/5; min[dim] = 0; max[dim] = 150; binEdges[dim] = GenerateFixedBinArray(nbins[dim], min[dim], max[dim]); dim++; TString thnname = TString::Format(""%s/fHistJetObservables"", jets->GetArrayName().Data()); THnSparse* hn = fHistManager.CreateTHnSparse(thnname.Data(), thnname.Data(), dim, nbins, min, max); for (Int_t i = 0; i < dim; i++) { hn->GetAxis(i)->SetTitle(axisTitle[i]); hn->SetBinEdges(i, binEdges[i]); } // Allocate other jet histograms TString histname; TString title; histname = TString::Format(""%s/fHistJetRejectionReason"", jets->GetArrayName().Data()); title = histname + "";Rejection reason;#it{p}_{T,jet} (GeV/#it{c});counts""; TH2* hist = fHistManager.CreateTH2(histname.Data(), title.Data(), 32, 0, 32, 50, 0, 250); SetRejectionReasonLabels(hist->GetXaxis()); if (!jets->GetRhoName().IsNull()) { histname = TString::Format(""%s/fHistRhoVsCent"", jets->GetArrayName().Data()); title = histname + "";Centrality (%);#rho (GeV/#it{c});counts""; fHistManager.CreateTH2(histname.Data(), title.Data(), 101, 0, 101, 100, 0, 500); } if (fForceBeamType != kpp) { histname = TString::Format(""%s/hNEFVsPtEMC"", jets->GetArrayName().Data()); title = histname + "";Centrality (%); #it{p}_{T}^{corr} (GeV/#it{c});NEF""; fHistManager.CreateTH3(histname.Data(), title.Data(), 20, 0, 100, 250, 0, 250, 50, 0, 1); histname = TString::Format(""%s/hNEFVsPtDCal"", jets->GetArrayName().Data()); title = histname + "";Centrality (%); #it{p}_{T}^{corr} (GeV/#it{c});NEF""; fHistManager.CreateTH3(histname.Data(), title.Data(), 20, 0, 100, 250, 0, 250, 50, 0, 1); histname = TString::Format(""%s/hDeltaEHadCorr"", jets->GetArrayName().Data()); title = histname + "";Centrality (%); #it{p}_{T}^{corr} (GeV/#it{c}); #sum #it{E_{nonlincorr}} - #it{E}_{hadcorr}""; fHistManager.CreateTH3(histname.Data(), title.Data(), 20, 0, 100, 250, 0, 250, 250, 0, 50); } else{ histname = TString::Format(""%s/hNEFVsPtEMC"", jets->GetArrayName().Data()); title = histname + "";#it{p}_{T}^{corr} (GeV/#it{c});NEF""; fHistManager.CreateTH2(histname.Data(), title.Data(), 250, 0, 250, 50, 0, 1); histname = TString::Format(""%s/hNEFVsPtDCal"", jets->GetArrayName().Data()); title = histname + "";#it{p}_{T}^{corr} (GeV/#it{c});NEF""; fHistManager.CreateTH2(histname.Data(), title.Data(), 250, 0, 250, 50, 0, 1); histname = TString::Format(""%s/hDeltaEHadCorr"", jets->GetArrayName().Data()); title = histname + "";#it{p}_{T}^{corr} (GeV/#it{c}); #sum#it{E_{nonlincorr}} - #it{E}_{hadcorr}""; fHistManager.CreateTH2(histname.Data(), title.Data(), 250, 0, 250, 250, 0, 50); } } } //________________________________________________________________________ void AliAnalysisTaskPWGJEQA::AllocateEventQAHistograms() { Int_t nPtBins = 2*fMaxPt; Int_t dim = 0; TString axistitle[40]; Int_t nbins[40] = {0}; Double_t min[40] = {0}; Double_t max[40] = {0}; Double_t *binEdges[20] = {0}; if (fForceBeamType != AliAnalysisTaskEmcal::kpp) { axistitle[dim] = ""Centrality %""; nbins[dim] = fNCentHistBins; binEdges[dim] = fCentHistBins; min[dim] = fCentHistBins[0]; max[dim] = fCentHistBins[fNCentHistBins]; dim++; } if (fParticleCollArray.GetEntriesFast()>0) { axistitle[dim] = ""No. of tracks""; if (fForceBeamType != AliAnalysisTaskEmcal::kpp) { nbins[dim] = 50; min[dim] = -0.5; max[dim] = 10000-0.5; binEdges[dim] = GenerateFixedBinArray(nbins[dim], min[dim], max[dim]); } else { nbins[dim] = 50; min[dim] = 0; max[dim] = 200; binEdges[dim] = GenerateFixedBinArray(nbins[dim], min[dim], max[dim]); } dim++; axistitle[dim] = ""#it{p}_{T,track}^{leading} (GeV/c)""; nbins[dim] = fMaxPt/5; min[dim] = 0; max[dim] = 150; binEdges[dim] = GenerateFixedBinArray(nbins[dim], min[dim], max[dim]); dim++; } if (fClusterCollArray.GetEntriesFast()>0) { axistitle[dim] = ""No. of clusters""; if (fForceBeamType != AliAnalysisTaskEmcal::kpp) { nbins[dim] = 50; min[dim] = -0.5; max[dim] = 4000-0.5; binEdges[dim] = GenerateFixedBinArray(nbins[dim], min[dim], max[dim]); } else { nbins[dim] = 50; min[dim] = 0; max[dim] = 200; binEdges[dim] = GenerateFixedBinArray(nbins[dim], min[dim], max[dim]); } dim++; axistitle[dim] = ""#it{E}_{cluster}^{leading} (GeV)""; nbins[dim] = fMaxPt/5; min[dim] = 0; max[dim] = 150; binEdges[dim] = GenerateFixedBinArray(nbins[dim], min[dim], max[dim]); dim++; } THnSparse* hn = fHistManager.CreateTHnSparse(""eventQA"",""eventQA"",dim,nbins,min,max); for (Int_t i = 0; i < dim; i++) { hn->GetAxis(i)->SetTitle(axistitle[i]); hn->SetBinEdges(i, binEdges[i]); } if (fIsPtHard) { TString histname = ""hPtHard""; TString title = histname + "";#it{p}_{T,hard} (GeV/c);counts""; fHistManager.CreateTH1(histname.Data(), title.Data(), nPtBins, 0, fMaxPt); TH1* hTrials = fHistManager.CreateTH1(""hNtrials"", ""hNtrials"", 1, 0, 1); hTrials->GetXaxis()->SetBinLabel(1,""#sum{ntrials}""); TH1* hxsection = fHistManager.CreateTH1(""hXsec"", ""hXsec"", 1, 0, 1); hxsection->GetXaxis()->SetBinLabel(1,""<#sigma>""); } if(fUseBuiltinEventSelection) fHistEventRejection->GetXaxis()->SetBinLabel(15,""PtHardBinJetOutlier""); } //________________________________________________________________________ void AliAnalysisTaskPWGJEQA::AllocateDetectorLevelTHnSparse() { Int_t dim = 0; TString title[20]; Int_t nbins[20] = {0}; Double_t min[30] = {0.}; Double_t max[30] = {0.}; Double_t *binEdges[20] = {0}; if (fForceBeamType != AliAnalysisTaskEmcal::kpp) { title[dim] = ""Centrality %""; nbins[dim] = fNCentHistBins; binEdges[dim] = fCentHistBins; min[dim] = fCentHistBins[0]; max[dim] = fCentHistBins[fNCentHistBins]; dim++; } title[dim] = ""#it{p}_{T} (GeV/#it{c})""; nbins[dim] = fNPtHistBins; binEdges[dim] = fPtHistBins; min[dim] = fPtHistBins[0]; max[dim] = fPtHistBins[fNPtHistBins]; dim++; title[dim] = ""#eta""; nbins[dim] = fNEtaHistBins; binEdges[dim] = fEtaHistBins; min[dim] = fEtaHistBins[0]; max[dim] = fEtaHistBins[fNEtaHistBins]; dim++; title[dim] = ""#phi""; nbins[dim] = fNPhiHistBins; binEdges[dim] = fPhiHistBins; min[dim] = fPhiHistBins[0]; max[dim] = fPhiHistBins[fNPhiHistBins]; dim++; title[dim] = ""track type""; nbins[dim] = 3; binEdges[dim] = fIntegerHistBins; min[dim] = fIntegerHistBins[0]; max[dim] = fIntegerHistBins[3]; dim++; title[dim] = ""#sigma(#it{p}_{T}) / #it{p}_{T}""; nbins[dim] = fNPtResHistBins; binEdges[dim] = fPtResHistBins; min[dim] = fPtResHistBins[0]; max[dim] = fPtResHistBins[fNPtResHistBins]; dim++; THnSparse* hn = fHistManager.CreateTHnSparse(""tracks"",""tracks"", dim, nbins, min, max); for (Int_t i = 0; i < dim; i++) { hn->GetAxis(i)->SetTitle(title[i]); hn->SetBinEdges(i, binEdges[i]); } } //________________________________________________________________________ void AliAnalysisTaskPWGJEQA::AllocateGeneratorLevelTHnSparse() { Int_t dim = 0; TString title[20]; Int_t nbins[20] = {0}; Double_t min[30] = {0.}; Double_t max[30] = {0.}; Double_t *binEdges[20] = {0}; if (fForceBeamType != AliAnalysisTaskEmcal::kpp) { title[dim] = ""Centrality %""; nbins[dim] = fNCentHistBins; binEdges[dim] = fCentHistBins; min[dim] = fCentHistBins[0]; max[dim] = fCentHistBins[fNCentHistBins]; dim++; } title[dim] = ""#it{p}_{T} (GeV/#it{c})""; nbins[dim] = fNPtHistBins; binEdges[dim] = fPtHistBins; min[dim] = fPtHistBins[0]; max[dim] = fPtHistBins[fNPtHistBins]; dim++; title[dim] = ""#eta""; nbins[dim] = fNEtaHistBins; binEdges[dim] = fEtaHistBins; min[dim] = fEtaHistBins[0]; max[dim] = fEtaHistBins[fNEtaHistBins]; dim++; title[dim] = ""#phi""; nbins[dim] = fNPhiHistBins; binEdges[dim] = fPhiHistBins; min[dim] = fPhiHistBins[0]; max[dim] = fPhiHistBins[fNPhiHistBins]; dim++; title[dim] = ""Findable""; nbins[dim] = 2; binEdges[dim] = fIntegerHistBins; min[dim] = fIntegerHistBins[0]; max[dim] = fIntegerHistBins[2]; dim++; THnSparse* hn = fHistManager.CreateTHnSparse(""tracks_PhysPrim"",""tracks_PhysPrim"", dim, nbins, min, max); for (Int_t i = 0; i < dim; i++) { hn->GetAxis(i)->SetTitle(title[i]); hn->SetBinEdges(i, binEdges[i]); } } //________________________________________________________________________ void AliAnalysisTaskPWGJEQA::AllocateMatchedParticlesTHnSparse() { Int_t dim = 0; TString title[20]; Int_t nbins[20] = {0}; Double_t min[30] = {0.}; Double_t max[30] = {0.}; Double_t *binEdges[20] = {0}; if (fForceBeamType != AliAnalysisTaskEmcal::kpp) { title[dim] = ""Centrality %""; nbins[dim] = fNCentHistBins; binEdges[dim] = fCentHistBins; min[dim] = fCentHistBins[0]; max[dim] = fCentHistBins[fNCentHistBins]; dim++; } title[dim] = ""#it{p}_{T}^{gen} (GeV/#it{c})""; nbins[dim] = fNPtHistBins; binEdges[dim] = fPtHistBins; min[dim] = fPtHistBins[0]; max[dim] = fPtHistBins[fNPtHistBins]; dim++; title[dim] = ""#eta^{gen}""; nbins[dim] = fNEtaHistBins; binEdges[dim] = fEtaHistBins; min[dim] = fEtaHistBins[0]; max[dim] = fEtaHistBins[fNEtaHistBins]; dim++; title[dim] = ""#phi^{gen}""; nbins[dim] = fNPhiHistBins; binEdges[dim] = fPhiHistBins; min[dim] = fPhiHistBins[0]; max[dim] = fPhiHistBins[fNPhiHistBins]; dim++; title[dim] = ""#it{p}_{T}^{det} (GeV/#it{c})""; nbins[dim] = fNPtHistBins; binEdges[dim] = fPtHistBins; min[dim] = fPtHistBins[0]; max[dim] = fPtHistBins[fNPtHistBins]; dim++; title[dim] = ""#eta^{det}""; nbins[dim] = fNEtaHistBins; binEdges[dim] = fEtaHistBins; min[dim] = fEtaHistBins[0]; max[dim] = fEtaHistBins[fNEtaHistBins]; dim++; title[dim] = ""#phi^{det}""; nbins[dim] = fNPhiHistBins; binEdges[dim] = fPhiHistBins; min[dim] = fPhiHistBins[0]; max[dim] = fPhiHistBins[fNPhiHistBins]; dim++; title[dim] = ""(#it{p}_{T}^{gen} - #it{p}_{T}^{det}) / #it{p}_{T}^{gen}""; nbins[dim] = fNPtRelDiffHistBins; binEdges[dim] = fPtRelDiffHistBins; min[dim] = fPtRelDiffHistBins[0]; max[dim] = fPtRelDiffHistBins[fNPtRelDiffHistBins]; dim++; title[dim] = ""track type""; nbins[dim] = 3; binEdges[dim] = fIntegerHistBins; min[dim] = fIntegerHistBins[0]; max[dim] = fIntegerHistBins[3]; dim++; THnSparse* hn = fHistManager.CreateTHnSparse(""tracks_Matched"",""tracks_Matched"", dim, nbins, min, max); for (Int_t i = 0; i < dim; i++) { hn->GetAxis(i)->SetTitle(title[i]); hn->SetBinEdges(i, binEdges[i]); } } //________________________________________________________________________ /// Generate histogram binning arrays void AliAnalysisTaskPWGJEQA::GenerateHistoBins() { fNPtHistBins = 82; fPtHistBins = new Double_t[fNPtHistBins+1]; GenerateFixedBinArray(6, 0, 0.3, fPtHistBins); GenerateFixedBinArray(7, 0.3, 1, fPtHistBins+6); GenerateFixedBinArray(10, 1, 3, fPtHistBins+13); GenerateFixedBinArray(14, 3, 10, fPtHistBins+23); GenerateFixedBinArray(10, 10, 20, fPtHistBins+37); GenerateFixedBinArray(15, 20, 50, fPtHistBins+47); GenerateFixedBinArray(20, 50, 150, fPtHistBins+62); fNEtaHistBins = 70; fEtaHistBins = new Double_t[fNEtaHistBins+1]; GenerateFixedBinArray(fNEtaHistBins, -1, 1, fEtaHistBins); fNPhiHistBins = 101; fPhiHistBins = new Double_t[fNPhiHistBins+1]; GenerateFixedBinArray(fNPhiHistBins, 0, TMath::Pi() * 2.02, fPhiHistBins); fNCentHistBins = 4; fCentHistBins = new Double_t[fNCentHistBins+1]; fCentHistBins[0] = 0; fCentHistBins[1] = 10; fCentHistBins[2] = 30; fCentHistBins[3] = 50; fCentHistBins[4] = 90; fNPtResHistBins = 100; fPtResHistBins = new Double_t[fNPtResHistBins+1]; GenerateFixedBinArray(50, 0, 0.05, fPtResHistBins); GenerateFixedBinArray(25, 0.05, 0.10, fPtResHistBins+50); GenerateFixedBinArray(15, 0.10, 0.20, fPtResHistBins+75); GenerateFixedBinArray(10, 0.20, 0.50, fPtResHistBins+90); fNPtRelDiffHistBins = 50; fPtRelDiffHistBins = new Double_t[fNPtRelDiffHistBins+1]; GenerateFixedBinArray(fNPtRelDiffHistBins, -0.5, 0.5, fPtRelDiffHistBins); fNIntegerHistBins = 3; fIntegerHistBins = new Double_t[fNIntegerHistBins+1]; GenerateFixedBinArray(fNIntegerHistBins, -0.5, 2.5, fIntegerHistBins); } //________________________________________________________________________ void AliAnalysisTaskPWGJEQA::ExecOnce() { if (fClusterCollArray.GetEntriesFast() == 0 && fCaloCellsName.IsNull()) { fNeedEmcalGeom = kFALSE; } else { fNeedEmcalGeom = kTRUE; } AliAnalysisTaskEmcalJet::ExecOnce(); // Load the PHOS geometry fPHOSGeo = AliPHOSGeometry::GetInstance(); if (fPHOSGeo) { AliInfo(""Found instance of PHOS geometry!""); } else { AliInfo(""Creating PHOS geometry!""); Int_t runNum = InputEvent()->GetRunNumber(); if(runNum<209122) //Run1 fPHOSGeo = AliPHOSGeometry::GetInstance(""IHEP""); else fPHOSGeo = AliPHOSGeometry::GetInstance(""Run2""); if (fPHOSGeo) { AliOADBContainer geomContainer(""phosGeo""); geomContainer.InitFromFile(""$ALICE_PHYSICS/OADB/PHOS/PHOSMCGeometry.root"",""PHOSMCRotationMatrixes""); TObjArray* matrixes = (TObjArray*)geomContainer.GetObject(runNum,""PHOSRotationMatrixes""); for(Int_t mod=0; mod<6; mod++) { if(!matrixes->At(mod)) continue; fPHOSGeo->SetMisalMatrix(((TGeoHMatrix*)matrixes->At(mod)),mod); printf("".........Adding Matrix(%d), geo=%p\\n"",mod,fPHOSGeo); ((TGeoHMatrix*)matrixes->At(mod))->Print(); } } } } /// /// This function (overloading the base class) uses AliEventCuts to perform event selection. ///________________________________________________________________________ Bool_t AliAnalysisTaskPWGJEQA::IsEventSelected() { if (fUseAliEventCuts) { if (!fEventCuts.AcceptEvent(InputEvent())) { PostData(1, fOutput); return kFALSE; } } else { Bool_t answer = AliAnalysisTaskEmcal::IsEventSelected(); return answer; } return kTRUE; } //________________________________________________________________________ Bool_t AliAnalysisTaskPWGJEQA::RetrieveEventObjects() { if (!AliAnalysisTaskEmcalJet::RetrieveEventObjects()) return kFALSE; // If Pt-hard production, get the Pt-hard of the event, and have possibility to reject the event for jet outliers if (fIsPtHard) { AliGenPythiaEventHeader* pygen = nullptr; if (MCEvent()) { pygen = dynamic_cast(MCEvent()->GenEventHeader()); if (!pygen) { // Check if AOD AliAODMCHeader* aodMCH = dynamic_cast(InputEvent()->FindListObject(AliAODMCHeader::StdBranchName())); if (aodMCH) { for (UInt_t i = 0;iGetNCocktailHeaders();i++) { pygen = dynamic_cast(aodMCH->GetCocktailHeader(i)); if (pygen) break; } } } } if (pygen) { fPtHard = pygen->GetPtHard(); //fNTrials = pygen->Trials(); //fXsection = pygen->GetXsection(); // reject outlier events, where the jet Pt is much larger than Pt-hard if (fRejectOutlierEvents) { AliTLorentzVector jet; Int_t nTriggerJets = pygen->NTriggerJets(); Float_t tmpjet[]={0,0,0,0}; for (Int_t ijet = 0; ijet< nTriggerJets; ijet++) { pygen->TriggerJet(ijet, tmpjet); jet.SetPxPyPzE(tmpjet[0],tmpjet[1],tmpjet[2],tmpjet[3]); if (jet.Pt() > 4. * fPtHard) { //AliInfo(Form(""Reject jet event with: pT Hard %2.2f, pycell jet pT %2.2f, rejection factor %1.1f\\n"", fPtHard, jet.Pt(), 4.)); if (fGeneralHistograms && fHistEventRejection) fHistEventRejection->Fill(""PtHardBinJetOutlier"",1); return kFALSE; } } } } } return kTRUE; } /** * Notifying the user that the input data file has * changed. Fill pt-hard histograms if applicable. * * @return False if the data tree or the data file * doesn't exist, true otherwise */ //________________________________________________________________________ Bool_t AliAnalysisTaskPWGJEQA::UserNotify() { if (fIsPtHard) { TTree *tree = AliAnalysisManager::GetAnalysisManager()->GetTree(); if (!tree) { AliError(Form(""%s - UserNotify: No current tree!"",GetName())); return kFALSE; } Float_t xsection = 0; Float_t trials = 0; TFile *curfile = tree->GetCurrentFile(); if (!curfile) { AliError(Form(""%s - UserNotify: No current file!"",GetName())); return kFALSE; } TChain *chain = dynamic_cast(tree); if (chain) tree = chain->GetTree(); PythiaInfoFromFile(curfile->GetName(), xsection, trials); fHistManager.FillTH1(""hNtrials"", ""#sum{ntrials}"", trials); fHistManager.FillTH1(""hXsec"", ""<#sigma>"", xsection); } return kTRUE; } //________________________________________________________________________ Bool_t AliAnalysisTaskPWGJEQA::FillHistograms() { if (fDoTrackQA) FillTrackHistograms(); if (fDoCaloQA) FillCellHistograms(); if (fDoCaloQA) FillClusterHistograms(); if (fDoJetQA) FillJetHistograms(); if (fDoEventQA) FillEventQAHistograms(); return kTRUE; } //________________________________________________________________________ void AliAnalysisTaskPWGJEQA::FillTrackHistograms() { fNTotTracks = 0; fLeadingTrack.SetPxPyPzE(0,0,0,0); AliVTrack* track; for (auto trackIterator : fDetectorLevel->accepted_momentum() ) { fNTotTracks++; if (fLeadingTrack.Pt() < trackIterator.first.Pt()) fLeadingTrack = trackIterator.first; track = trackIterator.second; Byte_t type = fDetectorLevel->GetTrackType(track); if (type <= 2) { Double_t sigma = 0; if (fIsEsd) { AliESDtrack *esdTrack = dynamic_cast(track); if (esdTrack) sigma = TMath::Sqrt(esdTrack->GetSigma1Pt2()); } else { // AOD AliAODTrack *aodtrack = dynamic_cast(track); if(!aodtrack) AliFatal(""Not a standard AOD""); AliExternalTrackParam exParam; //get covariance matrix Double_t cov[21] = {0,}; aodtrack->GetCovMatrix(cov); Double_t pxpypz[3] = {0,}; aodtrack->PxPyPz(pxpypz); Double_t xyz[3] = {0,}; aodtrack->GetXYZ(xyz); Short_t sign = aodtrack->Charge(); exParam.Set(xyz,pxpypz,cov,sign); sigma = TMath::Sqrt(exParam.GetSigma1Pt2()); } Int_t label = TMath::Abs(track->GetLabel()); FillDetectorLevelTHnSparse(fCent, track->Eta(), track->Phi(), track->Pt(), sigma, type); if (fGeneratorLevel && label > 0) { AliAODMCParticle *part = fGeneratorLevel->GetAcceptMCParticleWithLabel(label); if (part) { if (fMCGeneratorIndex == -1 || fMCGeneratorIndex == part->GetGeneratorIndex()) { Int_t pdg = TMath::Abs(part->PdgCode()); // select charged pions, protons, kaons, electrons, muons if (pdg == 211 || pdg == 2212 || pdg == 321 || pdg == 11 || pdg == 13) { FillMatchedParticlesTHnSparse(fCent, part->Eta(), part->Phi(), part->Pt(), track->Eta(), track->Phi(), track->Pt(), type); } } } } } else { AliError(Form(""Track %d has type %d not recognized!"", fDetectorLevel->GetCurrentID(), type)); } } if (fGeneratorLevel) { AliAODMCParticle* part; for (auto partIterator : fGeneratorLevel->accepted_momentum() ) { part = partIterator.second; if (fMCGeneratorIndex == -1 || fMCGeneratorIndex == part->GetGeneratorIndex()) { Byte_t findable = 0; Int_t pdg = TMath::Abs(part->PdgCode()); // select charged pions, protons, kaons, electrons, muons if (pdg == 211 || pdg == 2212 || pdg == 321 || pdg == 11 || pdg == 13) findable = 1; FillGeneratorLevelTHnSparse(fCent, part->Eta(), part->Phi(), part->Pt(), findable); } } } } //________________________________________________________________________ void AliAnalysisTaskPWGJEQA::FillCellHistograms() { if (!fCaloCells) return; TString histname_energy = TString::Format(""%s/fHistCellEnergy"", fCaloCellsName.Data()); TString histname_time = TString::Format(""%s/fHistCellTime"", fCaloCellsName.Data()); TString histname_energyProf = TString::Format(""%s/fProfCellAbsIdEnergy"", fCaloCellsName.Data()); TString histname_timeProf = TString::Format(""%s/fProfCellAbsIdTime"", fCaloCellsName.Data()); TString histname_EnergyvsTime = TString::Format(""%s/fHistCellEvsTime"", fCaloCellsName.Data()); const Int_t ncells = fCaloCells->GetNumberOfCells(); for (Int_t pos = 0; pos < ncells; pos++) { Float_t amp = fCaloCells->GetAmplitude(pos); Float_t time = fCaloCells->GetTime(pos); Int_t absId = fCaloCells->GetCellNumber(pos); if (amp < fCellEnergyCut) continue; fHistManager.FillTH1(histname_energy, amp); fHistManager.FillTH1(histname_time, time); fHistManager.FillProfile(histname_energyProf, absId, amp); fHistManager.FillProfile(histname_timeProf, absId, time); fHistManager.FillTH2(histname_EnergyvsTime, time, amp); } } //________________________________________________________________________ void AliAnalysisTaskPWGJEQA::FillClusterHistograms() { memset(fNTotClusters, 0, sizeof(Int_t)*3); for (Int_t i = 0; i < 3; i++) fLeadingCluster[i].SetPxPyPzE(0,0,0,0); TString histname; AliClusterContainer* clusters = 0; TIter nextClusColl(&fClusterCollArray); while ((clusters = static_cast(nextClusColl()))) { // Cluster loop AliClusterIterableMomentumContainer itcont = clusters->all_momentum(); for (AliClusterIterableMomentumContainer::iterator it = itcont.begin(); it != itcont.end(); it++) { UInt_t rejectionReason = 0; if (!clusters->AcceptCluster(it.current_index(), rejectionReason)) { histname = TString::Format(""%s/fHistClusterRejectionReason"", clusters->GetArrayName().Data()); fHistManager.FillTH2(histname, clusters->GetRejectionReasonBitPosition(rejectionReason), it->first.E()); continue; } // Determine cluster type (EMCal/DCal/Phos) and record relevant eventQA info ClusterType clusType = kNA; if (it->second->IsEMCAL()) { Double_t phi = it->first.Phi_0_2pi(); Int_t isDcal = Int_t(phi > fgkEMCalDCalPhiDivide); if (isDcal == 0) { clusType = kEMCal; } else if (isDcal == 1) { clusType = kDCal; } if (fLeadingCluster[isDcal].E() < it->first.E()) fLeadingCluster[isDcal] = it->first; fNTotClusters[isDcal]++; Int_t sm = fGeom->GetSuperModuleNumber(it->second->GetCellAbsId(0)); if (sm >=0 && sm < 20) { histname = TString::Format(""%s/BySM/hEmcalClusEnergy_SM%d"", clusters->GetArrayName().Data(), sm); fHistManager.FillTH1(histname, it->second->E()); } else { AliError(Form(""Supermodule %d does not exist!"", sm)); } } else if (it->second->GetType() == AliVCluster::kPHOSNeutral){ Int_t nCells = it->second->GetNCells(); Double_t M02 = it->second->GetM02(); Double_t energy = it->second->E(); histname = TString::Format(""%s/hPhosNCellsVsEnergy"", clusters->GetArrayName().Data()); fHistManager.FillTH2(histname, nCells, energy); histname = TString::Format(""%s/hPhosM02VsEnergy"", clusters->GetArrayName().Data()); fHistManager.FillTH2(histname, M02, energy); clusType = kPHOS; fNTotClusters[2]++; if (fLeadingCluster[2].E() < it->first.E()) fLeadingCluster[2] = it->first; // Fill Phos spectra by module Int_t relid[4]; if (fPHOSGeo) { fPHOSGeo->AbsToRelNumbering(it->second->GetCellAbsId(0), relid); Int_t sm = relid[0]; if (sm >=1 && sm < 5) { histname = TString::Format(""%s/BySM/hPhosClusEnergy_SM%d"", clusters->GetArrayName().Data(), sm); fHistManager.FillTH1(histname, energy); } else { AliError(Form(""Supermodule %d does not exist!"", sm)); } } // Loop through cells in the cluster, and histogram their energy histname = TString::Format(""%s/hPhosCellIdVsEnergy"", clusters->GetArrayName().Data()); for (Int_t i=0; i < nCells; i++) { fHistManager.FillTH2(histname, it->second->GetCellAbsId(i), energy); } } Double_t contents[30]={0}; histname = TString::Format(""%s/clusterObservables"", clusters->GetArrayName().Data()); THnSparse* histClusterObservables = static_cast(fHistManager.FindObject(histname)); if (!histClusterObservables) return; for (Int_t i = 0; i < histClusterObservables->GetNdimensions(); i++) { TString title(histClusterObservables->GetAxis(i)->GetTitle()); if (title==""Centrality %"") contents[i] = fCent; else if (title==""#it{E}_{clus} (GeV)"") contents[i] = it->first.E(); else if (title==""#eta"") contents[i] = it->first.Eta(); else if (title==""#phi"") contents[i] = it->first.Phi_0_2pi(); else if (title==""cluster type"") contents[i] = clusType; else AliWarning(Form(""Unable to fill dimension %s!"",title.Data())); } histClusterObservables->Fill(contents); } } } //________________________________________________________________________ void AliAnalysisTaskPWGJEQA::FillJetHistograms() { TString histname; AliJetContainer* jets = 0; TIter nextJetColl(&fJetCollArray); while ((jets = static_cast(nextJetColl()))) { Double_t rhoVal = 0; if (jets->GetRhoParameter()) { rhoVal = jets->GetRhoVal(); histname = TString::Format(""%s/fHistRhoVsCent"", jets->GetArrayName().Data()); fHistManager.FillTH2(histname.Data(), fCent, rhoVal); } for (auto jet : jets->all()) { UInt_t rejectionReason = 0; if (!jets->AcceptJet(jet, rejectionReason)) { histname = TString::Format(""%s/fHistJetRejectionReason"", jets->GetArrayName().Data()); fHistManager.FillTH2(histname.Data(), jets->GetRejectionReasonBitPosition(rejectionReason), jet->Pt()); continue; } Float_t ptLeading = jets->GetLeadingHadronPt(jet); Float_t corrPt = jet->Pt() - rhoVal * jet->Area(); TLorentzVector leadPart; jets->GetLeadingHadronMomentum(leadPart, jet); Double_t contents[30]={0}; histname = TString::Format(""%s/fHistJetObservables"", jets->GetArrayName().Data()); THnSparse* histJetObservables = static_cast(fHistManager.FindObject(histname)); if (!histJetObservables) return; for (Int_t i = 0; i < histJetObservables->GetNdimensions(); i++) { TString title(histJetObservables->GetAxis(i)->GetTitle()); if (title==""Centrality (%)"") contents[i] = fCent; else if (title==""#eta_{jet}"") contents[i] = jet->Eta(); else if (title==""#phi_{jet} (rad)"") contents[i] = jet->Phi_0_2pi(); else if (title==""#it{p}_{T} (GeV/#it{c})"") contents[i] = jet->Pt(); else if (title==""#it{p}_{T}^{MC} (GeV/#it{c})"") contents[i] = jet->MCPt(); else if (title==""#it{p}_{T}^{corr} (GeV/#it{c})"") contents[i] = corrPt; else if (title==""#it{p}_{T,particle}^{leading} (GeV/#it{c})"") contents[i] = ptLeading; else AliWarning(Form(""Unable to fill dimension %s!"",title.Data())); } histJetObservables->Fill(contents); UInt_t jetType = jet->GetJetAcceptanceType(); if(jetType & AliEmcalJet::kEMCALfid) { histname = TString::Format(""%s/hNEFVsPtEMC"", jets->GetArrayName().Data()); if (fForceBeamType != kpp){fHistManager.FillTH3(histname.Data(), fCent, jet->Pt(), jet->NEF());} else {fHistManager.FillTH2(histname.Data(), jet->Pt(), jet->NEF());} } else if(jetType & AliEmcalJet::kDCALonlyfid) { histname = TString::Format(""%s/hNEFVsPtDCal"", jets->GetArrayName().Data()); if (fForceBeamType != kpp){ fHistManager.FillTH3(histname.Data(), fCent, jet->Pt(), jet->NEF()); } else{ fHistManager.FillTH2(histname.Data(), jet->Pt(), jet->NEF()); } } Double_t deltaEhadcorr = 0; const AliVCluster* clus = nullptr; Int_t nClusters = jet->GetNumberOfClusters(); for (Int_t iClus = 0; iClus < nClusters; iClus++) { clus = jet->Cluster(iClus); deltaEhadcorr += (clus->GetNonLinCorrEnergy() - clus->GetHadCorrEnergy()); } histname = TString::Format(""%s/hDeltaEHadCorr"", jets->GetArrayName().Data()); if (fForceBeamType != kpp){ fHistManager.FillTH3(histname, fCent, jet->Pt(), deltaEhadcorr); } else{ fHistManager.FillTH2(histname, jet->Pt(), deltaEhadcorr); } } //jet loop } } //________________________________________________________________________ void AliAnalysisTaskPWGJEQA::FillEventQAHistograms() { EventQA_t eventQA; for (Int_t i = 0; i < 3; i++) { eventQA.fMaxCluster[i] = fLeadingCluster[i]; } eventQA.fCent = fCent; eventQA.fNTracks = fNTotTracks; eventQA.fNClusters[0] = fNTotClusters[0]; eventQA.fNClusters[1] = fNTotClusters[1]; eventQA.fNClusters[2] = fNTotClusters[2]; eventQA.fMaxTrack = fLeadingTrack; Int_t globalNclusters = eventQA.fNClusters[0] + eventQA.fNClusters[1] + eventQA.fNClusters[2]; AliTLorentzVector globalMaxCluster; for (Int_t i = 0; i < 3; i++) { if (globalMaxCluster.E() < eventQA.fMaxCluster[i].E()) globalMaxCluster = eventQA.fMaxCluster[i]; } THnSparse* histEventQA = static_cast(fHistManager.FindObject(""eventQA"")); Double_t contents[40]={0}; for (Int_t i = 0; i < histEventQA->GetNdimensions(); i++) { TString title(histEventQA->GetAxis(i)->GetTitle()); if (title==""Centrality %"") contents[i] = eventQA.fCent; else if (title==""No. of tracks"") contents[i] = eventQA.fNTracks; else if (title==""No. of clusters"") contents[i] = globalNclusters; else if (title==""#it{p}_{T,track}^{leading} (GeV/c)"") contents[i] = eventQA.fMaxTrack.Pt(); else if (title==""#it{E}_{cluster}^{leading} (GeV)"") contents[i] = globalMaxCluster.E(); else AliWarning(Form(""Unable to fill dimension %s!"",title.Data())); } histEventQA->Fill(contents); // Fill pythia pt hard histograms, if applicable if (fPtHard > 1e-6) { fHistManager.FillTH1(""hPtHard"", fPtHard); } } //________________________________________________________________________ void AliAnalysisTaskPWGJEQA::FillDetectorLevelTHnSparse(Double_t cent, Double_t trackEta, Double_t trackPhi, Double_t trackPt, Double_t sigma1OverPt, Byte_t trackType) { Double_t contents[20]={0}; THnSparse* thnTracks = static_cast(fHistManager.FindObject(""tracks"")); if (!thnTracks) return; for (Int_t i = 0; i < thnTracks->GetNdimensions(); i++) { TString title(thnTracks->GetAxis(i)->GetTitle()); if (title==""Centrality %"") contents[i] = cent; else if (title==""#it{p}_{T} (GeV/#it{c})"") contents[i] = trackPt; else if (title==""#eta"") contents[i] = trackEta; else if (title==""#phi"") contents[i] = trackPhi; else if (title==""#sigma(1/#it{p}_{T}) (GeV/#it{c})^{-1}"") contents[i] = sigma1OverPt; else if (title==""#sigma(#it{p}_{T}) / #it{p}_{T}"") contents[i] = sigma1OverPt*trackPt; else if (title==""track type"") contents[i] = trackType; else AliWarning(Form(""Unable to fill dimension %s of histogram %s!"", title.Data(), thnTracks->GetName())); } thnTracks->Fill(contents); } //________________________________________________________________________ void AliAnalysisTaskPWGJEQA::FillGeneratorLevelTHnSparse(Double_t cent, Double_t partEta, Double_t partPhi, Double_t partPt, Byte_t findable) { Double_t contents[20]={0}; THnSparse* thnTracks_PhysPrim = static_cast(fHistManager.FindObject(""tracks_PhysPrim"")); if (!thnTracks_PhysPrim) return; for (Int_t i = 0; i < thnTracks_PhysPrim->GetNdimensions(); i++) { TString title(thnTracks_PhysPrim->GetAxis(i)->GetTitle()); if (title==""Centrality %"") contents[i] = cent; else if (title==""#it{p}_{T} (GeV/#it{c})"") contents[i] = partPt; else if (title==""#eta"") contents[i] = partEta; else if (title==""#phi"") contents[i] = partPhi; else if (title==""Findable"") contents[i] = findable; else AliWarning(Form(""Unable to fill dimension %s of histogram %s!"", title.Data(), thnTracks_PhysPrim->GetName())); } thnTracks_PhysPrim->Fill(contents); } //________________________________________________________________________ void AliAnalysisTaskPWGJEQA::FillMatchedParticlesTHnSparse(Double_t cent, Double_t partEta, Double_t partPhi, Double_t partPt, Double_t trackEta, Double_t trackPhi, Double_t trackPt, Byte_t trackType) { Double_t contents[20]={0}; THnSparse* thnTracks_Matched = static_cast(fHistManager.FindObject(""tracks_Matched"")); if (!thnTracks_Matched) return; for (Int_t i = 0; i < thnTracks_Matched->GetNdimensions(); i++) { TString title(thnTracks_Matched->GetAxis(i)->GetTitle()); if (title==""Centrality %"") contents[i] = cent; else if (title==""#it{p}_{T}^{gen} (GeV/#it{c})"") contents[i] = partPt; else if (title==""#eta^{gen}"") contents[i] = partEta; else if (title==""#phi^{gen}"") contents[i] = partPhi; else if (title==""#it{p}_{T}^{det} (GeV/#it{c})"") contents[i] = trackPt; else if (title==""#eta^{det}"") contents[i] = trackEta; else if (title==""#phi^{det}"") contents[i] = trackPhi; else if (title==""(#it{p}_{T}^{gen} - #it{p}_{T}^{det}) / #it{p}_{T}^{gen}"") contents[i] = (partPt - trackPt) / partPt; else if (title==""(#it{p}_{T}^{gen} - #it{p}_{T}^{det}) / #it{p}_{T}^{det}"") contents[i] = (partPt - trackPt) / trackPt; else if (title==""track type"") contents[i] = (Double_t)trackType; else AliWarning(Form(""Unable to fill dimension %s of histogram %s!"", title.Data(), thnTracks_Matched->GetName())); } thnTracks_Matched->Fill(contents); } /** * This function adds the task to the analysis manager. Often, this function is called * by an AddTask C macro. However, by compiling the code, it ensures that we do not * have to deal with difficulties caused by CINT. */ AliAnalysisTaskPWGJEQA* AliAnalysisTaskPWGJEQA::AddTaskPWGJEQA( const char* ntracks, const char* nclusters, const char* ncells, const char *nGenLev, Bool_t doTrackQA, Bool_t doCaloQA, Bool_t doJetQA, Bool_t doEventQA, Double_t trackPtCut, Double_t clusECut, const char* suffix) { // Get the pointer to the existing analysis manager via the static access method AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error(""AddTaskPWGJEQA"", ""No analysis manager to connect to.""); return NULL; } // Check the analysis type using the event handlers connected to the analysis manager AliVEventHandler* handler = mgr->GetInputEventHandler(); if (!handler) { ::Error(""AddTaskPWGJEQA"", ""This task requires an input event handler""); return NULL; } enum EDataType_t { kUnknown, kESD, kAOD }; EDataType_t dataType = kUnknown; if (handler->InheritsFrom(""AliESDInputHandler"")) { dataType = kESD; } else if (handler->InheritsFrom(""AliAODInputHandler"")) { dataType = kAOD; } // Init the task and do settings TString trackName(ntracks); TString clusName(nclusters); TString cellName(ncells); if (trackName == ""usedefault"") { if (dataType == kESD) { trackName = ""Tracks""; } else if (dataType == kAOD) { trackName = ""tracks""; } else { trackName = """"; } } if (clusName == ""usedefault"") { if (dataType == kESD) { clusName = ""CaloClusters""; } else if (dataType == kAOD) { clusName = ""caloClusters""; } else { clusName = """"; } } if (cellName == ""usedefault"") { if (dataType == kESD) { cellName = ""EMCALCells""; } else if (dataType == kAOD) { cellName = ""emcalCells""; } else { cellName = """"; } } TString name(""AliAnalysisTaskPWGJEQA""); if (!trackName.IsNull()) { name += ""_""; name += trackName; } if (!clusName.IsNull()) { name += ""_""; name += clusName; } if (!cellName.IsNull()) { name += ""_""; name += cellName; } if (strcmp(suffix,"""")) { name += ""_""; name += suffix; } if (nGenLev && strcmp(nGenLev,"""")!=0) cout<<""MC Part: ""<< nGenLev<SetVzRange(-10,10); qaTask->SetNeedEmcalGeom(kFALSE); qaTask->SetCaloCellsName(cellName); qaTask->SetDetectorLevelName(trackName); if (nGenLev && strcmp(nGenLev,"""")!=0) qaTask->SetGeneratorLevelName(nGenLev); qaTask->SetDoTrackQA(doTrackQA); qaTask->SetDoCaloQA(doCaloQA); qaTask->SetDoJetQA(doJetQA); qaTask->SetDoEventQA(doEventQA); // Add the detector-level track container if (trackName == ""tracks"" || trackName == ""Tracks"") { AliTrackContainer* trackCont = qaTask->AddTrackContainer(trackName); trackCont->SetFilterHybridTracks(kTRUE); } else if (!trackName.IsNull()) { qaTask->AddParticleContainer(trackName); } AliParticleContainer *partCont = qaTask->GetParticleContainer(trackName); if (partCont) { partCont->SetParticlePtCut(trackPtCut); } // Add the generator-level container, if specified if (nGenLev && strcmp(nGenLev,"""")!=0) { AliMCParticleContainer* mcpartCont = qaTask->AddMCParticleContainer(nGenLev); mcpartCont->SelectPhysicalPrimaries(kTRUE); mcpartCont->SetParticlePtCut(0); } // Add the cluster container AliClusterContainer *clusterCont = qaTask->AddClusterContainer(clusName); if (clusterCont) { clusterCont->SetClusECut(0.); clusterCont->SetClusPtCut(0.); clusterCont->SetClusHadCorrEnergyCut(clusECut); clusterCont->SetDefaultClusterEnergy(AliVCluster::kHadCorr); } // Final settings, pass to manager and set the containers mgr->AddTask(qaTask); // Create containers for input/output AliAnalysisDataContainer *cinput1 = mgr->GetCommonInputContainer() ; TString contName = TString::Format(""%s_histos"", name.Data()); TString commonoutput; commonoutput = mgr->GetCommonFileName(); AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(contName.Data(), TList::Class(),AliAnalysisManager::kOutputContainer, commonoutput); mgr->ConnectInput (qaTask, 0, cinput1 ); mgr->ConnectOutput (qaTask, 1, coutput1 ); return qaTask; } ",16247,True,2863.4887601558244,median "//===-- AMDILCFGStructurizer.cpp - CFG Structurizer -----------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // /// \\file //==-----------------------------------------------------------------------===// #include ""AMDGPU.h"" #include ""AMDGPUSubtarget.h"" #include ""R600InstrInfo.h"" #include ""R600RegisterInfo.h"" #include ""llvm/ADT/DepthFirstIterator.h"" #include ""llvm/ADT/SCCIterator.h"" #include ""llvm/ADT/SmallPtrSet.h"" #include ""llvm/ADT/SmallVector.h"" #include ""llvm/ADT/Statistic.h"" #include ""llvm/ADT/StringRef.h"" #include ""llvm/CodeGen/MachineBasicBlock.h"" #include ""llvm/CodeGen/MachineDominators.h"" #include ""llvm/CodeGen/MachineFunction.h"" #include ""llvm/CodeGen/MachineFunctionPass.h"" #include ""llvm/CodeGen/MachineInstr.h"" #include ""llvm/CodeGen/MachineInstrBuilder.h"" #include ""llvm/CodeGen/MachineJumpTableInfo.h"" #include ""llvm/CodeGen/MachineLoopInfo.h"" #include ""llvm/CodeGen/MachineOperand.h"" #include ""llvm/CodeGen/MachinePostDominators.h"" #include ""llvm/CodeGen/MachineRegisterInfo.h"" #include ""llvm/CodeGen/MachineValueType.h"" #include ""llvm/IR/DebugLoc.h"" #include ""llvm/IR/LLVMContext.h"" #include ""llvm/Pass.h"" #include ""llvm/Support/Debug.h"" #include ""llvm/Support/ErrorHandling.h"" #include ""llvm/Support/raw_ostream.h"" #include #include #include #include #include #include #include using namespace llvm; #define DEBUG_TYPE ""structcfg"" #define DEFAULT_VEC_SLOTS 8 // TODO: move-begin. //===----------------------------------------------------------------------===// // // Statistics for CFGStructurizer. // //===----------------------------------------------------------------------===// STATISTIC(numSerialPatternMatch, ""CFGStructurizer number of serial pattern "" ""matched""); STATISTIC(numIfPatternMatch, ""CFGStructurizer number of if pattern "" ""matched""); STATISTIC(numClonedBlock, ""CFGStructurizer cloned blocks""); STATISTIC(numClonedInstr, ""CFGStructurizer cloned instructions""); namespace llvm { void initializeAMDGPUCFGStructurizerPass(PassRegistry&); } // end namespace llvm namespace { //===----------------------------------------------------------------------===// // // Miscellaneous utility for CFGStructurizer. // //===----------------------------------------------------------------------===// #define SHOWNEWINSTR(i) \\ DEBUG(dbgs() << ""New instr: "" << *i << ""\\n""); #define SHOWNEWBLK(b, msg) \\ DEBUG( \\ dbgs() << msg << ""BB"" << b->getNumber() << ""size "" << b->size(); \\ dbgs() << ""\\n""; \\ ); #define SHOWBLK_DETAIL(b, msg) \\ DEBUG( \\ if (b) { \\ dbgs() << msg << ""BB"" << b->getNumber() << ""size "" << b->size(); \\ b->print(dbgs()); \\ dbgs() << ""\\n""; \\ } \\ ); #define INVALIDSCCNUM -1 //===----------------------------------------------------------------------===// // // supporting data structure for CFGStructurizer // //===----------------------------------------------------------------------===// class BlockInformation { public: bool IsRetired = false; int SccNum = INVALIDSCCNUM; BlockInformation() = default; }; //===----------------------------------------------------------------------===// // // CFGStructurizer // //===----------------------------------------------------------------------===// class AMDGPUCFGStructurizer : public MachineFunctionPass { public: typedef SmallVector MBBVector; typedef std::map MBBInfoMap; typedef std::map LoopLandInfoMap; enum PathToKind { Not_SinglePath = 0, SinglePath_InPath = 1, SinglePath_NotInPath = 2 }; static char ID; AMDGPUCFGStructurizer() : MachineFunctionPass(ID) { initializeAMDGPUCFGStructurizerPass(*PassRegistry::getPassRegistry()); } StringRef getPassName() const override { return ""AMDGPU Control Flow Graph structurizer Pass""; } void getAnalysisUsage(AnalysisUsage &AU) const override { AU.addRequired(); AU.addRequired(); AU.addRequired(); MachineFunctionPass::getAnalysisUsage(AU); } /// Perform the CFG structurization bool run(); /// Perform the CFG preparation /// This step will remove every unconditionnal/dead jump instructions and make /// sure all loops have an exit block bool prepare(); bool runOnMachineFunction(MachineFunction &MF) override { TII = MF.getSubtarget().getInstrInfo(); TRI = &TII->getRegisterInfo(); DEBUG(MF.dump();); OrderedBlks.clear(); Visited.clear(); FuncRep = &MF; MLI = &getAnalysis(); DEBUG(dbgs() << ""LoopInfo:\\n""; PrintLoopinfo(*MLI);); MDT = &getAnalysis(); DEBUG(MDT->print(dbgs(), (const Module*)nullptr);); PDT = &getAnalysis(); DEBUG(PDT->print(dbgs());); prepare(); run(); DEBUG(MF.dump();); return true; } protected: MachineDominatorTree *MDT; MachinePostDominatorTree *PDT; MachineLoopInfo *MLI; const R600InstrInfo *TII = nullptr; const R600RegisterInfo *TRI = nullptr; // PRINT FUNCTIONS /// Print the ordered Blocks. void printOrderedBlocks() const { size_t i = 0; for (MBBVector::const_iterator iterBlk = OrderedBlks.begin(), iterBlkEnd = OrderedBlks.end(); iterBlk != iterBlkEnd; ++iterBlk, ++i) { dbgs() << ""BB"" << (*iterBlk)->getNumber(); dbgs() << ""("" << getSCCNum(*iterBlk) << "","" << (*iterBlk)->size() << "")""; if (i != 0 && i % 10 == 0) { dbgs() << ""\\n""; } else { dbgs() << "" ""; } } } static void PrintLoopinfo(const MachineLoopInfo &LoopInfo) { for (MachineLoop::iterator iter = LoopInfo.begin(), iterEnd = LoopInfo.end(); iter != iterEnd; ++iter) { (*iter)->print(dbgs(), 0); } } // UTILITY FUNCTIONS int getSCCNum(MachineBasicBlock *MBB) const; MachineBasicBlock *getLoopLandInfo(MachineLoop *LoopRep) const; bool hasBackEdge(MachineBasicBlock *MBB) const; bool isRetiredBlock(MachineBasicBlock *MBB) const; bool isActiveLoophead(MachineBasicBlock *MBB) const; PathToKind singlePathTo(MachineBasicBlock *SrcMBB, MachineBasicBlock *DstMBB, bool AllowSideEntry = true) const; int countActiveBlock(MBBVector::const_iterator It, MBBVector::const_iterator E) const; bool needMigrateBlock(MachineBasicBlock *MBB) const; // Utility Functions void reversePredicateSetter(MachineBasicBlock::iterator I, MachineBasicBlock &MBB); /// Compute the reversed DFS post order of Blocks void orderBlocks(MachineFunction *MF); // Function originally from CFGStructTraits void insertInstrEnd(MachineBasicBlock *MBB, int NewOpcode, const DebugLoc &DL = DebugLoc()); MachineInstr *insertInstrBefore(MachineBasicBlock *MBB, int NewOpcode, const DebugLoc &DL = DebugLoc()); MachineInstr *insertInstrBefore(MachineBasicBlock::iterator I, int NewOpcode); void insertCondBranchBefore(MachineBasicBlock::iterator I, int NewOpcode, const DebugLoc &DL); void insertCondBranchBefore(MachineBasicBlock *MBB, MachineBasicBlock::iterator I, int NewOpcode, int RegNum, const DebugLoc &DL); static int getBranchNzeroOpcode(int OldOpcode); static int getBranchZeroOpcode(int OldOpcode); static int getContinueNzeroOpcode(int OldOpcode); static int getContinueZeroOpcode(int OldOpcode); static MachineBasicBlock *getTrueBranch(MachineInstr *MI); static void setTrueBranch(MachineInstr *MI, MachineBasicBlock *MBB); static MachineBasicBlock *getFalseBranch(MachineBasicBlock *MBB, MachineInstr *MI); static bool isCondBranch(MachineInstr *MI); static bool isUncondBranch(MachineInstr *MI); static DebugLoc getLastDebugLocInBB(MachineBasicBlock *MBB); static MachineInstr *getNormalBlockBranchInstr(MachineBasicBlock *MBB); /// The correct naming for this is getPossibleLoopendBlockBranchInstr. /// /// BB with backward-edge could have move instructions after the branch /// instruction. Such move instruction ""belong to"" the loop backward-edge. MachineInstr *getLoopendBlockBranchInstr(MachineBasicBlock *MBB); static MachineInstr *getReturnInstr(MachineBasicBlock *MBB); static bool isReturnBlock(MachineBasicBlock *MBB); static void cloneSuccessorList(MachineBasicBlock *DstMBB, MachineBasicBlock *SrcMBB) ; static MachineBasicBlock *clone(MachineBasicBlock *MBB); /// MachineBasicBlock::ReplaceUsesOfBlockWith doesn't serve the purpose /// because the AMDGPU instruction is not recognized as terminator fix this /// and retire this routine void replaceInstrUseOfBlockWith(MachineBasicBlock *SrcMBB, MachineBasicBlock *OldMBB, MachineBasicBlock *NewBlk); static void wrapup(MachineBasicBlock *MBB); int patternMatch(MachineBasicBlock *MBB); int patternMatchGroup(MachineBasicBlock *MBB); int serialPatternMatch(MachineBasicBlock *MBB); int ifPatternMatch(MachineBasicBlock *MBB); int loopendPatternMatch(); int mergeLoop(MachineLoop *LoopRep); /// return true iff src1Blk->succ_size() == 0 && src1Blk and src2Blk are in /// the same loop with LoopLandInfo without explicitly keeping track of /// loopContBlks and loopBreakBlks, this is a method to get the information. bool isSameloopDetachedContbreak(MachineBasicBlock *Src1MBB, MachineBasicBlock *Src2MBB); int handleJumpintoIf(MachineBasicBlock *HeadMBB, MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB); int handleJumpintoIfImp(MachineBasicBlock *HeadMBB, MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB); int improveSimpleJumpintoIf(MachineBasicBlock *HeadMBB, MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB, MachineBasicBlock **LandMBBPtr); void showImproveSimpleJumpintoIf(MachineBasicBlock *HeadMBB, MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB, MachineBasicBlock *LandMBB, bool Detail = false); int cloneOnSideEntryTo(MachineBasicBlock *PreMBB, MachineBasicBlock *SrcMBB, MachineBasicBlock *DstMBB); void mergeSerialBlock(MachineBasicBlock *DstMBB, MachineBasicBlock *SrcMBB); void mergeIfthenelseBlock(MachineInstr *BranchMI, MachineBasicBlock *MBB, MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB, MachineBasicBlock *LandMBB); void mergeLooplandBlock(MachineBasicBlock *DstMBB, MachineBasicBlock *LandMBB); void mergeLoopbreakBlock(MachineBasicBlock *ExitingMBB, MachineBasicBlock *LandMBB); void settleLoopcontBlock(MachineBasicBlock *ContingMBB, MachineBasicBlock *ContMBB); /// normalizeInfiniteLoopExit change /// B1: /// uncond_br LoopHeader /// /// to /// B1: /// cond_br 1 LoopHeader dummyExit /// and return the newly added dummy exit block MachineBasicBlock *normalizeInfiniteLoopExit(MachineLoop *LoopRep); void removeUnconditionalBranch(MachineBasicBlock *MBB); /// Remove duplicate branches instructions in a block. /// For instance /// B0: /// cond_br X B1 B2 /// cond_br X B1 B2 /// is transformed to /// B0: /// cond_br X B1 B2 void removeRedundantConditionalBranch(MachineBasicBlock *MBB); void addDummyExitBlock(SmallVectorImpl &RetMBB); void removeSuccessor(MachineBasicBlock *MBB); MachineBasicBlock *cloneBlockForPredecessor(MachineBasicBlock *MBB, MachineBasicBlock *PredMBB); void migrateInstruction(MachineBasicBlock *SrcMBB, MachineBasicBlock *DstMBB, MachineBasicBlock::iterator I); void recordSccnum(MachineBasicBlock *MBB, int SCCNum); void retireBlock(MachineBasicBlock *MBB); private: MBBInfoMap BlockInfoMap; LoopLandInfoMap LLInfoMap; std::map Visited; MachineFunction *FuncRep; SmallVector OrderedBlks; }; char AMDGPUCFGStructurizer::ID = 0; } // end anonymous namespace int AMDGPUCFGStructurizer::getSCCNum(MachineBasicBlock *MBB) const { MBBInfoMap::const_iterator It = BlockInfoMap.find(MBB); if (It == BlockInfoMap.end()) return INVALIDSCCNUM; return (*It).second->SccNum; } MachineBasicBlock *AMDGPUCFGStructurizer::getLoopLandInfo(MachineLoop *LoopRep) const { LoopLandInfoMap::const_iterator It = LLInfoMap.find(LoopRep); if (It == LLInfoMap.end()) return nullptr; return (*It).second; } bool AMDGPUCFGStructurizer::hasBackEdge(MachineBasicBlock *MBB) const { MachineLoop *LoopRep = MLI->getLoopFor(MBB); if (!LoopRep) return false; MachineBasicBlock *LoopHeader = LoopRep->getHeader(); return MBB->isSuccessor(LoopHeader); } bool AMDGPUCFGStructurizer::isRetiredBlock(MachineBasicBlock *MBB) const { MBBInfoMap::const_iterator It = BlockInfoMap.find(MBB); if (It == BlockInfoMap.end()) return false; return (*It).second->IsRetired; } bool AMDGPUCFGStructurizer::isActiveLoophead(MachineBasicBlock *MBB) const { MachineLoop *LoopRep = MLI->getLoopFor(MBB); while (LoopRep && LoopRep->getHeader() == MBB) { MachineBasicBlock *LoopLand = getLoopLandInfo(LoopRep); if(!LoopLand) return true; if (!isRetiredBlock(LoopLand)) return true; LoopRep = LoopRep->getParentLoop(); } return false; } AMDGPUCFGStructurizer::PathToKind AMDGPUCFGStructurizer::singlePathTo( MachineBasicBlock *SrcMBB, MachineBasicBlock *DstMBB, bool AllowSideEntry) const { assert(DstMBB); if (SrcMBB == DstMBB) return SinglePath_InPath; while (SrcMBB && SrcMBB->succ_size() == 1) { SrcMBB = *SrcMBB->succ_begin(); if (SrcMBB == DstMBB) return SinglePath_InPath; if (!AllowSideEntry && SrcMBB->pred_size() > 1) return Not_SinglePath; } if (SrcMBB && SrcMBB->succ_size()==0) return SinglePath_NotInPath; return Not_SinglePath; } int AMDGPUCFGStructurizer::countActiveBlock(MBBVector::const_iterator It, MBBVector::const_iterator E) const { int Count = 0; while (It != E) { if (!isRetiredBlock(*It)) ++Count; ++It; } return Count; } bool AMDGPUCFGStructurizer::needMigrateBlock(MachineBasicBlock *MBB) const { unsigned BlockSizeThreshold = 30; unsigned CloneInstrThreshold = 100; bool MultiplePreds = MBB && (MBB->pred_size() > 1); if(!MultiplePreds) return false; unsigned BlkSize = MBB->size(); return ((BlkSize > BlockSizeThreshold) && (BlkSize * (MBB->pred_size() - 1) > CloneInstrThreshold)); } void AMDGPUCFGStructurizer::reversePredicateSetter( MachineBasicBlock::iterator I, MachineBasicBlock &MBB) { assert(I.isValid() && ""Expected valid iterator""); for (;; --I) { if (I == MBB.end()) continue; if (I->getOpcode() == AMDGPU::PRED_X) { switch (I->getOperand(2).getImm()) { case AMDGPU::PRED_SETE_INT: I->getOperand(2).setImm(AMDGPU::PRED_SETNE_INT); return; case AMDGPU::PRED_SETNE_INT: I->getOperand(2).setImm(AMDGPU::PRED_SETE_INT); return; case AMDGPU::PRED_SETE: I->getOperand(2).setImm(AMDGPU::PRED_SETNE); return; case AMDGPU::PRED_SETNE: I->getOperand(2).setImm(AMDGPU::PRED_SETE); return; default: llvm_unreachable(""PRED_X Opcode invalid!""); } } } } void AMDGPUCFGStructurizer::insertInstrEnd(MachineBasicBlock *MBB, int NewOpcode, const DebugLoc &DL) { MachineInstr *MI = MBB->getParent()->CreateMachineInstr(TII->get(NewOpcode), DL); MBB->push_back(MI); //assume the instruction doesn't take any reg operand ... SHOWNEWINSTR(MI); } MachineInstr *AMDGPUCFGStructurizer::insertInstrBefore(MachineBasicBlock *MBB, int NewOpcode, const DebugLoc &DL) { MachineInstr *MI = MBB->getParent()->CreateMachineInstr(TII->get(NewOpcode), DL); if (MBB->begin() != MBB->end()) MBB->insert(MBB->begin(), MI); else MBB->push_back(MI); SHOWNEWINSTR(MI); return MI; } MachineInstr *AMDGPUCFGStructurizer::insertInstrBefore( MachineBasicBlock::iterator I, int NewOpcode) { MachineInstr *OldMI = &(*I); MachineBasicBlock *MBB = OldMI->getParent(); MachineInstr *NewMBB = MBB->getParent()->CreateMachineInstr(TII->get(NewOpcode), DebugLoc()); MBB->insert(I, NewMBB); //assume the instruction doesn't take any reg operand ... SHOWNEWINSTR(NewMBB); return NewMBB; } void AMDGPUCFGStructurizer::insertCondBranchBefore( MachineBasicBlock::iterator I, int NewOpcode, const DebugLoc &DL) { MachineInstr *OldMI = &(*I); MachineBasicBlock *MBB = OldMI->getParent(); MachineFunction *MF = MBB->getParent(); MachineInstr *NewMI = MF->CreateMachineInstr(TII->get(NewOpcode), DL); MBB->insert(I, NewMI); MachineInstrBuilder MIB(*MF, NewMI); MIB.addReg(OldMI->getOperand(1).getReg(), false); SHOWNEWINSTR(NewMI); //erase later oldInstr->eraseFromParent(); } void AMDGPUCFGStructurizer::insertCondBranchBefore( MachineBasicBlock *blk, MachineBasicBlock::iterator I, int NewOpcode, int RegNum, const DebugLoc &DL) { MachineFunction *MF = blk->getParent(); MachineInstr *NewInstr = MF->CreateMachineInstr(TII->get(NewOpcode), DL); //insert before blk->insert(I, NewInstr); MachineInstrBuilder(*MF, NewInstr).addReg(RegNum, false); SHOWNEWINSTR(NewInstr); } int AMDGPUCFGStructurizer::getBranchNzeroOpcode(int OldOpcode) { switch(OldOpcode) { case AMDGPU::JUMP_COND: case AMDGPU::JUMP: return AMDGPU::IF_PREDICATE_SET; case AMDGPU::BRANCH_COND_i32: case AMDGPU::BRANCH_COND_f32: return AMDGPU::IF_LOGICALNZ_f32; default: llvm_unreachable(""internal error""); } return -1; } int AMDGPUCFGStructurizer::getBranchZeroOpcode(int OldOpcode) { switch(OldOpcode) { case AMDGPU::JUMP_COND: case AMDGPU::JUMP: return AMDGPU::IF_PREDICATE_SET; case AMDGPU::BRANCH_COND_i32: case AMDGPU::BRANCH_COND_f32: return AMDGPU::IF_LOGICALZ_f32; default: llvm_unreachable(""internal error""); } return -1; } int AMDGPUCFGStructurizer::getContinueNzeroOpcode(int OldOpcode) { switch(OldOpcode) { case AMDGPU::JUMP_COND: case AMDGPU::JUMP: return AMDGPU::CONTINUE_LOGICALNZ_i32; default: llvm_unreachable(""internal error""); }; return -1; } int AMDGPUCFGStructurizer::getContinueZeroOpcode(int OldOpcode) { switch(OldOpcode) { case AMDGPU::JUMP_COND: case AMDGPU::JUMP: return AMDGPU::CONTINUE_LOGICALZ_i32; default: llvm_unreachable(""internal error""); } return -1; } MachineBasicBlock *AMDGPUCFGStructurizer::getTrueBranch(MachineInstr *MI) { return MI->getOperand(0).getMBB(); } void AMDGPUCFGStructurizer::setTrueBranch(MachineInstr *MI, MachineBasicBlock *MBB) { MI->getOperand(0).setMBB(MBB); } MachineBasicBlock * AMDGPUCFGStructurizer::getFalseBranch(MachineBasicBlock *MBB, MachineInstr *MI) { assert(MBB->succ_size() == 2); MachineBasicBlock *TrueBranch = getTrueBranch(MI); MachineBasicBlock::succ_iterator It = MBB->succ_begin(); MachineBasicBlock::succ_iterator Next = It; ++Next; return (*It == TrueBranch) ? *Next : *It; } bool AMDGPUCFGStructurizer::isCondBranch(MachineInstr *MI) { switch (MI->getOpcode()) { case AMDGPU::JUMP_COND: case AMDGPU::BRANCH_COND_i32: case AMDGPU::BRANCH_COND_f32: return true; default: return false; } return false; } bool AMDGPUCFGStructurizer::isUncondBranch(MachineInstr *MI) { switch (MI->getOpcode()) { case AMDGPU::JUMP: case AMDGPU::BRANCH: return true; default: return false; } return false; } DebugLoc AMDGPUCFGStructurizer::getLastDebugLocInBB(MachineBasicBlock *MBB) { //get DebugLoc from the first MachineBasicBlock instruction with debug info DebugLoc DL; for (MachineBasicBlock::iterator It = MBB->begin(); It != MBB->end(); ++It) { MachineInstr *instr = &(*It); if (instr->getDebugLoc()) DL = instr->getDebugLoc(); } return DL; } MachineInstr *AMDGPUCFGStructurizer::getNormalBlockBranchInstr( MachineBasicBlock *MBB) { MachineBasicBlock::reverse_iterator It = MBB->rbegin(); MachineInstr *MI = &*It; if (MI && (isCondBranch(MI) || isUncondBranch(MI))) return MI; return nullptr; } MachineInstr *AMDGPUCFGStructurizer::getLoopendBlockBranchInstr( MachineBasicBlock *MBB) { for (MachineBasicBlock::reverse_iterator It = MBB->rbegin(), E = MBB->rend(); It != E; ++It) { // FIXME: Simplify MachineInstr *MI = &*It; if (MI) { if (isCondBranch(MI) || isUncondBranch(MI)) return MI; else if (!TII->isMov(MI->getOpcode())) break; } } return nullptr; } MachineInstr *AMDGPUCFGStructurizer::getReturnInstr(MachineBasicBlock *MBB) { MachineBasicBlock::reverse_iterator It = MBB->rbegin(); if (It != MBB->rend()) { MachineInstr *instr = &(*It); if (instr->getOpcode() == AMDGPU::RETURN) return instr; } return nullptr; } bool AMDGPUCFGStructurizer::isReturnBlock(MachineBasicBlock *MBB) { MachineInstr *MI = getReturnInstr(MBB); bool IsReturn = (MBB->succ_size() == 0); if (MI) assert(IsReturn); else if (IsReturn) DEBUG( dbgs() << ""BB"" << MBB->getNumber() <<"" is return block without RETURN instr\\n"";); return IsReturn; } void AMDGPUCFGStructurizer::cloneSuccessorList(MachineBasicBlock *DstMBB, MachineBasicBlock *SrcMBB) { for (MachineBasicBlock::succ_iterator It = SrcMBB->succ_begin(), iterEnd = SrcMBB->succ_end(); It != iterEnd; ++It) DstMBB->addSuccessor(*It); // *iter's predecessor is also taken care of } MachineBasicBlock *AMDGPUCFGStructurizer::clone(MachineBasicBlock *MBB) { MachineFunction *Func = MBB->getParent(); MachineBasicBlock *NewMBB = Func->CreateMachineBasicBlock(); Func->push_back(NewMBB); //insert to function for (const MachineInstr &It : *MBB) NewMBB->push_back(Func->CloneMachineInstr(&It)); return NewMBB; } void AMDGPUCFGStructurizer::replaceInstrUseOfBlockWith( MachineBasicBlock *SrcMBB, MachineBasicBlock *OldMBB, MachineBasicBlock *NewBlk) { MachineInstr *BranchMI = getLoopendBlockBranchInstr(SrcMBB); if (BranchMI && isCondBranch(BranchMI) && getTrueBranch(BranchMI) == OldMBB) setTrueBranch(BranchMI, NewBlk); } void AMDGPUCFGStructurizer::wrapup(MachineBasicBlock *MBB) { assert((!MBB->getParent()->getJumpTableInfo() || MBB->getParent()->getJumpTableInfo()->isEmpty()) && ""found a jump table""); //collect continue right before endloop SmallVector ContInstr; MachineBasicBlock::iterator Pre = MBB->begin(); MachineBasicBlock::iterator E = MBB->end(); MachineBasicBlock::iterator It = Pre; while (It != E) { if (Pre->getOpcode() == AMDGPU::CONTINUE && It->getOpcode() == AMDGPU::ENDLOOP) ContInstr.push_back(&*Pre); Pre = It; ++It; } //delete continue right before endloop for (unsigned i = 0; i < ContInstr.size(); ++i) ContInstr[i]->eraseFromParent(); // TODO to fix up jump table so later phase won't be confused. if // (jumpTableInfo->isEmpty() == false) { need to clean the jump table, but // there isn't such an interface yet. alternatively, replace all the other // blocks in the jump table with the entryBlk //} } bool AMDGPUCFGStructurizer::prepare() { bool Changed = false; //FIXME: if not reducible flow graph, make it so ??? DEBUG(dbgs() << ""AMDGPUCFGStructurizer::prepare\\n"";); orderBlocks(FuncRep); SmallVector RetBlks; // Add an ExitBlk to loop that don't have one for (MachineLoopInfo::iterator It = MLI->begin(), E = MLI->end(); It != E; ++It) { MachineLoop *LoopRep = (*It); MBBVector ExitingMBBs; LoopRep->getExitingBlocks(ExitingMBBs); if (ExitingMBBs.size() == 0) { MachineBasicBlock* DummyExitBlk = normalizeInfiniteLoopExit(LoopRep); if (DummyExitBlk) RetBlks.push_back(DummyExitBlk); } } // Remove unconditional branch instr. // Add dummy exit block iff there are multiple returns. for (SmallVectorImpl::const_iterator It = OrderedBlks.begin(), E = OrderedBlks.end(); It != E; ++It) { MachineBasicBlock *MBB = *It; removeUnconditionalBranch(MBB); removeRedundantConditionalBranch(MBB); if (isReturnBlock(MBB)) { RetBlks.push_back(MBB); } assert(MBB->succ_size() <= 2); } if (RetBlks.size() >= 2) { addDummyExitBlock(RetBlks); Changed = true; } return Changed; } bool AMDGPUCFGStructurizer::run() { //Assume reducible CFG... DEBUG(dbgs() << ""AMDGPUCFGStructurizer::run\\n""); #ifdef STRESSTEST //Use the worse block ordering to test the algorithm. ReverseVector(orderedBlks); #endif DEBUG(dbgs() << ""Ordered blocks:\\n""; printOrderedBlocks();); int NumIter = 0; bool Finish = false; MachineBasicBlock *MBB; bool MakeProgress = false; int NumRemainedBlk = countActiveBlock(OrderedBlks.begin(), OrderedBlks.end()); do { ++NumIter; DEBUG( dbgs() << ""numIter = "" << NumIter << "", numRemaintedBlk = "" << NumRemainedBlk << ""\\n""; ); SmallVectorImpl::const_iterator It = OrderedBlks.begin(); SmallVectorImpl::const_iterator E = OrderedBlks.end(); SmallVectorImpl::const_iterator SccBeginIter = It; MachineBasicBlock *SccBeginMBB = nullptr; int SccNumBlk = 0; // The number of active blocks, init to a // maximum possible number. int SccNumIter; // Number of iteration in this SCC. while (It != E) { MBB = *It; if (!SccBeginMBB) { SccBeginIter = It; SccBeginMBB = MBB; SccNumIter = 0; SccNumBlk = NumRemainedBlk; // Init to maximum possible number. DEBUG( dbgs() << ""start processing SCC"" << getSCCNum(SccBeginMBB); dbgs() << ""\\n""; ); } if (!isRetiredBlock(MBB)) patternMatch(MBB); ++It; bool ContNextScc = true; if (It == E || getSCCNum(SccBeginMBB) != getSCCNum(*It)) { // Just finish one scc. ++SccNumIter; int sccRemainedNumBlk = countActiveBlock(SccBeginIter, It); if (sccRemainedNumBlk != 1 && sccRemainedNumBlk >= SccNumBlk) { DEBUG( dbgs() << ""Can't reduce SCC "" << getSCCNum(MBB) << "", sccNumIter = "" << SccNumIter; dbgs() << ""doesn't make any progress\\n""; ); ContNextScc = true; } else if (sccRemainedNumBlk != 1 && sccRemainedNumBlk < SccNumBlk) { SccNumBlk = sccRemainedNumBlk; It = SccBeginIter; ContNextScc = false; DEBUG( dbgs() << ""repeat processing SCC"" << getSCCNum(MBB) << ""sccNumIter = "" << SccNumIter << '\\n'; ); } else { // Finish the current scc. ContNextScc = true; } } else { // Continue on next component in the current scc. ContNextScc = false; } if (ContNextScc) SccBeginMBB = nullptr; } //while, ""one iteration"" over the function. MachineBasicBlock *EntryMBB = *GraphTraits::nodes_begin(FuncRep); if (EntryMBB->succ_size() == 0) { Finish = true; DEBUG( dbgs() << ""Reduce to one block\\n""; ); } else { int NewnumRemainedBlk = countActiveBlock(OrderedBlks.begin(), OrderedBlks.end()); // consider cloned blocks ?? if (NewnumRemainedBlk == 1 || NewnumRemainedBlk < NumRemainedBlk) { MakeProgress = true; NumRemainedBlk = NewnumRemainedBlk; } else { MakeProgress = false; DEBUG( dbgs() << ""No progress\\n""; ); } } } while (!Finish && MakeProgress); // Misc wrap up to maintain the consistency of the Function representation. wrapup(*GraphTraits::nodes_begin(FuncRep)); // Detach retired Block, release memory. for (MBBInfoMap::iterator It = BlockInfoMap.begin(), E = BlockInfoMap.end(); It != E; ++It) { if ((*It).second && (*It).second->IsRetired) { assert(((*It).first)->getNumber() != -1); DEBUG( dbgs() << ""Erase BB"" << ((*It).first)->getNumber() << ""\\n""; ); (*It).first->eraseFromParent(); //Remove from the parent Function. } delete (*It).second; } BlockInfoMap.clear(); LLInfoMap.clear(); if (!Finish) { DEBUG(FuncRep->viewCFG()); report_fatal_error(""IRREDUCIBLE_CFG""); } return true; } void AMDGPUCFGStructurizer::orderBlocks(MachineFunction *MF) { int SccNum = 0; MachineBasicBlock *MBB; for (scc_iterator It = scc_begin(MF); !It.isAtEnd(); ++It, ++SccNum) { const std::vector &SccNext = *It; for (std::vector::const_iterator blockIter = SccNext.begin(), blockEnd = SccNext.end(); blockIter != blockEnd; ++blockIter) { MBB = *blockIter; OrderedBlks.push_back(MBB); recordSccnum(MBB, SccNum); } } // walk through all the block in func to check for unreachable for (auto *MBB : nodes(MF)) { SccNum = getSCCNum(MBB); if (SccNum == INVALIDSCCNUM) dbgs() << ""unreachable block BB"" << MBB->getNumber() << ""\\n""; } } int AMDGPUCFGStructurizer::patternMatch(MachineBasicBlock *MBB) { int NumMatch = 0; int CurMatch; DEBUG( dbgs() << ""Begin patternMatch BB"" << MBB->getNumber() << ""\\n""; ); while ((CurMatch = patternMatchGroup(MBB)) > 0) NumMatch += CurMatch; DEBUG( dbgs() << ""End patternMatch BB"" << MBB->getNumber() << "", numMatch = "" << NumMatch << ""\\n""; ); return NumMatch; } int AMDGPUCFGStructurizer::patternMatchGroup(MachineBasicBlock *MBB) { int NumMatch = 0; NumMatch += loopendPatternMatch(); NumMatch += serialPatternMatch(MBB); NumMatch += ifPatternMatch(MBB); return NumMatch; } int AMDGPUCFGStructurizer::serialPatternMatch(MachineBasicBlock *MBB) { if (MBB->succ_size() != 1) return 0; MachineBasicBlock *childBlk = *MBB->succ_begin(); if (childBlk->pred_size() != 1 || isActiveLoophead(childBlk)) return 0; mergeSerialBlock(MBB, childBlk); ++numSerialPatternMatch; return 1; } int AMDGPUCFGStructurizer::ifPatternMatch(MachineBasicBlock *MBB) { //two edges if (MBB->succ_size() != 2) return 0; if (hasBackEdge(MBB)) return 0; MachineInstr *BranchMI = getNormalBlockBranchInstr(MBB); if (!BranchMI) return 0; assert(isCondBranch(BranchMI)); int NumMatch = 0; MachineBasicBlock *TrueMBB = getTrueBranch(BranchMI); NumMatch += serialPatternMatch(TrueMBB); NumMatch += ifPatternMatch(TrueMBB); MachineBasicBlock *FalseMBB = getFalseBranch(MBB, BranchMI); NumMatch += serialPatternMatch(FalseMBB); NumMatch += ifPatternMatch(FalseMBB); MachineBasicBlock *LandBlk; int Cloned = 0; assert (!TrueMBB->succ_empty() || !FalseMBB->succ_empty()); // TODO: Simplify if (TrueMBB->succ_size() == 1 && FalseMBB->succ_size() == 1 && *TrueMBB->succ_begin() == *FalseMBB->succ_begin()) { // Diamond pattern LandBlk = *TrueMBB->succ_begin(); } else if (TrueMBB->succ_size() == 1 && *TrueMBB->succ_begin() == FalseMBB) { // Triangle pattern, false is empty LandBlk = FalseMBB; FalseMBB = nullptr; } else if (FalseMBB->succ_size() == 1 && *FalseMBB->succ_begin() == TrueMBB) { // Triangle pattern, true is empty // We reverse the predicate to make a triangle, empty false pattern; std::swap(TrueMBB, FalseMBB); reversePredicateSetter(MBB->end(), *MBB); LandBlk = FalseMBB; FalseMBB = nullptr; } else if (FalseMBB->succ_size() == 1 && isSameloopDetachedContbreak(TrueMBB, FalseMBB)) { LandBlk = *FalseMBB->succ_begin(); } else if (TrueMBB->succ_size() == 1 && isSameloopDetachedContbreak(FalseMBB, TrueMBB)) { LandBlk = *TrueMBB->succ_begin(); } else { return NumMatch + handleJumpintoIf(MBB, TrueMBB, FalseMBB); } // improveSimpleJumpinfoIf can handle the case where landBlk == NULL but the // new BB created for landBlk==NULL may introduce new challenge to the // reduction process. if (LandBlk && ((TrueMBB && TrueMBB->pred_size() > 1) || (FalseMBB && FalseMBB->pred_size() > 1))) { Cloned += improveSimpleJumpintoIf(MBB, TrueMBB, FalseMBB, &LandBlk); } if (TrueMBB && TrueMBB->pred_size() > 1) { TrueMBB = cloneBlockForPredecessor(TrueMBB, MBB); ++Cloned; } if (FalseMBB && FalseMBB->pred_size() > 1) { FalseMBB = cloneBlockForPredecessor(FalseMBB, MBB); ++Cloned; } mergeIfthenelseBlock(BranchMI, MBB, TrueMBB, FalseMBB, LandBlk); ++numIfPatternMatch; numClonedBlock += Cloned; return 1 + Cloned + NumMatch; } int AMDGPUCFGStructurizer::loopendPatternMatch() { std::deque NestedLoops; for (auto &It: *MLI) for (MachineLoop *ML : depth_first(It)) NestedLoops.push_front(ML); if (NestedLoops.empty()) return 0; // Process nested loop outside->inside (we did push_front), // so ""continue"" to a outside loop won't be mistaken as ""break"" // of the current loop. int Num = 0; for (MachineLoop *ExaminedLoop : NestedLoops) { if (ExaminedLoop->getNumBlocks() == 0 || Visited[ExaminedLoop]) continue; DEBUG(dbgs() << ""Processing:\\n""; ExaminedLoop->dump();); int NumBreak = mergeLoop(ExaminedLoop); if (NumBreak == -1) break; Num += NumBreak; } return Num; } int AMDGPUCFGStructurizer::mergeLoop(MachineLoop *LoopRep) { MachineBasicBlock *LoopHeader = LoopRep->getHeader(); MBBVector ExitingMBBs; LoopRep->getExitingBlocks(ExitingMBBs); assert(!ExitingMBBs.empty() && ""Infinite Loop not supported""); DEBUG(dbgs() << ""Loop has "" << ExitingMBBs.size() << "" exiting blocks\\n"";); // We assume a single ExitBlk MBBVector ExitBlks; LoopRep->getExitBlocks(ExitBlks); SmallPtrSet ExitBlkSet; for (unsigned i = 0, e = ExitBlks.size(); i < e; ++i) ExitBlkSet.insert(ExitBlks[i]); assert(ExitBlkSet.size() == 1); MachineBasicBlock *ExitBlk = *ExitBlks.begin(); assert(ExitBlk && ""Loop has several exit block""); MBBVector LatchBlks; for (auto *LB : inverse_children(LoopHeader)) if (LoopRep->contains(LB)) LatchBlks.push_back(LB); for (unsigned i = 0, e = ExitingMBBs.size(); i < e; ++i) mergeLoopbreakBlock(ExitingMBBs[i], ExitBlk); for (unsigned i = 0, e = LatchBlks.size(); i < e; ++i) settleLoopcontBlock(LatchBlks[i], LoopHeader); int Match = 0; do { Match = 0; Match += serialPatternMatch(LoopHeader); Match += ifPatternMatch(LoopHeader); } while (Match > 0); mergeLooplandBlock(LoopHeader, ExitBlk); MachineLoop *ParentLoop = LoopRep->getParentLoop(); if (ParentLoop) MLI->changeLoopFor(LoopHeader, ParentLoop); else MLI->removeBlock(LoopHeader); Visited[LoopRep] = true; return 1; } bool AMDGPUCFGStructurizer::isSameloopDetachedContbreak( MachineBasicBlock *Src1MBB, MachineBasicBlock *Src2MBB) { if (Src1MBB->succ_size() == 0) { MachineLoop *LoopRep = MLI->getLoopFor(Src1MBB); if (LoopRep&& LoopRep == MLI->getLoopFor(Src2MBB)) { MachineBasicBlock *&TheEntry = LLInfoMap[LoopRep]; if (TheEntry) { DEBUG( dbgs() << ""isLoopContBreakBlock yes src1 = BB"" << Src1MBB->getNumber() << "" src2 = BB"" << Src2MBB->getNumber() << ""\\n""; ); return true; } } } return false; } int AMDGPUCFGStructurizer::handleJumpintoIf(MachineBasicBlock *HeadMBB, MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB) { int Num = handleJumpintoIfImp(HeadMBB, TrueMBB, FalseMBB); if (Num == 0) { DEBUG( dbgs() << ""handleJumpintoIf swap trueBlk and FalseBlk"" << ""\\n""; ); Num = handleJumpintoIfImp(HeadMBB, FalseMBB, TrueMBB); } return Num; } int AMDGPUCFGStructurizer::handleJumpintoIfImp(MachineBasicBlock *HeadMBB, MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB) { int Num = 0; MachineBasicBlock *DownBlk; //trueBlk could be the common post dominator DownBlk = TrueMBB; DEBUG( dbgs() << ""handleJumpintoIfImp head = BB"" << HeadMBB->getNumber() << "" true = BB"" << TrueMBB->getNumber() << "", numSucc="" << TrueMBB->succ_size() << "" false = BB"" << FalseMBB->getNumber() << ""\\n""; ); while (DownBlk) { DEBUG( dbgs() << ""check down = BB"" << DownBlk->getNumber(); ); if (singlePathTo(FalseMBB, DownBlk) == SinglePath_InPath) { DEBUG( dbgs() << "" working\\n""; ); Num += cloneOnSideEntryTo(HeadMBB, TrueMBB, DownBlk); Num += cloneOnSideEntryTo(HeadMBB, FalseMBB, DownBlk); numClonedBlock += Num; Num += serialPatternMatch(*HeadMBB->succ_begin()); Num += serialPatternMatch(*std::next(HeadMBB->succ_begin())); Num += ifPatternMatch(HeadMBB); assert(Num > 0); break; } DEBUG( dbgs() << "" not working\\n""; ); DownBlk = (DownBlk->succ_size() == 1) ? (*DownBlk->succ_begin()) : nullptr; } // walk down the postDomTree return Num; } void AMDGPUCFGStructurizer::showImproveSimpleJumpintoIf( MachineBasicBlock *HeadMBB, MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB, MachineBasicBlock *LandMBB, bool Detail) { dbgs() << ""head = BB"" << HeadMBB->getNumber() << "" size = "" << HeadMBB->size(); if (Detail) { dbgs() << ""\\n""; HeadMBB->print(dbgs()); dbgs() << ""\\n""; } if (TrueMBB) { dbgs() << "", true = BB"" << TrueMBB->getNumber() << "" size = "" << TrueMBB->size() << "" numPred = "" << TrueMBB->pred_size(); if (Detail) { dbgs() << ""\\n""; TrueMBB->print(dbgs()); dbgs() << ""\\n""; } } if (FalseMBB) { dbgs() << "", false = BB"" << FalseMBB->getNumber() << "" size = "" << FalseMBB->size() << "" numPred = "" << FalseMBB->pred_size(); if (Detail) { dbgs() << ""\\n""; FalseMBB->print(dbgs()); dbgs() << ""\\n""; } } if (LandMBB) { dbgs() << "", land = BB"" << LandMBB->getNumber() << "" size = "" << LandMBB->size() << "" numPred = "" << LandMBB->pred_size(); if (Detail) { dbgs() << ""\\n""; LandMBB->print(dbgs()); dbgs() << ""\\n""; } } dbgs() << ""\\n""; } int AMDGPUCFGStructurizer::improveSimpleJumpintoIf(MachineBasicBlock *HeadMBB, MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB, MachineBasicBlock **LandMBBPtr) { bool MigrateTrue = false; bool MigrateFalse = false; MachineBasicBlock *LandBlk = *LandMBBPtr; assert((!TrueMBB || TrueMBB->succ_size() <= 1) && (!FalseMBB || FalseMBB->succ_size() <= 1)); if (TrueMBB == FalseMBB) return 0; MigrateTrue = needMigrateBlock(TrueMBB); MigrateFalse = needMigrateBlock(FalseMBB); if (!MigrateTrue && !MigrateFalse) return 0; // If we need to migrate either trueBlk and falseBlk, migrate the rest that // have more than one predecessors. without doing this, its predecessor // rather than headBlk will have undefined value in initReg. if (!MigrateTrue && TrueMBB && TrueMBB->pred_size() > 1) MigrateTrue = true; if (!MigrateFalse && FalseMBB && FalseMBB->pred_size() > 1) MigrateFalse = true; DEBUG( dbgs() << ""before improveSimpleJumpintoIf: ""; showImproveSimpleJumpintoIf(HeadMBB, TrueMBB, FalseMBB, LandBlk, 0); ); // org: headBlk => if () {trueBlk} else {falseBlk} => landBlk // // new: headBlk => if () {initReg = 1; org trueBlk branch} else // {initReg = 0; org falseBlk branch } // => landBlk => if (initReg) {org trueBlk} else {org falseBlk} // => org landBlk // if landBlk->pred_size() > 2, put the about if-else inside // if (initReg !=2) {...} // // add initReg = initVal to headBlk const TargetRegisterClass * I32RC = TRI->getCFGStructurizerRegClass(MVT::i32); if (!MigrateTrue || !MigrateFalse) { // XXX: We have an opportunity here to optimize the ""branch into if"" case // here. Branch into if looks like this: // entry // / | // diamond_head branch_from // / \\ | // diamond_false diamond_true // \\ / // done // // The diamond_head block begins the ""if"" and the diamond_true block // is the block being ""branched into"". // // If MigrateTrue is true, then TrueBB is the block being ""branched into"" // and if MigrateFalse is true, then FalseBB is the block being // ""branched into"" // // Here is the pseudo code for how I think the optimization should work: // 1. Insert MOV GPR0, 0 before the branch instruction in diamond_head. // 2. Insert MOV GPR0, 1 before the branch instruction in branch_from. // 3. Move the branch instruction from diamond_head into its own basic // block (new_block). // 4. Add an unconditional branch from diamond_head to new_block // 5. Replace the branch instruction in branch_from with an unconditional // branch to new_block. If branch_from has multiple predecessors, then // we need to replace the True/False block in the branch // instruction instead of replacing it. // 6. Change the condition of the branch instruction in new_block from // COND to (COND || GPR0) // // In order insert these MOV instruction, we will need to use the // RegisterScavenger. Usually liveness stops being tracked during // the late machine optimization passes, however if we implement // bool TargetRegisterInfo::requiresRegisterScavenging( // const MachineFunction &MF) // and have it return true, liveness will be tracked correctly // by generic optimization passes. We will also need to make sure that // all of our target-specific passes that run after regalloc and before // the CFGStructurizer track liveness and we will need to modify this pass // to correctly track liveness. // // After the above changes, the new CFG should look like this: // entry // / | // diamond_head branch_from // \\ / // new_block // / | // diamond_false diamond_true // \\ / // done // // Without this optimization, we are forced to duplicate the diamond_true // block and we will end up with a CFG like this: // // entry // / | // diamond_head branch_from // / \\ | // diamond_false diamond_true diamond_true (duplicate) // \\ / | // done --------------------| // // Duplicating diamond_true can be very costly especially if it has a // lot of instructions. return 0; } int NumNewBlk = 0; bool LandBlkHasOtherPred = (LandBlk->pred_size() > 2); //insert AMDGPU::ENDIF to avoid special case ""input landBlk == NULL"" MachineBasicBlock::iterator I = insertInstrBefore(LandBlk, AMDGPU::ENDIF); if (LandBlkHasOtherPred) { report_fatal_error(""Extra register needed to handle CFG""); unsigned CmpResReg = HeadMBB->getParent()->getRegInfo().createVirtualRegister(I32RC); report_fatal_error(""Extra compare instruction needed to handle CFG""); insertCondBranchBefore(LandBlk, I, AMDGPU::IF_PREDICATE_SET, CmpResReg, DebugLoc()); } // XXX: We are running this after RA, so creating virtual registers will // cause an assertion failure in the PostRA scheduling pass. unsigned InitReg = HeadMBB->getParent()->getRegInfo().createVirtualRegister(I32RC); insertCondBranchBefore(LandBlk, I, AMDGPU::IF_PREDICATE_SET, InitReg, DebugLoc()); if (MigrateTrue) { migrateInstruction(TrueMBB, LandBlk, I); // need to uncondionally insert the assignment to ensure a path from its // predecessor rather than headBlk has valid value in initReg if // (initVal != 1). report_fatal_error(""Extra register needed to handle CFG""); } insertInstrBefore(I, AMDGPU::ELSE); if (MigrateFalse) { migrateInstruction(FalseMBB, LandBlk, I); // need to uncondionally insert the assignment to ensure a path from its // predecessor rather than headBlk has valid value in initReg if // (initVal != 0) report_fatal_error(""Extra register needed to handle CFG""); } if (LandBlkHasOtherPred) { // add endif insertInstrBefore(I, AMDGPU::ENDIF); // put initReg = 2 to other predecessors of landBlk for (MachineBasicBlock::pred_iterator PI = LandBlk->pred_begin(), PE = LandBlk->pred_end(); PI != PE; ++PI) { MachineBasicBlock *MBB = *PI; if (MBB != TrueMBB && MBB != FalseMBB) report_fatal_error(""Extra register needed to handle CFG""); } } DEBUG( dbgs() << ""result from improveSimpleJumpintoIf: ""; showImproveSimpleJumpintoIf(HeadMBB, TrueMBB, FalseMBB, LandBlk, 0); ); // update landBlk *LandMBBPtr = LandBlk; return NumNewBlk; } void AMDGPUCFGStructurizer::mergeSerialBlock(MachineBasicBlock *DstMBB, MachineBasicBlock *SrcMBB) { DEBUG( dbgs() << ""serialPattern BB"" << DstMBB->getNumber() << "" <= BB"" << SrcMBB->getNumber() << ""\\n""; ); DstMBB->splice(DstMBB->end(), SrcMBB, SrcMBB->begin(), SrcMBB->end()); DstMBB->removeSuccessor(SrcMBB, true); cloneSuccessorList(DstMBB, SrcMBB); removeSuccessor(SrcMBB); MLI->removeBlock(SrcMBB); retireBlock(SrcMBB); } void AMDGPUCFGStructurizer::mergeIfthenelseBlock(MachineInstr *BranchMI, MachineBasicBlock *MBB, MachineBasicBlock *TrueMBB, MachineBasicBlock *FalseMBB, MachineBasicBlock *LandMBB) { assert (TrueMBB); DEBUG( dbgs() << ""ifPattern BB"" << MBB->getNumber(); dbgs() << ""{ ""; if (TrueMBB) { dbgs() << ""BB"" << TrueMBB->getNumber(); } dbgs() << "" } else ""; dbgs() << ""{ ""; if (FalseMBB) { dbgs() << ""BB"" << FalseMBB->getNumber(); } dbgs() << "" }\\n ""; dbgs() << ""landBlock: ""; if (!LandMBB) { dbgs() << ""NULL""; } else { dbgs() << ""BB"" << LandMBB->getNumber(); } dbgs() << ""\\n""; ); int OldOpcode = BranchMI->getOpcode(); DebugLoc BranchDL = BranchMI->getDebugLoc(); // transform to // if cond // trueBlk // else // falseBlk // endif // landBlk MachineBasicBlock::iterator I = BranchMI; insertCondBranchBefore(I, getBranchNzeroOpcode(OldOpcode), BranchDL); if (TrueMBB) { MBB->splice(I, TrueMBB, TrueMBB->begin(), TrueMBB->end()); MBB->removeSuccessor(TrueMBB, true); if (LandMBB && TrueMBB->succ_size()!=0) TrueMBB->removeSuccessor(LandMBB, true); retireBlock(TrueMBB); MLI->removeBlock(TrueMBB); } if (FalseMBB) { insertInstrBefore(I, AMDGPU::ELSE); MBB->splice(I, FalseMBB, FalseMBB->begin(), FalseMBB->end()); MBB->removeSuccessor(FalseMBB, true); if (LandMBB && FalseMBB->succ_size() != 0) FalseMBB->removeSuccessor(LandMBB, true); retireBlock(FalseMBB); MLI->removeBlock(FalseMBB); } insertInstrBefore(I, AMDGPU::ENDIF); BranchMI->eraseFromParent(); if (LandMBB && TrueMBB && FalseMBB) MBB->addSuccessor(LandMBB); } void AMDGPUCFGStructurizer::mergeLooplandBlock(MachineBasicBlock *DstBlk, MachineBasicBlock *LandMBB) { DEBUG(dbgs() << ""loopPattern header = BB"" << DstBlk->getNumber() << "" land = BB"" << LandMBB->getNumber() << ""\\n"";); insertInstrBefore(DstBlk, AMDGPU::WHILELOOP, DebugLoc()); insertInstrEnd(DstBlk, AMDGPU::ENDLOOP, DebugLoc()); DstBlk->replaceSuccessor(DstBlk, LandMBB); } void AMDGPUCFGStructurizer::mergeLoopbreakBlock(MachineBasicBlock *ExitingMBB, MachineBasicBlock *LandMBB) { DEBUG(dbgs() << ""loopbreakPattern exiting = BB"" << ExitingMBB->getNumber() << "" land = BB"" << LandMBB->getNumber() << ""\\n"";); MachineInstr *BranchMI = getLoopendBlockBranchInstr(ExitingMBB); assert(BranchMI && isCondBranch(BranchMI)); DebugLoc DL = BranchMI->getDebugLoc(); MachineBasicBlock *TrueBranch = getTrueBranch(BranchMI); MachineBasicBlock::iterator I = BranchMI; if (TrueBranch != LandMBB) reversePredicateSetter(I, *I->getParent()); insertCondBranchBefore(ExitingMBB, I, AMDGPU::IF_PREDICATE_SET, AMDGPU::PREDICATE_BIT, DL); insertInstrBefore(I, AMDGPU::BREAK); insertInstrBefore(I, AMDGPU::ENDIF); //now branchInst can be erase safely BranchMI->eraseFromParent(); //now take care of successors, retire blocks ExitingMBB->removeSuccessor(LandMBB, true); } void AMDGPUCFGStructurizer::settleLoopcontBlock(MachineBasicBlock *ContingMBB, MachineBasicBlock *ContMBB) { DEBUG(dbgs() << ""settleLoopcontBlock conting = BB"" << ContingMBB->getNumber() << "", cont = BB"" << ContMBB->getNumber() << ""\\n"";); MachineInstr *MI = getLoopendBlockBranchInstr(ContingMBB); if (MI) { assert(isCondBranch(MI)); MachineBasicBlock::iterator I = MI; MachineBasicBlock *TrueBranch = getTrueBranch(MI); int OldOpcode = MI->getOpcode(); DebugLoc DL = MI->getDebugLoc(); bool UseContinueLogical = ((&*ContingMBB->rbegin()) == MI); if (!UseContinueLogical) { int BranchOpcode = TrueBranch == ContMBB ? getBranchNzeroOpcode(OldOpcode) : getBranchZeroOpcode(OldOpcode); insertCondBranchBefore(I, BranchOpcode, DL); // insertEnd to ensure phi-moves, if exist, go before the continue-instr. insertInstrEnd(ContingMBB, AMDGPU::CONTINUE, DL); insertInstrEnd(ContingMBB, AMDGPU::ENDIF, DL); } else { int BranchOpcode = TrueBranch == ContMBB ? getContinueNzeroOpcode(OldOpcode) : getContinueZeroOpcode(OldOpcode); insertCondBranchBefore(I, BranchOpcode, DL); } MI->eraseFromParent(); } else { // if we've arrived here then we've already erased the branch instruction // travel back up the basic block to see the last reference of our debug // location we've just inserted that reference here so it should be // representative insertEnd to ensure phi-moves, if exist, go before the // continue-instr. insertInstrEnd(ContingMBB, AMDGPU::CONTINUE, getLastDebugLocInBB(ContingMBB)); } } int AMDGPUCFGStructurizer::cloneOnSideEntryTo(MachineBasicBlock *PreMBB, MachineBasicBlock *SrcMBB, MachineBasicBlock *DstMBB) { int Cloned = 0; assert(PreMBB->isSuccessor(SrcMBB)); while (SrcMBB && SrcMBB != DstMBB) { assert(SrcMBB->succ_size() == 1); if (SrcMBB->pred_size() > 1) { SrcMBB = cloneBlockForPredecessor(SrcMBB, PreMBB); ++Cloned; } PreMBB = SrcMBB; SrcMBB = *SrcMBB->succ_begin(); } return Cloned; } MachineBasicBlock * AMDGPUCFGStructurizer::cloneBlockForPredecessor(MachineBasicBlock *MBB, MachineBasicBlock *PredMBB) { assert(PredMBB->isSuccessor(MBB) && ""succBlk is not a prececessor of curBlk""); MachineBasicBlock *CloneMBB = clone(MBB); //clone instructions replaceInstrUseOfBlockWith(PredMBB, MBB, CloneMBB); //srcBlk, oldBlk, newBlk PredMBB->replaceSuccessor(MBB, CloneMBB); // add all successor to cloneBlk cloneSuccessorList(CloneMBB, MBB); numClonedInstr += MBB->size(); DEBUG( dbgs() << ""Cloned block: "" << ""BB"" << MBB->getNumber() << ""size "" << MBB->size() << ""\\n""; ); SHOWNEWBLK(CloneMBB, ""result of Cloned block: ""); return CloneMBB; } void AMDGPUCFGStructurizer::migrateInstruction(MachineBasicBlock *SrcMBB, MachineBasicBlock *DstMBB, MachineBasicBlock::iterator I) { MachineBasicBlock::iterator SpliceEnd; //look for the input branchinstr, not the AMDGPU branchinstr MachineInstr *BranchMI = getNormalBlockBranchInstr(SrcMBB); if (!BranchMI) { DEBUG( dbgs() << ""migrateInstruction don't see branch instr\\n"" ; ); SpliceEnd = SrcMBB->end(); } else { DEBUG(dbgs() << ""migrateInstruction see branch instr: "" << *BranchMI); SpliceEnd = BranchMI; } DEBUG( dbgs() << ""migrateInstruction before splice dstSize = "" << DstMBB->size() << ""srcSize = "" << SrcMBB->size() << ""\\n""; ); //splice insert before insertPos DstMBB->splice(I, SrcMBB, SrcMBB->begin(), SpliceEnd); DEBUG( dbgs() << ""migrateInstruction after splice dstSize = "" << DstMBB->size() << ""srcSize = "" << SrcMBB->size() << '\\n'; ); } MachineBasicBlock * AMDGPUCFGStructurizer::normalizeInfiniteLoopExit(MachineLoop* LoopRep) { MachineBasicBlock *LoopHeader = LoopRep->getHeader(); MachineBasicBlock *LoopLatch = LoopRep->getLoopLatch(); if (!LoopHeader || !LoopLatch) return nullptr; MachineInstr *BranchMI = getLoopendBlockBranchInstr(LoopLatch); // Is LoopRep an infinite loop ? if (!BranchMI || !isUncondBranch(BranchMI)) return nullptr; MachineBasicBlock *DummyExitBlk = FuncRep->CreateMachineBasicBlock(); FuncRep->push_back(DummyExitBlk); //insert to function SHOWNEWBLK(DummyExitBlk, ""DummyExitBlock to normalize infiniteLoop: ""); DEBUG(dbgs() << ""Old branch instr: "" << *BranchMI << ""\\n"";); LLVMContext &Ctx = LoopHeader->getParent()->getFunction()->getContext(); Ctx.emitError(""Extra register needed to handle CFG""); return nullptr; } void AMDGPUCFGStructurizer::removeUnconditionalBranch(MachineBasicBlock *MBB) { MachineInstr *BranchMI; // I saw two unconditional branch in one basic block in example // test_fc_do_while_or.c need to fix the upstream on this to remove the loop. while ((BranchMI = getLoopendBlockBranchInstr(MBB)) && isUncondBranch(BranchMI)) { DEBUG(dbgs() << ""Removing uncond branch instr: "" << *BranchMI); BranchMI->eraseFromParent(); } } void AMDGPUCFGStructurizer::removeRedundantConditionalBranch( MachineBasicBlock *MBB) { if (MBB->succ_size() != 2) return; MachineBasicBlock *MBB1 = *MBB->succ_begin(); MachineBasicBlock *MBB2 = *std::next(MBB->succ_begin()); if (MBB1 != MBB2) return; MachineInstr *BranchMI = getNormalBlockBranchInstr(MBB); assert(BranchMI && isCondBranch(BranchMI)); DEBUG(dbgs() << ""Removing unneeded cond branch instr: "" << *BranchMI); BranchMI->eraseFromParent(); SHOWNEWBLK(MBB1, ""Removing redundant successor""); MBB->removeSuccessor(MBB1, true); } void AMDGPUCFGStructurizer::addDummyExitBlock( SmallVectorImpl &RetMBB) { MachineBasicBlock *DummyExitBlk = FuncRep->CreateMachineBasicBlock(); FuncRep->push_back(DummyExitBlk); //insert to function insertInstrEnd(DummyExitBlk, AMDGPU::RETURN); for (SmallVectorImpl::iterator It = RetMBB.begin(), E = RetMBB.end(); It != E; ++It) { MachineBasicBlock *MBB = *It; MachineInstr *MI = getReturnInstr(MBB); if (MI) MI->eraseFromParent(); MBB->addSuccessor(DummyExitBlk); DEBUG( dbgs() << ""Add dummyExitBlock to BB"" << MBB->getNumber() << "" successors\\n""; ); } SHOWNEWBLK(DummyExitBlk, ""DummyExitBlock: ""); } void AMDGPUCFGStructurizer::removeSuccessor(MachineBasicBlock *MBB) { while (MBB->succ_size()) MBB->removeSuccessor(*MBB->succ_begin()); } void AMDGPUCFGStructurizer::recordSccnum(MachineBasicBlock *MBB, int SccNum) { BlockInformation *&srcBlkInfo = BlockInfoMap[MBB]; if (!srcBlkInfo) srcBlkInfo = new BlockInformation(); srcBlkInfo->SccNum = SccNum; } void AMDGPUCFGStructurizer::retireBlock(MachineBasicBlock *MBB) { DEBUG( dbgs() << ""Retiring BB"" << MBB->getNumber() << ""\\n""; ); BlockInformation *&SrcBlkInfo = BlockInfoMap[MBB]; if (!SrcBlkInfo) SrcBlkInfo = new BlockInformation(); SrcBlkInfo->IsRetired = true; assert(MBB->succ_size() == 0 && MBB->pred_size() == 0 && ""can't retire block yet""); } INITIALIZE_PASS_BEGIN(AMDGPUCFGStructurizer, ""amdgpustructurizer"", ""AMDGPU CFG Structurizer"", false, false) INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree) INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTree) INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo) INITIALIZE_PASS_END(AMDGPUCFGStructurizer, ""amdgpustructurizer"", ""AMDGPU CFG Structurizer"", false, false) FunctionPass *llvm::createAMDGPUCFGStructurizerPass() { return new AMDGPUCFGStructurizer(); } ",16282,True,3288.476995970418,median "/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-2015 Facebook, Inc. (http://www.facebook.com) | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include ""hphp/runtime/vm/jit/translator.h"" #include #include #include #include #include #include #include #include #include #include #include #include ""hphp/util/map-walker.h"" #include ""hphp/util/ringbuffer.h"" #include ""hphp/util/timer.h"" #include ""hphp/util/trace.h"" #include ""hphp/runtime/base/arch.h"" #include ""hphp/runtime/base/repo-auth-type-codec.h"" #include ""hphp/runtime/base/runtime-option.h"" #include ""hphp/runtime/base/stats.h"" #include ""hphp/runtime/base/unit-cache.h"" #include ""hphp/runtime/ext/collections/ext_collections-idl.h"" #include ""hphp/runtime/ext/generator/ext_generator.h"" #include ""hphp/runtime/vm/bytecode.h"" #include ""hphp/runtime/vm/hhbc.h"" #include ""hphp/runtime/vm/runtime.h"" #include ""hphp/runtime/vm/treadmill.h"" #include ""hphp/runtime/vm/type-profile.h"" #include ""hphp/runtime/vm/bc-pattern.h"" #include ""hphp/runtime/vm/jit/annotation.h"" #include ""hphp/runtime/vm/jit/guard-relaxation.h"" #include ""hphp/runtime/vm/jit/inlining-decider.h"" #include ""hphp/runtime/vm/jit/ir-unit.h"" #include ""hphp/runtime/vm/jit/irgen-exit.h"" #include ""hphp/runtime/vm/jit/irgen.h"" #include ""hphp/runtime/vm/jit/mc-generator.h"" #include ""hphp/runtime/vm/jit/normalized-instruction.h"" #include ""hphp/runtime/vm/jit/print.h"" #include ""hphp/runtime/vm/jit/prof-data.h"" #include ""hphp/runtime/vm/jit/punt.h"" #include ""hphp/runtime/vm/jit/region-selection.h"" #include ""hphp/runtime/vm/jit/timer.h"" #include ""hphp/runtime/vm/jit/translate-region.h"" #include ""hphp/runtime/vm/jit/translator-inline.h"" #include ""hphp/runtime/vm/jit/type.h"" TRACE_SET_MOD(trans); namespace HPHP { namespace jit { /////////////////////////////////////////////////////////////////////////////// Lease Translator::s_writeLease; /////////////////////////////////////////////////////////////////////////////// /* * NB: this opcode structure is sparse; it cannot just be indexed by * opcode. */ using namespace InstrFlags; static const struct { Op op; InstrInfo info; } instrInfoSparse [] = { // Op Inputs Outputs OutputTypes // -- ------ ------- ----------- /*** 1. Basic instructions ***/ { OpPopA, {Stack1, None, OutNone }}, { OpPopC, {Stack1| DontGuardStack1, None, OutNone }}, { OpPopV, {Stack1| DontGuardStack1| IgnoreInnerType, None, OutNone }}, { OpPopR, {Stack1| DontGuardStack1| IgnoreInnerType, None, OutNone }}, { OpDup, {Stack1, StackTop2, OutSameAsInput }}, { OpBox, {Stack1, Stack1, OutVInput }}, { OpUnbox, {Stack1, Stack1, OutCInput }}, { OpBoxR, {Stack1, Stack1, OutVInput }}, { OpUnboxR, {Stack1, Stack1, OutCInput }}, /*** 2. Literal and constant instructions ***/ { OpNull, {None, Stack1, OutNull }}, { OpNullUninit, {None, Stack1, OutNullUninit }}, { OpTrue, {None, Stack1, OutBooleanImm }}, { OpFalse, {None, Stack1, OutBooleanImm }}, { OpInt, {None, Stack1, OutInt64 }}, { OpDouble, {None, Stack1, OutDouble }}, { OpString, {None, Stack1, OutStringImm }}, { OpArray, {None, Stack1, OutArrayImm }}, { OpNewArray, {None, Stack1, OutArray }}, { OpNewMixedArray, {None, Stack1, OutArray }}, { OpNewLikeArrayL, {Local, Stack1, OutArray }}, { OpNewPackedArray, {StackN, Stack1, OutArray }}, { OpNewStructArray, {StackN, Stack1, OutArray }}, { OpAddElemC, {StackTop3, Stack1, OutArray }}, { OpAddElemV, {StackTop3, Stack1, OutArray }}, { OpAddNewElemC, {StackTop2, Stack1, OutArray }}, { OpAddNewElemV, {StackTop2, Stack1, OutArray }}, { OpNewCol, {None, Stack1, OutObject }}, { OpColFromArray, {Stack1, Stack1, OutObject }}, { OpMapAddElemC, {StackTop3, Stack1, OutObject }}, { OpColAddNewElemC, {StackTop2, Stack1, OutObject }}, { OpCns, {None, Stack1, OutCns }}, { OpCnsE, {None, Stack1, OutCns }}, { OpCnsU, {None, Stack1, OutCns }}, { OpClsCns, {Stack1, Stack1, OutUnknown }}, { OpClsCnsD, {None, Stack1, OutUnknown }}, { OpFile, {None, Stack1, OutString }}, { OpDir, {None, Stack1, OutString }}, { OpNameA, {Stack1, Stack1, OutString }}, /*** 3. Operator instructions ***/ /* Binary string */ { OpConcat, {StackTop2, Stack1, OutString }}, { OpConcatN, {StackN, Stack1, OutString }}, /* Arithmetic ops */ { OpAdd, {StackTop2, Stack1, OutArith }}, { OpSub, {StackTop2, Stack1, OutArith }}, { OpMul, {StackTop2, Stack1, OutArith }}, /* Arithmetic ops that overflow ints to floats */ { OpAddO, {StackTop2, Stack1, OutArithO }}, { OpSubO, {StackTop2, Stack1, OutArithO }}, { OpMulO, {StackTop2, Stack1, OutArithO }}, /* Div and mod might return boolean false. Sigh. */ { OpDiv, {StackTop2, Stack1, OutUnknown }}, { OpMod, {StackTop2, Stack1, OutUnknown }}, { OpPow, {StackTop2, Stack1, OutUnknown }}, /* Logical ops */ { OpXor, {StackTop2, Stack1, OutBoolean }}, { OpNot, {Stack1, Stack1, OutBoolean }}, { OpSame, {StackTop2, Stack1, OutBoolean }}, { OpNSame, {StackTop2, Stack1, OutBoolean }}, { OpEq, {StackTop2, Stack1, OutBoolean }}, { OpNeq, {StackTop2, Stack1, OutBoolean }}, { OpLt, {StackTop2, Stack1, OutBoolean }}, { OpLte, {StackTop2, Stack1, OutBoolean }}, { OpGt, {StackTop2, Stack1, OutBoolean }}, { OpGte, {StackTop2, Stack1, OutBoolean }}, /* Bitwise ops */ { OpBitAnd, {StackTop2, Stack1, OutBitOp }}, { OpBitOr, {StackTop2, Stack1, OutBitOp }}, { OpBitXor, {StackTop2, Stack1, OutBitOp }}, { OpBitNot, {Stack1, Stack1, OutBitOp }}, { OpShl, {StackTop2, Stack1, OutInt64 }}, { OpShr, {StackTop2, Stack1, OutInt64 }}, /* Cast instructions */ { OpCastBool, {Stack1, Stack1, OutBoolean }}, { OpCastInt, {Stack1, Stack1, OutInt64 }}, { OpCastDouble, {Stack1, Stack1, OutDouble }}, { OpCastString, {Stack1, Stack1, OutString }}, { OpCastArray, {Stack1, Stack1, OutArray }}, { OpCastObject, {Stack1, Stack1, OutObject }}, { OpInstanceOf, {StackTop2, Stack1, OutBoolean }}, { OpInstanceOfD, {Stack1, Stack1, OutPredBool }}, { OpPrint, {Stack1, Stack1, OutInt64 }}, { OpClone, {Stack1, Stack1, OutObject }}, { OpExit, {Stack1, Stack1, OutNull }}, { OpFatal, {Stack1, None, OutNone }}, /*** 4. Control flow instructions ***/ { OpJmp, {None, None, OutNone }}, { OpJmpNS, {None, None, OutNone }}, { OpJmpZ, {Stack1, None, OutNone }}, { OpJmpNZ, {Stack1, None, OutNone }}, { OpSwitch, {Stack1, None, OutNone }}, { OpSSwitch, {Stack1, None, OutNone }}, /* * RetC and RetV are special. Their manipulation of the runtime stack are * outside the boundaries of the tracelet abstraction; since they always end * a basic block, they behave more like ""glue"" between BBs than the * instructions in the body of a BB. * * RetC and RetV consume a value from the stack, and this value's type needs * to be known at compile-time. */ { OpRetC, {AllLocals, None, OutNone }}, { OpRetV, {AllLocals, None, OutNone }}, { OpThrow, {Stack1, None, OutNone }}, { OpUnwind, {None, None, OutNone }}, /*** 5. Get instructions ***/ { OpCGetL, {Local, Stack1, OutCInputL }}, { OpCGetL2, {Stack1|DontGuardStack1| Local, StackIns1, OutCInputL }}, { OpCGetL3, {StackTop2|Local, StackIns2, OutCInputL }}, // In OpCUGetL we rely on OutCInputL returning TCell (which covers Uninit // values) instead of TInitCell. { OpCUGetL, {Local, Stack1, OutCInputL }}, { OpPushL, {Local, Stack1|Local, OutCInputL }}, { OpCGetN, {Stack1, Stack1, OutUnknown }}, { OpCGetG, {Stack1, Stack1, OutUnknown }}, { OpCGetS, {StackTop2, Stack1, OutUnknown }}, { OpCGetM, {MVector, Stack1, OutUnknown }}, { OpVGetL, {Local, Stack1|Local, OutVInputL }}, { OpVGetN, {Stack1, Stack1|Local, OutVUnknown }}, // TODO: In pseudo-main, the VGetG instruction invalidates what we know // about the types of the locals because it could cause any one of the // local variables to become ""boxed"". We need to add logic to tracelet // analysis to deal with this properly. { OpVGetG, {Stack1, Stack1, OutVUnknown }}, { OpVGetS, {StackTop2, Stack1, OutVUnknown }}, { OpVGetM, {MVector, Stack1|Local, OutVUnknown }}, { OpAGetC, {Stack1, Stack1, OutClassRef }}, { OpAGetL, {Local, Stack1, OutClassRef }}, /*** 6. Isset, Empty, and type querying instructions ***/ { OpAKExists, {StackTop2, Stack1, OutBoolean }}, { OpIssetL, {Local, Stack1, OutBoolean }}, { OpIssetN, {Stack1, Stack1, OutBoolean }}, { OpIssetG, {Stack1, Stack1, OutBoolean }}, { OpIssetS, {StackTop2, Stack1, OutBoolean }}, { OpIssetM, {MVector, Stack1, OutBoolean }}, { OpEmptyL, {Local, Stack1, OutBoolean }}, { OpEmptyN, {Stack1, Stack1, OutBoolean }}, { OpEmptyG, {Stack1, Stack1, OutBoolean }}, { OpEmptyS, {StackTop2, Stack1, OutBoolean }}, { OpEmptyM, {MVector, Stack1, OutBoolean }}, { OpIsTypeC, {Stack1| DontGuardStack1, Stack1, OutBoolean }}, { OpIsTypeL, {Local, Stack1, OutIsTypeL }}, /*** 7. Mutator instructions ***/ { OpSetL, {Stack1|Local, Stack1|Local, OutSameAsInput }}, { OpSetN, {StackTop2, Stack1|Local, OutSameAsInput }}, { OpSetG, {StackTop2, Stack1, OutSameAsInput }}, { OpSetS, {StackTop3, Stack1, OutSameAsInput }}, { OpSetM, {MVector|Stack1, Stack1|Local, OutUnknown }}, { OpSetWithRefLM,{MVector|Local , Local, OutNone }}, { OpSetWithRefRM,{MVector|Stack1, Local, OutNone }}, { OpSetOpL, {Stack1|Local, Stack1|Local, OutSetOp }}, { OpSetOpN, {StackTop2, Stack1|Local, OutUnknown }}, { OpSetOpG, {StackTop2, Stack1, OutUnknown }}, { OpSetOpS, {StackTop3, Stack1, OutUnknown }}, { OpSetOpM, {MVector|Stack1, Stack1|Local, OutUnknown }}, { OpIncDecL, {Local, Stack1|Local, OutIncDec }}, { OpIncDecN, {Stack1, Stack1|Local, OutUnknown }}, { OpIncDecG, {Stack1, Stack1, OutUnknown }}, { OpIncDecS, {StackTop2, Stack1, OutUnknown }}, { OpIncDecM, {MVector, Stack1|Local, OutUnknown }}, { OpBindL, {Stack1|Local| IgnoreInnerType, Stack1|Local, OutSameAsInput }}, { OpBindN, {StackTop2, Stack1|Local, OutSameAsInput }}, { OpBindG, {StackTop2, Stack1, OutSameAsInput }}, { OpBindS, {StackTop3, Stack1, OutSameAsInput }}, { OpBindM, {MVector|Stack1, Stack1|Local, OutSameAsInput }}, { OpUnsetL, {Local, Local, OutNone }}, { OpUnsetN, {Stack1, Local, OutNone }}, { OpUnsetG, {Stack1, None, OutNone }}, { OpUnsetM, {MVector, Local, OutNone }}, /*** 8. Call instructions ***/ { OpFPushFunc, {Stack1, FStack, OutFDesc }}, { OpFPushFuncD, {None, FStack, OutFDesc }}, { OpFPushFuncU, {None, FStack, OutFDesc }}, { OpFPushObjMethod, {StackTop2, FStack, OutFDesc }}, { OpFPushObjMethodD, {Stack1, FStack, OutFDesc }}, { OpFPushClsMethod, {StackTop2, FStack, OutFDesc }}, { OpFPushClsMethodF, {StackTop2, FStack, OutFDesc }}, { OpFPushClsMethodD, {None, FStack, OutFDesc }}, { OpFPushCtor, {Stack1, Stack1|FStack,OutObject }}, { OpFPushCtorD, {None, Stack1|FStack,OutObject }}, { OpFPushCufIter,{None, FStack, OutFDesc }}, { OpFPushCuf, {Stack1, FStack, OutFDesc }}, { OpFPushCufF, {Stack1, FStack, OutFDesc }}, { OpFPushCufSafe,{StackTop2|DontGuardAny, StackTop2|FStack, OutFPushCufSafe }}, { OpFPassCW, {FuncdRef, None, OutSameAsInput }}, { OpFPassCE, {FuncdRef, None, OutSameAsInput }}, { OpFPassV, {Stack1|FuncdRef, Stack1, OutUnknown }}, { OpFPassR, {Stack1|FuncdRef, Stack1, OutFInputR }}, { OpFPassL, {Local|FuncdRef, Stack1, OutFInputL }}, { OpFPassN, {Stack1|FuncdRef, Stack1, OutUnknown }}, { OpFPassG, {Stack1|FuncdRef, Stack1, OutUnknown }}, { OpFPassS, {StackTop2|FuncdRef, Stack1, OutUnknown }}, { OpFPassM, {MVector|FuncdRef, Stack1|Local, OutUnknown }}, /* * FCall is special. Like the Ret* instructions, its manipulation of the * runtime stack are outside the boundaries of the tracelet abstraction. */ { OpFCall, {FStack, Stack1, OutUnknown }}, { OpFCallD, {FStack, Stack1, OutUnknown }}, { OpFCallUnpack, {FStack, Stack1, OutUnknown }}, { OpFCallArray, {FStack, Stack1, OutUnknown }}, { OpFCallBuiltin,{BStackN|DontGuardAny, Stack1, OutUnknown }}, { OpCufSafeArray,{StackTop3|DontGuardAny, Stack1, OutArray }}, { OpCufSafeReturn,{StackTop3|DontGuardAny, Stack1, OutUnknown }}, { OpDecodeCufIter,{Stack1, None, OutNone }}, /*** 11. Iterator instructions ***/ { OpIterInit, {Stack1, Local, OutUnknown }}, { OpMIterInit, {Stack1, Local, OutUnknown }}, { OpWIterInit, {Stack1, Local, OutUnknown }}, { OpIterInitK, {Stack1, Local, OutUnknown }}, { OpMIterInitK, {Stack1, Local, OutUnknown }}, { OpWIterInitK, {Stack1, Local, OutUnknown }}, { OpIterNext, {None, Local, OutUnknown }}, { OpMIterNext, {None, Local, OutUnknown }}, { OpWIterNext, {None, Local, OutUnknown }}, { OpIterNextK, {None, Local, OutUnknown }}, { OpMIterNextK, {None, Local, OutUnknown }}, { OpWIterNextK, {None, Local, OutUnknown }}, { OpIterFree, {None, None, OutNone }}, { OpMIterFree, {None, None, OutNone }}, { OpCIterFree, {None, None, OutNone }}, { OpIterBreak, {None, None, OutNone }}, /*** 12. Include, eval, and define instructions ***/ { OpIncl, {Stack1, Stack1, OutUnknown }}, { OpInclOnce, {Stack1, Stack1, OutUnknown }}, { OpReq, {Stack1, Stack1, OutUnknown }}, { OpReqOnce, {Stack1, Stack1, OutUnknown }}, { OpReqDoc, {Stack1, Stack1, OutUnknown }}, { OpEval, {Stack1, Stack1, OutUnknown }}, { OpDefFunc, {None, None, OutNone }}, { OpDefTypeAlias,{None, None, OutNone }}, { OpDefCls, {None, None, OutNone }}, { OpDefCns, {Stack1, Stack1, OutBoolean }}, /*** 13. Miscellaneous instructions ***/ { OpThis, {None, Stack1, OutThisObject }}, { OpBareThis, {None, Stack1, OutUnknown }}, { OpCheckThis, {This, None, OutNone }}, { OpInitThisLoc, {None, Local, OutUnknown }}, { OpStaticLoc, {None, Stack1, OutBoolean }}, { OpStaticLocInit, {Stack1, Local, OutVUnknown }}, { OpCatch, {None, Stack1, OutObject }}, { OpVerifyParamType, {Local, Local, OutUnknown }}, { OpVerifyRetTypeV, {Stack1, Stack1, OutSameAsInput }}, { OpVerifyRetTypeC, {Stack1, Stack1, OutSameAsInput }}, { OpOODeclExists, {StackTop2, Stack1, OutBoolean }}, { OpSelf, {None, Stack1, OutClassRef }}, { OpParent, {None, Stack1, OutClassRef }}, { OpLateBoundCls,{None, Stack1, OutClassRef }}, { OpNativeImpl, {None, None, OutNone }}, { OpCreateCl, {BStackN, Stack1, OutObject }}, { OpIncStat, {None, None, OutNone }}, { OpIdx, {StackTop3, Stack1, OutUnknown }}, { OpArrayIdx, {StackTop3, Stack1, OutUnknown }}, { OpCheckProp, {None, Stack1, OutBoolean }}, { OpInitProp, {Stack1, None, OutNone }}, { OpSilence, {Local|DontGuardAny, Local, OutNone }}, { OpAssertRATL, {None, None, OutNone }}, { OpAssertRATStk,{None, None, OutNone }}, { OpBreakTraceHint,{None, None, OutNone }}, { OpGetMemoKey, {Stack1, Stack1, OutUnknown }}, /*** 14. Generator instructions ***/ { OpCreateCont, {None, Stack1, OutNull }}, { OpContEnter, {Stack1, Stack1, OutUnknown }}, { OpContRaise, {Stack1, Stack1, OutUnknown }}, { OpYield, {Stack1, Stack1, OutUnknown }}, { OpYieldK, {StackTop2, Stack1, OutUnknown }}, { OpContCheck, {None, None, OutNone }}, { OpContValid, {None, Stack1, OutBoolean }}, { OpContKey, {None, Stack1, OutUnknown }}, { OpContCurrent, {None, Stack1, OutUnknown }}, /*** 15. Async functions instructions ***/ { OpWHResult, {Stack1, Stack1, OutUnknown }}, { OpAwait, {Stack1, Stack1, OutUnknown }}, }; static hphp_hash_map instrInfo; static bool instrInfoInited; static void initInstrInfo() { if (!instrInfoInited) { for (size_t i = 0; i < sizeof(instrInfoSparse) / sizeof(instrInfoSparse[0]); i++) { instrInfo[instrInfoSparse[i].op] = instrInfoSparse[i].info; } if (!RuntimeOption::EvalCheckReturnTypeHints) { for (size_t j = 0; j < 2; ++j) { auto& ii = instrInfo[j == 0 ? OpVerifyRetTypeC : OpVerifyRetTypeV]; ii.in = ii.out = None; ii.type = OutNone; } } instrInfoInited = true; } } const InstrInfo& getInstrInfo(Op op) { assertx(instrInfoInited); return instrInfo[op]; } namespace { int64_t countOperands(uint64_t mask) { const uint64_t ignore = FuncdRef | Local | Iter | AllLocals | DontGuardStack1 | IgnoreInnerType | DontGuardAny | This; mask &= ~ignore; static const uint64_t counts[][2] = { {Stack3, 1}, {Stack2, 1}, {Stack1, 1}, {StackIns1, 2}, {StackIns2, 3}, {FStack, kNumActRecCells}, }; int64_t count = 0; for (auto const& pair : counts) { if (mask & pair[0]) { count += pair[1]; mask &= ~pair[0]; } } assertx(mask == 0); return count; } } int64_t getStackPopped(PC pc) { auto const op = *reinterpret_cast(pc); switch (op) { case Op::FCall: return getImm((Op*)pc, 0).u_IVA + kNumActRecCells; case Op::FCallD: return getImm((Op*)pc, 0).u_IVA + kNumActRecCells; case Op::FCallArray: return kNumActRecCells + 1; case Op::NewPackedArray: case Op::ConcatN: case Op::FCallBuiltin: case Op::CreateCl: return getImm((Op*)pc, 0).u_IVA; case Op::NewStructArray: return getImmVector((Op*)pc).size(); default: break; } uint64_t mask = getInstrInfo(op).in; int64_t count = 0; // All instructions with these properties are handled above assertx((mask & (StackN | BStackN)) == 0); if (mask & MVector) { count += getImmVector((Op*)pc).numStackValues(); mask &= ~MVector; } return count + countOperands(mask); } int64_t getStackPushed(PC pc) { return countOperands(getInstrInfo(*reinterpret_cast(pc)).out); } bool isAlwaysNop(Op op) { switch (op) { case Op::BoxRNop: case Op::DefClsNop: case Op::FPassC: case Op::FPassVNop: case Op::Nop: case Op::UnboxRNop: case Op::RGetCNop: return true; case Op::VerifyRetTypeC: case Op::VerifyRetTypeV: return !RuntimeOption::EvalCheckReturnTypeHints; default: return false; } } static void addMVectorInputs(NormalizedInstruction& ni, int& currentStackOffset, std::vector& inputs) { assertx(ni.immVec.isValid()); ni.immVecM.reserve(ni.immVec.size()); int UNUSED stackCount = 0; int UNUSED localCount = 0; currentStackOffset -= ni.immVec.numStackValues(); int localStackOffset = currentStackOffset; auto push_stack = [&] { ++stackCount; inputs.emplace_back(Location(BCSPOffset{localStackOffset++})); }; auto push_local = [&] (int imm) { ++localCount; inputs.emplace_back(Location(Location::Local, imm)); }; /* * Note that we have to push as we go so that the arguments come in * the order expected for the M-vector. */ /* * Also note: if we eventually have immediates that are not local * ids (i.e. string ids), this analysis step is going to have to be * a bit wiser. */ auto opPtr = (const Op*)ni.source.pc(); auto const location = getMLocation(opPtr); auto const lcode = location.lcode; const bool trailingClassRef = lcode == LSL || lcode == LSC; switch (numLocationCodeStackVals(lcode)) { case 0: { if (lcode == LH) { inputs.emplace_back(Location(Location::This)); } else { assertx(lcode == LL || lcode == LGL || lcode == LNL); if (location.hasImm()) { push_local(location.imm); } } } break; case 1: if (lcode == LSL) { // We'll get the trailing stack value after pushing all the // member vector elements. assertx(location.hasImm()); push_local(location.imm); } else { push_stack(); } break; case 2: push_stack(); if (!trailingClassRef) { // This one is actually at the back. push_stack(); } break; default: not_reached(); } // Now push all the members in the correct order. for (auto const& member : getMVector(opPtr)) { auto const mcode = member.mcode; ni.immVecM.push_back(mcode); if (mcode == MW) { // No stack and no locals. continue; } else if (member.hasImm()) { int64_t imm = member.imm; if (memberCodeImmIsLoc(mcode)) { push_local(imm); } else if (memberCodeImmIsString(mcode)) { inputs.emplace_back(Location(Location::Litstr, imm)); } else { assertx(memberCodeImmIsInt(mcode)); inputs.emplace_back(Location(Location::Litint, imm)); } } else { push_stack(); } inputs.back().dontGuardInner = true; } if (trailingClassRef) { push_stack(); } assertx(stackCount == ni.immVec.numStackValues()); SKTRACE(2, ni.source, ""M-vector using %d hidden stack "" ""inputs, %d locals\\n"", stackCount, localCount); } /* * getInputsImpl -- * Returns locations for this instruction's inputs. * * Throws: * TranslationFailedExc: * Unimplemented functionality, probably an opcode. * * UnknownInputExc: * Consumed a datum whose type or value could not be constrained at * translation time, because the tracelet has already modified it. * Truncate the tracelet at the preceding instruction, which must * exists because *something* modified something in it. */ static void getInputsImpl(NormalizedInstruction* ni, int& currentStackOffset, InputInfoVec& inputs) { #ifdef USE_TRACE auto sk = ni->source; #endif if (isAlwaysNop(ni->op())) return; assertx(inputs.empty()); always_assert_flog( instrInfo.count(ni->op()), ""Invalid opcode in getInputsImpl: {}\\n"", opcodeToName(ni->op()) ); const InstrInfo& info = instrInfo[ni->op()]; Operands input = info.in; if (input & FuncdRef) { inputs.needsRefCheck = true; } if (input & Iter) { inputs.emplace_back(Location(Location::Iter, ni->imm[0].u_IVA)); } if (input & FStack) { currentStackOffset -= ni->imm[0].u_IVA; // arguments consumed currentStackOffset -= kNumActRecCells; // ActRec is torn down as well } if (input & IgnoreInnerType) ni->ignoreInnerType = true; if (input & Stack1) { SKTRACE(1, sk, ""getInputs: stack1 %d\\n"", currentStackOffset - 1); inputs.emplace_back(Location(BCSPOffset{--currentStackOffset})); if (input & DontGuardStack1) inputs.back().dontGuard = true; if (input & Stack2) { SKTRACE(1, sk, ""getInputs: stack2 %d\\n"", currentStackOffset - 1); inputs.emplace_back(Location(BCSPOffset{--currentStackOffset})); if (input & Stack3) { SKTRACE(1, sk, ""getInputs: stack3 %d\\n"", currentStackOffset - 1); inputs.emplace_back(Location(BCSPOffset{--currentStackOffset})); } } } if (input & StackN) { int numArgs = (ni->op() == Op::NewPackedArray || ni->op() == Op::ConcatN) ? ni->imm[0].u_IVA : ni->immVec.numStackValues(); SKTRACE(1, sk, ""getInputs: stackN %d %d\\n"", currentStackOffset - 1, numArgs); for (int i = 0; i < numArgs; i++) { inputs.emplace_back(Location(BCSPOffset{--currentStackOffset})); inputs.back().dontGuard = true; inputs.back().dontBreak = true; } } if (input & BStackN) { int numArgs = ni->imm[0].u_IVA; SKTRACE(1, sk, ""getInputs: BStackN %d %d\\n"", currentStackOffset - 1, numArgs); for (int i = 0; i < numArgs; i++) { inputs.emplace_back(Location(BCSPOffset{--currentStackOffset})); } } if (input & MVector) { addMVectorInputs(*ni, currentStackOffset, inputs); } if (input & Local) { // (Almost) all instructions that take a Local have its index at // their first immediate. int loc; auto insertAt = inputs.end(); switch (ni->op()) { case OpSetWithRefLM: insertAt = inputs.begin(); // fallthrough case OpFPassL: loc = ni->imm[1].u_IVA; break; default: loc = ni->imm[0].u_IVA; break; } SKTRACE(1, sk, ""getInputs: local %d\\n"", loc); inputs.emplace(insertAt, Location(Location::Local, loc)); } if (input & AllLocals) { ni->ignoreInnerType = true; } SKTRACE(1, sk, ""stack args: virtual sfo now %d\\n"", currentStackOffset); TRACE(1, ""%s\\n"", Trace::prettyNode(""Inputs"", inputs).c_str()); if (inputs.size() && ((input & DontGuardAny) || dontGuardAnyInputs(ni->op()))) { for (int i = inputs.size(); i--; ) { inputs[i].dontGuard = true; } } if (input & This) { inputs.emplace_back(Location(Location::This)); } } InputInfoVec getInputs(NormalizedInstruction& inst) { InputInfoVec infos; // MCGenerator expected top of stack to be index -1, with indexes growing // down from there. hhir defines top of stack to be index 0, with indexes // growing up from there. To compensate we start with a stack offset of 1 and // negate the index of any stack input after the call to getInputs. int stackOff = 1; getInputsImpl(&inst, stackOff, infos); for (auto& info : infos) { if (!info.loc.isStack()) continue; info.loc.bcRelOffset = -info.loc.bcRelOffset; } return infos; } bool dontGuardAnyInputs(Op op) { switch (op) { case Op::IterBreak: case Op::DecodeCufIter: case Op::IterNext: case Op::IterNextK: case Op::WIterInit: case Op::WIterInitK: case Op::WIterNext: case Op::WIterNextK: case Op::MIterInit: case Op::MIterInitK: case Op::MIterNext: case Op::MIterNextK: case Op::IterInitK: case Op::IterInit: case Op::JmpZ: case Op::JmpNZ: case Op::Jmp: case Op::JmpNS: case Op::BindM: case Op::CGetM: case Op::EmptyM: case Op::FPassM: case Op::IncDecM: case Op::IssetM: case Op::SetM: case Op::SetOpM: case Op::SetWithRefLM: case Op::SetWithRefRM: case Op::UnsetM: case Op::VGetM: case Op::FCallArray: case Op::FCall: case Op::FCallD: case Op::ClsCnsD: case Op::FPassCW: case Op::FPassCE: case Op::FPassR: case Op::FPassV: case Op::FPassG: case Op::FPassL: case Op::FPassS: case Op::FCallBuiltin: case Op::NewStructArray: case Op::Switch: case Op::SSwitch: case Op::Lt: case Op::Lte: case Op::Gt: case Op::Gte: case Op::SetOpL: case Op::InitProp: case Op::BreakTraceHint: case Op::IsTypeL: case Op::IsTypeC: case Op::IncDecL: case Op::DefCls: case Op::FPushCuf: case Op::FPushCufF: case Op::FPushCufSafe: case Op::IncStat: case Op::Eq: case Op::Neq: case Op::AssertRATL: case Op::AssertRATStk: case Op::SetL: case Op::BindL: case Op::EmptyL: case Op::CastBool: case Op::Same: case Op::NSame: case Op::Yield: case Op::YieldK: case Op::ContEnter: case Op::ContRaise: case Op::CreateCont: case Op::Await: case Op::BitAnd: case Op::BitOr: case Op::BitXor: case Op::Sub: case Op::Mul: case Op::SubO: case Op::MulO: case Op::Add: case Op::AddO: case Op::AGetC: case Op::AGetL: case Op::AKExists: case Op::AddElemC: case Op::AddNewElemC: case Op::Array: case Op::ArrayIdx: case Op::BareThis: case Op::BindG: case Op::BindS: case Op::BitNot: case Op::CGetG: case Op::CGetL: case Op::CGetL2: case Op::CGetS: case Op::CUGetL: case Op::CIterFree: case Op::CastArray: case Op::CastDouble: case Op::CastInt: case Op::CastObject: case Op::CastString: case Op::CheckProp: case Op::CheckThis: case Op::Clone: case Op::Cns: case Op::CnsE: case Op::CnsU: case Op::MapAddElemC: case Op::ColAddNewElemC: case Op::ColFromArray: case Op::ConcatN: case Op::Concat: case Op::ContCheck: case Op::ContCurrent: case Op::ContKey: case Op::ContValid: case Op::CreateCl: case Op::DefCns: case Op::DefFunc: case Op::Dir: case Op::Div: case Op::Double: case Op::Dup: case Op::EmptyG: case Op::EmptyS: case Op::FPushClsMethodD: case Op::FPushClsMethod: case Op::FPushClsMethodF: case Op::FPushCtor: case Op::FPushCtorD: case Op::FPushCufIter: case Op::FPushFunc: case Op::FPushFuncD: case Op::FPushFuncU: case Op::FPushObjMethodD: case Op::False: case Op::File: case Op::GetMemoKey: case Op::Idx: case Op::InitThisLoc: case Op::InstanceOf: case Op::InstanceOfD: case Op::Int: case Op::IssetG: case Op::IssetL: case Op::IssetS: case Op::IterFree: case Op::LateBoundCls: case Op::MIterFree: case Op::Mod: case Op::Pow: case Op::NameA: case Op::NativeImpl: case Op::NewArray: case Op::NewCol: case Op::NewLikeArrayL: case Op::NewMixedArray: case Op::NewPackedArray: case Op::Not: case Op::Null: case Op::NullUninit: case Op::OODeclExists: case Op::Parent: case Op::PopA: case Op::PopC: case Op::PopR: case Op::PopV: case Op::Print: case Op::PushL: case Op::RetC: case Op::RetV: case Op::Self: case Op::SetG: case Op::SetS: case Op::Shl: case Op::Shr: case Op::Silence: case Op::StaticLoc: case Op::StaticLocInit: case Op::String: case Op::This: case Op::True: case Op::Unbox: case Op::UnboxR: case Op::UnsetL: case Op::VGetG: case Op::VGetL: case Op::VGetS: case Op::VerifyParamType: case Op::VerifyRetTypeC: case Op::VerifyRetTypeV: case Op::WHResult: case Op::Xor: return false; // These are instructions that are always interp-one'd, or are always no-ops. case Op::LowInvalid: case Op::Nop: case Op::Box: case Op::BoxR: case Op::BoxRNop: case Op::UnboxRNop: case Op::RGetCNop: case Op::AddElemV: case Op::AddNewElemV: case Op::ClsCns: case Op::Exit: case Op::Fatal: case Op::Unwind: case Op::Throw: case Op::CGetL3: case Op::CGetN: case Op::VGetN: case Op::IssetN: case Op::EmptyN: case Op::SetN: case Op::SetOpN: case Op::SetOpG: case Op::SetOpS: case Op::IncDecN: case Op::IncDecG: case Op::IncDecS: case Op::BindN: case Op::UnsetN: case Op::UnsetG: case Op::FPushObjMethod: case Op::FPassC: case Op::FPassVNop: case Op::FPassN: case Op::FCallUnpack: case Op::CufSafeArray: case Op::CufSafeReturn: case Op::Incl: case Op::InclOnce: case Op::Req: case Op::ReqOnce: case Op::ReqDoc: case Op::Eval: case Op::DefClsNop: case Op::DefTypeAlias: case Op::Catch: case Op::HighInvalid: return true; } always_assert_flog(0, ""invalid opcode {}\\n"", static_cast(op)); } const StaticString s_http_response_header(""http_response_header""); const StaticString s_php_errormsg(""php_errormsg""); const StaticString s_extract(""extract""); const StaticString s_extractNative(""__SystemLib\\\\extract""); const StaticString s_parse_str(""parse_str""); const StaticString s_parse_strNative(""__SystemLib\\\\parse_str""); const StaticString s_assert(""assert""); const StaticString s_assertNative(""__SystemLib\\\\assert""); const StaticString s_set_frame_metadata(""HH\\\\set_frame_metadata""); bool funcByNameDestroysLocals(const StringData* fname) { if (!fname) return false; return fname->isame(s_extract.get()) || fname->isame(s_extractNative.get()) || fname->isame(s_parse_str.get()) || fname->isame(s_parse_strNative.get()) || fname->isame(s_assert.get()) || fname->isame(s_assertNative.get()) || fname->isame(s_set_frame_metadata.get()); } bool builtinFuncDestroysLocals(const Func* callee) { assertx(callee && callee->isCPPBuiltin()); auto const fname = callee->name(); return funcByNameDestroysLocals(fname); } bool callDestroysLocals(const NormalizedInstruction& inst, const Func* caller) { // We don't handle these two cases, because we don't compile functions // containing them: assertx(caller->lookupVarId(s_php_errormsg.get()) == -1); assertx(caller->lookupVarId(s_http_response_header.get()) == -1); auto* unit = caller->unit(); auto checkTaintId = [&](Id id) { auto const str = unit->lookupLitstrId(id); return funcByNameDestroysLocals(str); }; if (inst.op() == OpFCallBuiltin) return checkTaintId(inst.imm[2].u_SA); if (!isFCallStar(inst.op())) return false; const FPIEnt *fpi = caller->findFPI(inst.source.offset()); assertx(fpi); Op* fpushPc = (Op*)unit->at(fpi->m_fpushOff); auto const op = *fpushPc; if (op == OpFPushFunc) { // If the call has any arguments, the FPushFunc will be in a different // tracelet -- the tracelet will break on every FPass* because the reffiness // of the callee isn't knowable. So we have to say the call destroys locals, // to be conservative. If there aren't any arguments, then it can't destroy // locals -- even if the call is to extract(), there's no argument, so it // won't do anything. auto const numArgs = inst.imm[0].u_IVA; return (numArgs != 0); } if (op == OpFPushFuncD) return checkTaintId(getImm(fpushPc, 1).u_SA); if (op == OpFPushFuncU) { return checkTaintId(getImm(fpushPc, 1).u_SA) || checkTaintId(getImm(fpushPc, 2).u_SA); } return false; } bool instrBreaksProfileBB(const NormalizedInstruction* inst) { if (instrIsNonCallControlFlow(inst->op()) || inst->op() == OpAwait || // may branch to scheduler and suspend execution inst->op() == OpClsCnsD) { // side exits if misses in the RDS return true; } // In profiling mode, don't trace through a control flow merge point, // however, allow inlining of default parameter funclets if (mcg->tx().profData()->anyBlockEndsAt(inst->func(), inst->offset()) && !inst->func()->isEntry(inst->nextSk().offset())) { return true; } return false; } Translator::Translator() : uniqueStubs{} , m_createdTime(HPHP::Timer::GetCurrentTimeMicros()) , m_mode(TransKind::Invalid) , m_profData(nullptr) , m_useAHot(RuntimeOption::RepoAuthoritative && RuntimeOption::EvalJitAHotSize > 0) { initInstrInfo(); if (RuntimeOption::EvalJitPGO) { m_profData.reset(new ProfData()); } } bool Translator::isSrcKeyInBL(SrcKey sk) { auto unit = sk.unit(); if (unit->isInterpretOnly()) return true; Lock l(m_dbgBlacklistLock); if (m_dbgBLSrcKey.find(sk) != m_dbgBLSrcKey.end()) { return true; } // Loop until the end of the basic block inclusively. This is useful for // function exit breakpoints, which are implemented by blacklisting the RetC // opcodes. PC pc = nullptr; do { pc = (pc == nullptr) ? unit->at(sk.offset()) : pc + instrLen((Op*) pc); if (m_dbgBLPC.checkPC(pc)) { m_dbgBLSrcKey.insert(sk); return true; } } while (!opcodeBreaksBB(*reinterpret_cast(pc))); return false; } void Translator::clearDbgBL() { Lock l(m_dbgBlacklistLock); m_dbgBLSrcKey.clear(); m_dbgBLPC.clear(); } bool Translator::addDbgBLPC(PC pc) { Lock l(m_dbgBlacklistLock); if (m_dbgBLPC.checkPC(pc)) { // already there return false; } m_dbgBLPC.addPC(pc); return true; } const char* show(TranslateResult r) { switch (r) { case TranslateResult::Failure: return ""Failure""; case TranslateResult::Retry: return ""Retry""; case TranslateResult::Success: return ""Success""; } not_reached(); } ////////////////////////////////////////////////////////////////////// #define IMM_MA(n) 0 /* ignored, but we need something (for commas) */ #define IMM_BLA(n) ni.immVec #define IMM_SLA(n) ni.immVec #define IMM_ILA(n) ni.immVec #define IMM_VSA(n) ni.immVec #define IMM_IVA(n) ni.imm[n].u_IVA #define IMM_I64A(n) ni.imm[n].u_I64A #define IMM_LA(n) ni.imm[n].u_LA #define IMM_IA(n) ni.imm[n].u_IA #define IMM_DA(n) ni.imm[n].u_DA #define IMM_SA(n) ni.unit()->lookupLitstrId(ni.imm[n].u_SA) #define IMM_RATA(n) ni.imm[n].u_RATA #define IMM_AA(n) ni.unit()->lookupArrayId(ni.imm[n].u_AA) #define IMM_BA(n) ni.imm[n].u_BA #define IMM_OA_IMPL(n) ni.imm[n].u_OA #define IMM_OA(subop) (subop)IMM_OA_IMPL #define ONE(x0) , IMM_##x0(0) #define TWO(x0,x1) , IMM_##x0(0), IMM_##x1(1) #define THREE(x0,x1,x2) , IMM_##x0(0), IMM_##x1(1), IMM_##x2(2) #define FOUR(x0,x1,x2,x3) , IMM_##x0(0), IMM_##x1(1), IMM_##x2(2), IMM_##x3(3) #define NA /* */ static void translateDispatch(IRGS& irgs, const NormalizedInstruction& ni) { #define O(nm, imms, ...) case Op::nm: irgen::emit##nm(irgs imms); return; switch (ni.op()) { OPCODES } #undef O } #undef FOUR #undef THREE #undef TWO #undef ONE #undef NA #undef IMM_MA #undef IMM_BLA #undef IMM_SLA #undef IMM_ILA #undef IMM_IVA #undef IMM_I64A #undef IMM_LA #undef IMM_IA #undef IMM_DA #undef IMM_SA #undef IMM_RATA #undef IMM_AA #undef IMM_BA #undef IMM_OA_IMPL #undef IMM_OA #undef IMM_VSA ////////////////////////////////////////////////////////////////////// namespace { Type flavorToType(FlavorDesc f) { switch (f) { case NOV: not_reached(); case CV: return TCell; // TODO(#3029148) this could be InitCell case CUV: return TCell; case UV: return TUninit; case VV: return TBoxedInitCell; case AV: return TCls; case RV: case FV: case CVV: case CVUV: return TGen; } not_reached(); } TypeConstraint constraintForInput( IRGS& irgs, const NormalizedInstruction& ni, int32_t opndIdx, Type predictedType ) { auto opc = ni.op(); switch (opc) { case OpSetS: case OpSetG: case OpSetL: { // stack value if (opndIdx == 0) { return DataTypeCountness; } if (opc == OpSetL) { // old local value is dec-refed assert(opndIdx == 1); return DataTypeCountness; } return DataTypeSpecific; } case OpUnsetL: { return DataTypeCountness; } case OpCGetL: case OpVGetL: case OpFPassL: { return DataTypeCountnessInit; } case OpCGetL2: { // Stack input isn't touched, Local input is CountnessInit. return opndIdx == 0 ? DataTypeGeneric : DataTypeCountnessInit; } case OpCUGetL: { return DataTypeCountness; } case OpPushL: case OpContEnter: case OpContRaise: { return DataTypeGeneric; } case OpRetC: case OpRetV: { return DataTypeCountness; } case OpFCallArray: { return DataTypeGeneric; } case OpPopC: case OpPopV: case OpPopR: { return DataTypeCountness; } case OpYield: case OpYieldK: { // The stack input is teleported to the continuation's m_value field return DataTypeGeneric; } case OpAddElemC: { // The stack input is teleported to the array return opndIdx == 0 ? DataTypeGeneric : DataTypeSpecific; } case OpIdx: { // Default value is Generic, key is Specific, and base is more // complicated. if (opndIdx == 0) return DataTypeGeneric; if (opndIdx == 1) return DataTypeSpecific; auto baseType = irgen::predictedTypeFromLocation(irgs, ni.inputs[2]); auto keyType = irgen::predictedTypeFromLocation(irgs, ni.inputs[1]); return irgen::idxBaseConstraint(baseType, keyType); } case OpArrayIdx: { // The default value (w/ opndIdx 0) is simply passed to a helper, // which takes care of dec-refing it if needed return opndIdx == 0 ? DataTypeGeneric : DataTypeSpecific; } case OpNewPackedArray: { return DataTypeGeneric; } case OpIterInit: case OpIterInitK: case OpMIterInit: case OpMIterInitK: case OpWIterInit: case OpWIterInitK: { // We care about the type of the stack input but not the locals. return opndIdx == 0 ? DataTypeSpecific : DataTypeGeneric; } case OpIterNext: case OpIterNextK: case OpMIterNext: case OpMIterNextK: case OpWIterNext: case OpWIterNextK: { // Don't care about local input types; all we do is pass their address to // helpers. return DataTypeGeneric; } default: { break; } } if (hasMVector(opc) && opndIdx == getMInstrInfo(ni.mInstrOp()).valCount()) { return irgen::mInstrBaseConstraint(irgs, predictedType); } return DataTypeSpecific; } void emitInputChecks( IRGS& irgs, const NormalizedInstruction& ni, bool checkOuterTypeOnly ) { FTRACE(4, ""\\n{}: {}\\n"", ni.offset(), opcodeToName(ni.op())); if (isAlwaysNop(ni.op())) return; for (auto i = 0; i < ni.inputs.size(); ++i) { FTRACE(4, ""Input {}: "", i); auto loc = ni.inputs[i]; if (!loc.isLocal() && !loc.isStack()) { FTRACE(4, ""!isLocal && !isStack, skipping\\n""); continue; } auto const predictedType = irgen::predictedTypeFromLocation(irgs, loc); FTRACE(4, ""predicted {}\\n"", predictedType); if (!(predictedType <= TGen) && !(predictedType <= TCls)) { FTRACE(4, ""predictedType ({}) !<= TGen|TCls, skipping\\n"", predictedType); continue; } assertx(predictedType != TBottom); auto typeToCheck = predictedType <= TCls ? predictedType : relaxType(predictedType, constraintForInput(irgs, ni, i, predictedType)); // Make sure typeToCheck is checkable. if (!(typeToCheck <= TCell || typeToCheck <= TBoxedInitCell)) { FTRACE(4, ""typeToCheck isn't checkable, skipping\\n""); continue; } if (typeToCheck == TCountedStr) { FTRACE(4, ""typeToCheck is CountedStr, widening to Str\\n""); typeToCheck = TStr; } else if (typeToCheck <= TStaticArr) { FTRACE(4, ""typeToCheck is StaticArr, widening to Arr\\n""); typeToCheck = TArr; } else if (typeToCheck.clsSpec() && !(typeToCheck.clsSpec().cls()->attrs() & AttrNoOverride)) { FTRACE(4, ""class specialization could be overridden, widening to Obj\\n""); typeToCheck = TObj; } else if (typeToCheck.arrSpec() && typeToCheck.arrSpec().type()) { FTRACE(4, ""array specialization is RAT, widening to Arr\\n""); typeToCheck = TArr; } if (loc.isLocal()) { FTRACE(4, ""Checking local {} for type {}\\n"", loc.offset, typeToCheck); irgen::checkTypeLocal(irgs, loc.offset, typeToCheck, ni.source.offset(), checkOuterTypeOnly); } else { FTRACE(4, ""Checking stack offset {} for type {}\\n"", loc.bcRelOffset.offset, typeToCheck); irgen::checkTypeStack(irgs, loc.bcRelOffset, typeToCheck, ni.source.offset(), checkOuterTypeOnly); } } // Calling checkTypeStack with a Type t such that t <= BoxedCell causes us to // spill the stack, so we need to sync the stack with an exception stack // boundary here. irgs.irb->exceptionStackBoundary(); } } void translateInstr( IRGS& irgs, const NormalizedInstruction& ni, bool checkOuterTypeOnly, bool firstInst ) { irgen::prepareForNextHHBC( irgs, &ni, ni.source, ni.endsRegion && !irgen::isInlining(irgs) ); const Func* builtinFunc = nullptr; if (ni.op() == OpFCallBuiltin) { auto str = ni.m_unit->lookupLitstrId(ni.imm[2].u_SA); builtinFunc = Unit::lookupFunc(str); } auto pc = reinterpret_cast(ni.pc()); for (auto i = 0, num = instrNumPops(pc); i < num; ++i) { auto const type = !builtinFunc ? flavorToType(instrInputFlavor(pc, i)) : builtinFunc->byRef(num - i - 1) ? TGen : TCell; // TODO(#5706706): want to use assertTypeLocation, but Location::Stack // is a little unsure of itself. irgen::assertTypeStack(irgs, BCSPOffset{i}, type); } if (RuntimeOption::EvalHHIRConstrictGuards) { emitInputChecks(irgs, ni, checkOuterTypeOnly); if (firstInst) irgen::gen(irgs, EndGuards); } FTRACE(1, ""\\nTranslating {}: {} with state:\\n{}\\n"", ni.offset(), ni, show(irgs)); irgen::ringbufferEntry(irgs, Trace::RBTypeBytecodeStart, ni.source, 2); irgen::emitIncStat(irgs, Stats::Instr_TC, 1); if (Trace::moduleEnabledRelease(Trace::llvm_count, 1) || RuntimeOption::EvalJitLLVMCounters) { irgen::gen(irgs, CountBytecode); } if (isAlwaysNop(ni.op())) return; if (ni.interp || RuntimeOption::EvalJitAlwaysInterpOne) { irgen::interpOne(irgs, ni); return; } translateDispatch(irgs, ni); FTRACE(3, ""\\nTranslated {}: {} with state:\\n{}\\n"", ni.offset(), ni, show(irgs)); } ////////////////////////////////////////////////////////////////////// uint64_t* Translator::getTransCounterAddr() { if (!isTransDBEnabled()) return nullptr; TransID id = m_translations.size(); // allocate a new chunk of counters if necessary if (id >= m_transCounters.size() * transCountersPerChunk) { uint32_t size = sizeof(uint64_t) * transCountersPerChunk; auto *chunk = (uint64_t*)malloc(size); bzero(chunk, size); m_transCounters.push_back(chunk); } assertx(id / transCountersPerChunk < m_transCounters.size()); return &(m_transCounters[id / transCountersPerChunk] [id % transCountersPerChunk]); } void Translator::addTranslation(const TransRec& transRec) { if (Trace::moduleEnabledRelease(Trace::trans, 1)) { // Log the translation's size, creation time, SrcKey, and size Trace::traceRelease(""New translation: %"" PRId64 "" %s %u %u %d\\n"", HPHP::Timer::GetCurrentTimeMicros() - m_createdTime, folly::format(""{}:{}:{}"", transRec.src.unit()->filepath(), transRec.src.funcID(), transRec.src.offset()).str().c_str(), transRec.aLen, transRec.acoldLen, static_cast(transRec.kind)); } if (!isTransDBEnabled()) return; uint32_t id = getCurrentTransID(); m_translations.emplace_back(transRec); auto& newTransRec = m_translations[id]; newTransRec.id = id; if (transRec.aLen > 0) { m_transDB[transRec.aStart] = id; } if (transRec.acoldLen > 0) { m_transDB[transRec.acoldStart] = id; } // Optimize storage of the created TransRec. newTransRec.optimizeForMemory(); } uint64_t Translator::getTransCounter(TransID transId) const { if (!isTransDBEnabled()) return -1ul; assertx(transId < m_translations.size()); uint64_t counter; if (transId / transCountersPerChunk >= m_transCounters.size()) { counter = 0; } else { counter = m_transCounters[transId / transCountersPerChunk] [transId % transCountersPerChunk]; } return counter; } const Func* lookupImmutableMethod(const Class* cls, const StringData* name, bool& magicCall, bool staticLookup, const Class* ctx) { if (!cls || RuntimeOption::EvalJitEnableRenameFunction) return nullptr; if (cls->attrs() & AttrInterface) return nullptr; bool privateOnly = false; if (!(cls->attrs() & AttrUnique)) { if (!ctx || !ctx->classof(cls)) { return nullptr; } if (!staticLookup) privateOnly = true; } const Func* func; LookupResult res = staticLookup ? g_context->lookupClsMethod(func, cls, name, nullptr, ctx, false) : g_context->lookupObjMethod(func, cls, name, ctx, false); if (res == LookupResult::MethodNotFound) return nullptr; assertx(res == LookupResult::MethodFoundWithThis || res == LookupResult::MethodFoundNoThis || (staticLookup ? res == LookupResult::MagicCallStaticFound : res == LookupResult::MagicCallFound)); magicCall = res == LookupResult::MagicCallStaticFound || res == LookupResult::MagicCallFound; if ((privateOnly && (!(func->attrs() & AttrPrivate) || magicCall)) || func->isAbstract() || func->attrs() & AttrInterceptable) { return nullptr; } if (staticLookup) { if (magicCall) { /* * i) We cant tell if a magic call would go to __call or __callStatic * - Could deal with this by checking for the existence of __call * * ii) hphp semantics is that in the case of an object call, we look * for __call in the scope of the object (this is incompatible * with zend) which means we would have to know that there is no * __call higher up in the tree * - Could deal with this by checking for AttrNoOverride on the * class */ func = nullptr; } } else if (!(func->attrs() & AttrPrivate)) { if (magicCall || func->attrs() & AttrStatic) { if (!(cls->preClass()->attrs() & AttrNoOverride)) { func = nullptr; } } else if (!(func->attrs() & AttrNoOverride && !func->hasStaticLocals()) && !(cls->preClass()->attrs() & AttrNoOverride)) { // Even if a func has AttrNoOverride, if it has static locals it // is cloned into subclasses (to give them different copies of // the static locals), so we need to skip this. func = nullptr; } } return func; } const Func* lookupImmutableCtor(const Class* cls, const Class* ctx) { if (!cls || RuntimeOption::EvalJitEnableRenameFunction) return nullptr; if (!(cls->attrs() & AttrUnique)) { if (!ctx || !ctx->classof(cls)) { return nullptr; } } auto const func = cls->getCtor(); if (func && !(func->attrs() & AttrPublic)) { auto fcls = func->cls(); if (fcls != ctx) { if (!ctx) return nullptr; if ((func->attrs() & AttrPrivate) || !(ctx->classof(fcls) || fcls->classof(ctx))) { return nullptr; } } } return func; } /////////////////////////////////////////////////////////////////////////////// } void invalidatePath(const std::string& path) { TRACE(1, ""invalidatePath: abspath %s\\n"", path.c_str()); assertx(path.size() >= 1 && path[0] == '/'); Treadmill::enqueue([path] { /* * inotify saw this path change. Now poke the unit loader; it will * notice the underlying php file has changed. * * We don't actually need to *do* anything with the Unit* from * this lookup; since the path has changed, the file we'll get out is * going to be some new file, not the old file that needs invalidation. */ String spath(path); lookupUnit(spath.get(), """", nullptr /* initial_opt */); }); } /////////////////////////////////////////////////////////////////////////////// } ",16338,True,2550.561681179743,median "//===--- GenFunc.cpp - Swift IR Generation for Function Types -------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This file implements IR generation for function types in Swift. This // includes creating the IR type as well as capturing variables and // performing calls. // // Swift supports three representations of functions: // // - thin, which are just a function pointer; // // - thick, which are a pair of a function pointer and // an optional ref-counted opaque context pointer; and // // - block, which match the Apple blocks extension: a ref-counted // pointer to a mostly-opaque structure with the function pointer // stored at a fixed offset. // // The order of function parameters is as follows: // // - indirect return pointer // - block context parameter, if applicable // - expanded formal parameter types // - implicit generic parameters // - thick context parameter, if applicable // - error result out-parameter, if applicable // - witness_method generic parameters, if applicable // // The context and error parameters are last because they are // optional: we'd like to be able to turn a thin function into a // thick function, or a non-throwing function into a throwing one, // without adding a thunk. A thick context parameter is required // (but can be passed undef) if an error result is required. // // The additional generic parameters for witness methods follow the // same logic: we'd like to be able to use non-generic method // implementations directly as protocol witnesses if the rest of the // ABI matches up. // // Note that some of this business with context parameters and error // results is just IR formalism; on most of our targets, both of // these are passed in registers. This is also why passing them // as the final argument isn't bad for performance. // // For now, function pointer types are always stored as opaque // pointers in LLVM IR; using a well-typed function type is // very challenging because of issues with recursive type expansion, // which can potentially introduce infinite types. For example: // struct A { // var fn: (A) -> () // } // Our CC lowering expands the fields of A into the argument list // of A.fn, which is necessarily infinite. Attempting to use better // types when not in a situation like this would just make the // compiler complacent, leading to a long tail of undiscovered // crashes. So instead we always store as i8* and require the // bitcast whenever we change representations. // //===----------------------------------------------------------------------===// #include ""swift/AST/ASTContext.h"" #include ""swift/AST/ASTWalker.h"" #include ""swift/AST/Builtins.h"" #include ""swift/AST/Decl.h"" #include ""swift/AST/IRGenOptions.h"" #include ""swift/AST/Module.h"" #include ""swift/AST/Pattern.h"" #include ""swift/AST/PrettyStackTrace.h"" #include ""swift/AST/SubstitutionMap.h"" #include ""swift/AST/Types.h"" #include ""swift/IRGen/Linking.h"" #include ""clang/AST/ASTContext.h"" #include ""clang/CodeGen/CodeGenABITypes.h"" #include ""llvm/IR/Constants.h"" #include ""llvm/IR/DerivedTypes.h"" #include ""llvm/IR/Function.h"" #include ""llvm/IR/Module.h"" #include ""llvm/ProfileData/InstrProf.h"" #include ""llvm/Support/Debug.h"" #include ""llvm/ADT/StringSwitch.h"" #include ""BitPatternBuilder.h"" #include ""Callee.h"" #include ""ConstantBuilder.h"" #include ""EnumPayload.h"" #include ""Explosion.h"" #include ""FixedTypeInfo.h"" #include ""GenCall.h"" #include ""GenClass.h"" #include ""GenFunc.h"" #include ""GenHeap.h"" #include ""GenMeta.h"" #include ""GenObjC.h"" #include ""GenPoly.h"" #include ""GenProto.h"" #include ""GenType.h"" #include ""HeapTypeInfo.h"" #include ""IRGenDebugInfo.h"" #include ""IRGenFunction.h"" #include ""IRGenModule.h"" #include ""IndirectTypeInfo.h"" #include ""ScalarPairTypeInfo.h"" #include ""Signature.h"" #include ""IRGenMangler.h"" using namespace swift; using namespace irgen; namespace { /// Information about the IR-level signature of a function type. class FuncSignatureInfo { private: /// The SIL function type being represented. const CanSILFunctionType FormalType; mutable Signature TheSignature; public: FuncSignatureInfo(CanSILFunctionType formalType) : FormalType(formalType) {} Signature getSignature(IRGenModule &IGM) const; }; /// The @thin function type-info class. class ThinFuncTypeInfo : public PODSingleScalarTypeInfo, public FuncSignatureInfo { ThinFuncTypeInfo(CanSILFunctionType formalType, llvm::Type *storageType, Size size, Alignment align, const SpareBitVector &spareBits) : PODSingleScalarTypeInfo(storageType, size, spareBits, align), FuncSignatureInfo(formalType) { } public: static const ThinFuncTypeInfo *create(CanSILFunctionType formalType, llvm::Type *storageType, Size size, Alignment align, const SpareBitVector &spareBits) { return new ThinFuncTypeInfo(formalType, storageType, size, align, spareBits); } bool mayHaveExtraInhabitants(IRGenModule &IGM) const override { return true; } unsigned getFixedExtraInhabitantCount(IRGenModule &IGM) const override { return getFunctionPointerExtraInhabitantCount(IGM); } APInt getFixedExtraInhabitantValue(IRGenModule &IGM, unsigned bits, unsigned index) const override { return getFunctionPointerFixedExtraInhabitantValue(IGM, bits, index, 0); } llvm::Value *getExtraInhabitantIndex(IRGenFunction &IGF, Address src, SILType T, bool isOutlined) const override { return getFunctionPointerExtraInhabitantIndex(IGF, src); } void storeExtraInhabitant(IRGenFunction &IGF, llvm::Value *index, Address dest, SILType T, bool isOutlined) const override { return storeFunctionPointerExtraInhabitant(IGF, index, dest); } }; /// The @thick function type-info class. class FuncTypeInfo : public ScalarPairTypeInfo, public FuncSignatureInfo { FuncTypeInfo(CanSILFunctionType formalType, llvm::StructType *storageType, Size size, Alignment align, SpareBitVector &&spareBits, IsPOD_t pod) : ScalarPairTypeInfo(storageType, size, std::move(spareBits), align, pod), FuncSignatureInfo(formalType) { } public: static const FuncTypeInfo *create(CanSILFunctionType formalType, llvm::StructType *storageType, Size size, Alignment align, SpareBitVector &&spareBits, IsPOD_t pod) { return new FuncTypeInfo(formalType, storageType, size, align, std::move(spareBits), pod); } // Function types do not satisfy allowsOwnership. #define REF_STORAGE(Name, name, ...) \\ const TypeInfo * \\ create##Name##StorageType(TypeConverter &TC, \\ bool isOptional) const override { \\ llvm_unreachable(""["" #name ""] function type""); \\ } #include ""swift/AST/ReferenceStorage.def"" static Size getFirstElementSize(IRGenModule &IGM) { return IGM.getPointerSize(); } static StringRef getFirstElementLabel() { return "".fn""; } static bool isFirstElementTrivial() { return true; } void emitRetainFirstElement(IRGenFunction &IGF, llvm::Value *fn, Optional atomicity = None) const {} void emitReleaseFirstElement(IRGenFunction &IGF, llvm::Value *fn, Optional atomicity = None) const {} void emitAssignFirstElement(IRGenFunction &IGF, llvm::Value *fn, Address fnAddr) const { IGF.Builder.CreateStore(fn, fnAddr); } static Size getSecondElementOffset(IRGenModule &IGM) { return IGM.getPointerSize(); } static Size getSecondElementSize(IRGenModule &IGM) { return IGM.getPointerSize(); } static StringRef getSecondElementLabel() { return "".data""; } bool isSecondElementTrivial() const { return isPOD(ResilienceExpansion::Maximal); } void emitRetainSecondElement(IRGenFunction &IGF, llvm::Value *data, Optional atomicity = None) const { if (!isPOD(ResilienceExpansion::Maximal)) { if (!atomicity) atomicity = IGF.getDefaultAtomicity(); IGF.emitNativeStrongRetain(data, *atomicity); } } void emitReleaseSecondElement(IRGenFunction &IGF, llvm::Value *data, Optional atomicity = None) const { if (!isPOD(ResilienceExpansion::Maximal)) { if (!atomicity) atomicity = IGF.getDefaultAtomicity(); IGF.emitNativeStrongRelease(data, *atomicity); } } void emitAssignSecondElement(IRGenFunction &IGF, llvm::Value *context, Address dataAddr) const { if (isPOD(ResilienceExpansion::Maximal)) IGF.Builder.CreateStore(context, dataAddr); else IGF.emitNativeStrongAssign(context, dataAddr); } Address projectFunction(IRGenFunction &IGF, Address address) const { return projectFirstElement(IGF, address); } Address projectData(IRGenFunction &IGF, Address address) const { return IGF.Builder.CreateStructGEP(address, 1, IGF.IGM.getPointerSize(), address->getName() + "".data""); } void strongRetain(IRGenFunction &IGF, Explosion &e, Atomicity atomicity) const override { e.claimNext(); emitRetainSecondElement(IGF, e.claimNext(), atomicity); } void strongRelease(IRGenFunction &IGF, Explosion &e, Atomicity atomicity) const override { e.claimNext(); emitReleaseSecondElement(IGF, e.claimNext(), atomicity); } #define NEVER_LOADABLE_CHECKED_REF_STORAGE(Name, name, ...) \\ void name##LoadStrong(IRGenFunction &IGF, Address src, \\ Explosion &out, bool isOptional) const override { \\ llvm_unreachable(#name "" references to functions are not supported""); \\ } \\ void name##TakeStrong(IRGenFunction &IGF, Address src, \\ Explosion &out, bool isOptional) const override { \\ llvm_unreachable(#name "" references to functions are not supported""); \\ } \\ void name##Init(IRGenFunction &IGF, Explosion &in, \\ Address dest, bool isOptional) const override { \\ llvm_unreachable(#name "" references to functions are not supported""); \\ } \\ void name##Assign(IRGenFunction &IGF, Explosion &in, \\ Address dest, bool isOptional) const override { \\ llvm_unreachable(#name "" references to functions are not supported""); \\ } #define ALWAYS_LOADABLE_CHECKED_REF_STORAGE(Name, name, ...) \\ void strongRetain##Name(IRGenFunction &IGF, Explosion &e, \\ Atomicity atomicity) const override { \\ llvm_unreachable(#name "" references to functions are not supported""); \\ } \\ void strongRetain##Name##Release(IRGenFunction &IGF, \\ Explosion &e, \\ Atomicity atomicity) const override { \\ llvm_unreachable(#name "" references to functions are not supported""); \\ } \\ void name##Retain(IRGenFunction &IGF, Explosion &e, \\ Atomicity atomicity) const override { \\ llvm_unreachable(#name "" references to functions are not supported""); \\ } \\ void name##Release(IRGenFunction &IGF, Explosion &e, \\ Atomicity atomicity) const override { \\ llvm_unreachable(#name "" references to functions are not supported""); \\ } #define SOMETIMES_LOADABLE_CHECKED_REF_STORAGE(Name, name, ...) \\ NEVER_LOADABLE_CHECKED_REF_STORAGE(Name, name, ""..."") \\ ALWAYS_LOADABLE_CHECKED_REF_STORAGE(Name, name, ""..."") #include ""swift/AST/ReferenceStorage.def"" bool mayHaveExtraInhabitants(IRGenModule &IGM) const override { return true; } unsigned getFixedExtraInhabitantCount(IRGenModule &IGM) const override { return getFunctionPointerExtraInhabitantCount(IGM); } APInt getFixedExtraInhabitantValue(IRGenModule &IGM, unsigned bits, unsigned index) const override { return getFunctionPointerFixedExtraInhabitantValue(IGM, bits, index, 0); } llvm::Value *getExtraInhabitantIndex(IRGenFunction &IGF, Address src, SILType T, bool isOutlined) const override { src = projectFunction(IGF, src); return getFunctionPointerExtraInhabitantIndex(IGF, src); } APInt getFixedExtraInhabitantMask(IRGenModule &IGM) const override { // Only the function pointer value is used for extra inhabitants. auto pointerSize = IGM.getPointerSize(); auto mask = BitPatternBuilder(IGM.Triple.isLittleEndian()); mask.appendSetBits(pointerSize.getValueInBits()); mask.appendClearBits(pointerSize.getValueInBits()); return mask.build().getValue(); } void storeExtraInhabitant(IRGenFunction &IGF, llvm::Value *index, Address dest, SILType T, bool isOutlined) const override { dest = projectFunction(IGF, dest); return storeFunctionPointerExtraInhabitant(IGF, index, dest); } }; /// The type-info class for ObjC blocks, which are represented by an ObjC /// heap pointer. class BlockTypeInfo : public HeapTypeInfo, public FuncSignatureInfo { public: BlockTypeInfo(CanSILFunctionType ty, llvm::PointerType *storageType, Size size, SpareBitVector spareBits, Alignment align) : HeapTypeInfo(storageType, size, spareBits, align), FuncSignatureInfo(ty) { } ReferenceCounting getReferenceCounting() const { return ReferenceCounting::Block; } }; /// The type info class for the on-stack representation of an ObjC block. /// /// TODO: May not be fixed-layout if we capture generics. class BlockStorageTypeInfo final : public IndirectTypeInfo { Size CaptureOffset; public: BlockStorageTypeInfo(llvm::Type *type, Size size, Alignment align, SpareBitVector &&spareBits, IsPOD_t pod, IsBitwiseTakable_t bt, Size captureOffset) : IndirectTypeInfo(type, size, std::move(spareBits), align, pod, bt, IsFixedSize), CaptureOffset(captureOffset) {} // The lowered type should be an LLVM struct comprising the block header // (IGM.ObjCBlockStructTy) as its first element and the capture as its // second. Address projectBlockHeader(IRGenFunction &IGF, Address storage) const { return IGF.Builder.CreateStructGEP(storage, 0, Size(0)); } Address projectCapture(IRGenFunction &IGF, Address storage) const { return IGF.Builder.CreateStructGEP(storage, 1, CaptureOffset); } // TODO // The frontend will currently never emit copy_addr or destroy_addr for // block storage. void assignWithCopy(IRGenFunction &IGF, Address dest, Address src, SILType T, bool isOutlined) const override { IGF.unimplemented(SourceLoc(), ""copying @block_storage""); } void initializeWithCopy(IRGenFunction &IGF, Address dest, Address src, SILType T, bool isOutlined) const override { IGF.unimplemented(SourceLoc(), ""copying @block_storage""); } void destroy(IRGenFunction &IGF, Address addr, SILType T, bool isOutlined) const override { IGF.unimplemented(SourceLoc(), ""destroying @block_storage""); } }; } // end anonymous namespace const TypeInfo *TypeConverter::convertBlockStorageType(SILBlockStorageType *T) { // The block storage consists of the block header (ObjCBlockStructTy) // followed by the lowered type of the capture. auto &capture = IGM.getTypeInfoForLowered(T->getCaptureType()); // TODO: Support dynamic-sized captures. const auto *fixedCapture = dyn_cast(&capture); llvm::Type *fixedCaptureTy; // The block header is pointer aligned. The capture may be worse aligned. Alignment align = IGM.getPointerAlignment(); Size captureOffset( IGM.DataLayout.getStructLayout(IGM.ObjCBlockStructTy)->getSizeInBytes()); auto spareBits = BitPatternBuilder(IGM.Triple.isLittleEndian()); spareBits.appendClearBits(captureOffset.getValueInBits()); Size size = captureOffset; IsPOD_t pod = IsNotPOD; IsBitwiseTakable_t bt = IsNotBitwiseTakable; if (!fixedCapture) { IGM.unimplemented(SourceLoc(), ""dynamic @block_storage capture""); fixedCaptureTy = llvm::StructType::get(IGM.getLLVMContext(), {}); } else { fixedCaptureTy = cast(capture).getStorageType(); align = std::max(align, fixedCapture->getFixedAlignment()); captureOffset = captureOffset.roundUpToAlignment(align); spareBits.padWithSetBitsTo(captureOffset.getValueInBits()); spareBits.append(fixedCapture->getSpareBits()); size = captureOffset + fixedCapture->getFixedSize(); pod = fixedCapture->isPOD(ResilienceExpansion::Maximal); bt = fixedCapture->isBitwiseTakable(ResilienceExpansion::Maximal); } llvm::Type *storageElts[] = { IGM.ObjCBlockStructTy, fixedCaptureTy, }; auto storageTy = llvm::StructType::get(IGM.getLLVMContext(), storageElts, /*packed*/ false); return new BlockStorageTypeInfo(storageTy, size, align, spareBits.build(), pod, bt, captureOffset); } Address irgen::projectBlockStorageCapture(IRGenFunction &IGF, Address storageAddr, CanSILBlockStorageType storageTy) { auto &tl = IGF.getTypeInfoForLowered(storageTy).as(); return tl.projectCapture(IGF, storageAddr); } const TypeInfo *TypeConverter::convertFunctionType(SILFunctionType *T) { switch (T->getRepresentation()) { case SILFunctionType::Representation::Block: return new BlockTypeInfo(CanSILFunctionType(T), IGM.ObjCBlockPtrTy, IGM.getPointerSize(), IGM.getHeapObjectSpareBits(), IGM.getPointerAlignment()); case SILFunctionType::Representation::Thin: case SILFunctionType::Representation::Method: case SILFunctionType::Representation::WitnessMethod: case SILFunctionType::Representation::ObjCMethod: case SILFunctionType::Representation::CFunctionPointer: case SILFunctionType::Representation::Closure: return ThinFuncTypeInfo::create(CanSILFunctionType(T), IGM.FunctionPtrTy, IGM.getPointerSize(), IGM.getPointerAlignment(), IGM.getFunctionPointerSpareBits()); case SILFunctionType::Representation::Thick: { SpareBitVector spareBits; spareBits.append(IGM.getFunctionPointerSpareBits()); // Although the context pointer of a closure (at least, an escaping one) // is a refcounted pointer, we'd like to reserve the right to pack small // contexts into the pointer value, so let's not take any spare bits from // it. spareBits.appendClearBits(IGM.getPointerSize().getValueInBits()); if (T->isNoEscape()) { // @noescape thick functions are trivial types. return FuncTypeInfo::create( CanSILFunctionType(T), IGM.NoEscapeFunctionPairTy, IGM.getPointerSize() * 2, IGM.getPointerAlignment(), std::move(spareBits), IsPOD); } return FuncTypeInfo::create( CanSILFunctionType(T), IGM.FunctionPairTy, IGM.getPointerSize() * 2, IGM.getPointerAlignment(), std::move(spareBits), IsNotPOD); } } llvm_unreachable(""bad function type representation""); } Signature FuncSignatureInfo::getSignature(IRGenModule &IGM) const { // If it's already been filled in, we're done. if (TheSignature.isValid()) return TheSignature; // Update the cache and return. TheSignature = Signature::getUncached(IGM, FormalType); assert(TheSignature.isValid()); return TheSignature; } static const FuncSignatureInfo & getFuncSignatureInfoForLowered(IRGenModule &IGM, CanSILFunctionType type) { auto &ti = IGM.getTypeInfoForLowered(type); switch (type->getRepresentation()) { case SILFunctionType::Representation::Block: return ti.as(); case SILFunctionType::Representation::Thin: case SILFunctionType::Representation::CFunctionPointer: case SILFunctionType::Representation::Method: case SILFunctionType::Representation::WitnessMethod: case SILFunctionType::Representation::ObjCMethod: case SILFunctionType::Representation::Closure: return ti.as(); case SILFunctionType::Representation::Thick: return ti.as(); } llvm_unreachable(""bad function type representation""); } Signature IRGenModule::getSignature(CanSILFunctionType type) { auto &sigInfo = getFuncSignatureInfoForLowered(*this, type); return sigInfo.getSignature(*this); } llvm::FunctionType * IRGenModule::getFunctionType(CanSILFunctionType type, llvm::AttributeList &attrs, ForeignFunctionInfo *foreignInfo) { auto &sigInfo = getFuncSignatureInfoForLowered(*this, type); Signature sig = sigInfo.getSignature(*this); attrs = sig.getAttributes(); if (foreignInfo) *foreignInfo = sig.getForeignInfo(); return sig.getType(); } ForeignFunctionInfo IRGenModule::getForeignFunctionInfo(CanSILFunctionType type) { if (type->getLanguage() == SILFunctionLanguage::Swift) return ForeignFunctionInfo(); auto &sigInfo = getFuncSignatureInfoForLowered(*this, type); return sigInfo.getSignature(*this).getForeignInfo(); } static void emitApplyArgument(IRGenFunction &IGF, CanSILFunctionType origFnTy, SILParameterInfo origParam, CanSILFunctionType substFnTy, SILParameterInfo substParam, Explosion &in, Explosion &out) { auto silConv = IGF.IGM.silConv; bool isSubstituted = (silConv.getSILType(substParam, substFnTy) != silConv.getSILType(origParam, origFnTy)); // For indirect arguments, we just need to pass a pointer. if (silConv.isSILIndirect(origParam)) { // This address is of the substituted type. auto addr = in.claimNext(); // If a substitution is in play, just bitcast the address. if (isSubstituted) { auto origType = IGF.IGM.getStoragePointerType(silConv.getSILType(origParam, origFnTy)); addr = IGF.Builder.CreateBitCast(addr, origType); } out.add(addr); return; } assert(!silConv.isSILIndirect(origParam) && ""Unexpected opaque apply parameter.""); // Otherwise, it's an explosion, which we may need to translate, // both in terms of explosion level and substitution levels. // Handle the last unsubstituted case. if (!isSubstituted) { auto &substArgTI = cast( IGF.getTypeInfo(silConv.getSILType(substParam, substFnTy))); substArgTI.reexplode(IGF, in, out); return; } reemitAsUnsubstituted(IGF, silConv.getSILType(origParam, origFnTy), silConv.getSILType(substParam, substFnTy), in, out); } static CanType getArgumentLoweringType(CanType type, SILParameterInfo paramInfo) { switch (paramInfo.getConvention()) { // Capture value parameters by value, consuming them. case ParameterConvention::Direct_Owned: case ParameterConvention::Direct_Unowned: case ParameterConvention::Direct_Guaranteed: case ParameterConvention::Indirect_In: case ParameterConvention::Indirect_In_Constant: case ParameterConvention::Indirect_In_Guaranteed: return type; // Capture inout parameters by pointer. case ParameterConvention::Indirect_Inout: case ParameterConvention::Indirect_InoutAliasable: return CanInOutType::get(type); } llvm_unreachable(""unhandled convention""); } static bool isABIIgnoredParameterWithoutStorage(IRGenModule &IGM, IRGenFunction &IGF, CanSILFunctionType substType, unsigned paramIdx) { auto param = substType->getParameters()[paramIdx]; if (param.isFormalIndirect()) return false; SILType argType = IGM.silConv.getSILType(param, substType); auto &ti = IGF.getTypeInfoForLowered(argType.getASTType()); // Empty values don't matter. return ti.getSchema().empty(); } /// Find the parameter index for the one (assuming there was only one) partially /// applied argument ignoring empty types that are not passed as part of the /// ABI. static unsigned findSinglePartiallyAppliedParameterIndexIgnoringEmptyTypes( IRGenFunction &IGF, CanSILFunctionType substType, CanSILFunctionType outType) { auto substParameters = substType->getParameters(); auto outParamters = outType->getParameters(); unsigned firstNonEmpty = -1U; for (unsigned paramIdx = outParamters.size() ; paramIdx != substParameters.size(); ++paramIdx) { bool isEmpty = isABIIgnoredParameterWithoutStorage(IGF.IGM, IGF, substType, paramIdx); assert((isEmpty || firstNonEmpty == -1U) && ""Expect at most one partially "" ""applied that is passed as an "" ""ABI argument""); if (!isEmpty) firstNonEmpty = paramIdx; } assert(firstNonEmpty != -1U); return firstNonEmpty; } /// Emit the forwarding stub function for a partial application. /// /// If 'layout' is null, there is a single captured value of /// Swift-refcountable type that is being used directly as the /// context object. static llvm::Function *emitPartialApplicationForwarder(IRGenModule &IGM, const Optional &staticFnPtr, bool calleeHasContext, const Signature &origSig, CanSILFunctionType origType, CanSILFunctionType substType, CanSILFunctionType outType, SubstitutionMap subs, HeapLayout const *layout, ArrayRef conventions) { auto outSig = IGM.getSignature(outType); llvm::AttributeList outAttrs = outSig.getAttributes(); llvm::FunctionType *fwdTy = outSig.getType(); SILFunctionConventions outConv(outType, IGM.getSILModule()); StringRef FnName; if (staticFnPtr) FnName = staticFnPtr->getPointer()->getName(); IRGenMangler Mangler; std::string thunkName = Mangler.manglePartialApplyForwarder(FnName); // FIXME: Maybe cache the thunk by function and closure types?. llvm::Function *fwd = llvm::Function::Create(fwdTy, llvm::Function::InternalLinkage, llvm::StringRef(thunkName), &IGM.Module); fwd->setCallingConv(outSig.getCallingConv()); fwd->setAttributes(outAttrs); // Merge initial attributes with outAttrs. llvm::AttrBuilder b; IGM.constructInitialFnAttributes(b); fwd->addAttributes(llvm::AttributeList::FunctionIndex, b); IRGenFunction subIGF(IGM, fwd); if (IGM.DebugInfo) IGM.DebugInfo->emitArtificialFunction(subIGF, fwd); Explosion origParams = subIGF.collectParameters(); // Create a new explosion for potentially reabstracted parameters. Explosion args; Address resultValueAddr; { // Lower the forwarded arguments in the original function's generic context. GenericContextScope scope(IGM, origType->getInvocationGenericSignature()); SILFunctionConventions origConv(origType, IGM.getSILModule()); auto &outResultTI = IGM.getTypeInfo(outConv.getSILResultType()); auto &nativeResultSchema = outResultTI.nativeReturnValueSchema(IGM); auto &origResultTI = IGM.getTypeInfo(origConv.getSILResultType()); auto &origNativeSchema = origResultTI.nativeReturnValueSchema(IGM); // Forward the indirect return values. We might have to reabstract the // return value. if (nativeResultSchema.requiresIndirect()) { assert(origNativeSchema.requiresIndirect()); auto resultAddr = origParams.claimNext(); resultAddr = subIGF.Builder.CreateBitCast( resultAddr, IGM.getStoragePointerType(origConv.getSILResultType())); args.add(resultAddr); } else if (origNativeSchema.requiresIndirect()) { assert(!nativeResultSchema.requiresIndirect()); auto stackAddr = outResultTI.allocateStack( subIGF, outConv.getSILResultType(), ""return.temp""); resultValueAddr = stackAddr.getAddress(); auto resultAddr = subIGF.Builder.CreateBitCast( resultValueAddr, IGM.getStoragePointerType(origConv.getSILResultType())); args.add(resultAddr.getAddress()); } for (auto resultType : origConv.getIndirectSILResultTypes()) { auto addr = origParams.claimNext(); addr = subIGF.Builder.CreateBitCast( addr, IGM.getStoragePointerType(resultType)); args.add(addr); } // Reemit the parameters as unsubstituted. for (unsigned i = 0; i < outType->getParameters().size(); ++i) { auto origParamInfo = origType->getParameters()[i]; auto &ti = IGM.getTypeInfoForLowered( origParamInfo.getArgumentType(IGM.getSILModule(), origType)); auto schema = ti.getSchema(); auto origParamSILType = IGM.silConv.getSILType(origParamInfo, origType); // Forward the address of indirect value params. auto &nativeSchemaOrigParam = ti.nativeParameterValueSchema(IGM); bool isIndirectParam = origConv.isSILIndirect(origParamInfo); if (!isIndirectParam && nativeSchemaOrigParam.requiresIndirect()) { auto addr = origParams.claimNext(); if (addr->getType() != ti.getStorageType()->getPointerTo()) addr = subIGF.Builder.CreateBitCast(addr, ti.getStorageType()->getPointerTo()); args.add(addr); continue; } auto outTypeParamInfo = outType->getParameters()[i]; // Indirect parameters need no mapping through the native calling // convention. if (isIndirectParam) { emitApplyArgument(subIGF, origType, origParamInfo, outType, outTypeParamInfo, origParams, args); continue; } // Map from the native calling convention into the explosion schema. auto outTypeParamSILType = IGM.silConv.getSILType(origParamInfo, origType); auto &nativeSchemaOutTypeParam = IGM.getTypeInfo(outTypeParamSILType).nativeParameterValueSchema(IGM); Explosion nativeParam; origParams.transferInto(nativeParam, nativeSchemaOutTypeParam.size()); bindPolymorphicParameter(subIGF, origType, substType, nativeParam, i); Explosion nonNativeParam = nativeSchemaOutTypeParam.mapFromNative( subIGF.IGM, subIGF, nativeParam, outTypeParamSILType); assert(nativeParam.empty()); // Emit unsubstituted argument for call. Explosion nonNativeApplyArg; emitApplyArgument(subIGF, origType, origParamInfo, outType, outTypeParamInfo, nonNativeParam, nonNativeApplyArg); assert(nonNativeParam.empty()); // Map back from the explosion scheme to the native calling convention for // the call. Explosion nativeApplyArg = nativeSchemaOrigParam.mapIntoNative( subIGF.IGM, subIGF, nonNativeApplyArg, origParamSILType, false); assert(nonNativeApplyArg.empty()); nativeApplyArg.transferInto(args, nativeApplyArg.size()); } } struct AddressToDeallocate { SILType Type; const TypeInfo &TI; StackAddress Addr; }; SmallVector addressesToDeallocate; bool dependsOnContextLifetime = false; bool consumesContext; bool needsAllocas = false; switch (outType->getCalleeConvention()) { case ParameterConvention::Direct_Owned: consumesContext = true; break; case ParameterConvention::Direct_Unowned: case ParameterConvention::Direct_Guaranteed: consumesContext = false; break; case ParameterConvention::Indirect_Inout: case ParameterConvention::Indirect_InoutAliasable: case ParameterConvention::Indirect_In: case ParameterConvention::Indirect_In_Constant: case ParameterConvention::Indirect_In_Guaranteed: llvm_unreachable(""indirect callables not supported""); } // Lower the captured arguments in the original function's generic context. GenericContextScope scope(IGM, origType->getInvocationGenericSignature()); // This is where the context parameter appears. llvm::Value *rawData = nullptr; Address data; unsigned nextCapturedField = 0; if (!layout) { rawData = origParams.claimNext(); } else if (!layout->isKnownEmpty()) { rawData = origParams.claimNext(); data = layout->emitCastTo(subIGF, rawData); // Restore type metadata bindings, if we have them. if (layout->hasBindings()) { auto bindingLayout = layout->getElement(nextCapturedField++); // The bindings should be fixed-layout inside the object, so we can // pass None here. If they weren't, we'd have a chicken-egg problem. auto bindingsAddr = bindingLayout.project(subIGF, data, /*offsets*/ None); layout->getBindings().restore(subIGF, bindingsAddr, MetadataState::Complete); } // There's still a placeholder to claim if the target type is thick // or there's an error result. } else if (outType->getRepresentation()==SILFunctionTypeRepresentation::Thick || outType->hasErrorResult()) { llvm::Value *contextPtr = origParams.claimNext(); (void)contextPtr; assert(contextPtr->getType() == IGM.RefCountedPtrTy); } Explosion polyArgs; // Emit the polymorphic arguments. assert((subs.hasAnySubstitutableParams() == hasPolymorphicParameters(origType) || (!subs.hasAnySubstitutableParams() && origType->getRepresentation() == SILFunctionTypeRepresentation::WitnessMethod)) && ""should have substitutions iff original function is generic""); WitnessMetadata witnessMetadata; // If we have a layout we might have to bind polymorphic arguments from the // captured arguments which we will do later. Otherwise, we have to // potentially bind polymorphic arguments from the context if it was a // partially applied argument. bool hasPolymorphicParams = hasPolymorphicParameters(origType); if (!layout && hasPolymorphicParams) { assert(conventions.size() == 1); // We could have either partially applied an argument from the function // signature or otherwise we could have a closure context to forward. We only // care for the former for the purpose of reconstructing polymorphic // parameters from regular arguments. if (!calleeHasContext) { unsigned paramI = findSinglePartiallyAppliedParameterIndexIgnoringEmptyTypes( subIGF, substType, outType); auto paramInfo = substType->getParameters()[paramI]; auto &ti = IGM.getTypeInfoForLowered( paramInfo.getArgumentType(IGM.getSILModule(), substType)); Explosion param; auto ref = rawData; // We can get a '{ swift.refcounted* }' type for AnyObject on linux. if (!ti.getStorageType()->isPointerTy() && ti.isSingleSwiftRetainablePointer(ResilienceExpansion::Maximal)) ref = subIGF.coerceValue(rawData, ti.getStorageType(), subIGF.IGM.DataLayout); else ref = subIGF.Builder.CreateBitCast(rawData, ti.getStorageType()); param.add(ref); bindPolymorphicParameter(subIGF, origType, substType, param, paramI); (void)param.claimAll(); } emitPolymorphicArguments(subIGF, origType, subs, &witnessMetadata, polyArgs); } auto haveContextArgument = calleeHasContext || hasSelfContextParameter(origType); // Witness method calls expect self, followed by the self type followed by, // the witness table at the end of the parameter list. But polymorphic // arguments come before this. bool isWitnessMethodCallee = origType->getRepresentation() == SILFunctionTypeRepresentation::WitnessMethod; Explosion witnessMethodSelfValue; // If there's a data pointer required, but it's a swift-retainable // value being passed as the context, just forward it down. if (!layout) { assert(conventions.size() == 1); // We need to retain the parameter if: // - we received at +0 (either) and are passing as owned // - we received as unowned and are passing as guaranteed auto argConvention = conventions[nextCapturedField++]; switch (argConvention) { case ParameterConvention::Indirect_In: case ParameterConvention::Indirect_In_Constant: case ParameterConvention::Direct_Owned: if (!consumesContext) subIGF.emitNativeStrongRetain(rawData, subIGF.getDefaultAtomicity()); break; case ParameterConvention::Indirect_In_Guaranteed: case ParameterConvention::Direct_Guaranteed: dependsOnContextLifetime = true; if (outType->getCalleeConvention() == ParameterConvention::Direct_Unowned) { subIGF.emitNativeStrongRetain(rawData, subIGF.getDefaultAtomicity()); consumesContext = true; } break; case ParameterConvention::Direct_Unowned: // Make sure we release later if we received at +1. if (consumesContext) dependsOnContextLifetime = true; break; case ParameterConvention::Indirect_Inout: case ParameterConvention::Indirect_InoutAliasable: llvm_unreachable(""should never happen!""); } // FIXME: The naming and documentation here isn't ideal. This // parameter is always present which is evident since we always // grab a type to cast to, but sometimes after the polymorphic // arguments. This is just following the lead of existing (and not // terribly easy to follow) code. // If there is a context argument, it comes after the polymorphic // arguments. auto argIndex = args.size(); if (haveContextArgument) argIndex += polyArgs.size(); llvm::Type *expectedArgTy = origSig.getType()->getParamType(argIndex); llvm::Value *argValue; if (isIndirectFormalParameter(argConvention)) { // We can use rawData's type for the alloca because it is a swift // retainable value. Defensively, give it that type. We can't use the // expectedArgType because it might be a generic parameter and therefore // have opaque storage. auto RetainableValue = rawData; if (RetainableValue->getType() != subIGF.IGM.RefCountedPtrTy) RetainableValue = subIGF.Builder.CreateBitCast( RetainableValue, subIGF.IGM.RefCountedPtrTy); needsAllocas = true; auto temporary = subIGF.createAlloca(RetainableValue->getType(), subIGF.IGM.getPointerAlignment(), ""partial-apply.context""); subIGF.Builder.CreateStore(RetainableValue, temporary); argValue = temporary.getAddress(); argValue = subIGF.Builder.CreateBitCast(argValue, expectedArgTy); } else { argValue = subIGF.Builder.CreateBitCast(rawData, expectedArgTy); } args.add(argValue); // If there's a data pointer required, grab it and load out the // extra, previously-curried parameters. } else { unsigned origParamI = outType->getParameters().size(); assert(layout->getElements().size() == conventions.size() && ""conventions don't match context layout""); // Calculate non-fixed field offsets. HeapNonFixedOffsets offsets(subIGF, *layout); // Perform the loads. for (unsigned n = layout->getElements().size(); nextCapturedField < n; ++nextCapturedField) { auto &fieldLayout = layout->getElement(nextCapturedField); auto &fieldTy = layout->getElementTypes()[nextCapturedField]; auto fieldConvention = conventions[nextCapturedField]; Address fieldAddr = fieldLayout.project(subIGF, data, offsets); auto &fieldTI = fieldLayout.getType(); auto fieldSchema = fieldTI.getSchema(); Explosion param; switch (fieldConvention) { case ParameterConvention::Indirect_In: case ParameterConvention::Indirect_In_Constant: { // The +1 argument is passed indirectly, so we need to copy into a // temporary. needsAllocas = true; auto stackAddr = fieldTI.allocateStack(subIGF, fieldTy, ""arg.temp""); auto addressPointer = stackAddr.getAddress().getAddress(); fieldTI.initializeWithCopy(subIGF, stackAddr.getAddress(), fieldAddr, fieldTy, false); param.add(addressPointer); // Remember to deallocate later. addressesToDeallocate.push_back( AddressToDeallocate{fieldTy, fieldTI, stackAddr}); break; } case ParameterConvention::Indirect_In_Guaranteed: // The argument is +0, so we can use the address of the param in // the context directly. param.add(fieldAddr.getAddress()); dependsOnContextLifetime = true; break; case ParameterConvention::Indirect_Inout: case ParameterConvention::Indirect_InoutAliasable: // Load the address of the inout parameter. cast(fieldTI).loadAsCopy(subIGF, fieldAddr, param); break; case ParameterConvention::Direct_Guaranteed: case ParameterConvention::Direct_Unowned: // If the type is nontrivial, keep the context alive since the field // depends on the context to not be deallocated. if (!fieldTI.isPOD(ResilienceExpansion::Maximal)) dependsOnContextLifetime = true; // Load these parameters directly. We can ""take"" since the parameter is // +0. This can happen since the context will keep the parameter alive. cast(fieldTI).loadAsTake(subIGF, fieldAddr, param); break; case ParameterConvention::Direct_Owned: // Copy the value out at +1. cast(fieldTI).loadAsCopy(subIGF, fieldAddr, param); break; } // Reemit the capture params as unsubstituted. // Skip empty parameters. while (origParamI < origType->getParameters().size()) { if (!isABIIgnoredParameterWithoutStorage(IGM, subIGF, substType, origParamI)) break; origParamI++; } if (origParamI < origType->getParameters().size()) { Explosion origParam; auto origParamInfo = origType->getParameters()[origParamI]; if (hasPolymorphicParams) bindPolymorphicParameter(subIGF, origType, substType, param, origParamI); emitApplyArgument(subIGF, origType, origParamInfo, substType, substType->getParameters()[origParamI], param, origParam); bool isWitnessMethodCalleeSelf = (isWitnessMethodCallee && origParamI + 1 == origType->getParameters().size()); needsAllocas |= addNativeArgument( subIGF, origParam, origType, origParamInfo, isWitnessMethodCalleeSelf ? witnessMethodSelfValue : args, false); ++origParamI; } else { args.add(param.claimAll()); } } // If the parameters can live independent of the context, release it now // so we can tail call. The safety of this assumes that neither this release // nor any of the loads can throw. if (consumesContext && !dependsOnContextLifetime && rawData) { assert(!outType->isNoEscape() && ""Trivial context must not be released""); subIGF.emitNativeStrongRelease(rawData, subIGF.getDefaultAtomicity()); } // Now that we have bound generic parameters from the captured arguments // emit the polymorphic arguments. if (hasPolymorphicParameters(origType)) { emitPolymorphicArguments(subIGF, origType, subs, &witnessMetadata, polyArgs); } } // Derive the callee function pointer. auto fnTy = origSig.getType()->getPointerTo(); FunctionPointer fnPtr = [&]() -> FunctionPointer { // If we found a function pointer statically, great. if (staticFnPtr) { assert(staticFnPtr->getPointer()->getType() == fnTy && ""static function type mismatch?!""); return *staticFnPtr; } // Otherwise, it was the last thing we added to the layout. // The dynamic function pointer is packed ""last"" into the context, // and we pulled it out as an argument. Just pop it off. auto fnPtr = args.takeLast(); // It comes out of the context as an i8*. Cast to the function type. fnPtr = subIGF.Builder.CreateBitCast(fnPtr, fnTy); return FunctionPointer(fnPtr, origSig); }(); // Derive the context argument if needed. This is either: // - the saved context argument, in which case it was the last // thing we added to the layout other than a possible non-static // function pointer (which we already popped off of 'args'); or // - 'self', in which case it was the last formal argument. // In either case, it's the last thing in 'args'. llvm::Value *fnContext = nullptr; if (haveContextArgument) fnContext = args.takeLast(); polyArgs.transferInto(args, polyArgs.size()); // If we have a witness method call, the inner context is the // witness table. Metadata for Self is derived inside the partial // application thunk and doesn't need to be stored in the outer // context. if (isWitnessMethodCallee) { assert(fnContext->getType() == IGM.Int8PtrTy); llvm::Value *wtable = subIGF.Builder.CreateBitCast( fnContext, IGM.WitnessTablePtrTy); assert(wtable->getType() == IGM.WitnessTablePtrTy); witnessMetadata.SelfWitnessTable = wtable; // Okay, this is where the callee context goes. } else if (fnContext) { args.add(fnContext); // Pass a placeholder for thin function calls. } else if (origType->hasErrorResult()) { args.add(llvm::UndefValue::get(IGM.RefCountedPtrTy)); } // Add the witness methods self argument before the error parameter after the // polymorphic arguments. if (isWitnessMethodCallee) witnessMethodSelfValue.transferInto(args, witnessMethodSelfValue.size()); // Pass down the error result. if (origType->hasErrorResult()) { llvm::Value *errorResultPtr = origParams.claimNext(); args.add(errorResultPtr); } assert(origParams.empty()); if (isWitnessMethodCallee) { assert(witnessMetadata.SelfMetadata->getType() == IGM.TypeMetadataPtrTy); args.add(witnessMetadata.SelfMetadata); assert(witnessMetadata.SelfWitnessTable->getType() == IGM.WitnessTablePtrTy); args.add(witnessMetadata.SelfWitnessTable); } llvm::CallInst *call = subIGF.Builder.CreateCall(fnPtr, args.claimAll()); if (addressesToDeallocate.empty() && !needsAllocas && (!consumesContext || !dependsOnContextLifetime)) call->setTailCall(); // Deallocate everything we allocated above. // FIXME: exceptions? for (auto &entry : addressesToDeallocate) { entry.TI.deallocateStack(subIGF, entry.Addr, entry.Type); } // If the parameters depended on the context, consume the context now. if (rawData && consumesContext && dependsOnContextLifetime) { assert(!outType->isNoEscape() && ""Trivial context must not be released""); subIGF.emitNativeStrongRelease(rawData, subIGF.getDefaultAtomicity()); } // Reabstract the result value as substituted. SILFunctionConventions origConv(origType, IGM.getSILModule()); auto &outResultTI = IGM.getTypeInfo(outConv.getSILResultType()); auto &nativeResultSchema = outResultTI.nativeReturnValueSchema(IGM); if (call->getType()->isVoidTy()) { if (!resultValueAddr.isValid()) subIGF.Builder.CreateRetVoid(); else { // Okay, we have called a function that expects an indirect return type // but the partially applied return type is direct. assert(!nativeResultSchema.requiresIndirect()); Explosion loadedResult; cast(outResultTI) .loadAsTake(subIGF, resultValueAddr, loadedResult); Explosion nativeResult = nativeResultSchema.mapIntoNative( IGM, subIGF, loadedResult, outConv.getSILResultType(), false); outResultTI.deallocateStack(subIGF, resultValueAddr, outConv.getSILResultType()); if (nativeResult.size() == 1) subIGF.Builder.CreateRet(nativeResult.claimNext()); else { llvm::Value *nativeAgg = llvm::UndefValue::get(nativeResultSchema.getExpandedType(IGM)); for (unsigned i = 0, e = nativeResult.size(); i != e; ++i) { auto *elt = nativeResult.claimNext(); nativeAgg = subIGF.Builder.CreateInsertValue(nativeAgg, elt, i); } subIGF.Builder.CreateRet(nativeAgg); } } } else { llvm::Value *callResult = call; // If the result type is dependent on a type parameter we might have to // cast to the result type - it could be substituted. if (origConv.getSILResultType().hasTypeParameter()) { auto ResType = fwd->getReturnType(); if (ResType != callResult->getType()) callResult = subIGF.coerceValue(callResult, ResType, subIGF.IGM.DataLayout); } subIGF.Builder.CreateRet(callResult); } return fwd; } /// Emit a partial application thunk for a function pointer applied to a partial /// set of argument values. Optional irgen::emitFunctionPartialApplication( IRGenFunction &IGF, SILFunction &SILFn, const FunctionPointer &fn, llvm::Value *fnContext, Explosion &args, ArrayRef params, SubstitutionMap subs, CanSILFunctionType origType, CanSILFunctionType substType, CanSILFunctionType outType, Explosion &out, bool isOutlined) { // If we have a single Swift-refcounted context value, we can adopt it // directly as our closure context without creating a box and thunk. enum HasSingleSwiftRefcountedContext { Maybe, Yes, No, Thunkable } hasSingleSwiftRefcountedContext = Maybe; Optional singleRefcountedConvention; SmallVector argTypeInfos; SmallVector argValTypes; SmallVector argConventions; // Reserve space for polymorphic bindings. auto bindings = NecessaryBindings::forFunctionInvocations(IGF.IGM, origType, subs); if (!bindings.empty()) { hasSingleSwiftRefcountedContext = No; auto bindingsSize = bindings.getBufferSize(IGF.IGM); auto &bindingsTI = IGF.IGM.getOpaqueStorageTypeInfo(bindingsSize, IGF.IGM.getPointerAlignment()); argValTypes.push_back(SILType()); argTypeInfos.push_back(&bindingsTI); argConventions.push_back(ParameterConvention::Direct_Unowned); } // Collect the type infos for the context parameters. for (auto param : params) { SILType argType = IGF.IGM.silConv.getSILType(param, origType); auto argLoweringTy = getArgumentLoweringType(argType.getASTType(), param); auto &ti = IGF.getTypeInfoForLowered(argLoweringTy); // Empty values don't matter. auto schema = ti.getSchema(); if (schema.empty() && !param.isFormalIndirect()) continue; argValTypes.push_back(argType); argConventions.push_back(param.getConvention()); argTypeInfos.push_back(&ti); // Update the single-swift-refcounted check, unless we already ruled that // out. if (hasSingleSwiftRefcountedContext == No) continue; // Adding nonempty values when we already have a single refcounted pointer // means we don't have a single value anymore. if (hasSingleSwiftRefcountedContext != Maybe) { hasSingleSwiftRefcountedContext = No; continue; } if (ti.isSingleSwiftRetainablePointer(ResilienceExpansion::Maximal)) { hasSingleSwiftRefcountedContext = Yes; singleRefcountedConvention = param.getConvention(); } else { hasSingleSwiftRefcountedContext = No; } } // We can't just bitcast if there's an error parameter to forward. // This is an unfortunate restriction arising from the fact that a // thin throwing function will have the signature: // %result (%arg*, %context*, %error*) // but the output signature needs to be // %result (%context*, %error*) // // 'swifterror' fixes this physically, but there's still a risk of // miscompiles because the LLVM optimizer may forward arguments // positionally without considering 'swifterror'. // // Note, however, that we will override this decision below if the // only thing we have to forward is already a context pointer. // That's fine. // // The proper long-term fix is that closure functions should be // emitted with a convention that takes the closure box as the // context parameter. When we do that, all of this code will // disappear. if (hasSingleSwiftRefcountedContext == Yes && origType->hasErrorResult()) { hasSingleSwiftRefcountedContext = Thunkable; } // If the function pointer is a witness method call, include the witness // table in the context. if (origType->getRepresentation() == SILFunctionTypeRepresentation::WitnessMethod) { llvm::Value *wtable = fnContext; assert(wtable->getType() == IGF.IGM.WitnessTablePtrTy); // TheRawPointerType lowers as i8*, not i8**. args.add(IGF.Builder.CreateBitCast(wtable, IGF.IGM.Int8PtrTy)); argValTypes.push_back(SILType::getRawPointerType(IGF.IGM.Context)); argTypeInfos.push_back( &IGF.getTypeInfoForLowered(IGF.IGM.Context.TheRawPointerType)); argConventions.push_back(ParameterConvention::Direct_Unowned); hasSingleSwiftRefcountedContext = No; // Otherwise, we might have a reference-counted context pointer. } else if (fnContext) { args.add(fnContext); argValTypes.push_back(SILType::getNativeObjectType(IGF.IGM.Context)); argConventions.push_back(origType->getCalleeConvention()); argTypeInfos.push_back( &IGF.getTypeInfoForLowered(IGF.IGM.Context.TheNativeObjectType)); // If this is the only context argument we end up with, we can just share // it. if (args.size() == 1) { assert(bindings.empty()); hasSingleSwiftRefcountedContext = Yes; singleRefcountedConvention = origType->getCalleeConvention(); } } // If we have a single refcounted pointer context (and no polymorphic args // to capture), and the dest ownership semantics match the parameter's, // skip building the box and thunk and just take the pointer as // context. // TODO: We can only do this and use swiftself if all our swiftcc emit the // last parameter that fits into a register as swiftself. // We should get this optimization back using the @convention(closure) whose // box argument should just be swift self. if (/* DISABLES CODE */ (false) && !origType->isPolymorphic() && hasSingleSwiftRefcountedContext == Yes && outType->getCalleeConvention() == *singleRefcountedConvention) { assert(args.size() == 1); auto fnPtr = fn.getPointer(); fnPtr = IGF.Builder.CreateBitCast(fnPtr, IGF.IGM.Int8PtrTy); out.add(fnPtr); llvm::Value *ctx = args.claimNext(); ctx = IGF.Builder.CreateBitCast(ctx, IGF.IGM.RefCountedPtrTy); out.add(ctx); return {}; } Optional staticFn; if (fn.isConstant()) staticFn = fn; // If the function pointer is dynamic, include it in the context. size_t nonStaticFnIndex = ~size_t(0); if (!staticFn) { nonStaticFnIndex = argTypeInfos.size(); argValTypes.push_back(SILType::getRawPointerType(IGF.IGM.Context)); argTypeInfos.push_back( &IGF.getTypeInfoForLowered(IGF.IGM.Context.TheRawPointerType)); argConventions.push_back(ParameterConvention::Direct_Unowned); hasSingleSwiftRefcountedContext = No; } // If we only need to capture a single Swift-refcounted object, we // still need to build a thunk, but we don't need to allocate anything. if ((hasSingleSwiftRefcountedContext == Yes || hasSingleSwiftRefcountedContext == Thunkable) && *singleRefcountedConvention != ParameterConvention::Indirect_Inout && *singleRefcountedConvention != ParameterConvention::Indirect_InoutAliasable) { assert(bindings.empty()); assert(args.size() == 1); auto origSig = IGF.IGM.getSignature(origType); llvm::Value *forwarder = emitPartialApplicationForwarder(IGF.IGM, staticFn, fnContext != nullptr, origSig, origType, substType, outType, subs, nullptr, argConventions); forwarder = IGF.Builder.CreateBitCast(forwarder, IGF.IGM.Int8PtrTy); out.add(forwarder); llvm::Value *ctx = args.claimNext(); if (isIndirectFormalParameter(*singleRefcountedConvention)) ctx = IGF.Builder.CreateLoad(ctx, IGF.IGM.getPointerAlignment()); auto expectedClosureTy = outType->isNoEscape() ? IGF.IGM.OpaquePtrTy : IGF.IGM.RefCountedPtrTy; // We might get a struct containing a pointer e.g type <{ %AClass* }> if (ctx->getType() != expectedClosureTy) ctx = IGF.coerceValue(ctx, expectedClosureTy, IGF.IGM.DataLayout); out.add(ctx); if (outType->isNoEscape()) return StackAddress(); return {}; } // Store the context arguments on the heap/stack. assert(argValTypes.size() == argTypeInfos.size() && argTypeInfos.size() == argConventions.size() && ""argument info lists out of sync""); HeapLayout layout(IGF.IGM, LayoutStrategy::Optimal, argValTypes, argTypeInfos, /*typeToFill*/ nullptr, std::move(bindings)); llvm::Value *data; Optional stackAddr; if (args.empty() && layout.isKnownEmpty()) { if (outType->isNoEscape()) data = llvm::ConstantPointerNull::get(IGF.IGM.OpaquePtrTy); else data = IGF.IGM.RefCountedNull; } else { // Allocate a new object on the heap or stack. HeapNonFixedOffsets offsets(IGF, layout); if (outType->isNoEscape()) { stackAddr = IGF.emitDynamicAlloca( IGF.IGM.Int8Ty, layout.emitSize(IGF.IGM), Alignment(16)); stackAddr = stackAddr->withAddress(IGF.Builder.CreateBitCast( stackAddr->getAddress(), IGF.IGM.OpaquePtrTy)); data = stackAddr->getAddress().getAddress(); } else { auto descriptor = IGF.IGM.getAddrOfCaptureDescriptor(SILFn, origType, substType, subs, layout); data = IGF.emitUnmanagedAlloc(layout, ""closure"", descriptor, &offsets); } Address dataAddr = layout.emitCastTo(IGF, data); unsigned i = 0; // Store necessary bindings, if we have them. if (layout.hasBindings()) { auto &bindingsLayout = layout.getElement(i); Address bindingsAddr = bindingsLayout.project(IGF, dataAddr, offsets); layout.getBindings().save(IGF, bindingsAddr); ++i; } // Store the context arguments. for (unsigned end = layout.getElements().size(); i < end; ++i) { auto &fieldLayout = layout.getElement(i); auto &fieldTy = layout.getElementTypes()[i]; Address fieldAddr = fieldLayout.project(IGF, dataAddr, offsets); // We don't add non-constant function pointers to the explosion above, // so we need to handle them specially now. if (i == nonStaticFnIndex) { llvm::Value *fnPtr = fn.getPointer(); fnPtr = IGF.Builder.CreateBitCast(fnPtr, IGF.IGM.Int8PtrTy); IGF.Builder.CreateStore(fnPtr, fieldAddr); continue; } switch (argConventions[i]) { // Take indirect value arguments out of memory. case ParameterConvention::Indirect_In: case ParameterConvention::Indirect_In_Constant: case ParameterConvention::Indirect_In_Guaranteed: { auto addr = fieldLayout.getType().getAddressForPointer(args.claimNext()); fieldLayout.getType().initializeWithTake(IGF, fieldAddr, addr, fieldTy, isOutlined); break; } // Take direct value arguments and inout pointers by value. case ParameterConvention::Direct_Unowned: case ParameterConvention::Direct_Owned: case ParameterConvention::Direct_Guaranteed: case ParameterConvention::Indirect_Inout: case ParameterConvention::Indirect_InoutAliasable: cast(fieldLayout.getType()) .initialize(IGF, args, fieldAddr, isOutlined); break; } } } assert(args.empty() && ""unused args in partial application?!""); // Create the forwarding stub. auto origSig = IGF.IGM.getSignature(origType); llvm::Value *forwarder = emitPartialApplicationForwarder(IGF.IGM, staticFn, fnContext != nullptr, origSig, origType, substType, outType, subs, &layout, argConventions); forwarder = IGF.Builder.CreateBitCast(forwarder, IGF.IGM.Int8PtrTy); out.add(forwarder); out.add(data); return stackAddr; } /// Emit the block copy helper for a block. static llvm::Function *emitBlockCopyHelper(IRGenModule &IGM, CanSILBlockStorageType blockTy, const BlockStorageTypeInfo &blockTL){ // See if we've produced a block copy helper for this type before. // TODO // Create the helper. llvm::Type *args[] = { blockTL.getStorageType()->getPointerTo(), blockTL.getStorageType()->getPointerTo(), }; auto copyTy = llvm::FunctionType::get(IGM.VoidTy, args, /*vararg*/ false); // TODO: Give these predictable mangled names and shared linkage. auto func = llvm::Function::Create(copyTy, llvm::GlobalValue::InternalLinkage, ""block_copy_helper"", IGM.getModule()); func->setAttributes(IGM.constructInitialAttributes()); IRGenFunction IGF(IGM, func); if (IGM.DebugInfo) IGM.DebugInfo->emitArtificialFunction(IGF, func); // Copy the captures from the source to the destination. Explosion params = IGF.collectParameters(); auto dest = Address(params.claimNext(), blockTL.getFixedAlignment()); auto src = Address(params.claimNext(), blockTL.getFixedAlignment()); auto destCapture = blockTL.projectCapture(IGF, dest); auto srcCapture = blockTL.projectCapture(IGF, src); auto &captureTL = IGM.getTypeInfoForLowered(blockTy->getCaptureType()); captureTL.initializeWithCopy(IGF, destCapture, srcCapture, blockTy->getCaptureAddressType(), false); IGF.Builder.CreateRetVoid(); return func; } /// Emit the block copy helper for a block. static llvm::Function *emitBlockDisposeHelper(IRGenModule &IGM, CanSILBlockStorageType blockTy, const BlockStorageTypeInfo &blockTL){ // See if we've produced a block destroy helper for this type before. // TODO // Create the helper. auto destroyTy = llvm::FunctionType::get(IGM.VoidTy, blockTL.getStorageType()->getPointerTo(), /*vararg*/ false); // TODO: Give these predictable mangled names and shared linkage. auto func = llvm::Function::Create(destroyTy, llvm::GlobalValue::InternalLinkage, ""block_destroy_helper"", IGM.getModule()); func->setAttributes(IGM.constructInitialAttributes()); IRGenFunction IGF(IGM, func); assert(!func->hasFnAttribute(llvm::Attribute::SanitizeThread)); if (IGM.DebugInfo) IGM.DebugInfo->emitArtificialFunction(IGF, func); // Destroy the captures. Explosion params = IGF.collectParameters(); auto storage = Address(params.claimNext(), blockTL.getFixedAlignment()); auto capture = blockTL.projectCapture(IGF, storage); auto &captureTL = IGM.getTypeInfoForLowered(blockTy->getCaptureType()); captureTL.destroy(IGF, capture, blockTy->getCaptureAddressType(), false /*block storage code path: never outlined*/); IGF.Builder.CreateRetVoid(); return func; } /// Emit the block header into a block storage slot. void irgen::emitBlockHeader(IRGenFunction &IGF, Address storage, CanSILBlockStorageType blockTy, llvm::Constant *invokeFunction, CanSILFunctionType invokeTy, ForeignFunctionInfo foreignInfo) { auto &storageTL = IGF.getTypeInfoForLowered(blockTy).as(); Address headerAddr = storageTL.projectBlockHeader(IGF, storage); // // Initialize the ""isa"" pointer, which is _NSConcreteStackBlock. auto NSConcreteStackBlock = IGF.IGM.getModule()->getOrInsertGlobal(""_NSConcreteStackBlock"", IGF.IGM.ObjCClassStructTy); ApplyIRLinkage(IRLinkage::ExternalImport) .to(cast(NSConcreteStackBlock)); // // Set the flags. // - HAS_COPY_DISPOSE unless the capture type is POD uint32_t flags = 0; auto &captureTL = IGF.getTypeInfoForLowered(blockTy->getCaptureType()); bool isPOD = captureTL.isPOD(ResilienceExpansion::Maximal); if (!isPOD) flags |= 1 << 25; // - HAS_STRET, if the invoke function is sret assert(foreignInfo.ClangInfo); if (foreignInfo.ClangInfo->getReturnInfo().isIndirect()) flags |= 1 << 29; // - HAS_SIGNATURE flags |= 1 << 30; auto flagsVal = llvm::ConstantInt::get(IGF.IGM.Int32Ty, flags); // Collect the reserved and invoke pointer fields. auto reserved = llvm::ConstantInt::get(IGF.IGM.Int32Ty, 0); auto invokeVal = llvm::ConstantExpr::getBitCast(invokeFunction, IGF.IGM.FunctionPtrTy); // Build the block descriptor. ConstantInitBuilder builder(IGF.IGM); auto descriptorFields = builder.beginStruct(); const clang::ASTContext &ASTContext = IGF.IGM.getClangASTContext(); llvm::IntegerType *UnsignedLongTy = llvm::IntegerType::get(IGF.IGM.LLVMContext, ASTContext.getTypeSize(ASTContext.UnsignedLongTy)); descriptorFields.addInt(UnsignedLongTy, 0); descriptorFields.addInt(UnsignedLongTy, storageTL.getFixedSize().getValue()); if (!isPOD) { // Define the copy and dispose helpers. descriptorFields.add(emitBlockCopyHelper(IGF.IGM, blockTy, storageTL)); descriptorFields.add(emitBlockDisposeHelper(IGF.IGM, blockTy, storageTL)); } // Build the descriptor signature. descriptorFields.add(getBlockTypeExtendedEncoding(IGF.IGM, invokeTy)); // Create the descriptor. auto descriptor = descriptorFields.finishAndCreateGlobal(""block_descriptor"", IGF.IGM.getPointerAlignment(), /*constant*/ true); auto descriptorVal = llvm::ConstantExpr::getBitCast(descriptor, IGF.IGM.Int8PtrTy); // Store the block header. auto layout = IGF.IGM.DataLayout.getStructLayout(IGF.IGM.ObjCBlockStructTy); IGF.Builder.CreateStore(NSConcreteStackBlock, IGF.Builder.CreateStructGEP(headerAddr, 0, layout)); IGF.Builder.CreateStore(flagsVal, IGF.Builder.CreateStructGEP(headerAddr, 1, layout)); IGF.Builder.CreateStore(reserved, IGF.Builder.CreateStructGEP(headerAddr, 2, layout)); IGF.Builder.CreateStore(invokeVal, IGF.Builder.CreateStructGEP(headerAddr, 3, layout)); IGF.Builder.CreateStore(descriptorVal, IGF.Builder.CreateStructGEP(headerAddr, 4, layout)); } ",16266,True,2946.3027855265127,median "/* * benchmark.cc * LLAMA Graph Analytics * * Copyright 2014 * The President and Fellows of Harvard College. * * Copyright 2014 * Oracle Labs. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * 3. Neither the name of the University 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 UNIVERSITY 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 UNIVERSITY 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 #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include ""benchmarks/avg_teen_cnt.h"" #include ""benchmarks/bc_adj.h"" #include ""benchmarks/bc_random.h"" #include ""benchmarks/bfs.h"" #include ""benchmarks/pagerank.h"" #include ""benchmarks/sssp.h"" #include ""benchmarks/tarjan_scc.h"" #include ""benchmarks/triangle_counting.h"" #include ""tests/delete_edges.h"" #include ""tests/delete_nodes.h"" #include ""tools/cross_validate.h"" #include ""tools/level_spread.h"" #include ""tools/degree_distribution.h"" #include ""tools/flatten.h"" #include ""tools/dump.h"" #include ""tools/property_stats.h"" /* * Customize the benchmark using the following preprocessor directives: * * BENCHMARK_WRITABLE * BENCHMARK_TASK_ID * BENCHMARK_CONTINUOUS_LOAD * DO_CP * TEST_CXX_ITER */ //==========================================================================// // Global Initialization & Sanity Checks // //==========================================================================// //#define BENCHMARK_WRITABLE //#define BENCHMARK_CONTINUOUS_LOAD //#define DO_CP #define TEST_CXX_ITER #ifdef LL_STREAMING # ifndef BENCHMARK_CONTINUOUS_LOAD # define BENCHMARK_CONTINUOUS_LOAD # endif #endif #ifdef BENCHMARK_WRITABLE typedef ll_writable_graph benchmarkable_graph_t; #define benchmarkable_graph(g) (g) #else typedef ll_mlcsr_ro_graph benchmarkable_graph_t; #define benchmarkable_graph(g) ((g).ro_graph()) #endif #ifdef BENCHMARK_WRITABLE # ifndef LL_DELETIONS # warning ""Attempting to use BENCHMARK_WRITABLE without LL_DELETIONS"" # endif # ifdef LL_STREAMING # error ""Using BENCHMARK_WRITABLE with LL_STREAMING"" # endif #endif #ifdef BENCHMARK_CONTINUOUS_LOAD # ifndef LL_STREAMING # error ""BENCHMARK_CONTINUOUS_LOAD requires LL_STREAMING"" # endif #endif #ifdef LL_S_SINGLE_SNAPSHOT # ifndef BENCHMARK_CONTINUOUS_LOAD # error ""LL_S_SINGLE_SNAPSHOT requires BENCHMARK_CONTINUOUS_LOAD"" # endif #endif //==========================================================================// // Testing // //==========================================================================// template node_t __attribute__ ((noinline)) TEST_FUNCTION(EXP_GRAPH& G_exp) { node_t u = 0x3; node_t nothing = 0; if (u >= G_exp.max_nodes()) return nothing; ll_edge_iterator iter; G_exp.out_iter_begin(iter, u); for (edge_t v_idx = G_exp.out_iter_next(iter); v_idx != LL_NIL_EDGE; v_idx = G_exp.out_iter_next(iter)) { nothing ^= LL_ITER_OUT_NEXT_NODE(G_exp, iter, v_idx); } /*typename EXP_GRAPH::iterator iter; for (iter = G_exp.begin(u); iter != G_exp.end(); ++iter) { nothing ^= *iter; }*/ return nothing; } //==========================================================================// // The Tested Simple OLTP Functions // //==========================================================================// template void w_test(EXP_W_GRAPH& G) { printf(""\\n\\nTEST START\\n""); G.tx_begin(); edge_t e1 = G.add_edge(0, 1); edge_t e2 = G.add_edge(1, 2); printf(""%lld --> %lld\\n"", G.src(e1), G.dst(e1)); printf(""%lld --> %lld\\n"", G.src(e2), G.dst(e2)); node_t n = 0; printf(""TEST%3u:"", (unsigned) n); ll_edge_iterator iter = G.out(n); for (edge_t v_idx = G.iter_next(iter); v_idx != LL_NIL_EDGE; v_idx = G.iter_next(iter)) { node_t v = LL_ITER_OUT_NEXT_NODE(G, iter, v_idx); printf("" %7u"", (unsigned) v); } printf(""\\n""); G.tx_commit(); printf(""DID NOT CRASH :)\\n""); } //==========================================================================// // Supporting Functions // //==========================================================================// /** * Print time in appropriate units * * @param f the output file * @param prefix the prefix * @param t the time in ms * @param newline true to print the newline */ static void print_time(FILE* f, const char* prefix, double t, bool newline=true) { fprintf(f, ""%s%0.3lf seconds"", prefix, t/1000.0); if (t > 45000) fprintf(f, "" (%0.2lf min)"", t/60000.0); if (newline) fprintf(f, ""\\n""); } /** * Print time and confidence in appropriate units * * @param f the output file * @param prefix the prefix * @param t the time in ms * @param c the confidence interval size * @param newline true to print the newline */ static void print_time_and_confidence(FILE* f, const char* prefix, double t, double c, bool newline=true) { fprintf(f, ""%s%0.3lf +- %0.3lf seconds"", prefix, t/1000.0, c/1000.0); if (t > 45000) fprintf(f, "" (%0.2lf +- %0.2lf min)"", t/60000.0, c/60000.0); if (newline) fprintf(f, ""\\n""); } #if defined(__linux__) /** * The I/O info */ struct io_stat { size_t io_rchar; size_t io_wchar; size_t io_syscr; size_t io_syscw; size_t io_read_bytes; size_t io_write_bytes; size_t io_cancelled_write_bytes; }; /** * Get the I/O info about the process * * @param io the pointer to the io_stat struct * @return 0 if okay, -1 on error */ int getiostat(struct io_stat* io) { memset(io, 0, sizeof(io_stat)); FILE* f = fopen(""/proc/self/io"", ""r""); if (!f) return -1; char* line = NULL; size_t len = 0; ssize_t read; while ((read = getline(&line, &len, f)) != -1) { char* p = strchr(line, ':'); if (p == NULL) continue; *(p++) = '\\0'; while (*p != '\\0' && isspace(*p)) p++; if (strcmp(line, ""rchar"") == 0) io->io_rchar = atol(p); if (strcmp(line, ""wchar"") == 0) io->io_wchar = atol(p); if (strcmp(line, ""syscr"") == 0) io->io_syscr = atol(p); if (strcmp(line, ""syscw"") == 0) io->io_syscw = atol(p); if (strcmp(line, ""read_bytes"") == 0) io->io_read_bytes = atol(p); if (strcmp(line, ""write_bytes"") == 0) io->io_write_bytes = atol(p); if (strcmp(line, ""cancelled_write_bytes"") == 0) io->io_cancelled_write_bytes = atol(p); } if (line) free(line); fclose(f); return 0; } #endif /** * Statistics, counters, and the corresponding temporary contexts */ class ll_benchmark_stats { friend class ll_benchmark_counter; public: time_t start_time; struct tm tm_start_time; long maxrss_start; long maxrss_loaded; std::vector load_times; std::vector load_pull_times; std::vector load_cp_times; std::vector advance_window_times; std::vector batch_times; std::vector runtimes; std::vector cpu_times; std::vector cpu_user_times; std::vector cpu_sys_times; std::vector cpu_util; std::vector major_faults; std::vector in_blocks; std::vector out_blocks; std::vector io_rchar; std::vector io_wchar; std::vector io_syscr; std::vector io_syscw; std::vector io_read_bytes; std::vector io_write_bytes; std::vector io_cancelled_write_bytes; const ll_stream_stats* stream_stats; private: // Benchmark stats #if defined(__linux__) struct io_stat _b_io_start; #endif struct rusage _b_ru_start; double _benchmark_t_start; // Load stats double _l_t_start; double _l_t_pull_start; double _l_t_cp_start; // Delete stats double _a_t_start; // Other stats double _b_t_start; public: /** * Create an instance of ll_benchmark_stats */ ll_benchmark_stats(void) { struct rusage ru_start; getrusage(RUSAGE_SELF, &ru_start); maxrss_start = ru_start.ru_maxrss; maxrss_loaded = maxrss_start; // Zero this relative to maxrss_start start_time = time(NULL); localtime_r(&start_time, &tm_start_time); } /** * Start counters before benchmark */ void before_benchmark(void) { #if defined(__linux__) getiostat(&_b_io_start); #endif getrusage(RUSAGE_SELF, &_b_ru_start); _benchmark_t_start = ll_get_time_ms(); } /** * Stop counters after benchmark */ void after_benchmark(void) { double t = ll_get_time_ms() - _benchmark_t_start; struct rusage ru_end; getrusage(RUSAGE_SELF, &ru_end); #if defined(__linux__) struct io_stat io_end; getiostat(&io_end); #endif runtimes.push_back(t); cpu_times.push_back(ll_timeval_to_ms(ru_end.ru_utime) + ll_timeval_to_ms(ru_end.ru_stime) - ll_timeval_to_ms(_b_ru_start.ru_utime) - ll_timeval_to_ms(_b_ru_start.ru_stime)); cpu_user_times.push_back(ll_timeval_to_ms(ru_end.ru_utime) - ll_timeval_to_ms(_b_ru_start.ru_utime)); cpu_sys_times.push_back(ll_timeval_to_ms(ru_end.ru_stime) - ll_timeval_to_ms(_b_ru_start.ru_stime)); cpu_util.push_back((cpu_times[cpu_times.size()-1] / omp_get_max_threads()) / t); major_faults.push_back(ru_end.ru_majflt - _b_ru_start.ru_majflt); in_blocks.push_back(ru_end.ru_inblock - _b_ru_start.ru_inblock); out_blocks.push_back(ru_end.ru_oublock - _b_ru_start.ru_oublock); #if defined(__linux__) io_rchar.push_back(io_end.io_rchar - _b_io_start.io_rchar); io_wchar.push_back(io_end.io_wchar - _b_io_start.io_wchar); io_syscr.push_back(io_end.io_syscr - _b_io_start.io_syscr); io_syscw.push_back(io_end.io_syscw - _b_io_start.io_syscw); io_read_bytes.push_back(io_end.io_read_bytes - _b_io_start.io_read_bytes); io_write_bytes.push_back(io_end.io_write_bytes - _b_io_start.io_write_bytes); io_cancelled_write_bytes.push_back( io_end.io_cancelled_write_bytes - _b_io_start.io_cancelled_write_bytes); #endif } /** * Start counters before batch */ void before_batch(void) { _b_t_start = ll_get_time_ms(); } /** * Stop counters after batch */ void after_batch(void) { double t = ll_get_time_ms() - _b_t_start; batch_times.push_back(t); } /** * Start counters before load */ void before_load(void) { _l_t_start = ll_get_time_ms(); } /** * Stop counters after load */ void after_load(void) { double t = ll_get_time_ms() - _l_t_start; load_times.push_back(t); struct rusage r_loaded; getrusage(RUSAGE_SELF, &r_loaded); maxrss_loaded = r_loaded.ru_maxrss; } /** * Start counters before load's pull phase */ void before_load_pull(void) { _l_t_pull_start = ll_get_time_ms(); } /** * Stop counters after load's pull phase */ void after_load_pull(void) { double t = ll_get_time_ms() - _l_t_pull_start; load_pull_times.push_back(t); } /** * Start counters before load's CP phase */ void before_load_cp(void) { _l_t_cp_start = ll_get_time_ms(); } /** * Stop counters after load's CP phase */ void after_load_cp(void) { double t = ll_get_time_ms() - _l_t_cp_start; load_cp_times.push_back(t); } /** * Start counters before advancing a window */ void before_advance_window(void) { _a_t_start = ll_get_time_ms(); } /** * Stop counters after advancing a window */ void after_advance_window(void) { double t = ll_get_time_ms() - _a_t_start; advance_window_times.push_back(t); } /** * Add an advance window time to the log * * @param t the time in ms */ void report_advance_window_ms(double t) { advance_window_times.push_back(t); } /** * Print the statistics * * @param f the output file */ void print_stats(FILE* f = stdout) { #if !defined(BENCHMARK_CONTINUOUS_LOAD) if (load_times.size() > 0) { fprintf(f, ""\\nLOAD\\n""); # ifdef LL_STREAMING print_time(f, ""Load Time : "", ll_mean(load_times), false); print_time(f, "" each, "", ll_sum(load_times), false); fprintf(f, "" total\\n""); # else print_time(f, ""Load Time : "", ll_mean(load_times)); # endif fprintf(f, ""Memory : %0.2lf MB\\n"", (maxrss_loaded - maxrss_start) / 1024.0); } #endif if (runtimes.size() > 0) { if (runtimes.size() == 1) { fprintf(f, ""\\nTIME\\n""); print_time(f, ""Time : "", ll_sum(runtimes)); print_time(f, ""User Time : "", ll_sum(cpu_user_times)); print_time(f, ""System Time: "", ll_sum(cpu_sys_times)); print_time(f, ""CPU Time : "", ll_sum(cpu_times)); fprintf(f, ""CPU Util. : %0.2lf%%\\n"", 100*ll_mean(cpu_util)); fprintf(f, ""\\nRESOURCE USAGE\\n""); fprintf(f, ""Mjr Faults : %ld\\n"", ll_sum(major_faults)); fprintf(f, ""In Blocks : %ld\\n"", ll_sum(in_blocks)); fprintf(f, ""Out Blocks : %ld\\n"", ll_sum(out_blocks)); #if defined(__linux__) fprintf(f, ""In Bytes : %ld (%0.2lf GB)\\n"", ll_sum(io_read_bytes), ll_sum(io_read_bytes) / (1024.0*1024.0*1024.0)); fprintf(f, ""Out Bytes : %ld (%0.2lf GB)\\n"", ll_sum(io_write_bytes), ll_sum(io_write_bytes) / (1024.0*1024.0*1024.0)); #endif } else { fprintf(f, ""\\nTIME\\n""); #ifdef LL_STREAMING print_time_and_confidence(f, ""Time : "", ll_mean(runtimes), ll_c95(runtimes), false); print_time(f, "" each, "", ll_sum(runtimes), false); fprintf(f, "" total\\n""); #else print_time_and_confidence(f, ""Time : "", ll_mean(runtimes), ll_c95(runtimes)); #endif print_time_and_confidence(f, ""User Time : "", ll_mean(cpu_user_times), ll_c95(cpu_user_times)); print_time_and_confidence(f, ""System Time: "", ll_mean(cpu_sys_times), ll_c95(cpu_sys_times)); print_time_and_confidence(f, ""CPU Time : "", ll_mean(cpu_times), ll_c95(cpu_times)); fprintf(f, ""CPU Util. : %0.2lf +- %0.2lf%%\\n"", 100*ll_mean(cpu_util), 100*ll_c95(cpu_util)); fprintf(f, ""\\nRESOURCE USAGE\\n""); fprintf(f, ""Mjr Faults : %0.2lf +- %0.2lf\\n"", ll_mean(major_faults), ll_c95(major_faults)); fprintf(f, ""In Blocks : %0.2lf +- %0.2lf\\n"", ll_mean(in_blocks), ll_c95(in_blocks)); fprintf(f, ""Out Blocks : %0.2lf +- %0.2lf\\n"", ll_mean(out_blocks), ll_c95(out_blocks)); #if defined(__linux__) fprintf(f, ""In Bytes : %0.2lf +- %0.2lf "" ""(%0.2lf +- %0.2lf GB)\\n"", ll_mean(io_read_bytes), ll_c95(io_read_bytes), ll_mean(io_read_bytes) / (1024.0*1024.0*1024.0), ll_c95(io_read_bytes) / (1024.0*1024.0*1024.0)); fprintf(f, ""Out Bytes : %0.2lf +- %0.2lf "" ""(%0.2lf +- %0.2lf GB)\\n"", ll_mean(io_write_bytes), ll_c95(io_write_bytes), ll_mean(io_write_bytes) / (1024.0*1024.0*1024.0), ll_c95(io_write_bytes) / (1024.0*1024.0*1024.0)); #endif } } struct rusage ru; getrusage(RUSAGE_SELF, &ru); fprintf(f, ""Max RSS : %0.2lf MB\\n"", ru.ru_maxrss / 1024.0); fprintf(f, ""\\n""); fflush(f); } /** * Save the statistics to a file * * @param G the graph * @param representation the representation/configuration identifier * @param task the task identifier */ template void save_stats(Graph& G, const char* representation, const char* task) { // Generate the file name char date_time[64]; snprintf(date_time, 64, ""%04d%02d%02d-%02d%02d%02d"", tm_start_time.tm_year + 1900, tm_start_time.tm_mon + 1, tm_start_time.tm_mday, tm_start_time.tm_hour, tm_start_time.tm_min, tm_start_time.tm_sec); std::string file_name = representation; file_name += ""__""; file_name += task; file_name += ""__""; file_name += date_time; file_name += "".csv""; // Open the file FILE* f = fopen(file_name.c_str(), ""w""); if (f == NULL) { perror(""fopen""); abort(); } // Write the meta-data std::ostringstream header; std::ostringstream data; data << std::setprecision(6) << std::fixed; header << ""representation,specialized""; data << representation; #if BENCHMARK_TASK_ID >= 0 data << "",true""; #else data << "",false""; #endif header << "",year,month,day,hour,min,sec""; data << "","" << tm_start_time.tm_year + 1900; data << "","" << tm_start_time.tm_mon + 1; data << "","" << tm_start_time.tm_mday; data << "","" << tm_start_time.tm_hour; data << "","" << tm_start_time.tm_min; data << "","" << tm_start_time.tm_sec; header << "",load_time""; if (load_times.empty()) data << "",0""; else data << "","" << ll_mean(load_times); header << "",graph_max_nodes,graph_levels""; data << G.max_nodes(); data << G.num_levels(); fprintf(f, ""%s\\n%s\\n\\n"", header.str().c_str(), data.str().c_str()); // Write the summary results header.str(""""); data.str(""""); header << ""name""; data << task; header << "",runtime_ms,stdev_ms,min_ms,max_ms,c95_ms""; data << "","" << ll_mean(runtimes); data << "","" << ll_stdev(runtimes); data << "","" << ll_min(runtimes); data << "","" << ll_max(runtimes); data << "","" << ll_c95(runtimes); header << "",cpu_ms,cpu_util,major_faults,in_blocks,out_blocks""; data << "","" << ll_mean(cpu_times); data << "","" << ll_mean(cpu_util); data << "","" << ll_mean(major_faults); data << "","" << ll_mean(in_blocks); data << "","" << ll_mean(out_blocks); fprintf(f, ""%s\\n%s\\n\\n"", header.str().c_str(), data.str().c_str()); // Write the individual operations header.str(""""); header << ""id,runtime_ms,cpu_ms,cpu_util""; header << "",major_faults,in_blocks,out_blocks""; fprintf(f, ""%s\\n"", header.str().c_str()); for (size_t i = 0; i < runtimes.size(); i++) { data.str(""""); data << i << "","" << runtimes[i]; data << "","" << cpu_times[i]; data << "","" << cpu_util[i]; data << "","" << major_faults[i]; data << "","" << in_blocks[i]; data << "","" << out_blocks[i]; fprintf(f, ""%s\\n"", data.str().c_str()); } // Close fclose(f); } }; /** * The benchmark repeat count and current state */ class ll_benchmark_counter { public: size_t benchmark_count; size_t current_iteration; // within benchmark_count size_t max_batches; size_t current_batch; bool print_progress; bool verbose; protected: double last_st; public: /** * Create an instance of ll_benchmark_counter */ ll_benchmark_counter(void) { benchmark_count = 1; current_iteration = 0; max_batches = 0; current_batch = 0; print_progress = true; verbose = false; last_st = 0; } /** * Print the stuff before a batch */ void print_before_batch() { if (print_progress && verbose) { fprintf(stderr, ""\\r%5lu: Loading..."", current_batch+1); } } /** * Print the stuff after a batch * * @param stats the stats */ void print_after_batch_load(const ll_benchmark_stats& stats) { if (print_progress && verbose) { fprintf(stderr, ""\\r%5lu: \\b\\b\\b\\b\\b\\b\\b\\b\\b\\b"", current_batch); #ifndef BENCHMARK_CONTINUOUS_LOAD if (benchmark_count > 1) { #endif double load_time = stats.load_times[stats.load_times.size()-1]; double load_pull = stats.load_pull_times[stats.load_pull_times.size()-1]; double load_cp = stats.load_cp_times.empty() ? 0 : stats.load_cp_times[stats.load_cp_times.size()-1]; double load_advance = stats.advance_window_times.empty() ? 0 : stats.advance_window_times [stats.advance_window_times.size()-1]; print_time(stderr, ""Load: "", load_time, false); fprintf(stderr, "" (%0.3lf pull, %0.3lf cp, %0.3lf advance)\\n"", load_pull/1000.0, load_cp/1000.0, load_advance/1000.0); #ifndef BENCHMARK_CONTINUOUS_LOAD } #endif } } /** * Print the stuff before a benchmark */ void print_before_benchmark() { if (print_progress) { if (verbose) { #ifdef LL_STREAMING if (benchmark_count > 1) fprintf(stderr, ""\\r%5lu - %lu/%lu: "", current_batch, current_iteration+1, benchmark_count); else fprintf(stderr, ""\\r%5lu: "", current_batch); #else fprintf(stderr, ""\\r%3lu/%lu: "", current_iteration+1, benchmark_count); #endif } else { fprintf(stderr, "".""); if ((current_iteration + 1) % 10 == 0) { fprintf(stderr, ""%lu"", current_iteration + 1); } } } } /** * Print the stuff after a benchmark * * @param stats the stats */ void print_after_benchmark(const ll_benchmark_stats& stats) { double now = ll_get_time_ms(); (void) now; if (print_progress && verbose) { double t = stats.runtimes.empty() ? 0 : stats.runtimes[stats.runtimes.size()-1]; #ifdef LL_STREAMING # ifndef BENCHMARK_CONTINUOUS_LOAD if (current_iteration == 0 && benchmark_count == 1) { double load_time = stats.load_times[stats.load_times.size()-1]; double load_pull = stats.load_pull_times[stats.load_pull_times.size()-1]; double load_cp = stats.load_cp_times.empty() ? 0 : stats.load_cp_times[stats.load_cp_times.size()-1]; double load_advance = stats.advance_window_times.empty() ? 0 : stats.advance_window_times [stats.advance_window_times.size()-1]; print_time(stderr, ""Load: "", load_time, false); fprintf(stderr, "" (%0.3lf pull, %0.3lf cp, %0.3lf advance)"", load_pull/1000.0, load_cp/1000.0, load_advance/1000.0); print_time(stderr, "", Run: "", t); } else { print_time(stderr, ""Run: "", t); } # else double load_advance = stats.advance_window_times.empty() ? 0 : stats.advance_window_times [stats.advance_window_times.size()-1]; double st = now - stats.stream_stats->ss_start; double int_ms = st - last_st; if (int_ms < 0) int_ms = 1e+30; double batch_time = stats.batch_times.empty() ? 0 : stats.batch_times[stats.batch_times.size()-1]; fprintf(stderr, ""%6.2lf s, %6.3lf Mreq, %0.3lf Mreq/s, "" ""%0.3lf Mreq queued, %0.3lf adv, %0.3lf run, "" ""%0.3lf batch\\n"", st / 1000.0, stats.stream_stats->ss_requests_processed / 1000000.0, stats.stream_stats->ss_last_batch_requests / 1000.0 / int_ms, stats.stream_stats->num_outstanding_requests() / 1000000.0, load_advance / 1000.0, t / 1000.0, batch_time / 1000.0); last_st = st; # endif #else print_time(stderr, """", t); #endif } } /** * Print stuff at the end */ void print_at_end() { if (print_progress && !verbose) { fprintf(stderr, ""\\n""); } } }; //==========================================================================// // Things to run: Benchmarks, tools, and tests // //==========================================================================// struct ll_runnable_thing { const char* rt_class; const char* rt_identifier; const char* rt_name; bool rt_needs_reverse_edges; }; static ll_runnable_thing g_runnable_things[] = { { ""ll_b_avg_teen_cnt"" , ""avg_teen_cnt"" , ""Average teen friends count"" , true }, { ""ll_b_bc_adj"" , ""bc_adj"" , ""Betweenness centrality - exact"" , false }, { ""ll_b_bc_random"" , ""bc_random"" , ""Betweenness centrality - randomized"" , false }, { ""ll_b_bfs"" , ""bfs_count"" , ""Breadth-first search - count vertices"" , false }, { ""ll_b_pagerank_pull_float"" , ""pagerank"" , ""PageRank - pull version"" , true }, { ""ll_b_pagerank_push_float"" , ""pagerank_push"" , ""PageRank - push version"" , false }, { ""ll_b_sssp_weighted"" , ""sssp_weighted"" , ""Weighted SSSP"" , false }, { ""ll_b_sssp_unweighted_bfs"" , ""sssp_unweighted"" , ""Unweighted SSSP - BFS"" , false }, { ""ll_b_tarjan_scc"" , ""tarjan_scc"" , ""Tarjan's SCC algorithm"" , false }, { ""ll_b_triangle_counting_LI"" , ""tc_i"" , ""Triangle counting for graph loaded with -I"" , true }, { ""ll_b_triangle_counting_LOD"", ""tc_od"" , ""Triangle counting for graph loaded with -OD"" , false }, { ""ll_b_triangle_counting_LU"" , ""tc_u"" , ""Triangle counting for graph loaded with -U"" , false }, { ""ll_t_delete_edges"" , ""t:delete_edges"" , ""Regression test: delete edges"" , true }, { ""ll_t_delete_nodes"" , ""t:delete_nodes"" , ""Regression test: delete nodes"" , true }, { ""ll_t_level_spread"" , ""level_spread"" , ""Compute the level spread"" , false }, { ""ll_t_degree_distribution"" , ""degree_distribution"" , ""Compute the degree distribution"" , false }, { ""ll_t_flatten"" , ""flatten"" , ""Flatten (fully merge) the graph"" , false }, { ""ll_t_dump"" , ""dump"" , ""Dump the graph"" , false }, { ""ll_t_edge_property_stats"" , ""edge_prop_stats"" , ""Edge property stats"" , false }, { ""ll_b_pagerank_pull_double"" , ""pagerank_double"" , ""PageRank - pull version, double"" , true }, { ""ll_b_pagerank_push_double"" , ""pagerank_double_push"" , ""PageRank - push version, double"" , false }, { ""ll_b_sssp_unweighted_iter"" , ""sssp_unweighted_iter"" , ""Unweighted SSSP - iterative"" , false }, { NULL, NULL, NULL, false } }; #ifndef BENCHMARK_TASK_ID #define BENCHMARK_TASK_ID -1 #endif #ifndef BENCHMARK_TASK_STR #define BENCHMARK_TASK_STR NULL #endif #define LL_RT_COND_CREATE(var, index, class_name, ...) { \\ assert(strcmp(g_runnable_things[index].rt_class, #class_name) == 0); \\ if (strcmp(var, #class_name) == 0) \\ benchmark = new class_name(__VA_ARGS__); \\ } #define LL_RT_COND_CREATE_EXT(var, index, class_name, template_parameter, ...) { \\ assert(strcmp(g_runnable_things[index].rt_class, #class_name) == 0); \\ if (strcmp(var, #class_name) == 0) \\ benchmark = new class_name(__VA_ARGS__); \\ } //==========================================================================// // The Command-Line Arguments // //==========================================================================// static const char* SHORT_OPTIONS = ""c:C:d:DIhl:Ln:No:Op:P:r:R:t:ST:UvX:"" IF_LL_STREAMING(""B:M:W:"") #ifdef BENCHMARK_CONTINUOUS_LOAD ""E:F:"" #endif #ifndef LL_STREAMING ""m:"" #endif ; static struct option LONG_OPTIONS[] = { #ifdef LL_STREAMING {""batch"" , required_argument, 0, 'B'}, #endif {""count"" , required_argument, 0, 'c'}, {""compare"" , required_argument, 0, 'C'}, {""database"" , required_argument, 0, 'd'}, {""deduplicate"" , no_argument , 0, 'D'}, #ifdef BENCHMARK_CONTINUOUS_LOAD {""target-rate"" , required_argument, 0, 'E'}, {""freeze-int"" , required_argument, 0, 'F'}, #endif {""help"" , no_argument, 0, 'h'}, {""in-edges"" , no_argument, 0, 'I'}, {""level"" , required_argument, 0, 'l'}, {""levels"" , required_argument, 0, 'l'}, {""load"" , no_argument, 0, 'L'}, #ifndef LL_STREAMING {""max-edges"" , required_argument, 0, 'm'}, #endif #ifdef LL_STREAMING {""max-batches"" , required_argument, 0, 'M'}, #endif {""num-iters"" , required_argument, 0, 'n'}, {""no-properties"", no_argument, 0, 'N'}, {""output"" , required_argument, 0, 'o'}, {""print"" , required_argument, 0, 'p'}, {""partial"" , required_argument, 0, 'P'}, {""run"" , required_argument, 0, 'r'}, {""root"" , required_argument, 0, 'R'}, {""save-stats"" , no_argument, 0, 'S'}, {""threads"" , required_argument, 0, 't'}, {""temp-dir"" , required_argument, 0, 'T'}, {""undir-double"" , no_argument, 0, 'U'}, {""undir-order"" , no_argument, 0, 'O'}, {""verbose"" , no_argument, 0, 'v'}, {""xs-buffer"" , required_argument, 0, 'X'}, #ifdef LL_STREAMING {""window"" , required_argument, 0, 'W'}, #endif {0, 0, 0, 0} }; /** * Print the usage information * * @param arg0 the first element in the argv array */ static void usage(const char* arg0) { char* s = strdup(arg0); char* p = basename(s); fprintf(stderr, ""Usage: %s [OPTIONS] INPUT_FILE [INPUT_FILE...]\\n\\n"", p); free(s); fprintf(stderr, ""Options:\\n""); #ifdef LL_STREAMING fprintf(stderr, "" -B, --batch N Set the batch size for advancing the stream\\n""); #endif fprintf(stderr, "" -c, --count N Run the given benchmark operation N times\\n""); fprintf(stderr, "" -C, --compare FILE Compare graph to the one in the given file\\n""); fprintf(stderr, "" -d, --database DIR Set the database directory\\n""); fprintf(stderr, "" -D, --deduplicate Deduplicate edges within level while loading\\n""); #ifdef BENCHMARK_CONTINUOUS_LOAD fprintf(stderr, "" -E, --target-rate N Set the target rate for continuous load (events/sec.)\\n""); fprintf(stderr, "" -F, --freeze-int N Set the interval for freezing the writable state (sec.)\\n""); #endif fprintf(stderr, "" -h, --help Show this usage information and exit\\n""); fprintf(stderr, "" -I, --in-edges Load or generate in-edges\\n""); fprintf(stderr, "" -l, --level N[-M] Set the level or the min and max levels\\n""); #ifdef LL_PERSISTENCE fprintf(stderr, "" -L, --load Load the input files into the database\\n""); #endif #ifndef LL_STREAMING fprintf(stderr, "" -m, --max-edges N Set the maximum number of edges to load\\n""); #endif #ifdef LL_STREAMING fprintf(stderr, "" -M, --max-batches N Set the maximum number of batches\\n""); #endif fprintf(stderr, "" -n, --num-iters N Set the number of iterations (if applicable)\\n""); fprintf(stderr, "" -N, --no-properties Do not load (ingest) properties\\n""); fprintf(stderr, "" -o, --output FILE Write the query output to a file\\n""); fprintf(stderr, "" -O, --undir-order Load undirected by ordering all edges\\n""); fprintf(stderr, "" -p, --print N[-M] Print edges adjacent to one or more nodes\\n""); fprintf(stderr, "" -P, --partial N/M Split the input file to M parts and load N-th part\\n""); #if BENCHMARK_TASK_ID < 0 fprintf(stderr, "" -r, --run TASK Run a task\\n""); #endif fprintf(stderr, "" -R, --root N Set the root node for SSSP and BFS\\n""); fprintf(stderr, "" -S, --save-stats Save the execution statistics\\n""); fprintf(stderr, "" -t, --threads N Set the number of threads\\n""); fprintf(stderr, "" -T, --temp DIR Add a temporary directory\\n""); fprintf(stderr, "" -U, --undir-double Load undirected by doubling all edges\\n""); fprintf(stderr, "" -v, --verbose Enable verbose output\\n""); #ifdef LL_STREAMING fprintf(stderr, "" -W, --window N Set the sliding window size to be N batches\\n""); #endif fprintf(stderr, "" -X, --xs-buffer GB Set the external sort buffer size, in GB\\n""); fprintf(stderr, ""\\nTasks (run using the --run/-r option):\\n""); int longest_identifier_length = 0; for (ll_runnable_thing* rt = g_runnable_things; rt->rt_class != NULL; rt++) { int l = (int) strlen(rt->rt_identifier); if (l > longest_identifier_length) longest_identifier_length = l; } std::vector l; char buffer[256]; for (ll_runnable_thing* rt = g_runnable_things; rt->rt_class != NULL; rt++) { snprintf(buffer, 255, "" %-*s %s"", longest_identifier_length, rt->rt_identifier, rt->rt_name); l.push_back(buffer); } std::stable_sort(l.begin(), l.end()); for (size_t i = 0; i < l.size(); i++) { fprintf(stderr, ""%s\\n"", l[i].c_str()); } } //==========================================================================// // Benchmark Components // //==========================================================================// #ifndef LL_S_DIRECT /** * Load a part of the graph using the writable representation * * @param graph the writable graph * @param data_source the data source * @param loader_config the loader configuration * @param batch_size the batch size (the max number of edges to load) * @param window_size the streaming window size (if streaming) * @param stats the stats * @return true if the graph was loaded */ bool load_batch_via_writable_graph(ll_writable_graph& graph, ll_data_source& data_source, const ll_loader_config& loader_config, size_t batch_size, ssize_t window_size, ll_benchmark_stats& stats) { stats.before_load(); stats.before_load_pull(); bool loaded = data_source.pull(&graph, batch_size); stats.after_load_pull(); if (!loaded) return false; stats.before_load_cp(); graph.checkpoint(&loader_config); stats.after_load_cp(); #ifdef LL_STREAMING stats.before_advance_window(); if (window_size > 0 && graph.num_levels() >= (size_t) window_size) { graph.set_min_level(graph.num_levels() - window_size); if (graph.num_levels() >= (size_t) window_size + 3) { graph.delete_level(graph.num_levels() - window_size - 3); } } stats.after_advance_window(); #endif stats.after_load(); return true; } #endif /** * Run the benchmark on the given graph * * @param graph the graph * @param benchmark the benchmark * @param stats the stats * @return the return code */ template double run_benchmark(Graph& graph, ll_benchmark* benchmark, ll_benchmark_stats& stats) { benchmark->initialize(&graph); stats.before_benchmark(); double return_d = benchmark->run(); stats.after_benchmark(); double r_d_adj = benchmark->finalize(); if (!std::isnan(r_d_adj)) return_d = r_d_adj; return return_d; } //==========================================================================// // SLOTH Customization // //==========================================================================// /** * The customized sliding window driver */ class ll_benchmark_sliding_window_driver : public ll_sliding_window_driver { ll_benchmark* _benchmark; ll_benchmark_counter* _counter; ll_benchmark_stats* _stats; double _last_return_value; public: /** * Create an instance of class ll_benchmark_sliding_window_driver * * @param database the database * @param data_source the data source * @param stream_config the streaming configuration * @param window_config the sliding window configuration * @param loader_config the loader configuration * @param window the sliding window size * @param num_threads the number of threads (-1 = all, must be >= 2) * @param benchmark the benchmark * @param counter the benchmark counter * @param stats the benchmark stats */ ll_benchmark_sliding_window_driver(ll_database* database, ll_data_source* data_source, const ll_stream_config* stream_config, const ll_sliding_window_config* window_config, const ll_loader_config* loader_config, int num_threads, ll_benchmark* benchmark, ll_benchmark_counter* counter, ll_benchmark_stats* stats) : ll_sliding_window_driver(database, data_source, stream_config, window_config, loader_config, num_threads) { _benchmark = benchmark; _counter = counter; _stats = stats; _last_return_value = 0; _stats->stream_stats = &stream_stats(); } /** * Destroy the instance */ virtual ~ll_benchmark_sliding_window_driver() {} /** * Get the last return value * * @return the last return value */ inline double last_return_value() { return _last_return_value; } protected: /** * Callback for before starting a batch in an execution thread */ virtual void before_batch() { _counter->current_batch = batch(); _stats->before_batch(); } /** * Callback for after completing a batch in an execution thread */ virtual void after_batch() { _stats->report_advance_window_ms(last_advance_time_ms()); _stats->after_batch(); _counter->print_after_benchmark(*_stats); } /** * Callback for skipping a round of computation (e.g. if the graph is not * ready) */ virtual void skipped() { _counter->current_iteration = _counter->benchmark_count - 1; _counter->print_before_benchmark(); } /** * Callback for being behind * * @param ms the number of ms we are behind the schedule */ virtual void behind(double ms) { double int_ms = window_config().swc_advance_interval_ms; if (ms > 0.05 * int_ms) { double p = (ms / int_ms) * 100.0; LL_W_PRINT(""Falling behind: %0.3lf seconds (%0.2lf%%)\\n"", ms / 1000.0, p); if (p > 10 * 100.0) abort(); } } /** * Callback for finishing the entire run */ virtual void finished() {} /** * Run the computation * * @param G the graph */ virtual void compute(ll_mlcsr_ro_graph& G) { #ifdef BENCHMARK_WRITABLE LL_E_PRINT(""Using ll_benchmark_sliding_window_driver "" ""with BENCHMARK_WRITABLE\\n""); abort(); #else for (_counter->current_iteration = 0; _counter->current_iteration < _counter->benchmark_count; _counter->current_iteration++) { ll_clear_counters(); _counter->print_before_benchmark(); _last_return_value = run_benchmark(G, _benchmark, *_stats); } #endif } }; //==========================================================================// // The Main Function // //==========================================================================// /** * The main function */ int main(int argc, char** argv) { // Preliminary initialization // Calibrate the RDTSC counter double rdtsc_per_ms = ll_rdtsc_per_ms(); (void) rdtsc_per_ms; // Initial configuration char* cross_validate_with = NULL; char* database_directory = NULL; char* run_task = NULL; char* output_file = NULL; bool verbose = false; bool save_execution_statistics = false; ll_benchmark_counter counter; int min_level = 0; int max_level = -1; int num_threads = -1; int num_iters = -1; node_t root_node = 0; (void) root_node; node_t print_node_from = LL_NIL_NODE; node_t print_node_to = LL_NIL_NODE; bool do_load = false; bool do_in_edges = false; ll_loader_config loader_config; (void) loader_config; ll_stream_config stream_config(rdtsc_per_ms); (void) stream_config; ll_sliding_window_config window_config; (void) window_config; // Pase the command-line arguments int option_index = 0; while (true) { int c = getopt_long(argc, argv, SHORT_OPTIONS, LONG_OPTIONS, &option_index); if (c == -1) break; switch (c) { case 'B': stream_config.sc_max_edges_per_batch = atoi(optarg); if (stream_config.sc_max_edges_per_batch <= 0) { fprintf(stderr, ""Error: The batch size must be positive\\n""); return 1; } break; case 'c': counter.benchmark_count = atoi(optarg); break; case 'C': cross_validate_with = optarg; break; case 'd': database_directory = optarg; break; case 'D': loader_config.lc_deduplicate = true; break; case 'E': stream_config.sc_max_edges_per_second = atoi(optarg); if (stream_config.sc_max_edges_per_second <= 0) { fprintf(stderr, ""Error: The target rate must be positive\\n""); return 1; } break; case 'F': window_config.swc_advance_interval_ms = atof(optarg) * 1000; break; case 'h': usage(argv[0]); return 0; case 'I': do_in_edges = true; break; case 'l': if (strchr(optarg, '-') == NULL) { max_level = atoi(optarg); } else { char* x = strdup(optarg); char* y = strchr(x, '-'); *(y++) = '\\0'; min_level = atoi(x); max_level = atoi(y); free(x); } break; case 'L': do_load = true; break; case 'n': num_iters = atoi(optarg); break; case 'N': loader_config.lc_no_properties = true; break; #ifndef LL_STREAMING case 'm': loader_config.lc_max_edges = atoi(optarg); break; #endif case 'M': counter.max_batches = atoi(optarg); window_config.swc_max_advances = counter.max_batches; break; case 'o': output_file = optarg; break; case 'O': loader_config.lc_direction = LL_L_UNDIRECTED_ORDERED; break; case 'p': if (strchr(optarg, '-') == NULL) { print_node_from = print_node_to = atoi(optarg); } else { char* x = strdup(optarg); char* y = strchr(x, '-'); *(y++) = '\\0'; print_node_from = atoi(x); print_node_to = atoi(y); free(x); } break; case 'P': if (strchr(optarg, '/') == NULL) { LL_E_PRINT(""Invalid format of the -P argument""); return -1; } else { char* x = strdup(optarg); char* y = strchr(x, '/'); *(y++) = '\\0'; loader_config.lc_partial_load_part = atoi(x); loader_config.lc_partial_load_num_parts = atoi(y); free(x); } break; case 'r': run_task = optarg; break; case 'R': root_node = atoi(optarg); break; case 'S': save_execution_statistics = true; break; case 't': num_threads = atoi(optarg); break; case 'T': loader_config.lc_tmp_dirs.push_back(std::string(optarg)); break; case 'U': loader_config.lc_direction = LL_L_UNDIRECTED_DOUBLE; break; case 'v': verbose = true; break; case 'W': window_config.swc_window_snapshots = atoi(optarg); if (window_config.swc_window_snapshots <= 0) { fprintf(stderr, ""Error: The window size must be positive\\n""); return 1; } break; case 'X': loader_config.lc_xs_buffer_size = (size_t) (atof(optarg) * 1024ul*1048576ul); break; case '?': case ':': return 1; default: abort(); } } counter.verbose = verbose; std::vector input_files; for (int i = optind; i < argc; i++) { input_files.push_back(std::string(argv[i])); } #ifdef LL_PERSISTENCE if (do_load && input_files.empty()) { fprintf(stderr, ""Error: No input files specified (use -h for help).\\n""); return 1; } if (!do_load && !input_files.empty()) { fprintf(stderr, ""Error: Input files specified without the --load/-L argument.\\n""); return 1; } #else if (input_files.empty()) { fprintf(stderr, ""Error: No input files specified (use -h for help).\\n""); return 1; } #endif if (database_directory == NULL) { database_directory = (char*) alloca(16); strcpy(database_directory, ""db""); } #ifdef LL_PERSISTENCE if (loader_config.lc_tmp_dirs.empty()) { loader_config.lc_tmp_dirs.push_back(std::string(database_directory)); } #endif if (max_level < 0) max_level = input_files.size() - 1; // Get the task/operation to run const char* run_task_class = """"; bool needs_reverse_edges = do_in_edges; ll_runnable_thing* run = NULL; #if BENCHMARK_TASK_ID >= 0 run = &g_runnable_things[BENCHMARK_TASK_ID]; run_task_class = run->rt_class; if (run->rt_needs_reverse_edges) needs_reverse_edges = true; run_task = NULL; (void) run_task; (void) do_load; #else if (run_task != NULL) { for (ll_runnable_thing* rt = g_runnable_things; rt->rt_class != NULL; rt++) { if (strcmp(run_task, rt->rt_identifier) == 0) { run = rt; run_task_class = rt->rt_class; if (rt->rt_needs_reverse_edges) needs_reverse_edges = true; break; } } if (*run_task_class == '\\0') { fprintf(stderr, ""Error: Unknown task (use -h for help).\\n""); return 1; } } else if (!do_load) { fprintf(stderr, ""Error: No task to run (use -h for help).\\n""); return 1; } #endif // Check the files' type consistency const char* file_type = NULL; const char* first_input = NULL; if (!input_files.empty()) { first_input = input_files[0].c_str(); file_type = ll_file_extension(first_input); for (size_t i = 1; i < input_files.size(); i++) { if (strcmp(ll_file_extension(input_files[i].c_str()), file_type)!=0) { fprintf(stderr, ""Error: All imput files must have the same "" ""file extension.\\n""); return 1; } } if (cross_validate_with != NULL) { if (strcmp(ll_file_extension(cross_validate_with), file_type) != 0) { fprintf(stderr, ""Error: All imput files must have the same "" ""file extension.\\n""); return 1; } } } else if (cross_validate_with != NULL) { file_type = ll_file_extension(cross_validate_with); } // // // Init // // if (verbose) { fprintf(stderr, ""LLAMA BENCHMARK COLLECTION\\n\\n""); #if BENCHMARK_TASK_ID < 0 fprintf(stderr, ""IMPORTANT: Please compile and run the individual "" ""benchmark tasks\\nusing \\""make TASK=...\\"" in order to get "" ""better performance results.\\n\\n""); #endif } // Create the benchmark ll_benchmark* benchmark = NULL; int pagerank_iters = num_iters < 0 ? 10 : num_iters; (void) pagerank_iters; #define B BENCHMARK_TASK_ID #if B < 0 || B == 0 LL_RT_COND_CREATE(run_task_class, 0, ll_b_avg_teen_cnt, 0); #endif #if B < 0 || B == 1 LL_RT_COND_CREATE(run_task_class, 1, ll_b_bc_adj); #endif #if B < 0 || B == 2 LL_RT_COND_CREATE(run_task_class, 2, ll_b_bc_random, 100); #endif #if B < 0 || B == 3 LL_RT_COND_CREATE(run_task_class, 3, ll_b_bfs, root_node); #endif #if B < 0 || B == 4 LL_RT_COND_CREATE(run_task_class, 4, ll_b_pagerank_pull_float, pagerank_iters); #endif #if B < 0 || B == 5 LL_RT_COND_CREATE(run_task_class, 5, ll_b_pagerank_push_float, pagerank_iters); #endif #if B < 0 || B == 6 LL_RT_COND_CREATE_EXT(run_task_class, 6, ll_b_sssp_weighted, float, root_node, ""weight""); #endif #if B < 0 || B == 7 LL_RT_COND_CREATE(run_task_class, 7, ll_b_sssp_unweighted_bfs, root_node); #endif #if B < 0 || B == 8 LL_RT_COND_CREATE(run_task_class, 8, ll_b_tarjan_scc); #endif #if B < 0 || B == 9 LL_RT_COND_CREATE(run_task_class, 9, ll_b_triangle_counting_LI); #endif #if B < 0 || B == 10 LL_RT_COND_CREATE(run_task_class, 10, ll_b_triangle_counting_LOD); #endif #if B < 0 || B == 11 LL_RT_COND_CREATE(run_task_class, 11, ll_b_triangle_counting_LU); #endif #if B < 0 || B == 12 # ifdef BENCHMARK_WRITABLE LL_RT_COND_CREATE(run_task_class, 12, ll_t_delete_edges); # endif #endif #if B < 0 || B == 13 # ifdef BENCHMARK_WRITABLE LL_RT_COND_CREATE(run_task_class, 13, ll_t_delete_nodes); # endif #endif #if B < 0 || B == 14 LL_RT_COND_CREATE(run_task_class, 14, ll_t_level_spread); #endif #if B < 0 || B == 15 LL_RT_COND_CREATE(run_task_class, 15, ll_t_degree_distribution); #endif #if B < 0 || B == 16 LL_RT_COND_CREATE(run_task_class, 16, ll_t_flatten, ""db-m""); #endif #if B < 0 || B == 17 LL_RT_COND_CREATE(run_task_class, 17, ll_t_dump); #endif #if B < 0 || B == 18 LL_RT_COND_CREATE_EXT(run_task_class, 18, ll_t_edge_property_stats, uint32_t, ""stream-weight""); #endif #if B < 0 || B == 19 LL_RT_COND_CREATE(run_task_class, 19, ll_b_pagerank_pull_double, pagerank_iters); #endif #if B < 0 || B == 20 LL_RT_COND_CREATE(run_task_class, 20, ll_b_pagerank_push_double, pagerank_iters); #endif #if B < 0 || B == 21 LL_RT_COND_CREATE(run_task_class, 21, ll_b_sssp_unweighted_iter, root_node); #endif #undef B if (benchmark == NULL) counter.benchmark_count = 0; // Preallocate some writable objects // TODO This should be a bit more customizable #ifndef LL_WRITABLE_USE_MEMORY_POOL if (false) { w_node_deallocator wdn; w_edge_deallocator wde; int nc = 1048576, ec = 1048576; #if defined(_DEBUG) || !(defined(DO_CP) || defined(BENCHMARK_WRITABLE)) nc = ec = 4; #endif LL_D_PRINT(""Preallocating %d nodes (x %lu bytes) and %d edges (x %lu bytes)\\n"", nc, sizeof(w_node), ec, sizeof(w_edge)); while (ec --> 0) wde(new w_edge()); while (nc --> 0) wdn(new w_node()); } #endif // Counters and helper variables double return_d = 0; ll_benchmark_stats stats; // Print the header if (benchmark != NULL) { char s_start_time[64]; strftime(s_start_time, sizeof(s_start_time), ""%m/%d/%y %H:%M:%S"", &stats.tm_start_time); printf(""Benchmark : %s\\n"", benchmark->name()); printf(""Start Time : %s\\n"", s_start_time); printf(""Count : %lu\\n"", counter.benchmark_count); fflush(stdout); } // Prepare the benchmark stats.before_load(); bool ll = true; (void) ll; loader_config.lc_reverse_edges = needs_reverse_edges; #ifdef BENCHMARK_WRITABLE ll = false; loader_config.lc_reverse_maps = needs_reverse_edges; #else #ifdef DO_CP ll = false; #endif #endif ll_database database(database_directory); if (num_threads > 0) database.set_num_threads(num_threads); ll_writable_graph& graph = *database.graph();//(max_nodes); #ifndef LL_STREAMING // Load the graph if (!input_files.empty()) { ll_file_loaders loaders; ll_file_loader* loader = loaders.loader_for(first_input); if (loader == NULL) { fprintf(stderr, ""Error: Unsupported input file type\\n""); return 1; } if (verbose) fprintf(stderr, ""\\nLoading:\\n""); for (int i = 0; i <= max_level; i++) { if (verbose) fprintf(stderr, "" %2d: %s"", i, input_files[i].c_str()); double ts = ll_get_time_ms(); #ifdef DO_CP bool loadRO = false; #else bool loadRO = i == max_level ? ll : true; #endif if (loadRO) loader->load_direct(&graph, input_files[i].c_str(), &loader_config); else loader->load_incremental(&graph, input_files[i].c_str(), &loader_config); double t_l = ll_get_time_ms() - ts; double tt = t_l; if (verbose) fprintf(stderr, "" (Load: %3.2lf s"", t_l/1000.0); #ifdef DO_CP ts = ll_get_time_ms(); # ifdef BENCHMARK_WRITABLE if (i < max_level) graph.checkpoint(&loader_config); # else graph.checkpoint(&loader_config); # endif double t_c = ll_get_time_ms() - ts; tt += t_c; if (verbose) { fprintf(stderr, "", CP: %3.2lf s"", t_c/1000.0); } #endif if (verbose) { fprintf(stderr, "", %7.2lf Kedges/s)\\n"", graph.max_edges(graph.num_levels() - 2) / tt); } } //if (verbose) fprintf(stderr, ""\\n""); stats.after_load(); } #endif // Prepare the graph benchmarkable_graph_t& G = benchmarkable_graph(graph); if (input_files.empty() && max_level < 0) { max_level = G.num_levels() - 1; } #ifdef LL_PERSISTENCE //XXX /*if (input_files.empty()) { graph.ro_graph().create_uninitialized_edge_property_32(""weight"", LL_T_FLOAT) ->init_from_persistent_storage(G.ro_graph().num_levels()); }*/ #endif #ifdef LL_MIN_LEVEL // Set the min level if (min_level > 0) { G.set_min_level(min_level); for (int i = 0; i + 1 < min_level; i++) { graph.delete_level(i); } } #endif // Print a part of the graph if (print_node_from <= print_node_to && print_node_from != LL_NIL_NODE) { printf(""\\n""); printf(""Number of nodes : %lu\\n"", (size_t) G.max_nodes()); if (G.num_levels() == 1) printf(""Number of edges : %lu\\n"", (size_t) G.max_edges(0)); printf(""Number of levels: %lu\\n"", (size_t) G.num_levels()); printf(""\\n""); printf(""A part of the graph:\\n""); for (node_t n = print_node_from; n <= print_node_to; n++) { printf(""%7u [out]:"", (unsigned) n); print_exp_adj_out(G, n); if (needs_reverse_edges) { printf(""%7u [ in]:"", (unsigned) n); print_exp_adj_in(G, n); } } printf(""\\n""); } // The test function for disassembly analysis (do not run) if (1 + ((int) (rand() & 3)) == 0) TEST_FUNCTION(G); // Cross-validate with the provided file if (cross_validate_with != NULL) { if (verbose) { fprintf(stderr, ""\\n""); } int r = cross_validate_with_file(graph, cross_validate_with, file_type, verbose, &loader_config); if (r != 0) return r; if (verbose) { fprintf(stderr, ""\\n""); } } // // // Run the benchmark // // if (counter.print_progress && counter.benchmark_count > 0) { benchmark->set_print_progress(verbose); if (verbose) { fprintf(stderr, ""\\nRunning:\\n""); } else { fprintf(stderr, ""\\nProgress: ""); } } #if defined(LL_STREAMING) ll_file_loaders loaders; ll_file_loader* loader = loaders.loader_for(input_files[0].c_str()); if (loader == NULL) { fprintf(stderr, ""Error: Unsupported input file type\\n""); return 1; } ll_concat_data_source combined_data_source; for (int i = 0; i <= max_level; i++) { ll_data_source* d = loader->create_data_source(input_files[i].c_str()); combined_data_source.add(d); } #if defined(BENCHMARK_CONTINUOUS_LOAD) ll_benchmark_sliding_window_driver sliding_window_benchmark( &database, &combined_data_source, &stream_config, &window_config, &loader_config, num_threads, benchmark, &counter, &stats); sliding_window_benchmark.run(); return_d = sliding_window_benchmark.last_return_value(); #else /* if !defined(BENCHMARK_CONTINUOUS_LOAD) */ counter.current_batch = 0; while (true) { if (counter.max_batches > 0) { if (counter.current_batch >= counter.max_batches) break; } counter.print_before_batch(); if (!load_batch_via_writable_graph(graph, combined_data_source, loader_config, streaming_batch, streaming_window, stats)) break; counter.current_batch++; counter.print_after_batch_load(stats); for (counter.current_iteration = 0; counter.current_iteration < counter.benchmark_count; counter.current_iteration++) { ll_clear_counters(); counter.print_before_benchmark(); return_d = run_benchmark(G, benchmark, stats); counter.print_after_benchmark(stats); } } #endif /* !defined(BENCHMARK_CONTINUOUS_LOAD) */ #else /* if !defined(LL_STREAMING) */ for (counter.current_iteration = 0; counter.current_iteration < counter.benchmark_count; counter.current_iteration++) { ll_clear_counters(); counter.print_before_benchmark(); return_d = run_benchmark(G, benchmark, stats); counter.print_after_benchmark(stats); } #endif counter.print_at_end(); // // // Get the configuration summary // // #if defined(LL_SLCSR) const char* type = ""slcsr""; #elif defined(LL_PERSISTENCE) const char* type = ""persistence""; #elif defined(LL_MEMORY_ONLY) const char* type = ""memory""; #elif defined(LL_STREAMING) const char* type = ""streaming""; #else #error ""Unknown configuration"" #endif std::string configuration_summary = type; #ifdef LL_S_SINGLE_SNAPSHOT configuration_summary += ""-ss""; #endif #ifdef LL_S_WEIGHTS_INSTEAD_OF_DUPLICATE_EDGES configuration_summary += ""-weights""; #endif #ifdef BENCHMARK_CONTINUOUS_LOAD configuration_summary += ""_cont-load""; #endif #if defined(LL_ONE_VT) configuration_summary += ""_onevt""; #elif defined(LL_FLAT_VT) configuration_summary += ""_flatvt""; #endif #ifdef LL_MLCSR_CONTINUATIONS configuration_summary += ""_cont""; #endif #ifdef LL_COPY_ADJ_LIST #if defined(LL_COPY_ADJ_LIST__ALWAYS) configuration_summary += ""_perf""; #elif defined(LL_COPY_ADJ_LIST__LARGE) configuration_summary += ""_l""; char __s[32]; sprintf(__s, ""%d"", LL_COPY_ADJ_LIST__LARGE); configuration_summary += __s; #elif defined(LL_COPY_ADJ_LIST__SMALL) configuration_summary += ""_s""; char __s[32]; sprintf(__s, ""%d"", LL_COPY_ADJ_LIST__SMALL); configuration_summary += __s; #endif #endif #ifdef BENCHMARK_WRITABLE configuration_summary += ""_w""; #else # ifdef LL_DELETIONS configuration_summary += ""_wd""; # endif #endif #if BENCHMARK_TASK_ID >= 0 //configuration_summary += ""_specialized""; configuration_summary += ""_s-""; configuration_summary += run->rt_identifier; #endif // // // Print the benchmark configuration and relevant statistics // // printf(""\\nNode type : %d-bit\\nEdge type : %d-bit\\n"", (int) sizeof(node_t) * 8, (int) sizeof(edge_t) * 8); printf(""Deletions : %s\\n"", IFE_LL_DELETIONS(""yes"", ""no"")); #ifdef BENCHMARK_CONTINUOUS_LOAD printf(""Strm. Drain: %s\\n"", window_config.swc_drain_threshold > 0 ? ""yes"" : ""no""); #endif printf(""Levels : %d--%d%s\\n"", min_level, max_level, #ifdef BENCHMARK_WRITABLE "" (W)"" #else """" #endif ); printf(""Type : %s\\n\\n"", configuration_summary.c_str()); printf(""# Nodes : %lu\\n"", (size_t) graph.max_nodes()); if (graph.ro_graph().num_levels() == 1) printf(""# Edges : %lu\\n"", (size_t) graph.ro_graph().max_edges(0)); printf(""# Levels : %lu\\n"", (size_t) G.num_levels()); stats.print_stats(stdout); #ifdef LL_S_WEIGHTS_INSTEAD_OF_DUPLICATE_EDGES #ifndef LL_S_SINGLE_SNAPSHOT printf(""Edge weights:\\n""); for (int i=0;i<500;i++) { uint32_t w = graph.ro_graph().get_edge_weights_streaming()->get(i); printf("" %u"", w); if ((i+1) % 50 == 0) printf(""\\n""); } printf(""\\n""); #endif #endif // Save the execution statistics if (benchmark != NULL && save_execution_statistics) { stats.save_stats(G, configuration_summary.c_str(), run->rt_identifier); } // Print the results if (benchmark != NULL && output_file != NULL) { FILE* f = NULL; if (strcmp(output_file, """") == 0 || strcmp(output_file, ""-"") == 0) { f = stdout; fprintf(f, ""Results:\\n""); } else { f = fopen(output_file, ""w""); if (f == NULL) { perror(""fopen""); abort(); } } benchmark->print_results(f); if (f != stdout && f != stderr) fclose(f); } if (!std::isnan((double) return_d)) { printf(""Return value: %lf\\n"", return_d); } #ifdef LL_COUNTERS fprintf(stderr, ""\\nCounters:\\n""); ll_print_counters(); #endif if (benchmark != NULL) delete benchmark; return 0; } ",16306,True,2738.901016145491,median " /*++ Copyright (c) 2017 Microsoft Corporation Module Name: nla_core.cpp Author: Nikolaj Bjorner (nbjorner) Lev Nachmanson (levnach) --*/ #include ""math/lp/nla_core.h"" #include ""math/lp/factorization_factory_imp.h"" #include ""math/lp/nex.h"" #include ""math/grobner/pdd_solver.h"" #include ""math/dd/pdd_interval.h"" #include ""math/dd/pdd_eval.h"" namespace nla { core::core(lp::lar_solver& s, reslimit & lim) : m_evars(), m_lar_solver(s), m_tangents(this), m_basics(this), m_order(this), m_monotone(this), m_intervals(this, lim), m_horner(this), m_pdd_manager(s.number_of_vars()), m_pdd_grobner(lim, m_pdd_manager), m_emons(m_evars), m_reslim(lim) {} bool core::compare_holds(const rational& ls, llc cmp, const rational& rs) const { switch(cmp) { case llc::LE: return ls <= rs; case llc::LT: return ls < rs; case llc::GE: return ls >= rs; case llc::GT: return ls > rs; case llc::EQ: return ls == rs; case llc::NE: return ls != rs; default: SASSERT(false); }; return false; } rational core::value(const lp::lar_term& r) const { rational ret(0); for (const auto & t : r) { ret += t.coeff() * val(t.column()); } return ret; } lp::lar_term core::subs_terms_to_columns(const lp::lar_term& t) const { lp::lar_term r; for (const auto& p : t) { lpvar j = p.column(); if (lp::tv::is_term(j)) j = m_lar_solver.map_term_index_to_column_index(j); r.add_monomial(p.coeff(), j); } return r; } bool core::ineq_holds(const ineq& n) const { return compare_holds(value(n.term()), n.cmp(), n.rs()); } bool core::lemma_holds(const lemma& l) const { for(const ineq &i : l.ineqs()) { if (ineq_holds(i)) return true; } return false; } lpvar core::map_to_root(lpvar j) const { return m_evars.find(j).var(); } svector core::sorted_rvars(const factor& f) const { if (f.is_var()) { svector r; r.push_back(map_to_root(f.var())); return r; } return m_emons[f.var()].rvars(); } // the value of the factor is equal to the value of the variable multiplied // by the canonize_sign bool core::canonize_sign(const factor& f) const { return f.sign() ^ (f.is_var()? canonize_sign(f.var()) : canonize_sign(m_emons[f.var()])); } bool core::canonize_sign(lpvar j) const { return m_evars.find(j).sign(); } bool core::canonize_sign_is_correct(const monic& m) const { bool r = false; for (lpvar j : m.vars()) { r ^= canonize_sign(j); } return r == m.rsign(); } bool core::canonize_sign(const monic& m) const { SASSERT(canonize_sign_is_correct(m)); return m.rsign(); } bool core::canonize_sign(const factorization& f) const { bool r = false; for (const factor & a : f) { r ^= canonize_sign(a); } return r; } void core::add_monic(lpvar v, unsigned sz, lpvar const* vs) { m_add_buffer.resize(sz); for (unsigned i = 0; i < sz; i++) { lpvar j = vs[i]; if (lp::tv::is_term(j)) j = m_lar_solver.map_term_index_to_column_index(j); m_add_buffer[i] = j; } m_emons.add(v, m_add_buffer); } void core::push() { TRACE(""nla_solver"",); m_emons.push(); } void core::pop(unsigned n) { TRACE(""nla_solver"", tout << ""n = "" << n << ""\\n"";); m_emons.pop(n); SASSERT(elists_are_consistent(false)); } rational core::product_value(const monic& m) const { rational r(1); for (auto j : m.vars()) { r *= m_lar_solver.get_column_value(j).x; } return r; } // return true iff the monic value is equal to the product of the values of the factors bool core::check_monic(const monic& m) const { SASSERT((!m_lar_solver.column_is_int(m.var())) || m_lar_solver.get_column_value(m.var()).is_int()); bool ret = product_value(m) == m_lar_solver.get_column_value(m.var()).x; CTRACE(""nla_solver_check_monic"", !ret, print_monic(m, tout) << '\\n';); return ret; } void core::explain(const monic& m, lp::explanation& exp) const { for (lpvar j : m.vars()) explain(j, exp); } void core::explain(const factor& f, lp::explanation& exp) const { if (f.type() == factor_type::VAR) { explain(f.var(), exp); } else { explain(m_emons[f.var()], exp); } } void core::explain(lpvar j, lp::explanation& exp) const { m_evars.explain(j, exp); } template std::ostream& core::print_product(const T & m, std::ostream& out) const { bool first = true; for (lpvar v : m) { if (!first) out << ""*""; else first = false; if (lp_settings().m_print_external_var_name) out << ""("" << m_lar_solver.get_variable_name(v) << ""="" << val(v) << "")""; else out << ""(j"" << v << "" ="" << val(v) << "")""; } return out; } template std::string core::product_indices_str(const T & m) const { std::stringstream out; bool first = true; for (lpvar v : m) { if (!first) out << ""*""; else first = false; out << ""j"" << v;; } return out.str(); } std::ostream & core::print_factor(const factor& f, std::ostream& out) const { if (f.sign()) out << ""- ""; if (f.is_var()) { out << ""VAR, ""; print_var(f.var(), out); } else { out << ""MON, v"" << m_emons[f.var()] << "" = ""; print_product(m_emons[f.var()].rvars(), out); } out << ""\\n""; return out; } std::ostream & core::print_factor_with_vars(const factor& f, std::ostream& out) const { if (f.is_var()) { print_var(f.var(), out); } else { out << "" MON = "" << pp_mon_with_vars(*this, m_emons[f.var()]); } return out; } std::ostream& core::print_monic(const monic& m, std::ostream& out) const { if (lp_settings().m_print_external_var_name) out << ""(["" << m.var() << ""] = "" << m_lar_solver.get_variable_name(m.var()) << "" = "" << val(m.var()) << "" = ""; else out << ""(j"" << m.var() << "" = "" << val(m.var()) << "" = ""; print_product(m.vars(), out) << "")\\n""; return out; } std::ostream& core::print_bfc(const factorization& m, std::ostream& out) const { SASSERT(m.size() == 2); out << ""( x = ""; print_factor(m[0], out); out << ""* y = ""; print_factor(m[1], out); out << "")""; return out; } std::ostream& core::print_monic_with_vars(lpvar v, std::ostream& out) const { return print_monic_with_vars(m_emons[v], out); } template std::ostream& core::print_product_with_vars(const T& m, std::ostream& out) const { print_product(m, out) << ""\\n""; for (unsigned k = 0; k < m.size(); k++) { print_var(m[k], out); } return out; } std::ostream& core::print_monic_with_vars(const monic& m, std::ostream& out) const { out << ""[""; print_var(m.var(), out) << ""]\\n""; out << ""vars:""; print_product_with_vars(m.vars(), out) << ""\\n""; if (m.vars() == m.rvars()) out << ""same rvars, and m.rsign = "" << m.rsign() << "" of course\\n""; else { out << ""rvars:""; print_product_with_vars(m.rvars(), out) << ""\\n""; out << ""rsign:"" << m.rsign() << ""\\n""; } return out; } std::ostream& core::print_explanation(const lp::explanation& exp, std::ostream& out) const { out << ""expl: ""; unsigned i = 0; for (auto &p : exp) { out << ""("" << p.second << "")""; m_lar_solver.constraints().display(out, [this](lpvar j) { return var_str(j);}, p.second); if (++i < exp.size()) out << "" ""; } return out; } bool core::explain_upper_bound(const lp::lar_term& t, const rational& rs, lp::explanation& e) const { rational b(0); // the bound for (const auto& p : t) { rational pb; if (explain_coeff_upper_bound(p, pb, e)) { b += pb; } else { e.clear(); return false; } } if (b > rs ) { e.clear(); return false; } return true; } bool core::explain_lower_bound(const lp::lar_term& t, const rational& rs, lp::explanation& e) const { rational b(0); // the bound for (const auto& p : t) { rational pb; if (explain_coeff_lower_bound(p, pb, e)) { b += pb; } else { e.clear(); return false; } } if (b < rs ) { e.clear(); return false; } return true; } bool core:: explain_coeff_lower_bound(const lp::lar_term::ival& p, rational& bound, lp::explanation& e) const { const rational& a = p.coeff(); SASSERT(!a.is_zero()); unsigned c; // the index for the lower or the upper bound if (a.is_pos()) { unsigned c = m_lar_solver.get_column_lower_bound_witness(p.column()); if (c + 1 == 0) return false; bound = a * m_lar_solver.get_lower_bound(p.column()).x; e.add(c); return true; } // a.is_neg() c = m_lar_solver.get_column_upper_bound_witness(p.column()); if (c + 1 == 0) return false; bound = a * m_lar_solver.get_upper_bound(p.column()).x; e.add(c); return true; } bool core::explain_coeff_upper_bound(const lp::lar_term::ival& p, rational& bound, lp::explanation& e) const { const rational& a = p.coeff(); lpvar j = p.column(); SASSERT(!a.is_zero()); unsigned c; // the index for the lower or the upper bound if (a.is_neg()) { unsigned c = m_lar_solver.get_column_lower_bound_witness(j); if (c + 1 == 0) return false; bound = a * m_lar_solver.get_lower_bound(j).x; e.add(c); return true; } // a.is_pos() c = m_lar_solver.get_column_upper_bound_witness(j); if (c + 1 == 0) return false; bound = a * m_lar_solver.get_upper_bound(j).x; e.add(c); return true; } // return true iff the negation of the ineq can be derived from the constraints bool core:: explain_ineq(const lp::lar_term& t, llc cmp, const rational& rs) { // check that we have something like 0 < 0, which is always false and can be safely // removed from the lemma if (t.is_empty() && rs.is_zero() && (cmp == llc::LT || cmp == llc::GT || cmp == llc::NE)) return true; lp::explanation exp; bool r; switch(negate(cmp)) { case llc::LE: r = explain_upper_bound(t, rs, exp); break; case llc::LT: r = explain_upper_bound(t, rs - rational(1), exp); break; case llc::GE: r = explain_lower_bound(t, rs, exp); break; case llc::GT: r = explain_lower_bound(t, rs + rational(1), exp); break; case llc::EQ: r = (explain_lower_bound(t, rs, exp) && explain_upper_bound(t, rs, exp)) || (rs.is_zero() && explain_by_equiv(t, exp)); break; case llc::NE: // TBD - NB: does this work for Reals? r = explain_lower_bound(t, rs + rational(1), exp) || explain_upper_bound(t, rs - rational(1), exp); break; default: UNREACHABLE(); return false; } if (r) { current_expl().add(exp); return true; } return false; } /** * \\brief if t is an octagon term -+x -+ y try to explain why the term always is equal zero */ bool core:: explain_by_equiv(const lp::lar_term& t, lp::explanation& e) const { lpvar i,j; bool sign; if (!is_octagon_term(t, sign, i, j)) return false; if (m_evars.find(signed_var(i, false)) != m_evars.find(signed_var(j, sign))) return false; m_evars.explain(signed_var(i, false), signed_var(j, sign), e); TRACE(""nla_solver"", tout << ""explained :""; m_lar_solver.print_term_as_indices(t, tout);); return true; } void core::mk_ineq(lp::lar_term& t, llc cmp, const rational& rs) { TRACE(""nla_solver_details"", m_lar_solver.print_term_as_indices(t, tout << ""t = "");); if (!explain_ineq(t, cmp, rs)) { current_lemma().push_back(ineq(cmp, t, rs)); CTRACE(""nla_solver"", ineq_holds(ineq(cmp, t, rs)), print_ineq(ineq(cmp, t, rs), tout) << ""\\n"";); SASSERT(!ineq_holds(ineq(cmp, t, rs))); } } void core::mk_ineq_no_expl_check(lp::lar_term& t, llc cmp, const rational& rs) { TRACE(""nla_solver_details"", m_lar_solver.print_term_as_indices(t, tout << ""t = "");); current_lemma().push_back(ineq(cmp, t, rs)); CTRACE(""nla_solver"", ineq_holds(ineq(cmp, t, rs)), print_ineq(ineq(cmp, t, rs), tout) << ""\\n"";); SASSERT(!ineq_holds(ineq(cmp, t, rs))); } void core::mk_ineq(const rational& a, lpvar j, const rational& b, lpvar k, llc cmp, const rational& rs) { lp::lar_term t; t.add_monomial(a, j); t.add_monomial(b, k); mk_ineq(t, cmp, rs); } void core:: mk_ineq(lpvar j, const rational& b, lpvar k, llc cmp, const rational& rs) { mk_ineq(rational(1), j, b, k, cmp, rs); } void core:: mk_ineq(lpvar j, const rational& b, lpvar k, llc cmp) { mk_ineq(j, b, k, cmp, rational::zero()); } void core:: mk_ineq(const rational& a, lpvar j, const rational& b, lpvar k, llc cmp) { mk_ineq(a, j, b, k, cmp, rational::zero()); } void core:: mk_ineq(const rational& a ,lpvar j, lpvar k, llc cmp, const rational& rs) { mk_ineq(a, j, rational(1), k, cmp, rs); } void core:: mk_ineq(lpvar j, lpvar k, llc cmp, const rational& rs) { mk_ineq(j, rational(1), k, cmp, rs); } void core:: mk_ineq(lpvar j, llc cmp, const rational& rs) { mk_ineq(rational(1), j, cmp, rs); } void core:: mk_ineq(const rational& a, lpvar j, llc cmp, const rational& rs) { lp::lar_term t; t.add_monomial(a, j); mk_ineq(t, cmp, rs); } llc apply_minus(llc cmp) { switch(cmp) { case llc::LE: return llc::GE; case llc::LT: return llc::GT; case llc::GE: return llc::LE; case llc::GT: return llc::LT; default: break; } return cmp; } void core:: mk_ineq(const rational& a, lpvar j, llc cmp) { mk_ineq(a, j, cmp, rational::zero()); } void core:: mk_ineq(lpvar j, lpvar k, llc cmp, lemma& l) { mk_ineq(rational(1), j, rational(1), k, cmp, rational::zero()); } void core:: mk_ineq(lpvar j, llc cmp) { mk_ineq(j, cmp, rational::zero()); } // the monics should be equal by modulo sign but this is not so in the model void core:: fill_explanation_and_lemma_sign(const monic& a, const monic & b, rational const& sign) { SASSERT(sign == 1 || sign == -1); explain(a, current_expl()); explain(b, current_expl()); TRACE(""nla_solver"", tout << ""used constraints: ""; for (auto &p : current_expl()) m_lar_solver.constraints().display(tout, p.second); tout << ""\\n""; ); SASSERT(current_ineqs().size() == 0); mk_ineq(rational(1), a.var(), -sign, b.var(), llc::EQ, rational::zero()); TRACE(""nla_solver"", print_lemma(tout);); } // Replaces each variable index by the root in the tree and flips the sign if the var comes with a minus. // Also sorts the result. // svector core::reduce_monic_to_rooted(const svector & vars, rational & sign) const { svector ret; bool s = false; for (lpvar v : vars) { auto root = m_evars.find(v); s ^= root.sign(); TRACE(""nla_solver_eq"", print_var(v,tout); tout << "" mapped to ""; print_var(root.var(), tout);); ret.push_back(root.var()); } sign = rational(s? -1: 1); std::sort(ret.begin(), ret.end()); return ret; } // Replaces definition m_v = v1* .. * vn by // m_v = coeff * w1 * ... * wn, where w1, .., wn are canonical // representatives, which are the roots of the equivalence tree, under current equations. // monic_coeff core::canonize_monic(monic const& m) const { rational sign = rational(1); svector vars = reduce_monic_to_rooted(m.vars(), sign); return monic_coeff(vars, sign); } lemma& core::current_lemma() { return m_lemma_vec->back(); } const lemma& core::current_lemma() const { return m_lemma_vec->back(); } vector& core::current_ineqs() { return current_lemma().ineqs(); } lp::explanation& core::current_expl() { return current_lemma().expl(); } const lp::explanation& core::current_expl() const { return current_lemma().expl(); } int core::vars_sign(const svector& v) { int sign = 1; for (lpvar j : v) { sign *= nla::rat_sign(val(j)); if (sign == 0) return 0; } return sign; } bool core:: has_upper_bound(lpvar j) const { return m_lar_solver.column_has_upper_bound(j); } bool core:: has_lower_bound(lpvar j) const { return m_lar_solver.column_has_lower_bound(j); } const rational& core::get_upper_bound(unsigned j) const { return m_lar_solver.get_upper_bound(j).x; } const rational& core::get_lower_bound(unsigned j) const { return m_lar_solver.get_lower_bound(j).x; } bool core::zero_is_an_inner_point_of_bounds(lpvar j) const { if (has_upper_bound(j) && get_upper_bound(j) <= rational(0)) return false; if (has_lower_bound(j) && get_lower_bound(j) >= rational(0)) return false; return true; } int core::rat_sign(const monic& m) const { int sign = 1; for (lpvar j : m.vars()) { auto v = val(j); if (v.is_neg()) { sign = - sign; continue; } if (v.is_pos()) { continue; } sign = 0; break; } return sign; } // Returns true if the monic sign is incorrect bool core::sign_contradiction(const monic& m) const { return nla::rat_sign(var_val(m)) != rat_sign(m); } /* unsigned_vector eq_vars(lpvar j) const { TRACE(""nla_solver_eq"", tout << ""j = ""; print_var(j, tout); tout << ""eqs = ""; for(auto jj : m_evars.eq_vars(j)) { print_var(jj, tout); }); return m_evars.eq_vars(j); } */ bool core:: var_is_fixed_to_zero(lpvar j) const { return m_lar_solver.column_is_fixed(j) && m_lar_solver.get_lower_bound(j) == lp::zero_of_type(); } bool core:: var_is_fixed_to_val(lpvar j, const rational& v) const { return m_lar_solver.column_is_fixed(j) && m_lar_solver.get_lower_bound(j) == lp::impq(v); } bool core:: var_is_fixed(lpvar j) const { return m_lar_solver.column_is_fixed(j); } bool core:: var_is_free(lpvar j) const { return m_lar_solver.column_is_free(j); } std::ostream & core::print_ineq(const ineq & in, std::ostream & out) const { m_lar_solver.print_term_as_indices(in.m_term, out); out << "" "" << lconstraint_kind_string(in.m_cmp) << "" "" << in.m_rs; return out; } std::ostream & core::print_var(lpvar j, std::ostream & out) const { if (m_emons.is_monic_var(j)) { print_monic(m_emons[j], out); } m_lar_solver.print_column_info(j, out); signed_var jr = m_evars.find(j); out << ""root=""; if (jr.sign()) { out << ""-""; } out << m_lar_solver.get_variable_name(jr.var()) << ""\\n""; return out; } std::ostream & core::print_monics(std::ostream & out) const { for (auto &m : m_emons) { print_monic_with_vars(m, out); } return out; } std::ostream & core::print_ineqs(const lemma& l, std::ostream & out) const { std::unordered_set vars; out << ""ineqs: ""; if (l.ineqs().size() == 0) { out << ""conflict\\n""; } else { for (unsigned i = 0; i < l.ineqs().size(); i++) { auto & in = l.ineqs()[i]; print_ineq(in, out); if (i + 1 < l.ineqs().size()) out << "" or ""; for (const auto & p: in.m_term) vars.insert(p.column()); } out << std::endl; for (lpvar j : vars) { print_var(j, out); } out << ""\\n""; } return out; } std::ostream & core::print_factorization(const factorization& f, std::ostream& out) const { if (f.is_mon()){ out << ""is_mon "" << pp_mon(*this, f.mon()); } else { for (unsigned k = 0; k < f.size(); k++ ) { out << ""(""; print_factor(f[k], out) << "")""; if (k < f.size() - 1) out << ""*""; } } return out; } bool core::find_canonical_monic_of_vars(const svector& vars, lpvar & i) const { monic const* sv = m_emons.find_canonical(vars); return sv && (i = sv->var(), true); } bool core::is_canonical_monic(lpvar j) const { return m_emons.is_canonical_monic(j); } void core::explain_existing_lower_bound(lpvar j) { SASSERT(has_lower_bound(j)); current_expl().add(m_lar_solver.get_column_lower_bound_witness(j)); } void core::explain_existing_upper_bound(lpvar j) { SASSERT(has_upper_bound(j)); current_expl().add(m_lar_solver.get_column_upper_bound_witness(j)); } void core::explain_separation_from_zero(lpvar j) { SASSERT(!val(j).is_zero()); if (val(j).is_pos()) explain_existing_lower_bound(j); else explain_existing_upper_bound(j); } void core::trace_print_monic_and_factorization(const monic& rm, const factorization& f, std::ostream& out) const { out << ""rooted vars: ""; print_product(rm.rvars(), out); out << ""\\n""; out << ""mon: "" << pp_mon(*this, rm.var()) << ""\\n""; out << ""value: "" << var_val(rm) << ""\\n""; print_factorization(f, out << ""fact: "") << ""\\n""; } void core::explain_var_separated_from_zero(lpvar j) { SASSERT(var_is_separated_from_zero(j)); if (m_lar_solver.column_has_upper_bound(j) && (m_lar_solver.get_upper_bound(j)< lp::zero_of_type())) current_expl().add(m_lar_solver.get_column_upper_bound_witness(j)); else current_expl().add(m_lar_solver.get_column_lower_bound_witness(j)); } void core::explain_fixed_var(lpvar j) { SASSERT(var_is_fixed(j)); current_expl().add(m_lar_solver.get_column_upper_bound_witness(j)); current_expl().add(m_lar_solver.get_column_lower_bound_witness(j)); } bool core:: var_has_positive_lower_bound(lpvar j) const { return m_lar_solver.column_has_lower_bound(j) && m_lar_solver.get_lower_bound(j) > lp::zero_of_type(); } bool core:: var_has_negative_upper_bound(lpvar j) const { return m_lar_solver.column_has_upper_bound(j) && m_lar_solver.get_upper_bound(j) < lp::zero_of_type(); } bool core:: var_is_separated_from_zero(lpvar j) const { return var_has_negative_upper_bound(j) || var_has_positive_lower_bound(j); } bool core::vars_are_equiv(lpvar a, lpvar b) const { SASSERT(abs(val(a)) == abs(val(b))); return m_evars.vars_are_equiv(a, b); } void core::explain_equiv_vars(lpvar a, lpvar b) { SASSERT(abs(val(a)) == abs(val(b))); if (m_evars.vars_are_equiv(a, b)) { explain(a, current_expl()); explain(b, current_expl()); } else { explain_fixed_var(a); explain_fixed_var(b); } } void core::explain(const factorization& f, lp::explanation& exp) { SASSERT(!f.is_mon()); for (const auto& fc : f) { explain(fc, exp); } } bool core::has_zero_factor(const factorization& factorization) const { for (factor f : factorization) { if (val(f).is_zero()) return true; } return false; } template bool core:: mon_has_zero(const T& product) const { for (lpvar j: product) { if (val(j).is_zero()) return true; } return false; } template bool core::mon_has_zero(const unsigned_vector& product) const; lp::lp_settings& core::lp_settings() { return m_lar_solver.settings(); } const lp::lp_settings& core::lp_settings() const { return m_lar_solver.settings(); } unsigned core::random() { return lp_settings().random_next(); } // we look for octagon constraints here, with a left part +-x +- y void core::collect_equivs() { const lp::lar_solver& s = m_lar_solver; for (unsigned i = 0; i < s.terms().size(); i++) { if (!s.term_is_used_as_row(i)) continue; lpvar j = s.external_to_local(lp::tv::mask_term(i)); if (var_is_fixed_to_zero(j)) { TRACE(""nla_solver_mons"", s.print_term_as_indices(*s.terms()[i], tout << ""term = "") << ""\\n"";); add_equivalence_maybe(s.terms()[i], s.get_column_upper_bound_witness(j), s.get_column_lower_bound_witness(j)); } } m_emons.ensure_canonized(); } // returns true iff the term is in a form +-x-+y. // the sign is true iff the term is x+y, -x-y. bool core:: is_octagon_term(const lp::lar_term& t, bool & sign, lpvar& i, lpvar &j) const { if (t.size() != 2) return false; bool seen_minus = false; bool seen_plus = false; i = -1; for(const auto & p : t) { const auto & c = p.coeff(); if (c == 1) { seen_plus = true; } else if (c == - 1) { seen_minus = true; } else { return false; } if (i == static_cast(-1)) i = p.column(); else j = p.column(); } SASSERT(j != static_cast(-1)); sign = (seen_minus && seen_plus)? false : true; return true; } void core::add_equivalence_maybe(const lp::lar_term *t, lpci c0, lpci c1) { bool sign; lpvar i, j; if (!is_octagon_term(*t, sign, i, j)) return; if (sign) m_evars.merge_minus(i, j, eq_justification({c0, c1})); else m_evars.merge_plus(i, j, eq_justification({c0, c1})); } // x is equivalent to y if x = +- y void core::init_vars_equivalence() { collect_equivs(); // SASSERT(tables_are_ok()); } bool core::vars_table_is_ok() const { // return m_var_eqs.is_ok(); return true; } bool core::rm_table_is_ok() const { // return m_emons.is_ok(); return true; } bool core:: tables_are_ok() const { return vars_table_is_ok() && rm_table_is_ok(); } bool core:: var_is_a_root(lpvar j) const { return m_evars.is_root(j); } template bool core:: vars_are_roots(const T& v) const { for (lpvar j: v) { if (!var_is_a_root(j)) return false; } return true; } template void core::trace_print_rms(const T& p, std::ostream& out) { out << ""p = {\\n""; for (auto j : p) { out << ""j = "" << j << "", rm = "" << m_emons[j] << ""\\n""; } out << ""}""; } void core::print_monic_stats(const monic& m, std::ostream& out) { if (m.size() == 2) return; monic_coeff mc = canonize_monic(m); for(unsigned i = 0; i < mc.vars().size(); i++){ if (abs(val(mc.vars()[i])) == rational(1)) { auto vv = mc.vars(); vv.erase(vv.begin()+i); monic const* sv = m_emons.find_canonical(vv); if (!sv) { out << ""nf length"" << vv.size() << ""\\n""; ; } } } } void core::print_stats(std::ostream& out) { } void core::clear() { m_lemma_vec->clear(); } void core::init_search() { TRACE(""nla_solver_mons"", tout << ""init\\n"";); SASSERT(m_emons.invariant()); clear(); init_vars_equivalence(); SASSERT(m_emons.invariant()); SASSERT(elists_are_consistent(false)); } void core::insert_to_refine(lpvar j) { TRACE(""lar_solver"", tout << ""j="" << j << '\\n';); m_to_refine.insert(j); } void core::erase_from_to_refine(lpvar j) { TRACE(""lar_solver"", tout << ""j="" << j << '\\n';); m_to_refine.erase(j); } void core::init_to_refine() { TRACE(""nla_solver_details"", tout << ""emons:"" << pp_emons(*this, m_emons);); m_to_refine.clear(); m_to_refine.resize(m_lar_solver.number_of_vars()); unsigned r = random(), sz = m_emons.number_of_monics(); for (unsigned k = 0; k < sz; k++) { auto const & m = *(m_emons.begin() + (k + r)% sz); if (!check_monic(m)) insert_to_refine(m.var()); } TRACE(""nla_solver"", tout << m_to_refine.size() << "" mons to refine:\\n""; for (lpvar v : m_to_refine) tout << pp_mon(*this, m_emons[v]) << "":error = "" << (val(v) - mul_val(m_emons[v])).get_double() << ""\\n"";); } std::unordered_set core::collect_vars(const lemma& l) const { std::unordered_set vars; auto insert_j = [&](lpvar j) { vars.insert(j); if (m_emons.is_monic_var(j)) { for (lpvar k : m_emons[j].vars()) vars.insert(k); } }; for (const auto& i : current_lemma().ineqs()) { for (const auto& p : i.term()) { insert_j(p.column()); } } for (const auto& p : current_expl()) { const auto& c = m_lar_solver.constraints()[p.second]; for (const auto& r : c.coeffs()) { insert_j(r.second); } } return vars; } // divides bc by c, so bc = b*c bool core::divide(const monic& bc, const factor& c, factor & b) const { svector c_rvars = sorted_rvars(c); TRACE(""nla_solver_div"", tout << ""c_rvars = ""; print_product(c_rvars, tout); tout << ""\\nbc_rvars = ""; print_product(bc.rvars(), tout);); if (!lp::is_proper_factor(c_rvars, bc.rvars())) return false; auto b_rvars = lp::vector_div(bc.rvars(), c_rvars); TRACE(""nla_solver_div"", tout << ""b_rvars = ""; print_product(b_rvars, tout);); SASSERT(b_rvars.size() > 0); if (b_rvars.size() == 1) { b = factor(b_rvars[0], factor_type::VAR); } else { monic const* sv = m_emons.find_canonical(b_rvars); if (sv == nullptr) { TRACE(""nla_solver_div"", tout << ""not in rooted"";); return false; } b = factor(sv->var(), factor_type::MON); } SASSERT(!b.sign()); // We have bc = canonize_sign(bc)*bc.rvars() = canonize_sign(b)*b.rvars()*canonize_sign(c)*c.rvars(). // Dividing by bc.rvars() we get canonize_sign(bc) = canonize_sign(b)*canonize_sign(c) // Currently, canonize_sign(b) is 1, we might need to adjust it b.sign() = canonize_sign(b) ^ canonize_sign(c) ^ canonize_sign(bc); TRACE(""nla_solver"", tout << ""success div:""; print_factor(b, tout);); return true; } void core::negate_var_relation_strictly(lpvar a, lpvar b) { SASSERT(val(a) != val(b)); if (val(a) < val(b)) { mk_ineq(a, -rational(1), b, llc::GT); } else { mk_ineq(a, -rational(1), b, llc::LT); } } void core::negate_factor_equality(const factor& c, const factor& d) { if (c == d) return; lpvar i = var(c); lpvar j = var(d); auto iv = val(i), jv = val(j); SASSERT(abs(iv) == abs(jv)); if (iv == jv) { mk_ineq(i, -rational(1), j, llc::NE); } else { // iv == -jv mk_ineq(i, j, llc::NE, current_lemma()); } } void core::negate_factor_relation(const rational& a_sign, const factor& a, const rational& b_sign, const factor& b) { rational a_fs = sign_to_rat(canonize_sign(a)); rational b_fs = sign_to_rat(canonize_sign(b)); llc cmp = a_sign*val(a) < b_sign*val(b)? llc::GE : llc::LE; mk_ineq(a_fs*a_sign, var(a), - b_fs*b_sign, var(b), cmp); } std::ostream& core::print_lemma(std::ostream& out) const { print_specific_lemma(current_lemma(), out); return out; } void core::print_specific_lemma(const lemma& l, std::ostream& out) const { static int n = 0; out << ""lemma:"" << ++n << "" ""; print_ineqs(l, out); print_explanation(l.expl(), out); std::unordered_set vars = collect_vars(current_lemma()); for (lpvar j : vars) { print_var(j, out); } } void core::trace_print_ol(const monic& ac, const factor& a, const factor& c, const monic& bc, const factor& b, std::ostream& out) { out << ""ac = "" << pp_mon(*this, ac) << ""\\n""; out << ""bc = "" << pp_mon(*this, bc) << ""\\n""; out << ""a = ""; print_factor_with_vars(a, out); out << "", \\nb = ""; print_factor_with_vars(b, out); out << ""\\nc = ""; print_factor_with_vars(c, out); } void core::maybe_add_a_factor(lpvar i, const factor& c, std::unordered_set& found_vars, std::unordered_set& found_rm, vector & r) const { SASSERT(abs(val(i)) == abs(val(c))); if (!m_emons.is_monic_var(i)) { i = m_evars.find(i).var(); if (try_insert(i, found_vars)) { r.push_back(factor(i, factor_type::VAR)); } } else { if (try_insert(i, found_rm)) { r.push_back(factor(i, factor_type::MON)); TRACE(""nla_solver"", tout << ""inserting factor = ""; print_factor_with_vars(factor(i, factor_type::MON), tout); ); } } } // Returns rooted monics by arity std::unordered_map core::get_rm_by_arity() { std::unordered_map m; for (auto const& mon : m_emons) { unsigned arity = mon.vars().size(); auto it = m.find(arity); if (it == m.end()) { it = m.insert(it, std::make_pair(arity, unsigned_vector())); } it->second.push_back(mon.var()); } return m; } bool core::rm_check(const monic& rm) const { return check_monic(m_emons[rm.var()]); } /** \\brief Add |v| ~ |bound| where ~ is <, <=, >, >=, and bound = val(v) |v| > |bound| <=> (v < 0 or v > |bound|) & (v > 0 or -v > |bound|) => Let s be the sign of val(v) (s*v < 0 or s*v > |bound|) |v| < |bound| <=> v < |bound| & -v < |bound| => Let s be the sign of val(v) s*v < |bound| */ void core::add_abs_bound(lpvar v, llc cmp) { add_abs_bound(v, cmp, val(v)); } void core::add_abs_bound(lpvar v, llc cmp, rational const& bound) { SASSERT(!val(v).is_zero()); lp::lar_term t; // t = abs(v) t.add_monomial(rrat_sign(val(v)), v); switch (cmp) { case llc::GT: case llc::GE: // negate abs(v) >= 0 mk_ineq(t, llc::LT, rational(0)); break; case llc::LT: case llc::LE: break; default: UNREACHABLE(); break; } mk_ineq(t, cmp, abs(bound)); } // NB - move this comment to monotonicity or appropriate. /** \\brief enforce the inequality |m| <= product |m[i]| . by enforcing lemma: /\\_i |m[i]| <= |val(m[i])| => |m| <= |product_i val(m[i])| <=> \\/_i |m[i]| > |val(m[i])} or |m| <= |product_i val(m[i])| */ bool core::find_bfc_to_refine_on_monic(const monic& m, factorization & bf) { for (auto f : factorization_factory_imp(m, *this)) { if (f.size() == 2) { auto a = f[0]; auto b = f[1]; if (var_val(m) != val(a) * val(b)) { bf = f; TRACE(""nla_solver"", tout << ""found bf""; tout << "":m:"" << pp_mon_with_vars(*this, m) << ""\\n""; tout << ""bf:""; print_bfc(bf, tout);); return true; } } } return false; } // finds a monic to refine with its binary factorization bool core::find_bfc_to_refine(const monic* & m, factorization & bf){ m = nullptr; unsigned r = random(), sz = m_to_refine.size(); for (unsigned k = 0; k < sz; k++) { lpvar i = m_to_refine[(k + r) % sz]; m = &m_emons[i]; SASSERT (!check_monic(*m)); if (m->size() == 2) { bf.set_mon(m); bf.push_back(factor(m->vars()[0], factor_type::VAR)); bf.push_back(factor(m->vars()[1], factor_type::VAR)); return true; } if (find_bfc_to_refine_on_monic(*m, bf)) { TRACE(""nla_solver"", tout << ""bf = ""; print_factorization(bf, tout); tout << ""\\nval(*m) = "" << var_val(*m) << "", should be = (val(bf[0])="" << val(bf[0]) << "")*(val(bf[1]) = "" << val(bf[1]) << "") = "" << val(bf[0])*val(bf[1]) << ""\\n"";); return true; } } return false; } rational core::val(const factorization& f) const { rational r(1); for (const factor &p : f) { r *= val(p); } return r; } void core::add_empty_lemma() { m_lemma_vec->push_back(lemma()); } void core::negate_relation(unsigned j, const rational& a) { SASSERT(val(j) != a); if (val(j) < a) { mk_ineq(j, llc::GE, a); } else { mk_ineq(j, llc::LE, a); } } bool core::conflict_found() const { for (const auto & l : * m_lemma_vec) { if (l.is_conflict()) return true; } return false; } bool core::done() const { return m_lemma_vec->size() >= 10 || conflict_found() || lp_settings().get_cancel_flag(); } lbool core::incremental_linearization(bool constraint_derived) { TRACE(""nla_solver_details"", print_terms(tout); tout << m_lar_solver.constraints();); for (int search_level = 0; search_level < 3 && !done(); search_level++) { TRACE(""nla_solver"", tout << ""constraint_derived = "" << constraint_derived << "", search_level = "" << search_level << ""\\n"";); if (search_level == 0) { m_basics.basic_lemma(constraint_derived); if (!m_lemma_vec->empty()) return l_false; } if (constraint_derived) continue; TRACE(""nla_solver"", tout << ""passed constraint_derived and basic lemmas\\n"";); SASSERT(elists_are_consistent(true)); if (search_level == 1) { m_order.order_lemma(); } else { // search_level == 2 m_monotone. monotonicity_lemma(); m_tangents.tangent_lemma(); } } return m_lemma_vec->empty()? l_undef : l_false; } // constraint_derived is set to true when we do not use the model values to // obtain the lemmas lbool core::inner_check(bool constraint_derived) { if (constraint_derived) { if (need_to_call_algebraic_methods()) if (!m_horner.horner_lemmas()) { clear_and_resize_active_var_set(); if (m_nla_settings.run_grobner()) { find_nl_cluster(); run_grobner(); } } if (done()) { return l_false; } } return incremental_linearization(constraint_derived); } bool core::elist_is_consistent(const std::unordered_set & list) const { bool first = true; bool p; for (lpvar j : list) { if (first) { p = check_monic(m_emons[j]); first = false; } else if (check_monic(m_emons[j]) != p) return false; } return true; } bool core::elists_are_consistent(bool check_in_model) const { std::unordered_map, hash_svector> lists; if (!m_emons.elists_are_consistent(lists)) return false; if (!check_in_model) return true; for (const auto & p : lists) { if (! elist_is_consistent(p.second)) return false; } return true; } bool core::var_is_used_in_a_correct_monic(lpvar j) const { if (emons().is_monic_var(j)) { if (!m_to_refine.contains(j)) return true; } for (const monic & m : emons().get_use_list(j)) { if (!m_to_refine.contains(m.var())) { TRACE(""nla_solver"", tout << ""j"" << j << "" is used in a correct monic \\n"";); return true; } } return false; } void core::update_to_refine_of_var(lpvar j) { for (const monic & m : emons().get_use_list(j)) { if (var_val(m) == mul_val(m)) erase_from_to_refine(var(m)); else insert_to_refine(var(m)); } if (is_monic_var(j)) { const monic& m = emons()[j]; if (var_val(m) == mul_val(m)) erase_from_to_refine(j); else insert_to_refine(j); } } bool core::patch_blocker(lpvar u, const monic& m) const { SASSERT(m_to_refine.contains(m.var())); if (var_is_used_in_a_correct_monic(u)) { TRACE(""nla_solver"", tout << ""u = "" << u << "" blocked as used in a correct monomial\\n"";); return true; } bool ret = u == m.var() || m.contains_var(u); TRACE(""nla_solver"", tout << ""u = "" << u << "", m = ""; print_monic(m, tout) << ""ret = "" << ret << ""\\n"";); return ret; } bool core::try_to_patch(lpvar k, const rational& v, const monic & m) { return m_lar_solver.try_to_patch(k, v, [this, k, m](lpvar u) { if (u == k) return false; // ok to patch return patch_blocker(u, m); }, [this](lpvar u) { update_to_refine_of_var(u); }); } bool in_power(const svector& vs, unsigned l) { unsigned k = vs[l]; return (l != 0 && vs[l - 1] == k) || (l + 1 < vs.size() && k == vs[l + 1]); } bool core::to_refine_is_correct() const { for (unsigned j = 0; j < m_lar_solver.number_of_vars(); j++) { if (!emons().is_monic_var(j)) continue; bool valid = check_monic(emons()[j]); if (valid == m_to_refine.contains(j)) { TRACE(""nla_solver"", tout << ""inconstency in m_to_refine : ""; print_monic(emons()[j], tout) << ""\\n""; if (valid) tout << ""should NOT be in to_refine\\n""; else tout << ""should be in to_refine\\n"";); return false; } } return true; } // looking for any real var to patch void core::patch_monomial_with_real_var(lpvar j) { const monic& m = emons()[j]; TRACE(""nla_solver"", tout << ""m = ""; print_monic(m, tout) << ""\\n"";); rational v = mul_val(m); SASSERT(j == var(m)); if (var_val(m) == v) { erase_from_to_refine(j); return; } if (val(j).is_zero() || v.is_zero()) // a lemma will catch it return; if (!var_is_int(j) && !var_is_used_in_a_correct_monic(j) && try_to_patch(j, v, m)) { SASSERT(to_refine_is_correct()); return; } // handle perfect squares if (m.vars().size() == 2 && m.vars()[0] == m.vars()[1]) { rational root; if (v.is_perfect_square(root)) { lpvar k = m.vars()[0]; if (!var_is_int(k) && !var_is_used_in_a_correct_monic(k) && (try_to_patch(k, root, m) || try_to_patch(k, -root, m)) ) { } } return; } // We have v != abc. Let us suppose we patch b. Then b should // be equal to v/ac = v/(abc/b) = b(v/abc) rational r = val(j) / v; SASSERT(m.is_sorted()); for (unsigned l = 0; l < m.size(); l++) { lpvar k = m.vars()[l]; if (!in_power(m.vars(), l) && !var_is_int(k) && !var_is_used_in_a_correct_monic(k) && try_to_patch(k, r * val(k), m)) { // r * val(k) gives the right value of k SASSERT(mul_val(m) == var_val(m)); erase_from_to_refine(j); break; } } } void core::patch_monomials_with_real_vars() { auto to_refine = m_to_refine.index(); // the rest of the function might change m_to_refine, so have to copy unsigned sz = to_refine.size(); TRACE(""nla_solver"", tout << ""sz = "" << sz << ""\\n"";); unsigned start = random(); for (unsigned i = 0; i < sz; i++) { patch_monomial_with_real_var(to_refine[(start + i) % sz]); if (m_to_refine.size() == 0) break; } TRACE(""nla_solver"", tout << ""sz = "" << m_to_refine.size() << ""\\n"";); SASSERT(m_lar_solver.ax_is_correct()); } lbool core::check(vector& l_vec) { lp_settings().stats().m_nla_calls++; TRACE(""nla_solver"", tout << ""calls = "" << lp_settings().stats().m_nla_calls << ""\\n"";); m_lar_solver.get_rid_of_inf_eps(); m_lemma_vec = &l_vec; if (!(m_lar_solver.get_status() == lp::lp_status::OPTIMAL || m_lar_solver.get_status() == lp::lp_status::FEASIBLE )) { TRACE(""nla_solver"", tout << ""unknown because of the m_lar_solver.m_status = "" << m_lar_solver.get_status() << ""\\n"";); return l_undef; } init_to_refine(); patch_monomials_with_real_vars(); if (m_to_refine.is_empty()) { return l_true; } init_search(); lbool ret = inner_check(true); if (ret == l_undef) ret = inner_check(false); TRACE(""nla_solver"", tout << ""ret = "" << ret << "", lemmas count = "" << m_lemma_vec->size() << ""\\n"";); IF_VERBOSE(2, if(ret == l_undef) {verbose_stream() << ""Monomials\\n""; print_monics(verbose_stream());}); CTRACE(""nla_solver"", ret == l_undef, tout << ""Monomials\\n""; print_monics(tout);); return ret; } bool core:: no_lemmas_hold() const { for (auto & l : * m_lemma_vec) { if (lemma_holds(l)) { TRACE(""nla_solver"", print_specific_lemma(l, tout);); return false; } } return true; } lbool core::test_check( vector& l) { m_lar_solver.set_status(lp::lp_status::OPTIMAL); return check(l); } std::ostream& core::print_terms(std::ostream& out) const { for (unsigned i = 0; i< m_lar_solver.terms().size(); i++) { unsigned ext = lp::tv::mask_term(i); if (!m_lar_solver.var_is_registered(ext)) { out << ""term is not registered\\n""; continue; } const lp::lar_term & t = *m_lar_solver.terms()[i]; out << ""term:""; print_term(t, out) << std::endl; lpvar j = m_lar_solver.external_to_local(ext); print_var(j, out); } return out; } std::string core::var_str(lpvar j) const { return is_monic_var(j)? (product_indices_str(m_emons[j].vars()) + (check_monic(m_emons[j])? """": ""_"")) : (std::string(""j"") + lp::T_to_string(j)); } std::ostream& core::print_term( const lp::lar_term& t, std::ostream& out) const { return lp::print_linear_combination_customized( t.coeffs_as_vector(), [this](lpvar j) { return var_str(j); }, out); } void core::run_grobner() { unsigned& quota = m_nla_settings.grobner_quota(); if (quota == 1) { return; } lp_settings().stats().m_grobner_calls++; configure_grobner(); m_pdd_grobner.saturate(); bool conflict = false; unsigned n = m_pdd_grobner.number_of_conflicts_to_report(); SASSERT(n > 0); for (auto eq : m_pdd_grobner.equations()) { if (check_pdd_eq(eq)) { conflict = true; if (--n == 0) break; } } if (conflict) { IF_VERBOSE(2, verbose_stream() << ""grobner conflict\\n""); } else { if (quota > 1) quota--; IF_VERBOSE(2, verbose_stream() << ""grobner miss, quota "" << quota << ""\\n""); IF_VERBOSE(4, diagnose_pdd_miss(verbose_stream())); } } void core::configure_grobner() { m_pdd_grobner.reset(); try { set_level2var_for_grobner(); for (unsigned i : m_rows) { add_row_to_grobner(m_lar_solver.A_r().m_rows[i]); } } catch (...) { IF_VERBOSE(2, verbose_stream() << ""pdd throw\\n""); return; } #if 0 IF_VERBOSE(2, m_pdd_grobner.display(verbose_stream())); dd::pdd_eval eval(m_pdd_manager); eval.var2val() = [&](unsigned j){ return val(j); }; for (auto* e : m_pdd_grobner.equations()) { dd::pdd p = e->poly(); rational v = eval(p); if (p.is_linear() && !eval(p).is_zero()) { IF_VERBOSE(0, verbose_stream() << ""violated linear constraint "" << p << ""\\n""); } } #endif struct dd::solver::config cfg; cfg.m_max_steps = m_pdd_grobner.equations().size(); cfg.m_max_simplified = m_nla_settings.grobner_max_simplified(); cfg.m_eqs_growth = m_nla_settings.grobner_eqs_growth(); cfg.m_expr_size_growth = m_nla_settings.grobner_expr_size_growth(); cfg.m_expr_degree_growth = m_nla_settings.grobner_expr_degree_growth(); cfg.m_number_of_conflicts_to_report = m_nla_settings.grobner_number_of_conflicts_to_report(); m_pdd_grobner.set(cfg); m_pdd_grobner.adjust_cfg(); m_pdd_manager.set_max_num_nodes(10000); // or something proportional to the number of initial nodes. } std::ostream& core::diagnose_pdd_miss(std::ostream& out) { // m_pdd_grobner.display(out); dd::pdd_eval eval; eval.var2val() = [&](unsigned j){ return val(j); }; for (auto* e : m_pdd_grobner.equations()) { dd::pdd p = e->poly(); rational v = eval(p); if (!v.is_zero()) { out << p << "" := "" << v << ""\\n""; } } for (unsigned j = 0; j < m_lar_solver.number_of_vars(); ++j) { if (m_lar_solver.column_has_lower_bound(j) || m_lar_solver.column_has_upper_bound(j)) { out << j << "": [""; if (m_lar_solver.column_has_lower_bound(j)) out << m_lar_solver.get_lower_bound(j); out << ""..""; if (m_lar_solver.column_has_upper_bound(j)) out << m_lar_solver.get_upper_bound(j); out << ""]\\n""; } } return out; } bool core::check_pdd_eq(const dd::solver::equation* e) { auto& di = m_intervals.get_dep_intervals(); dd::pdd_interval eval(di); eval.var2interval() = [this](lpvar j, bool deps, scoped_dep_interval& a) { if (deps) m_intervals.set_var_interval(j, a); else m_intervals.set_var_interval(j, a); }; scoped_dep_interval i(di), i_wd(di); eval.get_interval(e->poly(), i); if (!di.separated_from_zero(i)) return false; eval.get_interval(e->poly(), i_wd); std::function f = [this](const lp::explanation& e) { add_empty_lemma(); current_expl().add(e); }; if (di.check_interval_for_conflict_on_zero(i_wd, e->dep(), f)) { lp_settings().stats().m_grobner_conflicts++; return true; } else { return false; } } void core::add_var_and_its_factors_to_q_and_collect_new_rows(lpvar j, svector & q) { if (active_var_set_contains(j) || var_is_fixed(j)) return; TRACE(""grobner"", tout << ""j = "" << j << "", ""; print_var(j, tout) << ""\\n"";); const auto& matrix = m_lar_solver.A_r(); insert_to_active_var_set(j); for (auto & s : matrix.m_columns[j]) { unsigned row = s.var(); if (m_rows.contains(row)) continue; if (matrix.m_rows[row].size() > m_nla_settings.grobner_row_length_limit()) { TRACE(""grobner"", tout << ""ignore the row "" << row << "" with the size "" << matrix.m_rows[row].size() << ""\\n"";); continue; } m_rows.insert(row); for (auto& rc : matrix.m_rows[row]) { add_var_and_its_factors_to_q_and_collect_new_rows(rc.var(), q); } } if (!is_monic_var(j)) return; const monic& m = emons()[j]; for (auto fcn : factorization_factory_imp(m, *this)) { for (const factor& fc: fcn) { q.push_back(var(fc)); } } } const rational& core::val_of_fixed_var_with_deps(lpvar j, u_dependency*& dep) { unsigned lc, uc; m_lar_solver.get_bound_constraint_witnesses_for_column(j, lc, uc); dep = m_intervals.mk_join(dep, m_intervals.mk_leaf(lc)); dep = m_intervals.mk_join(dep, m_intervals.mk_leaf(uc)); return m_lar_solver.column_lower_bound(j).x; } dd::pdd core::pdd_expr(const rational& c, lpvar j, u_dependency*& dep) { if (m_nla_settings.grobner_subs_fixed() == 1 && var_is_fixed(j)) { return m_pdd_manager.mk_val(c * val_of_fixed_var_with_deps(j, dep)); } if (m_nla_settings.grobner_subs_fixed() == 2 && var_is_fixed_to_zero(j)) { return m_pdd_manager.mk_val(val_of_fixed_var_with_deps(j, dep)); } if (!is_monic_var(j)) return c * m_pdd_manager.mk_var(j); u_dependency* zero_dep = dep; // j is a monic var dd::pdd r = m_pdd_manager.mk_val(c); const monic& m = emons()[j]; for (lpvar k : m.vars()) { if (m_nla_settings.grobner_subs_fixed() && var_is_fixed(k)) { r *= m_pdd_manager.mk_val(val_of_fixed_var_with_deps(k, dep)); } else if (m_nla_settings.grobner_subs_fixed() == 2 && var_is_fixed_to_zero(k)) { r = m_pdd_manager.mk_val(val_of_fixed_var_with_deps(k, zero_dep)); dep = zero_dep; return r; } else { r *= m_pdd_manager.mk_var(k); } } return r; } void core::add_row_to_grobner(const vector> & row) { u_dependency *dep = nullptr; dd::pdd sum = m_pdd_manager.mk_val(rational(0)); for (const auto &p : row) { sum += pdd_expr(p.coeff(), p.var(), dep); } m_pdd_grobner.add(sum, dep); } void core::find_nl_cluster() { prepare_rows_and_active_vars(); svector q; for (lpvar j : m_to_refine) { TRACE(""grobner"", print_monic(emons()[j], tout) << ""\\n"";); q.push_back(j); } while (!q.empty()) { lpvar j = q.back(); q.pop_back(); add_var_and_its_factors_to_q_and_collect_new_rows(j, q); } TRACE(""grobner"", display_matrix_of_m_rows(tout);); } void core::prepare_rows_and_active_vars() { m_rows.clear(); m_rows.resize(m_lar_solver.row_count()); clear_and_resize_active_var_set(); } std::unordered_set core::get_vars_of_expr_with_opening_terms(const nex *e ) { auto ret = get_vars_of_expr(e); auto & ls = m_lar_solver; svector added; for (auto j : ret) { added.push_back(j); } for (unsigned i = 0; i < added.size(); ++i) { lpvar j = added[i]; if (ls.column_corresponds_to_term(j)) { const auto& t = m_lar_solver.get_term(lp::tv::raw(ls.local_to_external(j))); for (auto p : t) { if (ret.find(p.column()) == ret.end()) { added.push_back(p.column()); ret.insert(p.column()); } } } } return ret; } void core::display_matrix_of_m_rows(std::ostream & out) const { const auto& matrix = m_lar_solver.A_r(); out << m_rows.size() << "" rows"" <<""\\n""; out << ""the matrix\\n""; for (const auto & r : matrix.m_rows) { print_row(r, out) << std::endl; } } void core::set_active_vars_weights(nex_creator& nc) { nc.set_number_of_vars(m_lar_solver.column_count()); for (lpvar j : active_var_set()) { nc.set_var_weight(j, get_var_weight(j)); } } void core::set_level2var_for_grobner() { unsigned n = m_lar_solver.column_count(); unsigned_vector sorted_vars(n), weighted_vars(n); for (unsigned j = 0; j < n; j++) { sorted_vars[j] = j; weighted_vars[j] = get_var_weight(j); } #if 1 // potential update to weights for (unsigned j = 0; j < n; j++) { if (is_monic_var(j) && m_to_refine.contains(j)) { for (lpvar k : m_emons[j].vars()) { weighted_vars[k] += 6; } } } #endif std::sort(sorted_vars.begin(), sorted_vars.end(), [&](unsigned a, unsigned b) { unsigned wa = weighted_vars[a]; unsigned wb = weighted_vars[b]; return wa < wb || (wa == wb && a < b); }); unsigned_vector l2v(n); for (unsigned j = 0; j < n; j++) l2v[j] = sorted_vars[j]; m_pdd_manager.reset(l2v); } unsigned core::get_var_weight(lpvar j) const { unsigned k; switch (m_lar_solver.get_column_type(j)) { case lp::column_type::fixed: k = 0; break; case lp::column_type::boxed: k = 2; break; case lp::column_type::lower_bound: case lp::column_type::upper_bound: k = 4; case lp::column_type::free_column: k = 6; break; default: UNREACHABLE(); break; } if (is_monic_var(j)) { k++; if (m_to_refine.contains(j)) { k++; } } return k; } bool core::is_nl_var(lpvar j) const { if (is_monic_var(j)) return true; return m_emons.is_used_in_monic(j); } bool core::influences_nl_var(lpvar j) const { if (lp::tv::is_term(j)) j = lp::tv::unmask_term(j); if (is_nl_var(j)) return true; for (const auto & c : m_lar_solver.A_r().m_columns[j]) { lpvar basic_in_row = m_lar_solver.r_basis()[c.var()]; if (is_nl_var(basic_in_row)) return true; } return false; } } // end of nla ",16258,True,3098.8647537872725,median ":application_email_config_override_text: :optional_tag: pass:normal[[optional]#Optional#] :default_localhost: pass:normal[[default]#defaults to `localhost`#] :default_change_me: pass:normal[[default]#defaults to `change-me@fusionauth.io`#] :default_port_25: pass:normal[[default]#defaults to `25`#] :default_none: pass:normal[[default]#defaults to `NONE`#] :default_false: pass:normal[[default]#defaults to `none`#] :default_allow: pass:normal[[default]#defaults to `Allow`#] :show_feature_blurb: true :base_field_name: tenant :is_tenant: true ==== Request Body [.api] [field]#sourceTenantId# [type]#[UUID]# [optional]#Optional# [since]#Available since 1.14.0#:: The optional Id of an existing Tenant to make a copy of. A unique [field]#tenant.name# is required. If present, the [field]#tenant.id# value will used for the new Tenant. All other values will be copied from the source Tenant to the new Tenant. [field]#tenant.accessControlConfiguration.uiIPAccessControlListId# [type]#[UUID]# [optional]#Optional# [since]#Available since 1.30.0#:: The Id of the link:/docs/v1/tech/apis/ip-acl/[IP Access Control List] limiting access to all applications in this tenant. + :enterprise_feature: IP ACLs include::../shared/_enterprise-edition-blurb-api.adoc[] + :enterprise_feature!: [field]#tenant.captchaConfiguration.captchaMethod# [type]#[String]# [optional]#Optional# [since]#Available since 1.30.0#:: The type of captcha method to use. This field is required when [field]#tenant.captchaConfiguration.enabled# is set to `true`. The possible values are: + * `GoogleRecaptchaV2` - use Google Recaptcha v2 * `GoogleRecaptchaV3` - use Google Recaptcha v3 * `HCaptcha` - use HCaptcha * `HCaptchaEnterprise` - use HCaptcha Enterprise - v25 + :enterprise_feature: CAPTCHA include::../shared/_enterprise-edition-blurb-api.adoc[] // You must keep the empty line above the `+` and you cannot undefine :enterprise_feature!: here it breaks the formatting because of the list. [field]#tenant.captchaConfiguration.enabled# [type]#[Boolean]# [optional]#Optional# [default]#defaults to `false`# [since]#Available since 1.30.0#:: Whether captcha configuration is enabled. + :enterprise_feature: CAPTCHA include::../shared/_enterprise-edition-blurb-api.adoc[] + :enterprise_feature!: [field]#tenant.captchaConfiguration.secretKey# [type]#[String]# [optional]#Optional# [since]#Available since 1.30.0#:: The secret key for this captcha method. This field is required when [field]#tenant.captchaConfiguration.enabled# is set to `true`. + :enterprise_feature: CAPTCHA include::../shared/_enterprise-edition-blurb-api.adoc[] + :enterprise_feature!: [field]#tenant.captchaConfiguration.siteKey# [type]#[String]# [optional]#Optional# [since]#Available since 1.30.0#:: The site key for this captcha method. This field is required when [field]#tenant.captchaConfiguration.enabled# is set to `true`. + :enterprise_feature: CAPTCHA include::../shared/_enterprise-edition-blurb-api.adoc[] + :enterprise_feature!: [field]#tenant.captchaConfiguration.threshold# [type]#[Float]# [optional]#Optional# [default]#defaults to `0.5`# [since]#Available since 1.30.0#:: The numeric threshold which separates a passing score from a failing one. This value only applies if using either the Google v3 or HCaptcha Enterprise method, otherwise this value is ignored. + The value must be between `0.0` and `1.0`. Values outside of that range will result in an error. + :enterprise_feature: CAPTCHA include::../shared/_enterprise-edition-blurb-api.adoc[] + :enterprise_feature!: [field]#tenant.connectorPolicies# [type]#[Array]# [optional]#Optional# [since]#Available since 1.18.0#:: A list of Connector policies. Users will be authenticated against Connectors in order. Each Connector can be included in this list at most once and must exist. [field]#tenant.connectorPolicies``[x]``.connectorId# [type]#[UUID]# [optional]#Optional# [default]#defaults to the FusionAuth connector Id of `e3306678-a53a-4964-9040-1c96f36dda72`# [since]#Available since 1.18.0#:: The identifier of the Connector to which this policy refers. [field]#tenant.connectorPolicies``[x]``.domains# [type]#[Array]# [optional]#Optional# [default]#defaults to `[""*""]`# [since]#Available since 1.18.0#:: An list of email domains to which this connector should apply. + A value of `[""*""]` indicates this connector applies to all users. [field]#tenant.connectorPolicies``[x]``.migrate# [type]#[Boolean]# [optional]#Optional# [default]#defaults to `false`# [since]#Available since 1.18.0#:: If true, the user's data will be migrated to FusionAuth at first successful authentication; subsequent authentications will occur against the FusionAuth datastore. If false, the Connector's source will be treated as authoritative. + Prior to version 1.28.0 this value was required. [field]#tenant.data# [type]#[Object]# [optional]#Optional#:: An object that can hold any information about the Tenant that should be persisted. include::_tenant-application-email-configuration.adoc[] [field]#tenant.eventConfiguration.events# [type]#[Object]# [optional]#Optional# [since]#Available since 1.8.0#:: A mapping of the configuration for each event type that FusionAuth sends. The event types that are the keys into this Object are: + include::_event-types.adoc[] [field]#tenant.eventConfiguration.events``[type]``.enabled# [type]#[Boolean]# [optional]#Optional# [default]#defaults to `false`# [since]#Available since 1.8.0#:: Whether or not FusionAuth should send these types of events to any configured Webhooks. [field]#tenant.eventConfiguration.events``[type]``.transactionType# [type]#[String]# [optional]#Optional# [since]#Available since 1.8.0#:: The transaction type that FusionAuth uses when sending these types of events to any configured Webhooks. The transaction types are: + include::_transaction-types.adoc[] [field]#tenant.externalIdentifierConfiguration.authorizationGrantIdTimeToLiveInSeconds# [type]#[Integer]# [optional]#Optional# [default]#defaults to `30`# [since]#Available since 1.8.0#:: The time in seconds until a OAuth authorization code in no longer valid to be exchanged for an access token. This is essentially the time allowed between the start of an Authorization request during the Authorization code grant and when you request an access token using this authorization code on the Token endpoint. + Value must be greater than 0 and less than or equal to 600. + Prior to version 1.28.0 this value was required. [field]#tenant.externalIdentifierConfiguration.changePasswordIdGenerator.length# [type]#[Integer]# [optional]#Optional# [default]#defaults to `32`# [since]#Available since 1.8.0#:: + :generator_type: changePasswordIdGenerator :generator_display_name: change password Id include::_tenant-generator-length-config-rules.adoc[] :generator_type!: :generator_display_name!: + Prior to version 1.28.0 this value was required. [field]#tenant.externalIdentifierConfiguration.changePasswordIdGenerator.type# [type]#[String]# [optional]#Optional# [default]#defaults to `randomBytes`# [since]#Available since 1.8.0#:: + :generator_display_name: change password Id include::_tenant-generator-type-config-rules.adoc[] :generator_display_name!: + Prior to version 1.28.0 this value was required. [field]#tenant.externalIdentifierConfiguration.changePasswordIdTimeToLiveInSeconds# [type]#[Integer]# [optional]#Optional# [default]#defaults to `600`# [since]#Available since 1.8.0#:: The time in seconds until a change password Id is no longer valid and cannot be used by the Change Password API. Value must be greater than 0. + Prior to version 1.28.0 this value was required. [field]#tenant.externalIdentifierConfiguration.deviceCodeTimeToLiveInSeconds# [type]#[Integer]# [optional]#Optional# [default]#defaults to `300`# [since]#Available since 1.11.0#:: The time in seconds until a device code Id is no longer valid and cannot be used by the Token API. Value must be greater than 0. + Prior to version 1.28.0 this value was required. [field]#tenant.externalIdentifierConfiguration.deviceUserCodeIdGenerator.length# [type]#[Integer]# [optional]#Optional# [default]#defaults to `6`# [since]#Available since 1.11.0#:: + :generator_type: deviceCodeTimeToLiveInSeconds :generator_display_name: device code Id include::_tenant-generator-length-config-rules.adoc[] :generator_type!: :generator_display_name!: + Prior to version 1.28.0 this value was required. [field]#tenant.externalIdentifierConfiguration.deviceUserCodeIdGenerator.type# [type]#[String]# [optional]#Optional# [default]#defaults to `randomAlphaNumeric`# [since]#Available since 1.11.0#:: + :generator_display_name: device code Id include::_tenant-generator-type-config-rules.adoc[] :generator_display_name!: + Prior to version 1.28.0 this value was required. [field]#tenant.externalIdentifierConfiguration.emailVerificationIdGenerator.length# [type]#[Integer]# [optional]#Optional# [default]#defaults to `32`# [since]#Available since 1.8.0#:: + :generator_type: emailVerificationIdGenerator :generator_display_name: the email verification Id include::_tenant-generator-length-config-rules.adoc[] :generator_type!: :generator_display_name!: + Prior to version 1.28.0 this value was required. [field]#tenant.externalIdentifierConfiguration.emailVerificationIdGenerator.type# [type]#[String]# [optional]#Optional# [default]#defaults to `randomBytes`# [since]#Available since 1.8.0#:: + :generator_display_name: email verification Id include::_tenant-generator-type-config-rules.adoc[] :generator_display_name!: + Prior to version 1.28.0 this value was required. [field]#tenant.externalIdentifierConfiguration.emailVerificationIdTimeToLiveInSeconds# [type]#[Integer]# [optional]#Optional# [default]#defaults to `86,400`# [since]#Available since 1.8.0#:: The time in seconds until a email verification Id is no longer valid and cannot be used by the Verify Email API. Value must be greater than 0. + Prior to version 1.28.0 this value was required. [field]#tenant.externalIdentifierConfiguration.emailVerificationOneTimeCodeGenerator.length# [type]#[Integer]# [optional]#Optional# [default]#defaults to `6`# [since]#Available since 1.27.0#:: + :generator_type: emailVerificationIdGenerator :generator_display_name: email verification one time code include::_tenant-generator-length-config-rules.adoc[] :generator_type!: :generator_display_name!: + [field]#tenant.externalIdentifierConfiguration.emailVerificationOneTimeCodeGenerator.type# [type]#[String]# [optional]#Optional# [default]#defaults to `randomAlphaNumeric`# [since]#Available since 1.27.0#:: + :generator_display_name: email verification one time code include::_tenant-generator-type-config-rules.adoc[] :generator_display_name!: + [field]#tenant.externalIdentifierConfiguration.externalAuthenticationIdTimeToLiveInSeconds# [type]#[Integer]# [optional]#Optional# [default]#defaults to `300`# [since]#Available since 1.12.0#:: The time in seconds until an external authentication Id is no longer valid and cannot be used by the Token API. Value must be greater than 0. + Prior to version 1.28.0 this value was required. [field]#tenant.externalIdentifierConfiguration.oneTimePasswordTimeToLiveInSeconds# [type]#[Integer]# [optional]#Optional# [default]#defaults to `60`# [since]#Available since 1.8.0#:: The time in seconds until a One Time Password is no longer valid and cannot be used by the Login API. Value must be greater than 0. + Prior to version 1.28.0 this value was required. [field]#tenant.externalIdentifierConfiguration.passwordlessLoginGenerator.length# [type]#[Integer]# [optional]#Optional# [default]#defaults to `32`# [since]#Available since 1.8.0#:: + :generator_type: passwordlessLoginGenerator :generator_display_name: passwordless login include::_tenant-generator-length-config-rules.adoc[] :generator_type!: :generator_display_name!: + Prior to version 1.28.0 this value was required. [field]#tenant.externalIdentifierConfiguration.passwordlessLoginGenerator.type# [type]#[String]# [optional]#Optional# [default]#defaults to `randomBytes`# [since]#Available since 1.8.0#:: + :generator_display_name: passwordless login include::_tenant-generator-type-config-rules.adoc[] :generator_display_name!: + Prior to version 1.28.0 this value was required. [field]#tenant.externalIdentifierConfiguration.passwordlessLoginTimeToLiveInSeconds# [type]#[Integer]# [optional]#Optional# [default]#defaults to `180`# [since]#Available since 1.8.0#:: The time in seconds until a passwordless code is no longer valid and cannot be used by the Passwordless API. Value must be greater than 0. + Prior to version 1.28.0 this value was required. [field]#tenant.externalIdentifierConfiguration.pendingAccountLinkTimeToLiveInSeconds# [type]#[Integer]# [optional]#Optional# [default]#defaults to `3600`# [since]#Available since 1.28.0#:: The number of seconds before the pending account link identifier is no longer valid to complete an account link request. Value must be greater than 0. [field]#tenant.externalIdentifierConfiguration.registrationVerificationIdGenerator.length# [type]#[Integer]# [optional]#Optional# [default]#defaults to `32`# [since]#Available since 1.8.0#:: + :generator_type: registrationVerificationIdGenerator :generator_display_name: registration verification Id include::_tenant-generator-length-config-rules.adoc[] :generator_type!: :generator_display_name!: + Prior to version 1.28.0 this value was required. [field]#tenant.externalIdentifierConfiguration.registrationVerificationIdGenerator.type# [type]#[String]# [optional]#Optional# [default]#defaults to `randomBytes`# [since]#Available since 1.8.0#:: + :generator_display_name: registration verification Id include::_tenant-generator-type-config-rules.adoc[] :generator_display_name!: + Prior to version 1.28.0 this value was required. [field]#tenant.externalIdentifierConfiguration.registrationVerificationIdTimeToLiveInSeconds# [type]#[Integer]# [optional]#Optional# [default]#defaults to `86,400`# [since]#Available since 1.8.0#:: The time in seconds until a registration verification Id is no longer valid and cannot be used by the Verify Registration API. Value must be greater than 0. + Prior to version 1.28.0 this value was required. [field]#tenant.externalIdentifierConfiguration.registrationVerificationOneTimeCodeGenerator.length# [type]#[Integer]# [optional]#Optional# [default]#defaults to `6`# [since]#Available since 1.27.0#:: + :generator_type: registrationVerificationIdGenerator :generator_display_name: registration verification one time code include::_tenant-generator-length-config-rules.adoc[] :generator_type!: :generator_display_name!: + Prior to version 1.28.0 this value was required. [field]#tenant.externalIdentifierConfiguration.registrationVerificationOneTimeCodeGenerator.type# [type]#[String]# [optional]#Optional# [default]#defaults to `randomAlphaNumeric`# [since]#Available since 1.27.0#:: + :generator_display_name: registration verification one time code include::_tenant-generator-type-config-rules.adoc[] :generator_display_name!: + Prior to version 1.28.0 this value was required. [field]#tenant.externalIdentifierConfiguration.samlv2AuthNRequestIdTimeToLiveInSeconds# [type]#[Integer]# [optional]#Optional# [default]#defaults to `300`# [since]#Available since 1.19.0#:: The time in seconds that a SAML AuthN request Id returned by the Start SAML v2 Login Request API will be eligible to be used to complete a SAML v2 Login request. [field]#tenant.externalIdentifierConfiguration.setupPasswordIdGenerator.length# [type]#[Integer]# [optional]#Optional# [default]#defaults to `32`# [since]#Available since 1.8.0#:: + :generator_type: setupPasswordIdGenerator :generator_display_name: setup password Id include::_tenant-generator-length-config-rules.adoc[] :generator_type!: :generator_display_name!: + Prior to version 1.28.0 this value was required. [field]#tenant.externalIdentifierConfiguration.setupPasswordIdGenerator.type# [type]#[String]# [optional]#Optional# [default]#defaults to `randomBytes`# [since]#Available since 1.8.0#:: + :generator_display_name: setup password Id include::_tenant-generator-type-config-rules.adoc[] :generator_display_name!: + Prior to version 1.28.0 this value was required. [field]#tenant.externalIdentifierConfiguration.setupPasswordIdTimeToLiveInSeconds# [type]#[Integer]# [optional]#Optional# [default]#defaults to `86,400`# [since]#Available since 1.8.0#:: The time in seconds until a setup password Id is no longer valid and cannot be used by the Change Password API. Value must be greater than 0. + Prior to version 1.28.0 this value was required. [field]#tenant.externalIdentifierConfiguration.twoFactorIdTimeToLiveInSeconds# [type]#[Integer]# [optional]#Optional# [default]#defaults to `300`# [since]#Available since 1.8.0#:: The time in seconds until a two factor Id is no longer valid and cannot be used by the Two Factor Login API. Value must be greater than 0. + Prior to version 1.28.0 this value was required. [field]#tenant.externalIdentifierConfiguration.twoFactorOneTimeCodeIdGenerator.length# [type]#[Integer]# [optional]#Optional# [default]#defaults to `6`# [since]#Available since 1.27.0#:: + :generator_type: twoFactorOneTimeCodeIdGenerator :generator_display_name: the two factor code Id include::_tenant-generator-length-config-rules.adoc[] :generator_type!: :generator_display_name!: + Prior to version 1.28.0 this value was required. [field]#tenant.externalIdentifierConfiguration.twoFactorOneTimeCodeIdGenerator.type# [type]#[String]# [optional]#Optional# [default]#defaults to `randomDigits`# [since]#Available since 1.27.0#:: + :generator_display_name: two factor one time code Id include::_tenant-generator-type-config-rules.adoc[] :generator_display_name!: + Prior to version 1.28.0 this value was required. [field]#tenant.externalIdentifierConfiguration.twoFactorOneTimeCodeIdTimeToLiveInSeconds# [type]#[Integer]# [optional]#Optional# [default]#defaults to `60`# [since]#Available since 1.26.0#:: The number of seconds before the Two-Factor One Time Code used to enable or disable a two-factor method is no longer valid. Must be greater than 0. + Prior to version 1.28.0 this value was required. [field]#tenant.externalIdentifierConfiguration.twoFactorTrustIdTimeToLiveInSeconds# [type]#[Integer]# [optional]#Optional# [default]#defaults to `2,592,000`# [since]#Available since 1.8.0#:: The time in seconds until an issued Two Factor trust Id is no longer valid and the User will be required to complete Two Factor authentication during the next authentication attempt. Value must be greater than 0. + Prior to version 1.28.0 this value was required. [field]#tenant.failedAuthenticationConfiguration.actionDuration# [type]#[Long]# [optional]#Optional# [default]#defaults to `3`# [since]#Available since 1.8.0#:: The duration of the User Action. This value along with the `actionDurationUnit` will be used to set the duration of the User Action. Value must be greater than 0. [field]#tenant.failedAuthenticationConfiguration.actionDurationUnit# [type]#[String]# [optional]#Optional# [default]#defaults to `""MINUTES""`# [since]#Available since 1.8.0#:: include::_expiry_unit.adoc[] [field]#tenant.failedAuthenticationConfiguration.resetCountInSeconds# [type]#[Integer]# [optional]#Optional# [default]#defaults to `60`# [since]#Available since 1.8.0#:: The length of time in seconds before the failed authentication count will be reset. Value must be greater than 0. + For example, if `tooManyAttempts` is set to `5` and you fail to authenticate `4` times in a row, waiting for the duration specified here will cause your fifth attempt to start back at `1`. [field]#tenant.failedAuthenticationConfiguration.tooManyAttempts# [type]#[Integer]# [optional]#Optional# [default]#defaults to `5`# [since]#Available since 1.8.0#:: The number of failed attempts considered to be too many. Once this threshold is reached the specified User Action will be applied to the user for the duration specified. Value must be greater than 0. [field]#tenant.failedAuthenticationConfiguration.userActionId# [type]#[UUID]# [optional]#Optional# [since]#Available since 1.8.0#:: The Id of the User Action that is applied when the threshold is reached for too many failed authentication attempts. [field]#tenant.familyConfiguration.allowChildRegistrations# [type]#[Boolean]# [optional]#Optional# [default]#defaults to `true`# [since]#Available since 1.8.0#:: Whether to allow child registrations. [field]#tenant.familyConfiguration.confirmChildEmailTemplateId# [type]#[UUID]# [optional]#Optional# [since]#Available since 1.8.0#:: The unique Id of the email template to use when confirming a child. [field]#tenant.familyConfiguration.deleteOrphanedAccounts# [type]#[Boolean]# [optional]#Optional# [default]#defaults to `false`# [since]#Available since 1.8.0#:: Indicates that child users without parental verification will be permanently deleted after [field]#tenant.familyConfiguration.deleteOrphanedAccountsDays# days. [field]#tenant.familyConfiguration.deleteOrphanedAccountsDays# [type]#[Integer]# [optional]#Optional# [default]#defaults to `30`# [since]#Available since 1.8.0#:: The number of days from creation child users will be retained before being deleted for not completing parental verification. Value must be greater than 0. [field]#tenant.familyConfiguration.enabled# [type]#[Boolean]# [optional]#Optional# [default]#defaults to `false`# [since]#Available since 1.8.0#:: Whether family configuration is enabled. [field]#tenant.familyConfiguration.familyRequestEmailTemplateId# [type]#[UUID]# [optional]#Optional# [since]#Available since 1.8.0#:: The unique Id of the email template to use when a family request is made. [field]#tenant.familyConfiguration.maximumChildAge# [type]#[Integer]# [optional]#Optional# [default]#defaults to `12`# [since]#Available since 1.8.0#:: The maximum age of a child. Value must be greater than 0. [field]#tenant.familyConfiguration.minimumOwnerAge# [type]#[Integer]# [optional]#Optional# [default]#defaults to `21`# [since]#Available since 1.8.0#:: The minimum age to be an owner. Value must be greater than 0. [field]#tenant.familyConfiguration.parentEmailRequired# [type]#[Boolean]# [optional]#Optional# [default]#defaults to `false`# [since]#Available since 1.8.0#:: Whether a parent email is required. [field]#tenant.familyConfiguration.parentRegistrationEmailTemplateId# [type]#[UUID]# [optional]#Optional# [since]#Available since 1.8.0#:: The unique Id of the email template to use for parent registration. [field]#tenant.formConfiguration.adminUserFormId# [type]#[UUID]# [optional]#Optional# [default]#defaults to **[see description]**# [since]#Available since 1.20.0#:: The unique Id of the form to use for the Add and Edit User form when used in the FusionAuth admin UI. + When this parameter is not provided, it will default to the form Id currently assigned to the Default tenant. + :premium_feature: custom forms include::../shared/_premium-edition-blurb-api.adoc[] + :premium_feature!: [field]#tenant.httpSessionMaxInactiveInterval# [type]#[Integer]# [optional]#Optional# [default]#defaults to `3600`# [since]#Available since 1.8.0#:: Time in seconds until an inactive session will be invalidated. Used when creating a new session in the FusionAuth OAuth frontend. [field]#tenant.issuer# [type]#[String]# [optional]#Optional# [default]#defaults to `fusionauth.io`# [since]#Available since 1.8.0#:: The named issuer used to sign tokens, this is generally your public fully qualified domain. + Prior to version 1.30.0 this value was required. [field]#tenant.jwtConfiguration.accessTokenKeyId# [type]#[UUID]# [optional]#Optional# [default]#defaults to key value of the FusionAuth application# [since]#Available since 1.8.0#:: The unique id of the signing key used to sign the access token. + Prior to version 1.30.0 this value was required. [field]#tenant.jwtConfiguration.idTokenKeyId# [type]#[UUID]# [optional]#Optional# [default]#defaults to key value of the FusionAuth application# [since]#Available since 1.8.0#:: The unique id of the signing key used to sign the Id token. + Prior to version 1.30.0 this value was required. [field]#tenant.jwtConfiguration.refreshTokenExpirationPolicy# [type]#[String]# [optional]#Optional# [default]#defaults to `Fixed`# [since]#Available since 1.17.0#:: The refresh token expiration policy. The following are valid values: * `Fixed` - the expiration is calculated from the time the token is issued. * `SlidingWindow` - the expiration is calculated from the last time the token was used. [field]#tenant.jwtConfiguration.refreshTokenRevocationPolicy.onLoginPrevented# [type]#[Boolean]# [optional]#Optional# [default]#defaults to `true`# [since]#Available since 1.17.0#:: When enabled, the refresh token will be revoked when a user action, such as locking an account based on a number of failed login attempts, prevents user login. [field]#tenant.jwtConfiguration.refreshTokenRevocationPolicy.onPasswordChanged# [type]#[Boolean]# [optional]#Optional# [default]#defaults to `true`# [since]#Available since 1.17.0#:: When enabled, the refresh token will be revoked when a user changes their password. [field]#tenant.jwtConfiguration.refreshTokenTimeToLiveInMinutes# [type]#[Integer]# [optional]#Optional# [default]#defaults to `43,200`# [since]#Available since 1.8.0#:: The length of time in minutes a Refresh Token is valid from the time it was issued. Value must be greater than 0. + Prior to version 1.28.0 this value was required. [field]#tenant.jwtConfiguration.refreshTokenUsagePolicy# [type]#[String]# [optional]#Optional# [default]#defaults to `Reusable`# [since]#Available since 1.17.0#:: The refresh token usage policy. The following are valid values: * `Reusable` - the token does not change after it was issued. * `OneTimeUse` - the token value will be changed each time the token is used to refresh a JWT. The client must store the new value after each usage. + Prior to version 1.28.0 this value was required. [field]#tenant.jwtConfiguration.timeToLiveInSeconds# [type]#[Integer]# [optional]#Optional# [default]#defaults to `3,600`# [since]#Available since 1.8.0#:: The length of time in seconds this JWT is valid from the time it was issued. Value must be greater than 0. + Prior to version 1.28.0 this value was required. [field]#tenant.loginConfiguration.requireAuthentication# [type]#[Boolean]# [optional]#Optional# [default]#defaults to `true`# [since]#Available since 1.26.0#:: Indicates whether to require an API key for the Login API when an `applicationId` is not provided. When an `applicationId` is provided to the Login API call, the application configuration will take precedence. + In almost all cases, you will want to this to be `true`. [field]#tenant.logoutURL# [type]#[String]# [optional]#Optional# [since]#Available since 1.8.0#:: The logout redirect URL when sending the user's browser to the `/oauth2/logout` URI of the FusionAuth Front End. This value is only used when a logout URL is not defined in your Application. [field]#tenant.maximumPasswordAge.days# [type]#[Integer]# [optional]#Optional# [default]#defaults to `180`# [since]#Available since 1.8.0#:: The password maximum age in days. The number of days after which FusionAuth will require a user to change their password. Required when [field]#tenant.maximumPasswordAge.enabled# is set to `true`. [field]#tenant.maximumPasswordAge.enabled# [type]#[Boolean]# [optional]#Optional# [default]#defaults to `false`# [since]#Available since 1.8.0#:: Indicates that the maximum password age is enabled and being enforced. [field]#tenant.minimumPasswordAge.seconds# [type]#[Integer]# [optional]#Optional# [default]#defaults to `30`# [since]#Available since 1.8.0#:: The password minimum age in seconds. When enabled FusionAuth will not allow a password to be changed until it reaches this minimum age. Required when [field]#tenant.minimumPasswordAge.enabled# is set to `true`. [field]#tenant.minimumPasswordAge.enabled# [type]#[Boolean]# [optional]#Optional# [default]#defaults to `false`# [since]#Available since 1.8.0#:: Indicates that the minimum password age is enabled and being enforced. [field]#tenant.multiFactorConfiguration.authenticator.enabled# [type]#[Boolean]# [optional]#Optional# [default]#defaults to `true`# [since]#Available since 1.26.0#:: When enabled, users may utilize an authenticator application to complete a multi-factor authentication request. This method uses TOTP (Time-Based One-Time Password) as defined in link:https://tools.ietf.org/html/rfc6238[RFC 6238] and often uses an native mobile app such as Google Authenticator. [field]#tenant.multiFactorConfiguration.email.enabled# [type]#[Boolean]# [optional]#Optional# [default]#defaults to `false`# [since]#Available since 1.26.0#:: When enabled, users may utilize an email address to complete a multi-factor authentication request. [field]#tenant.multiFactorConfiguration.email.templateId# [type]#[UUID]# [optional]#Optional# [since]#Available since 1.26.0#:: The Id of the email template that is used when notifying a user to complete a multi-factor authentication request. This field is required when [field]#tenant.multiFactorConfiguration.email.enabled# is set to `true`. [field]#tenant.multiFactorConfiguration.sms.enabled# [type]#[Boolean]# [optional]#Optional# [default]#defaults to `false`# [since]#Available since 1.26.0#:: When enabled, users may utilize a mobile phone number to complete a multi-factor authentication request. [field]#tenant.multiFactorConfiguration.sms.messengerId# [type]#[UUID]# [optional]#Optional# [since]#Available since 1.26.0#:: The messenger that is used to deliver a SMS multi-factor authentication request. This field is required when [field]#tenant.multiFactorConfiguration.sms.enabled# is set to `true`. [field]#tenant.multiFactorConfiguration.sms.templateId# [type]#[UUID]# [optional]#Optional# [since]#Available since 1.26.0#:: The Id of the SMS template that is used when notifying a user to complete a multi-factor authentication request. This field is required when [field]#tenant.multiFactorConfiguration.sms.enabled# is set to `true`. [field]#tenant.name# [type]#[String]# [required]#Required#:: The unique name of the Tenant. [field]#tenant.oauthConfiguration.clientCredentialsAccessTokenPopulateLambdaId# [type]#[UUID]# [optional]#Optional# [since]#Available since 1.26.0#:: The Id of a lambda that will be called to populate the JWT during a client credentials grant. + :premium_feature: client credentials grant include::../shared/_premium-edition-blurb-api.adoc[] + :premium_feature!: [field]#tenant.passwordEncryptionConfiguration.encryptionScheme# [type]#[String]# [optional]#Optional# [default]#defaults to `""salted-pbkdf2-hmac-sha256""`# [since]#Available since 1.8.0#:: The default method for encrypting the User's password. The following encryptors are provided with FusionAuth: + * `link:/docs/v1/tech/reference/password-hashes/#salted-md5[salted-md5]` * `link:/docs/v1/tech/reference/password-hashes/#salted-sha-256[salted-sha256]` * `link:/docs/v1/tech/reference/password-hashes/#salted-hmac-sha-256[salted-hmac-sha256]` * `link:/docs/v1/tech/reference/password-hashes/#salted-pbkdf2-hmac-sha-256[salted-pbkdf2-hmac-sha256]` * `link:/docs/v1/tech/reference/password-hashes/#salted-bcrypt[bcrypt]` [field]#tenant.passwordEncryptionConfiguration.encryptionSchemeFactor# [type]#[Integer]# [optional]#Optional# [default]#defaults to `24000`# [since]#Available since 1.8.0#:: The factor used by the password encryption scheme. If not provided, the `PasswordEncryptor` provides a default value. Generally this will be used as an iteration count to generate the hash. The actual use of this value is up to the `PasswordEncryptor` implementation. [field]#tenant.passwordEncryptionConfiguration.modifyEncryptionSchemeOnLogin# [type]#[Boolean]# [optional]#Optional# [default]#defaults to `false`# [since]#Available since 1.8.0#:: When enabled a user's hash configuration will be modified to match these configured settings. This can be useful to increase a password hash strength over time or upgrade imported users to a more secure encryption scheme after an initial import. [field]#tenant.passwordValidationRules.breachDetection.enabled# [type]#[Boolean]# [optional]#Optional# [default]#defaults to `false`# [since]#Available since 1.15.0#:: Whether to enable Reactor breach detection. Requires an activated license. [field]#tenant.passwordValidationRules.breachDetection.matchMode# [type]#[String]# [optional]#Optional# [since]#Available since 1.15.0#:: The level of severity where Reactor will consider a breach. The following are valid values: + * `High` Only requires a password match, this is the most secure and is recommended * `Medium` Exact match on username, email address or email sub-address * `Low` Exact match on an email or username, or the password is a common breached value [field]#tenant.passwordValidationRules.breachDetection.notifyUserEmailTemplateId# [type]#[UUID]# [optional]#Optional# [since]#Available since 1.15.0#:: The Id of the email template to use when notifying user of breached password. Required if [field]#tenant.passwordValidationRules.breachDetection.onLogin# is set to `NotifyUser`. [field]#tenant.passwordValidationRules.breachDetection.onLogin# [type]#[String]# [optional]#Optional# [since]#Available since 1.15.0#:: The behavior when detecting breaches at time of user login. The following are valid values: + * `Off` Do not perform breach detection at login * `RecordOnly` Only record the result, take no action * `NotifyUser` Notify the end user via email * `RequireChange` Require immediate password change [field]#tenant.passwordValidationRules.maxLength# [type]#[Integer]# [optional]#Optional# [default]#defaults to `256`# [since]#Available since 1.8.0#:: The maximum length of a password when a new user is created or a user requests a password change. [field]#tenant.passwordValidationRules.minLength# [type]#[Integer]# [optional]#Optional# [default]#defaults to `8`# [since]#Available since 1.8.0#:: The minimum length of a password when a new user is created or a user requests a password change. [field]#tenant.passwordValidationRules.rememberPreviousPasswords.count# [type]#[Integer]# [optional]#Optional# [since]#Available since 1.8.0#:: The number of previous passwords to remember. Value must be greater than 0. [field]#tenant.passwordValidationRules.rememberPreviousPasswords.enabled# [type]#[Boolean]# [optional]#Optional# [default]#defaults to `false`# [since]#Available since 1.8.0#:: Whether to prevent a user from using any of their previous passwords. [field]#tenant.passwordValidationRules.requireMixedCase# [type]#[Boolean]# [optional]#Optional# [default]#defaults to `false`# [since]#Available since 1.8.0#:: Whether to force the user to use at least one uppercase and one lowercase character. [field]#tenant.passwordValidationRules.requireNonAlpha# [type]#[Boolean]# [optional]#Optional# [default]#defaults to `false`# [since]#Available since 1.8.0#:: Whether to force the user to use at least one non-alphanumeric character. [field]#tenant.passwordValidationRules.requireNumber# [type]#[Boolean]# [optional]#Optional# [default]#defaults to `false`# [since]#Available since 1.8.0#:: Whether to force the user to use at least one number. [field]#tenant.passwordValidationRules.validateOnLogin# [type]#[Boolean]# [optional]#Optional# [default]#defaults to `false`# [since]#Available since 1.15.0#:: When enabled the user's password will be validated during login. If the password does not meet the currently configured validation rules the user will be required to change their password. [field]#tenant.rateLimitConfiguration.failedLogin.enabled# [type]#[Boolean]# [optional]#Optional# [default]#defaults to `false`# [since]#Available since 1.30.0#:: Whether rate limiting is enabled for failed login. + :premium_feature: rate limiting include::../shared/_premium-edition-blurb-api.adoc[] + :premium_feature!: [field]#tenant.rateLimitConfiguration.failedLogin.limit# [type]#[Integer]# [optional]#Optional# [default]#defaults to `5`# [since]#Available since 1.30.0#:: The number of times a user can fail to login within the configured [field]#timePeriodInSeconds# duration. If a Failed authentication action has been configured then it will take precedence. + Required when `enabled` is set to `true`. + :premium_feature: rate limiting include::../shared/_premium-edition-blurb-api.adoc[] + :premium_feature!: [field]#tenant.rateLimitConfiguration.failedLogin.timePeriodInSeconds# [type]#[Integer]# [optional]#Optional# [default]#defaults to `60`# [since]#Available since 1.30.0#:: The duration for the number of times a user can fail login before being rate limited. + Required when `enabled` is set to `true`. + :premium_feature: rate limiting include::../shared/_premium-edition-blurb-api.adoc[] + :premium_feature!: [field]#tenant.rateLimitConfiguration.forgotPassword.enabled# [type]#[Boolean]# [optional]#Optional# [default]#defaults to `false`# [since]#Available since 1.30.0#:: Whether rate limiting is enabled for forgot password. + :premium_feature: rate limiting include::../shared/_premium-edition-blurb-api.adoc[] + :premium_feature!: [field]#tenant.rateLimitConfiguration.forgotPassword.limit# [type]#[Integer]# [optional]#Optional# [default]#defaults to `5`# [since]#Available since 1.30.0#:: The number of times a user can request a forgot password email within the configured [field]#timePeriodInSeconds# duration. + Required when `enabled` is set to `true`. + :premium_feature: rate limiting include::../shared/_premium-edition-blurb-api.adoc[] + :premium_feature!: [field]#tenant.rateLimitConfiguration.forgotPassword.timePeriodInSeconds# [type]#[Integer]# [optional]#Optional# [default]#defaults to `60`# [since]#Available since 1.30.0#:: The duration for the number of times a user can request a forgot password email before being rate limited. + Required when `enabled` is set to `true`. + :premium_feature: rate limiting include::../shared/_premium-edition-blurb-api.adoc[] + :premium_feature!: [field]#tenant.rateLimitConfiguration.sendEmailVerification.enabled# [type]#[Boolean]# [optional]#Optional# [default]#defaults to `false`# [since]#Available since 1.30.0#:: Whether rate limiting is enabled for send email verification. + :premium_feature: rate limiting include::../shared/_premium-edition-blurb-api.adoc[] + :premium_feature!: [field]#tenant.rateLimitConfiguration.sendEmailVerification.limit# [type]#[Integer]# [optional]#Optional# [default]#defaults to `5`# [since]#Available since 1.30.0#:: The number of times a user can request a verification email within the configured [field]#timePeriodInSeconds# duration. + Required when `enabled` is set to `true`. + :premium_feature: rate limiting include::../shared/_premium-edition-blurb-api.adoc[] + :premium_feature!: [field]#tenant.rateLimitConfiguration.sendEmailVerification.timePeriodInSeconds# [type]#[Integer]# [optional]#Optional# [default]#defaults to `60`# [since]#Available since 1.30.0#:: The duration for the number of times a user can request a verification email before being rate limited. + Required when `enabled` is set to `true`. + :premium_feature: rate limiting include::../shared/_premium-edition-blurb-api.adoc[] + :premium_feature!: [field]#tenant.rateLimitConfiguration.sendPasswordless.enabled# [type]#[Boolean]# [optional]#Optional# [default]#defaults to `false`# [since]#Available since 1.30.0#:: Whether rate limiting is enabled for send passwordless. + :premium_feature: rate limiting include::../shared/_premium-edition-blurb-api.adoc[] + :premium_feature!: [field]#tenant.rateLimitConfiguration.sendPasswordless.limit# [type]#[Integer]# [optional]#Optional# [default]#defaults to `5`# [since]#Available since 1.30.0#:: The number of times a user can request a passwordless login email within the configured [field]#timePeriodInSeconds# duration. + Required when `enabled` is set to `true`. + :premium_feature: rate limiting include::../shared/_premium-edition-blurb-api.adoc[] + :premium_feature!: [field]#tenant.rateLimitConfiguration.sendPasswordless.timePeriodInSeconds# [type]#[Integer]# [optional]#Optional# [default]#defaults to `60`# [since]#Available since 1.30.0#:: The duration for the number of times a user can request a passwordless login email before being rate limited. + Required when `enabled` is set to `true`. + :premium_feature: rate limiting include::../shared/_premium-edition-blurb-api.adoc[] + :premium_feature!: [field]#tenant.rateLimitConfiguration.sendRegistrationVerification.enabled# [type]#[Boolean]# [optional]#Optional# [default]#defaults to `false`# [since]#Available since 1.30.0#:: Whether rate limiting is enabled for send registration verification. + :premium_feature: rate limiting include::../shared/_premium-edition-blurb-api.adoc[] + :premium_feature!: [field]#tenant.rateLimitConfiguration.sendRegistrationVerification.limit# [type]#[Integer]# [optional]#Optional# [default]#defaults to `5`# [since]#Available since 1.30.0#:: The number of times a user can request a registration verification email within the configured [field]#timePeriodInSeconds# duration. + Required when `enabled` is set to `true`. + :premium_feature: rate limiting include::../shared/_premium-edition-blurb-api.adoc[] + :premium_feature!: [field]#tenant.rateLimitConfiguration.sendRegistrationVerification.timePeriodInSeconds# [type]#[Integer]# [optional]#Optional# [default]#defaults to `60`# [since]#Available since 1.30.0#:: The duration for the number of times a user can request a registration verification email before being rate limited. + Required when `enabled` is set to `true`. + :premium_feature: rate limiting include::../shared/_premium-edition-blurb-api.adoc[] + :premium_feature!: [field]#tenant.rateLimitConfiguration.sendTwoFactor.enabled# [type]#[Boolean]# [optional]#Optional# [default]#defaults to `false`# [since]#Available since 1.30.0#:: Whether rate limiting is enabled for send two factor. + :premium_feature: rate limiting include::../shared/_premium-edition-blurb-api.adoc[] + :premium_feature!: [field]#tenant.rateLimitConfiguration.sendTwoFactor.limit# [type]#[Integer]# [optional]#Optional# [default]#defaults to `5`# [since]#Available since 1.30.0#:: The number of times a user can request a two-factor code by email or SMS within the configured [field]#timePeriodInSeconds# duration. + Required when `enabled` is set to `true`. + :premium_feature: rate limiting include::../shared/_premium-edition-blurb-api.adoc[] + :premium_feature!: [field]#tenant.rateLimitConfiguration.sendTwoFactor.timePeriodInSeconds# [type]#[Integer]# [optional]#Optional# [default]#defaults to `60`# [since]#Available since 1.30.0#:: The duration for the number of times a user can request a two-factor code by email or SMS before being rate limited. + Required when `enabled` is set to `true`. + :premium_feature: rate limiting include::../shared/_premium-edition-blurb-api.adoc[] + :premium_feature!: [field]#tenant.registrationConfiguration.blockedDomains# [type]#[Array]# [optional]#Optional# [since]#Available since 1.30.0#:: A list of unique domains that are not allowed to register when self service is enabled. + :premium_feature: blocked domains include::../shared/_premium-edition-blurb-api.adoc[] + :premium_feature!: [field]#tenant.ssoConfiguration.deviceTrustTimeToLiveInSeconds# [type]#[Integer]# [optional]#Optional# [default]#defaults to `31,536,000` (1 year)# [since]#Available since 1.30.2#:: The number of seconds before a trusted device is reset. When reset, a user is forced to complete captcha during login and complete two factor authentication if applicable. [field]#tenant.themeId# [type]#[UUID]# [optional]#Optional# [default]#defaults to the default tenant theme Id of `75a068fd-e94b-451a-9aeb-3ddb9a3b5987`# [since]#Available since 1.8.0#:: The unique Id of the theme to be used to style the login page and other end user templates. + Prior to version 1.30.0 this value was required. [field]#tenant.userDeletePolicy.unverified.enabled# [type]#[Boolean]# [optional]#Optional# [default]#defaults to `false`# [since]#Available since 1.13.0#:: Indicates that users without a verified email address will be permanently deleted after [field]#tenant.userDeletePolicy.unverified.numberOfDaysToRetain# days. [field]#tenant.userDeletePolicy.unverified.numberOfDaysToRetain# [type]#[Integer]# [optional]#Optional# [since]#Available since 1.13.0#:: The number of days from creation users will be retained before being deleted for not completing email verification. This field is required when [field]#tenant.userDeletePolicy.unverified.enabled# is set to `true`. Value must be greater than 0. [field]#tenant.usernameConfiguration.unique.enabled# [type]#[Boolean]# [optional]#Optional# [default]#defaults to `false`# [since]#Available since 1.27.0#:: When `true`, FusionAuth will handle username collisions by generating a random suffix. + :premium_feature: unique usernames include::../shared/_premium-edition-blurb-api.adoc[] + :premium_feature!: [field]#tenant.usernameConfiguration.unique.numberOfDigits# [type]#[Integer]# [optional]#Optional# [default]#defaults to `5`# [since]#Available since 1.27.0#:: The maximum number of digits to use when building a unique suffix for a username. A number will be randomly selected and will be 1 or more digits up to this configured value in length. For example, if this value is `5`, the suffix will be a number between `00001` and `99999`, inclusive. The value of this field must be greater than or equal to `3` and less than or equal to `10`. [field]#tenant.usernameConfiguration.unique.separator# [type]#[String]# [optional]#Optional# [default]#defaults to the `#` character# [since]#Available since 1.27.0#:: A single character to use as a separator from the requested username and a unique suffix that is added when a duplicate username is detected. This value can be a single non-alphanumeric ASCII character. [field]#tenant.usernameConfiguration.unique.strategy# [type]#[String]# [optional]#Optional# [default]#defaults to `OnCollision`# [since]#Available since 1.29.0#:: This strategy instructions FusionAuth when to append a unique suffix to the username. The possible values are: + * `Always` - Always append a unique suffix even when the requested username is not in use. * `OnCollision` - Only append a unique suffix when the requested username is in use. [source,json] .Example Request JSON ---- include::../../../src/json/tenants/request.json[] ---- ",12144,True,3015.278545903989,median "// ==================================================================== // This file is part of FlexibleSUSY. // // FlexibleSUSY 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. // // FlexibleSUSY 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 FlexibleSUSY. If not, see // . // ==================================================================== // File generated at Thu 10 May 2018 14:56:11 #include ""CMSSMNoFV_effective_couplings.hpp"" #include ""effective_couplings.hpp"" #include ""wrappers.hpp"" namespace flexiblesusy { using namespace effective_couplings; #define INPUTPARAMETER(parameter) model.get_input().parameter #define MODELPARAMETER(parameter) model.get_##parameter() #define DERIVEDPARAMETER(parameter) model.##parameter() #define PHASE(parameter) model.get_##parameter() #define PHYSICAL(parameter) model.get_physical().parameter CMSSMNoFV_effective_couplings::CMSSMNoFV_effective_couplings( const CMSSMNoFV_mass_eigenstates& model_, const softsusy::QedQcd& qedqcd_, const Physical_input& input_) : model(model_), qedqcd(qedqcd_), physical_input(input_) , rg_improve(true), include_qcd_corrections(true) , ZD(MODELPARAMETER(ZD)), ZU(MODELPARAMETER(ZU)), ZE(MODELPARAMETER(ZE)), ZM (MODELPARAMETER(ZM)), ZTau(MODELPARAMETER(ZTau)), ZS(MODELPARAMETER(ZS)), ZC (MODELPARAMETER(ZC)), ZB(MODELPARAMETER(ZB)), ZT(MODELPARAMETER(ZT)), ZH( MODELPARAMETER(ZH)), ZA(MODELPARAMETER(ZA)), ZP(MODELPARAMETER(ZP)), ZN( MODELPARAMETER(ZN)), UM(MODELPARAMETER(UM)), UP(MODELPARAMETER(UP)), ZZ( MODELPARAMETER(ZZ)) , eff_CphhVPVP(Eigen::Array,2,1>::Zero()), eff_CphhVGVG (Eigen::Array,2,1>::Zero()), eff_CpAhVPVP(Eigen::Array< std::complex,2,1>::Zero()), eff_CpAhVGVG(Eigen::Array,2,1>::Zero()) { } void CMSSMNoFV_effective_couplings::calculate_effective_couplings() { const standard_model::Standard_model sm(initialise_SM()); const double scale = model.get_scale(); const Eigen::ArrayXd saved_parameters(model.get()); const double saved_mt = PHYSICAL(MFt); PHYSICAL(MFt) = qedqcd.displayPoleMt(); const auto Mhh = PHYSICAL(Mhh); for (int gO1 = 0; gO1 < 2; ++gO1) { if (rg_improve && scale > Mhh(gO1)) { model.run_to(Mhh(gO1)); } model.calculate_DRbar_masses(); copy_mixing_matrices_from_model(); run_SM_strong_coupling_to(sm, 0.5 * Mhh(gO1)); calculate_eff_CphhVPVP(gO1); run_SM_strong_coupling_to(sm, Mhh(gO1)); calculate_eff_CphhVGVG(gO1); } const auto MAh = PHYSICAL(MAh); for (int gO1 = 1; gO1 < 2; ++gO1) { if (rg_improve && scale > MAh(gO1)) { model.run_to(MAh(gO1)); } model.calculate_DRbar_masses(); copy_mixing_matrices_from_model(); run_SM_strong_coupling_to(sm, 0.5 * MAh(gO1)); calculate_eff_CpAhVPVP(gO1); run_SM_strong_coupling_to(sm, MAh(gO1)); calculate_eff_CpAhVGVG(gO1); } PHYSICAL(MFt) = saved_mt; model.set_scale(scale); model.set(saved_parameters); } void CMSSMNoFV_effective_couplings::set_model(const CMSSMNoFV_mass_eigenstates& model_) { model = model_; copy_mixing_matrices_from_model(); } void CMSSMNoFV_effective_couplings::copy_mixing_matrices_from_model() { ZD = MODELPARAMETER(ZD); ZU = MODELPARAMETER(ZU); ZE = MODELPARAMETER(ZE); ZM = MODELPARAMETER(ZM); ZTau = MODELPARAMETER(ZTau); ZS = MODELPARAMETER(ZS); ZC = MODELPARAMETER(ZC); ZB = MODELPARAMETER(ZB); ZT = MODELPARAMETER(ZT); ZH = MODELPARAMETER(ZH); ZA = MODELPARAMETER(ZA); ZP = MODELPARAMETER(ZP); ZN = MODELPARAMETER(ZN); UM = MODELPARAMETER(UM); UP = MODELPARAMETER(UP); ZZ = MODELPARAMETER(ZZ); } standard_model::Standard_model CMSSMNoFV_effective_couplings::initialise_SM() const { standard_model::Standard_model sm; sm.set_loops(2); sm.set_thresholds(2); sm.set_physical_input(physical_input); sm.initialise_from_input(qedqcd); return sm; } void CMSSMNoFV_effective_couplings::run_SM_strong_coupling_to(standard_model::Standard_model sm, double m) { sm.run_to(m); model.set_g3(sm.get_g3()); } std::complex CMSSMNoFV_effective_couplings::scalar_scalar_qcd_factor(double m_decay, double m_loop) const { std::complex result(1.0, 0.0); if (include_qcd_corrections) { const auto g3 = MODELPARAMETER(g3); if (m_loop > m_decay) { result = 1 + 0.06754745576155852*Sqr(g3); } } return result; } std::complex CMSSMNoFV_effective_couplings::scalar_fermion_qcd_factor(double m_decay, double m_loop) const { std::complex result(1.0, 0.0); if (include_qcd_corrections) { const auto g3 = MODELPARAMETER(g3); result = 1.0 + 0.025330295910584444*Sqr(g3) * scalar_diphoton_fermion_loop(m_decay, m_loop); } return result; } std::complex CMSSMNoFV_effective_couplings::pseudoscalar_fermion_qcd_factor(double m_decay, double m_loop) const { std::complex result(1.0, 0.0); if (include_qcd_corrections) { const auto g3 = MODELPARAMETER(g3); result = 1.0 + 0.025330295910584444*Sqr(g3) * pseudoscalar_diphoton_fermion_loop(m_decay, m_loop); } return result; } double CMSSMNoFV_effective_couplings::number_of_active_flavours(double m) const { if (m < qedqcd.displayMbMb()) { return 4.0; } else if (m < qedqcd.displayPoleMt()) { return 5.0; } else { return 6.0; } } double CMSSMNoFV_effective_couplings::scalar_scaling_factor(double m) const { const double Nf = number_of_active_flavours(m); const double mtpole = qedqcd.displayPoleMt(); const double l = Log(Sqr(m) / Sqr(mtpole)); const auto g3 = MODELPARAMETER(g3); const double nlo_qcd = 0.025330295910584444*(23.75 - 1.1666666666666667*Nf)* Sqr(g3); const double nnlo_qcd = 0.000641623890917771*Quad(g3)*(370.1956513893174 + 2.375*l + (-47.18640261449638 + 0.6666666666666666*l)*Nf + 0.9017702481178881*Sqr(Nf)); const double nnnlo_qcd = 0.000016252523020247696*Power6(g3)*(467.683620788 + 122.440972222*l + 10.9409722222*Sqr(l)); return Sqrt(1.0 + nlo_qcd + nnlo_qcd + nnnlo_qcd); } double CMSSMNoFV_effective_couplings::pseudoscalar_scaling_factor(double m) const { const double Nf = number_of_active_flavours(m); const double mtpole = qedqcd.displayPoleMt(); const double l = Log(Sqr(m) / Sqr(mtpole)); const auto g3 = MODELPARAMETER(g3); const double nlo_qcd = 0.025330295910584444*(24.25 - 1.1666666666666667*Nf)* Sqr(g3); const double nnlo_qcd = 0.000641623890917771*(171.54400563089382 + 5*l)*Quad (g3); const double nnnlo_qcd = 0; return Sqrt(1.0 + nlo_qcd + nnlo_qcd + nnnlo_qcd); } double CMSSMNoFV_effective_couplings::get_hhVPVP_partial_width(int gO1) const { const double mass = PHYSICAL(Mhh)(gO1); return 0.0049735919716217296 * Power(mass, 3.0) * AbsSqr(eff_CphhVPVP(gO1)); } double CMSSMNoFV_effective_couplings::get_hhVGVG_partial_width(int gO1) const { const double mass = PHYSICAL(Mhh)(gO1); return 0.039788735772973836 * Power(mass, 3.0) * AbsSqr(eff_CphhVGVG(gO1)); } double CMSSMNoFV_effective_couplings::get_AhVPVP_partial_width(int gO1) const { const double mass = PHYSICAL(MAh)(gO1); return 0.0049735919716217296 * Power(mass, 3.0) * AbsSqr(eff_CpAhVPVP(gO1)); } double CMSSMNoFV_effective_couplings::get_AhVGVG_partial_width(int gO1) const { const double mass = PHYSICAL(MAh)(gO1); return 0.039788735772973836 * Power(mass, 3.0) * AbsSqr(eff_CpAhVGVG(gO1)); } std::complex CMSSMNoFV_effective_couplings::CphhconjVWmVWm(int gI2) const { const auto g2 = MODELPARAMETER(g2); const auto vd = MODELPARAMETER(vd); const auto vu = MODELPARAMETER(vu); const std::complex result = 0.5*Sqr(g2)*(vd*ZH(gI2,0) + vu*ZH(gI2,1) ); return result; } std::complex CMSSMNoFV_effective_couplings::CpbarFdFdhhPL(int gI1) const { const auto Yd = MODELPARAMETER(Yd); const std::complex result = -0.7071067811865475*Yd(0,0)*ZH(gI1,0); return result; } std::complex CMSSMNoFV_effective_couplings::CpbarFdFdAhPL(int gI2) const { const auto Yd = MODELPARAMETER(Yd); const std::complex result = std::complex(0., -0.7071067811865475)*Yd(0,0)*ZA(gI2,0); return result; } std::complex CMSSMNoFV_effective_couplings::CpbarFsFshhPL(int gI1) const { const auto Yd = MODELPARAMETER(Yd); const std::complex result = -0.7071067811865475*Yd(1,1)*ZH(gI1,0); return result; } std::complex CMSSMNoFV_effective_couplings::CpbarFsFsAhPL(int gI2) const { const auto Yd = MODELPARAMETER(Yd); const std::complex result = std::complex(0., -0.7071067811865475)*Yd(1,1)*ZA(gI2,0); return result; } std::complex CMSSMNoFV_effective_couplings::CpbarFbFbhhPL(int gI1) const { const auto Yd = MODELPARAMETER(Yd); const std::complex result = -0.7071067811865475*Yd(2,2)*ZH(gI1,0); return result; } std::complex CMSSMNoFV_effective_couplings::CpbarFbFbAhPL(int gI2) const { const auto Yd = MODELPARAMETER(Yd); const std::complex result = std::complex(0., -0.7071067811865475)*Yd(2,2)*ZA(gI2,0); return result; } std::complex CMSSMNoFV_effective_couplings::CpbarFuFuhhPL(int gI1) const { const auto Yu = MODELPARAMETER(Yu); const std::complex result = -0.7071067811865475*Yu(0,0)*ZH(gI1,1); return result; } std::complex CMSSMNoFV_effective_couplings::CpbarFuFuAhPL(int gI2) const { const auto Yu = MODELPARAMETER(Yu); const std::complex result = std::complex(0., -0.7071067811865475)*Yu(0,0)*ZA(gI2,1); return result; } std::complex CMSSMNoFV_effective_couplings::CpbarFcFchhPL(int gI1) const { const auto Yu = MODELPARAMETER(Yu); const std::complex result = -0.7071067811865475*Yu(1,1)*ZH(gI1,1); return result; } std::complex CMSSMNoFV_effective_couplings::CpbarFcFcAhPL(int gI2) const { const auto Yu = MODELPARAMETER(Yu); const std::complex result = std::complex(0., -0.7071067811865475)*Yu(1,1)*ZA(gI2,1); return result; } std::complex CMSSMNoFV_effective_couplings::CpbarFtFthhPL(int gI1) const { const auto Yu = MODELPARAMETER(Yu); const std::complex result = -0.7071067811865475*Yu(2,2)*ZH(gI1,1); return result; } std::complex CMSSMNoFV_effective_couplings::CpbarFtFtAhPL(int gI2) const { const auto Yu = MODELPARAMETER(Yu); const std::complex result = std::complex(0., -0.7071067811865475)*Yu(2,2)*ZA(gI2,1); return result; } std::complex CMSSMNoFV_effective_couplings::CpbarFeFehhPL(int gI1) const { const auto Ye = MODELPARAMETER(Ye); const std::complex result = -0.7071067811865475*Ye(0,0)*ZH(gI1,0); return result; } std::complex CMSSMNoFV_effective_couplings::CpbarFeFeAhPL(int gI2) const { const auto Ye = MODELPARAMETER(Ye); const std::complex result = std::complex(0., -0.7071067811865475)*Ye(0,0)*ZA(gI2,0); return result; } std::complex CMSSMNoFV_effective_couplings::CpbarFmFmhhPL(int gI1) const { const auto Ye = MODELPARAMETER(Ye); const std::complex result = -0.7071067811865475*Ye(1,1)*ZH(gI1,0); return result; } std::complex CMSSMNoFV_effective_couplings::CpbarFmFmAhPL(int gI2) const { const auto Ye = MODELPARAMETER(Ye); const std::complex result = std::complex(0., -0.7071067811865475)*Ye(1,1)*ZA(gI2,0); return result; } std::complex CMSSMNoFV_effective_couplings::CpbarFtauFtauhhPL(int gI1) const { const auto Ye = MODELPARAMETER(Ye); const std::complex result = -0.7071067811865475*Ye(2,2)*ZH(gI1,0); return result; } std::complex CMSSMNoFV_effective_couplings::CpbarFtauFtauAhPL(int gI2) const { const auto Ye = MODELPARAMETER(Ye); const std::complex result = std::complex(0., -0.7071067811865475)*Ye(2,2)*ZA(gI2,0); return result; } std::complex CMSSMNoFV_effective_couplings::CphhSdconjSd(int gt1, int gt2, int gt3) const { const auto TYd = MODELPARAMETER(TYd); const auto g1 = MODELPARAMETER(g1); const auto g2 = MODELPARAMETER(g2); const auto vd = MODELPARAMETER(vd); const auto vu = MODELPARAMETER(vu); const auto Yd = MODELPARAMETER(Yd); const auto Mu = MODELPARAMETER(Mu); const std::complex result = 0.05*(-2*Conj(ZD(gt2,1))*( 7.0710678118654755*Conj(TYd(0,0))*ZD(gt3,0)*ZH(gt1,0) - 7.0710678118654755* Conj(Yd(0,0))*Mu*ZD(gt3,0)*ZH(gt1,1) + ZD(gt3,1)*(-(vd*(-10*AbsSqr(Yd(0,0)) + Sqr(g1))*ZH(gt1,0)) + vu*Sqr(g1)*ZH(gt1,1))) + Conj(ZD(gt2,0))*(ZD(gt3,0)* (vd*(-20*AbsSqr(Yd(0,0)) + Sqr(g1) + 5*Sqr(g2))*ZH(gt1,0) - vu*(Sqr(g1) + 5* Sqr(g2))*ZH(gt1,1)) + 14.142135623730951*ZD(gt3,1)*(Conj(Mu)*Yd(0,0)*ZH(gt1, 1) - ZH(gt1,0)*TYd(0,0)))); return result; } std::complex CMSSMNoFV_effective_couplings::CphhSuconjSu(int gt1, int gt2, int gt3) const { const auto TYu = MODELPARAMETER(TYu); const auto g1 = MODELPARAMETER(g1); const auto g2 = MODELPARAMETER(g2); const auto vd = MODELPARAMETER(vd); const auto vu = MODELPARAMETER(vu); const auto Yu = MODELPARAMETER(Yu); const auto Mu = MODELPARAMETER(Mu); const std::complex result = 0.05*(2*Conj(ZU(gt2,1))*( -7.0710678118654755*Conj(TYu(0,0))*ZH(gt1,1)*ZU(gt3,0) + 2*Sqr(g1)*(-(vd*ZH( gt1,0)) + vu*ZH(gt1,1))*ZU(gt3,1) + 5*Conj(Yu(0,0))*(1.4142135623730951*Mu* ZH(gt1,0)*ZU(gt3,0) - 2*vu*Yu(0,0)*ZH(gt1,1)*ZU(gt3,1))) + Conj(ZU(gt2,0))*( ZH(gt1,0)*(vd*(Sqr(g1) - 5*Sqr(g2))*ZU(gt3,0) + 14.142135623730951*Conj(Mu)* Yu(0,0)*ZU(gt3,1)) - ZH(gt1,1)*(vu*(20*AbsSqr(Yu(0,0)) + Sqr(g1) - 5*Sqr(g2) )*ZU(gt3,0) + 14.142135623730951*ZU(gt3,1)*TYu(0,0)))); return result; } std::complex CMSSMNoFV_effective_couplings::CphhSeconjSe(int gt1, int gt2, int gt3) const { const auto TYe = MODELPARAMETER(TYe); const auto g1 = MODELPARAMETER(g1); const auto g2 = MODELPARAMETER(g2); const auto vd = MODELPARAMETER(vd); const auto vu = MODELPARAMETER(vu); const auto Ye = MODELPARAMETER(Ye); const auto Mu = MODELPARAMETER(Mu); const std::complex result = 0.05*(-2*Conj(ZE(gt2,1))*( 7.0710678118654755*Conj(TYe(0,0))*ZE(gt3,0)*ZH(gt1,0) - 7.0710678118654755* Conj(Ye(0,0))*Mu*ZE(gt3,0)*ZH(gt1,1) + ZE(gt3,1)*((10*vd*AbsSqr(Ye(0,0)) - 3 *vd*Sqr(g1))*ZH(gt1,0) + 3*vu*Sqr(g1)*ZH(gt1,1))) + Conj(ZE(gt2,0))*(ZE(gt3, 0)*(vd*(-20*AbsSqr(Ye(0,0)) - 3*Sqr(g1) + 5*Sqr(g2))*ZH(gt1,0) + vu*(3*Sqr( g1) - 5*Sqr(g2))*ZH(gt1,1)) + 14.142135623730951*ZE(gt3,1)*(Conj(Mu)*Ye(0,0) *ZH(gt1,1) - ZH(gt1,0)*TYe(0,0)))); return result; } std::complex CMSSMNoFV_effective_couplings::CphhSmconjSm(int gt1, int gt2, int gt3) const { const auto TYe = MODELPARAMETER(TYe); const auto g1 = MODELPARAMETER(g1); const auto g2 = MODELPARAMETER(g2); const auto vd = MODELPARAMETER(vd); const auto vu = MODELPARAMETER(vu); const auto Ye = MODELPARAMETER(Ye); const auto Mu = MODELPARAMETER(Mu); const std::complex result = 0.25*(-2*Conj(ZM(gt2,1))*( 1.4142135623730951*Conj(TYe(1,1))*ZH(gt1,0)*ZM(gt3,0) + 0.6*Sqr(g1)*(-(vd*ZH (gt1,0)) + vu*ZH(gt1,1))*ZM(gt3,1) + Conj(Ye(1,1))*(-1.4142135623730951*Mu* ZH(gt1,1)*ZM(gt3,0) + 2*vd*Ye(1,1)*ZH(gt1,0)*ZM(gt3,1))) + Conj(ZM(gt2,0))*( ZH(gt1,1)*(vu*(0.6*Sqr(g1) - Sqr(g2))*ZM(gt3,0) + 2.8284271247461903*Conj(Mu )*Ye(1,1)*ZM(gt3,1)) - ZH(gt1,0)*(vd*(4*AbsSqr(Ye(1,1)) + 0.6*Sqr(g1) - Sqr( g2))*ZM(gt3,0) + 2.8284271247461903*ZM(gt3,1)*TYe(1,1)))); return result; } std::complex CMSSMNoFV_effective_couplings::CphhStauconjStau(int gt1, int gt2, int gt3) const { const auto TYe = MODELPARAMETER(TYe); const auto g1 = MODELPARAMETER(g1); const auto g2 = MODELPARAMETER(g2); const auto vd = MODELPARAMETER(vd); const auto vu = MODELPARAMETER(vu); const auto Ye = MODELPARAMETER(Ye); const auto Mu = MODELPARAMETER(Mu); const std::complex result = 0.25*(-2*Conj(ZTau(gt2,1))*( 1.4142135623730951*Conj(TYe(2,2))*ZH(gt1,0)*ZTau(gt3,0) + 0.6*Sqr(g1)*(-(vd* ZH(gt1,0)) + vu*ZH(gt1,1))*ZTau(gt3,1) + Conj(Ye(2,2))*(-1.4142135623730951* Mu*ZH(gt1,1)*ZTau(gt3,0) + 2*vd*Ye(2,2)*ZH(gt1,0)*ZTau(gt3,1))) + Conj(ZTau( gt2,0))*(ZH(gt1,1)*(vu*(0.6*Sqr(g1) - Sqr(g2))*ZTau(gt3,0) + 2.8284271247461903*Conj(Mu)*Ye(2,2)*ZTau(gt3,1)) - ZH(gt1,0)*(vd*(4*AbsSqr( Ye(2,2)) + 0.6*Sqr(g1) - Sqr(g2))*ZTau(gt3,0) + 2.8284271247461903*ZTau(gt3, 1)*TYe(2,2)))); return result; } std::complex CMSSMNoFV_effective_couplings::CphhSsconjSs(int gt1, int gt2, int gt3) const { const auto TYd = MODELPARAMETER(TYd); const auto g1 = MODELPARAMETER(g1); const auto g2 = MODELPARAMETER(g2); const auto vd = MODELPARAMETER(vd); const auto vu = MODELPARAMETER(vu); const auto Yd = MODELPARAMETER(Yd); const auto Mu = MODELPARAMETER(Mu); const std::complex result = 0.05*(-2*Conj(ZS(gt2,1))*( 7.0710678118654755*Conj(TYd(1,1))*ZH(gt1,0)*ZS(gt3,0) + Sqr(g1)*(-(vd*ZH(gt1 ,0)) + vu*ZH(gt1,1))*ZS(gt3,1) - 5*Conj(Yd(1,1))*(1.4142135623730951*Mu*ZH( gt1,1)*ZS(gt3,0) - 2*vd*Yd(1,1)*ZH(gt1,0)*ZS(gt3,1))) + Conj(ZS(gt2,0))*(-( ZH(gt1,1)*(vu*(Sqr(g1) + 5*Sqr(g2))*ZS(gt3,0) - 14.142135623730951*Conj(Mu)* Yd(1,1)*ZS(gt3,1))) + ZH(gt1,0)*(vd*(-20*AbsSqr(Yd(1,1)) + Sqr(g1) + 5*Sqr( g2))*ZS(gt3,0) - 14.142135623730951*ZS(gt3,1)*TYd(1,1)))); return result; } std::complex CMSSMNoFV_effective_couplings::CphhScconjSc(int gt1, int gt2, int gt3) const { const auto TYu = MODELPARAMETER(TYu); const auto g1 = MODELPARAMETER(g1); const auto g2 = MODELPARAMETER(g2); const auto vd = MODELPARAMETER(vd); const auto vu = MODELPARAMETER(vu); const auto Yu = MODELPARAMETER(Yu); const auto Mu = MODELPARAMETER(Mu); const std::complex result = 0.05*(2*Conj(ZC(gt2,1))*( -7.0710678118654755*Conj(TYu(1,1))*ZC(gt3,0)*ZH(gt1,1) + 2*Sqr(g1)*ZC(gt3,1) *(-(vd*ZH(gt1,0)) + vu*ZH(gt1,1)) + 5*Conj(Yu(1,1))*(1.4142135623730951*Mu* ZC(gt3,0)*ZH(gt1,0) - 2*vu*Yu(1,1)*ZC(gt3,1)*ZH(gt1,1))) + Conj(ZC(gt2,0))*( ZC(gt3,0)*(vd*(Sqr(g1) - 5*Sqr(g2))*ZH(gt1,0) - vu*(20*AbsSqr(Yu(1,1)) + Sqr (g1) - 5*Sqr(g2))*ZH(gt1,1)) + 14.142135623730951*ZC(gt3,1)*(Conj(Mu)*Yu(1,1 )*ZH(gt1,0) - ZH(gt1,1)*TYu(1,1)))); return result; } std::complex CMSSMNoFV_effective_couplings::CphhSbconjSb(int gt1, int gt2, int gt3) const { const auto TYd = MODELPARAMETER(TYd); const auto g1 = MODELPARAMETER(g1); const auto g2 = MODELPARAMETER(g2); const auto vd = MODELPARAMETER(vd); const auto vu = MODELPARAMETER(vu); const auto Yd = MODELPARAMETER(Yd); const auto Mu = MODELPARAMETER(Mu); const std::complex result = 0.05*(-2*Conj(ZB(gt2,1))*( 7.0710678118654755*Conj(TYd(2,2))*ZB(gt3,0)*ZH(gt1,0) - 7.0710678118654755* Conj(Yd(2,2))*Mu*ZB(gt3,0)*ZH(gt1,1) + ZB(gt3,1)*(-(vd*(-10*AbsSqr(Yd(2,2)) + Sqr(g1))*ZH(gt1,0)) + vu*Sqr(g1)*ZH(gt1,1))) + Conj(ZB(gt2,0))*(ZB(gt3,0)* (vd*(-20*AbsSqr(Yd(2,2)) + Sqr(g1) + 5*Sqr(g2))*ZH(gt1,0) - vu*(Sqr(g1) + 5* Sqr(g2))*ZH(gt1,1)) + 14.142135623730951*ZB(gt3,1)*(Conj(Mu)*Yd(2,2)*ZH(gt1, 1) - ZH(gt1,0)*TYd(2,2)))); return result; } std::complex CMSSMNoFV_effective_couplings::CphhStconjSt(int gt1, int gt2, int gt3) const { const auto TYu = MODELPARAMETER(TYu); const auto g1 = MODELPARAMETER(g1); const auto g2 = MODELPARAMETER(g2); const auto vd = MODELPARAMETER(vd); const auto vu = MODELPARAMETER(vu); const auto Yu = MODELPARAMETER(Yu); const auto Mu = MODELPARAMETER(Mu); const std::complex result = 0.05*(2*Conj(ZT(gt2,1))*( -7.0710678118654755*Conj(TYu(2,2))*ZH(gt1,1)*ZT(gt3,0) + 2*Sqr(g1)*(-(vd*ZH( gt1,0)) + vu*ZH(gt1,1))*ZT(gt3,1) + 5*Conj(Yu(2,2))*(1.4142135623730951*Mu* ZH(gt1,0)*ZT(gt3,0) - 2*vu*Yu(2,2)*ZH(gt1,1)*ZT(gt3,1))) + Conj(ZT(gt2,0))*( ZH(gt1,0)*(vd*(Sqr(g1) - 5*Sqr(g2))*ZT(gt3,0) + 14.142135623730951*Conj(Mu)* Yu(2,2)*ZT(gt3,1)) - ZH(gt1,1)*(vu*(20*AbsSqr(Yu(2,2)) + Sqr(g1) - 5*Sqr(g2) )*ZT(gt3,0) + 14.142135623730951*ZT(gt3,1)*TYu(2,2)))); return result; } std::complex CMSSMNoFV_effective_couplings::CphhHpmconjHpm(int gt1, int gt2, int gt3) const { const auto g1 = MODELPARAMETER(g1); const auto g2 = MODELPARAMETER(g2); const auto vd = MODELPARAMETER(vd); const auto vu = MODELPARAMETER(vu); const std::complex result = 0.25*(-(ZH(gt1,0)*(ZP(gt2,0)*(vd*(0.6* Sqr(g1) + Sqr(g2))*ZP(gt3,0) + vu*Sqr(g2)*ZP(gt3,1)) + ZP(gt2,1)*(vu*Sqr(g2) *ZP(gt3,0) + vd*(-0.6*Sqr(g1) + Sqr(g2))*ZP(gt3,1)))) + ZH(gt1,1)*(ZP(gt2,0) *(vu*(0.6*Sqr(g1) - Sqr(g2))*ZP(gt3,0) - vd*Sqr(g2)*ZP(gt3,1)) - ZP(gt2,1)*( vd*Sqr(g2)*ZP(gt3,0) + vu*(0.6*Sqr(g1) + Sqr(g2))*ZP(gt3,1)))); return result; } std::complex CMSSMNoFV_effective_couplings::CpbarChaChahhPL(int gt3, int gt1, int gt2) const { const auto g2 = MODELPARAMETER(g2); const std::complex result = -0.7071067811865475*g2*(Conj(UM(gt1,1))* Conj(UP(gt3,0))*ZH(gt2,0) + Conj(UM(gt1,0))*Conj(UP(gt3,1))*ZH(gt2,1)); return result; } std::complex CMSSMNoFV_effective_couplings::CpAhSdconjSd(int gt1, int gt2, int gt3) const { const auto TYd = MODELPARAMETER(TYd); const auto Yd = MODELPARAMETER(Yd); const auto Mu = MODELPARAMETER(Mu); const std::complex result = std::complex(0., 0.7071067811865475)*(Conj(ZD(gt2,1))*(Conj(TYd(0,0))*ZA(gt1,0) + Conj(Yd(0,0 ))*Mu*ZA(gt1,1))*ZD(gt3,0) - Conj(ZD(gt2,0))*ZD(gt3,1)*(Conj(Mu)*Yd(0,0)*ZA( gt1,1) + ZA(gt1,0)*TYd(0,0))); return result; } std::complex CMSSMNoFV_effective_couplings::CpAhSuconjSu(int gt1, int gt2, int gt3) const { const auto TYu = MODELPARAMETER(TYu); const auto Yu = MODELPARAMETER(Yu); const auto Mu = MODELPARAMETER(Mu); const std::complex result = std::complex(0., 0.7071067811865475)*(Conj(Yu(0,0))*Conj(ZU(gt2,1))*Mu*ZA(gt1,0)*ZU(gt3,0) + Conj(ZU(gt2,1))*Conj(TYu(0,0))*ZA(gt1,1)*ZU(gt3,0) - Conj(ZU(gt2,0))*ZU(gt3, 1)*(Conj(Mu)*Yu(0,0)*ZA(gt1,0) + ZA(gt1,1)*TYu(0,0))); return result; } std::complex CMSSMNoFV_effective_couplings::CpAhSeconjSe(int gt1, int gt2, int gt3) const { const auto TYe = MODELPARAMETER(TYe); const auto Ye = MODELPARAMETER(Ye); const auto Mu = MODELPARAMETER(Mu); const std::complex result = std::complex(0., 0.7071067811865475)*(Conj(ZE(gt2,1))*(Conj(TYe(0,0))*ZA(gt1,0) + Conj(Ye(0,0 ))*Mu*ZA(gt1,1))*ZE(gt3,0) - Conj(ZE(gt2,0))*ZE(gt3,1)*(Conj(Mu)*Ye(0,0)*ZA( gt1,1) + ZA(gt1,0)*TYe(0,0))); return result; } std::complex CMSSMNoFV_effective_couplings::CpAhSmconjSm(int gt1, int gt2, int gt3) const { const auto TYe = MODELPARAMETER(TYe); const auto Ye = MODELPARAMETER(Ye); const auto Mu = MODELPARAMETER(Mu); const std::complex result = std::complex(0., 0.7071067811865475)*(Conj(ZM(gt2,1))*(Conj(TYe(1,1))*ZA(gt1,0) + Conj(Ye(1,1 ))*Mu*ZA(gt1,1))*ZM(gt3,0) - Conj(ZM(gt2,0))*ZM(gt3,1)*(Conj(Mu)*Ye(1,1)*ZA( gt1,1) + ZA(gt1,0)*TYe(1,1))); return result; } std::complex CMSSMNoFV_effective_couplings::CpAhStauconjStau(int gt1, int gt2, int gt3) const { const auto TYe = MODELPARAMETER(TYe); const auto Ye = MODELPARAMETER(Ye); const auto Mu = MODELPARAMETER(Mu); const std::complex result = std::complex(0., 0.7071067811865475)*(Conj(ZTau(gt2,1))*(Conj(TYe(2,2))*ZA(gt1,0) + Conj(Ye(2 ,2))*Mu*ZA(gt1,1))*ZTau(gt3,0) - Conj(ZTau(gt2,0))*ZTau(gt3,1)*(Conj(Mu)*Ye( 2,2)*ZA(gt1,1) + ZA(gt1,0)*TYe(2,2))); return result; } std::complex CMSSMNoFV_effective_couplings::CpAhSsconjSs(int gt1, int gt2, int gt3) const { const auto TYd = MODELPARAMETER(TYd); const auto Yd = MODELPARAMETER(Yd); const auto Mu = MODELPARAMETER(Mu); const std::complex result = std::complex(0., 0.7071067811865475)*(Conj(ZS(gt2,1))*(Conj(TYd(1,1))*ZA(gt1,0) + Conj(Yd(1,1 ))*Mu*ZA(gt1,1))*ZS(gt3,0) - Conj(ZS(gt2,0))*ZS(gt3,1)*(Conj(Mu)*Yd(1,1)*ZA( gt1,1) + ZA(gt1,0)*TYd(1,1))); return result; } std::complex CMSSMNoFV_effective_couplings::CpAhScconjSc(int gt1, int gt2, int gt3) const { const auto TYu = MODELPARAMETER(TYu); const auto Yu = MODELPARAMETER(Yu); const auto Mu = MODELPARAMETER(Mu); const std::complex result = std::complex(0., 0.7071067811865475)*(Conj(Yu(1,1))*Conj(ZC(gt2,1))*Mu*ZA(gt1,0)*ZC(gt3,0) + Conj(ZC(gt2,1))*Conj(TYu(1,1))*ZA(gt1,1)*ZC(gt3,0) - Conj(ZC(gt2,0))*ZC(gt3, 1)*(Conj(Mu)*Yu(1,1)*ZA(gt1,0) + ZA(gt1,1)*TYu(1,1))); return result; } std::complex CMSSMNoFV_effective_couplings::CpAhSbconjSb(int gt1, int gt2, int gt3) const { const auto TYd = MODELPARAMETER(TYd); const auto Yd = MODELPARAMETER(Yd); const auto Mu = MODELPARAMETER(Mu); const std::complex result = std::complex(0., 0.7071067811865475)*(Conj(ZB(gt2,1))*(Conj(TYd(2,2))*ZA(gt1,0) + Conj(Yd(2,2 ))*Mu*ZA(gt1,1))*ZB(gt3,0) - Conj(ZB(gt2,0))*ZB(gt3,1)*(Conj(Mu)*Yd(2,2)*ZA( gt1,1) + ZA(gt1,0)*TYd(2,2))); return result; } std::complex CMSSMNoFV_effective_couplings::CpAhStconjSt(int gt1, int gt2, int gt3) const { const auto TYu = MODELPARAMETER(TYu); const auto Yu = MODELPARAMETER(Yu); const auto Mu = MODELPARAMETER(Mu); const std::complex result = std::complex(0., 0.7071067811865475)*(Conj(Yu(2,2))*Conj(ZT(gt2,1))*Mu*ZA(gt1,0)*ZT(gt3,0) + Conj(ZT(gt2,1))*Conj(TYu(2,2))*ZA(gt1,1)*ZT(gt3,0) - Conj(ZT(gt2,0))*ZT(gt3, 1)*(Conj(Mu)*Yu(2,2)*ZA(gt1,0) + ZA(gt1,1)*TYu(2,2))); return result; } std::complex CMSSMNoFV_effective_couplings::CpAhHpmconjHpm(int gt1, int gt2, int gt3) const { const auto g2 = MODELPARAMETER(g2); const auto vd = MODELPARAMETER(vd); const auto vu = MODELPARAMETER(vu); const std::complex result = std::complex(0,-0.25)*Sqr(g2)*( vu*ZA(gt1,0) + vd*ZA(gt1,1))*(ZP(gt2,1)*ZP(gt3,0) - ZP(gt2,0)*ZP(gt3,1)); return result; } std::complex CMSSMNoFV_effective_couplings::CpbarChaChaAhPL(int gt3, int gt2, int gt1) const { const auto g2 = MODELPARAMETER(g2); const std::complex result = std::complex(0., 0.7071067811865475)*g2*(Conj(UM(gt2,1))*Conj(UP(gt3,0))*ZA(gt1,0) + Conj(UM( gt2,0))*Conj(UP(gt3,1))*ZA(gt1,1)); return result; } void CMSSMNoFV_effective_couplings::calculate_eff_CphhVPVP(int gO1) { const auto vd = MODELPARAMETER(vd); const auto vu = MODELPARAMETER(vu); const auto MFd = MODELPARAMETER(MFd); const auto MFs = MODELPARAMETER(MFs); const auto MFb = MODELPARAMETER(MFb); const auto MFu = MODELPARAMETER(MFu); const auto MFc = MODELPARAMETER(MFc); const auto MFt = MODELPARAMETER(MFt); const auto MFe = MODELPARAMETER(MFe); const auto MFm = MODELPARAMETER(MFm); const auto MFtau = MODELPARAMETER(MFtau); const auto MSd = MODELPARAMETER(MSd); const auto MSu = MODELPARAMETER(MSu); const auto MSe = MODELPARAMETER(MSe); const auto MSm = MODELPARAMETER(MSm); const auto MStau = MODELPARAMETER(MStau); const auto MSs = MODELPARAMETER(MSs); const auto MSc = MODELPARAMETER(MSc); const auto MSb = MODELPARAMETER(MSb); const auto MSt = MODELPARAMETER(MSt); const auto MHpm = MODELPARAMETER(MHpm); const auto MCha = MODELPARAMETER(MCha); const auto MVWm = MODELPARAMETER(MVWm); const auto decay_mass = PHYSICAL(Mhh)(gO1); const auto decay_scale = 0.25 * Sqr(decay_mass); const auto saved_ZH = ZH; ZH = PHYSICAL(ZH); const auto vev = Sqrt(Sqr(vd) + Sqr(vu)); std::complex result = 0; result += 0.3333333333333333 * scalar_fermion_qcd_factor(decay_mass, MFd) * CpbarFdFdhhPL(gO1) * vev * AS12(decay_scale / Sqr(MFd)) / MFd; result += 0.3333333333333333 * scalar_fermion_qcd_factor(decay_mass, MFs) * CpbarFsFshhPL(gO1) * vev * AS12(decay_scale / Sqr(MFs)) / MFs; result += 0.3333333333333333 * scalar_fermion_qcd_factor(decay_mass, MFb) * CpbarFbFbhhPL(gO1) * vev * AS12(decay_scale / Sqr(MFb)) / MFb; result += 1.3333333333333333 * scalar_fermion_qcd_factor(decay_mass, MFu) * CpbarFuFuhhPL(gO1) * vev * AS12(decay_scale / Sqr(MFu)) / MFu; result += 1.3333333333333333 * scalar_fermion_qcd_factor(decay_mass, MFc) * CpbarFcFchhPL(gO1) * vev * AS12(decay_scale / Sqr(MFc)) / MFc; result += 1.3333333333333333 * scalar_fermion_qcd_factor(decay_mass, MFt) * CpbarFtFthhPL(gO1) * vev * AS12(decay_scale / Sqr(MFt)) / MFt; result += CpbarFeFehhPL(gO1) * vev * AS12(decay_scale / Sqr(MFe)) / MFe; result += CpbarFmFmhhPL(gO1) * vev * AS12(decay_scale / Sqr(MFm)) / MFm; result += CpbarFtauFtauhhPL(gO1) * vev * AS12(decay_scale / Sqr(MFtau)) / MFtau; for (int gI1 = 0; gI1 < 2; ++gI1) { result += 0.16666666666666666 * scalar_scalar_qcd_factor(decay_mass, MSd(gI1)) * CphhSdconjSd(gO1, gI1, gI1) * vev * AS0(decay_scale / Sqr(MSd (gI1))) / Sqr(MSd(gI1)); } for (int gI1 = 0; gI1 < 2; ++gI1) { result += 0.6666666666666666 * scalar_scalar_qcd_factor(decay_mass, MSu(gI1)) * CphhSuconjSu(gO1, gI1, gI1) * vev * AS0(decay_scale / Sqr(MSu (gI1))) / Sqr(MSu(gI1)); } for (int gI1 = 0; gI1 < 2; ++gI1) { result += 0.5 * CphhSeconjSe(gO1, gI1, gI1) * vev * AS0(decay_scale / Sqr(MSe(gI1))) / Sqr(MSe(gI1)); } for (int gI1 = 0; gI1 < 2; ++gI1) { result += 0.5 * CphhSmconjSm(gO1, gI1, gI1) * vev * AS0(decay_scale / Sqr(MSm(gI1))) / Sqr(MSm(gI1)); } for (int gI1 = 0; gI1 < 2; ++gI1) { result += 0.5 * CphhStauconjStau(gO1, gI1, gI1) * vev * AS0( decay_scale / Sqr(MStau(gI1))) / Sqr(MStau(gI1)); } for (int gI1 = 0; gI1 < 2; ++gI1) { result += 0.16666666666666666 * scalar_scalar_qcd_factor(decay_mass, MSs(gI1)) * CphhSsconjSs(gO1, gI1, gI1) * vev * AS0(decay_scale / Sqr(MSs (gI1))) / Sqr(MSs(gI1)); } for (int gI1 = 0; gI1 < 2; ++gI1) { result += 0.6666666666666666 * scalar_scalar_qcd_factor(decay_mass, MSc(gI1)) * CphhScconjSc(gO1, gI1, gI1) * vev * AS0(decay_scale / Sqr(MSc (gI1))) / Sqr(MSc(gI1)); } for (int gI1 = 0; gI1 < 2; ++gI1) { result += 0.16666666666666666 * scalar_scalar_qcd_factor(decay_mass, MSb(gI1)) * CphhSbconjSb(gO1, gI1, gI1) * vev * AS0(decay_scale / Sqr(MSb (gI1))) / Sqr(MSb(gI1)); } for (int gI1 = 0; gI1 < 2; ++gI1) { result += 0.6666666666666666 * scalar_scalar_qcd_factor(decay_mass, MSt(gI1)) * CphhStconjSt(gO1, gI1, gI1) * vev * AS0(decay_scale / Sqr(MSt (gI1))) / Sqr(MSt(gI1)); } for (int gI1 = 1; gI1 < 2; ++gI1) { result += 0.5 * CphhHpmconjHpm(gO1, gI1, gI1) * vev * AS0(decay_scale / Sqr(MHpm(gI1))) / Sqr(MHpm(gI1)); } for (int gI1 = 0; gI1 < 2; ++gI1) { result += CpbarChaChahhPL(gI1, gI1, gO1) * vev * AS12(decay_scale / Sqr(MCha(gI1))) / MCha(gI1); } result += -0.5 * CphhconjVWmVWm(gO1) * vev * AS1(decay_scale / Sqr(MVWm)) / Sqr(MVWm); result *= 0.1892681907127351 * physical_input.get(Physical_input::alpha_em_0 ) * Sqrt(qedqcd.displayFermiConstant()); ZH = saved_ZH; eff_CphhVPVP(gO1) = result; } void CMSSMNoFV_effective_couplings::calculate_eff_CphhVGVG(int gO1) { const auto vd = MODELPARAMETER(vd); const auto vu = MODELPARAMETER(vu); const auto g3 = MODELPARAMETER(g3); const auto MFd = MODELPARAMETER(MFd); const auto MFs = MODELPARAMETER(MFs); const auto MFb = MODELPARAMETER(MFb); const auto MFu = MODELPARAMETER(MFu); const auto MFc = MODELPARAMETER(MFc); const auto MFt = MODELPARAMETER(MFt); const auto MSd = MODELPARAMETER(MSd); const auto MSu = MODELPARAMETER(MSu); const auto MSs = MODELPARAMETER(MSs); const auto MSc = MODELPARAMETER(MSc); const auto MSb = MODELPARAMETER(MSb); const auto MSt = MODELPARAMETER(MSt); const double alpha_s = 0.07957747154594767*Sqr(g3); const auto decay_mass = PHYSICAL(Mhh)(gO1); const auto decay_scale = 0.25 * Sqr(decay_mass); const auto saved_ZH = ZH; ZH = PHYSICAL(ZH); const auto vev = Sqrt(Sqr(vd) + Sqr(vu)); std::complex result = 0; result += CpbarFdFdhhPL(gO1) * vev * AS12(decay_scale / Sqr(MFd)) / MFd; result += CpbarFsFshhPL(gO1) * vev * AS12(decay_scale / Sqr(MFs)) / MFs; result += CpbarFbFbhhPL(gO1) * vev * AS12(decay_scale / Sqr(MFb)) / MFb; result += CpbarFuFuhhPL(gO1) * vev * AS12(decay_scale / Sqr(MFu)) / MFu; result += CpbarFcFchhPL(gO1) * vev * AS12(decay_scale / Sqr(MFc)) / MFc; result += CpbarFtFthhPL(gO1) * vev * AS12(decay_scale / Sqr(MFt)) / MFt; for (int gI1 = 0; gI1 < 2; ++gI1) { result += 0.5 * CphhSdconjSd(gO1, gI1, gI1) * vev * AS0(decay_scale / Sqr(MSd(gI1))) / Sqr(MSd(gI1)); } for (int gI1 = 0; gI1 < 2; ++gI1) { result += 0.5 * CphhSuconjSu(gO1, gI1, gI1) * vev * AS0(decay_scale / Sqr(MSu(gI1))) / Sqr(MSu(gI1)); } for (int gI1 = 0; gI1 < 2; ++gI1) { result += 0.5 * CphhSsconjSs(gO1, gI1, gI1) * vev * AS0(decay_scale / Sqr(MSs(gI1))) / Sqr(MSs(gI1)); } for (int gI1 = 0; gI1 < 2; ++gI1) { result += 0.5 * CphhScconjSc(gO1, gI1, gI1) * vev * AS0(decay_scale / Sqr(MSc(gI1))) / Sqr(MSc(gI1)); } for (int gI1 = 0; gI1 < 2; ++gI1) { result += 0.5 * CphhSbconjSb(gO1, gI1, gI1) * vev * AS0(decay_scale / Sqr(MSb(gI1))) / Sqr(MSb(gI1)); } for (int gI1 = 0; gI1 < 2; ++gI1) { result += 0.5 * CphhStconjSt(gO1, gI1, gI1) * vev * AS0(decay_scale / Sqr(MSt(gI1))) / Sqr(MSt(gI1)); } result *= 0.75; if (include_qcd_corrections) { result *= scalar_scaling_factor(decay_mass); } result *= 0.12617879380849006 * alpha_s * Sqrt(qedqcd.displayFermiConstant() ); ZH = saved_ZH; eff_CphhVGVG(gO1) = result; } void CMSSMNoFV_effective_couplings::calculate_eff_CpAhVPVP(int gO1) { const auto vd = MODELPARAMETER(vd); const auto vu = MODELPARAMETER(vu); const auto MFd = MODELPARAMETER(MFd); const auto MFs = MODELPARAMETER(MFs); const auto MFb = MODELPARAMETER(MFb); const auto MFu = MODELPARAMETER(MFu); const auto MFc = MODELPARAMETER(MFc); const auto MFt = MODELPARAMETER(MFt); const auto MFe = MODELPARAMETER(MFe); const auto MFm = MODELPARAMETER(MFm); const auto MFtau = MODELPARAMETER(MFtau); const auto MCha = MODELPARAMETER(MCha); const auto decay_mass = PHYSICAL(MAh)(gO1); const auto decay_scale = 0.25 * Sqr(decay_mass); const auto saved_ZA = ZA; ZA = PHYSICAL(ZA); const auto vev = Sqrt(Sqr(vd) + Sqr(vu)); std::complex result = 0; result += 0.3333333333333333 * pseudoscalar_fermion_qcd_factor(decay_mass, MFd) * CpbarFdFdAhPL(gO1) * vev * AP12(decay_scale / Sqr(MFd)) / MFd; result += 0.3333333333333333 * pseudoscalar_fermion_qcd_factor(decay_mass, MFs) * CpbarFsFsAhPL(gO1) * vev * AP12(decay_scale / Sqr(MFs)) / MFs; result += 0.3333333333333333 * pseudoscalar_fermion_qcd_factor(decay_mass, MFb) * CpbarFbFbAhPL(gO1) * vev * AP12(decay_scale / Sqr(MFb)) / MFb; result += 1.3333333333333333 * pseudoscalar_fermion_qcd_factor(decay_mass, MFu) * CpbarFuFuAhPL(gO1) * vev * AP12(decay_scale / Sqr(MFu)) / MFu; result += 1.3333333333333333 * pseudoscalar_fermion_qcd_factor(decay_mass, MFc) * CpbarFcFcAhPL(gO1) * vev * AP12(decay_scale / Sqr(MFc)) / MFc; result += 1.3333333333333333 * pseudoscalar_fermion_qcd_factor(decay_mass, MFt) * CpbarFtFtAhPL(gO1) * vev * AP12(decay_scale / Sqr(MFt)) / MFt; result += CpbarFeFeAhPL(gO1) * vev * AP12(decay_scale / Sqr(MFe)) / MFe; result += CpbarFmFmAhPL(gO1) * vev * AP12(decay_scale / Sqr(MFm)) / MFm; result += CpbarFtauFtauAhPL(gO1) * vev * AP12(decay_scale / Sqr(MFtau)) / MFtau; for (int gI1 = 0; gI1 < 2; ++gI1) { result += CpbarChaChaAhPL(gI1, gI1, gO1) * vev * AP12(decay_scale / Sqr(MCha(gI1))) / MCha(gI1); } result *= 2.0; result *= 0.1892681907127351 * physical_input.get(Physical_input::alpha_em_0 ) * Sqrt(qedqcd.displayFermiConstant()); ZA = saved_ZA; eff_CpAhVPVP(gO1) = result; } void CMSSMNoFV_effective_couplings::calculate_eff_CpAhVGVG(int gO1) { const auto vd = MODELPARAMETER(vd); const auto vu = MODELPARAMETER(vu); const auto g3 = MODELPARAMETER(g3); const auto MFd = MODELPARAMETER(MFd); const auto MFs = MODELPARAMETER(MFs); const auto MFb = MODELPARAMETER(MFb); const auto MFu = MODELPARAMETER(MFu); const auto MFc = MODELPARAMETER(MFc); const auto MFt = MODELPARAMETER(MFt); const double alpha_s = 0.07957747154594767*Sqr(g3); const auto decay_mass = PHYSICAL(MAh)(gO1); const auto decay_scale = 0.25 * Sqr(decay_mass); const auto saved_ZA = ZA; ZA = PHYSICAL(ZA); const auto vev = Sqrt(Sqr(vd) + Sqr(vu)); std::complex result = 0; result += CpbarFdFdAhPL(gO1) * vev * AP12(decay_scale / Sqr(MFd)) / MFd; result += CpbarFsFsAhPL(gO1) * vev * AP12(decay_scale / Sqr(MFs)) / MFs; result += CpbarFbFbAhPL(gO1) * vev * AP12(decay_scale / Sqr(MFb)) / MFb; result += CpbarFuFuAhPL(gO1) * vev * AP12(decay_scale / Sqr(MFu)) / MFu; result += CpbarFcFcAhPL(gO1) * vev * AP12(decay_scale / Sqr(MFc)) / MFc; result += CpbarFtFtAhPL(gO1) * vev * AP12(decay_scale / Sqr(MFt)) / MFt; result *= 1.5; if (include_qcd_corrections) { result *= pseudoscalar_scaling_factor(decay_mass); } result *= 0.12617879380849006 * alpha_s * Sqrt(qedqcd.displayFermiConstant() ); ZA = saved_ZA; eff_CpAhVGVG(gO1) = result; } } // namespace flexiblesusy ",16200,True,3823.3054729378778,median "/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the ""License""). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ // include required headers #include #include ""../StandardPluginsConfig.h"" #include #include #include ""../../../../EMStudioSDK/Source/EMStudioManager.h"" #include ""BlendGraphWidget.h"" #include ""BlendGraphViewWidget.h"" #include ""NodeGroupWindow.h"" #include ""BlendSpace2DNodeWidget.h"" #include ""BlendSpace1DNodeWidget.h"" #include ""AnimGraphPlugin.h"" #include ""AttributesWindow.h"" #include ""NavigateWidget.h"" #include ""ParameterWindow.h"" #include ""GraphNode.h"" #include ""NodePaletteWidget.h"" // qt includes #include #include #include #include #include #include #include #include #include #include #include // emfx and core includes #include #include #include #include #include #include #include #include #include // emstudio SDK #include ""../../../../EMStudioSDK/Source/EMStudioManager.h"" namespace EMStudio { // constructor BlendGraphViewWidget::BlendGraphViewWidget(AnimGraphPlugin* plugin, QWidget* parentWidget) : QWidget(parentWidget) { mSelectedAnimGraphID = MCORE_INVALIDINDEX32; mParentPlugin = plugin; // create the command callbacks and register them mSaveAnimGraphCallback = new CommandSaveAnimGraphCallback(true); mCreateAnimGraphCallback = new CommandCreateAnimGraphCallback(true); mRemoveAnimGraphCallback = new CommandRemoveAnimGraphCallback(true); mSelectCallback = new CommandSelectCallback(false); mUnselectCallback = new CommandUnselectCallback(false); mClearSelectionCallback = new CommandClearSelectionCallback(false); mCreateMotionSetCallback = new CommandCreateMotionSetCallback(false); mRemoveMotionSetCallback = new CommandRemoveMotionSetCallback(false); mAdjustMotionSetCallback = new CommandAdjustMotionSetCallback(false); mSaveMotionSetCallback = new CommandSaveMotionSetCallback(false); mLoadMotionSetCallback = new CommandLoadMotionSetCallback(false); mActivateAnimGraphCallback = new CommandActivateAnimGraphCallback(false); mAnimGraphAddConditionCallback = new CommandAnimGraphAddConditionCallback(false); mAnimGraphRemoveConditionCallback = new CommandAnimGraphRemoveConditionCallback(false); mAnimGraphCreateConnectionCallback = new CommandAnimGraphCreateConnectionCallback(false); mAnimGraphRemoveConnectionCallback = new CommandAnimGraphRemoveConnectionCallback(false); mAnimGraphAdjustConnectionCallback = new CommandAnimGraphAdjustConnectionCallback(false); mAnimGraphCreateNodeCallback = new CommandAnimGraphCreateNodeCallback(false); mAnimGraphAdjustNodeCallback = new CommandAnimGraphAdjustNodeCallback(false); mAnimGraphRemoveNodeCallback = new CommandAnimGraphRemoveNodeCallback(false); mAnimGraphSetEntryStateCallback = new CommandAnimGraphSetEntryStateCallback(false); mAnimGraphAdjustNodeGroupCallback = new CommandAnimGraphAdjustNodeGroupCallback(false); mAnimGraphAddNodeGroupCallback = new CommandAnimGraphAddNodeGroupCallback(false); mAnimGraphRemoveNodeGroupCallback = new CommandAnimGraphRemoveNodeGroupCallback(false); mAnimGraphCreateParameterCallback = new CommandAnimGraphCreateParameterCallback(false); mAnimGraphRemoveParameterCallback = new CommandAnimGraphRemoveParameterCallback(false); mAnimGraphAdjustParameterCallback = new CommandAnimGraphAdjustParameterCallback(false); mAnimGraphSwapParametersCallback = new CommandAnimGraphSwapParametersCallback(false); mAnimGraphAdjustParameterGroupCallback = new CommandAnimGraphAdjustParameterGroupCallback(false); mAnimGraphAddParameterGroupCallback = new CommandAnimGraphAddParameterGroupCallback(false); mAnimGraphRemoveParameterGroupCallback = new CommandAnimGraphRemoveParameterGroupCallback(false); GetCommandManager()->RegisterCommandCallback(""SaveAnimGraph"", mSaveAnimGraphCallback); GetCommandManager()->RegisterCommandCallback(""CreateAnimGraph"", mCreateAnimGraphCallback); GetCommandManager()->RegisterCommandCallback(""RemoveAnimGraph"", mRemoveAnimGraphCallback); GetCommandManager()->RegisterCommandCallback(""Select"", mSelectCallback); GetCommandManager()->RegisterCommandCallback(""Unselect"", mUnselectCallback); GetCommandManager()->RegisterCommandCallback(""ClearSelection"", mClearSelectionCallback); GetCommandManager()->RegisterCommandCallback(""CreateMotionSet"", mCreateMotionSetCallback); GetCommandManager()->RegisterCommandCallback(""RemoveMotionSet"", mRemoveMotionSetCallback); GetCommandManager()->RegisterCommandCallback(""AdjustMotionSet"", mAdjustMotionSetCallback); GetCommandManager()->RegisterCommandCallback(""SaveMotionSet"", mSaveMotionSetCallback); GetCommandManager()->RegisterCommandCallback(""LoadMotionSet"", mLoadMotionSetCallback); GetCommandManager()->RegisterCommandCallback(""ActivateAnimGraph"", mActivateAnimGraphCallback); GetCommandManager()->RegisterCommandCallback(""AnimGraphAddCondition"", mAnimGraphAddConditionCallback); GetCommandManager()->RegisterCommandCallback(""AnimGraphRemoveCondition"", mAnimGraphRemoveConditionCallback); GetCommandManager()->RegisterCommandCallback(""AnimGraphCreateConnection"", mAnimGraphCreateConnectionCallback); GetCommandManager()->RegisterCommandCallback(""AnimGraphRemoveConnection"", mAnimGraphRemoveConnectionCallback); GetCommandManager()->RegisterCommandCallback(""AnimGraphAdjustConnection"", mAnimGraphAdjustConnectionCallback); GetCommandManager()->RegisterCommandCallback(""AnimGraphCreateNode"", mAnimGraphCreateNodeCallback); GetCommandManager()->RegisterCommandCallback(""AnimGraphAdjustNode"", mAnimGraphAdjustNodeCallback); GetCommandManager()->RegisterCommandCallback(""AnimGraphRemoveNode"", mAnimGraphRemoveNodeCallback); GetCommandManager()->RegisterCommandCallback(""AnimGraphSetEntryState"", mAnimGraphSetEntryStateCallback); GetCommandManager()->RegisterCommandCallback(""AnimGraphAdjustNodeGroup"", mAnimGraphAdjustNodeGroupCallback); GetCommandManager()->RegisterCommandCallback(""AnimGraphAddNodeGroup"", mAnimGraphAddNodeGroupCallback); GetCommandManager()->RegisterCommandCallback(""AnimGraphRemoveNodeGroup"", mAnimGraphRemoveNodeGroupCallback); GetCommandManager()->RegisterCommandCallback(""AnimGraphCreateParameter"", mAnimGraphCreateParameterCallback); GetCommandManager()->RegisterCommandCallback(""AnimGraphRemoveParameter"", mAnimGraphRemoveParameterCallback); GetCommandManager()->RegisterCommandCallback(""AnimGraphAdjustParameter"", mAnimGraphAdjustParameterCallback); GetCommandManager()->RegisterCommandCallback(""AnimGraphSwapParameters"", mAnimGraphSwapParametersCallback); GetCommandManager()->RegisterCommandCallback(""AnimGraphAdjustParameterGroup"", mAnimGraphAdjustParameterGroupCallback); GetCommandManager()->RegisterCommandCallback(""AnimGraphAddParameterGroup"", mAnimGraphAddParameterGroupCallback); GetCommandManager()->RegisterCommandCallback(""AnimGraphRemoveParameterGroup"", mAnimGraphRemoveParameterGroupCallback); EMotionFX::ActorEditorRequestBus::Handler::BusConnect(); } void BlendGraphViewWidget::Init(BlendGraphWidget* blendGraphWidget) { NavigateWidget* navigateWidget = mParentPlugin->GetNavigateWidget(); BlendGraphWidget* graphWidget = mParentPlugin->GetGraphWidget(); for (uint32 i = 0; i < NUM_OPTIONS; ++i) { mToolbarButtons[i] = nullptr; mActions[i] = nullptr; } // create the vertical layout with the menu and the graph widget as entries QVBoxLayout* verticalLayout = new QVBoxLayout(this); verticalLayout->setSizeConstraint(QLayout::SetNoConstraint); verticalLayout->setSpacing(0); verticalLayout->setMargin(2); // create the toolbar QWidget* toolbarWidget = new QWidget(); mToolbarLayout = new QHBoxLayout(); mToolbarLayout->setSpacing(6); mToolbarLayout->setContentsMargins(8, 2, 8, 2); toolbarWidget->setLayout(mToolbarLayout); toolbarWidget->setMinimumHeight(28); toolbarWidget->setObjectName(""EMFXFauxToolbar""); toolbarWidget->setStyleSheet(""QWidget#EMFXFauxToolbar { border-bottom: 1px solid black; }""); QMenu* fileMenu = nullptr; QMenu* selectionMenu = nullptr; QMenu* navigationMenu = nullptr; QSize buttonSize = QSize(24, 24); QSize dropdownButtonSize = QSize(30, 24); // file section CreateEntry(fileMenu, mToolbarLayout, ""New"", ""Images/Icons/Plus.png"", true, false, FILE_NEW, 0, false, false /*, QKeySequence::New*/); connect(mActions[FILE_NEW], SIGNAL(triggered()), this, SLOT(OnCreateAnimGraph())); QPushButton* openMenuButton = new QPushButton(); mOpenMenu = new QMenu(""&Open""); openMenuButton->setMenu(mOpenMenu); openMenuButton->setIcon(MysticQt::GetMysticQt()->FindIcon(""Images/Icons/Open.png"")); openMenuButton->setToolTip(""Open""); openMenuButton->setMinimumSize(dropdownButtonSize); openMenuButton->setMaximumSize(dropdownButtonSize); openMenuButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred); mToolbarLayout->addWidget(openMenuButton); openMenuButton->setIconSize(QSize(16, 16)); openMenuButton->setObjectName(""EMFXAnimGraphOpenButton""); openMenuButton->setStyleSheet(""QPushButton#EMFXAnimGraphOpenButton::menu-indicator \\ { \\ subcontrol-position: right bottom; \\ subcontrol-origin: padding; \\ left: +1px; \\ top: -4px; \\ } \\ QPushButton#EMFXAnimGraphOpenButton \\ { \\ border: 0px; \\ }""); connect(mOpenMenu, &QMenu::aboutToShow, this, &BlendGraphViewWidget::BuildOpenMenu); connect(mActions[FILE_OPEN], &QAction::triggered, mParentPlugin, &AnimGraphPlugin::OnFileOpen); BuildOpenMenu(); QPushButton* saveMenuButton = new QPushButton(); QMenu* saveMenu = new QMenu(""&Save""); saveMenuButton->setMenu(saveMenu); saveMenuButton->setIcon(MysticQt::GetMysticQt()->FindIcon(""Images/Icons/Save.png"")); saveMenuButton->setToolTip(""Save""); saveMenuButton->setMinimumSize(dropdownButtonSize); saveMenuButton->setMaximumSize(dropdownButtonSize); saveMenuButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred); mToolbarLayout->addWidget(saveMenuButton); saveMenuButton->setIconSize(QSize(16, 16)); saveMenuButton->setObjectName(""EMFXAnimGraphSaveButton""); saveMenuButton->setStyleSheet(""QPushButton#EMFXAnimGraphSaveButton::menu-indicator \\ { \\ subcontrol-position: right bottom; \\ subcontrol-origin: padding; \\ left: +1px; \\ top: -4px; \\ } \\ QPushButton#EMFXAnimGraphSaveButton \\ { \\ border: 0px; \\ }""); CreateEntry(saveMenu, mToolbarLayout, ""Save"", """", false, false, FILE_SAVE, 0, false); CreateEntry(saveMenu, mToolbarLayout, ""Save As"", """", false, false, FILE_SAVEAS, 0, false); connect(mActions[FILE_SAVEAS], SIGNAL(triggered()), mParentPlugin, SLOT(OnFileSaveAs())); connect(mActions[FILE_SAVE], SIGNAL(triggered()), mParentPlugin, SLOT(OnFileSave())); AddSeparator(); // Activate Nodes Options CreateEntry(selectionMenu, mToolbarLayout, ""Activate Animgraph/State"", ""Images/AnimGraphPLugin/Play.png"", true, false, SELECTION_ACTIVATESTATE, 0, false, false); connect(mActions[SELECTION_ACTIVATESTATE], SIGNAL(triggered()), this, SLOT(OnActivateState())); // Viz options AddSeparator(); CreateEntry(selectionMenu, mToolbarLayout, ""Zoom Selection"", ""Images/AnimGraphPlugin/ZoomSelected.png"", true, false, SELECTION_ZOOMSELECTION, 0, false, false); connect(mActions[SELECTION_ZOOMSELECTION], SIGNAL(triggered()), this, SLOT(ZoomSelected())); // Create the viz settings dropdown button QPushButton* vizMenuButton = new QPushButton(); QMenu* vizMenu = new QMenu(""&Visualization""); vizMenuButton->setMenu(vizMenu); vizMenuButton->setIcon(MysticQt::GetMysticQt()->FindIcon(""Images/Icons/Visualization.png"")); vizMenuButton->setToolTip(""Visualization""); vizMenuButton->setStyleSheet(""border: 0px;""); vizMenuButton->setMinimumSize(dropdownButtonSize); vizMenuButton->setMaximumSize(dropdownButtonSize); vizMenuButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred); mToolbarLayout->addWidget(vizMenuButton); vizMenuButton->setIconSize(QSize(16, 16)); vizMenuButton->setObjectName(""EMFXAnimGraphVizButton""); vizMenuButton->setStyleSheet(""QPushButton#EMFXAnimGraphVizButton::menu-indicator \\ { \\ subcontrol-position: right bottom; \\ subcontrol-origin: padding; \\ left: +1px; \\ top: -4px; \\ } \\ QPushButton#EMFXAnimGraphVizButton \\ { \\ border: 0px; \\ }""); mActions[VISUALIZATION_PLAYSPEEDS] = vizMenu->addAction(""Display Play Speeds""); mActions[VISUALIZATION_GLOBALWEIGHTS] = vizMenu->addAction(""Display Global Weights""); mActions[VISUALIZATION_SYNCSTATUS] = vizMenu->addAction(""Display Sync Status""); mActions[VISUALIZATION_PLAYPOSITIONS] = vizMenu->addAction(""Display Play Positions""); connect(mActions[VISUALIZATION_PLAYSPEEDS], SIGNAL(triggered()), this, SLOT(OnDisplayPlaySpeeds())); connect(mActions[VISUALIZATION_GLOBALWEIGHTS], SIGNAL(triggered()), this, SLOT(OnDisplayGlobalWeights())); connect(mActions[VISUALIZATION_SYNCSTATUS], SIGNAL(triggered()), this, SLOT(OnDisplaySyncStatus())); connect(mActions[VISUALIZATION_PLAYPOSITIONS], SIGNAL(triggered()), this, SLOT(OnDisplayPlayPositions())); AddSeparator(); // Alignment Options CreateEntry(selectionMenu, mToolbarLayout, ""Align Left"", ""Images/AnimGraphPlugin/AlignLeft.png"", true, false, SELECTION_ALIGNLEFT, 0, false, false); CreateEntry(selectionMenu, mToolbarLayout, ""Align Right"", ""Images/AnimGraphPlugin/AlignRight.png"", true, false, SELECTION_ALIGNRIGHT, 0, false, false); CreateEntry(selectionMenu, mToolbarLayout, ""Align Top"", ""Images/AnimGraphPlugin/AlignTop.png"", true, false, SELECTION_ALIGNTOP, 0, false, false); CreateEntry(selectionMenu, mToolbarLayout, ""Align Bottom"", ""Images/AnimGraphPlugin/AlignBottom.png"", true, false, SELECTION_ALIGNBOTTOM, 0, false, false); connect(mActions[SELECTION_ALIGNLEFT], &QAction::triggered, this, &BlendGraphViewWidget::AlignLeft); connect(mActions[SELECTION_ALIGNRIGHT], &QAction::triggered, this, &BlendGraphViewWidget::AlignRight); connect(mActions[SELECTION_ALIGNTOP], &QAction::triggered, this, &BlendGraphViewWidget::AlignTop); connect(mActions[SELECTION_ALIGNBOTTOM], &QAction::triggered, this, &BlendGraphViewWidget::AlignBottom); QWidget* toolbarSpacerWidget = new QWidget(); toolbarSpacerWidget->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Fixed); mToolbarLayout->addWidget(toolbarSpacerWidget); ///////////////////////////////////////////////////////////////////////////////////// // hierarchy navigation ///////////////////////////////////////////////////////////////////////////////////// QHBoxLayout* navigationLayout = new QHBoxLayout(); navigationLayout->setSizeConstraint(QLayout::SetMaximumSize); navigationLayout->setSpacing(2); navigationLayout->setMargin(0); // navigation section CreateEntry(navigationMenu, navigationLayout, ""Back"", ""Images/AnimGraphPlugin/StepBack.png"", true, false, NAVIGATION_BACK, 0, false, false); CreateEntry(navigationMenu, navigationLayout, ""Forward"", ""Images/AnimGraphPlugin/StepForward.png"", true, false, NAVIGATION_FORWARD, 0, false, false); connect(mActions[NAVIGATION_FORWARD], SIGNAL(triggered()), this, SLOT(NavigateForward())); connect(mActions[NAVIGATION_BACK], SIGNAL(triggered()), this, SLOT(NavigateBackward())); AddSeparator(navigationLayout); // add the hierarchy navigation mNavigationLink = new NavigationLinkWidget(mParentPlugin, this); mNavigationLink->setMinimumHeight(28); navigationLayout->addWidget(mNavigationLink); CreateEntry(navigationMenu, navigationLayout, ""Toggle Navigation Pane"", ""Images/AnimGraphPlugin/HierarchyView.png"", true, false, NAVIGATION_NAVPANETOGGLE, 0, false, false); connect(mActions[NAVIGATION_NAVPANETOGGLE], SIGNAL(triggered()), this, SLOT(ToggleNavigationPane())); // add the top widget with the menu and toolbar and the gl widget to the vertical layout verticalLayout->addWidget(toolbarWidget); verticalLayout->addLayout(navigationLayout); verticalLayout->addWidget(&mViewportStack); mViewportSplitter = new QSplitter(Qt::Horizontal, this); mViewportSplitter->addWidget(blendGraphWidget); mViewportSplitter->addWidget(navigateWidget); mViewportSplitter->setCollapsible(0, false); QList sizes = { this->width(), 0 }; mViewportSplitter->setSizes(sizes); mViewportStack.addWidget(mViewportSplitter); Reset(); Update(); } BlendGraphViewWidget::~BlendGraphViewWidget() { EMotionFX::ActorEditorRequestBus::Handler::BusDisconnect(); for (auto entry : mNodeTypeToWidgetMap) { AnimGraphNodeWidget* widget = entry.second; delete widget; } // unregister and destroy the command callbacks GetCommandManager()->RemoveCommandCallback(mSaveAnimGraphCallback, false); GetCommandManager()->RemoveCommandCallback(mCreateAnimGraphCallback, false); GetCommandManager()->RemoveCommandCallback(mRemoveAnimGraphCallback, false); GetCommandManager()->RemoveCommandCallback(mSelectCallback, false); GetCommandManager()->RemoveCommandCallback(mUnselectCallback, false); GetCommandManager()->RemoveCommandCallback(mClearSelectionCallback, false); GetCommandManager()->RemoveCommandCallback(mCreateMotionSetCallback, false); GetCommandManager()->RemoveCommandCallback(mRemoveMotionSetCallback, false); GetCommandManager()->RemoveCommandCallback(mAdjustMotionSetCallback, false); GetCommandManager()->RemoveCommandCallback(mSaveMotionSetCallback, false); GetCommandManager()->RemoveCommandCallback(mLoadMotionSetCallback, false); GetCommandManager()->RemoveCommandCallback(mActivateAnimGraphCallback, false); GetCommandManager()->RemoveCommandCallback(mAnimGraphAddConditionCallback, false); GetCommandManager()->RemoveCommandCallback(mAnimGraphRemoveConditionCallback, false); GetCommandManager()->RemoveCommandCallback(mAnimGraphCreateConnectionCallback, false); GetCommandManager()->RemoveCommandCallback(mAnimGraphRemoveConnectionCallback, false); GetCommandManager()->RemoveCommandCallback(mAnimGraphAdjustConnectionCallback, false); GetCommandManager()->RemoveCommandCallback(mAnimGraphCreateNodeCallback, false); GetCommandManager()->RemoveCommandCallback(mAnimGraphAdjustNodeCallback, false); GetCommandManager()->RemoveCommandCallback(mAnimGraphRemoveNodeCallback, false); GetCommandManager()->RemoveCommandCallback(mAnimGraphSetEntryStateCallback, false); GetCommandManager()->RemoveCommandCallback(mAnimGraphAdjustNodeGroupCallback, false); GetCommandManager()->RemoveCommandCallback(mAnimGraphAddNodeGroupCallback, false); GetCommandManager()->RemoveCommandCallback(mAnimGraphRemoveNodeGroupCallback, false); GetCommandManager()->RemoveCommandCallback(mAnimGraphCreateParameterCallback, false); GetCommandManager()->RemoveCommandCallback(mAnimGraphRemoveParameterCallback, false); GetCommandManager()->RemoveCommandCallback(mAnimGraphAdjustParameterCallback, false); GetCommandManager()->RemoveCommandCallback(mAnimGraphSwapParametersCallback, false); GetCommandManager()->RemoveCommandCallback(mAnimGraphAdjustParameterGroupCallback, false); GetCommandManager()->RemoveCommandCallback(mAnimGraphAddParameterGroupCallback, false); GetCommandManager()->RemoveCommandCallback(mAnimGraphRemoveParameterGroupCallback, false); // delete callbacks delete mSaveAnimGraphCallback; delete mCreateAnimGraphCallback; delete mRemoveAnimGraphCallback; delete mSelectCallback; delete mUnselectCallback; delete mClearSelectionCallback; delete mCreateMotionSetCallback; delete mRemoveMotionSetCallback; delete mAdjustMotionSetCallback; delete mSaveMotionSetCallback; delete mLoadMotionSetCallback; delete mActivateAnimGraphCallback; delete mAnimGraphAddConditionCallback; delete mAnimGraphRemoveConditionCallback; delete mAnimGraphCreateConnectionCallback; delete mAnimGraphRemoveConnectionCallback; delete mAnimGraphAdjustConnectionCallback; delete mAnimGraphCreateNodeCallback; delete mAnimGraphAdjustNodeCallback; delete mAnimGraphRemoveNodeCallback; delete mAnimGraphSetEntryStateCallback; delete mAnimGraphAdjustNodeGroupCallback; delete mAnimGraphAddNodeGroupCallback; delete mAnimGraphRemoveNodeGroupCallback; delete mAnimGraphCreateParameterCallback; delete mAnimGraphRemoveParameterCallback; delete mAnimGraphAdjustParameterCallback; delete mAnimGraphSwapParametersCallback; delete mAnimGraphAdjustParameterGroupCallback; delete mAnimGraphAddParameterGroupCallback; delete mAnimGraphRemoveParameterGroupCallback; } void BlendGraphViewWidget::Update() { mActions[NAVIGATION_BACK]->setEnabled(mParentPlugin->CanPopHistory()); mActions[NAVIGATION_FORWARD]->setEnabled(mParentPlugin->CanStepForwardInHistory()); mToolbarButtons[NAVIGATION_BACK]->setEnabled(mParentPlugin->CanPopHistory()); mToolbarButtons[NAVIGATION_FORWARD]->setEnabled(mParentPlugin->CanStepForwardInHistory()); // get the anim graph that is currently selected in the resource widget EMotionFX::AnimGraph* animGraph = mParentPlugin->GetActiveAnimGraph(); if (animGraph == nullptr) { SetOptionEnabled(FILE_SAVE, false); SetOptionEnabled(FILE_SAVEAS, false); SetOptionEnabled(NAVIGATION_ROOT, false); } else { SetOptionEnabled(FILE_SAVE, true); SetOptionEnabled(FILE_SAVEAS, true); SetOptionEnabled(NAVIGATION_ROOT, true); } SetOptionEnabled(NAVIGATION_PARENT, false); EMotionFX::AnimGraphNode* currentAnimGraphNode = mParentPlugin->GetGraphWidget()->GetCurrentNode(); if (currentAnimGraphNode) { EMotionFX::AnimGraphNode* parentNode = currentAnimGraphNode->GetParentNode(); if (parentNode) { SetOptionEnabled(NAVIGATION_PARENT, true); } } // update the navigation link mNavigationLink->Update(animGraph, currentAnimGraphNode); // get the number of selected nodes BlendGraphWidget* blendGraphWidget = mParentPlugin->GetGraphWidget(); NodeGraph* nodeGraph = blendGraphWidget->GetActiveGraph(); uint32 numSelectedNodes = 0; if (nodeGraph) { // get the number of selected nodes numSelectedNodes = nodeGraph->CalcNumSelectedNodes(); // graph not empty flag const bool GraphNotEmpty = nodeGraph->GetNumNodes() > 0; // enable the select all menu only if at least one node is in the graph SetOptionEnabled(SELECTION_ZOOMSELECTION, true); } else { // select all and zoom all menus can not be enabled if one graph is not valid SetOptionEnabled(SELECTION_ZOOMSELECTION, false); } SetOptionEnabled(NAVIGATION_OPENSELECTEDNODE, false); if (numSelectedNodes == 1) { EMotionFX::AnimGraphNode* animGraphNode = blendGraphWidget->FindFirstSelectedAnimGraphNode(); if (animGraphNode) { if (animGraphNode->GetHasVisualGraph()) { SetOptionEnabled(NAVIGATION_OPENSELECTEDNODE, true); } // get the parent node and check if it is valid EMotionFX::AnimGraphNode* parentNode = animGraphNode->GetParentNode(); if (parentNode) { SetOptionEnabled(NAVIGATION_PARENT, true); } } } if (numSelectedNodes > 1) { SetOptionEnabled(SELECTION_ALIGNLEFT, true); SetOptionEnabled(SELECTION_ALIGNRIGHT, true); SetOptionEnabled(SELECTION_ALIGNTOP, true); SetOptionEnabled(SELECTION_ALIGNBOTTOM, true); } else { SetOptionEnabled(SELECTION_ALIGNLEFT, false); SetOptionEnabled(SELECTION_ALIGNRIGHT, false); SetOptionEnabled(SELECTION_ALIGNTOP, false); SetOptionEnabled(SELECTION_ALIGNBOTTOM, false); } } void BlendGraphViewWidget::UpdateOpenMenu() { BuildOpenMenu(); } EMotionFX::ActorInstance* BlendGraphViewWidget::GetSelectedActorInstance() { return GetCommandManager()->GetCurrentSelection().GetSingleActorInstance(); } AnimGraphNodeWidget* BlendGraphViewWidget::GetWidgetForNode(const EMotionFX::AnimGraphNode* node) { if (!node) { return nullptr; } const AZ::TypeId nodeType = azrtti_typeid(node); AnimGraphNodeWidget* widget = nullptr; AZStd::unordered_map::iterator it = mNodeTypeToWidgetMap.find(nodeType); if (it != mNodeTypeToWidgetMap.end()) { widget = it->second; } else { if (nodeType == azrtti_typeid()) { widget = new BlendSpace2DNodeWidget(mParentPlugin); mNodeTypeToWidgetMap[nodeType] = widget; } else if (nodeType == azrtti_typeid()) { widget = new BlendSpace1DNodeWidget(mParentPlugin); mNodeTypeToWidgetMap[nodeType] = widget; } } return widget; } void BlendGraphViewWidget::SetCurrentNode(EMotionFX::AnimGraphNode* node) { // Reset the viewports to avoid dangling pointers. for (auto& item : mNodeTypeToWidgetMap) { AnimGraphNodeWidget* viewport = item.second; viewport->SetCurrentNode(nullptr); } AnimGraphNodeWidget* widget = GetWidgetForNode(node); if (widget) { int index = mViewportStack.indexOf(widget); if (index == -1) { mViewportStack.addWidget(widget); mViewportStack.setCurrentIndex(mViewportStack.count() - 1); } else { mViewportStack.setCurrentIndex(index); } widget->SetCurrentNode(node); } else { // Show the default widget. mViewportStack.setCurrentIndex(0); } } void BlendGraphViewWidget::SetOptionFlag(EOptionFlag option, bool isEnabled) { const uint32 optionIndex = (uint32)option; if (mToolbarButtons[optionIndex]) { mToolbarButtons[optionIndex]->setChecked(isEnabled); } if (mActions[optionIndex]) { mActions[optionIndex]->setChecked(isEnabled); } } void BlendGraphViewWidget::SetOptionEnabled(EOptionFlag option, bool isEnabled) { const uint32 optionIndex = (uint32)option; if (mToolbarButtons[optionIndex]) { mToolbarButtons[optionIndex]->setEnabled(isEnabled); } if (mActions[optionIndex]) { mActions[optionIndex]->setEnabled(isEnabled); } } void BlendGraphViewWidget::CreateEntry(QMenu* menu, QHBoxLayout* toolbarLayout, const char* entryName, const char* toolbarIconFileName, bool addToToolbar, bool checkable, int32 actionIndex, const QKeySequence& shortcut, bool border, bool addToMenu) { // menu entry if (addToMenu) { mActions[actionIndex] = menu->addAction(entryName); mActions[actionIndex]->setVisible(addToMenu); mActions[actionIndex]->setCheckable(checkable); mActions[actionIndex]->setShortcut(shortcut); } else { mActions[actionIndex] = new QAction(entryName, this); } if (strcmp(toolbarIconFileName, """") != 0 && checkable == false) { mActions[actionIndex]->setIcon(MysticQt::GetMysticQt()->FindIcon(toolbarIconFileName)); } // toolbar button if (addToToolbar && strcmp(toolbarIconFileName, """") != 0) { QPushButton* toolbarButton = new QPushButton(); mToolbarButtons[actionIndex] = toolbarButton; toolbarButton->setIcon(MysticQt::GetMysticQt()->FindIcon(toolbarIconFileName)); toolbarButton->setCheckable(checkable); toolbarButton->setToolTip(entryName); if (border == false) { toolbarButton->setStyleSheet(""border: 0px;""); } QSize buttonSize = QSize(24, 24); toolbarButton->setMinimumSize(buttonSize); toolbarButton->setMaximumSize(buttonSize); toolbarButton->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); toolbarLayout->addWidget(toolbarButton); toolbarButton->setIconSize(buttonSize - QSize(2, 2)); // connect the menu entry with the toolbar button connect(toolbarButton, SIGNAL(clicked()), mActions[actionIndex], SLOT(trigger())); } } void BlendGraphViewWidget::BuildOpenMenu() { mOpenMenu->clear(); // disconnect(mActions[FILE_OPEN], SIGNAL(triggered()), mParentPlugin, SLOT(OnFileOpen())); mActions[FILE_OPEN] = mOpenMenu->addAction(""Open...""); connect(mActions[FILE_OPEN], SIGNAL(triggered()), mParentPlugin, SLOT(OnFileOpen())); const uint32 numAnimGraphs = EMotionFX::GetAnimGraphManager().GetNumAnimGraphs(); if (numAnimGraphs > 0) { // /*mActions[FILE_OPEN] =*/ mOpenMenu->addAction(""Manage AnimGraphs...""); mOpenMenu->addSeparator(); for (uint32 i = 0; i < numAnimGraphs; ++i) { EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().GetAnimGraph(i); if (animGraph->GetIsOwnedByRuntime() == false) { QString itemName = """"; if (animGraph->GetFileNameString().size() > 0) { // convert full absolute paths to friendlier relative paths + folder they're found in. // GetSourceInfoBySourcePath works on relative paths and absolute paths and doesn't need to wait for // cached products to exist in order to function, so it is orders of magnitude faster than asking about product files. itemName = QString::fromUtf8(animGraph->GetFileName()); bool success = false; AZStd::string watchFolder; AZ::Data::AssetInfo assetInfo; AzToolsFramework::AssetSystemRequestBus::BroadcastResult(success, &AzToolsFramework::AssetSystemRequestBus::Events::GetSourceInfoBySourcePath, animGraph->GetFileName(), assetInfo, watchFolder); if (success) { itemName = QString::fromUtf8(assetInfo.m_relativePath.c_str()); } } QAction* openItem = mOpenMenu->addAction(itemName); connect(openItem, &QAction::triggered, this, &BlendGraphViewWidget::OpenAnimGraph); openItem->setData(animGraph->GetID()); } } } } void BlendGraphViewWidget::OpenAnimGraph() { QAction *action = qobject_cast(sender()); if (action) { uint32 animGraphID = action->data().toUInt(); EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(animGraphID); EMotionFX::MotionSet* motionSet = nullptr; EMotionFX::AnimGraphEditorRequestBus::BroadcastResult(motionSet, &EMotionFX::AnimGraphEditorRequests::GetSelectedMotionSet); ActivateAnimGraphToSelection(animGraph, motionSet); } } // get the selected anim graph EMotionFX::AnimGraph* BlendGraphViewWidget::GetSelectedAnimGraph() { // check if the ID is not valid (nothing selected or multiple selection) if (mSelectedAnimGraphID == MCORE_INVALIDINDEX32) { return nullptr; } // get the anim graph by the ID return EMotionFX::GetAnimGraphManager().FindAnimGraphByID(mSelectedAnimGraphID); } // activate anim graph to the selected actor instances void BlendGraphViewWidget::ActivateAnimGraphToSelection(EMotionFX::AnimGraph* animGraph, EMotionFX::MotionSet* motionSet) { if (!animGraph) { return; } const CommandSystem::SelectionList& selectionList = GetCommandManager()->GetCurrentSelection(); const uint32 numActorInstances = selectionList.GetNumSelectedActorInstances(); // Anim graph can only be activated in case there are actor instances. if (numActorInstances == 0) { mParentPlugin->SetActiveAnimGraph(animGraph); return; } MCore::CommandGroup commandGroup(""Activate anim graph""); // Activate the anim graph each selected actor instance. for (uint32 i = 0; i < numActorInstances; ++i) { EMotionFX::ActorInstance* actorInstance = selectionList.GetActorInstance(i); if (actorInstance->GetIsOwnedByRuntime()) { continue; } EMotionFX::AnimGraphInstance* animGraphInstance = actorInstance->GetAnimGraphInstance(); // Use the given motion set in case it is valid, elsewise use the one previously set to the actor instance. uint32 motionSetId = MCORE_INVALIDINDEX32; if (motionSet) { motionSetId = motionSet->GetID(); } else { if (animGraphInstance) { EMotionFX::MotionSet* animGraphInstanceMotionSet = animGraphInstance->GetMotionSet(); if (animGraphInstanceMotionSet) { motionSetId = animGraphInstanceMotionSet->GetID(); } } } commandGroup.AddCommandString(AZStd::string::format(""ActivateAnimGraph -actorInstanceID %d -animGraphID %d -motionSetID %d"", actorInstance->GetID(), animGraph->GetID(), motionSetId)); } if (commandGroup.GetNumCommands() > 0) { AZStd::string result; if (!EMStudio::GetCommandManager()->ExecuteCommandGroup(commandGroup, result)) { AZ_Error(""EMotionFX"", false, result.c_str()); } mParentPlugin->SetActiveAnimGraph(animGraph); mParentPlugin->SetAnimGraphRunning(true); } } void BlendGraphViewWidget::AddSeparator(QLayout* layout) { if (layout == nullptr) { layout = mToolbarLayout; } QLabel* spacer = new QLabel(); QSize spacerSize = QSize(2, 18); spacer->setMinimumSize(spacerSize); spacer->setMaximumSize(spacerSize); QPixmap img = MysticQt::GetMysticQt()->FindIcon(""Images/Icons/divider.png"").pixmap(spacerSize); spacer->setPixmap(img); spacer->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); layout->addWidget(spacer); } void BlendGraphViewWidget::Reset() { } void BlendGraphViewWidget::SaveOptions(QSettings* settings) { const uint32 numOptions = NUM_OPTIONS; for (uint32 i = 0; i < numOptions; ++i) { QString name = QString(i); if (mActions[i]->isCheckable()) { settings->setValue(name, mActions[i]->isChecked()); } } } void BlendGraphViewWidget::LoadOptions(QSettings* settings) { const uint32 numOptions = NUM_OPTIONS; for (uint32 i = 0; i < numOptions; ++i) { QString name = QString(i); if (mActions[i]->isCheckable()) { const bool isEnabled = settings->value(name, mActions[i]->isChecked()).toBool(); SetOptionFlag((EOptionFlag)i, isEnabled); } } } void BlendGraphViewWidget::AlignNodes(uint32 mode) { NodeGraph* nodeGraph = mParentPlugin->GetGraphWidget()->GetActiveGraph(); if (nodeGraph == nullptr) { return; } EMotionFX::AnimGraph* animGraph = mParentPlugin->GetActiveAnimGraph(); if (animGraph == nullptr) { return; } uint32 i; int32 alignedXPos = 0; int32 alignedYPos = 0; int32 maxGraphNodeHeight = 0; int32 maxGraphNodeWidth = 0; // iterate over all graph nodes bool firstSelectedNode = true; const uint32 numNodes = nodeGraph->GetNumNodes(); for (i = 0; i < numNodes; ++i) { // get the graph and the anim graph node GraphNode* graphNode = nodeGraph->GetNode(i); EMotionFX::AnimGraphNode* animGraphNode = animGraph->RecursiveFindNodeByName(graphNode->GetName()); if (animGraphNode == nullptr) { continue; } if (graphNode->GetIsSelected()) { const int32 xPos = animGraphNode->GetVisualPosX(); const int32 yPos = animGraphNode->GetVisualPosY(); const int32 graphNodeHeight = graphNode->CalcRequiredHeight(); const int32 graphNodeWidth = graphNode->CalcRequiredWidth(); if (firstSelectedNode) { alignedXPos = xPos; alignedYPos = yPos; maxGraphNodeHeight = graphNodeHeight; maxGraphNodeWidth = graphNodeWidth; firstSelectedNode = false; } if (graphNodeHeight > maxGraphNodeHeight) { maxGraphNodeHeight = graphNodeHeight; } if (graphNodeWidth > maxGraphNodeWidth) { maxGraphNodeWidth = graphNodeWidth; } switch (mode) { case SELECTION_ALIGNLEFT: { if (xPos < alignedXPos) { alignedXPos = xPos; } break; } case SELECTION_ALIGNRIGHT: { if (xPos + graphNodeWidth > alignedXPos) { alignedXPos = xPos + graphNodeWidth; } break; } case SELECTION_ALIGNTOP: { if (yPos < alignedYPos) { alignedYPos = yPos; } break; } case SELECTION_ALIGNBOTTOM: { if (yPos + graphNodeHeight > alignedYPos) { alignedYPos = yPos + graphNodeHeight; } break; } default: MCORE_ASSERT(false); } } } // create the command group AZStd::string command; AZStd::string outResult; MCore::CommandGroup commandGroup(""Align anim graph nodes""); // iterate over all nodes for (i = 0; i < numNodes; ++i) { GraphNode* node = nodeGraph->GetNode(i); if (node->GetIsSelected()) { command = AZStd::string::format(""AnimGraphAdjustNode -animGraphID %i -name \\""%s\\"" "", animGraph->GetID(), node->GetName()); switch (mode) { case SELECTION_ALIGNLEFT: command += AZStd::string::format(""-xPos %i"", alignedXPos); break; case SELECTION_ALIGNRIGHT: command += AZStd::string::format(""-xPos %i"", alignedXPos - node->CalcRequiredWidth()); break; case SELECTION_ALIGNTOP: command += AZStd::string::format(""-yPos %i"", alignedYPos); break; case SELECTION_ALIGNBOTTOM: command += AZStd::string::format(""-yPos %i"", alignedYPos - node->CalcRequiredHeight()); break; default: MCORE_ASSERT(false); } commandGroup.AddCommandString(command); } } // execute the group command GetCommandManager()->ExecuteCommandGroup(commandGroup, outResult); } void BlendGraphViewWidget::OnCreateAnimGraph() { // get the current selection list and the number of actor instances selected const CommandSystem::SelectionList& selectionList = GetCommandManager()->GetCurrentSelection(); const uint32 numActorInstances = selectionList.GetNumSelectedActorInstances(); // Activate the new anim graph automatically (The shown anim graph should always be the activated one). if (numActorInstances > 0) { // create the command group MCore::CommandGroup commandGroup(""Create an anim graph""); // add the create anim graph command commandGroup.AddCommandString(""CreateAnimGraph""); // get the correct motion set // nullptr can only be because it's the first anim graph so no one is activated // if no motion set selected but one is possible, use the first possible // if no motion set selected and no one created, use no motion set // if one already selected, use the already selected EMotionFX::MotionSet* motionSet = nullptr; EMotionFX::AnimGraphEditorRequestBus::BroadcastResult(motionSet, &EMotionFX::AnimGraphEditorRequests::GetSelectedMotionSet); if (!motionSet) { if (EMotionFX::GetMotionManager().GetNumMotionSets() > 0) { motionSet = EMotionFX::GetMotionManager().GetMotionSet(0); } } // get the motion set ID const uint32 motionSetID = (motionSet) ? motionSet->GetID() : MCORE_INVALIDINDEX32; // activate on each selected actor instance for (uint32 i = 0; i < numActorInstances; ++i) { EMotionFX::ActorInstance* actorInstance = selectionList.GetActorInstance(i); m_tempString = AZStd::string::format(""ActivateAnimGraph -actorInstanceID %d -animGraphID %%LASTRESULT%% -motionSetID %d"", actorInstance->GetID(), motionSetID); commandGroup.AddCommandString(m_tempString); } AZStd::string result; if (!EMStudio::GetCommandManager()->ExecuteCommandGroup(commandGroup, result)) { AZ_Error(""EMotionFX"", false, result.c_str()); } } else { AZStd::string result; if (!EMStudio::GetCommandManager()->ExecuteCommand(""CreateAnimGraph"", result)) { AZ_Error(""EMotionFX"", false, result.c_str()); } } } void BlendGraphViewWidget::AlignLeft() { AlignNodes(SELECTION_ALIGNLEFT); } void BlendGraphViewWidget::AlignRight() { AlignNodes(SELECTION_ALIGNRIGHT); } void BlendGraphViewWidget::AlignTop() { AlignNodes(SELECTION_ALIGNTOP); } void BlendGraphViewWidget::AlignBottom() { AlignNodes(SELECTION_ALIGNBOTTOM); } void BlendGraphViewWidget::ZoomSelected() { mParentPlugin->FitActiveSelectionOnScreen(); } void BlendGraphViewWidget::OnActivateState() { NavigateWidget* navigateWidget = mParentPlugin->GetNavigateWidget(); BlendGraphWidget* blendGraphWidget = mParentPlugin->GetGraphWidget(); if (!navigateWidget || !blendGraphWidget) { return; } EMotionFX::AnimGraph* animGraph = GetSelectedAnimGraph(); NodeGraph* nodeGraph = blendGraphWidget->GetActiveGraph(); if (!nodeGraph || !animGraph) { return; } // Reactivate the anim graph for visual feedback of button click. EMotionFX::MotionSet* motionSet = nullptr; EMotionFX::AnimGraphEditorRequestBus::BroadcastResult(motionSet, &EMotionFX::AnimGraphEditorRequests::GetSelectedMotionSet); ActivateAnimGraphToSelection(animGraph, motionSet); // Transition to the selected state. EMotionFX::AnimGraphNode* selectedNode = blendGraphWidget->FindFirstSelectedAnimGraphNode(); if (selectedNode) { EMotionFX::AnimGraphNode* parentNode = selectedNode->GetParentNode(); if (parentNode && azrtti_typeid(parentNode) == azrtti_typeid()) { EMotionFX::AnimGraphStateMachine* stateMachine = static_cast(parentNode); // For all selected actor instances that are running the given anim graph. const CommandSystem::SelectionList& selectionList = GetCommandManager()->GetCurrentSelection(); const AZ::u32 numSelectedActorInstances = selectionList.GetNumSelectedActorInstances(); for (AZ::u32 i = 0; i < numSelectedActorInstances; ++i) { EMotionFX::ActorInstance* actorInstance = selectionList.GetActorInstance(i); EMotionFX::AnimGraphInstance* animGraphInstance = actorInstance->GetAnimGraphInstance(); if (animGraphInstance && animGraphInstance->GetAnimGraph() == animGraph) { stateMachine->TransitionToState(animGraphInstance, selectedNode); } } } } } void BlendGraphViewWidget::NavigateForward() { mParentPlugin->HistoryStepForward(); Update(); } void BlendGraphViewWidget::NavigateBackward() { mParentPlugin->HistoryStepBack(); Update(); } void BlendGraphViewWidget::NavigateToRoot() { EMotionFX::AnimGraph* animGraph = mParentPlugin->GetActiveAnimGraph(); if (animGraph == nullptr) { return; } EMotionFX::AnimGraphNode* rootNode = nullptr; mParentPlugin->GetNavigateWidget()->ShowGraph(rootNode, true); } void BlendGraphViewWidget::NavigateToParent() { EMotionFX::AnimGraphNode* animGraphNode = mParentPlugin->GetGraphWidget()->GetCurrentNode(); if (animGraphNode == nullptr) { return; } EMotionFX::AnimGraphNode* parentNode = animGraphNode->GetParentNode(); mParentPlugin->GetNavigateWidget()->ShowGraph(parentNode, true); } void BlendGraphViewWidget::ToggleNavigationPane() { QList sizes = mViewportSplitter->sizes(); if (sizes[1] == 0) { // the nav pane is hidden if the width is 0, so set the width to 25% sizes[0] = (this->width() * 75) / 100; sizes[1] = this->width() - sizes[0]; } else { // hide the nav pane sizes[0] = this->width(); sizes[1] = 0; } mViewportSplitter->setSizes(sizes); } void BlendGraphViewWidget::NavigateToNode() { EMotionFX::AnimGraphNode* animGraphNode = mParentPlugin->GetGraphWidget()->FindFirstSelectedAnimGraphNode(); if (animGraphNode == nullptr) { return; } mParentPlugin->GetNavigateWidget()->ShowGraph(animGraphNode, true); } // toggle visualization of processed nodes and connections /*void BlendGraphViewWidget::OnShowProcessed() { const bool showProcessed = !mParentPlugin->GetShowProcessed(); mParentPlugin->SetShowProcessed( showProcessed ); SetOptionFlag( SELECTION_SHOWPROCESSED, showProcessed ); }*/ // toggle playspeed viz void BlendGraphViewWidget::OnDisplayPlaySpeeds() { const bool showPlaySpeeds = !mParentPlugin->GetIsDisplayFlagEnabled(AnimGraphPlugin::DISPLAYFLAG_PLAYSPEED); mParentPlugin->SetDisplayFlagEnabled(AnimGraphPlugin::DISPLAYFLAG_PLAYSPEED, showPlaySpeeds); SetOptionFlag(VISUALIZATION_PLAYSPEEDS, showPlaySpeeds); } // toggle sync status viz void BlendGraphViewWidget::OnDisplaySyncStatus() { const bool show = !mParentPlugin->GetIsDisplayFlagEnabled(AnimGraphPlugin::DISPLAYFLAG_SYNCSTATUS); mParentPlugin->SetDisplayFlagEnabled(AnimGraphPlugin::DISPLAYFLAG_SYNCSTATUS, show); SetOptionFlag(VISUALIZATION_SYNCSTATUS, show); } // toggle global weights viz void BlendGraphViewWidget::OnDisplayGlobalWeights() { const bool displayGlobalWeights = !mParentPlugin->GetIsDisplayFlagEnabled(AnimGraphPlugin::DISPLAYFLAG_GLOBALWEIGHT); mParentPlugin->SetDisplayFlagEnabled(AnimGraphPlugin::DISPLAYFLAG_GLOBALWEIGHT, displayGlobalWeights); SetOptionFlag(VISUALIZATION_GLOBALWEIGHTS, displayGlobalWeights); } // toggle play position viz void BlendGraphViewWidget::OnDisplayPlayPositions() { const bool show = !mParentPlugin->GetIsDisplayFlagEnabled(AnimGraphPlugin::DISPLAYFLAG_PLAYPOSITION); mParentPlugin->SetDisplayFlagEnabled(AnimGraphPlugin::DISPLAYFLAG_PLAYPOSITION, show); SetOptionFlag(VISUALIZATION_PLAYPOSITIONS, show); } // on keypress void BlendGraphViewWidget::keyPressEvent(QKeyEvent* event) { switch (event->key()) { case Qt::Key_Backspace: { NavigateBackward(); event->accept(); break; } default: event->ignore(); } } // on key release void BlendGraphViewWidget::keyReleaseEvent(QKeyEvent* event) { switch (event->key()) { case Qt::Key_Backspace: { event->accept(); break; } default: event->ignore(); } } //---------------------------------------------------------------------------------------------------------------------------------- // command callbacks //---------------------------------------------------------------------------------------------------------------------------------- bool UpdateOpenMenuBlendGraphViewWidget() { EMStudioPlugin* plugin = EMStudio::GetPluginManager()->FindActivePlugin(AnimGraphPlugin::CLASS_ID); if (!plugin) { return false; } AnimGraphPlugin* animGraphPlugin = static_cast(plugin); BlendGraphViewWidget* blendGraphViewWidget = animGraphPlugin->GetViewWidget(); animGraphPlugin->RemoveAllUnusedGraphInfos(); blendGraphViewWidget->UpdateOpenMenu(); return true; } bool UpdateOpenMenuAndMotionSetBlendGraphViewWidget() { EMStudioPlugin* plugin = EMStudio::GetPluginManager()->FindActivePlugin(AnimGraphPlugin::CLASS_ID); if (!plugin) { return false; } AnimGraphPlugin* animGraphPlugin = static_cast(plugin); BlendGraphViewWidget* blendGraphViewWidget = animGraphPlugin->GetViewWidget(); animGraphPlugin->RemoveAllUnusedGraphInfos(); blendGraphViewWidget->UpdateOpenMenu(); EMotionFX::AnimGraphEditorNotificationBus::Broadcast(&EMotionFX::AnimGraphEditorNotifications::UpdateMotionSetComboBox); return true; } bool UpdateAnimGraphPluginAfterActivate() { EMStudioPlugin* plugin = EMStudio::GetPluginManager()->FindActivePlugin(AnimGraphPlugin::CLASS_ID); if (!plugin) { return false; } AnimGraphPlugin* animGraphPlugin = static_cast(plugin); animGraphPlugin->SetAnimGraphRunning(true); BlendGraphViewWidget* blendGraphViewWidget = animGraphPlugin->GetViewWidget(); EMStudio::ParameterWindow* parameterWindow = animGraphPlugin->GetParameterWindow(); EMStudio::AttributesWindow* attributesWindow = animGraphPlugin->GetAttributesWindow(); EMStudio::NodeGroupWindow* nodeGroupWindow = animGraphPlugin->GetNodeGroupWidget(); animGraphPlugin->RemoveAllUnusedGraphInfos(); blendGraphViewWidget->UpdateOpenMenu(); animGraphPlugin->UpdateStateMachineColors(); parameterWindow->Init(); nodeGroupWindow->Init(); return true; } bool UpdateMotionSetComboBoxResourceWidget() { EMStudioPlugin* plugin = EMStudio::GetPluginManager()->FindActivePlugin(AnimGraphPlugin::CLASS_ID); if (!plugin) { return false; } AnimGraphPlugin* animGraphPlugin = static_cast(plugin); BlendGraphViewWidget* blendGraphViewWidget = animGraphPlugin->GetViewWidget(); EMotionFX::AnimGraphEditorNotificationBus::Broadcast(&EMotionFX::AnimGraphEditorNotifications::UpdateMotionSetComboBox); return true; } bool BlendGraphViewWidget::CommandSaveAnimGraphCallback::Execute(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); GetOutlinerManager()->FireItemModifiedEvent(); return UpdateOpenMenuBlendGraphViewWidget(); } bool BlendGraphViewWidget::CommandSaveAnimGraphCallback::Undo(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); return UpdateOpenMenuBlendGraphViewWidget(); } bool BlendGraphViewWidget::CommandActivateAnimGraphCallback::Execute(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); return UpdateAnimGraphPluginAfterActivate(); } bool BlendGraphViewWidget::CommandActivateAnimGraphCallback::Undo(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); return UpdateAnimGraphPluginAfterActivate(); } bool BlendGraphViewWidget::CommandCreateAnimGraphCallback::Execute(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(commandLine); CommandSystem::CommandCreateAnimGraph* createAnimGraphCommand = static_cast(command); EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(createAnimGraphCommand->mPreviouslyUsedID); GetOutlinerManager()->AddItemToCategory(""Anim Graphs"", animGraph->GetID(), animGraph); return UpdateOpenMenuBlendGraphViewWidget(); } bool BlendGraphViewWidget::CommandCreateAnimGraphCallback::Undo(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); return UpdateOpenMenuBlendGraphViewWidget(); } bool BlendGraphViewWidget::CommandRemoveAnimGraphCallback::Execute(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(commandLine); CommandSystem::CommandRemoveAnimGraph* removeAnimGraphCommand = static_cast(command); for (const AZStd::pair& oldFilenameAndIds : removeAnimGraphCommand->m_oldFileNamesAndIds) { GetOutlinerManager()->RemoveItemFromCategory(""Anim Graphs"", oldFilenameAndIds.second); } return UpdateOpenMenuBlendGraphViewWidget(); } bool BlendGraphViewWidget::CommandRemoveAnimGraphCallback::Undo(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); return UpdateOpenMenuBlendGraphViewWidget(); } bool BlendGraphViewWidget::CommandAnimGraphAddConditionCallback::Execute(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); GetOutlinerManager()->FireItemModifiedEvent(); return UpdateOpenMenuBlendGraphViewWidget(); } bool BlendGraphViewWidget::CommandAnimGraphAddConditionCallback::Undo(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); GetOutlinerManager()->FireItemModifiedEvent(); return UpdateOpenMenuBlendGraphViewWidget(); } bool BlendGraphViewWidget::CommandAnimGraphRemoveConditionCallback::Execute(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); GetOutlinerManager()->FireItemModifiedEvent(); return UpdateOpenMenuBlendGraphViewWidget(); } bool BlendGraphViewWidget::CommandAnimGraphRemoveConditionCallback::Undo(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); GetOutlinerManager()->FireItemModifiedEvent(); return UpdateOpenMenuBlendGraphViewWidget(); } bool BlendGraphViewWidget::CommandAnimGraphCreateConnectionCallback::Execute(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); GetOutlinerManager()->FireItemModifiedEvent(); return UpdateOpenMenuBlendGraphViewWidget(); } bool BlendGraphViewWidget::CommandAnimGraphCreateConnectionCallback::Undo(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); GetOutlinerManager()->FireItemModifiedEvent(); return UpdateOpenMenuBlendGraphViewWidget(); } bool BlendGraphViewWidget::CommandAnimGraphRemoveConnectionCallback::Execute(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); GetOutlinerManager()->FireItemModifiedEvent(); return UpdateOpenMenuBlendGraphViewWidget(); } bool BlendGraphViewWidget::CommandAnimGraphRemoveConnectionCallback::Undo(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); GetOutlinerManager()->FireItemModifiedEvent(); return UpdateOpenMenuBlendGraphViewWidget(); } bool BlendGraphViewWidget::CommandAnimGraphAdjustConnectionCallback::Execute(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); GetOutlinerManager()->FireItemModifiedEvent(); return UpdateOpenMenuBlendGraphViewWidget(); } bool BlendGraphViewWidget::CommandAnimGraphAdjustConnectionCallback::Undo(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); GetOutlinerManager()->FireItemModifiedEvent(); return UpdateOpenMenuBlendGraphViewWidget(); } bool BlendGraphViewWidget::CommandAnimGraphCreateNodeCallback::Execute(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); GetOutlinerManager()->FireItemModifiedEvent(); return UpdateOpenMenuBlendGraphViewWidget(); } bool BlendGraphViewWidget::CommandAnimGraphCreateNodeCallback::Undo(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); GetOutlinerManager()->FireItemModifiedEvent(); return UpdateOpenMenuBlendGraphViewWidget(); } bool BlendGraphViewWidget::CommandAnimGraphAdjustNodeCallback::Execute(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); GetOutlinerManager()->FireItemModifiedEvent(); return UpdateOpenMenuBlendGraphViewWidget(); } bool BlendGraphViewWidget::CommandAnimGraphAdjustNodeCallback::Undo(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); GetOutlinerManager()->FireItemModifiedEvent(); return UpdateOpenMenuBlendGraphViewWidget(); } bool BlendGraphViewWidget::CommandAnimGraphRemoveNodeCallback::Execute(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); GetOutlinerManager()->FireItemModifiedEvent(); return UpdateOpenMenuBlendGraphViewWidget(); } bool BlendGraphViewWidget::CommandAnimGraphRemoveNodeCallback::Undo(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); GetOutlinerManager()->FireItemModifiedEvent(); return UpdateOpenMenuBlendGraphViewWidget(); } bool BlendGraphViewWidget::CommandAnimGraphSetEntryStateCallback::Execute(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); GetOutlinerManager()->FireItemModifiedEvent(); return UpdateOpenMenuBlendGraphViewWidget(); } bool BlendGraphViewWidget::CommandAnimGraphSetEntryStateCallback::Undo(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); GetOutlinerManager()->FireItemModifiedEvent(); return UpdateOpenMenuBlendGraphViewWidget(); } bool BlendGraphViewWidget::CommandAnimGraphAdjustNodeGroupCallback::Execute(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); GetOutlinerManager()->FireItemModifiedEvent(); return UpdateOpenMenuBlendGraphViewWidget(); } bool BlendGraphViewWidget::CommandAnimGraphAdjustNodeGroupCallback::Undo(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); GetOutlinerManager()->FireItemModifiedEvent(); return UpdateOpenMenuBlendGraphViewWidget(); } bool BlendGraphViewWidget::CommandAnimGraphAddNodeGroupCallback::Execute(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); GetOutlinerManager()->FireItemModifiedEvent(); return UpdateOpenMenuBlendGraphViewWidget(); } bool BlendGraphViewWidget::CommandAnimGraphAddNodeGroupCallback::Undo(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); GetOutlinerManager()->FireItemModifiedEvent(); return UpdateOpenMenuBlendGraphViewWidget(); } bool BlendGraphViewWidget::CommandAnimGraphRemoveNodeGroupCallback::Execute(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); GetOutlinerManager()->FireItemModifiedEvent(); return UpdateOpenMenuBlendGraphViewWidget(); } bool BlendGraphViewWidget::CommandAnimGraphRemoveNodeGroupCallback::Undo(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); GetOutlinerManager()->FireItemModifiedEvent(); return UpdateOpenMenuBlendGraphViewWidget(); } bool BlendGraphViewWidget::CommandAnimGraphCreateParameterCallback::Execute(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); GetOutlinerManager()->FireItemModifiedEvent(); return UpdateOpenMenuBlendGraphViewWidget(); } bool BlendGraphViewWidget::CommandAnimGraphCreateParameterCallback::Undo(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); GetOutlinerManager()->FireItemModifiedEvent(); return UpdateOpenMenuBlendGraphViewWidget(); } bool BlendGraphViewWidget::CommandAnimGraphRemoveParameterCallback::Execute(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); GetOutlinerManager()->FireItemModifiedEvent(); return UpdateOpenMenuBlendGraphViewWidget(); } bool BlendGraphViewWidget::CommandAnimGraphRemoveParameterCallback::Undo(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); GetOutlinerManager()->FireItemModifiedEvent(); return UpdateOpenMenuBlendGraphViewWidget(); } bool BlendGraphViewWidget::CommandAnimGraphAdjustParameterCallback::Execute(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); GetOutlinerManager()->FireItemModifiedEvent(); return UpdateOpenMenuBlendGraphViewWidget(); } bool BlendGraphViewWidget::CommandAnimGraphAdjustParameterCallback::Undo(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); GetOutlinerManager()->FireItemModifiedEvent(); return UpdateOpenMenuBlendGraphViewWidget(); } bool BlendGraphViewWidget::CommandAnimGraphSwapParametersCallback::Execute(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); GetOutlinerManager()->FireItemModifiedEvent(); return UpdateOpenMenuBlendGraphViewWidget(); } bool BlendGraphViewWidget::CommandAnimGraphSwapParametersCallback::Undo(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); GetOutlinerManager()->FireItemModifiedEvent(); return UpdateOpenMenuBlendGraphViewWidget(); } bool BlendGraphViewWidget::CommandAnimGraphAdjustParameterGroupCallback::Execute(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); GetOutlinerManager()->FireItemModifiedEvent(); return UpdateOpenMenuBlendGraphViewWidget(); } bool BlendGraphViewWidget::CommandAnimGraphAdjustParameterGroupCallback::Undo(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); GetOutlinerManager()->FireItemModifiedEvent(); return UpdateOpenMenuBlendGraphViewWidget(); } bool BlendGraphViewWidget::CommandAnimGraphAddParameterGroupCallback::Execute(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); GetOutlinerManager()->FireItemModifiedEvent(); return UpdateOpenMenuBlendGraphViewWidget(); } bool BlendGraphViewWidget::CommandAnimGraphAddParameterGroupCallback::Undo(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); GetOutlinerManager()->FireItemModifiedEvent(); return UpdateOpenMenuBlendGraphViewWidget(); } bool BlendGraphViewWidget::CommandAnimGraphRemoveParameterGroupCallback::Execute(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); GetOutlinerManager()->FireItemModifiedEvent(); return UpdateOpenMenuBlendGraphViewWidget(); } bool BlendGraphViewWidget::CommandAnimGraphRemoveParameterGroupCallback::Undo(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); GetOutlinerManager()->FireItemModifiedEvent(); return UpdateOpenMenuBlendGraphViewWidget(); } bool BlendGraphViewWidget::CommandSelectCallback::Execute(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); if (CommandSystem::CheckIfHasAnimGraphSelectionParameter(commandLine) == false && CommandSystem::CheckIfHasActorSelectionParameter(commandLine) == false) { return true; } return UpdateOpenMenuAndMotionSetBlendGraphViewWidget(); } bool BlendGraphViewWidget::CommandSelectCallback::Undo(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); if (CommandSystem::CheckIfHasAnimGraphSelectionParameter(commandLine) == false && CommandSystem::CheckIfHasActorSelectionParameter(commandLine) == false) { return true; } return UpdateOpenMenuAndMotionSetBlendGraphViewWidget(); } bool BlendGraphViewWidget::CommandUnselectCallback::Execute(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); if (CommandSystem::CheckIfHasAnimGraphSelectionParameter(commandLine) == false && CommandSystem::CheckIfHasActorSelectionParameter(commandLine) == false) { return true; } return UpdateOpenMenuAndMotionSetBlendGraphViewWidget(); } bool BlendGraphViewWidget::CommandUnselectCallback::Undo(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); if (CommandSystem::CheckIfHasAnimGraphSelectionParameter(commandLine) == false) { return true; } return UpdateOpenMenuAndMotionSetBlendGraphViewWidget(); } bool BlendGraphViewWidget::CommandClearSelectionCallback::Execute(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); return UpdateOpenMenuAndMotionSetBlendGraphViewWidget(); } bool BlendGraphViewWidget::CommandClearSelectionCallback::Undo(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); return UpdateOpenMenuAndMotionSetBlendGraphViewWidget(); } ////////////////////////////////////////////////////////////////////////////////////////////////// // Motion set related callbacks ////////////////////////////////////////////////////////////////////////////////////////////////// bool BlendGraphViewWidget::CommandAdjustMotionSetCallback::Execute(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); if (commandLine.CheckIfHasParameter(""newName"")) { return UpdateMotionSetComboBoxResourceWidget(); } return true; } bool BlendGraphViewWidget::CommandAdjustMotionSetCallback::Undo(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); if (commandLine.CheckIfHasParameter(""newName"")) { return UpdateMotionSetComboBoxResourceWidget(); } return true; } bool BlendGraphViewWidget::CommandCreateMotionSetCallback::Execute(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); return UpdateMotionSetComboBoxResourceWidget(); } bool BlendGraphViewWidget::CommandCreateMotionSetCallback::Undo(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); return UpdateMotionSetComboBoxResourceWidget(); } bool BlendGraphViewWidget::CommandRemoveMotionSetCallback::Execute(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); return UpdateMotionSetComboBoxResourceWidget(); } bool BlendGraphViewWidget::CommandRemoveMotionSetCallback::Undo(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); return UpdateMotionSetComboBoxResourceWidget(); } bool BlendGraphViewWidget::CommandSaveMotionSetCallback::Execute(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); return UpdateMotionSetComboBoxResourceWidget(); } bool BlendGraphViewWidget::CommandSaveMotionSetCallback::Undo(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); return UpdateMotionSetComboBoxResourceWidget(); } bool BlendGraphViewWidget::CommandLoadMotionSetCallback::Execute(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); return UpdateMotionSetComboBoxResourceWidget(); } bool BlendGraphViewWidget::CommandLoadMotionSetCallback::Undo(MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(command); MCORE_UNUSED(commandLine); return UpdateMotionSetComboBoxResourceWidget(); } } // namespace EMStudio #include ",16201,True,2778.31505767449,median "/* Copyright 2020 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. */ #define _CRT_SECURE_NO_WARNINGS #include #include #include #include using namespace std; #include ""tinyinst.h"" extern ""C"" { #include ""xed/xed-interface.h"" } // nop unsigned char NOP[] = { 0x90 }; // jmp offset unsigned char JMP[] = { 0xe9, 0x00, 0x00, 0x00, 0x00 }; //call offset unsigned char CALL[] = { 0xe8, 0x00, 0x00, 0x00, 0x00 }; // warning, this is rip-relative on x64 but absolute on 32-bit // jmp [offset] unsigned char JMP_MEM[] = { 0xFF, 0x25, 0x00, 0x00, 0x00, 0x00 }; // lea rsp, [rsp + disp] unsigned char LEARSP[] = { 0x48, 0x8d, 0xa4, 0x24, 0x00, 0x00, 0x00, 0x00 }; // lea esp, [esp + disp] unsigned char LEAESP[] = { 0x8D, 0xA4, 0x24, 0x00, 0x00, 0x00, 0x00 }; // push flags // push rax // push rbx unsigned char PUSH_FAB[] = { 0x9c, 0x50, 0x53 }; // push flags // push rax unsigned char PUSH_FA[] = { 0x9c, 0x50 }; // push flags unsigned char PUSH_F[] = { 0x9c }; // push rax unsigned char PUSH_A[] = { 0x50 }; // push rbx unsigned char PUSH_B[] = { 0x53 }; // pop rbx // pop rax // pop flags unsigned char POP_BAF[] = { 0x5B, 0x58, 0x9d }; // pop rax // pop flags unsigned char POP_AF[] = { 0x58, 0x9d }; // pop rax unsigned char POP_A[] = { 0x58 }; // and rbx, constant unsigned char AND_RBX[] = { 0x48, 0x81, 0xe3, 0x00, 0x00, 0x00, 0x00 }; // and ebx, constant unsigned char AND_EBX[] = { 0x81, 0xe3, 0x00, 0x00, 0x00, 0x00 }; // mov rbx, rax unsigned char MOV_RBXRAX[] = { 0x48, 0x89, 0xC3 }; // mov ebx, eax unsigned char MOV_EBXEAX[] = { 0x89, 0xC3 }; // add rbx, [offset] unsigned char ADD_RBXRIPRELATIVE[] = { 0x48, 0x03, 0x1D, 0x00, 0x00, 0x00, 0x00 }; // add ebx, [offset] unsigned char ADD_EBXRIPRELATIVE[] = { 0x03, 0x1D, 0x00, 0x00, 0x00, 0x00 }; // jmp [rbx] unsigned char JMP_B[] = { 0xFF, 0x23 }; // cmp rax, [offset] unsigned char CMP_RAX[] = { 0x48, 0x3B, 0x05, 0x00, 0x00, 0x00, 0x00 }; // cmp eax, [offset] unsigned char CMP_EAX[] = { 0x3B, 0x05, 0x00, 0x00, 0x00, 0x00 }; // je offset unsigned char JE[] = { 0x0F, 0x84, 0x00, 0x00, 0x00, 0x00 }; // mov [rsp], imm unsigned char WRITE_SP_IMM[] = { 0xC7, 0x04, 0x24, 0xAA, 0xAA, 0xAA, 0xAA }; // mov [rsp+4], imm unsigned char WRITE_SP_4_IMM[] = { 0xC7, 0x44, 0x24, 0x04, 0xAA, 0xAA, 0xAA, 0xAA }; // mov rax, [rsp + offset] unsigned char MOV_RAX_RSPMEM[] = { 0x48, 0x8B, 0x84, 0x24, 0xAA, 0xAA, 0xAA, 0x0A }; // mov eax, [esp + offset] unsigned char MOV_EAX_ESPMEM[] = { 0x8B, 0x84, 0x24, 0xAA, 0xAA, 0xAA, 0x0A }; // mov [rsp + offset], rax unsigned char MOV_RSPMEM_RAX[] = { 0x48, 0x89, 0x84, 0x24, 0xAA, 0xAA, 0xAA, 0x0A }; // mov [esp + offset], eax unsigned char MOV_ESPMEM_EAX[] = { 0x89, 0x84, 0x24, 0xAA, 0xAA, 0xAA, 0x0A }; // mov byte ptr [0], 0 unsigned char CRASH_64[] = { 0xC6, 0x04, 0x25, 0x00, 0x00, 0x00, 0x00, 0x00 }; unsigned char CRASH_32[] = { 0xC6, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00 }; TinyInst::ModuleInfo::ModuleInfo() { module_name[0] = 0; module_header = NULL; min_address = 0; max_address = 0; loaded = false; instrumented = false; instrumented_code_local = NULL; instrumented_code_remote = NULL; instrumented_code_remote_previous = NULL; instrumented_code_size = 0; } void TinyInst::ModuleInfo::ClearInstrumentation() { instrumented = false; for (auto iter = executable_ranges.begin(); iter != executable_ranges.end(); iter++) { if (iter->data) free(iter->data); } executable_ranges.clear(); code_size = 0; if (instrumented_code_local) free(instrumented_code_local); instrumented_code_local = NULL; instrumented_code_remote = NULL; instrumented_code_remote_previous = NULL; instrumented_code_size = 0; instrumented_code_allocated = 0; basic_blocks.clear(); br_indirect_newtarget_global = 0; br_indirect_newtarget_list.clear(); jumptable_offset = 0; jumptable_address_offset = 0; invalid_instructions.clear(); tracepoints.clear(); } void TinyInst::InvalidateCrossModuleLink(CrossModuleLink *link) { ModuleInfo *module1 = link->module1; size_t original_value = ReadPointer(module1, link->offset1); WritePointerAtOffset(module1, original_value, link->offset1 + child_ptr_size); CommitCode(module1, link->offset1 + child_ptr_size, child_ptr_size); } void TinyInst::FixCrossModuleLink(CrossModuleLink *link) { ModuleInfo *module1 = link->module1; ModuleInfo *module2 = link->module2; size_t original_value = (size_t)module2->min_address + link->offset2; size_t translated_value = GetTranslatedAddress(module2, original_value); WritePointerAtOffset(module1, original_value, link->offset1); WritePointerAtOffset(module1, translated_value, link->offset1 + child_ptr_size); CommitCode(module1, link->offset1, 2 * child_ptr_size); } void TinyInst::InvalidateCrossModuleLinks(ModuleInfo *module) { for (auto iter = cross_module_links.begin(); iter != cross_module_links.end(); iter++) { if (iter->module2 == module) { InvalidateCrossModuleLink(&(*iter)); } } } void TinyInst::InvalidateCrossModuleLinks() { for (auto iter = cross_module_links.begin(); iter != cross_module_links.end(); iter++) { InvalidateCrossModuleLink(&(*iter)); } } void TinyInst::FixCrossModuleLinks(ModuleInfo *module) { for (auto iter = cross_module_links.begin(); iter != cross_module_links.end(); iter++) { if (iter->module2 == module) { FixCrossModuleLink(&(*iter)); } } } void TinyInst::ClearCrossModuleLinks(ModuleInfo *module) { auto iter = cross_module_links.begin(); while (iter != cross_module_links.end()) { if (iter->module1 == module) { iter = cross_module_links.erase(iter); } else { iter++; } } } void TinyInst::ClearCrossModuleLinks() { cross_module_links.clear(); } // Global jumptable for indirect jumps/calls. // This is an array of size JUMPTABLE_SIZE where each entry initially // points to indirect_breakpoint_address. // When a new indirect jump/call target is detected, this will cause a breakpoint // which will be resolved by adding a new entry into this hashtable. void TinyInst::InitGlobalJumptable(ModuleInfo *module) { size_t code_size_before = module->instrumented_code_allocated; module->jumptable_offset = module->instrumented_code_allocated; module->br_indirect_newtarget_global = (size_t)module->instrumented_code_remote + module->instrumented_code_allocated + JUMPTABLE_SIZE * child_ptr_size + child_ptr_size; for (size_t i = 0; i < JUMPTABLE_SIZE; i++) { WritePointer(module, module->br_indirect_newtarget_global); } module->jumptable_address_offset = module->instrumented_code_allocated; WritePointer(module, (size_t)module->instrumented_code_remote + module->jumptable_offset); unsigned char breakpoint = 0xCC; WriteCode(module, &breakpoint, 1); size_t code_size_after = module->instrumented_code_allocated; CommitCode(module, code_size_before, (code_size_after - code_size_before)); } // Writes the modified code from the debugger process into the target process void TinyInst::CommitCode(ModuleInfo *module, size_t start_offset, size_t size) { if (!module->instrumented_code_remote) return; RemoteWrite(module->instrumented_code_remote + start_offset, module->instrumented_code_local + start_offset, size); } // Checks if there is sufficient space and writes code at the current offset void TinyInst::WriteCode(ModuleInfo *module, void *data, size_t size) { if (module->instrumented_code_allocated + size > module->instrumented_code_size) { FATAL(""Insufficient memory allocated for instrumented code""); } memcpy(module->instrumented_code_local + module->instrumented_code_allocated, data, size); module->instrumented_code_allocated += size; } // Checks if there is sufficient space and writes code at the chosen offset void TinyInst::WriteCodeAtOffset(ModuleInfo *module, size_t offset, void *data, size_t size) { if (offset + size > module->instrumented_code_size) { FATAL(""Insufficient memory allocated for instrumented code""); } memcpy(module->instrumented_code_local + offset, data, size); if (offset + size > module->instrumented_code_allocated) { module->instrumented_code_allocated = offset + size; } } // writes a pointer to the instrumented code void TinyInst::WritePointer(ModuleInfo *module, size_t value) { if (module->instrumented_code_allocated + child_ptr_size > module->instrumented_code_size) { FATAL(""Insufficient memory allocated for instrumented code""); } if (child_ptr_size == 8) { *(uint64_t *)(module->instrumented_code_local + module->instrumented_code_allocated) = (uint64_t)value; } else { *(uint32_t *)(module->instrumented_code_local + module->instrumented_code_allocated) = (uint32_t)value; } module->instrumented_code_allocated += child_ptr_size; } // writes a pointer to the instrumented code void TinyInst::WritePointerAtOffset(ModuleInfo *module, size_t value, size_t offset) { if (offset + child_ptr_size > module->instrumented_code_size) { FATAL(""Insufficient memory allocated for instrumented code""); } if (child_ptr_size == 8) { *(uint64_t *)(module->instrumented_code_local + offset) = (uint64_t)value; } else { *(uint32_t *)(module->instrumented_code_local + offset) = (uint32_t)value; } if (offset + child_ptr_size > module->instrumented_code_allocated) { module->instrumented_code_allocated += offset + child_ptr_size; } } // reads a pointer from the instrumented code size_t TinyInst::ReadPointer(ModuleInfo *module, size_t offset) { if (child_ptr_size == 8) { return (size_t)(*(uint64_t *)(module->instrumented_code_local + offset)); } else { return (size_t)(*(uint32_t *)(module->instrumented_code_local + offset)); } } // fixes an offset in the jump instruction (at offset jmp_offset in the instrumented code) // to jump to the given basic block (at offset bb in the original code) // in case the basic block hasn't been instrumented yet, queues it for instrumentation void TinyInst::FixOffsetOrEnqueue(ModuleInfo *module, uint32_t bb, uint32_t jmp_offset, std::set *queue, std::list> *offset_fixes) { auto iter = module->basic_blocks.find(bb); if (iter == module->basic_blocks.end()) { char *address = (char *)module->min_address + bb; if (queue->find(address) == queue->end()) { queue->insert(address); } offset_fixes->push_back({ bb, jmp_offset }); } else { int32_t jmp_relative_offset = (int32_t)iter->second - (int32_t)(jmp_offset + 4); *(int32_t *)(module->instrumented_code_local + jmp_offset) = jmp_relative_offset; } } // adds/subtracts a given offset to the stack pointer // this is done using LEA instruction rather than ADD/SUB // to avoid clobbering the flags void TinyInst::OffsetStack(ModuleInfo *module, int32_t offset) { // lea rsp, [rsp + offset] if (child_ptr_size == 8) { WriteCode(module, LEARSP, sizeof(LEARSP)); } else { WriteCode(module, LEAESP, sizeof(LEAESP)); } FixDisp4(module, offset); } // mov rax, [rsp + offset] void TinyInst::ReadStack(ModuleInfo *module, int32_t offset) { if (child_ptr_size == 8) { WriteCode(module, MOV_RAX_RSPMEM, sizeof(MOV_RAX_RSPMEM)); } else { WriteCode(module, MOV_EAX_ESPMEM, sizeof(MOV_EAX_ESPMEM)); } FixDisp4(module, offset); } // mov [rsp + offset], rax void TinyInst::WriteStack(ModuleInfo *module, int32_t offset) { if (child_ptr_size == 8) { WriteCode(module, MOV_RSPMEM_RAX, sizeof(MOV_RSPMEM_RAX)); } else { WriteCode(module, MOV_ESPMEM_EAX, sizeof(MOV_ESPMEM_EAX)); } FixDisp4(module, offset); } // converts an indirect jump/call into a MOV instruction // which moves the target of the indirect call into the RAX/EAX reguster // and writes this instruction into the code buffer void TinyInst::MovIndirectTarget(ModuleInfo *module, xed_decoded_inst_t *xedd, size_t original_address, int32_t stack_offset) { size_t mem_address = 0; bool rip_relative = IsRipRelative(module, xedd, original_address, &mem_address); xed_error_enum_t xed_error; uint32_t olen; const xed_inst_t* xi = xed_decoded_inst_inst(xedd); const xed_operand_t* op = xed_inst_operand(xi, 0); xed_operand_enum_t operand_name = xed_operand_name(op); xed_state_t dstate; dstate.mmode = (xed_machine_mode_enum_t)xed_mmode; dstate.stack_addr_width = (xed_address_width_enum_t)child_ptr_size; xed_reg_enum_t dest_reg; if (child_ptr_size == 4) { dest_reg = XED_REG_EAX; } else { dest_reg = XED_REG_RAX; } xed_encoder_request_t mov; xed_encoder_request_zero_set_mode(&mov, &dstate); xed_encoder_request_set_iclass(&mov, XED_ICLASS_MOV); xed_encoder_request_set_effective_operand_width(&mov, (uint32_t)(child_ptr_size * 8)); xed_encoder_request_set_effective_address_size(&mov, (uint32_t)(child_ptr_size * 8)); xed_encoder_request_set_reg(&mov, XED_OPERAND_REG0, dest_reg); xed_encoder_request_set_operand_order(&mov, 0, XED_OPERAND_REG0); if (operand_name == XED_OPERAND_MEM0) { xed_encoder_request_set_mem0(&mov); xed_reg_enum_t base_reg = xed_decoded_inst_get_base_reg(xedd, 0); xed_encoder_request_set_base0(&mov, base_reg); xed_encoder_request_set_seg0(&mov, xed_decoded_inst_get_seg_reg(xedd, 0)); xed_encoder_request_set_index(&mov, xed_decoded_inst_get_index_reg(xedd, 0)); xed_encoder_request_set_scale(&mov, xed_decoded_inst_get_scale(xedd, 0)); // in an unlikely case where base is rsp, disp needs fixing // this is because we pushed stuff on the stack if ((base_reg == XED_REG_SP) || (base_reg == XED_REG_ESP) || (base_reg == XED_REG_RSP)) { // printf(""base = sp\\n""); int64_t disp = xed_decoded_inst_get_memory_displacement(xedd, 0) + stack_offset; // always use disp width 4 in this case xed_encoder_request_set_memory_displacement(&mov, disp, 4); } else { xed_encoder_request_set_memory_displacement(&mov, xed_decoded_inst_get_memory_displacement(xedd, 0), xed_decoded_inst_get_memory_displacement_width(xedd, 0)); } xed_encoder_request_set_memory_operand_length(&mov, xed_decoded_inst_get_memory_operand_length(xedd, 0)); xed_encoder_request_set_operand_order(&mov, 1, XED_OPERAND_MEM0); } else if (operand_name == XED_OPERAND_REG0) { xed_encoder_request_set_reg(&mov, XED_OPERAND_REG1, xed_decoded_inst_get_reg(xedd, XED_OPERAND_REG0)); xed_encoder_request_set_operand_order(&mov, 1, XED_OPERAND_REG1); } else { FATAL(""Unexpected operand in indirect jump/call""); } unsigned char encoded[15]; xed_error = xed_encode(&mov, encoded, sizeof(encoded), &olen); if (xed_error != XED_ERROR_NONE) { FATAL(""Error encoding instruction""); } if (rip_relative) { // fix displacement size_t out_instruction_size = olen; int64_t fixed_disp = (int64_t)mem_address - (int64_t)((size_t)module->instrumented_code_remote + module->instrumented_code_allocated + out_instruction_size); xed_encoder_request_set_memory_displacement(&mov, fixed_disp, 4); xed_error = xed_encode(&mov, encoded, sizeof(encoded), &olen); if (xed_error != XED_ERROR_NONE) { FATAL(""Error encoding instruction""); } if (olen != out_instruction_size) { FATAL(""Unexpected instruction size""); } } WriteCode(module, encoded, olen); } // various breapoints bool TinyInst::HandleBreakpoint(void *address) { ModuleInfo *module = GetModuleFromInstrumented((size_t)address); if (!module) return false; // bb tracing if (trace_basic_blocks) { auto iter = module->tracepoints.find((size_t)address); if (iter != module->tracepoints.end()) { printf(""TRACE: Executing basic block, original at %p, instrumented at %p\\n"", (void *)iter->second, (void *)iter->first); return true; } else { printf(""TRACE: Breakpoint\\n""); } } // indirect jump new target if (HandleIndirectJMPBreakpoint(address)) return true; // invalid instruction if (module->invalid_instructions.find((size_t)address) != module->invalid_instructions.end()) { WARN(""Attempting to execute an instruction TinyInst couldn't translate""); WARN(""This could be either due to a bug in the target or the bug/incompatibility in TinyInst""); WARN(""The target will crash now""); return true; } return false; } // handles a breakpoint that occurs // when an indirect jump or call wants to go to a previously // unseen target bool TinyInst::HandleIndirectJMPBreakpoint(void *address) { if (indirect_instrumentation_mode == II_NONE) return false; ModuleInfo *module = GetModuleFromInstrumented((size_t)address); if (!module) return false; bool is_indirect_breakpoint = false; bool global_indirect; size_t list_head_offset; size_t instruction_address = 0; if ((size_t)address == module->br_indirect_newtarget_global) { is_indirect_breakpoint = true; global_indirect = true; } else { auto iter = module->br_indirect_newtarget_list.find((size_t)address); if (iter != module->br_indirect_newtarget_list.end()) { is_indirect_breakpoint = true; global_indirect = false; list_head_offset = iter->second.list_head; instruction_address = iter->second.source_bb; } } if (!is_indirect_breakpoint) return false; size_t original_address = GetRegister(RAX); // if it's a global indirect, list head must be calculated from target // otherwise it's a per-callsite indirect and the list head was set earlier if (global_indirect) { list_head_offset = module->jumptable_offset + original_address & ((JUMPTABLE_SIZE - 1) * child_ptr_size); } size_t translated_address; ModuleInfo *target_module = GetModule((size_t)original_address); if (target_module == module) { translated_address = GetTranslatedAddress(module, original_address); } else if (target_module && instrument_cross_module_calls) { translated_address = GetTranslatedAddress(target_module, original_address); } else { translated_address = original_address; } // printf(""Adding jumptable entry, %p -> %p\\n"", // (void *)original_address, (void *)translated_address); size_t entry_offset = AddTranslatedJump(module, target_module, original_address, translated_address, list_head_offset, instruction_address, global_indirect); // redirect execution to just created entry which should handle it immediately SetRegister(RIP, (size_t)module->instrumented_code_remote + entry_offset); return true; } // adds another observed original_target -> actual_target pair // to the golbal jumptable at the appropriate location size_t TinyInst::AddTranslatedJump(ModuleInfo *module, ModuleInfo *target_module, size_t original_target, size_t actual_target, size_t list_head_offset, size_t edge_start_address, bool global_indirect) { size_t entry_offset = module->instrumented_code_allocated; size_t previous; size_t previous_offset; // gets the previous list head if (child_ptr_size == 8) { previous = (size_t)(*(uint64_t *)(module->instrumented_code_local + list_head_offset)); } else { previous = *(uint32_t *)(module->instrumented_code_local + list_head_offset); } previous_offset = previous - (size_t)module->instrumented_code_remote; // cmp RAX, [original_target] if (child_ptr_size == 8) { WriteCode(module, CMP_RAX, sizeof(CMP_RAX)); } else { WriteCode(module, CMP_EAX, sizeof(CMP_EAX)); } size_t cmp_offset = module->instrumented_code_allocated; // je label WriteCode(module, JE, sizeof(JE)); FixDisp4(module, sizeof(JMP)); // jmp previous_list_head WriteCode(module, JMP, sizeof(JMP)); FixDisp4(module, (int32_t)((int64_t)previous_offset - (int64_t)module->instrumented_code_allocated)); // (maybe) pop RBX // pop RAX // pop flags if (global_indirect) { WriteCode(module, POP_BAF, sizeof(POP_BAF)); } else { WriteCode(module, POP_AF, sizeof(POP_AF)); } if (sp_offset) { OffsetStack(module, sp_offset); } // consider indirect call/jump an edge and insert appropriate instrumentation InstrumentEdge(module, target_module, edge_start_address, original_target); // jmp [actual_target] WriteCode(module, JMP_MEM, sizeof(JMP_MEM)); if (child_ptr_size == 8) { FixDisp4(module, (int32_t)child_ptr_size); *(int32_t *)(module->instrumented_code_local + cmp_offset - 4) = (int32_t)((int64_t)module->instrumented_code_allocated - (int64_t)cmp_offset); } else { FixDisp4(module, (int32_t)(GetCurrentInstrumentedAddress(module) + child_ptr_size)); *(int32_t *)(module->instrumented_code_local + cmp_offset - 4) = (int32_t)GetCurrentInstrumentedAddress(module); } if (target_module && (module != target_module)) { CrossModuleLink link; link.module1 = module; link.module2 = target_module; link.offset1 = module->instrumented_code_allocated; link.offset2 = original_target - (size_t)target_module->min_address; // printf(""Cross module link to %p\\n"", (void *)original_target); cross_module_links.push_back(link); } WritePointer(module, original_target); WritePointer(module, actual_target); // add to the head of the linked list if (child_ptr_size == 8) { *(uint64_t *)(module->instrumented_code_local + list_head_offset) = (uint64_t)((size_t)module->instrumented_code_remote + entry_offset); } else { *(uint32_t *)(module->instrumented_code_local + list_head_offset) = (uint32_t)((size_t)module->instrumented_code_remote + entry_offset); } CommitCode(module, list_head_offset, child_ptr_size); CommitCode(module, entry_offset, module->instrumented_code_allocated - entry_offset); return entry_offset; } TinyInst::IndirectInstrumentation TinyInst::ShouldInstrumentIndirect( ModuleInfo *module, xed_decoded_inst_t *xedd, size_t instruction_address) { xed_category_enum_t category; category = xed_decoded_inst_get_category(xedd); xed_iclass_enum_t iclass; iclass = xed_decoded_inst_get_iclass(xedd); if (category == XED_CATEGORY_RET) { if (!patch_return_addresses) return II_NONE; if (iclass != XED_ICLASS_RET_NEAR) return II_NONE; } else { if ((iclass != XED_ICLASS_JMP) && (iclass != XED_ICLASS_CALL_NEAR)) return II_NONE; } if (indirect_instrumentation_mode != II_AUTO) { return indirect_instrumentation_mode; } else { // default to the most performant mode which is II_GLOBAL return II_GLOBAL; } } void TinyInst::InstrumentRet(ModuleInfo *module, xed_decoded_inst_t *xedd, size_t instruction_address, IndirectInstrumentation mode, size_t bb_address) { // lots of moving around, but the problem is // we need to store context in the same place // where the return address is // at the end, the stack must be // saved RAX // saved EFLAGS // // and RAX must contain return address // store rax to a safe offset int32_t ax_offset = -sp_offset - 2 * child_ptr_size; WriteStack(module, ax_offset); // copy return address to a safe offset int32_t ret_offset = ax_offset - child_ptr_size; ReadStack(module, 0); WriteStack(module, ret_offset); // get ret immediate int32_t imm = (int32_t)xed_decoded_inst_get_unsigned_immediate(xedd); // align the stack int32_t ret_pop = (int32_t)child_ptr_size + imm - sp_offset; OffsetStack(module, ret_pop); //pop ax_offset -= ret_pop; ret_offset -= ret_pop; // write data to stack WriteCode(module, PUSH_F, sizeof(PUSH_F)); ax_offset += child_ptr_size; ret_offset += child_ptr_size; ReadStack(module, ax_offset); WriteCode(module, PUSH_A, sizeof(PUSH_A)); ax_offset += child_ptr_size; ret_offset += child_ptr_size; ReadStack(module, ret_offset); InstrumentIndirect(module, xedd, instruction_address, mode, bb_address); } void TinyInst::InstrumentIndirect(ModuleInfo *module, xed_decoded_inst_t *xedd, size_t instruction_address, IndirectInstrumentation mode, size_t bb_address) { if (mode == II_GLOBAL) { InstrumentGlobalIndirect(module, xedd, instruction_address); } else if (mode == II_LOCAL) { InstrumentLocalIndirect(module, xedd, instruction_address, bb_address); } else { FATAL(""Unexpected IndirectInstrumentation value""); } } // translates indirect jump or call // using global jumptable void TinyInst::InstrumentGlobalIndirect(ModuleInfo *module, xed_decoded_inst_t *xedd, size_t instruction_address) { if (xed_decoded_inst_get_category(xedd) != XED_CATEGORY_RET) { if (sp_offset) { OffsetStack(module, -sp_offset); } // push eflags // push RAX // push RBX WriteCode(module, PUSH_FAB, sizeof(PUSH_FAB)); int32_t stack_offset = sp_offset + 3 * child_ptr_size; if (xed_decoded_inst_get_category(xedd) == XED_CATEGORY_CALL) { stack_offset += child_ptr_size; } MovIndirectTarget(module, xedd, instruction_address, stack_offset); } else { // stack already set up, just push RBX WriteCode(module, PUSH_B, sizeof(PUSH_B)); } // mov rbx, rax // and rbx, (JUMPTABLE_SIZE - 1) * child_ptr_size if (child_ptr_size == 8) { WriteCode(module, MOV_RBXRAX, sizeof(MOV_RBXRAX)); WriteCode(module, AND_RBX, sizeof(AND_RBX)); } else { WriteCode(module, MOV_EBXEAX, sizeof(MOV_EBXEAX)); WriteCode(module, AND_EBX, sizeof(AND_EBX)); } FixDisp4(module, (int32_t)((JUMPTABLE_SIZE - 1) * child_ptr_size)); // add rbx, [jumptable_address] if (child_ptr_size == 8) { WriteCode(module, ADD_RBXRIPRELATIVE, sizeof(ADD_RBXRIPRELATIVE)); FixDisp4(module, (int32_t)((int64_t)module->jumptable_address_offset - (int64_t)module->instrumented_code_allocated)); } else { WriteCode(module, ADD_EBXRIPRELATIVE, sizeof(ADD_EBXRIPRELATIVE)); FixDisp4(module, (int32_t)((size_t)module->instrumented_code_remote + module->jumptable_address_offset)); } // jmp RBX WriteCode(module, JMP_B, sizeof(JMP_B)); } // translates indirect jump or call // using local jumptable void TinyInst::InstrumentLocalIndirect(ModuleInfo *module, xed_decoded_inst_t *xedd, size_t instruction_address, size_t bb_address) { if (xed_decoded_inst_get_category(xedd) != XED_CATEGORY_RET) { if (sp_offset) { OffsetStack(module, -sp_offset); } // push eflags // push RAX WriteCode(module, PUSH_FA, sizeof(PUSH_FA)); int32_t stack_offset = sp_offset + 2 * child_ptr_size; if (xed_decoded_inst_get_category(xedd) == XED_CATEGORY_CALL) { stack_offset += child_ptr_size; } MovIndirectTarget(module, xedd, instruction_address, stack_offset); } else { // stack already set up } // jmp [breakpoint] WriteCode(module, JMP_MEM, sizeof(JMP_MEM)); size_t breakpoint_address = GetCurrentInstrumentedAddress(module); if (child_ptr_size == 8) { FixDisp4(module, 1); } else { FixDisp4(module, (int32_t)(breakpoint_address + 1)); } // int3 unsigned char breakpoint = 0xCC; WriteCode(module, &breakpoint, 1); module->br_indirect_newtarget_list[breakpoint_address] = { module->instrumented_code_allocated, bb_address }; // breakpoint_address if (child_ptr_size == 8) { uint64_t address = (uint64_t)breakpoint_address; WriteCode(module, &address, sizeof(address)); } else { uint32_t address = (uint32_t)breakpoint_address; WriteCode(module, &address, sizeof(address)); } } // pushes return address on the target stack void TinyInst::PushReturnAddress(ModuleInfo *module, uint64_t return_address) { // printf(""retun address: %llx\\n"", return_address); // write the original return address OffsetStack(module, -(int)child_ptr_size); uint32_t return_lo = (uint32_t)(((uint64_t)return_address) & 0xFFFFFFFF); uint32_t return_hi = (uint32_t)(((uint64_t)return_address) >> 32); // mov dword ptr [sp], return_lo WriteCode(module, WRITE_SP_IMM, sizeof(WRITE_SP_IMM)); *(uint32_t *)(module->instrumented_code_local + module->instrumented_code_allocated - 4) = return_lo; if (child_ptr_size == 8) { // mov dword ptr [sp+4], return_hi WriteCode(module, WRITE_SP_4_IMM, sizeof(WRITE_SP_4_IMM)); *(uint32_t *)(module->instrumented_code_local + module->instrumented_code_allocated - 4) = return_hi; } } // checks if the instruction uses RIP-relative addressing, // e.g. mov rax, [rip+displacement]; call [rip+displacement] // and, if so, returns the memory address being referenced bool TinyInst::IsRipRelative(ModuleInfo *module, xed_decoded_inst_t *xedd, size_t instruction_address, size_t *mem_address) { bool rip_relative = false; int64_t disp; uint32_t memops = xed_decoded_inst_number_of_memory_operands(xedd); for (uint32_t i = 0; iinstrumented_code_remote + module->instrumented_code_allocated + original_instruction_size; // encode an instruction once just to get the instruction size // as it needs not be the original size fixed_disp = (int64_t)(mem_address) - (int64_t)(instruction_end_addr); if (llabs(fixed_disp) > 0x7FFFFFFF) FATAL(""Offset larger than 2G""); xed_encoder_request_set_memory_displacement(xedd, fixed_disp, 4); xed_error = xed_encode(xedd, tmp, sizeof(tmp), &olen); if (xed_error != XED_ERROR_NONE) { FATAL(""Error encoding instruction""); } size_t out_instruction_size = olen; if ((module->instrumented_code_allocated + out_instruction_size) > module->instrumented_code_size) { FATAL(""Insufficient memory allocated for instrumented code""); } instruction_end_addr = (size_t)module->instrumented_code_remote + module->instrumented_code_allocated + out_instruction_size; fixed_disp = (int64_t)(mem_address) - (int64_t)(instruction_end_addr); if (llabs(fixed_disp) > 0x7FFFFFFF) FATAL(""Offset larger than 2G""); xed_encoder_request_set_memory_displacement(xedd, fixed_disp, 4); xed_error = xed_encode(xedd, (unsigned char *)(module->instrumented_code_local + module->instrumented_code_allocated), (uint32_t)(module->instrumented_code_size - module->instrumented_code_allocated), &olen); if (xed_error != XED_ERROR_NONE) { FATAL(""Error encoding instruction""); } if (olen != out_instruction_size) { FATAL(""Unexpected instruction size""); } module->instrumented_code_allocated += olen; } // when an invalid instruction is encountered // emit a breakpoint followed by crashing the process void TinyInst::InvalidInstruction(ModuleInfo *module) { unsigned char breakpoint = 0xCC; size_t breakpoint_address = (size_t)module->instrumented_code_remote + module->instrumented_code_allocated; WriteCode(module, &breakpoint, 1); module->invalid_instructions.insert(breakpoint_address); if (child_ptr_size == 8) { WriteCode(module, CRASH_64, sizeof(CRASH_64)); } else { WriteCode(module, CRASH_32, sizeof(CRASH_32)); } } void TinyInst::TranslateBasicBlock(char *address, ModuleInfo *module, set *queue, list> *offset_fixes) { uint32_t original_offset = (uint32_t)((size_t)address - (size_t)(module->min_address)); uint32_t translated_offset = (uint32_t)module->instrumented_code_allocated; // printf(""Instrumenting bb, original at %p, instrumented at %p\\n"", // address, module->instrumented_code_remote + translated_offset); module->basic_blocks.insert({ original_offset, translated_offset }); AddressRange *range = GetRegion(module, (size_t)address); if (!range) { // just insert a jump to address WriteCode(module, JMP_MEM, sizeof(JMP_MEM)); WritePointer(module, (size_t)address); return; } uint32_t range_offset = (uint32_t)((size_t)address - (size_t)range->from); size_t code_size = (uint32_t)((size_t)range->to - (size_t)address); char *code_ptr = range->data + range_offset; size_t offset = 0, last_offset = 0; xed_decoded_inst_t xedd; xed_error_enum_t xed_error; xed_state_t dstate; dstate.mmode = (xed_machine_mode_enum_t)xed_mmode; dstate.stack_addr_width = (xed_address_width_enum_t)child_ptr_size; xed_category_enum_t category; bool bbend = false; if (trace_basic_blocks) { unsigned char breakpoint = 0xCC; size_t breakpoint_address = (size_t)module->instrumented_code_remote + module->instrumented_code_allocated; WriteCode(module, &breakpoint, 1); module->tracepoints[breakpoint_address] = (size_t)address; } else if (GetTargetMethodAddress()) { // hack, allow 1 byte of unused space at the beginning // of the target method. This is needed because we // are setting a brekpoint here. If this breakpoint falls // into code inserted by the client, and the client modifies // that code later, we loose the breakpoint. if(GetTargetMethodAddress() == address) { WriteCode(module, NOP, sizeof(NOP)); } } // write pre-bb instrumentation InstrumentBasicBlock(module, (size_t)address); while (true) { xed_decoded_inst_zero_set_mode(&xedd, &dstate); xed_error = xed_decode(&xedd, (const unsigned char *)(code_ptr + offset), (unsigned int)(code_size - offset)); if (xed_error != XED_ERROR_NONE) break; size_t instruction_length = xed_decoded_inst_get_length(&xedd); // instruction-level-instrumentation InstructionResult instrumentation_result = InstrumentInstruction(module, &xedd, (size_t)address, (size_t)address + offset); switch (instrumentation_result) { case INST_HANDLED: offset += instruction_length; continue; case INST_STOPBB: return; case INST_NOTHANDLED: default: break; } category = xed_decoded_inst_get_category(&xedd); switch (category) { case XED_CATEGORY_CALL: case XED_CATEGORY_RET: case XED_CATEGORY_UNCOND_BR: case XED_CATEGORY_COND_BR: bbend = true; break; default: break; } last_offset = offset; offset += instruction_length; if (bbend) break; FixInstructionAndOutput(module, &xedd, (unsigned char *)(code_ptr + last_offset), (unsigned char *)(address + last_offset)); } if (!bbend) { // WARN(""Could not find end of bb at %p.\\n"", address); InvalidInstruction(module); return; } if (category == XED_CATEGORY_RET) { IndirectInstrumentation ii_mode = ShouldInstrumentIndirect(module, &xedd, (size_t)address + last_offset); if (ii_mode != II_NONE) { InstrumentRet(module, &xedd, (size_t)address + last_offset, ii_mode, (size_t)address); } else { FixInstructionAndOutput(module, &xedd, (unsigned char *)(code_ptr + last_offset), (unsigned char *)(address + last_offset)); } } else if(category == XED_CATEGORY_COND_BR) { // j* target_address // gets instrumented as: // j* label // // jmp continue_address // label: // // jmp target_address // must have an operand const xed_inst_t* xi = xed_decoded_inst_inst(&xedd); const xed_operand_t* op = xed_inst_operand(xi, 0); xed_operand_enum_t operand_name = xed_operand_name(op); if (operand_name != XED_OPERAND_RELBR) { FATAL(""Error getting branch target""); } int32_t disp = xed_decoded_inst_get_branch_displacement(&xedd); uint32_t disp_width = xed_decoded_inst_get_branch_displacement_width(&xedd); if (disp_width == 0) { FATAL(""Error getting branch target""); } char* target_address1 = address + offset; char* target_address2 = address + offset + disp; if (GetModule((size_t)target_address2) != module) { WARN(""Relative jump to a differen module in bb at %p\\n"", address); InvalidInstruction(module); return; } // preliminary encode jump instruction // displacement might be changed later as we don't know // the size of edge instrumentation yet // assuming 0 for now int32_t fixed_disp = sizeof(JMP); unsigned char encoded[15]; unsigned int olen; unsigned int jump_size; xed_encoder_request_init_from_decode(&xedd); xed_encoder_request_set_branch_displacement(&xedd, fixed_disp, disp_width); xed_error = xed_encode(&xedd, encoded, sizeof(encoded), &olen); if (xed_error != XED_ERROR_NONE) { FATAL(""Error encoding instruction""); } jump_size = olen; size_t jump_start_offset = module->instrumented_code_allocated; WriteCode(module, encoded, jump_size); size_t jump_end_offset = module->instrumented_code_allocated; // instrument the 1st edge InstrumentEdge(module, module, (size_t)address, (size_t)target_address1); // jmp target_address1 WriteCode(module, JMP, sizeof(JMP)); FixOffsetOrEnqueue(module, (uint32_t)((size_t)target_address1 - (size_t)(module->min_address)), (uint32_t)(module->instrumented_code_allocated - 4), queue, offset_fixes); // time to fix that conditional jump offset if ((module->instrumented_code_allocated - jump_end_offset) != fixed_disp) { fixed_disp = (int32_t)(module->instrumented_code_allocated - jump_end_offset); xed_encoder_request_set_branch_displacement(&xedd, fixed_disp, disp_width); xed_error = xed_encode(&xedd, encoded, sizeof(encoded), &olen); if (xed_error != XED_ERROR_NONE) { FATAL(""Error encoding instruction""); } if (jump_size != olen) { FATAL(""Instruction size changed?""); } WriteCodeAtOffset(module, jump_start_offset, encoded, jump_size); } // instrument the 2nd edge InstrumentEdge(module, module, (size_t)address, (size_t)target_address2); // jmp target_address2 WriteCode(module, JMP, sizeof(JMP)); FixOffsetOrEnqueue(module, (uint32_t)((size_t)target_address2 - (size_t)(module->min_address)), (uint32_t)(module->instrumented_code_allocated - 4), queue, offset_fixes); } else if (category == XED_CATEGORY_UNCOND_BR) { // must have an operand const xed_inst_t* xi = xed_decoded_inst_inst(&xedd); const xed_operand_t* op = xed_inst_operand(xi, 0); xed_operand_enum_t operand_name = xed_operand_name(op); if (operand_name == XED_OPERAND_RELBR) { // jmp address // gets instrumented as: // jmp fixed_address int32_t disp = xed_decoded_inst_get_branch_displacement(&xedd); uint32_t disp_width = xed_decoded_inst_get_branch_displacement_width(&xedd); if (disp_width == 0) { FATAL(""Error getting branch target""); } char *target_address = address + offset + disp; if (GetModule((size_t)target_address) != module) { WARN(""Relative jump to a differen module in bb at %p\\n"", address); InvalidInstruction(module); return; } // jmp target_address WriteCode(module, JMP, sizeof(JMP)); FixOffsetOrEnqueue(module, (uint32_t)((size_t)target_address - (size_t)(module->min_address)), (uint32_t)(module->instrumented_code_allocated - 4), queue, offset_fixes); } else { IndirectInstrumentation ii_mode = ShouldInstrumentIndirect(module, &xedd, (size_t)address + last_offset); if (ii_mode != II_NONE) { InstrumentIndirect(module, &xedd, (size_t)address + last_offset, ii_mode, (size_t)address); } else { FixInstructionAndOutput(module, &xedd, (unsigned char *)(code_ptr + last_offset), (unsigned char *)(address + last_offset)); } } } else if (category == XED_CATEGORY_CALL) { // must have an operand const xed_inst_t* xi = xed_decoded_inst_inst(&xedd); const xed_operand_t* op = xed_inst_operand(xi, 0); xed_operand_enum_t operand_name = xed_operand_name(op); if (operand_name == XED_OPERAND_RELBR) { // call target_address // gets instrumented as: // call label // jmp return_address // label: // jmp target_address int32_t disp = xed_decoded_inst_get_branch_displacement(&xedd); uint32_t disp_width = xed_decoded_inst_get_branch_displacement_width(&xedd); if (disp_width == 0) { FATAL(""Error getting branch target""); } char* return_address = address + offset; char *call_address = address + offset + disp; if (GetModule((size_t)call_address) != module) { WARN(""Relative jump to a differen module in bb at %p\\n"", address); InvalidInstruction(module); return; } // fix the displacement and emit the call if (!patch_return_addresses) { unsigned char encoded[15]; unsigned int olen; xed_encoder_request_init_from_decode(&xedd); xed_encoder_request_set_branch_displacement(&xedd, sizeof(JMP), disp_width); xed_error = xed_encode(&xedd, encoded, sizeof(encoded), &olen); if (xed_error != XED_ERROR_NONE) { FATAL(""Error encoding instruction""); } WriteCode(module, encoded, olen); // jmp return_address WriteCode(module, JMP, sizeof(JMP)); FixOffsetOrEnqueue(module, (uint32_t)((size_t)return_address - (size_t)(module->min_address)), (uint32_t)(module->instrumented_code_allocated - 4), queue, offset_fixes); // jmp call_address WriteCode(module, JMP, sizeof(JMP)); FixOffsetOrEnqueue(module, (uint32_t)((size_t)call_address - (size_t)(module->min_address)), (uint32_t)(module->instrumented_code_allocated - 4), queue, offset_fixes); } else { PushReturnAddress(module, (uint64_t)return_address); // jmp call_address WriteCode(module, JMP, sizeof(JMP)); FixOffsetOrEnqueue(module, (uint32_t)((size_t)call_address - (size_t)(module->min_address)), (uint32_t)(module->instrumented_code_allocated - 4), queue, offset_fixes); // done, we don't need to do anything else as return gets redirected later } } else /* CALL, operand_name != XED_OPERAND_RELBR */ { char* return_address = address + offset; IndirectInstrumentation ii_mode = ShouldInstrumentIndirect(module, &xedd, (size_t)address + last_offset); if (ii_mode != II_NONE) { if (patch_return_addresses) { PushReturnAddress(module, (uint64_t)return_address); InstrumentIndirect(module, &xedd, (size_t)address + last_offset, ii_mode, (size_t)address); } else { // call label // jmp return_address // label: // WriteCode(module, CALL, sizeof(CALL)); FixDisp4(module, sizeof(JMP)); WriteCode(module, JMP, sizeof(JMP)); FixOffsetOrEnqueue(module, (uint32_t)((size_t)return_address - (size_t)(module->min_address)), (uint32_t)(module->instrumented_code_allocated - 4), queue, offset_fixes); InstrumentIndirect(module, &xedd, (size_t)address + last_offset, ii_mode, (size_t)address); } } else { if (patch_return_addresses) { PushReturnAddress(module, (uint64_t)return_address); //xed_decoded_inst_t jmp; //CallToJmp(&xedd, &jmp); FixInstructionAndOutput(module, &xedd, (unsigned char *)(code_ptr + last_offset), (unsigned char *)(address + last_offset), true); } else { FixInstructionAndOutput(module, &xedd, (unsigned char *)(code_ptr + last_offset), (unsigned char *)(address + last_offset)); WriteCode(module, JMP, sizeof(JMP)); FixOffsetOrEnqueue(module, (uint32_t)((size_t)return_address - (size_t)(module->min_address)), (uint32_t)(module->instrumented_code_allocated - 4), queue, offset_fixes); } } } } } // starting from address, starts instrumenting code in the module // any other basic blocks detected during instrumentation // (e.g. jump, call targets) get added to the queue // and instrumented as well void TinyInst::TranslateBasicBlockRecursive(char *address, ModuleInfo *module) { set queue; list> offset_fixes; size_t code_size_before = module->instrumented_code_allocated; TranslateBasicBlock(address, module, &queue, &offset_fixes); while (!queue.empty()) { address = *queue.begin(); TranslateBasicBlock(address, module, &queue, &offset_fixes); queue.erase(address); } for (auto iter = offset_fixes.begin(); iter != offset_fixes.end(); iter++) { uint32_t bb = iter->first; uint32_t jmp_offset = iter->second; auto bb_iter = module->basic_blocks.find(bb); if (bb_iter == module->basic_blocks.end()) { FATAL(""Couldn't fix jump offset\\n""); } int32_t jmp_relative_offset = (int32_t)bb_iter->second - (int32_t)(jmp_offset + 4); *(int32_t *)(module->instrumented_code_local + jmp_offset) = jmp_relative_offset; } size_t code_size_after = module->instrumented_code_allocated; // Commit everything in one go here CommitCode(module, code_size_before, (code_size_after - code_size_before)); } // gets ModuleInfo for the module specified by name TinyInst::ModuleInfo *TinyInst::GetModuleByName(const char *name) { for (auto iter = instrumented_modules.begin(); iter != instrumented_modules.end(); iter++) { ModuleInfo *cur_module = *iter; if (_stricmp(cur_module->module_name.c_str(), name) == 0) { return cur_module; } } return NULL; } // gets module corresponding to address TinyInst::ModuleInfo *TinyInst::GetModule(size_t address) { for (auto iter = instrumented_modules.begin(); iter != instrumented_modules.end(); iter++) { ModuleInfo *cur_module = *iter; if (!cur_module->loaded) continue; if (!cur_module->instrumented) continue; if ((address >= (size_t)cur_module->min_address) && (address < (size_t)cur_module->max_address)) { if (GetRegion(cur_module, address)) { return cur_module; } } } return NULL; } // gets a memory region corresponding to address TinyInst::AddressRange *TinyInst::GetRegion(ModuleInfo *module, size_t address) { for (auto iter = module->executable_ranges.begin(); iter != module->executable_ranges.end(); iter++) { AddressRange *cur_range = &(*iter); if (((size_t)address >= cur_range->from) && ((size_t)address < cur_range->to)) { return cur_range; break; } } return NULL; } // gets module where address falls into instrumented code buffer TinyInst::ModuleInfo *TinyInst::GetModuleFromInstrumented(size_t address) { for (auto iter = instrumented_modules.begin(); iter != instrumented_modules.end(); iter++) { ModuleInfo *cur_module = *iter; if (!cur_module->loaded) continue; if (!cur_module->instrumented) continue; if ((address >= (size_t)cur_module->instrumented_code_remote) && (address < ((size_t)cur_module->instrumented_code_remote + cur_module->instrumented_code_allocated))) { return cur_module; break; } } return NULL; } void TinyInst::OnCrashed(Exception *exception_record) { char *address = (char *)exception_record->ip; printf(""Exception at address %p\\n"", address); if (exception_record->type == ACCESS_VIOLATION) { // printf(""Access type: %d\\n"", (int)exception_record->ExceptionInformation[0]); printf(""Access address: %p\\n"", exception_record->access_address); } ModuleInfo *module = GetModuleFromInstrumented((size_t)address); if (!module) return; printf(""Exception in instrumented module %s\\n"", module->module_name.c_str()); size_t offset = (size_t)address - (size_t)module->instrumented_code_remote; printf(""Code before:\\n""); size_t offset_from; if (offset < 10) offset_from = 0; else offset_from = offset - 10; for (size_t i = offset_from; i < offset; i++) { printf(""%02x "", (unsigned char)(module->instrumented_code_local[i])); } printf(""Code after:\\n""); size_t offset_to = offset + 0x10; if (offset_to > module->instrumented_code_size) offset_to = module->instrumented_code_size; for (size_t i = offset; i < offset_to; i++) { printf(""%02x "", (unsigned char)(module->instrumented_code_local[i])); } } // gets the address in the instrumented code corresponding to // address in the original module size_t TinyInst::GetTranslatedAddress(ModuleInfo *module, size_t address) { uint32_t offset = (uint32_t)(address - (size_t)module->min_address); uint32_t translated_offset; if (!GetRegion(module, address)) return address; auto iter = module->basic_blocks.find(offset); if (iter == module->basic_blocks.end()) { TranslateBasicBlockRecursive((char *)address, module); iter = module->basic_blocks.find(offset); if (iter == module->basic_blocks.end()) { FATAL(""Can't find translated basic block""); } } translated_offset = iter->second; return (size_t)module->instrumented_code_remote + translated_offset; } size_t TinyInst::GetTranslatedAddress(size_t address) { ModuleInfo *module = GetModule(address); if (!module) return address; if (!module->instrumented) return address; return GetTranslatedAddress(module, address); } // checks if address falls into one of the instrumented modules // and if so, redirects execution to the translated code bool TinyInst::TryExecuteInstrumented(char *address) { ModuleInfo *module = GetModule((size_t)address); if (!module) return false; if (!GetRegion(module, (size_t)address)) return false; if (trace_module_entries) { printf(""TRACE: Entered module %s at address %p\\n"", module->module_name.c_str(), address); } size_t translated_address = GetTranslatedAddress(module, (size_t)address); OnModuleEntered(module, (size_t)address); SetRegister(RIP, translated_address); return true; } // clears all instrumentation data from module locally // and if clear_remote_data is set, also in the remote process void TinyInst::ClearInstrumentation(ModuleInfo *module) { if (module->instrumented_code_remote) { RemoteFree(module->instrumented_code_remote, module->instrumented_code_size); module->instrumented_code_remote = NULL; } module->ClearInstrumentation(); OnModuleUninstrumented(module); ClearCrossModuleLinks(module); } void TinyInst::InstrumentModule(ModuleInfo *module) { if (instrumentation_disabled) return; // if the module was previously instrumented // just reuse the same data if (persist_instrumentation_data && module->instrumented) { ProtectCodeRanges(&module->executable_ranges); FixCrossModuleLinks(module); printf(""Module %s already instrumented, "" ""reusing instrumentation data\\n"", module->module_name.c_str()); return; } ExtractCodeRanges(module->module_header, module->min_address, module->max_address, &module->executable_ranges, &module->code_size); // allocate buffer for instrumented code module->instrumented_code_size = module->code_size * CODE_SIZE_MULTIPLIER; if ((indirect_instrumentation_mode == II_GLOBAL) || (indirect_instrumentation_mode == II_AUTO)) { module->instrumented_code_size += child_ptr_size * JUMPTABLE_SIZE; } module->instrumented_code_allocated = 0; module->instrumented_code_local = (char *)malloc(module->instrumented_code_size); if (!module->instrumented_code_local) { FATAL(""Error allocating local code buffer\\n""); } module->instrumented_code_remote = (char *)RemoteAllocateNear((uint64_t)module->min_address, (uint64_t)module->max_address, module->instrumented_code_size, READEXECUTE); if (!module->instrumented_code_remote) { // TODO also try allocating after the module FATAL(""Error allocating remote code buffer\\n""); } if ((indirect_instrumentation_mode == II_GLOBAL) || (indirect_instrumentation_mode == II_AUTO)) { InitGlobalJumptable(module); } module->instrumented = true; FixCrossModuleLinks(module); printf(""Instrumented module %s, code size: %zd\\n"", module->module_name.c_str(), module->code_size); OnModuleInstrumented(module); } // walks the list of modules and instruments // all loaded so far void TinyInst::InstrumentAllLoadedModules() { for (auto iter = instrumented_modules.begin(); iter != instrumented_modules.end(); iter++) { ModuleInfo *cur_module = *iter; if (cur_module->module_header && cur_module->max_address) { if (!cur_module->loaded) continue; InstrumentModule(cur_module); } } } // should we instrument coverage for this module TinyInst::ModuleInfo *TinyInst::IsInstrumentModule(char *module_name) { for (auto iter = instrumented_modules.begin(); iter != instrumented_modules.end(); iter++) { ModuleInfo *cur_module = *iter; if (_stricmp(module_name, cur_module->module_name.c_str()) == 0) { return cur_module; } } return NULL; } void TinyInst::OnInstrumentModuleLoaded(void *module, ModuleInfo *target_module) { if (target_module->instrumented && target_module->module_header && (target_module->module_header != (void *)module)) { WARN(""Instrumented module loaded on a different address than seen previously\\n"" ""Module will need to be re-instrumented. Expect a drop in performance.""); ClearInstrumentation(target_module); } target_module->module_header = (void *)module; GetImageSize(target_module->module_header, &target_module->min_address, &target_module->max_address); target_module->loaded = true; if (target_function_defined) { if (target_reached) InstrumentModule(target_module); } else if (child_entrypoint_reached) { InstrumentModule(target_module); } } // called when a potentialy interesting module gets loaded void TinyInst::OnModuleLoaded(void *module, char *module_name) { Debugger::OnModuleLoaded(module, module_name); ModuleInfo *instrument_module = IsInstrumentModule(module_name); if (instrument_module) { OnInstrumentModuleLoaded(module, instrument_module); } } // called when a potentialy interesting module gets loaded void TinyInst::OnModuleUnloaded(void *module) { Debugger::OnModuleUnloaded(module); for (auto iter = instrumented_modules.begin(); iter != instrumented_modules.end(); iter++) { ModuleInfo *cur_module = *iter; if (cur_module->module_header == (void *)module) { cur_module->loaded = false; if (!persist_instrumentation_data) { ClearInstrumentation(cur_module); } InvalidateCrossModuleLinks(cur_module); } } } void TinyInst::OnTargetMethodReached() { Debugger::OnTargetMethodReached(); if (target_function_defined) InstrumentAllLoadedModules(); } void TinyInst::OnEntrypoint() { Debugger::OnEntrypoint(); if(!target_function_defined) InstrumentAllLoadedModules(); } bool TinyInst::OnException(Exception *exception_record) { switch (exception_record->type) { case BREAKPOINT: if (HandleBreakpoint(exception_record->ip)) { return true; } case ACCESS_VIOLATION: if (exception_record->maybe_execute_violation) { // possibly we are trying to executed code in an instrumented module if (TryExecuteInstrumented((char *)exception_record->access_address)) { return true; } } default: break; } return false; } void TinyInst::OnProcessCreated() { Debugger::OnProcessCreated(); if (child_ptr_size == 8) { xed_mmode = XED_MACHINE_MODE_LONG_64; } else { xed_mmode = XED_MACHINE_MODE_LEGACY_32; } } void TinyInst::OnProcessExit() { Debugger::OnProcessExit(); // clear all instrumentation data for (auto iter = instrumented_modules.begin(); iter != instrumented_modules.end(); iter++) { ModuleInfo *cur_module = *iter; cur_module->loaded = false; cur_module->ClearInstrumentation(); } // clear cross-module links ClearCrossModuleLinks(); } // initializes instrumentation from command line options void TinyInst::Init(int argc, char **argv) { // init the debugger first Debugger::Init(argc, argv); instrumentation_disabled = false; patch_return_addresses = GetBinaryOption(""-patch_return_addresses"", argc, argv, false); instrument_cross_module_calls = GetBinaryOption(""-instrument_cross_module_calls"", argc, argv, true); persist_instrumentation_data = GetBinaryOption(""-persist_instrumentation_data"", argc, argv, true); trace_basic_blocks = GetBinaryOption(""-trace_basic_blocks"", argc, argv, false); trace_module_entries = GetBinaryOption(""-trace_module_entries"", argc, argv, false); sp_offset = GetIntOption(""-stack_offset"", argc, argv, 0); xed_tables_init(); list module_names; GetOptionAll(""-instrument_module"", argc, argv, &module_names); for (auto iter = module_names.begin(); iter != module_names.end(); iter++) { ModuleInfo *new_module = new ModuleInfo(); new_module->module_name = *iter; instrumented_modules.push_back(new_module); } char *option; indirect_instrumentation_mode = II_AUTO; option = GetOption(""-indirect_instrumentation"", argc, argv); if (option) { if (strcmp(option, ""none"") == 0) indirect_instrumentation_mode = II_NONE; else if (strcmp(option, ""local"") == 0) indirect_instrumentation_mode = II_LOCAL; else if (strcmp(option, ""global"") == 0) indirect_instrumentation_mode = II_GLOBAL; else if (strcmp(option, ""auto"") == 0) indirect_instrumentation_mode = II_AUTO; else FATAL(""Unknown indirect instrumentation mode""); } } ",16196,True,2845.5080904345186,median "// Licensed to the Apache Software Foundation (ASF) under one // 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. // = Integration Testing Framework Users Guide Karl Heinz Marbaise; {docdate} :author: Karl Heinz Marbaise :sectnums: :sectlinks: :xrefstyle: full :toc: left // :junit-jupiter: https://junit.org/junit5/[JUnit Jupiter] :junit-jupiter-extension: https://junit.org/junit5/docs/current/user-guide/#extensions :junit-jupiter-user-guide: https://junit.org/junit5/docs/current/user-guide/[JUnit Jupiter User Guide] :junit-jupiter-user-guide-conditional-jre: https://junit.org/junit5/docs/current/user-guide/#writing-tests-conditional-execution-jre :maven-invoker-plugin: https://maven.apache.org/plugins/maven-invoker-plugin[Maven Invoker Plugin] :maven-plugins: https://maven.apache.org/plugins/[Maven Plugins] :maven-failsafe-plugin: https://maven.apache.org/surefire/maven-failsafe-plugin/[Maven Failsafe Plugin] :mock-repository-manager: https://www.mojohaus.org/mrm/index.html[Mock Repository Manager] :backgorund-guide: https://khmarbaise.github.io/maven-it-extension/itf-documentation/background/background.html :itf-issues: https://github.com/khmarbaise/maven-it-extension/issues :assertj: https://assertj.github.io/doc/ // :itfexample: _basedir/../.. == Overview The documentation intends to give a comprehensive reference for programmers writing integration tests for Maven Plugins / Maven Core Extensions / Maven Core. === What is Integration Testing Framework? The Integration Testing Framework (ITF for short) is in its foundation a {junit-jupiter-extension}[JUnit Jupiter Extension], which supports you in writing integration tests for Maven Plugins etc. There are several aspects, that makes writing integration tests for Maven Plugins at the {backgorund-guide}[moment harder than it should be]. This is the reason, why this framework exists. === Status The current status of this extension is experimental while some people call it Proof of Concept (PoC). This framework has not yet reached version `1.0.0` which means that anything can change, but I try to keep compatibility as much as possible. I will only break it if really needed. In such cases it will be documented in the release notes. I strongly recommend reading the release notes. == About this Guide This guide represents the current state of development and things, which work (or more accurate: **should work**). If you find things which do not work as described here or even don't work at all, please don't hesitate to {itf-issues}[create an appropriate issue] and describe what does not work or does not work at all as described or maybe does not work as you might expect it to work. WARNING: This guide is of course not a guarantee that it works, cause the project is in a very early stage. == Overview The idea of integration tests for Maven Plugins, Maven Extensions, Maven Core is to keep the functionality the way it has been defined independent of refactoring code or improving functionality. This maven integration test framework is an extension for {junit-jupiter}. The usage of JUnit Jupiter already gives a lot of support for things, which are very useful while writing unit- and integration tests. The idea of testing is to express the requirements in code. Those are in other words the tests, which should be written. If you are not familiar with JUnit Jupiter, I strongly recommend reading the {junit-jupiter-user-guide} first. The significance of tests is a very important part of writing integration tests or test in general. If a test is not easy to understand, it is very likely not being written. Let us take a look into the following test code example which gives you an impression, how an integration test for a {maven-plugins}/Maven Extensions/Maven-Core should look like: [source,java] ---- package org.it; import static org.assertj.core.api.Assertions.assertThat; import com.soebes.itf.jupiter.extension.MavenJupiterExtension; import com.soebes.itf.jupiter.extension.MavenTest; import com.soebes.itf.jupiter.maven.MavenExecutionResult; @MavenJupiterExtension // <1> class FirstMavenIT { @MavenTest // <2> void the_first_test_case(MavenExecutionResult result) { // <3> assertThat(result).build().isSuccessful(); // <4> } } ---- <1> The Maven Integration test annotation <2> The Maven Test annotation. <3> The result of the execution injected into the test method (details in Chapter link:[Needs to be written]) <4> The above used assertions like `assertThat(..)` are custom assertions which will be explained in link:#_assertions[Assertions chapter]. //FIXME: link to chapter for assertions. <<< == Configuration in Maven === User's Point of View You are a user who want to use the integration test framework to write integration tests for a plugin etc. This area shows how to configure the integration test framework in your Maven build and what kind of requirements exist. The prerequisites to use this integration test framework is, that you are running JDK8 at minimum for your tests. This is based on using {junit-jupiter-extension}[JUnit Jupiter Extension] and of course on the implemented code of this extension. The requirements are: * JDK8+ * Apache Maven 3.1.0 or above. The first step is to add the appropriate dependencies to your project. They are usually with `test` scope, cause you only need them during the integration tests. [source,xml] ---- include::{itfexample}/itf-examples/pom.xml[tag=dependencies] ---- The dependency `com.soebes.itf.jupiter.extension:itf-assertj` contains custom assertions of {assertj}[AssertJ] in case you want to use {assertj}[AssertJ] as your assertion framework. This means you have to include `org.assertj:assertj-core` as well. If you don't want to use AssertJ as assertion framework you can omit them both. Now you have to have the dependency `org.junit.jupiter:junit-jupiter-engine` to get tests running with {junit-jupiter} and finally you have to add the `com.soebes.itf.jupiter.extension:itf-jupiter-extension` dependency to get the support for your Maven integration tests. //TODO: Need to reconsider? More details? Or a separate paragraph about that. Based on the described structures the content (with the projects which is used as test) from `src/test/resources-its` has to be copied into `target/test-classes` which usually means including filtering. This is used to replace placeholders in files like `@project.version@` and replace with the real version of your extension/plugin etc. You have to be careful, which delimiter you have chosen. So you might need to tweak your configuration based on your choices. [source,xml] ---- include::{itfexample}/itf-examples/pom.xml[tag=resources] ---- The next thing is to configure the `itf-maven-plugin` with the `install` goal like this: [source,xml] ---- include::{itfexample}/itf-examples/pom.xml[tag=itf-maven-plugin] ---- //FIXME: Needed to be changed after itf-maven-plugin will run also the tests. The `itf-maven-plugin` copies the code of your extension/plugin into appropriate directories which are used during the integration tests. Finally you have to add a configuration for {maven-failsafe-plugin} like the following: [source,xml] ---- include::{itfexample}/itf-examples/pom.xml[tag=failsafe] ---- The given properties like `maven.version` transfers the version of Maven which is used within the `itf-jupiter-extension` to run your integration tests and the `maven.home` transfers the information of where to find the current Maven installation. This is needed to start the Maven process from within the integration tests. //TODO: Check if we can omit maven.home cause we are searching already via PATH? The usage of {maven-failsafe-plugin} implies the naming convention for the integration tests like `*IT.java` but of course you can change that by using the appropriate configuration if you like or need to. The above described configuration will make it possible to run all tests via command line by using `mvn clean verify`. IMPORTANT: It is also possible to run the integration tests from your IDE. This only works if you have done the `mvn clean verify` once before on command line. Then you can run the integration tests from your IDE as long as you don't change the code of the plugin/extension etc. which is under test. You can change the tests without any limitation (If you find any please create an issue for that.) NOTE: The whole given configuration which comprises of `itf-maven-plugin` and the configuration for `maven-failsafe-plugin` should be replaced by separate maven plugin later to make the usage more convenient. === Developer's Point of View You are a potential contributor or just interested in how the code of this extension is working/looks like or you are a user who wants to test with the bleeding edge of this extension. The requirements for building this extensions are: * JDK8+ (need to reconsider) * https://maven.apache.org/[Apache Maven 3.6.0+] You have to clone the git repository and you can build the extension simply via: `mvn clean install`. The `install` is needed to install the created artifacts into your local repository for reuse. <<< == Structuring Integration Tests === A Single Test Case The location of an integration test defaults to `src/test/java//FirstMavenIT.java`. The selected naming schema like `IT.java` implies that it will be executed by the {maven-failsafe-plugin} by convention. This will lead us to a directory structure as follows: [source] ---- . └── src/ └── test/ └── java/ └── org/ └── it/ └── FirstMavenIT.java ---- In case of an integration test for a Maven plugin/extension or others, we need to be able to define also the projects which are the *real test cases* (Maven projects). This needs to be put somewhere in the directory tree to be easily associated with the given test `FirstMavenIT`. The project to be used as a test case implies to be located into `src/test/resources-its//FirstMavenIT`, this looks like this: //TODO: should we keep the location `resources-its` ? [source,text] ---- . └── src/ └── test/ └── resources-its/ └── org/ └── it/ └── FirstMavenIT/ ---- Currently this location is separated from all other resources directories to make filtering easier, what has to be configured within your `pom.xml` file and preventing interfering with other configurations. We have an integration test class for example `FirstMavenIT` but what if we like to write several test cases? So we need to make separation between different *test cases* which can be achieved by using the *method name* within the test class `FirstMavenIT` which is `the_first_test_case` in our example. This results in the following directory layout: [source,text] ---- . └── src/ └── test/ └── resources-its/ └── org/ └── it/ └── FirstMavenIT/ └── the_first_test_case/ ├── src/ └── pom.xml ---- This approach gives us the opportunity to write several integration test cases within a single test class `FirstMavenIT` and also separates them easily. The usage of the *method name* implies some limitations based on the naming rules for *method names*. The best practice is to write *method names* with lowercase letters and separate words by using an underscore `_`. This will prevent issues with case insensitive file systems. === Test Case Execution During the execution of the integration tests the following directory structure will be created within the `target` directory: [source,text] ---- . └──target/ └── maven-it/ └── org/ └── it/ └── FirstMavenIT/ └── the_first_test_case/ ├── .m2/ ├── project/ │ ├── src/ │ ├── target/ │ └── pom.xml ├── mvn-stdout.log ├── mvn-stderr.log ├── mvn-arguments.log └── orther logs. ---- Based on the above you can see that each *test case* (method within the test class `FirstMavenIT`) has its own local repository (aka local cache) `.m2/repository`. Furthermore you see that the project is being built within the `project` directory. This gives you a view of the built project as you did on plain command line and take a look into it. The output of the build has been written into `mvn-stdout.log`(stdout) and the output to stderr is written to `mvn-stderr.log`. The used command line parameters to call Maven are wrote into `mvn-arguments.log`. //TODO: Define `other logs` ? environment output, command line parameters ? //FIXME: Needs to be implemented === Several Test Cases If we like to define several integration test cases within a single test class `SeveralMavenIT` we have to define different methods, which are the test cases. This results in the following class layout: [source,java] ---- package org.it; import static org.assertj.core.api.Assertions.assertThat; import com.soebes.itf.jupiter.extension.MavenJupiterExtension; import com.soebes.itf.jupiter.extension.MavenTest; import com.soebes.itf.jupiter.maven.MavenExecutionResult; @MavenJupiterExtension class SeveralMavenIT { @MavenTest void the_first_test_case(MavenExecutionResult result) { ... } @MavenTest void the_second_test_case(MavenExecutionResult result) { ... } @MavenTest void the_third_test_case(MavenExecutionResult result) { ... } } ---- The structure for the Maven projects, which is used by each of the test cases (*method names*) looks like the following: [source,text] ---- . └── src/ └── test/ └── resources-its/ └── org/ └── it/ └── SeveralMavenIT/ ├── the_first_test_case/ │ ├── src/ │ └── pom.xml ├── the_second_test_case/ │ ├── src/ │ └── pom.xml └── the_this_test_case/ ├── src/ └── pom.xml ---- After running the integration tests the resulting directory structure in the `target` directory will look like this: [source,text] ---- . └──target/ └── maven-it/ └── org/ └── it/ └── SeveralMavenIT/ ├── the_first_test_case/ │ ├── .m2/ │ ├── project/ │ │ ├── src/ │ │ ├── target/ │ │ └── pom.xml │ ├── mvn-stdout.log │ ├── mvn-stderr.log │ └── other logs ├── the_second_test_case/ │ ├── .m2/ │ ├── project/ │ │ ├── src/ │ │ ├── target/ │ │ └── pom.xml │ ├── mvn-stdout.log │ ├── mvn-stderr.log │ └── other logs └── the_third_test_case/ ├── .m2/ ├── project/ │ ├── src/ │ ├── target/ │ └── pom.xml ├── mvn-stdout.log ├── mvn-stderr.log └── mvn-arguments.log ---- Based on the structure you can exactly dive into each test case separately and take a look at the console output of the test case via `mvn-stdout.log` or maybe in case of errors in the `mvn-stderr.log`. In the `project` directory you will find the usual `target` directory, which contains the Maven output which might be interesting as well. Furthermore the local cache (aka maven repository) is available separately for each test case and can be found in the `.m2/repository` directory. <<< == Goals, Profiles, Properties and Command Line Options === Goals In each test case method you define `@MavenTest` which says execute Maven with the given default goals and parameters. A typical integration test looks like this: [source,java] .BasicIT.java ---- @MavenJupiterExtension class BasicIT { @MavenTest void first(MavenExecutionResult result) { } } ---- So now the question is: Which goals and parameters will be used to execute Maven for the `first` test case? Very brief the default set of goals which will be executed if not defined otherwise is `package` (See xref:_default_goalsoptions[for a more detailed explanation]). That means if we keep the test as in our example maven would be called like `mvn package`. From a technical perspective some other parameters have been added which are `mvn -Dmaven.repo.local=Path package`. The `-Dmaven.repo.local=..` is needed to make sure that each call uses the defined local cache (See xref:_common_maven_cache[Common Maven Cache]). You can of course change the default for the goal, if you like by simply add the `@MavenGoal` annotation `@MavenGoal(""install"")` that would mean to execute all subjacent tests like `mvn -D.. install` instead of `mvn -D .. package`. A usual command parameter set includes `--batch-mode` and `-V` (See xref:_default_goalsoptions[for a more detailed explanation]). How could you write a test which uses a plugin goal instead? You can simply define the goal(s) via the `@MavenGoal` annotation like this: [source,java] ---- @MavenGoal(""${project.groupId}:${project.artifactId}:${project.version}:compare-dependencies"") @MavenTest ---- The used `@MavenGoal` will overwrite any goal which is predefined. The given goals in `@MavenGoal` support replacement of placeholders which currently supports the following: * ${project.groupId} * ${project.artifactId} * ${project.version} Those are the ones which are used in the majority of cases for Maven plugins. If you like to call several goals and/or lifecycle parts in one go you can simply define it like this: [source,java] ---- @MavenGoal(""${project.groupId}:${project.artifactId}:${project.version}:compare-dependencies"") @MavenGoal(""site:stage"") @MavenGoal(""install"") @MavenTest void test_case(MavenExecutionResult result) { .. } ---- The equivalent on command line would be: [source,bash] ---- mvn ${project.groupId}:${project.artifactId}:${project.version}:compare-dependencies site:stage install ---- === Profiles In some cases you need to activate one or https://maven.apache.org/guides/introduction/introduction-to-profiles.html[more Maven profiles] for test purposes etc. This can be achieved by using `@MavenProfile` which looks like this: [source,java] ---- @MavenJupiterExtension class BasicIT { @MavenTest @MavenProfile(""run-its"") void first(MavenExecutionResult result) { } ---- If you like to activate multiple Maven profiles you can simply repeat the annotation like this: [source,java] ---- @MavenJupiterExtension class BasicIT { @MavenTest @MavenProfile(""run-its"") @MavenProfile(""run-e2e"") void first(MavenExecutionResult result) { } ---- An alternative is to use the array like definition like this: [source,java] ---- @MavenJupiterExtension class BasicIT { @MavenTest @MavenProfile({""run-its"",""run-e2e""}) void first(MavenExecutionResult result) { } ---- The profiles can also be activated for a bunch of test cases that you don't need to add the annotation on each test case. So you can define the Maven profile on the class level instead. [source,java] ---- @MavenJupiterExtension @MavenProfile({""run-its"",""run-e2e""}) class BasicIT { @MavenTest void first(MavenExecutionResult result) { } ---- If you want to explicitly deactivate a profile this can be achieved like this: [source,java] ---- @MavenJupiterExtension class BasicIT { @MavenTest @MavenProfile(""+run-its"") void first(MavenExecutionResult result) { } ---- The `+` prefix is responsible for deactivating a given profile during the build. We strongly recommend to use `+` sign (instead of `!`) to prevent issues on different operating systems. === System Properties There are situations where you need to use system properties which are usually defined on command like this: [source,bash] ---- mvn versions:set -DgenerateBackups=false -DnewVersion=2.0 ---- This can be achieved by using the `@SystemProperty` annotation which could look like this: [source,java] .CompareDependenciesIT.java ---- package org.codehaus.mojo.versions.it; import com.soebes.itf.jupiter.extension.MavenJupiterExtension; import com.soebes.itf.jupiter.extension.MavenTest; import com.soebes.itf.jupiter.maven.MavenExecutionResult; import com.soebes.itf.jupiter.maven.MavenProjectResult; import com.soebes.itf.extension.assertj.MavenITAssertions.assertThat; @MavenJupiterExtension class CompareDependenciesIT { @MavenGoal(""versions:set"") @SystemProperty(value = ""generateBackups"", content = ""false"") @SystemProperty(value = ""newVersion"", content = ""2.0"") @MavenTest void it_compare_dependencies_001( MavenExecutionResult result ) { ... } } ---- Other options are to set only the value for example if you like to do this: [source,bash] ---- mvn clean verify -DskipTests ---- You can do it the like the following: [source,java] .CompareDependenciesIT.java ---- package org.codehaus.mojo.versions.it; import com.soebes.itf.jupiter.extension.MavenJupiterExtension; import com.soebes.itf.jupiter.extension.MavenTest; import com.soebes.itf.jupiter.maven.MavenExecutionResult; import com.soebes.itf.jupiter.maven.MavenProjectResult; import com.soebes.itf.extension.assertj.MavenITAssertions.assertThat; @MavenJupiterExtension class RunningIT { @MavenGoal(""clean"") @MavenGoal(""verify"") @SystemProperty(""skipTests"") @MavenTest void running( MavenExecutionResult result ) { ... } } ---- === Command Line Options In different scenarios it is needed to define command line options for example `--non-recursive` etc. This can be done by using the `@MavenOption` annotation. There is a convenience class `MavenCLIOptions` available, which contains all existing command line options. You are not forced to use the `MavenCLIOptions` class. [source,java] ---- @MavenGoal(""versions:set"") @SystemProperty(value = ""newVersion"", content = ""2.0"") @MavenOption(MavenCLIOptions.NON_RECURSIVE) @MavenOption(""--offline"") @MavenTest void first( MavenExecutionResult result ) { assertThat( result ).isSuccessful(); } ---- This gives you the choice to decide to use `MavenCLIOptions` or not: [source,java] ---- @MavenGoal(""versions:set"") @SystemProperty(value = ""newVersion"", content = ""2.0"") @MavenOption({""-N"",""--offline""}) @MavenTest void first( MavenExecutionResult result ) { assertThat( result ).isSuccessful(); } ---- === Default Goals,Options ==== Goals Basically to run a usual integration test it needs to be defined by which goals and options such test has to run. Let us take a look at a simple example: [source,java] ---- @MavenJupiterExtension class BasicIT { @MavenTest void first(MavenExecutionResult result) { } } ---- The execution of the test will run with the goal `package` which is defined by default if not defined otherwise. There are defined some useful default command line options like `--errors`, `-V` and `--batch-mode` also by default if not defined otherwise. So let us take a look what otherwise means. You can replace the default goal `package` by simply defining a different goal on your test class like this (you can also put that annotation on the method as well): [source,java] ---- @MavenJupiterExtension @MavenGoal(""verify"") class BasicIT { @MavenTest void first(MavenExecutionResult result) { } } ---- This means all consecutive tests will run with the goal `verify` instead of `package`. It is also possible to define several goals like this: [source,java] ---- @MavenJupiterExtension @MavenGoal(""clean"") @MavenGoal(""verify"") class BasicIT { @MavenTest void first(MavenExecutionResult result) { } } ---- If you don't like to repeat that on each test class you can define a meta annotation like this: [source,java] ---- @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RUNTIME) @Inherited @MavenGoal({""clean"", ""verify""}) public @interface GoalsCleanVerify { } ---- This meta annotation can now be used instead. This makes it easy to change the goal for all of your tests from a single location. [source,java] ---- @MavenJupiterExtension @GoalsCleanVerify class BasicIT { @MavenTest void first(MavenExecutionResult result) { } } ---- Now let us summarize the information for goals. As long as no explicit `@MavenGoal` is defined the default will be used which is `package`. ==== Options Now let us going back to the example: [source,java] ---- @MavenJupiterExtension class BasicIT { @MavenTest void first(MavenExecutionResult result) { } } ---- This example will run the test with the following command line options: * `-V` * `--batch-mode` * `--errors` So if you like to change the command line options which are used to run an integration test you can simply define different options via the appropriate annotations: [source,java] ---- @MavenJupiterExtension @MavenOption(MavenCLIOptions.DEBUG) class BasicIT { @MavenTest void first(MavenExecutionResult result) { } } ---- Using the option like this means (like for goals as mentioned before) all consecutive tests will now run with the given option which in this case is only a single command line option `--debug` and nothing else. You can add supplemental command line options just by adding supplemental annotations to your tests like this: [source,java] ---- @MavenJupiterExtension @MavenOption(MavenCLIOptions.ERRORS) @MavenOption(MavenCLIOptions.DEBUG) class BasicIT { @MavenTest void first(MavenExecutionResult result) { } } ---- The MavenOption annotation can also be used to create a meta annotation like this: [source,java] ---- @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RUNTIME) @Inherited @MavenOption(MavenCLIOptions.DEBUG) @MavenOption(MavenCLIOptions.ERRORS) @MavenOption(MavenCLIOptions.FAIL_AT_END) public @interface OptionDebugErrorFailAtEnd { } ---- The newly defined meta annotation can simply being used like this: [source,java] ---- @MavenJupiterExtension @OptionDebugErrorFailAtEnd class BasicIT { @MavenTest void first(MavenExecutionResult result) { } } ---- Now let us summarize the information for options. As long as no explicit `@MavenOption` is defined the default will be used which are the following: * `-V` * `--batch-mode` * `--errors` ==== Combined Annotation Sometimes you would like to combine things from options and goals in a more convenient way. That is possible by using a custom annotation like this one: [source,java] ---- @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RUNTIME) @Inherited @MavenJupiterExtension @MavenOption(MavenCLIOptions.DEBUG) @MavenOption(MavenCLIOptions.ERRORS) @MavenOption(MavenCLIOptions.FAIL_AT_END) @MavenGoal(""clean"") @MavenGoal(""verify"") public @interface MavenJupiterExtensionWithDefaults { } ---- The given annotation include the usage of `@MavenJupiterExtension` which handles the loading of the extension part. By using the above defined annotation your test could look like this: [source,java] ---- @MavenJupiterExtensionWithDefaults class BasicIT { @MavenTest void first(MavenExecutionResult result) { } } ---- So this makes it very easy to define your own default set of goals, options or maybe more. You can of course add properties etc. if you need. <<< == Scenarios === Grouping Test Cases Sometimes it makes sense to group test into different groups together. This can be achieved via the `@Nested` annotation which is provided by {junit-jupiter}. This would result in a test class like this: [source,java] .MavenIntegrationGroupingIT.java ---- @MavenJupiterExtension class MavenIntegrationGroupingIT { @MavenTest void packaging_includes(MavenExecutionResult result) { } @Nested class NestedExample { @MavenTest void basic(MavenExecutionResult result) { } @MavenTest void packaging_includes(MavenExecutionResult result) { } } } ---- After test execution the resulting directory tree looks like this: [source,text] ---- . └──target/ └── maven-it/ └── org/ └── it/ └── MavenIntegrationGroupingIT/ ├── packaging_includes/ │ ├── .m2/ │ ├── project/ │ │ ├── src/ │ │ ├── target/ │ │ └── pom.xml │ ├── mvn-stdout.log │ ├── mvn-stderr.log │ └── other logs └── NestedExample/ ├── basic/ │ ├── .m2/ │ ├── project/ │ │ ├── src/ │ │ ├── target/ │ │ └── pom.xml │ ├── mvn-stdout.log │ ├── mvn-stderr.log │ └── other logs └── packaging_includes/ ├── .m2/ ├── project/ │ ├── src/ │ ├── target/ │ └── pom.xml ├── mvn-stdout.log ├── mvn-stderr.log └── other logs ---- === Common Maven Cache In all previous test case examples the maven cache (aka maven repository) is created separately for each of the test cases (*test methods*). There are times, where you need to have a common cache (aka maven repository) for two or more test cases. This can be achieved easily via the `@MavenRepository` annotation.footnote:[Based on the usage of this annotation the parallelizing is automatically deactivated, cause Maven has never been designed to make a parallel access to the maven cache possible.] The usage looks like the following: [source,java] .MavenIntegrationExampleNestedGlobalRepoIT.java ---- package org.it; import com.soebes.itf.jupiter.extension.MavenJupiterExtension; import com.soebes.itf.jupiter.extension.MavenRepository; import com.soebes.itf.jupiter.extension.MavenTest; import com.soebes.itf.jupiter.maven.MavenExecutionResult; @MavenJupiterExtension @MavenRepository class MavenITWithGlobalMavenCacheIT { @MavenTest void packaging_includes(MavenExecutionResult result) { } @MavenTest void basic(MavenExecutionResult result) { } } ---- After test execution the resulting directory tree looks like this: [source,text] ---- . └──target/ └── maven-it/ └── org/ └── it/ └── MavenITWithGlobalMavenCacheIT/ ├── .m2/ ├── packaging_includes/ │ ├── project/ │ │ ├── src/ │ │ ├── target/ │ │ └── pom.xml │ ├── mvn-stdout.log │ ├── mvn-stderr.log │ └── other logs └── basic/ ├── project/ │ ├── src/ │ ├── target/ │ └── pom.xml ├── mvn-stdout.log ├── mvn-stderr.log └── other logs ---- There you see that the `.m2/` directory (maven local cache) is directly located under the `MavenITWithGlobalMavenCacheIT` directory which is the equivalent of the `MavenITWithGlobalMavenCacheIT` class. The usage of `@MavenRepository` is also possible in combination with `@Nested` annotation which, will look like this: [source,java] .MavenIntegrationGroupingIT.java ---- @MavenJupiterExtension class MavenIntegrationGroupingIT { @MavenTest void packaging_includes(MavenExecutionResult result) { } @Nested @MavenRepository class NestedExample { @MavenTest void basic(MavenExecutionResult result) { } @MavenTest void packaging_excludes(MavenExecutionResult result) { } } } ---- That would result in having a common cache for the methods `basic` and `packaging_includes` within the nested class `NestedExample`. The test method `packaging_includes` will have a cache on its own. The directory tree looks like this: [source,text] ---- . └──target/ └── maven-it/ └── org/ └── it/ └── MavenIntegrationGroupingIT/ ├── packaging_includes/ │ ├── .m2/ │ ├── project/ │ │ ├── src/ │ │ ├── target/ │ │ └── pom.xml │ ├── mvn-stdout.log │ ├── mvn-stderr.log │ └── other logs └── NestedExample/ ├── .m2/ ├── basic/ │ ├── project/ │ │ ├── src/ │ │ ├── target/ │ │ └── pom.xml │ ├── mvn-stdout.log │ ├── mvn-stderr.log │ └── other logs └── packaging_excludes/ ├── project/ │ ├── src/ │ ├── target/ │ └── pom.xml ├── mvn-stdout.log ├── mvn-stderr.log └── other logs ---- === Predefined Repository Content for Tests There are existing test cases in which you need predefined dependencies, cause you can't rely on existing dependencies in the central repository or anywhere else. You have the option to define a repository either per testcase or per test class where you can put existing dependencies for your test cases. Those dependencies are behaving like you have installed them in your local repository via `mvn install:install-file`. In your test code the setup looks like the following. The important part is the definition of the `@MavenPredefinedRepository` which indicates that the predefined repository in the appropriate location needs to exist. This means that those dependencies from this directory are available for each test case (`project_001` and `proeject_002`) in this test class. [source,java] .ProjectIT.java ---- @MavenJupiterExtension @MavenPredefinedRepository class ProjectIT { @MavenOption(MavenCLIOptions.DEBUG) @MavenTest void project_001(MavenExecutionResult result) { assertThat(result).isSuccessful(); } @MavenOption(MavenCLIOptions.DEBUG) @MavenTest void project_002(MavenExecutionResult result) { assertThat(result).isSuccessful(); } } ---- In your test project definition you need to create the appropriate directory structure including the needed contents, which looks like this: [source,text] ---- . └── src/ └── test/ └── resources-its/ └── org/ └── it/ └── ProjectIT/ ├── .predefined-repo │ ├── ... │ └── ... └── project_001/ │ ├── src/ │ └── pom.xml └── project_002/ ├── src/ └── pom.xml ---- In the `.predefined-repo` you have to follow a usual maven repository structure. You can of course define the `@MavenPredefinedRepository` also on the test method level, which would look like this: [source,java] .ProjectLevelIT.java ---- @MavenJupiterExtension class ProjectIT { @MavenOption(MavenCLIOptions.DEBUG) @MavenTest @MavenPredefinedRepository void project_001(MavenExecutionResult result) { assertThat(result).isSuccessful(); } @MavenOption(MavenCLIOptions.DEBUG) @MavenTest @MavenPredefinedRepository void project_002(MavenExecutionResult result) { assertThat(result).isSuccessful(); } } ---- The setup directories look like this: [source,text] ---- . └── src/ └── test/ └── resources-its/ └── org/ └── it/ └── ProjectIT/ └── project_001/ │ ├── .predefined-repo │ ├── src/ │ └── pom.xml └── project_002/ ├── .predefined-repo ├── src/ └── pom.xml ---- === Single Project With Several Executions Sometimes you need to execute a consecutive number of commands (usually maven executions) on the same single project. This means having a single project and executing several maven execution on that project in the end. Such a use case looks like this: [source,java] .SetIT.java ---- @MavenJupiterExtension class SetIT { private static final String VERSIONS_PLUGIN_SET = ""${project.groupId}:${project.artifactId}:${project.version}:set""; @Nested @MavenProject @TestMethodOrder( OrderAnnotation.class ) @MavenOption(MavenCLIOptions.NON_RECURSIVE) @MavenGoal(VERSIONS_PLUGIN_SET) class set_001 { @SystemProperty(value = ""newVersion"", content=""2.0"") @MavenTest @Order(10) void first( MavenExecutionResult result ) { assertThat( result ).isSuccessful(); } @SystemProperty(value = ""newVersion"", content=""2.0"") @SystemProperty(value = ""groupId"", content=""*"") @SystemProperty(value = ""artifactId"", content=""*"") @SystemProperty(value = ""oldVersion"", content=""*"") @MavenTest @Order(20) void second( MavenExecutionResult result) { assertThat( result ).isSuccessful(); } } } ---- The important part here is the `@MavenProject` annotation which marks the nested class as a container which contains executions (`first` and `second`) with conditions on the same single project. The `@MavenProject` defines that project name which is by default `maven_project`. This means, you have to define the project you would like to test on like this: [source,text] ---- . └── src/ └── test/ └── resources-its/ └── org/ └── it/ └── SetIT/ └── set_001/ └── maven_project/ ├── src/ └── pom.xml ---- After test execution it looks like this: [source,text] ---- . └──target/ └── maven-it/ └── org/ └── it/ └── SetIT/ └── set_001/ └── maven_project/ ├── .m2/ ├── project/ │ ├── src/ │ ├── target/ │ └── pom.xml ├── first-mvn-arguments.log ├── first-mvn-stdout.log ├── first-mvn-stderr.log ├── second-mvn-arguments.log ├── second-mvn-stdout.log └── second-mvn-stderr.log ---- Each test case defined by the method name `first` and `second` has been executed on the same project `maven_project`. Each execution has its own sets of log files which can be identified by the prefix based on the method name like `first-mvn-arguments.log` etc. The `@MavenProject` annotation can only be used on a nested class or on the test class itself (where `MavenJupiterExtension` is located.). If you like to change the name of the project `maven_project` into something different this can be achieved by using `@MavenProject(""another_project_name"")`. <<< == Test Case Execution === Conditionally Executing Tests You might want to run an integration test only for a particular Maven version for example running only for Maven 3.6.0? So how could you express this? The following code will show how you can do that. [source,java] .ForthMavenIT.java ---- import static com.soebes.itf.extension.assertj.MavenCacheResultAssert.assertThat; import static com.soebes.itf.jupiter.maven.MavenVersion.M3_0_5; import static com.soebes.itf.jupiter.maven.MavenVersion.M3_6_0; import com.soebes.itf.jupiter.extension.DisabledForMavenVersion; import com.soebes.itf.jupiter.extension.EnabledForMavenVersion; import com.soebes.itf.jupiter.extension.MavenJupiterExtension; import com.soebes.itf.jupiter.extension.MavenTest; import com.soebes.itf.jupiter.maven.MavenExecutionResult; @MavenJupiterExtension class FirstMavenIT { @MavenTest @EnabledForMavenVersion(M3_6_0) void first_test_case(MavenExecutionResult execResult) { assertThat(execResult).isSuccessful(); } @DisabledForMavenVersion(M3_0_5) @MavenTest void second_test_case(MavenExecutionResult execResult) { assertThat(execResult).isFailure(); } } ---- If you like to disable some tests on a particular Java version, this can be handled via {junit-jupiter-user-guide-conditional-jre}[conditions like this]. //TODO: Make reference to JUnit Jupiter Manual [source,java] ---- import static com.soebes.itf.extension.assertj.MavenITAssertions.assertThat; import static com.soebes.itf.jupiter.maven.MavenVersion.M3_0_5; import static com.soebes.itf.jupiter.maven.MavenVersion.M3_6_0; import com.soebes.itf.jupiter.extension.DisabledForMavenVersion; import com.soebes.itf.jupiter.extension.EnabledForMavenVersion; import com.soebes.itf.jupiter.extension.MavenJupiterExtension; import com.soebes.itf.jupiter.extension.MavenTest; import com.soebes.itf.jupiter.maven.MavenExecutionResult; import org.junit.jupiter.api.condition.DisabledOnJre; import org.junit.jupiter.api.condition.JRE; @MavenJupiterExtension @DisabledOnJre(JRE.JAVA_10) class FirstMavenIT { @MavenTest @EnabledForMavenVersion(M3_6_0) void first_test_case(MavenExecutionResult execResult) { assertThat(execResult).isSuccessful(); } @DisabledForMavenVersion(M3_0_5) @MavenTest void second_test_case(MavenExecutionResult execResult) { assertThat(execResult).isFailure(); } } ---- <<< [#_assertions] == Assertions === Overview Let us take a look into a simple integration test. We would like to concentrate on the assertion part. [source,java] ---- @MavenJupiterExtension class FirstIT { @MavenTest void the_first_test_case(MavenExecutionResult result) { assertThat(result).isSuccessful(); } } ---- After the test has run the resulting directory structure looks like this: [source,text] ---- . └──target/ └── maven-its/ └── org/ └── it/ └── FirstIT/ └── the_first_test_case/ ├── .m2/ ├── project/ │ ├── src/ │ ├── target/ │ └── pom.xml ├── mvn-stdout.log ├── mvn-stderr.log └── other logs ---- In each integration test you should let inject `MavenExecutionResult result` as a parameter of your test case method, cause that gives you the opportunity to write assertion on the result of the maven execution or what has been written into the resulting structure. Let us start with two general assertions: * `assertThat(result).isSuccessful();` The build was successful (return code of Maven run 0). * `assertThat(result).isFailure();` The build has failed (return code of Maven run != 0). Sometimes this is sufficient, but more often you have more complex scenarios to be checked. Based on the directory structure in the result you can make assumptions about the names which can be used in your assertions like the following: //Check issue-25 * `assertThat(result).project()....` which will go into the `project` directory * `assertThat(result).cache()...` will go into the `.m2/repository` directory. // FIXME: https://github.com/khmarbaise/maven-it-extension/issues/26 // FIXME: * Reconsider how it should look like: result).log().stdout() or alike? // FIXME: * `assertThat(result).stdout()..' will result into the access of the `mvn-stdout.log` file. // FIXME: * `assertThat(result).stderr()..' will result into the access of the `mvn-stderr.log` file. So next will be to check that a file in the `target` directory has been created during a test and should contain the required contents. How should that be expressed? The following gives you an example how you can achieve that: [source,java] ---- assertThat( result ).isSuccessful() .project() .hasTarget() .withFile( ""depDiffs.txt"" ) .hasContent( String.join( ""\\n"", ""The following differences were found:"", """", "" none"", """", ""The following property differences were found:"", """", "" none"" ) ); ---- The first part `.isSuccessful()` checks that the build has gone fine then we go into `project` directory and via `withTarget()` we check the existence of the `target` directory as well as going into that directory. Finally we append `withFile(...)`, which selects which file and redirects to the `AbstractFileAssert` of AssertJ which gives you the choice to check the contents of the file as you like. [source,java] ---- assertThat(project).hasTarget() .withEarFile() .containsOnlyOnce(""META-INF/application.xml"", ""META-INF/appserver-application.xml""); ---- === Assertion for Maven Log In integration tests is necessary to check the log output of a build. This is sometimes needed because you want to check for particular output etc. which has been done by a plugin/extension etc. In general there are currently two different outputs which can be reviewed: * Console output (stdout) * Error output (stderr) These two parts are redirected into appropriate files within the integration result directory (see `the_first_test_case`). In the following example you see two output files `mvn-stdout.log` and `mvn-stderr.log`. [source,text] ---- . └──target/ └── maven-its/ └── org/ └── it/ └── FirstIT/ └── the_first_test_case/ ├── .m2/ ├── project/ │ ├── src/ │ ├── target/ │ └── pom.xml ├── mvn-stdout.log ├── mvn-stderr.log └── other logs ---- Let us take a look into an example test case like this: [source,java] .LogoutputIT.java ---- package com.its; import com.soebes.itf.jupiter.extension.MavenJupiterExtension; import com.soebes.itf.jupiter.extension.MavenCLIOptions; @MavenJupiterExtension class LogoutputIT { @MavenTest void basic(MavenExecutionResult result) { assertThat(result) .out() .warn() .containsExactly(""Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!""); } } ---- Usually you will be using the injection of the `MavenExecutionResult` in your test case. This gives you the option to enhance the assertions like the following: * `assertThat(result).out()....` * `assertThat(result).err()....` The first one `assertThat(result).out()....` will give you access to the `stdout` of the build (which means `mvn-stdout.log`) whereas the second one give you access to the `stderr` of the build (means `mvn-stderr.log`). In using the `..out()` it can be combined with things like: * `.info()` * `.warn()` * `.debug()` * `.error()` Those parts will remove the appropriate prefix from each output line `[INFO]`, `[WARNING]`, `[DEBUG]` or `[ERROR]` (This includes the single space which is followed by them). From that point on you can use the usual AssertJ assertions as in the given example above `containsExactly` which implies that only a single would be allowed to have that single warning. Furthermore if you like to get the plain log output that can be achieved by using: * `.plain()` That will not filter anything. Another example of using the assertions could look like this: include::{itfexample}/itf-examples/src/test/java/com/soebes/itf/examples/LogoutputIT.java[tag=stdout] This will extract all messages with the prefix `[INFO] ` of the log and check if there is at least one line which contains the given content. We can check for warnings like the following: include::{itfexample}/itf-examples/src/test/java/com/soebes/itf/examples/LogoutputIT.java[tag=warning] You can access directly the `stdout` and/or the `stderr` of the Maven build and do things yourself if you prefer to go that way. In this case you have to add another injection to the test case (`MavenLog mavenLog` or like this `result.getMavenLog().getStdout()`). include::{itfexample}/itf-examples/src/test/java/com/soebes/itf/examples/LogoutputIT.java[tag=selfmade] The `stderr` output can be accessed as well like this: include::{itfexample}/itf-examples/src/test/java/com/soebes/itf/examples/LogoutputIT.java[tag=error] A full fledged example can be found `itf-examples/src/test/java/com/soebes/itf/examples/LogoutputIT.java` within the itf project. === Expressing Assertions [source,java] .CompareDependenciesIT.java ---- package org.codehaus.mojo.versions.it; import com.soebes.itf.jupiter.extension.MavenJupiterExtension; import com.soebes.itf.jupiter.extension.MavenTest; import com.soebes.itf.jupiter.maven.MavenExecutionResult; import com.soebes.itf.jupiter.maven.MavenProjectResult; import com.soebes.itf.extension.assertj.MavenITAssertions.assertThat; @MavenJupiterExtension class CompareDependenciesIT { @MavenGoal(""${project.groupId}:${project.artifactId}:${project.version}:compare-dependencies"") @SystemProperty(value = ""remotePom"", content=""localhost:dummy-bom-pom:1.0"") @SystemProperty(value = ""reportOutputFile"", content=""target/depDiffs.txt"") @MavenTest void it_compare_dependencies_001( MavenExecutionResult result ) { assertThat( result ).isSuccessful() .project() .hasTarget() .withFile( ""depDiffs.txt"" ) .hasContent( String.join( ""\\n"", ""The following differences were found:"", """", "" none"", """", ""The following property differences were found:"", """", "" none"" ) ); } } ---- <<< == Special Cases === Overview In some situations it is needed to fail a build of a plugin/extension for testing purposes or other things which not that usual. This chapter describes such situations and shows solutions for those. === Failing the build The integration testing framework contains a plugin `itf-failure-plugin` which (implied by the name) it's only purpose is to fail a build. The following shows a configuration which will produce a `[WARNING]` during the build cause the plugin needs to be configured. [source,xml] ---- include::{itfexample}/itf-failure-plugin/src/test/resources-its/com/soebes/itf/maven/plugin/failure/FailureIT/basic_configuration/pom.xml[tag=configuration] ---- The plugin does not bind to any life cycle phase by default which is intentionally to require a binding to a phase you like. This means also you can bind that plugin to any phase you would like to. In the previous example it is bound to `initialize`. The following example shows a real example how the plugin has been configured correctly (only the `configuration` area). The configuration will fail the build with a `MojoExecutionException` (exeuctionException=true) and a text of the exception can given via `exception` configuration part. [source,xml] ---- include::{itfexample}/itf-failure-plugin/src/test/resources-its/com/soebes/itf/maven/plugin/failure/FailureIT/fail_with_mojo_execution_exception/pom.xml[tag=configuration] ---- The final example will fail the build with a `MojoFailureException` (failureException=true) and the text of the exception can given via `exception` configuration part as before. [source,xml] ---- include::{itfexample}/itf-failure-plugin/src/test/resources-its/com/soebes/itf/maven/plugin/failure/FailureIT/fail_with_mojo_failure_exception/pom.xml[tag=configuration] ---- ",12374,False,2314.2717641519444,median "//// 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. //// == TinkerPop 3.5.0 === Upgrading for Users ==== Upgrade Neo4j Refer to Neo4j link:https://neo4j.com/guides/upgrade-archive/[3.4 Upgrade FAQ] for guide on how to upgrade from the previous 3.2.3 version. For example, configuration setting `dbms.allow_format_migration` is now `dbms.allow_upgrade`. = TinkerPop 3.4.0 image::https://raw.githubusercontent.com/apache/tinkerpop/master/docs/static/images/avant-gremlin.png[width=225] *Avant-Gremlin Construction #3 for Theremin and Flowers* == TinkerPop 3.4.3 *Release Date: NOT OFFICIALLY RELEASED YET* Please see the link:https://github.com/apache/tinkerpop/blob/3.4.3/CHANGELOG.asciidoc#release-3-4-3[changelog] for a complete list of all the modifications that are part of this release. === Upgrading for Users ==== Deprecated store() The `store()`-step and `aggregate()`-step do the same thing in different ways, where the former is lazy and the latter is eager in the side-effect collection of objects from the traversal. The different behaviors can be thought of as differing applications of `Scope` where `global` is eager and `local` is lazy. As a result, there is no need for both steps when one will do. As of 3.4.3, `store(String)` is now deprecated in favor of `aggregate(Scope, String)` where the `Scope` should be set to `local` to ensure the same functionality as `store()`. Note that `aggregate('x')` is the same as `aggregate(global,'x')`. See: link:https://issues.apache.org/jira/browse/TINKERPOP-1553[TINKERPOP-1553] ==== Deprecate Gryo in Gremlin Server Gryo is now deprecated as a serialization format for Gremlin Server, however, it is still configured as a default option in the sample configuration files packaged with the server. The preferred serialization option should now be GraphBinary. Note that Gremlin Console is now configured to use GraphBinary by default. See: link:https://issues.apache.org/jira/browse/TINKERPOP-2250[TINKERPOP-2250] === Upgrading for Providers ==== Graph Driver Providers ===== Gremlin Server Test Configuration Gremlin Server has a test configuration built into its Maven build process which all integration tests and Gremlin Language Variants use to validate their operations. While this approach has worked really well for test automation within Maven, there are often times where it would be helpful to simply have Gremlin Server running with that configuration. This need is especially true when developing Gremlin Language Variants which is something that is done outside of the JVM. This release introduces a Docker script that will start Gremlin Server with this test configuration. It can be started with: [source,text] docker/gremlin-server.sh Once started, it is then possible to run GLV tests directly from a debugger against this instance which should hopefully reduce development friction. see: link:http://tinkerpop.apache.org/docs/3.4.3/dev/developer/#docker-integration[Developer Documentation] == TinkerPop 3.4.2 *Release Date: May 28, 2019* Please see the link:https://github.com/apache/tinkerpop/blob/3.4.2/CHANGELOG.asciidoc#release-3-4-2[changelog] for a complete list of all the modifications that are part of this release. === Upgrading for Users ==== Per Request Options In 3.4.0, the notion of `RequestOptions` were added so that users could have an easier way to configure settings on individual requests made through the Java driver. While that change provided a way to set those configurations for script based requests, it didn't include options to make those settings in a `Traversal` submitted via `Bytecode`. In this release those settings become available via `with()` step on the `TraversalSource` as follows: [source,java] ---- GraphTraversalSource g = traversal().withRemote(conf); List vertices = g.with(RemoteConnection.PER_REQUEST_TIMEOUT, 500).V().out(""knows"").toList() ---- See: link:https://issues.apache.org/jira/browse/TINKERPOP-2211[TINKERPOP-2211] ==== Gremlin Console Timeout The Gremlin Console timeout that is set by `:remote config timeout x` was client-side only in prior versions, which meant that if the console timeout was less than the server timeout the client would timeout but the server might still be processing the request. Similarly, a longer timeout on the console would not change the server and the timeout would occur sooner than expected. These discrepancies often led to confusion. As of 3.4.0, the Java Driver API allowed for timeout settings to be more easily passed per request, so the console was modified for this current version to pass the console timeout for each remote submission thus yielding more consistent and intuitive behavior. See: link:https://issues.apache.org/jira/browse/TINKERPOP-2203[TINKERPOP-2203] === Upgrading for Providers ==== Graph System Providers ===== Warnings It is now possible to pass warnings over the Gremlin Server protocol using a `warnings` status attribute. The warnings are expected to be a string value or a `List` of string values which can be consumed by the user or tools that check for that status attribute. Note that Gremlin Console is one such tool that will respond to this status attribute - it will print the messages to the console as they are detected when doing remote script submissions. See: link:https://issues.apache.org/jira/browse/TINKERPOP-2216[TINKERPOP-2216] ==== Graph Driver Providers ===== GraphBinary API Change In GraphBinary serialization, Java `write()` and `writeValue()` from `TypeSerializer` interface now take a Netty's `ByteBuf` instance instead of an `ByteBufAllocator`, that way the same buffer instance gets reused during the write of a message. Additionally, we took the opportunity to remove the unused parameter from `ResponseMessageSerializer`. See: link:https://issues.apache.org/jira/browse/TINKERPOP-2161[TINKERPOP-2161] == TinkerPop 3.4.1 *Release Date: March 18, 2019* Please see the link:https://github.com/apache/tinkerpop/blob/3.4.1/CHANGELOG.asciidoc#release-3-4-1[changelog] for a complete list of all the modifications that are part of this release. === Upgrading for Users ==== Mix SPARQL and Gremlin In the initial release of `sparql-gremlin` it was only possible to execute a SPARQL query and have it translate to Gremlin. Therefore, it was only possible to write a query like this: [source,text] ---- gremlin> g.sparql(""SELECT ?name ?age WHERE { ?person v:name ?name . ?person v:age ?age }"") ==>[name:marko,age:29] ==>[name:vadas,age:27] ==>[name:josh,age:32] ==>[name:peter,age:35] gremlin> g.sparql(""SELECT * WHERE { }"") ==>v[1] ==>v[2] ==>v[3] ==>v[4] ==>v[5] ==>v[6] ---- In this release, however, it is now possible to further process that result with Gremlin steps: [source,text] ---- gremlin> g.sparql(""SELECT ?name ?age WHERE { ?person v:name ?name . ?person v:age ?age }"").select(""name"") ==>marko ==>vadas ==>josh ==>peter gremlin> g.sparql(""SELECT * WHERE { }"").out(""knows"").values(""name"") ==>vadas ==>josh ---- See: link:https://issues.apache.org/jira/browse/TINKERPOP-2171[TINKERPOP-2171], link:http://tinkerpop.apache.org/docs/3.4.1/reference/#sparql-with-gremlin[Reference Documentation] === Upgrading for Providers ==== Graph Database Providers ===== GraphBinary Serializer Changes In GraphBinary serialization, Java `write()` and `writeValue()` from `TypeSerializer` interface now take a Netty's `ByteBuf` instance instead of an `ByteBufAllocator`, that way the same buffer instance gets reused during the write of a message. Additionally, we took the opportunity to remove the unused parameter from `ResponseMessageSerializer`. See: link:https://issues.apache.org/jira/browse/TINKERPOP-2161[TINKERPOP-2161] == TinkerPop 3.4.0 *Release Date: January 2, 2019* Please see the link:https://github.com/apache/tinkerpop/blob/3.4.0/CHANGELOG.asciidoc#release-3-4-0[changelog] for a complete list of all the modifications that are part of this release. === Upgrading for Users ==== sparql-gremlin The `sparql-gremlin` module is a link:https://en.wikipedia.org/wiki/SPARQL[SPARQL] to Gremlin compiler, which allows SPARQL to be executed over any TinkerPop-enabled graph system. [source,groovy] ---- graph = TinkerFactory.createModern() g = graph.traversal(SparqlTraversalSource) g.sparql(""""""SELECT ?name ?age WHERE { ?person v:name ?name . ?person v:age ?age } ORDER BY ASC(?age)"""""") ---- See: link:https://issues.apache.org/jira/browse/TINKERPOP-1878[TINKERPOP-1878], link:http://tinkerpop.apache.org/docs/3.4.0/reference/#sparql-gremlin[Reference Documentation] ==== Gremlin.NET Driver Improvements The Gremlin.NET driver now uses request pipelining. This allows connections to be reused for different requests in parallel which should lead to better utilization of connections. The `ConnectionPool` now also has a fixed size whereas it could previously create an unlimited number of connections. Each `Connection` can handle up to `MaxInProcessPerConnection` requests in parallel. If this limit is reached for all connections, then a `NoConnectionAvailableException` is thrown which makes this a breaking change. These settings can be set as properties on the `ConnectionPoolSettings` instance that can be passed to the `GremlinClient`. See: link:https://issues.apache.org/jira/browse/TINKERPOP-1774[TINKERPOP-1774], link:https://issues.apache.org/jira/browse/TINKERPOP-1775[TINKERPOP-1775], link:http://tinkerpop.apache.org/docs/3.4.0/reference/#_connection_pool[Reference Documentation] ==== Indexing of Collections TinkerPop 3.4.0 adds a new `index()`-step, which allows users to transform simple collections into index collections or maps. ``` gremlin> g.V().hasLabel(""software"").values(""name"").fold(). ......1> order(local). ......2> index().unfold() ==>[lop,0] ==>[ripple,1] gremlin> g.V().hasLabel(""person"").values(""name"").fold(). ......1> order(local).by(decr). ......2> index(). ......3> with(WithOptions.indexer, WithOptions.map) ==>[0:vadas,1:peter,2:marko,3:josh] ``` ==== Modulation of valueMap() The `valueMap()` step now supports `by` and `with` modulation, which also led to the deprecation of `valueMap(true)` overloads. ===== by() Modulation With the help of the `by()` modulator `valueMap()` result values can now be adjusted, which is particularly useful to turn multi-/list-values into single values. ``` gremlin> g.V().hasLabel(""person"").valueMap() ==>[name:[marko],age:[29]] ==>[name:[vadas],age:[27]] ==>[name:[josh],age:[32]] ==>[name:[peter],age:[35]] gremlin> g.V().hasLabel(""person"").valueMap().by(unfold()) ==>[name:marko,age:29] ==>[name:vadas,age:27] ==>[name:josh,age:32] ==>[name:peter,age:35] ``` ===== with() Modulation The `with()` modulator can be used to include certain tokens (`id`, `label`, `key` and/or `value`). The old way (still valid, but deprecated): ``` gremlin> g.V().hasLabel(""software"").valueMap(true) ==>[id:10,label:software,name:[gremlin]] ==>[id:11,label:software,name:[tinkergraph]] gremlin> g.V().has(""person"",""name"",""marko"").properties(""location"").valueMap(true) ==>[id:6,key:location,value:san diego,startTime:1997,endTime:2001] ==>[id:7,key:location,value:santa cruz,startTime:2001,endTime:2004] ==>[id:8,key:location,value:brussels,startTime:2004,endTime:2005] ==>[id:9,key:location,value:santa fe,startTime:2005] ``` The new way: ``` gremlin> g.V().hasLabel(""software"").valueMap().with(WithOptions.tokens) ==>[id:10,label:software,name:[gremlin]] ==>[id:11,label:software,name:[tinkergraph]] gremlin> g.V().has(""person"",""name"",""marko"").properties(""location"").valueMap().with(WithOptions.tokens) ==>[id:6,key:location,value:san diego,startTime:1997,endTime:2001] ==>[id:7,key:location,value:santa cruz,startTime:2001,endTime:2004] ==>[id:8,key:location,value:brussels,startTime:2004,endTime:2005] ==>[id:9,key:location,value:santa fe,startTime:2005] ``` Furthermore, now there's a finer control over which of the tokens should be included: ``` gremlin> g.V().hasLabel(""software"").valueMap().with(WithOptions.tokens, WithOptions.labels) ==>[label:software,name:[gremlin]] ==>[label:software,name:[tinkergraph]] gremlin> g.V().has(""person"",""name"",""marko"").properties(""location"").valueMap().with(WithOptions.tokens, WithOptions.values) ==>[value:san diego,startTime:1997,endTime:2001] ==>[value:santa cruz,startTime:2001,endTime:2004] ==>[value:brussels,startTime:2004,endTime:2005] ==>[value:santa fe,startTime:2005] ``` As shown above, the support of the `with()` modulator for `valueMap()` makes the `valueMap(boolean)` overload superfluous, hence this overload is now deprecated. This is a breaking API change, since `valueMap()` will now always yield instances of type `Map`. Prior this change only the `valueMap(boolean)` overload yielded `Map` objects, `valueMap()` without the boolean parameter used to yield instances of type `Map`. See: link:https://issues.apache.org/jira/browse/TINKERPOP-2059[TINKERPOP-2059] ==== Predicate Number Comparison In previous versions `within()` and `without()` performed strict number comparisons; that means these predicates did not only compare number values, but also the type. This was inconsistent with how other predicates (like `eq`, `gt`, etc.) work. All predicates will now ignore the number type and instead compare numbers only based on their value. Old behavior: ``` gremlin> g.V().has(""age"", eq(32L)) ==>v[4] gremlin> g.V().has(""age"", within(32L, 35L)) gremlin> ``` New behavior: ``` gremlin> g.V().has(""age"", eq(32L)) ==>v[4] gremlin> g.V().has(""age"", within(32L, 35L)) ==>v[4] ==>v[6] ``` See: link:https://issues.apache.org/jira/browse/TINKERPOP-2058[TINKERPOP-2058] ==== ReferenceElementStrategy Gremlin Server has had some inconsistent behavior in the serialization of the results it returns. Remote traversals based on Gremlin bytecode always detach returned graph elements to ""reference"" (i.e. removes properties and only include the `id` and `label`), but scripts would detach graph elements and include the properties. For 3.4.0, TinkerPop introduces the `ReferenceElementStrategy` which can be configured on a `GraphTraversalSource` to always detach to ""reference"". [source,text] ---- gremlin> graph = TinkerFactory.createModern() ==>tinkergraph[vertices:6 edges:6] gremlin> g = graph.traversal().withStrategies(ReferenceElementStrategy.instance()) ==>graphtraversalsource[tinkergraph[vertices:6 edges:6], standard] gremlin> v = g.V().has('person','name','marko').next() ==>v[1] gremlin> v.class ==>class org.apache.tinkerpop.gremlin.structure.util.reference.ReferenceVertex gremlin> v.properties() gremlin> ---- The packaged initialization scripts that come with Gremlin Server now pre-configure the sample graphs with this strategy to ensure that both scripts and bytecode based requests over any protocol (HTTP, websocket, etc) and serialization format all return a ""reference"". To revert to the old form, simply remove the strategy in the initialization script. It is recommended that users choose to configure their `GraphTraversalSource` instances with `ReferenceElementStrategy` as working with ""references"" only is the recommended method for developing applications with TinkerPop. In the future, it is possible that `ReferenceElementStrategy` will be configured by default for all graphs on or off Gremlin Server, so it would be best to start utilizing it now and grooming existing Gremlin and related application code to account for it. See: link:https://issues.apache.org/jira/browse/TINKERPOP-2075[TINKERPOP-2075] ==== Text Predicates Gremlin now supports simple text predicates on top of the existing `P` predicates. Both, the new `TextP` text predicates and the old `P` predicates, can be chained using `and()` and `or()`. [source,groovy] ---- gremlin> g.V().has(""person"",""name"", containing(""o"")).valueMap() ==>[name:[marko],age:[29]] ==>[name:[josh],age:[32]] gremlin> g.V().has(""person"",""name"", containing(""o"").and(gte(""j"").and(endingWith(""ko"")))).valueMap() ==>[name:[marko],age:[29]] ---- See: link:https://issues.apache.org/jira/browse/TINKERPOP-2041[TINKERPOP-2041] ==== Changed Infix Behavior The infix notation of `and()` and `or()` now supports an arbitrary number of traversals and `ConnectiveStrategy` produces a traversal with proper AND and OR semantics. ``` Input: a.or.b.and.c.or.d.and.e.or.f.and.g.and.h.or.i *BEFORE* Output: or(a, or(and(b, c), or(and(d, e), or(and(and(f, g), h), i)))) *NOW* Output: or(a, and(b, c), and(d, e), and(f, g, h), i) ``` Furthermore, previous versions failed to apply 3 or more `and()` steps using the infix notation, this is now fixed. [source,groovy] ---- gremlin> g.V().has(""name"",""marko"").and().has(""age"", lt(30)).or().has(""name"",""josh"").and().has(""age"", gt(30)).and().out(""created"") ==>v[1] ==>v[4] ---- See: link:https://issues.apache.org/jira/browse/TINKERPOP-2029[TINKERPOP-2029] ==== GraphBinary GraphBinary is a new language agnostic, network serialization format designed to replace Gryo and GraphSON. At this time it is only available on the JVM, but support will be added for other languages in upcoming releases. The serializer has been configured in Gremlin Server's packaged configuration files. The serializer can be configured using the Java driver as follows: [source,java] ---- Cluster cluster = Cluster.build(""localhost"").port(8182). serializer(Serializers.GRAPHBINARY_V1D0).create(); Client client = cluster.connect(); List r = client.submit(""g.V().has('person','name','marko')"").all().join(); ---- See: link:https://issues.apache.org/jira/browse/TINKERPOP-1942[TINKERPOP-1942], link:http://tinkerpop.apache.org/docs/3.4.0/dev/io/#graphbinary[IO Documentation] ==== Status Attributes The Gremlin Server protocol allows for status attributes to be returned in responses. These attributes were typically for internal use, but were designed with extensibility in mind so that providers could place return their own attributes to calling clients. Unfortunately, unless the client was being used with protocol level requests (which wasn't convenient) those attributes were essentially hidden from view. As of this version however, status attributes are fully retrievable for both successful requests and exceptions. See: link:https://issues.apache.org/jira/browse/TINKERPOP-1913[TINKERPOP-1913] ==== with() Step This version of TinkerPop introduces the `with()`-step to Gremlin. It isn't really a step but is instead a step modulator. This modulator allows the step it is modifying to accept configurations that can be used to alter the behavior of the step itself. A good example of its usage is shown with the revised syntax of the `pageRank()`-step which now uses `with()` to replace the old `by()` options: [source,groovy] ---- g.V().hasLabel('person'). pageRank(). with(PageRank.edges, __.outE('knows')). with(PageRank.propertyName, 'friendRank'). order(). by('friendRank',desc). valueMap('name','friendRank') ---- A similar change was made for `peerPressure()`-step: [source,groovy] ---- g.V().hasLabel('person'). peerPressure(). with(PeerPressure.propertyName, 'cluster'). group(). by('cluster'). by('name') ---- Note that the `by()` modulators still work, but should be considered deprecated and open for removal in a future release where breaking changes are allowed. See: link:https://issues.apache.org/jira/browse/TINKERPOP-1975[TINKERPOP-1975], link:http://tinkerpop.apache.org/docs/3.4.0/reference/#with-step[Reference Documentation] ==== shortestPath() Step Calculating the link:https://en.wikipedia.org/wiki/Shortest_path_problem[shortest path] between vertices is a common graph use case. While the traversal to determine a shortest path can be expressed in Gremlin, this particular problem is common enough that the feature has been encapsulated into its own step, demonstrated as follows: [source,text] ---- gremlin> g.withComputer().V().has('name','marko'). ......1> shortestPath().with(ShortestPath.target, has('name','peter')) ==>[v[1],v[3],v[6]] ---- See: link:https://issues.apache.org/jira/browse/TINKERPOP-1990[TINKERPOP-1990], link:http://tinkerpop.apache.org/docs/3.4.0/reference/#shortestpath-step[Reference Documentation] ==== connectedComponent() Step In prior version of TinkerPop, it was recommended that the identification of link:https://en.wikipedia.org/wiki/Connected_component_(graph_theory)[Connected Component] instances in a graph be computed by way of a reasonably complex bit of Gremlin that looked something like this: [source,groovy] ---- g.V().emit(cyclicPath().or().not(both())).repeat(both()).until(cyclicPath()). path().aggregate(""p""). unfold().dedup(). map(__.as(""v"").select(""p"").unfold(). filter(unfold().where(eq(""v""))). unfold().dedup().order().by(id).fold()). dedup() ---- The above approach had a number of drawbacks that included a large execution cost as well as incompatibilities in OLAP. To simplify usage of this commonly use graph algorithm, TinkerPop 3.4.0 introduces the `connectedComponent()` step which reduces the above operation to: [source,groovy] ---- g.withComputer().V().connectedComponent() ---- It is important to note that this step does require the use of a `GraphComputer` to work, as it utilizes a `VertexProgram` behind the scenes. See: link:https://issues.apache.org/jira/browse/TINKERPOP-1967[TINKERPOP-1967], link:http://tinkerpop.apache.org/docs/x.y.z/reference/#connectedcomponent-step[Reference Documentation] ==== io() Step There have been some important changes to IO operations for reading and writing graph data. The use of `Graph.io()` has been deprecated to further remove dependence on the Graph (Structure) API for users and to extend these basic operations to GLV users by making these features available as part of the Gremlin language. It is now possible to simply use Gremlin: [source,groovy] ---- graph = ... g = graph.traversal() g.io(someInputFile).read().iterate() g.io(someOutputFile).write().iterate() ---- While `io()`-step is still single-threaded for OLTP style loading, it can be utilized in conjunction with OLAP which internally uses `CloneVertexProgram` and therefore any graph `InputFormat` or `OutputFormat` can be configured in conjunction with this step for parallel loads of large datasets. It is also worth noting that the `io()`-step may be overridden by graph providers to utilize their native bulk-loading features, so consult the documentation of the implementation being used to determine if there are any improved efficiencies there. See: link:https://issues.apache.org/jira/browse/TINKERPOP-1996[TINKERPOP-1996], link:http://tinkerpop.apache.org/docs/3.4.0/reference/#io-step[Reference Documentation] ==== Per Request Options The Java driver now allows for various options to be set on a per-request basis via new overloads to `submit()` that accept `RequestOption` instances. A good use-case for this feature is to set a per-request override to the `scriptEvaluationTimeout` so that it only applies to the current request. [source,java] ---- Cluster cluster = Cluster.open(); Client client = cluster.connect(); RequestOptions options = RequestOptions.build().timeout(500).create(); List result = client.submit(""g.V()"", options).all().get(); ---- See: link:https://issues.apache.org/jira/browse/TINKERPOP-1342[TINKERPOP-1342] ==== min() max() and Comparable Previously `min()` and `max()` were only working for numeric values. This has been changed and these steps can now operate over any `Comparable` value. The common workaround was the combination of `order().by()` and `limit()` as shown here: [source,groovy] ---- gremlin> g.V().values('name').order().by().limit(1) // workaround for min() ==>josh gremlin> g.V().values('name').order().by(decr).limit(1) // workaround for max() ==>vadas ---- Any attempt to use `min()` or `max()` on non-numeric values lead to an exception: [source,groovy] ---- gremlin> g.V().values('name').min() java.lang.String cannot be cast to java.lang.Number Type ':help' or ':h' for help. Display stack trace? [yN] ---- With the changes in this release these kind of queries became a lot easier: [source,groovy] ---- gremlin> g.V().values('name').min() ==>josh gremlin> g.V().values('name').max() ==>vadas ---- ==== Nested Loop Support Traversals now support nesting of `repeat()` loops. These can now be used to repeat another traversal while in a looped context, either inside the body of a `repeat()` or in its step modifiers (`until()` or `emit()`). [source,groovy] ---- gremlin> g.V().repeat(__.in('traverses').repeat(__.in('develops')).emit()).emit().values('name') ==>stephen ==>matthias ==>marko ---- See: link:https://issues.apache.org/jira/browse/TINKERPOP-967[TINKERPOP-967] ==== EventStrategy API There were some minor modifications to how `EventStrategy` is constructed and what can be expected from events raised from the addition of new properties. With respect to the change in terms of `EventStrategy` construction, the `detach()` builder method formerly took a `Class` as an argument and that `Class` was meant to be one of the various ""detachment factories"" or `null`. That approach was a bit confusing, so that signature has changed to `detach(EventStrategy.Detachment)` where the argument is a more handy enum of detachment options. As for the changes related to events themselves, it is first worth noting that the previously deprecated `vertexPropertyChanged(Vertex, Property, Object, Object...)` on `MutationListener` has been removed for what should have originally been the correct signature of `vertexPropertyChanged(Vertex, VertexProperty, Object, Object...)`. In prior versions when this method and its related `edgePropertyChanged()` and `vertexPropertyPropertyChanged()` were triggered by way of the addition of a new property a ""fake"" property was included with a `null` value for the ""oldValue"" argument to these methods (as it did not exist prior to this event). That was a bit awkward to reason about when dealing with that event. To make this easier, the event now raises with a `KeyedVertexProperty` or `KeyedProperty` instance, which only contains a property key and no value in them. link:https://issues.apache.org/jira/browse/TINKERPOP-1831[TINKERPOP-1831] ==== Reducing Barrier Steps The behavior of `min()`, `max()`, `mean()` and `sum()` has been modified to return no result if there's no input. Previously these steps yielded the internal seed value: [source,groovy] ---- gremlin> g.V().values('foo').min() ==>NaN gremlin> g.V().values('foo').max() ==>NaN gremlin> g.V().values('foo').mean() ==>NaN gremlin> g.V().values('foo').sum() ==>0 ---- These traversals will no longer emit a result. Note, that this also affects more complex scenarios, e.g. if these steps are used in `by()` modulators: [source,groovy] ---- gremlin> g.V().group(). ......1> by(label). ......2> by(outE().values(""weight"").sum()) ==>[software:0,person:3.5] ---- Since software vertices have no outgoing edges and thus no weight values to sum, `software` will no longer show up in the result. In order to get the same result as before, one would have to add a `coalesce()`-step: [source,groovy] ---- gremlin> g.V().group(). ......1> by(label). ......2> by(outE().values(""weight"").sum()) ==>[person:3.5] gremlin> g.V().group(). ......1> by(label). ......2> by(coalesce(outE().values(""weight""), constant(0)).sum()) ==>[software:0,person:3.5] ---- See: link:https://issues.apache.org/jira/browse/TINKERPOP-1777[TINKERPOP-1777] ==== Order of select() Scopes The order of select scopes has been changed to: maps, side-effects, paths. Previously the order was: side-effects, maps, paths - which made it almost impossible to select a specific map entry if a side-effect with the same name existed. The following snippets illustrate the changed behavior: [source,groovy] ---- gremlin> g.V(1). ......1> group(""a""). ......2> by(__.constant(""a"")). ......3> by(__.values(""name"")). ......4> select(""a"") ==>[a:marko] gremlin> g.V(1). ......1> group(""a""). ......2> by(__.constant(""a"")). ......3> by(__.values(""name"")). ......4> select(""a"").select(""a"") ==>[a:marko] ---- Above is the old behavior; the second `select(""a"")` has no effect, it selects the side-effect `a` again, although one would expect to get the map entry `a`. What follows is the new behavior: [source,groovy] ---- gremlin> g.V(1). ......1> group(""a""). ......2> by(__.constant(""a"")). ......3> by(__.values(""name"")). ......4> select(""a"") ==>[a:marko] gremlin> g.V(1). ......1> group(""a""). ......2> by(__.constant(""a"")). ......3> by(__.values(""name"")). ......4> select(""a"").select(""a"") ==>marko ---- See: link:https://issues.apache.org/jira/browse/TINKERPOP-1522[TINKERPOP-1522] ==== GraphSON BulkSet In earlier versions of TinkerPop, `BulkSet` was coerced to a `List` for GraphSON which was convenient in that it didn't add a new data type to support, but inconvenient in that it meant that certain process tests were not consistent in terms of how they ran and the benefits of the `BulkSet` were ""lost"" in that the ""bulk"" was being resolved server side. With the addition of `BulkSet` as a GraphSON type the ""bulk"" is now resolved on the client side by the language variant. How that resolution occurs depends upon the language variant. For Java, there is a `BulkSet` object which maintains that structure sent from the server. For the other variants, the `BulkSet` is deserialized to a `List` form which results in a much larger memory footprint than what is contained the `BulkSet`. See: link:https://issues.apache.org/jira/browse/TINKERPOP-2111[TINKERPOP-2111] ==== Python Bindings Bindings were formerly created using a Python 2-tuple as a bit of syntactic sugar, but all other language variants used an explicit `Bindings` object which `gremlin-python` already had in place. To make all work variants behave consistently, the 2-tuple syntax has been removed in favor of the explicit `Bindings.of()` option. [source,python] ---- g.V(Bindings.of('id',1)).out('created').map(lambda: (""it.get().value('name').length()"", ""gremlin-groovy"")).sum() ---- See: link:https://issues.apache.org/jira/browse/TINKERPOP-2116[TINKERPOP-2116] ==== Deprecation and Removal This section describes newly deprecated classes, methods, components and patterns of usage as well as which previously deprecated features have been officially removed or repurposed. ===== Moving of RemoteGraph `RemoteGraph` was long ago deprecated in favor of `withRemote()`. It became even less useful with the introduction of the `AnonymousTraversalSource` concept in 3.3.5. It's only real use was for testing remote bytecode based traversals in the test suite as the test suite requires an actual `Graph` object to function properly. As such, `RemoteGraph` has been moved to `gremlin-test`. It should no longer be used in any capacity besides that. See: link:https://issues.apache.org/jira/browse/TINKERPOP-2079[TINKERPOP-2079] ===== Removal of Giraph Support Support for Giraph has been removed as of this version. There were a number of reasons for this decision which were discussed in the community prior to taking this step. Users should switch to Spark for their OLAP based graph-computing needs. See: link:https://issues.apache.org/jira/browse/TINKERPOP-1930[TINKERPOP-1930] ===== Removal of Rebindings Options The ""rebindings"" option is no longer supported for clients. It was deprecated long ago at 3.1.0. The server will not respond to them on any channel - websockets, nio or HTTP. Use the ""aliases"" option instead. link:https://issues.apache.org/jira/browse/TINKERPOP-1705[TINKERPOP-1705] ===== gremlin-server.sh -i Removal The `-i` option for installing dependencies in Gremlin Server was long ago deprecated and has now been removed. Please use `install` as its replacement going forward. link:https://issues.apache.org/jira/browse/TINKERPOP-2031[TINKERPOP-2031] ===== Deprecation Removal The following deprecated classes, methods or fields have been removed in this version: * `gremlin-core` ** `org.apache.tinkerpop.gremlin.jsr223.ImportCustomizer#GREMLIN_CORE` ** `org.apache.tinkerpop.gremlin.process.remote.RemoteGraph` - moved to `gremlin-test` ** `org.apache.tinkerpop.gremlin.process.remote.RemoteConnection.submit(Traversal)` ** `org.apache.tinkerpop.gremlin.process.remote.RemoteConnection.submit(Bytecode)` ** `org.apache.tinkerpop.gremlin.process.remote.traversal.strategy.decoration.RemoteStrategy#identity()` ** `org.apache.tinkerpop.gremlin.process.traversal.TraversalEngine` ** `org.apache.tinkerpop.gremlin.process.traversal.engine.*` ** `org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.PartitionStrategy.Builder#addReadPartition(String)` ** `org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.SubgraphStrategy.Builder#edgeCriterion(Traversal)` ** `org.apache.tinkerpop.gremlin.process.traversal.strategy.decoration.SubgraphStrategy.Builder#vertexCriterion(Traversal)` ** `org.apache.tinkerpop.gremlin.process.traversal.step.map.LambdaCollectingBarrierStep.Consumers` ** `org.apache.tinkerpop.gremlin.process.traversal.step.util.HasContainer#makeHasContainers(String, P)` ** `org.apache.tinkerpop.gremlin.process.traversal.step.util.event.MutationListener#vertexPropertyChanged(Vertex, Property, Object, Object...)` ** `org.apache.tinkerpop.gremlin.structure.Element.Exceptions#elementAlreadyRemoved(Class, Object)` ** `org.apache.tinkerpop.gremlin.structure.Graph.Exceptions#elementNotFound(Class, Object)` ** `org.apache.tinkerpop.gremlin.structure.Graph.Exceptions#elementNotFound(Class, Object, Exception)` * `gremlin-driver` ** `org.apache.tinkerpop.gremlin.driver.Client#rebind(String)` ** `org.apache.tinkerpop.gremlin.driver.Client.ReboundClusterdClient` ** `org.apache.tinkerpop.gremlin.driver.Tokens#ARGS_REBINDINGS` * `gremlin-groovy` ** `org.apache.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngine.close()` - no longer implements `AutoCloseable` * `gremlin-server` ** `org.apache.tinkerpop.gremlin.server.GraphManager#getGraphs()` ** `org.apache.tinkerpop.gremlin.server.GraphManager#getTraversalSources()` ** `org.apache.tinkerpop.gremlin.server.Settings#serializedResponseTimeout` ** `org.apache.tinkerpop.gremlin.server.Settings.AuthenticationSettings#className` ** `org.apache.tinkerpop.gremlin.server.handler.OpSelectorHandler(Settings, GraphManager, GremlinExecutor, ScheduledExecutorService)` ** `org.apache.tinkerpop.gremlin.server.op.AbstractOpProcessor#makeFrame(ChannelHandlerContext, RequestMessage, MessageSerializer serializer, boolean, List, ResponseStatusCode code)` * `hadoop-graph` ** `org.apache.tinkerpop.gremlin.hadoop.structure.HadoopConfiguration#getGraphInputFormat()` ** `org.apache.tinkerpop.gremlin.hadoop.structure.HadoopConfiguration#getGraphOutputFormat()` Please see the javadoc deprecation notes or upgrade documentation specific to when the deprecation took place to understand how to resolve this breaking change. See: link:https://issues.apache.org/jira/browse/TINKERPOP-1143[TINKERPOP-1143], link:https://issues.apache.org/jira/browse/TINKERPOP-1296[TINKERPOP-1296], link:https://issues.apache.org/jira/browse/TINKERPOP-1705[TINKERPOP-1705], link:https://issues.apache.org/jira/browse/TINKERPOP-1707[TINKERPOP-1707], link:https://issues.apache.org/jira/browse/TINKERPOP-1954[TINKERPOP-1954], link:https://issues.apache.org/jira/browse/TINKERPOP-1986[TINKERPOP-1986], link:https://issues.apache.org/jira/browse/TINKERPOP-2079[TINKERPOP-2079], link:https://issues.apache.org/jira/browse/TINKERPOP-2103[TINKERPOP-2103] ===== Deprecated GraphSONMessageSerializerGremlinV2d0 The `GraphSONMessageSerializerGremlinV2d0` serializer is now analogous to `GraphSONMessageSerializerV2d0` and therefore redundant. It has technically always been equivalent in terms of functionality as both serialized to the same format (i.e. GraphSON 2.0 with embedded types). It is no longer clear why these two classes were established this way, but it does carry the negative effect where multiple serializer versions could not be bound to Gremlin Server's HTTP endpoint as the MIME types conflicted on `application/json`. By simply making both message serializers support `application/json` and `application/vnd.gremlin-v2.0+json`, it then became possible to overcome that limitation. In short, prefer use of `GraphSONMessageSerializerV2d0` when possible. Note that this is a breaking change in the sense that `GraphSONMessageSerializerV2d0` will no longer set the header of requests messages to `application/json`. As a result, older versions of Gremlin Server not configured with `GraphSONMessageSerializerGremlinV2d0` will not find a deserializer to match the request. See: link:https://issues.apache.org/jira/browse/TINKERPOP-1984[TINKERPOP-1984] ===== Removed groovy-sql Dependency Gremlin Console and Gremlin Server no longer include groovy-sql. If you depend on groovy-sql, you can install it in Gremlin Console or Gremlin Server using the plugin system. Console: ``` :install org.codehaus.groovy groovy-sql 2.5.2 ``` Server: ``` bin/gremlin-server.sh install org.codehaus.groovy groovy-sql 2.5.2 ``` If your project depended on groovy-sql transitively, simply include it in your project's build file (e.g. maven: pom.xml). See: link:https://issues.apache.org/jira/browse/TINKERPOP-2037[TINKERPOP-2037] === Upgrading for Providers ==== Graph Database Providers ===== io() Step The new `io()`-step that was introduced provides some new changes to consider. Note that `Graph.io()` has been deprecated and users are no longer instructed to utilize that method. It is not yet decided when that method will be removed completely, but given the public nature of it and the high chance of common usage, it should be hanging around for some time. As with any step in Gremlin, it is possible to replace it with a more provider specific implementation that could be more efficient. Developing a `TraversalStrategy` to do this is encouraged, especially for those graph providers who might have special bulk loaders that could be abstracted by this step. Examples of this are already shown with `HadoopGraph` which replaces the simple single-threaded loader with `CloneVertexProgram`. Graph providers are encouraged to use the `with()` step to capture any necessary configurations required for their underlying loader to work. Graph providers should not feel restricted to `graphson`, `gryo` and `graphml` formats either. If a graph supports CSV or some custom graph specific format, it shouldn't be difficult to gather the configurations necessary to make that available to users. See: link:https://issues.apache.org/jira/browse/TINKERPOP-1996[TINKERPOP-1996] ===== Caching Graph Features For graph implementations that have expensive creation times, it can be time consuming to run the TinkerPop test suite as each test run requires a `Graph` instance even if the test is ultimately ignored becaue it doesn't pass the feature checks. To possibly help alleviate this problem, the `GraphProvider` interface now includes this method: [source,java] ---- public default Optional getStaticFeatures() { return Optional.empty(); } ---- This method can be implemented to return a cacheable set of features for a `Graph` generated from that `GraphProvider`. Assuming this method is faster than the cost of creating a new `Graph` instance, the test suite should execute significantly faster depending on how many tests end up being ignored. See: link:https://issues.apache.org/jira/browse/TINKERPOP-1518[TINKERPOP-1518] ===== Configuring Interface There were some changes to interfaces that were related to `Step`. A new `Configuring` interface was added that was helpful in the implementation of the `with()`-step modulator. This new interface extends the `Parameterizing` interface (which moved to the `org.apache.tinkerpop.gremlin.process.traversal.step` package with the other step interfaces) and in turn is extended by the `Mutating` interface. Making this change meant that the `Mutating.addPropertyMutations()` method could be removed in favor of the new `Configuring.configure()` method. All of the changes above basically mean, that if the `Mutating` interface was being used in prior versions, the `addPropertyMutations()` method simply needs to be changed to `configure()`. See: link:https://issues.apache.org/jira/browse/TINKERPOP-1975[TINKERPOP-1975] ===== OptionsStrategy `OptionsStrategy` is a `TraversalStrategy` that makes it possible for users to set arbitrary configurations on a `Traversal`. These configurations can be used by graph providers to allow for traversal-level configurations to be accessible to their custom steps. A user would write something like: [source,java] ---- g.withStrategies(OptionsStrategy.build().with(""specialLimit"", 10000).create()).V(); ---- The `OptionsStrategy` is really only the carrier for the configurations and while users can choose to utilize that more verbose method for constructing it shown above, it is more elegantly constructed as follows using `with()`-step: [source,java] ---- g.with(""specialLimit"", 10000)).V(); ---- The graph provider could then access that value of ""specialLimit"" in their custom step (or elsewhere) as follows: [source,java] ---- OptionsStrategy strategy = this.getTraversal().asAdmin().getStrategies().getStrategy(OptionsStrategy.class).get(); int specialLimit = (int) strategy.getOptions().get(""specialLimit""); ---- See: link:https://issues.apache.org/jira/browse/TINKERPOP-2053[TINKERPOP-2053] ===== Removed hadoop-gremlin Test Artifact The `hadoop-gremlin` module no longer generates a test jar that can be used as a test dependency in other modules. Generally speaking, that approach tends to be a bad practice and can cause build problems with Maven that aren't always obvious to troubleshoot. With the removal of `giraph-gremlin` for 3.4.0, it seemed even less useful to have this test artifact present. All tests are still present. The follow provides a basic summary of how this refactoring occurred: * A new `AbstractFileGraphProvider` was created in `gremlin-test` which provided a lot of the features that `HadoopGraphProvider` was exposing. Both `HadoopGraphProvider` and `SparkHadoopGraphProvider` extend from that class now. * `ToyIoRegistry` and related classes were moved to `gremlin-test`. * The various tests that validated capabilities of `Storage` have been moved to `spark-gremlin` and are part of those tests now. Obviously, that makes those tests specific to Spark testing now. If that location creates a problem for some reason, that decision can be revisited at some point. See: link:https://issues.apache.org/jira/browse/TINKERPOP-1410[TINKERPOP-1410] ===== TraversalEngine Moved The `TraversalEngine` interface was deprecated in 3.2.0 along with all related methods that used it and classes that implemented it. It was replaced by the `Computer` interface and provided a much nicer way to plug different implementations of `Computer` into a traversal. `TraversalEngine` was never wholly removed however as it had some deep dependencies in the inner workings of the test suite. That infrastructure has largely remained as is until now. As of 3.4.0, `TraversalEngine` is no longer in `gremlin-core` and can instead be found in `gremlin-test` as it is effectively a ""test-only"" component and serves no other real function. As explained in the javadocs going back to 3.2.0, providers should implement the `Computer` class and use that instead. At this point, graph providers should have long ago moved to the `Computer` infrastructure as methods for constructing a `TraversalSource` with a `TraversalEngine` were long ago removed. See: link:https://issues.apache.org/jira/browse/TINKERPOP-1143[TINKERPOP-1143] ===== Upsert Graph Feature Some `Graph` implementations may be able to offer upsert functionality for vertices and edges, which can help improve usability and performance. To help make it clear to users that a graph operates in this fashion, the `supportsUpsert()` feature has been added to both `Graph.VertexFeatures` and `Graph.EdgeFeatures`. By default, both of these methods will return `false`. Should a provider wish to support this feature, the behavior of `addV()` and/or `addE()` should change such that when a vertex or edge with the same identifier is provided, the respective step will insert the new element if that value is not present or update an existing element if it is found. The method by which the provider ""identifies"" an element is completely up to the capabilities of that provider. In the most simple fashion, a graph could simply check the value of the supplied `T.id`, however graphs that support some form of schema will likely have other methods for determining whether or not an existing element is present. The extent to which TinkerPop tests ""upsert"" is fairly narrow. Graph providers that choose to support this feature should consider their own test suites carefully to ensure appropriate coverage. See: link:https://issues.apache.org/jira/browse/TINKERPOP-1685[TINKERPOP-1685] ===== TypeTranslator Changes The `TypeTranslator` experienced a change in its API and `GroovyTranslator` a change in expectations. `TypeTranslator` now implements `BiFunction` and takes the graph traversal source name as an argument along with the object to translate. This interface is implemented by default for Groovy with `GroovyTranslator.DefaultTypeTranslator` which encapsulates all the functionality of what `GroovyTranslator` formerly did by default. To provide customize translation, simply extend the `DefaultTypeTranslator` and override the methods. `GroovyTranslator` now expects that the `TypeTranslator` provide to it as part of its `of()` static method overload is ""complete"" - i.e. that it provides all the functionality to translate the types passed to it. Thus, a ""complete"" `TypeTranslator` is one that does everything that `DefaultTypeTranslator` does as a minimum requirement. Therefore, the extension model described above is the easiest way to get going with a custom `TypeTranslator` approach. See: link:https://issues.apache.org/jira/browse/TINKERPOP-2072[TINKERPOP-2072] ==== Graph Driver Providers ===== Deprecation Removal in RemoteConnection The two deprecated synchronous `submit()` methods on the `RemoteConnection` interface have been removed, which means that `RemoteConnection` implementations will need to implement `submitAsync(Bytecode)` if they have not already done so. See: link:https://issues.apache.org/jira/browse/TINKERPOP-2103[TINKERPOP-2103] ",12089,False,2272.0373095031728,median "// Copyright (c) YugaByte, 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. // #include ""yb/docdb/cql_operation.h"" #include #include #include #include #include #include #include ""yb/common/index.h"" #include ""yb/common/jsonb.h"" #include ""yb/common/partition.h"" #include ""yb/common/ql_protocol_util.h"" #include ""yb/common/ql_resultset.h"" #include ""yb/common/ql_storage_interface.h"" #include ""yb/common/ql_value.h"" #include ""yb/docdb/doc_ql_scanspec.h"" #include ""yb/docdb/docdb_debug.h"" #include ""yb/docdb/docdb_rocksdb_util.h"" #include ""yb/docdb/docdb_util.h"" #include ""yb/docdb/primitive_value_util.h"" #include ""yb/util/bfpg/tserver_opcodes.h"" #include ""yb/util/flag_tags.h"" #include ""yb/util/status.h"" #include ""yb/util/trace.h"" #include ""yb/yql/cql/ql/util/errcodes.h"" DEFINE_test_flag(bool, pause_write_apply_after_if, false, ""Pause application of QLWriteOperation after evaluating if condition.""); DEFINE_bool(ycql_consistent_transactional_paging, false, ""Whether to enforce consistency of data returned for second page and beyond for YCQL "" ""queries on transactional tables. If true, read restart errors could be returned to "" ""prevent inconsistency. If false, no read restart errors are returned but the data may "" ""be stale. The latter is preferable for long scans. The data returned for the first "" ""page of results is never stale regardless of this flag.""); DEFINE_bool(ycql_disable_index_updating_optimization, false, ""If true all secondary indexes must be updated even if the update does not change "" ""the index data.""); TAG_FLAG(ycql_disable_index_updating_optimization, advanced); namespace yb { namespace docdb { using std::pair; using std::unordered_map; using std::unordered_set; using std::vector; namespace { // Append dummy entries in schema to table_row // TODO(omer): this should most probably be added somewhere else void AddProjection(const Schema& schema, QLTableRow* table_row) { for (size_t i = 0; i < schema.num_columns(); i++) { const auto& column_id = schema.column_id(i); table_row->AllocColumn(column_id); } } // Create projection schemas of static and non-static columns from a rowblock projection schema // (for read) and a WHERE / IF condition (for read / write). ""schema"" is the full table schema // and ""rowblock_schema"" is the selected columns from which we are splitting into static and // non-static column portions. CHECKED_STATUS CreateProjections(const Schema& schema, const QLReferencedColumnsPB& column_refs, Schema* static_projection, Schema* non_static_projection) { // The projection schemas are used to scan docdb. unordered_set static_columns, non_static_columns; // Add regular columns. for (int32_t id : column_refs.ids()) { const ColumnId column_id(id); if (!schema.is_key_column(column_id)) { non_static_columns.insert(column_id); } } // Add static columns. for (int32_t id : column_refs.static_ids()) { const ColumnId column_id(id); static_columns.insert(column_id); } RETURN_NOT_OK( schema.CreateProjectionByIdsIgnoreMissing( vector(static_columns.begin(), static_columns.end()), static_projection)); RETURN_NOT_OK( schema.CreateProjectionByIdsIgnoreMissing( vector(non_static_columns.begin(), non_static_columns.end()), non_static_projection)); return Status::OK(); } CHECKED_STATUS PopulateRow(const QLTableRow& table_row, const Schema& schema, const size_t begin_idx, const size_t col_count, QLRow* row, size_t *col_idx) { for (size_t i = begin_idx; i < begin_idx + col_count; i++) { RETURN_NOT_OK(table_row.GetValue(schema.column_id(i), row->mutable_column((*col_idx)++))); } return Status::OK(); } CHECKED_STATUS PopulateRow(const QLTableRow& table_row, const Schema& projection, QLRow* row, size_t* col_idx) { return PopulateRow(table_row, projection, 0, projection.num_columns(), row, col_idx); } // Outer join a static row with a non-static row. // A join is successful if and only if for every hash key, the values in the static and the // non-static row are either non-NULL and the same, or one of them is NULL. Therefore we say that // a join is successful if the static row is empty, and in turn return true. // Copies the entries from the static row into the non-static one. bool JoinStaticRow( const Schema& schema, const Schema& static_projection, const QLTableRow& static_row, QLTableRow* non_static_row) { // The join is successful if the static row is empty if (static_row.IsEmpty()) { return true; } // Now we know that the static row is not empty. The non-static row cannot be empty, therefore // we know that both the static row and the non-static one have non-NULL entries for all // hash keys. Therefore if MatchColumn returns false, we know the join is unsuccessful. // TODO(neil) // - Need to assign TTL and WriteTime to their default values. // - Check if they should be compared and copied over. Most likely not needed as we don't allow // selecting TTL and WriteTime for static columns. // - This copying function should be moved to QLTableRow class. for (size_t i = 0; i < schema.num_hash_key_columns(); i++) { if (!non_static_row->MatchColumn(schema.column_id(i), static_row)) { return false; } } // Join the static columns in the static row into the non-static row. for (size_t i = 0; i < static_projection.num_columns(); i++) { non_static_row->CopyColumn(static_projection.column_id(i), static_row); } return true; } // Join a non-static row with a static row. // Returns true if the two rows match bool JoinNonStaticRow( const Schema& schema, const Schema& static_projection, const QLTableRow& non_static_row, QLTableRow* static_row) { bool join_successful = true; for (size_t i = 0; i < schema.num_hash_key_columns(); i++) { if (!static_row->MatchColumn(schema.column_id(i), non_static_row)) { join_successful = false; break; } } if (!join_successful) { static_row->Clear(); for (size_t i = 0; i < static_projection.num_columns(); i++) { static_row->AllocColumn(static_projection.column_id(i)); } for (size_t i = 0; i < schema.num_hash_key_columns(); i++) { static_row->CopyColumn(schema.column_id(i), non_static_row); } } return join_successful; } CHECKED_STATUS FindMemberForIndex(const QLColumnValuePB& column_value, size_t index, rapidjson::Value* document, rapidjson::Value::MemberIterator* memberit, rapidjson::Value::ValueIterator* valueit, bool* last_elem_object, bool is_insert) { *last_elem_object = false; int64_t array_index; if (document->IsArray()) { util::VarInt varint; RETURN_NOT_OK(varint.DecodeFromComparable( column_value.json_args(index).operand().value().varint_value())); array_index = VERIFY_RESULT(varint.ToInt64()); if (array_index >= document->GetArray().Size() || array_index < 0) { return STATUS_SUBSTITUTE(QLError, ""Array index out of bounds: "", array_index); } *valueit = document->Begin(); std::advance(*valueit, array_index); } else if (document->IsObject()) { if (!is_insert) { util::VarInt varint; auto status = varint.DecodeFromComparable(column_value.json_args(index).operand().value().varint_value()); if (status.ok()) { array_index = VERIFY_RESULT(varint.ToInt64()); return STATUS_SUBSTITUTE(QLError, ""Cannot use array index $0 to access object"", array_index); } } *last_elem_object = true; const auto& member = column_value.json_args(index).operand().value().string_value().c_str(); *memberit = document->FindMember(member); if (*memberit == document->MemberEnd()) { return STATUS_SUBSTITUTE(QLError, ""Could not find member: "", member); } } else { return STATUS_SUBSTITUTE(QLError, ""JSON field is invalid"", column_value.ShortDebugString()); } return Status::OK(); } CHECKED_STATUS CheckUserTimestampForCollections(const UserTimeMicros user_timestamp) { if (user_timestamp != Value::kInvalidUserTimestamp) { return STATUS(InvalidArgument, ""User supplied timestamp is only allowed for "" ""replacing the whole collection""); } return Status::OK(); } } // namespace QLWriteOperation::QLWriteOperation(std::shared_ptr schema, const IndexMap& index_map, const Schema* unique_index_key_schema, const TransactionOperationContextOpt& txn_op_context) : schema_(std::move(schema)), index_map_(index_map), unique_index_key_schema_(unique_index_key_schema), txn_op_context_(txn_op_context) {} Status QLWriteOperation::Init(QLWriteRequestPB* request, QLResponsePB* response) { request_.Swap(request); response_ = response; insert_into_unique_index_ = request_.type() == QLWriteRequestPB::QL_STMT_INSERT && unique_index_key_schema_ != nullptr; require_read_ = RequireRead(request_, *schema_) || insert_into_unique_index_; update_indexes_ = !request_.update_index_ids().empty(); // Determine if static / non-static columns are being written. bool write_static_columns = false; bool write_non_static_columns = false; // TODO(Amit): Remove the DVLOGS after backfill features stabilize. DVLOG(4) << ""Processing request "" << yb::ToString(*request); for (const auto& column : request_.column_values()) { DVLOG(4) << ""Looking at column : "" << yb::ToString(column); auto schema_column = schema_->column_by_id(ColumnId(column.column_id())); DVLOG(4) << ""schema column : "" << yb::ToString(schema_column); RETURN_NOT_OK(schema_column); if (schema_column->is_static()) { write_static_columns = true; } else { write_non_static_columns = true; } if (write_static_columns && write_non_static_columns) { break; } } bool is_range_operation = IsRangeOperation(request_, *schema_); // We need the hashed key if writing to the static columns, and need primary key if writing to // non-static columns or writing the full primary key (i.e. range columns are present or table // does not have range columns). return InitializeKeys( write_static_columns || is_range_operation, write_non_static_columns || !request_.range_column_values().empty() || schema_->num_range_key_columns() == 0); } Status QLWriteOperation::InitializeKeys(const bool hashed_key, const bool primary_key) { // Populate the hashed and range components in the same order as they are in the table schema. const auto& hashed_column_values = request_.hashed_column_values(); const auto& range_column_values = request_.range_column_values(); std::vector hashed_components; std::vector range_components; RETURN_NOT_OK(QLKeyColumnValuesToPrimitiveValues( hashed_column_values, *schema_, 0, schema_->num_hash_key_columns(), &hashed_components)); RETURN_NOT_OK(QLKeyColumnValuesToPrimitiveValues( range_column_values, *schema_, schema_->num_hash_key_columns(), schema_->num_range_key_columns(), &range_components)); // need_pk - true is we should construct pk_key_key_ const bool need_pk = primary_key && !pk_doc_key_; // We need the hash key if writing to the static columns. if (hashed_key && !hashed_doc_key_) { if (need_pk) { hashed_doc_key_.emplace(request_.hash_code(), hashed_components); } else { hashed_doc_key_.emplace(request_.hash_code(), std::move(hashed_components)); } encoded_hashed_doc_key_ = hashed_doc_key_->EncodeAsRefCntPrefix(); } // We need the primary key if writing to non-static columns or writing the full primary key // (i.e. range columns are present). if (need_pk) { if (request_.has_hash_code() && !hashed_column_values.empty()) { pk_doc_key_.emplace( request_.hash_code(), std::move(hashed_components), std::move(range_components)); } else { // In case of syscatalog tables, we don't have any hash components. pk_doc_key_.emplace(std::move(range_components)); } encoded_pk_doc_key_ = pk_doc_key_->EncodeAsRefCntPrefix(); } return Status::OK(); } Status QLWriteOperation::GetDocPaths( GetDocPathsMode mode, DocPathsToLock *paths, IsolationLevel *level) const { if (mode == GetDocPathsMode::kLock || request_.column_values().empty()) { if (encoded_hashed_doc_key_) { paths->push_back(encoded_hashed_doc_key_); } if (encoded_pk_doc_key_) { paths->push_back(encoded_pk_doc_key_); } } else { KeyBytes buffer; for (const auto& column_value : request_.column_values()) { ColumnId column_id(column_value.column_id()); const ColumnSchema& column = VERIFY_RESULT(schema_->column_by_id(column_id)); Slice doc_key = column.is_static() ? encoded_hashed_doc_key_.as_slice() : encoded_pk_doc_key_.as_slice(); buffer.Clear(); buffer.AppendValueType(ValueType::kColumnId); buffer.AppendColumnId(column_id); RefCntBuffer path(doc_key.size() + buffer.size()); memcpy(path.data(), doc_key.data(), doc_key.size()); buffer.AsSlice().CopyTo(path.data() + doc_key.size()); paths->push_back(RefCntPrefix(path)); } } // When this write operation requires a read, it requires a read snapshot so paths will be locked // in snapshot isolation for consistency. Otherwise, pure writes will happen in serializable // isolation so that they will serialize but do not conflict with one another. // // Currently, only keys that are being written are locked, no lock is taken on read at the // snapshot isolation level. *level = require_read_ ? IsolationLevel::SNAPSHOT_ISOLATION : IsolationLevel::SERIALIZABLE_ISOLATION; return Status::OK(); } Status QLWriteOperation::ReadColumns(const DocOperationApplyData& data, Schema *param_static_projection, Schema *param_non_static_projection, QLTableRow* table_row) { Schema *static_projection = param_static_projection; Schema *non_static_projection = param_non_static_projection; Schema local_static_projection; Schema local_non_static_projection; if (static_projection == nullptr) { static_projection = &local_static_projection; } if (non_static_projection == nullptr) { non_static_projection = &local_non_static_projection; } // Create projections to scan docdb. RETURN_NOT_OK(CreateProjections(*schema_, request_.column_refs(), static_projection, non_static_projection)); // Generate hashed / primary key depending on if static / non-static columns are referenced in // the if-condition. RETURN_NOT_OK(InitializeKeys( !static_projection->columns().empty(), !non_static_projection->columns().empty())); // Scan docdb for the static and non-static columns of the row using the hashed / primary key. if (hashed_doc_key_) { DocQLScanSpec spec(*static_projection, *hashed_doc_key_, request_.query_id()); DocRowwiseIterator iterator(*static_projection, *schema_, txn_op_context_, data.doc_write_batch->doc_db(), data.deadline, data.read_time); RETURN_NOT_OK(iterator.Init(spec)); if (VERIFY_RESULT(iterator.HasNext())) { RETURN_NOT_OK(iterator.NextRow(table_row)); } data.restart_read_ht->MakeAtLeast(iterator.RestartReadHt()); } if (pk_doc_key_) { DocQLScanSpec spec(*non_static_projection, *pk_doc_key_, request_.query_id()); DocRowwiseIterator iterator(*non_static_projection, *schema_, txn_op_context_, data.doc_write_batch->doc_db(), data.deadline, data.read_time); RETURN_NOT_OK(iterator.Init(spec)); if (VERIFY_RESULT(iterator.HasNext())) { RETURN_NOT_OK(iterator.NextRow(table_row)); // If there are indexes to update, check if liveness column exists for update/delete because // that will affect whether the row will still exist after the DML and whether we need to // remove the key from the indexes. if (update_indexes_ && (request_.type() == QLWriteRequestPB::QL_STMT_UPDATE || request_.type() == QLWriteRequestPB::QL_STMT_DELETE)) { liveness_column_exists_ = iterator.LivenessColumnExists(); } } else { // If no non-static column is found, the row does not exist and we should clear the static // columns in the map to indicate the row does not exist. table_row->Clear(); } data.restart_read_ht->MakeAtLeast(iterator.RestartReadHt()); } return Status::OK(); } Status QLWriteOperation::PopulateConditionalDmlRow(const DocOperationApplyData& data, const bool should_apply, const QLTableRow& table_row, Schema static_projection, Schema non_static_projection, std::unique_ptr* rowblock) { // Populate the result set to return the ""applied"" status, and optionally the hash / primary key // and the present column values if the condition is not satisfied and the row does exist // (value_map is not empty). const bool return_present_values = !should_apply && !table_row.IsEmpty(); const size_t num_key_columns = pk_doc_key_ ? schema_->num_key_columns() : schema_->num_hash_key_columns(); std::vector columns; columns.emplace_back(ColumnSchema(""[applied]"", BOOL)); if (return_present_values) { columns.insert(columns.end(), schema_->columns().begin(), schema_->columns().begin() + num_key_columns); columns.insert(columns.end(), static_projection.columns().begin(), static_projection.columns().end()); columns.insert(columns.end(), non_static_projection.columns().begin(), non_static_projection.columns().end()); } rowblock->reset(new QLRowBlock(Schema(columns, 0))); QLRow& row = rowblock->get()->Extend(); row.mutable_column(0)->set_bool_value(should_apply); size_t col_idx = 1; if (return_present_values) { RETURN_NOT_OK(PopulateRow(table_row, *schema_, 0, num_key_columns, &row, &col_idx)); RETURN_NOT_OK(PopulateRow(table_row, static_projection, &row, &col_idx)); RETURN_NOT_OK(PopulateRow(table_row, non_static_projection, &row, &col_idx)); } return Status::OK(); } Status QLWriteOperation::PopulateStatusRow(const DocOperationApplyData& data, const bool should_apply, const QLTableRow& table_row, std::unique_ptr* rowblock) { std::vector columns; columns.emplace_back(ColumnSchema(""[applied]"", BOOL)); columns.emplace_back(ColumnSchema(""[message]"", STRING)); columns.insert(columns.end(), schema_->columns().begin(), schema_->columns().end()); rowblock->reset(new QLRowBlock(Schema(columns, 0))); QLRow& row = rowblock->get()->Extend(); row.mutable_column(0)->set_bool_value(should_apply); // No message unless there is an error (then message will be set in executor). // If not applied report the existing row values as for regular if clause. if (!should_apply) { for (size_t i = 0; i < schema_->num_columns(); i++) { boost::optional col_val = table_row.GetValue(schema_->column_id(i)); if (col_val.is_initialized()) { *(row.mutable_column(i + 2)) = *col_val; } } } return Status::OK(); } // Check if a duplicate value is inserted into a unique index. Result QLWriteOperation::HasDuplicateUniqueIndexValue(const DocOperationApplyData& data) { VLOG(3) << ""Looking for collisions in\\n"" << docdb::DocDBDebugDumpToStr(data.doc_write_batch->doc_db()); // We need to check backwards only for backfilled entries. bool ret = VERIFY_RESULT(HasDuplicateUniqueIndexValue(data, Direction::kForward)) || (request_.is_backfill() && VERIFY_RESULT(HasDuplicateUniqueIndexValue(data, Direction::kBackward))); if (!ret) { VLOG(3) << ""No collisions found""; } return ret; } Result QLWriteOperation::HasDuplicateUniqueIndexValue( const DocOperationApplyData& data, Direction direction) { VLOG(2) << ""Looking for collision while going "" << yb::ToString(direction) << "". Trying to insert "" << *pk_doc_key_; auto requested_read_time = data.read_time; if (direction == Direction::kForward) { return HasDuplicateUniqueIndexValue(data, requested_read_time); } auto iter = CreateIntentAwareIterator( data.doc_write_batch->doc_db(), BloomFilterMode::USE_BLOOM_FILTER, pk_doc_key_->Encode().AsSlice(), request_.query_id(), txn_op_context_, data.deadline, ReadHybridTime::Max()); HybridTime oldest_past_min_ht = VERIFY_RESULT(FindOldestOverwrittenTimestamp( iter.get(), SubDocKey(*pk_doc_key_), requested_read_time.read)); const HybridTime oldest_past_min_ht_liveness = VERIFY_RESULT(FindOldestOverwrittenTimestamp( iter.get(), SubDocKey(*pk_doc_key_, PrimitiveValue::SystemColumnId(SystemColumnIds::kLivenessColumn)), requested_read_time.read)); oldest_past_min_ht.MakeAtMost(oldest_past_min_ht_liveness); if (!oldest_past_min_ht.is_valid()) { return false; } return HasDuplicateUniqueIndexValue( data, ReadHybridTime::SingleTime(oldest_past_min_ht)); } Result QLWriteOperation::HasDuplicateUniqueIndexValue( const DocOperationApplyData& data, ReadHybridTime read_time) { // Set up the iterator to read the current primary key associated with the index key. DocQLScanSpec spec(*unique_index_key_schema_, *pk_doc_key_, request_.query_id(), true); DocRowwiseIterator iterator( *unique_index_key_schema_, *schema_, txn_op_context_, data.doc_write_batch->doc_db(), data.deadline, read_time); RETURN_NOT_OK(iterator.Init(spec)); // It is a duplicate value if the index key exists already and the index value (corresponding to // the indexed table's primary key) is not the same. if (!VERIFY_RESULT(iterator.HasNext())) { VLOG(2) << ""No collision found while checking at "" << yb::ToString(read_time); return false; } QLTableRow table_row; RETURN_NOT_OK(iterator.NextRow(&table_row)); std::unordered_set key_column_ids(unique_index_key_schema_->column_ids().begin(), unique_index_key_schema_->column_ids().end()); for (const auto& column_value : request_.column_values()) { ColumnId column_id(column_value.column_id()); if (key_column_ids.count(column_id) > 0) { boost::optional existing_value = table_row.GetValue(column_id); const QLValuePB& new_value = column_value.expr().value(); if (existing_value && *existing_value != new_value) { VLOG(2) << ""Found collision while checking at "" << yb::ToString(read_time) << ""\\nExisting: "" << yb::ToString(*existing_value) << "" vs New: "" << yb::ToString(new_value) << ""\\nUsed read time as "" << yb::ToString(data.read_time); DVLOG(3) << ""DocDB is now:\\n"" << docdb::DocDBDebugDumpToStr(data.doc_write_batch->doc_db()); return true; } } } VLOG(2) << ""No collision while checking at "" << yb::ToString(read_time); return false; } Result QLWriteOperation::FindOldestOverwrittenTimestamp( IntentAwareIterator* iter, const SubDocKey& sub_doc_key, HybridTime min_read_time) { HybridTime result; VLOG(3) << ""Doing iter->Seek "" << *pk_doc_key_; iter->Seek(*pk_doc_key_); if (iter->valid()) { const KeyBytes bytes = sub_doc_key.EncodeWithoutHt(); const Slice& sub_key_slice = bytes.AsSlice(); result = VERIFY_RESULT( iter->FindOldestRecord(sub_key_slice, min_read_time)); VLOG(2) << ""iter->FindOldestRecord returned "" << result << "" for "" << SubDocKey::DebugSliceToString(sub_key_slice); } else { VLOG(3) << ""iter->Seek "" << *pk_doc_key_ << "" turned out to be invalid""; } return result; } Status QLWriteOperation::ApplyForJsonOperators(const QLColumnValuePB& column_value, const DocOperationApplyData& data, const DocPath& sub_path, const MonoDelta& ttl, const UserTimeMicros& user_timestamp, const ColumnSchema& column, QLTableRow* existing_row, bool is_insert) { using common::Jsonb; // Read the json column value inorder to perform a read modify write. QLExprResult temp; rapidjson::Document document; RETURN_NOT_OK(existing_row->ReadColumn(column_value.column_id(), temp.Writer())); const auto& ql_value = temp.Value(); if (!IsNull(ql_value)) { Jsonb jsonb(std::move(ql_value.jsonb_value())); RETURN_NOT_OK(jsonb.ToRapidJson(&document)); } else { if (!is_insert && column_value.json_args_size() > 1) { return STATUS_SUBSTITUTE(QLError, ""JSON path depth should be 1 for upsert"", column_value.ShortDebugString()); } common::Jsonb empty_jsonb; RETURN_NOT_OK(empty_jsonb.FromString(""{}"")); QLTableColumn& column = existing_row->AllocColumn(column_value.column_id()); column.value.set_jsonb_value(empty_jsonb.MoveSerializedJsonb()); Jsonb jsonb(column.value.jsonb_value()); RETURN_NOT_OK(jsonb.ToRapidJson(&document)); } // Deserialize the rhs. Jsonb rhs(std::move(column_value.expr().value().jsonb_value())); rapidjson::Document rhs_doc; RETURN_NOT_OK(rhs.ToRapidJson(&rhs_doc)); // Update the json value. rapidjson::Value::MemberIterator memberit; rapidjson::Value::ValueIterator valueit; bool last_elem_object; rapidjson::Value* node = &document; int i = 0; auto status = FindMemberForIndex(column_value, i, node, &memberit, &valueit, &last_elem_object, is_insert); for (i = 1; i < column_value.json_args_size() && status.ok(); i++) { node = (last_elem_object) ? &(memberit->value) : &(*valueit); status = FindMemberForIndex(column_value, i, node, &memberit, &valueit, &last_elem_object, is_insert); } bool update_missing = false; if (is_insert) { RETURN_NOT_OK(status); } else { update_missing = !status.ok(); } if (update_missing) { // NOTE: lhs path cannot exceed by more than one hop if (last_elem_object && i == column_value.json_args_size()) { auto val = column_value.json_args(i - 1).operand().value().string_value(); rapidjson::Value v(val.c_str(), val.size(), document.GetAllocator()); node->AddMember(v, rhs_doc, document.GetAllocator()); } else { RETURN_NOT_OK(status); } } else if (last_elem_object) { memberit->value = rhs_doc.Move(); } else { *valueit = rhs_doc.Move(); } // Now write the new json value back. QLValue result; Jsonb jsonb_result; RETURN_NOT_OK(jsonb_result.FromRapidJson(document)); *result.mutable_jsonb_value() = std::move(jsonb_result.MoveSerializedJsonb()); const SubDocument& sub_doc = SubDocument::FromQLValuePB(result.value(), column.sorting_type(), yb::bfql::TSOpcode::kScalarInsert); RETURN_NOT_OK(data.doc_write_batch->InsertSubDocument( sub_path, sub_doc, data.read_time, data.deadline, request_.query_id(), ttl, user_timestamp)); // Update the current row as well so that we can accumulate the result of multiple json // operations and write the final value. existing_row->AllocColumn(column_value.column_id()).value = result.value(); return Status::OK(); } Status QLWriteOperation::ApplyForSubscriptArgs(const QLColumnValuePB& column_value, const QLTableRow& existing_row, const DocOperationApplyData& data, const MonoDelta& ttl, const UserTimeMicros& user_timestamp, const ColumnSchema& column, DocPath* sub_path) { QLExprResult expr_result; RETURN_NOT_OK(EvalExpr(column_value.expr(), existing_row, expr_result.Writer())); const yb::bfql::TSOpcode write_instr = GetTSWriteInstruction(column_value.expr()); const SubDocument& sub_doc = SubDocument::FromQLValuePB(expr_result.Value(), column.sorting_type(), write_instr); RETURN_NOT_OK(CheckUserTimestampForCollections(user_timestamp)); // Setting the value for a sub-column // Currently we only support two cases here: `map['key'] = v` and `list[index] = v`) // Any other case should be rejected by the semantic analyser before getting here // Later when we support frozen or nested collections this code may need refactoring DCHECK_EQ(column_value.subscript_args().size(), 1); DCHECK(column_value.subscript_args(0).has_value()) << ""An index must be a constant""; switch (column.type()->main()) { case MAP: { const PrimitiveValue &pv = PrimitiveValue::FromQLValuePB( column_value.subscript_args(0).value(), ColumnSchema::SortingType::kNotSpecified); sub_path->AddSubKey(pv); RETURN_NOT_OK(data.doc_write_batch->InsertSubDocument( *sub_path, sub_doc, data.read_time, data.deadline, request_.query_id(), ttl, user_timestamp)); break; } case LIST: { MonoDelta default_ttl = schema_->table_properties().HasDefaultTimeToLive() ? MonoDelta::FromMilliseconds(schema_->table_properties().DefaultTimeToLive()) : MonoDelta::kMax; int target_cql_index = column_value.subscript_args(0).value().int32_value(); RETURN_NOT_OK(data.doc_write_batch->ReplaceCqlInList( *sub_path, target_cql_index, sub_doc, data.read_time, data.deadline, request_.query_id(), default_ttl, ttl)); break; } default: { LOG(ERROR) << ""Unexpected type for setting subcolumn: "" << column.type()->ToString(); } } return Status::OK(); } Status QLWriteOperation::ApplyForRegularColumns(const QLColumnValuePB& column_value, const QLTableRow& existing_row, const DocOperationApplyData& data, const DocPath& sub_path, const MonoDelta& ttl, const UserTimeMicros& user_timestamp, const ColumnSchema& column, const ColumnId& column_id, QLTableRow* new_row) { using yb::bfql::TSOpcode; // Typical case, setting a columns value QLExprResult expr_result; RETURN_NOT_OK(EvalExpr(column_value.expr(), existing_row, expr_result.Writer())); const TSOpcode write_instr = GetTSWriteInstruction(column_value.expr()); const SubDocument& sub_doc = SubDocument::FromQLValuePB(expr_result.Value(), column.sorting_type(), write_instr); switch (write_instr) { case TSOpcode::kToJson: FALLTHROUGH_INTENDED; case TSOpcode::kScalarInsert: RETURN_NOT_OK(data.doc_write_batch->InsertSubDocument( sub_path, sub_doc, data.read_time, data.deadline, request_.query_id(), ttl, user_timestamp)); break; case TSOpcode::kMapExtend: case TSOpcode::kSetExtend: case TSOpcode::kMapRemove: case TSOpcode::kSetRemove: RETURN_NOT_OK(CheckUserTimestampForCollections(user_timestamp)); RETURN_NOT_OK(data.doc_write_batch->ExtendSubDocument( sub_path, sub_doc, data.read_time, data.deadline, request_.query_id(), ttl)); break; case TSOpcode::kListPrepend: sub_doc.SetExtendOrder(ListExtendOrder::PREPEND_BLOCK); FALLTHROUGH_INTENDED; case TSOpcode::kListAppend: RETURN_NOT_OK(CheckUserTimestampForCollections(user_timestamp)); RETURN_NOT_OK(data.doc_write_batch->ExtendList( sub_path, sub_doc, data.read_time, data.deadline, request_.query_id(), ttl)); break; case TSOpcode::kListRemove: // TODO(akashnil or mihnea) this should call RemoveFromList once thats implemented // Currently list subtraction is computed in memory using builtin call so this // case should never be reached. Once it is implemented the corresponding case // from EvalQLExpressionPB should be uncommented to enable this optimization. RETURN_NOT_OK(CheckUserTimestampForCollections(user_timestamp)); RETURN_NOT_OK(data.doc_write_batch->InsertSubDocument( sub_path, sub_doc, data.read_time, data.deadline, request_.query_id(), ttl, user_timestamp)); break; default: LOG(FATAL) << ""Unsupported operation: "" << static_cast(write_instr); break; } if (update_indexes_) { new_row->AllocColumn(column_id, expr_result.Value()); } return Status::OK(); } Status QLWriteOperation::Apply(const DocOperationApplyData& data) { QLTableRow existing_row; if (request_.has_if_expr()) { // Check if the if-condition is satisfied. bool should_apply = true; Schema static_projection, non_static_projection; RETURN_NOT_OK(ReadColumns(data, &static_projection, &non_static_projection, &existing_row)); RETURN_NOT_OK(EvalCondition(request_.if_expr().condition(), existing_row, &should_apply)); // Set the response accordingly. response_->set_applied(should_apply); if (!should_apply && request_.else_error()) { return ql::ErrorStatus(ql::ErrorCode::CONDITION_NOT_SATISFIED); // QLError } else if (request_.returns_status()) { RETURN_NOT_OK(PopulateStatusRow(data, should_apply, existing_row, &rowblock_)); } else { RETURN_NOT_OK(PopulateConditionalDmlRow(data, should_apply, existing_row, static_projection, non_static_projection, &rowblock_)); } // If we do not need to apply we are already done. if (!should_apply) { response_->set_status(QLResponsePB::YQL_STATUS_OK); return Status::OK(); } TEST_PAUSE_IF_FLAG(TEST_pause_write_apply_after_if); } else if (RequireReadForExpressions(request_) || request_.returns_status()) { RETURN_NOT_OK(ReadColumns(data, nullptr, nullptr, &existing_row)); if (request_.returns_status()) { RETURN_NOT_OK(PopulateStatusRow(data, /* should_apply = */ true, existing_row, &rowblock_)); } } VLOG(3) << ""insert_into_unique_index_ is "" << insert_into_unique_index_; if (insert_into_unique_index_ && VERIFY_RESULT(HasDuplicateUniqueIndexValue(data))) { VLOG(3) << ""set_applied is set to "" << false << "" for over "" << yb::ToString(existing_row); response_->set_applied(false); response_->set_status(QLResponsePB::YQL_STATUS_OK); return Status::OK(); } const MonoDelta ttl = request_.has_ttl() ? MonoDelta::FromMilliseconds(request_.ttl()) : Value::kMaxTtl; const UserTimeMicros user_timestamp = request_.has_user_timestamp_usec() ? request_.user_timestamp_usec() : Value::kInvalidUserTimestamp; // Initialize the new row being written to either the existing row if read, or just populate // the primary key. QLTableRow new_row; if (!existing_row.IsEmpty()) { new_row = existing_row; } else { size_t idx = 0; for (const QLExpressionPB& expr : request_.hashed_column_values()) { new_row.AllocColumn(schema_->column_id(idx), expr.value()); idx++; } for (const QLExpressionPB& expr : request_.range_column_values()) { new_row.AllocColumn(schema_->column_id(idx), expr.value()); idx++; } } switch (request_.type()) { // QL insert == update (upsert) to be consistent with Cassandra's semantics. In either // INSERT or UPDATE, if non-key columns are specified, they will be inserted which will cause // the primary key to be inserted also when necessary. Otherwise, we should insert the // primary key at least. case QLWriteRequestPB::QL_STMT_INSERT: case QLWriteRequestPB::QL_STMT_UPDATE: { // Add the appropriate liveness column only for inserts. // We never use init markers for QL to ensure we perform writes without any reads to // ensure our write path is fast while complicating the read path a bit. auto is_insert = request_.type() == QLWriteRequestPB::QL_STMT_INSERT; if (is_insert && encoded_pk_doc_key_) { const DocPath sub_path(encoded_pk_doc_key_.as_slice(), PrimitiveValue::SystemColumnId(SystemColumnIds::kLivenessColumn)); const auto value = Value(PrimitiveValue(), ttl, user_timestamp); RETURN_NOT_OK(data.doc_write_batch->SetPrimitive( sub_path, value, data.read_time, data.deadline, request_.query_id())); } for (const auto& column_value : request_.column_values()) { if (!column_value.has_column_id()) { return STATUS_FORMAT(InvalidArgument, ""column id missing: $0"", column_value.DebugString()); } const ColumnId column_id(column_value.column_id()); const auto maybe_column = schema_->column_by_id(column_id); RETURN_NOT_OK(maybe_column); const ColumnSchema& column = *maybe_column; DocPath sub_path( column.is_static() ? encoded_hashed_doc_key_.as_slice() : encoded_pk_doc_key_.as_slice(), PrimitiveValue(column_id)); QLValue expr_result; if (!column_value.json_args().empty()) { RETURN_NOT_OK(ApplyForJsonOperators(column_value, data, sub_path, ttl, user_timestamp, column, &new_row, is_insert)); } else if (!column_value.subscript_args().empty()) { RETURN_NOT_OK(ApplyForSubscriptArgs(column_value, existing_row, data, ttl, user_timestamp, column, &sub_path)); } else { RETURN_NOT_OK(ApplyForRegularColumns(column_value, existing_row, data, sub_path, ttl, user_timestamp, column, column_id, &new_row)); } } if (update_indexes_) { RETURN_NOT_OK(UpdateIndexes(existing_row, new_row)); } break; } case QLWriteRequestPB::QL_STMT_DELETE: { // We have three cases: // 1. If non-key columns are specified, we delete only those columns. // 2. Otherwise, if range cols are missing, this must be a range delete. // 3. Otherwise, this is a normal delete. // Analyzer ensures these are the only cases before getting here (e.g. range deletes cannot // specify non-key columns). if (request_.column_values_size() > 0) { // Delete the referenced columns only. for (const auto& column_value : request_.column_values()) { CHECK(column_value.has_column_id()) << ""column id missing: "" << column_value.DebugString(); const ColumnId column_id(column_value.column_id()); const auto& column = VERIFY_RESULT_REF(schema_->column_by_id(column_id)); const DocPath sub_path( column.is_static() ? encoded_hashed_doc_key_.as_slice() : encoded_pk_doc_key_.as_slice(), PrimitiveValue(column_id)); RETURN_NOT_OK(data.doc_write_batch->DeleteSubDoc(sub_path, data.read_time, data.deadline, request_.query_id(), user_timestamp)); if (update_indexes_) { new_row.MarkTombstoned(column_id); } } if (update_indexes_) { RETURN_NOT_OK(UpdateIndexes(existing_row, new_row)); } } else if (IsRangeOperation(request_, *schema_)) { // If the range columns are not specified, we read everything and delete all rows for // which the where condition matches. // Create the schema projection -- range deletes cannot reference non-primary key columns, // so the non-static projection is all we need, it should contain all referenced columns. Schema static_projection; Schema projection; RETURN_NOT_OK(CreateProjections(*schema_, request_.column_refs(), &static_projection, &projection)); // Construct the scan spec basing on the WHERE condition. vector hashed_components; RETURN_NOT_OK(QLKeyColumnValuesToPrimitiveValues( request_.hashed_column_values(), *schema_, 0, schema_->num_hash_key_columns(), &hashed_components)); boost::optional hash_code = request_.has_hash_code() ? boost::make_optional(request_.hash_code()) : boost::none; const auto range_covers_whole_partition_key = !request_.has_where_expr(); const auto include_static_columns_in_scan = range_covers_whole_partition_key && schema_->has_statics(); DocQLScanSpec spec(*schema_, hash_code, hash_code, // max hash code. hashed_components, request_.has_where_expr() ? &request_.where_expr().condition() : nullptr, nullptr, request_.query_id(), true /* is_forward_scan */, include_static_columns_in_scan); // Create iterator. DocRowwiseIterator iterator( projection, *schema_, txn_op_context_, data.doc_write_batch->doc_db(), data.deadline, data.read_time); RETURN_NOT_OK(iterator.Init(spec)); // Iterate through rows and delete those that match the condition. // TODO(mihnea): We do not lock here, so other write transactions coming in might appear // partially applied if they happen in the middle of a ranged delete. while (VERIFY_RESULT(iterator.HasNext())) { existing_row.Clear(); RETURN_NOT_OK(iterator.NextRow(&existing_row)); // Match the row with the where condition before deleting it. bool match = false; RETURN_NOT_OK(spec.Match(existing_row, &match)); if (match) { const DocPath row_path(iterator.row_key()); RETURN_NOT_OK(DeleteRow(row_path, data.doc_write_batch, data.read_time, data.deadline)); if (update_indexes_) { liveness_column_exists_ = iterator.LivenessColumnExists(); RETURN_NOT_OK(UpdateIndexes(existing_row, new_row)); } } } data.restart_read_ht->MakeAtLeast(iterator.RestartReadHt()); } else { // Otherwise, delete the referenced row (all columns). RETURN_NOT_OK(DeleteRow(DocPath(encoded_pk_doc_key_.as_slice()), data.doc_write_batch, data.read_time, data.deadline)); if (update_indexes_) { RETURN_NOT_OK(UpdateIndexes(existing_row, new_row)); } } break; } } response_->set_status(QLResponsePB::YQL_STATUS_OK); return Status::OK(); } Status QLWriteOperation::DeleteRow(const DocPath& row_path, DocWriteBatch* doc_write_batch, const ReadHybridTime& read_ht, const CoarseTimePoint deadline) { if (request_.has_user_timestamp_usec()) { // If user_timestamp is provided, we need to add a tombstone for each individual // column in the schema since we don't want to analyze this on the read path. for (int i = schema_->num_key_columns(); i < schema_->num_columns(); i++) { const DocPath sub_path(row_path.encoded_doc_key(), PrimitiveValue(schema_->column_id(i))); RETURN_NOT_OK(doc_write_batch->DeleteSubDoc(sub_path, read_ht, deadline, request_.query_id(), request_.user_timestamp_usec())); } // Delete the liveness column as well. const DocPath liveness_column( row_path.encoded_doc_key(), PrimitiveValue::SystemColumnId(SystemColumnIds::kLivenessColumn)); RETURN_NOT_OK(doc_write_batch->DeleteSubDoc(liveness_column, read_ht, deadline, request_.query_id(), request_.user_timestamp_usec())); } else { RETURN_NOT_OK(doc_write_batch->DeleteSubDoc(row_path, read_ht, deadline)); } return Status::OK(); } namespace { YB_DEFINE_ENUM(ValueState, (kNull)(kNotNull)(kMissing)); ValueState GetValueState(const QLTableRow& row, const ColumnId column_id) { const auto value = row.GetValue(column_id); return !value ? ValueState::kMissing : IsNull(*value) ? ValueState::kNull : ValueState::kNotNull; } } // namespace Result QLWriteOperation::IsRowDeleted(const QLTableRow& existing_row, const QLTableRow& new_row) const { // Delete the whole row? if (request_.type() == QLWriteRequestPB::QL_STMT_DELETE && request_.column_values().empty()) { return true; } if (existing_row.IsEmpty()) { // If the row doesn't exist, don't check further. return false; } // For update/delete, if there is no liveness column, the row will be deleted after the DML unless // a non-null column still remains. if ((request_.type() == QLWriteRequestPB::QL_STMT_UPDATE || request_.type() == QLWriteRequestPB::QL_STMT_DELETE) && !liveness_column_exists_) { for (size_t idx = schema_->num_key_columns(); idx < schema_->num_columns(); idx++) { if (schema_->column(idx).is_static()) { continue; } const ColumnId column_id = schema_->column_id(idx); switch (GetValueState(new_row, column_id)) { case ValueState::kNull: continue; case ValueState::kNotNull: return false; case ValueState::kMissing: break; } switch (GetValueState(existing_row, column_id)) { case ValueState::kNull: continue; case ValueState::kNotNull: return false; case ValueState::kMissing: // In case there exists a row with the same primary key, we definitely need to know if its // columns have value NULL or not. Populate the column before executing this function. RSTATUS_DCHECK(false, InternalError, ""CQL proxy should mention all required columns in "" ""QLWriteRequestPB's column_refs.""); } } return true; } return false; } namespace { QLExpressionPB* NewKeyColumn(QLWriteRequestPB* request, const IndexInfo& index, const size_t idx) { return (idx < index.hash_column_count() ? request->add_hashed_column_values() : request->add_range_column_values()); } QLWriteRequestPB* NewIndexRequest( const IndexInfo& index, QLWriteRequestPB::QLStmtType type, vector>* index_requests) { index_requests->emplace_back(&index, QLWriteRequestPB()); QLWriteRequestPB* const request = &index_requests->back().second; request->set_type(type); return request; } } // namespace Status QLWriteOperation::UpdateIndexes(const QLTableRow& existing_row, const QLTableRow& new_row) { // Prepare the write requests to update the indexes. There should be at most 2 requests for each // index (one insert and one delete). VLOG(2) << ""Updating indexes""; const auto& index_ids = request_.update_index_ids(); index_requests_.reserve(index_ids.size() * 2); for (const TableId& index_id : index_ids) { const IndexInfo* index = VERIFY_RESULT(index_map_.FindIndex(index_id)); bool index_key_changed = false; bool index_pred_existing_row = true; bool index_pred_new_row = true; bool is_row_deleted = VERIFY_RESULT(IsRowDeleted(existing_row, new_row)); if (index->where_predicate_spec()) { RETURN_NOT_OK(EvalCondition( index->where_predicate_spec()->where_expr().condition(), existing_row, &index_pred_existing_row)); } if (is_row_deleted) { // If it is a partial index and predicate wasn't satisfied for the existing row // which is being deleted, we need to do nothing. if (index->where_predicate_spec() && !index_pred_existing_row) { VLOG(3) << ""Skip index entry delete for index_id="" << index->table_id() << "" since predicate not satisfied""; continue; } index_key_changed = true; } else { VERIFY_RESULT(CreateAndSetupIndexInsertRequest( this, index->HasWritePermission(), existing_row, new_row, index, &index_requests_, &index_key_changed, &index_pred_new_row, index_pred_existing_row)); } bool index_pred_switched_to_false = false; if (index->where_predicate_spec() && !existing_row.IsEmpty() && index_pred_existing_row && !index_pred_new_row) index_pred_switched_to_false = true; // If the index key is changed, delete the current key. if ((index_key_changed || index_pred_switched_to_false) && index->HasDeletePermission()) { if (!index_pred_switched_to_false) { // 1. In case of a switch of predicate satisfiability to false, we surely have to delete the // row. (Even if there wasn't any index key change). // 2. But in case of an index key change without predicate satisfiability switch, if the // index predicate was already false for the existing row, we have to do nothing. // TODO(Piyush): Ensure EvalCondition returns an error if some column is missing. if (!index_pred_existing_row) { VLOG(3) << ""Skip index entry delete of existing row for index_id="" << index->table_id() << "" since predicate not satisfied""; return Status::OK(); } } QLWriteRequestPB* const index_request = NewIndexRequest(*index, QLWriteRequestPB::QL_STMT_DELETE, &index_requests_); for (size_t idx = 0; idx < index->key_column_count(); idx++) { const IndexInfo::IndexColumn& index_column = index->column(idx); QLExpressionPB *key_column = NewKeyColumn(index_request, *index, idx); // For old message expr_case() == NOT SET. // For new message expr_case == kColumnId when indexing expression is a column-ref. if (index_column.colexpr.expr_case() != QLExpressionPB::ExprCase::EXPR_NOT_SET && index_column.colexpr.expr_case() != QLExpressionPB::ExprCase::kColumnId) { QLExprResult result; RETURN_NOT_OK(EvalExpr(index_column.colexpr, existing_row, result.Writer())); result.MoveTo(key_column->mutable_value()); } else { auto result = existing_row.GetValue(index_column.indexed_column_id); if (result) { key_column->mutable_value()->CopyFrom(*result); } } } } } return Status::OK(); } Result CreateAndSetupIndexInsertRequest( QLExprExecutor* expr_executor, bool index_has_write_permission, const QLTableRow& existing_row, const QLTableRow& new_row, const IndexInfo* index, vector>* index_requests, bool* has_index_key_changed, bool* index_pred_new_row, bool index_pred_existing_row) { bool index_key_changed = false; bool update_this_index = false; unordered_map values; // Prepare the new index key. for (size_t idx = 0; idx < index->key_column_count(); idx++) { const IndexInfo::IndexColumn& index_column = index->column(idx); bool column_changed = true; // Column_id should be used without executing ""colexpr"" for the following cases (we want // to avoid executing colexpr as it is less efficient). // - Old PROTO messages (expr_case() == NOT SET). // - When indexing expression is just a column-ref (expr_case == kColumnId) if (index_column.colexpr.expr_case() == QLExpressionPB::ExprCase::EXPR_NOT_SET || index_column.colexpr.expr_case() == QLExpressionPB::ExprCase::kColumnId) { auto result = new_row.GetValue(index_column.indexed_column_id); if (!existing_row.IsEmpty()) { // For each column in the index key, if there is a new value, see if the value is // changed from the current value. Else, use the current value. if (result) { if (new_row.MatchColumn(index_column.indexed_column_id, existing_row)) { column_changed = false; } else { index_key_changed = true; } } else { // TODO(Piyush): This else is possibly dead code. It can never happen that the new_row // doesn't have some column but the existing one does because we copy the existing one // into the new one before this function call. result = existing_row.GetValue(index_column.indexed_column_id); } } if (result) { values[idx] = std::move(*result); } } else { QLExprResult result; if (existing_row.IsEmpty()) { RETURN_NOT_OK(expr_executor->EvalExpr(index_column.colexpr, new_row, result.Writer())); } else { // For each column in the index key, if there is a new value, see if the value is // specified in the new value. Otherwise, use the current value. if (new_row.IsColumnSpecified(index_column.indexed_column_id)) { RETURN_NOT_OK(expr_executor->EvalExpr(index_column.colexpr, new_row, result.Writer())); // Compare new and existing results of the expression, if the results are equal // that means the key is NOT changed in fact even if the column value is changed. QLExprResult existing_result; RETURN_NOT_OK(expr_executor->EvalExpr( index_column.colexpr, existing_row, existing_result.Writer())); if (result.Value() == existing_result.Value()) { column_changed = false; } else { index_key_changed = true; } } else { // TODO(Piyush): This else is possibly dead code. RETURN_NOT_OK(expr_executor->EvalExpr( index_column.colexpr, existing_row, result.Writer())); } } result.MoveTo(&values[idx]); } if (column_changed) { update_this_index = true; } } // Prepare the covering columns. for (size_t idx = index->key_column_count(); idx < index->columns().size(); idx++) { const IndexInfo::IndexColumn& index_column = index->column(idx); auto result = new_row.GetValue(index_column.indexed_column_id); bool column_changed = true; // If the index value is changed and there is no new covering column value set, use the // current value. if (index_key_changed) { if (!result) { // TODO(Piyush): This if is possibly dead code. result = existing_row.GetValue(index_column.indexed_column_id); } } else if (!FLAGS_ycql_disable_index_updating_optimization && result && new_row.MatchColumn(index_column.indexed_column_id, existing_row)) { column_changed = false; } if (result) { values[idx] = std::move(*result); } if (column_changed) { update_this_index = true; } } if (has_index_key_changed) { *has_index_key_changed = index_key_changed; } bool new_row_satisfies_idx_pred = true; if (index->where_predicate_spec()) { // TODO(Piyush): Ensure EvalCondition returns an error if some column is missing. RETURN_NOT_OK(expr_executor->EvalCondition( index->where_predicate_spec()->where_expr().condition(), new_row, &new_row_satisfies_idx_pred)); if (index_pred_new_row) { *index_pred_new_row = new_row_satisfies_idx_pred; } if (new_row_satisfies_idx_pred && !index_pred_existing_row) { // In case the row is unchanged but the predicate switches to true (can happen if the // predicate involves no indexed/covering cols). if (!update_this_index) VLOG(3) << ""Indexed/covering cols unchanged but predicate switched to true for index_id="" << index->table_id(); update_this_index = true; } } if (index_has_write_permission && (update_this_index || FLAGS_ycql_disable_index_updating_optimization)) { // If this is a partial index and the index predicate is false for the new row, skip the insert. if (index->where_predicate_spec() && !new_row_satisfies_idx_pred) { VLOG(3) << ""Skip index entry write for index_id="" << index->table_id() << "" since predicate not satisfied""; return nullptr; } QLWriteRequestPB* const index_request = NewIndexRequest(*index, QLWriteRequestPB::QL_STMT_INSERT, index_requests); // Setup the key columns. for (size_t idx = 0; idx < index->key_column_count(); idx++) { QLExpressionPB* const key_column = NewKeyColumn(index_request, *index, idx); auto it = values.find(idx); if (it != values.end()) { *key_column->mutable_value() = std::move(it->second); } } // Setup the covering columns. for (size_t idx = index->key_column_count(); idx < index->columns().size(); idx++) { auto it = values.find(idx); if (it != values.end()) { const IndexInfo::IndexColumn& index_column = index->column(idx); QLColumnValuePB* const covering_column = index_request->add_column_values(); covering_column->set_column_id(index_column.column_id); *covering_column->mutable_expr()->mutable_value() = std::move(it->second); } } return index_request; } return nullptr; // The index updating was skipped. } Status QLReadOperation::Execute(const common::YQLStorageIf& ql_storage, CoarseTimePoint deadline, const ReadHybridTime& read_time, const Schema& schema, const Schema& projection, QLResultSet* resultset, HybridTime* restart_read_ht) { SimulateTimeoutIfTesting(&deadline); size_t row_count_limit = std::numeric_limits::max(); size_t num_rows_skipped = 0; size_t offset = 0; if (request_.has_offset()) { offset = request_.offset(); } if (request_.has_limit()) { if (request_.limit() == 0) { return Status::OK(); } row_count_limit = request_.limit(); } // Create the projections of the non-key columns selected by the row block plus any referenced in // the WHERE condition. When DocRowwiseIterator::NextRow() populates the value map, it uses this // projection only to scan sub-documents. The query schema is used to select only referenced // columns and key columns. Schema static_projection, non_static_projection; RETURN_NOT_OK(CreateProjections(schema, request_.column_refs(), &static_projection, &non_static_projection)); const bool read_static_columns = !static_projection.columns().empty(); const bool read_distinct_columns = request_.distinct(); std::unique_ptr iter; std::unique_ptr spec, static_row_spec; RETURN_NOT_OK(ql_storage.BuildYQLScanSpec( request_, read_time, schema, read_static_columns, static_projection, &spec, &static_row_spec)); RETURN_NOT_OK(ql_storage.GetIterator(request_, projection, schema, txn_op_context_, deadline, read_time, *spec, &iter)); VTRACE(1, ""Initialized iterator""); QLTableRow static_row; QLTableRow non_static_row; QLTableRow& selected_row = read_distinct_columns ? static_row : non_static_row; // In case when we are continuing a select with a paging state, or when using a reverse scan, // the static columns for the next row to fetch are not included in the first iterator and we // need to fetch them with a separate spec and iterator before beginning the normal fetch below. if (static_row_spec != nullptr) { std::unique_ptr static_row_iter; RETURN_NOT_OK(ql_storage.GetIterator( request_, static_projection, schema, txn_op_context_, deadline, read_time, *static_row_spec, &static_row_iter)); if (VERIFY_RESULT(static_row_iter->HasNext())) { RETURN_NOT_OK(static_row_iter->NextRow(&static_row)); } } // Begin the normal fetch. int match_count = 0; bool static_dealt_with = true; while (resultset->rsrow_count() < row_count_limit && VERIFY_RESULT(iter->HasNext())) { const bool last_read_static = iter->IsNextStaticColumn(); // Note that static columns are sorted before non-static columns in DocDB as follows. This is // because """" is empty and terminated by kGroupEnd which sorts before // all other ValueType characters in a non-empty range component. // -> value; // -> value; if (last_read_static) { static_row.Clear(); RETURN_NOT_OK(iter->NextRow(static_projection, &static_row)); } else { // Reading a regular row that contains non-static columns. // Read this regular row. // TODO(omer): this is quite inefficient if read_distinct_column. A better way to do this // would be to only read the first non-static column for each hash key, and skip the rest non_static_row.Clear(); RETURN_NOT_OK(iter->NextRow(non_static_projection, &non_static_row)); } // We have two possible cases: whether we use distinct or not // If we use distinct, then in general we only need to add the static rows // However, we might have to add non-static rows, if there is no static row corresponding to // it. Of course, we add one entry per hash key in non-static row. // If we do not use distinct, we are generally only adding non-static rows // However, if there is no non-static row for the static row, we have to add it. if (read_distinct_columns) { bool join_successful = false; if (!last_read_static) { join_successful = JoinNonStaticRow(schema, static_projection, non_static_row, &static_row); } // If the join was not successful, it means that the non-static row we read has no // corresponding static row, so we have to add it to the result if (!join_successful) { RETURN_NOT_OK(AddRowToResult( spec, static_row, row_count_limit, offset, resultset, &match_count, &num_rows_skipped)); } } else { if (last_read_static) { // If the next row to be read is not static, deal with it later, as we do not know whether // the non-static row corresponds to this static row; if the non-static row doesn't // correspond to this static row, we will have to add it later, so set static_dealt_with to // false if (VERIFY_RESULT(iter->HasNext()) && !iter->IsNextStaticColumn()) { static_dealt_with = false; continue; } AddProjection(non_static_projection, &static_row); RETURN_NOT_OK(AddRowToResult(spec, static_row, row_count_limit, offset, resultset, &match_count, &num_rows_skipped)); } else { // We also have to do the join if we are not reading any static columns, as Cassandra // reports nulls for static rows with no corresponding non-static row if (read_static_columns || !static_dealt_with) { const bool join_successful = JoinStaticRow(schema, static_projection, static_row, &non_static_row); // Add the static row if the join was not successful and it is the first time we are // dealing with this static row if (!join_successful && !static_dealt_with) { AddProjection(non_static_projection, &static_row); RETURN_NOT_OK(AddRowToResult( spec, static_row, row_count_limit, offset, resultset, &match_count, &num_rows_skipped)); } } static_dealt_with = true; RETURN_NOT_OK(AddRowToResult( spec, non_static_row, row_count_limit, offset, resultset, &match_count, &num_rows_skipped)); } } } if (request_.is_aggregate() && match_count > 0) { RETURN_NOT_OK(PopulateAggregate(selected_row, resultset)); } VTRACE(1, ""Fetched $0 rows."", resultset->rsrow_count()); RETURN_NOT_OK(SetPagingStateIfNecessary( iter.get(), resultset, row_count_limit, num_rows_skipped, read_time)); // SetPagingStateIfNecessary could perform read, so we assign restart_read_ht after it. *restart_read_ht = iter->RestartReadHt(); return Status::OK(); } Status QLReadOperation::SetPagingStateIfNecessary(const common::YQLRowwiseIteratorIf* iter, const QLResultSet* resultset, const size_t row_count_limit, const size_t num_rows_skipped, const ReadHybridTime& read_time) { if ((resultset->rsrow_count() >= row_count_limit || request_.has_offset()) && !request_.is_aggregate()) { SubDocKey next_row_key; RETURN_NOT_OK(iter->GetNextReadSubDocKey(&next_row_key)); // When the ""limit"" number of rows are returned and we are asked to return the paging state, // return the partition key and row key of the next row to read in the paging state if there are // still more rows to read. Otherwise, leave the paging state empty which means we are done // reading from this tablet. if (request_.return_paging_state()) { if (!next_row_key.doc_key().empty()) { QLPagingStatePB* paging_state = response_.mutable_paging_state(); paging_state->set_next_partition_key( PartitionSchema::EncodeMultiColumnHashValue(next_row_key.doc_key().hash())); paging_state->set_next_row_key(next_row_key.Encode().ToStringBuffer()); paging_state->set_total_rows_skipped(request_.paging_state().total_rows_skipped() + num_rows_skipped); } else if (request_.has_offset()) { QLPagingStatePB* paging_state = response_.mutable_paging_state(); paging_state->set_total_rows_skipped(request_.paging_state().total_rows_skipped() + num_rows_skipped); } } if (response_.has_paging_state()) { if (FLAGS_ycql_consistent_transactional_paging) { read_time.AddToPB(response_.mutable_paging_state()); } else { // Using SingleTime will help avoid read restarts on second page and later but will // potentially produce stale results on those pages. auto per_row_consistent_read_time = ReadHybridTime::SingleTime(read_time.read); per_row_consistent_read_time.AddToPB(response_.mutable_paging_state()); } } } return Status::OK(); } Status QLReadOperation::GetIntents(const Schema& schema, KeyValueWriteBatchPB* out) { std::vector hashed_components; RETURN_NOT_OK(QLKeyColumnValuesToPrimitiveValues( request_.hashed_column_values(), schema, 0, schema.num_hash_key_columns(), &hashed_components)); auto pair = out->mutable_read_pairs()->Add(); if (hashed_components.empty()) { // Empty hashed components mean that we don't have primary key at all, but request // could still contain hash_code as part of tablet routing. // So we should ignore it. pair->set_key(std::string(1, ValueTypeAsChar::kGroupEnd)); } else { DocKey doc_key(request_.hash_code(), hashed_components); pair->set_key(doc_key.Encode().ToStringBuffer()); } pair->set_value(std::string(1, ValueTypeAsChar::kNullLow)); return Status::OK(); } Status QLReadOperation::PopulateResultSet(const std::unique_ptr& spec, const QLTableRow& table_row, QLResultSet *resultset) { resultset->AllocateRow(); int rscol_index = 0; for (const QLExpressionPB& expr : request_.selected_exprs()) { QLExprResult value; RETURN_NOT_OK(EvalExpr(expr, table_row, value.Writer(), spec->schema())); resultset->AppendColumn(rscol_index, value.Value()); rscol_index++; } return Status::OK(); } Status QLReadOperation::EvalAggregate(const QLTableRow& table_row) { if (aggr_result_.empty()) { int column_count = request_.selected_exprs().size(); aggr_result_.resize(column_count); } int aggr_index = 0; for (const QLExpressionPB& expr : request_.selected_exprs()) { RETURN_NOT_OK(EvalExpr(expr, table_row, aggr_result_[aggr_index++].Writer())); } return Status::OK(); } Status QLReadOperation::PopulateAggregate(const QLTableRow& table_row, QLResultSet *resultset) { resultset->AllocateRow(); int column_count = request_.selected_exprs().size(); for (int rscol_index = 0; rscol_index < column_count; rscol_index++) { resultset->AppendColumn(rscol_index, aggr_result_[rscol_index].Value()); } return Status::OK(); } Status QLReadOperation::AddRowToResult(const std::unique_ptr& spec, const QLTableRow& row, const size_t row_count_limit, const size_t offset, QLResultSet* resultset, int* match_count, size_t *num_rows_skipped) { VLOG(3) << __FUNCTION__ << "" : "" << yb::ToString(row); if (resultset->rsrow_count() < row_count_limit) { bool match = false; RETURN_NOT_OK(spec->Match(row, &match)); if (match) { if (*num_rows_skipped >= offset) { (*match_count)++; if (request_.is_aggregate()) { RETURN_NOT_OK(EvalAggregate(row)); } else { RETURN_NOT_OK(PopulateResultSet(spec, row, resultset)); } } else { (*num_rows_skipped)++; } } } return Status::OK(); } } // namespace docdb } // namespace yb ",16265,True,3039.1780291817513,median "[role=""xpack""] [[security-settings]] === Security settings in {es} ++++ Security settings ++++ By default, {security} is disabled when you have a basic or trial license. To enable {security}, use the `xpack.security.enabled` setting. You configure `xpack.security` settings to <> and perform message authentication, <>, <>, <>, and <>. All of these settings can be added to the `elasticsearch.yml` configuration file, with the exception of the secure settings, which you add to the {es} keystore. For more information about creating and updating the {es} keystore, see <>. [float] [[general-security-settings]] ==== General security settings `xpack.security.enabled`:: Set to `true` to enable {security} on the node. + + If set to `false`, which is the default value for basic and trial licenses, {security} is disabled. It also affects all {kib} instances that connect to this {es} instance; you do not need to disable {security} in those `kibana.yml` files. For more information about disabling {security} in specific {kib} instances, see {kibana-ref}/security-settings-kb.html[{kib} security settings]. `xpack.security.hide_settings`:: A comma-separated list of settings that are omitted from the results of the <>. You can use wildcards to include multiple settings in the list. For example, the following value hides all the settings for the ad1 realm: `xpack.security.authc.realms.ad1.*`. The API already omits all `ssl` settings, `bind_dn`, and `bind_password` due to the sensitive nature of the information. [float] [[password-security-settings]] ==== Default password security settings `xpack.security.authc.accept_default_password`:: In `elasticsearch.yml`, set this to `false` to disable support for the default ""changeme"" password. [float] [[anonymous-access-settings]] ==== Anonymous access settings You can configure the following anonymous access settings in `elasticsearch.yml`. For more information, see {xpack-ref}/anonymous-access.html[ Enabling anonymous access]. `xpack.security.authc.anonymous.username`:: The username (principal) of the anonymous user. Defaults to `_es_anonymous_user`. `xpack.security.authc.anonymous.roles`:: The roles to associate with the anonymous user. Required. `xpack.security.authc.anonymous.authz_exception`:: When `true`, an HTTP 403 response is returned if the anonymous user does not have the appropriate permissions for the requested action. The user is not prompted to provide credentials to access the requested resource. When set to `false`, a HTTP 401 is returned and the user can provide credentials with the appropriate permissions to gain access. Defaults to `true`. [float] [[field-document-security-settings]] ==== Document and field level security settings You can set the following document and field level security settings in `elasticsearch.yml`. For more information, see {xpack-ref}/field-and-document-access-control.html[Setting up document and field level security]. `xpack.security.dls_fls.enabled`:: Set to `false` to prevent document and field level security from being configured. Defaults to `true`. [float] [[token-service-settings]] ==== Token service settings You can set the following token service settings in `elasticsearch.yml`. `xpack.security.authc.token.enabled`:: Set to `false` to disable the built-in token service. Defaults to `true` unless `xpack.security.http.ssl.enabled` is `false`. This prevents sniffing the token from a connection over plain http. `xpack.security.authc.token.timeout`:: The length of time that a token is valid for. By default this value is `20m` or 20 minutes. The maximum value is 1 hour. [float] [[realm-settings]] ==== Realm settings You configure realm settings in the `xpack.security.authc.realms` namespace in `elasticsearch.yml`. For example: [source,yaml] ---------------------------------------- xpack.security.authc.realms: realm1: type: native order: 0 ... realm2: type: ldap order: 1 ... realm3: type: active_directory order: 2 ... ... ---------------------------------------- The valid settings vary depending on the realm type. For more information, see {xpack-ref}/setting-up-authentication.html[Setting up authentication]. [float] [[ref-realm-settings]] ===== Settings valid for all realms `type`:: The type of the realm: `native, `ldap`, `active_directory`, `pki`, or `file`. Required. `order`:: The priority of the realm within the realm chain. Realms with a lower order are consulted first. Although not required, use of this setting is strongly recommended when you configure multiple realms. Defaults to `Integer.MAX_VALUE`. `enabled`:: Indicates whether a realm is enabled. You can use this setting to disable a realm without removing its configuration information. Defaults to `true`. [[ref-native-settings]] [float] ===== Native realm settings For a native realm, the `type` must be set to `native`. In addition to the <>, you can specify the following optional settings: `cache.ttl`:: The time-to-live for cached user entries. A user and a hash of its credentials are cached for this period of time. Specify the time period using the standard {es} <>. Defaults to `20m`. `cache.max_users`:: The maximum number of user entries that can live in the cache at any given time. Defaults to 100,000. `cache.hash_algo`:: (Expert Setting) The hashing algorithm that is used for the in-memory cached user credentials. For possible values, see {xpack-ref}/controlling-user-cache.html[Cache hash algorithms]. Defaults to `ssha256`. [[ref-users-settings]] [float] ===== File realm settings The `type` setting must be set to `file`. In addition to the <>, you can specify the following settings: `cache.ttl`:: The time-to-live for cached user entries. A user and a hash of its credentials are cached for this configured period of time. Defaults to `20m`. Specify values using the standard {es} {ref}/common-options.html#time-units[time units]. Defaults to `20m`. `cache.max_users`:: The maximum number of user entries that can live in the cache at a given time. Defaults to 100,000. `cache.hash_algo`:: (Expert Setting) The hashing algorithm that is used for the in-memory cached user credentials. See the {xpack-ref}/controlling-user-cache.html#controlling-user-cache[Cache hash algorithms] table for all possible values. Defaults to `ssha256`. [[ref-ldap-settings]] [float] ===== LDAP realm settings The `type` setting must be set to `ldap`. In addition to the <>, you can specify the following settings: `url`:: Specifies one or more LDAP URLs in the format `ldap[s]://:`. Multiple URLs can be defined using a comma separated value or array syntax: `[ ""ldaps://server1:636"", ""ldaps://server2:636"" ]`. `ldaps` and `ldap` URL protocols cannot be mixed in the same realm. Required. `load_balance.type`:: The behavior to use when there are multiple LDAP URLs defined. For supported values see <>. Defaults to `failover`. `load_balance.cache_ttl`:: When using `dns_failover` or `dns_round_robin` as the load balancing type, this setting controls the amount of time to cache DNS lookups. Defaults to `1h`. `bind_dn`:: The DN of the user that is used to bind to the LDAP and perform searches. Only applicable in user search mode. If not specified, an anonymous bind is attempted. Defaults to Empty. Due to its potential security impact, `bind_dn` is not exposed via the <>. `bind_password`:: deprecated[6.3] Use `secure_bind_password` instead. The password for the user that is used to bind to the LDAP directory. Defaults to Empty. Due to its potential security impact, `bind_password` is not exposed via the <>. `secure_bind_password` (<>):: The password for the user that is used to bind to the LDAP directory. Defaults to Empty. `user_dn_templates`:: The DN template that replaces the user name with the string `{0}`. This setting is multivalued; you can specify multiple user contexts. Required to operate in user template mode. If `user_search.base_dn` is specified, this setting is not valid. For more information on the different modes, see {xpack-ref}/ldap-realm.html[LDAP realms]. + -- NOTE: If any settings starting with `user_search` are specified, the `user_dn_templates` settings are ignored. -- `user_group_attribute`:: Specifies the attribute to examine on the user for group membership. If any `group_search` settings are specified, this setting is ignored. Defaults to `memberOf`. `user_search.base_dn`:: Specifies a container DN to search for users. Required to operated in user search mode. If `user_dn_templates` is specified, this setting is not valid. For more information on the different modes, see {xpack-ref}/ldap-realm.html[LDAP realms]. `user_search.scope`:: The scope of the user search. Valid values are `sub_tree`, `one_level` or `base`. `one_level` only searches objects directly contained within the `base_dn`. `sub_tree` searches all objects contained under `base_dn`. `base` specifies that the `base_dn` is the user object, and that it is the only user considered. Defaults to `sub_tree`. `user_search.filter`:: Specifies the filter used to search the directory in attempts to match an entry with the username provided by the user. Defaults to `(uid={0})`. `{0}` is substituted with the username provided when searching. `user_search.attribute`:: deprecated[5.6] Use `user_search.filter` instead. The attribute to match with the username sent with the request. Defaults to `uid`. `user_search.pool.enabled`:: Enables or disables connection pooling for user search. If set to `false`, a new connection is created for every search. The default is `true` when `bind_dn` is set. `user_search.pool.size`:: The maximum number of connections to the LDAP server to allow in the connection pool. Defaults to `20`. `user_search.pool.initial_size`:: The initial number of connections to create to the LDAP server on startup. Defaults to `0`. If the LDAP server is down, values greater than `0` could cause startup failures. `user_search.pool.health_check.enabled`:: Enables or disables a health check on LDAP connections in the connection pool. Connections are checked in the background at the specified interval. Defaults to `true`. `user_search.pool.health_check.dn`:: The distinguished name that is retrieved as part of the health check. Defaults to the value of `bind_dn` if present; if not, falls back to `user_search.base_dn`. `user_search.pool.health_check.interval`:: The interval to perform background checks of connections in the pool. Defaults to `60s`. `group_search.base_dn`:: The container DN to search for groups in which the user has membership. When this element is absent, {security} searches for the attribute specified by `user_group_attribute` set on the user in order to determine group membership. `group_search.scope`:: Specifies whether the group search should be `sub_tree`, `one_level` or `base`. `one_level` only searches objects directly contained within the `base_dn`. `sub_tree` searches all objects contained under `base_dn`. `base` specifies that the `base_dn` is a group object, and that it is the only group considered. Defaults to `sub_tree`. `group_search.filter`:: Specifies a filter to use to look up a group. When not set, the realm searches for `group`, `groupOfNames`, `groupOfUniqueNames`, or `posixGroup` with the attributes `member`, `memberOf`, or `memberUid`. Any instance of `{0}` in the filter is replaced by the user attribute defined in `group_search.user_attribute`. `group_search.user_attribute`:: Specifies the user attribute that is fetched and provided as a parameter to the filter. If not set, the user DN is passed into the filter. Defaults to Empty. `unmapped_groups_as_roles`:: If set to `true`, the names of any unmapped LDAP groups are used as role names and assigned to the user. A group is considered to be _unmapped_ if it is not not referenced in a {xpack-ref}/mapping-roles.html#mapping-roles-file[role-mapping file]. API-based role mappings are not considered. Defaults to `false`. `files.role_mapping`:: The {xpack-ref}/security-files.html[location] for the {xpack-ref}/mapping-roles.html#mapping-roles[ YAML role mapping configuration file]. Defaults to `CONFIG_DIR/role_mapping.yml`. `follow_referrals`:: Specifies whether {security} should follow referrals returned by the LDAP server. Referrals are URLs returned by the server that are to be used to continue the LDAP operation (for example, search). Defaults to `true`. `metadata`:: A list of additional LDAP attributes that should be loaded from the LDAP server and stored in the authenticated user's metadata field. `timeout.tcp_connect`:: The TCP connect timeout period for establishing an LDAP connection. An `s` at the end indicates seconds, or `ms` indicates milliseconds. Defaults to `5s` (5 seconds ). `timeout.tcp_read`:: The TCP read timeout period after establishing an LDAP connection. An `s` at the end indicates seconds, or `ms` indicates milliseconds. Defaults to `5s` (5 seconds ). `timeout.ldap_search`:: The LDAP Server enforced timeout period for an LDAP search. An `s` at the end indicates seconds, or `ms` indicates milliseconds. Defaults to `5s` (5 seconds ). `ssl.key`:: Path to a PEM encoded file containing the private key, which is used if the LDAP server requires client authentication. `ssl.key` and `ssl.keystore.path` cannot be used at the same time. `ssl.key_passphrase`:: The passphrase that is used to decrypt the private key. This value is optional as the key may not be encrypted. `ssl.secure_key_passphrase` (<>):: The passphrase that is used to decrypt the private key. `ssl.certificate`:: Path to a PEM encoded file containing the certificate (or certificate chain) that will be presented to clients when they connect. `ssl.certificate_authorities`:: List of paths to PEM encoded certificate files that should be trusted. `ssl.certificate_authorities` and `ssl.truststore.path` cannot be used at the same time. `ssl.keystore.path`:: The path to the Java Keystore file that contains a private key and certificate. `ssl.key` and `ssl.keystore.path` may not be used at the same time. `ssl.keystore.type`:: The format of the keystore file. Should be either `jks` to use the Java Keystore format, or `PKCS12` to use PKCS#12 files. The default is `jks`. `ssl.keystore.password`:: The password to the keystore. `ssl.keystore.secure_password` (<>):: The password to the keystore. `ssl.keystore.key_password`:: The password for the key in the keystore. Defaults to the keystore password. `ssl.keystore.secure_key_password`:: The password for the key in the keystore. Defaults to the keystore password. `ssl.truststore.path`:: The path to the Java Keystore file that contains the certificates to trust. `ssl.certificate_authorities` and `ssl.truststore.path` cannot be used at the same time. `ssl.truststore.password`:: The password to the truststore. `ssl.truststore.secure_password` (<>):: The password to the truststore. `ssl.truststore.type`:: The format of the keystore file. Should be either `jks` to use the Java Keystore format, or `PKCS12` to use PKCS#12 files. The default is `jks`. `ssl.verification_mode`:: Indicates the type of verification when using `ldaps` to protect against man in the middle attacks and certificate forgery. Values are `none`, `certificate`, and `full`. Defaults to the value of `xpack.ssl.verification_mode`. + See <> for an explanation of these values. `ssl.supported_protocols`:: Supported protocols for TLS/SSL (with versions). Defaults to the value of `xpack.ssl.supported_protocols`. `ssl.cipher_suites`:: Specifies the cipher suites that should be supported when communicating with the LDAP server. Supported cipher suites can be found in Oracle's http://docs.oracle.com/javase/8/docs/technotes/guides/security/SunProviders.html[ Java Cryptography Architecture documentation]. Defaults to the value of `xpack.ssl.cipher_suites`. `cache.ttl`:: Specifies the time-to-live for cached user entries. A user and a hash of its credentials are cached for this period of time. Use the standard {es} <>. Defaults to `20m`. `cache.max_users`:: Specifies the maximum number of user entries that the cache can contain. Defaults to `100000`. `cache.hash_algo`:: (Expert Setting) Specifies the hashing algorithm that is used for the in-memory cached user credentials. See {xpack-ref}/controlling-user-cache.html#controlling-user-cache[Cache hash algorithms] table for all possible values. Defaults to `ssha256`. [[ref-ad-settings]] [float] ===== Active Directory realm settings The `type` setting must be set to `active_directory`. In addition to the <>, you can specify the following settings: `url`:: An LDAP URL of the form `ldap[s]://:`. {security} attempts to authenticate against this URL. If the URL is not specified, it is derived from the `domain_name` setting and assumes an unencrypted connection to port 389. Defaults to `ldap://:389`. This setting is required when connecting using SSL/TLS or when using a custom port. `load_balance.type`:: The behavior to use when there are multiple LDAP URLs defined. For supported values see <>. Defaults to `failover`. `load_balance.cache_ttl`:: When using `dns_failover` or `dns_round_robin` as the load balancing type, this setting controls the amount of time to cache DNS lookups. Defaults to `1h`. `domain_name`:: The domain name of Active Directory. If the the `url` and `user_search_dn` settings are not specified, the cluster can derive those values from this setting. Required. `bind_dn`:: The DN of the user that is used to bind to Active Directory and perform searches. Defaults to Empty. Due to its potential security impact, `bind_dn` is not exposed via the <>. `bind_password`:: deprecated[6.3] Use `secure_bind_password` instead. The password for the user that is used to bind to Active Directory. Defaults to Empty. Due to its potential security impact, `bind_password` is not exposed via the <>. `secure_bind_password` (<>):: The password for the user that is used to bind to Active Directory. Defaults to Empty. `unmapped_groups_as_roles`:: If set to `true`, the names of any unmapped Active Directory groups are used as role names and assigned to the user. A group is considered _unmapped_ when it is not referenced in any role-mapping files. API-based role mappings are not considered. Defaults to `false`. `files.role_mapping`:: The {xpack-ref}/security-files.html[location] for the YAML role mapping configuration file. Defaults to `CONFIG_DIR/role_mapping.yml`. `user_search.base_dn`:: The context to search for a user. Defaults to the root of the Active Directory domain. `user_search.scope`:: Specifies whether the user search should be `sub_tree`, `one_level` or `base`. `one_level` only searches users directly contained within the `base_dn`. `sub_tree` searches all objects contained under `base_dn`. `base` specifies that the `base_dn` is a user object, and that it is the only user considered. Defaults to `sub_tree`. `user_search.filter`:: Specifies a filter to use to lookup a user given a username. The default filter looks up `user` objects with either `sAMAccountName` or `userPrincipalName`. If specified, this must be a valid LDAP user search filter. For example `(&(objectClass=user)(sAMAccountName={0}))`. For more information, see https://msdn.microsoft.com/en-us/library/aa746475(v=vs.85).aspx[Search Filter Syntax]. `user_search.upn_filter`:: Specifies a filter to use to lookup a user given a user principal name. The default filter looks up `user` objects with a matching `userPrincipalName`. If specified, this must be a valid LDAP user search filter. For example, `(&(objectClass=user)(userPrincipalName={1}))`. `{1}` is the full user principal name provided by the user. For more information, see https://msdn.microsoft.com/en-us/library/aa746475(v=vs.85).aspx[Search Filter Syntax]. `user_search.down_level_filter`:: Specifies a filter to use to lookup a user given a down level logon name (DOMAIN\\user). The default filter looks up `user` objects with a matching `sAMAccountName` in the domain provided. If specified, this must be a valid LDAP user search filter. For example, `(&(objectClass=user)(sAMAccountName={0}))`. For more information, see https://msdn.microsoft.com/en-us/library/aa746475(v=vs.85).aspx[Search Filter Syntax]. `user_search.pool.enabled`:: Enables or disables connection pooling for user search. When disabled a new connection is created for every search. The default is `true` when `bind_dn` is provided. `user_search.pool.size`:: The maximum number of connections to the Active Directory server to allow in the connection pool. Defaults to `20`. `user_search.pool.initial_size`:: The initial number of connections to create to the Active Directory server on startup. Defaults to `0`. If the LDAP server is down, values greater than 0 could cause startup failures. `user_search.pool.health_check.enabled`:: Enables or disables a health check on Active Directory connections in the connection pool. Connections are checked in the background at the specified interval. Defaults to `true`. `user_search.pool.health_check.dn`:: The distinguished name to be retrieved as part of the health check. Defaults to the value of `bind_dn` if that setting is present. Otherwise, it defaults to the value of the `user_search.base_dn` setting. `user_search.pool.health_check.interval`:: The interval to perform background checks of connections in the pool. Defaults to `60s`. `group_search.base_dn`:: The context to search for groups in which the user has membership. Defaults to the root of the Active Directory domain. `group_search.scope`:: Specifies whether the group search should be `sub_tree`, `one_level` or `base`. `one_level` searches for groups directly contained within the `base_dn`. `sub_tree` searches all objects contained under `base_dn`. `base` specifies that the `base_dn` is a group object, and that it is the only group considered. Defaults to `sub_tree`. `metadata`:: A list of additional LDAP attributes that should be loaded from the LDAP server and stored in the authenticated user's metadata field. `timeout.tcp_connect`:: The TCP connect timeout period for establishing an LDAP connection. An `s` at the end indicates seconds, or `ms` indicates milliseconds. Defaults to `5s` (5 seconds ). `timeout.tcp_read`:: The TCP read timeout period after establishing an LDAP connection. An `s` at the end indicates seconds, or `ms` indicates milliseconds. Defaults to `5s` (5 seconds ). `timeout.ldap_search`:: The LDAP Server enforced timeout period for an LDAP search. An `s` at the end indicates seconds, or `ms` indicates milliseconds. Defaults to `5s` (5 seconds ). `ssl.certificate`:: Path to a PEM encoded file containing the certificate (or certificate chain) that will be presented to clients when they connect. `ssl.certificate_authorities`:: List of paths to PEM encoded certificate files that should be trusted. `ssl.certificate_authorities` and `ssl.truststore.path` cannot be used at the same time. `ssl.key`:: Path to the PEM encoded file containing the private key, which is used when the Active Directory server requires client authentication. `ssl.key` and `ssl.keystore.path` cannot be used at the same time. `ssl.key_passphrase`:: The passphrase that is used to decrypt the private key. This value is optional as the key might not be encrypted. `ssl.secure_key_passphrase` (<>):: The passphrase that is used to decrypt the private key. This value is optional as the key might not be encrypted. `ssl.keystore.key_password`:: The password for the key in the keystore. Defaults to the keystore password. `ssl.keystore.secure_key_password` (<>):: The password for the key in the keystore. Defaults to the keystore password. `ssl.keystore.password`:: The password to the keystore. `ssl.secure_keystore.password` (<>):: The password to the keystore. `ssl.keystore.path`:: The path to the Java Keystore file that contains a private key and certificate. `ssl.key` and `ssl.keystore.path` cannot be used at the same time. `ssl.keystore.type`:: The format of the keystore file. Should be either `jks` to use the Java Keystore format, or `PKCS12` to use PKCS#12 files. The default is `jks`. `ssl.truststore.password`:: The password to the truststore. `ssl.truststore.secure_password` (<>):: The password to the truststore. `ssl.truststore.path`:: The path to the Java Keystore file that contains the certificates to trust. `ssl.certificate_authorities` and `ssl.truststore.path` cannot be used at the same time. `ssl.truststore.type`:: The format of the truststore file. Should be either `jks` to use the Java Keystore format, or `PKCS12` to use PKCS#12 files. The default is `jks`. `ssl.verification_mode`:: Indicates the type of verification when using `ldaps` to protect against man in the middle attacks and certificate forgery. Values are `none`, `certificate`, and `full`. Defaults to the value of `xpack.ssl.verification_mode`. + See <> for an explanation of these values. `ssl.supported_protocols`:: Supported protocols for TLS/SSL (with versions). Defaults to the value of `xpack.ssl.supported_protocols`. `ssl.cipher_suites`:: Specifies the cipher suites that should be supported when communicating with the Active Directory server. Supported cipher suites can be found in Oracle's http://docs.oracle.com/javase/8/docs/technotes/guides/security/SunProviders.html[ Java Cryptography Architecture documentation]. Defaults to the value of `xpack.ssl.cipher_suites`. `cache.ttl`:: Specifies the time-to-live for cached user entries. A user and a hash of its credentials are cached for this configured period of time. Use the standard Elasticsearch {ref}/common-options.html#time-units[time units]). Defaults to `20m`. `cache.max_users`:: Specifies the maximum number of user entries that the cache can contain. Defaults to `100000`. `cache.hash_algo`:: (Expert Setting) Specifies the hashing algorithm that is used for the in-memory cached user credentials (see {xpack-ref}/controlling-user-cache.html#controlling-user-cache[Cache hash algorithms] table for all possible values). Defaults to `ssha256`. `follow_referrals`:: If set to `true` {security} follows referrals returned by the LDAP server. Referrals are URLs returned by the server that are to be used to continue the LDAP operation (such as `search`). Defaults to `true`. [[ref-pki-settings]] [float] ===== PKI realm settings The `type` setting must be set to `pki`. In addition to the <>, you can specify the following settings: `username_pattern`:: The regular expression pattern used to extract the username from the certificate DN. The first match group is the used as the username. Defaults to `CN=(.*?)(?:,\\|$)`. `certificate_authorities`:: List of paths to the PEM certificate files that should be used to authenticate a user's certificate as trusted. Defaults to the trusted certificates configured for SSL. This setting cannot be used with `truststore.path`. `truststore.algorithm`:: Algorithm for the truststore. Defaults to `SunX509`. `truststore.password`:: The password for the truststore. Must be provided if `truststore.path` is set. `truststore.secure_password` (<>):: The password for the truststore. `truststore.path`:: The path of a truststore to use. Defaults to the trusted certificates configured for SSL. This setting cannot be used with `certificate_authorities`. `files.role_mapping`:: Specifies the {xpack-ref}/security-files.html[location] of the {xpack-ref}/mapping-roles.html[YAML role mapping configuration file]. Defaults to `CONFIG_DIR/role_mapping.yml`. `cache.ttl`:: Specifies the time-to-live for cached user entries. A user and a hash of its credentials are cached for this period of time. Use the standard {es} {ref}/common-options.html#time-units[time units]). Defaults to `20m`. `cache.max_users`:: Specifies the maximum number of user entries that the cache can contain. Defaults to `100000`. [[ref-saml-settings]] [float] ===== SAML realm settings The `type` setting must be set to `saml`. In addition to the <>, you can specify the following settings: `idp.entity_id`:: The Entity ID of the SAML Identity Provider. An Entity ID is a URI with a maximum length of 1024 characters. It can be a URL (https://idp.example.com/) or a URN (`urn:example.com:idp`) and can be found in the configuration or the SAML metadata of the Identity Provider. `idp.metadata.path`:: The path _(recommended)_ or URL to a SAML 2.0 metadata file describing the capabilities and configuration of the Identity Provider. If a path is provided, then it is resolved relative to the {es} config directory. If a URL is provided, then it must be either a `file` URL or a `https` URL. {security} automatically polls this metadata resource and reloads the IdP configuration when changes are detected. File based resources are polled at a frequency determined by the global {es} `resource.reload.interval.high` setting, which defaults to 5 seconds. HTTPS resources are polled at a frequency determined by the realm's `idp.metadata.http.refresh` setting. `idp.metadata.http.refresh`:: Controls the frequency with which `https` metadata is checked for changes. Defaults to `1h` (1 hour). `idp.use_single_logout`:: Indicates whether to utilise the Identity Provider's Single Logout service (if one exists in the IdP metadata file). Defaults to `true`. `sp.entity_id`:: The Entity ID to use for this SAML Service Provider. This should be entered as a URI. We recommend that you use the base URL of your Kibana instance. For example, `https://kibana.example.com/`. `sp.acs`:: The URL of the Assertion Consumer Service within {kib}. Typically this is the ""api/security/v1/saml"" endpoint of your Kibana server. For example, `https://kibana.example.com/api/security/v1/saml`. `sp.logout`:: The URL of the Single Logout service within {kib}. Typically this is the ""logout"" endpoint of your Kibana server. For example, `https://kibana.example.com/logout`. `attributes.principal`:: The Name of the SAML attribute that should be used as the {security} user's principal (username). `attributes.groups`:: The Name of the SAML attribute that should be used to populate {security} user's groups. `attributes.name`:: The Name of the SAML attribute that should be used to populate {security} user's full name. `attributes.mail`:: The Name of the SAML attribute that should be used to populate {security} user's email address. `attributes.dn`:: The Name of the SAML attribute that should be used to populate {security} user's X.500 _Distinguished Name_. `attribute_patterns.principal`:: A Java regular expression that is matched against the SAML attribute specified by `attributes.pattern` before it is applied to the user's _principal_ property. The attribute value must match the pattern and the value of the first _capturing group_ is used as the principal. For example, `^([^@]+)@example\\\\.com$` matches email addresses from the ""example.com"" domain and uses the local-part as the principal. `attribute_patterns.groups`:: As per `attribute_patterns.principal`, but for the _group_ property. `attribute_patterns.name`:: As per `attribute_patterns.principal`, but for the _name_ property. `attribute_patterns.mail`:: As per `attribute_patterns.principal`, but for the _mail_ property. `attribute_patterns.dn`:: As per `attribute_patterns.principal`, but for the _dn_ property. `nameid_format`:: The NameID format that should be requested when asking the IdP to authenticate the current user. Defaults to requesting _transient_ names (`urn:oasis:names:tc:SAML:2.0:nameid-format:transient`). `nameid.allow_create`:: The value of the `AllowCreate` attribute of the `NameIdPolicy` element in an authentication request. Defaults to `false`. `nameid.sp_qualifier`:: The value of the `SPNameQualifier` attribute of the `NameIdPolicy` element in an authentication request. The default is to not include the `SPNameQualifier` attribute. `force_authn`:: Specifies whether to set the `ForceAuthn` attribute when requesting that the IdP authenticate the current user. If set to `true`, the IdP is required to verify the user’s identity, irrespective of any existing sessions they might have. Defaults to `false`. `populate_user_metadata`:: Specifies whether to populate the {es} user's metadata with the values that are provided by the SAML attributes. Defaults to `true`. `allowed_clock_skew`:: The maximum amount of skew that can be tolerated between the IdP's clock and the {es} node's clock. Defaults to `3m` (3 minutes). [float] [[ref-saml-signing-settings]] ===== SAML realm signing settings If a signing key is configured (that is, either `signing.key` or `signing.keystore.path` is set), then {security} signs outgoing SAML messages. Signing can be configured using the following settings: `signing.saml_messages`:: A list of SAML message types that should be signed or `*` to sign all messages. Each element in the list should be the local name of a SAML XML Element. Supported element types are `AuthnRequest`, `LogoutRequest` and `LogoutResponse`. Only valid if `signing.key` or `signing.keystore.path` is also specified. Defaults to `*`. `signing.key`:: Specifies the path to the PEM encoded private key to use for SAML message signing. `signing.key` and `signing.keystore.path` cannot be used at the same time. `signing.secure_key_passphrase` (<>):: Specifies the passphrase to decrypt the PEM encoded private key (`signing.key`) if it is encrypted. `signing.certificate`:: Specifies the path to the PEM encoded certificate (or certificate chain) that corresponds to the `signing.key`. This certificate must also be included in the Service Provider metadata or manually configured within the IdP to allow for signature validation. This setting can only be used if `signing.key` is set. `signing.keystore.path`:: The path to the keystore that contains a private key and certificate. Must be either a Java Keystore (jks) or a PKCS#12 file. `signing.key` and `signing.keystore.path` cannot be used at the same time. `signing.keystore.type`:: The type of the keystore in `signing.keystore.path`. Must be either `jks` or `PKCS12`. If the keystore path ends in "".p12"", "".pfx"", or ""pkcs12"", this setting defaults to `PKCS12`. Otherwise, it defaults to `jks`. `signing.keystore.alias`:: Specifies the alias of the key within the keystore that should be used for SAML message signing. If the keystore contains more than one private key, this setting must be specified. `signing.keystore.secure_password` (<>):: The password to the keystore in `signing.keystore.path`. `signing.keystore.secure_key_password` (<>):: The password for the key in the keystore (`signing.keystore.path`). Defaults to the keystore password. [float] [[ref-saml-encryption-settings]] ===== SAML realm encryption settings If an encryption key is configured (that is, either `encryption.key` or `encryption.keystore.path` is set), then {security} publishes an encryption certificate when generating metadata and attempts to decrypt incoming SAML content. Encryption can be configured using the following settings: `encryption.key`:: Specifies the path to the PEM encoded private key to use for SAML message decryption. `encryption.key` and `encryption.keystore.path` cannot be used at the same time. `encryption.secure_key_passphrase` (<>):: Specifies the passphrase to decrypt the PEM encoded private key (`encryption.key`) if it is encrypted. `encryption.certificate`:: Specifies the path to the PEM encoded certificate (or certificate chain) that is associated with the `encryption.key`. This certificate must also be included in the Service Provider metadata or manually configured within the IdP to enable message encryption. This setting can be used only if `encryption.key` is set. `encryption.keystore.path`:: The path to the keystore that contains a private key and certificate. Must be either a Java Keystore (jks) or a PKCS#12 file. `encryption.key` and `encryption.keystore.path` cannot be used at the same time. `encryption.keystore.type`:: The type of the keystore (`encryption.keystore.path`). Must be either `jks` or `PKCS12`. If the keystore path ends in "".p12"", "".pfx"", or ""pkcs12"", this setting defaults to `PKCS12`. Otherwise, it defaults to `jks`. `encryption.keystore.alias`:: Specifies the alias of the key within the keystore (`encryption.keystore.path`) that should be used for SAML message decryption. If not specified, all compatible key pairs from the keystore are considered as candidate keys for decryption. `encryption.keystore.secure_password` (<>):: The password to the keystore (`encryption.keystore.path`). `encryption.keystore.secure_key_password` (<>):: The password for the key in the keystore (`encryption.keystore.path`). Only a single password is supported. If you are using multiple decryption keys, they cannot have individual passwords. [float] [[ref-saml-ssl-settings]] ===== SAML realm SSL settings If you are loading the IdP metadata over SSL/TLS (that is, `idp.metadata.path` is a URL using the `https` protocol), the following settings can be used to configure SSL. If these are not specified, then the <> are used. NOTE: These settings are not used for any purpose other than loading metadata over https. `ssl.key`:: Specifies the path to the PEM encoded private key to use for http client authentication (if required). `ssl.key` and `ssl.keystore.path` cannot be used at the same time. `ssl.key_passphrase`:: Specifies the passphrase to decrypt the PEM encoded private key (`ssl.key`) if it is encrypted. Cannot be used with `ssl.secure_key_passphrase`. `ssl.secure_key_passphrase` (<>):: Specifies the passphrase to decrypt the PEM encoded private key (`ssl.key`) if it is encrypted. Cannot be used with `ssl.key_passphrase`. `ssl.certificate`:: Specifies the path to the PEM encoded certificate (or certificate chain) that is associated with the key (`ssl.key`). This setting can be used only if `ssl.key` is set. `ssl.certificate_authorities`:: Specifies the paths to the PEM encoded certificate authority certificates that should be trusted. `ssl.certificate_authorities` and `ssl.truststore.path` cannot be used at the same time. `ssl.keystore.path`:: Specifies the path to the keystore that contains a private key and certificate. Must be either a Java Keystore (jks) or a PKCS#12 file. `ssl.key` and `ssl.keystore.path` cannot be used at the same time. `ssl.keystore.type`:: The type of the keystore (`ssl.keystore.path`). Must be either `jks` or `PKCS12`. If the keystore path ends in "".p12"", "".pfx"" or ""pkcs12"", this setting defaults to `PKCS12`. Otherwise, it defaults to `jks`. `ssl.keystore.password`:: The password to the keystore (`ssl.keystore.path`). This setting cannot be used with `ssl.keystore.secure_password`. `ssl.keystore.secure_password` (<>):: The password to the keystore (`ssl.keystore.path`). This setting cannot be used with `ssl.keystore.password`. `ssl.keystore.key_password`:: The password for the key in the keystore (`ssl.keystore.path`). Defaults to the keystore password. This setting cannot be used with `ssl.keystore.secure_key_password`. `ssl.keystore.secure_key_password` (<>):: The password for the key in the keystore (`ssl.keystore.path`). Defaults to the keystore password. This setting cannot be used with `ssl.keystore.key_password`. `ssl.truststore.path`:: The path to the keystore that contains the certificates to trust. Must be either a Java Keystore (jks) or a PKCS#12 file. `ssl.certificate_authorities` and `ssl.truststore.path` cannot be used at the same time. `ssl.truststore.type`:: The type of the truststore (`ssl.truststore.path`). Must be either `jks` or `PKCS12`. If the keystore path ends in "".p12"", "".pfx"" or ""pkcs12"", this setting defaults to `PKCS12`. Otherwise, it defaults to `jks`. `ssl.truststore.password`:: The password to the truststore (`ssl.truststore.path`). This setting cannot be used with `ssl.truststore.secure_password`. `ssl.truststore.secure_password` (<>):: The password to the truststore (`ssl.truststore.path`). This setting cannot be used with `ssl.truststore.password`. `ssl.verification_mode`:: One of `full` (verify the hostname and the certificate path), `certificate` (verify the certificate path, but not the hostname) or `none` (perform no verification). Defaults to `full`. + See <> for a more detailed explanation of these values. `ssl.supported_protocols`:: Specifies the supported protocols for TLS/SSL. `ssl.cipher_suites`:: Specifies the cipher suites that should be supported. [float] [[load-balancing]] ===== Load balancing and failover The `load_balance.type` setting can have the following values: * `failover`: The URLs specified are used in the order that they are specified. The first server that can be connected to will be used for all subsequent connections. If a connection to that server fails then the next server that a connection can be established to will be used for subsequent connections. * `dns_failover`: In this mode of operation, only a single URL may be specified. This URL must contain a DNS name. The system will be queried for all IP addresses that correspond to this DNS name. Connections to the Active Directory or LDAP server will always be tried in the order in which they were retrieved. This differs from `failover` in that there is no reordering of the list and if a server has failed at the beginning of the list, it will still be tried for each subsequent connection. * `round_robin`: Connections will continuously iterate through the list of provided URLs. If a server is unavailable, iterating through the list of URLs will continue until a successful connection is made. * `dns_round_robin`: In this mode of operation, only a single URL may be specified. This URL must contain a DNS name. The system will be queried for all IP addresses that correspond to this DNS name. Connections will continuously iterate through the list of addresses. If a server is unavailable, iterating through the list of URLs will continue until a successful connection is made. [float] [[ssl-tls-settings]] ==== Default TLS/SSL settings You can configure the following TLS/SSL settings in `elasticsearch.yml`. For more information, see {xpack-ref}/encrypting-communications.html[Encrypting communications]. These settings will be used for all of {xpack} unless they have been overridden by more specific settings such as those for HTTP or Transport. `xpack.ssl.supported_protocols`:: Supported protocols with versions. Valid protocols: `SSLv2Hello`, `SSLv3`, `TLSv1`, `TLSv1.1`, `TLSv1.2`. Defaults to `TLSv1.2`, `TLSv1.1`, `TLSv1`. `xpack.ssl.client_authentication`:: Controls the server's behavior in regard to requesting a certificate from client connections. Valid values are `required`, `optional`, and `none`. `required` forces a client to present a certificate, while `optional` requests a client certificate but the client is not required to present one. Defaults to `required`. This global setting is not applicable for HTTP, see <>. `xpack.ssl.verification_mode`:: Controls the verification of certificates. Valid values are: - `full`, which verifies that the provided certificate is signed by a trusted authority (CA) and also verifies that the server's hostname (or IP address) matches the names identified within the certificate. - `certificate`, which verifies that the provided certificate is signed by a trusted authority (CA), but does not perform any hostname verification. - `none`, which performs _no verification_ of the server's certificate. This mode disables many of the security benefits of SSL/TLS and should only be used after very careful consideration. It is primarily intended as a temporary diagnostic mechanism when attempting to resolve TLS errors, and its use on production clusters is strongly discouraged. + The default value is `full`. `xpack.ssl.cipher_suites`:: Supported cipher suites can be found in Oracle's http://docs.oracle.com/javase/8/docs/technotes/guides/security/SunProviders.html[ Java Cryptography Architecture documentation]. Defaults to `TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256`, `TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256`, `TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA`, `TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA`, `TLS_RSA_WITH_AES_128_CBC_SHA256`, `TLS_RSA_WITH_AES_128_CBC_SHA`. If the _Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files_ has been installed, the default value also includes `TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384`, `TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384`, `TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA`, `TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA`, `TLS_RSA_WITH_AES_256_CBC_SHA256`, `TLS_RSA_WITH_AES_256_CBC_SHA`. [float] [[tls-ssl-key-settings]] ===== Default TLS/SSL key and trusted certificate settings The following settings are used to specify a private key, certificate, and the trusted certificates that should be used when communicating over an SSL/TLS connection. If none of the settings below are specified, this will default to the <>. If no trusted certificates are configured, the default certificates that are trusted by the JVM will be trusted along with the certificate(s) from the <>. The key and certificate must be in place for connections that require client authentication or when acting as a SSL enabled server. [float] ===== PEM encoded files When using PEM encoded files, use the following settings: `xpack.ssl.key`:: Path to the PEM encoded file containing the private key. `xpack.ssl.key_passphrase`:: The passphrase that is used to decrypt the private key. This value is optional as the key might not be encrypted. `xpack.ssl.secure_key_passphrase` ({<>):: The passphrase that is used to decrypt the private key. This value is optional as the key might not be encrypted. `xpack.ssl.certificate`:: Path to a PEM encoded file containing the certificate (or certificate chain) that will be presented to clients when they connect. `xpack.ssl.certificate_authorities`:: List of paths to the PEM encoded certificate files that should be trusted. [float] ===== Java keystore files When using Java keystore files (JKS), which contain the private key, certificate and certificates that should be trusted, use the following settings: `xpack.ssl.keystore.path`:: Path to the keystore that holds the private key and certificate. `xpack.ssl.keystore.password`:: Password to the keystore. `xpack.ssl.keystore.secure_password` (<>):: Password to the keystore. `xpack.ssl.keystore.key_password`:: Password for the private key in the keystore. Defaults to the same value as `xpack.ssl.keystore.password`. `xpack.ssl.keystore.secure_key_password` (<>):: Password for the private key in the keystore. `xpack.ssl.truststore.path`:: Path to the truststore file. `xpack.ssl.truststore.password`:: Password to the truststore. `xpack.ssl.truststore.secure_password` (<>):: Password to the truststore. [float] ===== PKCS#12 files When using PKCS#12 container files (`.p12` or `.pfx`), which contain the private key, certificate, and certificates that should be trusted, use the following settings: `xpack.ssl.keystore.path`:: Path to the PKCS#12 file that holds the private key and certificate. `xpack.ssl.keystore.type`:: Set this to `PKCS12`. `xpack.ssl.keystore.password`:: Password to the PKCS#12 file. `xpack.ssl.keystore.secure_password` (<>):: Password to the PKCS#12 file. `xpack.ssl.keystore.key_password`:: Password for the private key in the PKCS12 file. Defaults to the same value as `xpack.ssl.keystore.password`. `xpack.ssl.keystore.secure_key_password` (<>):: Password for the private key in the PKCS12 file. `xpack.ssl.truststore.path`:: Path to the truststore file. `xpack.ssl.truststore.type`:: Set this to `PKCS12`. `xpack.ssl.truststore.password`:: Password to the truststore. `xpack.ssl.truststore.secure_password` (<>):: Password to the truststore. [[http-tls-ssl-settings]] :ssl-prefix: xpack.security.http :component: HTTP :client-auth-default: none :verifies!: :server: include::ssl-settings.asciidoc[] [[transport-tls-ssl-settings]] :ssl-prefix: xpack.security.transport :component: Transport :client-auth-default!: :verifies: :server: include::ssl-settings.asciidoc[] [[ssl-tls-profile-settings]] [float] ===== Transport profile TLS/SSL settings The same settings that are available for the <> are also available for each transport profile. By default, the settings for a transport profile will be the same as the default transport unless they are specified. As an example, lets look at the key setting. For the default transport this is `xpack.security.transport.ssl.key`. In order to use this setting in a transport profile, use the prefix `transport.profiles.$PROFILE.xpack.security.` and append the portion of the setting after `xpack.security.transport.`. For the key setting, this would be `transport.profiles.$PROFILE.xpack.security.ssl.key`. [float] [[ip-filtering-settings]] ==== IP filtering settings You can configure the following settings for {xpack-ref}/ip-filtering.html[IP filtering]. `xpack.security.transport.filter.allow`:: List of IP addresses to allow. `xpack.security.transport.filter.deny`:: List of IP addresses to deny. `xpack.security.http.filter.allow`:: List of IP addresses to allow just for HTTP. `xpack.security.http.filter.deny`:: List of IP addresses to deny just for HTTP. `transport.profiles.$PROFILE.xpack.security.filter.allow`:: List of IP addresses to allow for this profile. `transport.profiles.$PROFILE.xpack.security.filter.deny`:: List of IP addresses to deny for this profile. ",12350,False,2437.3557965046953,median "// tag::HeaderFullDisplayName[] = repo.usp_PERSIST_RepoObject_external_tgt - P // end::HeaderFullDisplayName[] == existing_properties // tag::existing_properties[] :ExistsProperty--adocuspsteps: :ExistsProperty--antorareferencedlist: :ExistsProperty--antorareferencinglist: :ExistsProperty--exampleusage: :ExistsProperty--is_repo_managed: :ExistsProperty--is_ssas: :ExistsProperty--referencedobjectlist: :ExistsProperty--uspgenerator_usp_id: :ExistsProperty--sql_modules_definition: :ExistsProperty--AntoraParameterList: // end::existing_properties[] == RepoObject_guid // tag::RepoObject_guid[] 83B52D46-1B1B-EC11-8520-A81E8446D5B0 // end::RepoObject_guid[] == RepoObject_FullDisplayName2 // tag::RepoObject_FullDisplayName2[] repo.usp_PERSIST_RepoObject_external_tgt // end::RepoObject_FullDisplayName2[] == SysObject_type // tag::SysObject_type[] P // end::SysObject_type[] == SysObject_type_name // tag::SysObject_type_name[] stored procedure // end::SysObject_type_name[] == SysObject_id // tag::SysObject_id[] 1116583066 // end::SysObject_id[] == SysObject_modify_date // tag::SysObject_modify_date[] 2021-12-17 19:13:08 // end::SysObject_modify_date[] == AntoraColumnDetails // tag::AntoraColumnDetails[] // end::AntoraColumnDetails[] == AntoraPkColumnTableRows // tag::AntoraPkColumnTableRows[] // end::AntoraPkColumnTableRows[] == AntoraNonPkColumnTableRows // tag::AntoraNonPkColumnTableRows[] // end::AntoraNonPkColumnTableRows[] == AntoraIndexList // tag::AntoraIndexList[] // end::AntoraIndexList[] == AntoraMeasureDetails // tag::AntoraMeasureDetails[] // end::AntoraMeasureDetails[] == AntoraMeasureDescriptions == AntoraParameterList // tag::AntoraParameterList[] * @execution_instance_guid (uniqueidentifier) * @ssis_execution_id (bigint) * @sub_execution_id (int) * @parent_execution_log_id (bigint) // end::AntoraParameterList[] == AntoraXrefCulturesList // tag::AntoraXrefCulturesList[] * xref:dhw:sqldb:repo.usp_persist_repoobject_external_tgt.adoc[] - // end::AntoraXrefCulturesList[] == cultures_count // tag::cultures_count[] 1 // end::cultures_count[] == Other tags source: property.RepoObjectProperty_cross As rop_cross === additional_reference_csv // tag::additional_reference_csv[] // end::additional_reference_csv[] === AdocUspSteps // tag::adocuspsteps[] .Steps in [repo].[usp_PERSIST_RepoObject_external_tgt] [cols=""d,15a,d""] |=== |Number|Name (Action, Source, Target)|Parent |500 | *delete persistence target missing in source* * D * [repo].[RepoObject_external_src] * [repo].[RepoObject_external_tgt] .Statement [%collapsible] ===== [source,sql,numbered] ---- DELETE T FROM [repo].[RepoObject_external_tgt] AS T WHERE NOT EXISTS (SELECT 1 FROM [repo].[RepoObject_external_src] AS S WHERE T.[RepoObject_guid] = S.[RepoObject_guid] ) ---- ===== | |600 | *update changed* * U * [repo].[RepoObject_external_src] * [repo].[RepoObject_external_tgt] .Statement [%collapsible] ===== [source,sql,numbered] ---- UPDATE T SET T.[RepoObject_guid] = S.[RepoObject_guid] , T.[external_AntoraComponent] = S.[external_AntoraComponent] , T.[external_AntoraModule] = S.[external_AntoraModule] , T.[is_external] = S.[is_external] , T.[is_repo_managed] = S.[is_repo_managed] , T.[RepoObject_name] = S.[RepoObject_name] , T.[RepoObject_schema_name] = S.[RepoObject_schema_name] , T.[RepoObject_type] = S.[RepoObject_type] , T.[SysObject_name] = S.[SysObject_name] , T.[SysObject_schema_name] = S.[SysObject_schema_name] , T.[SysObject_type] = S.[SysObject_type] FROM [repo].[RepoObject_external_tgt] AS T INNER JOIN [repo].[RepoObject_external_src] AS S ON T.[RepoObject_guid] = S.[RepoObject_guid] WHERE T.[external_AntoraComponent] <> S.[external_AntoraComponent] OR T.[external_AntoraModule] <> S.[external_AntoraModule] OR T.[is_external] <> S.[is_external] OR T.[is_repo_managed] <> S.[is_repo_managed] OR T.[RepoObject_name] <> S.[RepoObject_name] OR T.[RepoObject_schema_name] <> S.[RepoObject_schema_name] OR T.[RepoObject_type] <> S.[RepoObject_type] OR T.[SysObject_name] <> S.[SysObject_name] OR T.[SysObject_schema_name] <> S.[SysObject_schema_name] OR T.[SysObject_type] <> S.[SysObject_type] ---- ===== | |700 | *insert missing* * I * [repo].[RepoObject_external_src] * [repo].[RepoObject_external_tgt] .Statement [%collapsible] ===== [source,sql,numbered] ---- INSERT INTO [repo].[RepoObject_external_tgt] ( [RepoObject_guid] , [external_AntoraComponent] , [external_AntoraModule] , [is_external] , [is_repo_managed] , [RepoObject_name] , [RepoObject_schema_name] , [RepoObject_type] , [SysObject_name] , [SysObject_schema_name] , [SysObject_type] ) SELECT [RepoObject_guid] , [external_AntoraComponent] , [external_AntoraModule] , [is_external] , [is_repo_managed] , [RepoObject_name] , [RepoObject_schema_name] , [RepoObject_type] , [SysObject_name] , [SysObject_schema_name] , [SysObject_type] FROM [repo].[RepoObject_external_src] AS S WHERE NOT EXISTS (SELECT 1 FROM [repo].[RepoObject_external_tgt] AS T WHERE T.[RepoObject_guid] = S.[RepoObject_guid] ) ---- ===== | |=== // end::adocuspsteps[] === AntoraReferencedList // tag::antorareferencedlist[] * xref:dhw:sqldb:logs.usp_executionlog_insert.adoc[] * xref:dhw:sqldb:repo.repoobject_external_src.adoc[] * xref:dhw:sqldb:repo.repoobject_external_tgt.adoc[] // end::antorareferencedlist[] === AntoraReferencingList // tag::antorareferencinglist[] * xref:dhw:sqldb:reference.usp_additional_reference.adoc[] // end::antorareferencinglist[] === Description // tag::description[] // end::description[] === exampleUsage // tag::exampleusage[] EXEC [repo].[usp_PERSIST_RepoObject_external_tgt] // end::exampleusage[] === exampleUsage_2 // tag::exampleusage_2[] // end::exampleusage_2[] === exampleUsage_3 // tag::exampleusage_3[] // end::exampleusage_3[] === exampleUsage_4 // tag::exampleusage_4[] // end::exampleusage_4[] === exampleUsage_5 // tag::exampleusage_5[] // end::exampleusage_5[] === exampleWrong_Usage // tag::examplewrong_usage[] // end::examplewrong_usage[] === has_execution_plan_issue // tag::has_execution_plan_issue[] // end::has_execution_plan_issue[] === has_get_referenced_issue // tag::has_get_referenced_issue[] // end::has_get_referenced_issue[] === has_history // tag::has_history[] // end::has_history[] === has_history_columns // tag::has_history_columns[] // end::has_history_columns[] === InheritanceType // tag::inheritancetype[] // end::inheritancetype[] === is_persistence // tag::is_persistence[] // end::is_persistence[] === is_persistence_check_duplicate_per_pk // tag::is_persistence_check_duplicate_per_pk[] // end::is_persistence_check_duplicate_per_pk[] === is_persistence_check_for_empty_source // tag::is_persistence_check_for_empty_source[] // end::is_persistence_check_for_empty_source[] === is_persistence_delete_changed // tag::is_persistence_delete_changed[] // end::is_persistence_delete_changed[] === is_persistence_delete_missing // tag::is_persistence_delete_missing[] // end::is_persistence_delete_missing[] === is_persistence_insert // tag::is_persistence_insert[] // end::is_persistence_insert[] === is_persistence_truncate // tag::is_persistence_truncate[] // end::is_persistence_truncate[] === is_persistence_update_changed // tag::is_persistence_update_changed[] // end::is_persistence_update_changed[] === is_repo_managed // tag::is_repo_managed[] 0 // end::is_repo_managed[] === is_ssas // tag::is_ssas[] 0 // end::is_ssas[] === microsoft_database_tools_support // tag::microsoft_database_tools_support[] // end::microsoft_database_tools_support[] === MS_Description // tag::ms_description[] // end::ms_description[] === persistence_source_RepoObject_fullname // tag::persistence_source_repoobject_fullname[] // end::persistence_source_repoobject_fullname[] === persistence_source_RepoObject_fullname2 // tag::persistence_source_repoobject_fullname2[] // end::persistence_source_repoobject_fullname2[] === persistence_source_RepoObject_guid // tag::persistence_source_repoobject_guid[] // end::persistence_source_repoobject_guid[] === persistence_source_RepoObject_xref // tag::persistence_source_repoobject_xref[] // end::persistence_source_repoobject_xref[] === pk_index_guid // tag::pk_index_guid[] // end::pk_index_guid[] === pk_IndexPatternColumnDatatype // tag::pk_indexpatterncolumndatatype[] // end::pk_indexpatterncolumndatatype[] === pk_IndexPatternColumnName // tag::pk_indexpatterncolumnname[] // end::pk_indexpatterncolumnname[] === pk_IndexSemanticGroup // tag::pk_indexsemanticgroup[] // end::pk_indexsemanticgroup[] === ReferencedObjectList // tag::referencedobjectlist[] * [logs].[usp_ExecutionLog_insert] * [repo].[RepoObject_external_src] * [repo].[RepoObject_external_tgt] // end::referencedobjectlist[] === usp_persistence_RepoObject_guid // tag::usp_persistence_repoobject_guid[] // end::usp_persistence_repoobject_guid[] === UspExamples // tag::uspexamples[] // end::uspexamples[] === uspgenerator_usp_id // tag::uspgenerator_usp_id[] 97 // end::uspgenerator_usp_id[] === UspParameters // tag::uspparameters[] // end::uspparameters[] == Boolean Attributes source: property.RepoObjectProperty WHERE property_int = 1 // tag::boolean_attributes[] // end::boolean_attributes[] == PlantUML diagrams === PlantUML Entity // tag::puml_entity[] [plantuml, entity-{docname}, svg, subs=macros] .... 'Left to right direction top to bottom direction hide circle 'avoide ""."" issues: set namespaceSeparator none skinparam class { BackgroundColor White BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<> LightGray BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<

> Aqua BackgroundColor<> Aqua BackgroundColor<> Yellow BackgroundColor<> SlateBlue BackgroundColor<> LightGray BackgroundColor<> Tomato BackgroundColor<> White BackgroundColor<> WhiteSmoke BackgroundColor<> Aqua BackgroundColor<> AliceBlue } entity ""puml-link:dhw:sqldb:repo.usp_persist_repoobject_external_tgt.adoc[]"" as repo.usp_PERSIST_RepoObject_external_tgt << P >> { -- } .... // end::puml_entity[] === PlantUML Entity 1 1 FK // tag::puml_entity_1_1_fk[] [plantuml, entity_1_1_fk-{docname}, svg, subs=macros] .... @startuml left to right direction 'top to bottom direction hide circle 'avoide ""."" issues: set namespaceSeparator none skinparam class { BackgroundColor White BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<> LightGray BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<

> Aqua BackgroundColor<> Aqua BackgroundColor<> Yellow BackgroundColor<> SlateBlue BackgroundColor<> LightGray BackgroundColor<> Tomato BackgroundColor<> White BackgroundColor<> WhiteSmoke BackgroundColor<> Aqua BackgroundColor<> AliceBlue } footer The diagram is interactive and contains links. @enduml .... // end::puml_entity_1_1_fk[] === PlantUML 1 1 ObjectRef // tag::puml_entity_1_1_objectref[] [plantuml, entity_1_1_objectref-{docname}, svg, subs=macros] .... @startuml left to right direction 'top to bottom direction hide circle 'avoide ""."" issues: set namespaceSeparator none skinparam class { BackgroundColor White BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<> LightGray BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<

> Aqua BackgroundColor<> Aqua BackgroundColor<> Yellow BackgroundColor<> SlateBlue BackgroundColor<> LightGray BackgroundColor<> Tomato BackgroundColor<> White BackgroundColor<> WhiteSmoke BackgroundColor<> Aqua BackgroundColor<> AliceBlue } entity ""puml-link:dhw:sqldb:logs.usp_executionlog_insert.adoc[]"" as logs.usp_ExecutionLog_insert << P >> { -- } entity ""puml-link:dhw:sqldb:reference.usp_additional_reference.adoc[]"" as reference.usp_additional_Reference << P >> { -- } entity ""puml-link:dhw:sqldb:repo.repoobject_external_src.adoc[]"" as repo.RepoObject_external_src << V >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobject_external_tgt.adoc[]"" as repo.RepoObject_external_tgt << V >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.usp_persist_repoobject_external_tgt.adoc[]"" as repo.usp_PERSIST_RepoObject_external_tgt << P >> { -- } logs.usp_ExecutionLog_insert <.. repo.usp_PERSIST_RepoObject_external_tgt repo.RepoObject_external_src <.. repo.usp_PERSIST_RepoObject_external_tgt repo.RepoObject_external_tgt <.. repo.usp_PERSIST_RepoObject_external_tgt repo.usp_PERSIST_RepoObject_external_tgt <.. reference.usp_additional_Reference footer The diagram is interactive and contains links. @enduml .... // end::puml_entity_1_1_objectref[] === PlantUML 30 0 ObjectRef // tag::puml_entity_30_0_objectref[] [plantuml, entity_30_0_objectref-{docname}, svg, subs=macros] .... @startuml 'Left to right direction top to bottom direction hide circle 'avoide ""."" issues: set namespaceSeparator none skinparam class { BackgroundColor White BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<> LightGray BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<

> Aqua BackgroundColor<> Aqua BackgroundColor<> Yellow BackgroundColor<> SlateBlue BackgroundColor<> LightGray BackgroundColor<> Tomato BackgroundColor<> White BackgroundColor<> WhiteSmoke BackgroundColor<> Aqua BackgroundColor<> AliceBlue } entity ""puml-link:dhw:sqldb:config.ftv_get_parameter_value.adoc[]"" as config.ftv_get_parameter_value << IF >> { -- } entity ""puml-link:dhw:sqldb:config.parameter.adoc[]"" as config.Parameter << U >> { - **Parameter_name** : (varchar(100)) - **sub_Parameter** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:configt.parameter_default.adoc[]"" as configT.Parameter_default << V >> { - **Parameter_name** : (varchar(52)) - **sub_Parameter** : (nvarchar(26)) -- } entity ""puml-link:dhw:sqldb:logs.executionlog.adoc[]"" as logs.ExecutionLog << U >> { - **id** : (bigint) -- } entity ""puml-link:dhw:sqldb:logs.usp_executionlog_insert.adoc[]"" as logs.usp_ExecutionLog_insert << P >> { -- } entity ""puml-link:dhw:sqldb:property.external_repoobjectproperty.adoc[]"" as property.external_RepoObjectProperty << U >> { - **RepoObject_guid** : (uniqueidentifier) - **property_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:property.propertyname_repoobject.adoc[]"" as property.PropertyName_RepoObject << V >> { **property_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:property.propertyname_repoobject_t.adoc[]"" as property.PropertyName_RepoObject_T << U >> { **property_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:property.repoobjectproperty.adoc[]"" as property.RepoObjectProperty << U >> { - **RepoObjectProperty_id** : (int) -- } entity ""puml-link:dhw:sqldb:property.repoobjectproperty_external_src.adoc[]"" as property.RepoObjectProperty_external_src << V >> { - **RepoObject_guid** : (uniqueidentifier) - **property_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:property.repoobjectproperty_external_tgt.adoc[]"" as property.RepoObjectProperty_external_tgt << V >> { - **RepoObject_guid** : (uniqueidentifier) - **property_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:property.repoobjectproperty_selectedpropertyname_split.adoc[]"" as property.RepoObjectProperty_SelectedPropertyName_split << V >> { -- } entity ""puml-link:dhw:sqldb:reference.additional_reference.adoc[]"" as reference.additional_Reference << U >> { - **Id** : (int) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_from_properties_src.adoc[]"" as reference.additional_Reference_from_properties_src << V >> { **referenced_AntoraComponent** : (nvarchar(max)) **referenced_AntoraModule** : (nvarchar(max)) **referenced_Schema** : (nvarchar(max)) **referenced_Object** : (nvarchar(max)) **referenced_Column** : (nvarchar(max)) **referencing_AntoraComponent** : (nvarchar(max)) **referencing_AntoraModule** : (nvarchar(max)) **referencing_Schema** : (nvarchar(max)) **referencing_Object** : (nvarchar(max)) **referencing_Column** : (nvarchar(max)) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_from_properties_tgt.adoc[]"" as reference.additional_Reference_from_properties_tgt << V >> { **referenced_AntoraComponent** : (nvarchar(max)) **referenced_AntoraModule** : (nvarchar(max)) **referenced_Schema** : (nvarchar(max)) **referenced_Object** : (nvarchar(max)) **referenced_Column** : (nvarchar(max)) **referencing_AntoraComponent** : (nvarchar(max)) **referencing_AntoraModule** : (nvarchar(max)) **referencing_Schema** : (nvarchar(max)) **referencing_Object** : (nvarchar(max)) **referencing_Column** : (nvarchar(max)) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_from_ssas_src.adoc[]"" as reference.additional_Reference_from_ssas_src << V >> { **referenced_AntoraComponent** : (nvarchar(128)) **referenced_AntoraModule** : (nvarchar(128)) **referenced_Schema** : (nvarchar(max)) **referenced_Object** : (nvarchar(max)) **referenced_Column** : (nvarchar(500)) **referencing_AntoraComponent** : (nvarchar(max)) **referencing_AntoraModule** : (nvarchar(max)) - **referencing_Schema** : (nvarchar(128)) - **referencing_Object** : (nvarchar(128)) **referencing_Column** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_from_ssas_tgt.adoc[]"" as reference.additional_Reference_from_ssas_tgt << V >> { **referenced_AntoraComponent** : (nvarchar(128)) **referenced_AntoraModule** : (nvarchar(128)) **referenced_Schema** : (nvarchar(max)) **referenced_Object** : (nvarchar(max)) **referenced_Column** : (nvarchar(500)) **referencing_AntoraComponent** : (nvarchar(max)) **referencing_AntoraModule** : (nvarchar(max)) - **referencing_Schema** : (nvarchar(128)) - **referencing_Object** : (nvarchar(128)) **referencing_Column** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_is_external.adoc[]"" as reference.additional_Reference_is_external << V >> { -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_object.adoc[]"" as reference.additional_Reference_Object << V >> { - **AntoraComponent** : (nvarchar(128)) - **AntoraModule** : (nvarchar(128)) - **SchemaName** : (nvarchar(128)) - **ObjectName** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_object_t.adoc[]"" as reference.additional_Reference_Object_T << U >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_wo_columns_from_properties_src.adoc[]"" as reference.additional_Reference_wo_columns_from_properties_src << V >> { **referenced_AntoraComponent** : (nvarchar(max)) **referenced_AntoraModule** : (nvarchar(max)) **referenced_Schema** : (nvarchar(max)) **referenced_Object** : (nvarchar(max)) **referencing_AntoraComponent** : (nvarchar(max)) **referencing_AntoraModule** : (nvarchar(max)) **referencing_Schema** : (nvarchar(max)) **referencing_Object** : (nvarchar(max)) -- } entity ""puml-link:dhw:sqldb:reference.additional_reference_wo_columns_from_properties_tgt.adoc[]"" as reference.additional_Reference_wo_columns_from_properties_tgt << V >> { **referenced_AntoraComponent** : (nvarchar(max)) **referenced_AntoraModule** : (nvarchar(max)) **referenced_Schema** : (nvarchar(max)) **referenced_Object** : (nvarchar(max)) **referencing_AntoraComponent** : (nvarchar(max)) **referencing_AntoraModule** : (nvarchar(max)) **referencing_Schema** : (nvarchar(max)) **referencing_Object** : (nvarchar(max)) -- } entity ""puml-link:dhw:sqldb:repo.repoobject.adoc[]"" as repo.RepoObject << U >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobject_external_src.adoc[]"" as repo.RepoObject_external_src << V >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobject_external_tgt.adoc[]"" as repo.RepoObject_external_tgt << V >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobject_ssas_src.adoc[]"" as repo.RepoObject_SSAS_src << V >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.repoobject_ssas_tgt.adoc[]"" as repo.RepoObject_SSAS_tgt << V >> { - **RepoObject_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.reposchema.adoc[]"" as repo.RepoSchema << U >> { - **RepoSchema_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.reposchema_ssas_src.adoc[]"" as repo.RepoSchema_ssas_src << V >> { - **RepoSchema_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:repo.reposchema_ssas_tgt.adoc[]"" as repo.RepoSchema_ssas_tgt << V >> { - **RepoSchema_guid** : (uniqueidentifier) -- } entity ""puml-link:dhw:sqldb:repo.usp_persist_repoobject_external_tgt.adoc[]"" as repo.usp_PERSIST_RepoObject_external_tgt << P >> { -- } entity ""puml-link:dhw:sqldb:ssas.additional_reference_step1.adoc[]"" as ssas.additional_Reference_step1 << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json.adoc[]"" as ssas.model_json << U >> { - **databasename** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_10.adoc[]"" as ssas.model_json_10 << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_20.adoc[]"" as ssas.model_json_20 << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_201_descriptions_multiline.adoc[]"" as ssas.model_json_201_descriptions_multiline << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_2011_descriptions_stragg.adoc[]"" as ssas.model_json_2011_descriptions_StrAgg << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_31_tables.adoc[]"" as ssas.model_json_31_tables << V >> { - **databasename** : (nvarchar(128)) **tables_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_31_tables_t.adoc[]"" as ssas.model_json_31_tables_T << U >> { - **databasename** : (nvarchar(128)) **tables_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_311_tables_columns.adoc[]"" as ssas.model_json_311_tables_columns << V >> { - **databasename** : (nvarchar(128)) - **tables_name** : (nvarchar(128)) **tables_columns_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_311_tables_columns_t.adoc[]"" as ssas.model_json_311_tables_columns_T << U >> { - **databasename** : (nvarchar(128)) - **tables_name** : (nvarchar(128)) **tables_columns_name** : (nvarchar(128)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_313_tables_partitions.adoc[]"" as ssas.model_json_313_tables_partitions << V >> { - **databasename** : (nvarchar(128)) - **tables_name** : (nvarchar(128)) **tables_partitions_name** : (nvarchar(500)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_3131_tables_partitions_source.adoc[]"" as ssas.model_json_3131_tables_partitions_source << V >> { - **databasename** : (nvarchar(128)) - **tables_name** : (nvarchar(128)) **tables_partitions_name** : (nvarchar(500)) **tables_partitions_source_name** : (nvarchar(500)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_31311_tables_partitions_source_posfrom.adoc[]"" as ssas.model_json_31311_tables_partitions_source_PosFrom << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_313111_tables_partitions_source_stringfrom.adoc[]"" as ssas.model_json_313111_tables_partitions_source_StringFrom << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_3131111_tables_partitions_source_posdot.adoc[]"" as ssas.model_json_3131111_tables_partitions_source_PosDot << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_31311111_tables_partitions_source_part123.adoc[]"" as ssas.model_json_31311111_tables_partitions_source_Part123 << V >> { -- } entity ""puml-link:dhw:sqldb:ssas.model_json_33_datasources.adoc[]"" as ssas.model_json_33_dataSources << V >> { - **databasename** : (nvarchar(128)) **dataSources_name** : (nvarchar(500)) -- } entity ""puml-link:dhw:sqldb:ssas.model_json_33_datasources_t.adoc[]"" as ssas.model_json_33_dataSources_T << U >> { - **databasename** : (nvarchar(128)) **dataSources_name** : (nvarchar(500)) -- } config.ftv_get_parameter_value <.. repo.RepoObject_external_src config.ftv_get_parameter_value <.. reference.additional_Reference_is_external config.ftv_get_parameter_value <.. ssas.additional_Reference_step1 config.Parameter <.. config.ftv_get_parameter_value config.Parameter <.. property.PropertyName_RepoObject configT.Parameter_default <.. config.Parameter logs.ExecutionLog <.. logs.usp_ExecutionLog_insert logs.usp_ExecutionLog_insert <.. repo.usp_PERSIST_RepoObject_external_tgt property.external_RepoObjectProperty <.. property.RepoObjectProperty_external_src property.PropertyName_RepoObject <.. property.PropertyName_RepoObject_T property.PropertyName_RepoObject_T <.. property.RepoObjectProperty_external_tgt property.RepoObjectProperty <.. property.RepoObjectProperty_SelectedPropertyName_split property.RepoObjectProperty <.. property.PropertyName_RepoObject property.RepoObjectProperty_external_src <.. property.RepoObjectProperty_external_tgt property.RepoObjectProperty_external_tgt <.. property.RepoObjectProperty property.RepoObjectProperty_SelectedPropertyName_split <.. reference.additional_Reference_from_properties_src property.RepoObjectProperty_SelectedPropertyName_split <.. reference.additional_Reference_wo_columns_from_properties_src reference.additional_Reference <.. reference.additional_Reference_is_external reference.additional_Reference_from_properties_src <.. reference.additional_Reference_from_properties_tgt reference.additional_Reference_from_properties_tgt <.. reference.additional_Reference reference.additional_Reference_from_ssas_src <.. reference.additional_Reference_from_ssas_tgt reference.additional_Reference_from_ssas_tgt <.. reference.additional_Reference reference.additional_Reference_is_external <.. reference.additional_Reference_Object reference.additional_Reference_Object <.. reference.additional_Reference_Object_T reference.additional_Reference_Object_T <.. repo.RepoObject_external_src reference.additional_Reference_wo_columns_from_properties_src <.. reference.additional_Reference_wo_columns_from_properties_tgt reference.additional_Reference_wo_columns_from_properties_tgt <.. reference.additional_Reference repo.RepoObject <.. property.RepoObjectProperty_external_tgt repo.RepoObject <.. repo.RepoObject_external_src repo.RepoObject_external_src <.. repo.RepoObject_external_tgt repo.RepoObject_external_src <.. repo.usp_PERSIST_RepoObject_external_tgt repo.RepoObject_external_tgt <.. repo.usp_PERSIST_RepoObject_external_tgt repo.RepoObject_external_tgt <.. repo.RepoObject repo.RepoObject_SSAS_src <.. repo.RepoObject_SSAS_tgt repo.RepoObject_SSAS_tgt <.. repo.RepoObject repo.RepoSchema <.. repo.RepoObject_SSAS_src repo.RepoSchema_ssas_src <.. repo.RepoSchema_ssas_tgt repo.RepoSchema_ssas_tgt <.. repo.RepoSchema ssas.additional_Reference_step1 <.. reference.additional_Reference_from_ssas_src ssas.model_json <.. ssas.model_json_10 ssas.model_json_10 <.. ssas.model_json_20 ssas.model_json_20 <.. repo.RepoSchema_ssas_src ssas.model_json_20 <.. ssas.model_json_201_descriptions_multiline ssas.model_json_20 <.. ssas.model_json_31_tables ssas.model_json_20 <.. ssas.model_json_33_dataSources ssas.model_json_201_descriptions_multiline <.. ssas.model_json_2011_descriptions_StrAgg ssas.model_json_2011_descriptions_StrAgg <.. repo.RepoSchema_ssas_src ssas.model_json_31_tables <.. ssas.model_json_31_tables_T ssas.model_json_31_tables_T <.. repo.RepoObject_SSAS_src ssas.model_json_31_tables_T <.. ssas.model_json_311_tables_columns ssas.model_json_31_tables_T <.. ssas.model_json_313_tables_partitions ssas.model_json_311_tables_columns <.. ssas.model_json_311_tables_columns_T ssas.model_json_311_tables_columns_T <.. ssas.additional_Reference_step1 ssas.model_json_313_tables_partitions <.. ssas.model_json_3131_tables_partitions_source ssas.model_json_3131_tables_partitions_source <.. ssas.model_json_31311_tables_partitions_source_PosFrom ssas.model_json_31311_tables_partitions_source_PosFrom <.. ssas.model_json_313111_tables_partitions_source_StringFrom ssas.model_json_313111_tables_partitions_source_StringFrom <.. ssas.model_json_3131111_tables_partitions_source_PosDot ssas.model_json_3131111_tables_partitions_source_PosDot <.. ssas.model_json_31311111_tables_partitions_source_Part123 ssas.model_json_31311111_tables_partitions_source_Part123 <.. ssas.additional_Reference_step1 ssas.model_json_33_dataSources <.. ssas.model_json_33_dataSources_T ssas.model_json_33_dataSources_T <.. ssas.additional_Reference_step1 footer The diagram is interactive and contains links. @enduml .... // end::puml_entity_30_0_objectref[] === PlantUML 0 30 ObjectRef // tag::puml_entity_0_30_objectref[] [plantuml, entity_0_30_objectref-{docname}, svg, subs=macros] .... @startuml 'Left to right direction top to bottom direction hide circle 'avoide ""."" issues: set namespaceSeparator none skinparam class { BackgroundColor White BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<> LightGray BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<

> Aqua BackgroundColor<> Aqua BackgroundColor<> Yellow BackgroundColor<> SlateBlue BackgroundColor<> LightGray BackgroundColor<> Tomato BackgroundColor<> White BackgroundColor<> WhiteSmoke BackgroundColor<> Aqua BackgroundColor<> AliceBlue } entity ""puml-link:dhw:sqldb:property.usp_external_property_import.adoc[]"" as property.usp_external_property_import << P >> { -- } entity ""puml-link:dhw:sqldb:reference.usp_additional_reference.adoc[]"" as reference.usp_additional_Reference << P >> { -- } entity ""puml-link:dhw:sqldb:repo.usp_main.adoc[]"" as repo.usp_main << P >> { -- } entity ""puml-link:dhw:sqldb:repo.usp_persist_repoobject_external_tgt.adoc[]"" as repo.usp_PERSIST_RepoObject_external_tgt << P >> { -- } property.usp_external_property_import <.. repo.usp_main reference.usp_additional_Reference <.. property.usp_external_property_import reference.usp_additional_Reference <.. repo.usp_main repo.usp_PERSIST_RepoObject_external_tgt <.. reference.usp_additional_Reference footer The diagram is interactive and contains links. @enduml .... // end::puml_entity_0_30_objectref[] === PlantUML 1 1 ColumnRef // tag::puml_entity_1_1_colref[] [plantuml, entity_1_1_colref-{docname}, svg, subs=macros] .... @startuml left to right direction 'top to bottom direction hide circle 'avoide ""."" issues: set namespaceSeparator none skinparam class { BackgroundColor White BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<> LightGray BackgroundColor<> Yellow BackgroundColor<> Yellow BackgroundColor<

> Aqua BackgroundColor<> Aqua BackgroundColor<> Yellow BackgroundColor<> SlateBlue BackgroundColor<> LightGray BackgroundColor<> Tomato BackgroundColor<> White BackgroundColor<> WhiteSmoke BackgroundColor<> Aqua BackgroundColor<> AliceBlue } entity ""puml-link:dhw:sqldb:logs.usp_executionlog_insert.adoc[]"" as logs.usp_ExecutionLog_insert << P >> { -- } entity ""puml-link:dhw:sqldb:reference.usp_additional_reference.adoc[]"" as reference.usp_additional_Reference << P >> { -- } entity ""puml-link:dhw:sqldb:repo.repoobject_external_src.adoc[]"" as repo.RepoObject_external_src << V >> { - **RepoObject_guid** : (uniqueidentifier) - external_AntoraComponent : (nvarchar(128)) - external_AntoraModule : (nvarchar(128)) - is_external : (int) - is_repo_managed : (int) - RepoObject_name : (nvarchar(128)) - RepoObject_schema_name : (nvarchar(128)) - RepoObject_type : (varchar(1)) - SysObject_name : (nvarchar(128)) - SysObject_schema_name : (nvarchar(128)) - SysObject_type : (varchar(1)) -- } entity ""puml-link:dhw:sqldb:repo.repoobject_external_tgt.adoc[]"" as repo.RepoObject_external_tgt << V >> { - **RepoObject_guid** : (uniqueidentifier) - external_AntoraComponent : (nvarchar(128)) - external_AntoraModule : (nvarchar(128)) has_execution_plan_issue : (bit) has_get_referenced_issue : (bit) Inheritance_StringAggSeparatorSql : (nvarchar(4000)) InheritanceDefinition : (nvarchar(4000)) InheritanceType : (tinyint) - is_external : (int) - is_repo_managed : (int) is_required_ObjectMerge : (bit) - is_ssas : (bit) is_SysObject_missing : (bit) - modify_dt : (datetime) pk_index_guid : (uniqueidentifier) pk_IndexPatternColumnName_new : (nvarchar(4000)) Repo_history_table_guid : (uniqueidentifier) Repo_temporal_type : (tinyint) - RepoObject_name : (nvarchar(128)) RepoObject_Referencing_Count : (int) - RepoObject_schema_name : (nvarchar(128)) - RepoObject_type : (varchar(1)) SysObject_id : (int) SysObject_modify_date : (datetime) - SysObject_name : (nvarchar(128)) - SysObject_parent_object_id : (int) - SysObject_schema_name : (nvarchar(128)) - SysObject_type : (varchar(1)) -- } entity ""puml-link:dhw:sqldb:repo.usp_persist_repoobject_external_tgt.adoc[]"" as repo.usp_PERSIST_RepoObject_external_tgt << P >> { -- } logs.usp_ExecutionLog_insert <.. repo.usp_PERSIST_RepoObject_external_tgt repo.RepoObject_external_src <.. repo.usp_PERSIST_RepoObject_external_tgt repo.RepoObject_external_tgt <.. repo.usp_PERSIST_RepoObject_external_tgt repo.usp_PERSIST_RepoObject_external_tgt <.. reference.usp_additional_Reference footer The diagram is interactive and contains links. @enduml .... // end::puml_entity_1_1_colref[] == sql_modules_definition // tag::sql_modules_definition[] [%collapsible] ======= [source,sql,numbered,indent=0] ---- /* code of this procedure is managed in the dhw repository. Do not modify manually. Use [uspgenerator].[GeneratorUsp], [uspgenerator].[GeneratorUspParameter], [uspgenerator].[GeneratorUspStep], [uspgenerator].[GeneratorUsp_SqlUsp] */ CREATE PROCEDURE [repo].[usp_PERSIST_RepoObject_external_tgt] ----keep the code between logging parameters and ""START"" unchanged! ---- parameters, used for logging; you don't need to care about them, but you can use them, wenn calling from SSIS or in your workflow to log the context of the procedure call @execution_instance_guid UNIQUEIDENTIFIER = NULL --SSIS system variable ExecutionInstanceGUID could be used, any other unique guid is also fine. If NULL, then NEWID() is used to create one , @ssis_execution_id BIGINT = NULL --only SSIS system variable ServerExecutionID should be used, or any other consistent number system, do not mix different number systems , @sub_execution_id INT = NULL --in case you log some sub_executions, for example in SSIS loops or sub packages , @parent_execution_log_id BIGINT = NULL --in case a sup procedure is called, the @current_execution_log_id of the parent procedure should be propagated here. It allowes call stack analyzing AS BEGIN DECLARE -- @current_execution_log_id BIGINT --this variable should be filled only once per procedure call, it contains the first logging call for the step 'start'. , @current_execution_guid UNIQUEIDENTIFIER = NEWID() --a unique guid for any procedure call. It should be propagated to sub procedures using ""@parent_execution_log_id = @current_execution_log_id"" , @source_object NVARCHAR(261) = NULL --use it like '[schema].[object]', this allows data flow vizualizatiuon (include square brackets) , @target_object NVARCHAR(261) = NULL --use it like '[schema].[object]', this allows data flow vizualizatiuon (include square brackets) , @proc_id INT = @@procid , @proc_schema_name NVARCHAR(128) = OBJECT_SCHEMA_NAME(@@procid) --schema ande name of the current procedure should be automatically logged , @proc_name NVARCHAR(128) = OBJECT_NAME(@@procid) --schema ande name of the current procedure should be automatically logged , @event_info NVARCHAR(MAX) , @step_id INT = 0 , @step_name NVARCHAR(1000) = NULL , @rows INT --[event_info] get's only the information about the ""outer"" calling process --wenn the procedure calls sub procedures, the [event_info] will not change SET @event_info = ( SELECT TOP 1 [event_info] FROM sys.dm_exec_input_buffer(@@spid, CURRENT_REQUEST_ID()) ORDER BY [event_info] ) IF @execution_instance_guid IS NULL SET @execution_instance_guid = NEWID(); -- --SET @rows = @@ROWCOUNT; SET @step_id = @step_id + 1 SET @step_name = 'start' SET @source_object = NULL SET @target_object = NULL EXEC logs.usp_ExecutionLog_insert --these parameters should be the same for all logging execution @execution_instance_guid = @execution_instance_guid , @ssis_execution_id = @ssis_execution_id , @sub_execution_id = @sub_execution_id , @parent_execution_log_id = @parent_execution_log_id , @current_execution_guid = @current_execution_guid , @proc_id = @proc_id , @proc_schema_name = @proc_schema_name , @proc_name = @proc_name , @event_info = @event_info --the following parameters are individual for each call , @step_id = @step_id --@step_id should be incremented before each call , @step_name = @step_name --assign individual step names for each call --only the ""start"" step should return the log id into @current_execution_log_id --all other calls should not overwrite @current_execution_log_id , @execution_log_id = @current_execution_log_id OUTPUT ----you can log the content of your own parameters, do this only in the start-step ----data type is sql_variant -- PRINT '[repo].[usp_PERSIST_RepoObject_external_tgt]' --keep the code between logging parameters and ""START"" unchanged! -- ----START -- ----- start here with your own code -- /*{""ReportUspStep"":[{""Number"":500,""Name"":""delete persistence target missing in source"",""has_logging"":1,""is_condition"":0,""is_inactive"":0,""is_SubProcedure"":0,""log_source_object"":""[repo].[RepoObject_external_src]"",""log_target_object"":""[repo].[RepoObject_external_tgt]"",""log_flag_InsertUpdateDelete"":""D""}]}*/ PRINT CONCAT('usp_id;Number;Parent_Number: ',97,';',500,';',NULL); DELETE T FROM [repo].[RepoObject_external_tgt] AS T WHERE NOT EXISTS (SELECT 1 FROM [repo].[RepoObject_external_src] AS S WHERE T.[RepoObject_guid] = S.[RepoObject_guid] ) -- Logging START -- SET @rows = @@ROWCOUNT SET @step_id = @step_id + 1 SET @step_name = 'delete persistence target missing in source' SET @source_object = '[repo].[RepoObject_external_src]' SET @target_object = '[repo].[RepoObject_external_tgt]' EXEC logs.usp_ExecutionLog_insert @execution_instance_guid = @execution_instance_guid , @ssis_execution_id = @ssis_execution_id , @sub_execution_id = @sub_execution_id , @parent_execution_log_id = @parent_execution_log_id , @current_execution_guid = @current_execution_guid , @proc_id = @proc_id , @proc_schema_name = @proc_schema_name , @proc_name = @proc_name , @event_info = @event_info , @step_id = @step_id , @step_name = @step_name , @source_object = @source_object , @target_object = @target_object , @deleted = @rows -- Logging END -- /*{""ReportUspStep"":[{""Number"":600,""Name"":""update changed"",""has_logging"":1,""is_condition"":0,""is_inactive"":0,""is_SubProcedure"":0,""log_source_object"":""[repo].[RepoObject_external_src]"",""log_target_object"":""[repo].[RepoObject_external_tgt]"",""log_flag_InsertUpdateDelete"":""U""}]}*/ PRINT CONCAT('usp_id;Number;Parent_Number: ',97,';',600,';',NULL); UPDATE T SET T.[RepoObject_guid] = S.[RepoObject_guid] , T.[external_AntoraComponent] = S.[external_AntoraComponent] , T.[external_AntoraModule] = S.[external_AntoraModule] , T.[is_external] = S.[is_external] , T.[is_repo_managed] = S.[is_repo_managed] , T.[RepoObject_name] = S.[RepoObject_name] , T.[RepoObject_schema_name] = S.[RepoObject_schema_name] , T.[RepoObject_type] = S.[RepoObject_type] , T.[SysObject_name] = S.[SysObject_name] , T.[SysObject_schema_name] = S.[SysObject_schema_name] , T.[SysObject_type] = S.[SysObject_type] FROM [repo].[RepoObject_external_tgt] AS T INNER JOIN [repo].[RepoObject_external_src] AS S ON T.[RepoObject_guid] = S.[RepoObject_guid] WHERE T.[external_AntoraComponent] <> S.[external_AntoraComponent] OR T.[external_AntoraModule] <> S.[external_AntoraModule] OR T.[is_external] <> S.[is_external] OR T.[is_repo_managed] <> S.[is_repo_managed] OR T.[RepoObject_name] <> S.[RepoObject_name] OR T.[RepoObject_schema_name] <> S.[RepoObject_schema_name] OR T.[RepoObject_type] <> S.[RepoObject_type] OR T.[SysObject_name] <> S.[SysObject_name] OR T.[SysObject_schema_name] <> S.[SysObject_schema_name] OR T.[SysObject_type] <> S.[SysObject_type] -- Logging START -- SET @rows = @@ROWCOUNT SET @step_id = @step_id + 1 SET @step_name = 'update changed' SET @source_object = '[repo].[RepoObject_external_src]' SET @target_object = '[repo].[RepoObject_external_tgt]' EXEC logs.usp_ExecutionLog_insert @execution_instance_guid = @execution_instance_guid , @ssis_execution_id = @ssis_execution_id , @sub_execution_id = @sub_execution_id , @parent_execution_log_id = @parent_execution_log_id , @current_execution_guid = @current_execution_guid , @proc_id = @proc_id , @proc_schema_name = @proc_schema_name , @proc_name = @proc_name , @event_info = @event_info , @step_id = @step_id , @step_name = @step_name , @source_object = @source_object , @target_object = @target_object , @updated = @rows -- Logging END -- /*{""ReportUspStep"":[{""Number"":700,""Name"":""insert missing"",""has_logging"":1,""is_condition"":0,""is_inactive"":0,""is_SubProcedure"":0,""log_source_object"":""[repo].[RepoObject_external_src]"",""log_target_object"":""[repo].[RepoObject_external_tgt]"",""log_flag_InsertUpdateDelete"":""I""}]}*/ PRINT CONCAT('usp_id;Number;Parent_Number: ',97,';',700,';',NULL); INSERT INTO [repo].[RepoObject_external_tgt] ( [RepoObject_guid] , [external_AntoraComponent] , [external_AntoraModule] , [is_external] , [is_repo_managed] , [RepoObject_name] , [RepoObject_schema_name] , [RepoObject_type] , [SysObject_name] , [SysObject_schema_name] , [SysObject_type] ) SELECT [RepoObject_guid] , [external_AntoraComponent] , [external_AntoraModule] , [is_external] , [is_repo_managed] , [RepoObject_name] , [RepoObject_schema_name] , [RepoObject_type] , [SysObject_name] , [SysObject_schema_name] , [SysObject_type] FROM [repo].[RepoObject_external_src] AS S WHERE NOT EXISTS (SELECT 1 FROM [repo].[RepoObject_external_tgt] AS T WHERE T.[RepoObject_guid] = S.[RepoObject_guid] ) -- Logging START -- SET @rows = @@ROWCOUNT SET @step_id = @step_id + 1 SET @step_name = 'insert missing' SET @source_object = '[repo].[RepoObject_external_src]' SET @target_object = '[repo].[RepoObject_external_tgt]' EXEC logs.usp_ExecutionLog_insert @execution_instance_guid = @execution_instance_guid , @ssis_execution_id = @ssis_execution_id , @sub_execution_id = @sub_execution_id , @parent_execution_log_id = @parent_execution_log_id , @current_execution_guid = @current_execution_guid , @proc_id = @proc_id , @proc_schema_name = @proc_schema_name , @proc_name = @proc_name , @event_info = @event_info , @step_id = @step_id , @step_name = @step_name , @source_object = @source_object , @target_object = @target_object , @inserted = @rows -- Logging END -- -- --finish your own code here --keep the code between ""END"" and the end of the procedure unchanged! -- --END -- --SET @rows = @@ROWCOUNT SET @step_id = @step_id + 1 SET @step_name = 'end' SET @source_object = NULL SET @target_object = NULL EXEC logs.usp_ExecutionLog_insert @execution_instance_guid = @execution_instance_guid , @ssis_execution_id = @ssis_execution_id , @sub_execution_id = @sub_execution_id , @parent_execution_log_id = @parent_execution_log_id , @current_execution_guid = @current_execution_guid , @proc_id = @proc_id , @proc_schema_name = @proc_schema_name , @proc_name = @proc_name , @event_info = @event_info , @step_id = @step_id , @step_name = @step_name , @source_object = @source_object , @target_object = @target_object END ---- ======= // end::sql_modules_definition[] ",12360,False,2449.4411088446886,median "[[features.external-config]] == Externalized Configuration Spring Boot lets you externalize your configuration so that you can work with the same application code in different environments. You can use a variety of external configuration sources, include Java properties files, YAML files, environment variables, and command-line arguments. Property values can be injected directly into your beans by using the `@Value` annotation, accessed through Spring's `Environment` abstraction, or be <> through `@ConfigurationProperties`. Spring Boot uses a very particular `PropertySource` order that is designed to allow sensible overriding of values. Properties are considered in the following order (with values from lower items overriding earlier ones): . Default properties (specified by setting `SpringApplication.setDefaultProperties`). . {spring-framework-api}/context/annotation/PropertySource.html[`@PropertySource`] annotations on your `@Configuration` classes. Please note that such property sources are not added to the `Environment` until the application context is being refreshed. This is too late to configure certain properties such as `+logging.*+` and `+spring.main.*+` which are read before refresh begins. . Config data (such as `application.properties` files). . A `RandomValuePropertySource` that has properties only in `+random.*+`. . OS environment variables. . Java System properties (`System.getProperties()`). . JNDI attributes from `java:comp/env`. . `ServletContext` init parameters. . `ServletConfig` init parameters. . Properties from `SPRING_APPLICATION_JSON` (inline JSON embedded in an environment variable or system property). . Command line arguments. . `properties` attribute on your tests. Available on {spring-boot-test-module-api}/context/SpringBootTest.html[`@SpringBootTest`] and the <>. . {spring-framework-api}/test/context/TestPropertySource.html[`@TestPropertySource`] annotations on your tests. . <> in the `$HOME/.config/spring-boot` directory when devtools is active. Config data files are considered in the following order: . <> packaged inside your jar (`application.properties` and YAML variants). . <> packaged inside your jar (`application-\\{profile}.properties` and YAML variants). . <> outside of your packaged jar (`application.properties` and YAML variants). . <> outside of your packaged jar (`application-\\{profile}.properties` and YAML variants). NOTE: It is recommended to stick with one format for your entire application. If you have configuration files with both `.properties` and `.yml` format in the same location, `.properties` takes precedence. To provide a concrete example, suppose you develop a `@Component` that uses a `name` property, as shown in the following example: include::code:MyBean[] On your application classpath (for example, inside your jar) you can have an `application.properties` file that provides a sensible default property value for `name`. When running in a new environment, an `application.properties` file can be provided outside of your jar that overrides the `name`. For one-off testing, you can launch with a specific command line switch (for example, `java -jar app.jar --name=""Spring""`). TIP: The `env` and `configprops` endpoints can be useful in determining why a property has a particular value. You can use these two endpoints to diagnose unexpected property values. See the ""<>"" section for details. [[features.external-config.command-line-args]] === Accessing Command Line Properties By default, `SpringApplication` converts any command line option arguments (that is, arguments starting with `--`, such as `--server.port=9000`) to a `property` and adds them to the Spring `Environment`. As mentioned previously, command line properties always take precedence over file-based property sources. If you do not want command line properties to be added to the `Environment`, you can disable them by using `SpringApplication.setAddCommandLineProperties(false)`. [[features.external-config.application-json]] === JSON Application Properties Environment variables and system properties often have restrictions that mean some property names cannot be used. To help with this, Spring Boot allows you to encode a block of properties into a single JSON structure. When your application starts, any `spring.application.json` or `SPRING_APPLICATION_JSON` properties will be parsed and added to the `Environment`. For example, the `SPRING_APPLICATION_JSON` property can be supplied on the command line in a UN{asterisk}X shell as an environment variable: [source,shell,indent=0,subs=""verbatim""] ---- $ SPRING_APPLICATION_JSON='{""my"":{""name"":""test""}}' java -jar myapp.jar ---- In the preceding example, you end up with `my.name=test` in the Spring `Environment`. The same JSON can also be provided as a system property: [source,shell,indent=0,subs=""verbatim""] ---- $ java -Dspring.application.json='{""my"":{""name"":""test""}}' -jar myapp.jar ---- Or you could supply the JSON by using a command line argument: [source,shell,indent=0,subs=""verbatim""] ---- $ java -jar myapp.jar --spring.application.json='{""my"":{""name"":""test""}}' ---- If you are deploying to a classic Application Server, you could also use a JNDI variable named `java:comp/env/spring.application.json`. NOTE: Although `null` values from the JSON will be added to the resulting property source, the `PropertySourcesPropertyResolver` treats `null` properties as missing values. This means that the JSON cannot override properties from lower order property sources with a `null` value. [[features.external-config.files]] === External Application Properties [[features.external-config.files]] Spring Boot will automatically find and load `application.properties` and `application.yaml` files from the following locations when your application starts: . From the classpath .. The classpath root .. The classpath `/config` package . From the current directory .. The current directory .. The `/config` subdirectory in the current directory .. Immediate child directories of the `/config` subdirectory The list is ordered by precedence (with values from lower items overriding earlier ones). Documents from the loaded files are added as `PropertySources` to the Spring `Environment`. If you do not like `application` as the configuration file name, you can switch to another file name by specifying a configprop:spring.config.name[] environment property. For example, to look for `myproject.properties` and `myproject.yaml` files you can run your application as follows: [source,shell,indent=0,subs=""verbatim""] ---- $ java -jar myproject.jar --spring.config.name=myproject ---- You can also refer to an explicit location by using the configprop:spring.config.location[] environment property. This properties accepts a comma-separated list of one or more locations to check. The following example shows how to specify two distinct files: [source,shell,indent=0,subs=""verbatim""] ---- $ java -jar myproject.jar --spring.config.location=\\ optional:classpath:/default.properties,\\ optional:classpath:/override.properties ---- TIP: Use the prefix `optional:` if the <> and you do not mind if they do not exist. WARNING: `spring.config.name`, `spring.config.location`, and `spring.config.additional-location` are used very early to determine which files have to be loaded. They must be defined as an environment property (typically an OS environment variable, a system property, or a command-line argument). If `spring.config.location` contains directories (as opposed to files), they should end in `/`. At runtime they will be appended with the names generated from `spring.config.name` before being loaded. Files specified in `spring.config.location` are imported directly. NOTE: Both directory and file location values are also expanded to check for <>. For example, if you have a `spring.config.location` of `classpath:myconfig.properties`, you will also find appropriate `classpath:myconfig-.properties` files are loaded. In most situations, each configprop:spring.config.location[] item you add will reference a single file or directory. Locations are processed in the order that they are defined and later ones can override the values of earlier ones. [[features.external-config.files.location-groups]] If you have a complex location setup, and you use profile-specific configuration files, you may need to provide further hints so that Spring Boot knows how they should be grouped. A location group is a collection of locations that are all considered at the same level. For example, you might want to group all classpath locations, then all external locations. Items within a location group should be separated with `;`. See the example in the ""`<>`"" section for more details. Locations configured by using `spring.config.location` replace the default locations. For example, if `spring.config.location` is configured with the value `optional:classpath:/custom-config/,optional:file:./custom-config/`, the complete set of locations considered is: . `optional:classpath:custom-config/` . `optional:file:./custom-config/` If you prefer to add additional locations, rather than replacing them, you can use `spring.config.additional-location`. Properties loaded from additional locations can override those in the default locations. For example, if `spring.config.additional-location` is configured with the value `optional:classpath:/custom-config/,optional:file:./custom-config/`, the complete set of locations considered is: . `optional:classpath:/;optional:classpath:/config/` . `optional:file:./;optional:file:./config/;optional:file:./config/*/` . `optional:classpath:custom-config/` . `optional:file:./custom-config/` This search ordering lets you specify default values in one configuration file and then selectively override those values in another. You can provide default values for your application in `application.properties` (or whatever other basename you choose with `spring.config.name`) in one of the default locations. These default values can then be overridden at runtime with a different file located in one of the custom locations. NOTE: If you use environment variables rather than system properties, most operating systems disallow period-separated key names, but you can use underscores instead (for example, configprop:spring.config.name[format=envvar] instead of configprop:spring.config.name[]). See <> for details. NOTE: If your application runs in a servlet container or application server, then JNDI properties (in `java:comp/env`) or servlet context initialization parameters can be used instead of, or as well as, environment variables or system properties. [[features.external-config.files.optional-prefix]] ==== Optional Locations By default, when a specified config data location does not exist, Spring Boot will throw a `ConfigDataLocationNotFoundException` and your application will not start. If you want to specify a location, but you do not mind if it does not always exist, you can use the `optional:` prefix. You can use this prefix with the `spring.config.location` and `spring.config.additional-location` properties, as well as with <> declarations. For example, a `spring.config.import` value of `optional:file:./myconfig.properties` allows your application to start, even if the `myconfig.properties` file is missing. If you want to ignore all `ConfigDataLocationNotFoundExceptions` and always continue to start your application, you can use the `spring.config.on-not-found` property. Set the value to `ignore` using `SpringApplication.setDefaultProperties(...)` or with a system/environment variable. [[features.external-config.files.wildcard-locations]] ==== Wildcard Locations If a config file location includes the `{asterisk}` character for the last path segment, it is considered a wildcard location. Wildcards are expanded when the config is loaded so that immediate subdirectories are also checked. Wildcard locations are particularly useful in an environment such as Kubernetes when there are multiple sources of config properties. For example, if you have some Redis configuration and some MySQL configuration, you might want to keep those two pieces of configuration separate, while requiring that both those are present in an `application.properties` file. This might result in two separate `application.properties` files mounted at different locations such as `/config/redis/application.properties` and `/config/mysql/application.properties`. In such a case, having a wildcard location of `config/*/`, will result in both files being processed. By default, Spring Boot includes `config/*/` in the default search locations. It means that all subdirectories of the `/config` directory outside of your jar will be searched. You can use wildcard locations yourself with the `spring.config.location` and `spring.config.additional-location` properties. NOTE: A wildcard location must contain only one `{asterisk}` and end with `{asterisk}/` for search locations that are directories or `*/` for search locations that are files. Locations with wildcards are sorted alphabetically based on the absolute path of the file names. TIP: Wildcard locations only work with external directories. You cannot use a wildcard in a `classpath:` location. [[features.external-config.files.profile-specific]] ==== Profile Specific Files As well as `application` property files, Spring Boot will also attempt to load profile-specific files using the naming convention `application-\\{profile}`. For example, if your application activates a profile named `prod` and uses YAML files, then both `application.yml` and `application-prod.yml` will be considered. Profile-specific properties are loaded from the same locations as standard `application.properties`, with profile-specific files always overriding the non-specific ones. If several profiles are specified, a last-wins strategy applies. For example, if profiles `prod,live` are specified by the configprop:spring.profiles.active[] property, values in `application-prod.properties` can be overridden by those in `application-live.properties`. [NOTE] ==== The last-wins strategy applies at the <> level. A configprop:spring.config.location[] of `classpath:/cfg/,classpath:/ext/` will not have the same override rules as `classpath:/cfg/;classpath:/ext/`. For example, continuing our `prod,live` example above, we might have the following files: ---- /cfg application-live.properties /ext application-live.properties application-prod.properties ---- When we have a configprop:spring.config.location[] of `classpath:/cfg/,classpath:/ext/` we process all `/cfg` files before all `/ext` files: . `/cfg/application-live.properties` . `/ext/application-prod.properties` . `/ext/application-live.properties` When we have `classpath:/cfg/;classpath:/ext/` instead (with a `;` delimiter) we process `/cfg` and `/ext` at the same level: . `/ext/application-prod.properties` . `/cfg/application-live.properties` . `/ext/application-live.properties` ==== The `Environment` has a set of default profiles (by default, `[default]`) that are used if no active profiles are set. In other words, if no profiles are explicitly activated, then properties from `application-default` are considered. NOTE: Properties files are only ever loaded once. If you have already directly <> a profile specific property files then it will not be imported a second time. [[features.external-config.files.importing]] ==== Importing Additional Data Application properties may import further config data from other locations using the `spring.config.import` property. Imports are processed as they are discovered, and are treated as additional documents inserted immediately below the one that declares the import. For example, you might have the following in your classpath `application.properties` file: [source,yaml,indent=0,subs=""verbatim"",configblocks] ---- spring: application: name: ""myapp"" config: import: ""optional:file:./dev.properties"" ---- This will trigger the import of a `dev.properties` file in current directory (if such a file exists). Values from the imported `dev.properties` will take precedence over the file that triggered the import. In the above example, the `dev.properties` could redefine `spring.application.name` to a different value. An import will only be imported once no matter how many times it is declared. The order an import is defined inside a single document within the properties/yaml file does not matter. For instance, the two examples below produce the same result: [source,yaml,indent=0,subs=""verbatim"",configblocks] ---- spring: config: import: ""my.properties"" my: property: ""value"" ---- [source,yaml,indent=0,subs=""verbatim"",configblocks] ---- my: property: ""value"" spring: config: import: ""my.properties"" ---- In both of the above examples, the values from the `my.properties` file will take precedence over the file that triggered its import. Several locations can be specified under a single `spring.config.import` key. Locations will be processed in the order that they are defined, with later imports taking precedence. NOTE: When appropriate, <> are also considered for import. The example above would import both `my.properties` as well as any `my-.properties` variants. [TIP] ==== Spring Boot includes pluggable API that allows various different location addresses to be supported. By default you can import Java Properties, YAML and ""`<>`"". Third-party jars can offer support for additional technologies (there is no requirement for files to be local). For example, you can imagine config data being from external stores such as Consul, Apache ZooKeeper or Netflix Archaius. If you want to support your own locations, see the `ConfigDataLocationResolver` and `ConfigDataLoader` classes in the `org.springframework.boot.context.config` package. ==== [[features.external-config.files.importing-extensionless]] ==== Importing Extensionless Files Some cloud platforms cannot add a file extension to volume mounted files. To import these extensionless files, you need to give Spring Boot a hint so that it knows how to load them. You can do this by putting an extension hint in square brackets. For example, suppose you have a `/etc/config/myconfig` file that you wish to import as yaml. You can import it from your `application.properties` using the following: [source,yaml,indent=0,subs=""verbatim"",configprops,configblocks] ---- spring: config: import: ""file:/etc/config/myconfig[.yaml]"" ---- [[features.external-config.files.configtree]] ==== Using Configuration Trees When running applications on a cloud platform (such as Kubernetes) you often need to read config values that the platform supplies. It is not uncommon to use environment variables for such purposes, but this can have drawbacks, especially if the value is supposed to be kept secret. As an alternative to environment variables, many cloud platforms now allow you to map configuration into mounted data volumes. For example, Kubernetes can volume mount both https://kubernetes.io/docs/tasks/configure-pod-container/configure-pod-configmap/#populate-a-volume-with-data-stored-in-a-configmap[`ConfigMaps`] and https://kubernetes.io/docs/concepts/configuration/secret/#using-secrets-as-files-from-a-pod[`Secrets`]. There are two common volume mount patterns that can be used: . A single file contains a complete set of properties (usually written as YAML). . Multiple files are written to a directory tree, with the filename becoming the '`key`' and the contents becoming the '`value`'. For the first case, you can import the YAML or Properties file directly using `spring.config.import` as described <>. For the second case, you need to use the `configtree:` prefix so that Spring Boot knows it needs to expose all the files as properties. As an example, let's imagine that Kubernetes has mounted the following volume: [indent=0] ---- etc/ config/ myapp/ username password ---- The contents of the `username` file would be a config value, and the contents of `password` would be a secret. To import these properties, you can add the following to your `application.properties` or `application.yaml` file: [source,yaml,indent=0,subs=""verbatim"",configprops,configblocks] ---- spring: config: import: ""optional:configtree:/etc/config/"" ---- You can then access or inject `myapp.username` and `myapp.password` properties from the `Environment` in the usual way. TIP: The folders under the config tree form the property name. In the above example, to access the properties as `username` and `password`, you can set `spring.config.import` to `optional:configtree:/etc/config/myapp`. NOTE: Filenames with dot notation are also correctly mapped. For example, in the above example, a file named `myapp.username` in `/etc/config` would result in a `myapp.username` property in the `Environment`. TIP: Configuration tree values can be bound to both string `String` and `byte[]` types depending on the contents expected. If you have multiple config trees to import from the same parent folder you can use a wildcard shortcut. Any `configtree:` location that ends with `/*/` will import all immediate children as config trees. For example, given the following volume: [indent=0] ---- etc/ config/ dbconfig/ db/ username password mqconfig/ mq/ username password ---- You can use `configtree:/etc/config/*/` as the import location: [source,yaml,indent=0,subs=""verbatim"",configprops,configblocks] ---- spring: config: import: ""optional:configtree:/etc/config/*/"" ---- This will add `db.username`, `db.password`, `mq.username` and `mq.password` properties. NOTE: Directories loaded using a wildcard are sorted alphabetically. If you need a different order, then you should list each location as a separate import Configuration trees can also be used for Docker secrets. When a Docker swarm service is granted access to a secret, the secret gets mounted into the container. For example, if a secret named `db.password` is mounted at location `/run/secrets/`, you can make `db.password` available to the Spring environment using the following: [source,yaml,indent=0,subs=""verbatim"",configprops,configblocks] ---- spring: config: import: ""optional:configtree:/run/secrets/"" ---- [[features.external-config.files.property-placeholders]] ==== Property Placeholders The values in `application.properties` and `application.yml` are filtered through the existing `Environment` when they are used, so you can refer back to previously defined values (for example, from System properties or environment variables). The standard `$\\{name}` property-placeholder syntax can be used anywhere within a value. Property placeholders can also specify a default value using a `:` to separate the default value from the property name, for example `${name:default}`. The use of placeholders with and without defaults is shown in the following example: [source,yaml,indent=0,subs=""verbatim"",configblocks] ---- app: name: ""MyApp"" description: ""${app.name} is a Spring Boot application written by ${username:Unknown}"" ---- Assuming that the `username` property has not be set elsewhere, `app.description` will have the value `MyApp is a Spring Boot application written by Unknown`. TIP: You can also use this technique to create ""`short`"" variants of existing Spring Boot properties. See the _<>_ how-to for details. [[features.external-config.files.multi-document]] ==== Working with Multi-Document Files Spring Boot allows you to split a single physical file into multiple logical documents which are each added independently. Documents are processed in order, from top to bottom. Later documents can override the properties defined in earlier ones. For `application.yml` files, the standard YAML multi-document syntax is used. Three consecutive hyphens represent the end of one document, and the start of the next. For example, the following file has two logical documents: [source,yaml,indent=0,subs=""verbatim""] ---- spring: application: name: ""MyApp"" --- spring: application: name: ""MyCloudApp"" config: activate: on-cloud-platform: ""kubernetes"" ---- For `application.properties` files a special `#---` comment is used to mark the document splits: [source,properties,indent=0,subs=""verbatim""] ---- spring.application.name=MyApp #--- spring.application.name=MyCloudApp spring.config.activate.on-cloud-platform=kubernetes ---- NOTE: Property file separators must not have any leading whitespace and must have exactly three hyphen characters. The lines immediately before and after the separator must not be comments. TIP: Multi-document property files are often used in conjunction with activation properties such as `spring.config.activate.on-profile`. See the <> for details. WARNING: Multi-document property files cannot be loaded by using the `@PropertySource` or `@TestPropertySource` annotations. [[features.external-config.files.activation-properties]] ==== Activation Properties It is sometimes useful to only activate a given set of properties when certain conditions are met. For example, you might have properties that are only relevant when a specific profile is active. You can conditionally activate a properties document using `spring.config.activate.*`. The following activation properties are available: .activation properties [cols=""1,4""] |=== | Property | Note | `on-profile` | A profile expression that must match for the document to be active. | `on-cloud-platform` | The `CloudPlatform` that must be detected for the document to be active. |=== For example, the following specifies that the second document is only active when running on Kubernetes, and only when either the ""`prod`"" or ""`staging`"" profiles are active: [source,yaml,indent=0,subs=""verbatim"",configblocks] ---- myprop: ""always-set"" --- spring: config: activate: on-cloud-platform: ""kubernetes"" on-profile: ""prod | staging"" myotherprop: ""sometimes-set"" ---- [[features.external-config.encrypting]] === Encrypting Properties Spring Boot does not provide any built in support for encrypting property values, however, it does provide the hook points necessary to modify values contained in the Spring `Environment`. The `EnvironmentPostProcessor` interface allows you to manipulate the `Environment` before the application starts. See <> for details. If you need a secure way to store credentials and passwords, the https://cloud.spring.io/spring-cloud-vault/[Spring Cloud Vault] project provides support for storing externalized configuration in https://www.vaultproject.io/[HashiCorp Vault]. [[features.external-config.yaml]] === Working with YAML https://yaml.org[YAML] is a superset of JSON and, as such, is a convenient format for specifying hierarchical configuration data. The `SpringApplication` class automatically supports YAML as an alternative to properties whenever you have the https://bitbucket.org/asomov/snakeyaml[SnakeYAML] library on your classpath. NOTE: If you use ""`Starters`"", SnakeYAML is automatically provided by `spring-boot-starter`. [[features.external-config.yaml.mapping-to-properties]] ==== Mapping YAML to Properties YAML documents need to be converted from their hierarchical format to a flat structure that can be used with the Spring `Environment`. For example, consider the following YAML document: [source,yaml,indent=0,subs=""verbatim""] ---- environments: dev: url: ""https://dev.example.com"" name: ""Developer Setup"" prod: url: ""https://another.example.com"" name: ""My Cool App"" ---- In order to access these properties from the `Environment`, they would be flattened as follows: [source,properties,indent=0,subs=""verbatim""] ---- environments.dev.url=https://dev.example.com environments.dev.name=Developer Setup environments.prod.url=https://another.example.com environments.prod.name=My Cool App ---- Likewise, YAML lists also need to be flattened. They are represented as property keys with `[index]` dereferencers. For example, consider the following YAML: [source,yaml,indent=0,subs=""verbatim""] ---- my: servers: - ""dev.example.com"" - ""another.example.com"" ---- The preceding example would be transformed into these properties: [source,properties,indent=0,subs=""verbatim""] ---- my.servers[0]=dev.example.com my.servers[1]=another.example.com ---- TIP: Properties that use the `[index]` notation can be bound to Java `List` or `Set` objects using Spring Boot's `Binder` class. For more details see the ""`<>`"" section below. WARNING: YAML files cannot be loaded by using the `@PropertySource` or `@TestPropertySource` annotations. So, in the case that you need to load values that way, you need to use a properties file. [[features.external-config.yaml.directly-loading]] [[features.external-config.yaml.directly-loading]] ==== Directly Loading YAML Spring Framework provides two convenient classes that can be used to load YAML documents. The `YamlPropertiesFactoryBean` loads YAML as `Properties` and the `YamlMapFactoryBean` loads YAML as a `Map`. You can also use the `YamlPropertySourceLoader` class if you want to load YAML as a Spring `PropertySource`. [[features.external-config.random-values]] === Configuring Random Values The `RandomValuePropertySource` is useful for injecting random values (for example, into secrets or test cases). It can produce integers, longs, uuids, or strings, as shown in the following example: [source,yaml,indent=0,subs=""verbatim"",configblocks] ---- my: secret: ""${random.value}"" number: ""${random.int}"" bignumber: ""${random.long}"" uuid: ""${random.uuid}"" number-less-than-ten: ""${random.int(10)}"" number-in-range: ""${random.int[1024,65536]}"" ---- The `+random.int*+` syntax is `OPEN value (,max) CLOSE` where the `OPEN,CLOSE` are any character and `value,max` are integers. If `max` is provided, then `value` is the minimum value and `max` is the maximum value (exclusive). [[features.external-config.system-environment]] === Configuring System Environment Properties Spring Boot supports setting a prefix for environment properties. This is useful if the system environment is shared by multiple Spring Boot applications with different configuration requirements. The prefix for system environment properties can be set directly on `SpringApplication`. For example, if you set the prefix to `input`, a property such as `remote.timeout` will also be resolved as `input.remote.timeout` in the system environment. [[features.external-config.typesafe-configuration-properties]] === Type-safe Configuration Properties Using the `@Value(""$\\{property}"")` annotation to inject configuration properties can sometimes be cumbersome, especially if you are working with multiple properties or your data is hierarchical in nature. Spring Boot provides an alternative method of working with properties that lets strongly typed beans govern and validate the configuration of your application. TIP: See also the <>. [[features.external-config.typesafe-configuration-properties.java-bean-binding]] ==== JavaBean properties binding It is possible to bind a bean declaring standard JavaBean properties as shown in the following example: include::code:MyProperties[] The preceding POJO defines the following properties: * `my.service.enabled`, with a value of `false` by default. * `my.service.remote-address`, with a type that can be coerced from `String`. * `my.service.security.username`, with a nested ""security"" object whose name is determined by the name of the property. In particular, the type is not used at all there and could have been `SecurityProperties`. * `my.service.security.password`. * `my.service.security.roles`, with a collection of `String` that defaults to `USER`. NOTE: The properties that map to `@ConfigurationProperties` classes available in Spring Boot, which are configured through properties files, YAML files, environment variables, and other mechanisms, are public API but the accessors (getters/setters) of the class itself are not meant to be used directly. [NOTE] ==== Such arrangement relies on a default empty constructor and getters and setters are usually mandatory, since binding is through standard Java Beans property descriptors, just like in Spring MVC. A setter may be omitted in the following cases: * Maps, as long as they are initialized, need a getter but not necessarily a setter, since they can be mutated by the binder. * Collections and arrays can be accessed either through an index (typically with YAML) or by using a single comma-separated value (properties). In the latter case, a setter is mandatory. We recommend to always add a setter for such types. If you initialize a collection, make sure it is not immutable (as in the preceding example). * If nested POJO properties are initialized (like the `Security` field in the preceding example), a setter is not required. If you want the binder to create the instance on the fly by using its default constructor, you need a setter. Some people use Project Lombok to add getters and setters automatically. Make sure that Lombok does not generate any particular constructor for such a type, as it is used automatically by the container to instantiate the object. Finally, only standard Java Bean properties are considered and binding on static properties is not supported. ==== [[features.external-config.typesafe-configuration-properties.constructor-binding]] ==== Constructor binding The example in the previous section can be rewritten in an immutable fashion as shown in the following example: include::code:MyProperties[] In this setup, the presence of a single parameterized constructor implies that constructor binding should be used. This means that the binder will find a constructor with the parameters that you wish to have bound. If your class has multiple constructors, the `@ConstructorBinding` annotation can be used to specify which constructor to use for constructor binding. To opt out of constructor binding for a class with a single parameterized constructor, the constructor must be annotated with `@Autowired`. If you are using Java 16 or later, constructor binding can be used with records. Unless your record has multiple constructors, there is no need to use `@ConstructorBinding`. Nested members of a constructor bound class (such as `Security` in the example above) will also be bound through their constructor. Default values can be specified using `@DefaultValue` on constructor parameters and record components. The conversion service will be applied to coerce the annotation's `String` value to the target type of a missing property. By default, if no properties are bound to `Security`, the `MyProperties` instance will contain a `null` value for `security`. If you wish you return a non-null instance of `Security` even when no properties are bound to it, you can use an empty `@DefaultValue` annotation to do so: include::code:nonnull/MyProperties[tag=*] NOTE: To use constructor binding the class must be enabled using `@EnableConfigurationProperties` or configuration property scanning. You cannot use constructor binding with beans that are created by the regular Spring mechanisms (for example `@Component` beans, beans created by using `@Bean` methods or beans loaded by using `@Import`) NOTE: The use of `java.util.Optional` with `@ConfigurationProperties` is not recommended as it is primarily intended for use as a return type. As such, it is not well-suited to configuration property injection. For consistency with properties of other types, if you do declare an `Optional` property and it has no value, `null` rather than an empty `Optional` will be bound. [[features.external-config.typesafe-configuration-properties.enabling-annotated-types]] ==== Enabling @ConfigurationProperties-annotated types Spring Boot provides infrastructure to bind `@ConfigurationProperties` types and register them as beans. You can either enable configuration properties on a class-by-class basis or enable configuration property scanning that works in a similar manner to component scanning. Sometimes, classes annotated with `@ConfigurationProperties` might not be suitable for scanning, for example, if you're developing your own auto-configuration or you want to enable them conditionally. In these cases, specify the list of types to process using the `@EnableConfigurationProperties` annotation. This can be done on any `@Configuration` class, as shown in the following example: include::code:MyConfiguration[] To use configuration property scanning, add the `@ConfigurationPropertiesScan` annotation to your application. Typically, it is added to the main application class that is annotated with `@SpringBootApplication` but it can be added to any `@Configuration` class. By default, scanning will occur from the package of the class that declares the annotation. If you want to define specific packages to scan, you can do so as shown in the following example: include::code:MyApplication[] [NOTE] ==== When the `@ConfigurationProperties` bean is registered using configuration property scanning or through `@EnableConfigurationProperties`, the bean has a conventional name: `-`, where `` is the environment key prefix specified in the `@ConfigurationProperties` annotation and `` is the fully qualified name of the bean. If the annotation does not provide any prefix, only the fully qualified name of the bean is used. The bean name in the example above is `com.example.app-com.example.app.SomeProperties`. ==== We recommend that `@ConfigurationProperties` only deal with the environment and, in particular, does not inject other beans from the context. For corner cases, setter injection can be used or any of the `*Aware` interfaces provided by the framework (such as `EnvironmentAware` if you need access to the `Environment`). If you still want to inject other beans using the constructor, the configuration properties bean must be annotated with `@Component` and use JavaBean-based property binding. [[features.external-config.typesafe-configuration-properties.using-annotated-types]] ==== Using @ConfigurationProperties-annotated types This style of configuration works particularly well with the `SpringApplication` external YAML configuration, as shown in the following example: [source,yaml,indent=0,subs=""verbatim""] ---- my: service: remote-address: 192.168.1.1 security: username: ""admin"" roles: - ""USER"" - ""ADMIN"" ---- To work with `@ConfigurationProperties` beans, you can inject them in the same way as any other bean, as shown in the following example: include::code:MyService[] TIP: Using `@ConfigurationProperties` also lets you generate metadata files that can be used by IDEs to offer auto-completion for your own keys. See the <> for details. [[features.external-config.typesafe-configuration-properties.third-party-configuration]] ==== Third-party Configuration As well as using `@ConfigurationProperties` to annotate a class, you can also use it on public `@Bean` methods. Doing so can be particularly useful when you want to bind properties to third-party components that are outside of your control. To configure a bean from the `Environment` properties, add `@ConfigurationProperties` to its bean registration, as shown in the following example: include::code:ThirdPartyConfiguration[] Any JavaBean property defined with the `another` prefix is mapped onto that `AnotherComponent` bean in manner similar to the preceding `SomeProperties` example. [[features.external-config.typesafe-configuration-properties.relaxed-binding]] ==== Relaxed Binding Spring Boot uses some relaxed rules for binding `Environment` properties to `@ConfigurationProperties` beans, so there does not need to be an exact match between the `Environment` property name and the bean property name. Common examples where this is useful include dash-separated environment properties (for example, `context-path` binds to `contextPath`), and capitalized environment properties (for example, `PORT` binds to `port`). As an example, consider the following `@ConfigurationProperties` class: include::code:MyPersonProperties[] With the preceding code, the following properties names can all be used: .relaxed binding [cols=""1,4""] |=== | Property | Note | `my.main-project.person.first-name` | Kebab case, which is recommended for use in `.properties` and `.yml` files. | `my.main-project.person.firstName` | Standard camel case syntax. | `my.main-project.person.first_name` | Underscore notation, which is an alternative format for use in `.properties` and `.yml` files. | `MY_MAINPROJECT_PERSON_FIRSTNAME` | Upper case format, which is recommended when using system environment variables. |=== NOTE: The `prefix` value for the annotation _must_ be in kebab case (lowercase and separated by `-`, such as `my.main-project.person`). .relaxed binding rules per property source [cols=""2,4,4""] |=== | Property Source | Simple | List | Properties Files | Camel case, kebab case, or underscore notation | Standard list syntax using `[ ]` or comma-separated values | YAML Files | Camel case, kebab case, or underscore notation | Standard YAML list syntax or comma-separated values | Environment Variables | Upper case format with underscore as the delimiter (see <>). | Numeric values surrounded by underscores (see <>) | System properties | Camel case, kebab case, or underscore notation | Standard list syntax using `[ ]` or comma-separated values |=== TIP: We recommend that, when possible, properties are stored in lower-case kebab format, such as `my.person.first-name=Rod`. [[features.external-config.typesafe-configuration-properties.relaxed-binding.maps]] ===== Binding Maps When binding to `Map` properties you may need to use a special bracket notation so that the original `key` value is preserved. If the key is not surrounded by `[]`, any characters that are not alpha-numeric, `-` or `.` are removed. For example, consider binding the following properties to a `Map`: [source,properties,indent=0,subs=""verbatim"",role=""primary""] .Properties ---- my.map.[/key1]=value1 my.map.[/key2]=value2 my.map./key3=value3 ---- [source,yaml,indent=0,subs=""verbatim"",role=""secondary""] .Yaml ---- my: map: ""[/key1]"": ""value1"" ""[/key2]"": ""value2"" ""/key3"": ""value3"" ---- NOTE: For YAML files, the brackets need to be surrounded by quotes for the keys to be parsed properly. The properties above will bind to a `Map` with `/key1`, `/key2` and `key3` as the keys in the map. The slash has been removed from `key3` because it was not surrounded by square brackets. You may also occasionally need to use the bracket notation if your `key` contains a `.` and you are binding to non-scalar value. For example, binding `a.b=c` to `Map` will return a Map with the entry `{""a""={""b""=""c""}}` whereas `[a.b]=c` will return a Map with the entry `{""a.b""=""c""}`. [[features.external-config.typesafe-configuration-properties.relaxed-binding.environment-variables]] ===== Binding from Environment Variables Most operating systems impose strict rules around the names that can be used for environment variables. For example, Linux shell variables can contain only letters (`a` to `z` or `A` to `Z`), numbers (`0` to `9`) or the underscore character (`_`). By convention, Unix shell variables will also have their names in UPPERCASE. Spring Boot's relaxed binding rules are, as much as possible, designed to be compatible with these naming restrictions. To convert a property name in the canonical-form to an environment variable name you can follow these rules: * Replace dots (`.`) with underscores (`_`). * Remove any dashes (`-`). * Convert to uppercase. For example, the configuration property `spring.main.log-startup-info` would be an environment variable named `SPRING_MAIN_LOGSTARTUPINFO`. Environment variables can also be used when binding to object lists. To bind to a `List`, the element number should be surrounded with underscores in the variable name. For example, the configuration property `my.service[0].other` would use an environment variable named `MY_SERVICE_0_OTHER`. [[features.external-config.typesafe-configuration-properties.merging-complex-types]] ==== Merging Complex Types When lists are configured in more than one place, overriding works by replacing the entire list. For example, assume a `MyPojo` object with `name` and `description` attributes that are `null` by default. The following example exposes a list of `MyPojo` objects from `MyProperties`: include::code:list/MyProperties[] Consider the following configuration: [source,yaml,indent=0,subs=""verbatim"",configblocks] ---- my: list: - name: ""my name"" description: ""my description"" --- spring: config: activate: on-profile: ""dev"" my: list: - name: ""my another name"" ---- If the `dev` profile is not active, `MyProperties.list` contains one `MyPojo` entry, as previously defined. If the `dev` profile is enabled, however, the `list` _still_ contains only one entry (with a name of `my another name` and a description of `null`). This configuration _does not_ add a second `MyPojo` instance to the list, and it does not merge the items. When a `List` is specified in multiple profiles, the one with the highest priority (and only that one) is used. Consider the following example: [source,yaml,indent=0,subs=""verbatim"",configblocks] ---- my: list: - name: ""my name"" description: ""my description"" - name: ""another name"" description: ""another description"" --- spring: config: activate: on-profile: ""dev"" my: list: - name: ""my another name"" ---- In the preceding example, if the `dev` profile is active, `MyProperties.list` contains _one_ `MyPojo` entry (with a name of `my another name` and a description of `null`). For YAML, both comma-separated lists and YAML lists can be used for completely overriding the contents of the list. For `Map` properties, you can bind with property values drawn from multiple sources. However, for the same property in multiple sources, the one with the highest priority is used. The following example exposes a `Map` from `MyProperties`: include::code:map/MyProperties[] Consider the following configuration: [source,yaml,indent=0,subs=""verbatim"",configblocks] ---- my: map: key1: name: ""my name 1"" description: ""my description 1"" --- spring: config: activate: on-profile: ""dev"" my: map: key1: name: ""dev name 1"" key2: name: ""dev name 2"" description: ""dev description 2"" ---- If the `dev` profile is not active, `MyProperties.map` contains one entry with key `key1` (with a name of `my name 1` and a description of `my description 1`). If the `dev` profile is enabled, however, `map` contains two entries with keys `key1` (with a name of `dev name 1` and a description of `my description 1`) and `key2` (with a name of `dev name 2` and a description of `dev description 2`). NOTE: The preceding merging rules apply to properties from all property sources, and not just files. [[features.external-config.typesafe-configuration-properties.conversion]] ==== Properties Conversion Spring Boot attempts to coerce the external application properties to the right type when it binds to the `@ConfigurationProperties` beans. If you need custom type conversion, you can provide a `ConversionService` bean (with a bean named `conversionService`) or custom property editors (through a `CustomEditorConfigurer` bean) or custom `Converters` (with bean definitions annotated as `@ConfigurationPropertiesBinding`). NOTE: As this bean is requested very early during the application lifecycle, make sure to limit the dependencies that your `ConversionService` is using. Typically, any dependency that you require may not be fully initialized at creation time. You may want to rename your custom `ConversionService` if it is not required for configuration keys coercion and only rely on custom converters qualified with `@ConfigurationPropertiesBinding`. [[features.external-config.typesafe-configuration-properties.conversion.durations]] ===== Converting Durations Spring Boot has dedicated support for expressing durations. If you expose a `java.time.Duration` property, the following formats in application properties are available: * A regular `long` representation (using milliseconds as the default unit unless a `@DurationUnit` has been specified) * The standard ISO-8601 format {java-api}/java/time/Duration.html#parse-java.lang.CharSequence-[used by `java.time.Duration`] * A more readable format where the value and the unit are coupled (`10s` means 10 seconds) Consider the following example: include::code:javabeanbinding/MyProperties[] To specify a session timeout of 30 seconds, `30`, `PT30S` and `30s` are all equivalent. A read timeout of 500ms can be specified in any of the following form: `500`, `PT0.5S` and `500ms`. You can also use any of the supported units. These are: * `ns` for nanoseconds * `us` for microseconds * `ms` for milliseconds * `s` for seconds * `m` for minutes * `h` for hours * `d` for days The default unit is milliseconds and can be overridden using `@DurationUnit` as illustrated in the sample above. If you prefer to use constructor binding, the same properties can be exposed, as shown in the following example: include::code:constructorbinding/MyProperties[] TIP: If you are upgrading a `Long` property, make sure to define the unit (using `@DurationUnit`) if it is not milliseconds. Doing so gives a transparent upgrade path while supporting a much richer format. [[features.external-config.typesafe-configuration-properties.conversion.periods]] ===== Converting periods In addition to durations, Spring Boot can also work with `java.time.Period` type. The following formats can be used in application properties: * An regular `int` representation (using days as the default unit unless a `@PeriodUnit` has been specified) * The standard ISO-8601 format {java-api}/java/time/Period.html#parse-java.lang.CharSequence-[used by `java.time.Period`] * A simpler format where the value and the unit pairs are coupled (`1y3d` means 1 year and 3 days) The following units are supported with the simple format: * `y` for years * `m` for months * `w` for weeks * `d` for days NOTE: The `java.time.Period` type never actually stores the number of weeks, it is a shortcut that means ""`7 days`"". [[features.external-config.typesafe-configuration-properties.conversion.data-sizes]] ===== Converting Data Sizes Spring Framework has a `DataSize` value type that expresses a size in bytes. If you expose a `DataSize` property, the following formats in application properties are available: * A regular `long` representation (using bytes as the default unit unless a `@DataSizeUnit` has been specified) * A more readable format where the value and the unit are coupled (`10MB` means 10 megabytes) Consider the following example: include::code:javabeanbinding/MyProperties[] To specify a buffer size of 10 megabytes, `10` and `10MB` are equivalent. A size threshold of 256 bytes can be specified as `256` or `256B`. You can also use any of the supported units. These are: * `B` for bytes * `KB` for kilobytes * `MB` for megabytes * `GB` for gigabytes * `TB` for terabytes The default unit is bytes and can be overridden using `@DataSizeUnit` as illustrated in the sample above. If you prefer to use constructor binding, the same properties can be exposed, as shown in the following example: include::code:constructorbinding/MyProperties[] TIP: If you are upgrading a `Long` property, make sure to define the unit (using `@DataSizeUnit`) if it is not bytes. Doing so gives a transparent upgrade path while supporting a much richer format. [[features.external-config.typesafe-configuration-properties.validation]] ==== @ConfigurationProperties Validation Spring Boot attempts to validate `@ConfigurationProperties` classes whenever they are annotated with Spring's `@Validated` annotation. You can use JSR-303 `javax.validation` constraint annotations directly on your configuration class. To do so, ensure that a compliant JSR-303 implementation is on your classpath and then add constraint annotations to your fields, as shown in the following example: include::code:MyProperties[] TIP: You can also trigger validation by annotating the `@Bean` method that creates the configuration properties with `@Validated`. To ensure that validation is always triggered for nested properties, even when no properties are found, the associated field must be annotated with `@Valid`. The following example builds on the preceding `MyProperties` example: include::code:nested/MyProperties[] You can also add a custom Spring `Validator` by creating a bean definition called `configurationPropertiesValidator`. The `@Bean` method should be declared `static`. The configuration properties validator is created very early in the application's lifecycle, and declaring the `@Bean` method as static lets the bean be created without having to instantiate the `@Configuration` class. Doing so avoids any problems that may be caused by early instantiation. TIP: The `spring-boot-actuator` module includes an endpoint that exposes all `@ConfigurationProperties` beans. Point your web browser to `/actuator/configprops` or use the equivalent JMX endpoint. See the ""<>"" section for details. [[features.external-config.typesafe-configuration-properties.vs-value-annotation]] ==== @ConfigurationProperties vs. @Value The `@Value` annotation is a core container feature, and it does not provide the same features as type-safe configuration properties. The following table summarizes the features that are supported by `@ConfigurationProperties` and `@Value`: [cols=""4,2,2""] |=== | Feature |`@ConfigurationProperties` |`@Value` | <> | Yes | Limited (see <>) | <> | Yes | No | `SpEL` evaluation | No | Yes |=== [[features.external-config.typesafe-configuration-properties.vs-value-annotation.note]] NOTE: If you do want to use `@Value`, we recommend that you refer to property names using their canonical form (kebab-case using only lowercase letters). This will allow Spring Boot to use the same logic as it does when relaxed binding `@ConfigurationProperties`. For example, `@Value(""{demo.item-price}"")` will pick up `demo.item-price` and `demo.itemPrice` forms from the `application.properties` file, as well as `DEMO_ITEMPRICE` from the system environment. If you used `@Value(""{demo.itemPrice}"")` instead, `demo.item-price` and `DEMO_ITEMPRICE` would not be considered. If you define a set of configuration keys for your own components, we recommend you group them in a POJO annotated with `@ConfigurationProperties`. Doing so will provide you with structured, type-safe object that you can inject into your own beans. `SpEL` expressions from <> are not processed at time of parsing these files and populating the environment. However, it is possible to write a `SpEL` expression in `@Value`. If the value of a property from an application property file is a `SpEL` expression, it will be evaluated when consumed through `@Value`. ",12354,False,2148.721774871657,median "/* * Copyright (c) Facebook, Inc. and its affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #include #include #include #include #include #include #include #include #include #include #include using namespace folly::io; using namespace folly; using std::string; namespace { std::string base64url_encode(ByteRange range) { return proxygen::Base64::urlEncode(range); } std::string base64url_decode(const std::string& str) { return proxygen::Base64::urlDecode(str); } const size_t kDefaultGrowth = 4000; constexpr auto kOkhttp2 = ""okhttp/2""; constexpr int kOkhttp2GoawayLogFreq = 1000; } // namespace namespace proxygen { HTTP2Codec::HTTP2Codec(TransportDirection direction) : HTTPParallelCodec(direction), headerCodec_(direction), frameState_(direction == TransportDirection::DOWNSTREAM ? FrameState::UPSTREAM_CONNECTION_PREFACE : FrameState::DOWNSTREAM_CONNECTION_PREFACE) { const auto maxHeaderListSize = egressSettings_.getSetting(SettingsId::MAX_HEADER_LIST_SIZE); if (maxHeaderListSize) { headerCodec_.setMaxUncompressed(maxHeaderListSize->value); } VLOG(4) << ""creating "" << getTransportDirectionString(direction) << "" HTTP/2 codec""; } HTTP2Codec::~HTTP2Codec() { } // HTTPCodec API size_t HTTP2Codec::onIngress(const folly::IOBuf& buf) { // TODO: ensure only 1 parse at a time on stack. FOLLY_SCOPED_TRACE_SECTION(""HTTP2Codec - onIngress""); Cursor cursor(&buf); size_t parsed = 0; ErrorCode connError = ErrorCode::NO_ERROR; auto bufLen = cursor.totalLength(); while (connError == ErrorCode::NO_ERROR) { size_t remaining = bufLen - parsed; if (frameState_ == FrameState::UPSTREAM_CONNECTION_PREFACE) { if (remaining >= http2::kConnectionPreface.length()) { auto test = cursor.readFixedString(http2::kConnectionPreface.length()); parsed += http2::kConnectionPreface.length(); if (test != http2::kConnectionPreface) { goawayErrorMessage_ = ""missing connection preface""; VLOG(4) << goawayErrorMessage_; connError = ErrorCode::PROTOCOL_ERROR; } frameState_ = FrameState::FRAME_HEADER; } else { break; } } else if (frameState_ == FrameState::FRAME_HEADER || frameState_ == FrameState::DOWNSTREAM_CONNECTION_PREFACE) { // Waiting to parse the common frame header if (remaining >= http2::kFrameHeaderSize) { connError = parseFrameHeader(cursor, curHeader_); parsed += http2::kFrameHeaderSize; if (frameState_ == FrameState::DOWNSTREAM_CONNECTION_PREFACE && curHeader_.type != http2::FrameType::SETTINGS) { goawayErrorMessage_ = folly::to( ""GOAWAY error: got invalid connection preface frame type="", getFrameTypeString(curHeader_.type), ""("", curHeader_.type, "")"", "" for streamID="", curHeader_.stream); VLOG(4) << goawayErrorMessage_; connError = ErrorCode::PROTOCOL_ERROR; } if (curHeader_.length > maxRecvFrameSize()) { VLOG(4) << ""Excessively large frame len="" << curHeader_.length; connError = ErrorCode::FRAME_SIZE_ERROR; } if (callback_) { callback_->onFrameHeader(curHeader_.stream, curHeader_.flags, curHeader_.length, static_cast(curHeader_.type)); } if (curHeader_.type == http2::FrameType::DATA) { frameState_ = FrameState::DATA_FRAME_DATA; pendingDataFrameBytes_ = curHeader_.length; pendingDataFramePaddingBytes_ = 0; } else { frameState_ = FrameState::FRAME_DATA; } #ifndef NDEBUG receivedFrameCount_++; #endif } else { break; } } else if (frameState_ == FrameState::DATA_FRAME_DATA && remaining > 0 && (remaining < curHeader_.length || pendingDataFrameBytes_ < curHeader_.length)) { // FrameState::DATA_FRAME_DATA with partial data only size_t dataParsed = 0; connError = parseDataFrameData(cursor, remaining, dataParsed); if (dataParsed == 0 && pendingDataFrameBytes_ > 0) { // We received only the padding byte, we will wait for more break; } else { parsed += dataParsed; if (pendingDataFrameBytes_ == 0) { frameState_ = FrameState::FRAME_HEADER; } } } else { // FrameState::FRAME_DATA // or FrameState::DATA_FRAME_DATA with all data available // Already parsed the common frame header const auto frameLen = curHeader_.length; if (remaining >= frameLen) { connError = parseFrame(cursor); parsed += curHeader_.length; frameState_ = FrameState::FRAME_HEADER; } else { break; } } } checkConnectionError(connError, &buf); return parsed; } ErrorCode HTTP2Codec::parseFrame(folly::io::Cursor& cursor) { FOLLY_SCOPED_TRACE_SECTION(""HTTP2Codec - parseFrame""); if (expectedContinuationStream_ != 0 && (curHeader_.type != http2::FrameType::CONTINUATION || expectedContinuationStream_ != curHeader_.stream)) { goawayErrorMessage_ = folly::to( ""GOAWAY error: while expected CONTINUATION with stream="", expectedContinuationStream_, "", received streamID="", curHeader_.stream, "" of type="", getFrameTypeString(curHeader_.type)); VLOG(4) << goawayErrorMessage_; return ErrorCode::PROTOCOL_ERROR; } if (expectedContinuationStream_ == 0 && curHeader_.type == http2::FrameType::CONTINUATION) { goawayErrorMessage_ = folly::to( ""GOAWAY error: unexpected CONTINUATION received with streamID="", curHeader_.stream); VLOG(4) << goawayErrorMessage_; return ErrorCode::PROTOCOL_ERROR; } if (frameAffectsCompression(curHeader_.type) && curHeaderBlock_.chainLength() + curHeader_.length > egressSettings_.getSetting(SettingsId::MAX_HEADER_LIST_SIZE, 0)) { // this may be off by up to the padding length (max 255), but // these numbers are already so generous, and we're comparing the // max-uncompressed to the actual compressed size. Let's fail // before buffering. // TODO(t6513634): it would be nicer to stream-process this header // block to keep the connection state consistent without consuming // memory, and fail just the request per the HTTP/2 spec (section // 10.3) goawayErrorMessage_ = folly::to( ""Failing connection due to excessively large headers""); LOG(ERROR) << goawayErrorMessage_; return ErrorCode::PROTOCOL_ERROR; } expectedContinuationStream_ = (frameAffectsCompression(curHeader_.type) && !(curHeader_.flags & http2::END_HEADERS)) ? curHeader_.stream : 0; switch (curHeader_.type) { case http2::FrameType::DATA: return parseAllData(cursor); case http2::FrameType::HEADERS: return parseHeaders(cursor); case http2::FrameType::PRIORITY: return parsePriority(cursor); case http2::FrameType::RST_STREAM: return parseRstStream(cursor); case http2::FrameType::SETTINGS: return parseSettings(cursor); case http2::FrameType::PUSH_PROMISE: return parsePushPromise(cursor); case http2::FrameType::EX_HEADERS: if (ingressSettings_.getSetting(SettingsId::ENABLE_EX_HEADERS, 0)) { return parseExHeaders(cursor); } else { VLOG(2) << ""EX_HEADERS not enabled, ignoring the frame""; break; } case http2::FrameType::PING: return parsePing(cursor); case http2::FrameType::GOAWAY: return parseGoaway(cursor); case http2::FrameType::WINDOW_UPDATE: return parseWindowUpdate(cursor); case http2::FrameType::CONTINUATION: return parseContinuation(cursor); case http2::FrameType::ALTSVC: // fall through, unimplemented break; case http2::FrameType::CERTIFICATE_REQUEST: return parseCertificateRequest(cursor); case http2::FrameType::CERTIFICATE: return parseCertificate(cursor); default: // Implementations MUST ignore and discard any frame that has a // type that is unknown break; } // Landing here means unknown, unimplemented or ignored frame. VLOG(2) << ""Skipping frame (type="" << (uint8_t)curHeader_.type << "")""; cursor.skip(curHeader_.length); return ErrorCode::NO_ERROR; } ErrorCode HTTP2Codec::handleEndStream() { if (curHeader_.type != http2::FrameType::HEADERS && curHeader_.type != http2::FrameType::EX_HEADERS && curHeader_.type != http2::FrameType::CONTINUATION && curHeader_.type != http2::FrameType::DATA) { return ErrorCode::NO_ERROR; } // do we need to handle case where this stream has already aborted via // another callback (onHeadersComplete/onBody)? pendingEndStreamHandling_ |= (curHeader_.flags & http2::END_STREAM); // with a websocket upgrade, we need to send message complete cb to // mirror h1x codec's behavior. when the stream closes, we need to // send another callback to clean up the stream's resources. if (ingressWebsocketUpgrade_) { ingressWebsocketUpgrade_ = false; deliverCallbackIfAllowed(&HTTPCodec::Callback::onMessageComplete, ""onMessageComplete"", curHeader_.stream, true); } if (pendingEndStreamHandling_ && expectedContinuationStream_ == 0) { pendingEndStreamHandling_ = false; deliverCallbackIfAllowed(&HTTPCodec::Callback::onMessageComplete, ""onMessageComplete"", curHeader_.stream, false); } return ErrorCode::NO_ERROR; } ErrorCode HTTP2Codec::parseAllData(Cursor& cursor) { std::unique_ptr outData; uint16_t padding = 0; VLOG(10) << ""parsing all frame DATA bytes for stream="" << curHeader_.stream << "" length="" << curHeader_.length; auto ret = http2::parseData(cursor, curHeader_, outData, padding); RETURN_IF_ERROR(ret); if (callback_ && (padding > 0 || (outData && !outData->empty()))) { if (!outData) { outData = std::make_unique(); } deliverCallbackIfAllowed(&HTTPCodec::Callback::onBody, ""onBody"", curHeader_.stream, std::move(outData), padding); } return handleEndStream(); } ErrorCode HTTP2Codec::parseDataFrameData(Cursor& cursor, size_t bufLen, size_t& parsed) { FOLLY_SCOPED_TRACE_SECTION(""HTTP2Codec - parseDataFrameData""); if (bufLen == 0) { VLOG(10) << ""No data to parse""; return ErrorCode::NO_ERROR; } std::unique_ptr outData; uint16_t padding = 0; VLOG(10) << ""parsing DATA frame data for stream="" << curHeader_.stream << "" frame data length="" << curHeader_.length << "" pendingDataFrameBytes_="" << pendingDataFrameBytes_ << "" pendingDataFramePaddingBytes_="" << pendingDataFramePaddingBytes_ << "" bufLen="" << bufLen << "" parsed="" << parsed; // Parse the padding information only the first time if (pendingDataFrameBytes_ == curHeader_.length && pendingDataFramePaddingBytes_ == 0) { if (frameHasPadding(curHeader_) && bufLen == 1) { // We need to wait for more bytes otherwise we won't be able to pass // the correct padding to the first onBody call return ErrorCode::NO_ERROR; } const auto ret = http2::parseDataBegin(cursor, curHeader_, parsed, padding); RETURN_IF_ERROR(ret); if (padding > 0) { pendingDataFramePaddingBytes_ = padding - 1; pendingDataFrameBytes_--; bufLen--; parsed++; } VLOG(10) << ""out padding="" << padding << "" pendingDataFrameBytes_="" << pendingDataFrameBytes_ << "" pendingDataFramePaddingBytes_="" << pendingDataFramePaddingBytes_ << "" bufLen="" << bufLen << "" parsed="" << parsed; } if (bufLen > 0) { // Check if we have application data to parse if (pendingDataFrameBytes_ > pendingDataFramePaddingBytes_) { const size_t pendingAppData = pendingDataFrameBytes_ - pendingDataFramePaddingBytes_; const size_t toClone = std::min(pendingAppData, bufLen); cursor.clone(outData, toClone); bufLen -= toClone; pendingDataFrameBytes_ -= toClone; parsed += toClone; VLOG(10) << ""parsed some app data, pendingDataFrameBytes_="" << pendingDataFrameBytes_ << "" pendingDataFramePaddingBytes_="" << pendingDataFramePaddingBytes_ << "" bufLen="" << bufLen << "" parsed="" << parsed; } // Check if we have padding bytes to parse if (bufLen > 0 && pendingDataFramePaddingBytes_ > 0) { size_t toSkip = 0; auto ret = http2::parseDataEnd( cursor, bufLen, pendingDataFramePaddingBytes_, toSkip); RETURN_IF_ERROR(ret); pendingDataFrameBytes_ -= toSkip; pendingDataFramePaddingBytes_ -= toSkip; parsed += toSkip; VLOG(10) << ""parsed some padding, pendingDataFrameBytes_="" << pendingDataFrameBytes_ << "" pendingDataFramePaddingBytes_="" << pendingDataFramePaddingBytes_ << "" bufLen="" << bufLen << "" parsed="" << parsed; } } if (callback_ && (padding > 0 || (outData && !outData->empty()))) { if (!outData) { outData = std::make_unique(); } deliverCallbackIfAllowed(&HTTPCodec::Callback::onBody, ""onBody"", curHeader_.stream, std::move(outData), padding); } return (pendingDataFrameBytes_ > 0) ? ErrorCode::NO_ERROR : handleEndStream(); } ErrorCode HTTP2Codec::parseHeaders(Cursor& cursor) { FOLLY_SCOPED_TRACE_SECTION(""HTTP2Codec - parseHeaders""); folly::Optional priority; std::unique_ptr headerBuf; VLOG(4) << ""parsing HEADERS frame for stream="" << curHeader_.stream << "" length="" << curHeader_.length; auto err = http2::parseHeaders(cursor, curHeader_, priority, headerBuf); RETURN_IF_ERROR(err); if (transportDirection_ == TransportDirection::DOWNSTREAM) { RETURN_IF_ERROR( checkNewStream(curHeader_.stream, true /* trailersAllowed */)); } err = parseHeadersImpl( cursor, std::move(headerBuf), priority, folly::none, folly::none); return err; } ErrorCode HTTP2Codec::parseExHeaders(Cursor& cursor) { FOLLY_SCOPED_TRACE_SECTION(""HTTP2Codec - parseExHeaders""); HTTPCodec::ExAttributes exAttributes; folly::Optional priority; std::unique_ptr headerBuf; VLOG(4) << ""parsing ExHEADERS frame for stream="" << curHeader_.stream << "" length="" << curHeader_.length; auto err = http2::parseExHeaders( cursor, curHeader_, exAttributes, priority, headerBuf); RETURN_IF_ERROR(err); if (isRequest(curHeader_.stream)) { RETURN_IF_ERROR( checkNewStream(curHeader_.stream, false /* trailersAllowed */)); } return parseHeadersImpl( cursor, std::move(headerBuf), priority, folly::none, exAttributes); } ErrorCode HTTP2Codec::parseContinuation(Cursor& cursor) { std::unique_ptr headerBuf; VLOG(4) << ""parsing CONTINUATION frame for stream="" << curHeader_.stream << "" length="" << curHeader_.length; auto err = http2::parseContinuation(cursor, curHeader_, headerBuf); RETURN_IF_ERROR(err); err = parseHeadersImpl( cursor, std::move(headerBuf), folly::none, folly::none, folly::none); return err; } ErrorCode HTTP2Codec::parseHeadersImpl( Cursor& /*cursor*/, std::unique_ptr headerBuf, const folly::Optional& priority, const folly::Optional& promisedStream, const folly::Optional& exAttributes) { curHeaderBlock_.append(std::move(headerBuf)); std::unique_ptr msg; uint32_t headersCompleteStream = curHeader_.stream; // if we're not parsing CONTINUATION, then it's start of new header block if (curHeader_.type != http2::FrameType::CONTINUATION) { headerBlockFrameType_ = curHeader_.type; if (promisedStream) { parsingReq_ = true; } else if (exAttributes) { parsingReq_ = isRequest(curHeader_.stream); } else { parsingReq_ = transportDirection_ == TransportDirection::DOWNSTREAM; } } else if (headerBlockFrameType_ == http2::FrameType::PUSH_PROMISE) { CHECK(promisedStream_.hasValue()); headersCompleteStream = *promisedStream_; } DeferredParseError parseError; if (curHeader_.flags & http2::END_HEADERS) { auto parseRes = parseHeadersDecodeFrames(priority, exAttributes); if (parseRes.hasError()) { parseError = std::move(parseRes.error()); if (parseError.connectionError) { return parseError.errorCode; } } else { msg = std::move(*parseRes); } } // Report back what we've parsed auto concurError = parseHeadersCheckConcurrentStreams(priority); if (concurError.has_value()) { return concurError.value(); } bool trailers = parsingTrailers(); bool allHeaderFramesReceived = (curHeader_.flags & http2::END_HEADERS) && (headerBlockFrameType_ == http2::FrameType::HEADERS); if (allHeaderFramesReceived && !trailers) { // Only deliver onMessageBegin once per stream. // For responses with CONTINUATION, this will be delayed until // the frame with the END_HEADERS flag set. deliverCallbackIfAllowed(&HTTPCodec::Callback::onMessageBegin, ""onMessageBegin"", curHeader_.stream, msg.get()); } else if (curHeader_.type == http2::FrameType::EX_HEADERS) { deliverCallbackIfAllowed(&HTTPCodec::Callback::onExMessageBegin, ""onExMessageBegin"", curHeader_.stream, exAttributes->controlStream, exAttributes->unidirectional, msg.get()); } else if (curHeader_.type == http2::FrameType::PUSH_PROMISE) { DCHECK(promisedStream); deliverCallbackIfAllowed(&HTTPCodec::Callback::onPushMessageBegin, ""onPushMessageBegin"", *promisedStream, curHeader_.stream, msg.get()); promisedStream_ = *promisedStream; headersCompleteStream = *promisedStream; } if (curHeader_.flags & http2::END_HEADERS) { if (!msg) { deliverDeferredParseError(parseError); return ErrorCode::NO_ERROR; } if (!(curHeader_.flags & http2::END_STREAM)) { // If it there are DATA frames coming, consider it chunked msg->setIsChunked(true); } if (trailers) { VLOG(4) << ""Trailers complete for streamId="" << headersCompleteStream << "" direction="" << transportDirection_; auto trailerHeaders = std::make_unique(msg->extractHeaders()); msg.reset(); deliverCallbackIfAllowed(&HTTPCodec::Callback::onTrailersComplete, ""onTrailersComplete"", headersCompleteStream, std::move(trailerHeaders)); } else { deliverCallbackIfAllowed(&HTTPCodec::Callback::onHeadersComplete, ""onHeadersComplete"", headersCompleteStream, std::move(msg)); promisedStream_ = folly::none; } } return handleEndStream(); } folly::Expected, HTTP2Codec::DeferredParseError> HTTP2Codec::parseHeadersDecodeFrames( const folly::Optional& priority, const folly::Optional& exAttributes) { // decompress headers Cursor headerCursor(curHeaderBlock_.front()); // Validate circular dependencies. if (priority && (curHeader_.stream == priority->streamDependency)) { return folly::makeUnexpected(DeferredParseError( ErrorCode::PROTOCOL_ERROR, false, folly::to(""Circular dependency for txn="", curHeader_.stream))); } decodeInfo_.init(parsingReq_, parsingDownstreamTrailers_, validateHeaders_, strictValidation_, exAttributes && exAttributes->controlStream != 0); if (priority) { decodeInfo_.msg->setHTTP2Priority(std::make_tuple( priority->streamDependency, priority->exclusive, priority->weight)); } headerCodec_.decodeStreaming( headerCursor, curHeaderBlock_.chainLength(), this); auto msg = std::move(decodeInfo_.msg); // Saving this in case we need to log it on error auto g = folly::makeGuard([this] { curHeaderBlock_.move(); }); // Check decoding error if (decodeInfo_.decodeError != HPACK::DecodeError::NONE) { static const std::string decodeErrorMessage = ""Failed decoding header block for stream=""; // Avoid logging header blocks that have failed decoding due to being // excessively large. if (decodeInfo_.decodeError != HPACK::DecodeError::HEADERS_TOO_LARGE) { LOG(ERROR) << decodeErrorMessage << curHeader_.stream << "" header block=""; VLOG(3) << IOBufPrinter::printHexFolly(curHeaderBlock_.front(), true); } else { LOG(ERROR) << decodeErrorMessage << curHeader_.stream; } if (msg) { // print the partial message msg->dumpMessage(3); } return folly::makeUnexpected( DeferredParseError(ErrorCode::COMPRESSION_ERROR, true, empty_string)); } // Check parsing error if (!decodeInfo_.parsingError.empty()) { // This is ""malformed"" per the RFC LOG(ERROR) << ""Failed parsing header list for stream="" << curHeader_.stream << "", error="" << decodeInfo_.parsingError; if (!decodeInfo_.headerErrorValue.empty()) { std::cerr << "" value="" << decodeInfo_.headerErrorValue << std::endl; } VLOG(3) << ""Header block="" << IOBufPrinter::printHexFolly(curHeaderBlock_.front(), true); if (transportDirection_ == TransportDirection::DOWNSTREAM && parsingHeaders() && !parsingTrailers()) { return folly::makeUnexpected( DeferredParseError(ErrorCode::NO_ERROR, false, folly::to(""HTTP2Codec stream error: "", ""stream="", curHeader_.stream, "" status="", 400, "" error: "", decodeInfo_.parsingError))); } else { // Upstream, PUSH_PROMISE, EX_HEADERS or trailers parsing failed: // PROTOCOL_ERROR return folly::makeUnexpected(DeferredParseError( ErrorCode::PROTOCOL_ERROR, false, folly::to(""Field section parsing failed txn="", curHeader_.stream))); } } return msg; } void HTTP2Codec::deliverDeferredParseError( const DeferredParseError& parseError) { CHECK(!parseError.connectionError); if (parseError.errorCode != ErrorCode::NO_ERROR) { streamError( parseError.errorMessage, parseError.errorCode, parsingHeaders()); if (promisedStream_) { streamError(""Malformed PUSH_PROMISE"", ErrorCode::REFUSED_STREAM, false, *promisedStream_); promisedStream_ = folly::none; } } else { HTTPException err(HTTPException::Direction::INGRESS, parseError.errorMessage); err.setHttpStatusCode(400); err.setProxygenError(kErrorParseHeader); deliverCallbackIfAllowed(&HTTPCodec::Callback::onError, ""onError"", curHeader_.stream, err, parsingHeaders()); } } folly::Optional HTTP2Codec::parseHeadersCheckConcurrentStreams( const folly::Optional& priority) { if (!isInitiatedStream(curHeader_.stream) && (curHeader_.type == http2::FrameType::HEADERS || curHeader_.type == http2::FrameType::EX_HEADERS)) { if (curHeader_.flags & http2::PRIORITY) { DCHECK(priority); // callback_->onPriority(priority.get()); } // callback checks total number of streams is smaller than settings max if (callback_ && callback_->numIncomingStreams() >= egressSettings_.getSetting(SettingsId::MAX_CONCURRENT_STREAMS, std::numeric_limits::max())) { streamError(folly::to(""Exceeded max_concurrent_streams""), ErrorCode::REFUSED_STREAM, true); return ErrorCode::NO_ERROR; } } return folly::none; } void HTTP2Codec::onHeader(const HPACKHeaderName& name, const folly::fbstring& value) { if (decodeInfo_.onHeader(name, value)) { if (userAgent_.empty() && name.getHeaderCode() == HTTP_HEADER_USER_AGENT) { userAgent_ = value.toStdString(); } } else { VLOG(4) << ""dir="" << uint32_t(transportDirection_) << decodeInfo_.parsingError << "" codec="" << headerCodec_; } } void HTTP2Codec::onHeadersComplete(HTTPHeaderSize decodedSize, bool /*acknowledge*/) { decodeInfo_.onHeadersComplete(decodedSize); decodeInfo_.msg->setAdvancedProtocolString(http2::kProtocolString); HTTPMessage* msg = decodeInfo_.msg.get(); HTTPRequestVerifier& verifier = decodeInfo_.verifier; if ((transportDirection_ == TransportDirection::DOWNSTREAM) && verifier.hasUpgradeProtocol() && (*msg->getUpgradeProtocol() == headers::kWebsocketString) && msg->getMethod() == HTTPMethod::CONNECT) { msg->setIngressWebsocketUpgrade(); ingressWebsocketUpgrade_ = true; } else if (!upgradedStreams_.empty()) { auto it = upgradedStreams_.find(curHeader_.stream); if (it != upgradedStreams_.end()) { upgradedStreams_.erase(curHeader_.stream); // a websocket upgrade was sent on this stream. if (msg->getStatusCode() != 200) { return; } msg->setIngressWebsocketUpgrade(); } } } void HTTP2Codec::onDecodeError(HPACK::DecodeError decodeError) { decodeInfo_.decodeError = decodeError; } ErrorCode HTTP2Codec::parsePriority(Cursor& cursor) { VLOG(4) << ""parsing PRIORITY frame for stream="" << curHeader_.stream << "" length="" << curHeader_.length; http2::PriorityUpdate pri; auto err = http2::parsePriority(cursor, curHeader_, pri); RETURN_IF_ERROR(err); if (curHeader_.stream == pri.streamDependency) { streamError( folly::to(""Circular dependency for txn="", curHeader_.stream), ErrorCode::PROTOCOL_ERROR, false); return ErrorCode::NO_ERROR; } // Now we have two onPriority overloads, this function pointer has to be // explicitly specified via a cast: auto onPriFunc = static_cast( &HTTPCodec::Callback::onPriority); deliverCallbackIfAllowed( onPriFunc, ""onPriority"", curHeader_.stream, std::make_tuple(pri.streamDependency, pri.exclusive, pri.weight)); return ErrorCode::NO_ERROR; } size_t HTTP2Codec::addPriorityNodes(PriorityQueue& queue, folly::IOBufQueue& writeBuf, uint8_t maxLevel) { HTTPCodec::StreamID parent = 0; size_t bytes = 0; while (maxLevel--) { auto id = createStream(); virtualPriorityNodes_.push_back(id); queue.addPriorityNode(id, parent); bytes += generatePriority(writeBuf, id, std::make_tuple(parent, false, 0)); parent = id; } return bytes; } ErrorCode HTTP2Codec::parseRstStream(Cursor& cursor) { // rst for stream in idle state - protocol error VLOG(4) << ""parsing RST_STREAM frame for stream="" << curHeader_.stream << "" length="" << curHeader_.length; upgradedStreams_.erase(curHeader_.stream); ErrorCode statusCode = ErrorCode::NO_ERROR; auto err = http2::parseRstStream(cursor, curHeader_, statusCode); RETURN_IF_ERROR(err); if (statusCode == ErrorCode::PROTOCOL_ERROR) { goawayErrorMessage_ = folly::to(""GOAWAY error: RST_STREAM with code="", getErrorCodeString(statusCode), "" for streamID="", curHeader_.stream, "" user-agent="", userAgent_); int logFreq = userAgent_.find(kOkhttp2) == std::string::npos ? 1 : kOkhttp2GoawayLogFreq; VLOG_EVERY_N(2, logFreq) << goawayErrorMessage_; } deliverCallbackIfAllowed( &HTTPCodec::Callback::onAbort, ""onAbort"", curHeader_.stream, statusCode); return ErrorCode::NO_ERROR; } ErrorCode HTTP2Codec::parseSettings(Cursor& cursor) { VLOG(4) << ""parsing SETTINGS frame for stream="" << curHeader_.stream << "" length="" << curHeader_.length; std::deque settings; auto err = http2::parseSettings(cursor, curHeader_, settings); RETURN_IF_ERROR(err); if (curHeader_.flags & http2::ACK) { handleSettingsAck(); return ErrorCode::NO_ERROR; } return handleSettings(settings); } void HTTP2Codec::handleSettingsAck() { if (pendingTableMaxSize_) { headerCodec_.setDecoderHeaderTableMaxSize(*pendingTableMaxSize_); pendingTableMaxSize_ = folly::none; } if (callback_) { callback_->onSettingsAck(); } } ErrorCode HTTP2Codec::handleSettings(const std::deque& settings) { SettingsList settingsList; for (auto& setting : settings) { switch (setting.first) { case SettingsId::HEADER_TABLE_SIZE: { uint32_t tableSize = setting.second; if (setting.second > http2::kMaxHeaderTableSize) { VLOG(2) << ""Limiting table size from "" << tableSize << "" to "" << http2::kMaxHeaderTableSize; tableSize = http2::kMaxHeaderTableSize; } headerCodec_.setEncoderHeaderTableSize(tableSize); } break; case SettingsId::ENABLE_PUSH: if ((setting.second != 0 && setting.second != 1) || (setting.second == 1 && transportDirection_ == TransportDirection::UPSTREAM)) { goawayErrorMessage_ = folly::to(""GOAWAY error: ENABLE_PUSH invalid setting="", setting.second, "" for streamID="", curHeader_.stream); VLOG(4) << goawayErrorMessage_; return ErrorCode::PROTOCOL_ERROR; } break; case SettingsId::MAX_CONCURRENT_STREAMS: break; case SettingsId::INITIAL_WINDOW_SIZE: if (setting.second > http2::kMaxWindowUpdateSize) { goawayErrorMessage_ = folly::to( ""GOAWAY error: INITIAL_WINDOW_SIZE invalid size="", setting.second, "" for streamID="", curHeader_.stream); VLOG(4) << goawayErrorMessage_; return ErrorCode::PROTOCOL_ERROR; } break; case SettingsId::MAX_FRAME_SIZE: if (setting.second < http2::kMaxFramePayloadLengthMin || setting.second > http2::kMaxFramePayloadLength) { goawayErrorMessage_ = folly::to(""GOAWAY error: MAX_FRAME_SIZE invalid size="", setting.second, "" for streamID="", curHeader_.stream); VLOG(4) << goawayErrorMessage_; return ErrorCode::PROTOCOL_ERROR; } ingressSettings_.setSetting(SettingsId::MAX_FRAME_SIZE, setting.second); break; case SettingsId::MAX_HEADER_LIST_SIZE: break; case SettingsId::ENABLE_EX_HEADERS: { auto ptr = egressSettings_.getSetting(SettingsId::ENABLE_EX_HEADERS); if (ptr && ptr->value > 0) { VLOG(4) << getTransportDirectionString(getTransportDirection()) << "" got ENABLE_EX_HEADERS="" << setting.second; if (setting.second != 0 && setting.second != 1) { goawayErrorMessage_ = folly::to(""GOAWAY error: invalid ENABLE_EX_HEADERS="", setting.second, "" for streamID="", curHeader_.stream); VLOG(4) << goawayErrorMessage_; return ErrorCode::PROTOCOL_ERROR; } break; } else { // egress ENABLE_EX_HEADERS is disabled, consider the ingress // ENABLE_EX_HEADERS as unknown setting, and ignore it. continue; } } case SettingsId::ENABLE_CONNECT_PROTOCOL: if (setting.second > 1) { goawayErrorMessage_ = folly::to( ""GOAWAY error: ENABLE_CONNECT_PROTOCOL invalid number="", setting.second, "" for streamID="", curHeader_.stream); VLOG(4) << goawayErrorMessage_; return ErrorCode::PROTOCOL_ERROR; } break; case SettingsId::THRIFT_CHANNEL_ID: case SettingsId::THRIFT_CHANNEL_ID_DEPRECATED: break; case SettingsId::SETTINGS_HTTP_CERT_AUTH: break; default: continue; // ignore unknown setting } ingressSettings_.setSetting(setting.first, setting.second); settingsList.push_back(*ingressSettings_.getSetting(setting.first)); } if (callback_) { callback_->onSettings(settingsList); } return ErrorCode::NO_ERROR; } ErrorCode HTTP2Codec::parsePushPromise(Cursor& cursor) { // stream id must be idle - protocol error // assoc-stream-id=closed/unknown - protocol error, unless rst_stream sent /* * What does ""must handle"" mean in the following context? I have to * accept this as a valid pushed resource? However, an endpoint that has sent RST_STREAM on the associated stream MUST handle PUSH_PROMISE frames that might have been created before the RST_STREAM frame is received and processed. */ if (transportDirection_ != TransportDirection::UPSTREAM) { goawayErrorMessage_ = folly::to(""Received PUSH_PROMISE on DOWNSTREAM codec""); VLOG(2) << goawayErrorMessage_; return ErrorCode::PROTOCOL_ERROR; } if (egressSettings_.getSetting(SettingsId::ENABLE_PUSH, -1) != 1) { goawayErrorMessage_ = folly::to(""Received PUSH_PROMISE on codec with push disabled""); VLOG(2) << goawayErrorMessage_; return ErrorCode::PROTOCOL_ERROR; } VLOG(4) << ""parsing PUSH_PROMISE frame for stream="" << curHeader_.stream << "" length="" << curHeader_.length; uint32_t promisedStream; std::unique_ptr headerBlockFragment; auto err = http2::parsePushPromise( cursor, curHeader_, promisedStream, headerBlockFragment); RETURN_IF_ERROR(err); RETURN_IF_ERROR(checkNewStream(promisedStream, false /* trailersAllowed */)); err = parseHeadersImpl(cursor, std::move(headerBlockFragment), folly::none, promisedStream, folly::none); return err; } ErrorCode HTTP2Codec::parsePing(Cursor& cursor) { VLOG(4) << ""parsing PING frame length="" << curHeader_.length; uint64_t opaqueData = 0; auto err = http2::parsePing(cursor, curHeader_, opaqueData); RETURN_IF_ERROR(err); if (callback_) { if (curHeader_.flags & http2::ACK) { callback_->onPingReply(opaqueData); } else { callback_->onPingRequest(opaqueData); } } return ErrorCode::NO_ERROR; } ErrorCode HTTP2Codec::parseGoaway(Cursor& cursor) { VLOG(4) << ""parsing GOAWAY frame length="" << curHeader_.length; uint32_t lastGoodStream = 0; ErrorCode statusCode = ErrorCode::NO_ERROR; std::unique_ptr debugData; auto err = http2::parseGoaway( cursor, curHeader_, lastGoodStream, statusCode, debugData); if (statusCode != ErrorCode::NO_ERROR) { VLOG(3) << ""Goaway error statusCode="" << getErrorCodeString(statusCode) << "" lastStream="" << lastGoodStream << "" user-agent="" << userAgent_ << "" debugData="" << ((debugData) ? string((char*)debugData->data(), debugData->length()) : empty_string); } RETURN_IF_ERROR(err); if (lastGoodStream < ingressGoawayAck_) { ingressGoawayAck_ = lastGoodStream; // Drain all streams <= lastGoodStream // and abort streams > lastGoodStream if (callback_) { callback_->onGoaway(lastGoodStream, statusCode, std::move(debugData)); } } else { LOG(WARNING) << ""Received multiple GOAWAY with increasing ack""; } return ErrorCode::NO_ERROR; } ErrorCode HTTP2Codec::parseWindowUpdate(Cursor& cursor) { VLOG(4) << ""parsing WINDOW_UPDATE frame for stream="" << curHeader_.stream << "" length="" << curHeader_.length; uint32_t delta = 0; auto err = http2::parseWindowUpdate(cursor, curHeader_, delta); RETURN_IF_ERROR(err); if (delta == 0) { VLOG(4) << ""Invalid 0 length delta for stream="" << curHeader_.stream; if (curHeader_.stream == 0) { goawayErrorMessage_ = folly::to( ""GOAWAY error: invalid/0 length delta for streamID="", curHeader_.stream); return ErrorCode::PROTOCOL_ERROR; } else { // Parsing a zero delta window update should cause a protocol error // and send a rst stream goawayErrorMessage_ = folly::to(""parseWindowUpdate Invalid 0 length""); VLOG(4) << goawayErrorMessage_; streamError(folly::to(""streamID="", curHeader_.stream, "" with HTTP2Codec stream error: "", ""window update delta="", delta), ErrorCode::PROTOCOL_ERROR); return ErrorCode::PROTOCOL_ERROR; } } // if window exceeds 2^31-1, connection/stream error flow control error // must be checked in session/txn deliverCallbackIfAllowed(&HTTPCodec::Callback::onWindowUpdate, ""onWindowUpdate"", curHeader_.stream, delta); return ErrorCode::NO_ERROR; } ErrorCode HTTP2Codec::parseCertificateRequest(Cursor& cursor) { VLOG(4) << ""parsing CERTIFICATE_REQUEST frame length="" << curHeader_.length; uint16_t requestId = 0; std::unique_ptr authRequest; auto err = http2::parseCertificateRequest( cursor, curHeader_, requestId, authRequest); RETURN_IF_ERROR(err); if (callback_) { callback_->onCertificateRequest(requestId, std::move(authRequest)); } return ErrorCode::NO_ERROR; } ErrorCode HTTP2Codec::parseCertificate(Cursor& cursor) { VLOG(4) << ""parsing CERTIFICATE frame length="" << curHeader_.length; uint16_t certId = 0; std::unique_ptr authData; auto err = http2::parseCertificate(cursor, curHeader_, certId, authData); RETURN_IF_ERROR(err); if (curAuthenticatorBlock_.empty()) { curCertId_ = certId; } else if (certId != curCertId_) { // Received CERTIFICATE frame with different Cert-ID. return ErrorCode::PROTOCOL_ERROR; } curAuthenticatorBlock_.append(std::move(authData)); if (curAuthenticatorBlock_.chainLength() > http2::kMaxAuthenticatorBufSize) { // Received excessively long authenticator. return ErrorCode::PROTOCOL_ERROR; } if (!(curHeader_.flags & http2::TO_BE_CONTINUED)) { auto authenticator = curAuthenticatorBlock_.move(); if (callback_) { callback_->onCertificate(certId, std::move(authenticator)); } else { curAuthenticatorBlock_.clear(); } } return ErrorCode::NO_ERROR; } ErrorCode HTTP2Codec::checkNewStream(uint32_t streamId, bool trailersAllowed) { bool existingStream = (streamId <= lastStreamID_); if (streamId == 0 || (!trailersAllowed && existingStream)) { goawayErrorMessage_ = folly::to(""GOAWAY error: received streamID="", streamId, "" as invalid new stream for lastStreamID_="", lastStreamID_); VLOG(4) << goawayErrorMessage_; return ErrorCode::PROTOCOL_ERROR; } parsingDownstreamTrailers_ = trailersAllowed && existingStream; if (parsingDownstreamTrailers_) { VLOG(4) << ""Parsing downstream trailers streamId="" << streamId; } if (sessionClosing_ != ClosingState::CLOSED && !existingStream) { lastStreamID_ = streamId; } if (isInitiatedStream(streamId)) { // this stream should be initiated by us, not by peer goawayErrorMessage_ = folly::to( ""GOAWAY error: invalid new stream received with streamID="", streamId); VLOG(4) << goawayErrorMessage_; return ErrorCode::PROTOCOL_ERROR; } else { return ErrorCode::NO_ERROR; } } size_t HTTP2Codec::generateConnectionPreface(folly::IOBufQueue& writeBuf) { if (transportDirection_ == TransportDirection::UPSTREAM) { VLOG(4) << ""generating connection preface""; writeBuf.append(http2::kConnectionPreface); return http2::kConnectionPreface.length(); } return 0; } bool HTTP2Codec::onIngressUpgradeMessage(const HTTPMessage& msg) { if (!HTTPParallelCodec::onIngressUpgradeMessage(msg)) { return false; } if (msg.getHeaders().getNumberOfValues(http2::kProtocolSettingsHeader) != 1) { VLOG(4) << __func__ << "" with no HTTP2-Settings""; return false; } const auto& settingsHeader = msg.getHeaders().getSingleOrEmpty(http2::kProtocolSettingsHeader); if (settingsHeader.empty()) { return true; } auto decoded = base64url_decode(settingsHeader); // Must be well formed Base64Url and not too large if (decoded.empty() || decoded.length() > http2::kMaxFramePayloadLength) { VLOG(4) << __func__ << "" failed to decode HTTP2-Settings""; return false; } std::unique_ptr decodedBuf = IOBuf::wrapBuffer(decoded.data(), decoded.length()); IOBufQueue settingsQueue{IOBufQueue::cacheChainLength()}; settingsQueue.append(std::move(decodedBuf)); Cursor c(settingsQueue.front()); std::deque settings; // downcast is ok because of above length check http2::FrameHeader frameHeader{(uint32_t)settingsQueue.chainLength(), 0, http2::FrameType::SETTINGS, 0, 0}; auto err = http2::parseSettings(c, frameHeader, settings); if (err != ErrorCode::NO_ERROR) { VLOG(4) << __func__ << "" bad settings frame""; return false; } if (handleSettings(settings) != ErrorCode::NO_ERROR) { VLOG(4) << __func__ << "" handleSettings failed""; return false; } return true; } void HTTP2Codec::generateHeader( folly::IOBufQueue& writeBuf, StreamID stream, const HTTPMessage& msg, bool eom, HTTPHeaderSize* size, const folly::Optional& extraHeaders) { generateHeaderImpl(writeBuf, stream, msg, folly::none, /* assocStream */ folly::none, /* controlStream */ eom, size, extraHeaders); } void HTTP2Codec::generatePushPromise(folly::IOBufQueue& writeBuf, StreamID stream, const HTTPMessage& msg, StreamID assocStream, bool eom, HTTPHeaderSize* size) { generateHeaderImpl(writeBuf, stream, msg, assocStream, folly::none, /* controlStream */ eom, size, folly::none /* extraHeaders */); } void HTTP2Codec::generateExHeader(folly::IOBufQueue& writeBuf, StreamID stream, const HTTPMessage& msg, const HTTPCodec::ExAttributes& exAttributes, bool eom, HTTPHeaderSize* size) { generateHeaderImpl(writeBuf, stream, msg, folly::none, /* assocStream */ exAttributes, eom, size, folly::none /* extraHeaders */); } size_t HTTP2Codec::splitCompressed(size_t compressed, uint32_t remainingFrameSize, folly::IOBufQueue& writeBuf, folly::IOBufQueue& queue) { CHECK_GT(compressed, 0) << ""compressed block must be at least 1 byte""; auto chunkLen = compressed; if (chunkLen > remainingFrameSize) { // There's more here than fits in one frame. Put the remainder in queue chunkLen = remainingFrameSize; auto tailSize = compressed - remainingFrameSize; auto head = writeBuf.split(writeBuf.chainLength() - tailSize); queue.append(writeBuf.move()); writeBuf.append(std::move(head)); } return chunkLen; } void HTTP2Codec::generateHeaderImpl( folly::IOBufQueue& writeBuf, StreamID stream, const HTTPMessage& msg, const folly::Optional& assocStream, const folly::Optional& exAttributes, bool eom, HTTPHeaderSize* size, const folly::Optional& extraHeaders) { HTTPHeaderSize localSize; if (!size) { size = &localSize; } if (assocStream) { CHECK(!exAttributes); VLOG(4) << ""generating PUSH_PROMISE for stream="" << stream; } else if (exAttributes) { CHECK(!assocStream); VLOG(4) << ""generating ExHEADERS for stream="" << stream << "" with control stream="" << exAttributes->controlStream << "" unidirectional="" << exAttributes->unidirectional; } else { VLOG(4) << ""generating HEADERS for stream="" << stream; } if (!isStreamIngressEgressAllowed(stream)) { VLOG(2) << ""Suppressing HEADERS/PROMISE for stream="" << stream << "" ingressGoawayAck_="" << ingressGoawayAck_; if (size) { size->uncompressed = 0; size->compressed = 0; } return; } if (msg.isRequest()) { DCHECK(transportDirection_ == TransportDirection::UPSTREAM || assocStream || exAttributes); if (msg.isEgressWebsocketUpgrade()) { upgradedStreams_.insert(stream); } } else { DCHECK(transportDirection_ == TransportDirection::DOWNSTREAM || exAttributes); } auto httpPri = msg.getHTTP2Priority(); folly::Optional pri; if (httpPri) { pri = http2::PriorityUpdate{ std::get<0>(*httpPri), std::get<1>(*httpPri), std::get<2>(*httpPri)}; if (pri->streamDependency == stream) { LOG(ERROR) << ""Overwriting circular dependency for stream="" << stream; pri = http2::DefaultPriority; } } auto headerSize = http2::calculatePreHeaderBlockSize(assocStream.has_value(), exAttributes.has_value(), pri.has_value(), false); auto maxFrameSize = maxSendFrameSize(); uint32_t remainingFrameSize = maxFrameSize - headerSize + http2::kFrameHeaderSize; auto frameHeader = writeBuf.preallocate(headerSize, kDefaultGrowth); writeBuf.postallocate(headerSize); headerCodec_.encodeHTTP(msg, writeBuf, addDateToResponse_, extraHeaders); *size = headerCodec_.getEncodedSize(); IOBufQueue queue(IOBufQueue::cacheChainLength()); auto chunkLen = splitCompressed(size->compressed, remainingFrameSize, writeBuf, queue); bool endHeaders = queue.chainLength() == 0; if (assocStream) { DCHECK_EQ(transportDirection_, TransportDirection::DOWNSTREAM); DCHECK(!eom); generateHeaderCallbackWrapper( stream, http2::FrameType::PUSH_PROMISE, http2::writePushPromise((uint8_t*)frameHeader.first, frameHeader.second, writeBuf, *assocStream, stream, chunkLen, http2::kNoPadding, endHeaders)); } else if (exAttributes) { generateHeaderCallbackWrapper( stream, http2::FrameType::EX_HEADERS, http2::writeExHeaders((uint8_t*)frameHeader.first, frameHeader.second, writeBuf, chunkLen, stream, *exAttributes, pri, http2::kNoPadding, eom, endHeaders)); } else { generateHeaderCallbackWrapper( stream, http2::FrameType::HEADERS, http2::writeHeaders((uint8_t*)frameHeader.first, frameHeader.second, writeBuf, chunkLen, stream, pri, http2::kNoPadding, eom, endHeaders)); } if (!endHeaders) { generateContinuation( writeBuf, queue, assocStream ? *assocStream : stream, maxFrameSize); } } void HTTP2Codec::generateContinuation(folly::IOBufQueue& writeBuf, folly::IOBufQueue& queue, StreamID stream, size_t maxFrameSize) { bool endHeaders = false; while (!endHeaders) { auto chunk = queue.split(std::min(maxFrameSize, queue.chainLength())); endHeaders = (queue.chainLength() == 0); VLOG(4) << ""generating CONTINUATION for stream="" << stream; generateHeaderCallbackWrapper( stream, http2::FrameType::CONTINUATION, http2::writeContinuation( writeBuf, stream, endHeaders, std::move(chunk))); } } void HTTP2Codec::encodeHeaders(folly::IOBufQueue& writeBuf, const HTTPHeaders& headers, std::vector& allHeaders, HTTPHeaderSize* size) { headerCodec_.encode(allHeaders, writeBuf); if (size) { *size = headerCodec_.getEncodedSize(); } if (headerCodec_.getEncodedSize().uncompressed > ingressSettings_.getSetting(SettingsId::MAX_HEADER_LIST_SIZE, std::numeric_limits::max())) { // The remote side told us they don't want headers this large... // but this function has no mechanism to fail string serializedHeaders; headers.forEach( [&serializedHeaders](const string& name, const string& value) { serializedHeaders = folly::to(serializedHeaders, ""\\\\n"", name, "":"", value); }); LOG(ERROR) << ""generating HEADERS frame larger than peer maximum nHeaders="" << headers.size() << "" all headers="" << serializedHeaders; } } size_t HTTP2Codec::generateHeaderCallbackWrapper(StreamID stream, http2::FrameType type, size_t length) { if (callback_) { callback_->onGenerateFrameHeader( stream, static_cast(type), length); } return length; } size_t HTTP2Codec::generateBody(folly::IOBufQueue& writeBuf, StreamID stream, std::unique_ptr chain, folly::Optional padding, bool eom) { // todo: generate random padding for everything? size_t written = 0; if (!isStreamIngressEgressAllowed(stream)) { VLOG(2) << ""Suppressing DATA for stream="" << stream << "" ingressGoawayAck_="" << ingressGoawayAck_; return 0; } IOBufQueue queue(IOBufQueue::cacheChainLength()); queue.append(std::move(chain)); size_t maxFrameSize = maxSendFrameSize(); while (queue.chainLength() > maxFrameSize) { auto chunk = queue.split(maxFrameSize); written += generateHeaderCallbackWrapper( stream, http2::FrameType::DATA, http2::writeData(writeBuf, std::move(chunk), stream, padding, false, reuseIOBufHeadroomForData_)); } return written + generateHeaderCallbackWrapper( stream, http2::FrameType::DATA, http2::writeData(writeBuf, queue.move(), stream, padding, eom, reuseIOBufHeadroomForData_)); } size_t HTTP2Codec::generateChunkHeader(folly::IOBufQueue& /*writeBuf*/, StreamID /*stream*/, size_t /*length*/) { // HTTP/2 has no chunk headers return 0; } size_t HTTP2Codec::generateChunkTerminator(folly::IOBufQueue& /*writeBuf*/, StreamID /*stream*/) { // HTTP/2 has no chunk terminators return 0; } size_t HTTP2Codec::generateTrailers(folly::IOBufQueue& writeBuf, StreamID stream, const HTTPHeaders& trailers) { VLOG(4) << ""generating TRAILERS for stream="" << stream; std::vector allHeaders; CodecUtil::appendHeaders(trailers, allHeaders, HTTP_HEADER_NONE); HTTPHeaderSize size{0, 0, 0}; uint8_t headerSize = http2::kFrameHeaderSize; auto remainingFrameSize = maxSendFrameSize(); auto frameHeader = writeBuf.preallocate(headerSize, kDefaultGrowth); writeBuf.postallocate(headerSize); encodeHeaders(writeBuf, trailers, allHeaders, &size); IOBufQueue queue(IOBufQueue::cacheChainLength()); auto chunkLen = splitCompressed(size.compressed, remainingFrameSize, writeBuf, queue); bool endHeaders = queue.chainLength() == 0; generateHeaderCallbackWrapper(stream, http2::FrameType::HEADERS, http2::writeHeaders((uint8_t*)frameHeader.first, frameHeader.second, writeBuf, chunkLen, stream, folly::none, http2::kNoPadding, true /*eom*/, endHeaders)); if (!endHeaders) { generateContinuation(writeBuf, queue, stream, remainingFrameSize); } return size.compressed; } size_t HTTP2Codec::generateEOM(folly::IOBufQueue& writeBuf, StreamID stream) { VLOG(4) << ""sending EOM for stream="" << stream; upgradedStreams_.erase(stream); if (!isStreamIngressEgressAllowed(stream)) { VLOG(2) << ""suppressed EOM for stream="" << stream << "" ingressGoawayAck_="" << ingressGoawayAck_; return 0; } return generateHeaderCallbackWrapper( stream, http2::FrameType::DATA, http2::writeData(writeBuf, nullptr, stream, http2::kNoPadding, true, reuseIOBufHeadroomForData_)); } size_t HTTP2Codec::generateRstStream(folly::IOBufQueue& writeBuf, StreamID stream, ErrorCode statusCode) { VLOG(4) << ""sending RST_STREAM for stream="" << stream << "" with code="" << getErrorCodeString(statusCode); if (!isStreamIngressEgressAllowed(stream)) { VLOG(2) << ""suppressed RST_STREAM for stream="" << stream << "" ingressGoawayAck_="" << ingressGoawayAck_; return 0; } // Suppress any EOM callback for the current frame. if (stream == curHeader_.stream) { curHeader_.flags &= ~http2::END_STREAM; pendingEndStreamHandling_ = false; ingressWebsocketUpgrade_ = false; } upgradedStreams_.erase(stream); if (statusCode == ErrorCode::PROTOCOL_ERROR) { VLOG(2) << ""sending RST_STREAM with code="" << getErrorCodeString(statusCode) << "" for stream="" << stream << "" user-agent="" << userAgent_; } return generateHeaderCallbackWrapper( stream, http2::FrameType::RST_STREAM, http2::writeRstStream(writeBuf, stream, statusCode)); } size_t HTTP2Codec::generateGoaway(folly::IOBufQueue& writeBuf, StreamID lastStream, ErrorCode statusCode, std::unique_ptr debugData) { if (sessionClosing_ == ClosingState::CLOSED) { VLOG(4) << ""Not sending GOAWAY for closed session""; return 0; } // If the caller didn't specify a last stream, choose the correct one // If there's an error or this is the final GOAWAY, use last received stream if (lastStream == HTTPCodec::MaxStreamID) { if (statusCode != ErrorCode::NO_ERROR || !isReusable() || isWaitingToDrain()) { lastStream = getLastIncomingStreamID(); } else { lastStream = http2::kMaxStreamID; } } DCHECK_LE(lastStream, egressGoawayAck_) << ""Cannot increase last good stream""; egressGoawayAck_ = lastStream; switch (sessionClosing_) { case ClosingState::OPEN: case ClosingState::OPEN_WITH_GRACEFUL_DRAIN_ENABLED: if (lastStream == http2::kMaxStreamID && statusCode == ErrorCode::NO_ERROR) { sessionClosing_ = ClosingState::FIRST_GOAWAY_SENT; } else { // The user of this codec decided not to do the double goaway // drain, or this is not a graceful shutdown sessionClosing_ = ClosingState::CLOSED; } break; case ClosingState::FIRST_GOAWAY_SENT: sessionClosing_ = ClosingState::CLOSED; break; case ClosingState::CLOSING: case ClosingState::CLOSED: LOG(FATAL) << ""unreachable""; } VLOG(4) << ""Sending GOAWAY with last acknowledged stream="" << lastStream << "" with code="" << getErrorCodeString(statusCode); if (statusCode == ErrorCode::PROTOCOL_ERROR) { VLOG(2) << ""sending GOAWAY with last acknowledged stream="" << lastStream << "" with code="" << getErrorCodeString(statusCode) << "" user-agent="" << userAgent_; } return generateHeaderCallbackWrapper( 0, http2::FrameType::GOAWAY, http2::writeGoaway( writeBuf, lastStream, statusCode, std::move(debugData))); } size_t HTTP2Codec::generatePingRequest(folly::IOBufQueue& writeBuf, folly::Optional data) { // should probably let the caller specify when integrating with session // we know HTTPSession sets up events to track ping latency if (!data.has_value()) { data = folly::Random::rand64(); } VLOG(4) << ""Generating ping request with data="" << *data; return generateHeaderCallbackWrapper( 0, http2::FrameType::PING, http2::writePing(writeBuf, *data, false /* no ack */)); } size_t HTTP2Codec::generatePingReply(folly::IOBufQueue& writeBuf, uint64_t data) { VLOG(4) << ""Generating ping reply with data="" << data; return generateHeaderCallbackWrapper( 0, http2::FrameType::PING, http2::writePing(writeBuf, data, true /* ack */)); } size_t HTTP2Codec::generateSettings(folly::IOBufQueue& writeBuf) { std::deque settings; for (auto& setting : egressSettings_.getAllSettings()) { switch (setting.id) { case SettingsId::HEADER_TABLE_SIZE: if (pendingTableMaxSize_) { LOG(ERROR) << ""Can't have more than one settings in flight, skipping""; continue; } else { pendingTableMaxSize_ = setting.value; } break; case SettingsId::ENABLE_PUSH: if (transportDirection_ == TransportDirection::DOWNSTREAM) { // HTTP/2 spec says downstream must not send this flag // HTTP2Codec uses it to determine if push features are enabled continue; } else { CHECK(setting.value == 0 || setting.value == 1); } break; case SettingsId::MAX_CONCURRENT_STREAMS: case SettingsId::INITIAL_WINDOW_SIZE: case SettingsId::MAX_FRAME_SIZE: break; case SettingsId::MAX_HEADER_LIST_SIZE: headerCodec_.setMaxUncompressed(setting.value); break; case SettingsId::ENABLE_EX_HEADERS: CHECK(setting.value == 0 || setting.value == 1); if (setting.value == 0) { continue; // just skip the experimental setting if disabled } else { VLOG(4) << ""generating ENABLE_EX_HEADERS="" << setting.value; } break; case SettingsId::ENABLE_CONNECT_PROTOCOL: if (setting.value == 0) { continue; } break; case SettingsId::THRIFT_CHANNEL_ID: case SettingsId::THRIFT_CHANNEL_ID_DEPRECATED: break; default: LOG(ERROR) << ""ignore unknown settingsId="" << std::underlying_type::type(setting.id) << "" value="" << setting.value; continue; } settings.push_back(SettingPair(setting.id, setting.value)); } VLOG(4) << getTransportDirectionString(getTransportDirection()) << "" generating "" << (unsigned)settings.size() << "" settings""; return generateHeaderCallbackWrapper( 0, http2::FrameType::SETTINGS, http2::writeSettings(writeBuf, settings)); } void HTTP2Codec::requestUpgrade(HTTPMessage& request) { HTTP2Codec defaultCodec{TransportDirection::UPSTREAM}; auto& headers = request.getHeaders(); headers.set(HTTP_HEADER_UPGRADE, http2::kProtocolCleartextString); bool addUpgrade = !request.checkForHeaderToken(HTTP_HEADER_CONNECTION, ""Upgrade"", false); IOBufQueue writeBuf{IOBufQueue::cacheChainLength()}; // TODO staatic generateSettings defaultCodec.generateSettings(writeBuf); writeBuf.trimStart(http2::kFrameHeaderSize); auto buf = writeBuf.move(); buf->coalesce(); headers.set(http2::kProtocolSettingsHeader, base64url_encode(folly::ByteRange(buf->data(), buf->length()))); bool addSettings = !request.checkForHeaderToken( HTTP_HEADER_CONNECTION, http2::kProtocolSettingsHeader.c_str(), false); if (addUpgrade && addSettings) { headers.add(HTTP_HEADER_CONNECTION, folly::to(""Upgrade, "", http2::kProtocolSettingsHeader)); } else if (addUpgrade) { headers.add(HTTP_HEADER_CONNECTION, ""Upgrade""); } else if (addSettings) { headers.add(HTTP_HEADER_CONNECTION, http2::kProtocolSettingsHeader); } } size_t HTTP2Codec::generateSettingsAck(folly::IOBufQueue& writeBuf) { VLOG(4) << getTransportDirectionString(getTransportDirection()) << "" generating settings ack""; return generateHeaderCallbackWrapper( 0, http2::FrameType::SETTINGS, http2::writeSettingsAck(writeBuf)); } size_t HTTP2Codec::generateWindowUpdate(folly::IOBufQueue& writeBuf, StreamID stream, uint32_t delta) { VLOG(4) << ""generating window update for stream="" << stream << "": Processed "" << delta << "" bytes""; if (!isStreamIngressEgressAllowed(stream)) { VLOG(2) << ""suppressed WINDOW_UPDATE for stream="" << stream << "" ingressGoawayAck_="" << ingressGoawayAck_; return 0; } return generateHeaderCallbackWrapper( stream, http2::FrameType::WINDOW_UPDATE, http2::writeWindowUpdate(writeBuf, stream, delta)); } size_t HTTP2Codec::generatePriority(folly::IOBufQueue& writeBuf, StreamID stream, const HTTPMessage::HTTP2Priority& pri) { VLOG(4) << ""generating priority for stream="" << stream; if (!isStreamIngressEgressAllowed(stream)) { VLOG(2) << ""suppressed PRIORITY for stream="" << stream << "" ingressGoawayAck_="" << ingressGoawayAck_; return 0; } return generateHeaderCallbackWrapper( stream, http2::FrameType::PRIORITY, http2::writePriority( writeBuf, stream, {std::get<0>(pri), std::get<1>(pri), std::get<2>(pri)})); } size_t HTTP2Codec::generatePriority(folly::IOBufQueue& /* writeBuf */, StreamID /* stream */, HTTPPriority /* priority */) { return 0; } size_t HTTP2Codec::generateCertificateRequest( folly::IOBufQueue& writeBuf, uint16_t requestId, std::unique_ptr certificateRequestData) { VLOG(4) << ""generating CERTIFICATE_REQUEST with Request-ID="" << requestId; return http2::writeCertificateRequest( writeBuf, requestId, std::move(certificateRequestData)); } size_t HTTP2Codec::generateCertificate(folly::IOBufQueue& writeBuf, uint16_t certId, std::unique_ptr certData) { size_t written = 0; VLOG(4) << ""sending CERTIFICATE with Cert-ID="" << certId << ""for stream=0""; IOBufQueue queue(IOBufQueue::cacheChainLength()); queue.append(std::move(certData)); // The maximum size of an autenticator fragment, combined with the Cert-ID can // not exceed the maximal allowable size of a sent frame. size_t maxChunkSize = maxSendFrameSize() - sizeof(certId); while (queue.chainLength() > maxChunkSize) { auto chunk = queue.splitAtMost(maxChunkSize); written += http2::writeCertificate(writeBuf, certId, std::move(chunk), true); } return written + http2::writeCertificate(writeBuf, certId, queue.move(), false); } bool HTTP2Codec::checkConnectionError(ErrorCode err, const folly::IOBuf* buf) { if (err != ErrorCode::NO_ERROR) { LOG(ERROR) << ""Connection error "" << getErrorCodeString(err) << "" with ingress=""; VLOG(3) << IOBufPrinter::printHexFolly(buf, true); if (callback_) { std::string errorDescription = goawayErrorMessage_.empty() ? ""Connection error"" : goawayErrorMessage_; HTTPException ex(HTTPException::Direction::INGRESS_AND_EGRESS, errorDescription); ex.setCodecStatusCode(err); callback_->onError(0, ex, false); } return true; } return false; } void HTTP2Codec::streamError(const std::string& msg, ErrorCode code, bool newTxn, folly::Optional streamId) { HTTPException error(HTTPException::Direction::INGRESS_AND_EGRESS, msg); error.setCodecStatusCode(code); deliverCallbackIfAllowed(&HTTPCodec::Callback::onError, ""onError"", streamId ? *streamId : curHeader_.stream, error, newTxn); } HTTPCodec::StreamID HTTP2Codec::mapPriorityToDependency( uint8_t priority) const { // If the priority is out of the maximum index of virtual nodes array, we // return the lowest level virtual node as a punishment of not setting // priority correctly. return virtualPriorityNodes_.empty() ? 0 : virtualPriorityNodes_[std::min( priority, uint8_t(virtualPriorityNodes_.size() - 1))]; } bool HTTP2Codec::parsingHeaders() const { return (curHeader_.type == http2::FrameType::HEADERS || (curHeader_.type == http2::FrameType::CONTINUATION && headerBlockFrameType_ == http2::FrameType::HEADERS)); } bool HTTP2Codec::parsingTrailers() const { // HEADERS frame is used for request/response headers and trailers. // Per spec, specific role of HEADERS frame is determined by it's postion // within the stream. We don't keep full stream state in this codec, // thus using heuristics to distinguish between headers/trailers. // For DOWNSTREAM case, request headers HEADERS frame would be creating // new stream, thus HEADERS on existing stream ID are considered trailers // (see checkNewStream). // For UPSTREAM case, response headers are required to have status code, // thus if no status code we consider that trailers. if (parsingHeaders()) { if (transportDirection_ == TransportDirection::DOWNSTREAM) { return parsingDownstreamTrailers_; } else { // We *might* be parsing trailers even if we couldn't decode the block. // We probably aren't, because trailers are rare, but if we do, // we might miscategorize as headers and give a second onMessageBegin. return decodeInfo_.parsingError.empty() && !decodeInfo_.hasStatus(); } } return false; } } // namespace proxygen ",16172,True,3334.840122969568,median "// Copyright (c) 2009-2019 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include #include #include #include #include #include #include