text,length,is_long_context,metric_val,label_metric "// 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/master/master_snapshot_coordinator.h"" #include #include #include #include #include ""yb/common/snapshot.h"" #include ""yb/docdb/consensus_frontier.h"" #include ""yb/docdb/doc_key.h"" #include ""yb/docdb/rocksdb_writer.h"" #include ""yb/docdb/value.h"" #include ""yb/docdb/value_type.h"" #include ""yb/master/async_snapshot_tasks.h"" #include ""yb/master/catalog_entity_info.h"" #include ""yb/master/master_error.h"" #include ""yb/master/master_heartbeat.pb.h"" #include ""yb/master/master_util.h"" #include ""yb/master/restoration_state.h"" #include ""yb/master/scoped_leader_shared_lock.h"" #include ""yb/master/snapshot_coordinator_context.h"" #include ""yb/master/snapshot_schedule_state.h"" #include ""yb/master/snapshot_state.h"" #include ""yb/master/sys_catalog_writer.h"" #include ""yb/rpc/poller.h"" #include ""yb/rpc/scheduler.h"" #include ""yb/tablet/operations/snapshot_operation.h"" #include ""yb/tablet/operations/write_operation.h"" #include ""yb/tablet/tablet.h"" #include ""yb/tablet/tablet_snapshots.h"" #include ""yb/tablet/write_query.h"" #include ""yb/util/async_util.h"" #include ""yb/util/flag_tags.h"" #include ""yb/util/pb_util.h"" #include ""yb/util/status_format.h"" #include ""yb/util/status_log.h"" #include ""yb/util/stopwatch.h"" using namespace std::literals; using namespace std::placeholders; DECLARE_int32(sys_catalog_write_timeout_ms); DEFINE_uint64(snapshot_coordinator_poll_interval_ms, 5000, ""Poll interval for snapshot coordinator in milliseconds.""); DEFINE_test_flag(bool, skip_sending_restore_finished, false, ""Whether we should skip sending RESTORE_FINISHED to tablets.""); DEFINE_bool(schedule_snapshot_rpcs_out_of_band, true, ""Should tablet snapshot RPCs be scheduled out of band from the periodic"" "" background scheduling.""); TAG_FLAG(schedule_snapshot_rpcs_out_of_band, runtime); DEFINE_bool(schedule_restoration_rpcs_out_of_band, true, ""Should tablet restoration RPCs be scheduled out of band from the periodic"" "" background scheduling.""); TAG_FLAG(schedule_restoration_rpcs_out_of_band, runtime); DEFINE_bool(skip_crash_on_duplicate_snapshot, false, ""Should we not crash when we get a create snapshot request with the same "" ""id as one of the previous snapshots.""); TAG_FLAG(skip_crash_on_duplicate_snapshot, runtime); DEFINE_test_flag(int32, delay_sys_catalog_restore_on_followers_secs, 0, ""Sleep for these many seconds on followers during sys catalog restore""); TAG_FLAG(TEST_delay_sys_catalog_restore_on_followers_secs, runtime); DECLARE_bool(allow_consecutive_restore); namespace yb { namespace master { namespace { YB_DEFINE_ENUM(Bound, (kFirst)(kLast)); void SubmitWrite( docdb::KeyValueWriteBatchPB&& write_batch, int64_t leader_term, SnapshotCoordinatorContext* context, const std::shared_ptr& synchronizer = nullptr) { auto query = std::make_unique( leader_term, CoarseMonoClock::now() + FLAGS_sys_catalog_write_timeout_ms * 1ms, /* context */ nullptr, /* tablet= */ nullptr); if (synchronizer) { query->set_callback( tablet::MakeWeakSynchronizerOperationCompletionCallback(synchronizer)); } *query->operation().AllocateRequest()->mutable_write_batch() = std::move(write_batch); context->Submit(query.release()->PrepareSubmit(), leader_term); } Status SynchronizedWrite( docdb::KeyValueWriteBatchPB&& write_batch, int64_t leader_term, CoarseTimePoint deadline, SnapshotCoordinatorContext* context) { auto synchronizer = std::make_shared(); SubmitWrite(std::move(write_batch), leader_term, context, synchronizer); return synchronizer->WaitUntil(ToSteady(deadline)); } struct RestorationData { TxnSnapshotId snapshot_id; TxnSnapshotRestorationId restoration_id; HybridTime restore_at; std::optional db_oid; }; struct NoOp { template void operator()(Args&&... args) const {} }; // Utility to create callback that is invoked when operation done. // Finds appropriate entry in passed collection and invokes Done on it. template auto MakeDoneCallback( std::mutex* mutex, const Collection& collection, const typename Collection::key_type& key, const TabletId& tablet_id, const PostProcess& post_process = PostProcess()) { struct DoneFunctor { std::mutex& mutex; const Collection& collection; typename Collection::key_type key; TabletId tablet_id; PostProcess post_process; void operator()(Result resp) const { std::unique_lock lock(mutex); auto it = collection.find(key); if (it == collection.end()) { LOG(DFATAL) << ""Received reply for unknown "" << key; return; } (**it).Done(tablet_id, ResultToStatus(resp)); post_process(it->get(), &lock); } }; return DoneFunctor { .mutex = *mutex, .collection = collection, .key = key, .tablet_id = tablet_id, .post_process = post_process, }; } } // namespace class MasterSnapshotCoordinator::Impl { public: explicit Impl(SnapshotCoordinatorContext* context, enterprise::CatalogManager* cm) : context_(*context), cm_(cm), poller_(std::bind(&Impl::Poll, this)) {} Result Create( const SysRowEntries& entries, bool imported, int64_t leader_term, CoarseTimePoint deadline) { auto synchronizer = std::make_shared(); auto snapshot_id = TxnSnapshotId::GenerateRandom(); SubmitCreate( entries, imported, SnapshotScheduleId::Nil(), HybridTime::kInvalid, snapshot_id, leader_term, tablet::MakeWeakSynchronizerOperationCompletionCallback(synchronizer)); RETURN_NOT_OK(synchronizer->WaitUntil(ToSteady(deadline))); return snapshot_id; } Result CreateForSchedule( const SnapshotScheduleId& schedule_id, int64_t leader_term, CoarseTimePoint deadline) { boost::optional operation; { std::lock_guard lock(mutex_); auto it = schedules_.find(schedule_id); if (it == schedules_.end()) { return STATUS_FORMAT(NotFound, ""Unknown snapshot schedule: $0"", schedule_id); } auto* last_snapshot = BoundingSnapshot((**it).id(), Bound::kLast); auto last_snapshot_time = last_snapshot ? last_snapshot->snapshot_hybrid_time() : HybridTime::kInvalid; auto creating_snapshot_data = (**it).creating_snapshot_data(); if (creating_snapshot_data.snapshot_id) { auto snapshot_it = snapshots_.find(creating_snapshot_data.snapshot_id); if (snapshot_it != snapshots_.end()) { VLOG(2) << __func__ << "" for "" << schedule_id << "" while creating snapshot: "" << (**snapshot_it).ToString(); } else { auto passed = CoarseMonoClock::now() - creating_snapshot_data.start_time; auto message = Format( ""$0 for $1 while creating unknown snapshot: $2 (passed $3)"", __func__, schedule_id, creating_snapshot_data.snapshot_id, passed); if (passed > 30s) { LOG(DFATAL) << message; } else { VLOG(2) << message; } } } operation = VERIFY_RESULT((**it).ForceCreateSnapshot(last_snapshot_time)); } auto synchronizer = std::make_shared(); RETURN_NOT_OK(ExecuteScheduleOperation(*operation, leader_term, synchronizer)); RETURN_NOT_OK(synchronizer->WaitUntil(ToSteady(deadline))); return operation->snapshot_id; } Status CreateReplicated( int64_t leader_term, const tablet::SnapshotOperation& operation) { // TODO(txn_backup) retain logs with this operation while doing snapshot auto id = VERIFY_RESULT(FullyDecodeTxnSnapshotId(operation.request()->snapshot_id())); VLOG(1) << __func__ << ""("" << id << "", "" << operation.ToString() << "")""; auto snapshot = std::make_unique( &context_, id, *operation.request(), GetRpcLimit(FLAGS_max_concurrent_snapshot_rpcs, FLAGS_max_concurrent_snapshot_rpcs_per_tserver, leader_term)); TabletSnapshotOperations operations; docdb::KeyValueWriteBatchPB write_batch; RETURN_NOT_OK(snapshot->StoreToWriteBatch(&write_batch)); boost::optional sys_catalog_snapshot_data; bool snapshot_empty = false; { std::lock_guard lock(mutex_); auto emplace_result = snapshots_.emplace(std::move(snapshot)); if (!emplace_result.second) { LOG(INFO) << ""Received a duplicate create snapshot request for id: "" << id; if (FLAGS_skip_crash_on_duplicate_snapshot) { LOG(INFO) << ""Skipping duplicate create snapshot request gracefully.""; return Status::OK(); } else { return STATUS_FORMAT(IllegalState, ""Duplicate snapshot id: $0"", id); } } if (leader_term >= 0) { (**emplace_result.first).PrepareOperations(&operations); } auto temp = (**emplace_result.first).SysCatalogSnapshotData(operation); if (temp.ok()) { sys_catalog_snapshot_data = *temp; } else if (!temp.status().IsUninitialized()) { return temp.status(); } snapshot_empty = (**emplace_result.first).Empty(); } RETURN_NOT_OK(operation.tablet()->ApplyOperation(operation, /* batch_idx= */ -1, write_batch)); if (sys_catalog_snapshot_data) { RETURN_NOT_OK(operation.tablet()->snapshots().Create(*sys_catalog_snapshot_data)); } ExecuteOperations(operations, leader_term); if (leader_term >= 0 && snapshot_empty) { // There could be snapshot for 0 tables, so they should be marked as complete right after // creation. UpdateSnapshotIfPresent(id, leader_term); } return Status::OK(); } void UpdateSnapshotIfPresent(const TxnSnapshotId& id, int64_t leader_term) NO_THREAD_SAFETY_ANALYSIS EXCLUDES(mutex_) { std::unique_lock lock(mutex_); auto it = snapshots_.find(id); if (it != snapshots_.end()) { UpdateSnapshot(it->get(), leader_term, &lock); } } template Status LoadEntryOfType( tablet::Tablet* tablet, const SysRowEntryType& type, Map* m) REQUIRES(mutex_) { return EnumerateSysCatalog(tablet, context_.schema(), type, [this, &m](const Slice& id, const Slice& data) NO_THREAD_SAFETY_ANALYSIS -> Status { return LoadEntry(id, data, m); }); } Status Load(tablet::Tablet* tablet) { std::lock_guard lock(mutex_); RETURN_NOT_OK(LoadEntryOfType( tablet, SysRowEntryType::SNAPSHOT, &snapshots_)); RETURN_NOT_OK(LoadEntryOfType( tablet, SysRowEntryType::SNAPSHOT_SCHEDULE, &schedules_)); return LoadEntryOfType( tablet, SysRowEntryType::SNAPSHOT_RESTORATION, &restorations_); } Status ApplyWritePair(Slice key, const Slice& value) { docdb::SubDocKey sub_doc_key; RETURN_NOT_OK(sub_doc_key.FullyDecodeFrom(key, docdb::HybridTimeRequired::kFalse)); if (sub_doc_key.doc_key().has_cotable_id()) { return Status::OK(); } if (sub_doc_key.doc_key().range_group().size() != 2) { LOG(DFATAL) << ""Unexpected size of range group in sys catalog entry (2 expected): "" << AsString(sub_doc_key.doc_key().range_group()) << ""("" << sub_doc_key.ToString() << "")""; return Status::OK(); } auto first_key = sub_doc_key.doc_key().range_group().front(); if (first_key.type() != docdb::KeyEntryType::kInt32) { LOG(DFATAL) << ""Unexpected value type for the first range component of sys catalog entry "" << ""(kInt32 expected): "" << AsString(sub_doc_key.doc_key().range_group());; } switch (first_key.GetInt32()) { case SysRowEntryType::SNAPSHOT: return DoApplyWrite( sub_doc_key.doc_key().range_group()[1].GetString(), value, &snapshots_); case SysRowEntryType::SNAPSHOT_SCHEDULE: return DoApplyWrite( sub_doc_key.doc_key().range_group()[1].GetString(), value, &schedules_); case SysRowEntryType::SNAPSHOT_RESTORATION: return DoApplyWrite( sub_doc_key.doc_key().range_group()[1].GetString(), value, &restorations_); default: return Status::OK(); } } template Status DoApplyWrite(const std::string& id_str, const Slice& value, Map* map) { docdb::Value decoded_value; RETURN_NOT_OK(decoded_value.Decode(value)); auto value_type = decoded_value.primitive_value().value_type(); if (value_type == docdb::ValueEntryType::kTombstone) { std::lock_guard lock(mutex_); auto id = Uuid::TryFullyDecode(id_str); if (id.IsNil()) { LOG(WARNING) << ""Unable to decode id: "" << id_str; return Status::OK(); } bool erased = map->erase(typename Map::key_type(id)) != 0; LOG_IF(DFATAL, !erased) << ""Unknown entry tombstoned: "" << id.ToString(); return Status::OK(); } if (value_type != docdb::ValueEntryType::kString) { return STATUS_FORMAT( Corruption, ""Bad value type: $0, expected kString while replaying write for sys catalog"", decoded_value.primitive_value().value_type()); } std::lock_guard lock(mutex_); return LoadEntry(id_str, decoded_value.primitive_value().GetString(), map); } Status ListSnapshots( const TxnSnapshotId& snapshot_id, bool list_deleted, ListSnapshotsResponsePB* resp) { std::lock_guard lock(mutex_); if (snapshot_id.IsNil()) { for (const auto& p : snapshots_.get()) { if (!list_deleted) { auto aggreaged_state = p->AggregatedState(); if (aggreaged_state.ok() && *aggreaged_state == SysSnapshotEntryPB::DELETED) { continue; } } RETURN_NOT_OK(p->ToPB(resp->add_snapshots())); } return Status::OK(); } SnapshotState& snapshot = VERIFY_RESULT(FindSnapshot(snapshot_id)); return snapshot.ToPB(resp->add_snapshots()); } Status Delete( const TxnSnapshotId& snapshot_id, int64_t leader_term, CoarseTimePoint deadline) { VLOG_WITH_FUNC(4) << snapshot_id << "", "" << leader_term; { std::lock_guard lock(mutex_); SnapshotState& snapshot = VERIFY_RESULT(FindSnapshot(snapshot_id)); RETURN_NOT_OK(snapshot.TryStartDelete()); } auto synchronizer = std::make_shared(); SubmitDelete(snapshot_id, leader_term, synchronizer); return synchronizer->WaitUntil(ToSteady(deadline)); } Status DeleteReplicated( int64_t leader_term, const tablet::SnapshotOperation& operation) { auto snapshot_id = VERIFY_RESULT(FullyDecodeTxnSnapshotId(operation.request()->snapshot_id())); VLOG_WITH_FUNC(4) << leader_term << "", "" << snapshot_id; docdb::KeyValueWriteBatchPB write_batch; TabletSnapshotOperations operations; bool delete_sys_catalog_snapshot; { std::lock_guard lock(mutex_); SnapshotState& snapshot = VERIFY_RESULT(FindSnapshot(snapshot_id)); if (snapshot.schedule_id()) { delete_sys_catalog_snapshot = true; } snapshot.SetInitialTabletsState(SysSnapshotEntryPB::DELETING); RETURN_NOT_OK(snapshot.StoreToWriteBatch(&write_batch)); if (leader_term >= 0) { snapshot.PrepareOperations(&operations); } } if (delete_sys_catalog_snapshot) { RETURN_NOT_OK(operation.tablet()->snapshots().Delete(operation)); } RETURN_NOT_OK(operation.tablet()->ApplyOperation(operation, /* batch_idx= */ -1, write_batch)); ExecuteOperations(operations, leader_term); return Status::OK(); } Status RestoreSysCatalogReplicated( int64_t leader_term, const tablet::SnapshotOperation& operation, Status* complete_status) { auto restoration = std::make_shared(SnapshotScheduleRestoration { .snapshot_id = VERIFY_RESULT(FullyDecodeTxnSnapshotId(operation.request()->snapshot_id())), .restore_at = HybridTime::FromPB(operation.request()->snapshot_hybrid_time()), .restoration_id = VERIFY_RESULT(FullyDecodeTxnSnapshotRestorationId( operation.request()->restoration_id())), .op_id = operation.op_id(), .write_time = operation.hybrid_time(), .term = leader_term, .schedules = {}, .non_system_obsolete_tablets = {}, .non_system_obsolete_tables = {}, .non_system_objects_to_restore = {}, .existing_system_tables = {}, .restoring_system_tables = {}, }); { std::lock_guard lock(mutex_); SnapshotState& snapshot = VERIFY_RESULT(FindSnapshot(restoration->snapshot_id)); SnapshotScheduleState& schedule_state = VERIFY_RESULT( FindSnapshotSchedule(snapshot.schedule_id())); LOG(INFO) << ""Restore sys catalog from snapshot: "" << snapshot.ToString() << "", schedule: "" << schedule_state.ToString() << "" at "" << restoration->restore_at << "", op id: "" << restoration->op_id; size_t this_idx = std::numeric_limits::max(); for (const auto& snapshot_schedule : schedules_) { if (snapshot_schedule->id() == snapshot.schedule_id()) { this_idx = restoration->schedules.size(); } restoration->schedules.emplace_back( snapshot_schedule->id(), snapshot_schedule->options().filter()); } if (this_idx == std::numeric_limits::max()) { return STATUS_FORMAT(IllegalState, ""Cannot find schedule for restoration: $0"", snapshot.schedule_id()); } std::swap(restoration->schedules[0], restoration->schedules[this_idx]); } // Inject artificial delay on followers for tests. if (leader_term < 0 && FLAGS_TEST_delay_sys_catalog_restore_on_followers_secs > 0) { SleepFor(MonoDelta::FromSeconds(FLAGS_TEST_delay_sys_catalog_restore_on_followers_secs)); } // Disable concurrent RPCs to the master leader for the duration of sys catalog restore. if (leader_term >= 0) { context_.PrepareRestore(); } LOG_SLOW_EXECUTION(INFO, 1000, ""Restore sys catalog took"") { RETURN_NOT_OK_PREPEND( context_.RestoreSysCatalog(restoration.get(), operation.tablet(), complete_status), ""Restore sys catalog failed""); } return Status::OK(); } Status ListRestorations( const TxnSnapshotRestorationId& restoration_id, const TxnSnapshotId& snapshot_id, ListSnapshotRestorationsResponsePB* resp) { std::lock_guard lock(mutex_); if (!restoration_id) { for (const auto& p : restorations_) { if (!snapshot_id || p->snapshot_id() == snapshot_id) { RETURN_NOT_OK(p->ToPB(resp->add_restorations())); } } return Status::OK(); } RestorationState& restoration = VERIFY_RESULT(FindRestoration(restoration_id)); return restoration.ToPB(resp->add_restorations()); } Result Restore( const TxnSnapshotId& snapshot_id, HybridTime restore_at, int64_t leader_term) { auto restoration_id = TxnSnapshotRestorationId::GenerateRandom(); RETURN_NOT_OK(DoRestore( snapshot_id, restore_at, restoration_id, RestorePhase::kInitial, leader_term)); return restoration_id; } Result CreateSchedule( const CreateSnapshotScheduleRequestPB& req, int64_t leader_term, CoarseTimePoint deadline) { SnapshotScheduleState schedule(&context_, req); docdb::KeyValueWriteBatchPB write_batch; RETURN_NOT_OK(schedule.StoreToWriteBatch(&write_batch)); RETURN_NOT_OK(SynchronizedWrite(std::move(write_batch), leader_term, deadline, &context_)); return schedule.id(); } Status ListSnapshotSchedules( const SnapshotScheduleId& snapshot_schedule_id, ListSnapshotSchedulesResponsePB* resp) { std::lock_guard lock(mutex_); if (snapshot_schedule_id.IsNil()) { for (const auto& p : schedules_) { RETURN_NOT_OK(FillSchedule(*p, resp->add_schedules())); } return Status::OK(); } SnapshotScheduleState& schedule = VERIFY_RESULT(FindSnapshotSchedule(snapshot_schedule_id)); return FillSchedule(schedule, resp->add_schedules()); } Status DeleteSnapshotSchedule( const SnapshotScheduleId& snapshot_schedule_id, int64_t leader_term, CoarseTimePoint deadline) { docdb::KeyValueWriteBatchPB write_batch; { std::lock_guard lock(mutex_); SnapshotScheduleState& schedule = VERIFY_RESULT(FindSnapshotSchedule(snapshot_schedule_id)); auto encoded_key = VERIFY_RESULT(schedule.EncodedKey()); auto pair = write_batch.add_write_pairs(); pair->set_key(encoded_key.AsSlice().cdata(), encoded_key.size()); auto options = schedule.options(); options.set_delete_time(context_.Clock()->Now().ToUint64()); auto* value = pair->mutable_value(); value->push_back(docdb::ValueEntryTypeAsChar::kString); RETURN_NOT_OK(pb_util::AppendPartialToString(options, value)); } return SynchronizedWrite(std::move(write_batch), leader_term, deadline, &context_); } Status FillHeartbeatResponse(TSHeartbeatResponsePB* resp) { std::lock_guard lock(mutex_); auto* out = resp->mutable_snapshots_info(); for (const auto& schedule : schedules_) { // Don't send deleted schedules. if (schedule->deleted()) { continue; } const auto& id = schedule->id(); auto* out_schedule = out->add_schedules(); out_schedule->set_id(id.data(), id.size()); auto time = LastSnapshotTime(id); if (time) { out_schedule->set_last_snapshot_hybrid_time(time.ToUint64()); } } out->set_last_restorations_update_ht(last_restorations_update_ht_.ToUint64()); for (const auto& restoration : restorations_) { auto* out_restoration = out->add_restorations(); const auto& id = restoration->restoration_id(); out_restoration->set_id(id.data(), id.size()); auto complete_time = restoration->complete_time(); if (complete_time) { out_restoration->set_complete_time_ht(complete_time.ToUint64()); } } return Status::OK(); } void VerifyRestoration(RestorationState* restoration) REQUIRES(mutex_) { auto schedule_result = FindSnapshotSchedule(restoration->schedule_id()); LOG_IF(DFATAL, !schedule_result.ok()) << ""Snapshot schedule not found for pending restore with id "" << restoration->restoration_id() << "", status: "" << schedule_result.status(); auto status = context_.VerifyRestoredObjects( restoration->MasterMetadata(), (*schedule_result).options().filter().tables().tables()); LOG_IF(DFATAL, !status.ok()) << ""Verify restoration failed: "" << status; LOG(INFO) << ""PITR: Master metadata verified successsfully for restoration "" << restoration->restoration_id(); } boost::optional ValidateRestoreAndGetSnapshot( RestorationState* restoration) REQUIRES(mutex_) { // Ignore if already completed. if (restoration->complete_time()) { return boost::none; } // If the restore is still undergoing the sys catalog phase. if (!restoration->IsSysCatalogRestorationDone()) { return boost::none; } // If the snapshot to restore is not ok. auto snapshot = FindSnapshot(restoration->snapshot_id()); if (!snapshot.ok()) { LOG(DFATAL) << ""Snapshot not found for pending restore with id "" << restoration->restoration_id(); return boost::none; } return *snapshot; } void SendPendingRestoreRpcs( const vector& postponed_restores, int64_t term) { for (const auto& restoration : postponed_restores) { LOG(INFO) << ""PITR: Issuing pending tserver RPCs for restoration "" << restoration.restoration_id; auto status = DoRestore(restoration.snapshot_id, restoration.restore_at, restoration.restoration_id, RestorePhase::kPostSysCatalogLoad, term, restoration.db_oid); LOG_IF(DFATAL, !status.ok()) << ""Failed to restore tablets for restoration "" << restoration.restoration_id << "": "" << status; } } std::optional ComputeDbOid(RestorationState* restoration) REQUIRES(mutex_) { std::optional db_oid; bool contains_sequences_data = false; for (const auto& id_and_type : restoration->MasterMetadata()) { if (id_and_type.second == SysRowEntryType::NAMESPACE && id_and_type.first == kPgSequencesDataNamespaceId) { contains_sequences_data = true; } } if (contains_sequences_data) { for (const auto& id_and_type : restoration->MasterMetadata()) { if (id_and_type.second == SysRowEntryType::NAMESPACE && id_and_type.first != kPgSequencesDataNamespaceId) { auto db_oid_res = GetPgsqlDatabaseOid(id_and_type.first); LOG_IF(DFATAL, !db_oid_res.ok()) << ""Unable to obtain db_oid for namespace id "" << id_and_type.first << "": "" << db_oid_res.status(); db_oid = static_cast(*db_oid_res); LOG(INFO) << ""DB OID of restoring database "" << *db_oid; // TODO(Sanket): In future can enhance to pass a list of db_oids. break; } } LOG_IF(DFATAL, !db_oid) << ""Unable to fetch db oid for the restoring database""; } return db_oid; } void SysCatalogLoaded(int64_t term) { if (term == OpId::kUnknownTerm) { // Do nothing on follower. return; } // Issue pending restoration rpcs. vector postponed_restores; { std::lock_guard lock(mutex_); // TODO(pitr) cancel restorations. for (const auto& restoration : restorations_) { auto snapshot = ValidateRestoreAndGetSnapshot(restoration.get()); if (!snapshot) { continue; } // If it is PITR restore, then verify restoration and add to the queue for rpcs. if (!restoration->schedule_id().IsNil()) { VerifyRestoration(restoration.get()); auto db_oid = ComputeDbOid(restoration.get()); postponed_restores.push_back(RestorationData { .snapshot_id = restoration->snapshot_id(), .restoration_id = restoration->restoration_id(), .restore_at = restoration->restore_at(), .db_oid = db_oid, }); } // Set the throttling limits. restoration->Throttler().RefreshLimit( GetRpcLimit(FLAGS_max_concurrent_restoration_rpcs, FLAGS_max_concurrent_restoration_rpcs_per_tserver, term)); // Set the current term so that the snapshot coordinator can pick it up. restoration->SetLeaderTerm(term); } } SendPendingRestoreRpcs(postponed_restores, term); } Result MakeSnapshotSchedulesToObjectIdsMap( SysRowEntryType type) { std::vector> schedules; { std::lock_guard lock(mutex_); for (const auto& schedule : schedules_) { if (!schedule->deleted()) { schedules.emplace_back(schedule->id(), schedule->options().filter()); } } } SnapshotSchedulesToObjectIdsMap result; for (const auto& id_and_filter : schedules) { auto entries = VERIFY_RESULT(CollectEntries(id_and_filter.second)); auto& ids = result[id_and_filter.first]; for (const auto& entry : entries.entries()) { if (entry.type() == type) { ids.push_back(entry.id()); } } std::sort(ids.begin(), ids.end()); } return result; } Result IsTableCoveredBySomeSnapshotSchedule(const TableInfo& table_info) { auto lock = table_info.LockForRead(); { std::lock_guard l(mutex_); for (const auto& schedule : schedules_) { for (const auto& table_identifier : schedule->options().filter().tables().tables()) { if (VERIFY_RESULT(TableMatchesIdentifier(table_info.id(), lock->pb, table_identifier))) { return true; } } } } return false; } bool IsPitrActive() { std::lock_guard lock(mutex_); for (const auto& schedule : schedules_) { if (!schedule->deleted()) { return true; } } return false; } Result UpdateRestorationAndGetWritePair( SnapshotScheduleRestoration* restoration) { std::lock_guard lock(mutex_); RestorationState* restoration_ptr = VERIFY_RESULT(GetRestorationPtrOrNull(restoration->restoration_id)); // Won't be found on followers. if (!restoration_ptr) { LOG(INFO) << ""Constructing new restoration state for id "" << restoration->restoration_id; SnapshotState& snapshot = VERIFY_RESULT(FindSnapshot(restoration->snapshot_id)); if (!VERIFY_RESULT(snapshot.Complete())) { return STATUS(IllegalState, ""The snapshot state is not complete"", restoration->snapshot_id.ToString(), MasterError(MasterErrorPB::SNAPSHOT_IS_NOT_READY)); } auto restoration_state = std::make_unique( &context_, restoration->restoration_id, &snapshot, restoration->restore_at, IsSysCatalogRestored::kTrue, GetRpcLimit(FLAGS_max_concurrent_restoration_rpcs, FLAGS_max_concurrent_restoration_rpcs_per_tserver, restoration->term)); restoration_ptr = restorations_.emplace(std::move(restoration_state)).first->get(); } // Set the phase to post sys catalog restoration. restoration_ptr->SetSysCatalogRestored(IsSysCatalogRestored::kTrue); // Reset the tablet list since it could have changed from the time of snapshot // to restoration time. Also, set the metadata for verifying restoration // post sys catalog load. std::vector restore_tablets; for (const auto& id_and_type : restoration->non_system_objects_to_restore) { restoration_ptr->MutableMasterMetadata()->emplace(id_and_type.first, id_and_type.second); if (id_and_type.second == SysRowEntryType::TABLET) { restore_tablets.push_back(id_and_type.first); } } LOG(INFO) << ""PITR: "" << restoration->restoration_id << "", tablets to restore: "" << AsString(restore_tablets); restoration_ptr->InitTabletIds(restore_tablets); // Prepare write batch. docdb::KeyValuePairPB restore_kv; RETURN_NOT_OK(restoration_ptr->StoreToKeyValuePair(&restore_kv)); return restore_kv; } void Start() { { std::lock_guard lock(mutex_); last_restorations_update_ht_ = context_.Clock()->Now(); } poller_.Start(&context_.Scheduler(), FLAGS_snapshot_coordinator_poll_interval_ms * 1ms); } void Shutdown() { poller_.Shutdown(); } private: template Status LoadEntry(const Slice& id_slice, const Slice& data, Map* map) REQUIRES(mutex_) { VLOG(2) << __func__ << ""("" << id_slice.ToDebugString() << "", "" << data.ToDebugString() << "")""; auto id = Uuid::TryFullyDecode(id_slice); if (id.IsNil()) { return Status::OK(); } auto metadata = VERIFY_RESULT(pb_util::ParseFromSlice(data)); return LoadEntry(typename Map::key_type(id), metadata, map); } template Status LoadEntry( const typename Map::key_type& id, const Pb& data, Map* map) REQUIRES(mutex_) { VLOG(1) << __func__ << ""("" << id << "", "" << data.ShortDebugString() << "")""; auto new_entry = std::make_unique(&context_, id, data); auto it = map->find(id); if (it == map->end()) { map->emplace(std::move(new_entry)); } else if ((**it).ShouldUpdate(*new_entry)) { map->replace(it, std::move(new_entry)); } else { VLOG_WITH_FUNC(1) << ""Ignore because of version check, existing: "" << (**it).ToString() << "", loaded: "" << new_entry->ToString(); } return Status::OK(); } Result FindSnapshot(const TxnSnapshotId& snapshot_id) REQUIRES(mutex_) { auto it = snapshots_.find(snapshot_id); if (it == snapshots_.end()) { return STATUS(NotFound, ""Could not find snapshot"", snapshot_id.ToString(), MasterError(MasterErrorPB::SNAPSHOT_NOT_FOUND)); } return **it; } Result FindRestoration( const TxnSnapshotRestorationId& restoration_id) REQUIRES(mutex_) { auto it = restorations_.find(restoration_id); if (it == restorations_.end()) { return STATUS(NotFound, ""Could not find restoration"", restoration_id.ToString(), MasterError(MasterErrorPB::OBJECT_NOT_FOUND)); } return **it; } Result GetRestorationPtrOrNull( const TxnSnapshotRestorationId& restoration_id) REQUIRES(mutex_) { auto restoration_result = FindRestoration(restoration_id); if (!restoration_result.ok() && restoration_result.status().IsNotFound()) { return nullptr; } RETURN_NOT_OK(restoration_result); return &*restoration_result; } Result FindSnapshotSchedule( const SnapshotScheduleId& id) REQUIRES(mutex_) { auto it = schedules_.find(id); if (it == schedules_.end()) { return STATUS(NotFound, ""Could not find snapshot schedule"", id.ToString(), MasterError(MasterErrorPB::SNAPSHOT_NOT_FOUND)); } return **it; } void ExecuteOperations(const TabletSnapshotOperations& operations, int64_t leader_term) { if (operations.empty()) { return; } VLOG(4) << __func__ << ""("" << AsString(operations) << "")""; size_t num_operations = operations.size(); LOG(INFO) << ""Number of snapshot operations to be executed "" << num_operations; std::vector tablet_ids; tablet_ids.reserve(num_operations); for (const auto& operation : operations) { tablet_ids.push_back(operation.tablet_id); } auto tablet_infos = context_.GetTabletInfos(tablet_ids); for (size_t i = 0; i != num_operations; ++i) { ExecuteOperation(operations[i], tablet_infos[i], leader_term); } } void ExecuteOperation( const TabletSnapshotOperation& operation, const TabletInfoPtr& tablet_info, int64_t leader_term) { auto callback = MakeDoneCallback( &mutex_, snapshots_, operation.snapshot_id, operation.tablet_id, std::bind(&Impl::UpdateSnapshot, this, _1, leader_term, _2)); if (!tablet_info) { callback(STATUS_EC_FORMAT(NotFound, MasterError(MasterErrorPB::TABLET_NOT_RUNNING), ""Tablet info not found for $0"", operation.tablet_id)); return; } auto snapshot_id_str = operation.snapshot_id.AsSlice().ToBuffer(); if (operation.state == SysSnapshotEntryPB::DELETING) { auto task = context_.CreateAsyncTabletSnapshotOp( tablet_info, snapshot_id_str, tserver::TabletSnapshotOpRequestPB::DELETE_ON_TABLET, callback); context_.ScheduleTabletSnapshotOp(task); } else if (operation.state == SysSnapshotEntryPB::CREATING) { auto task = context_.CreateAsyncTabletSnapshotOp( tablet_info, snapshot_id_str, tserver::TabletSnapshotOpRequestPB::CREATE_ON_TABLET, callback); task->SetSnapshotScheduleId(operation.schedule_id); task->SetSnapshotHybridTime(operation.snapshot_hybrid_time); context_.ScheduleTabletSnapshotOp(task); } else { LOG(DFATAL) << ""Unsupported snapshot operation: "" << operation.ToString(); } } void ExecuteRestoreOperations( const TabletRestoreOperations& operations, int64_t leader_term) { if (operations.empty()) { return; } size_t num_operations = operations.size(); LOG(INFO) << ""Number of tablet restore operations to be executed "" << num_operations; std::vector tablet_ids; tablet_ids.reserve(num_operations); for (const auto& operation : operations) { tablet_ids.push_back(operation.tablet_id); } auto tablet_infos = context_.GetTabletInfos(tablet_ids); for (size_t i = 0; i != num_operations; ++i) { ExecuteRestoreOperation( operations[i], tablet_infos[i], leader_term); } } void ExecuteRestoreOperation( const TabletRestoreOperation& operation, const TabletInfoPtr& tablet_info, int64_t leader_term) { auto snapshot_id_str = operation.snapshot_id.AsSlice().ToBuffer(); // If this tablet did not participate in snapshot, i.e. was deleted. // We just change hybrid hybrid time limit and clear hide state. auto task = context_.CreateAsyncTabletSnapshotOp( tablet_info, operation.is_tablet_part_of_snapshot ? snapshot_id_str : std::string(), tserver::TabletSnapshotOpRequestPB::RESTORE_ON_TABLET, MakeDoneCallback(&mutex_, restorations_, operation.restoration_id, operation.tablet_id, std::bind(&Impl::FinishRestoration, this, _1, leader_term))); task->SetSnapshotHybridTime(operation.restore_at); task->SetRestorationId(operation.restoration_id); if (operation.sys_catalog_restore_needed) { task->SetMetadata(tablet_info->table()->LockForRead()->pb); } // For sequences_data_table, we should set partial restore and db_oid. if (tablet_info->table()->id() == kPgSequencesDataTableId) { LOG_IF(DFATAL, !operation.db_oid) << ""DB OID not found for restoring database""; task->SetDbOid(*operation.db_oid); } context_.ScheduleTabletSnapshotOp(task); } struct PollSchedulesData { std::vector delete_snapshots; SnapshotScheduleOperations schedule_operations; ScheduleMinRestoreTime schedule_min_restore_time; }; void Poll() { auto leader_term = context_.LeaderTerm(); if (leader_term < 0) { return; } SCOPED_LEADER_SHARED_LOCK(l, cm_); if (!l.catalog_status().ok() || !l.leader_status().ok()) { return; } VLOG(4) << __func__ << ""()""; std::vector cleanup_snapshots; TabletSnapshotOperations operations; TabletRestoreOperations restore_operations; PollSchedulesData schedules_data; { std::lock_guard lock(mutex_); for (const auto& p : snapshots_) { if (p->NeedCleanup()) { LOG(INFO) << ""Cleanup of snapshot "" << p->id() << "" started.""; if (!p->CleanupTracker().Start().ok()) { LOG(DFATAL) << ""Cleanup of snapshot "" << p->id() << "" was already started.""; } cleanup_snapshots.push_back(p->id()); } else { // Refresh the throttle limit. p->Throttler().RefreshLimit( GetRpcLimit(FLAGS_max_concurrent_snapshot_rpcs, FLAGS_max_concurrent_snapshot_rpcs_per_tserver, leader_term)); p->PrepareOperations(&operations); } } PollSchedulesPrepare(&schedules_data); for (const auto& r : restorations_) { auto snapshot = ValidateRestoreAndGetSnapshot(r.get()); if (!snapshot || r->GetLeaderTerm() != leader_term) { continue; } r->Throttler().RefreshLimit( GetRpcLimit(FLAGS_max_concurrent_restoration_rpcs, FLAGS_max_concurrent_restoration_rpcs_per_tserver, leader_term)); auto tablets = (*snapshot).tablet_ids(); std::unordered_set tablets_snapshot(tablets.begin(), tablets.end()); std::optional db_oid = std::nullopt; if (!snapshot->schedule_id().IsNil()) { db_oid = ComputeDbOid(r.get()); } r->PrepareOperations(&restore_operations, tablets_snapshot, db_oid); } } for (const auto& id : cleanup_snapshots) { CleanupObject(leader_term, id, snapshots_, EncodedSnapshotKey(id, &context_)); } ExecuteOperations(operations, leader_term); PollSchedulesComplete(schedules_data, leader_term); ExecuteRestoreOperations(restore_operations, leader_term); } void TryDeleteSnapshot(SnapshotState* snapshot, PollSchedulesData* data) { auto delete_status = snapshot->TryStartDelete(); if (!delete_status.ok()) { VLOG(1) << ""Unable to delete snapshot "" << snapshot->id() << ""/"" << snapshot->schedule_id() << "": "" << delete_status << "", state: "" << snapshot->ToString(); return; } VLOG(1) << ""Cleanup snapshot: "" << snapshot->id() << ""/"" << snapshot->schedule_id(); data->delete_snapshots.push_back(snapshot->id()); } void PollSchedulesPrepare(PollSchedulesData* data) REQUIRES(mutex_) { auto now = context_.Clock()->Now(); for (const auto& p : schedules_) { HybridTime last_snapshot_time; if (p->deleted()) { auto range = snapshots_.get().equal_range(p->id()); for (const auto& snapshot : boost::make_iterator_range(range.first, range.second)) { TryDeleteSnapshot(snapshot.get(), data); } } else { auto& index = snapshots_.get(); auto range = index.equal_range(p->id()); if (range.first != range.second) { --range.second; for (; range.first != range.second; ++range.first) { if ((**range.first).initial_state() != SysSnapshotEntryPB::DELETING) { break; } } auto& first_snapshot = **range.first; data->schedule_min_restore_time[p->id()] = first_snapshot.previous_snapshot_hybrid_time() ? first_snapshot.previous_snapshot_hybrid_time() : first_snapshot.snapshot_hybrid_time(); auto gc_limit = now.AddSeconds(-p->options().retention_duration_sec()); VLOG_WITH_FUNC(4) << ""Gc limit: "" << gc_limit; for (; range.first != range.second; ++range.first) { if ((**range.first).snapshot_hybrid_time() >= gc_limit) { break; } TryDeleteSnapshot(range.first->get(), data); } last_snapshot_time = (**range.second).snapshot_hybrid_time(); } } p->PrepareOperations(last_snapshot_time, now, &data->schedule_operations); } } void PollSchedulesComplete(const PollSchedulesData& data, int64_t leader_term) EXCLUDES(mutex_) { for (const auto& id : data.delete_snapshots) { SubmitDelete(id, leader_term, nullptr); } for (const auto& operation : data.schedule_operations) { switch (operation.type) { case SnapshotScheduleOperationType::kCreateSnapshot: WARN_NOT_OK(ExecuteScheduleOperation(operation, leader_term), Format(""Failed to execute operation on $0"", operation.schedule_id)); break; case SnapshotScheduleOperationType::kCleanup: CleanupObject( leader_term, operation.schedule_id, schedules_, SnapshotScheduleState::EncodedKey(operation.schedule_id, &context_)); break; default: LOG(DFATAL) << ""Unexpected operation type: "" << operation.type; break; } } context_.CleanupHiddenObjects(data.schedule_min_restore_time); } SnapshotState* BoundingSnapshot(const SnapshotScheduleId& schedule_id, Bound bound) REQUIRES(mutex_) { auto& index = snapshots_.get(); decltype(index.begin()) it; if (bound == Bound::kFirst) { it = index.lower_bound(schedule_id); if (it == index.end()) { return nullptr; } } else { it = index.upper_bound(schedule_id); if (it == index.begin()) { return nullptr; } --it; } return (**it).schedule_id() == schedule_id ? it->get() : nullptr; } HybridTime LastSnapshotTime(const SnapshotScheduleId& schedule_id) REQUIRES(mutex_) { auto snapshot = BoundingSnapshot(schedule_id, Bound::kLast); return snapshot ? snapshot->snapshot_hybrid_time() : HybridTime::kInvalid; } template void CleanupObjectAborted(Id id, const Map& map) { LOG(INFO) << ""Aborting cleanup of object "" << id; std::lock_guard l(mutex_); auto it = map.find(id); if (it == map.end()) { return; } (**it).CleanupTracker().Abort(); } template void CleanupObject(int64_t leader_term, Id id, const Map& map, const Result& encoded_key) { if (!encoded_key.ok()) { LOG(DFATAL) << ""Failed to encode id for deletion: "" << encoded_key.status(); return; } auto query = std::make_unique( leader_term, CoarseMonoClock::Now() + FLAGS_sys_catalog_write_timeout_ms * 1ms, nullptr /* context */, nullptr /* tablet */); auto* write_batch = query->operation().AllocateRequest()->mutable_write_batch(); auto pair = write_batch->add_write_pairs(); pair->set_key((*encoded_key).AsSlice().cdata(), (*encoded_key).size()); char value = { docdb::ValueEntryTypeAsChar::kTombstone }; pair->set_value(&value, 1); query->set_callback([this, id, &map](const Status& s) { if (s.ok()) { LOG(INFO) << ""Finished cleanup of object "" << id; return; } CleanupObjectAborted(id, map); }); context_.Submit(query.release()->PrepareSubmit(), leader_term); } Status ExecuteScheduleOperation( const SnapshotScheduleOperation& operation, int64_t leader_term, const std::weak_ptr& synchronizer = std::weak_ptr()) { auto entries = CollectEntries(operation.filter); VLOG(2) << __func__ << ""("" << AsString(operation) << "", "" << leader_term << ""), entries: "" << AsString(entries); if (!entries.ok()) { CreateSnapshotAborted(entries.status(), operation.schedule_id, operation.snapshot_id); return entries.status(); } SubmitCreate( *entries, /* imported= */ false, operation.schedule_id, operation.previous_snapshot_hybrid_time, operation.snapshot_id, leader_term, [this, schedule_id = operation.schedule_id, snapshot_id = operation.snapshot_id, synchronizer]( const Status& status) { if (!status.ok()) { CreateSnapshotAborted(status, schedule_id, snapshot_id); } auto locked_synchronizer = synchronizer.lock(); if (locked_synchronizer) { locked_synchronizer->StatusCB(status); } }); return Status::OK(); } void CreateSnapshotAborted( const Status& status, const SnapshotScheduleId& schedule_id, const TxnSnapshotId& snapshot_id) { LOG(INFO) << __func__ << "" for "" << schedule_id << "", snapshot: "" << snapshot_id << "", status: "" << status; std::lock_guard lock(mutex_); auto it = schedules_.find(schedule_id); if (it == schedules_.end()) { return; } (**it).SnapshotFinished(snapshot_id, status); } void SubmitCreate( const SysRowEntries& entries, bool imported, const SnapshotScheduleId& schedule_id, HybridTime previous_snapshot_hybrid_time, TxnSnapshotId snapshot_id, int64_t leader_term, tablet::OperationCompletionCallback completion_clbk) { auto operation = std::make_unique(/* tablet= */ nullptr); auto request = operation->AllocateRequest(); VLOG(1) << __func__ << ""("" << AsString(entries) << "", "" << imported << "", "" << schedule_id << "", "" << snapshot_id << "")""; // There could be more than one entry of the same tablet, // for instance in the case of colocated tables. std::unordered_set unique_tablet_ids; for (const auto& entry : entries.entries()) { if (entry.type() == SysRowEntryType::TABLET) { if (unique_tablet_ids.insert(entry.id()).second) { VLOG(1) << __func__ << ""(Adding tablet "" << entry.id() << "" for snapshot "" << snapshot_id << "")""; request->add_tablet_id(entry.id()); } } } request->set_snapshot_hybrid_time(context_.Clock()->MaxGlobalNow().ToUint64()); request->set_operation(tserver::TabletSnapshotOpRequestPB::CREATE_ON_MASTER); request->set_snapshot_id(snapshot_id.data(), snapshot_id.size()); request->set_imported(imported); if (schedule_id) { request->set_schedule_id(schedule_id.data(), schedule_id.size()); } if (previous_snapshot_hybrid_time) { request->set_previous_snapshot_hybrid_time(previous_snapshot_hybrid_time.ToUint64()); } request->mutable_extra_data()->PackFrom(entries); operation->set_completion_callback(std::move(completion_clbk)); context_.Submit(std::move(operation), leader_term); } void SubmitDelete(const TxnSnapshotId& snapshot_id, int64_t leader_term, const std::shared_ptr& synchronizer) { auto operation = std::make_unique(nullptr); auto request = operation->AllocateRequest(); request->set_operation(tserver::TabletSnapshotOpRequestPB::DELETE_ON_MASTER); request->set_snapshot_id(snapshot_id.data(), snapshot_id.size()); operation->set_completion_callback( [this, wsynchronizer = std::weak_ptr(synchronizer), snapshot_id] (const Status& status) { auto synchronizer = wsynchronizer.lock(); if (synchronizer) { synchronizer->StatusCB(status); } if (!status.ok()) { DeleteSnapshotAborted(status, snapshot_id); } }); context_.Submit(std::move(operation), leader_term); } Status SubmitRestore( const TxnSnapshotId& snapshot_id, HybridTime restore_at, const TxnSnapshotRestorationId& restoration_id, int64_t leader_term) { auto synchronizer = std::make_shared(); auto operation = std::make_unique(nullptr); auto request = operation->AllocateRequest(); request->set_operation(tserver::TabletSnapshotOpRequestPB::RESTORE_SYS_CATALOG); request->set_snapshot_id(snapshot_id.data(), snapshot_id.size()); request->set_snapshot_hybrid_time(restore_at.ToUint64()); if (restoration_id) { request->set_restoration_id(restoration_id.data(), restoration_id.size()); } operation->set_completion_callback( tablet::MakeWeakSynchronizerOperationCompletionCallback(synchronizer)); context_.Submit(std::move(operation), leader_term); return synchronizer->Wait(); } void DeleteSnapshotAborted( const Status& status, const TxnSnapshotId& snapshot_id) { LOG(INFO) << __func__ << "", snapshot: "" << snapshot_id << "", status: "" << status; std::lock_guard lock(mutex_); auto it = snapshots_.find(snapshot_id); if (it == snapshots_.end()) { return; } (**it).DeleteAborted(status); } void UpdateSnapshot( SnapshotState* snapshot, int64_t leader_term, std::unique_lock* lock) REQUIRES(mutex_) { bool batch_done = false; bool is_empty = snapshot->Empty(); if (!is_empty) { batch_done = snapshot->Throttler().RemoveOutstandingTask(); } if (!snapshot->AllTabletsDone()) { if (FLAGS_schedule_snapshot_rpcs_out_of_band && batch_done && !is_empty) { // Send another batch. This prevents having to wait for the regular cycle // of master snapshot coordinator which can be too slow. context_.Scheduler().io_service().post([this]() { LOG(INFO) << ""Rescheduling Snapshot RPCs out of band.""; Poll(); }); } return; } if (snapshot->schedule_id()) { UpdateSchedule(*snapshot); } docdb::KeyValueWriteBatchPB write_batch; auto status = snapshot->StoreToWriteBatch(&write_batch); if (!status.ok()) { LOG(DFATAL) << ""Failed to prepare write batch for snapshot: "" << status; return; } lock->unlock(); SubmitWrite(std::move(write_batch), leader_term, &context_); }; void FinishRestoration(RestorationState* restoration, int64_t leader_term) REQUIRES(mutex_) { bool tablet_list_empty = restoration->Empty(); if (!tablet_list_empty) { bool batch_done = restoration->Throttler().RemoveOutstandingTask(); if (!restoration->AllTabletsDone()) { if (FLAGS_schedule_restoration_rpcs_out_of_band && batch_done) { // Send another batch. This prevents having to wait for the regular cycle // of master snapshot coordinator which can be too slow. context_.Scheduler().io_service().post([this]() { LOG(INFO) << ""Rescheduling restoration RPCs out of band.""; Poll(); }); } return; } } last_restorations_update_ht_ = context_.Clock()->Now(); restoration->set_complete_time(last_restorations_update_ht_); LOG(INFO) << ""Setting restore complete time to "" << last_restorations_update_ht_; if (restoration->schedule_id()) { auto schedule = FindSnapshotSchedule(restoration->schedule_id()); if (schedule.ok()) { docdb::KeyValueWriteBatchPB write_batch; schedule->mutable_options().add_restoration_times( last_restorations_update_ht_.ToUint64()); Status s = schedule->StoreToWriteBatch(&write_batch); if (s.ok()) { SubmitWrite(std::move(write_batch), leader_term, &context_); } else { LOG(INFO) << ""Unable to prepare write batch for schedule "" << schedule->id(); } } else { LOG(INFO) << ""Snapshot Schedule with id "" << restoration->schedule_id() << "" not found""; } } if (FLAGS_TEST_skip_sending_restore_finished) { return; } auto temp_ids = restoration->tablet_ids(); std::vector tablet_ids(temp_ids.begin(), temp_ids.end()); auto tablets = context_.GetTabletInfos(tablet_ids); for (const auto& tablet : tablets) { auto task = context_.CreateAsyncTabletSnapshotOp( tablet, std::string(), tserver::TabletSnapshotOpRequestPB::RESTORE_FINISHED, /* callback= */ nullptr); task->SetRestorationId(restoration->restoration_id()); task->SetRestorationTime(restoration->complete_time()); context_.ScheduleTabletSnapshotOp(task); } // Update restoration entry to sys catalog. LOG(INFO) << ""Marking restoration "" << restoration->restoration_id() << "" as complete in sys catalog""; docdb::KeyValueWriteBatchPB write_batch; auto status = restoration->StoreToWriteBatch(&write_batch); if (!status.ok()) { LOG(DFATAL) << ""Failed to prepare write batch for snapshot: "" << status; return; } SubmitWrite(std::move(write_batch), leader_term, &context_); // Enable tablet splitting again. if (restoration->schedule_id()) { context_.EnableTabletSplitting(""PITR""); } } void UpdateSchedule(const SnapshotState& snapshot) REQUIRES(mutex_) { auto it = schedules_.find(snapshot.schedule_id()); if (it == schedules_.end()) { return; } auto state = snapshot.AggregatedState(); Status status; if (!state.ok()) { status = state.status(); } else { switch (*state) { case SysSnapshotEntryPB::COMPLETE: status = Status::OK(); break; case SysSnapshotEntryPB::FAILED: status = snapshot.AnyFailure(); break; case SysSnapshotEntryPB::DELETED: return; default: LOG(DFATAL) << ""Unexpected snapshot state: "" << *state << "" for "" << snapshot.id(); return; } } (**it).SnapshotFinished(snapshot.id(), status); } Status FillSchedule(const SnapshotScheduleState& schedule, SnapshotScheduleInfoPB* out) REQUIRES(mutex_) { RETURN_NOT_OK(schedule.ToPB(out)); const auto& index = snapshots_.get(); auto p = index.equal_range(boost::make_tuple(schedule.id())); for (auto i = p.first; i != p.second; ++i) { RETURN_NOT_OK((**i).ToPB(out->add_snapshots())); } return Status::OK(); } Result CollectEntries(const SnapshotScheduleFilterPB& filter) { return context_.CollectEntriesForSnapshot(filter.tables().tables()); } Status ConsecutiveRestoreCheck( const SnapshotState& snapshot, HybridTime restore_at, const TxnSnapshotRestorationId& restoration_id) REQUIRES(mutex_) { SnapshotScheduleState& schedule = VERIFY_RESULT(FindSnapshotSchedule(snapshot.schedule_id())); // Find the latest restore. HybridTime latest_restore_ht = HybridTime::kMin; for (const auto& restoration_ht : schedule.options().restoration_times()) { if (HybridTime::FromPB(restoration_ht) > latest_restore_ht) { latest_restore_ht = HybridTime::FromPB(restoration_ht); } } LOG(INFO) << ""Last successful restoration completed at "" << latest_restore_ht; if (restore_at <= latest_restore_ht) { LOG(INFO) << ""Restore with id "" << restoration_id << "" not supported "" << ""because it is consecutive. Attempting to restore to "" << restore_at << "" while last successful restoration completed at "" << latest_restore_ht; return STATUS_FORMAT(NotSupported, ""Cannot restore before the previous restoration time. "" ""A Restoration was performed at $0 and the requested "" ""restoration is for $1 which is before the last restoration."", latest_restore_ht, restore_at); } return Status::OK(); } Status SubmitRestoreWrite(RestorationState* restoration, int64_t leader_term) REQUIRES(mutex_) { LOG(INFO) << ""Writing restoration "" << restoration->restoration_id() << "" entry to sys catalog""; docdb::KeyValueWriteBatchPB write_batch; RETURN_NOT_OK(restoration->StoreToWriteBatch(&write_batch)); SubmitWrite(std::move(write_batch), leader_term, &context_); return Status::OK(); } Status DoRestore( const TxnSnapshotId& snapshot_id, HybridTime restore_at, const TxnSnapshotRestorationId& restoration_id, RestorePhase phase, int64_t leader_term, std::optional db_oid = std::nullopt) { TabletRestoreOperations operations; bool restore_sys_catalog; std::unordered_set snapshot_tablets; bool tablet_list_empty = false; { std::lock_guard lock(mutex_); SnapshotState& snapshot = VERIFY_RESULT(FindSnapshot(snapshot_id)); if (!VERIFY_RESULT(snapshot.Complete())) { return STATUS(IllegalState, ""The snapshot state is not complete"", snapshot_id.ToString(), MasterError(MasterErrorPB::SNAPSHOT_IS_NOT_READY)); } restore_sys_catalog = phase == RestorePhase::kInitial && !snapshot.schedule_id().IsNil(); if (!FLAGS_allow_consecutive_restore && restore_sys_catalog) { RETURN_NOT_OK(ConsecutiveRestoreCheck(snapshot, restore_at, restoration_id)); } // Get the restoration state. Construct if in initial phase. RestorationState* restoration_ptr; if (phase == RestorePhase::kInitial) { LOG(INFO) << ""Creating a new restoration entry with id "" << restoration_id; // We mark sys catalog restoration phase to be complete in case of restorations // from external backups where we don't need to restore the sys catalog. auto restoration = std::make_unique( &context_, restoration_id, &snapshot, restore_at, (snapshot.schedule_id().IsNil() ? IsSysCatalogRestored::kTrue : IsSysCatalogRestored::kFalse), GetRpcLimit(FLAGS_max_concurrent_restoration_rpcs, FLAGS_max_concurrent_restoration_rpcs_per_tserver, leader_term)); restoration_ptr = restorations_.emplace(std::move(restoration)).first->get(); last_restorations_update_ht_ = context_.Clock()->Now(); } else { restoration_ptr = &VERIFY_RESULT(FindRestoration(restoration_id)).get(); } if (!restore_sys_catalog) { // Persist and replicate restoration entry to the sys catalog. // This ensures that followers can continue RPCs if this leader fails. // For PITR restorations, it is persisted as part of RESTORE_SYS_CATALOG operation. if (phase == RestorePhase::kInitial) { // Update the current leader term so that snapshot coordinator can pick it up. restoration_ptr->SetLeaderTerm(leader_term); RETURN_NOT_OK(SubmitRestoreWrite(restoration_ptr, leader_term)); } tablet_list_empty = restoration_ptr->Empty(); auto tablet_ids = snapshot.tablet_ids(); snapshot_tablets.insert(tablet_ids.begin(), tablet_ids.end()); restoration_ptr->PrepareOperations(&operations, snapshot_tablets, db_oid); } } // If sys catalog is restored, then tablets data will be restored after that using postponed // restores. if (restore_sys_catalog) { return SubmitRestore(snapshot_id, restore_at, restoration_id, leader_term); } ExecuteRestoreOperations(operations, leader_term); // For empty tablet list, finish the restore. if (tablet_list_empty) { std::lock_guard lock(mutex_); RestorationState* restoration_ptr = &VERIFY_RESULT(FindRestoration(restoration_id)).get(); if (restoration_ptr) { FinishRestoration(restoration_ptr, leader_term); } } return Status::OK(); } // Computes the maximum outstanding Snapshot Create/Delete RPC // that is permitted. If total limit is specified then it is used otherwise // the value is computed by multiplying tserver count with the per tserver limit. uint64_t GetRpcLimit(int64_t total_limit, int64_t per_tserver_limit, int64_t leader_term) { // NO OP for followers. if (leader_term < 0) { return std::numeric_limits::max(); } // Should execute only for leaders. if (total_limit == 0) { return std::numeric_limits::max(); } if (total_limit > 0) { return total_limit; } auto num_result = context_.GetNumLiveTServersForActiveCluster(); // The cluster config could be empty for e.g. if a restore is in progress // or e.g. if a new master leader is elected. This is a temporary intermediate // state (we have bigger problems if the cluster config remains empty forever). // We use the limit set per tserver as the overall limit in such cases. if (!num_result.ok()) { LOG(INFO) << ""Cluster Config is not available. Using per tserver limit of "" << per_tserver_limit << "" as the throttled limit.""; return per_tserver_limit; } uint64_t num_tservers = *num_result; return num_tservers * per_tserver_limit; } SnapshotCoordinatorContext& context_; enterprise::CatalogManager* cm_; std::mutex mutex_; class ScheduleTag; using Snapshots = boost::multi_index_container< std::unique_ptr, boost::multi_index::indexed_by< // Access snapshots by id. boost::multi_index::hashed_unique< boost::multi_index::const_mem_fun< SnapshotState, const TxnSnapshotId&, &SnapshotState::id> >, // Group snapshots by schedule id. Ordered by hybrid time for the same schedule. boost::multi_index::ordered_non_unique< boost::multi_index::tag, boost::multi_index::composite_key< SnapshotState, boost::multi_index::const_mem_fun< SnapshotState, const SnapshotScheduleId&, &SnapshotState::schedule_id>, boost::multi_index::const_mem_fun< SnapshotState, HybridTime, &SnapshotState::snapshot_hybrid_time> > > > >; // For restorations and schedules we have to use multi_index since there are template // functions that expect same interface for those collections. using Restorations = boost::multi_index_container< std::unique_ptr, boost::multi_index::indexed_by< boost::multi_index::hashed_unique< boost::multi_index::const_mem_fun< RestorationState, const TxnSnapshotRestorationId&, &RestorationState::restoration_id> > > >; using Schedules = boost::multi_index_container< std::unique_ptr, boost::multi_index::indexed_by< boost::multi_index::hashed_unique< boost::multi_index::const_mem_fun< SnapshotScheduleState, const SnapshotScheduleId&, &SnapshotScheduleState::id> > > >; Snapshots snapshots_ GUARDED_BY(mutex_); Restorations restorations_ GUARDED_BY(mutex_); HybridTime last_restorations_update_ht_ GUARDED_BY(mutex_); Schedules schedules_ GUARDED_BY(mutex_); rpc::Poller poller_; }; MasterSnapshotCoordinator::MasterSnapshotCoordinator( SnapshotCoordinatorContext* context, enterprise::CatalogManager* cm) : impl_(new Impl(context, cm)) {} MasterSnapshotCoordinator::~MasterSnapshotCoordinator() {} Result MasterSnapshotCoordinator::Create( const SysRowEntries& entries, bool imported, int64_t leader_term, CoarseTimePoint deadline) { return impl_->Create(entries, imported, leader_term, deadline); } Status MasterSnapshotCoordinator::CreateReplicated( int64_t leader_term, const tablet::SnapshotOperation& operation) { return impl_->CreateReplicated(leader_term, operation); } Status MasterSnapshotCoordinator::DeleteReplicated( int64_t leader_term, const tablet::SnapshotOperation& operation) { return impl_->DeleteReplicated(leader_term, operation); } Status MasterSnapshotCoordinator::RestoreSysCatalogReplicated( int64_t leader_term, const tablet::SnapshotOperation& operation, Status* complete_status) { return impl_->RestoreSysCatalogReplicated(leader_term, operation, complete_status); } Status MasterSnapshotCoordinator::ListSnapshots( const TxnSnapshotId& snapshot_id, bool list_deleted, ListSnapshotsResponsePB* resp) { return impl_->ListSnapshots(snapshot_id, list_deleted, resp); } Status MasterSnapshotCoordinator::Delete( const TxnSnapshotId& snapshot_id, int64_t leader_term, CoarseTimePoint deadline) { return impl_->Delete(snapshot_id, leader_term, deadline); } Result MasterSnapshotCoordinator::Restore( const TxnSnapshotId& snapshot_id, HybridTime restore_at, int64_t leader_term) { return impl_->Restore(snapshot_id, restore_at, leader_term); } Status MasterSnapshotCoordinator::ListRestorations( const TxnSnapshotRestorationId& restoration_id, const TxnSnapshotId& snapshot_id, ListSnapshotRestorationsResponsePB* resp) { return impl_->ListRestorations(restoration_id, snapshot_id, resp); } Result MasterSnapshotCoordinator::CreateSchedule( const CreateSnapshotScheduleRequestPB& request, int64_t leader_term, CoarseTimePoint deadline) { return impl_->CreateSchedule(request, leader_term, deadline); } Status MasterSnapshotCoordinator::ListSnapshotSchedules( const SnapshotScheduleId& snapshot_schedule_id, ListSnapshotSchedulesResponsePB* resp) { return impl_->ListSnapshotSchedules(snapshot_schedule_id, resp); } Status MasterSnapshotCoordinator::DeleteSnapshotSchedule( const SnapshotScheduleId& snapshot_schedule_id, int64_t leader_term, CoarseTimePoint deadline) { return impl_->DeleteSnapshotSchedule(snapshot_schedule_id, leader_term, deadline); } Status MasterSnapshotCoordinator::Load(tablet::Tablet* tablet) { return impl_->Load(tablet); } void MasterSnapshotCoordinator::Start() { impl_->Start(); } void MasterSnapshotCoordinator::Shutdown() { impl_->Shutdown(); } Status MasterSnapshotCoordinator::ApplyWritePair(const Slice& key, const Slice& value) { return impl_->ApplyWritePair(key, value); } Status MasterSnapshotCoordinator::FillHeartbeatResponse(TSHeartbeatResponsePB* resp) { return impl_->FillHeartbeatResponse(resp); } Result MasterSnapshotCoordinator::MakeSnapshotSchedulesToObjectIdsMap(SysRowEntryType type) { return impl_->MakeSnapshotSchedulesToObjectIdsMap(type); } Result MasterSnapshotCoordinator::IsTableCoveredBySomeSnapshotSchedule( const TableInfo& table_info) { return impl_->IsTableCoveredBySomeSnapshotSchedule(table_info); } void MasterSnapshotCoordinator::SysCatalogLoaded(int64_t term) { impl_->SysCatalogLoaded(term); } Result MasterSnapshotCoordinator::CreateForSchedule( const SnapshotScheduleId& schedule_id, int64_t leader_term, CoarseTimePoint deadline) { return impl_->CreateForSchedule(schedule_id, leader_term, deadline); } Result MasterSnapshotCoordinator::UpdateRestorationAndGetWritePair( SnapshotScheduleRestoration* restoration) { return impl_->UpdateRestorationAndGetWritePair(restoration); } bool MasterSnapshotCoordinator::IsPitrActive() { return impl_->IsPitrActive(); } } // namespace master } // namespace yb ",16136,True,3512.6749119484425,median "[[amqp-component]] == AMQP Component *Available as of Camel version 1.2* The *amqp:* component supports the http://www.amqp.org/[AMQP 1.0 protocol] using the JMS Client API of the http://qpid.apache.org/[Qpid] project. In case you want to use AMQP 0.9 (in particular RabbitMQ) you might also be interested in the <> component. Please keep in mind that prior to the Camel 2.17.0 AMQP component supported AMQP 0.9 and above, however since Camel 2.17.0 it supports only AMQP 1.0. Maven users will need to add the following dependency to their `pom.xml` for this component: [source,xml] ------------------------------------------------------------------------------------------------ org.apache.camel camel-amqp ${camel.version} ------------------------------------------------------------------------------------------------ ### URI format [source,java] --------------------------------------------- amqp:[queue:|topic:]destinationName[?options] --------------------------------------------- ### AMQP Options You can specify all of the various configuration options of the link:../../../../camel-jms/src/main/docs/readme.html[JMS] component after the destination name. // component options: START The AMQP component supports 79 options which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *configuration* (advanced) | To use a shared JMS configuration | | JmsConfiguration | *acceptMessagesWhile Stopping* (consumer) | Specifies whether the consumer accept messages while it is stopping. You may consider enabling this option if you start and stop JMS routes at runtime while there are still messages enqueued on the queue. If this option is false and you stop the JMS route then messages may be rejected and the JMS broker would have to attempt redeliveries which yet again may be rejected and eventually the message may be moved at a dead letter queue on the JMS broker. To avoid this its recommended to enable this option. | false | boolean | *allowReplyManagerQuick Stop* (consumer) | Whether the DefaultMessageListenerContainer used in the reply managers for request-reply messaging allow the DefaultMessageListenerContainer.runningAllowed flag to quick stop in case JmsConfigurationisAcceptMessagesWhileStopping is enabled and org.apache.camel.CamelContext is currently being stopped. This quick stop ability is enabled by default in the regular JMS consumers but to enable for reply managers you must enable this flag. | false | boolean | *acknowledgementMode* (consumer) | The JMS acknowledgement mode defined as an Integer. Allows you to set vendor-specific extensions to the acknowledgment mode.For the regular modes it is preferable to use the acknowledgementModeName instead. | | int | *eagerLoadingOf Properties* (consumer) | Enables eager loading of JMS properties as soon as a message is loaded which generally is inefficient as the JMS properties may not be required but sometimes can catch early any issues with the underlying JMS provider and the use of JMS properties | false | boolean | *acknowledgementModeName* (consumer) | The JMS acknowledgement name which is one of: SESSION_TRANSACTED CLIENT_ACKNOWLEDGE AUTO_ACKNOWLEDGE DUPS_OK_ACKNOWLEDGE | AUTO_ ACKNOWLEDGE | String | *autoStartup* (consumer) | Specifies whether the consumer container should auto-startup. | true | boolean | *cacheLevel* (consumer) | Sets the cache level by ID for the underlying JMS resources. See cacheLevelName option for more details. | | int | *cacheLevelName* (consumer) | Sets the cache level by name for the underlying JMS resources. Possible values are: CACHE_AUTO CACHE_CONNECTION CACHE_CONSUMER CACHE_NONE and CACHE_SESSION. The default setting is CACHE_AUTO. See the Spring documentation and Transactions Cache Levels for more information. | CACHE_AUTO | String | *replyToCacheLevelName* (producer) | Sets the cache level by name for the reply consumer when doing request/reply over JMS. This option only applies when using fixed reply queues (not temporary). Camel will by default use: CACHE_CONSUMER for exclusive or shared w/ replyToSelectorName. And CACHE_SESSION for shared without replyToSelectorName. Some JMS brokers such as IBM WebSphere may require to set the replyToCacheLevelName=CACHE_NONE to work. Note: If using temporary queues then CACHE_NONE is not allowed and you must use a higher value such as CACHE_CONSUMER or CACHE_SESSION. | | String | *clientId* (common) | Sets the JMS client ID to use. Note that this value if specified must be unique and can only be used by a single JMS connection instance. It is typically only required for durable topic subscriptions. If using Apache ActiveMQ you may prefer to use Virtual Topics instead. | | String | *concurrentConsumers* (consumer) | Specifies the default number of concurrent consumers when consuming from JMS (not for request/reply over JMS). See also the maxMessagesPerTask option to control dynamic scaling up/down of threads. When doing request/reply over JMS then the option replyToConcurrentConsumers is used to control number of concurrent consumers on the reply message listener. | 1 | int | *replyToConcurrent Consumers* (producer) | Specifies the default number of concurrent consumers when doing request/reply over JMS. See also the maxMessagesPerTask option to control dynamic scaling up/down of threads. | 1 | int | *connectionFactory* (common) | The connection factory to be use. A connection factory must be configured either on the component or endpoint. | | ConnectionFactory | *username* (security) | Username to use with the ConnectionFactory. You can also configure username/password directly on the ConnectionFactory. | | String | *password* (security) | Password to use with the ConnectionFactory. You can also configure username/password directly on the ConnectionFactory. | | String | *deliveryPersistent* (producer) | Specifies whether persistent delivery is used by default. | true | boolean | *deliveryMode* (producer) | Specifies the delivery mode to be used. Possibles values are those defined by javax.jms.DeliveryMode. NON_PERSISTENT = 1 and PERSISTENT = 2. | | Integer | *durableSubscriptionName* (common) | The durable subscriber name for specifying durable topic subscriptions. The clientId option must be configured as well. | | String | *exceptionListener* (advanced) | Specifies the JMS Exception Listener that is to be notified of any underlying JMS exceptions. | | ExceptionListener | *errorHandler* (advanced) | Specifies a org.springframework.util.ErrorHandler to be invoked in case of any uncaught exceptions thrown while processing a Message. By default these exceptions will be logged at the WARN level if no errorHandler has been configured. You can configure logging level and whether stack traces should be logged using errorHandlerLoggingLevel and errorHandlerLogStackTrace options. This makes it much easier to configure than having to code a custom errorHandler. | | ErrorHandler | *errorHandlerLogging Level* (logging) | Allows to configure the default errorHandler logging level for logging uncaught exceptions. | WARN | LoggingLevel | *errorHandlerLogStack Trace* (logging) | Allows to control whether stacktraces should be logged or not by the default errorHandler. | true | boolean | *explicitQosEnabled* (producer) | Set if the deliveryMode priority or timeToLive qualities of service should be used when sending messages. This option is based on Spring's JmsTemplate. The deliveryMode priority and timeToLive options are applied to the current endpoint. This contrasts with the preserveMessageQos option which operates at message granularity reading QoS properties exclusively from the Camel In message headers. | false | boolean | *exposeListenerSession* (consumer) | Specifies whether the listener session should be exposed when consuming messages. | false | boolean | *idleTaskExecutionLimit* (advanced) | Specifies the limit for idle executions of a receive task not having received any message within its execution. If this limit is reached the task will shut down and leave receiving to other executing tasks (in the case of dynamic scheduling; see the maxConcurrentConsumers setting). There is additional doc available from Spring. | 1 | int | *idleConsumerLimit* (advanced) | Specify the limit for the number of consumers that are allowed to be idle at any given time. | 1 | int | *maxConcurrentConsumers* (consumer) | Specifies the maximum number of concurrent consumers when consuming from JMS (not for request/reply over JMS). See also the maxMessagesPerTask option to control dynamic scaling up/down of threads. When doing request/reply over JMS then the option replyToMaxConcurrentConsumers is used to control number of concurrent consumers on the reply message listener. | | int | *replyToMaxConcurrent Consumers* (producer) | Specifies the maximum number of concurrent consumers when using request/reply over JMS. See also the maxMessagesPerTask option to control dynamic scaling up/down of threads. | | int | *replyOnTimeoutToMax ConcurrentConsumers* (producer) | Specifies the maximum number of concurrent consumers for continue routing when timeout occurred when using request/reply over JMS. | 1 | int | *maxMessagesPerTask* (advanced) | The number of messages per task. -1 is unlimited. If you use a range for concurrent consumers (eg min max) then this option can be used to set a value to eg 100 to control how fast the consumers will shrink when less work is required. | -1 | int | *messageConverter* (advanced) | To use a custom Spring org.springframework.jms.support.converter.MessageConverter so you can be in control how to map to/from a javax.jms.Message. | | MessageConverter | *mapJmsMessage* (advanced) | Specifies whether Camel should auto map the received JMS message to a suited payload type such as javax.jms.TextMessage to a String etc. | true | boolean | *messageIdEnabled* (advanced) | When sending specifies whether message IDs should be added. This is just an hint to the JMS broker.If the JMS provider accepts this hint these messages must have the message ID set to null; if the provider ignores the hint the message ID must be set to its normal unique value | true | boolean | *messageTimestampEnabled* (advanced) | Specifies whether timestamps should be enabled by default on sending messages. This is just an hint to the JMS broker.If the JMS provider accepts this hint these messages must have the timestamp set to zero; if the provider ignores the hint the timestamp must be set to its normal value | true | boolean | *alwaysCopyMessage* (producer) | If true Camel will always make a JMS message copy of the message when it is passed to the producer for sending. Copying the message is needed in some situations such as when a replyToDestinationSelectorName is set (incidentally Camel will set the alwaysCopyMessage option to true if a replyToDestinationSelectorName is set) | false | boolean | *useMessageIDAs CorrelationID* (advanced) | Specifies whether JMSMessageID should always be used as JMSCorrelationID for InOut messages. | false | boolean | *priority* (producer) | Values greater than 1 specify the message priority when sending (where 0 is the lowest priority and 9 is the highest). The explicitQosEnabled option must also be enabled in order for this option to have any effect. | 4 | int | *pubSubNoLocal* (advanced) | Specifies whether to inhibit the delivery of messages published by its own connection. | false | boolean | *receiveTimeout* (advanced) | The timeout for receiving messages (in milliseconds). | 1000 | long | *recoveryInterval* (advanced) | Specifies the interval between recovery attempts i.e. when a connection is being refreshed in milliseconds. The default is 5000 ms that is 5 seconds. | 5000 | long | *taskExecutor* (consumer) | Allows you to specify a custom task executor for consuming messages. | | TaskExecutor | *timeToLive* (producer) | When sending messages specifies the time-to-live of the message (in milliseconds). | -1 | long | *transacted* (transaction) | Specifies whether to use transacted mode | false | boolean | *lazyCreateTransaction Manager* (transaction) | If true Camel will create a JmsTransactionManager if there is no transactionManager injected when option transacted=true. | true | boolean | *transactionManager* (transaction) | The Spring transaction manager to use. | | PlatformTransaction Manager | *transactionName* (transaction) | The name of the transaction to use. | | String | *transactionTimeout* (transaction) | The timeout value of the transaction (in seconds) if using transacted mode. | -1 | int | *testConnectionOn Startup* (common) | Specifies whether to test the connection on startup. This ensures that when Camel starts that all the JMS consumers have a valid connection to the JMS broker. If a connection cannot be granted then Camel throws an exception on startup. This ensures that Camel is not started with failed connections. The JMS producers is tested as well. | false | boolean | *asyncStartListener* (advanced) | Whether to startup the JmsConsumer message listener asynchronously when starting a route. For example if a JmsConsumer cannot get a connection to a remote JMS broker then it may block while retrying and/or failover. This will cause Camel to block while starting routes. By setting this option to true you will let routes startup while the JmsConsumer connects to the JMS broker using a dedicated thread in asynchronous mode. If this option is used then beware that if the connection could not be established then an exception is logged at WARN level and the consumer will not be able to receive messages; You can then restart the route to retry. | false | boolean | *asyncStopListener* (advanced) | Whether to stop the JmsConsumer message listener asynchronously when stopping a route. | false | boolean | *forceSendOriginal Message* (producer) | When using mapJmsMessage=false Camel will create a new JMS message to send to a new JMS destination if you touch the headers (get or set) during the route. Set this option to true to force Camel to send the original JMS message that was received. | false | boolean | *requestTimeout* (producer) | The timeout for waiting for a reply when using the InOut Exchange Pattern (in milliseconds). The default is 20 seconds. You can include the header CamelJmsRequestTimeout to override this endpoint configured timeout value and thus have per message individual timeout values. See also the requestTimeoutCheckerInterval option. | 20000 | long | *requestTimeoutChecker Interval* (advanced) | Configures how often Camel should check for timed out Exchanges when doing request/reply over JMS. By default Camel checks once per second. But if you must react faster when a timeout occurs then you can lower this interval to check more frequently. The timeout is determined by the option requestTimeout. | 1000 | long | *transferExchange* (advanced) | You can transfer the exchange over the wire instead of just the body and headers. 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. You must enable this option on both the producer and consumer side so Camel knows the payloads is an Exchange and not a regular payload. | false | boolean | *transferException* (advanced) | If enabled and you are using Request Reply messaging (InOut) and an Exchange failed on the consumer side then the caused Exception will be send back in response as a javax.jms.ObjectMessage. If the client is Camel the returned Exception is rethrown. This allows you to use Camel JMS as a bridge in your routing - for example using persistent queues to enable robust routing. Notice that if you also have transferExchange enabled this option takes precedence. The caught exception is required to be serializable. The original Exception on the consumer side can be wrapped in an outer exception such as org.apache.camel.RuntimeCamelException when returned to the producer. | false | boolean | *transferFault* (advanced) | If enabled and you are using Request Reply messaging (InOut) and an Exchange failed with a SOAP fault (not exception) on the consumer side then the fault flag on MessageisFault() will be send back in the response as a JMS header with the key org.apache.camel.component.jms.JmsConstantsJMS_TRANSFER_FAULTJMS_TRANSFER_FAULT. If the client is Camel the returned fault flag will be set on the link org.apache.camel.MessagesetFault(boolean). You may want to enable this when using Camel components that support faults such as SOAP based such as cxf or spring-ws. | false | boolean | *jmsOperations* (advanced) | Allows you to use your own implementation of the org.springframework.jms.core.JmsOperations interface. Camel uses JmsTemplate as default. Can be used for testing purpose but not used much as stated in the spring API docs. | | JmsOperations | *destinationResolver* (advanced) | A pluggable org.springframework.jms.support.destination.DestinationResolver that allows you to use your own resolver (for example to lookup the real destination in a JNDI registry). | | DestinationResolver | *replyToType* (producer) | Allows for explicitly specifying which kind of strategy to use for replyTo queues when doing request/reply over JMS. Possible values are: Temporary Shared or Exclusive. By default Camel will use temporary queues. However if replyTo has been configured then Shared is used by default. This option allows you to use exclusive queues instead of shared ones. See Camel JMS documentation for more details and especially the notes about the implications if running in a clustered environment and the fact that Shared reply queues has lower performance than its alternatives Temporary and Exclusive. | | ReplyToType | *preserveMessageQos* (producer) | Set to true if you want to send message using the QoS settings specified on the message instead of the QoS settings on the JMS endpoint. The following three headers are considered JMSPriority JMSDeliveryMode and JMSExpiration. You can provide all or only some of them. If not provided Camel will fall back to use the values from the endpoint instead. So when using this option the headers override the values from the endpoint. The explicitQosEnabled option by contrast will only use options set on the endpoint and not values from the message header. | false | boolean | *asyncConsumer* (consumer) | Whether the JmsConsumer processes the Exchange asynchronously. If enabled then the JmsConsumer may pickup the next message from the JMS queue while the previous message is being processed asynchronously (by the Asynchronous Routing Engine). This means that messages may be processed not 100 strictly in order. If disabled (as default) then the Exchange is fully processed before the JmsConsumer will pickup the next message from the JMS queue. Note if transacted has been enabled then asyncConsumer=true does not run asynchronously as transaction must be executed synchronously (Camel 3.0 may support async transactions). | false | boolean | *allowNullBody* (producer) | Whether to allow sending messages with no body. If this option is false and the message body is null then an JMSException is thrown. | true | boolean | *includeSentJMS MessageID* (producer) | Only applicable when sending to JMS destination using InOnly (eg fire and forget). Enabling this option will enrich the Camel Exchange with the actual JMSMessageID that was used by the JMS client when the message was sent to the JMS destination. | false | boolean | *includeAllJMSX Properties* (advanced) | Whether to include all JMSXxxx properties when mapping from JMS to Camel Message. Setting this to true will include properties such as JMSXAppID and JMSXUserID etc. Note: If you are using a custom headerFilterStrategy then this option does not apply. | false | boolean | *defaultTaskExecutor Type* (consumer) | Specifies what default TaskExecutor type to use in the DefaultMessageListenerContainer for both consumer endpoints and the ReplyTo consumer of producer endpoints. Possible values: SimpleAsync (uses Spring's SimpleAsyncTaskExecutor) or ThreadPool (uses Spring's ThreadPoolTaskExecutor with optimal values - cached threadpool-like). If not set it defaults to the previous behaviour which uses a cached thread pool for consumer endpoints and SimpleAsync for reply consumers. The use of ThreadPool is recommended to reduce thread trash in elastic configurations with dynamically increasing and decreasing concurrent consumers. | | DefaultTaskExecutor Type | *jmsKeyFormatStrategy* (advanced) | Pluggable strategy for encoding and decoding JMS keys so they can be compliant with the JMS specification. Camel provides two implementations out of the box: default and passthrough. The default strategy will safely marshal dots and hyphens (. and -). The passthrough strategy leaves the key as is. Can be used for JMS brokers which do not care whether JMS header keys contain illegal characters. You can provide your own implementation of the org.apache.camel.component.jms.JmsKeyFormatStrategy and refer to it using the notation. | | JmsKeyFormatStrategy | *allowAdditionalHeaders* (producer) | This option is used to allow additional headers which may have values that are invalid according to JMS specification. For example some message systems such as WMQ do this with header names using prefix JMS_IBM_MQMD_ containing values with byte array or other invalid types. You can specify multiple header names separated by comma and use as suffix for wildcard matching. | | String | *queueBrowseStrategy* (advanced) | To use a custom QueueBrowseStrategy when browsing queues | | QueueBrowseStrategy | *messageCreatedStrategy* (advanced) | To use the given MessageCreatedStrategy which are invoked when Camel creates new instances of javax.jms.Message objects when Camel is sending a JMS message. | | MessageCreatedStrategy | *waitForProvision CorrelationToBeUpdated Counter* (advanced) | Number of times to wait for provisional correlation id to be updated to the actual correlation id when doing request/reply over JMS and when the option useMessageIDAsCorrelationID is enabled. | 50 | int | *waitForProvision CorrelationToBeUpdated ThreadSleepingTime* (advanced) | Interval in millis to sleep each time while waiting for provisional correlation id to be updated. | 100 | long | *correlationProperty* (producer) | Use this JMS property to correlate messages in InOut exchange pattern (request-reply) instead of JMSCorrelationID property. This allows you to exchange messages with systems that do not correlate messages using JMSCorrelationID JMS property. If used JMSCorrelationID will not be used or set by Camel. The value of here named property will be generated if not supplied in the header of the message under the same name. | | String | *subscriptionDurable* (consumer) | Set whether to make the subscription durable. The durable subscription name to be used can be specified through the subscriptionName property. Default is false. Set this to true to register a durable subscription typically in combination with a subscriptionName value (unless your message listener class name is good enough as subscription name). Only makes sense when listening to a topic (pub-sub domain) therefore this method switches the pubSubDomain flag as well. | false | boolean | *subscriptionShared* (consumer) | Set whether to make the subscription shared. The shared subscription name to be used can be specified through the subscriptionName property. Default is false. Set this to true to register a shared subscription typically in combination with a subscriptionName value (unless your message listener class name is good enough as subscription name). Note that shared subscriptions may also be durable so this flag can (and often will) be combined with subscriptionDurable as well. Only makes sense when listening to a topic (pub-sub domain) therefore this method switches the pubSubDomain flag as well. Requires a JMS 2.0 compatible message broker. | false | boolean | *subscriptionName* (consumer) | Set the name of a subscription to create. To be applied in case of a topic (pub-sub domain) with a shared or durable subscription. The subscription name needs to be unique within this client's JMS client id. Default is the class name of the specified message listener. Note: Only 1 concurrent consumer (which is the default of this message listener container) is allowed for each subscription except for a shared subscription (which requires JMS 2.0). | | String | *streamMessageType Enabled* (producer) | Sets whether StreamMessage type is enabled or not. Message payloads of streaming kind such as files InputStream etc will either by sent as BytesMessage or StreamMessage. This option controls which kind will be used. By default BytesMessage is used which enforces the entire message payload to be read into memory. By enabling this option the message payload is read into memory in chunks and each chunk is then written to the StreamMessage until no more data. | false | boolean | *headerFilterStrategy* (filter) | To use a custom org.apache.camel.spi.HeaderFilterStrategy to filter header to and from Camel message. | | HeaderFilterStrategy | *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 AMQP endpoint is configured using URI syntax: ---- amqp:destinationType:destinationName ---- with the following path and query parameters: ==== Path Parameters (2 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *destinationType* | The kind of destination to use | queue | String | *destinationName* | *Required* Name of the queue or topic to use as destination | | String |=== ==== Query Parameters (90 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *clientId* (common) | Sets the JMS client ID to use. Note that this value if specified must be unique and can only be used by a single JMS connection instance. It is typically only required for durable topic subscriptions. If using Apache ActiveMQ you may prefer to use Virtual Topics instead. | | String | *connectionFactory* (common) | The connection factory to be use. A connection factory must be configured either on the component or endpoint. | | ConnectionFactory | *disableReplyTo* (common) | Specifies whether Camel ignores the JMSReplyTo header in messages. If true Camel does not send a reply back to the destination specified in the JMSReplyTo header. You can use this option if you want Camel to consume from a route and you do not want Camel to automatically send back a reply message because another component in your code handles the reply message. You can also use this option if you want to use Camel as a proxy between different message brokers and you want to route message from one system to another. | false | boolean | *durableSubscriptionName* (common) | The durable subscriber name for specifying durable topic subscriptions. The clientId option must be configured as well. | | String | *jmsMessageType* (common) | Allows you to force the use of a specific javax.jms.Message implementation for sending JMS messages. Possible values are: Bytes Map Object Stream Text. By default Camel would determine which JMS message type to use from the In body type. This option allows you to specify it. | | JmsMessageType | *testConnectionOnStartup* (common) | Specifies whether to test the connection on startup. This ensures that when Camel starts that all the JMS consumers have a valid connection to the JMS broker. If a connection cannot be granted then Camel throws an exception on startup. This ensures that Camel is not started with failed connections. The JMS producers is tested as well. | false | boolean | *acknowledgementModeName* (consumer) | The JMS acknowledgement name which is one of: SESSION_TRANSACTED CLIENT_ACKNOWLEDGE AUTO_ACKNOWLEDGE DUPS_OK_ACKNOWLEDGE | AUTO_ ACKNOWLEDGE | String | *asyncConsumer* (consumer) | Whether the JmsConsumer processes the Exchange asynchronously. If enabled then the JmsConsumer may pickup the next message from the JMS queue while the previous message is being processed asynchronously (by the Asynchronous Routing Engine). This means that messages may be processed not 100 strictly in order. If disabled (as default) then the Exchange is fully processed before the JmsConsumer will pickup the next message from the JMS queue. Note if transacted has been enabled then asyncConsumer=true does not run asynchronously as transaction must be executed synchronously (Camel 3.0 may support async transactions). | false | boolean | *autoStartup* (consumer) | Specifies whether the consumer container should auto-startup. | 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 | *cacheLevel* (consumer) | Sets the cache level by ID for the underlying JMS resources. See cacheLevelName option for more details. | | int | *cacheLevelName* (consumer) | Sets the cache level by name for the underlying JMS resources. Possible values are: CACHE_AUTO CACHE_CONNECTION CACHE_CONSUMER CACHE_NONE and CACHE_SESSION. The default setting is CACHE_AUTO. See the Spring documentation and Transactions Cache Levels for more information. | CACHE_AUTO | String | *concurrentConsumers* (consumer) | Specifies the default number of concurrent consumers when consuming from JMS (not for request/reply over JMS). See also the maxMessagesPerTask option to control dynamic scaling up/down of threads. When doing request/reply over JMS then the option replyToConcurrentConsumers is used to control number of concurrent consumers on the reply message listener. | 1 | int | *maxConcurrentConsumers* (consumer) | Specifies the maximum number of concurrent consumers when consuming from JMS (not for request/reply over JMS). See also the maxMessagesPerTask option to control dynamic scaling up/down of threads. When doing request/reply over JMS then the option replyToMaxConcurrentConsumers is used to control number of concurrent consumers on the reply message listener. | | int | *replyTo* (consumer) | Provides an explicit ReplyTo destination which overrides any incoming value of Message.getJMSReplyTo(). | | String | *replyToDeliveryPersistent* (consumer) | Specifies whether to use persistent delivery by default for replies. | true | boolean | *selector* (consumer) | Sets the JMS selector to use | | String | *subscriptionDurable* (consumer) | Set whether to make the subscription durable. The durable subscription name to be used can be specified through the subscriptionName property. Default is false. Set this to true to register a durable subscription typically in combination with a subscriptionName value (unless your message listener class name is good enough as subscription name). Only makes sense when listening to a topic (pub-sub domain) therefore this method switches the pubSubDomain flag as well. | false | boolean | *subscriptionName* (consumer) | Set the name of a subscription to create. To be applied in case of a topic (pub-sub domain) with a shared or durable subscription. The subscription name needs to be unique within this client's JMS client id. Default is the class name of the specified message listener. Note: Only 1 concurrent consumer (which is the default of this message listener container) is allowed for each subscription except for a shared subscription (which requires JMS 2.0). | | String | *subscriptionShared* (consumer) | Set whether to make the subscription shared. The shared subscription name to be used can be specified through the subscriptionName property. Default is false. Set this to true to register a shared subscription typically in combination with a subscriptionName value (unless your message listener class name is good enough as subscription name). Note that shared subscriptions may also be durable so this flag can (and often will) be combined with subscriptionDurable as well. Only makes sense when listening to a topic (pub-sub domain) therefore this method switches the pubSubDomain flag as well. Requires a JMS 2.0 compatible message broker. | false | boolean | *acceptMessagesWhileStopping* (consumer) | Specifies whether the consumer accept messages while it is stopping. You may consider enabling this option if you start and stop JMS routes at runtime while there are still messages enqueued on the queue. If this option is false and you stop the JMS route then messages may be rejected and the JMS broker would have to attempt redeliveries which yet again may be rejected and eventually the message may be moved at a dead letter queue on the JMS broker. To avoid this its recommended to enable this option. | false | boolean | *allowReplyManagerQuickStop* (consumer) | Whether the DefaultMessageListenerContainer used in the reply managers for request-reply messaging allow the DefaultMessageListenerContainer.runningAllowed flag to quick stop in case JmsConfigurationisAcceptMessagesWhileStopping is enabled and org.apache.camel.CamelContext is currently being stopped. This quick stop ability is enabled by default in the regular JMS consumers but to enable for reply managers you must enable this flag. | false | boolean | *consumerType* (consumer) | The consumer type to use which can be one of: Simple Default or Custom. The consumer type determines which Spring JMS listener to use. Default will use org.springframework.jms.listener.DefaultMessageListenerContainer Simple will use org.springframework.jms.listener.SimpleMessageListenerContainer. When Custom is specified the MessageListenerContainerFactory defined by the messageListenerContainerFactory option will determine what org.springframework.jms.listener.AbstractMessageListenerContainer to use. | Default | ConsumerType | *defaultTaskExecutorType* (consumer) | Specifies what default TaskExecutor type to use in the DefaultMessageListenerContainer for both consumer endpoints and the ReplyTo consumer of producer endpoints. Possible values: SimpleAsync (uses Spring's SimpleAsyncTaskExecutor) or ThreadPool (uses Spring's ThreadPoolTaskExecutor with optimal values - cached threadpool-like). If not set it defaults to the previous behaviour which uses a cached thread pool for consumer endpoints and SimpleAsync for reply consumers. The use of ThreadPool is recommended to reduce thread trash in elastic configurations with dynamically increasing and decreasing concurrent consumers. | | DefaultTaskExecutor Type | *eagerLoadingOfProperties* (consumer) | Enables eager loading of JMS properties and payload as soon as a message is loaded which generally is inefficient as the JMS properties may not be required but sometimes can catch early any issues with the underlying JMS provider and the use of JMS properties | false | 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 | *exposeListenerSession* (consumer) | Specifies whether the listener session should be exposed when consuming messages. | false | boolean | *replyToSameDestination Allowed* (consumer) | Whether a JMS consumer is allowed to send a reply message to the same destination that the consumer is using to consume from. This prevents an endless loop by consuming and sending back the same message to itself. | false | boolean | *taskExecutor* (consumer) | Allows you to specify a custom task executor for consuming messages. | | TaskExecutor | *deliveryMode* (producer) | Specifies the delivery mode to be used. Possibles values are those defined by javax.jms.DeliveryMode. NON_PERSISTENT = 1 and PERSISTENT = 2. | | Integer | *deliveryPersistent* (producer) | Specifies whether persistent delivery is used by default. | true | boolean | *explicitQosEnabled* (producer) | Set if the deliveryMode priority or timeToLive qualities of service should be used when sending messages. This option is based on Spring's JmsTemplate. The deliveryMode priority and timeToLive options are applied to the current endpoint. This contrasts with the preserveMessageQos option which operates at message granularity reading QoS properties exclusively from the Camel In message headers. | false | Boolean | *preserveMessageQos* (producer) | Set to true if you want to send message using the QoS settings specified on the message instead of the QoS settings on the JMS endpoint. The following three headers are considered JMSPriority JMSDeliveryMode and JMSExpiration. You can provide all or only some of them. If not provided Camel will fall back to use the values from the endpoint instead. So when using this option the headers override the values from the endpoint. The explicitQosEnabled option by contrast will only use options set on the endpoint and not values from the message header. | false | boolean | *priority* (producer) | Values greater than 1 specify the message priority when sending (where 0 is the lowest priority and 9 is the highest). The explicitQosEnabled option must also be enabled in order for this option to have any effect. | 4 | int | *replyToConcurrentConsumers* (producer) | Specifies the default number of concurrent consumers when doing request/reply over JMS. See also the maxMessagesPerTask option to control dynamic scaling up/down of threads. | 1 | int | *replyToMaxConcurrent Consumers* (producer) | Specifies the maximum number of concurrent consumers when using request/reply over JMS. See also the maxMessagesPerTask option to control dynamic scaling up/down of threads. | | int | *replyToOnTimeoutMax ConcurrentConsumers* (producer) | Specifies the maximum number of concurrent consumers for continue routing when timeout occurred when using request/reply over JMS. | 1 | int | *replyToOverride* (producer) | Provides an explicit ReplyTo destination in the JMS message which overrides the setting of replyTo. It is useful if you want to forward the message to a remote Queue and receive the reply message from the ReplyTo destination. | | String | *replyToType* (producer) | Allows for explicitly specifying which kind of strategy to use for replyTo queues when doing request/reply over JMS. Possible values are: Temporary Shared or Exclusive. By default Camel will use temporary queues. However if replyTo has been configured then Shared is used by default. This option allows you to use exclusive queues instead of shared ones. See Camel JMS documentation for more details and especially the notes about the implications if running in a clustered environment and the fact that Shared reply queues has lower performance than its alternatives Temporary and Exclusive. | | ReplyToType | *requestTimeout* (producer) | The timeout for waiting for a reply when using the InOut Exchange Pattern (in milliseconds). The default is 20 seconds. You can include the header CamelJmsRequestTimeout to override this endpoint configured timeout value and thus have per message individual timeout values. See also the requestTimeoutCheckerInterval option. | 20000 | long | *timeToLive* (producer) | When sending messages specifies the time-to-live of the message (in milliseconds). | -1 | long | *allowAdditionalHeaders* (producer) | This option is used to allow additional headers which may have values that are invalid according to JMS specification. For example some message systems such as WMQ do this with header names using prefix JMS_IBM_MQMD_ containing values with byte array or other invalid types. You can specify multiple header names separated by comma and use as suffix for wildcard matching. | | String | *allowNullBody* (producer) | Whether to allow sending messages with no body. If this option is false and the message body is null then an JMSException is thrown. | true | boolean | *alwaysCopyMessage* (producer) | If true Camel will always make a JMS message copy of the message when it is passed to the producer for sending. Copying the message is needed in some situations such as when a replyToDestinationSelectorName is set (incidentally Camel will set the alwaysCopyMessage option to true if a replyToDestinationSelectorName is set) | false | boolean | *correlationProperty* (producer) | When using InOut exchange pattern use this JMS property instead of JMSCorrelationID JMS property to correlate messages. If set messages will be correlated solely on the value of this property JMSCorrelationID property will be ignored and not set by Camel. | | String | *disableTimeToLive* (producer) | Use this option to force disabling time to live. For example when you do request/reply over JMS then Camel will by default use the requestTimeout value as time to live on the message being sent. The problem is that the sender and receiver systems have to have their clocks synchronized so they are in sync. This is not always so easy to archive. So you can use disableTimeToLive=true to not set a time to live value on the sent message. Then the message will not expire on the receiver system. See below in section About time to live for more details. | false | boolean | *forceSendOriginalMessage* (producer) | When using mapJmsMessage=false Camel will create a new JMS message to send to a new JMS destination if you touch the headers (get or set) during the route. Set this option to true to force Camel to send the original JMS message that was received. | false | boolean | *includeSentJMSMessageID* (producer) | Only applicable when sending to JMS destination using InOnly (eg fire and forget). Enabling this option will enrich the Camel Exchange with the actual JMSMessageID that was used by the JMS client when the message was sent to the JMS destination. | false | boolean | *replyToCacheLevelName* (producer) | Sets the cache level by name for the reply consumer when doing request/reply over JMS. This option only applies when using fixed reply queues (not temporary). Camel will by default use: CACHE_CONSUMER for exclusive or shared w/ replyToSelectorName. And CACHE_SESSION for shared without replyToSelectorName. Some JMS brokers such as IBM WebSphere may require to set the replyToCacheLevelName=CACHE_NONE to work. Note: If using temporary queues then CACHE_NONE is not allowed and you must use a higher value such as CACHE_CONSUMER or CACHE_SESSION. | | String | *replyToDestinationSelector Name* (producer) | Sets the JMS Selector using the fixed name to be used so you can filter out your own replies from the others when using a shared queue (that is if you are not using a temporary reply queue). | | String | *streamMessageTypeEnabled* (producer) | Sets whether StreamMessage type is enabled or not. Message payloads of streaming kind such as files InputStream etc will either by sent as BytesMessage or StreamMessage. This option controls which kind will be used. By default BytesMessage is used which enforces the entire message payload to be read into memory. By enabling this option the message payload is read into memory in chunks and each chunk is then written to the StreamMessage until no more data. | false | boolean | *allowSerializedHeaders* (advanced) | Controls whether or not to include serialized headers. Applies only when transferExchange is true. This requires that the objects are serializable. Camel will exclude any non-serializable objects and log it at WARN level. | false | boolean | *asyncStartListener* (advanced) | Whether to startup the JmsConsumer message listener asynchronously when starting a route. For example if a JmsConsumer cannot get a connection to a remote JMS broker then it may block while retrying and/or failover. This will cause Camel to block while starting routes. By setting this option to true you will let routes startup while the JmsConsumer connects to the JMS broker using a dedicated thread in asynchronous mode. If this option is used then beware that if the connection could not be established then an exception is logged at WARN level and the consumer will not be able to receive messages; You can then restart the route to retry. | false | boolean | *asyncStopListener* (advanced) | Whether to stop the JmsConsumer message listener asynchronously when stopping a route. | false | boolean | *destinationResolver* (advanced) | A pluggable org.springframework.jms.support.destination.DestinationResolver that allows you to use your own resolver (for example to lookup the real destination in a JNDI registry). | | DestinationResolver | *errorHandler* (advanced) | Specifies a org.springframework.util.ErrorHandler to be invoked in case of any uncaught exceptions thrown while processing a Message. By default these exceptions will be logged at the WARN level if no errorHandler has been configured. You can configure logging level and whether stack traces should be logged using errorHandlerLoggingLevel and errorHandlerLogStackTrace options. This makes it much easier to configure than having to code a custom errorHandler. | | ErrorHandler | *exceptionListener* (advanced) | Specifies the JMS Exception Listener that is to be notified of any underlying JMS exceptions. | | ExceptionListener | *headerFilterStrategy* (advanced) | To use a custom HeaderFilterStrategy to filter header to and from Camel message. | | HeaderFilterStrategy | *idleConsumerLimit* (advanced) | Specify the limit for the number of consumers that are allowed to be idle at any given time. | 1 | int | *idleTaskExecutionLimit* (advanced) | Specifies the limit for idle executions of a receive task not having received any message within its execution. If this limit is reached the task will shut down and leave receiving to other executing tasks (in the case of dynamic scheduling; see the maxConcurrentConsumers setting). There is additional doc available from Spring. | 1 | int | *includeAllJMSXProperties* (advanced) | Whether to include all JMSXxxx properties when mapping from JMS to Camel Message. Setting this to true will include properties such as JMSXAppID and JMSXUserID etc. Note: If you are using a custom headerFilterStrategy then this option does not apply. | false | boolean | *jmsKeyFormatStrategy* (advanced) | Pluggable strategy for encoding and decoding JMS keys so they can be compliant with the JMS specification. Camel provides two implementations out of the box: default and passthrough. The default strategy will safely marshal dots and hyphens (. and -). The passthrough strategy leaves the key as is. Can be used for JMS brokers which do not care whether JMS header keys contain illegal characters. You can provide your own implementation of the org.apache.camel.component.jms.JmsKeyFormatStrategy and refer to it using the notation. | | String | *mapJmsMessage* (advanced) | Specifies whether Camel should auto map the received JMS message to a suited payload type such as javax.jms.TextMessage to a String etc. | true | boolean | *maxMessagesPerTask* (advanced) | The number of messages per task. -1 is unlimited. If you use a range for concurrent consumers (eg min max) then this option can be used to set a value to eg 100 to control how fast the consumers will shrink when less work is required. | -1 | int | *messageConverter* (advanced) | To use a custom Spring org.springframework.jms.support.converter.MessageConverter so you can be in control how to map to/from a javax.jms.Message. | | MessageConverter | *messageCreatedStrategy* (advanced) | To use the given MessageCreatedStrategy which are invoked when Camel creates new instances of javax.jms.Message objects when Camel is sending a JMS message. | | MessageCreatedStrategy | *messageIdEnabled* (advanced) | When sending specifies whether message IDs should be added. This is just an hint to the JMS broker.If the JMS provider accepts this hint these messages must have the message ID set to null; if the provider ignores the hint the message ID must be set to its normal unique value | true | boolean | *messageListenerContainer Factory* (advanced) | Registry ID of the MessageListenerContainerFactory used to determine what org.springframework.jms.listener.AbstractMessageListenerContainer to use to consume messages. Setting this will automatically set consumerType to Custom. | | MessageListener ContainerFactory | *messageTimestampEnabled* (advanced) | Specifies whether timestamps should be enabled by default on sending messages. This is just an hint to the JMS broker.If the JMS provider accepts this hint these messages must have the timestamp set to zero; if the provider ignores the hint the timestamp must be set to its normal value | true | boolean | *pubSubNoLocal* (advanced) | Specifies whether to inhibit the delivery of messages published by its own connection. | false | boolean | *receiveTimeout* (advanced) | The timeout for receiving messages (in milliseconds). | 1000 | long | *recoveryInterval* (advanced) | Specifies the interval between recovery attempts i.e. when a connection is being refreshed in milliseconds. The default is 5000 ms that is 5 seconds. | 5000 | long | *requestTimeoutChecker Interval* (advanced) | Configures how often Camel should check for timed out Exchanges when doing request/reply over JMS. By default Camel checks once per second. But if you must react faster when a timeout occurs then you can lower this interval to check more frequently. The timeout is determined by the option requestTimeout. | 1000 | long | *synchronous* (advanced) | Sets whether synchronous processing should be strictly used or Camel is allowed to use asynchronous processing (if supported). | false | boolean | *transferException* (advanced) | If enabled and you are using Request Reply messaging (InOut) and an Exchange failed on the consumer side then the caused Exception will be send back in response as a javax.jms.ObjectMessage. If the client is Camel the returned Exception is rethrown. This allows you to use Camel JMS as a bridge in your routing - for example using persistent queues to enable robust routing. Notice that if you also have transferExchange enabled this option takes precedence. The caught exception is required to be serializable. The original Exception on the consumer side can be wrapped in an outer exception such as org.apache.camel.RuntimeCamelException when returned to the producer. | false | boolean | *transferExchange* (advanced) | You can transfer the exchange over the wire instead of just the body and headers. 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. You must enable this option on both the producer and consumer side so Camel knows the payloads is an Exchange and not a regular payload. | false | boolean | *transferFault* (advanced) | If enabled and you are using Request Reply messaging (InOut) and an Exchange failed with a SOAP fault (not exception) on the consumer side then the fault flag on MessageisFault() will be send back in the response as a JMS header with the key org.apache.camel.component.jms.JmsConstantsJMS_TRANSFER_FAULTJMS_TRANSFER_FAULT. If the client is Camel the returned fault flag will be set on the link org.apache.camel.MessagesetFault(boolean). You may want to enable this when using Camel components that support faults such as SOAP based such as cxf or spring-ws. | false | boolean | *useMessageIDAsCorrelation ID* (advanced) | Specifies whether JMSMessageID should always be used as JMSCorrelationID for InOut messages. | false | boolean | *waitForProvisionCorrelation ToBeUpdatedCounter* (advanced) | Number of times to wait for provisional correlation id to be updated to the actual correlation id when doing request/reply over JMS and when the option useMessageIDAsCorrelationID is enabled. | 50 | int | *waitForProvisionCorrelation ToBeUpdatedThreadSleeping Time* (advanced) | Interval in millis to sleep each time while waiting for provisional correlation id to be updated. | 100 | long | *errorHandlerLoggingLevel* (logging) | Allows to configure the default errorHandler logging level for logging uncaught exceptions. | WARN | LoggingLevel | *errorHandlerLogStackTrace* (logging) | Allows to control whether stacktraces should be logged or not by the default errorHandler. | true | boolean | *password* (security) | Password to use with the ConnectionFactory. You can also configure username/password directly on the ConnectionFactory. | | String | *username* (security) | Username to use with the ConnectionFactory. You can also configure username/password directly on the ConnectionFactory. | | String | *transacted* (transaction) | Specifies whether to use transacted mode | false | boolean | *lazyCreateTransaction Manager* (transaction) | If true Camel will create a JmsTransactionManager if there is no transactionManager injected when option transacted=true. | true | boolean | *transactionManager* (transaction) | The Spring transaction manager to use. | | PlatformTransaction Manager | *transactionName* (transaction) | The name of the transaction to use. | | String | *transactionTimeout* (transaction) | The timeout value of the transaction (in seconds) if using transacted mode. | -1 | int |=== // endpoint options: END ### Usage As AMQP component is inherited from JMS component, the usage of the former is almost identical to the latter: *Using AMQP component* [source,java] ------------------------------------ // Consuming from AMQP queue from(""amqp:queue:incoming""). to(...);   // Sending message to the AMQP topic from(...). to(""amqp:topic:notify""); ------------------------------------ ### Configuring AMQP component Starting from the Camel 2.16.1 you can also use the `AMQPComponent#amqp10Component(String connectionURI)` factory method to return the AMQP 1.0 component with the pre-configured topic prefix:  *Creating AMQP 1.0 component* [source,java] ----------------------------------------------------------------------------------------- AMQPComponent amqp = AMQPComponent.amqp10Component(""amqp://guest:guest@localhost:5672""); ----------------------------------------------------------------------------------------- Keep in mind that starting from the Camel 2.17 the `AMQPComponent#amqp10Component(String connectionURI)` factory method has been deprecated on the behalf of the `AMQPComponent#amqpComponent(String connectionURI)`:  *Creating AMQP 1.0 component* [source,java] -------------------------------------------------------------------------------------------------------- AMQPComponent amqp = AMQPComponent.amqpComponent(""amqp://localhost:5672"");   AMQPComponent authorizedAmqp = AMQPComponent.amqpComponent(""amqp://localhost:5672"", ""user"", ""password""); -------------------------------------------------------------------------------------------------------- Starting from Camel 2.17, in order to automatically configure the AMQP component, you can also add an instance of `org.apache.camel.component.amqp.AMQPConnectionDetails` to the registry. For example for Spring Boot you just have to define bean: *AMQP connection details auto-configuration* [source,java] ------------------------------------------------------------------------------------- @Bean AMQPConnectionDetails amqpConnection() { return new AMQPConnectionDetails(""amqp://localhost:5672""); }   @Bean AMQPConnectionDetails securedAmqpConnection() { return new AMQPConnectionDetails(""amqp://lcoalhost:5672"", ""username"", ""password""); } ------------------------------------------------------------------------------------- Likewise, you can also use CDI producer methods when using Camel-CDI *AMQP connection details auto-configuration for CDI* [source,java] ------------------------------------------------------------------------------------- @Produces AMQPConnectionDetails amqpConnection() { return new AMQPConnectionDetails(""amqp://localhost:5672""); } -------------------------------------------------------------------------------------  You can also rely on the <> to read the AMQP connection details. Factory method `AMQPConnectionDetails.discoverAMQP()` attempts to read Camel properties in a Kubernetes-like convention, just as demonstrated on the snippet below:   *AMQP connection details auto-configuration* [source,java] ----------------------------------------------- export AMQP_SERVICE_HOST = ""mybroker.com"" export AMQP_SERVICE_PORT = ""6666"" export AMQP_SERVICE_USERNAME = ""username"" export AMQP_SERVICE_PASSWORD = ""password""   ...   @Bean AMQPConnectionDetails amqpConnection() { return AMQPConnectionDetails.discoverAMQP(); } ----------------------------------------------- ### Using topics To have using topics working with `camel-amqp` you need to configure the component to use `topic://` as topic prefix, as shown below: [source,java] ------------------------------------------------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------------------------------------------------- Keep in mind that both  `AMQPComponent#amqpComponent()` methods and `AMQPConnectionDetails` pre-configure the component with the topic prefix, so you don't have to configure it explicitly. ### See Also * Configuring Camel * Component * Endpoint * Getting Started ",12486,True,2960.1689984961,median "/* * Copyright (c) 2010-2013 ARM Limited * All rights reserved. * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * Copyright (c) 2002-2005 The Regents of The University of Michigan * Copyright (c) 2010 Advanced Micro Devices, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ""AS IS"" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Erik Hallnor * Dave Greene * Nathan Binkert * Steve Reinhardt * Ron Dreslinski * Andreas Sandberg */ #ifndef __MEM_CACHE_CACHE_IMPL_HH__ #define __MEM_CACHE_CACHE_IMPL_HH__ /** * @file * Cache definitions. */ #include ""base/misc.hh"" #include ""base/types.hh"" #include ""debug/Cache.hh"" #include ""debug/CachePort.hh"" #include ""debug/CacheTags.hh"" #include ""mem/cache/prefetch/base.hh"" #include ""mem/cache/blk.hh"" #include ""mem/cache/cache.hh"" #include ""mem/cache/mshr.hh"" #include ""sim/sim_exit.hh"" template Cache::Cache(const Params *p) : BaseCache(p), tags(dynamic_cast(p->tags)), prefetcher(p->prefetcher), doFastWrites(true), prefetchOnAccess(p->prefetch_on_access) { tempBlock = new BlkType(); tempBlock->data = new uint8_t[blkSize]; cpuSidePort = new CpuSidePort(p->name + "".cpu_side"", this, ""CpuSidePort""); memSidePort = new MemSidePort(p->name + "".mem_side"", this, ""MemSidePort""); tags->setCache(this); if (prefetcher) prefetcher->setCache(this); } template Cache::~Cache() { delete [] tempBlock->data; delete tempBlock; delete cpuSidePort; delete memSidePort; } template void Cache::regStats() { BaseCache::regStats(); } template void Cache::cmpAndSwap(BlkType *blk, PacketPtr pkt) { uint64_t overwrite_val; bool overwrite_mem; uint64_t condition_val64; uint32_t condition_val32; int offset = tags->extractBlkOffset(pkt->getAddr()); uint8_t *blk_data = blk->data + offset; assert(sizeof(uint64_t) >= pkt->getSize()); overwrite_mem = true; // keep a copy of our possible write value, and copy what is at the // memory address into the packet pkt->writeData((uint8_t *)&overwrite_val); pkt->setData(blk_data); if (pkt->req->isCondSwap()) { if (pkt->getSize() == sizeof(uint64_t)) { condition_val64 = pkt->req->getExtraData(); overwrite_mem = !std::memcmp(&condition_val64, blk_data, sizeof(uint64_t)); } else if (pkt->getSize() == sizeof(uint32_t)) { condition_val32 = (uint32_t)pkt->req->getExtraData(); overwrite_mem = !std::memcmp(&condition_val32, blk_data, sizeof(uint32_t)); } else panic(""Invalid size for conditional read/write\\n""); } if (overwrite_mem) { std::memcpy(blk_data, &overwrite_val, pkt->getSize()); blk->status |= BlkDirty; } } template void Cache::satisfyCpuSideRequest(PacketPtr pkt, BlkType *blk, bool deferred_response, bool pending_downgrade) { assert(blk && blk->isValid()); // Occasionally this is not true... if we are a lower-level cache // satisfying a string of Read and ReadEx requests from // upper-level caches, a Read will mark the block as shared but we // can satisfy a following ReadEx anyway since we can rely on the // Read requester(s) to have buffered the ReadEx snoop and to // invalidate their blocks after receiving them. // assert(!pkt->needsExclusive() || blk->isWritable()); assert(pkt->getOffset(blkSize) + pkt->getSize() <= blkSize); // Check RMW operations first since both isRead() and // isWrite() will be true for them if (pkt->cmd == MemCmd::SwapReq) { cmpAndSwap(blk, pkt); } else if (pkt->isWrite()) { if (blk->checkWrite(pkt)) { pkt->writeDataToBlock(blk->data, blkSize); blk->status |= BlkDirty; } } else if (pkt->isRead()) { if (pkt->isLLSC()) { blk->trackLoadLocked(pkt); } pkt->setDataFromBlock(blk->data, blkSize); if (pkt->getSize() == blkSize) { // special handling for coherent block requests from // upper-level caches if (pkt->needsExclusive()) { // if we have a dirty copy, make sure the recipient // keeps it marked dirty if (blk->isDirty()) { pkt->assertMemInhibit(); } // on ReadExReq we give up our copy unconditionally if (blk != tempBlock) tags->invalidate(blk); blk->invalidate(); } else if (blk->isWritable() && !pending_downgrade && !pkt->sharedAsserted() && !pkt->req->isInstFetch()) { // we can give the requester an exclusive copy (by not // asserting shared line) on a read request if: // - we have an exclusive copy at this level (& below) // - we don't have a pending snoop from below // signaling another read request // - no other cache above has a copy (otherwise it // would have asseretd shared line on request) // - we are not satisfying an instruction fetch (this // prevents dirty data in the i-cache) if (blk->isDirty()) { // special considerations if we're owner: if (!deferred_response && !isTopLevel) { // if we are responding immediately and can // signal that we're transferring ownership // along with exclusivity, do so pkt->assertMemInhibit(); blk->status &= ~BlkDirty; } else { // if we're responding after our own miss, // there's a window where the recipient didn't // know it was getting ownership and may not // have responded to snoops correctly, so we // can't pass off ownership *or* exclusivity pkt->assertShared(); } } } else { // otherwise only respond with a shared copy pkt->assertShared(); } } } else { // Not a read or write... must be an upgrade. it's OK // to just ack those as long as we have an exclusive // copy at this level. assert(pkt->isUpgrade()); assert(blk != tempBlock); tags->invalidate(blk); blk->invalidate(); } } ///////////////////////////////////////////////////// // // MSHR helper functions // ///////////////////////////////////////////////////// template void Cache::markInService(MSHR *mshr, PacketPtr pkt) { markInServiceInternal(mshr, pkt); #if 0 if (mshr->originalCmd == MemCmd::HardPFReq) { DPRINTF(HWPrefetch, ""%s:Marking a HW_PF in service\\n"", name()); //Also clear pending if need be if (!prefetcher->havePending()) { deassertMemSideBusRequest(Request_PF); } } #endif } template void Cache::squash(int threadNum) { bool unblock = false; BlockedCause cause = NUM_BLOCKED_CAUSES; if (noTargetMSHR && noTargetMSHR->threadNum == threadNum) { noTargetMSHR = NULL; unblock = true; cause = Blocked_NoTargets; } if (mshrQueue.isFull()) { unblock = true; cause = Blocked_NoMSHRs; } mshrQueue.squash(threadNum); if (unblock && !mshrQueue.isFull()) { clearBlocked(cause); } } ///////////////////////////////////////////////////// // // Access path: requests coming in from the CPU side // ///////////////////////////////////////////////////// template bool Cache::access(PacketPtr pkt, BlkType *&blk, Cycles &lat, PacketList &writebacks) { DPRINTF(Cache, ""%s for %s address %x size %d\\n"", __func__, pkt->cmdString(), pkt->getAddr(), pkt->getSize()); if (pkt->req->isUncacheable()) { uncacheableFlush(pkt); blk = NULL; lat = hitLatency; return false; } int id = pkt->req->hasContextId() ? pkt->req->contextId() : -1; blk = tags->accessBlock(pkt->getAddr(), pkt->isSecure(), lat, id); DPRINTF(Cache, ""%s%s %x (%s) %s %s\\n"", pkt->cmdString(), pkt->req->isInstFetch() ? "" (ifetch)"" : """", pkt->getAddr(), pkt->isSecure() ? ""s"" : ""ns"", blk ? ""hit"" : ""miss"", blk ? blk->print() : """"); if (blk != NULL) { if (pkt->needsExclusive() ? blk->isWritable() : blk->isReadable()) { // OK to satisfy access incHitCount(pkt); satisfyCpuSideRequest(pkt, blk); return true; } } // Can't satisfy access normally... either no block (blk == NULL) // or have block but need exclusive & only have shared. // Writeback handling is special case. We can write the block // into the cache without having a writeable copy (or any copy at // all). if (pkt->cmd == MemCmd::Writeback) { assert(blkSize == pkt->getSize()); if (blk == NULL) { // need to do a replacement blk = allocateBlock(pkt->getAddr(), pkt->isSecure(), writebacks); if (blk == NULL) { // no replaceable block available, give up. // writeback will be forwarded to next level. incMissCount(pkt); return false; } tags->insertBlock(pkt, blk); blk->status = BlkValid | BlkReadable; } std::memcpy(blk->data, pkt->getPtr(), blkSize); blk->status |= BlkDirty; if (pkt->isSupplyExclusive()) { blk->status |= BlkWritable; } // nothing else to do; writeback doesn't expect response assert(!pkt->needsResponse()); DPRINTF(Cache, ""%s new state is %s\\n"", __func__, blk->print()); incHitCount(pkt); return true; } incMissCount(pkt); if (blk == NULL && pkt->isLLSC() && pkt->isWrite()) { // complete miss on store conditional... just give up now pkt->req->setExtraData(0); return true; } return false; } class ForwardResponseRecord : public Packet::SenderState { public: PortID prevSrc; ForwardResponseRecord(PortID prev_src) : prevSrc(prev_src) {} }; template void Cache::recvTimingSnoopResp(PacketPtr pkt) { DPRINTF(Cache, ""%s for %s address %x size %d\\n"", __func__, pkt->cmdString(), pkt->getAddr(), pkt->getSize()); Tick time = clockEdge(hitLatency); assert(pkt->isResponse()); // must be cache-to-cache response from upper to lower level ForwardResponseRecord *rec = dynamic_cast(pkt->senderState); assert(!system->bypassCaches()); if (rec == NULL) { assert(pkt->cmd == MemCmd::HardPFResp); // Check if it's a prefetch response and handle it. We shouldn't // get any other kinds of responses without FRRs. DPRINTF(Cache, ""Got prefetch response from above for addr %#x (%s)\\n"", pkt->getAddr(), pkt->isSecure() ? ""s"" : ""ns""); recvTimingResp(pkt); return; } pkt->popSenderState(); pkt->setDest(rec->prevSrc); delete rec; // @todo someone should pay for this pkt->busFirstWordDelay = pkt->busLastWordDelay = 0; memSidePort->schedTimingSnoopResp(pkt, time); } template bool Cache::recvTimingReq(PacketPtr pkt) { DPRINTF(CacheTags, ""%s tags: %s\\n"", __func__, tags->print()); //@todo Add back in MemDebug Calls // MemDebug::cacheAccess(pkt); /// @todo temporary hack to deal with memory corruption issue until /// 4-phase transactions are complete for (int x = 0; x < pendingDelete.size(); x++) delete pendingDelete[x]; pendingDelete.clear(); // we charge hitLatency for doing just about anything here Tick time = clockEdge(hitLatency); assert(pkt->isRequest()); // Just forward the packet if caches are disabled. if (system->bypassCaches()) { memSidePort->sendTimingReq(pkt); return true; } if (pkt->memInhibitAsserted()) { DPRINTF(Cache, ""mem inhibited on 0x%x (%s): not responding\\n"", pkt->getAddr(), pkt->isSecure() ? ""s"" : ""ns""); assert(!pkt->req->isUncacheable()); // Special tweak for multilevel coherence: snoop downward here // on invalidates since there may be other caches below here // that have shared copies. Not necessary if we know that // supplier had exclusive copy to begin with. if (pkt->needsExclusive() && !pkt->isSupplyExclusive()) { Packet *snoopPkt = new Packet(pkt, true); // clear flags // also reset the bus time that the original packet has // not yet paid for snoopPkt->busFirstWordDelay = snoopPkt->busLastWordDelay = 0; snoopPkt->setExpressSnoop(); snoopPkt->assertMemInhibit(); memSidePort->sendTimingReq(snoopPkt); // main memory will delete snoopPkt } // since we're the official target but we aren't responding, // delete the packet now. /// @todo nominally we should just delete the packet here, /// however, until 4-phase stuff we can't because sending /// cache is still relying on it pendingDelete.push_back(pkt); return true; } if (pkt->req->isUncacheable()) { uncacheableFlush(pkt); // @todo: someone should pay for this pkt->busFirstWordDelay = pkt->busLastWordDelay = 0; // writes go in write buffer, reads use MSHR if (pkt->isWrite() && !pkt->isRead()) { allocateWriteBuffer(pkt, time, true); } else { allocateUncachedReadBuffer(pkt, time, true); } assert(pkt->needsResponse()); // else we should delete it here?? return true; } Cycles lat = hitLatency; BlkType *blk = NULL; PacketList writebacks; bool satisfied = access(pkt, blk, lat, writebacks); #if 0 /** @todo make the fast write alloc (wh64) work with coherence. */ // If this is a block size write/hint (WH64) allocate the block here // if the coherence protocol allows it. if (!blk && pkt->getSize() >= blkSize && coherence->allowFastWrites() && (pkt->cmd == MemCmd::WriteReq || pkt->cmd == MemCmd::WriteInvalidateReq) ) { // not outstanding misses, can do this MSHR *outstanding_miss = mshrQueue.findMatch(pkt->getAddr(), pkt->isSecure()); if (pkt->cmd == MemCmd::WriteInvalidateReq || !outstanding_miss) { if (outstanding_miss) { warn(""WriteInv doing a fastallocate"" ""with an outstanding miss to the same address\\n""); } blk = handleFill(NULL, pkt, BlkValid | BlkWritable, writebacks); ++fastWrites; } } #endif // track time of availability of next prefetch, if any Tick next_pf_time = 0; bool needsResponse = pkt->needsResponse(); if (satisfied) { if (prefetcher && (prefetchOnAccess || (blk && blk->wasPrefetched()))) { if (blk) blk->status &= ~BlkHWPrefetched; next_pf_time = prefetcher->notify(pkt, time); } if (needsResponse) { pkt->makeTimingResponse(); // @todo: Make someone pay for this pkt->busFirstWordDelay = pkt->busLastWordDelay = 0; cpuSidePort->schedTimingResp(pkt, clockEdge(lat)); } else { /// @todo nominally we should just delete the packet here, /// however, until 4-phase stuff we can't because sending /// cache is still relying on it pendingDelete.push_back(pkt); } } else { // miss // @todo: Make someone pay for this pkt->busFirstWordDelay = pkt->busLastWordDelay = 0; Addr blk_addr = blockAlign(pkt->getAddr()); MSHR *mshr = mshrQueue.findMatch(blk_addr, pkt->isSecure()); if (mshr) { /// MSHR hit /// @note writebacks will be checked in getNextMSHR() /// for any conflicting requests to the same block //@todo remove hw_pf here assert(pkt->req->masterId() < system->maxMasters()); mshr_hits[pkt->cmdToIndex()][pkt->req->masterId()]++; if (mshr->threadNum != 0/*pkt->req->threadId()*/) { mshr->threadNum = -1; } mshr->allocateTarget(pkt, time, order++); if (mshr->getNumTargets() == numTarget) { noTargetMSHR = mshr; setBlocked(Blocked_NoTargets); // need to be careful with this... if this mshr isn't // ready yet (i.e. time > curTick()_, we don't want to // move it ahead of mshrs that are ready // mshrQueue.moveToFront(mshr); } // We should call the prefetcher reguardless if the request is // satisfied or not, reguardless if the request is in the MSHR or // not. The request could be a ReadReq hit, but still not // satisfied (potentially because of a prior write to the same // cache line. So, even when not satisfied, tehre is an MSHR // already allocated for this, we need to let the prefetcher know // about the request if (prefetcher) { next_pf_time = prefetcher->notify(pkt, time); } } else { // no MSHR assert(pkt->req->masterId() < system->maxMasters()); mshr_misses[pkt->cmdToIndex()][pkt->req->masterId()]++; // always mark as cache fill for now... if we implement // no-write-allocate or bypass accesses this will have to // be changed. if (pkt->cmd == MemCmd::Writeback) { allocateWriteBuffer(pkt, time, true); } else { if (blk && blk->isValid()) { // If we have a write miss to a valid block, we // need to mark the block non-readable. Otherwise // if we allow reads while there's an outstanding // write miss, the read could return stale data // out of the cache block... a more aggressive // system could detect the overlap (if any) and // forward data out of the MSHRs, but we don't do // that yet. Note that we do need to leave the // block valid so that it stays in the cache, in // case we get an upgrade response (and hence no // new data) when the write miss completes. // As long as CPUs do proper store/load forwarding // internally, and have a sufficiently weak memory // model, this is probably unnecessary, but at some // point it must have seemed like we needed it... assert(pkt->needsExclusive() && !blk->isWritable()); blk->status &= ~BlkReadable; } allocateMissBuffer(pkt, time, true); } if (prefetcher) { next_pf_time = prefetcher->notify(pkt, time); } } } if (next_pf_time != 0) requestMemSideBus(Request_PF, std::max(time, next_pf_time)); // copy writebacks to write buffer while (!writebacks.empty()) { PacketPtr wbPkt = writebacks.front(); allocateWriteBuffer(wbPkt, time, true); writebacks.pop_front(); } return true; } // See comment in cache.hh. template PacketPtr Cache::getBusPacket(PacketPtr cpu_pkt, BlkType *blk, bool needsExclusive) const { bool blkValid = blk && blk->isValid(); if (cpu_pkt->req->isUncacheable()) { //assert(blk == NULL); return NULL; } if (!blkValid && (cpu_pkt->cmd == MemCmd::Writeback || cpu_pkt->isUpgrade())) { // Writebacks that weren't allocated in access() and upgrades // from upper-level caches that missed completely just go // through. return NULL; } assert(cpu_pkt->needsResponse()); MemCmd cmd; // @TODO make useUpgrades a parameter. // Note that ownership protocols require upgrade, otherwise a // write miss on a shared owned block will generate a ReadExcl, // which will clobber the owned copy. const bool useUpgrades = true; if (blkValid && useUpgrades) { // only reason to be here is that blk is shared // (read-only) and we need exclusive assert(needsExclusive && !blk->isWritable()); cmd = cpu_pkt->isLLSC() ? MemCmd::SCUpgradeReq : MemCmd::UpgradeReq; } else { // block is invalid cmd = needsExclusive ? MemCmd::ReadExReq : MemCmd::ReadReq; } PacketPtr pkt = new Packet(cpu_pkt->req, cmd, blkSize); pkt->allocate(); DPRINTF(Cache, ""%s created %s address %x size %d\\n"", __func__, pkt->cmdString(), pkt->getAddr(), pkt->getSize()); return pkt; } template Tick Cache::recvAtomic(PacketPtr pkt) { Cycles lat = hitLatency; // @TODO: make this a parameter bool last_level_cache = false; // Forward the request if the system is in cache bypass mode. if (system->bypassCaches()) return ticksToCycles(memSidePort->sendAtomic(pkt)); if (pkt->memInhibitAsserted()) { assert(!pkt->req->isUncacheable()); // have to invalidate ourselves and any lower caches even if // upper cache will be responding if (pkt->isInvalidate()) { BlkType *blk = tags->findBlock(pkt->getAddr(), pkt->isSecure()); if (blk && blk->isValid()) { tags->invalidate(blk); blk->invalidate(); DPRINTF(Cache, ""rcvd mem-inhibited %s on 0x%x (%s):"" "" invalidating\\n"", pkt->cmdString(), pkt->getAddr(), pkt->isSecure() ? ""s"" : ""ns""); } if (!last_level_cache) { DPRINTF(Cache, ""forwarding mem-inhibited %s on 0x%x (%s)\\n"", pkt->cmdString(), pkt->getAddr(), pkt->isSecure() ? ""s"" : ""ns""); lat += ticksToCycles(memSidePort->sendAtomic(pkt)); } } else { DPRINTF(Cache, ""rcvd mem-inhibited %s on 0x%x: not responding\\n"", pkt->cmdString(), pkt->getAddr()); } return lat * clockPeriod(); } // should assert here that there are no outstanding MSHRs or // writebacks... that would mean that someone used an atomic // access in timing mode BlkType *blk = NULL; PacketList writebacks; if (!access(pkt, blk, lat, writebacks)) { // MISS PacketPtr bus_pkt = getBusPacket(pkt, blk, pkt->needsExclusive()); bool is_forward = (bus_pkt == NULL); if (is_forward) { // just forwarding the same request to the next level // no local cache operation involved bus_pkt = pkt; } DPRINTF(Cache, ""Sending an atomic %s for %x (%s)\\n"", bus_pkt->cmdString(), bus_pkt->getAddr(), bus_pkt->isSecure() ? ""s"" : ""ns""); #if TRACING_ON CacheBlk::State old_state = blk ? blk->status : 0; #endif lat += ticksToCycles(memSidePort->sendAtomic(bus_pkt)); DPRINTF(Cache, ""Receive response: %s for addr %x (%s) in state %i\\n"", bus_pkt->cmdString(), bus_pkt->getAddr(), bus_pkt->isSecure() ? ""s"" : ""ns"", old_state); // If packet was a forward, the response (if any) is already // in place in the bus_pkt == pkt structure, so we don't need // to do anything. Otherwise, use the separate bus_pkt to // generate response to pkt and then delete it. if (!is_forward) { if (pkt->needsResponse()) { assert(bus_pkt->isResponse()); if (bus_pkt->isError()) { pkt->makeAtomicResponse(); pkt->copyError(bus_pkt); } else if (bus_pkt->isRead() || bus_pkt->cmd == MemCmd::UpgradeResp) { // we're updating cache state to allow us to // satisfy the upstream request from the cache blk = handleFill(bus_pkt, blk, writebacks); satisfyCpuSideRequest(pkt, blk); } else { // we're satisfying the upstream request without // modifying cache state, e.g., a write-through pkt->makeAtomicResponse(); } } delete bus_pkt; } } // Note that we don't invoke the prefetcher at all in atomic mode. // It's not clear how to do it properly, particularly for // prefetchers that aggressively generate prefetch candidates and // rely on bandwidth contention to throttle them; these will tend // to pollute the cache in atomic mode since there is no bandwidth // contention. If we ever do want to enable prefetching in atomic // mode, though, this is the place to do it... see timingAccess() // for an example (though we'd want to issue the prefetch(es) // immediately rather than calling requestMemSideBus() as we do // there). // Handle writebacks if needed while (!writebacks.empty()){ PacketPtr wbPkt = writebacks.front(); memSidePort->sendAtomic(wbPkt); writebacks.pop_front(); delete wbPkt; } // We now have the block one way or another (hit or completed miss) if (pkt->needsResponse()) { pkt->makeAtomicResponse(); } return lat * clockPeriod(); } template void Cache::functionalAccess(PacketPtr pkt, bool fromCpuSide) { if (system->bypassCaches()) { // Packets from the memory side are snoop request and // shouldn't happen in bypass mode. assert(fromCpuSide); // The cache should be flushed if we are in cache bypass mode, // so we don't need to check if we need to update anything. memSidePort->sendFunctional(pkt); return; } Addr blk_addr = blockAlign(pkt->getAddr()); bool is_secure = pkt->isSecure(); BlkType *blk = tags->findBlock(pkt->getAddr(), is_secure); MSHR *mshr = mshrQueue.findMatch(blk_addr, is_secure); pkt->pushLabel(name()); CacheBlkPrintWrapper cbpw(blk); // Note that just because an L2/L3 has valid data doesn't mean an // L1 doesn't have a more up-to-date modified copy that still // needs to be found. As a result we always update the request if // we have it, but only declare it satisfied if we are the owner. // see if we have data at all (owned or otherwise) bool have_data = blk && blk->isValid() && pkt->checkFunctional(&cbpw, blk_addr, is_secure, blkSize, blk->data); // data we have is dirty if marked as such or if valid & ownership // pending due to outstanding UpgradeReq bool have_dirty = have_data && (blk->isDirty() || (mshr && mshr->inService && mshr->isPendingDirty())); bool done = have_dirty || cpuSidePort->checkFunctional(pkt) || mshrQueue.checkFunctional(pkt, blk_addr) || writeBuffer.checkFunctional(pkt, blk_addr) || memSidePort->checkFunctional(pkt); DPRINTF(Cache, ""functional %s %x (%s) %s%s%s\\n"", pkt->cmdString(), pkt->getAddr(), is_secure ? ""s"" : ""ns"", (blk && blk->isValid()) ? ""valid "" : """", have_data ? ""data "" : """", done ? ""done "" : """"); // We're leaving the cache, so pop cache->name() label pkt->popLabel(); if (done) { pkt->makeResponse(); } else { // if it came as a request from the CPU side then make sure it // continues towards the memory side if (fromCpuSide) { memSidePort->sendFunctional(pkt); } else if (forwardSnoops && cpuSidePort->isSnooping()) { // if it came from the memory side, it must be a snoop request // and we should only forward it if we are forwarding snoops cpuSidePort->sendFunctionalSnoop(pkt); } } } ///////////////////////////////////////////////////// // // Response handling: responses from the memory side // ///////////////////////////////////////////////////// template void Cache::recvTimingResp(PacketPtr pkt) { assert(pkt->isResponse()); Tick time = clockEdge(hitLatency); MSHR *mshr = dynamic_cast(pkt->senderState); bool is_error = pkt->isError(); assert(mshr); if (is_error) { DPRINTF(Cache, ""Cache received packet with error for address %x (%s), "" ""cmd: %s\\n"", pkt->getAddr(), pkt->isSecure() ? ""s"" : ""ns"", pkt->cmdString()); } DPRINTF(Cache, ""Handling response to %s for address %x (%s)\\n"", pkt->cmdString(), pkt->getAddr(), pkt->isSecure() ? ""s"" : ""ns""); MSHRQueue *mq = mshr->queue; bool wasFull = mq->isFull(); if (mshr == noTargetMSHR) { // we always clear at least one target clearBlocked(Blocked_NoTargets); noTargetMSHR = NULL; } // Initial target is used just for stats MSHR::Target *initial_tgt = mshr->getTarget(); BlkType *blk = tags->findBlock(pkt->getAddr(), pkt->isSecure()); int stats_cmd_idx = initial_tgt->pkt->cmdToIndex(); Tick miss_latency = curTick() - initial_tgt->recvTime; PacketList writebacks; if (pkt->req->isUncacheable()) { assert(pkt->req->masterId() < system->maxMasters()); mshr_uncacheable_lat[stats_cmd_idx][pkt->req->masterId()] += miss_latency; } else { assert(pkt->req->masterId() < system->maxMasters()); mshr_miss_latency[stats_cmd_idx][pkt->req->masterId()] += miss_latency; } bool is_fill = !mshr->isForward && (pkt->isRead() || pkt->cmd == MemCmd::UpgradeResp); if (is_fill && !is_error) { DPRINTF(Cache, ""Block for addr %x being updated in Cache\\n"", pkt->getAddr()); // give mshr a chance to do some dirty work mshr->handleFill(pkt, blk); blk = handleFill(pkt, blk, writebacks); assert(blk != NULL); } // First offset for critical word first calculations int initial_offset = 0; if (mshr->hasTargets()) { initial_offset = mshr->getTarget()->pkt->getOffset(blkSize); } while (mshr->hasTargets()) { MSHR::Target *target = mshr->getTarget(); switch (target->source) { case MSHR::Target::FromCPU: Tick completion_time; if (is_fill) { satisfyCpuSideRequest(target->pkt, blk, true, mshr->hasPostDowngrade()); // How many bytes past the first request is this one int transfer_offset = target->pkt->getOffset(blkSize) - initial_offset; if (transfer_offset < 0) { transfer_offset += blkSize; } // If critical word (no offset) return first word time. // responseLatency is the latency of the return path // from lower level caches/memory to an upper level cache or // the core. completion_time = clockEdge(responseLatency) + (transfer_offset ? pkt->busLastWordDelay : pkt->busFirstWordDelay); assert(!target->pkt->req->isUncacheable()); assert(target->pkt->req->masterId() < system->maxMasters()); missLatency[target->pkt->cmdToIndex()][target->pkt->req->masterId()] += completion_time - target->recvTime; } else if (pkt->cmd == MemCmd::UpgradeFailResp) { // failed StoreCond upgrade assert(target->pkt->cmd == MemCmd::StoreCondReq || target->pkt->cmd == MemCmd::StoreCondFailReq || target->pkt->cmd == MemCmd::SCUpgradeFailReq); // responseLatency is the latency of the return path // from lower level caches/memory to an upper level cache or // the core. completion_time = clockEdge(responseLatency) + pkt->busLastWordDelay; target->pkt->req->setExtraData(0); } else { // not a cache fill, just forwarding response // responseLatency is the latency of the return path // from lower level cahces/memory to the core. completion_time = clockEdge(responseLatency) + pkt->busLastWordDelay; if (pkt->isRead() && !is_error) { target->pkt->setData(pkt->getPtr()); } } target->pkt->makeTimingResponse(); // if this packet is an error copy that to the new packet if (is_error) target->pkt->copyError(pkt); if (target->pkt->cmd == MemCmd::ReadResp && (pkt->isInvalidate() || mshr->hasPostInvalidate())) { // If intermediate cache got ReadRespWithInvalidate, // propagate that. Response should not have // isInvalidate() set otherwise. target->pkt->cmd = MemCmd::ReadRespWithInvalidate; DPRINTF(Cache, ""%s updated cmd to %s for address %x\\n"", __func__, target->pkt->cmdString(), target->pkt->getAddr()); } // reset the bus additional time as it is now accounted for target->pkt->busFirstWordDelay = target->pkt->busLastWordDelay = 0; cpuSidePort->schedTimingResp(target->pkt, completion_time); break; case MSHR::Target::FromPrefetcher: assert(target->pkt->cmd == MemCmd::HardPFReq); if (blk) blk->status |= BlkHWPrefetched; delete target->pkt->req; delete target->pkt; break; case MSHR::Target::FromSnoop: // I don't believe that a snoop can be in an error state assert(!is_error); // response to snoop request DPRINTF(Cache, ""processing deferred snoop...\\n""); assert(!(pkt->isInvalidate() && !mshr->hasPostInvalidate())); handleSnoop(target->pkt, blk, true, true, mshr->hasPostInvalidate()); break; default: panic(""Illegal target->source enum %d\\n"", target->source); } mshr->popTarget(); } if (blk && blk->isValid()) { if (pkt->isInvalidate() || mshr->hasPostInvalidate()) { assert(blk != tempBlock); tags->invalidate(blk); blk->invalidate(); } else if (mshr->hasPostDowngrade()) { blk->status &= ~BlkWritable; } } if (mshr->promoteDeferredTargets()) { // avoid later read getting stale data while write miss is // outstanding.. see comment in timingAccess() if (blk) { blk->status &= ~BlkReadable; } mq = mshr->queue; mq->markPending(mshr); requestMemSideBus((RequestCause)mq->index, clockEdge() + pkt->busLastWordDelay); } else { mq->deallocate(mshr); if (wasFull && !mq->isFull()) { clearBlocked((BlockedCause)mq->index); } } // copy writebacks to write buffer while (!writebacks.empty()) { PacketPtr wbPkt = writebacks.front(); allocateWriteBuffer(wbPkt, time, true); writebacks.pop_front(); } // if we used temp block, clear it out if (blk == tempBlock) { if (blk->isDirty()) { allocateWriteBuffer(writebackBlk(blk), time, true); } blk->invalidate(); } DPRINTF(Cache, ""Leaving %s with %s for address %x\\n"", __func__, pkt->cmdString(), pkt->getAddr()); delete pkt; } template PacketPtr Cache::writebackBlk(BlkType *blk) { assert(blk && blk->isValid() && blk->isDirty()); writebacks[Request::wbMasterId]++; Request *writebackReq = new Request(tags->regenerateBlkAddr(blk->tag, blk->set), blkSize, 0, Request::wbMasterId); if (blk->isSecure()) writebackReq->setFlags(Request::SECURE); writebackReq->taskId(blk->task_id); blk->task_id= ContextSwitchTaskId::Unknown; blk->tickInserted = curTick(); PacketPtr writeback = new Packet(writebackReq, MemCmd::Writeback); if (blk->isWritable()) { writeback->setSupplyExclusive(); } writeback->allocate(); std::memcpy(writeback->getPtr(), blk->data, blkSize); blk->status &= ~BlkDirty; return writeback; } template void Cache::memWriteback() { WrappedBlkVisitor visitor(*this, &Cache::writebackVisitor); tags->forEachBlk(visitor); } template void Cache::memInvalidate() { WrappedBlkVisitor visitor(*this, &Cache::invalidateVisitor); tags->forEachBlk(visitor); } template bool Cache::isDirty() const { CacheBlkIsDirtyVisitor visitor; tags->forEachBlk(visitor); return visitor.isDirty(); } template bool Cache::writebackVisitor(BlkType &blk) { if (blk.isDirty()) { assert(blk.isValid()); Request request(tags->regenerateBlkAddr(blk.tag, blk.set), blkSize, 0, Request::funcMasterId); request.taskId(blk.task_id); Packet packet(&request, MemCmd::WriteReq); packet.dataStatic(blk.data); memSidePort->sendFunctional(&packet); blk.status &= ~BlkDirty; } return true; } template bool Cache::invalidateVisitor(BlkType &blk) { if (blk.isDirty()) warn_once(""Invalidating dirty cache lines. Expect things to break.\\n""); if (blk.isValid()) { assert(!blk.isDirty()); tags->invalidate(dynamic_cast< BlkType *>(&blk)); blk.invalidate(); } return true; } template void Cache::uncacheableFlush(PacketPtr pkt) { DPRINTF(Cache, ""%s%s %x uncacheable\\n"", pkt->cmdString(), pkt->req->isInstFetch() ? "" (ifetch)"" : """", pkt->getAddr()); if (pkt->req->isClearLL()) tags->clearLocks(); BlkType *blk(tags->findBlock(pkt->getAddr(), pkt->isSecure())); if (blk) { writebackVisitor(*blk); invalidateVisitor(*blk); } } template typename Cache::BlkType* Cache::allocateBlock(Addr addr, bool is_secure, PacketList &writebacks) { BlkType *blk = tags->findVictim(addr); if (blk->isValid()) { Addr repl_addr = tags->regenerateBlkAddr(blk->tag, blk->set); MSHR *repl_mshr = mshrQueue.findMatch(repl_addr, blk->isSecure()); if (repl_mshr) { // must be an outstanding upgrade request on block // we're about to replace... assert(!blk->isWritable()); assert(repl_mshr->needsExclusive()); // too hard to replace block with transient state // allocation failed, block not inserted return NULL; } else { DPRINTF(Cache, ""replacement: replacing %x (%s) with %x (%s): %s\\n"", repl_addr, blk->isSecure() ? ""s"" : ""ns"", addr, is_secure ? ""s"" : ""ns"", blk->isDirty() ? ""writeback"" : ""clean""); if (blk->isDirty()) { // Save writeback packet for handling by caller writebacks.push_back(writebackBlk(blk)); } } } return blk; } // Note that the reason we return a list of writebacks rather than // inserting them directly in the write buffer is that this function // is called by both atomic and timing-mode accesses, and in atomic // mode we don't mess with the write buffer (we just perform the // writebacks atomically once the original request is complete). template typename Cache::BlkType* Cache::handleFill(PacketPtr pkt, BlkType *blk, PacketList &writebacks) { Addr addr = pkt->getAddr(); bool is_secure = pkt->isSecure(); #if TRACING_ON CacheBlk::State old_state = blk ? blk->status : 0; #endif if (blk == NULL) { // better have read new data... assert(pkt->hasData()); // need to do a replacement blk = allocateBlock(addr, is_secure, writebacks); if (blk == NULL) { // No replaceable block... just use temporary storage to // complete the current request and then get rid of it assert(!tempBlock->isValid()); blk = tempBlock; tempBlock->set = tags->extractSet(addr); tempBlock->tag = tags->extractTag(addr); // @todo: set security state as well... DPRINTF(Cache, ""using temp block for %x (%s)\\n"", addr, is_secure ? ""s"" : ""ns""); } else { tags->insertBlock(pkt, blk); } // we should never be overwriting a valid block assert(!blk->isValid()); } else { // existing block... probably an upgrade assert(blk->tag == tags->extractTag(addr)); // either we're getting new data or the block should already be valid assert(pkt->hasData() || blk->isValid()); // don't clear block status... if block is already dirty we // don't want to lose that } if (is_secure) blk->status |= BlkSecure; blk->status |= BlkValid | BlkReadable; if (!pkt->sharedAsserted()) { blk->status |= BlkWritable; // If we got this via cache-to-cache transfer (i.e., from a // cache that was an owner) and took away that owner's copy, // then we need to write it back. Normally this happens // anyway as a side effect of getting a copy to write it, but // there are cases (such as failed store conditionals or // compare-and-swaps) where we'll demand an exclusive copy but // end up not writing it. if (pkt->memInhibitAsserted()) blk->status |= BlkDirty; } DPRINTF(Cache, ""Block addr %x (%s) moving from state %x to %s\\n"", addr, is_secure ? ""s"" : ""ns"", old_state, blk->print()); // if we got new data, copy it in if (pkt->isRead()) { std::memcpy(blk->data, pkt->getPtr(), blkSize); } blk->whenReady = clockEdge() + responseLatency * clockPeriod() + pkt->busLastWordDelay; return blk; } ///////////////////////////////////////////////////// // // Snoop path: requests coming in from the memory side // ///////////////////////////////////////////////////// template void Cache:: doTimingSupplyResponse(PacketPtr req_pkt, uint8_t *blk_data, bool already_copied, bool pending_inval) { DPRINTF(Cache, ""%s for %s address %x size %d\\n"", __func__, req_pkt->cmdString(), req_pkt->getAddr(), req_pkt->getSize()); // timing-mode snoop responses require a new packet, unless we // already made a copy... PacketPtr pkt = already_copied ? req_pkt : new Packet(req_pkt); assert(req_pkt->isInvalidate() || pkt->sharedAsserted()); pkt->allocate(); pkt->makeTimingResponse(); // @todo Make someone pay for this pkt->busFirstWordDelay = pkt->busLastWordDelay = 0; if (pkt->isRead()) { pkt->setDataFromBlock(blk_data, blkSize); } if (pkt->cmd == MemCmd::ReadResp && pending_inval) { // Assume we defer a response to a read from a far-away cache // A, then later defer a ReadExcl from a cache B on the same // bus as us. We'll assert MemInhibit in both cases, but in // the latter case MemInhibit will keep the invalidation from // reaching cache A. This special response tells cache A that // it gets the block to satisfy its read, but must immediately // invalidate it. pkt->cmd = MemCmd::ReadRespWithInvalidate; } DPRINTF(Cache, ""%s created response: %s address %x size %d\\n"", __func__, pkt->cmdString(), pkt->getAddr(), pkt->getSize()); memSidePort->schedTimingSnoopResp(pkt, clockEdge(hitLatency)); } template void Cache::handleSnoop(PacketPtr pkt, BlkType *blk, bool is_timing, bool is_deferred, bool pending_inval) { DPRINTF(Cache, ""%s for %s address %x size %d\\n"", __func__, pkt->cmdString(), pkt->getAddr(), pkt->getSize()); // deferred snoops can only happen in timing mode assert(!(is_deferred && !is_timing)); // pending_inval only makes sense on deferred snoops assert(!(pending_inval && !is_deferred)); assert(pkt->isRequest()); // the packet may get modified if we or a forwarded snooper // responds in atomic mode, so remember a few things about the // original packet up front bool invalidate = pkt->isInvalidate(); bool M5_VAR_USED needs_exclusive = pkt->needsExclusive(); if (forwardSnoops) { // first propagate snoop upward to see if anyone above us wants to // handle it. save & restore packet src since it will get // rewritten to be relative to cpu-side bus (if any) bool alreadyResponded = pkt->memInhibitAsserted(); if (is_timing) { Packet snoopPkt(pkt, true); // clear flags snoopPkt.setExpressSnoop(); snoopPkt.pushSenderState(new ForwardResponseRecord(pkt->getSrc())); // the snoop packet does not need to wait any additional // time snoopPkt.busFirstWordDelay = snoopPkt.busLastWordDelay = 0; cpuSidePort->sendTimingSnoopReq(&snoopPkt); if (snoopPkt.memInhibitAsserted()) { // cache-to-cache response from some upper cache assert(!alreadyResponded); pkt->assertMemInhibit(); } else { delete snoopPkt.popSenderState(); } if (snoopPkt.sharedAsserted()) { pkt->assertShared(); } } else { cpuSidePort->sendAtomicSnoop(pkt); if (!alreadyResponded && pkt->memInhibitAsserted()) { // cache-to-cache response from some upper cache: // forward response to original requester assert(pkt->isResponse()); } } } if (!blk || !blk->isValid()) { DPRINTF(Cache, ""%s snoop miss for %s address %x size %d\\n"", __func__, pkt->cmdString(), pkt->getAddr(), pkt->getSize()); return; } else { DPRINTF(Cache, ""%s snoop hit for %s for address %x size %d, "" ""old state is %s\\n"", __func__, pkt->cmdString(), pkt->getAddr(), pkt->getSize(), blk->print()); } // we may end up modifying both the block state and the packet (if // we respond in atomic mode), so just figure out what to do now // and then do it later bool respond = blk->isDirty() && pkt->needsResponse(); bool have_exclusive = blk->isWritable(); if (pkt->isRead() && !invalidate) { assert(!needs_exclusive); pkt->assertShared(); int bits_to_clear = BlkWritable; const bool haveOwnershipState = true; // for now if (!haveOwnershipState) { // if we don't support pure ownership (dirty && !writable), // have to clear dirty bit here, assume memory snarfs data // on cache-to-cache xfer bits_to_clear |= BlkDirty; } blk->status &= ~bits_to_clear; } if (respond) { assert(!pkt->memInhibitAsserted()); pkt->assertMemInhibit(); if (have_exclusive) { pkt->setSupplyExclusive(); } if (is_timing) { doTimingSupplyResponse(pkt, blk->data, is_deferred, pending_inval); } else { pkt->makeAtomicResponse(); pkt->setDataFromBlock(blk->data, blkSize); } } else if (is_timing && is_deferred) { // if it's a deferred timing snoop then we've made a copy of // the packet, and so if we're not using that copy to respond // then we need to delete it here. delete pkt; } // Do this last in case it deallocates block data or something // like that if (invalidate) { if (blk != tempBlock) tags->invalidate(blk); blk->invalidate(); } DPRINTF(Cache, ""new state is %s\\n"", blk->print()); } template void Cache::recvTimingSnoopReq(PacketPtr pkt) { DPRINTF(Cache, ""%s for %s address %x size %d\\n"", __func__, pkt->cmdString(), pkt->getAddr(), pkt->getSize()); // Snoops shouldn't happen when bypassing caches assert(!system->bypassCaches()); // check if the packet is for an address range covered by this // cache, partly to not waste time looking for it, but also to // ensure that we only forward the snoop upwards if it is within // our address ranges bool in_range = false; for (AddrRangeList::const_iterator r = addrRanges.begin(); r != addrRanges.end(); ++r) { if (r->contains(pkt->getAddr())) { in_range = true; break; } } // Note that some deferred snoops don't have requests, since the // original access may have already completed if ((pkt->req && pkt->req->isUncacheable()) || pkt->cmd == MemCmd::Writeback || !in_range) { //Can't get a hit on an uncacheable address //Revisit this for multi level coherence return; } bool is_secure = pkt->isSecure(); BlkType *blk = tags->findBlock(pkt->getAddr(), is_secure); Addr blk_addr = blockAlign(pkt->getAddr()); MSHR *mshr = mshrQueue.findMatch(blk_addr, is_secure); // Let the MSHR itself track the snoop and decide whether we want // to go ahead and do the regular cache snoop if (mshr && mshr->handleSnoop(pkt, order++)) { DPRINTF(Cache, ""Deferring snoop on in-service MSHR to blk %x (%s)."" ""mshrs: %s\\n"", blk_addr, is_secure ? ""s"" : ""ns"", mshr->print()); if (mshr->getNumTargets() > numTarget) warn(""allocating bonus target for snoop""); //handle later return; } //We also need to check the writeback buffers and handle those std::vector writebacks; if (writeBuffer.findMatches(blk_addr, is_secure, writebacks)) { DPRINTF(Cache, ""Snoop hit in writeback to addr: %x (%s)\\n"", pkt->getAddr(), is_secure ? ""s"" : ""ns""); //Look through writebacks for any non-uncachable writes, use that if (writebacks.size()) { // We should only ever find a single match assert(writebacks.size() == 1); mshr = writebacks[0]; assert(!mshr->isUncacheable()); assert(mshr->getNumTargets() == 1); PacketPtr wb_pkt = mshr->getTarget()->pkt; assert(wb_pkt->cmd == MemCmd::Writeback); assert(!pkt->memInhibitAsserted()); pkt->assertMemInhibit(); if (!pkt->needsExclusive()) { pkt->assertShared(); // the writeback is no longer the exclusive copy in the system wb_pkt->clearSupplyExclusive(); } else { // if we're not asserting the shared line, we need to // invalidate our copy. we'll do that below as long as // the packet's invalidate flag is set... assert(pkt->isInvalidate()); } doTimingSupplyResponse(pkt, wb_pkt->getPtr(), false, false); if (pkt->isInvalidate()) { // Invalidation trumps our writeback... discard here markInService(mshr); delete wb_pkt; } } // writebacks.size() } // If this was a shared writeback, there may still be // other shared copies above that require invalidation. // We could be more selective and return here if the // request is non-exclusive or if the writeback is // exclusive. handleSnoop(pkt, blk, true, false, false); } template bool Cache::CpuSidePort::recvTimingSnoopResp(PacketPtr pkt) { // Express snoop responses from master to slave, e.g., from L1 to L2 cache->recvTimingSnoopResp(pkt); return true; } template Tick Cache::recvAtomicSnoop(PacketPtr pkt) { // Snoops shouldn't happen when bypassing caches assert(!system->bypassCaches()); if (pkt->req->isUncacheable() || pkt->cmd == MemCmd::Writeback) { // Can't get a hit on an uncacheable address // Revisit this for multi level coherence return 0; } BlkType *blk = tags->findBlock(pkt->getAddr(), pkt->isSecure()); handleSnoop(pkt, blk, false, false, false); return hitLatency * clockPeriod(); } template MSHR * Cache::getNextMSHR() { // Check both MSHR queue and write buffer for potential requests MSHR *miss_mshr = mshrQueue.getNextMSHR(); MSHR *write_mshr = writeBuffer.getNextMSHR(); // Now figure out which one to send... some cases are easy if (miss_mshr && !write_mshr) { return miss_mshr; } if (write_mshr && !miss_mshr) { return write_mshr; } if (miss_mshr && write_mshr) { // We have one of each... normally we favor the miss request // unless the write buffer is full if (writeBuffer.isFull() && writeBuffer.inServiceEntries == 0) { // Write buffer is full, so we'd like to issue a write; // need to search MSHR queue for conflicting earlier miss. MSHR *conflict_mshr = mshrQueue.findPending(write_mshr->addr, write_mshr->size, write_mshr->isSecure); if (conflict_mshr && conflict_mshr->order < write_mshr->order) { // Service misses in order until conflict is cleared. return conflict_mshr; } // No conflicts; issue write return write_mshr; } // Write buffer isn't full, but need to check it for // conflicting earlier writeback MSHR *conflict_mshr = writeBuffer.findPending(miss_mshr->addr, miss_mshr->size, miss_mshr->isSecure); if (conflict_mshr) { // not sure why we don't check order here... it was in the // original code but commented out. // The only way this happens is if we are // doing a write and we didn't have permissions // then subsequently saw a writeback (owned got evicted) // We need to make sure to perform the writeback first // To preserve the dirty data, then we can issue the write // should we return write_mshr here instead? I.e. do we // have to flush writes in order? I don't think so... not // for Alpha anyway. Maybe for x86? return conflict_mshr; } // No conflicts; issue read return miss_mshr; } // fall through... no pending requests. Try a prefetch. assert(!miss_mshr && !write_mshr); if (prefetcher && !mshrQueue.isFull()) { // If we have a miss queue slot, we can try a prefetch PacketPtr pkt = prefetcher->getPacket(); if (pkt) { Addr pf_addr = blockAlign(pkt->getAddr()); if (!tags->findBlock(pf_addr, pkt->isSecure()) && !mshrQueue.findMatch(pf_addr, pkt->isSecure()) && !writeBuffer.findMatch(pf_addr, pkt->isSecure())) { // Update statistic on number of prefetches issued // (hwpf_mshr_misses) assert(pkt->req->masterId() < system->maxMasters()); mshr_misses[pkt->cmdToIndex()][pkt->req->masterId()]++; // Don't request bus, since we already have it return allocateMissBuffer(pkt, curTick(), false); } else { // free the request and packet delete pkt->req; delete pkt; } } } return NULL; } template PacketPtr Cache::getTimingPacket() { MSHR *mshr = getNextMSHR(); if (mshr == NULL) { return NULL; } // use request from 1st target PacketPtr tgt_pkt = mshr->getTarget()->pkt; PacketPtr pkt = NULL; DPRINTF(CachePort, ""%s %s for address %x size %d\\n"", __func__, tgt_pkt->cmdString(), tgt_pkt->getAddr(), tgt_pkt->getSize()); if (tgt_pkt->cmd == MemCmd::SCUpgradeFailReq || tgt_pkt->cmd == MemCmd::StoreCondFailReq) { // SCUpgradeReq or StoreCondReq saw invalidation while queued // in MSHR, so now that we are getting around to processing // it, just treat it as if we got a failure response pkt = new Packet(tgt_pkt); pkt->cmd = MemCmd::UpgradeFailResp; pkt->senderState = mshr; pkt->busFirstWordDelay = pkt->busLastWordDelay = 0; recvTimingResp(pkt); return NULL; } else if (mshr->isForwardNoResponse()) { // no response expected, just forward packet as it is assert(tags->findBlock(mshr->addr, mshr->isSecure) == NULL); pkt = tgt_pkt; } else { BlkType *blk = tags->findBlock(mshr->addr, mshr->isSecure); if (tgt_pkt->cmd == MemCmd::HardPFReq) { // It might be possible for a writeback to arrive between // the time the prefetch is placed in the MSHRs and when // it's selected to send... if so, this assert will catch // that, and then we'll have to figure out what to do. assert(blk == NULL); // We need to check the caches above us to verify that // they don't have a copy of this block in the dirty state // at the moment. Without this check we could get a stale // copy from memory that might get used in place of the // dirty one. Packet snoop_pkt(tgt_pkt, true); snoop_pkt.setExpressSnoop(); snoop_pkt.senderState = mshr; cpuSidePort->sendTimingSnoopReq(&snoop_pkt); if (snoop_pkt.memInhibitAsserted()) { markInService(mshr, &snoop_pkt); DPRINTF(Cache, ""Upward snoop of prefetch for addr"" "" %#x (%s) hit\\n"", tgt_pkt->getAddr(), tgt_pkt->isSecure()? ""s"": ""ns""); return NULL; } } pkt = getBusPacket(tgt_pkt, blk, mshr->needsExclusive()); mshr->isForward = (pkt == NULL); if (mshr->isForward) { // not a cache block request, but a response is expected // make copy of current packet to forward, keep current // copy for response handling pkt = new Packet(tgt_pkt); pkt->allocate(); if (pkt->isWrite()) { pkt->setData(tgt_pkt->getPtr()); } } } assert(pkt != NULL); pkt->senderState = mshr; return pkt; } template Tick Cache::nextMSHRReadyTime() const { Tick nextReady = std::min(mshrQueue.nextMSHRReadyTime(), writeBuffer.nextMSHRReadyTime()); if (prefetcher) { nextReady = std::min(nextReady, prefetcher->nextPrefetchReadyTime()); } return nextReady; } template void Cache::serialize(std::ostream &os) { bool dirty(isDirty()); if (dirty) { warn(""*** The cache still contains dirty data. ***\\n""); warn("" Make sure to drain the system using the correct flags.\\n""); warn("" This checkpoint will not restore correctly and dirty data in "" ""the cache will be lost!\\n""); } // Since we don't checkpoint the data in the cache, any dirty data // will be lost when restoring from a checkpoint of a system that // wasn't drained properly. Flag the checkpoint as invalid if the // cache contains dirty data. bool bad_checkpoint(dirty); SERIALIZE_SCALAR(bad_checkpoint); } template void Cache::unserialize(Checkpoint *cp, const std::string §ion) { bool bad_checkpoint; UNSERIALIZE_SCALAR(bad_checkpoint); if (bad_checkpoint) { fatal(""Restoring from checkpoints with dirty caches is not supported "" ""in the classic memory system. Please remove any caches or "" "" drain them properly before taking checkpoints.\\n""); } } /////////////// // // CpuSidePort // /////////////// template AddrRangeList Cache::CpuSidePort::getAddrRanges() const { return cache->getAddrRanges(); } template bool Cache::CpuSidePort::recvTimingReq(PacketPtr pkt) { // always let inhibited requests through even if blocked if (!pkt->memInhibitAsserted() && blocked) { assert(!cache->system->bypassCaches()); DPRINTF(Cache,""Scheduling a retry while blocked\\n""); mustSendRetry = true; return false; } cache->recvTimingReq(pkt); return true; } template Tick Cache::CpuSidePort::recvAtomic(PacketPtr pkt) { return cache->recvAtomic(pkt); } template void Cache::CpuSidePort::recvFunctional(PacketPtr pkt) { // functional request cache->functionalAccess(pkt, true); } template Cache:: CpuSidePort::CpuSidePort(const std::string &_name, Cache *_cache, const std::string &_label) : BaseCache::CacheSlavePort(_name, _cache, _label), cache(_cache) { } /////////////// // // MemSidePort // /////////////// template bool Cache::MemSidePort::recvTimingResp(PacketPtr pkt) { cache->recvTimingResp(pkt); return true; } // Express snooping requests to memside port template void Cache::MemSidePort::recvTimingSnoopReq(PacketPtr pkt) { // handle snooping requests cache->recvTimingSnoopReq(pkt); } template Tick Cache::MemSidePort::recvAtomicSnoop(PacketPtr pkt) { return cache->recvAtomicSnoop(pkt); } template void Cache::MemSidePort::recvFunctionalSnoop(PacketPtr pkt) { // functional snoop (note that in contrast to atomic we don't have // a specific functionalSnoop method, as they have the same // behaviour regardless) cache->functionalAccess(pkt, false); } template void Cache::MemSidePacketQueue::sendDeferredPacket() { // if we have a response packet waiting we have to start with that if (deferredPacketReady()) { // use the normal approach from the timing port trySendTiming(); } else { // check for request packets (requests & writebacks) PacketPtr pkt = cache.getTimingPacket(); if (pkt == NULL) { // can happen if e.g. we attempt a writeback and fail, but // before the retry, the writeback is eliminated because // we snoop another cache's ReadEx. waitingOnRetry = false; } else { MSHR *mshr = dynamic_cast(pkt->senderState); waitingOnRetry = !masterPort.sendTimingReq(pkt); if (waitingOnRetry) { DPRINTF(CachePort, ""now waiting on a retry\\n""); if (!mshr->isForwardNoResponse()) { // we are awaiting a retry, but we // delete the packet and will be creating a new packet // when we get the opportunity delete pkt; } // note that we have now masked any requestBus and // schedSendEvent (we will wait for a retry before // doing anything), and this is so even if we do not // care about this packet and might override it before // it gets retried } else { cache.markInService(mshr, pkt); } } } // if we succeeded and are not waiting for a retry, schedule the // next send, not only looking at the response transmit list, but // also considering when the next MSHR is ready if (!waitingOnRetry) { scheduleSend(cache.nextMSHRReadyTime()); } } template Cache:: MemSidePort::MemSidePort(const std::string &_name, Cache *_cache, const std::string &_label) : BaseCache::CacheMasterPort(_name, _cache, _queue), _queue(*_cache, *this, _label), cache(_cache) { } #endif//__MEM_CACHE_CACHE_IMPL_HH__ ",16284,True,3490.8618650652998,median "= NetSuite Connector :keywords: anypoint studio, connector, endpoint, netsuite :page-aliases: 3.7@mule-runtime::netsuite-connector.adoc *_Select_* MuleSoft's Anypoint™ Connector for NetSuite synchronizes data and automates business processes between NetSuite and third party applications, either on-premises or in the cloud. *Release Notes*: xref:release-notes::connector/netsuite-connector-release-notes.adoc[NetSuite Connector Release Notes] == Introduction NetSuite is the world’s leading provider of cloud-based business management software. NetSuite helps companies manage core business processes with a single, fully integrated system covering ERP/financials, CRM, e-commerce, inventory, and more. The NetSuite connector makes use of the SuiteTalk WSDL to provide SOAP-based integration and generate NetSuite business objects, make use of different authentication levels, and support error handling. == Prerequisites This document assumes that you are familiar with Mule, xref:3.7@mule-runtime::anypoint-connectors.adoc[Anypoint™ Connectors], and the xref:5@studio::index.adoc[Anypoint Studio interface]. To increase your familiarity with Studio, consider completing one or more xref:5@studio::basic-studio-tutorial.adoc[Anypoint Studio Tutorials]. Further, this page assumes that you have a basic understanding of xref:3.7@mule-runtime::mule-concepts.adoc[Mule flows] and xref:3.7@mule-runtime::global-elements.adoc[Mule Global Elements]. To use this connector, you need a NetSuite account with Web Services Features enabled, and Anypoint Studio installed on your development machine. == Compatibility The NetSuite connector v7.1.0 is compatible with: [%header,cols=""2*""] |=== a| Application/Service a| Version |*Mule Runtime* |3.5 and later |*API* |SuiteTalks 2015_2 |=== == To Install this Connector . In Anypoint Studio, click the Exchange icon in the Studio taskbar. . Click Login in Anypoint Exchange. . Search for the connector and click Install. . Follow the prompts to install the connector. When Studio has an update, a message displays in the lower right corner, which you can click to install the update. However, to use the NetSuite connector in a production environment, you must have either: * An *Enterprise Mule license*. * A *CloudHub* Starter, Professional, or Enterprise account. Contact the https://www.mulesoft.com/lp/contact[MuleSoft Sales Team] to obtain either of these. (Read more about xref:3.7@mule-runtime::installing-an-enterprise-license.adoc[Installing an Enterprise License].) == Creating a New Project To use the NetSuite connector in a Mule application project: . In Studio, click File > MuleNew > Mule Project. . Enter a name for your new project and leave the remaining options with their default values. + image::netsuite-new-mule-project.png[netsuite_new_mule_project] + . If you plan to use Git, select *Create a .gitignore file* for the project with default ignores for Studio Projects, and click *Next*. . Click *Finish* to create the project. == Configuring the NetSuite Connector Global Element To use the NetSuite connector in your Mule application, you must configure a global NetSuite element that can be used by all the NetSuite connectors in the application (read more about xref:3.7@mule-runtime::global-elements.adoc[global elements]). Not much has changed on this front, and as before (starting from v6.0.0) you are presented with a number of different Global Elements, each representing a different way of authenticating to NetSuite, but this release includes a new method of authentication: *NetSuite: Request Level Token Based Authentication*: [%header,cols=""2*""] |=== |Configuration |Description |*Login Authentication* |Makes use of the SuiteTalks login API call on the first request sent by the connector to establish a session with NetSuite. |*Request Level Authentication* |Using this strategy, you can send user credentials in the SOAP header of each request instead of authenticating to NetSuite by invoking login. |*Single Sign-On Login Authentication* |This is a token based authentication system that avoids the use of environment username and password. Here you supply a privateKey together with other information. The connector is then responsible for generating an authentication token and establishing a session with NetSuite via the `ssoLogin` API call on the first request. |*Request Level Token Based Authentication* |Similar to Single Sign-On Login Authentication, this is a token based authentication system. However, instead of using a privateKey generated via openssl, this uses a consumer and token key/secret pairs which are established within the NetSuite environment. |=== Follow these steps to configure NetSuite connector global element in a Mule application: [.ex] ===== [discrete.view] === Studio Visual Editor . Click the *Global Elements* tab at the base of the canvas. . On the Global Mule Configuration Elements screen, click *Create*. . In the ""Choose Global Type"" wizard, expand *Connector Configuration,* and then select *NetSuite: Login Authentication, NetSuite: Request Level Authentication,* *NetSuite: SSO Login Authentication,* or *NetSuite: Request Level Token Based Authentication* depending on your NetSuite authentication. + image::netsuite-global-configuration.png[netsuite_global_configuration] + . Click *Ok*. . Enter global element properties. .. For *NetSuite: Login Authentication* and *NetSuite: Request Level Authentication*: + [%header,cols=""2*""] |=== |Parameter |Description |*Name* |Enter a name for the configuration with which to reference it later. |*Email* |Enter the login email of the NetSuite UI. |*Password* |Enter the corresponding password to log into NetSuite UI. |*Account* |Enter the account ID of the SuiteTalk NetSuite web services. This is usually found within NetSuite sandbox UI under *Setup* > *Integration* > *Web Service Preferences.* |*Role Id* |Enter the role ID for the user in SuiteTalk, which determines the Processor privileges. |*Application Id* |Enter the application ID corresponding to the Integration record to be used (*New in NetSuite Connector version 7.0.0*). |*Connection Timeout* |Enter the amount of time, in milliseconds, that the client must attempt to establish a connection before timing out. |*Receive Timeout* |Enter the amount of time, in milliseconds, that the client must wait for a response before timing out. |*Enable DataSense* |If you select this option, DataSense extracts metadata for NetSuite standard objects to automatically determine the data type and format that your application must deliver to, or can expect from, NetSuite. By enabling this functionality, Mule does the heavy lifting of discovering the type of data you must send to, or be prepared to receive from NetSuite. For more information, see xref:5@studio::datasense.adoc[DataSense]. |*Endpoint* a| Enter the URL of the service endpoint. [NOTE] Make sure that the endpoint uses the version of NetSuite that the connector supports. |*Separator* |Enter the separator used to support the keys that are required to provide a better support for custom fields. |=== + .. For *NetSuite: SSO Login Authentication:* + To use the SSO Login Authentication, enable this feature in your sandbox environment by NetSuite’s Support. NetSuite provides an SSO Kit and information on how to proceed with setting up private and public keys for use in generating authentication tokens. They also provide you with a Partner ID. After this setup is established, a mapping has to be created between the standard NetSuite credentials, the partner ID, company ID, and user ID. A developer or administrator should perform this mapping. It is not handled by the connector and it is only done once for each user ID that is allowed to authenticate using SSO within your company. + For this mapping, start by generating a token using the SSO Kit provided by NetSuite. To establish the mapping, invoke the SuiteTalks Web Service API call `mapSso` using an external Java application or any other method of your choice. A sample SOAP request of the `mapSso` API call looks as follows: + [source,xml,linenums] ---- Your NetSuite email Your NetSuite password Your NetSuite account Id The token string generated using the SSO kit Your NetSuite partner Id ---- + [%header,cols=""2*""] |=== |Parameter |Description |*Name* |Enter a name for the configuration so it can be referenced later. |*Partner Id* |Enter the partner ID used in the mapping process. |*Partner Account* |Enter the account ID of the SuiteTalk NetSuite web services. |*Company ID* |Enter the company ID used in the mapping process for the connector to generate a token. |*User ID* |Enter the user ID used in the mapping process for the connector to generate a token. |*Key File* |Enter the *privateKey* file name to pick up from the project. This file should be the *.der* file generated as per NetSuite’s specifications. This is used to encrypt the company ID and user ID into a token for *ssoLogin*. |*Application Id* |Enter the application ID corresponding to the Integration record to be used (*New in NetSuite Connector version 7.0.0*). |*Connection Timeout* |Enter the amount of time, in milliseconds, that the client must attempt to establish a connection before timing out. |*Receive Timeout* |Enter the amount of time, in milliseconds, that the client must wait for a response before timing out. |*Enable DataSense* |If you select this option, DataSense extracts metadata for NetSuite standard objects to automatically determine the data type and format that your application must deliver to, or can expect from, NetSuite. By enabling this functionality, Mule does the heavy lifting of discovering the type of data you must send to, or be prepared to receive from NetSuite. For more information, see xref:5@studio::datasense.adoc[DataSense]. |*Endpoint* |Enter the URL of the service endpoint. |*Separator* |Enter the separator used to support the keys that are required to provide a better support for custom fields. |*Required Libraries* |Click Add File to add the SSO jar that you acquire via NetSuite support. |=== + .. For *NetSuite: Request Level Token Based Authentication:* + To use this authentication mechanism you will need to set up an Integration Record within NetSuite and enable Token Based Authentication. This will automatically generate a consumer key and secret for you. + Furthermore you must set up an access token from within your NetSuite environment that combines the Integration Record with a User. This could be done assuming that your NetSuite account has the required permissions enabled in order to generate such tokens and login using them. + Please refer to NetSuite's Help Center or SuiteAnswers for detailed information on how to navigate NetSuite and set this up. + [%header,cols=""2*""] |=== |Parameter |Description |*Consumer Key* |Enter the consumer key value for the token based authentication enabled integration record being used. |*Consumer Secret* |Enter the consumer secret value for the token based authentication enabled integration record being used. |*Token Id* |Enter the token id representing the unique combination of a user and integration generated within the NetSuite environment. |*Token Secret* |Enter the respective token secret for the user/integration pair. |*Account* |Enter the account ID of the SuiteTalk NetSuite web services. This is usually found within NetSuite sandbox UI under *Setup* > *Integration* > *Web Service Preferences.* |*Connection Timeout* |Enter the amount of time, in milliseconds, that the client must attempt to establish a connection before timing out. |*Receive Timeout* |Enter the amount of time, in milliseconds, that the client must wait for a response before timing out. |*Enable DataSense* |If you select this option, DataSense extracts metadata for NetSuite standard objects to automatically determine the data type and format that your application must deliver to, or can expect from, NetSuite. By enabling this functionality, Mule does the heavy lifting of discovering the type of data you must send to, or be prepared to receive from NetSuite. For more information, see xref:5@studio::datasense.adoc[DataSense]. |*Endpoint* a| Enter the URL of the service endpoint. [NOTE] Make sure that the endpoint uses the version of NetSuite that the connector supports. |*Separator* |Enter the separator used to support the keys that are required to provide a better support for custom fields. |=== + . Access the *Pooling Profile* tab to configure any settings relevant to managing multiple connections via a connection pool. . Access the *Reconnection* tab to configure any settings relevant to reconnection strategies that Mule should execute if it loses its connection to NetSuite. . Click *OK* to save the global connector configurations. . Return to the Message Flow tab in Studio. [discrete.view] === XML Editor . Ensure that you include the NetSuite namespaces in your configuration file. + [source,xml,linenums] ---- ---- + . Create a global NetSuite configuration outside and above your flows, using one of the following global configuration codes: + [source,xml,linenums] ---- ---- + [source,xml,linenums] ---- ---- + [source,xml,linenums] ---- ---- + [source,xml,linenums] ---- ---- ===== == Using the Connector NetSuite connector is an operation-based connector, which means that when you add the connector to your flow, you need to configure a specific web service operation for the connector to perform. NetSuite connector v7.1.0 supports 50 operations. === Adding to a Flow . Create a new Mule project in Anypoint Studio. . Add a suitable Mule inbound endpoint, such as the HTTP listener or File endpoint, to begin the flow. . Drag the NetSuite connector onto the canvas, then select it to open the properties editor. . Configure the connector's parameters as follows: + [%header,cols=""2*""] |=== |Field |Description |*Display Name* |Enter a unique label for the connector in your application. |*Config Reference* |Connect to a global element linked to this connector. Global elements encapsulate reusable data about the connection to the target resource or service. Select the global NetSuite connector element you create. |*Operation* |Select the action this component must perform. |=== == Custom Field DataSense In NetSuite one can add different types of custom fields and have these customizations apply to different record types. With DataSense enabled, the NetSuite connector retrieves and shows these fields. Note however that we do not fully support all the customization types that NetSuite users are able to define. The following lists outline what fields we do and do not handle, and where they currently appear in relation to the record type's attributes. For the most part you can see that customizations are usually present within a list field called _customFieldList_, but in some cases these might reside elsewhere. === Entity Fields [%header,cols=""2*""] |=== |Record Type |Custom Field Placement |*CONTACT* |Contact > customFieldList > customField |*CUSTOMER* |Customer > customFieldList > customField |*EMPLOYEE* |Employee > customFieldList > customField |*ENTITY_GROUP* |EntityGroup > customFieldList > customField |*PARTNER* |Partner > customFieldList > customField |*PROJECT_TASK* |ProjectTask > customFieldList > customField |*VENDOR* |Vendor > customFieldList > customField |=== === Item Fields [%header,cols=""2*""] |=== |Record Type |Custom Field Placement |*ASSEMBLY_ITEM* |AssemblyItem > customFieldList > customField |*ENTITY_GROUP* |EntityGroup > customFieldList > customField |*INVENTORY_ITEM* |InventoryItem > customFieldList > customField |*KIT_ITEM* |KitItem > customFieldList > customField |*NON_INVENTORY_PURCHASE_ITEM* |NonInventoryPurchaseItem > customFieldList > customField |*NON_INVENTORY_RESALE_ITEM* |NonInventoryResaleItem > customFieldList > customField |*NON_INVENTORY_SALE_ITEM* |NonInventorySaleItem > customFieldList > customField |*OTHER_CHARGE_PURCHASE_ITEM* |OtherChargePurchaseItem > customFieldList > customField |*OTHER_CHARGE_RESALE_ITEM* |OtherChargeResaleItem > customFieldList > customField |*OTHER_CHARGE_SALE_ITEM* |OtherChargeSaleItem > customFieldList > customField |*SERVICE_PURCHASE_ITEM* |ServicePurchaseItem > customFieldList > customField |*SERVICE_RESALE_ITEM* |ServiceResaleItem > customFieldList > customField |*SERVICE_SALE_ITEM* |ServiceSaleItem > customFieldList > customField |=== === CRM Fields [%header,cols=""2*""] |=== |Record Type |Custom Field Placement |*CALENDAR_EVENT* |CalendarEvent > customFieldList > customField |*CAMPAIGN* |Campaign > customFieldList > customField |*ISSUE* |Issue > customFieldList > customField |*MANUFACTURING_OPERATION_TASK* |ManufacturingOperationTask > customFieldList > customField |*PHONE_CALL* |PhoneCall > customFieldList > customField |*PROJECT_TASK* |ProjectTask > customFieldList > customField |*SOLUTION* |Solution > customFieldList > customField |*SUPPORT_CASE* |SupportCase > customFieldList > customField |*TASK* |Task > customFieldList > customField |=== === Transaction Body Fields [%header,cols=""2*""] |=== |Record Type |Custom Field Placement |*ASSEMBLY_BUILD* |AssemblyBuild > customFieldList > customField |*CASH_SALE* |CashSale > customFieldList > customField |*CUSTOMER_PAYMENT* |CustomerPayment > customFieldList > customField |*DEPOSIT* |Deposit > customFieldList > customField |*ESTIMATE* |Estimate > customFieldList > customField |*EXPENSE_REPORT* |ExpenseReport > customFieldList > customField |*INVENTORY_ADJUSTMENT* |InventoryAdjustment > customFieldList > customField |*INVOICE* |Invoice > customFieldList > customField |*ITEM_FULFILLMENT* |ItemFulfillment > customFieldList > customField |*ITEM_RECEIPT* |ItemReceipt > customFieldList > customField |*JOURNAL_ENTRY* |JournalEntry > customFieldList > customField |*OPPORTUNITY* |Opportunity > customFieldList > customField |*PURCHASE_ORDER* |PurchaseOrder > customFieldList > customField |*PURCHASE_REQUISITION* |PurchaseRequisition > customFieldList > customField |*SALES_ORDER* |SalesOrder > customFieldList > customField |*TRANSFER_ORDER* |TransferOrder > customFieldList > customField |*VENDOR_BILL* |VendorBill > customFieldList > customField |*VENDOR_CREDIT* |VendorCredit > customFieldList > customField |*VENDOR_PAYMENT* |VendorPayment > customFieldList > customField |*VENDOR_RETURN_AUTHORIZATION* |VendorReturnAuthorization > customFieldList > customField |*WORK_ORDER* |WorkOrder > customFieldList > customField |=== === Transaction Column Fields [%header,cols=""2*""] |=== |Record Type |Custom Field Placement |*CASH_SALE* |CashSale > itemList > item > customFieldList > customField |*ESTIMATE* |Estimate > itemList > item > customFieldList > customField |*EXPENSE_REPORT* |ExpenseReport > expenseList > expense > customFieldList > customField |*INVOICE* |Invoice > itemList > item > customFieldList > customField |*ITEM_FULFILLMENT* |ItemFulfillment > itemList > item > customFieldList > customField |*ITEM_RECEIPT* |ItemReceipt > itemList > item > customFieldList > customField |*JOURNAL_ENTRY* |JournalEntry > lineList > line > customFieldList > customField |*OPPORTUNITY* |Opportunity > itemList > item > customFieldList > customField |*PURCHASE_ORDER* |PurchaseOrder > itemList > item > customFieldList > customField |*PURCHASE_REQUISITION* |PurchaseRequisition > itemList > item > customFieldList > customField |*SALES_ORDER* |SalesOrder > itemList > item > customFieldList > customField |*TIME_BILL* |TimeBill > customFieldList > customField |*TRANSFER_ORDER* |TransferOrder > itemList > item > customFieldList > customField |*VENDOR_BILL* |VendorBill > itemList > item > customFieldList > customField |*VENDOR_CREDIT* |VendorCredit > itemList > item > customFieldList > customField |*VENDOR_PAYMENT* |VendorPayment > itemList > item > customFieldList > customField |*VENDOR_RETURN_AUTHORIZATION* |VendorReturnAuthorization > itemList > item > customFieldList > customField |*WORK_ORDER* |WorkOrder > itemList > item > customFieldList > customField |=== === Transaction Item Options Currently DataSense cannot detect NetSuite's Transaction Item Options. === Item Number Fields Currently DataSense cannot detect NetSuite's Item Number Fields. === Other Custom Fields [%header,cols=""2*""] |=== |Record Type |Custom Field Placement |*ACCOUNT* |Account > customFieldList > customField |*BIN* |Bin > customFieldList > customField |*CLASSIFICATION* |Classification > customFieldList > customField |*EXPENSE_CATEGORY* |ExpenseCategory > customFieldList > customField |*ITEM_DEMAND_PLAN* |ItemDemandPlan > customFieldList > customField |*ITEM_SUPPLY_PLAN* |ItemSupplyPlan > customFieldList > customField |*LOCATION* |Location > customFieldList > customField |*MANUFACTURING_COST_TEMPLATE* |ManufacturingCostTemplate > customFieldList > customField |*MANUFACTURING_ROUTING* |ManufacturingRouting > customFieldList > customField |*NOTE* |Note > customFieldList > customField |*PROMOTION_CODE* |PromotionCode > customFieldList > customField |*SUBSIDIARY* |Subsidiary > customFieldList > customField |=== == Example Use Case Add a new Employee record in NetSuite using a Mule application; use Login Authentication. image::netsuitedemoflow.png[NetSuiteDemoFlow] [.ex] ===== [discrete.view] === Studio Visual Editor . Drag an *HTTP* connector into a new flow, and configure it as follows: + image::netsuite-http.jpg[netsuite_http] + [%header,cols=""2*""] |=== |*Field* |Value |*Display Name* |HTTP (or any other name you prefer) |*config-ref* |Configure a global element with the desired host and port, we use 0.0.0.0 and 8081 respectively |*path* |/addEmployee |=== + . Drag the *NetSuite* connector onto the canvas, then select it to open the properties editor console. . Click the *+* sign next to the *Connector Configuration* field to add a new NetSuite global element. + image::netsuite-demonetsuite1.jpg[netsuite_demonetsuite1] + . Configure the global element as follows: + [%header,cols=""2*""] |=== |Field |Value |*Name* |NetSuite (or any other name you prefer) |*Email* | |*Password* | |*Account* | |*Role Id* |Enter the ID of the role you use to login in SuiteTalk, which determines the Processor privileges. |*Application Id* |Enter the application ID corresponding to the Integration record to be used (*New in NetSuite Connector version 7.0.0*). |=== + . In the properties editor of the NetSuite connector, configure the remaining parameters: + image::netsuite-addrecord.jpg[netsuite_addrecord] + [%header%autowidth.spread] |=== |Field |Value |*Display Name* |NetSuite (or any other name you prefer) |*Config Reference* |NetSuite (name of the global element you have created) |*Operation* |Add record |*Record Type* |Employee |=== + . Drag a *Transform Message* transformer before the NetSuite connector, then click the component to open its properties editor. . Once metadata has been retrieved, select the respective fields to populate for the Employee. . The DataWeave script in your Transform Message component should look similar to the following: + [source,json,linenums] ---- %dw 1.0 %output application/java --- { email: inboundProperties.""http.query.params"".email, externalId: inboundProperties.""http.query.params"".externalId, firstName: inboundProperties.""http.query.params"".name, lastName: inboundProperties.""http.query.params"".lastname, subsidiary: { internalId: 3 } } ---- . Add an *Object to JSON* transformer into the flow to capture the response from the NetSuite connector and display it as a HTTP response. . Run the project as a *Mule Application* (right-click the project name in the explorer, then select *Run As* > *Mule Application* ). . From a browser, enter the employee's e-mail address, externalId, lastname, and name in the form of the following query parameters: `http://localhost:8081/addEmployee? email= &externalId= &lastname= &name=` . Mule conducts the query, and adds the Employee record to NetSuite. [discrete.view] === XML Editor . Add a *netsuite:config* element to your project, then configure its attributes according to the table below. + [source,xml,linenums] ---- ---- + [%header%autowidth.spread] |=== |Attribute |Value |*name* |NetSuite |*email* | |*password* | |*account* | |*roleId* |Enter the ID of the role you use to login in SuiteTalk, which determines the Processor privileges. |*Application Id* |Enter the application ID corresponding to the Integration record to be used (*New in NetSuite Connector version 7.0.0*). |*doc:name* |NetSuite |=== + . Create a Mule flow with an HTTP endpoint, configuring the endpoint as follows: + [source,xml,linenums] ---- ---- + [%header,cols=""2*""] |=== |Attribute |Value |*exchange-pattern* |request-response |*host* |localhost |*port* |8081 |*path* a| `accountWithCustomFields` |*doc:name* |HTTP |=== + . Add a *Transform Message* transformer to pass the message payload to NetSuite. + [source,xml,linenums] ---- ---- + . Add a *netsuite:add-record* element to your flow as follows: + [source,xml,linenums] ---- ---- + . Configure the Transform Message through the Visual Editor. Switch the view to Message Flow view, then click the *Transform Message* transformer to set its properties. . Once metadata is retrieved, select the respective fields to populate for the Employee. . The script should look similar to the following: + [source,json,linenums] ---- %dw 1.0 %output application/java --- { email: inboundProperties.""http.query.params"".email, externalId: inboundProperties.""http.query.params"".externalId, firstName: inboundProperties.""http.query.params"".name, lastName: inboundProperties.""http.query.params"".lastname, subsidiary: { internalId: 3 } } ---- . Add a *json:object-to-json-transformer* element to the flow to capture the response from the NetSuite connector and display it as an HTTP response. + [source,xml,linenums] ---- ---- + . Run the project as a Mule Application (right-click project name, then select *Run As > Mule Application*). . From a browser, enter the employee's e-mail address, externalId, lastname, and name in the form of the following query parameters: `http://localhost:8081/accountWithCustomFields ?email = &externalId= &lname= &name=` . Mule conducts the query, and adds the Employee record to NetSuite. ===== == Example Use Case Code [NOTE] ==== Note that for this example code to work, you must manually configure the following values of the *global element for your NetSuite connector* to match your instance of NetSuite: * Email * Password * Account * Role ID * Application ID ==== [source,xml,linenums] ---- ---- == Other Code Examples === Working with Asynchronous Operations This code example demonstrates how to use `async-add-list` together with the `check-async-status`, `get-async-result`, and `delete` operations, using a custom record type. [NOTE] ==== Note that for this example code to work, you must use a custom record type of your own (or just a regular type), and manually configure the following values of the global NetSuite config to match your instance of NetSuite: * email * password * account * roleId * applicationId ==== image::netsuite-async1.jpg[netsuite_async1] [source,xml,linenums] ---- addListExt1 addListName1 addListExt2 addListName2 #[payload.getBaseRef().getTypeId()] ---- *Code Description* . `netsuite:config-login-authentication` is the NetSuite global configuration. . The first flow, labeled ""asyncAddList"" is triggered via an HTTP request. . `netsuite:async-add-list` provides the configuration for the `async-add-list` operation showing `externalIds` and names we defined for the custom record. . Store the `jobId` returned from the `async-add-list` operation in a flow variable called ""jobId"". See `set-variable`. . Calls a sub-flow named ""check_async_status"" that monitors the status of the async process. . The `until-successful` block queries NetSuite using the `check-async-result` operation to see whether the async job is finished or pending/processing. This loops for a number of defined retries and resumes control of the flow after the condition is satisfied. . A `choice` router directs the message based on whether the async operation finished successfully or not. . Displays a message in the console notifying that the async process is successful. . Displays a message in the console if it has failed. . The second flow is also triggered via an HTTP request, passing the `jobId` as a query parameter. . Uses the `get-async-result` operation to obtain the result for the async process using the `jobId` that is saved. . Extracts the response list from the `AsyncResult` object. . For each result list item, logs some details and delete the record we added. . Removes the custom records that are just added from the NetSuite sandbox using their `externalId`. === Using the Search Operation In NetSuite, the `search` operation can be used to execute a *Basic Search*, *Joined Search* or an *Advanced Search*. To this end, you need to instantiate one of these three search types for the record type you want to query: [cols=""2*""] |=== |`SearchBasic`|Used to execute a search on a record type based on search filter fields that are specific to that type. |`Search` + |Used to execute a search on a record type based on search filter fields specific to that type and others that are associated with a related record type. |`SearchAdvanced` + |Used to execute a search on a record type in which you specify search filter fields and/or search return columns or joined search columns. Using advanced search, you can also return an existing saved search. |=== This also applies for the asynchronous equivalent of search, the `asyncSearch` operation. ==== Search Pagination Support Support for pagination was added to `search` for NetSuite connector version 7.0.0. The connector's search capability is now unified under one operation. Other search-related processors have been removed. Thus, `search` will always retrieve the whole set of results. Therefore users will *not* need to work with `searchNext` or `searchMore` in order to get the rest of the records from subsequent pages. The return type is also different; the processor will output a List of Maps representing each and every record obtained by your search criteria. An important aspect to note is that pagination could not be applied to the asynchronous equivalent of `search` (`asyncSearch`). This is due to the fact that the actual pagination would have to be applied to the `getAsyncResult` operation. This would mean that only the first page would end up being retrieved asynchronously. Furthermore, `getAsyncResult` is common to all async operations. Hence we cannot even apply pagination here since the return type of this operation depends on what async operation was invoked. Regarding the new *search* configuration, the connector is the same apart from a new attribute called `fetchSize`: [source,xml,linenums] ---- ---- ==== ItemSearchAdvanced and returnSearchColumns When using `search`, the connector outputs a list of maps representing the Record objects returned by your `search` operation. If using an advanced search and the `returnSearchColumns` flag is set to true, NetSuite returns a `SearchRowList` containing the search results. However, in the case of `ItemSearchAdvanced` the connector does not do this mapping and simply provides the user with the SearchRows. This is the case due to the fact that ITEMs in NetSuite can be of various types and we cannot assume the item type from an `ItemSearchRow`. This issue would also occur with any other record type that behaves similar to `ITEM`, but we are currently not aware of others. ==== Example of Basic Search For this example, we set up a basic search operation for Customers (`CustomerSearchBasic`) with the criteria below: * `companyName` starts with ""A"". * The customer is not an individual. * The customer has a priority of 50, which is handled by a `customField`. Below is the Studio flow and the corresponding code: image::netsuite-basic-search.jpg[netsuite_basic_search] [source,xml,linenums] ---- ---- *Java Component Code* [source,java,linenums] ---- public class CustomerBasicSearchComponent implements Callable { @Override public Object onCall(MuleEventContext eventContext) throws Exception { CustomerSearchBasic searchCriteria = new CustomerSearchBasic(); SearchStringField companyNameFilter = new SearchStringField(); companyNameFilter.setOperator(SearchStringFieldOperator.STARTS_WITH); companyNameFilter.setSearchValue(""A""); searchCriteria.setCompanyName(companyNameFilter); SearchBooleanField isPersonFilter = new SearchBooleanField(); isPersonFilter.setSearchValue(false); searchCriteria.setIsPerson(isPersonFilter); SearchCustomFieldList customFieldListFilter = new SearchCustomFieldList(); List customFieldList = new ArrayList(); SearchLongCustomField priority = new SearchLongCustomField(); priority.setScriptId(""custentity_cust_priority""); priority.setOperator(SearchLongFieldOperator.EQUAL_TO); priority.setSearchValue(50l); customFieldList.add(priority); customFieldListFilter.setCustomField(customFieldList); searchCriteria.setCustomFieldList(customFieldListFilter); return searchCriteria; } } ---- ==== Example of a Joined Search This example here searches for all inventory items with a pricing join (ItemSearch) where the price rate is of 10.00. + The search criteria is set within a custom Java component. image::netsuite-joined-search.jpg[netsuite_joined_search] [source,xml,linenums] ---- ---- *Java Component Code* [source,java,linenums] ---- public class ItemSearchPricingJoinComponent implements Callable { @Override public Object onCall(MuleEventContext eventContext) throws Exception { ItemSearch searchCriteria = new ItemSearch(); ItemSearchBasic basicCriteria = new ItemSearchBasic(); SearchEnumMultiSelectField typeFilter = new SearchEnumMultiSelectField(); List typeList = new ArrayList(); typeList.add(""_inventoryItem""); typeFilter.setOperator(SearchEnumMultiSelectFieldOperator.ANY_OF); typeFilter.setSearchValue(typeList); basicCriteria.setType(typeFilter); searchCriteria.setBasic(basicCriteria); PricingSearchBasic pricingJoinCriteria = new PricingSearchBasic(); SearchDoubleField rateFilter = new SearchDoubleField(); rateFilter.setOperator(SearchDoubleFieldOperator.EQUAL_TO); rateFilter.setSearchValue(10.00d); pricingJoinCriteria.setRate(rateFilter); searchCriteria.setPricingJoin(pricingJoinCriteria); return searchCriteria; } } ---- ==== Example of Advanced Search The example constructs a simple Java component that creates a criteria to get the result of an Employee saved search in our NetSuite environment (EmployeeSearchAdvanced). Each saved search in NetSuite has a particular id. Here, we use the scriptId customsearch130. image::netsuite-code-example-search-advanced.jpg[netsuite_code_example_search_advanced] [source,xml,linenums] ---- ---- *Java Component Code* [source,java,linenums] ---- public class EmployeeSearchAdvancedSavedComponent implements Callable { @Override public Object onCall(MuleEventContext eventContext) throws Exception { EmployeeSearchAdvanced searchCriteria = new EmployeeSearchAdvanced(); searchCriteria.setSavedSearchScriptId(""customsearch130""); return searchCriteria; } } ---- === NetSuite and DataWeave The NetSuite connector’s DataSense capability coupled with that of DataWeave via the Transform Message component makes integrating with your NetSuite environment straightforward. For the following two examples, we use a JSON input string and extract the necessary data from it to form our NetSuite request. . This example code adds a Journal Entry to NetSuite from the following JSON input: + [source,json,linenums] ---- { ""tranId"":""SampleJournal123"", ""subsidiary"":{ ""internalId"":""1"" }, ""customFieldList"":{ ""customField"":[ { ""StringCustomFieldRef__custbodytestbodyfield"":""Sample Transaction Body Custom Field"" } ] }, ""lineList"":{ ""line"":[ { ""account"":{ ""internalId"":""1"" }, ""debit"":100.0, ""customFieldList"":{ ""customField"":[ { ""SelectCustomFieldRef__custcol_far_trn_relatedasset"":{ ""internalId"":""1"" } }, { ""StringCustomFieldRef__custcoltestcolumnfield"": ""Sample Transaction Column Custom Field 1"" } ] } }, { ""account"":{ ""internalId"":""1"" }, ""credit"":100.0, ""customFieldList"":{ ""customField"":[ { ""SelectCustomFieldRef__custcol_far_trn_relatedasset"":{ ""internalId"":""2"" } }, { ""StringCustomFieldRef__custcoltestcolumnfield"": ""Sample Transaction Column Custom Field 2"" } ] } } ] } } ---- + The ""add"" operation for the connector expects a Map as input. The DataWeave script looks as follows: + image::netsuite-dataweave1.jpg[netsuite_dataweave1] + . In this example, we use the same scenario for basic search as described in the previous section. However, instead of constructing the criteria in a java component, we transform a JSON string: + [source,json,linenums] ---- { ""companyName"": { ""operator"": ""STARTS_WITH"", ""searchValue"": ""A"" }, ""isPerson"": false, ""priority"": { ""operator"": ""EQUAL_TO"", ""searchValue"": 50 } } ---- + image::netsuite-code-example-dataweave02.jpg[netsuite_code_example_dataweave02] == See Also * Learn more about working with xref:3.7@mule-runtime::anypoint-connectors.adoc[Anypoint Connectors]. * xref:release-notes::connector/netsuite-connector-release-notes.adoc[NetSuite Connector Release Notes]. * https://www.mulesoft.com/exchange/org.mule.modules/mule-module-netsuite/[NetSuite Connector on Exchange] ",12278,False,1896.228048294749,median "/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the ""License"");; you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include #include ""Python.h"" #include ""absl/strings/str_format.h"" #include ""pybind11/chrono.h"" #include ""pybind11/complex.h"" #include ""pybind11/functional.h"" #include ""pybind11/pybind11.h"" #include ""pybind11/stl.h"" #include ""tensorflow/c/c_api.h"" #include ""tensorflow/c/c_api_experimental.h"" #include ""tensorflow/c/eager/c_api.h"" #include ""tensorflow/c/eager/c_api_experimental.h"" #include ""tensorflow/c/eager/c_api_internal.h"" #include ""tensorflow/c/eager/dlpack.h"" #include ""tensorflow/c/eager/tfe_tensorhandle_internal.h"" #include ""tensorflow/c/tf_status.h"" #include ""tensorflow/c/tf_status_helper.h"" #include ""tensorflow/compiler/jit/flags.h"" #include ""tensorflow/compiler/jit/get_compiler_ir.h"" #include ""tensorflow/python/eager/pywrap_tensor_conversion.h"" #include ""tensorflow/python/eager/pywrap_tfe.h"" #include ""tensorflow/python/lib/core/py_exception_registry.h"" #include ""tensorflow/python/lib/core/pybind11_lib.h"" #include ""tensorflow/python/lib/core/pybind11_status.h"" #include ""tensorflow/python/lib/core/safe_ptr.h"" #include ""tensorflow/python/lib/core/safe_pyobject_ptr.h"" #include ""tensorflow/python/util/util.h"" namespace py = pybind11; PYBIND11_MAKE_OPAQUE(TFE_Executor); PYBIND11_MAKE_OPAQUE(TFE_ContextOptions); PYBIND11_MAKE_OPAQUE(TFE_CancellationManager); PYBIND11_MAKE_OPAQUE(TFE_MonitoringCounter0); PYBIND11_MAKE_OPAQUE(TFE_MonitoringCounter1); PYBIND11_MAKE_OPAQUE(TFE_MonitoringCounter2); PYBIND11_MAKE_OPAQUE(TFE_MonitoringStringGauge0); PYBIND11_MAKE_OPAQUE(TFE_MonitoringStringGauge1); PYBIND11_MAKE_OPAQUE(TFE_MonitoringStringGauge2); PYBIND11_MAKE_OPAQUE(TFE_MonitoringIntGauge0); PYBIND11_MAKE_OPAQUE(TFE_MonitoringIntGauge1); PYBIND11_MAKE_OPAQUE(TFE_MonitoringIntGauge2); PYBIND11_MAKE_OPAQUE(TFE_MonitoringBoolGauge0); PYBIND11_MAKE_OPAQUE(TFE_MonitoringBoolGauge1); PYBIND11_MAKE_OPAQUE(TFE_MonitoringBoolGauge2); PYBIND11_MAKE_OPAQUE(TFE_MonitoringSampler0); PYBIND11_MAKE_OPAQUE(TFE_MonitoringSampler1); PYBIND11_MAKE_OPAQUE(TFE_MonitoringSampler2); PYBIND11_MAKE_OPAQUE(TFE_MonitoringCounterCell); PYBIND11_MAKE_OPAQUE(TFE_MonitoringIntGaugeCell); PYBIND11_MAKE_OPAQUE(TFE_MonitoringStringGaugeCell); PYBIND11_MAKE_OPAQUE(TFE_MonitoringBoolGaugeCell); PYBIND11_MAKE_OPAQUE(TFE_MonitoringSamplerCell); PYBIND11_MAKE_OPAQUE(TF_DeviceList); PYBIND11_MAKE_OPAQUE(TF_Function); PYBIND11_MAKE_OPAQUE(TF_Buffer); // Eager helper functions migrated from pywrap_tfe.i. namespace tensorflow { // We cannot use Context as an opaque type. SWIG also had // difficult directly passing the pointer around. These // typemaps are migrated over from pywrap_tfe.i. I tried // using a custom type caster, but we get segfaults periodically. // TODO(amitpatankar): Move input and output logic of Context into a // pybind11 custom type caster. TFE_Context* InputTFE_Context(const py::handle& ctx) { return static_cast(PyCapsule_GetPointer(ctx.ptr(), nullptr)); } PyObject* OutputTFE_Context(TFE_Context* context) { return PyCapsule_New(context, nullptr, TFE_DeleteContextCapsule); } TF_Buffer* ProtoStringToTFBuffer(PyObject* input) { // Convert a Python string object to TF_Buffer. char* c_string; Py_ssize_t py_size; // PyBytes_AsStringAndSize() does not copy but simply interprets the input if (PyBytes_AsStringAndSize(input, &c_string, &py_size) == -1) { // Python has raised an error (likely TypeError or UnicodeEncodeError). throw py::error_already_set(); } return TF_NewBufferFromString(static_cast(c_string), static_cast(py_size)); } // These functions are typemaps from the Python side. I did not use // a custom type caster since the logic is slightly harder to follow. This // converter is also only used once in `TFE_Py_ExecuteCancelable_wrapper`. TFE_InputTensorHandles InputTFE_InputTensorHandles( const py::handle& input_tensors) { TFE_InputTensorHandles input_tensor_handles; if (input_tensors.ptr() != Py_None) { if (!PyList_Check(input_tensors.ptr())) { tensorflow::ThrowTypeError(""must provide a list of Tensors as inputs""); } Py_ssize_t len = PyList_Size(input_tensors.ptr()); input_tensor_handles.resize(len); for (Py_ssize_t i = 0; i < len; ++i) { PyObject* elem = PyList_GetItem(input_tensors.ptr(), i); if (!elem) { tensorflow::ThrowTypeError(""Input Tensor does not exist.""); } if (EagerTensor_CheckExact(elem)) { (input_tensor_handles)[i] = EagerTensor_Handle(elem); } else if (tensorflow::swig::IsEagerTensorSlow(elem)) { // Use equivalent of object.__getattribute__ to get the underlying // tf wrapped EagerTensor (if there is one). tensorflow::Safe_PyObjectPtr tf_should_use_attr( #if PY_MAJOR_VERSION < 3 PyString_InternFromString(""_tf_should_use_wrapped_value"") #else PyUnicode_InternFromString(""_tf_should_use_wrapped_value"") #endif ); tensorflow::Safe_PyObjectPtr value_attr( PyObject_GenericGetAttr(elem, tf_should_use_attr.get())); if (value_attr) { // This is an EagerTensor wrapped inside a TFShouldUse wrapped object. (input_tensor_handles)[i] = EagerTensor_Handle(value_attr.get()); } else { // This is a subclass of EagerTensor that we don't support. PyErr_Clear(); tensorflow::ThrowTypeError( tensorflow::strings::StrCat( ""Saw an object that is an instance of a strict subclass of "" ""EagerTensor, which is not supported. Item "", i, "" is type: "", elem->ob_type->tp_name) .c_str()); } } else if (tensorflow::swig::IsTensor(elem)) { // If it isnt an EagerTensor, but is still a Tensor, it must be a graph // tensor. tensorflow::Safe_PyObjectPtr name_attr( PyObject_GetAttrString(elem, ""name"")); tensorflow::ThrowTypeError( tensorflow::strings::StrCat( ""An op outside of the function building code is being passed\\n"" ""a \\""Graph\\"" tensor. It is possible to have Graph tensors\\n"" ""leak out of the function building context by including a\\n"" ""tf.init_scope in your function building code.\\n"" ""For example, the following function will fail:\\n"", "" @tf.function\\n"", "" def has_init_scope():\\n"", "" my_constant = tf.constant(1.)\\n"", "" with tf.init_scope():\\n"", "" added = my_constant * 2\\n"", ""The graph tensor has name: "", name_attr ? TFE_GetPythonString(name_attr.get()) : """") .c_str()); } else { tensorflow::ThrowTypeError( tensorflow::strings::StrCat( ""provided list of inputs contains objects other "" ""than 'EagerTensor'. Item "", i, "" is type: "", elem->ob_type->tp_name) .c_str()); } } } return input_tensor_handles; } // These functions are typemaps from the Python side. I did not use // a custom type caster since the logic is slightly harder to follow. This // converter is also only used once in `TFE_Py_ExecuteCancelable_wrapper`. // This function actually takes a number rather than an output Tensor holder. TFE_OutputTensorHandles InputTFE_OutputTensorHandles( const py::handle& num_outputs) { TFE_OutputTensorHandles output_tensor_handles; #if PY_MAJOR_VERSION < 3 if (!PyInt_Check(num_outputs.ptr())) { #else if (!PyLong_Check(num_outputs.ptr())) { #endif PyErr_SetString(PyExc_TypeError, ""expected an integer value (size of the number of "" ""outputs of the operation)""); throw py::error_already_set(); } #if PY_MAJOR_VERSION < 3 long sz = PyInt_AsLong(num_outputs.ptr()); // NOLINT #else long sz = PyLong_AsLong(num_outputs.ptr()); // NOLINT #endif if (sz > 0) { #if PY_MAJOR_VERSION < 3 output_tensor_handles.resize(PyInt_AsLong(num_outputs.ptr()), nullptr); #else output_tensor_handles.resize(PyLong_AsLong(num_outputs.ptr()), nullptr); #endif } return output_tensor_handles; } // Packs multiple `EagerTensor`s of the same dtype and shape into one // `EagerTensor`. py::object TFE_Py_PackEagerTensors_wrapper(const py::handle& context, const py::handle& tensors) { TFE_Context* ctx = tensorflow::InputTFE_Context(context); TFE_InputTensorHandles handles = InputTFE_InputTensorHandles(tensors); tensorflow::Safe_TF_StatusPtr status = tensorflow::make_safe(TF_NewStatus()); int size = handles.size(); TFE_TensorHandle* packed_handle = TFE_CreatePackedTensorHandle(ctx, handles.data(), &size, status.get()); tensorflow::MaybeRaiseRegisteredFromTFStatus(status.get()); PyObject* packed_tensor = EagerTensorFromHandle(packed_handle, /*is_packed=*/true); return tensorflow::PyoOrThrow(packed_tensor); } // This function was created from fusing the typemap logic in platform/base.i. py::object TFE_Py_ExecuteCancelable_wrapper( const py::handle& context, const char* device_name, const char* op_name, const py::handle& inputs, const py::handle& attrs, TFE_CancellationManager* cancellation_manager, const py::handle& num_outputs) { TFE_Context* ctx = tensorflow::InputTFE_Context(context); TFE_InputTensorHandles input_tensor_handles = InputTFE_InputTensorHandles(inputs); TFE_OutputTensorHandles output_tensor_handles = InputTFE_OutputTensorHandles(num_outputs); tensorflow::Safe_TF_StatusPtr status = tensorflow::make_safe(TF_NewStatus()); TFE_Py_ExecuteCancelable(ctx, device_name, op_name, &input_tensor_handles, attrs.ptr(), cancellation_manager, &output_tensor_handles, status.get()); int output_len = output_tensor_handles.size(); PyObject* output_list = PyList_New(output_len); for (int i = 0; i < output_len; ++i) { PyObject* output; output = EagerTensorFromHandle(output_tensor_handles.at(i)); PyList_SetItem(output_list, i, output); } tensorflow::MaybeRaiseRegisteredFromTFStatus(status.get()); return tensorflow::PyoOrThrow(output_list); } static py::object TF_ListPhysicalDevices() { std::vector devices; tensorflow::Status s = tensorflow::DeviceFactory::ListAllPhysicalDevices(&devices); MaybeRaiseRegisteredFromStatus(s); PyObject* result = PyList_New(devices.size()); int i = 0; for (auto& dev : devices) { PyObject* dev_obj = PyBytes_FromStringAndSize(dev.data(), dev.size()); PyList_SetItem(result, i, dev_obj); ++i; } return tensorflow::PyoOrThrow(result); } static std::unordered_map TF_GetDeviceDetails(int index) { tensorflow::Safe_TF_StatusPtr status = tensorflow::make_safe(TF_NewStatus()); std::unordered_map device_details; tensorflow::Status s = tensorflow::DeviceFactory::GetAnyDeviceDetails(index, &device_details); tensorflow::Set_TF_Status_from_Status(status.get(), s); MaybeRaiseRegisteredFromTFStatus(status.get()); return device_details; } static py::object TFE_ClearScalarCache() { tensorflow::TFE_TensorHandleCache::Get()->Clear(); return py::none(); } // Returns compiler IR for a given function. static std::string TFE_GetCompilerIr(py::handle& ctx, const char* concrete_function_name, const char* stage, const char* device_name, py::handle& inputs) { EagerContext* context = ContextFromInterface( reinterpret_cast(InputTFE_Context(ctx))); std::string s_stage(stage); IrExportStage selected_stage = [&] { if (s_stage == ""hlo"") { return IrExportStage::HLO; } else if (s_stage == ""optimized_hlo"") { return IrExportStage::OPTIMIZED_HLO; } else if (s_stage == ""optimized_hlo_dot"") { return IrExportStage::OPTIMIZED_HLO_DOT; } else { ThrowValueError( absl::StrFormat(""Invalid stage selected: '%s'. Valid values are: "" ""'hlo', 'optimized_hlo', 'optimized_hlo_dot'"", s_stage) .c_str()); } }(); TFE_InputTensorHandles handles = InputTFE_InputTensorHandles(inputs); std::vector input_handles; for (TFE_TensorHandle* tensor_handle : handles) { AbstractTensorHandle* abstract_tensor_handle = unwrap(tensor_handle); input_handles.push_back(TensorHandleFromInterface(abstract_tensor_handle)); } DeviceNameUtils::ParsedName input_device_name; if (!DeviceNameUtils::ParseFullOrLocalName(device_name, &input_device_name)) { ThrowValueError( absl::StrFormat(""Failed parsing device name: '%s'"", device_name) .c_str()); } std::vector devices = context->local_device_mgr()->ListDevices(); auto selected_device = absl::c_find_if(devices, [&](const Device* d) { return DeviceNameUtils::AreCompatibleDevNames(input_device_name, d->parsed_name()); }); if (selected_device == devices.end()) { ThrowValueError(""No matching device found""); } xla::StatusOr hlo_text = GetCompilerIr(selected_stage, context->pflr(), concrete_function_name, *selected_device, context, input_handles); if (!hlo_text.ok()) { ThrowValueError(absl::StrFormat(""Failed getting HLO text: '%s'"", hlo_text.status().error_message()) .c_str()); } return *hlo_text; } } // namespace tensorflow namespace { // Wrapper around the EagerContextThreadLocalData struct (defined in // pywrap_tfe.h), so it can be accessed from Python. // // For PyObject* fields, the get_*() methods return a new reference; and the // set_*() methods create a new reference (i.e., they do not steal a reference). class EagerContextThreadLocalDataWrapper { public: explicit EagerContextThreadLocalDataWrapper(py::handle py_eager_context, py::handle is_eager, py::handle device_spec) : py_eager_context_(py_eager_context.ptr()) { tensorflow::MakeEagerContextThreadLocalData( py_eager_context.ptr(), is_eager.ptr(), device_spec.ptr()); } ~EagerContextThreadLocalDataWrapper() { tensorflow::DestroyEagerContextThreadLocalData(py_eager_context_); } bool get_is_eager() const { return GetData()->is_eager; } void set_is_eager(bool v) { GetData()->is_eager = v; } bool get_invoking_op_callbacks() const { return GetData()->invoking_op_callbacks; } void set_invoking_op_callbacks(bool v) { GetData()->invoking_op_callbacks = v; } py::handle get_device_name() const { return GetPyObject(&GetData()->device_name); } void set_device_name(py::handle v) { SetPyObject(v, &GetData()->device_name); } py::handle get_scope_name() const { return GetPyObject(&GetData()->scope_name); } void set_scope_name(py::handle v) { SetPyObject(v, &GetData()->scope_name); } py::handle get_device_spec() const { return GetPyObject(&GetData()->device_spec); } void set_device_spec(py::handle v) { SetPyObject(v, &GetData()->device_spec); } py::handle get_function_call_options() const { return GetPyObject(&GetData()->function_call_options); } void set_function_call_options(py::handle v) { SetPyObject(v, &GetData()->function_call_options); } py::handle get_executor() const { return GetPyObject(&GetData()->executor); } void set_executor(py::handle v) { SetPyObject(v, &GetData()->executor); } py::handle get_op_callbacks() const { return GetPyObject(&GetData()->op_callbacks); } void set_op_callbacks(py::handle v) { SetPyObject(v, &GetData()->op_callbacks); } private: tensorflow::EagerContextThreadLocalData* GetData() const { auto* result = tensorflow::GetEagerContextThreadLocalData(py_eager_context_); if (!result) { throw py::error_already_set(); } return result; } py::handle GetPyObject(tensorflow::Safe_PyObjectPtr* obj) const { Py_INCREF(obj->get()); return obj->get(); } void SetPyObject(py::handle value, tensorflow::Safe_PyObjectPtr* ptr) { Py_INCREF(value.ptr()); ptr->reset(value.ptr()); } PyObject* py_eager_context_; // not owned (borrowed reference). }; } // namespace // py::return_value_policy::reference is defined as specified by the // pybind11 documents listed here. // https://pybind11.readthedocs.io/en/stable/advanced/functions.html#return-value-policies // This means that C++ maintains ownership of the object. We // are only assigning this to functions that return opaque types. PYBIND11_MODULE(_pywrap_tfe, m) { py::class_ TFE_Executor_class(m, ""TFE_Executor""); py::class_ TFE_ContextOptions_class(m, ""TFE_ContextOptions""); py::class_ TFE_MonitoringCounter0_class( m, ""TFE_MonitoringCounter0""); py::class_ TFE_MonitoringCounter1_class( m, ""TFE_MonitoringCounter1""); py::class_ TFE_MonitoringCounter2_class( m, ""TFE_MonitoringCounter2""); py::class_ TFE_MonitoringStringGauge0_class( m, ""TFE_MonitoringStringGauge0""); py::class_ TFE_MonitoringStringGauge1_class( m, ""TFE_MonitoringStringGauge1""); py::class_ TFE_MonitoringStringGauge2_class( m, ""TFE_MonitoringStringGauge2""); py::class_ TFE_MonitoringIntGauge0_class( m, ""TFE_MonitoringIntGauge0""); py::class_ TFE_MonitoringIntGauge1_class( m, ""TFE_MonitoringIntGauge1""); py::class_ TFE_MonitoringIntGauge2_class( m, ""TFE_MonitoringIntGauge2""); py::class_ TFE_MonitoringBoolGauge0_class( m, ""TFE_MonitoringBoolGauge0""); py::class_ TFE_MonitoringBoolGauge1_class( m, ""TFE_MonitoringBoolGauge1""); py::class_ TFE_MonitoringBoolGauge2_class( m, ""TFE_MonitoringBoolGauge2""); py::class_ TFE_MonitoringCounterCell_class( m, ""TFE_MonitoringCounterCell""); py::class_ TFE_MonitoringIntGaugeCell_class( m, ""TFE_MonitoringIntGaugeCell""); py::class_ TFE_MonitoringStringGaugeCell_class( m, ""TFE_MonitoringStringGaugeCell""); py::class_ TFE_MonitoringBoolGaugeCell_class( m, ""TFE_MonitoringBoolGaugeCell""); py::class_ TFE_MonitoringSamplerCell_class( m, ""TFE_MonitoringSamplerCell""); py::class_ TFE_MonitoringBuckets_class( m, ""TFE_MonitoringBuckets""); py::class_ TFE_MonitoringSampler0_class( m, ""TFE_MonitoringSampler0""); py::class_ TFE_MonitoringSampler1_class( m, ""TFE_MonitoringSampler1""); py::class_ TFE_MonitoringSampler2_class( m, ""TFE_MonitoringSampler2""); py::class_ TFE_CancellationManager_class( m, ""TFE_CancellationManager""); py::class_ TF_DeviceList_class(m, ""TF_DeviceList""); py::class_ TF_Function_class(m, ""TF_Function""); m.def(""TFE_Py_RegisterExceptionClass"", [](const py::handle& e) { return tensorflow::PyoOrThrow(TFE_Py_RegisterExceptionClass(e.ptr())); }); m.def(""TFE_Py_RegisterFallbackExceptionClass"", [](const py::handle& e) { return tensorflow::PyoOrThrow( TFE_Py_RegisterFallbackExceptionClass(e.ptr())); }); m.def( ""TFE_GetTotalMemoryUsage"", [](py::handle& ctx, const char* device_name) { tensorflow::EagerContext* context = tensorflow::ContextFromInterface( reinterpret_cast( tensorflow::InputTFE_Context(ctx))); tensorflow::DeviceNameUtils::ParsedName input_device_name; if (!tensorflow::DeviceNameUtils::ParseFullOrLocalName( device_name, &input_device_name)) { tensorflow::ThrowValueError( absl::StrFormat(""Failed parsing device name: '%s'"", device_name) .c_str()); } std::vector devices = context->local_device_mgr()->ListDevices(); tensorflow::Device* matched_device = nullptr; for (int device_idx = 0; device_idx < devices.size(); device_idx++) { tensorflow::Device* device = devices[device_idx]; if (tensorflow::DeviceNameUtils::AreCompatibleDevNames( input_device_name, device->parsed_name())) { if (device->device_type() == tensorflow::DEVICE_CPU) { tensorflow::ThrowValueError( ""CPU does not support getting allocator information""); } if (matched_device != nullptr) { tensorflow::ThrowValueError( absl::StrFormat( ""Multiple devices matching the provided string "" ""'%s': '%s' and "" ""'%s' "", device_name, matched_device->name(), device->name()) .c_str()); } matched_device = device; } } if (matched_device == nullptr) { tensorflow::ThrowValueError( absl::StrFormat(""No matching devices found for '%s'"", device_name) .c_str()); } tensorflow::AllocatorAttributes attrs; tensorflow::Allocator* allocator = matched_device->GetAllocator(attrs); if (absl::optional stats = allocator->GetStats()) { return stats->bytes_in_use; } tensorflow::ThrowTypeError( absl::StrFormat(""Allocator stats not available for device '%s'"", matched_device->name()) .c_str()); }); // XLA Eager Logic m.def(""TF_SetXlaEnableLazyCompilation"", &TF_SetXlaEnableLazyCompilation); m.def(""TF_SetTfXlaCpuGlobalJit"", &TF_SetTfXlaCpuGlobalJit); m.def(""TF_SetXlaAutoJitMode"", &TF_SetXlaAutoJitMode); m.def(""TF_SetXlaConstantFoldingDisabled"", &TF_SetXlaConstantFoldingDisabled); m.def(""TF_GetXlaConstantFoldingDisabled"", &TF_GetXlaConstantFoldingDisabled); m.def(""TF_SetXlaMinClusterSize"", &TF_SetXlaMinClusterSize); m.def(""TF_GetCompilerIr"", &tensorflow::TFE_GetCompilerIr); // MLIR Logic m.def(""TF_IsMlirBridgeEnabled"", [] { return tensorflow::GetMlirCommonFlags()->tf_mlir_enable_mlir_bridge == tensorflow::ConfigProto::Experimental::MLIR_BRIDGE_ROLLOUT_ENABLED; }); m.def(""TF_EnableMlirBridge"", [](bool enabled) { tensorflow::GetMlirCommonFlags()->tf_mlir_enable_mlir_bridge = enabled ? tensorflow::ConfigProto::Experimental::MLIR_BRIDGE_ROLLOUT_ENABLED : tensorflow::ConfigProto::Experimental:: MLIR_BRIDGE_ROLLOUT_DISABLED; }); m.def(""TF_EnableXlaDevices"", [] { tensorflow::GetXlaDeviceFlags()->tf_xla_enable_xla_devices = true; }); // // TFE_Context Logic m.def( ""TFE_NewContext"", [](const TFE_ContextOptions* opts) { tensorflow::Safe_TF_StatusPtr status = tensorflow::make_safe(TF_NewStatus()); TFE_Context* context = TFE_NewContext(opts, status.get()); tensorflow::MaybeRaiseRegisteredFromTFStatus(status.get()); return tensorflow::PyoOrThrow(tensorflow::OutputTFE_Context(context)); }, py::return_value_policy::reference); m.def(""TFE_DeleteContext"", [](py::handle& o) { TFE_DeleteContext(tensorflow::InputTFE_Context(o)); }); m.def( ""TFE_ContextListDevices"", [](py::handle& o) { tensorflow::Safe_TF_StatusPtr status = tensorflow::make_safe(TF_NewStatus()); auto output = TFE_ContextListDevices(tensorflow::InputTFE_Context(o), status.get()); tensorflow::MaybeRaiseRegisteredFromTFStatus(status.get()); return output; }, py::return_value_policy::reference); m.def(""TFE_HostAddressSpace"", [](py::handle& o, TF_Buffer& buf) { TFE_HostAddressSpace(tensorflow::InputTFE_Context(o), &buf); }); m.def(""TFE_ContextAddFunction"", [](py::handle& ctx, TF_Function* func) { tensorflow::Safe_TF_StatusPtr status = tensorflow::make_safe(TF_NewStatus()); TFE_ContextAddFunction(tensorflow::InputTFE_Context(ctx), func, status.get()); tensorflow::MaybeRaiseRegisteredFromTFStatus(status.get()); }); m.def(""TFE_ContextAddFunctionDef"", [](py::handle& ctx, const char* serialized_function_def, size_t size) { tensorflow::Safe_TF_StatusPtr status = tensorflow::make_safe(TF_NewStatus()); TFE_ContextAddFunctionDef(tensorflow::InputTFE_Context(ctx), serialized_function_def, size, status.get()); tensorflow::MaybeRaiseRegisteredFromTFStatus(status.get()); }); m.def(""TFE_ContextGetFunctionDef"", [](py::handle& ctx, const char* function_name, TF_Buffer& buf) { tensorflow::Safe_TF_StatusPtr status = tensorflow::make_safe(TF_NewStatus()); TFE_ContextGetFunctionDef(tensorflow::InputTFE_Context(ctx), function_name, &buf, status.get()); tensorflow::MaybeRaiseRegisteredFromTFStatus(status.get()); }); m.def(""TFE_ContextRemoveFunction"", [](py::handle& ctx, const char* name) { tensorflow::Safe_TF_StatusPtr status = tensorflow::make_safe(TF_NewStatus()); TFE_ContextRemoveFunction(tensorflow::InputTFE_Context(ctx), name, status.get()); tensorflow::MaybeRaiseRegisteredFromTFStatus(status.get()); }); m.def(""TFE_ContextHasFunction"", [](py::handle& ctx, const char* name) { tensorflow::Safe_TF_StatusPtr status = tensorflow::make_safe(TF_NewStatus()); auto output = TFE_ContextHasFunction(tensorflow::InputTFE_Context(ctx), name); tensorflow::MaybeRaiseRegisteredFromTFStatus(status.get()); return output; }); m.def(""TFE_ContextEnableRunMetadata"", [](py::handle& ctx) { TFE_ContextEnableRunMetadata(tensorflow::InputTFE_Context(ctx)); }); m.def(""TFE_ContextDisableRunMetadata"", [](py::handle& ctx) { TFE_ContextEnableRunMetadata(tensorflow::InputTFE_Context(ctx)); }); m.def(""TFE_ContextEnableGraphCollection"", [](py::handle& ctx) { TFE_ContextEnableGraphCollection(tensorflow::InputTFE_Context(ctx)); }); m.def(""TFE_ContextDisableGraphCollection"", [](py::handle& ctx) { TFE_ContextDisableGraphCollection(tensorflow::InputTFE_Context(ctx)); }); m.def(""TFE_ContextExportRunMetadata"", [](py::handle& ctx, TF_Buffer& buf) { tensorflow::Safe_TF_StatusPtr status = tensorflow::make_safe(TF_NewStatus()); TFE_ContextExportRunMetadata(tensorflow::InputTFE_Context(ctx), &buf, status.get()); tensorflow::MaybeRaiseRegisteredFromTFStatus(status.get()); }); m.def(""TFE_ContextClearCaches"", [](py::handle& o) { TFE_ContextClearCaches(tensorflow::InputTFE_Context(o)); }); m.def(""TFE_GetContextId"", [](py::handle& ctx) { return TFE_GetContextId(tensorflow::InputTFE_Context(ctx)); }); m.def(""TFE_ContextGetDevicePlacementPolicy"", [](py::handle& ctx) { return TFE_ContextGetDevicePlacementPolicy( tensorflow::InputTFE_Context(ctx)); }); m.def(""TFE_ContextSetThreadLocalDevicePlacementPolicy"", [](py::handle& ctx, TFE_ContextDevicePlacementPolicy policy) { TFE_ContextSetThreadLocalDevicePlacementPolicy( tensorflow::InputTFE_Context(ctx), policy); }); m.def(""TFE_ContextSetServerDef"", [](py::handle& ctx, int keep_alive_secs, py::bytes proto) { tensorflow::Safe_TF_StatusPtr status = tensorflow::make_safe(TF_NewStatus()); tensorflow::Safe_TF_BufferPtr buf = tensorflow::make_safe(tensorflow::ProtoStringToTFBuffer(proto.ptr())); TFE_ContextSetServerDef(tensorflow::InputTFE_Context(ctx), keep_alive_secs, buf.get()->data, buf.get()->length, status.get()); tensorflow::MaybeRaiseRegisteredFromTFStatus(status.get()); }); m.def(""TFE_ContextUpdateServerDef"", [](py::handle& ctx, int keep_alive_secs, py::bytes proto) { tensorflow::Safe_TF_StatusPtr status = tensorflow::make_safe(TF_NewStatus()); tensorflow::Safe_TF_BufferPtr buf = tensorflow::make_safe(tensorflow::ProtoStringToTFBuffer(proto.ptr())); Py_BEGIN_ALLOW_THREADS; TFE_ContextUpdateServerDef(tensorflow::InputTFE_Context(ctx), keep_alive_secs, buf.get()->data, buf.get()->length, status.get()); Py_END_ALLOW_THREADS; tensorflow::MaybeRaiseRegisteredFromTFStatus(status.get()); }); m.def(""TFE_ContextCheckAlive"", [](py::handle& ctx, const char* worker_name) { tensorflow::Safe_TF_StatusPtr status = tensorflow::make_safe(TF_NewStatus()); bool output = TFE_ContextCheckAlive(tensorflow::InputTFE_Context(ctx), worker_name, status.get()); tensorflow::MaybeRaiseRegisteredFromTFStatus(status.get()); return output; }); m.def(""TFE_ContextSyncExecutors"", [](py::handle& ctx) { tensorflow::Safe_TF_StatusPtr status = tensorflow::make_safe(TF_NewStatus()); TFE_ContextAsyncWait(tensorflow::InputTFE_Context(ctx), status.get()); tensorflow::MaybeRaiseRegisteredFromTFStatus(status.get()); }); m.def(""TFE_ContextClearExecutors"", [](py::handle& ctx) { tensorflow::Safe_TF_StatusPtr status = tensorflow::make_safe(TF_NewStatus()); TFE_ContextAsyncWait(tensorflow::InputTFE_Context(ctx), status.get()); // NOTE: different from TFE_ContextSyncExecutors that raises potential // errors, deliberately ignore executor statuses in cleanup. }); m.def(""TFE_ContextSetSoftDevicePlacement"", [](py::handle& ctx, bool enable) { tensorflow::Safe_TF_StatusPtr status = tensorflow::make_safe(TF_NewStatus()); TFE_ContextSetSoftDevicePlacement(tensorflow::InputTFE_Context(ctx), enable, status.get()); }); m.def(""TFE_ContextSetLogDevicePlacement"", [](py::handle& ctx, bool enable) { tensorflow::Safe_TF_StatusPtr status = tensorflow::make_safe(TF_NewStatus()); TFE_ContextSetSoftDevicePlacement(tensorflow::InputTFE_Context(ctx), enable, status.get()); }); // TFE_Executor logic m.def( ""TFE_NewExecutor"", [](const bool is_async) { TFE_Executor* exc = TFE_NewExecutor(is_async); return exc; }, py::return_value_policy::reference); m.def(""TFE_DeleteExecutor"", &TFE_DeleteExecutor); m.def(""TFE_ExecutorIsAsync"", &TFE_ExecutorIsAsync); m.def(""TFE_ExecutorWaitForAllPendingNodes"", [](TFE_Executor& exc) { tensorflow::Safe_TF_StatusPtr status = tensorflow::make_safe(TF_NewStatus()); // NOTE: release Python GIL for pending PyFunc ops to be executed properly. Py_BEGIN_ALLOW_THREADS; TFE_ExecutorWaitForAllPendingNodes(&exc, status.get()); Py_END_ALLOW_THREADS; tensorflow::MaybeRaiseRegisteredFromTFStatus(status.get()); }); m.def(""TFE_ExecutorClearError"", &TFE_ExecutorClearError); m.def(""TFE_ContextSetExecutorForThread"", [](py::handle& ctx, TFE_Executor& exc) { TFE_ContextSetExecutorForThread(tensorflow::InputTFE_Context(ctx), &exc); }); m.def( ""TFE_ContextGetExecutorForThread"", [](py::handle& o) { return TFE_ContextGetExecutorForThread(tensorflow::InputTFE_Context(o)); }, py::return_value_policy::reference); m.def(""TFE_OpNameGetAttrType"", [](py::handle& ctx, const char* op_or_function_name, const char* attr_name) { int temp = 0; unsigned char* is_list = reinterpret_cast(&temp); tensorflow::Safe_TF_StatusPtr status = tensorflow::make_safe(TF_NewStatus()); auto output = TFE_OpNameGetAttrType(tensorflow::InputTFE_Context(ctx), op_or_function_name, attr_name, is_list, status.get()); tensorflow::MaybeRaiseRegisteredFromTFStatus(status.get()); #if PY_MAJOR_VERSION < 3 PyObject* output_pyo = PyInt_FromLong(output); #else PyObject* output_pyo = PyLong_FromLong(output); #endif if (*is_list == 1) { PyObject* list = PyList_New(1); PyList_SetItem(list, 0, output_pyo); return tensorflow::PyoOrThrow(list); } return tensorflow::PyoOrThrow(output_pyo); }); m.def(""TFE_Py_InitEagerTensor"", [](const py::handle& o) { return tensorflow::PyoOrThrow(TFE_Py_InitEagerTensor(o.ptr())); }); m.def(""TFE_Py_PackEagerTensors"", [](const py::handle& context, const py::handle& handles) { return tensorflow::TFE_Py_PackEagerTensors_wrapper(context, handles); }); m.def(""TFE_Py_SetEagerTensorProfiler"", &TFE_Py_SetEagerTensorProfiler); m.def(""TFE_Py_RegisterJVPFunction"", [](const py::handle& o) { return tensorflow::PyoOrThrow(TFE_Py_RegisterJVPFunction(o.ptr())); }); m.def(""TFE_Py_RegisterGradientFunction"", [](const py::handle& o) { return tensorflow::PyoOrThrow(TFE_Py_RegisterGradientFunction(o.ptr())); }); m.def(""TFE_Py_Execute"", [](const py::handle& context, const char* device_name, const char* op_name, const py::handle& inputs, const py::handle& attrs, const py::handle& num_outputs) { return tensorflow::TFE_Py_ExecuteCancelable_wrapper( context, device_name, op_name, inputs, attrs.ptr(), nullptr, num_outputs); }); m.def( ""TFE_Py_ExecuteCancelable"", [](const py::handle& context, const char* device_name, const char* op_name, const py::handle& inputs, const py::handle& attrs, TFE_CancellationManager& cancellation_manager, const py::handle& num_outputs) { return tensorflow::TFE_Py_ExecuteCancelable_wrapper( context, device_name, op_name, inputs, attrs.ptr(), &cancellation_manager, num_outputs); }); m.def(""TFE_Py_FastPathExecute"", [](const py::args args) { // TFE_Py_FastPathExecute requires error checking prior to returning. return tensorflow::PyoOrThrow(TFE_Py_FastPathExecute_C(args.ptr())); }); m.def(""TFE_Py_RecordGradient"", [](const py::handle& op_name, const py::handle& inputs, const py::handle& attrs, const py::handle& results, const py::handle& forward_pass_name_scope) { return tensorflow::PyoOrThrow(TFE_Py_RecordGradient( op_name.ptr(), inputs.ptr(), attrs.ptr(), results.ptr(), forward_pass_name_scope.ptr())); }); m.def(""TFE_Py_UID"", []() { return tensorflow::PyoOrThrow(TFE_Py_UID()); }); // TFE_Py_Tape Logic m.def(""TFE_Py_TapeSetNew"", [](const py::handle& persistent, const py::handle& watch_accessed_variables) { return tensorflow::PyoOrThrow( TFE_Py_TapeSetNew(persistent.ptr(), watch_accessed_variables.ptr())); }); m.def(""TFE_Py_TapeSetAdd"", [](const py::handle& tape) { TFE_Py_TapeSetAdd(tape.ptr()); }); m.def(""TFE_Py_TapeSetRemove"", [](const py::handle& tape) { TFE_Py_TapeSetRemove(tape.ptr()); }); m.def(""TFE_Py_TapeSetStopOnThread"", &TFE_Py_TapeSetStopOnThread); m.def(""TFE_Py_TapeSetRestartOnThread"", &TFE_Py_TapeSetRestartOnThread); m.def(""TFE_Py_TapeSetIsStopped"", []() { return tensorflow::PyoOrThrow(TFE_Py_TapeSetIsStopped()); }); m.def(""TFE_Py_TapeSetIsEmpty"", []() { return tensorflow::PyoOrThrow(TFE_Py_TapeSetIsEmpty()); }); m.def(""TFE_Py_TapeSetShouldRecordBackprop"", [](const py::handle& tensors) { return tensorflow::PyoOrThrow( TFE_Py_TapeSetShouldRecordBackprop(tensors.ptr())); }); m.def(""TFE_Py_TapeSetPossibleGradientTypes"", [](const py::handle& tensors) { return tensorflow::PyoOrThrow( TFE_Py_TapeSetPossibleGradientTypes(tensors.ptr())); }); m.def(""TFE_Py_TapeSetDeleteTrace"", &TFE_Py_TapeSetDeleteTrace); m.def(""TFE_Py_TapeSetRecordOperation"", [](const py::handle& op_type, const py::handle& output_tensors, const py::handle& input_tensors, const py::handle& backward_function, const py::handle& forward_function) { return tensorflow::PyoOrThrow(TFE_Py_TapeSetRecordOperation( op_type.ptr(), output_tensors.ptr(), input_tensors.ptr(), backward_function.ptr(), forward_function.ptr())); }); m.def( ""TFE_Py_TapeSetRecordOperationBackprop"", [](const py::handle& op_type, const py::handle& output_tensors, const py::handle& input_tensors, const py::handle& backward_function) { return tensorflow::PyoOrThrow(TFE_Py_TapeSetRecordOperationBackprop( op_type.ptr(), output_tensors.ptr(), input_tensors.ptr(), backward_function.ptr())); }); m.def( ""TFE_Py_TapeSetRecordOperationForwardprop"", [](const py::handle& op_type, const py::handle& output_tensors, const py::handle& input_tensors, const py::handle& backward_function, const py::handle& forwardprop_output_indices) { return tensorflow::PyoOrThrow(TFE_Py_TapeSetRecordOperationForwardprop( op_type.ptr(), output_tensors.ptr(), input_tensors.ptr(), backward_function.ptr(), forwardprop_output_indices.ptr())); }); m.def(""TFE_Py_TapeGradient"", [](const py::handle& tape, const py::handle& target, const py::handle& sources, const py::handle& output_gradients, const py::handle& sources_raw, const py::handle& unconnected_gradients) { tensorflow::Safe_TF_StatusPtr status = tensorflow::make_safe(TF_NewStatus()); PyObject* output = TFE_Py_TapeGradient( tape.ptr(), target.ptr(), sources.ptr(), output_gradients.ptr(), sources_raw.ptr(), unconnected_gradients.ptr(), status.get()); tensorflow::MaybeRaiseRegisteredFromTFStatus(status.get()); return tensorflow::PyoOrThrow(output); }); m.def(""TFE_Py_TapeVariableAccessed"", [](const py::handle& variable) { TFE_Py_TapeVariableAccessed(variable.ptr()); }); m.def(""TFE_Py_TapeWatch"", [](const py::handle& tape, const py::handle& tensor) { TFE_Py_TapeWatch(tape.ptr(), tensor.ptr()); }); m.def(""TFE_Py_TapeWatchVariable"", [](const py::handle& tape, const py::handle& variable) { TFE_Py_TapeWatchVariable(tape.ptr(), variable.ptr()); }); m.def(""TFE_Py_TapeWatchedVariables"", [](const py::handle& tape) { return tensorflow::PyoOrThrow(TFE_Py_TapeWatchedVariables(tape.ptr())); }); // TFE_Py_VariableWatcher logic. m.def(""TFE_Py_VariableWatcherNew"", []() { return tensorflow::PyoOrThrow(TFE_Py_VariableWatcherNew()); }); m.def(""TFE_Py_VariableWatcherRemove"", [](const py::handle& variable_watcher) { TFE_Py_VariableWatcherRemove(variable_watcher.ptr()); }); m.def(""TFE_Py_VariableWatcherVariableAccessed"", [](const py::handle& variable) { TFE_Py_VariableWatcherVariableAccessed(variable.ptr()); }); m.def(""TFE_Py_VariableWatcherWatchedVariables"", [](const py::handle& variable_watcher) { return tensorflow::PyoOrThrow( TFE_Py_VariableWatcherWatchedVariables(variable_watcher.ptr())); }); // TFE_Py_ForwardAccumulator logic. m.def(""TFE_Py_ForwardAccumulatorNew"", [](bool use_batch) { return tensorflow::PyoOrThrow(TFE_Py_ForwardAccumulatorNew(use_batch)); }); m.def(""TFE_Py_ForwardAccumulatorSetAdd"", [](const py::handle& accumulator) { return tensorflow::PyoOrThrow( TFE_Py_ForwardAccumulatorSetAdd(accumulator.ptr())); }); m.def(""TFE_Py_ForwardAccumulatorSetRemove"", [](const py::handle& accumulator) { TFE_Py_ForwardAccumulatorSetRemove(accumulator.ptr()); }); m.def(""TFE_Py_ForwardAccumulatorWatch"", [](const py::handle& accumulator, const py::handle& tensor, const py::handle& tangent) { TFE_Py_ForwardAccumulatorWatch(accumulator.ptr(), tensor.ptr(), tangent.ptr()); }); m.def(""TFE_Py_ForwardAccumulatorJVP"", [](const py::handle& accumulator, const py::handle& tensor) { return tensorflow::PyoOrThrow( TFE_Py_ForwardAccumulatorJVP(accumulator.ptr(), tensor.ptr())); }); m.def(""TFE_Py_ForwardAccumulatorPushState"", []() { return tensorflow::PyoOrThrow(TFE_Py_ForwardAccumulatorPushState()); }); m.def(""TFE_Py_ForwardAccumulatorPopState"", []() { return tensorflow::PyoOrThrow(TFE_Py_ForwardAccumulatorPopState()); }); m.def(""TFE_Py_PackJVPs"", [](const py::handle& tensors) { return tensorflow::PyoOrThrow(TFE_Py_PackJVPs(tensors.ptr())); }); // TFE_ContextOptions Logic m.def(""TFE_NewContextOptions"", &TFE_NewContextOptions, py::return_value_policy::reference); m.def(""TFE_ContextOptionsSetConfig"", [](TFE_ContextOptions* options, py::bytes proto) { tensorflow::Safe_TF_StatusPtr status = tensorflow::make_safe(TF_NewStatus()); tensorflow::Safe_TF_BufferPtr buf = tensorflow::make_safe(tensorflow::ProtoStringToTFBuffer(proto.ptr())); TFE_ContextOptionsSetConfig(options, buf.get()->data, buf.get()->length, status.get()); tensorflow::MaybeRaiseRegisteredFromTFStatus(status.get()); }); m.def(""TFE_ContextOptionsSetDevicePlacementPolicy"", &TFE_ContextOptionsSetDevicePlacementPolicy); m.def(""TFE_ContextOptionsSetLazyRemoteInputsCopy"", &TFE_ContextOptionsSetLazyRemoteInputsCopy); m.def(""TFE_ContextOptionsSetTfrt"", &TFE_ContextOptionsSetTfrt); m.def(""TFE_ContextOptionsSetAsync"", &TFE_ContextOptionsSetAsync); m.def(""TFE_DeleteContextOptions"", &TFE_DeleteContextOptions, py::return_value_policy::reference); // TFE_Py_TensorShape Logic m.def(""TFE_Py_TensorShapeSlice"", [](const py::handle& tensors, int slice_dim) { return tensorflow::PyoOrThrow( TFE_Py_TensorShapeSlice(tensors.ptr(), slice_dim)); }); m.def(""TFE_Py_TensorShapeOnDevice"", [](const py::handle& tensors, int slice_dim) { return tensorflow::PyoOrThrow(TFE_Py_TensorShapeOnDevice(tensors.ptr())); }); m.def(""TFE_Py_EnableInteractivePythonLogging"", &TFE_Py_EnableInteractivePythonLogging); // Additional Context Logic m.def(""TFE_Py_SetEagerContext"", [](const py::handle& o) { return tensorflow::PyoOrThrow(TFE_Py_SetEagerContext(o.ptr())); }); m.def(""TFE_ContextStartStep"", [](py::handle& o) { TFE_ContextStartStep(tensorflow::InputTFE_Context(o.ptr())); }); m.def(""TFE_ContextEndStep"", [](py::handle& o) { TFE_ContextEndStep(tensorflow::InputTFE_Context(o.ptr())); }); m.def(""TFE_Py_RegisterVSpace"", [](const py::handle& o) { return tensorflow::PyoOrThrow(TFE_Py_RegisterVSpace(o.ptr())); }); m.def(""TFE_Py_EncodeArg"", [](const py::handle& o, bool include_tensor_ranks_only) { return tensorflow::PyoOrThrow( TFE_Py_EncodeArg(o.ptr(), include_tensor_ranks_only)); }); m.def(""TFE_EnableCollectiveOps"", [](const py::handle& ctx, py::bytes proto) { tensorflow::Safe_TF_StatusPtr status = tensorflow::make_safe(TF_NewStatus()); tensorflow::Safe_TF_BufferPtr buf = tensorflow::make_safe(tensorflow::ProtoStringToTFBuffer(proto.ptr())); TFE_EnableCollectiveOps(tensorflow::InputTFE_Context(ctx), buf.get()->data, buf.get()->length, status.get()); tensorflow::MaybeRaiseRegisteredFromTFStatus(status.get()); }); m.def(""TFE_AbortCollectiveOps"", [](const py::handle& ctx, int code, const char* message) { tensorflow::Safe_TF_StatusPtr status = tensorflow::make_safe(TF_NewStatus()); TF_SetStatus(status.get(), static_cast(code), message); TFE_AbortCollectiveOps(tensorflow::InputTFE_Context(ctx), status.get()); }); m.def(""TFE_CollectiveOpsCheckPeerHealth"", [](const py::handle& ctx, const char* task) { tensorflow::Safe_TF_StatusPtr status = tensorflow::make_safe(TF_NewStatus()); TFE_CollectiveOpsCheckPeerHealth(tensorflow::InputTFE_Context(ctx), task, status.get()); tensorflow::MaybeRaiseRegisteredFromTFStatus(status.get()); }); m.def(""TF_ListPhysicalDevices"", &tensorflow::TF_ListPhysicalDevices); m.def(""TF_GetDeviceDetails"", &tensorflow::TF_GetDeviceDetails); m.def(""TF_DeleteDeviceList"", &TF_DeleteDeviceList, py::return_value_policy::reference); m.def(""TF_DeviceListCount"", &TF_DeviceListCount); m.def(""TF_DeviceListName"", [](const TF_DeviceList* list, int index) { tensorflow::Safe_TF_StatusPtr status = tensorflow::make_safe(TF_NewStatus()); auto output = TF_DeviceListName(list, index, status.get()); tensorflow::MaybeRaiseRegisteredFromTFStatus(status.get()); return output; }); m.def(""TF_DeviceListType"", [](const TF_DeviceList* list, int index) { tensorflow::Safe_TF_StatusPtr status = tensorflow::make_safe(TF_NewStatus()); auto output = TF_DeviceListType(list, index, status.get()); tensorflow::MaybeRaiseRegisteredFromTFStatus(status.get()); return output; }); m.def(""TF_PickUnusedPortOrDie"", &TF_PickUnusedPortOrDie); // TFE_MonitoringCounter Logic m.def(""TFE_MonitoringCounterCellIncrementBy"", &TFE_MonitoringCounterCellIncrementBy); m.def(""TFE_MonitoringCounterCellValue"", &TFE_MonitoringCounterCellValue); m.def( ""TFE_MonitoringNewCounter0"", [](const char* name, const char* description) { tensorflow::Safe_TF_StatusPtr status = tensorflow::make_safe(TF_NewStatus()); auto output = TFE_MonitoringNewCounter0(name, status.get(), description); tensorflow::MaybeRaiseRegisteredFromTFStatus(status.get()); return output; }, py::return_value_policy::reference); m.def(""TFE_MonitoringDeleteCounter0"", &TFE_MonitoringDeleteCounter0, py::return_value_policy::reference); m.def(""TFE_MonitoringGetCellCounter0"", &TFE_MonitoringGetCellCounter0, py::return_value_policy::reference); m.def( ""TFE_MonitoringNewCounter1"", [](const char* name, const char* description, const char* label1) { tensorflow::Safe_TF_StatusPtr status = tensorflow::make_safe(TF_NewStatus()); auto output = TFE_MonitoringNewCounter1(name, status.get(), description, label1); tensorflow::MaybeRaiseRegisteredFromTFStatus(status.get()); return output; }, py::return_value_policy::reference); m.def(""TFE_MonitoringDeleteCounter1"", &TFE_MonitoringDeleteCounter1, py::return_value_policy::reference); m.def(""TFE_MonitoringGetCellCounter1"", &TFE_MonitoringGetCellCounter1, py::return_value_policy::reference); m.def( ""TFE_MonitoringNewCounter2"", [](const char* name, const char* description, const char* label1, const char* label2) { tensorflow::Safe_TF_StatusPtr status = tensorflow::make_safe(TF_NewStatus()); auto output = TFE_MonitoringNewCounter2(name, status.get(), description, label1, label2); tensorflow::MaybeRaiseRegisteredFromTFStatus(status.get()); return output; }, py::return_value_policy::reference); m.def(""TFE_MonitoringDeleteCounter2"", &TFE_MonitoringDeleteCounter2, py::return_value_policy::reference); m.def(""TFE_MonitoringGetCellCounter2"", &TFE_MonitoringGetCellCounter2, py::return_value_policy::reference); // TFE_MonitoringIntGauge Logic m.def(""TFE_MonitoringIntGaugeCellSet"", &TFE_MonitoringIntGaugeCellSet); m.def(""TFE_MonitoringIntGaugeCellValue"", &TFE_MonitoringIntGaugeCellValue); m.def( ""TFE_MonitoringNewIntGauge0"", [](const char* name, const char* description) { tensorflow::Safe_TF_StatusPtr status = tensorflow::make_safe(TF_NewStatus()); auto output = TFE_MonitoringNewIntGauge0(name, status.get(), description); tensorflow::MaybeRaiseRegisteredFromTFStatus(status.get()); return output; }, py::return_value_policy::reference); m.def(""TFE_MonitoringDeleteIntGauge0"", &TFE_MonitoringDeleteIntGauge0, py::return_value_policy::reference); m.def(""TFE_MonitoringGetCellIntGauge0"", &TFE_MonitoringGetCellIntGauge0, py::return_value_policy::reference); m.def( ""TFE_MonitoringNewIntGauge1"", [](const char* name, const char* description, const char* label1) { tensorflow::Safe_TF_StatusPtr status = tensorflow::make_safe(TF_NewStatus()); auto output = TFE_MonitoringNewIntGauge1(name, status.get(), description, label1); tensorflow::MaybeRaiseRegisteredFromTFStatus(status.get()); return output; }, py::return_value_policy::reference); m.def(""TFE_MonitoringDeleteIntGauge1"", &TFE_MonitoringDeleteIntGauge1, py::return_value_policy::reference); m.def(""TFE_MonitoringGetCellIntGauge1"", &TFE_MonitoringGetCellIntGauge1, py::return_value_policy::reference); m.def( ""TFE_MonitoringNewIntGauge2"", [](const char* name, const char* description, const char* label1, const char* label2) { tensorflow::Safe_TF_StatusPtr status = tensorflow::make_safe(TF_NewStatus()); auto output = TFE_MonitoringNewIntGauge2(name, status.get(), description, label1, label2); tensorflow::MaybeRaiseRegisteredFromTFStatus(status.get()); return output; }, py::return_value_policy::reference); m.def(""TFE_MonitoringDeleteIntGauge2"", &TFE_MonitoringDeleteIntGauge2, py::return_value_policy::reference); m.def(""TFE_MonitoringGetCellIntGauge2"", &TFE_MonitoringGetCellIntGauge2, py::return_value_policy::reference); m.def(""TFE_MonitoringStringGaugeCellSet"", &TFE_MonitoringStringGaugeCellSet); m.def(""TFE_MonitoringStringGaugeCellValue"", &TFE_MonitoringStringGaugeCellValue); m.def( ""TFE_MonitoringNewStringGauge0"", [](const char* name, const char* description) { tensorflow::Safe_TF_StatusPtr status = tensorflow::make_safe(TF_NewStatus()); auto output = TFE_MonitoringNewStringGauge0(name, status.get(), description); tensorflow::MaybeRaiseRegisteredFromTFStatus(status.get()); return output; }, py::return_value_policy::reference); // TFE_MonitoringStringGauge Logic m.def(""TFE_MonitoringDeleteStringGauge0"", &TFE_MonitoringDeleteStringGauge0); m.def(""TFE_MonitoringGetCellStringGauge0"", &TFE_MonitoringGetCellStringGauge0, py::return_value_policy::reference); m.def( ""TFE_MonitoringNewStringGauge1"", [](const char* name, const char* description, const char* label1) { tensorflow::Safe_TF_StatusPtr status = tensorflow::make_safe(TF_NewStatus()); auto output = TFE_MonitoringNewStringGauge1(name, status.get(), description, label1); tensorflow::MaybeRaiseRegisteredFromTFStatus(status.get()); return output; }, py::return_value_policy::reference); m.def(""TFE_MonitoringDeleteStringGauge1"", &TFE_MonitoringDeleteStringGauge1); m.def(""TFE_MonitoringGetCellStringGauge1"", &TFE_MonitoringGetCellStringGauge1, py::return_value_policy::reference); m.def( ""TFE_MonitoringNewStringGauge2"", [](const char* name, const char* description, const char* label1, const char* label2) { tensorflow::Safe_TF_StatusPtr status = tensorflow::make_safe(TF_NewStatus()); auto output = TFE_MonitoringNewStringGauge2( name, status.get(), description, label1, label2); tensorflow::MaybeRaiseRegisteredFromTFStatus(status.get()); return output; }, py::return_value_policy::reference); m.def(""TFE_MonitoringDeleteStringGauge2"", &TFE_MonitoringDeleteStringGauge2); m.def(""TFE_MonitoringGetCellStringGauge2"", &TFE_MonitoringGetCellStringGauge2, py::return_value_policy::reference); // TFE_MonitoringBoolGauge Logic m.def(""TFE_MonitoringBoolGaugeCellSet"", &TFE_MonitoringBoolGaugeCellSet); m.def(""TFE_MonitoringBoolGaugeCellValue"", &TFE_MonitoringBoolGaugeCellValue); m.def( ""TFE_MonitoringNewBoolGauge0"", [](const char* name, const char* description) { tensorflow::Safe_TF_StatusPtr status = tensorflow::make_safe(TF_NewStatus()); auto output = TFE_MonitoringNewBoolGauge0(name, status.get(), description); tensorflow::MaybeRaiseRegisteredFromTFStatus(status.get()); return output; }, py::return_value_policy::reference); m.def(""TFE_MonitoringDeleteBoolGauge0"", &TFE_MonitoringDeleteBoolGauge0, py::return_value_policy::reference); m.def(""TFE_MonitoringGetCellBoolGauge0"", &TFE_MonitoringGetCellBoolGauge0, py::return_value_policy::reference); m.def( ""TFE_MonitoringNewBoolGauge1"", [](const char* name, const char* description, const char* label1) { tensorflow::Safe_TF_StatusPtr status = tensorflow::make_safe(TF_NewStatus()); auto output = TFE_MonitoringNewBoolGauge1(name, status.get(), description, label1); tensorflow::MaybeRaiseRegisteredFromTFStatus(status.get()); return output; }, py::return_value_policy::reference); m.def(""TFE_MonitoringDeleteBoolGauge1"", &TFE_MonitoringDeleteBoolGauge1, py::return_value_policy::reference); m.def(""TFE_MonitoringGetCellBoolGauge1"", &TFE_MonitoringGetCellBoolGauge1, py::return_value_policy::reference); m.def( ""TFE_MonitoringNewBoolGauge2"", [](const char* name, const char* description, const char* label1, const char* label2) { tensorflow::Safe_TF_StatusPtr status = tensorflow::make_safe(TF_NewStatus()); auto output = TFE_MonitoringNewBoolGauge2(name, status.get(), description, label1, label2); tensorflow::MaybeRaiseRegisteredFromTFStatus(status.get()); return output; }, py::return_value_policy::reference); m.def(""TFE_MonitoringDeleteBoolGauge2"", &TFE_MonitoringDeleteBoolGauge2, py::return_value_policy::reference); m.def(""TFE_MonitoringGetCellBoolGauge2"", &TFE_MonitoringGetCellBoolGauge2, py::return_value_policy::reference); // TFE_MonitoringSampler Logic m.def(""TFE_MonitoringSamplerCellAdd"", &TFE_MonitoringSamplerCellAdd); m.def(""TFE_MonitoringSamplerCellValue"", &TFE_MonitoringSamplerCellValue); m.def(""TFE_MonitoringNewExponentialBuckets"", &TFE_MonitoringNewExponentialBuckets, py::return_value_policy::reference); m.def(""TFE_MonitoringDeleteBuckets"", &TFE_MonitoringDeleteBuckets, py::return_value_policy::reference); m.def( ""TFE_MonitoringNewSampler0"", [](const char* name, TFE_MonitoringBuckets* buckets, const char* description) { tensorflow::Safe_TF_StatusPtr status = tensorflow::make_safe(TF_NewStatus()); auto output = TFE_MonitoringNewSampler0(name, buckets, status.get(), description); tensorflow::MaybeRaiseRegisteredFromTFStatus(status.get()); return output; }, py::return_value_policy::reference); m.def(""TFE_MonitoringDeleteSampler0"", &TFE_MonitoringDeleteSampler0, py::return_value_policy::reference); m.def(""TFE_MonitoringGetCellSampler0"", &TFE_MonitoringGetCellSampler0, py::return_value_policy::reference); m.def( ""TFE_MonitoringNewSampler1"", [](const char* name, TFE_MonitoringBuckets* buckets, const char* description, const char* label1) { tensorflow::Safe_TF_StatusPtr status = tensorflow::make_safe(TF_NewStatus()); auto output = TFE_MonitoringNewSampler1(name, buckets, status.get(), description, label1); tensorflow::MaybeRaiseRegisteredFromTFStatus(status.get()); return output; }, py::return_value_policy::reference); m.def(""TFE_MonitoringDeleteSampler1"", &TFE_MonitoringDeleteSampler1, py::return_value_policy::reference); m.def(""TFE_MonitoringGetCellSampler1"", &TFE_MonitoringGetCellSampler1, py::return_value_policy::reference); m.def( ""TFE_MonitoringNewSampler2"", [](const char* name, TFE_MonitoringBuckets* buckets, const char* description, const char* label1, const char* label2) { tensorflow::Safe_TF_StatusPtr status = tensorflow::make_safe(TF_NewStatus()); auto output = TFE_MonitoringNewSampler2(name, buckets, status.get(), description, label1, label2); tensorflow::MaybeRaiseRegisteredFromTFStatus(status.get()); return output; }, py::return_value_policy::reference); m.def(""TFE_MonitoringDeleteSampler2"", &TFE_MonitoringDeleteSampler2, py::return_value_policy::reference); m.def(""TFE_MonitoringGetCellSampler2"", &TFE_MonitoringGetCellSampler2, py::return_value_policy::reference); // TFE_CancellationManager Logic m.def(""TFE_NewCancellationManager"", &TFE_NewCancellationManager, py::return_value_policy::reference); m.def(""TFE_CancellationManagerIsCancelled"", &TFE_CancellationManagerIsCancelled); m.def(""TFE_CancellationManagerStartCancel"", &TFE_CancellationManagerStartCancel); m.def(""TFE_DeleteCancellationManager"", &TFE_DeleteCancellationManager, py::return_value_policy::reference); m.def(""TFE_ClearScalarCache"", &tensorflow::TFE_ClearScalarCache); // Util buffer helper functions m.def(""TF_NewBufferFromString"", &TF_NewBufferFromString, py::return_value_policy::reference); // DLPack functions m.def(""TFE_ToDlpackCapsule"", [](py::handle& o) { PyObject* eager_tensor_pyobject_ptr = o.ptr(); tensorflow::Safe_TF_StatusPtr status = tensorflow::make_safe(TF_NewStatus()); if (!EagerTensor_CheckExact(eager_tensor_pyobject_ptr)) { status->status = tensorflow::errors::InvalidArgument( ""The argument to `to_dlpack` must be a TF tensor, not Python object""); tensorflow::MaybeRaiseRegisteredFromTFStatus(status.get()); } TFE_TensorHandle* thandle = EagerTensor_Handle(eager_tensor_pyobject_ptr); void* dlm_ptr = tensorflow::TFE_HandleToDLPack(thandle, status.get()); tensorflow::MaybeRaiseRegisteredFromTFStatus(status.get()); py::capsule capsule( dlm_ptr, tensorflow::kDlTensorCapsuleName, [](PyObject* capsule) { if (PyCapsule_IsValid(capsule, tensorflow::kDlTensorCapsuleName)) { void* dlm_rptr = PyCapsule_GetPointer(capsule, tensorflow::kDlTensorCapsuleName); if (dlm_rptr) { tensorflow::TFE_CallDLManagedTensorDeleter(dlm_rptr); PyCapsule_SetDestructor(capsule, nullptr); } } }); return capsule; }); m.def(""TFE_FromDlpackCapsule"", [](const py::capsule& pycapsule, const py::handle& context) { tensorflow::Safe_TF_StatusPtr status = tensorflow::make_safe(TF_NewStatus()); if (absl::string_view(pycapsule.name()) != tensorflow::kDlTensorCapsuleName) { status->status = tensorflow::errors::InvalidArgument( ""DLPack tensor must be a capsule with name \\""dltensor\\"", got \\""%s\\"". "" ""Note that a DLPack tensor may be consumed at most once."", absl::string_view(pycapsule.name())); tensorflow::MaybeRaiseRegisteredFromTFStatus(status.get()); } TFE_TensorHandle* thandle = tensorflow::TFE_HandleFromDLPack( pycapsule, status.get(), tensorflow::InputTFE_Context(context)); tensorflow::MaybeRaiseRegisteredFromTFStatus(status.get()); PyCapsule_SetName(pycapsule.ptr(), ""used_dltensor""); PyCapsule_SetDestructor(pycapsule.ptr(), nullptr); PyObject* pyhandle = EagerTensorFromHandle(thandle); return tensorflow::PyoOrThrow(pyhandle); }); m.def(""TFE_Py_RegisterCustomDevice"", [](const py::handle& context, const py::capsule& device, const char* device_name, const py::capsule& device_info) { tensorflow::Safe_TF_StatusPtr status = tensorflow::make_safe(TF_NewStatus()); if (absl::string_view(device.name()) != ""TFE_CustomDevice"") { status->status = tensorflow::errors::InvalidArgument( ""Expected a capsule named 'TFE_CustomDevice' for the `device` "" ""argument, got "", absl::string_view(device.name())); tensorflow::MaybeRaiseRegisteredFromTFStatus(status.get()); } if (absl::string_view(device_info.name()) != ""TFE_CustomDevice_DeviceInfo"") { status->status = tensorflow::errors::InvalidArgument( ""Expected a capsule named 'TFE_CustomDevice_DeviceInfo' for "" ""the `device_info` argument, got "", absl::string_view(device_info.name())); tensorflow::MaybeRaiseRegisteredFromTFStatus(status.get()); } // TFE_RegisterCustomDevice takes ownership PyCapsule_SetDestructor(device_info.ptr(), nullptr); TFE_RegisterCustomDevice( tensorflow::InputTFE_Context(context), *reinterpret_cast( PyCapsule_GetPointer(device.ptr(), ""TFE_CustomDevice"")), device_name, PyCapsule_GetPointer(device_info.ptr(), ""TFE_CustomDevice_DeviceInfo""), status.get()); tensorflow::MaybeRaiseRegisteredFromTFStatus(status.get()); }); py::class_(m, ""EagerContextThreadLocalData"") .def(py::init(), py::arg(""py_eager_context""), py::arg(""is_eager""), py::arg(""device_spec"")) .def_property(""is_eager"", &EagerContextThreadLocalDataWrapper::get_is_eager, &EagerContextThreadLocalDataWrapper::set_is_eager) .def_property( ""invoking_op_callbacks"", &EagerContextThreadLocalDataWrapper::get_invoking_op_callbacks, &EagerContextThreadLocalDataWrapper::set_invoking_op_callbacks) .def_property(""device_name"", &EagerContextThreadLocalDataWrapper::get_device_name, &EagerContextThreadLocalDataWrapper::set_device_name) .def_property(""scope_name"", &EagerContextThreadLocalDataWrapper::get_scope_name, &EagerContextThreadLocalDataWrapper::set_scope_name) .def_property(""device_spec"", &EagerContextThreadLocalDataWrapper::get_device_spec, &EagerContextThreadLocalDataWrapper::set_device_spec) .def_property( ""function_call_options"", &EagerContextThreadLocalDataWrapper::get_function_call_options, &EagerContextThreadLocalDataWrapper::set_function_call_options) .def_property(""executor"", &EagerContextThreadLocalDataWrapper::get_executor, &EagerContextThreadLocalDataWrapper::set_executor) .def_property(""op_callbacks"", &EagerContextThreadLocalDataWrapper::get_op_callbacks, &EagerContextThreadLocalDataWrapper::set_op_callbacks); // C API Enum py::enum_( m, ""TFE_ContextDevicePlacementPolicy"") .value(""TFE_DEVICE_PLACEMENT_EXPLICIT"", TFE_DEVICE_PLACEMENT_EXPLICIT) .value(""TFE_DEVICE_PLACEMENT_WARN"", TFE_DEVICE_PLACEMENT_WARN) .value(""TFE_DEVICE_PLACEMENT_SILENT"", TFE_DEVICE_PLACEMENT_SILENT) .value(""TFE_DEVICE_PLACEMENT_SILENT_FOR_INT32"", TFE_DEVICE_PLACEMENT_SILENT_FOR_INT32) .export_values(); py::enum_(m, ""TF_AttrType"") .value(""TF_ATTR_STRING"", TF_ATTR_STRING) .value(""TF_ATTR_INT"", TF_ATTR_INT) .value(""TF_ATTR_FLOAT"", TF_ATTR_FLOAT) .value(""TF_ATTR_BOOL"", TF_ATTR_BOOL) .value(""TF_ATTR_TYPE"", TF_ATTR_TYPE) .value(""TF_ATTR_SHAPE"", TF_ATTR_SHAPE) .value(""TF_ATTR_TENSOR"", TF_ATTR_TENSOR) .value(""TF_ATTR_PLACEHOLDER"", TF_ATTR_PLACEHOLDER) .value(""TF_ATTR_FUNC"", TF_ATTR_FUNC) .export_values(); }; ",16371,True,3533.489428854389,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. #include ""kudu/client/client.h"" #include #include #include #include #include #include #include #include #include #include #include #include #include #include ""kudu/client/callbacks.h"" #include ""kudu/client/client-internal.h"" #include ""kudu/client/client.pb.h"" #include ""kudu/client/client_builder-internal.h"" #include ""kudu/client/columnar_scan_batch.h"" #include ""kudu/client/error-internal.h"" #include ""kudu/client/error_collector.h"" #include ""kudu/client/master_proxy_rpc.h"" #include ""kudu/client/meta_cache.h"" #include ""kudu/client/partitioner-internal.h"" #include ""kudu/client/replica-internal.h"" #include ""kudu/client/row_result.h"" #include ""kudu/client/scan_batch.h"" #include ""kudu/client/scan_configuration.h"" #include ""kudu/client/scan_predicate-internal.h"" #include ""kudu/client/scan_token-internal.h"" #include ""kudu/client/scanner-internal.h"" #include ""kudu/client/session-internal.h"" #include ""kudu/client/table-internal.h"" #include ""kudu/client/table_alterer-internal.h"" #include ""kudu/client/table_creator-internal.h"" #include ""kudu/client/table_statistics-internal.h"" #include ""kudu/client/tablet-internal.h"" #include ""kudu/client/tablet_server-internal.h"" #include ""kudu/client/value.h"" #include ""kudu/client/write_op.h"" #include ""kudu/common/common.pb.h"" #include ""kudu/common/partial_row.h"" #include ""kudu/common/partition.h"" #include ""kudu/common/partition_pruner.h"" #include ""kudu/common/row_operations.h"" #include ""kudu/common/scan_spec.h"" #include ""kudu/common/schema.h"" #include ""kudu/common/wire_protocol.h"" #include ""kudu/common/wire_protocol.pb.h"" #include ""kudu/consensus/metadata.pb.h"" #include ""kudu/gutil/casts.h"" #include ""kudu/gutil/ref_counted.h"" #include ""kudu/gutil/stl_util.h"" #include ""kudu/gutil/strings/numbers.h"" #include ""kudu/gutil/strings/substitute.h"" #include ""kudu/master/master.pb.h"" #include ""kudu/master/master.proxy.h"" #include ""kudu/rpc/messenger.h"" #include ""kudu/rpc/request_tracker.h"" #include ""kudu/rpc/response_callback.h"" #include ""kudu/rpc/rpc.h"" #include ""kudu/rpc/rpc_controller.h"" #include ""kudu/rpc/sasl_common.h"" #include ""kudu/rpc/user_credentials.h"" #include ""kudu/security/cert.h"" #include ""kudu/security/openssl_util.h"" #include ""kudu/security/tls_context.h"" #include ""kudu/security/token.pb.h"" #include ""kudu/tserver/tserver.pb.h"" #include ""kudu/tserver/tserver_service.proxy.h"" #include ""kudu/util/async_util.h"" #include ""kudu/util/debug-util.h"" #include ""kudu/util/init.h"" #include ""kudu/util/logging.h"" #include ""kudu/util/logging_callback.h"" #include ""kudu/util/monotime.h"" #include ""kudu/util/net/net_util.h"" #include ""kudu/util/oid_generator.h"" #include ""kudu/util/scoped_cleanup.h"" #include ""kudu/util/version_info.h"" namespace kudu { class BlockBloomFilter; } // namespace kudu using kudu::consensus::RaftPeerPB; using kudu::master::AlterTableRequestPB; using kudu::master::AlterTableResponsePB; using kudu::master::CreateTableRequestPB; using kudu::master::CreateTableResponsePB; using kudu::master::DeleteTableRequestPB; using kudu::master::DeleteTableResponsePB; using kudu::master::GetTableSchemaRequestPB; using kudu::master::GetTableSchemaResponsePB; using kudu::master::GetTableStatisticsRequestPB; using kudu::master::GetTableStatisticsResponsePB; using kudu::master::GetTabletLocationsRequestPB; using kudu::master::GetTabletLocationsResponsePB; using kudu::master::ListTablesRequestPB; using kudu::master::ListTablesResponsePB; using kudu::master::ListTabletServersRequestPB; using kudu::master::ListTabletServersResponsePB; using kudu::master::ListTabletServersResponsePB_Entry; using kudu::master::MasterServiceProxy; using kudu::master::TSInfoPB; using kudu::master::TableIdentifierPB; using kudu::master::TabletLocationsPB; using kudu::rpc::BackoffType; using kudu::rpc::Messenger; using kudu::rpc::MessengerBuilder; using kudu::rpc::RpcController; using kudu::rpc::UserCredentials; using kudu::tserver::ScanResponsePB; using std::map; using std::set; using std::string; using std::unique_ptr; using std::vector; using strings::Substitute; MAKE_ENUM_LIMITS(kudu::client::KuduSession::FlushMode, kudu::client::KuduSession::AUTO_FLUSH_SYNC, kudu::client::KuduSession::MANUAL_FLUSH); MAKE_ENUM_LIMITS(kudu::client::KuduSession::ExternalConsistencyMode, kudu::client::KuduSession::CLIENT_PROPAGATED, kudu::client::KuduSession::COMMIT_WAIT); MAKE_ENUM_LIMITS(kudu::client::KuduScanner::ReadMode, kudu::client::KuduScanner::READ_LATEST, kudu::client::KuduScanner::READ_YOUR_WRITES); MAKE_ENUM_LIMITS(kudu::client::KuduScanner::OrderMode, kudu::client::KuduScanner::UNORDERED, kudu::client::KuduScanner::ORDERED); struct tm; namespace kudu { class simple_spinlock; namespace client { class ResourceMetrics; using internal::AsyncLeaderMasterRpc; using internal::MetaCache; using sp::shared_ptr; const char* kVerboseEnvVar = ""KUDU_CLIENT_VERBOSE""; #if defined(kudu_client_exported_EXPORTS) static const char* kProgName = ""kudu_client""; // We need to reroute all logging to stderr when the client library is // loaded. GoogleOnceInit() can do that, but there are multiple entry // points into the client code, and it'd need to be called in each one. // So instead, let's use a constructor function. // // This is restricted to the exported client builds only. In case of linking // with non-exported kudu client library, logging must be initialized // from the main() function of the corresponding binary: usually, that's done // by calling InitGoogleLoggingSafe(argv[0]). __attribute__((constructor)) static void InitializeBasicLogging() { InitGoogleLoggingSafeBasic(kProgName); SetVerboseLevelFromEnvVar(); } #endif // Set Client logging verbose level from environment variable. void SetVerboseLevelFromEnvVar() { int32_t level = 0; // this is the default logging level; const char* env_verbose_level = std::getenv(kVerboseEnvVar); if (env_verbose_level != nullptr) { if (safe_strto32(env_verbose_level, &level) && (level >= 0)) { SetVerboseLogLevel(level); } else { LOG(WARNING) << ""Invalid verbose level from environment variable "" << kVerboseEnvVar; } } } // Adapts between the internal LogSeverity and the client's KuduLogSeverity. static void LoggingAdapterCB(KuduLoggingCallback* user_cb, LogSeverity severity, const char* filename, int line_number, const struct ::tm* time, const char* message, size_t message_len) { KuduLogSeverity client_severity; switch (severity) { case kudu::SEVERITY_INFO: client_severity = SEVERITY_INFO; break; case kudu::SEVERITY_WARNING: client_severity = SEVERITY_WARNING; break; case kudu::SEVERITY_ERROR: client_severity = SEVERITY_ERROR; break; case kudu::SEVERITY_FATAL: client_severity = SEVERITY_FATAL; break; default: LOG(FATAL) << ""Unknown Kudu log severity: "" << severity; } user_cb->Run(client_severity, filename, line_number, time, message, message_len); } void InstallLoggingCallback(KuduLoggingCallback* cb) { RegisterLoggingCallback( [=](LogSeverity severity, const char* filename, int line_number, const struct ::tm* time, const char* message, size_t message_len) { LoggingAdapterCB(cb, severity, filename, line_number, time, message, message_len); }); } void UninstallLoggingCallback() { UnregisterLoggingCallback(); } void SetVerboseLogLevel(int level) { FLAGS_v = level; } Status SetInternalSignalNumber(int signum) { return SetStackTraceSignal(signum); } Status DisableSaslInitialization() { return kudu::rpc::DisableSaslInitialization(); } Status DisableOpenSSLInitialization() { return kudu::security::DisableOpenSSLInitialization(); } string GetShortVersionString() { return VersionInfo::GetVersionInfo(); } string GetAllVersionInfo() { return VersionInfo::GetAllVersionInfo(); } KuduClientBuilder::KuduClientBuilder() : data_(new KuduClientBuilder::Data()) { } KuduClientBuilder::~KuduClientBuilder() { delete data_; } KuduClientBuilder& KuduClientBuilder::clear_master_server_addrs() { data_->master_server_addrs_.clear(); return *this; } KuduClientBuilder& KuduClientBuilder::master_server_addrs(const vector& addrs) { for (const string& addr : addrs) { data_->master_server_addrs_.push_back(addr); } return *this; } KuduClientBuilder& KuduClientBuilder::add_master_server_addr(const string& addr) { data_->master_server_addrs_.push_back(addr); return *this; } KuduClientBuilder& KuduClientBuilder::default_admin_operation_timeout(const MonoDelta& timeout) { data_->default_admin_operation_timeout_ = timeout; return *this; } KuduClientBuilder& KuduClientBuilder::default_rpc_timeout(const MonoDelta& timeout) { data_->default_rpc_timeout_ = timeout; return *this; } KuduClientBuilder& KuduClientBuilder::import_authentication_credentials(string authn_creds) { data_->authn_creds_ = std::move(authn_creds); return *this; } KuduClientBuilder& KuduClientBuilder::num_reactors(int num_reactors) { data_->num_reactors_ = num_reactors; return *this; } namespace { Status ImportAuthnCreds(const string& authn_creds, Messenger* messenger, UserCredentials* user_credentials) { AuthenticationCredentialsPB pb; if (!pb.ParseFromString(authn_creds)) { return Status::InvalidArgument(""invalid authentication data""); } if (pb.has_authn_token()) { const auto& tok = pb.authn_token(); if (!tok.has_token_data() || !tok.has_signature() || !tok.has_signing_key_seq_num()) { return Status::InvalidArgument(""invalid authentication token""); } messenger->set_authn_token(tok); } if (pb.has_real_user()) { user_credentials->set_real_user(pb.real_user()); } for (const string& cert_der : pb.ca_cert_ders()) { security::Cert cert; RETURN_NOT_OK_PREPEND(cert.FromString(cert_der, security::DataFormat::DER), ""could not import CA cert""); RETURN_NOT_OK_PREPEND(messenger->mutable_tls_context()->AddTrustedCertificate(cert), ""could not trust CA cert""); } return Status::OK(); } } // anonymous namespace Status KuduClientBuilder::Build(shared_ptr* client) { RETURN_NOT_OK(CheckCPUFlags()); // Init messenger. MessengerBuilder builder(""client""); if (data_->num_reactors_) { builder.set_num_reactors(data_->num_reactors_.get()); } std::shared_ptr messenger; RETURN_NOT_OK(builder.Build(&messenger)); UserCredentials user_credentials; // Parse and import the provided authn data, if any. if (!data_->authn_creds_.empty()) { RETURN_NOT_OK(ImportAuthnCreds(data_->authn_creds_, messenger.get(), &user_credentials)); } if (!user_credentials.has_real_user()) { // If there are no authentication credentials, then set the real user to the // currently logged-in user. RETURN_NOT_OK(user_credentials.SetLoggedInRealUser()); } shared_ptr c(new KuduClient); c->data_->messenger_ = std::move(messenger); c->data_->user_credentials_ = std::move(user_credentials); c->data_->master_server_addrs_ = data_->master_server_addrs_; c->data_->default_admin_operation_timeout_ = data_->default_admin_operation_timeout_; c->data_->default_rpc_timeout_ = data_->default_rpc_timeout_; // Let's allow for plenty of time for discovering the master the first // time around. MonoTime deadline = MonoTime::Now() + c->default_admin_operation_timeout(); RETURN_NOT_OK_PREPEND(c->data_->ConnectToCluster(c.get(), deadline), ""Could not connect to the cluster""); c->data_->meta_cache_.reset(new MetaCache(c.get(), data_->replica_visibility_)); // Init local host names used for locality decisions. RETURN_NOT_OK_PREPEND(c->data_->InitLocalHostNames(), ""Could not determine local host names""); c->data_->request_tracker_ = new rpc::RequestTracker(c->data_->client_id_); client->swap(c); return Status::OK(); } KuduClient::KuduClient() : data_(new KuduClient::Data()) { static ObjectIdGenerator oid_generator; data_->client_id_ = oid_generator.Next(); } KuduClient::~KuduClient() { delete data_; } KuduTableCreator* KuduClient::NewTableCreator() { return new KuduTableCreator(this); } Status KuduClient::IsCreateTableInProgress(const string& table_name, bool* create_in_progress) { MonoTime deadline = MonoTime::Now() + default_admin_operation_timeout(); TableIdentifierPB table; table.set_table_name(table_name); return data_->IsCreateTableInProgress(this, std::move(table), deadline, create_in_progress); } Status KuduClient::DeleteTable(const string& table_name) { return DeleteTableInCatalogs(table_name, true); } Status KuduClient::DeleteTableInCatalogs(const string& table_name, bool modify_external_catalogs) { MonoTime deadline = MonoTime::Now() + default_admin_operation_timeout(); return data_->DeleteTable(this, table_name, deadline, modify_external_catalogs); } KuduTableAlterer* KuduClient::NewTableAlterer(const string& table_name) { return new KuduTableAlterer(this, table_name); } Status KuduClient::IsAlterTableInProgress(const string& table_name, bool* alter_in_progress) { MonoTime deadline = MonoTime::Now() + default_admin_operation_timeout(); TableIdentifierPB table; table.set_table_name(table_name); return data_->IsAlterTableInProgress(this, std::move(table), deadline, alter_in_progress); } Status KuduClient::GetTableSchema(const string& table_name, KuduSchema* schema) { MonoTime deadline = MonoTime::Now() + default_admin_operation_timeout(); TableIdentifierPB table; table.set_table_name(table_name); return data_->GetTableSchema(this, deadline, table, schema, nullptr, // partition schema nullptr, // table id nullptr, // table name nullptr, // number of replicas nullptr); // extra configs } Status KuduClient::ListTabletServers(vector* tablet_servers) { ListTabletServersRequestPB req; ListTabletServersResponsePB resp; MonoTime deadline = MonoTime::Now() + default_admin_operation_timeout(); RETURN_NOT_OK(data_->ListTabletServers(this, deadline, req, &resp)); for (int i = 0; i < resp.servers_size(); i++) { const ListTabletServersResponsePB_Entry& e = resp.servers(i); HostPort hp = HostPortFromPB(e.registration().rpc_addresses(0)); unique_ptr ts(new KuduTabletServer); ts->data_ = new KuduTabletServer::Data(e.instance_id().permanent_uuid(), hp, e.location()); tablet_servers->push_back(ts.release()); } return Status::OK(); } Status KuduClient::ListTables(vector* tables, const string& filter) { ListTablesRequestPB req; ListTablesResponsePB resp; if (!filter.empty()) { req.set_name_filter(filter); } MonoTime deadline = MonoTime::Now() + default_admin_operation_timeout(); Synchronizer sync; AsyncLeaderMasterRpc rpc( deadline, this, BackoffType::EXPONENTIAL, req, &resp, &MasterServiceProxy::ListTablesAsync, ""ListTables"", sync.AsStatusCallback(), {}); rpc.SendRpc(); RETURN_NOT_OK(sync.Wait()); if (resp.has_error()) { return StatusFromPB(resp.error().status()); } for (int i = 0; i < resp.tables_size(); i++) { tables->push_back(resp.tables(i).name()); } return Status::OK(); } Status KuduClient::TableExists(const string& table_name, bool* exists) { auto s = GetTableSchema(table_name, nullptr); if (s.ok()) { *exists = true; } else if (s.IsNotFound()) { *exists = false; s = Status::OK(); } return s; } Status KuduClient::OpenTable(const string& table_name, shared_ptr* table) { TableIdentifierPB table_identifier; table_identifier.set_table_name(table_name); return data_->OpenTable(this, table_identifier, table); } shared_ptr KuduClient::NewSession() { shared_ptr ret(new KuduSession(shared_from_this())); ret->data_->Init(ret); return ret; } Status KuduClient::GetTablet(const string& tablet_id, KuduTablet** tablet) { GetTabletLocationsRequestPB req; GetTabletLocationsResponsePB resp; req.add_tablet_ids(tablet_id); req.set_intern_ts_infos_in_response(true); MonoTime deadline = MonoTime::Now() + default_admin_operation_timeout(); Synchronizer sync; AsyncLeaderMasterRpc rpc( deadline, this, BackoffType::EXPONENTIAL, req, &resp, &MasterServiceProxy::GetTabletLocationsAsync, ""GetTabletLocations"", sync.AsStatusCallback(), {}); rpc.SendRpc(); RETURN_NOT_OK(sync.Wait()); if (resp.has_error()) { return StatusFromPB(resp.error().status()); } if (resp.tablet_locations_size() == 0) { return Status::NotFound(Substitute(""$0: tablet not found"", tablet_id)); } if (resp.tablet_locations_size() != 1) { return Status::IllegalState(Substitute( ""Expected only one tablet, but received $0"", resp.tablet_locations_size())); } const TabletLocationsPB& t = resp.tablet_locations(0); vector replicas; ElementDeleter deleter(&replicas); auto add_replica_func = [](const TSInfoPB& ts_info, const RaftPeerPB::Role role, vector* replicas) { if (ts_info.rpc_addresses_size() == 0) { return Status::IllegalState(Substitute( ""No RPC addresses found for tserver $0"", ts_info.permanent_uuid())); } HostPort hp = HostPortFromPB(ts_info.rpc_addresses(0)); unique_ptr ts(new KuduTabletServer); ts->data_ = new KuduTabletServer::Data(ts_info.permanent_uuid(), hp, ts_info.location()); // TODO(aserbin): try to use member_type instead of role for metacache. bool is_leader = role == RaftPeerPB::LEADER; bool is_voter = is_leader || role == RaftPeerPB::FOLLOWER; unique_ptr replica(new KuduReplica); replica->data_ = new KuduReplica::Data(is_leader, is_voter, std::move(ts)); replicas->push_back(replica.release()); return Status::OK(); }; // Handle ""old-style"" non-interned replicas. It's used for backward compatibility. for (const auto& r : t.deprecated_replicas()) { RETURN_NOT_OK(add_replica_func(r.ts_info(), r.role(), &replicas)); } // Handle interned replicas. for (const auto& r : t.interned_replicas()) { RETURN_NOT_OK(add_replica_func(resp.ts_infos(r.ts_info_idx()), r.role(), &replicas)); } unique_ptr client_tablet(new KuduTablet); client_tablet->data_ = new KuduTablet::Data(tablet_id, std::move(replicas)); replicas.clear(); *tablet = client_tablet.release(); return Status::OK(); } Status KuduClient::GetTableStatistics(const string& table_name, KuduTableStatistics** statistics) { GetTableStatisticsRequestPB req; GetTableStatisticsResponsePB resp; TableIdentifierPB* table = req.mutable_table(); table->set_table_name(table_name); MonoTime deadline = MonoTime::Now() + default_admin_operation_timeout(); Synchronizer sync; AsyncLeaderMasterRpc rpc( deadline, this, BackoffType::EXPONENTIAL, req, &resp, &MasterServiceProxy::GetTableStatisticsAsync, ""GetTableStatistics"", sync.AsStatusCallback(), {}); rpc.SendRpc(); RETURN_NOT_OK(sync.Wait()); if (resp.has_error()) { return StatusFromPB(resp.error().status()); } unique_ptr table_statistics(new KuduTableStatistics); table_statistics->data_ = new KuduTableStatistics::Data( resp.has_on_disk_size() ? boost::optional(resp.on_disk_size()) : boost::none, resp.has_live_row_count() ? boost::optional(resp.live_row_count()) : boost::none); *statistics = table_statistics.release(); return Status::OK(); } string KuduClient::GetMasterAddresses() const { return HostPort::ToCommaSeparatedString(data_->master_hostports()); } bool KuduClient::IsMultiMaster() const { return data_->master_server_addrs_.size() > 1; } const MonoDelta& KuduClient::default_admin_operation_timeout() const { return data_->default_admin_operation_timeout_; } const MonoDelta& KuduClient::default_rpc_timeout() const { return data_->default_rpc_timeout_; } const uint64_t KuduClient::kNoTimestamp = 0; uint64_t KuduClient::GetLatestObservedTimestamp() const { return data_->GetLatestObservedTimestamp(); } void KuduClient::SetLatestObservedTimestamp(uint64_t ht_timestamp) { data_->UpdateLatestObservedTimestamp(ht_timestamp); } Status KuduClient::ExportAuthenticationCredentials(string* authn_creds) const { AuthenticationCredentialsPB pb; boost::optional tok = data_->messenger_->authn_token(); if (tok) { pb.mutable_authn_token()->CopyFrom(*tok); } pb.set_real_user(data_->user_credentials_.real_user()); vector cert_ders; RETURN_NOT_OK_PREPEND(data_->messenger_->tls_context().DumpTrustedCerts(&cert_ders), ""could not export trusted certs""); for (auto& der : cert_ders) { pb.add_ca_cert_ders()->assign(std::move(der)); } if (!pb.SerializeToString(authn_creds)) { return Status::RuntimeError(""could not serialize authentication data""); } return Status::OK(); } string KuduClient::GetHiveMetastoreUris() const { std::lock_guard l(data_->leader_master_lock_); return data_->hive_metastore_uris_; } bool KuduClient::GetHiveMetastoreSaslEnabled() const { std::lock_guard l(data_->leader_master_lock_); return data_->hive_metastore_sasl_enabled_; } string KuduClient::GetHiveMetastoreUuid() const { std::lock_guard l(data_->leader_master_lock_); return data_->hive_metastore_uuid_; } string KuduClient::location() const { return data_->location(); } //////////////////////////////////////////////////////////// // KuduTableCreator //////////////////////////////////////////////////////////// KuduTableCreator::KuduTableCreator(KuduClient* client) : data_(new KuduTableCreator::Data(client)) { } KuduTableCreator::~KuduTableCreator() { delete data_; } KuduTableCreator& KuduTableCreator::table_name(const string& name) { data_->table_name_ = name; return *this; } KuduTableCreator& KuduTableCreator::schema(const KuduSchema* schema) { data_->schema_ = schema; return *this; } KuduTableCreator& KuduTableCreator::add_hash_partitions(const vector& columns, int32_t num_buckets) { return add_hash_partitions(columns, num_buckets, 0); } KuduTableCreator& KuduTableCreator::add_hash_partitions(const vector& columns, int32_t num_buckets, int32_t seed) { PartitionSchemaPB::HashBucketSchemaPB* bucket_schema = data_->partition_schema_.add_hash_bucket_schemas(); for (const string& col_name : columns) { bucket_schema->add_columns()->set_name(col_name); } bucket_schema->set_num_buckets(num_buckets); bucket_schema->set_seed(seed); return *this; } KuduTableCreator& KuduTableCreator::set_range_partition_columns(const vector& columns) { PartitionSchemaPB::RangeSchemaPB* range_schema = data_->partition_schema_.mutable_range_schema(); range_schema->Clear(); for (const string& col_name : columns) { range_schema->add_columns()->set_name(col_name); } return *this; } KuduTableCreator& KuduTableCreator::add_range_partition_split(KuduPartialRow* split_row) { data_->range_partition_splits_.emplace_back(split_row); return *this; } KuduTableCreator& KuduTableCreator::split_rows(const vector& rows) { for (const KuduPartialRow* row : rows) { data_->range_partition_splits_.emplace_back(const_cast(row)); } return *this; } KuduTableCreator& KuduTableCreator::add_range_partition(KuduPartialRow* lower_bound, KuduPartialRow* upper_bound, RangePartitionBound lower_bound_type, RangePartitionBound upper_bound_type) { data_->range_partition_bounds_.push_back({ unique_ptr(lower_bound), unique_ptr(upper_bound), lower_bound_type, upper_bound_type, }); return *this; } KuduTableCreator& KuduTableCreator::num_replicas(int num_replicas) { data_->num_replicas_ = num_replicas; return *this; } KuduTableCreator& KuduTableCreator::dimension_label(const std::string& dimension_label) { data_->dimension_label_ = dimension_label; return *this; } KuduTableCreator& KuduTableCreator::extra_configs(const map& extra_configs) { data_->extra_configs_ = extra_configs; return *this; } KuduTableCreator& KuduTableCreator::timeout(const MonoDelta& timeout) { data_->timeout_ = timeout; return *this; } KuduTableCreator& KuduTableCreator::wait(bool wait) { data_->wait_ = wait; return *this; } Status KuduTableCreator::Create() { if (!data_->table_name_.length()) { return Status::InvalidArgument(""Missing table name""); } if (!data_->schema_) { return Status::InvalidArgument(""Missing schema""); } if (!data_->partition_schema_.has_range_schema() && data_->partition_schema_.hash_bucket_schemas().empty()) { return Status::InvalidArgument( ""Table partitioning must be specified using "" ""add_hash_partitions or set_range_partition_columns""); } // Build request. CreateTableRequestPB req; CreateTableResponsePB resp; req.set_name(data_->table_name_); if (data_->num_replicas_ != boost::none) { req.set_num_replicas(data_->num_replicas_.get()); } if (data_->dimension_label_) { req.set_dimension_label(data_->dimension_label_.get()); } if (data_->extra_configs_) { req.mutable_extra_configs()->insert(data_->extra_configs_->begin(), data_->extra_configs_->end()); } RETURN_NOT_OK_PREPEND(SchemaToPB(*data_->schema_->schema_, req.mutable_schema(), SCHEMA_PB_WITHOUT_WRITE_DEFAULT), ""Invalid schema""); RowOperationsPBEncoder encoder(req.mutable_split_rows_range_bounds()); for (const auto& row : data_->range_partition_splits_) { if (!row) { return Status::InvalidArgument(""range split row must not be null""); } encoder.Add(RowOperationsPB::SPLIT_ROW, *row); } for (const auto& bound : data_->range_partition_bounds_) { if (!bound.lower_bound || !bound.upper_bound) { return Status::InvalidArgument(""range bounds must not be null""); } RowOperationsPB_Type lower_bound_type = bound.lower_bound_type == KuduTableCreator::INCLUSIVE_BOUND ? RowOperationsPB::RANGE_LOWER_BOUND : RowOperationsPB::EXCLUSIVE_RANGE_LOWER_BOUND; RowOperationsPB_Type upper_bound_type = bound.upper_bound_type == KuduTableCreator::EXCLUSIVE_BOUND ? RowOperationsPB::RANGE_UPPER_BOUND : RowOperationsPB::INCLUSIVE_RANGE_UPPER_BOUND; encoder.Add(lower_bound_type, *bound.lower_bound); encoder.Add(upper_bound_type, *bound.upper_bound); } req.mutable_partition_schema()->CopyFrom(data_->partition_schema_); MonoTime deadline = MonoTime::Now(); if (data_->timeout_.Initialized()) { deadline += data_->timeout_; } else { deadline += data_->client_->default_admin_operation_timeout(); } RETURN_NOT_OK_PREPEND(data_->client_->data_->CreateTable(data_->client_, req, &resp, deadline, !data_->range_partition_bounds_.empty()), Substitute(""Error creating table $0 on the master"", data_->table_name_)); // Spin until the table is fully created, if requested. if (data_->wait_) { TableIdentifierPB table; table.set_table_id(resp.table_id()); RETURN_NOT_OK(data_->client_->data_->WaitForCreateTableToFinish(data_->client_, table, deadline)); } return Status::OK(); } //////////////////////////////////////////////////////////// // KuduTableStatistics //////////////////////////////////////////////////////////// KuduTableStatistics::KuduTableStatistics() : data_(nullptr) { } KuduTableStatistics::~KuduTableStatistics() { delete data_; } int64_t KuduTableStatistics::on_disk_size() const { return data_->on_disk_size_ ? *data_->on_disk_size_ : -1; } int64_t KuduTableStatistics::live_row_count() const { return data_->live_row_count_ ? *data_->live_row_count_ : -1; } std::string KuduTableStatistics::ToString() const { return data_->ToString(); } //////////////////////////////////////////////////////////// // KuduTable //////////////////////////////////////////////////////////// KuduTable::KuduTable(const shared_ptr& client, const string& name, const string& id, int num_replicas, const KuduSchema& schema, const PartitionSchema& partition_schema, const map& extra_configs) : data_(new KuduTable::Data(client, name, id, num_replicas, schema, partition_schema, extra_configs)) { } KuduTable::~KuduTable() { delete data_; } const string& KuduTable::name() const { return data_->name_; } const string& KuduTable::id() const { return data_->id_; } const KuduSchema& KuduTable::schema() const { return data_->schema_; } int KuduTable::num_replicas() const { return data_->num_replicas_; } KuduInsert* KuduTable::NewInsert() { return new KuduInsert(shared_from_this()); } KuduInsertIgnore* KuduTable::NewInsertIgnore() { return new KuduInsertIgnore(shared_from_this()); } KuduUpsert* KuduTable::NewUpsert() { return new KuduUpsert(shared_from_this()); } KuduUpdate* KuduTable::NewUpdate() { return new KuduUpdate(shared_from_this()); } KuduDelete* KuduTable::NewDelete() { return new KuduDelete(shared_from_this()); } KuduClient* KuduTable::client() const { return data_->client_.get(); } const PartitionSchema& KuduTable::partition_schema() const { return data_->partition_schema_; } const map& KuduTable::extra_configs() const { return data_->extra_configs_; } KuduPredicate* KuduTable::NewComparisonPredicate(const Slice& col_name, KuduPredicate::ComparisonOp op, KuduValue* value) { // We always take ownership of value; this ensures cleanup if the predicate is invalid. auto cleanup = MakeScopedCleanup([&]() { delete value; }); return data_->MakePredicate(col_name, [&](const ColumnSchema& col_schema) { // Ownership of value is passed to the valid returned predicate. cleanup.cancel(); return new KuduPredicate(new ComparisonPredicateData(col_schema, op, value)); }); } KuduPredicate* KuduTable::NewInBloomFilterPredicate(const Slice& col_name, vector* bloom_filters) { // We always take ownership of values; this ensures cleanup if the predicate is invalid. auto cleanup = MakeScopedCleanup([&]() { STLDeleteElements(bloom_filters); }); // Empty vector of bloom filters will select all rows. Hence disallowed. if (bloom_filters->empty()) { return new KuduPredicate( new ErrorPredicateData(Status::InvalidArgument(""No Bloom filters supplied""))); } // Transfer the Bloom filter raw ptrs over to vector of unique ptrs. // There is a possibility of emplace_back() throwing exception, so in such a case the // transferred Bloom filters in unique_ptrs will be cleaned-up on exiting scope // automatically and the non-nullptr Bloom filters in input ""bloom_filters"" vector // will be cleaned up by the explicit scoped ""cleanup"". vector> bloom_filters_owned; bloom_filters_owned.reserve(bloom_filters->size()); for (auto& bf : *bloom_filters) { bloom_filters_owned.emplace_back(bf); bf = nullptr; } return data_->MakePredicate(col_name, [&](const ColumnSchema& col_schema) { // At this point we could cancel the scoped ""cleanup"". But the scoped cleanup // not only deletes pointers contained in the vector but also clears the vector // and we want the vector be cleared as expected by the caller. return new KuduPredicate( new InBloomFilterPredicateData(col_schema, std::move(bloom_filters_owned))); }); } KuduPredicate* KuduTable::NewInBloomFilterPredicate(const Slice& col_name, const vector& bloom_filters) { // Empty vector of bloom filters will select all rows. Hence disallowed. if (bloom_filters.empty()) { return new KuduPredicate( new ErrorPredicateData(Status::InvalidArgument(""No Bloom filters supplied""))); } // Extract the Block Bloom filters. vector bbf_vec; for (const auto& bf_slice : bloom_filters) { auto* bbf = reinterpret_cast(const_cast(bf_slice.data())); // In this case, the Block Bloom filters are supplied as opaque pointers // and the predicate will convert them to well-defined pointer types // but will NOT take ownership of those pointers. Hence a custom deleter, // DirectBloomFilterDataDeleter, is used that gives control over ownership. DirectBlockBloomFilterUniqPtr bf_uniq_ptr( bbf, DirectBloomFilterDataDeleter(false /*owned*/)); bbf_vec.emplace_back(std::move(bf_uniq_ptr)); } return data_->MakePredicate(col_name, [&](const ColumnSchema& col_schema) { return new KuduPredicate( new InDirectBloomFilterPredicateData(col_schema, std::move(bbf_vec))); }); } KuduPredicate* KuduTable::NewInListPredicate(const Slice& col_name, vector* values) { // We always take ownership of values; this ensures cleanup if the predicate is invalid. auto cleanup = MakeScopedCleanup([&]() { STLDeleteElements(values); }); return data_->MakePredicate(col_name, [&](const ColumnSchema& col_schema) { // Ownership of values is passed to the valid returned predicate. cleanup.cancel(); return new KuduPredicate(new InListPredicateData(col_schema, values)); }); } KuduPredicate* KuduTable::NewIsNotNullPredicate(const Slice& col_name) { return data_->MakePredicate(col_name, [&](const ColumnSchema& col_schema) { return new KuduPredicate(new IsNotNullPredicateData(col_schema)); }); } KuduPredicate* KuduTable::NewIsNullPredicate(const Slice& col_name) { return data_->MakePredicate(col_name, [&](const ColumnSchema& col_schema) { return new KuduPredicate(new IsNullPredicateData(col_schema)); }); } // The strategy for retrieving the partitions from the metacache is adapted // from KuduScanTokenBuilder::Data::Build. Status KuduTable::ListPartitions(vector* partitions) { DCHECK(partitions); partitions->clear(); auto& client = data_->client_; const auto deadline = MonoTime::Now() + client->default_admin_operation_timeout(); PartitionPruner pruner; pruner.Init(*data_->schema_.schema_, data_->partition_schema_, ScanSpec()); while (pruner.HasMorePartitionKeyRanges()) { scoped_refptr tablet; Synchronizer sync; const string& partition_key = pruner.NextPartitionKey(); client->data_->meta_cache_->LookupTabletByKey( this, partition_key, deadline, client::internal::MetaCache::LookupType::kLowerBound, &tablet, sync.AsStatusCallback()); Status s = sync.Wait(); if (s.IsNotFound()) { // No more tablets. break; } RETURN_NOT_OK(s); partitions->emplace_back(tablet->partition()); pruner.RemovePartitionKeyRange(tablet->partition().partition_key_end()); } return Status::OK(); } //////////////////////////////////////////////////////////// // Error //////////////////////////////////////////////////////////// const Status& KuduError::status() const { return data_->status_; } const KuduWriteOperation& KuduError::failed_op() const { return *data_->failed_op_; } KuduWriteOperation* KuduError::release_failed_op() { CHECK_NOTNULL(data_->failed_op_.get()); return data_->failed_op_.release(); } bool KuduError::was_possibly_successful() const { // TODO: implement me - right now be conservative. return true; } KuduError::KuduError(KuduWriteOperation* failed_op, const Status& status) : data_(new KuduError::Data(unique_ptr(failed_op), status)) { } KuduError::~KuduError() { delete data_; } //////////////////////////////////////////////////////////// // KuduSession //////////////////////////////////////////////////////////// KuduSession::KuduSession(const shared_ptr& client) : data_(new KuduSession::Data(client, client->data_->messenger_)) { } KuduSession::~KuduSession() { WARN_NOT_OK(data_->Close(true), ""Closed Session with pending operations.""); delete data_; } Status KuduSession::Close() { return data_->Close(false); } Status KuduSession::SetFlushMode(FlushMode m) { if (!tight_enum_test(m)) { // Be paranoid in client code. return Status::InvalidArgument(""Bad flush mode""); } return data_->SetFlushMode(m); } Status KuduSession::SetExternalConsistencyMode(ExternalConsistencyMode m) { if (!tight_enum_test(m)) { // Be paranoid in client code. return Status::InvalidArgument(""Bad external consistency mode""); } return data_->SetExternalConsistencyMode(m); } Status KuduSession::SetMutationBufferSpace(size_t size) { return data_->SetBufferBytesLimit(size); } Status KuduSession::SetMutationBufferFlushWatermark(double watermark_pct) { return data_->SetBufferFlushWatermark( static_cast(100.0 * watermark_pct)); } Status KuduSession::SetMutationBufferFlushInterval(unsigned int millis) { return data_->SetBufferFlushInterval(millis); } Status KuduSession::SetMutationBufferMaxNum(unsigned int max_num) { return data_->SetMaxBatchersNum(max_num); } void KuduSession::SetTimeoutMillis(int timeout_ms) { data_->SetTimeoutMillis(timeout_ms); } Status KuduSession::Flush() { return data_->Flush(); } void KuduSession::FlushAsync(KuduStatusCallback* user_callback) { data_->FlushAsync(user_callback); } bool KuduSession::HasPendingOperations() const { return data_->HasPendingOperations(); } Status KuduSession::Apply(KuduWriteOperation* write_op) { RETURN_NOT_OK(data_->ApplyWriteOp(write_op)); // Thread-safety note: this method should not be called concurrently // with other methods which modify the KuduSession::Data members, so it // should be safe to read KuduSession::Data members without protection. if (data_->flush_mode_ == AUTO_FLUSH_SYNC) { RETURN_NOT_OK(data_->Flush()); } return Status::OK(); } int KuduSession::CountBufferedOperations() const { return data_->CountBufferedOperations(); } Status KuduSession::SetErrorBufferSpace(size_t size_bytes) { return data_->error_collector_->SetMaxMemSize(size_bytes); } int KuduSession::CountPendingErrors() const { return data_->error_collector_->CountErrors(); } void KuduSession::GetPendingErrors(vector* errors, bool* overflowed) { data_->error_collector_->GetErrors(errors, overflowed); } KuduClient* KuduSession::client() const { return data_->client_.get(); } //////////////////////////////////////////////////////////// // KuduTableAlterer //////////////////////////////////////////////////////////// KuduTableAlterer::KuduTableAlterer(KuduClient* client, const string& name) : data_(new Data(client, name)) { } KuduTableAlterer::~KuduTableAlterer() { delete data_; } KuduTableAlterer* KuduTableAlterer::RenameTo(const string& new_name) { data_->rename_to_ = new_name; return this; } KuduColumnSpec* KuduTableAlterer::AddColumn(const string& name) { Data::Step s = { AlterTableRequestPB::ADD_COLUMN, new KuduColumnSpec(name), nullptr, nullptr }; auto* spec = s.spec; data_->steps_.emplace_back(std::move(s)); return spec; } KuduColumnSpec* KuduTableAlterer::AlterColumn(const string& name) { Data::Step s = { AlterTableRequestPB::ALTER_COLUMN, new KuduColumnSpec(name), nullptr, nullptr }; auto* spec = s.spec; data_->steps_.emplace_back(std::move(s)); return spec; } KuduTableAlterer* KuduTableAlterer::DropColumn(const string& name) { Data::Step s = { AlterTableRequestPB::DROP_COLUMN, new KuduColumnSpec(name), nullptr, nullptr }; data_->steps_.emplace_back(std::move(s)); return this; } KuduTableAlterer* KuduTableAlterer::AddRangePartition( KuduPartialRow* lower_bound, KuduPartialRow* upper_bound, KuduTableCreator::RangePartitionBound lower_bound_type, KuduTableCreator::RangePartitionBound upper_bound_type) { return AddRangePartitionWithDimension( lower_bound, upper_bound, """", lower_bound_type, upper_bound_type); } KuduTableAlterer* KuduTableAlterer::AddRangePartitionWithDimension( KuduPartialRow* lower_bound, KuduPartialRow* upper_bound, const std::string& dimension_label, KuduTableCreator::RangePartitionBound lower_bound_type, KuduTableCreator::RangePartitionBound upper_bound_type) { if (lower_bound == nullptr || upper_bound == nullptr) { data_->status_ = Status::InvalidArgument(""range partition bounds may not be null""); return this; } if (!lower_bound->schema()->Equals(*upper_bound->schema())) { data_->status_ = Status::InvalidArgument(""range partition bounds must have matching schemas""); return this; } if (data_->schema_ == nullptr) { data_->schema_ = lower_bound->schema(); } else if (!lower_bound->schema()->Equals(*data_->schema_)) { data_->status_ = Status::InvalidArgument(""range partition bounds must have matching schemas""); return this; } Data::Step s { AlterTableRequestPB::ADD_RANGE_PARTITION, nullptr, unique_ptr(lower_bound), unique_ptr(upper_bound), lower_bound_type, upper_bound_type, dimension_label.empty() ? boost::none : boost::make_optional(dimension_label) }; data_->steps_.emplace_back(std::move(s)); data_->has_alter_partitioning_steps = true; return this; } KuduTableAlterer* KuduTableAlterer::DropRangePartition( KuduPartialRow* lower_bound, KuduPartialRow* upper_bound, KuduTableCreator::RangePartitionBound lower_bound_type, KuduTableCreator::RangePartitionBound upper_bound_type) { if (lower_bound == nullptr || upper_bound == nullptr) { data_->status_ = Status::InvalidArgument(""range partition bounds may not be null""); return this; } if (!lower_bound->schema()->Equals(*upper_bound->schema())) { data_->status_ = Status::InvalidArgument(""range partition bounds must have matching schemas""); return this; } if (data_->schema_ == nullptr) { data_->schema_ = lower_bound->schema(); } else if (!lower_bound->schema()->Equals(*data_->schema_)) { data_->status_ = Status::InvalidArgument(""range partition bounds must have matching schemas""); return this; } Data::Step s { AlterTableRequestPB::DROP_RANGE_PARTITION, nullptr, unique_ptr(lower_bound), unique_ptr(upper_bound), lower_bound_type, upper_bound_type }; data_->steps_.emplace_back(std::move(s)); data_->has_alter_partitioning_steps = true; return this; } KuduTableAlterer* KuduTableAlterer::AlterExtraConfig(const map& extra_configs) { data_->new_extra_configs_ = extra_configs; return this; } KuduTableAlterer* KuduTableAlterer::timeout(const MonoDelta& timeout) { data_->timeout_ = timeout; return this; } KuduTableAlterer* KuduTableAlterer::wait(bool wait) { data_->wait_ = wait; return this; } KuduTableAlterer* KuduTableAlterer::modify_external_catalogs( bool modify_external_catalogs) { data_->modify_external_catalogs_ = modify_external_catalogs; return this; } Status KuduTableAlterer::Alter() { AlterTableRequestPB req; AlterTableResponsePB resp; RETURN_NOT_OK(data_->ToRequest(&req)); MonoDelta timeout = data_->timeout_.Initialized() ? data_->timeout_ : data_->client_->default_admin_operation_timeout(); MonoTime deadline = MonoTime::Now() + timeout; RETURN_NOT_OK(data_->client_->data_->AlterTable(data_->client_, req, &resp, deadline, data_->has_alter_partitioning_steps)); if (data_->has_alter_partitioning_steps) { // If the table partitions change, clear the local meta cache so that the // new tablets can immediately be written to and scanned, and the old // tablets won't be seen again. This also prevents rows being batched for // the wrong tablet when a partition is dropped and added in the same alter // table transaction. We could clear the meta cache for just the table being // altered or just the partition key ranges being changed, but that would // require opening the table in order to get the ID, schema, and partition // schema. // // It is not necessary to wait for the alteration to be completed before // clearing the cache (i.e. the tablets to be created), because the master // has its soft state updated as part of handling the alter table RPC. When // the meta cache looks up the new tablet locations during a subsequent // write or scan, the master will return a ServiceUnavailable response if // the new tablets are not yet running. The meta cache will automatically // retry after a delay when it encounters this error. data_->client_->data_->meta_cache_->ClearCache(); } if (data_->wait_) { if (!resp.has_table_id()) { return Status::NotSupported(""Alter Table succeeded but the server's "" ""response did not include a table ID. This server is too old to wait "" ""for alter table to finish""); } TableIdentifierPB table; table.set_table_id(resp.table_id()); RETURN_NOT_OK(data_->client_->data_->WaitForAlterTableToFinish( data_->client_, table, deadline)); } return Status::OK(); } //////////////////////////////////////////////////////////// // KuduScanner //////////////////////////////////////////////////////////// KuduScanner::KuduScanner(KuduTable* table) : data_(new KuduScanner::Data(table)) { } KuduScanner::~KuduScanner() { Close(); delete data_; } Status KuduScanner::SetProjectedColumns(const vector& col_names) { return SetProjectedColumnNames(col_names); } Status KuduScanner::SetProjectedColumnNames(const vector& col_names) { if (data_->open_) { return Status::IllegalState(""Projection must be set before Open()""); } return data_->mutable_configuration()->SetProjectedColumnNames(col_names); } Status KuduScanner::SetProjectedColumnIndexes(const vector& col_indexes) { if (data_->open_) { return Status::IllegalState(""Projection must be set before Open()""); } return data_->mutable_configuration()->SetProjectedColumnIndexes(col_indexes); } Status KuduScanner::SetBatchSizeBytes(uint32_t batch_size) { return data_->mutable_configuration()->SetBatchSizeBytes(batch_size); } Status KuduScanner::SetReadMode(ReadMode read_mode) { if (data_->open_) { return Status::IllegalState(""Read mode must be set before Open()""); } if (!tight_enum_test(read_mode)) { return Status::InvalidArgument(""Bad read mode""); } return data_->mutable_configuration()->SetReadMode(read_mode); } Status KuduScanner::SetOrderMode(OrderMode order_mode) { if (data_->open_) { return Status::IllegalState(""Order mode must be set before Open()""); } if (!tight_enum_test(order_mode)) { return Status::InvalidArgument(""Bad order mode""); } return data_->mutable_configuration()->SetFaultTolerant(order_mode == ORDERED); } Status KuduScanner::SetFaultTolerant() { if (data_->open_) { return Status::IllegalState(""Fault-tolerance must be set before Open()""); } return data_->mutable_configuration()->SetFaultTolerant(true); } Status KuduScanner::SetSnapshotMicros(uint64_t snapshot_timestamp_micros) { if (data_->open_) { return Status::IllegalState(""Snapshot timestamp must be set before Open()""); } data_->mutable_configuration()->SetSnapshotMicros(snapshot_timestamp_micros); return Status::OK(); } Status KuduScanner::SetSnapshotRaw(uint64_t snapshot_timestamp) { if (data_->open_) { return Status::IllegalState(""Snapshot timestamp must be set before Open()""); } if (snapshot_timestamp == 0) { return Status::IllegalState(""Snapshot timestamp must be set bigger than 0""); } data_->mutable_configuration()->SetSnapshotRaw(snapshot_timestamp); return Status::OK(); } Status KuduScanner::SetDiffScan(uint64_t start_timestamp, uint64_t end_timestamp) { if (data_->open_) { return Status::IllegalState(""Diff scan must be set before Open()""); } return data_->mutable_configuration()->SetDiffScan(start_timestamp, end_timestamp); } Status KuduScanner::SetSelection(KuduClient::ReplicaSelection selection) { if (data_->open_) { return Status::IllegalState(""Replica selection must be set before Open()""); } return data_->mutable_configuration()->SetSelection(selection); } Status KuduScanner::SetTimeoutMillis(int millis) { if (data_->open_) { return Status::IllegalState(""Timeout must be set before Open()""); } data_->mutable_configuration()->SetTimeoutMillis(millis); return Status::OK(); } Status KuduScanner::AddConjunctPredicate(KuduPredicate* pred) { if (data_->open_) { // Take ownership even if we return a bad status. delete pred; return Status::IllegalState(""Predicate must be set before Open()""); } return data_->mutable_configuration()->AddConjunctPredicate(pred); } Status KuduScanner::AddLowerBound(const KuduPartialRow& key) { return data_->mutable_configuration()->AddLowerBound(key); } Status KuduScanner::AddLowerBoundRaw(const Slice& key) { return data_->mutable_configuration()->AddLowerBoundRaw(key); } Status KuduScanner::AddExclusiveUpperBound(const KuduPartialRow& key) { return data_->mutable_configuration()->AddUpperBound(key); } Status KuduScanner::AddExclusiveUpperBoundRaw(const Slice& key) { return data_->mutable_configuration()->AddUpperBoundRaw(key); } Status KuduScanner::AddLowerBoundPartitionKeyRaw(const Slice& partition_key) { return data_->mutable_configuration()->AddLowerBoundPartitionKeyRaw(partition_key); } Status KuduScanner::AddExclusiveUpperBoundPartitionKeyRaw(const Slice& partition_key) { return data_->mutable_configuration()->AddUpperBoundPartitionKeyRaw(partition_key); } Status KuduScanner::SetCacheBlocks(bool cache_blocks) { if (data_->open_) { return Status::IllegalState(""Block caching must be set before Open()""); } return data_->mutable_configuration()->SetCacheBlocks(cache_blocks); } KuduSchema KuduScanner::GetProjectionSchema() const { return KuduSchema::FromSchema(*data_->configuration().projection()); } Status KuduScanner::SetRowFormatFlags(uint64_t flags) { switch (flags) { case NO_FLAGS: case PAD_UNIXTIME_MICROS_TO_16_BYTES: case COLUMNAR_LAYOUT: break; default: return Status::InvalidArgument(Substitute(""Invalid row format flags: $0"", flags)); } if (data_->open_) { return Status::IllegalState(""Row format flags must be set before Open()""); } return data_->mutable_configuration()->SetRowFormatFlags(flags); } Status KuduScanner::SetLimit(int64_t limit) { if (data_->open_) { return Status::IllegalState(""Limit must be set before Open()""); } return data_->mutable_configuration()->SetLimit(limit); } const ResourceMetrics& KuduScanner::GetResourceMetrics() const { return data_->resource_metrics_; } namespace { // Callback for the RPC sent by Close(). // We can't use the KuduScanner response and RPC controller members for this // call, because the scanner object may be destructed while the call is still // being processed. struct CloseCallback { RpcController controller; ScanResponsePB response; string scanner_id; void Callback() { if (!controller.status().ok()) { LOG(WARNING) << ""Couldn't close scanner "" << scanner_id << "": "" << controller.status().ToString(); } delete this; } }; } // anonymous namespace string KuduScanner::ToString() const { return KUDU_DISABLE_REDACTION(Substitute( ""$0: $1"", data_->table_->name(), data_->configuration().spec().ToString(*data_->table_->schema().schema_))); } Status KuduScanner::Open() { CHECK(!data_->open_) << ""Scanner already open""; if (data_->configuration().has_start_timestamp()) { RETURN_NOT_OK(data_->mutable_configuration()->AddIsDeletedColumn()); } data_->mutable_configuration()->OptimizeScanSpec(); data_->partition_pruner_.Init(*data_->table_->schema().schema_, data_->table_->partition_schema(), data_->configuration().spec()); if (data_->configuration().spec().CanShortCircuit() || !data_->partition_pruner_.HasMorePartitionKeyRanges()) { VLOG(2) << ""Short circuiting scan "" << data_->DebugString(); data_->open_ = true; data_->short_circuit_ = true; return Status::OK(); } // For READ_YOUR_WRITES scan mode, get the latest observed timestamp and store it // to scan config. Always use this one as propagation timestamp for the duration // of the scan to avoid unnecessarily wait. if (data_->configuration().read_mode() == READ_YOUR_WRITES) { const uint64_t lo_ts = data_->table_->client()->data_->GetLatestObservedTimestamp(); data_->mutable_configuration()->SetScanLowerBoundTimestampRaw(lo_ts); } if (data_->configuration().read_mode() != READ_AT_SNAPSHOT && data_->configuration().has_snapshot_timestamp()) { return Status::InvalidArgument(""Snapshot timestamp should only be configured "" ""for READ_AT_SNAPSHOT scan mode.""); } VLOG(2) << ""Beginning "" << data_->DebugString(); MonoTime deadline = MonoTime::Now() + data_->configuration().timeout(); set blacklist; RETURN_NOT_OK(data_->OpenNextTablet(deadline, &blacklist)); data_->open_ = true; return Status::OK(); } Status KuduScanner::KeepAlive() { return data_->KeepAlive(); } void KuduScanner::Close() { if (!data_->open_) return; VLOG(2) << ""Ending "" << data_->DebugString(); // Close the scanner on the server-side, if necessary. // // If the scan did not match any rows, the tserver will not assign a scanner ID. // This is reflected in the Open() response. In this case, there is no server-side state // to clean up. if (!data_->next_req_.scanner_id().empty()) { CHECK(data_->proxy_); unique_ptr closer(new CloseCallback); closer->scanner_id = data_->next_req_.scanner_id(); data_->PrepareRequest(KuduScanner::Data::CLOSE); data_->next_req_.set_close_scanner(true); closer->controller.set_timeout(data_->configuration().timeout()); // CloseCallback::Callback() deletes the closer. CloseCallback* closer_raw = closer.release(); data_->proxy_->ScanAsync(data_->next_req_, &closer_raw->response, &closer_raw->controller, [closer_raw]() { closer_raw->Callback(); }); } data_->proxy_.reset(); data_->open_ = false; return; } bool KuduScanner::HasMoreRows() const { CHECK(data_->open_); return !data_->short_circuit_ && // The scan is not short circuited (data_->data_in_open_ || // more data in hand data_->last_response_.has_more_results() || // more data in this tablet data_->MoreTablets()); // more tablets to scan, possibly with more data } Status KuduScanner::NextBatch(vector* rows) { if (PREDICT_FALSE(data_->configuration().row_format_flags() != KuduScanner::NO_FLAGS)) { return Status::IllegalState( Substitute(""Cannot extract rows. Row format modifier flags were selected: $0"", data_->configuration().row_format_flags())); } RETURN_NOT_OK(NextBatch(&data_->batch_for_old_api_)); data_->batch_for_old_api_.data_->ExtractRows(rows); return Status::OK(); } Status KuduScanner::NextBatch(KuduScanBatch* batch) { return NextBatch(batch->data_); } Status KuduScanner::NextBatch(KuduColumnarScanBatch* batch) { return NextBatch(batch->data_); } Status KuduScanner::NextBatch(internal::ScanBatchDataInterface* batch_data) { // TODO: do some double-buffering here -- when we return this batch // we should already have fired off the RPC for the next batch, but // need to do some swapping of the response objects around to avoid // stomping on the memory the user is looking at. CHECK(data_->open_); CHECK(data_->proxy_); batch_data->Clear(); if (data_->short_circuit_) { return Status::OK(); } if (data_->data_in_open_) { // We have data from a previous scan. VLOG(2) << ""Extracting data from "" << data_->DebugString(); data_->data_in_open_ = false; return batch_data->Reset(&data_->controller_, data_->configuration().projection(), data_->configuration().client_projection(), data_->configuration().row_format_flags(), &data_->last_response_); } if (data_->last_response_.has_more_results()) { // More data is available in this tablet. VLOG(2) << ""Continuing "" << data_->DebugString(); MonoTime batch_deadline = MonoTime::Now() + data_->configuration().timeout(); data_->PrepareRequest(KuduScanner::Data::CONTINUE); while (true) { bool allow_time_for_failover = data_->configuration().is_fault_tolerant(); ScanRpcStatus result = data_->SendScanRpc(batch_deadline, allow_time_for_failover); // Success case. if (result.result == ScanRpcStatus::OK) { if (data_->last_response_.has_last_primary_key()) { data_->last_primary_key_ = data_->last_response_.last_primary_key(); } data_->scan_attempts_ = 0; return batch_data->Reset(&data_->controller_, data_->configuration().projection(), data_->configuration().client_projection(), data_->configuration().row_format_flags(), &data_->last_response_); } data_->scan_attempts_++; // Error handling. set blacklist; bool needs_reopen = false; Status s = data_->HandleError(result, batch_deadline, &blacklist, &needs_reopen); if (!s.ok()) { LOG(WARNING) << ""Scan on tablet server "" << data_->ts_->ToString() << "" with "" << data_->DebugString() << "" failed: "" << result.status.ToString(); return s; } if (data_->configuration().is_fault_tolerant()) { LOG(WARNING) << ""Attempting to retry "" << data_->DebugString() << "" elsewhere.""; return data_->ReopenCurrentTablet(batch_deadline, &blacklist); } if (blacklist.empty() && !needs_reopen) { // If we didn't blacklist the current server, we can just retry again. continue; } // If we blacklisted the current server, and it's not fault-tolerant, we can't // retry anywhere, so just propagate the error. return result.status; } } else if (data_->MoreTablets()) { // More data may be available in other tablets. // No need to close the current tablet; we scanned all the data so the // server closed it for us. VLOG(2) << ""Scanning next tablet "" << data_->DebugString(); data_->last_primary_key_.clear(); MonoTime deadline = MonoTime::Now() + data_->configuration().timeout(); set blacklist; RETURN_NOT_OK(data_->OpenNextTablet(deadline, &blacklist)); if (data_->data_in_open_) { // Avoid returning an empty batch in between tablets if we have data // we can return from this call. return NextBatch(batch_data); } return Status::OK(); } else { // No more data anywhere. return Status::OK(); } } Status KuduScanner::GetCurrentServer(KuduTabletServer** server) { CHECK(data_->open_); internal::RemoteTabletServer* rts = data_->ts_; CHECK(rts); vector host_ports; rts->GetHostPorts(&host_ports); if (host_ports.empty()) { return Status::IllegalState(Substitute(""No HostPort found for RemoteTabletServer $0"", rts->ToString())); } unique_ptr client_server(new KuduTabletServer); client_server->data_ = new KuduTabletServer::Data(rts->permanent_uuid(), host_ports[0], rts->location()); *server = client_server.release(); return Status::OK(); } //////////////////////////////////////////////////////////// // KuduScanToken //////////////////////////////////////////////////////////// KuduScanToken::KuduScanToken() : data_(nullptr) { } KuduScanToken::~KuduScanToken() { delete data_; } Status KuduScanToken::IntoKuduScanner(KuduScanner** scanner) const { return data_->IntoKuduScanner(scanner); } const KuduTablet& KuduScanToken::tablet() const { return data_->tablet(); } Status KuduScanToken::Serialize(string* buf) const { return data_->Serialize(buf); } Status KuduScanToken::DeserializeIntoScanner(KuduClient* client, const string& serialized_token, KuduScanner** scanner) { return KuduScanToken::Data::DeserializeIntoScanner( client, serialized_token, scanner); } //////////////////////////////////////////////////////////// // KuduScanTokenBuilder //////////////////////////////////////////////////////////// KuduScanTokenBuilder::KuduScanTokenBuilder(KuduTable* table) : data_(new KuduScanTokenBuilder::Data(table)) { } KuduScanTokenBuilder::~KuduScanTokenBuilder() { delete data_; } Status KuduScanTokenBuilder::SetProjectedColumnNames(const vector& col_names) { return data_->mutable_configuration()->SetProjectedColumnNames(col_names); } Status KuduScanTokenBuilder::SetProjectedColumnIndexes(const vector& col_indexes) { return data_->mutable_configuration()->SetProjectedColumnIndexes(col_indexes); } Status KuduScanTokenBuilder::SetBatchSizeBytes(uint32_t batch_size) { return data_->mutable_configuration()->SetBatchSizeBytes(batch_size); } Status KuduScanTokenBuilder::SetReadMode(KuduScanner::ReadMode read_mode) { if (!tight_enum_test(read_mode)) { return Status::InvalidArgument(""Bad read mode""); } return data_->mutable_configuration()->SetReadMode(read_mode); } Status KuduScanTokenBuilder::SetFaultTolerant() { return data_->mutable_configuration()->SetFaultTolerant(true); } Status KuduScanTokenBuilder::SetSnapshotMicros(uint64_t snapshot_timestamp_micros) { data_->mutable_configuration()->SetSnapshotMicros(snapshot_timestamp_micros); return Status::OK(); } Status KuduScanTokenBuilder::SetDiffScan(uint64_t start_timestamp, uint64_t end_timestamp) { return data_->mutable_configuration()->SetDiffScan(start_timestamp, end_timestamp); } Status KuduScanTokenBuilder::SetSnapshotRaw(uint64_t snapshot_timestamp) { data_->mutable_configuration()->SetSnapshotRaw(snapshot_timestamp); return Status::OK(); } Status KuduScanTokenBuilder::SetSelection(KuduClient::ReplicaSelection selection) { return data_->mutable_configuration()->SetSelection(selection); } Status KuduScanTokenBuilder::SetTimeoutMillis(int millis) { data_->mutable_configuration()->SetTimeoutMillis(millis); return Status::OK(); } Status KuduScanTokenBuilder::IncludeTableMetadata(bool include_metadata) { data_->IncludeTableMetadata(include_metadata); return Status::OK(); } Status KuduScanTokenBuilder::IncludeTabletMetadata(bool include_metadata) { data_->IncludeTabletMetadata(include_metadata); return Status::OK(); } Status KuduScanTokenBuilder::AddConjunctPredicate(KuduPredicate* pred) { return data_->mutable_configuration()->AddConjunctPredicate(pred); } Status KuduScanTokenBuilder::AddLowerBound(const KuduPartialRow& key) { return data_->mutable_configuration()->AddLowerBound(key); } Status KuduScanTokenBuilder::AddUpperBound(const KuduPartialRow& key) { return data_->mutable_configuration()->AddUpperBound(key); } Status KuduScanTokenBuilder::SetCacheBlocks(bool cache_blocks) { return data_->mutable_configuration()->SetCacheBlocks(cache_blocks); } Status KuduScanTokenBuilder::Build(vector* tokens) { return data_->Build(tokens); } //////////////////////////////////////////////////////////// // KuduReplica //////////////////////////////////////////////////////////// KuduReplica::KuduReplica() : data_(nullptr) { } KuduReplica::~KuduReplica() { delete data_; } bool KuduReplica::is_leader() const { return data_->is_leader_; } const KuduTabletServer& KuduReplica::ts() const { return *data_->ts_; } //////////////////////////////////////////////////////////// // KuduTablet //////////////////////////////////////////////////////////// KuduTablet::KuduTablet() : data_(nullptr) { } KuduTablet::~KuduTablet() { delete data_; } const string& KuduTablet::id() const { return data_->id_; } const vector& KuduTablet::replicas() const { return data_->replicas_; } //////////////////////////////////////////////////////////// // KuduTabletServer //////////////////////////////////////////////////////////// KuduTabletServer::KuduTabletServer() : data_(nullptr) { } KuduTabletServer::~KuduTabletServer() { delete data_; } const string& KuduTabletServer::uuid() const { return data_->uuid_; } const string& KuduTabletServer::hostname() const { return data_->hp_.host(); } uint16_t KuduTabletServer::port() const { return data_->hp_.port(); } const string& KuduTabletServer::location() const { return data_->location_; } //////////////////////////////////////////////////////////// // KuduPartitionerBuilder //////////////////////////////////////////////////////////// KuduPartitionerBuilder::KuduPartitionerBuilder(sp::shared_ptr table) : data_(new Data(std::move(table))) { } KuduPartitionerBuilder::~KuduPartitionerBuilder() { delete data_; } KuduPartitionerBuilder* KuduPartitionerBuilder::SetBuildTimeout(MonoDelta timeout) { data_->SetBuildTimeout(timeout); return this; } Status KuduPartitionerBuilder::Build(KuduPartitioner** partitioner) { return data_->Build(partitioner); } //////////////////////////////////////////////////////////// // KuduPartitioner //////////////////////////////////////////////////////////// KuduPartitioner::KuduPartitioner(Data* data) : data_(CHECK_NOTNULL(data)) { } KuduPartitioner::~KuduPartitioner() { delete data_; } int KuduPartitioner::NumPartitions() const { return data_->num_partitions_; } Status KuduPartitioner::PartitionRow(const KuduPartialRow& row, int* partition) { return data_->PartitionRow(row, partition); } } // namespace client } // namespace kudu ",16181,True,2631.7208527382872,median "= `just` :toc: macro :toc-title: image:https://img.shields.io/crates/v/just.svg[crates.io version,link=https://crates.io/crates/just] image:https://github.com/casey/just/workflows/Build/badge.svg[build status,link=https://github.com/casey/just/actions] image:https://img.shields.io/github/downloads/casey/just/total.svg[downloads,link=https://github.com/casey/just/releases] image:https://img.shields.io/discord/695580069837406228?logo=discord[chat on discord,link=https://discord.gg/ezYScXR] image:https://img.shields.io/badge/Say%20Thanks-!-1EAEDB.svg[say thanks,link=mailto:casey@rodarmor.com?subject=Thanks for Just!] `just` is a handy way to save and run project-specific commands. (非官方中文文档,link:https://github.com/chinanf-boy/just-zh[这里],快看过来!) Commands, called recipes, are stored in a file called `justfile` with syntax inspired by `make`: image:screenshot.png[screenshot] You can then run them with `just RECIPE`: ```sh $ just test-all cc *.c -o main ./test --all Yay, all your tests passed! ``` `just` has a ton of useful features, and many improvements over `make`: - `just` is a command runner, not a build system, so it avoids much of link:https://github.com/casey/just#what-are-the-idiosyncrasies-of-make-that-just-avoids[`make`'s complexity and idiosyncrasies]. No need for `.PHONY` recipes! - Linux, MacOS, and Windows are supported with no additional dependencies. (Although if your system doesn't have an `sh`, you'll need to link:https://github.com/casey/just#shell[choose a different shell].) - Errors are specific and informative, and syntax errors are reported along with their source context. - Recipes can accept link:https://github.com/casey/just#recipe-parameters[command line arguments]. - Wherever possible, errors are resolved statically. Unknown recipes and circular dependencies are reported before anything runs. - `just` link:https://github.com/casey/just#dotenv-integration[loads `.env` files], making it easy to populate environment variables. - Recipes can be link:https://github.com/casey/just#listing-available-recipes[listed from the command line]. - Command line completion scripts are link:https://github.com/casey/just#shell-completion-scripts[available for most popular shells]. - Recipes can be written in link:https://github.com/casey/just#writing-recipes-in-other-languages[arbitrary languages], like Python or NodeJS. - `just` can be invoked from any subdirectory, not just the directory that contains the `justfile`. - And link:https://github.com/casey/just#manual[much more]! If you need help with `just` please feel free to open an issue or ping me on link:https://discord.gg/ezYScXR[Discord]. Feature requests and bug reports are always welcome! [discrete] == Manual toc::[] == Installation === Prerequisites `just` should run on any system with a reasonable `sh`, including Linux, MacOS, and the BSDs. On Windows, `just` works with the `sh` provided by https://git-scm.com[Git for Windows], https://desktop.github.com[GitHub Desktop], or http://www.cygwin.com[Cygwin]. If you'd rather not install `sh`, you can use the `shell` setting to use the shell of your choice. Like PowerShell: ```make # use PowerShell instead of sh: set shell := [""powershell.exe"", ""-c""] hello: Write-Host ""Hello, world!"" ``` …or `cmd.exe`: ```make # use cmd.exe instead of sh: set shell := [""cmd.exe"", ""/c""] list: dir ``` (PowerShell is installed by default on Windows 7 SP1 and Windows Server 2008 R2 S1 and later, and `cmd.exe` is quite fiddly, so PowerShell is recommended for most Windows users.) === Packages [cols=""1,1,1,1"", options=""header""] |=== | Operating System | Package Manager | Package | Command | https://forge.rust-lang.org/release/platform-support.html[Various] | https://www.rust-lang.org[Cargo] | https://crates.io/crates/just[just] | `cargo install just` | https://en.wikipedia.org/wiki/Microsoft_Windows[Microsoft Windows] | https://scoop.sh[Scoop] | https://github.com/ScoopInstaller/Main/blob/master/bucket/just.json[just] | `scoop install just` | https://en.wikipedia.org/wiki/MacOS[macOS] | https://brew.sh[Homebrew] | https://formulae.brew.sh/formula/just[just] | `brew install just` | https://en.wikipedia.org/wiki/MacOS[macOS] | https://www.macports.org[MacPorts] | https://ports.macports.org/port/just/summary[just] | `port install just` | https://www.archlinux.org[Arch Linux] | https://wiki.archlinux.org/title/Pacman[pacman] | https://archlinux.org/packages/community/x86_64/just/[just] | `pacman -S just` | https://nixos.org/nixos/[NixOS], https://nixos.org/nix/manual/#ch-supported-platforms[Linux], https://nixos.org/nix/manual/#ch-supported-platforms[macOS] | https://nixos.org/nix/[Nix] | https://github.com/NixOS/nixpkgs/blob/master/pkgs/development/tools/just/default.nix[just] | `nix-env -iA nixos.just` | https://getsol.us/[Solus] | https://getsol.us/articles/package-management/basics/en[eopkg] | https://dev.getsol.us/source/just/[just] | `eopkg install just` | https://voidlinux.org[Void Linux] | https://wiki.voidlinux.org/XBPS[XBPS] | https://github.com/void-linux/void-packages/blob/master/srcpkgs/just/template[just] | `xbps-install -S just` | https://www.freebsd.org/[FreeBSD] | https://www.freebsd.org/doc/handbook/pkgng-intro.html[pkg] | https://www.freshports.org/deskutils/just/[just] | `pkg install just` | https://alpinelinux.org/[Alpine Linux] | https://wiki.alpinelinux.org/wiki/Alpine_Linux_package_management[apk-tools] | https://pkgs.alpinelinux.org/package/edge/community/x86_64/just[just] | `apk add just` | https://getfedora.org/[Fedora Linux] | https://dnf.readthedocs.io/en/latest/[DNF] | https://src.fedoraproject.org/rpms/rust-just[just] | `dnf install just` | https://www.gentoo.org/[Gentoo Linux] | https://wiki.gentoo.org/wiki/Portage[Portage] | https://github.com/gentoo-mirror/dm9pZCAq/tree/master/sys-devel/just[dm9pZCAq overlay: sys-devel/just] | `eselect repository enable dm9pZCAq && emerge --sync dm9pZCAq && emerge sys-devel/just` | https://docs.conda.io/en/latest/miniconda.html#system-requirements[Various] | https://docs.conda.io/projects/conda/en/latest/index.html[Conda] | https://anaconda.org/conda-forge/just[just] | `conda install -c conda-forge just` |=== === Pre-Built Binaries Pre-built binaries for Linux, MacOS, and Windows can be found on https://github.com/casey/just/releases[the releases page]. You can use the following command on Linux, MacOS, or Windows to download the latest release, just replace `DEST` with the directory where you'd like to put `just`: ```sh curl --proto '=https' --tlsv1.2 -sSf https://just.systems/install.sh | bash -s -- --to DEST ``` For example, to install `just` to `~/bin`: ``` # create `~/bin` mkdir -p ~/bin # download and extract `just` to `~/bin/just` curl --proto '=https' --tlsv1.2 -sSf https://just.systems/install.sh | bash -s -- --to ~/bin # add `~/bin` to the paths that your shell searches for executables # this line should be added to your shells initialization file, # e.g. `~/.bashrc` or `~/.zshrc` export PATH=""$PATH:$HOME/bin"" # just should now be executable just --help ``` === GitHub Actions link:https://github.com/extractions/setup-just[extractions/setup-just] can be used to install `just` in a GitHub Actions workflow. Example usage: ```yaml - uses: extractions/setup-just@v1 with: just-version: 0.8 # optional semver specification, otherwise latest ``` === Release RSS Feed An https://en.wikipedia.org/wiki/RSS[RSS feed] of `just` releases is available https://github.com/casey/just/releases.atom[here]. == Editor Support `justfile` syntax is close enough to `make` that you may want to tell your editor to use `make` syntax highlighting for `just`. === Vim and Neovim ==== `vim-just` The https://github.com/NoahTheDuke/vim-just[vim-just] plugin provides syntax highlighting for justfiles. Install it with your favorite package manager, like https://github.com/junegunn/vim-plug[Plug]: ```vim call plug#begin() Plug 'NoahTheDuke/vim-just' call plug#end() ``` Or with Vim's built-in package support: ``` mkdir -p ~/.vim/pack/vendor/start cd ~/.vim/pack/vendor/start git clone https://github.com/NoahTheDuke/vim-just.git ``` `vim-just` is also available from https://github.com/sheerun/vim-polyglot[vim-polyglot], a multi-language Vim plugin. ==== `tree-sitter-just` https://github.com/IndianBoy42/tree-sitter-just[tree-sitter-just] is an https://github.com/nvim-treesitter/nvim-treesitter[Nvim Treesitter] plugin for Neovim. ==== Makefile Syntax Highlighting Vim's built-in makefile syntax highlighting isn't perfect for justfiles, but it's better than nothing. You can put the following in `~/.vim/filetype.vim`: ```vimscript if exists(""did_load_filetypes"") finish endif augroup filetypedetect au BufNewFile,BufRead justfile setf make augroup END ``` Or add the following to an individual justfile to enable `make` mode on a per-file basis: ``` # vim: set ft=make : ``` === Emacs https://github.com/leon-barrett/just-mode.el[just-mode] provides syntax highlighting and automatic indentation of justfiles. It is available on https://melpa.org/[MELPA] as https://melpa.org/#/just-mode[just-mode] https://github.com/psibi/justl.el[justl] provides commands for executing and listing recipes. You can add the following to an individual justfile to enable `make` mode on a per-file basis: ``` # Local Variables: # mode: makefile # End: ``` === Visual Studio Code An extension for VS Code by https://github.com/skellock[skellock] is https://marketplace.visualstudio.com/items?itemName=skellock.just[available here]. (https://github.com/skellock/vscode-just[repository]) You can install it from the command line by running: ``` code --install-extension skellock.just ``` === Kakoune Kakoune supports `justfile` syntax highlighting out of the box, thanks to TeddyDD. === Sublime Text A syntax file for Sublime Text written by TonioGela is available in link:extras/just.sublime-syntax[extras/just.sublime-syntax]. === Other Editors Feel free to send me the commands necessary to get syntax highlighting working in your editor of choice so that I may include them here. == Quick Start See xref:Installation[] for how to install `just` on your computer. Try running `just --version` to make sure that it's installed correctly. Once `just` is installed and working, create a file named `justfile` in the root of your project with the following contents: ```make recipe-name: echo 'This is a recipe!' # this is a comment another-recipe: @echo 'This is another recipe.' ``` When you invoke `just` it looks for file `justfile` in the current directory and upwards, so you can invoke it from any subdirectory of your project. The search for a `justfile` is case insensitive, so any case, like `Justfile`, `JUSTFILE`, or `JuStFiLe`, will work. `just` will also look for files with the name `.justfile`, in case you'd like to hide a `justfile`. Running `just` with no arguments runs the first recipe in the `justfile`: ```sh $ just echo 'This is a recipe!' This is a recipe! ``` One or more arguments specify the recipe(s) to run: ```sh $ just another-recipe This is another recipe. ``` `just` prints each command to standard error before running it, which is why `echo 'This is a recipe!'` was printed. This is suppressed for lines starting with `@`, which is why `echo 'Another recipe.'` was not printed. Recipes stop running if a command fails. Here `cargo publish` will only run if `cargo test` succeeds: ```make publish: cargo test # tests passed, time to publish! cargo publish ``` Recipes can depend on other recipes. Here the `test` recipe depends on the `build` recipe, so `build` will run before `test`: ```make build: cc main.c foo.c bar.c -o main test: build ./test sloc: @echo ""`wc -l *.c` lines of code"" ``` ```sh $ just test cc main.c foo.c bar.c -o main ./test testing... all tests passed! ``` Recipes without dependencies will run in the order they're given on the command line: ```sh $ just build sloc cc main.c foo.c bar.c -o main 1337 lines of code ``` Dependencies will always run first, even if they are passed after a recipe that depends on them: ```sh $ just test build cc main.c foo.c bar.c -o main ./test testing... all tests passed! ``` == Examples A variety of example justfiles can be found in the link:examples[examples directory]. This https://toniogela.dev/just/[blog post] discusses using `just` to improve management of shared machines, and includes a number of example justfiles. == Features === Listing Available Recipes Recipes can be listed in alphabetical order with `just --list`: ```sh $ just --list Available recipes: build test deploy lint ``` `just --summary` is more concise: ```sh $ just --summary build test deploy lint ``` Pass `--unsorted` to print recipes in the order they appear in the justfile: ```make test: echo 'Testing!' build: echo 'Building!' ``` ```sh $ just --list --unsorted Available recipes: test build ``` ```sh $ just --summary --unsorted test build ``` If you'd like `just` to default to listing the recipes in the justfile, you can use this as your default recipe: ```make default: @just --list ``` The heading text can be customized with `--list-heading`: ``` $ just --list --list-heading $'Cool stuff…\\n' Cool stuff… test build ``` And the indentation can be customized with `--list-prefix`: ``` $ just --list --list-prefix ···· Available recipes: ····test ····build ``` The argument to `--list-heading` replaces both the heading and the newline following it, so it should contain a newline if non-empty. It works this way so you can suppress the heading line entirely by passing the empty string: ``` $ just --list --list-heading '' test build ``` === Aliases Aliases allow recipes to be invoked with alternative names: ```make alias b := build build: echo 'Building!' ``` ```sh $ just b build echo 'Building!' Building! ``` === Settings Settings control interpretation and execution. Each setting may be specified at most once, anywhere in the justfile. For example: ```make set shell := [""zsh"", ""-cu""] foo: # this line will be run as `zsh -cu 'ls **/*.txt'` ls **/*.txt ``` ==== Table of Settings [options=""header""] |================= | Name | Value | Description | `dotenv-load` | boolean | Load a `.env` file, if present. | `export` | boolean | Export all variables as environment variables. | `positional-arguments` | boolean | Pass positional arguments. | `shell` | `[COMMAND, ARGS...]` | Set the command used to invoke recipes and evaluate backticks. |================= Boolean settings can be written as: ``` set NAME ``` Which is equivalent to: ``` set NAME := true ``` ==== Dotenv Load If `dotenv-load` is `true`, a `.env` file will be loaded if present. Defaults to `true`. ==== Export The `export` setting causes all `just` variables to be exported as environment variables. Defaults to `false`. ```make set export a := ""hello"" @foo b: echo $a echo $b ``` ``` $ just foo goodbye hello goodbye ``` ==== Positional Arguments If `positional-arguments` is `true`, recipe arguments will be passed as positional arguments to commands. For linewise recipes, argument `$0` will be the name of the recipe. For example, running this recipe: ```make set positional-arguments @foo bar: echo $0 echo $1 ``` Will produce the following output: ``` $ just foo hello foo hello ``` ==== Shell The `shell` setting controls the command used to invoke recipe lines and backticks. Shebang recipes are unaffected. ```make # use python3 to execute recipe lines and backticks set shell := [""python3"", ""-c""] # use print to capture result of evaluation foos := `print(""foo"" * 4)` foo: print(""Snake snake snake snake."") print(""{{foos}}"") ``` `just` passes the command to be executed as an argument. Many shells will need an additional flag, often `-c`, to make them evaluate the first argument. ===== Python 3 ```make set shell := [""python3"", ""-c""] ``` ===== Bash ```make set shell := [""bash"", ""-uc""] ``` ===== Z Shell ```make set shell := [""zsh"", ""-uc""] ``` ===== Fish ```make set shell := [""fish"", ""-c""] ``` === Documentation Comments Comments immediately preceding a recipe will appear in `just --list`: ```make # build stuff build: ./bin/build # test stuff test: ./bin/test ``` ```sh $ just --list Available recipes: build # build stuff test # test stuff ``` === Variables and Substitution Variables, strings, concatenation, and substitution using `{{...}}` are supported: ```make version := ""0.2.7"" tardir := ""awesomesauce-"" + version tarball := tardir + "".tar.gz"" publish: rm -f {{tarball}} mkdir {{tardir}} cp README.md *.c {{tardir}} tar zcvf {{tarball}} {{tardir}} scp {{tarball}} me@server.com:release/ rm -rf {{tarball}} {{tardir}} ``` ==== Escaping `{{` To write a recipe containing `{{`, use `{{{{`: ```make braces: echo 'I {{{{LOVE}} curly braces!' ``` (An unmatched `}}` is ignored, so it doesn't need to be escaped.) Another option is to put all the text you'd like to escape inside of an interpolation: ```make braces: echo '{{'I {{LOVE}} curly braces!'}}' ``` Yet another option is to use `{{ ""{{"" }}`: ```make braces: echo 'I {{ ""{{"" }}LOVE}} curly braces!' ``` === Strings Double-quoted strings support escape sequences: ```make string-with-tab := ""\\t"" string-with-newline := ""\\n"" string-with-carriage-return := ""\\r"" string-with-double-quote := ""\\"""" string-with-slash := ""\\\\"" string-with-no-newline := ""\\ "" ``` ```sh $ just --evaluate ""tring-with-carriage-return := "" string-with-double-quote := """""" string-with-newline := "" "" string-with-no-newline := """" string-with-slash := ""\\"" string-with-tab := "" "" ``` Strings may contain line breaks: ```make single := ' hello ' double := "" goodbye "" ``` Single-quoted strings do not recognize escape sequences: ```make escapes := '\\t\\n\\r\\""\\\\' ``` ```sh $ just --evaluate escapes := ""\\t\\n\\r\\""\\\\"" ``` Indented versions of both single- and double-quoted strings, delimited by triple single- or triple double-quotes, are supported. Indented string lines are stripped of leading whitespace common to all non-blank lines: ```make # this string will evaluate to `foo\\nbar\\n` x := ''' foo bar ''' # this string will evaluate to `abc\\n wuv\\nbar\\n` y := """""" abc wuv xyz """""" ``` Similar to unindented strings, indented double-quoted strings process escape sequences, and indented single-quoted strings ignore escape sequences. Escape sequence processing takes place after unindentation. The unindention algorithm does not take escape-sequence produced whitespace or newlines into account. === Ignoring Errors Normally, if a command returns a non-zero exit status, execution will stop. To continue execution after a command, even if it fails, prefix the command with `-`: ```make foo: -cat foo echo 'Done!' ``` ```sh $ just foo cat foo cat: foo: No such file or directory echo 'Done!' Done! ``` === Functions `just` provides a few built-in functions that might be useful when writing recipes. ==== System Information - `arch()` – Instruction set architecture. Possible values are: `""aarch64""`, `""arm""`, `""asmjs""`, `""hexagon""`, `""mips""`, `""msp430""`, `""powerpc""`, `""powerpc64""`, `""s390x""`, `""sparc""`, `""wasm32""`, `""x86""`, `""x86_64""`, and `""xcore""`. - `os()` – Operating system. Possible values are: `""android""`, `""bitrig""`, `""dragonfly""`, `""emscripten""`, `""freebsd""`, `""haiku""`, `""ios""`, `""linux""`, `""macos""`, `""netbsd""`, `""openbsd""`, `""solaris""`, and `""windows""`. - `os_family()` – Operating system family; possible values are: `""unix""` and `""windows""`. For example: ```make system-info: @echo ""This is an {{arch()}} machine"". ``` ``` $ just system-info This is an x86_64 machine ``` ==== Environment Variables - `env_var(key)` – Retrieves the environment variable with name `key`, aborting if it is not present. - `env_var_or_default(key, default)` – Retrieves the environment variable with name `key`, returning `default` if it is not present. ==== Invocation Directory - `invocation_directory()` - Retrieves the path of the current working directory, before `just` changed it (chdir'd) prior to executing commands. For example, to call `rustfmt` on files just under the ""current directory"" (from the user/invoker's perspective), use the following rule: ``` rustfmt: find {{invocation_directory()}} -name \\*.rs -exec rustfmt {} \\; ``` Alternatively, if your command needs to be run from the current directory, you could use (e.g.): ``` build: cd {{invocation_directory()}}; ./some_script_that_needs_to_be_run_from_here ``` ==== Justfile and Justfile Directory - `justfile()` - Retrieves the path of the current justfile. - `justfile_directory()` - Retrieves the path of the parent directory of the current justfile. For example, to run a command relative to the location of the current justfile: ``` script: ./{{justfile_directory()}}/scripts/some_script ``` ==== Just Executable - `just_executable()` - Absolute path to the `just` executable. For example: ```make executable: @echo The executable is at: {{just_executable()}} ``` ``` $ just The executable is at: /bin/just ``` ==== String Manipulation - `uppercase(s)` - Convert `s` to uppercase. - `lowercase(s)` - Convert `s` to lowercase. - `trim(s)` - Remove leading and trailing whitespace from `s`. - `replace(s, from, to)` - Replace all occurrences of `from` in `s` to `to`. ==== Dotenv Integration `just` will load environment variables from a file named `.env`. This file can be located in the same directory as your justfile or in a parent directory. These variables are environment variables, not `just` variables, and so must be accessed using `$VARIABLE_NAME` in recipes and backticks. For example, if your `.env` file contains: ``` # a comment, will be ignored DATABASE_ADDRESS=localhost:6379 SERVER_PORT=1337 ``` And your justfile contains: ```make serve: @echo ""Starting server with database $DATABASE_ADDRESS on port $SERVER_PORT..."" ./server --database $DATABASE_ADDRESS --port $SERVER_PORT ``` `just serve` will output: ```sh $ just serve Starting server with database localhost:6379 on port 1337... ./server --database $DATABASE_ADDRESS --port $SERVER_PORT ``` ==== Path Manipulation ===== Fallible - `extension(path)` - Extension of `path`. `extension(""/foo/bar.txt"")` is `txt`. - `file_name(path)` - File name of `path` with any leading directory components removed. `file_name(""/foo/bar.txt"")` is `bar.txt`. - `file_stem(path)` - File name of `path` without extension. `file_stem(""/foo/bar.txt"")` is `bar`. - `parent_directory(path)` - Parent directory of `path`. `parent_directory(""/foo/bar.txt"")` is `/foo`. - `without_extension(path)` - `path` without extension. `without_extension(""/foo/bar.txt"")` is `/foo/bar`. These functions can fail, for example if a path does not have an extension, which will halt execution. ===== Infallible - `join(a, b)` - Join path `a` with path `b`. `join(""foo/bar"", ""baz"")` is `foo/bar/baz`. - `clean(path)` - Simplify `path` by removing extra path separators, intermediate `.` components, and `..` where possible. `clean(""foo//bar"")` is `foo/bar`, `clean(""foo/.."")` is `.`, `clean(""foo/./bar"")` is `foo/bar`. === Command Evaluation Using Backticks Backticks can be used to store the result of commands: ```make localhost := `dumpinterfaces | cut -d: -f2 | sed 's/\\/.*//' | sed 's/ //g'` serve: ./serve {{localhost}} 8080 ``` Indented backticks, delimited by three backticks, are de-indented in the same manner as indented strings: ```make # This backtick evaluates the command `echo foo\\necho bar\\n`, which produces the value `foo\\nbar\\n`. stuff := ``` echo foo echo bar ``` ``` See the <> section for details on unindenting. Backticks may not start with `#!`. This syntax is reserved for a future upgrade. === Conditional Expressions `if`/`else` expressions evaluate different branches depending on if two expressions evaluate to the same value: ```make foo := if ""2"" == ""2"" { ""Good!"" } else { ""1984"" } bar: @echo ""{{foo}}"" ``` ```sh $ just bar Good! ``` It is also possible to test for inequality: ```make foo := if ""hello"" != ""goodbye"" { ""xyz"" } else { ""abc"" } bar: @echo {{foo}} ``` ```sh $ just bar xyz ``` And match against regular expressions: ```make foo := if ""hello"" =~ 'hel+o' { ""match"" } else { ""mismatch"" } bar: @echo {{foo}} ``` ```sh $ just bar match ``` Regular expressions are provided by the https://github.com/rust-lang/regex[regex crate], whose syntax is documented on https://docs.rs/regex/1.5.4/regex/#syntax[docs.rs]. Since regular expressions commonly use backslash escape sequences, consider using single-quoted string literals, which will pass slashes to the regex parser unmolested. Conditional expressions short-circuit, which means they only evaluate one of their branches. This can be used to make sure that backtick expressions don't run when they shouldn't. ```make foo := if env_var(""RELEASE"") == ""true"" { `get-something-from-release-database` } else { ""dummy-value"" } ``` Conditionals can be used inside of recipes: ```make bar foo: echo {{ if foo == ""bar"" { ""hello"" } else { ""goodbye"" } }} ``` Note the space after the final `}`! Without the space, the interpolation will be prematurely closed. Multiple conditionals can be chained: ```make foo := if ""hello"" == ""goodbye"" { ""xyz"" } else if ""a"" == ""a"" { ""abc"" } else { ""123"" } bar: @echo {{foo}} ``` ```sh $ just bar abc ``` === Setting Variables from the Command Line Variables can be overridden from the command line. ```make os := ""linux"" test: build ./test --test {{os}} build: ./build {{os}} ``` ```sh $ just ./build linux ./test --test linux ``` Any number of arguments of the form `NAME=VALUE` can be passed before recipes: ```sh $ just os=plan9 ./build plan9 ./test --test plan9 ``` Or you can use the `--set` flag: ```sh $ just --set os bsd ./build bsd ./test --test bsd ``` === Environment Variables Assignments prefixed with the `export` keyword will be exported to recipes as environment variables: ```make export RUST_BACKTRACE := ""1"" test: # will print a stack trace if it crashes cargo test ``` Parameters prefixed with a `$` will be exported as environment variables: ```make test $RUST_BACKTRACE=""1"": # will print a stack trace if it crashes cargo test ``` Exported variables and parameters are not exported to backticks in the same scope. ```make export WORLD := ""world"" # This backtick will fail with ""WORLD: unbound variable"" BAR := `echo hello $WORLD` ``` ```make # Running `just a foo` will fail with ""A: unbound variable"" a $A $B=`echo $A`: echo $A $B ``` === Recipe Parameters Recipes may have parameters. Here recipe `build` has a parameter called `target`: ```make build target: @echo 'Building {{target}}...' cd {{target}} && make ``` To pass arguments on the command line, put them after the recipe name: ```sh $ just build my-awesome-project Building my-awesome-project... cd my-awesome-project && make ``` To pass arguments to a dependency, put the dependency in parentheses along with the arguments: ```make default: (build ""main"") build target: @echo 'Building {{target}}...' cd {{target}} && make ``` Parameters may have default values: ```make default := 'all' test target tests=default: @echo 'Testing {{target}}:{{tests}}...' ./test --tests {{tests}} {{target}} ``` Parameters with default values may be omitted: ```sh $ just test server Testing server:all... ./test --tests all server ``` Or supplied: ```sh $ just test server unit Testing server:unit... ./test --tests unit server ``` Default values may be arbitrary expressions, but concatenations must be parenthesized: ```make arch := ""wasm"" test triple=(arch + ""-unknown-unknown""): ./test {{triple}} ``` The last parameter of a recipe may be variadic, indicated with either a `+` or a `*` before the argument name: ```make backup +FILES: scp {{FILES}} me@server.com: ``` Variadic parameters prefixed with `+` accept _one or more_ arguments and expand to a string containing those arguments separated by spaces: ```sh $ just backup FAQ.md GRAMMAR.md scp FAQ.md GRAMMAR.md me@server.com: FAQ.md 100% 1831 1.8KB/s 00:00 GRAMMAR.md 100% 1666 1.6KB/s 00:00 ``` Variadic parameters prefixed with `*` accept _zero or more_ arguments and expand to a string containing those arguments separated by spaces, or an empty string if no arguments are present: ```make commit MESSAGE *FLAGS: git commit {{FLAGS}} -m ""{{MESSAGE}}"" ``` Variadic parameters can be assigned default values. These are overridden by arguments passed on the command line: ```make test +FLAGS='-q': cargo test {{FLAGS}} ``` `{{...}}` substitutions may need to be quoted if they contain spaces. For example, if you have the following recipe: ```make search QUERY: lynx https://www.google.com/?q={{QUERY}} ``` And you type: ```sh $ just search ""cat toupee"" ``` `just` will run the command `lynx https://www.google.com/?q=cat toupee`, which will get parsed by `sh` as `lynx`, `https://www.google.com/?q=cat`, and `toupee`, and not the intended `lynx` and `https://www.google.com/?q=cat toupee`. You can fix this by adding quotes: ```make search QUERY: lynx 'https://www.google.com/?q={{QUERY}}' ``` Parameters prefixed with a `$` will be exported as environment variables: ```make foo $bar: echo $bar ``` === Running Recipes at the End of a Recipe Normal dependencies of a recipes always run before a recipe starts. That is to say, the dependee always runs before the depender. These dependencies are called ""prior dependencies"". A recipe can also have subsequent dependencies, which run after the recipe and are introduced with an `&&`: ```make a: echo 'A!' b: a && c d echo 'B!' c: echo 'C!' d: echo 'D!' ``` …running 'b' prints: ```sh $ just b echo 'A!' A! echo 'B!' B! echo 'C!' C! echo 'D!' D! ``` === Running Recipes in the Middle of a Recipe `just` doesn't support running recipes in the middle of another recipe, but you can call `just` recursively in the middle of a recipe. Given the following justfile: ```make a: echo 'A!' b: a echo 'B start!' just c echo 'B end!' c: echo 'C!' ``` …running 'b' prints: ```sh $ just b echo 'A!' A! echo 'B start!' B start! echo 'C!' C! echo 'B end!' B end! ``` This has limitations, since recipe `c` is run with an entirely new invocation of `just`: Assignments will be recalculated, dependencies might run twice, and command line arguments will not be propagated to the child `just` process. === Writing Recipes in Other Languages Recipes that start with a `#!` are executed as scripts, so you can write recipes in other languages: ```make polyglot: python js perl sh ruby python: #!/usr/bin/env python3 print('Hello from python!') js: #!/usr/bin/env node console.log('Greetings from JavaScript!') perl: #!/usr/bin/env perl print ""Larry Wall says Hi!\\n""; sh: #!/usr/bin/env sh hello='Yo' echo ""$hello from a shell script!"" ruby: #!/usr/bin/env ruby puts ""Hello from ruby!"" ``` ```sh $ just polyglot Hello from python! Greetings from JavaScript! Larry Wall says Hi! Yo from a shell script! Hello from ruby! ``` === Safer Bash Shebang Recipes If you're writing a `bash` shebang recipe, consider adding `set -euxo pipefail`: ```make foo: #!/usr/bin/env bash set -euxo pipefail hello='Yo' echo ""$hello from Bash!"" ``` It isn't strictly necessary, but `set -euxo pipefail` turns on a few useful features that make `bash` shebang recipes behave more like normal, linewise `just` recipe: - `set -e` makes `bash` exit if a command fails. - `set -u` makes `bash` exit if a variable is undefined. - `set -x` makes `bash` print each script line before it's run. - `set -o pipefail` makes `bash` exit if a command in a pipeline fails. Together, these avoid a lot of shell scripting gotchas. ==== Shebang Recipe Execution on Windows On Windows, shebang interpreter paths containing a `/` are translated from Unix-style paths to Windows-style paths using `cygpath`, a utility that ships with http://www.cygwin.com[Cygwin]. For example, to execute this recipe on Windows: ```make echo: #!/bin/sh echo ""Hello!"" ``` The interpreter path `/bin/sh` will be translated to a Windows-style path using `cygpath` before being executed. If the interpreter path does not contain a `/` it will be executed without being translated. This is useful if `cygpath` is not available, or you wish to pass a Windows-style path to the interpreter. === Setting Variables in a Recipe Recipe lines are interpreted by the shell, not `just`, so it's not possible to set `just` variables in the middle of a recipe: ``` foo: x := ""hello"" # This doesn't work! echo {{x}} ``` It is possible to use shell variables, but there's another problem. Every recipe line is run by a new shell instance, so variables set in one line won't be set in the next: ```make foo: x=hello && echo $x # This works! y=bye echo $y # This doesn't, `y` is undefined here! ``` The best way to work around this is to use a shebang recipe. Shebang recipe bodies are extracted and run as scripts, so a single shell instance will run the whole thing: ```make foo: #!/usr/bin/env bash set -euxo pipefail x=hello echo $x ``` === Changing the Working Directory in a Recipe Each recipe line is executed by a new shell, so if you change the working directory on one line, it won't have an effect on later lines: ```make foo: pwd # This `pwd` will print the same directory… cd bar pwd # …as this `pwd`! ``` There are a couple ways around this. One is to call `cd` on the same line as the command you want to run: ```make foo: cd bar && pwd ``` The other is to use a shebang recipe. Shebang recipe bodies are extracted and run as scripts, so a single shell instance will run the whole thing, and thus a `pwd` on one line will affect later lines, just like a shell script: ```make foo: #!/usr/bin/env bash set -euxo pipefail cd bar pwd ``` === Multi-Line Constructs Recipes without an initial shebang are evaluated and run line-by-line, which means that multi-line constructs probably won't do what you want. For example, with the following justfile: ``` conditional: if true; then echo 'True!' fi ``` The extra leading whitespace before the second line of the `conditional` recipe will produce a parse error: ``` $ just conditional error: Recipe line has extra leading whitespace | 3 | echo 'True!' | ^^^^^^^^^^^^^^^^ ``` To work around this, you can write conditionals on one line, escape newlines with slashes, or add a shebang to your recipe. Some examples of multi-line constructs are provided for reference. ==== `if` statements ```make conditional: if true; then echo 'True!'; fi ``` ```make conditional: if true; then \\ echo 'True!'; \\ fi ``` ```make conditional: #!/usr/bin/env sh if true; then echo 'True!' fi ``` ==== `for` loops ```make for: for file in `ls .`; do echo $file; done ``` ```make for: for file in `ls .`; do \\ echo $file; \\ done ``` ```make for: #!/usr/bin/env sh for file in `ls .`; do echo $file done ``` ==== `while` loops ```make while: while `server-is-dead`; do ping -c 1 server; done ``` ```make while: while `server-is-dead`; do \\ ping -c 1 server; \\ done ``` ```make while: #!/usr/bin/env sh while `server-is-dead`; do do ping -c 1 server done ``` === Command Line Options `just` supports a number of useful command line options for listing, dumping, and debugging recipes and variable: ```sh $ just --list Available recipes: js perl polyglot python ruby $ just --show perl perl: #!/usr/bin/env perl print ""Larry Wall says Hi!\\n""; $ just --show polyglot polyglot: python js perl sh ruby ``` Run `just --help` to see all the options. === Private Recipes Recipes and aliases whose name starts with a `_` are omitted from `just --list`: ```make test: _test-helper ./bin/test _test-helper: ./bin/super-secret-test-helper-stuff ``` ```sh $ just --list Available recipes: test ``` And from `just --summary`: ```sh $ just --summary test ``` This is useful for helper recipes which are only meant to be used as dependencies of other recipes. === Quiet Recipes A recipe name may be prefixed with '@' to invert the meaning of '@' before each line: ```make @quiet: echo hello echo goodbye @# all done! ``` Now only the lines starting with '@' will be echoed: ```sh $ j quiet hello goodbye # all done! ``` Shebang recipes are quiet by default: ```make foo: #!/usr/bin/env bash echo 'Foo!' ``` ```sh $ just foo Foo! ``` Adding `@` to a shebang recipe name makes `just` print the recipe before executing it: ```make @bar: #!/usr/bin/env bash echo 'Bar!' ``` ```sh $ just bar ~/src/just #!/usr/bin/env bash echo 'Bar!' Bar! ``` === Selecting Recipes to Run With an Interactive Chooser The `--choose` subcommand makes `just` invoke a chooser to select which recipes to run. Choosers should read lines containing recipe names from standard input and print one or more of those names separated by spaces to standard output. Because there is currently no way to run a recipe that requires arguments with `--choose`, such recipes will not be given to the chooser. Private recipes and aliases are also skipped. The chooser can be overridden with the `--chooser` flag. If `--chooser` is not given, then `just` first checks if `$JUST_CHOOSER` is set. If it isn't, then the chooser defaults to `fzf`, a popular fuzzy finder. Arguments can be included in the chooser, i.e. `fzf --exact`. The chooser is invoked in the same way as recipe lines. For example, if the chooser is `fzf`, it will be invoked with `sh -cu 'fzf'`, and if the shell, or the shell arguments are overridden, the chooser invocation will respect those overrides. If you'd like `just` to default to selecting recipes with a chooser, you can use this as your default recipe: ```make default: @just --choose ``` === Invoking Justfiles in Other Directories If the first argument passed to `just` contains a `/`, then the following occurs: 1. The argument is split at the last `/`. 2. The part before the last `/` is treated as a directory. `just` will start its search for the justfile there, instead of in the current directory. 3. The part after the last slash is treated as a normal argument, or ignored if it is empty. This may seem a little strange, but it's useful if you wish to run a command in a justfile that is in a subdirectory. For example, if you are in a directory which contains a subdirectory named `foo`, which contains a justfile with the recipe `build`, which is also the default recipe, the following are all equivalent: ```sh $ (cd foo && just build) $ just foo/build $ just foo/ ``` === Hiding Justfiles `just` looks for justfiles named `justfile` and `.justfile`, which can be used to keep a `justfile` hidden. === Just Scripts By adding a shebang line to the top of a justfile and making it executable, `just` can be used as an interpreter for scripts: ```sh $ cat > script < just.zsh ``` === Grammar A non-normative grammar of justfiles can be found in link:GRAMMAR.md[]. === just.sh Before `just` was a fancy Rust program it was a tiny shell script that called `make`. You can find the old version in link:extras/just.sh[]. === Non-Project Specific Justfile If you want some commands to be available everywhere, put them in `~/.global.justfile` and add the following to your shell's initialization file: ```sh alias .j='just --justfile ~/.global.justfile --working-directory ~' ``` Or, if you'd rather they run in the current directory: ```sh alias .j='just --justfile ~/.global.justfile --working-directory .' ``` I'm pretty sure that nobody actually uses this feature, but it's there. ¯\\\\_(ツ)_/¯ == Contributing `just` welcomes your contributions! `just` is released under the maximally permissive https://creativecommons.org/publicdomain/zero/1.0/legalcode.txt[CC0] public domain dedication and fallback license, so your changes must also be released under this license. === Janus https://github.com/casey/janus[Janus] is a tool that collects and analyzes justfiles, and can determine if a new version of `just` breaks or changes the interpretation of existing justfiles. Before merging a particularly large or gruesome change, Janus should be run to make sure that nothing breaks. Don't worry about running Janus yourself, Casey will happily run it for you on changes that need it. === Minimum Supported Rust Version The minimum supported Rust version, or MSRV, can be found in link:rust-toolchain[]. == Frequently Asked Questions === What are the idiosyncrasies of Make that Just avoids? `make` has some behaviors which are confusing, complicated, or make it unsuitable for use as a general command runner. One example is that under some circumstances, `make` won't actually run the commands in a recipe. For example, if you have a file called `test` and the following makefile: ```make test: ./test ``` `make` will refuse to run your tests: ```sh $ make test make: `test' is up to date. ``` `make` assumes that the `test` recipe produces a file called `test`. Since this file exists and the recipe has no other dependencies, `make` thinks that it doesn't have anything to do and exits. To be fair, this behavior is desirable when using `make` as a build system, but not when using it as a command runner. You can disable this behavior for specific targets using `make`'s built-in link:https://www.gnu.org/software/make/manual/html_node/Phony-Targets.html[`.PHONY` target name], but the syntax is verbose and can be hard to remember. The explicit list of phony targets, written separately from the recipe definitions, also introduces the risk of accidentally defining a new non-phony target. In `just`, all recipes are treated as if they were phony. Other examples of `make`'s idiosyncrasies include the difference between `=` and `:=` in assignments, the confusing error messages that are produced if you mess up your makefile, needing `$$` to use environment variables in recipes, and incompatibilities between different flavors of `make`. === What's the relationship between Just and Cargo build scripts? http://doc.crates.io/build-script.html[`cargo` build scripts] have a pretty specific use, which is to control how `cargo` builds your Rust project. This might include adding flags to `rustc` invocations, building an external dependency, or running some kind of codegen step. `just`, on the other hand, is for all the other miscellaneous commands you might run as part of development. Things like running tests in different configurations, linting your code, pushing build artifacts to a server, removing temporary files, and the like. Also, although `just` is written in Rust, it can be used regardless of the language or build system your project uses. == Further Ramblings I personally find it very useful to write a `justfile` for almost every project, big or small. On a big project with multiple contributors, it's very useful to have a file with all the commands needed to work on the project close at hand. There are probably different commands to test, build, lint, deploy, and the like, and having them all in one place is useful and cuts down on the time you have to spend telling people which commands to run and how to type them. And, with an easy place to put commands, it's likely that you'll come up with other useful things which are part of the project's collective wisdom, but which aren't written down anywhere, like the arcane commands needed for some part of your revision control workflow, install all your project's dependencies, or all the random flags you might need to pass to the build system. Some ideas for recipes: * Deploying/publishing the project * Building in release mode vs debug mode * Running in debug mode or with logging enabled * Complex git workflows * Updating dependencies * Running different sets of tests, for example fast tests vs slow tests, or running them with verbose output * Any complex set of commands that you really should write down somewhere, if only to be able to remember them Even for small, personal projects it's nice to be able to remember commands by name instead of ^Reverse searching your shell history, and it's a huge boon to be able to go into an old project written in a random language with a mysterious build system and know that all the commands you need to do whatever you need to do are in the `justfile`, and that if you type `just` something useful (or at least interesting!) will probably happen. For ideas for recipes, check out link:justfile[this project's `justfile`], or some of the `justfile`{zwsp}s https://github.com/search?o=desc&q=filename%3Ajustfile&s=indexed&type=Code[out in the wild]. Anyways, I think that's about it for this incredibly long-winded README. I hope you enjoy using `just` and find great success and satisfaction in all your computational endeavors! 😸 ",12451,False,1938.4256326947811,median "[[debezium-mysql-component]] = Debezium MySQL Connector Component //THIS FILE IS COPIED: EDIT THE SOURCE FILE: :page-source: components/camel-debezium-mysql/src/main/docs/debezium-mysql-component.adoc :docTitle: Debezium MySQL Connector :artifactId: camel-debezium-mysql :description: Capture changes from a MySQL database. :since: 3.0 :supportLevel: Stable :component-header: Only consumer is supported include::{cq-version}@camel-quarkus:ROOT:partial$reference/components/debezium-mysql.adoc[opts=optional] *Since Camel {since}* *{component-header}* The Debezium MySQL component is wrapper around https://debezium.io/[Debezium] using https://debezium.io/documentation/reference/0.9/operations/embedded.html[Debezium Embedded], which enables Change Data Capture from MySQL database using Debezium without the need for Kafka or Kafka Connect. *Note on handling failures:* Per https://debezium.io/documentation/reference/0.9/operations/embedded.html#_handling_failures[Debezium Embedded Engine] documentation, the engines is actively recording source offsets and periodically flushes these offsets to a persistent storage, so when the application is restarted or crashed, the engine will resume from the last recorded offset. Thus, at normal operation, your downstream routes will receive each event exactly once, however in case of an application crash (not having a graceful shutdown), the application will resume from the last recorded offset, which may result in receiving duplicate events immediately after the restart. Therefore, your downstream routes should be tolerant enough of such case and deduplicate events if needed. *Note:* The Debezium MySQL component is currently not supported in OSGi Maven users will need to add the following dependency to their `pom.xml` for this component. [source,xml] ---- org.apache.camel camel-debezium-mysql x.x.x ---- == URI format [source,text] --------------------------- debezium-mysql:name[?options] --------------------------- *Note:* Due to licensing issues, you will need to add the dependency for `mysql-conenctor-java` if you are using MySQL connector, just add the following to your POM file: [source,xml] ---- mysql mysql-connector-java 8.0.15 ---- == Options // component options: START The Debezium MySQL Connector component supports 79 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *additionalProperties* (common) | Additional properties for debezium components in case they can't be set directly on the camel configurations (e.g: setting Kafka Connect properties needed by Debezium engine, for example setting KafkaOffsetBackingStore), the properties have to be prefixed with additionalProperties.. E.g: additionalProperties.transactional.id=12345&additionalProperties.schema.registry.url=\\http://localhost:8811/avro | | Map | *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 | *configuration* (consumer) | Allow pre-configured Configurations to be set. | | MySqlConnectorEmbeddedDebeziumConfiguration | *internalKeyConverter* (consumer) | The Converter class that should be used to serialize and deserialize key data for offsets. The default is JSON converter. | org.apache.kafka.connect.json.JsonConverter | String | *internalValueConverter* (consumer) | The Converter class that should be used to serialize and deserialize value data for offsets. The default is JSON converter. | org.apache.kafka.connect.json.JsonConverter | String | *offsetCommitPolicy* (consumer) | The name of the Java class of the commit policy. It defines when offsets commit has to be triggered based on the number of events processed and the time elapsed since the last commit. This class must implement the interface 'OffsetCommitPolicy'. The default is a periodic commit policy based upon time intervals. | io.debezium.embedded.spi.OffsetCommitPolicy.PeriodicCommitOffsetPolicy | String | *offsetCommitTimeoutMs* (consumer) | Maximum number of milliseconds to wait for records to flush and partition offset data to be committed to offset storage before cancelling the process and restoring the offset data to be committed in a future attempt. The default is 5 seconds. | 5s | long | *offsetFlushIntervalMs* (consumer) | Interval at which to try committing offsets. The default is 1 minute. | 60s | long | *offsetStorage* (consumer) | The name of the Java class that is responsible for persistence of connector offsets. | org.apache.kafka.connect.storage.FileOffsetBackingStore | String | *offsetStorageFileName* (consumer) | Path to file where offsets are to be stored. Required when offset.storage is set to the FileOffsetBackingStore. | | String | *offsetStoragePartitions* (consumer) | The number of partitions used when creating the offset storage topic. Required when offset.storage is set to the 'KafkaOffsetBackingStore'. | | int | *offsetStorageReplicationFactor* (consumer) | Replication factor used when creating the offset storage topic. Required when offset.storage is set to the KafkaOffsetBackingStore | | int | *offsetStorageTopic* (consumer) | The name of the Kafka topic where offsets are to be stored. Required when offset.storage is set to the KafkaOffsetBackingStore. | | String | *basicPropertyBinding* (advanced) | *Deprecated* Whether the component should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities | false | boolean | *bigintUnsignedHandlingMode* (mysql) | Specify how BIGINT UNSIGNED columns should be represented in change events, including:'precise' uses java.math.BigDecimal to represent values, which are encoded in the change events using a binary representation and Kafka Connect's 'org.apache.kafka.connect.data.Decimal' type; 'long' (the default) represents values using Java's 'long', which may not offer the precision but will be far easier to use in consumers. | long | String | *binaryHandlingMode* (mysql) | Specify how binary (blob, binary, etc.) columns should be represented in change events, including:'bytes' represents binary data as byte array (default)'base64' represents binary data as base64-encoded string'hex' represents binary data as hex-encoded (base16) string | bytes | String | *binlogBufferSize* (mysql) | The size of a look-ahead buffer used by the binlog reader to decide whether the transaction in progress is going to be committed or rolled back. Use 0 to disable look-ahead buffering. Defaults to 0 (i.e. buffering is disabled). | 0 | int | *columnBlacklist* (mysql) | Regular expressions matching columns to exclude from change events (deprecated, use column.exclude.list instead) | | String | *columnExcludeList* (mysql) | Regular expressions matching columns to exclude from change events | | String | *columnIncludeList* (mysql) | Regular expressions matching columns to include in change events | | String | *connectKeepAlive* (mysql) | Whether a separate thread should be used to ensure the connection is kept alive. | true | boolean | *connectKeepAliveIntervalMs* (mysql) | Interval in milliseconds to wait for connection checking if keep alive thread is used. | 1m | long | *connectTimeoutMs* (mysql) | Maximum time in milliseconds to wait after trying to connect to the database before timing out. | 30s | int | *databaseExcludeList* (mysql) | A comma-separated list of regular expressions that match database names to be excluded from monitoring | | String | *databaseHistory* (mysql) | The name of the DatabaseHistory class that should be used to store and recover database schema changes. The configuration properties for the history are prefixed with the 'database.history.' string. | io.debezium.relational.history.FileDatabaseHistory | String | *databaseHistoryFileFilename* (mysql) | The path to the file that will be used to record the database history | | String | *databaseHistoryKafkaBootstrap{zwsp}Servers* (mysql) | A list of host/port pairs that the connector will use for establishing the initial connection to the Kafka cluster for retrieving database schema history previously stored by the connector. This should point to the same Kafka cluster used by the Kafka Connect process. | | String | *databaseHistoryKafkaRecovery{zwsp}Attempts* (mysql) | The number of attempts in a row that no data are returned from Kafka before recover completes. The maximum amount of time to wait after receiving no data is (recovery.attempts) x (recovery.poll.interval.ms). | 100 | int | *databaseHistoryKafkaRecovery{zwsp}PollIntervalMs* (mysql) | The number of milliseconds to wait while polling for persisted data during recovery. | 100ms | int | *databaseHistoryKafkaTopic* (mysql) | The name of the topic for the database schema history | | String | *databaseHistorySkipUnparseable{zwsp}Ddl* (mysql) | Controls the action Debezium will take when it meets a DDL statement in binlog, that it cannot parse.By default the connector will stop operating but by changing the setting it can ignore the statements which it cannot parse. If skipping is enabled then Debezium can miss metadata changes. | false | boolean | *databaseHistoryStoreOnly{zwsp}MonitoredTablesDdl* (mysql) | Controls what DDL will Debezium store in database history.By default (false) Debezium will store all incoming DDL statements. If set to truethen only DDL that manipulates a monitored table will be stored. | false | boolean | *databaseHostname* (mysql) | Resolvable hostname or IP address of the MySQL database server. | | String | *databaseIncludeList* (mysql) | The databases for which changes are to be captured | | String | *databaseInitialStatements* (mysql) | A semicolon separated list of SQL statements to be executed when a JDBC connection (not binlog reading connection) to the database is established. Note that the connector may establish JDBC connections at its own discretion, so this should typically be used for configuration of session parameters only,but not for executing DML statements. Use doubled semicolon (';;') to use a semicolon as a character and not as a delimiter. | | String | *databaseJdbcDriver* (mysql) | JDBC Driver class name used to connect to the MySQL database server. | class com.mysql.cj.jdbc.Driver | String | *databasePassword* (mysql) | *Required* Password of the MySQL database user to be used when connecting to the database. | | String | *databasePort* (mysql) | Port of the MySQL database server. | 3306 | int | *databaseServerId* (mysql) | A numeric ID of this database client, which must be unique across all currently-running database processes in the cluster. This connector joins the MySQL database cluster as another server (with this unique ID) so it can read the binlog. By default, a random number is generated between 5400 and 6400. | | long | *databaseServerIdOffset* (mysql) | Only relevant if parallel snapshotting is configured. During parallel snapshotting, multiple (4) connections open to the database client, and they each need their own unique connection ID. This offset is used to generate those IDs from the base configured cluster ID. | 10000 | long | *databaseServerName* (mysql) | *Required* Unique name that identifies the database server and all recorded offsets, and that is used as a prefix for all schemas and topics. Each distinct installation should have a separate namespace and be monitored by at most one Debezium connector. | | String | *databaseSslKeystore* (mysql) | Location of the Java keystore file containing an application process's own certificate and private key. | | String | *databaseSslKeystorePassword* (mysql) | Password to access the private key from the keystore file specified by 'ssl.keystore' configuration property or the 'javax.net.ssl.keyStore' system or JVM property. This password is used to unlock the keystore file (store password), and to decrypt the private key stored in the keystore (key password). | | String | *databaseSslMode* (mysql) | Whether to use an encrypted connection to MySQL. Options include'disabled' (the default) to use an unencrypted connection; 'preferred' to establish a secure (encrypted) connection if the server supports secure connections, but fall back to an unencrypted connection otherwise; 'required' to use a secure (encrypted) connection, and fail if one cannot be established; 'verify_ca' like 'required' but additionally verify the server TLS certificate against the configured Certificate Authority (CA) certificates, or fail if no valid matching CA certificates are found; or'verify_identity' like 'verify_ca' but additionally verify that the server certificate matches the host to which the connection is attempted. | disabled | String | *databaseSslTruststore* (mysql) | Location of the Java truststore file containing the collection of CA certificates trusted by this application process (trust store). | | String | *databaseSslTruststorePassword* (mysql) | Password to unlock the keystore file (store password) specified by 'ssl.trustore' configuration property or the 'javax.net.ssl.trustStore' system or JVM property. | | String | *databaseUser* (mysql) | Name of the MySQL database user to be used when connecting to the database. | | String | *decimalHandlingMode* (mysql) | Specify how DECIMAL and NUMERIC columns should be represented in change events, including:'precise' (the default) uses java.math.BigDecimal to represent values, which are encoded in the change events using a binary representation and Kafka Connect's 'org.apache.kafka.connect.data.Decimal' type; 'string' uses string to represent values; 'double' represents values using Java's 'double', which may not offer the precision but will be far easier to use in consumers. | precise | String | *enableTimeAdjuster* (mysql) | MySQL allows user to insert year value as either 2-digit or 4-digit. In case of two digit the value is automatically mapped into 1970 - 2069.false - delegates the implicit conversion to the databasetrue - (the default) Debezium makes the conversion | true | boolean | *eventDeserializationFailure{zwsp}HandlingMode* (mysql) | Specify how failures during deserialization of binlog events (i.e. when encountering a corrupted event) should be handled, including:'fail' (the default) an exception indicating the problematic event and its binlog position is raised, causing the connector to be stopped; 'warn' the problematic event and its binlog position will be logged and the event will be skipped;'ignore' the problematic event will be skipped. | fail | String | *eventProcessingFailureHandling{zwsp}Mode* (mysql) | Specify how failures during processing of events (i.e. when encountering a corrupted event) should be handled, including:'fail' (the default) an exception indicating the problematic event and its position is raised, causing the connector to be stopped; 'warn' the problematic event and its position will be logged and the event will be skipped;'ignore' the problematic event will be skipped. | fail | String | *gtidNewChannelPosition* (mysql) | If set to 'latest', when connector sees new GTID, it will start consuming gtid channel from the server latest executed gtid position. If 'earliest' (the default) connector starts reading channel from first available (not purged) gtid position on the server. | earliest | String | *gtidSourceExcludes* (mysql) | The source UUIDs used to exclude GTID ranges when determine the starting position in the MySQL server's binlog. | | String | *gtidSourceFilterDmlEvents* (mysql) | If set to true, we will only produce DML events into Kafka for transactions that were written on mysql servers with UUIDs matching the filters defined by the gtid.source.includes or gtid.source.excludes configuration options, if they are specified. | true | boolean | *gtidSourceIncludes* (mysql) | The source UUIDs used to include GTID ranges when determine the starting position in the MySQL server's binlog. | | String | *heartbeatIntervalMs* (mysql) | Length of an interval in milli-seconds in in which the connector periodically sends heartbeat messages to a heartbeat topic. Use 0 to disable heartbeat messages. Disabled by default. | 0ms | int | *heartbeatTopicsPrefix* (mysql) | The prefix that is used to name heartbeat topics.Defaults to __debezium-heartbeat. | __debezium-heartbeat | String | *includeQuery* (mysql) | Whether the connector should include the original SQL query that generated the change event. Note: This option requires MySQL be configured with the binlog_rows_query_log_events option set to ON. Query will not be present for events generated from snapshot. WARNING: Enabling this option may expose tables or fields explicitly blacklisted or masked by including the original SQL statement in the change event. For this reason the default value is 'false'. | false | boolean | *includeSchemaChanges* (mysql) | Whether the connector should publish changes in the database schema to a Kafka topic with the same name as the database server ID. Each schema change will be recorded using a key that contains the database name and whose value include logical description of the new schema and optionally the DDL statement(s).The default is 'true'. This is independent of how the connector internally records database history. | true | boolean | *inconsistentSchemaHandlingMode* (mysql) | Specify how binlog events that belong to a table missing from internal schema representation (i.e. internal representation is not consistent with database) should be handled, including:'fail' (the default) an exception indicating the problematic event and its binlog position is raised, causing the connector to be stopped; 'warn' the problematic event and its binlog position will be logged and the event will be skipped;'skip' the problematic event will be skipped. | fail | String | *maxBatchSize* (mysql) | Maximum size of each batch of source records. Defaults to 2048. | 2048 | int | *maxQueueSize* (mysql) | Maximum size of the queue for change events read from the database log but not yet recorded or forwarded. Defaults to 8192, and should always be larger than the maximum batch size. | 8192 | int | *messageKeyColumns* (mysql) | A semicolon-separated list of expressions that match fully-qualified tables and column(s) to be used as message key. Each expression must match the pattern ':',where the table names could be defined as (DB_NAME.TABLE_NAME) or (SCHEMA_NAME.TABLE_NAME), depending on the specific connector,and the key columns are a comma-separated list of columns representing the custom key. For any table without an explicit key configuration the table's primary key column(s) will be used as message key.Example: dbserver1.inventory.orderlines:orderId,orderLineId;dbserver1.inventory.orders:id | | String | *pollIntervalMs* (mysql) | Frequency in milliseconds to wait for new change events to appear after receiving no events. Defaults to 500ms. | 500ms | long | *skippedOperations* (mysql) | The comma-separated list of operations to skip during streaming, defined as: 'i' for inserts; 'u' for updates; 'd' for deletes. By default, no operations will be skipped. | | String | *snapshotDelayMs* (mysql) | The number of milliseconds to delay before a snapshot will begin. | 0ms | long | *snapshotFetchSize* (mysql) | The maximum number of records that should be loaded into memory while performing a snapshot | | int | *snapshotLockingMode* (mysql) | Controls how long the connector holds onto the global read lock while it is performing a snapshot. The default is 'minimal', which means the connector holds the global read lock (and thus prevents any updates) for just the initial portion of the snapshot while the database schemas and other metadata are being read. The remaining work in a snapshot involves selecting all rows from each table, and this can be done using the snapshot process' REPEATABLE READ transaction even when the lock is no longer held and other operations are updating the database. However, in some cases it may be desirable to block all writes for the entire duration of the snapshot; in such cases set this property to 'extended'. Using a value of 'none' will prevent the connector from acquiring any table locks during the snapshot process. This mode can only be used in combination with snapshot.mode values of 'schema_only' or 'schema_only_recovery' and is only safe to use if no schema changes are happening while the snapshot is taken. | minimal | String | *snapshotMode* (mysql) | The criteria for running a snapshot upon startup of the connector. Options include: 'when_needed' to specify that the connector run a snapshot upon startup whenever it deems it necessary; 'schema_only' to only take a snapshot of the schema (table structures) but no actual data; 'initial' (the default) to specify the connector can run a snapshot only when no offsets are available for the logical server name; 'initial_only' same as 'initial' except the connector should stop after completing the snapshot and before it would normally read the binlog; and'never' to specify the connector should never run a snapshot and that upon first startup the connector should read from the beginning of the binlog. The 'never' mode should be used with care, and only when the binlog is known to contain all history. | initial | String | *snapshotNewTables* (mysql) | BETA FEATURE: On connector restart, the connector will check if there have been any new tables added to the configuration, and snapshot them. There is presently only two options:'off': Default behavior. Do not snapshot new tables.'parallel': The snapshot of the new tables will occur in parallel to the continued binlog reading of the old tables. When the snapshot completes, an independent binlog reader will begin reading the events for the new tables until it catches up to present time. At this point, both old and new binlog readers will be momentarily halted and new binlog reader will start that will read the binlog for all configured tables. The parallel binlog reader will have a configured server id of 10000 the primary binlog reader's server id. | off | String | *snapshotSelectStatement{zwsp}Overrides* (mysql) | This property contains a comma-separated list of fully-qualified tables (DB_NAME.TABLE_NAME) or (SCHEMA_NAME.TABLE_NAME), depending on thespecific connectors . Select statements for the individual tables are specified in further configuration properties, one for each table, identified by the id 'snapshot.select.statement.overrides.DB_NAME.TABLE_NAME' or 'snapshot.select.statement.overrides.SCHEMA_NAME.TABLE_NAME', respectively. The value of those properties is the select statement to use when retrieving data from the specific table during snapshotting. A possible use case for large append-only tables is setting a specific point where to start (resume) snapshotting, in case a previous snapshotting was interrupted. | | String | *sourceStructVersion* (mysql) | A version of the format of the publicly visible source part in the message | v2 | String | *tableBlacklist* (mysql) | A comma-separated list of regular expressions that match the fully-qualified names of tables to be excluded from monitoring (deprecated, use table.exclude.list instead) | | String | *tableExcludeList* (mysql) | A comma-separated list of regular expressions that match the fully-qualified names of tables to be excluded from monitoring | | String | *tableIgnoreBuiltin* (mysql) | Flag specifying whether built-in tables should be ignored. | true | boolean | *tableIncludeList* (mysql) | The tables for which changes are to be captured | | String | *tableWhitelist* (mysql) | The tables for which changes are to be captured (deprecated, use table.include.list instead) | | String | *timePrecisionMode* (mysql) | Time, date and timestamps can be represented with different kinds of precisions, including:'adaptive_time_microseconds': the precision of date and timestamp values is based the database column's precision; but time fields always use microseconds precision;'connect': always represents time, date and timestamp values using Kafka Connect's built-in representations for Time, Date, and Timestamp, which uses millisecond precision regardless of the database columns' precision. | adaptive_time_microseconds | String | *tombstonesOnDelete* (mysql) | Whether delete operations should be represented by a delete event and a subsquenttombstone event (true) or only by a delete event (false). Emitting the tombstone event (the default behavior) allows Kafka to completely delete all events pertaining to the given key once the source record got deleted. | false | boolean |=== // component options: END // endpoint options: START The Debezium MySQL Connector endpoint is configured using URI syntax: ---- debezium-mysql:name ---- with the following path and query parameters: === Path Parameters (1 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *name* | *Required* Unique name for the connector. Attempting to register again with the same name will fail. | | String |=== === Query Parameters (81 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *additionalProperties* (common) | Additional properties for debezium components in case they can't be set directly on the camel configurations (e.g: setting Kafka Connect properties needed by Debezium engine, for example setting KafkaOffsetBackingStore), the properties have to be prefixed with additionalProperties.. E.g: additionalProperties.transactional.id=12345&additionalProperties.schema.registry.url=\\http://localhost:8811/avro | | Map | *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 | *internalKeyConverter* (consumer) | The Converter class that should be used to serialize and deserialize key data for offsets. The default is JSON converter. | org.apache.kafka.connect.json.JsonConverter | String | *internalValueConverter* (consumer) | The Converter class that should be used to serialize and deserialize value data for offsets. The default is JSON converter. | org.apache.kafka.connect.json.JsonConverter | String | *offsetCommitPolicy* (consumer) | The name of the Java class of the commit policy. It defines when offsets commit has to be triggered based on the number of events processed and the time elapsed since the last commit. This class must implement the interface 'OffsetCommitPolicy'. The default is a periodic commit policy based upon time intervals. | io.debezium.embedded.spi.OffsetCommitPolicy.PeriodicCommitOffsetPolicy | String | *offsetCommitTimeoutMs* (consumer) | Maximum number of milliseconds to wait for records to flush and partition offset data to be committed to offset storage before cancelling the process and restoring the offset data to be committed in a future attempt. The default is 5 seconds. | 5s | long | *offsetFlushIntervalMs* (consumer) | Interval at which to try committing offsets. The default is 1 minute. | 60s | long | *offsetStorage* (consumer) | The name of the Java class that is responsible for persistence of connector offsets. | org.apache.kafka.connect.storage.FileOffsetBackingStore | String | *offsetStorageFileName* (consumer) | Path to file where offsets are to be stored. Required when offset.storage is set to the FileOffsetBackingStore. | | String | *offsetStoragePartitions* (consumer) | The number of partitions used when creating the offset storage topic. Required when offset.storage is set to the 'KafkaOffsetBackingStore'. | | int | *offsetStorageReplicationFactor* (consumer) | Replication factor used when creating the offset storage topic. Required when offset.storage is set to the KafkaOffsetBackingStore | | int | *offsetStorageTopic* (consumer) | The name of the Kafka topic where offsets are to be stored. Required when offset.storage is set to the KafkaOffsetBackingStore. | | String | *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. There are 3 enums and the value can be one of: InOnly, InOut, InOptionalOut | | ExchangePattern | *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 | *bigintUnsignedHandlingMode* (mysql) | Specify how BIGINT UNSIGNED columns should be represented in change events, including:'precise' uses java.math.BigDecimal to represent values, which are encoded in the change events using a binary representation and Kafka Connect's 'org.apache.kafka.connect.data.Decimal' type; 'long' (the default) represents values using Java's 'long', which may not offer the precision but will be far easier to use in consumers. | long | String | *binaryHandlingMode* (mysql) | Specify how binary (blob, binary, etc.) columns should be represented in change events, including:'bytes' represents binary data as byte array (default)'base64' represents binary data as base64-encoded string'hex' represents binary data as hex-encoded (base16) string | bytes | String | *binlogBufferSize* (mysql) | The size of a look-ahead buffer used by the binlog reader to decide whether the transaction in progress is going to be committed or rolled back. Use 0 to disable look-ahead buffering. Defaults to 0 (i.e. buffering is disabled). | 0 | int | *columnBlacklist* (mysql) | Regular expressions matching columns to exclude from change events (deprecated, use column.exclude.list instead) | | String | *columnExcludeList* (mysql) | Regular expressions matching columns to exclude from change events | | String | *columnIncludeList* (mysql) | Regular expressions matching columns to include in change events | | String | *connectKeepAlive* (mysql) | Whether a separate thread should be used to ensure the connection is kept alive. | true | boolean | *connectKeepAliveIntervalMs* (mysql) | Interval in milliseconds to wait for connection checking if keep alive thread is used. | 1m | long | *connectTimeoutMs* (mysql) | Maximum time in milliseconds to wait after trying to connect to the database before timing out. | 30s | int | *databaseExcludeList* (mysql) | A comma-separated list of regular expressions that match database names to be excluded from monitoring | | String | *databaseHistory* (mysql) | The name of the DatabaseHistory class that should be used to store and recover database schema changes. The configuration properties for the history are prefixed with the 'database.history.' string. | io.debezium.relational.history.FileDatabaseHistory | String | *databaseHistoryFileFilename* (mysql) | The path to the file that will be used to record the database history | | String | *databaseHistoryKafkaBootstrap{zwsp}Servers* (mysql) | A list of host/port pairs that the connector will use for establishing the initial connection to the Kafka cluster for retrieving database schema history previously stored by the connector. This should point to the same Kafka cluster used by the Kafka Connect process. | | String | *databaseHistoryKafkaRecovery{zwsp}Attempts* (mysql) | The number of attempts in a row that no data are returned from Kafka before recover completes. The maximum amount of time to wait after receiving no data is (recovery.attempts) x (recovery.poll.interval.ms). | 100 | int | *databaseHistoryKafkaRecovery{zwsp}PollIntervalMs* (mysql) | The number of milliseconds to wait while polling for persisted data during recovery. | 100ms | int | *databaseHistoryKafkaTopic* (mysql) | The name of the topic for the database schema history | | String | *databaseHistorySkipUnparseable{zwsp}Ddl* (mysql) | Controls the action Debezium will take when it meets a DDL statement in binlog, that it cannot parse.By default the connector will stop operating but by changing the setting it can ignore the statements which it cannot parse. If skipping is enabled then Debezium can miss metadata changes. | false | boolean | *databaseHistoryStoreOnly{zwsp}MonitoredTablesDdl* (mysql) | Controls what DDL will Debezium store in database history.By default (false) Debezium will store all incoming DDL statements. If set to truethen only DDL that manipulates a monitored table will be stored. | false | boolean | *databaseHostname* (mysql) | Resolvable hostname or IP address of the MySQL database server. | | String | *databaseIncludeList* (mysql) | The databases for which changes are to be captured | | String | *databaseInitialStatements* (mysql) | A semicolon separated list of SQL statements to be executed when a JDBC connection (not binlog reading connection) to the database is established. Note that the connector may establish JDBC connections at its own discretion, so this should typically be used for configuration of session parameters only,but not for executing DML statements. Use doubled semicolon (';;') to use a semicolon as a character and not as a delimiter. | | String | *databaseJdbcDriver* (mysql) | JDBC Driver class name used to connect to the MySQL database server. | class com.mysql.cj.jdbc.Driver | String | *databasePassword* (mysql) | *Required* Password of the MySQL database user to be used when connecting to the database. | | String | *databasePort* (mysql) | Port of the MySQL database server. | 3306 | int | *databaseServerId* (mysql) | A numeric ID of this database client, which must be unique across all currently-running database processes in the cluster. This connector joins the MySQL database cluster as another server (with this unique ID) so it can read the binlog. By default, a random number is generated between 5400 and 6400. | | long | *databaseServerIdOffset* (mysql) | Only relevant if parallel snapshotting is configured. During parallel snapshotting, multiple (4) connections open to the database client, and they each need their own unique connection ID. This offset is used to generate those IDs from the base configured cluster ID. | 10000 | long | *databaseServerName* (mysql) | *Required* Unique name that identifies the database server and all recorded offsets, and that is used as a prefix for all schemas and topics. Each distinct installation should have a separate namespace and be monitored by at most one Debezium connector. | | String | *databaseSslKeystore* (mysql) | Location of the Java keystore file containing an application process's own certificate and private key. | | String | *databaseSslKeystorePassword* (mysql) | Password to access the private key from the keystore file specified by 'ssl.keystore' configuration property or the 'javax.net.ssl.keyStore' system or JVM property. This password is used to unlock the keystore file (store password), and to decrypt the private key stored in the keystore (key password). | | String | *databaseSslMode* (mysql) | Whether to use an encrypted connection to MySQL. Options include'disabled' (the default) to use an unencrypted connection; 'preferred' to establish a secure (encrypted) connection if the server supports secure connections, but fall back to an unencrypted connection otherwise; 'required' to use a secure (encrypted) connection, and fail if one cannot be established; 'verify_ca' like 'required' but additionally verify the server TLS certificate against the configured Certificate Authority (CA) certificates, or fail if no valid matching CA certificates are found; or'verify_identity' like 'verify_ca' but additionally verify that the server certificate matches the host to which the connection is attempted. | disabled | String | *databaseSslTruststore* (mysql) | Location of the Java truststore file containing the collection of CA certificates trusted by this application process (trust store). | | String | *databaseSslTruststorePassword* (mysql) | Password to unlock the keystore file (store password) specified by 'ssl.trustore' configuration property or the 'javax.net.ssl.trustStore' system or JVM property. | | String | *databaseUser* (mysql) | Name of the MySQL database user to be used when connecting to the database. | | String | *decimalHandlingMode* (mysql) | Specify how DECIMAL and NUMERIC columns should be represented in change events, including:'precise' (the default) uses java.math.BigDecimal to represent values, which are encoded in the change events using a binary representation and Kafka Connect's 'org.apache.kafka.connect.data.Decimal' type; 'string' uses string to represent values; 'double' represents values using Java's 'double', which may not offer the precision but will be far easier to use in consumers. | precise | String | *enableTimeAdjuster* (mysql) | MySQL allows user to insert year value as either 2-digit or 4-digit. In case of two digit the value is automatically mapped into 1970 - 2069.false - delegates the implicit conversion to the databasetrue - (the default) Debezium makes the conversion | true | boolean | *eventDeserializationFailure{zwsp}HandlingMode* (mysql) | Specify how failures during deserialization of binlog events (i.e. when encountering a corrupted event) should be handled, including:'fail' (the default) an exception indicating the problematic event and its binlog position is raised, causing the connector to be stopped; 'warn' the problematic event and its binlog position will be logged and the event will be skipped;'ignore' the problematic event will be skipped. | fail | String | *eventProcessingFailureHandling{zwsp}Mode* (mysql) | Specify how failures during processing of events (i.e. when encountering a corrupted event) should be handled, including:'fail' (the default) an exception indicating the problematic event and its position is raised, causing the connector to be stopped; 'warn' the problematic event and its position will be logged and the event will be skipped;'ignore' the problematic event will be skipped. | fail | String | *gtidNewChannelPosition* (mysql) | If set to 'latest', when connector sees new GTID, it will start consuming gtid channel from the server latest executed gtid position. If 'earliest' (the default) connector starts reading channel from first available (not purged) gtid position on the server. | earliest | String | *gtidSourceExcludes* (mysql) | The source UUIDs used to exclude GTID ranges when determine the starting position in the MySQL server's binlog. | | String | *gtidSourceFilterDmlEvents* (mysql) | If set to true, we will only produce DML events into Kafka for transactions that were written on mysql servers with UUIDs matching the filters defined by the gtid.source.includes or gtid.source.excludes configuration options, if they are specified. | true | boolean | *gtidSourceIncludes* (mysql) | The source UUIDs used to include GTID ranges when determine the starting position in the MySQL server's binlog. | | String | *heartbeatIntervalMs* (mysql) | Length of an interval in milli-seconds in in which the connector periodically sends heartbeat messages to a heartbeat topic. Use 0 to disable heartbeat messages. Disabled by default. | 0ms | int | *heartbeatTopicsPrefix* (mysql) | The prefix that is used to name heartbeat topics.Defaults to __debezium-heartbeat. | __debezium-heartbeat | String | *includeQuery* (mysql) | Whether the connector should include the original SQL query that generated the change event. Note: This option requires MySQL be configured with the binlog_rows_query_log_events option set to ON. Query will not be present for events generated from snapshot. WARNING: Enabling this option may expose tables or fields explicitly blacklisted or masked by including the original SQL statement in the change event. For this reason the default value is 'false'. | false | boolean | *includeSchemaChanges* (mysql) | Whether the connector should publish changes in the database schema to a Kafka topic with the same name as the database server ID. Each schema change will be recorded using a key that contains the database name and whose value include logical description of the new schema and optionally the DDL statement(s).The default is 'true'. This is independent of how the connector internally records database history. | true | boolean | *inconsistentSchemaHandlingMode* (mysql) | Specify how binlog events that belong to a table missing from internal schema representation (i.e. internal representation is not consistent with database) should be handled, including:'fail' (the default) an exception indicating the problematic event and its binlog position is raised, causing the connector to be stopped; 'warn' the problematic event and its binlog position will be logged and the event will be skipped;'skip' the problematic event will be skipped. | fail | String | *maxBatchSize* (mysql) | Maximum size of each batch of source records. Defaults to 2048. | 2048 | int | *maxQueueSize* (mysql) | Maximum size of the queue for change events read from the database log but not yet recorded or forwarded. Defaults to 8192, and should always be larger than the maximum batch size. | 8192 | int | *messageKeyColumns* (mysql) | A semicolon-separated list of expressions that match fully-qualified tables and column(s) to be used as message key. Each expression must match the pattern ':',where the table names could be defined as (DB_NAME.TABLE_NAME) or (SCHEMA_NAME.TABLE_NAME), depending on the specific connector,and the key columns are a comma-separated list of columns representing the custom key. For any table without an explicit key configuration the table's primary key column(s) will be used as message key.Example: dbserver1.inventory.orderlines:orderId,orderLineId;dbserver1.inventory.orders:id | | String | *pollIntervalMs* (mysql) | Frequency in milliseconds to wait for new change events to appear after receiving no events. Defaults to 500ms. | 500ms | long | *skippedOperations* (mysql) | The comma-separated list of operations to skip during streaming, defined as: 'i' for inserts; 'u' for updates; 'd' for deletes. By default, no operations will be skipped. | | String | *snapshotDelayMs* (mysql) | The number of milliseconds to delay before a snapshot will begin. | 0ms | long | *snapshotFetchSize* (mysql) | The maximum number of records that should be loaded into memory while performing a snapshot | | int | *snapshotLockingMode* (mysql) | Controls how long the connector holds onto the global read lock while it is performing a snapshot. The default is 'minimal', which means the connector holds the global read lock (and thus prevents any updates) for just the initial portion of the snapshot while the database schemas and other metadata are being read. The remaining work in a snapshot involves selecting all rows from each table, and this can be done using the snapshot process' REPEATABLE READ transaction even when the lock is no longer held and other operations are updating the database. However, in some cases it may be desirable to block all writes for the entire duration of the snapshot; in such cases set this property to 'extended'. Using a value of 'none' will prevent the connector from acquiring any table locks during the snapshot process. This mode can only be used in combination with snapshot.mode values of 'schema_only' or 'schema_only_recovery' and is only safe to use if no schema changes are happening while the snapshot is taken. | minimal | String | *snapshotMode* (mysql) | The criteria for running a snapshot upon startup of the connector. Options include: 'when_needed' to specify that the connector run a snapshot upon startup whenever it deems it necessary; 'schema_only' to only take a snapshot of the schema (table structures) but no actual data; 'initial' (the default) to specify the connector can run a snapshot only when no offsets are available for the logical server name; 'initial_only' same as 'initial' except the connector should stop after completing the snapshot and before it would normally read the binlog; and'never' to specify the connector should never run a snapshot and that upon first startup the connector should read from the beginning of the binlog. The 'never' mode should be used with care, and only when the binlog is known to contain all history. | initial | String | *snapshotNewTables* (mysql) | BETA FEATURE: On connector restart, the connector will check if there have been any new tables added to the configuration, and snapshot them. There is presently only two options:'off': Default behavior. Do not snapshot new tables.'parallel': The snapshot of the new tables will occur in parallel to the continued binlog reading of the old tables. When the snapshot completes, an independent binlog reader will begin reading the events for the new tables until it catches up to present time. At this point, both old and new binlog readers will be momentarily halted and new binlog reader will start that will read the binlog for all configured tables. The parallel binlog reader will have a configured server id of 10000 the primary binlog reader's server id. | off | String | *snapshotSelectStatement{zwsp}Overrides* (mysql) | This property contains a comma-separated list of fully-qualified tables (DB_NAME.TABLE_NAME) or (SCHEMA_NAME.TABLE_NAME), depending on thespecific connectors . Select statements for the individual tables are specified in further configuration properties, one for each table, identified by the id 'snapshot.select.statement.overrides.DB_NAME.TABLE_NAME' or 'snapshot.select.statement.overrides.SCHEMA_NAME.TABLE_NAME', respectively. The value of those properties is the select statement to use when retrieving data from the specific table during snapshotting. A possible use case for large append-only tables is setting a specific point where to start (resume) snapshotting, in case a previous snapshotting was interrupted. | | String | *sourceStructVersion* (mysql) | A version of the format of the publicly visible source part in the message | v2 | String | *tableBlacklist* (mysql) | A comma-separated list of regular expressions that match the fully-qualified names of tables to be excluded from monitoring (deprecated, use table.exclude.list instead) | | String | *tableExcludeList* (mysql) | A comma-separated list of regular expressions that match the fully-qualified names of tables to be excluded from monitoring | | String | *tableIgnoreBuiltin* (mysql) | Flag specifying whether built-in tables should be ignored. | true | boolean | *tableIncludeList* (mysql) | The tables for which changes are to be captured | | String | *tableWhitelist* (mysql) | The tables for which changes are to be captured (deprecated, use table.include.list instead) | | String | *timePrecisionMode* (mysql) | Time, date and timestamps can be represented with different kinds of precisions, including:'adaptive_time_microseconds': the precision of date and timestamp values is based the database column's precision; but time fields always use microseconds precision;'connect': always represents time, date and timestamp values using Kafka Connect's built-in representations for Time, Date, and Timestamp, which uses millisecond precision regardless of the database columns' precision. | adaptive_time_microseconds | String | *tombstonesOnDelete* (mysql) | Whether delete operations should be represented by a delete event and a subsquenttombstone event (true) or only by a delete event (false). Emitting the tombstone event (the default behavior) allows Kafka to completely delete all events pertaining to the given key once the source record got deleted. | false | boolean |=== // endpoint options: END For more information about configuration: https://debezium.io/documentation/reference/0.10/operations/embedded.html#engine-properties[https://debezium.io/documentation/reference/0.10/operations/embedded.html#engine-properties] https://debezium.io/documentation/reference/0.10/connectors/mysql.html#connector-properties[https://debezium.io/documentation/reference/0.10/connectors/mysql.html#connector-properties] == Message headers === Consumer headers The following headers are available when consuming change events from Debezium. [width=""100%"",cols=""2m,2m,1m,5"",options=""header""] |=== | Header constant | Header value | Type | Description | DebeziumConstants.HEADER_IDENTIFIER | ""CamelDebeziumIdentifier"" | String | The identifier of the connector, normally is this format ""+++{server-name}.{database-name}.{table-name}+++"". | DebeziumConstants.HEADER_KEY | ""CamelDebeziumKey"" | Struct | The key of the event, normally is the table Primary Key. | DebeziumConstants.HEADER_SOURCE_METADATA | ""CamelDebeziumSourceMetadata"" | Map | The metadata about the source event, for example `table` name, database `name`, log position, etc, please refer to the Debezium documentation for more info. | DebeziumConstants.HEADER_OPERATION | ""CamelDebeziumOperation"" | String | If presents, the type of event operation. Values for the connector are `c` for create (or insert), `u` for update, `d` for delete or `r` in case of a snapshot event. | DebeziumConstants.HEADER_TIMESTAMP | ""CamelDebeziumTimestamp"" | Long | If presents, the time (using the system clock in the JVM) at which the connector processed the event. | DebeziumConstants.HEADER_BEFORE | ""CamelDebeziumBefore"" | Struct | If presents, contains the state of the row before the event occurred. |=== == Message body The message body if is not `null` (in case of tombstones), it contains the state of the row after the event occurred as `Struct` format or `Map` format if you use the included Type Converter from `Struct` to `Map` (please look below for more explanation). == Samples === Consuming events Here is a very simple route that you can use in order to listen to Debezium events from MySQL connector. [source,java] ---- from(""debezium-mysql:dbz-test-1?offsetStorageFileName=/usr/offset-file-1.dat&databaseHostName=localhost&databaseUser=debezium&databasePassword=dbz&databaseServerName=my-app-connector&databaseHistoryFileName=/usr/history-file-1.dat"") .log(""Event received from Debezium : ${body}"") .log("" with this identifier ${headers.CamelDebeziumIdentifier}"") .log("" with these source metadata ${headers.CamelDebeziumSourceMetadata}"") .log("" the event occured upon this operation '${headers.CamelDebeziumSourceOperation}'"") .log("" on this database '${headers.CamelDebeziumSourceMetadata[db]}' and this table '${headers.CamelDebeziumSourceMetadata[table]}'"") .log("" with the key ${headers.CamelDebeziumKey}"") .log("" the previous value is ${headers.CamelDebeziumBefore}"") ---- By default, the component will emit the events in the body and `CamelDebeziumBefore` header as https://kafka.apache.org/22/javadoc/org/apache/kafka/connect/data/Struct.html[`Struct`] data type, the reasoning behind this, is to perceive the schema information in case is needed. However, the component as well contains a xref:manual::type-converter.adoc[Type Converter] that converts from default output type of https://kafka.apache.org/22/javadoc/org/apache/kafka/connect/data/Struct.html[`Struct`] to `Map` in order to leverage Camel's rich xref:manual::data-format.adoc[Data Format] types which many of them work out of box with `Map` data type. To use it, you can either add `Map.class` type when you access the message e.g: `exchange.getIn().getBody(Map.class)`, or you can convert the body always to `Map` from the route builder by adding `.convertBodyTo(Map.class)` to your Camel Route DSL after `from` statement. We mentioned above about the schema, which can be used in case you need to perform advance data transformation and the schema is needed for that. If you choose not to convert your body to `Map`, you can obtain the schema information as https://kafka.apache.org/22/javadoc/org/apache/kafka/connect/data/Schema.html[`Schema`] type from `Struct` like this: [source,java] ---- from(""debezium-mysql:[name]?[options]]) .process(exchange -> { final Struct bodyValue = exchange.getIn().getBody(Struct.class); final Schema schemaValue = bodyValue.schema(); log.info(""Body value is :"" + bodyValue); log.info(""With Schema : "" + schemaValue); log.info(""And fields of :"" + schemaValue.fields()); log.info(""Field name has `"" + schemaValue.field(""name"").schema() + ""` type""); }); ---- *Important Note:* This component is a thin wrapper around Debezium Engine as mentioned, therefore before using this component in production, you need to understand how Debezium works and how configurations can reflect the expected behavior, especially in regards to https://debezium.io/documentation/reference/0.9/operations/embedded.html#_handling_failures[handling failures]. include::camel-spring-boot::page$debezium-mysql-starter.adoc[] ",12061,True,2998.392107945683,median "// Copyright (c) 2018, ETH Zurich and UNC Chapel Hill. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of ETH Zurich and UNC Chapel Hill nor the names of // its contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS 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. // // Author: Johannes L. Schoenberger (jsch-at-demuc-dot-de) #ifndef NOMINMAX #define NOMINMAX #endif #include #include #include ""base/similarity_transform.h"" #include ""controllers/automatic_reconstruction.h"" #include ""controllers/bundle_adjustment.h"" #include ""controllers/hierarchical_mapper.h"" #include ""estimators/coordinate_frame.h"" #include ""feature/extraction.h"" #include ""feature/matching.h"" #include ""feature/utils.h"" #include ""mvs/meshing.h"" #include ""mvs/patch_match.h"" #include ""retrieval/visual_index.h"" #include ""ui/main_window.h"" #include ""util/opengl_utils.h"" #include ""util/version.h"" using namespace colmap; #ifdef CUDA_ENABLED const bool kUseOpenGL = false; #else const bool kUseOpenGL = true; #endif int RunGraphicalUserInterface(int argc, char** argv) { OptionManager options; std::string import_path; if (argc > 1) { options.AddDefaultOption(""import_path"", &import_path); options.AddAllOptions(); options.Parse(argc, argv); } #if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)) QApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); #endif Q_INIT_RESOURCE(resources); QApplication app(argc, argv); MainWindow main_window(options); main_window.show(); if (!import_path.empty()) { main_window.ImportReconstruction(import_path); } return app.exec(); } int RunAutomaticReconstructor(int argc, char** argv) { AutomaticReconstructionController::Options reconstruction_options; std::string data_type = ""individual""; std::string quality = ""high""; std::string mesher = ""poisson""; OptionManager options; options.AddRequiredOption(""workspace_path"", &reconstruction_options.workspace_path); options.AddRequiredOption(""image_path"", &reconstruction_options.image_path); options.AddDefaultOption(""mask_path"", &reconstruction_options.mask_path); options.AddDefaultOption(""vocab_tree_path"", &reconstruction_options.vocab_tree_path); options.AddDefaultOption(""data_type"", &data_type, ""{individual, video, internet}""); options.AddDefaultOption(""quality"", &quality, ""{low, medium, high, extreme}""); options.AddDefaultOption(""camera_model"", &reconstruction_options.camera_model); options.AddDefaultOption(""single_camera"", &reconstruction_options.single_camera); options.AddDefaultOption(""sparse"", &reconstruction_options.sparse); options.AddDefaultOption(""dense"", &reconstruction_options.dense); options.AddDefaultOption(""mesher"", &mesher, ""{poisson, delaunay}""); options.AddDefaultOption(""num_threads"", &reconstruction_options.num_threads); options.AddDefaultOption(""use_gpu"", &reconstruction_options.use_gpu); options.AddDefaultOption(""gpu_index"", &reconstruction_options.gpu_index); options.Parse(argc, argv); StringToLower(&data_type); if (data_type == ""individual"") { reconstruction_options.data_type = AutomaticReconstructionController::DataType::INDIVIDUAL; } else if (data_type == ""video"") { reconstruction_options.data_type = AutomaticReconstructionController::DataType::VIDEO; } else if (data_type == ""internet"") { reconstruction_options.data_type = AutomaticReconstructionController::DataType::INTERNET; } else { LOG(FATAL) << ""Invalid data type provided""; } StringToLower(&quality); if (quality == ""low"") { reconstruction_options.quality = AutomaticReconstructionController::Quality::LOW; } else if (quality == ""medium"") { reconstruction_options.quality = AutomaticReconstructionController::Quality::MEDIUM; } else if (quality == ""high"") { reconstruction_options.quality = AutomaticReconstructionController::Quality::HIGH; } else if (quality == ""extreme"") { reconstruction_options.quality = AutomaticReconstructionController::Quality::EXTREME; } else { LOG(FATAL) << ""Invalid quality provided""; } StringToLower(&mesher); if (mesher == ""poisson"") { reconstruction_options.mesher = AutomaticReconstructionController::Mesher::POISSON; } else if (mesher == ""delaunay"") { reconstruction_options.mesher = AutomaticReconstructionController::Mesher::DELAUNAY; } else { LOG(FATAL) << ""Invalid mesher provided""; } ReconstructionManager reconstruction_manager; if (reconstruction_options.use_gpu && kUseOpenGL) { QApplication app(argc, argv); AutomaticReconstructionController controller(reconstruction_options, &reconstruction_manager); RunThreadWithOpenGLContext(&controller); } else { AutomaticReconstructionController controller(reconstruction_options, &reconstruction_manager); controller.Start(); controller.Wait(); } return EXIT_SUCCESS; } int RunBundleAdjuster(int argc, char** argv) { std::string input_path; std::string output_path; OptionManager options; options.AddRequiredOption(""input_path"", &input_path); options.AddRequiredOption(""output_path"", &output_path); options.AddBundleAdjustmentOptions(); options.Parse(argc, argv); Reconstruction reconstruction; reconstruction.Read(input_path); BundleAdjustmentController ba_controller(options, &reconstruction); ba_controller.Start(); ba_controller.Wait(); reconstruction.Write(output_path); return EXIT_SUCCESS; } int RunColorExtractor(int argc, char** argv) { std::string input_path; std::string output_path; OptionManager options; options.AddImageOptions(); options.AddDefaultOption(""input_path"", &input_path); options.AddRequiredOption(""output_path"", &output_path); options.Parse(argc, argv); Reconstruction reconstruction; reconstruction.Read(input_path); reconstruction.ExtractColorsForAllImages(*options.image_path); reconstruction.Write(output_path); return EXIT_SUCCESS; } int RunDatabaseCreator(int argc, char** argv) { OptionManager options; options.AddDatabaseOptions(); options.Parse(argc, argv); Database database(*options.database_path); return EXIT_SUCCESS; } int RunDatabaseMerger(int argc, char** argv) { std::string database_path1; std::string database_path2; std::string merged_database_path; OptionManager options; options.AddRequiredOption(""database_path1"", &database_path1); options.AddRequiredOption(""database_path2"", &database_path2); options.AddRequiredOption(""merged_database_path"", &merged_database_path); options.Parse(argc, argv); if (ExistsFile(merged_database_path)) { std::cout << ""ERROR: Merged database file must not exist."" << std::endl; return EXIT_FAILURE; } Database database1(database_path1); Database database2(database_path2); Database merged_database(merged_database_path); Database::Merge(database1, database2, &merged_database); return EXIT_SUCCESS; } int RunStereoFuser(int argc, char** argv) { std::string workspace_path; std::string input_type = ""geometric""; std::string workspace_format = ""COLMAP""; std::string pmvs_option_name = ""option-all""; std::string output_path; OptionManager options; options.AddRequiredOption(""workspace_path"", &workspace_path); options.AddDefaultOption(""workspace_format"", &workspace_format, ""{COLMAP, PMVS}""); options.AddDefaultOption(""pmvs_option_name"", &pmvs_option_name); options.AddDefaultOption(""input_type"", &input_type, ""{photometric, geometric}""); options.AddRequiredOption(""output_path"", &output_path); options.AddStereoFusionOptions(); options.Parse(argc, argv); StringToLower(&workspace_format); if (workspace_format != ""colmap"" && workspace_format != ""pmvs"") { std::cout << ""ERROR: Invalid `workspace_format` - supported values are "" ""'COLMAP' or 'PMVS'."" << std::endl; return EXIT_FAILURE; } StringToLower(&input_type); if (input_type != ""photometric"" && input_type != ""geometric"") { std::cout << ""ERROR: Invalid input type - supported values are "" ""'photometric' and 'geometric'."" << std::endl; return EXIT_FAILURE; } mvs::StereoFusion fuser(*options.stereo_fusion, workspace_path, workspace_format, pmvs_option_name, input_type); fuser.Start(); fuser.Wait(); std::cout << ""Writing output: "" << output_path << std::endl; WriteBinaryPlyPoints(output_path, fuser.GetFusedPoints()); mvs::WritePointsVisibility(output_path + "".vis"", fuser.GetFusedPointsVisibility()); return EXIT_SUCCESS; } int RunPoissonMesher(int argc, char** argv) { std::string input_path; std::string output_path; OptionManager options; options.AddRequiredOption(""input_path"", &input_path); options.AddRequiredOption(""output_path"", &output_path); options.AddPoissonMeshingOptions(); options.Parse(argc, argv); CHECK(mvs::PoissonMeshing(*options.poisson_meshing, input_path, output_path)); return EXIT_SUCCESS; } int RunProjectGenerator(int argc, char** argv) { std::string output_path; std::string quality = ""high""; OptionManager options; options.AddRequiredOption(""output_path"", &output_path); options.AddDefaultOption(""quality"", &quality, ""{low, medium, high, extreme}""); options.Parse(argc, argv); OptionManager output_options; output_options.AddAllOptions(); StringToLower(&quality); if (quality == ""low"") { output_options.ModifyForLowQuality(); } else if (quality == ""medium"") { output_options.ModifyForMediumQuality(); } else if (quality == ""high"") { output_options.ModifyForHighQuality(); } else if (quality == ""extreme"") { output_options.ModifyForExtremeQuality(); } else { LOG(FATAL) << ""Invalid quality provided""; } output_options.Write(output_path); return EXIT_SUCCESS; } int RunDelaunayMesher(int argc, char** argv) { #ifndef CGAL_ENABLED std::cerr << ""ERROR: Delaunay meshing requires CGAL, which is not "" ""available on your system."" << std::endl; return EXIT_FAILURE; #else // CGAL_ENABLED std::string input_path; std::string input_type = ""dense""; std::string output_path; OptionManager options; options.AddRequiredOption( ""input_path"", &input_path, ""Path to either the dense workspace folder or the sparse reconstruction""); options.AddDefaultOption(""input_type"", &input_type, ""{dense, sparse}""); options.AddRequiredOption(""output_path"", &output_path); options.AddDelaunayMeshingOptions(); options.Parse(argc, argv); StringToLower(&input_type); if (input_type == ""sparse"") { mvs::SparseDelaunayMeshing(*options.delaunay_meshing, input_path, output_path); } else if (input_type == ""dense"") { mvs::DenseDelaunayMeshing(*options.delaunay_meshing, input_path, output_path); } else { std::cout << ""ERROR: Invalid input type - "" ""supported values are 'sparse' and 'dense'."" << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; #endif // CGAL_ENABLED } int RunPatchMatchStereo(int argc, char** argv) { #ifndef CUDA_ENABLED std::cerr << ""ERROR: Dense stereo reconstruction requires CUDA, which is not "" ""available on your system."" << std::endl; return EXIT_FAILURE; #else // CUDA_ENABLED std::string workspace_path; std::string workspace_format = ""COLMAP""; std::string pmvs_option_name = ""option-all""; OptionManager options; options.AddRequiredOption( ""workspace_path"", &workspace_path, ""Path to the folder containing the undistorted images""); options.AddDefaultOption(""workspace_format"", &workspace_format, ""{COLMAP, PMVS}""); options.AddDefaultOption(""pmvs_option_name"", &pmvs_option_name); options.AddPatchMatchStereoOptions(); options.Parse(argc, argv); StringToLower(&workspace_format); if (workspace_format != ""colmap"" && workspace_format != ""pmvs"") { std::cout << ""ERROR: Invalid `workspace_format` - supported values are "" ""'COLMAP' or 'PMVS'."" << std::endl; return EXIT_FAILURE; } mvs::PatchMatchController controller(*options.patch_match_stereo, workspace_path, workspace_format, pmvs_option_name); controller.Start(); controller.Wait(); return EXIT_SUCCESS; #endif // CUDA_ENABLED } int RunExhaustiveMatcher(int argc, char** argv) { OptionManager options; options.AddDatabaseOptions(); options.AddExhaustiveMatchingOptions(); options.Parse(argc, argv); std::unique_ptr app; if (options.sift_matching->use_gpu && kUseOpenGL) { app.reset(new QApplication(argc, argv)); } ExhaustiveFeatureMatcher feature_matcher(*options.exhaustive_matching, *options.sift_matching, *options.database_path); if (options.sift_matching->use_gpu && kUseOpenGL) { RunThreadWithOpenGLContext(&feature_matcher); } else { feature_matcher.Start(); feature_matcher.Wait(); } return EXIT_SUCCESS; } bool VerifyCameraParams(const std::string& camera_model, const std::string& params) { if (!ExistsCameraModelWithName(camera_model)) { std::cerr << ""ERROR: Camera model does not exist"" << std::endl; return false; } const std::vector camera_params = CSVToVector(params); const int camera_model_id = CameraModelNameToId(camera_model); if (camera_params.size() > 0 && !CameraModelVerifyParams(camera_model_id, camera_params)) { std::cerr << ""ERROR: Invalid camera parameters"" << std::endl; return false; } return true; } int RunFeatureExtractor(int argc, char** argv) { std::string image_list_path; OptionManager options; options.AddDatabaseOptions(); options.AddImageOptions(); options.AddDefaultOption(""image_list_path"", &image_list_path); options.AddExtractionOptions(); options.Parse(argc, argv); ImageReaderOptions reader_options = *options.image_reader; reader_options.database_path = *options.database_path; reader_options.image_path = *options.image_path; if (!image_list_path.empty()) { reader_options.image_list = ReadTextFileLines(image_list_path); if (reader_options.image_list.empty()) { return EXIT_SUCCESS; } } if (!ExistsCameraModelWithName(options.image_reader->camera_model)) { std::cerr << ""ERROR: Camera model does not exist"" << std::endl; } if (!VerifyCameraParams(options.image_reader->camera_model, options.image_reader->camera_params)) { return EXIT_FAILURE; } std::unique_ptr app; if (options.sift_extraction->use_gpu && kUseOpenGL) { app.reset(new QApplication(argc, argv)); } SiftFeatureExtractor feature_extractor(reader_options, *options.sift_extraction); if (options.sift_extraction->use_gpu && kUseOpenGL) { RunThreadWithOpenGLContext(&feature_extractor); } else { feature_extractor.Start(); feature_extractor.Wait(); } return EXIT_SUCCESS; } int RunFeatureImporter(int argc, char** argv) { std::string import_path; std::string image_list_path; OptionManager options; options.AddDatabaseOptions(); options.AddImageOptions(); options.AddRequiredOption(""import_path"", &import_path); options.AddDefaultOption(""image_list_path"", &image_list_path); options.AddExtractionOptions(); options.Parse(argc, argv); ImageReaderOptions reader_options = *options.image_reader; reader_options.database_path = *options.database_path; reader_options.image_path = *options.image_path; if (!image_list_path.empty()) { reader_options.image_list = ReadTextFileLines(image_list_path); if (reader_options.image_list.empty()) { return EXIT_SUCCESS; } } if (!VerifyCameraParams(options.image_reader->camera_model, options.image_reader->camera_params)) { return EXIT_FAILURE; } FeatureImporter feature_importer(reader_options, import_path); feature_importer.Start(); feature_importer.Wait(); return EXIT_SUCCESS; } // Read stereo image pair names from a text file. The text file is expected to // have one image pair per line, e.g.: // // image_name1.jpg image_name2.jpg // image_name3.jpg image_name4.jpg // image_name5.jpg image_name6.jpg // ... // std::vector> ReadStereoImagePairs( const std::string& path, const Reconstruction& reconstruction) { const std::vector stereo_pair_lines = ReadTextFileLines(path); std::vector> stereo_pairs; stereo_pairs.reserve(stereo_pair_lines.size()); for (const auto& line : stereo_pair_lines) { const std::vector names = StringSplit(line, "" ""); CHECK_EQ(names.size(), 2); const Image* image1 = reconstruction.FindImageWithName(names[0]); const Image* image2 = reconstruction.FindImageWithName(names[1]); CHECK_NOTNULL(image1); CHECK_NOTNULL(image2); stereo_pairs.emplace_back(image1->ImageId(), image2->ImageId()); } return stereo_pairs; } int RunImageDeleter(int argc, char** argv) { std::string input_path; std::string output_path; std::string image_ids_path; std::string image_names_path; OptionManager options; options.AddRequiredOption(""input_path"", &input_path); options.AddRequiredOption(""output_path"", &output_path); options.AddDefaultOption( ""image_ids_path"", &image_ids_path, ""Path to text file containing one image_id to delete per line""); options.AddDefaultOption( ""image_names_path"", &image_names_path, ""Path to text file containing one image name to delete per line""); options.Parse(argc, argv); Reconstruction reconstruction; reconstruction.Read(input_path); if (!image_ids_path.empty()) { const auto image_ids = ReadTextFileLines(image_ids_path); for (const auto image_id_str : image_ids) { if (image_id_str.empty()) { continue; } const image_t image_id = std::stoi(image_id_str); if (reconstruction.ExistsImage(image_id)) { const auto& image = reconstruction.Image(image_id); std::cout << StringPrintf( ""Deleting image_id=%d, image_name=%s from reconstruction"", image.ImageId(), image.Name().c_str()) << std::endl; reconstruction.DeRegisterImage(image_id); } else { std::cout << StringPrintf( ""WARNING: Skipping image_id=%s, because it does not "" ""exist in the reconstruction"", image_id_str.c_str()) << std::endl; } } } if (!image_names_path.empty()) { const auto image_names = ReadTextFileLines(image_names_path); for (const auto image_name : image_names) { if (image_name.empty()) { continue; } const Image* image = reconstruction.FindImageWithName(image_name); if (image != nullptr) { std::cout << StringPrintf( ""Deleting image_id=%d, image_name=%s from reconstruction"", image->ImageId(), image->Name().c_str()) << std::endl; reconstruction.DeRegisterImage(image->ImageId()); } else { std::cout << StringPrintf( ""WARNING: Skipping image_name=%s, because it does not "" ""exist in the reconstruction"", image_name.c_str()) << std::endl; } } } reconstruction.Write(output_path); return EXIT_SUCCESS; } int RunImageFilterer(int argc, char** argv) { std::string input_path; std::string output_path; double min_focal_length_ratio = 0.1; double max_focal_length_ratio = 10.0; double max_extra_param = 100.0; size_t min_num_observations = 10; OptionManager options; options.AddRequiredOption(""input_path"", &input_path); options.AddRequiredOption(""output_path"", &output_path); options.AddDefaultOption(""min_focal_length_ratio"", &min_focal_length_ratio); options.AddDefaultOption(""max_focal_length_ratio"", &max_focal_length_ratio); options.AddDefaultOption(""max_extra_param"", &max_extra_param); options.AddDefaultOption(""min_num_observations"", &min_num_observations); options.Parse(argc, argv); Reconstruction reconstruction; reconstruction.Read(input_path); const size_t num_reg_images = reconstruction.NumRegImages(); reconstruction.FilterImages(min_focal_length_ratio, max_focal_length_ratio, max_extra_param); std::vector filtered_image_ids; for (const auto& image : reconstruction.Images()) { if (image.second.IsRegistered() && image.second.NumPoints3D() < min_num_observations) { filtered_image_ids.push_back(image.first); } } for (const auto image_id : filtered_image_ids) { reconstruction.DeRegisterImage(image_id); } const size_t num_filtered_images = num_reg_images - reconstruction.NumRegImages(); std::cout << StringPrintf(""Filtered %d images from a total of %d images"", num_filtered_images, num_reg_images) << std::endl; reconstruction.Write(output_path); return EXIT_SUCCESS; } int RunImageRectifier(int argc, char** argv) { std::string input_path; std::string output_path; std::string stereo_pairs_list; UndistortCameraOptions undistort_camera_options; OptionManager options; options.AddImageOptions(); options.AddRequiredOption(""input_path"", &input_path); options.AddRequiredOption(""output_path"", &output_path); options.AddRequiredOption(""stereo_pairs_list"", &stereo_pairs_list); options.AddDefaultOption(""blank_pixels"", &undistort_camera_options.blank_pixels); options.AddDefaultOption(""min_scale"", &undistort_camera_options.min_scale); options.AddDefaultOption(""max_scale"", &undistort_camera_options.max_scale); options.AddDefaultOption(""max_image_size"", &undistort_camera_options.max_image_size); options.Parse(argc, argv); Reconstruction reconstruction; reconstruction.Read(input_path); const auto stereo_pairs = ReadStereoImagePairs(stereo_pairs_list, reconstruction); StereoImageRectifier rectifier(undistort_camera_options, reconstruction, *options.image_path, output_path, stereo_pairs); rectifier.Start(); rectifier.Wait(); return EXIT_SUCCESS; } int RunImageRegistrator(int argc, char** argv) { std::string input_path; std::string output_path; OptionManager options; options.AddDatabaseOptions(); options.AddRequiredOption(""input_path"", &input_path); options.AddRequiredOption(""output_path"", &output_path); options.AddMapperOptions(); options.Parse(argc, argv); if (!ExistsDir(input_path)) { std::cerr << ""ERROR: `input_path` is not a directory"" << std::endl; return EXIT_FAILURE; } if (!ExistsDir(output_path)) { std::cerr << ""ERROR: `output_path` is not a directory"" << std::endl; return EXIT_FAILURE; } PrintHeading1(""Loading database""); DatabaseCache database_cache; { Database database(*options.database_path); Timer timer; timer.Start(); const size_t min_num_matches = static_cast(options.mapper->min_num_matches); database_cache.Load(database, min_num_matches, options.mapper->ignore_watermarks, options.mapper->image_names); std::cout << std::endl; timer.PrintMinutes(); } std::cout << std::endl; Reconstruction reconstruction; reconstruction.Read(input_path); IncrementalMapper mapper(&database_cache); mapper.BeginReconstruction(&reconstruction); const auto mapper_options = options.mapper->Mapper(); for (const auto& image : reconstruction.Images()) { if (image.second.IsRegistered()) { continue; } PrintHeading1(""Registering image #"" + std::to_string(image.first) + "" ("" + std::to_string(reconstruction.NumRegImages() + 1) + "")""); std::cout << "" => Image sees "" << image.second.NumVisiblePoints3D() << "" / "" << image.second.NumObservations() << "" points"" << std::endl; mapper.RegisterNextImage(mapper_options, image.first); } const bool kDiscardReconstruction = false; mapper.EndReconstruction(kDiscardReconstruction); reconstruction.Write(output_path); return EXIT_SUCCESS; } int RunImageUndistorter(int argc, char** argv) { std::string input_path; std::string output_path; std::string output_type = ""COLMAP""; UndistortCameraOptions undistort_camera_options; OptionManager options; options.AddImageOptions(); options.AddRequiredOption(""input_path"", &input_path); options.AddRequiredOption(""output_path"", &output_path); options.AddDefaultOption(""output_type"", &output_type, ""{COLMAP, PMVS, CMP-MVS}""); options.AddDefaultOption(""blank_pixels"", &undistort_camera_options.blank_pixels); options.AddDefaultOption(""min_scale"", &undistort_camera_options.min_scale); options.AddDefaultOption(""max_scale"", &undistort_camera_options.max_scale); options.AddDefaultOption(""max_image_size"", &undistort_camera_options.max_image_size); options.AddDefaultOption(""roi_min_x"", &undistort_camera_options.roi_min_x); options.AddDefaultOption(""roi_min_y"", &undistort_camera_options.roi_min_y); options.AddDefaultOption(""roi_max_x"", &undistort_camera_options.roi_max_x); options.AddDefaultOption(""roi_max_y"", &undistort_camera_options.roi_max_y); options.Parse(argc, argv); CreateDirIfNotExists(output_path); Reconstruction reconstruction; reconstruction.Read(input_path); std::unique_ptr undistorter; if (output_type == ""COLMAP"") { undistorter.reset(new COLMAPUndistorter(undistort_camera_options, reconstruction, *options.image_path, output_path)); } else if (output_type == ""PMVS"") { undistorter.reset(new PMVSUndistorter(undistort_camera_options, reconstruction, *options.image_path, output_path)); } else if (output_type == ""CMP-MVS"") { undistorter.reset(new CMPMVSUndistorter(undistort_camera_options, reconstruction, *options.image_path, output_path)); } else { std::cerr << ""ERROR: Invalid `output_type` - supported values are "" ""{'COLMAP', 'PMVS', 'CMP-MVS'}."" << std::endl; return EXIT_FAILURE; } undistorter->Start(); undistorter->Wait(); return EXIT_SUCCESS; } int RunMapper(int argc, char** argv) { std::string input_path; std::string output_path; std::string image_list_path; OptionManager options; options.AddDatabaseOptions(); options.AddImageOptions(); options.AddDefaultOption(""input_path"", &input_path); options.AddRequiredOption(""output_path"", &output_path); options.AddDefaultOption(""image_list_path"", &image_list_path); options.AddMapperOptions(); options.Parse(argc, argv); if (!ExistsDir(output_path)) { std::cerr << ""ERROR: `output_path` is not a directory."" << std::endl; return EXIT_FAILURE; } if (!image_list_path.empty()) { const auto image_names = ReadTextFileLines(image_list_path); options.mapper->image_names = std::unordered_set(image_names.begin(), image_names.end()); } ReconstructionManager reconstruction_manager; if (input_path != """") { if (!ExistsDir(input_path)) { std::cerr << ""ERROR: `input_path` is not a directory."" << std::endl; return EXIT_FAILURE; } reconstruction_manager.Read(input_path); } IncrementalMapperController mapper(options.mapper.get(), *options.image_path, *options.database_path, &reconstruction_manager); // In case a new reconstruction is started, write results of individual sub- // models to as their reconstruction finishes instead of writing all results // after all reconstructions finished. size_t prev_num_reconstructions = 0; if (input_path == """") { mapper.AddCallback( IncrementalMapperController::LAST_IMAGE_REG_CALLBACK, [&]() { // If the number of reconstructions has not changed, the last model // was discarded for some reason. if (reconstruction_manager.Size() > prev_num_reconstructions) { const std::string reconstruction_path = JoinPaths( output_path, std::to_string(prev_num_reconstructions)); const auto& reconstruction = reconstruction_manager.Get(prev_num_reconstructions); CreateDirIfNotExists(reconstruction_path); reconstruction.Write(reconstruction_path); options.Write(JoinPaths(reconstruction_path, ""project.ini"")); prev_num_reconstructions = reconstruction_manager.Size(); } }); } mapper.Start(); mapper.Wait(); // In case the reconstruction is continued from an existing reconstruction, do // not create sub-folders but directly write the results. if (input_path != """" && reconstruction_manager.Size() > 0) { reconstruction_manager.Get(0).Write(output_path); } return EXIT_SUCCESS; } int RunHierarchicalMapper(int argc, char** argv) { HierarchicalMapperController::Options hierarchical_options; SceneClustering::Options clustering_options; std::string output_path; OptionManager options; options.AddRequiredOption(""database_path"", &hierarchical_options.database_path); options.AddRequiredOption(""image_path"", &hierarchical_options.image_path); options.AddRequiredOption(""output_path"", &output_path); options.AddDefaultOption(""num_workers"", &hierarchical_options.num_workers); options.AddDefaultOption(""image_overlap"", &clustering_options.image_overlap); options.AddDefaultOption(""leaf_max_num_images"", &clustering_options.leaf_max_num_images); options.AddMapperOptions(); options.Parse(argc, argv); if (!ExistsDir(output_path)) { std::cerr << ""ERROR: `output_path` is not a directory."" << std::endl; return EXIT_FAILURE; } ReconstructionManager reconstruction_manager; HierarchicalMapperController hierarchical_mapper( hierarchical_options, clustering_options, *options.mapper, &reconstruction_manager); hierarchical_mapper.Start(); hierarchical_mapper.Wait(); reconstruction_manager.Write(output_path, &options); return EXIT_SUCCESS; } int RunMatchesImporter(int argc, char** argv) { std::string match_list_path; std::string match_type = ""pairs""; OptionManager options; options.AddDatabaseOptions(); options.AddRequiredOption(""match_list_path"", &match_list_path); options.AddDefaultOption(""match_type"", &match_type, ""{'pairs', 'raw', 'inliers'}""); options.AddMatchingOptions(); options.Parse(argc, argv); std::unique_ptr app; if (options.sift_matching->use_gpu && kUseOpenGL) { app.reset(new QApplication(argc, argv)); } std::unique_ptr feature_matcher; if (match_type == ""pairs"") { ImagePairsMatchingOptions matcher_options; matcher_options.match_list_path = match_list_path; feature_matcher.reset(new ImagePairsFeatureMatcher( matcher_options, *options.sift_matching, *options.database_path)); } else if (match_type == ""raw"" || match_type == ""inliers"") { FeaturePairsMatchingOptions matcher_options; matcher_options.match_list_path = match_list_path; matcher_options.verify_matches = match_type == ""raw""; feature_matcher.reset(new FeaturePairsFeatureMatcher( matcher_options, *options.sift_matching, *options.database_path)); } else { std::cerr << ""ERROR: Invalid `match_type`""; return EXIT_FAILURE; } if (options.sift_matching->use_gpu && kUseOpenGL) { RunThreadWithOpenGLContext(feature_matcher.get()); } else { feature_matcher->Start(); feature_matcher->Wait(); } return EXIT_SUCCESS; } int RunModelAligner(int argc, char** argv) { std::string input_path; std::string ref_images_path; std::string output_path; int min_common_images = 3; bool robust_alignment = true; RANSACOptions ransac_options; OptionManager options; options.AddRequiredOption(""input_path"", &input_path); options.AddRequiredOption(""ref_images_path"", &ref_images_path); options.AddRequiredOption(""output_path"", &output_path); options.AddDefaultOption(""min_common_images"", &min_common_images); options.AddDefaultOption(""robust_alignment"", &robust_alignment); options.AddDefaultOption(""robust_alignment_max_error"", &ransac_options.max_error); options.Parse(argc, argv); if (robust_alignment && ransac_options.max_error <= 0) { std::cout << ""ERROR: You must provide a maximum alignment error > 0"" << std::endl; return EXIT_FAILURE; } std::vector ref_image_names; std::vector ref_locations; std::vector lines = ReadTextFileLines(ref_images_path); for (const auto line : lines) { std::stringstream line_parser(line); std::string image_name = """"; Eigen::Vector3d camera_position; line_parser >> image_name >> camera_position[0] >> camera_position[1] >> camera_position[2]; ref_image_names.push_back(image_name); ref_locations.push_back(camera_position); } Reconstruction reconstruction; reconstruction.Read(input_path); PrintHeading2(""Aligning reconstruction""); std::cout << StringPrintf("" => Using %d reference images"", ref_image_names.size()) << std::endl; bool alignment_success; if (robust_alignment) { alignment_success = reconstruction.AlignRobust( ref_image_names, ref_locations, min_common_images, ransac_options); } else { alignment_success = reconstruction.Align(ref_image_names, ref_locations, min_common_images); } if (alignment_success) { std::cout << "" => Alignment succeeded"" << std::endl; reconstruction.Write(output_path); std::vector errors; errors.reserve(ref_image_names.size()); for (size_t i = 0; i < ref_image_names.size(); ++i) { const Image* image = reconstruction.FindImageWithName(ref_image_names[i]); if (image != nullptr) { errors.push_back((image->ProjectionCenter() - ref_locations[i]).norm()); } } std::cout << StringPrintf("" => Alignment error: %f (mean), %f (median)"", Mean(errors), Median(errors)) << std::endl; } else { std::cout << "" => Alignment failed"" << std::endl; } return EXIT_SUCCESS; } int RunModelAnalyzer(int argc, char** argv) { std::string path; OptionManager options; options.AddRequiredOption(""path"", &path); options.Parse(argc, argv); Reconstruction reconstruction; reconstruction.Read(path); std::cout << StringPrintf(""Cameras: %d"", reconstruction.NumCameras()) << std::endl; std::cout << StringPrintf(""Images: %d"", reconstruction.NumImages()) << std::endl; std::cout << StringPrintf(""Registered images: %d"", reconstruction.NumRegImages()) << std::endl; std::cout << StringPrintf(""Points: %d"", reconstruction.NumPoints3D()) << std::endl; std::cout << StringPrintf(""Observations: %d"", reconstruction.ComputeNumObservations()) << std::endl; std::cout << StringPrintf(""Mean track length: %f"", reconstruction.ComputeMeanTrackLength()) << std::endl; std::cout << StringPrintf(""Mean observations per image: %f"", reconstruction.ComputeMeanObservationsPerRegImage()) << std::endl; std::cout << StringPrintf(""Mean reprojection error: %fpx"", reconstruction.ComputeMeanReprojectionError()) << std::endl; return EXIT_SUCCESS; } int RunModelConverter(int argc, char** argv) { std::string input_path; std::string output_path; std::string output_type; OptionManager options; options.AddRequiredOption(""input_path"", &input_path); options.AddRequiredOption(""output_path"", &output_path); options.AddRequiredOption(""output_type"", &output_type, ""{BIN, TXT, NVM, Bundler, VRML, PLY}""); options.Parse(argc, argv); Reconstruction reconstruction; reconstruction.Read(input_path); StringToLower(&output_type); if (output_type == ""bin"") { reconstruction.WriteBinary(output_path); } else if (output_type == ""txt"") { reconstruction.WriteText(output_path); } else if (output_type == ""nvm"") { reconstruction.ExportNVM(output_path); } else if (output_type == ""bundler"") { reconstruction.ExportBundler(output_path + "".bundle.out"", output_path + "".list.txt""); } else if (output_type == ""ply"") { reconstruction.ExportPLY(output_path); } else if (output_type == ""vrml"") { const auto base_path = output_path.substr(0, output_path.find_last_of(""."")); reconstruction.ExportVRML(base_path + "".images.wrl"", base_path + "".points3D.wrl"", 1, Eigen::Vector3d(1, 0, 0)); } else { std::cerr << ""ERROR: Invalid `output_type`"" << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } int RunModelMerger(int argc, char** argv) { std::string input_path1; std::string input_path2; std::string output_path; double max_reproj_error = 64.0; OptionManager options; options.AddRequiredOption(""input_path1"", &input_path1); options.AddRequiredOption(""input_path2"", &input_path2); options.AddRequiredOption(""output_path"", &output_path); options.AddDefaultOption(""max_reproj_error"", &max_reproj_error); options.Parse(argc, argv); Reconstruction reconstruction1; reconstruction1.Read(input_path1); PrintHeading2(""Reconstruction 1""); std::cout << StringPrintf(""Images: %d"", reconstruction1.NumRegImages()) << std::endl; std::cout << StringPrintf(""Points: %d"", reconstruction1.NumPoints3D()) << std::endl; Reconstruction reconstruction2; reconstruction2.Read(input_path2); PrintHeading2(""Reconstruction 2""); std::cout << StringPrintf(""Images: %d"", reconstruction2.NumRegImages()) << std::endl; std::cout << StringPrintf(""Points: %d"", reconstruction2.NumPoints3D()) << std::endl; PrintHeading2(""Merging reconstructions""); if (reconstruction1.Merge(reconstruction2, max_reproj_error)) { std::cout << ""=> Merge succeeded"" << std::endl; PrintHeading2(""Merged reconstruction""); std::cout << StringPrintf(""Images: %d"", reconstruction1.NumRegImages()) << std::endl; std::cout << StringPrintf(""Points: %d"", reconstruction1.NumPoints3D()) << std::endl; } else { std::cout << ""=> Merge failed"" << std::endl; } reconstruction1.Write(output_path); return EXIT_SUCCESS; } int RunModelOrientationAligner(int argc, char** argv) { std::string input_path; std::string output_path; std::string method = ""MANHATTAN-WORLD""; ManhattanWorldFrameEstimationOptions frame_estimation_options; OptionManager options; options.AddImageOptions(); options.AddRequiredOption(""input_path"", &input_path); options.AddRequiredOption(""output_path"", &output_path); options.AddDefaultOption(""method"", &method, ""{MANHATTAN-WORLD, IMAGE-ORIENTATION}""); options.AddDefaultOption(""max_image_size"", &frame_estimation_options.max_image_size); options.Parse(argc, argv); StringToLower(&method); if (method != ""manhattan-world"" && method != ""image-orientation"") { std::cout << ""ERROR: Invalid `method` - supported values are "" ""'MANHATTAN-WORLD' or 'IMAGE-ORIENTATION'."" << std::endl; return EXIT_FAILURE; } Reconstruction reconstruction; reconstruction.Read(input_path); PrintHeading1(""Aligning Reconstruction""); Eigen::Matrix3d tform; if (method == ""manhattan-world"") { const Eigen::Matrix3d frame = EstimateManhattanWorldFrame( frame_estimation_options, reconstruction, *options.image_path); if (frame.col(0).nonZeros() == 0) { std::cout << ""Only aligning vertical axis"" << std::endl; tform = RotationFromUnitVectors(frame.col(1), Eigen::Vector3d(0, 1, 0)); } else if (frame.col(1).nonZeros() == 0) { tform = RotationFromUnitVectors(frame.col(0), Eigen::Vector3d(1, 0, 0)); std::cout << ""Only aligning horizontal axis"" << std::endl; } else { tform = frame.transpose(); std::cout << ""Aligning horizontal and vertical axes"" << std::endl; } } else if (method == ""image-orientation"") { const Eigen::Vector3d gravity_axis = EstimateGravityVectorFromImageOrientation(reconstruction); tform = RotationFromUnitVectors(gravity_axis, Eigen::Vector3d(0, 1, 0)); } else { LOG(FATAL) << ""Alignment method not supported""; } std::cout << ""Using the rotation matrix:"" << std::endl; std::cout << tform << std::endl; reconstruction.Transform(SimilarityTransform3( 1, RotationMatrixToQuaternion(tform), Eigen::Vector3d(0, 0, 0))); std::cout << ""Writing aligned reconstruction..."" << std::endl; reconstruction.Write(output_path); return EXIT_SUCCESS; } int RunSequentialMatcher(int argc, char** argv) { OptionManager options; options.AddDatabaseOptions(); options.AddSequentialMatchingOptions(); options.Parse(argc, argv); std::unique_ptr app; if (options.sift_matching->use_gpu && kUseOpenGL) { app.reset(new QApplication(argc, argv)); } SequentialFeatureMatcher feature_matcher(*options.sequential_matching, *options.sift_matching, *options.database_path); if (options.sift_matching->use_gpu && kUseOpenGL) { RunThreadWithOpenGLContext(&feature_matcher); } else { feature_matcher.Start(); feature_matcher.Wait(); } return EXIT_SUCCESS; } int RunPointFiltering(int argc, char** argv) { std::string input_path; std::string output_path; size_t min_track_len = 2; double max_reproj_error = 4.0; double min_tri_angle = 1.5; OptionManager options; options.AddRequiredOption(""input_path"", &input_path); options.AddRequiredOption(""output_path"", &output_path); options.AddDefaultOption(""min_track_len"", &min_track_len); options.AddDefaultOption(""max_reproj_error"", &max_reproj_error); options.AddDefaultOption(""min_tri_angle"", &min_tri_angle); options.Parse(argc, argv); Reconstruction reconstruction; reconstruction.Read(input_path); size_t num_filtered = reconstruction.FilterAllPoints3D(max_reproj_error, min_tri_angle); for (const auto point3D_id : reconstruction.Point3DIds()) { const auto& point3D = reconstruction.Point3D(point3D_id); if (point3D.Track().Length() < min_track_len) { num_filtered += point3D.Track().Length(); reconstruction.DeletePoint3D(point3D_id); } } std::cout << ""Filtered observations: "" << num_filtered << std::endl; reconstruction.Write(output_path); return EXIT_SUCCESS; } int RunPointTriangulator(int argc, char** argv) { std::string input_path; std::string output_path; bool clear_points = false; OptionManager options; options.AddDatabaseOptions(); options.AddImageOptions(); options.AddRequiredOption(""input_path"", &input_path); options.AddRequiredOption(""output_path"", &output_path); options.AddDefaultOption( ""clear_points"", &clear_points, ""Whether to clear all existing points and observations""); options.AddMapperOptions(); options.Parse(argc, argv); if (!ExistsDir(input_path)) { std::cerr << ""ERROR: `input_path` is not a directory"" << std::endl; return EXIT_FAILURE; } if (!ExistsDir(output_path)) { std::cerr << ""ERROR: `output_path` is not a directory"" << std::endl; return EXIT_FAILURE; } const auto& mapper_options = *options.mapper; PrintHeading1(""Loading model""); Reconstruction reconstruction; reconstruction.Read(input_path); PrintHeading1(""Loading database""); DatabaseCache database_cache; { Timer timer; timer.Start(); Database database(*options.database_path); const size_t min_num_matches = static_cast(mapper_options.min_num_matches); database_cache.Load(database, min_num_matches, mapper_options.ignore_watermarks, mapper_options.image_names); if (clear_points) { reconstruction.DeleteAllPoints2DAndPoints3D(); reconstruction.TranscribeImageIdsToDatabase(database); } std::cout << std::endl; timer.PrintMinutes(); } std::cout << std::endl; CHECK_GE(reconstruction.NumRegImages(), 2) << ""Need at least two images for triangulation""; IncrementalMapper mapper(&database_cache); mapper.BeginReconstruction(&reconstruction); ////////////////////////////////////////////////////////////////////////////// // Triangulation ////////////////////////////////////////////////////////////////////////////// const auto tri_options = mapper_options.Triangulation(); const auto& reg_image_ids = reconstruction.RegImageIds(); for (size_t i = 0; i < reg_image_ids.size(); ++i) { const image_t image_id = reg_image_ids[i]; const auto& image = reconstruction.Image(image_id); PrintHeading1(StringPrintf(""Triangulating image #%d (%d)"", image_id, i)); const size_t num_existing_points3D = image.NumPoints3D(); std::cout << "" => Image sees "" << num_existing_points3D << "" / "" << image.NumObservations() << "" points"" << std::endl; mapper.TriangulateImage(tri_options, image_id); std::cout << "" => Triangulated "" << (image.NumPoints3D() - num_existing_points3D) << "" points"" << std::endl; } ////////////////////////////////////////////////////////////////////////////// // Retriangulation ////////////////////////////////////////////////////////////////////////////// PrintHeading1(""Retriangulation""); CompleteAndMergeTracks(mapper_options, &mapper); ////////////////////////////////////////////////////////////////////////////// // Bundle adjustment ////////////////////////////////////////////////////////////////////////////// auto ba_options = mapper_options.GlobalBundleAdjustment(); ba_options.refine_focal_length = false; ba_options.refine_principal_point = false; ba_options.refine_extra_params = false; ba_options.refine_extrinsics = false; // Configure bundle adjustment. BundleAdjustmentConfig ba_config; for (const image_t image_id : reconstruction.RegImageIds()) { ba_config.AddImage(image_id); } for (int i = 0; i < mapper_options.ba_global_max_refinements; ++i) { // Avoid degeneracies in bundle adjustment. reconstruction.FilterObservationsWithNegativeDepth(); const size_t num_observations = reconstruction.ComputeNumObservations(); PrintHeading1(""Bundle adjustment""); BundleAdjuster bundle_adjuster(ba_options, ba_config); CHECK(bundle_adjuster.Solve(&reconstruction)); size_t num_changed_observations = 0; num_changed_observations += CompleteAndMergeTracks(mapper_options, &mapper); num_changed_observations += FilterPoints(mapper_options, &mapper); const double changed = static_cast(num_changed_observations) / num_observations; std::cout << StringPrintf("" => Changed observations: %.6f"", changed) << std::endl; if (changed < mapper_options.ba_global_max_refinement_change) { break; } } PrintHeading1(""Extracting colors""); reconstruction.ExtractColorsForAllImages(*options.image_path); const bool kDiscardReconstruction = false; mapper.EndReconstruction(kDiscardReconstruction); reconstruction.Write(output_path); return EXIT_SUCCESS; } // Read the configuration of the camera rigs from a JSON file. The input images // of a camera rig must be named consistently to assign them to the appropriate // camera rig and the respective snapshots. // // An example configuration of a single camera rig: // [ // { // ""ref_camera_id"": 1, // ""cameras"": // [ // { // ""camera_id"": 1, // ""image_prefix"": ""left1_image"" // }, // { // ""camera_id"": 2, // ""image_prefix"": ""left2_image"" // }, // { // ""camera_id"": 3, // ""image_prefix"": ""right1_image"" // }, // { // ""camera_id"": 4, // ""image_prefix"": ""right2_image"" // } // ] // } // ] // // This file specifies the configuration for a single camera rig and that you // could potentially define multiple camera rigs. The rig is composed of 4 // cameras: all images of the first camera must have ""left1_image"" as a name // prefix, e.g., ""left1_image_frame000.png"" or ""left1_image/frame000.png"". // Images with the same suffix (""_frame000.png"" and ""/frame000.png"") are // assigned to the same snapshot, i.e., they are assumed to be captured at the // same time. Only snapshots with the reference image registered will be added // to the bundle adjustment problem. The remaining images will be added with // independent poses to the bundle adjustment problem. The above configuration // could have the following input image file structure: // // /path/to/images/... // left1_image/... // frame000.png // frame001.png // frame002.png // ... // left2_image/... // frame000.png // frame001.png // frame002.png // ... // right1_image/... // frame000.png // frame001.png // frame002.png // ... // right2_image/... // frame000.png // frame001.png // frame002.png // ... // // TODO: Provide an option to manually / explicitly set the relative extrinsics // of the camera rig. At the moment, the relative extrinsics are automatically // inferred from the reconstruction. std::vector ReadCameraRigConfig( const std::string& rig_config_path, const Reconstruction& reconstruction) { boost::property_tree::ptree pt; boost::property_tree::read_json(rig_config_path.c_str(), pt); std::vector camera_rigs; for (const auto& rig_config : pt) { CameraRig camera_rig; std::vector image_prefixes; for (const auto& camera : rig_config.second.get_child(""cameras"")) { const int camera_id = camera.second.get(""camera_id""); image_prefixes.push_back(camera.second.get(""image_prefix"")); camera_rig.AddCamera(camera_id, ComposeIdentityQuaternion(), Eigen::Vector3d(0, 0, 0)); } camera_rig.SetRefCameraId(rig_config.second.get(""ref_camera_id"")); std::unordered_map> snapshots; for (const auto image_id : reconstruction.RegImageIds()) { const auto& image = reconstruction.Image(image_id); for (const auto& image_prefix : image_prefixes) { if (StringContains(image.Name(), image_prefix)) { const std::string image_suffix = StringGetAfter(image.Name(), image_prefix); snapshots[image_suffix].push_back(image_id); } } } for (const auto& snapshot : snapshots) { bool has_ref_camera = false; for (const auto image_id : snapshot.second) { const auto& image = reconstruction.Image(image_id); if (image.CameraId() == camera_rig.RefCameraId()) { has_ref_camera = true; } } if (has_ref_camera) { camera_rig.AddSnapshot(snapshot.second); } } camera_rig.Check(reconstruction); camera_rig.ComputeRelativePoses(reconstruction); camera_rigs.push_back(camera_rig); } return camera_rigs; } int RunRigBundleAdjuster(int argc, char** argv) { std::string input_path; std::string output_path; std::string rig_config_path; OptionManager options; options.AddRequiredOption(""input_path"", &input_path); options.AddRequiredOption(""output_path"", &output_path); options.AddRequiredOption(""rig_config_path"", &rig_config_path); options.AddBundleAdjustmentOptions(); options.Parse(argc, argv); Reconstruction reconstruction; reconstruction.Read(input_path); PrintHeading1(""Camera rig configuration""); auto camera_rigs = ReadCameraRigConfig(rig_config_path, reconstruction); BundleAdjustmentConfig config; for (size_t i = 0; i < camera_rigs.size(); ++i) { const auto& camera_rig = camera_rigs[i]; PrintHeading2(StringPrintf(""Camera Rig %d"", i + 1)); std::cout << StringPrintf(""Cameras: %d"", camera_rig.NumCameras()) << std::endl; std::cout << StringPrintf(""Snapshots: %d"", camera_rig.NumSnapshots()) << std::endl; // Add all registered images to the bundle adjustment configuration. for (const auto image_id : reconstruction.RegImageIds()) { config.AddImage(image_id); } } PrintHeading1(""Rig bundle adjustment""); BundleAdjustmentOptions ba_options = *options.bundle_adjustment; ba_options.solver_options.minimizer_progress_to_stdout = true; RigBundleAdjuster::Options rig_ba_options; RigBundleAdjuster bundle_adjuster(ba_options, rig_ba_options, config); CHECK(bundle_adjuster.Solve(&reconstruction, &camera_rigs)); reconstruction.Write(output_path); return EXIT_SUCCESS; } int RunSpatialMatcher(int argc, char** argv) { OptionManager options; options.AddDatabaseOptions(); options.AddSpatialMatchingOptions(); options.Parse(argc, argv); std::unique_ptr app; if (options.sift_matching->use_gpu && kUseOpenGL) { app.reset(new QApplication(argc, argv)); } SpatialFeatureMatcher feature_matcher(*options.spatial_matching, *options.sift_matching, *options.database_path); if (options.sift_matching->use_gpu && kUseOpenGL) { RunThreadWithOpenGLContext(&feature_matcher); } else { feature_matcher.Start(); feature_matcher.Wait(); } return EXIT_SUCCESS; } int RunTransitiveMatcher(int argc, char** argv) { OptionManager options; options.AddDatabaseOptions(); options.AddTransitiveMatchingOptions(); options.Parse(argc, argv); std::unique_ptr app; if (options.sift_matching->use_gpu && kUseOpenGL) { app.reset(new QApplication(argc, argv)); } TransitiveFeatureMatcher feature_matcher(*options.transitive_matching, *options.sift_matching, *options.database_path); if (options.sift_matching->use_gpu && kUseOpenGL) { RunThreadWithOpenGLContext(&feature_matcher); } else { feature_matcher.Start(); feature_matcher.Wait(); } return EXIT_SUCCESS; } // Loads descriptors for training from the database. Loads all descriptors from // the database if max_num_images < 0, otherwise the descriptors of a random // subset of images are selected. FeatureDescriptors LoadRandomDatabaseDescriptors( const std::string& database_path, const int max_num_images) { Database database(database_path); DatabaseTransaction database_transaction(&database); const std::vector images = database.ReadAllImages(); FeatureDescriptors descriptors; std::vector image_idxs; size_t num_descriptors = 0; if (max_num_images < 0) { // All images in the database. image_idxs.resize(images.size()); std::iota(image_idxs.begin(), image_idxs.end(), 0); num_descriptors = database.NumDescriptors(); } else { // Random subset of images in the database. CHECK_LE(max_num_images, images.size()); RandomSampler random_sampler(max_num_images); random_sampler.Initialize(images.size()); image_idxs = random_sampler.Sample(); for (const auto image_idx : image_idxs) { const auto& image = images.at(image_idx); num_descriptors += database.NumDescriptorsForImage(image.ImageId()); } } descriptors.resize(num_descriptors, 128); size_t descriptor_row = 0; for (const auto image_idx : image_idxs) { const auto& image = images.at(image_idx); const FeatureDescriptors image_descriptors = database.ReadDescriptors(image.ImageId()); descriptors.block(descriptor_row, 0, image_descriptors.rows(), 128) = image_descriptors; descriptor_row += image_descriptors.rows(); } CHECK_EQ(descriptor_row, num_descriptors); return descriptors; } int RunVocabTreeBuilder(int argc, char** argv) { std::string vocab_tree_path; retrieval::VisualIndex<>::BuildOptions build_options; int max_num_images = -1; OptionManager options; options.AddDatabaseOptions(); options.AddRequiredOption(""vocab_tree_path"", &vocab_tree_path); options.AddDefaultOption(""num_visual_words"", &build_options.num_visual_words); options.AddDefaultOption(""num_checks"", &build_options.num_checks); options.AddDefaultOption(""branching"", &build_options.branching); options.AddDefaultOption(""num_iterations"", &build_options.num_iterations); options.AddDefaultOption(""max_num_images"", &max_num_images); options.Parse(argc, argv); retrieval::VisualIndex<> visual_index; std::cout << ""Loading descriptors..."" << std::endl; const auto descriptors = LoadRandomDatabaseDescriptors(*options.database_path, max_num_images); std::cout << "" => Loaded a total of "" << descriptors.rows() << "" descriptors"" << std::endl; std::cout << ""Building index for visual words..."" << std::endl; visual_index.Build(build_options, descriptors); std::cout << "" => Quantized descriptor space using "" << visual_index.NumVisualWords() << "" visual words"" << std::endl; std::cout << ""Saving index to file..."" << std::endl; visual_index.Write(vocab_tree_path); return EXIT_SUCCESS; } int RunVocabTreeMatcher(int argc, char** argv) { OptionManager options; options.AddDatabaseOptions(); options.AddVocabTreeMatchingOptions(); options.Parse(argc, argv); std::unique_ptr app; if (options.sift_matching->use_gpu && kUseOpenGL) { app.reset(new QApplication(argc, argv)); } VocabTreeFeatureMatcher feature_matcher(*options.vocab_tree_matching, *options.sift_matching, *options.database_path); if (options.sift_matching->use_gpu && kUseOpenGL) { RunThreadWithOpenGLContext(&feature_matcher); } else { feature_matcher.Start(); feature_matcher.Wait(); } return EXIT_SUCCESS; } std::vector ReadVocabTreeRetrievalImageList(const std::string& path, Database* database) { std::vector images; if (path.empty()) { images.reserve(database->NumImages()); for (const auto& image : database->ReadAllImages()) { images.push_back(image); } } else { DatabaseTransaction database_transaction(database); const auto image_names = ReadTextFileLines(path); images.reserve(image_names.size()); for (const auto& image_name : image_names) { const auto image = database->ReadImageWithName(image_name); CHECK_NE(image.ImageId(), kInvalidImageId); images.push_back(image); } } return images; } int RunVocabTreeRetriever(int argc, char** argv) { std::string vocab_tree_path; std::string database_image_list_path; std::string query_image_list_path; std::string output_index_path; retrieval::VisualIndex<>::QueryOptions query_options; int max_num_features = -1; OptionManager options; options.AddDatabaseOptions(); options.AddRequiredOption(""vocab_tree_path"", &vocab_tree_path); options.AddDefaultOption(""database_image_list_path"", &database_image_list_path); options.AddDefaultOption(""query_image_list_path"", &query_image_list_path); options.AddDefaultOption(""output_index_path"", &output_index_path); options.AddDefaultOption(""num_images"", &query_options.max_num_images); options.AddDefaultOption(""num_neighbors"", &query_options.num_neighbors); options.AddDefaultOption(""num_checks"", &query_options.num_checks); options.AddDefaultOption(""num_images_after_verification"", &query_options.num_images_after_verification); options.AddDefaultOption(""max_num_features"", &max_num_features); options.Parse(argc, argv); retrieval::VisualIndex<> visual_index; visual_index.Read(vocab_tree_path); Database database(*options.database_path); const auto database_images = ReadVocabTreeRetrievalImageList(database_image_list_path, &database); const auto query_images = (!query_image_list_path.empty() || output_index_path.empty()) ? ReadVocabTreeRetrievalImageList(query_image_list_path, &database) : std::vector(); ////////////////////////////////////////////////////////////////////////////// // Perform image indexing ////////////////////////////////////////////////////////////////////////////// for (size_t i = 0; i < database_images.size(); ++i) { Timer timer; timer.Start(); std::cout << StringPrintf(""Indexing image [%d/%d]"", i + 1, database_images.size()) << std::flush; if (visual_index.ImageIndexed(database_images[i].ImageId())) { std::cout << std::endl; continue; } auto keypoints = database.ReadKeypoints(database_images[i].ImageId()); auto descriptors = database.ReadDescriptors(database_images[i].ImageId()); if (max_num_features > 0 && descriptors.rows() > max_num_features) { ExtractTopScaleFeatures(&keypoints, &descriptors, max_num_features); } visual_index.Add(retrieval::VisualIndex<>::IndexOptions(), database_images[i].ImageId(), keypoints, descriptors); std::cout << StringPrintf("" in %.3fs"", timer.ElapsedSeconds()) << std::endl; } // Compute the TF-IDF weights, etc. visual_index.Prepare(); // Optionally save the indexing data for the database images (as well as the // original vocabulary tree data) to speed up future indexing. if (!output_index_path.empty()) { visual_index.Write(output_index_path); } if (query_images.empty()) { return EXIT_SUCCESS; } ////////////////////////////////////////////////////////////////////////////// // Perform image queries ////////////////////////////////////////////////////////////////////////////// std::unordered_map image_id_to_image; image_id_to_image.reserve(database_images.size()); for (const auto& image : database_images) { image_id_to_image.emplace(image.ImageId(), &image); } for (size_t i = 0; i < query_images.size(); ++i) { Timer timer; timer.Start(); std::cout << StringPrintf(""Querying for image %s [%d/%d]"", query_images[i].Name().c_str(), i + 1, query_images.size()) << std::flush; auto keypoints = database.ReadKeypoints(query_images[i].ImageId()); auto descriptors = database.ReadDescriptors(query_images[i].ImageId()); if (max_num_features > 0 && descriptors.rows() > max_num_features) { ExtractTopScaleFeatures(&keypoints, &descriptors, max_num_features); } std::vector image_scores; visual_index.Query(query_options, keypoints, descriptors, &image_scores); std::cout << StringPrintf("" in %.3fs"", timer.ElapsedSeconds()) << std::endl; for (const auto& image_score : image_scores) { const auto& image = *image_id_to_image.at(image_score.image_id); std::cout << StringPrintf("" image_id=%d, image_name=%s, score=%f"", image_score.image_id, image.Name().c_str(), image_score.score) << std::endl; } } return EXIT_SUCCESS; } typedef std::function command_func_t; int ShowHelp( const std::vector>& commands) { std::cout << StringPrintf( ""%s -- Structure-from-Motion and Multi-View Stereo\\n"" "" (%s)"", GetVersionInfo().c_str(), GetBuildInfo().c_str()) << std::endl << std::endl; std::cout << ""Usage:"" << std::endl; std::cout << "" colmap [command] [options]"" << std::endl << std::endl; std::cout << ""Documentation:"" << std::endl; std::cout << "" https://colmap.github.io/"" << std::endl << std::endl; std::cout << ""Example usage:"" << std::endl; std::cout << "" colmap help [ -h, --help ]"" << std::endl; std::cout << "" colmap gui"" << std::endl; std::cout << "" colmap gui -h [ --help ]"" << std::endl; std::cout << "" colmap automatic_reconstructor -h [ --help ]"" << std::endl; std::cout << "" colmap automatic_reconstructor --image_path IMAGES "" ""--workspace_path WORKSPACE"" << std::endl; std::cout << "" colmap feature_extractor --image_path IMAGES --database_path "" ""DATABASE"" << std::endl; std::cout << "" colmap exhaustive_matcher --database_path DATABASE"" << std::endl; std::cout << "" colmap mapper --image_path IMAGES --database_path DATABASE "" ""--output_path MODEL"" << std::endl; std::cout << "" ..."" << std::endl << std::endl; std::cout << ""Available commands:"" << std::endl; std::cout << "" help"" << std::endl; for (const auto& command : commands) { std::cout << "" "" << command.first << std::endl; } std::cout << std::endl; return EXIT_SUCCESS; } int main(int argc, char** argv) { InitializeGlog(argv); std::vector> commands; commands.emplace_back(""gui"", &RunGraphicalUserInterface); commands.emplace_back(""automatic_reconstructor"", &RunAutomaticReconstructor); commands.emplace_back(""bundle_adjuster"", &RunBundleAdjuster); commands.emplace_back(""color_extractor"", &RunColorExtractor); commands.emplace_back(""database_creator"", &RunDatabaseCreator); commands.emplace_back(""database_merger"", &RunDatabaseMerger); commands.emplace_back(""delaunay_mesher"", &RunDelaunayMesher); commands.emplace_back(""exhaustive_matcher"", &RunExhaustiveMatcher); commands.emplace_back(""feature_extractor"", &RunFeatureExtractor); commands.emplace_back(""feature_importer"", &RunFeatureImporter); commands.emplace_back(""hierarchical_mapper"", &RunHierarchicalMapper); commands.emplace_back(""image_deleter"", &RunImageDeleter); commands.emplace_back(""image_filterer"", &RunImageFilterer); commands.emplace_back(""image_rectifier"", &RunImageRectifier); commands.emplace_back(""image_registrator"", &RunImageRegistrator); commands.emplace_back(""image_undistorter"", &RunImageUndistorter); commands.emplace_back(""mapper"", &RunMapper); commands.emplace_back(""matches_importer"", &RunMatchesImporter); commands.emplace_back(""model_aligner"", &RunModelAligner); commands.emplace_back(""model_analyzer"", &RunModelAnalyzer); commands.emplace_back(""model_converter"", &RunModelConverter); commands.emplace_back(""model_merger"", &RunModelMerger); commands.emplace_back(""model_orientation_aligner"", &RunModelOrientationAligner); commands.emplace_back(""patch_match_stereo"", &RunPatchMatchStereo); commands.emplace_back(""point_filtering"", &RunPointFiltering); commands.emplace_back(""point_triangulator"", &RunPointTriangulator); commands.emplace_back(""poisson_mesher"", &RunPoissonMesher); commands.emplace_back(""project_generator"", &RunProjectGenerator); commands.emplace_back(""rig_bundle_adjuster"", &RunRigBundleAdjuster); commands.emplace_back(""sequential_matcher"", &RunSequentialMatcher); commands.emplace_back(""spatial_matcher"", &RunSpatialMatcher); commands.emplace_back(""stereo_fusion"", &RunStereoFuser); commands.emplace_back(""transitive_matcher"", &RunTransitiveMatcher); commands.emplace_back(""vocab_tree_builder"", &RunVocabTreeBuilder); commands.emplace_back(""vocab_tree_matcher"", &RunVocabTreeMatcher); commands.emplace_back(""vocab_tree_retriever"", &RunVocabTreeRetriever); if (argc == 1) { return ShowHelp(commands); } const std::string command = argv[1]; if (command == ""help"" || command == ""-h"" || command == ""--help"") { return ShowHelp(commands); } else { command_func_t matched_command_func = nullptr; for (const auto& command_func : commands) { if (command == command_func.first) { matched_command_func = command_func.second; break; } } if (matched_command_func == nullptr) { std::cerr << StringPrintf( ""ERROR: Command `%s` not recognized. To list the "" ""available commands, run `colmap help`."", command.c_str()) << std::endl; return EXIT_FAILURE; } else { int command_argc = argc - 1; char** command_argv = &argv[1]; command_argv[0] = argv[0]; return matched_command_func(command_argc, command_argv); } } return ShowHelp(commands); } ",16162,True,3090.1958958223195,median "[[scoreCalculation]] = Score calculation :doctype: book :sectnums: :icons: font [[scoreTerminology]] == Score terminology [[whatIsAScore]] === What is a score? Every `@PlanningSolution` class has a score. The score is an objective way to compare two solutions. The solution with the higher score is better. The `Solver` aims to find the solution with the highest `Score` of all possible solutions. The _best solution_ is the solution with the highest `Score` that `Solver` has encountered during solving, which might be the __optimal solution__. OptaPlanner cannot automatically know which solution is best for your business, so you need to tell it how to calculate the score of a given `@PlanningSolution` instance according to your business needs. If you forget or are unable to implement an important business constraint, the solution is probably useless: image::score-calculation/optimalWithIncompleteConstraints.png[align=""center""] [[formalizeTheBusinessConstraints]] === Formalize the business constraints To implement a verbal business constraint, it needs to be formalized as a score constraint. Luckily, defining constraints in OptaPlanner is very flexible through the following score techniques: * **Score signum (positive or negative)**: maximize or minimize a constraint type * **Score weight**: put a cost/profit on a constraint type * **Score level (hard, soft, ...)**: prioritize a group of constraint types * *Pareto scoring* (rarely used) Take the time to acquaint yourself with the first three techniques. Once you understand them, formalizing most business constraints becomes straightforward. [NOTE] ==== Do not presume that your business knows all its score constraints in advance. Expect score constraints to be added, changed or removed after the first releases. ==== [[scoreConstraintSignum]] === Score constraint signum (positive or negative) All score techniques are based on constraints. A constraint can be a simple pattern (such as __Maximize the apple harvest in the solution__) or a more complex pattern. A positive constraint is a constraint you want to maximize. A negative constraint is a constraint you want to minimize image::score-calculation/positiveAndNegativeConstraints.png[align=""center""] The image above illustrates that **the optimal solution always has the highest score**, regardless if the constraints are positive or negative. Most planning problems have only negative constraints and therefore have a negative score. In that case, the score is the sum of the weight of the negative constraints being broken, with a perfect score of 0. For example in n queens, the score is the negative of the number of queen pairs which can attack each other. Negative and positive constraints can be combined, even in the same score level. When a constraint activates (because the negative constraint is broken or the positive constraint is fulfilled) on a certain planning entity set, it is called a __constraint match__. [[scoreConstraintWeight]] === Score constraint weight Not all score constraints are equally important. If breaking one constraint is equally bad as breaking another constraint x times, then those two constraints have a different weight (but they are in the same score level). For example in vehicle routing, you can make one _unhappy driver_ constraint match count as much as two _fuel tank usage_ constraint matches: image::score-calculation/scoreWeighting.png[align=""center""] Score weighting is easy in use cases where you can __put a price tag on everything__. In that case, the positive constraints maximize revenue and the negative constraints minimize expenses, so together they maximize profit. Alternatively, score weighting is also often used to create social <>. For example, a nurse, who requests a free day, pays a higher weight on New Years eve than on a normal day. The weight of a constraint match can depend on the planning entities involved. For example in cloud balancing, the weight of the soft constraint match for an active `Computer` is the maintenance `cost` of that `Computer` (which differs per computer). Putting a good weight on a constraint is often a difficult analytical decision, because it is about making choices and trade-offs against other constraints. Different stakeholders have different priorities. *Don't waste time with constraint weight discussions at the start of an implementation, instead add a <> and allow users to change them through a UI.* A non-accurate weight is less damaging than mediocre algorithms: image::score-calculation/scoreTradeoffInPerspective.png[align=""center""] Most use cases use a `Score` with `int` weights, such as <>. [[scoreLevel]] === Score constraint level (hard, soft, ...) Sometimes a score constraint outranks another score constraint, no matter how many times the latter is broken. In that case, those score constraints are in different levels. For example, a nurse cannot do two shifts at the same time (due to the constraints of physical reality), so this outranks all nurse happiness constraints. Most use cases have only two score levels, hard and soft. The levels of two scores are compared lexicographically. The first score level gets compared first. If those differ, the remaining score levels are ignored. For example, a score that breaks `0` hard constraints and `1000000` soft constraints is better than a score that breaks `1` hard constraint and `0` soft constraints. image::score-calculation/scoreLevels.png[align=""center""] If there are two (or more) score levels, for example <>, then a score is _feasible_ if no hard constraints are broken. [NOTE] ==== By default, OptaPlanner will always assign all planning variables a planning value. If there is no feasible solution, this means the best solution will be infeasible. To instead leave some of the planning entities unassigned, apply xref:repeated-planning/repeated-planning.adoc#overconstrainedPlanning[overconstrained planning]. ==== For each constraint, you need to pick a score level, a score weight and a score signum. For example: `-1soft` which has score level of ``soft``, a weight of `1` and a negative signum. Do not use a big constraint weight when your business actually wants different score levels. That hack, known as __score folding__, is broken: image::score-calculation/scoreFoldingIsBroken.png[align=""center""] [NOTE] ==== Your business might tell you that your hard constraints all have the same weight, because they cannot be broken (so the weight does not matter). This is not true because if no feasible solution exists for a specific dataset, the least infeasible solution allows the business to estimate how many business resources they are lacking. For example in cloud balancing, how many new computers to buy. Furthermore, it will likely create a <>. For example in cloud balance if a `Computer` has seven CPU too little for its ``Process``es, then it must be weighted seven times as much as if it had only one CPU too little. ==== Three or more score levels are also supported. For example: a company might decide that profit outranks employee satisfaction (or vice versa), while both are outranked by the constraints of physical reality. [NOTE] ==== To model <>, there is no need to use lots of score levels (even though OptaPlanner can handle many score levels). ==== Most use cases use a `Score` with two or three weights, such as <> and <>. [[paretoScoring]] === Pareto scoring (AKA multi-objective optimization scoring) Far less common is the use case of pareto optimization, which is also known as _multi-objective optimization_. In pareto scoring, score constraints are in the same score level, yet they are not weighted against each other. When two scores are compared, each of the score constraints are compared individually and the score with the most dominating score constraints wins. Pareto scoring can even be combined with score levels and score constraint weighting. Consider this example with positive constraints, where we want to get the most apples and oranges. Since it is impossible to compare apples and oranges, we cannot weigh them against each other. Yet, despite that we cannot compare them, we can state that two apples are better than one apple. Similarly, we can state that two apples and one orange are better than just one orange. So despite our inability to compare some Scores conclusively (at which point we declare them equal), we can find a set of optimal scores. Those are called pareto optimal. image::score-calculation/paretoOptimizationScoring.png[align=""center""] Scores are considered equal far more often. It is left up to a human to choose the better out of a set of best solutions (with equal scores) found by OptaPlanner. In the example above, the user must choose between solution A (three apples and one orange) and solution B (one apple and six oranges). It is guaranteed that OptaPlanner has not found another solution which has more apples or more oranges or even a better combination of both (such as two apples and three oranges). Pareto scoring is currently not supported in OptaPlanner. [NOTE] ==== A pareto ``Score``'s `compareTo` method is not transitive because it does a pareto comparison. For example: having two apples is greater than one apple. One apple is equal to One orange. Yet, two apples are not greater than one orange (but actually equal). Pareto comparison violates the contract of the interface ``java.lang.Comparable``'s `compareTo` method, but Planners systems are __pareto comparison safe__, unless explicitly stated otherwise in this documentation. ==== [[combiningScoreTechniques]] === Combining score techniques All the score techniques mentioned above, can be combined seamlessly: image::score-calculation/scoreComposition.png[align=""center""] [[scoreInterface]] === `Score` interface A score is represented by the `Score` interface, which naturally extends ``Comparable``: [source,java,options=""nowrap""] ---- public interface Score<...> extends Comparable<...> { ... } ---- The `Score` implementation to use depends on your use case. Your score might not efficiently fit in a single `long` value. OptaPlanner has several built-in `Score` implementations, but you can implement a custom `Score` too. Most use cases tend to use the built-in ``HardSoftScore``. image::score-calculation/scoreClassDiagram.png[align=""center""] All Score implementations also have an `initScore` (which is an ``int``).It is mostly intended for internal use in OptaPlanner: it is the negative number of uninitialized planning variables. From a user's perspective this is ``0``, unless a Construction Heuristic is terminated before it could initialize all planning variables (in which case `Score.isSolutionInitialized()` returns ``false``). The `Score` implementation (for example ``HardSoftScore``) must be the same throughout a `Solver` runtime. The `Score` implementation is configured in the solution domain class: [source,java,options=""nowrap""] ---- @PlanningSolution public class CloudBalance { ... @PlanningScore private HardSoftScore score; } ---- [[avoidFloatingPointNumbersInScoreCalculation]] === Avoid floating point numbers in score calculation Avoid the use of `float` or `double` in score calculation. Use `BigDecimal` or scaled `long` instead. Floating point numbers (``float`` and ``double``) cannot represent a decimal number correctly. For example: a `double` cannot hold the value `0.05` correctly. Instead, it holds the nearest representable value. Arithmetic (including addition and subtraction) with floating point numbers, especially for planning problems, leads to incorrect decisions: image::score-calculation/scoreWeightType.png[align=""center""] Additionally, floating point number addition is not associative: [source,java,options=""nowrap""] ---- System.out.println( ((0.01 + 0.02) + 0.03) == (0.01 + (0.02 + 0.03)) ); // returns false ---- This leads to __score corruption__. Decimal numbers (``BigDecimal``) have none of these problems. [NOTE] ==== BigDecimal arithmetic is considerably slower than ``int``, `long` or `double` arithmetic. In experiments we have seen the score calculation take five times longer. Therefore, in many cases, it can be worthwhile to multiply _all_ numbers for a single score weight by a plural of ten, so the score weight fits in a scaled `int` or ``long``. For example, if we multiply all weights by ``1000``, a fuelCost of `0.07` becomes a fuelCostMillis of `70` and no longer uses a decimal score weight. ==== [[scoreType]] == Choose a score type Depending on the number of score levels and type of score weights you need, choose a `Score` type. Most use cases use a ``HardSoftScore``. [NOTE] ==== To properly write a `Score` to a database (with JPA/Hibernate) or to XML/JSON (with XStream/JAXB/Jackson), see xref:integration/integration.adoc#integration[the integration chapter]. ==== [[simpleScore]] === `SimpleScore` A `SimpleScore` has a single `int` value, for example ``-123``. It has a single score level. [source,java,options=""nowrap""] ---- @PlanningScore private SimpleScore score; ---- Variants of this `Score` type: * `SimpleLongScore` uses a `long` value instead of an `int` value. * `SimpleBigDecimalScore` uses a `BigDecimal` value instead of an `int` value. [[hardSoftScore]] === `HardSoftScore` (Recommended) A `HardSoftScore` has a hard `int` value and a soft `int` value, for example ``-123hard/-456soft``. It has two score levels (hard and soft). [source,java,options=""nowrap""] ---- @PlanningScore private HardSoftScore score; ---- Variants of this `Score` type: * `HardSoftLongScore` uses `long` values instead of `int` values. * `HardSoftBigDecimalScore` uses `BigDecimal` values instead of `int` values. [[hardMediumSoftScore]] === `HardMediumSoftScore` A `HardMediumSoftScore` which has a hard `int` value, a medium `int` value and a soft `int` value, for example ``-123hard/-456medium/-789soft``. It has three score levels (hard, medium and soft). The hard level determines if the solution is feasible, and the medium level and soft level score values determine how well the solution meets business goals. Higher medium values take precedence over soft values irrespective of the soft value. [source,java,options=""nowrap""] ---- @PlanningScore private HardMediumSoftScore score; ---- Variants of this `Score` type: * `HardMediumSoftLongScore` uses `long` values instead of `int` values. * `HardMediumSoftBigDecimalScore` uses `BigDecimal` values instead of `int` values. [[bendableScore]] === `BendableScore` A `BendableScore` has a configurable number of score levels. It has an array of hard `int` values and an array of soft `int` values, for example with two hard levels and three soft levels, the score can be ``[-123/-456]hard/[-789/-012/-345]soft``. In that case, it has five score levels. A solution is feasible if all hard levels are at least zero. A BendableScore with one hard level and one soft level is equivalent to a HardSoftScore, while a BendableScore with one hard level and two soft levels is equivalent to a HardMediumSoftScore. [source,java,options=""nowrap""] ---- @PlanningScore(bendableHardLevelsSize = 2, bendableSoftLevelsSize = 3) private BendableScore score; ---- The number of hard and soft score levels need to be set at compilation time. It is not flexible to change during solving. [NOTE] ==== Do not use a `BendableScore` with seven levels just because you have seven constraints. It is extremely rare to use a different score level for each constraint, because that means one constraint match on soft 0 outweighs even a million constraint matches of soft 1. Usually, multiple constraints share the same level and are weighted against each other. Use <> to get the weight of individual constraints in the same level. ==== Variants of this `Score` type: * `BendableLongScore` uses `long` values instead of `int` values. * `BendableBigDecimalScore` uses `BigDecimal` values instead of `int` values. [[calculateTheScore]] == Calculate the `Score` [[scoreCalculationTypes]] === Score calculation types There are several ways to calculate the `Score` of a solution: * **<>**: Implement all constraints together in a single method in Java (or another JVM language). Does not scale. * **xref:constraint-streams/constraint-streams.adoc#constraintStreams[Constraint streams score calculation]**: Implement each constraint as a separate Constraint Stream in Java (or another JVM language). Fast and scalable. * **<>** (not recommended): Implement multiple low-level methods in Java (or another JVM language). Fast and scalable. Very difficult to implement and maintain. * **xref:drools-score-calculation/drools-score-calculation.adoc#droolsScoreCalculation[Drools score calculation]**: Implement each constraint as a separate score rule in DRL. Scalable. Every score calculation type can work with any Score definition (such as ``HardSoftScore`` or ``HardMediumSoftScore``). All score calculation types are Object Oriented and can reuse existing Java code. [IMPORTANT] ==== The score calculation must be read-only. It must not change the planning entities or the problem facts in any way. For example, it must not call a setter method on a planning entity in the score calculation. OptaPlanner does not recalculate the score of a solution if it can predict it (unless an xref:planner-configuration/planner-configuration.adoc#environmentMode[environmentMode assertion] is enabled). For example, after a winning step is done, there is no need to calculate the score because that move was done and undone earlier. As a result, there is no guarantee that changes applied during score calculation actually happen. To update planning entities when the planning variable change, use xref:shadow-variable/shadow-variable.adoc#shadowVariable[shadow variables] instead. ==== [[easyJavaScoreCalculation]] === Easy Java score calculation An easy way to implement your score calculation in Java. * Advantages: ** Plain old Java: no learning curve ** Opportunity to delegate score calculation to an existing code base or legacy system * Disadvantages: ** Slower ** Does not scale because there is no <> Implement the one method of the interface ``EasyScoreCalculator``: [source,java,options=""nowrap""] ---- public interface EasyScoreCalculator> { Score_ calculateScore(Solution_ solution); } ---- For example in n queens: [source,java,options=""nowrap""] ---- public class NQueensEasyScoreCalculator implements EasyScoreCalculator { @Override public SimpleScore calculateScore(NQueens nQueens) { int n = nQueens.getN(); List queenList = nQueens.getQueenList(); int score = 0; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { Queen leftQueen = queenList.get(i); Queen rightQueen = queenList.get(j); if (leftQueen.getRow() != null && rightQueen.getRow() != null) { if (leftQueen.getRowIndex() == rightQueen.getRowIndex()) { score--; } if (leftQueen.getAscendingDiagonalIndex() == rightQueen.getAscendingDiagonalIndex()) { score--; } if (leftQueen.getDescendingDiagonalIndex() == rightQueen.getDescendingDiagonalIndex()) { score--; } } } } return SimpleScore.valueOf(score); } } ---- Configure it in the solver configuration: [source,xml,options=""nowrap""] ---- org.optaplanner.examples.nqueens.optional.score.NQueensEasyScoreCalculator ---- To configure values of an `EasyScoreCalculator` dynamically in the solver configuration (so the xref:benchmarking-and-tweaking/benchmarking-and-tweaking.adoc#benchmarker[Benchmarker] can tweak those parameters), add the `easyScoreCalculatorCustomProperties` element and use xref:planner-configuration/planner-configuration.adoc#customPropertiesConfiguration[custom properties]: [source,xml,options=""nowrap""] ---- ...MyEasyScoreCalculator ---- [[incrementalJavaScoreCalculation]] === Incremental Java score calculation A way to implement your score calculation incrementally in Java. * Advantages: ** Very fast and scalable *** Currently the fastest if implemented correctly * Disadvantages: ** Hard to write *** A scalable implementation heavily uses maps, indexes, ... (things the Drools rule engine can do for you) *** You have to learn, design, write and improve all these performance optimizations yourself ** Hard to read *** Regular score constraint changes can lead to a high maintenance cost Implement all the methods of the interface `IncrementalScoreCalculator`: [source,java,options=""nowrap""] ---- public interface IncrementalScoreCalculator> { void resetWorkingSolution(Solution_ workingSolution); void beforeEntityAdded(Object entity); void afterEntityAdded(Object entity); void beforeVariableChanged(Object entity, String variableName); void afterVariableChanged(Object entity, String variableName); void beforeEntityRemoved(Object entity); void afterEntityRemoved(Object entity); Score_ calculateScore(); } ---- image::score-calculation/incrementalScoreCalculatorSequenceDiagram.png[align=""center""] For example in n queens: [source,java,options=""nowrap""] ---- public class NQueensAdvancedIncrementalScoreCalculator implements IncrementalScoreCalculator { private Map> rowIndexMap; private Map> ascendingDiagonalIndexMap; private Map> descendingDiagonalIndexMap; private int score; public void resetWorkingSolution(NQueens nQueens) { int n = nQueens.getN(); rowIndexMap = new HashMap>(n); ascendingDiagonalIndexMap = new HashMap>(n * 2); descendingDiagonalIndexMap = new HashMap>(n * 2); for (int i = 0; i < n; i++) { rowIndexMap.put(i, new ArrayList(n)); ascendingDiagonalIndexMap.put(i, new ArrayList(n)); descendingDiagonalIndexMap.put(i, new ArrayList(n)); if (i != 0) { ascendingDiagonalIndexMap.put(n - 1 + i, new ArrayList(n)); descendingDiagonalIndexMap.put((-i), new ArrayList(n)); } } score = 0; for (Queen queen : nQueens.getQueenList()) { insert(queen); } } public void beforeEntityAdded(Object entity) { // Do nothing } public void afterEntityAdded(Object entity) { insert((Queen) entity); } public void beforeVariableChanged(Object entity, String variableName) { retract((Queen) entity); } public void afterVariableChanged(Object entity, String variableName) { insert((Queen) entity); } public void beforeEntityRemoved(Object entity) { retract((Queen) entity); } public void afterEntityRemoved(Object entity) { // Do nothing } private void insert(Queen queen) { Row row = queen.getRow(); if (row != null) { int rowIndex = queen.getRowIndex(); List rowIndexList = rowIndexMap.get(rowIndex); score -= rowIndexList.size(); rowIndexList.add(queen); List ascendingDiagonalIndexList = ascendingDiagonalIndexMap.get(queen.getAscendingDiagonalIndex()); score -= ascendingDiagonalIndexList.size(); ascendingDiagonalIndexList.add(queen); List descendingDiagonalIndexList = descendingDiagonalIndexMap.get(queen.getDescendingDiagonalIndex()); score -= descendingDiagonalIndexList.size(); descendingDiagonalIndexList.add(queen); } } private void retract(Queen queen) { Row row = queen.getRow(); if (row != null) { List rowIndexList = rowIndexMap.get(queen.getRowIndex()); rowIndexList.remove(queen); score += rowIndexList.size(); List ascendingDiagonalIndexList = ascendingDiagonalIndexMap.get(queen.getAscendingDiagonalIndex()); ascendingDiagonalIndexList.remove(queen); score += ascendingDiagonalIndexList.size(); List descendingDiagonalIndexList = descendingDiagonalIndexMap.get(queen.getDescendingDiagonalIndex()); descendingDiagonalIndexList.remove(queen); score += descendingDiagonalIndexList.size(); } } public SimpleScore calculateScore() { return SimpleScore.valueOf(score); } } ---- Configure it in the solver configuration: [source,xml,options=""nowrap""] ---- org.optaplanner.examples.nqueens.optional.score.NQueensAdvancedIncrementalScoreCalculator ---- [IMPORTANT] ==== A piece of incremental score calculator code can be difficult to write and to review. <> by using an ``EasyScoreCalculator`` to fulfill the assertions triggered by the ``environmentMode``. ==== To configure values of an `IncrementalScoreCalculator` dynamically in the solver configuration (so the xref:benchmarking-and-tweaking/benchmarking-and-tweaking.adoc#benchmarker[Benchmarker] can tweak those parameters), add the `incrementalScoreCalculatorCustomProperties` element and use xref:planner-configuration/planner-configuration.adoc#customPropertiesConfiguration[custom properties]: [source,xml,options=""nowrap""] ---- ...MyIncrementalScoreCalculator ---- [[constraintMatchAwareIncrementalScoreCalculator]] ==== `ConstraintMatchAwareIncrementalScoreCalculator` Optionally, also implement the `ConstraintMatchAwareIncrementalScoreCalculator` interface to: * Explain a score by splitting it up per score constraint with `ScoreExplanation.getConstraintMatchTotalMap()`. * Visualize or sort planning entities by how many constraints each one breaks with `ScoreExplanation.getIndictmentMap()`. * Receive a detailed analysis if the `IncrementalScoreCalculator` is corrupted in `FAST_ASSERT` or `FULL_ASSERT` `environmentMode`, [source,java,options=""nowrap""] ---- public interface ConstraintMatchAwareIncrementalScoreCalculator> { void resetWorkingSolution(Solution_ workingSolution, boolean constraintMatchEnabled); Collection> getConstraintMatchTotals(); Map> getIndictmentMap(); } ---- For example in machine reassignment, create one `ConstraintMatchTotal` per constraint type and call `addConstraintMatch()` for each constraint match: [source,java,options=""nowrap""] ---- public class MachineReassignmentIncrementalScoreCalculator implements ConstraintMatchAwareIncrementalScoreCalculator { ... @Override public void resetWorkingSolution(MachineReassignment workingSolution, boolean constraintMatchEnabled) { resetWorkingSolution(workingSolution); // ignore constraintMatchEnabled, it is always presumed enabled } @Override public Collection> getConstraintMatchTotals() { ConstraintMatchTotal maximumCapacityMatchTotal = new DefaultConstraintMatchTotal<>(CONSTRAINT_PACKAGE, ""maximumCapacity"", HardSoftLongScore.ZERO); ... for (MrMachineScorePart machineScorePart : machineScorePartMap.values()) { for (MrMachineCapacityScorePart machineCapacityScorePart : machineScorePart.machineCapacityScorePartList) { if (machineCapacityScorePart.maximumAvailable < 0L) { maximumCapacityMatchTotal.addConstraintMatch( Arrays.asList(machineCapacityScorePart.machineCapacity), HardSoftLongScore.valueOf(machineCapacityScorePart.maximumAvailable, 0)); } } } ... List> constraintMatchTotalList = new ArrayList<>(4); constraintMatchTotalList.add(maximumCapacityMatchTotal); ... return constraintMatchTotalList; } @Override public Map> getIndictmentMap() { return null; // Calculate it non-incrementally from getConstraintMatchTotals() } } ---- That `getConstraintMatchTotals()` code often duplicates some of the logic of the normal `IncrementalScoreCalculator` methods. Constraint Streams and Drools Score Calculation don't have this disadvantage, because they are constraint match aware automatically when needed, without any extra domain-specific code. [[initializingScoreTrend]] === `InitializingScoreTrend` The `InitializingScoreTrend` specifies how the Score will change as more and more variables are initialized (while the already initialized variables do not change). Some optimization algorithms (such Construction Heuristics and Exhaustive Search) run faster if they have such information. For the Score (or each <> separately), specify a trend: * `ANY` (default): Initializing an extra variable can change the score positively or negatively. Gives no performance gain. * `ONLY_UP` (rare): Initializing an extra variable can only change the score positively. Implies that: ** There are only positive constraints ** And initializing the next variable cannot unmatch a positive constraint that was matched by a previous initialized variable. * ``ONLY_DOWN``: Initializing an extra variable can only change the score negatively. Implies that: ** There are only negative constraints ** And initializing the next variable cannot unmatch a negative constraint that was matched by a previous initialized variable. Most use cases only have negative constraints. Many of those have an `InitializingScoreTrend` that only goes down: [source,xml,options=""nowrap""] ---- org.optaplanner.examples.cloudbalancing.score.CloudBalancingConstraintProvider ONLY_DOWN ---- Alternatively, you can also specify the trend for each score level separately: [source,xml,options=""nowrap""] ---- org.optaplanner.examples.cloudbalancing.score.CloudBalancingConstraintProvider ONLY_DOWN/ONLY_DOWN ---- [[invalidScoreDetection]] === Invalid score detection When you put the xref:planner-configuration/planner-configuration.adoc#environmentMode[`environmentMode`] in `FULL_ASSERT` (or ``FAST_ASSERT``), it will detect score corruption in the <>. However, that will not verify that your score calculator actually implements your score constraints as your business desires. For example, one constraint might consistently match the wrong pattern. To verify the constraints against an independent implementation, configure a ``assertionScoreDirectorFactory``: [source,xml,options=""nowrap""] ---- FAST_ASSERT ... org.optaplanner.examples.nqueens.optional.score.NQueensConstraintProviderorg.optaplanner.examples.nqueens.optional.score.NQueensConstraintProvider org.optaplanner.examples.nqueens.optional.score.NQueensEasyScoreCalculator ---- This way, the `NQueensConstraintProvider` implementation is validated by the ``EasyScoreCalculator``. [NOTE] ==== This works well to isolate score corruption, but to verify that the constraint implement the real business needs, xref:constraint-streams/constraint-streams.adoc#constraintStreamsTesting[a unit test with a ConstraintVerifier] is usually better. ==== [[scoreCalculationPerformanceTricks]] == Score calculation performance tricks [[scoreCalculationPerformanceTricksOverview]] === Overview The `Solver` will normally spend most of its execution time running the score calculation (which is called in its deepest loops). Faster score calculation will return the same solution in less time with the same algorithm, which normally means a better solution in equal time. [[scoreCalculationSpeed]] === Score calculation speed After solving a problem, the `Solver` will log the __score calculation speed per second__. This is a good measurement of Score calculation performance, despite that it is affected by non score calculation execution time. It depends on the problem scale of the problem dataset. Normally, even for high scale problems, it is higher than ``1000``, except if you are using an ``EasyScoreCalculator``. [IMPORTANT] ==== When improving your score calculation, focus on maximizing the score calculation speed, instead of maximizing the best score. A big improvement in score calculation can sometimes yield little or no best score improvement, for example when the algorithm is stuck in a local or global optima. If you are watching the calculation speed instead, score calculation improvements are far more visible. Furthermore, watching the calculation speed allows you to remove or add score constraints, and still compare it with the original's calculation speed. Comparing the best score with the original's best score is pointless: it's comparing apples and oranges. ==== [[incrementalScoreCalculation]] === Incremental score calculation (with deltas) When a solution changes, incremental score calculation (AKA delta based score calculation) calculates the delta with the previous state to find the new ``Score``, instead of recalculating the entire score on every solution evaluation. For example, when a single queen A moves from row `1` to ``2``, it will not bother to check if queen B and C can attack each other, since neither of them changed: image::score-calculation/incrementalScoreCalculationNQueens04.png[align=""center""] Similarly in employee rostering: image::score-calculation/incrementalScoreCalculationEmployeeRostering.png[align=""center""] This is a huge performance and scalability gain. *xref:constraint-streams/constraint-streams.adoc#constraintStreams[Constraint Streams] or xref:drools-score-calculation/drools-score-calculation.adoc#droolsScoreCalculation[Drools score calculation] give you this huge scalability gain without forcing you to write a complicated incremental score calculation algorithm.* Just let the rule engine do the hard work. Notice that the speedup is relative to the size of your planning problem (your __n__), making incremental score calculation far more scalable. [[avoidCallingRemoteServicesDuringScoreCalculation]] === Avoid calling remote services during score calculation Do not call remote services in your score calculation (except if you are bridging `EasyScoreCalculator` to a legacy system). The network latency will kill your score calculation performance. Cache the results of those remote services if possible. If some parts of a constraint can be calculated once, when the `Solver` starts, and never change during solving, then turn them into xref:planner-configuration/planner-configuration.adoc#cachedProblemFact[cached problem facts]. [[pointlessConstraints]] === Pointless constraints If you know a certain constraint can never be broken (or it is always broken), do not write a score constraint for it. For example in n queens, the score calculation does not check if multiple queens occupy the same column, because a ``Queen``'s `column` never changes and every solution starts with each `Queen` on a different ``column``. [NOTE] ==== Do not go overboard with this. If some datasets do not use a specific constraint but others do, just return out of the constraint as soon as you can. There is no need to dynamically change your score calculation based on the dataset. ==== [[buildInHardConstraint]] === Built-in hard constraint Instead of implementing a hard constraint, it can sometimes be built in. For example, if `Lecture` A should never be assigned to `Room` X, but it uses `ValueRangeProvider` on Solution, so the `Solver` will often try to assign it to `Room` X too (only to find out that it breaks a hard constraint). Use xref:planner-configuration/planner-configuration.adoc#valueRangeProviderOnPlanningEntity[a ValueRangeProvider on the planning entity] or xref:move-and-neighborhood-selection/move-and-neighborhood-selection.adoc#filteredSelection[filtered selection] to define that Course A should only be assigned a `Room` different than X. This can give a good performance gain in some use cases, not just because the score calculation is faster, but mainly because most optimization algorithms will spend less time evaluating infeasible solutions. However, usually this is not a good idea because there is a real risk of trading short term benefits for long term harm: * Many optimization algorithms rely on the freedom to break hard constraints when changing planning entities, to get out of local optima. * Both implementation approaches have limitations (feature compatibility, disabling automatic performance optimizations), as explained in their documentation. [[otherScoreCalculationPerformanceTricks]] === Other score calculation performance tricks * Verify that your score calculation happens in the correct `Number` type. If you are making the sum of `int` values, do not sum it in a `double` which takes longer. * For optimal performance, always use server mode (``java -server``). We have seen performance increases of 50% by turning on server mode. * For optimal performance, use the latest Java version. For example, in the past we have seen performance increases of 30% by switching from java 1.5 to 1.6. * Always remember that premature optimization is the root of all evil. Make sure your design is flexible enough to allow configuration based tweaking. [[scoreTrap]] === Score trap Make sure that none of your score constraints cause a score trap. A trapped score constraint uses the same weight for different constraint matches, when it could just as easily use a different weight. It effectively lumps its constraint matches together, which creates a flatlined score function for that constraint. This can cause a solution state in which several moves need to be done to resolve or lower the weight of that single constraint. Some examples of score traps: * You need two doctors at each table, but you are only moving one doctor at a time. So the solver has no incentive to move a doctor to a table with no doctors. Punish a table with no doctors more than a table with only one doctor in that score constraint in the score function. * Two exams need to be conducted at the same time, but you are only moving one exam at a time. So the solver has to move one of those exams to another timeslot without moving the other in the same move. Add a coarse-grained move that moves both exams at the same time. For example, consider this score trap. If the blue item moves from an overloaded computer to an empty computer, the hard score should improve. The trapped score implementation fails to do that: image::score-calculation/scoreTrap.png[align=""center""] The Solver should eventually get out of this trap, but it will take a lot of effort (especially if there are even more processes on the overloaded computer). Before they do that, they might actually start moving more processes into that overloaded computer, as there is no penalty for doing so. [NOTE] ==== Avoiding score traps does not mean that your score function should be smart enough to avoid local optima. Leave it to the optimization algorithms to deal with the local optima. Avoiding score traps means to avoid, for each score constraint individually, a flatlined score function. ==== [IMPORTANT] ==== Always specify the degree of infeasibility. The business will often say ""if the solution is infeasible, it does not matter how infeasible it is."" While that is true for the business, it is not true for score calculation as it benefits from knowing how infeasible it is. In practice, soft constraints usually do this naturally and it is just a matter of doing it for the hard constraints too. ==== There are several ways to deal with a score trap: * Improve the score constraint to make a distinction in the score weight. For example, penalize `-1hard` for every missing CPU, instead of just `-1hard` if any CPU is missing. * If changing the score constraint is not allowed from the business perspective, add a lower score level with a score constraint that makes such a distinction. For example, penalize `-1subsoft` for every missing CPU, on top of `-1hard` if any CPU is missing. The business ignores the subsoft score level. * Add coarse-grained moves and union select them with the existing fine-grained moves. A coarse-grained move effectively does multiple moves to directly get out of a score trap with a single move. For example, move multiple items from the same container to another container. [[stepLimitBenchmark]] === `stepLimit` benchmark Not all score constraints have the same performance cost. Sometimes one score constraint can kill the score calculation performance outright. Use the xref:benchmarking-and-tweaking/benchmarking-and-tweaking.adoc#benchmarker[Benchmarker] to do a one minute run and check what happens to the score calculation speed if you comment out all but one of the score constraints. [[fairnessScoreConstraints]] === Fairness score constraints Some use cases have a business requirement to provide a fair schedule (usually as a soft score constraint), for example: * Fairly distribute the workload amongst the employees, to avoid envy. * Evenly distribute the workload amongst assets, to improve reliability. Implementing such a constraint can seem difficult (especially because there are different ways to formalize fairness), but usually the _squared workload_ implementation behaves most desirable. For each employee/asset, count the workload `w` and subtract `w²` from the score. image::score-calculation/fairnessScoreConstraint.png[align=""center""] As shown above, the _squared workload_ implementation guarantees that if you select two employees from a given solution and make their distribution between those two employees fairer, then the resulting new solution will have a better overall score. Do not just use the difference from the average workload, as that can lead to unfairness, as demonstrated below. image::score-calculation/fairnessScoreConstraintPitfall.png[align=""center""] [NOTE] ==== Instead of the _squared workload_, it is also possible to use the https://en.wikipedia.org/wiki/Variance[variance] (squared difference to the average) or the http://en.wikipedia.org/wiki/Standard_deviation[standard deviation] (square root of the variance). This has no effect on the score comparison, because the average will not change during planning. It is just more work to implement (because the average needs to be known) and trivially slower (because the calculation is a bit longer). ==== When the workload is perfectly balanced, the user often likes to see a `0` score, instead of the distracting `-34soft` in the image above (for the last solution which is almost perfectly balanced). To nullify this, either add the average multiplied by the number of entities to the score or instead show the variance or standard deviation in the UI. [[constraintConfiguration]] == Constraint configuration: adjust constraint weights dynamically Deciding the correct <> and <> for each constraint is not easy. It often involves negotiating with different stakeholders and their priorities. Furthermore, quantifying the impact of soft constraints is often a new experience for business managers, so they'll need a number of iterations to get it right. Don't get stuck between a rock and a hard place. Provide a UI to adjust the constraint weights and visualize the resulting solution, so the business managers can tweak the constraint weights themselves: image::score-calculation/parameterizeTheScoreWeights.png[align=""center""] [[createAConstraintConfiguration]] === Create a constraint configuration First, create a new class to hold the constraint weights and other constraint parameters. Annotate it with `@ConstraintConfiguration`: [source,java,options=""nowrap""] ---- @ConstraintConfiguration public class ConferenceConstraintConfiguration { ... } ---- There will be exactly one instance of this class per planning solution. The planning solution and the constraint configuration have a one-to-one relationship, but they serve a different purpose, so they aren't merged into a single class. A `@ConstraintConfiguration` class can extend a parent `@ConstraintConfiguration` class, which can be useful in international use cases with many regional constraints. Add the constraint configuration on the planning solution and annotate that field or property with `@ConstraintConfigurationProvider`: [source,java,options=""nowrap""] ---- @PlanningSolution public class ConferenceSolution { @ConstraintConfigurationProvider private ConferenceConstraintConfiguration constraintConfiguration; ... } ---- The `@ConstraintConfigurationProvider` annotation automatically exposes the constraint configuration as a xref:planner-configuration/planner-configuration.adoc#problemFacts[problem fact], there is no need to add a `@ProblemFactProperty` annotation. The constraint configuration class holds the <>, but it can also hold constraint parameters. For example in conference scheduling, the minimum pause constraint has a constraint weight (like any other constraint), but it also has a constraint parameter that defines the length of the minimum pause between two talks of the same speaker. That pause length depends on the conference (= the planning problem): in some big conferences 20 minutes isn't enough to go from one room to the other. That pause length is a field in the constraint configuration without a `@ConstraintWeight` annotation. [[constraintWeight]] === Add a constraint weight for each constraint In the constraint configuration class, add a `@ConstraintWeight` field or property for each constraint: [source,java,options=""nowrap""] ---- @ConstraintConfiguration(constraintPackage = ""...conferencescheduling.score"") public class ConferenceConstraintConfiguration { @ConstraintWeight(""Speaker conflict"") private HardMediumSoftScore speakerConflict = HardMediumSoftScore.ofHard(10); @ConstraintWeight(""Theme track conflict"") private HardMediumSoftScore themeTrackConflict = HardMediumSoftScore.ofSoft(10); @ConstraintWeight(""Content conflict"") private HardMediumSoftScore contentConflict = HardMediumSoftScore.ofSoft(100); ... } ---- The type of the constraint weights must be the same score class as xref:planner-configuration/planner-configuration.adoc#scoreOfASolution[the planning solution's score member]. For example in conference scheduling, `ConferenceSolution.getScore()` and `ConferenceConstraintConfiguration.getSpeakerConflict()` both return a `HardMediumSoftScore`. A constraint weight cannot be null. Give each constraint weight a default value, but expose them in a UI so the business users can tweak them. The example above uses the `ofHard()`, `ofMedium()` and `ofSoft()` methods to do that. Notice how it defaults the _content conflict_ constraint as ten times more important than the _theme track conflict_ constraint. Normally, a constraint weight only uses one score level, but it's possible to use multiple score levels (at a small performance cost). Each constraint has a constraint package and a constraint name, together they form the constraint id. These connect the constraint weight with the constraint implementation. *For each constraint weight, there must be a constraint implementation with the same package and the same name.* * The `@ConstraintConfiguration` annotation has a `constraintPackage` property that defaults to the package of the constraint configuration class. Most cases with xref:drools-score-calculation/drools-score-calculation.adoc#droolsScoreCalculation[Drools score calculation], need to override that because the DRLs use another package. For example, the DRL below uses the package `...conferencescheduling.score`, so the constraint configuration above specifies a `constraintPackage`. Cases with xref:constraint-streams/constraint-streams.adoc#constraintStreams[Constraint streams], normally don't need to specify it. * The `@ConstraintWeight` annotation has a `value` which is the constraint name (for example ""Speaker conflict""). It inherits the constraint package from the `@ConstraintConfiguration`, but it can override that, for example `@ConstraintWeight(constraintPackage = ""...region.france"", ...)` to use a different constraint package than some of the other weights. So every constraint weight ends up with a constraint package and a constraint name. Each constraint weight links with a constraint implementation, for example in xref:drools-score-calculation/drools-score-calculation.adoc#droolsScoreCalculation[Drools score calculation]: [source,options=""nowrap""] ---- package ...conferencescheduling.solver; rule ""Speaker conflict"" when ... then scoreHolder.penalize(kcontext); end rule ""Theme track conflict"" when ... then scoreHolder.penalize(kcontext, ...); end rule ""Content conflict"" when ... then scoreHolder.penalize(kcontext, ...); end ---- Each of the constraint weights defines the score level and score weight of their constraint. The constraint implementation calls `reward()` or `penalize()` and the constraint weight is automatically applied. If the constraint implementation provides a match weight, that *match weight is multiplied with the constraint weight*. For example, the _content conflict_ constraint weight defaults to `100soft` and the constraint implementation penalizes each match based on the number of shared content tags: [source,java,options=""nowrap""] ---- @ConstraintWeight(""Content conflict"") private HardMediumSoftScore contentConflict = HardMediumSoftScore.ofSoft(100); ---- [source,options=""nowrap""] ---- rule ""Content conflict"" when $talk1 : Talk(...) $talk2 : Talk(...) then scoreHolder.penalize(kcontext, $talk2.overlappingContentCount($talk1)); end ---- So when 2 overlapping talks share only 1 content tag, the score is impacted by `-100soft`. But when 2 overlapping talks share 3 content tags, the match weight is `3`, so the score is impacted by `-300soft`. [[explainingTheScore]] == Explaining the score: which constraints are broken? The easiest way to explain the score during development is to print the return value of `explainScore()`, but only use that method for diagnostic purposes: [source,java,options=""nowrap""] ---- System.out.println(scoreManager.explainScore(solution)); ---- For example in conference scheduling, this prints that talk `S51` is responsible for breaking the hard constraint `Speaker required room tag`: ---- Explanation of score (-1hard/-806soft): Constraint match totals: -1hard: constraint (Speaker required room tag) has 1 matches: -1hard: justifications ([S51]) -340soft: constraint (Theme track conflict) has 32 matches: -20soft: justifications ([S68, S66]) -20soft: justifications ([S61, S44]) ... ... Indictments (top 5 of 72): -1hard/-22soft: justification (S51) has 12 matches: -1hard: constraint (Speaker required room tag) -10soft: constraint (Theme track conflict) ... ... ---- [IMPORTANT] ==== Do not attempt to parse this string or use it in your UI or exposed services. Instead use the ConstraintMatch API below and do it properly. ==== [[usingScoreCalculationOutsideTheSolver]] === Using score calculation outside the `Solver` If other parts of your application, for example your webUI, need to calculate the score of a solution, use the `ScoreManager` API: [source,java,options=""nowrap""] ---- ScoreManager scoreManager = ScoreManager.create(solverFactory); ScoreExplanation scoreExplanation = scoreManager.explain(cloudBalance); ---- Then use it when you need to calculate the `Score` of a solution: [source,java,options=""nowrap""] ---- HardSoftScore score = scoreExplanation.getScore(); ---- Furthermore, the `ScoreExplanation` can help explain the score through constraint match totals and/or indictments: image::score-calculation/scoreVisualization.png[align=""center""] [[constraintMatchTotal]] === Constraint match total: break down the score by constraint To break down the score per constraint, get the ``ConstraintMatchTotal``s from the ``ScoreExplanation``: [source,java,options=""nowrap""] ---- Collection> constraintMatchTotals = scoreExplanation.getConstraintMatchTotalMap().values(); for (ConstraintMatchTotal constraintMatchTotal : constraintMatchTotals) { String constraintName = constraintMatchTotal.getConstraintName(); // The score impact of that constraint HardSoftScore totalScore = constraintMatchTotal.getScore(); for (ConstraintMatch constraintMatch : constraintMatchTotal.getConstraintMatchSet()) { List justificationList = constraintMatch.getJustificationList(); HardSoftScore score = constraintMatch.getScore(); ... } } ---- Each `ConstraintMatchTotal` represents one constraint and has a part of the overall score. The sum of all the `ConstraintMatchTotal.getScore()` equals the overall score. [NOTE] ==== xref:constraint-streams/constraint-streams.adoc#constraintStreams[Constraint streams] and xref:drools-score-calculation/drools-score-calculation.adoc#droolsScoreCalculation[Drools score calculation] supports constraint matches automatically, but <> requires <>. ==== [[indictmentHeatMap]] === Indictment heat map: visualize the hot planning entities To show a heat map in the UI that highlights the planning entities and problem facts have an impact on the ``Score``, get the `Indictment` map from the ``ScoreExplanation``: [source,java,options=""nowrap""] ---- Map> indictmentMap = scoreExplanation.getIndictmentMap(); for (CloudProcess process : cloudBalance.getProcessList()) { Indictment indictment = indictmentMap.get(process); if (indictment == null) { continue; } // The score impact of that planning entity HardSoftScore totalScore = indictment.getScore(); for (ConstraintMatch constraintMatch : indictment.getConstraintMatchSet()) { String constraintName = constraintMatch.getConstraintName(); HardSoftScore score = constraintMatch.getScore(); ... } } ---- Each `Indictment` is the sum of all constraints where that justification object is involved with. The sum of all the `Indictment.getScoreTotal()` differs from the overall score, because multiple ``Indictment``s can share the same `ConstraintMatch`. [NOTE] ==== xref:constraint-streams/constraint-streams.adoc#constraintStreams[Constraint streams] and xref:drools-score-calculation/drools-score-calculation.adoc#droolsScoreCalculation[Drools score calculation] supports constraint matches automatically, but <> requires <>. ==== [[testingScoreConstraints]] == Testing score constraints It's recommended to write a unit test for each score constraint individually to check that it behaves correctly. Different score calculation types come with different tools for testing. For more, see xref:constraint-streams/constraint-streams.adoc#constraintStreamsTesting[testing Constraint Streams] or xref:drools-score-calculation/drools-score-calculation.adoc#testingDroolsConstraints[testing Drools constraints]. ",12285,False,2174.9979158824112,median "/****************************************************************************** * $Id: ogr_gensql.cpp 27044 2014-03-16 23:41:27Z rouault $ * * Project: OpenGIS Simple Features Reference Implementation * Purpose: Implements OGRGenSQLResultsLayer. * Author: Frank Warmerdam, warmerdam@pobox.com * ****************************************************************************** * Copyright (c) 2002, Frank Warmerdam * Copyright (c) 2008-2014, Even Rouault * * 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 ""swq.h"" #include ""ogr_p.h"" #include ""ogr_gensql.h"" #include ""cpl_string.h"" #include ""ogr_api.h"" #include ""cpl_time.h"" #include CPL_CVSID(""$Id: ogr_gensql.cpp 27044 2014-03-16 23:41:27Z rouault $""); class OGRGenSQLGeomFieldDefn: public OGRGeomFieldDefn { public: OGRGenSQLGeomFieldDefn(OGRGeomFieldDefn* poGeomFieldDefn) : OGRGeomFieldDefn(poGeomFieldDefn->GetNameRef(), poGeomFieldDefn->GetType()), bForceGeomType(FALSE) { SetSpatialRef(poGeomFieldDefn->GetSpatialRef()); } int bForceGeomType; }; /************************************************************************/ /* OGRGenSQLResultsLayerHasSpecialField() */ /************************************************************************/ static int OGRGenSQLResultsLayerHasSpecialField(swq_expr_node* expr, int nMinIndexForSpecialField) { if (expr->eNodeType == SNT_COLUMN) { if (expr->table_index == 0) { return expr->field_index >= nMinIndexForSpecialField && expr->field_index < nMinIndexForSpecialField + SPECIAL_FIELD_COUNT; } } else if (expr->eNodeType == SNT_OPERATION) { for( int i = 0; i < expr->nSubExprCount; i++ ) { if (OGRGenSQLResultsLayerHasSpecialField(expr->papoSubExpr[i], nMinIndexForSpecialField)) return TRUE; } } return FALSE; } /************************************************************************/ /* OGRGenSQLResultsLayer() */ /************************************************************************/ OGRGenSQLResultsLayer::OGRGenSQLResultsLayer( OGRDataSource *poSrcDS, void *pSelectInfo, OGRGeometry *poSpatFilter, const char *pszWHERE, const char *pszDialect ) { swq_select *psSelectInfo = (swq_select *) pSelectInfo; this->poSrcDS = poSrcDS; this->pSelectInfo = pSelectInfo; poDefn = NULL; poSummaryFeature = NULL; panFIDIndex = NULL; bOrderByValid = FALSE; nIndexSize = 0; nNextIndexFID = 0; nExtraDSCount = 0; papoExtraDS = NULL; panGeomFieldToSrcGeomField = NULL; /* -------------------------------------------------------------------- */ /* Identify all the layers involved in the SELECT. */ /* -------------------------------------------------------------------- */ int iTable; papoTableLayers = (OGRLayer **) CPLCalloc( sizeof(OGRLayer *), psSelectInfo->table_count ); for( iTable = 0; iTable < psSelectInfo->table_count; iTable++ ) { swq_table_def *psTableDef = psSelectInfo->table_defs + iTable; OGRDataSource *poTableDS = poSrcDS; if( psTableDef->data_source != NULL ) { OGRSFDriverRegistrar *poReg=OGRSFDriverRegistrar::GetRegistrar(); poTableDS = poReg->OpenShared( psTableDef->data_source, FALSE, NULL ); if( poTableDS == NULL ) { if( strlen(CPLGetLastErrorMsg()) == 0 ) CPLError( CE_Failure, CPLE_AppDefined, ""Unable to open secondary datasource\\n"" ""`%s' required by JOIN."", psTableDef->data_source ); return; } papoExtraDS = (OGRDataSource **) CPLRealloc( papoExtraDS, sizeof(void*) * ++nExtraDSCount ); papoExtraDS[nExtraDSCount-1] = poTableDS; } papoTableLayers[iTable] = poTableDS->GetLayerByName( psTableDef->table_name ); CPLAssert( papoTableLayers[iTable] != NULL ); if( papoTableLayers[iTable] == NULL ) return; } poSrcLayer = papoTableLayers[0]; /* -------------------------------------------------------------------- */ /* If the user has explicitely requested a OGRSQL dialect, then */ /* we should avoid to forward the where clause to the source layer */ /* when there is a risk it cannot understand it (#4022) */ /* -------------------------------------------------------------------- */ int bForwardWhereToSourceLayer = TRUE; if( pszWHERE ) { if( psSelectInfo->where_expr && pszDialect != NULL && EQUAL(pszDialect, ""OGRSQL"") ) { int nMinIndexForSpecialField = poSrcLayer->GetLayerDefn()->GetFieldCount(); bForwardWhereToSourceLayer = !OGRGenSQLResultsLayerHasSpecialField (psSelectInfo->where_expr, nMinIndexForSpecialField); } if (bForwardWhereToSourceLayer) this->pszWHERE = CPLStrdup(pszWHERE); else this->pszWHERE = NULL; } else this->pszWHERE = NULL; /* -------------------------------------------------------------------- */ /* Prepare a feature definition based on the query. */ /* -------------------------------------------------------------------- */ OGRFeatureDefn *poSrcDefn = poSrcLayer->GetLayerDefn(); poDefn = new OGRFeatureDefn( psSelectInfo->table_defs[0].table_alias ); poDefn->SetGeomType(wkbNone); poDefn->Reference(); iFIDFieldIndex = poSrcDefn->GetFieldCount(); /* + 1 since we can add an implicit geometry field */ panGeomFieldToSrcGeomField = (int*) CPLMalloc(sizeof(int) * (1 + psSelectInfo->result_columns)); for( int iField = 0; iField < psSelectInfo->result_columns; iField++ ) { swq_col_def *psColDef = psSelectInfo->column_defs + iField; OGRFieldDefn oFDefn( """", OFTInteger ); OGRGeomFieldDefn oGFDefn( """", wkbUnknown ); OGRFieldDefn *poSrcFDefn = NULL; OGRGeomFieldDefn *poSrcGFDefn = NULL; int bIsGeometry = FALSE; OGRFeatureDefn *poLayerDefn = NULL; int iSrcGeomField = -1; if( psColDef->table_index != -1 ) poLayerDefn = papoTableLayers[psColDef->table_index]->GetLayerDefn(); if( psColDef->field_index > -1 && poLayerDefn != NULL && psColDef->field_index < poLayerDefn->GetFieldCount() ) { poSrcFDefn = poLayerDefn->GetFieldDefn(psColDef->field_index); } if( poLayerDefn != NULL && IS_GEOM_FIELD_INDEX(poLayerDefn, psColDef->field_index) ) { bIsGeometry = TRUE; iSrcGeomField = ALL_FIELD_INDEX_TO_GEOM_FIELD_INDEX(poLayerDefn, psColDef->field_index); poSrcGFDefn = poLayerDefn->GetGeomFieldDefn(iSrcGeomField); } if( psColDef->target_type == SWQ_GEOMETRY ) bIsGeometry = TRUE; if( psColDef->col_func == SWQCF_COUNT ) bIsGeometry = FALSE; if( strlen(psColDef->field_name) == 0 && !bIsGeometry ) { CPLFree( psColDef->field_name ); psColDef->field_name = (char *) CPLMalloc(40); sprintf( psColDef->field_name, ""FIELD_%d"", poDefn->GetFieldCount()+1 ); } if( psColDef->field_alias != NULL ) { if( bIsGeometry ) oGFDefn.SetName(psColDef->field_alias); else oFDefn.SetName(psColDef->field_alias); } else if( psColDef->col_func != SWQCF_NONE ) { const swq_operation *op = swq_op_registrar::GetOperator( (swq_op) psColDef->col_func ); oFDefn.SetName( CPLSPrintf( ""%s_%s"", op->pszName, psColDef->field_name ) ); } else { if( bIsGeometry ) oGFDefn.SetName(psColDef->field_name); else oFDefn.SetName( psColDef->field_name ); } if( psColDef->col_func == SWQCF_COUNT ) oFDefn.SetType( OFTInteger ); else if( poSrcFDefn != NULL ) { if( psColDef->col_func != SWQCF_AVG || psColDef->field_type == SWQ_DATE || psColDef->field_type == SWQ_TIME || psColDef->field_type == SWQ_TIMESTAMP ) oFDefn.SetType( poSrcFDefn->GetType() ); else oFDefn.SetType( OFTReal ); if( psColDef->col_func != SWQCF_AVG && psColDef->col_func != SWQCF_SUM ) { oFDefn.SetWidth( poSrcFDefn->GetWidth() ); oFDefn.SetPrecision( poSrcFDefn->GetPrecision() ); } } else if( poSrcGFDefn != NULL ) { oGFDefn.SetType( poSrcGFDefn->GetType() ); oGFDefn.SetSpatialRef( poSrcGFDefn->GetSpatialRef() ); } else if ( psColDef->field_index >= iFIDFieldIndex ) { switch ( SpecialFieldTypes[psColDef->field_index-iFIDFieldIndex] ) { case SWQ_INTEGER: oFDefn.SetType( OFTInteger ); break; case SWQ_FLOAT: oFDefn.SetType( OFTReal ); break; default: oFDefn.SetType( OFTString ); break; } } else { switch( psColDef->field_type ) { case SWQ_INTEGER: case SWQ_BOOLEAN: oFDefn.SetType( OFTInteger ); break; case SWQ_FLOAT: oFDefn.SetType( OFTReal ); break; default: oFDefn.SetType( OFTString ); break; } } /* setting up the target_type */ switch (psColDef->target_type) { case SWQ_OTHER: break; case SWQ_INTEGER: case SWQ_BOOLEAN: oFDefn.SetType( OFTInteger ); break; case SWQ_FLOAT: oFDefn.SetType( OFTReal ); break; case SWQ_STRING: oFDefn.SetType( OFTString ); break; case SWQ_TIMESTAMP: oFDefn.SetType( OFTDateTime ); break; case SWQ_DATE: oFDefn.SetType( OFTDate ); break; case SWQ_TIME: oFDefn.SetType( OFTTime ); break; case SWQ_GEOMETRY: break; default: CPLAssert( FALSE ); oFDefn.SetType( OFTString ); break; } if (psColDef->field_length > 0) { oFDefn.SetWidth( psColDef->field_length ); } if (psColDef->field_precision >= 0) { oFDefn.SetPrecision( psColDef->field_precision ); } if( bIsGeometry ) { panGeomFieldToSrcGeomField[poDefn->GetGeomFieldCount()] = iSrcGeomField; /* Hack while drivers haven't been updated so that */ /* poSrcDefn->GetGeomFieldDefn(0)->GetSpatialRef() == poSrcLayer->GetSpatialRef() */ if( iSrcGeomField == 0 && poSrcDefn->GetGeomFieldCount() == 1 && oGFDefn.GetSpatialRef() == NULL ) { oGFDefn.SetSpatialRef(poSrcLayer->GetSpatialRef()); } int bForceGeomType = FALSE; if( psColDef->eGeomType != wkbUnknown ) { oGFDefn.SetType( psColDef->eGeomType ); bForceGeomType = TRUE; } if( psColDef->nSRID > 0 ) { OGRSpatialReference* poSRS = new OGRSpatialReference(); if( poSRS->importFromEPSG( psColDef->nSRID ) == OGRERR_NONE ) { oGFDefn.SetSpatialRef( poSRS ); } poSRS->Release(); } OGRGenSQLGeomFieldDefn* poMyGeomFieldDefn = new OGRGenSQLGeomFieldDefn(&oGFDefn); poMyGeomFieldDefn->bForceGeomType = bForceGeomType; poDefn->AddGeomFieldDefn( poMyGeomFieldDefn, FALSE ); } else poDefn->AddFieldDefn( &oFDefn ); } /* -------------------------------------------------------------------- */ /* Add implicit geometry field. */ /* -------------------------------------------------------------------- */ if( psSelectInfo->query_mode == SWQM_RECORDSET && poDefn->GetGeomFieldCount() == 0 && poSrcDefn->GetGeomFieldCount() == 1 ) { psSelectInfo->result_columns++; psSelectInfo->column_defs = (swq_col_def *) CPLRealloc( psSelectInfo->column_defs, sizeof(swq_col_def) * psSelectInfo->result_columns ); swq_col_def *col_def = psSelectInfo->column_defs + psSelectInfo->result_columns - 1; memset( col_def, 0, sizeof(swq_col_def) ); const char* pszName = poSrcDefn->GetGeomFieldDefn(0)->GetNameRef(); if( *pszName != '\\0' ) col_def->field_name = CPLStrdup( pszName ); else col_def->field_name = CPLStrdup( OGR_GEOMETRY_DEFAULT_NON_EMPTY_NAME ); col_def->field_alias = NULL; col_def->table_index = 0; col_def->field_index = GEOM_FIELD_INDEX_TO_ALL_FIELD_INDEX(poSrcDefn, 0); col_def->field_type = SWQ_GEOMETRY; col_def->target_type = SWQ_GEOMETRY; panGeomFieldToSrcGeomField[poDefn->GetGeomFieldCount()] = 0; OGRGenSQLGeomFieldDefn* poMyGeomFieldDefn = new OGRGenSQLGeomFieldDefn(poSrcDefn->GetGeomFieldDefn(0)); poDefn->AddGeomFieldDefn( poMyGeomFieldDefn, FALSE ); /* Hack while drivers haven't been updated so that */ /* poSrcDefn->GetGeomFieldDefn(0)->GetSpatialRef() == poSrcLayer->GetSpatialRef() */ if( poSrcDefn->GetGeomFieldDefn(0)->GetSpatialRef() == NULL ) { poDefn->GetGeomFieldDefn(0)->SetSpatialRef(poSrcLayer->GetSpatialRef()); } } /* -------------------------------------------------------------------- */ /* Now that we have poSrcLayer, we can install a spatial filter */ /* if there is one. */ /* -------------------------------------------------------------------- */ if( poSpatFilter != NULL ) SetSpatialFilter( 0, poSpatFilter ); ResetReading(); FindAndSetIgnoredFields(); if( !bForwardWhereToSourceLayer ) SetAttributeFilter( pszWHERE ); } /************************************************************************/ /* ~OGRGenSQLResultsLayer() */ /************************************************************************/ OGRGenSQLResultsLayer::~OGRGenSQLResultsLayer() { if( m_nFeaturesRead > 0 && poDefn != NULL ) { CPLDebug( ""GenSQL"", ""%d features read on layer '%s'."", (int) m_nFeaturesRead, poDefn->GetName() ); } ClearFilters(); /* -------------------------------------------------------------------- */ /* Free various datastructures. */ /* -------------------------------------------------------------------- */ CPLFree( papoTableLayers ); papoTableLayers = NULL; CPLFree( panFIDIndex ); CPLFree( panGeomFieldToSrcGeomField ); delete poSummaryFeature; delete (swq_select *) pSelectInfo; if( poDefn != NULL ) { poDefn->Release(); } /* -------------------------------------------------------------------- */ /* Release any additional datasources being used in joins. */ /* -------------------------------------------------------------------- */ OGRSFDriverRegistrar *poReg=OGRSFDriverRegistrar::GetRegistrar(); for( int iEDS = 0; iEDS < nExtraDSCount; iEDS++ ) poReg->ReleaseDataSource( papoExtraDS[iEDS] ); CPLFree( papoExtraDS ); CPLFree( pszWHERE ); } /************************************************************************/ /* ClearFilters() */ /* */ /* Clear up all filters currently in place on the target layer, */ /* and joined layers. We try not to leave them installed */ /* except when actively fetching features. */ /************************************************************************/ void OGRGenSQLResultsLayer::ClearFilters() { /* -------------------------------------------------------------------- */ /* Clear any filters installed on the target layer. */ /* -------------------------------------------------------------------- */ if( poSrcLayer != NULL ) { poSrcLayer->SetAttributeFilter( """" ); poSrcLayer->SetSpatialFilter( NULL ); } /* -------------------------------------------------------------------- */ /* Clear any attribute filter installed on the joined layers. */ /* -------------------------------------------------------------------- */ swq_select *psSelectInfo = (swq_select *) pSelectInfo; int iJoin; if( psSelectInfo != NULL ) { for( iJoin = 0; iJoin < psSelectInfo->join_count; iJoin++ ) { swq_join_def *psJoinInfo = psSelectInfo->join_defs + iJoin; OGRLayer *poJoinLayer = papoTableLayers[psJoinInfo->secondary_table]; poJoinLayer->SetAttributeFilter( """" ); } } /* -------------------------------------------------------------------- */ /* Clear any ignored field lists installed on source layers */ /* -------------------------------------------------------------------- */ if( psSelectInfo != NULL ) { for( int iTable = 0; iTable < psSelectInfo->table_count; iTable++ ) { OGRLayer* poLayer = papoTableLayers[iTable]; poLayer->SetIgnoredFields(NULL); } } } /************************************************************************/ /* MustEvaluateSpatialFilterOnGenSQL() */ /************************************************************************/ int OGRGenSQLResultsLayer::MustEvaluateSpatialFilterOnGenSQL() { int bEvaluateSpatialFilter = FALSE; if( m_poFilterGeom != NULL && m_iGeomFieldFilter >= 0 && m_iGeomFieldFilter < GetLayerDefn()->GetGeomFieldCount() ) { int iSrcGeomField = panGeomFieldToSrcGeomField[m_iGeomFieldFilter]; if( iSrcGeomField < 0 ) bEvaluateSpatialFilter = TRUE; } return bEvaluateSpatialFilter; } /************************************************************************/ /* ApplyFiltersToSource() */ /************************************************************************/ void OGRGenSQLResultsLayer::ApplyFiltersToSource() { poSrcLayer->SetAttributeFilter( pszWHERE ); if( m_iGeomFieldFilter >= 0 && m_iGeomFieldFilter < GetLayerDefn()->GetGeomFieldCount() ) { int iSrcGeomField = panGeomFieldToSrcGeomField[m_iGeomFieldFilter]; if( iSrcGeomField >= 0 ) poSrcLayer->SetSpatialFilter( iSrcGeomField, m_poFilterGeom ); } poSrcLayer->ResetReading(); } /************************************************************************/ /* ResetReading() */ /************************************************************************/ void OGRGenSQLResultsLayer::ResetReading() { swq_select *psSelectInfo = (swq_select *) pSelectInfo; if( psSelectInfo->query_mode == SWQM_RECORDSET ) { ApplyFiltersToSource(); } nNextIndexFID = 0; } /************************************************************************/ /* SetNextByIndex() */ /* */ /* If we already have an FID list, we can easily resposition */ /* ourselves in it. */ /************************************************************************/ OGRErr OGRGenSQLResultsLayer::SetNextByIndex( long nIndex ) { swq_select *psSelectInfo = (swq_select *) pSelectInfo; CreateOrderByIndex(); if( psSelectInfo->query_mode == SWQM_SUMMARY_RECORD || psSelectInfo->query_mode == SWQM_DISTINCT_LIST || panFIDIndex != NULL ) { nNextIndexFID = nIndex; return OGRERR_NONE; } else { return poSrcLayer->SetNextByIndex( nIndex ); } } /************************************************************************/ /* GetExtent() */ /************************************************************************/ OGRErr OGRGenSQLResultsLayer::GetExtent( int iGeomField, OGREnvelope *psExtent, int bForce ) { swq_select *psSelectInfo = (swq_select *) pSelectInfo; if( iGeomField < 0 || iGeomField >= GetLayerDefn()->GetGeomFieldCount() || GetLayerDefn()->GetGeomFieldDefn(iGeomField)->GetType() == wkbNone ) { if( iGeomField != 0 ) { CPLError(CE_Failure, CPLE_AppDefined, ""Invalid geometry field index : %d"", iGeomField); } return OGRERR_FAILURE; } if( psSelectInfo->query_mode == SWQM_RECORDSET ) { int iSrcGeomField = panGeomFieldToSrcGeomField[iGeomField]; if( iSrcGeomField >= 0 ) return poSrcLayer->GetExtent( iSrcGeomField, psExtent, bForce ); else if( iGeomField == 0 ) return OGRLayer::GetExtent( psExtent, bForce ); else return OGRLayer::GetExtent( iGeomField, psExtent, bForce ); } else return OGRERR_FAILURE; } /************************************************************************/ /* GetFeatureCount() */ /************************************************************************/ int OGRGenSQLResultsLayer::GetFeatureCount( int bForce ) { swq_select *psSelectInfo = (swq_select *) pSelectInfo; CreateOrderByIndex(); if( psSelectInfo->query_mode == SWQM_DISTINCT_LIST ) { if( !PrepareSummary() ) return 0; swq_summary *psSummary = psSelectInfo->column_summary + 0; if( psSummary == NULL ) return 0; return psSummary->count; } else if( psSelectInfo->query_mode != SWQM_RECORDSET ) return 1; else if( m_poAttrQuery == NULL && !MustEvaluateSpatialFilterOnGenSQL() ) return poSrcLayer->GetFeatureCount( bForce ); else return OGRLayer::GetFeatureCount( bForce ); } /************************************************************************/ /* TestCapability() */ /************************************************************************/ int OGRGenSQLResultsLayer::TestCapability( const char *pszCap ) { swq_select *psSelectInfo = (swq_select *) pSelectInfo; if( EQUAL(pszCap,OLCFastSetNextByIndex) ) { if( psSelectInfo->query_mode == SWQM_SUMMARY_RECORD || psSelectInfo->query_mode == SWQM_DISTINCT_LIST || panFIDIndex != NULL ) return TRUE; else return poSrcLayer->TestCapability( pszCap ); } if( psSelectInfo->query_mode == SWQM_RECORDSET && (EQUAL(pszCap,OLCFastFeatureCount) || EQUAL(pszCap,OLCRandomRead) || EQUAL(pszCap,OLCFastGetExtent)) ) return poSrcLayer->TestCapability( pszCap ); else if( psSelectInfo->query_mode != SWQM_RECORDSET ) { if( EQUAL(pszCap,OLCFastFeatureCount) ) return TRUE; } return FALSE; } /************************************************************************/ /* ContainGeomSpecialField() */ /************************************************************************/ int OGRGenSQLResultsLayer::ContainGeomSpecialField(swq_expr_node* expr) { if (expr->eNodeType == SNT_COLUMN) { if( expr->table_index == 0 && expr->field_index != -1 ) { OGRLayer* poLayer = papoTableLayers[expr->table_index]; int nSpecialFieldIdx = expr->field_index - poLayer->GetLayerDefn()->GetFieldCount(); if( nSpecialFieldIdx == SPF_OGR_GEOMETRY || nSpecialFieldIdx == SPF_OGR_GEOM_WKT || nSpecialFieldIdx == SPF_OGR_GEOM_AREA ) return TRUE; if( expr->field_index == GEOM_FIELD_INDEX_TO_ALL_FIELD_INDEX(poLayer->GetLayerDefn(), 0) ) return TRUE; return FALSE; } } else if (expr->eNodeType == SNT_OPERATION) { for( int i = 0; i < expr->nSubExprCount; i++ ) { if (ContainGeomSpecialField(expr->papoSubExpr[i])) return TRUE; } } return FALSE; } /************************************************************************/ /* PrepareSummary() */ /************************************************************************/ int OGRGenSQLResultsLayer::PrepareSummary() { swq_select *psSelectInfo = (swq_select *) pSelectInfo; if( poSummaryFeature != NULL ) return TRUE; poSummaryFeature = new OGRFeature( poDefn ); poSummaryFeature->SetFID( 0 ); /* -------------------------------------------------------------------- */ /* Ensure our query parameters are in place on the source */ /* layer. And initialize reading. */ /* -------------------------------------------------------------------- */ ApplyFiltersToSource(); /* -------------------------------------------------------------------- */ /* Ignore geometry reading if no spatial filter in place and that */ /* the where clause and no column references OGR_GEOMETRY, */ /* OGR_GEOM_WKT or OGR_GEOM_AREA special fields. */ /* -------------------------------------------------------------------- */ int bSaveIsGeomIgnored = poSrcLayer->GetLayerDefn()->IsGeometryIgnored(); if ( m_poFilterGeom == NULL && ( psSelectInfo->where_expr == NULL || !ContainGeomSpecialField(psSelectInfo->where_expr) ) ) { int bFoundGeomExpr = FALSE; for( int iField = 0; iField < psSelectInfo->result_columns; iField++ ) { swq_col_def *psColDef = psSelectInfo->column_defs + iField; if (psColDef->table_index == 0 && psColDef->field_index != -1) { OGRLayer* poLayer = papoTableLayers[psColDef->table_index]; int nSpecialFieldIdx = psColDef->field_index - poLayer->GetLayerDefn()->GetFieldCount(); if (nSpecialFieldIdx == SPF_OGR_GEOMETRY || nSpecialFieldIdx == SPF_OGR_GEOM_WKT || nSpecialFieldIdx == SPF_OGR_GEOM_AREA) { bFoundGeomExpr = TRUE; break; } if( psColDef->field_index == GEOM_FIELD_INDEX_TO_ALL_FIELD_INDEX(poLayer->GetLayerDefn(), 0) ) { bFoundGeomExpr = TRUE; break; } } if (psColDef->expr != NULL && ContainGeomSpecialField(psColDef->expr)) { bFoundGeomExpr = TRUE; break; } } if (!bFoundGeomExpr) poSrcLayer->GetLayerDefn()->SetGeometryIgnored(TRUE); } /* -------------------------------------------------------------------- */ /* We treat COUNT(*) as a special case, and fill with */ /* GetFeatureCount(). */ /* -------------------------------------------------------------------- */ if( psSelectInfo->result_columns == 1 && psSelectInfo->column_defs[0].col_func == SWQCF_COUNT && psSelectInfo->column_defs[0].field_index < 0 ) { poSummaryFeature->SetField( 0, poSrcLayer->GetFeatureCount( TRUE ) ); poSrcLayer->GetLayerDefn()->SetGeometryIgnored(bSaveIsGeomIgnored); return TRUE; } /* -------------------------------------------------------------------- */ /* Otherwise, process all source feature through the summary */ /* building facilities of SWQ. */ /* -------------------------------------------------------------------- */ const char *pszError; OGRFeature *poSrcFeature; int iField; while( (poSrcFeature = poSrcLayer->GetNextFeature()) != NULL ) { for( iField = 0; iField < psSelectInfo->result_columns; iField++ ) { swq_col_def *psColDef = psSelectInfo->column_defs + iField; if (psColDef->col_func == SWQCF_COUNT) { /* psColDef->field_index can be -1 in the case of a COUNT(*) */ if (psColDef->field_index < 0) pszError = swq_select_summarize( psSelectInfo, iField, """" ); else if (IS_GEOM_FIELD_INDEX(poSrcLayer->GetLayerDefn(), psColDef->field_index) ) { int iSrcGeomField = ALL_FIELD_INDEX_TO_GEOM_FIELD_INDEX( poSrcLayer->GetLayerDefn(), psColDef->field_index); OGRGeometry* poGeom = poSrcFeature->GetGeomFieldRef(iSrcGeomField); if( poGeom != NULL ) pszError = swq_select_summarize( psSelectInfo, iField, """" ); else pszError = NULL; } else if (poSrcFeature->IsFieldSet(psColDef->field_index)) pszError = swq_select_summarize( psSelectInfo, iField, poSrcFeature->GetFieldAsString( psColDef->field_index ) ); else pszError = NULL; } else { const char* pszVal = NULL; if (poSrcFeature->IsFieldSet(psColDef->field_index)) pszVal = poSrcFeature->GetFieldAsString( psColDef->field_index ); pszError = swq_select_summarize( psSelectInfo, iField, pszVal ); } if( pszError != NULL ) { delete poSrcFeature; delete poSummaryFeature; poSummaryFeature = NULL; poSrcLayer->GetLayerDefn()->SetGeometryIgnored(bSaveIsGeomIgnored); CPLError( CE_Failure, CPLE_AppDefined, ""%s"", pszError ); return FALSE; } } delete poSrcFeature; } poSrcLayer->GetLayerDefn()->SetGeometryIgnored(bSaveIsGeomIgnored); pszError = swq_select_finish_summarize( psSelectInfo ); if( pszError != NULL ) { delete poSummaryFeature; poSummaryFeature = NULL; CPLError( CE_Failure, CPLE_AppDefined, ""%s"", pszError ); return FALSE; } /* -------------------------------------------------------------------- */ /* If we have run out of features on the source layer, clear */ /* away the filters we have installed till a next run through */ /* the features. */ /* -------------------------------------------------------------------- */ if( poSrcFeature == NULL ) ClearFilters(); /* -------------------------------------------------------------------- */ /* Now apply the values to the summary feature. If we are in */ /* DISTINCT_LIST mode we don't do this step. */ /* -------------------------------------------------------------------- */ if( psSelectInfo->query_mode == SWQM_SUMMARY_RECORD ) { for( iField = 0; iField < psSelectInfo->result_columns; iField++ ) { swq_col_def *psColDef = psSelectInfo->column_defs + iField; if (psSelectInfo->column_summary != NULL) { swq_summary *psSummary = psSelectInfo->column_summary + iField; if( psColDef->col_func == SWQCF_AVG ) { if( psColDef->field_type == SWQ_DATE || psColDef->field_type == SWQ_TIME || psColDef->field_type == SWQ_TIMESTAMP) { struct tm brokendowntime; CPLUnixTimeToYMDHMS((GIntBig)(psSummary->sum / psSummary->count), &brokendowntime); poSummaryFeature->SetField( iField, brokendowntime.tm_year + 1900, brokendowntime.tm_mon + 1, brokendowntime.tm_mday, brokendowntime.tm_hour, brokendowntime.tm_min, brokendowntime.tm_sec, 0); } else poSummaryFeature->SetField( iField, psSummary->sum / psSummary->count ); } else if( psColDef->col_func == SWQCF_MIN ) { if( psColDef->field_type == SWQ_DATE || psColDef->field_type == SWQ_TIME || psColDef->field_type == SWQ_TIMESTAMP) poSummaryFeature->SetField( iField, psSummary->szMin ); else poSummaryFeature->SetField( iField, psSummary->min ); } else if( psColDef->col_func == SWQCF_MAX ) { if( psColDef->field_type == SWQ_DATE || psColDef->field_type == SWQ_TIME || psColDef->field_type == SWQ_TIMESTAMP) poSummaryFeature->SetField( iField, psSummary->szMax ); else poSummaryFeature->SetField( iField, psSummary->max ); } else if( psColDef->col_func == SWQCF_COUNT ) poSummaryFeature->SetField( iField, psSummary->count ); else if( psColDef->col_func == SWQCF_SUM ) poSummaryFeature->SetField( iField, psSummary->sum ); } else if ( psColDef->col_func == SWQCF_COUNT ) poSummaryFeature->SetField( iField, 0 ); } } return TRUE; } /************************************************************************/ /* OGRMultiFeatureFetcher() */ /************************************************************************/ static swq_expr_node *OGRMultiFeatureFetcher( swq_expr_node *op, void *pFeatureList ) { std::vector *papoFeatures = (std::vector *) pFeatureList; OGRFeature *poFeature; swq_expr_node *poRetNode = NULL; CPLAssert( op->eNodeType == SNT_COLUMN ); /* -------------------------------------------------------------------- */ /* What feature are we using? The primary or one of the joined ones?*/ /* -------------------------------------------------------------------- */ if( op->table_index < 0 || op->table_index >= (int)papoFeatures->size() ) { CPLError( CE_Failure, CPLE_AppDefined, ""Request for unexpected table_index (%d) in field fetcher."", op->table_index ); return NULL; } poFeature = (*papoFeatures)[op->table_index]; /* -------------------------------------------------------------------- */ /* Fetch the value. */ /* -------------------------------------------------------------------- */ switch( op->field_type ) { case SWQ_INTEGER: case SWQ_BOOLEAN: if( poFeature == NULL || !poFeature->IsFieldSet(op->field_index) ) { poRetNode = new swq_expr_node(0); poRetNode->is_null = TRUE; } else poRetNode = new swq_expr_node( poFeature->GetFieldAsInteger(op->field_index) ); break; case SWQ_FLOAT: if( poFeature == NULL || !poFeature->IsFieldSet(op->field_index) ) { poRetNode = new swq_expr_node( 0.0 ); poRetNode->is_null = TRUE; } else poRetNode = new swq_expr_node( poFeature->GetFieldAsDouble(op->field_index) ); break; case SWQ_GEOMETRY: if( poFeature == NULL ) { poRetNode = new swq_expr_node( (OGRGeometry*) NULL ); } else { int iSrcGeomField = ALL_FIELD_INDEX_TO_GEOM_FIELD_INDEX( poFeature->GetDefnRef(), op->field_index); poRetNode = new swq_expr_node( poFeature->GetGeomFieldRef(iSrcGeomField) ); } break; default: if( poFeature == NULL || !poFeature->IsFieldSet(op->field_index) ) { poRetNode = new swq_expr_node(""""); poRetNode->is_null = TRUE; } else poRetNode = new swq_expr_node( poFeature->GetFieldAsString(op->field_index) ); break; } return poRetNode; } /************************************************************************/ /* TranslateFeature() */ /************************************************************************/ OGRFeature *OGRGenSQLResultsLayer::TranslateFeature( OGRFeature *poSrcFeat ) { swq_select *psSelectInfo = (swq_select *) pSelectInfo; OGRFeature *poDstFeat; std::vector apoFeatures; if( poSrcFeat == NULL ) return NULL; m_nFeaturesRead++; apoFeatures.push_back( poSrcFeat ); /* -------------------------------------------------------------------- */ /* Fetch the corresponding features from any jointed tables. */ /* -------------------------------------------------------------------- */ int iJoin; for( iJoin = 0; iJoin < psSelectInfo->join_count; iJoin++ ) { CPLString osFilter; swq_join_def *psJoinInfo = psSelectInfo->join_defs + iJoin; /* OGRMultiFeatureFetcher assumes that the features are pushed in */ /* apoFeatures with increasing secondary_table, so make sure */ /* we have taken care of this */ CPLAssert(psJoinInfo->secondary_table == iJoin + 1); OGRLayer *poJoinLayer = papoTableLayers[psJoinInfo->secondary_table]; // if source key is null, we can't do join. if( !poSrcFeat->IsFieldSet( psJoinInfo->primary_field ) ) { apoFeatures.push_back( NULL ); continue; } OGRFieldDefn* poSecondaryFieldDefn = poJoinLayer->GetLayerDefn()->GetFieldDefn( psJoinInfo->secondary_field ); OGRFieldType ePrimaryFieldType = poSrcLayer->GetLayerDefn()-> GetFieldDefn(psJoinInfo->primary_field )->GetType(); OGRFieldType eSecondaryFieldType = poSecondaryFieldDefn->GetType(); // Prepare attribute query to express fetching on the joined variable // If joining a (primary) numeric column with a (secondary) string column // then add implicit casting of the secondary column to numeric. This behaviour // worked in GDAL < 1.8, and it is consistant with how sqlite behaves too. See #4321 // For the reverse case, joining a string column with a numeric column, the // string constant will be cast to float by SWQAutoConvertStringToNumeric (#4259) if( eSecondaryFieldType == OFTString && (ePrimaryFieldType == OFTInteger || ePrimaryFieldType == OFTReal) ) osFilter.Printf(""CAST(%s AS FLOAT) = "", poSecondaryFieldDefn->GetNameRef() ); else osFilter.Printf(""%s = "", poSecondaryFieldDefn->GetNameRef() ); OGRField *psSrcField = poSrcFeat->GetRawFieldRef(psJoinInfo->primary_field); switch( ePrimaryFieldType ) { case OFTInteger: osFilter += CPLString().Printf(""%d"", psSrcField->Integer ); break; case OFTReal: osFilter += CPLString().Printf(""%.16g"", psSrcField->Real ); break; case OFTString: { char *pszEscaped = CPLEscapeString( psSrcField->String, strlen(psSrcField->String), CPLES_SQL ); osFilter += ""'""; osFilter += pszEscaped; osFilter += ""'""; CPLFree( pszEscaped ); } break; default: CPLAssert( FALSE ); continue; } OGRFeature *poJoinFeature = NULL; poJoinLayer->ResetReading(); if( poJoinLayer->SetAttributeFilter( osFilter.c_str() ) == OGRERR_NONE ) poJoinFeature = poJoinLayer->GetNextFeature(); apoFeatures.push_back( poJoinFeature ); } /* -------------------------------------------------------------------- */ /* Create destination feature. */ /* -------------------------------------------------------------------- */ poDstFeat = new OGRFeature( poDefn ); poDstFeat->SetFID( poSrcFeat->GetFID() ); poDstFeat->SetStyleString( poSrcFeat->GetStyleString() ); /* -------------------------------------------------------------------- */ /* Evaluate fields that are complex expressions. */ /* -------------------------------------------------------------------- */ int iRegularField = 0; int iGeomField = 0; for( int iField = 0; iField < psSelectInfo->result_columns; iField++ ) { swq_col_def *psColDef = psSelectInfo->column_defs + iField; swq_expr_node *poResult; if( psColDef->field_index != -1 ) { if( psColDef->field_type == SWQ_GEOMETRY || psColDef->target_type == SWQ_GEOMETRY ) iGeomField++; else iRegularField++; continue; } poResult = psColDef->expr->Evaluate( OGRMultiFeatureFetcher, (void *) &apoFeatures ); if( poResult == NULL ) { delete poDstFeat; return NULL; } if( poResult->is_null ) { if( poResult->field_type == SWQ_GEOMETRY ) iGeomField++; else iRegularField++; delete poResult; continue; } switch( poResult->field_type ) { case SWQ_INTEGER: poDstFeat->SetField( iRegularField++, poResult->int_value ); break; case SWQ_FLOAT: poDstFeat->SetField( iRegularField++, poResult->float_value ); break; case SWQ_GEOMETRY: { OGRGenSQLGeomFieldDefn* poGeomFieldDefn = (OGRGenSQLGeomFieldDefn*) poDstFeat->GetGeomFieldDefnRef(iGeomField); if( poGeomFieldDefn->bForceGeomType && poResult->geometry_value != NULL ) { OGRwkbGeometryType eCurType = wkbFlatten(poResult->geometry_value->getGeometryType()); OGRwkbGeometryType eReqType = wkbFlatten(poGeomFieldDefn->GetType()); if( eCurType == wkbPolygon && eReqType == wkbMultiPolygon ) { poResult->geometry_value = (OGRGeometry*) OGR_G_ForceToMultiPolygon( (OGRGeometryH) poResult->geometry_value ); } else if( (eCurType == wkbMultiPolygon || eCurType == wkbGeometryCollection) && eReqType == wkbPolygon ) { poResult->geometry_value = (OGRGeometry*) OGR_G_ForceToPolygon( (OGRGeometryH) poResult->geometry_value ); } else if( eCurType == wkbLineString && eReqType == wkbMultiLineString ) { poResult->geometry_value = (OGRGeometry*) OGR_G_ForceToMultiLineString( (OGRGeometryH) poResult->geometry_value ); } else if( (eCurType == wkbMultiLineString || eCurType == wkbGeometryCollection) && eReqType == wkbLineString ) { poResult->geometry_value = (OGRGeometry*) OGR_G_ForceToLineString( (OGRGeometryH) poResult->geometry_value ); } } poDstFeat->SetGeomField( iGeomField++, poResult->geometry_value ); break; } default: poDstFeat->SetField( iRegularField++, poResult->string_value ); break; } delete poResult; } /* -------------------------------------------------------------------- */ /* Copy fields from primary record to the destination feature. */ /* -------------------------------------------------------------------- */ iRegularField = 0; iGeomField = 0; for( int iField = 0; iField < psSelectInfo->result_columns; iField++ ) { swq_col_def *psColDef = psSelectInfo->column_defs + iField; if( psColDef->table_index != 0 ) { if( psColDef->field_type == SWQ_GEOMETRY || psColDef->target_type == SWQ_GEOMETRY ) iGeomField++; else iRegularField++; continue; } if( IS_GEOM_FIELD_INDEX(poSrcFeat->GetDefnRef(), psColDef->field_index) ) { int iSrcGeomField = ALL_FIELD_INDEX_TO_GEOM_FIELD_INDEX( poSrcFeat->GetDefnRef(), psColDef->field_index); poDstFeat->SetGeomField( iGeomField ++, poSrcFeat->GetGeomFieldRef(iSrcGeomField) ); } else if( psColDef->field_index >= iFIDFieldIndex && psColDef->field_index < iFIDFieldIndex + SPECIAL_FIELD_COUNT ) { switch (SpecialFieldTypes[psColDef->field_index - iFIDFieldIndex]) { case SWQ_INTEGER: poDstFeat->SetField( iRegularField, poSrcFeat->GetFieldAsInteger(psColDef->field_index) ); break; case SWQ_FLOAT: poDstFeat->SetField( iRegularField, poSrcFeat->GetFieldAsDouble(psColDef->field_index) ); break; default: poDstFeat->SetField( iRegularField, poSrcFeat->GetFieldAsString(psColDef->field_index) ); } iRegularField ++; } else { switch (psColDef->target_type) { case SWQ_INTEGER: poDstFeat->SetField( iRegularField, poSrcFeat->GetFieldAsInteger(psColDef->field_index) ); break; case SWQ_FLOAT: poDstFeat->SetField( iRegularField, poSrcFeat->GetFieldAsDouble(psColDef->field_index) ); break; case SWQ_STRING: case SWQ_TIMESTAMP: case SWQ_DATE: case SWQ_TIME: poDstFeat->SetField( iRegularField, poSrcFeat->GetFieldAsString(psColDef->field_index) ); break; case SWQ_GEOMETRY: CPLAssert(0); break; default: poDstFeat->SetField( iRegularField, poSrcFeat->GetRawFieldRef( psColDef->field_index ) ); } iRegularField ++; } } /* -------------------------------------------------------------------- */ /* Copy values from any joined tables. */ /* -------------------------------------------------------------------- */ for( iJoin = 0; iJoin < psSelectInfo->join_count; iJoin++ ) { CPLString osFilter; swq_join_def *psJoinInfo = psSelectInfo->join_defs + iJoin; OGRFeature *poJoinFeature = apoFeatures[iJoin+1]; if( poJoinFeature == NULL ) continue; // Copy over selected field values. iRegularField = 0; for( int iField = 0; iField < psSelectInfo->result_columns; iField++ ) { swq_col_def *psColDef = psSelectInfo->column_defs + iField; if( psColDef->field_type == SWQ_GEOMETRY || psColDef->target_type == SWQ_GEOMETRY ) continue; if( psColDef->table_index == psJoinInfo->secondary_table ) poDstFeat->SetField( iRegularField, poJoinFeature->GetRawFieldRef( psColDef->field_index ) ); iRegularField ++; } delete poJoinFeature; } return poDstFeat; } /************************************************************************/ /* GetNextFeature() */ /************************************************************************/ OGRFeature *OGRGenSQLResultsLayer::GetNextFeature() { swq_select *psSelectInfo = (swq_select *) pSelectInfo; CreateOrderByIndex(); /* -------------------------------------------------------------------- */ /* Handle summary sets. */ /* -------------------------------------------------------------------- */ if( psSelectInfo->query_mode == SWQM_SUMMARY_RECORD || psSelectInfo->query_mode == SWQM_DISTINCT_LIST ) return GetFeature( nNextIndexFID++ ); int bEvaluateSpatialFilter = MustEvaluateSpatialFilterOnGenSQL(); /* -------------------------------------------------------------------- */ /* Handle ordered sets. */ /* -------------------------------------------------------------------- */ while( TRUE ) { OGRFeature *poFeature; if( panFIDIndex != NULL ) poFeature = GetFeature( nNextIndexFID++ ); else { OGRFeature *poSrcFeat = poSrcLayer->GetNextFeature(); if( poSrcFeat == NULL ) return NULL; poFeature = TranslateFeature( poSrcFeat ); delete poSrcFeat; } if( poFeature == NULL ) return NULL; if( (m_poAttrQuery == NULL || m_poAttrQuery->Evaluate( poFeature )) && (!bEvaluateSpatialFilter || FilterGeometry( poFeature->GetGeomFieldRef(m_iGeomFieldFilter) )) ) return poFeature; delete poFeature; } return NULL; } /************************************************************************/ /* GetFeature() */ /************************************************************************/ OGRFeature *OGRGenSQLResultsLayer::GetFeature( long nFID ) { swq_select *psSelectInfo = (swq_select *) pSelectInfo; CreateOrderByIndex(); /* -------------------------------------------------------------------- */ /* Handle request for summary record. */ /* -------------------------------------------------------------------- */ if( psSelectInfo->query_mode == SWQM_SUMMARY_RECORD ) { if( !PrepareSummary() || nFID != 0 || poSummaryFeature == NULL ) return NULL; else return poSummaryFeature->Clone(); } /* -------------------------------------------------------------------- */ /* Handle request for distinct list record. */ /* -------------------------------------------------------------------- */ if( psSelectInfo->query_mode == SWQM_DISTINCT_LIST ) { if( !PrepareSummary() ) return NULL; swq_summary *psSummary = psSelectInfo->column_summary + 0; if( psSummary == NULL ) return NULL; if( nFID < 0 || nFID >= psSummary->count ) return NULL; if( psSummary->distinct_list[nFID] != NULL ) poSummaryFeature->SetField( 0, psSummary->distinct_list[nFID] ); else poSummaryFeature->UnsetField( 0 ); poSummaryFeature->SetFID( nFID ); return poSummaryFeature->Clone(); } /* -------------------------------------------------------------------- */ /* Are we running in sorted mode? If so, run the fid through */ /* the index. */ /* -------------------------------------------------------------------- */ if( panFIDIndex != NULL ) { if( nFID < 0 || nFID >= nIndexSize ) return NULL; else nFID = panFIDIndex[nFID]; } /* -------------------------------------------------------------------- */ /* Handle request for random record. */ /* -------------------------------------------------------------------- */ OGRFeature *poSrcFeature = poSrcLayer->GetFeature( nFID ); OGRFeature *poResult; if( poSrcFeature == NULL ) return NULL; poResult = TranslateFeature( poSrcFeature ); poResult->SetFID( nFID ); delete poSrcFeature; return poResult; } /************************************************************************/ /* GetSpatialFilter() */ /************************************************************************/ OGRGeometry *OGRGenSQLResultsLayer::GetSpatialFilter() { return NULL; } /************************************************************************/ /* GetLayerDefn() */ /************************************************************************/ OGRFeatureDefn *OGRGenSQLResultsLayer::GetLayerDefn() { return poDefn; } /************************************************************************/ /* CreateOrderByIndex() */ /* */ /* This method is responsible for creating an index providing */ /* ordered access to the features according to the supplied */ /* ORDER BY clauses. */ /* */ /* This is accomplished by making one pass through all the */ /* eligible source features, and capturing the order by fields */ /* of all records in memory. A quick sort is then applied to */ /* this in memory copy of the order-by fields to create the */ /* required index. */ /* */ /* Keeping all the key values in memory will *not* scale up to */ /* very large input datasets. */ /************************************************************************/ void OGRGenSQLResultsLayer::CreateOrderByIndex() { swq_select *psSelectInfo = (swq_select *) pSelectInfo; OGRField *pasIndexFields; int i, nOrderItems = psSelectInfo->order_specs; long *panFIDList; if( ! (psSelectInfo->order_specs > 0 && psSelectInfo->query_mode == SWQM_RECORDSET && nOrderItems != 0 ) ) return; if( bOrderByValid ) return; bOrderByValid = TRUE; ResetReading(); /* -------------------------------------------------------------------- */ /* Allocate set of key values, and the output index. */ /* -------------------------------------------------------------------- */ int nFeaturesAlloc = 100; panFIDIndex = NULL; pasIndexFields = (OGRField *) CPLCalloc(sizeof(OGRField), nOrderItems * nFeaturesAlloc); panFIDList = (long *) CPLMalloc(sizeof(long) * nFeaturesAlloc); /* -------------------------------------------------------------------- */ /* Read in all the key values. */ /* -------------------------------------------------------------------- */ OGRFeature *poSrcFeat; nIndexSize = 0; while( (poSrcFeat = poSrcLayer->GetNextFeature()) != NULL ) { int iKey; if (nIndexSize == nFeaturesAlloc) { int nNewFeaturesAlloc = (nFeaturesAlloc * 4) / 3; OGRField* pasNewIndexFields = (OGRField *) VSIRealloc(pasIndexFields, sizeof(OGRField) * nOrderItems * nNewFeaturesAlloc); if (pasNewIndexFields == NULL) { VSIFree(pasIndexFields); VSIFree(panFIDList); nIndexSize = 0; return; } pasIndexFields = pasNewIndexFields; long* panNewFIDList = (long *) VSIRealloc(panFIDList, sizeof(long) * nNewFeaturesAlloc); if (panNewFIDList == NULL) { VSIFree(pasIndexFields); VSIFree(panFIDList); nIndexSize = 0; return; } panFIDList = panNewFIDList; memset(pasIndexFields + nFeaturesAlloc, 0, sizeof(OGRField) * nOrderItems * (nNewFeaturesAlloc - nFeaturesAlloc)); nFeaturesAlloc = nNewFeaturesAlloc; } for( iKey = 0; iKey < nOrderItems; iKey++ ) { swq_order_def *psKeyDef = psSelectInfo->order_defs + iKey; OGRFieldDefn *poFDefn; OGRField *psSrcField, *psDstField; psDstField = pasIndexFields + nIndexSize * nOrderItems + iKey; if ( psKeyDef->field_index >= iFIDFieldIndex) { if ( psKeyDef->field_index < iFIDFieldIndex + SPECIAL_FIELD_COUNT ) { switch (SpecialFieldTypes[psKeyDef->field_index - iFIDFieldIndex]) { case SWQ_INTEGER: psDstField->Integer = poSrcFeat->GetFieldAsInteger(psKeyDef->field_index); break; case SWQ_FLOAT: psDstField->Real = poSrcFeat->GetFieldAsDouble(psKeyDef->field_index); break; default: psDstField->String = CPLStrdup( poSrcFeat->GetFieldAsString(psKeyDef->field_index) ); break; } } continue; } poFDefn = poSrcLayer->GetLayerDefn()->GetFieldDefn( psKeyDef->field_index ); psSrcField = poSrcFeat->GetRawFieldRef( psKeyDef->field_index ); if( poFDefn->GetType() == OFTInteger || poFDefn->GetType() == OFTReal || poFDefn->GetType() == OFTDate || poFDefn->GetType() == OFTTime || poFDefn->GetType() == OFTDateTime) memcpy( psDstField, psSrcField, sizeof(OGRField) ); else if( poFDefn->GetType() == OFTString ) { if( poSrcFeat->IsFieldSet( psKeyDef->field_index ) ) psDstField->String = CPLStrdup( psSrcField->String ); else memcpy( psDstField, psSrcField, sizeof(OGRField) ); } } panFIDList[nIndexSize] = poSrcFeat->GetFID(); delete poSrcFeat; nIndexSize++; } //CPLDebug(""GenSQL"", ""CreateOrderByIndex() = %d features"", nIndexSize); /* -------------------------------------------------------------------- */ /* Initialize panFIDIndex */ /* -------------------------------------------------------------------- */ panFIDIndex = (long *) CPLMalloc(sizeof(long) * nIndexSize); for( i = 0; i < nIndexSize; i++ ) panFIDIndex[i] = i; /* -------------------------------------------------------------------- */ /* Quick sort the records. */ /* -------------------------------------------------------------------- */ SortIndexSection( pasIndexFields, 0, nIndexSize ); /* -------------------------------------------------------------------- */ /* Rework the FID map to map to real FIDs. */ /* -------------------------------------------------------------------- */ int bAlreadySorted = TRUE; for( i = 0; i < nIndexSize; i++ ) { if (panFIDIndex[i] != i) bAlreadySorted = FALSE; panFIDIndex[i] = panFIDList[panFIDIndex[i]]; } CPLFree( panFIDList ); /* -------------------------------------------------------------------- */ /* Free the key field values. */ /* -------------------------------------------------------------------- */ for( int iKey = 0; iKey < nOrderItems; iKey++ ) { swq_order_def *psKeyDef = psSelectInfo->order_defs + iKey; OGRFieldDefn *poFDefn; if ( psKeyDef->field_index >= iFIDFieldIndex && psKeyDef->field_index < iFIDFieldIndex + SPECIAL_FIELD_COUNT ) { /* warning: only special fields of type string should be deallocated */ if (SpecialFieldTypes[psKeyDef->field_index - iFIDFieldIndex] == SWQ_STRING) { for( i = 0; i < nIndexSize; i++ ) { OGRField *psField = pasIndexFields + iKey + i * nOrderItems; CPLFree( psField->String ); } } continue; } poFDefn = poSrcLayer->GetLayerDefn()->GetFieldDefn( psKeyDef->field_index ); if( poFDefn->GetType() == OFTString ) { for( i = 0; i < nIndexSize; i++ ) { OGRField *psField = pasIndexFields + iKey + i * nOrderItems; if( psField->Set.nMarker1 != OGRUnsetMarker || psField->Set.nMarker2 != OGRUnsetMarker ) CPLFree( psField->String ); } } } CPLFree( pasIndexFields ); /* If it is already sorted, then free than panFIDIndex array */ /* so that GetNextFeature() can call a sequential GetNextFeature() */ /* on the source array. Very usefull for layers where random access */ /* is slow. */ /* Use case: the GML result of a WFS GetFeature with a SORTBY */ if (bAlreadySorted) { CPLFree( panFIDIndex ); panFIDIndex = NULL; nIndexSize = 0; } ResetReading(); } /************************************************************************/ /* SortIndexSection() */ /* */ /* Sort the records in a section of the index. */ /************************************************************************/ void OGRGenSQLResultsLayer::SortIndexSection( OGRField *pasIndexFields, int nStart, int nEntries ) { if( nEntries < 2 ) return; swq_select *psSelectInfo = (swq_select *) pSelectInfo; int nOrderItems = psSelectInfo->order_specs; int nFirstGroup = nEntries / 2; int nFirstStart = nStart; int nSecondGroup = nEntries - nFirstGroup; int nSecondStart = nStart + nFirstGroup; int iMerge = 0; long *panMerged; SortIndexSection( pasIndexFields, nFirstStart, nFirstGroup ); SortIndexSection( pasIndexFields, nSecondStart, nSecondGroup ); panMerged = (long *) CPLMalloc( sizeof(long) * nEntries ); while( iMerge < nEntries ) { int nResult; if( nFirstGroup == 0 ) nResult = -1; else if( nSecondGroup == 0 ) nResult = 1; else nResult = Compare( pasIndexFields + panFIDIndex[nFirstStart] * nOrderItems, pasIndexFields + panFIDIndex[nSecondStart] * nOrderItems ); if( nResult < 0 ) { panMerged[iMerge++] = panFIDIndex[nSecondStart++]; nSecondGroup--; } else { panMerged[iMerge++] = panFIDIndex[nFirstStart++]; nFirstGroup--; } } /* Copy the merge list back into the main index */ memcpy( panFIDIndex + nStart, panMerged, sizeof(long) * nEntries ); CPLFree( panMerged ); } /************************************************************************/ /* Compare() */ /************************************************************************/ int OGRGenSQLResultsLayer::Compare( OGRField *pasFirstTuple, OGRField *pasSecondTuple ) { swq_select *psSelectInfo = (swq_select *) pSelectInfo; int nResult = 0, iKey; for( iKey = 0; nResult == 0 && iKey < psSelectInfo->order_specs; iKey++ ) { swq_order_def *psKeyDef = psSelectInfo->order_defs + iKey; OGRFieldDefn *poFDefn; if( psKeyDef->field_index >= iFIDFieldIndex + SPECIAL_FIELD_COUNT ) { CPLAssert( FALSE ); return 0; } else if( psKeyDef->field_index >= iFIDFieldIndex ) poFDefn = NULL; else poFDefn = poSrcLayer->GetLayerDefn()->GetFieldDefn( psKeyDef->field_index ); if( (pasFirstTuple[iKey].Set.nMarker1 == OGRUnsetMarker && pasFirstTuple[iKey].Set.nMarker2 == OGRUnsetMarker) || (pasSecondTuple[iKey].Set.nMarker1 == OGRUnsetMarker && pasSecondTuple[iKey].Set.nMarker2 == OGRUnsetMarker) ) nResult = 0; else if ( poFDefn == NULL ) { switch (SpecialFieldTypes[psKeyDef->field_index - iFIDFieldIndex]) { case SWQ_INTEGER: if( pasFirstTuple[iKey].Integer < pasSecondTuple[iKey].Integer ) nResult = -1; else if( pasFirstTuple[iKey].Integer > pasSecondTuple[iKey].Integer ) nResult = 1; break; case SWQ_FLOAT: if( pasFirstTuple[iKey].Real < pasSecondTuple[iKey].Real ) nResult = -1; else if( pasFirstTuple[iKey].Real > pasSecondTuple[iKey].Real ) nResult = 1; break; case SWQ_STRING: nResult = strcmp(pasFirstTuple[iKey].String, pasSecondTuple[iKey].String); break; default: CPLAssert( FALSE ); nResult = 0; } } else if( poFDefn->GetType() == OFTInteger ) { if( pasFirstTuple[iKey].Integer < pasSecondTuple[iKey].Integer ) nResult = -1; else if( pasFirstTuple[iKey].Integer > pasSecondTuple[iKey].Integer ) nResult = 1; } else if( poFDefn->GetType() == OFTString ) nResult = strcmp(pasFirstTuple[iKey].String, pasSecondTuple[iKey].String); else if( poFDefn->GetType() == OFTReal ) { if( pasFirstTuple[iKey].Real < pasSecondTuple[iKey].Real ) nResult = -1; else if( pasFirstTuple[iKey].Real > pasSecondTuple[iKey].Real ) nResult = 1; } else if( poFDefn->GetType() == OFTDate || poFDefn->GetType() == OFTTime || poFDefn->GetType() == OFTDateTime) { nResult = OGRCompareDate(&pasFirstTuple[iKey], &pasSecondTuple[iKey]); } if( psKeyDef->ascending_flag ) nResult *= -1; } return nResult; } /************************************************************************/ /* AddFieldDefnToSet() */ /************************************************************************/ void OGRGenSQLResultsLayer::AddFieldDefnToSet(int iTable, int iColumn, CPLHashSet* hSet) { if (iTable != -1 && iColumn != -1) { OGRLayer* poLayer = papoTableLayers[iTable]; if (iColumn < poLayer->GetLayerDefn()->GetFieldCount()) { OGRFieldDefn* poFDefn = poLayer->GetLayerDefn()->GetFieldDefn(iColumn); CPLHashSetInsert(hSet, poFDefn); } } } /************************************************************************/ /* ExploreExprForIgnoredFields() */ /************************************************************************/ void OGRGenSQLResultsLayer::ExploreExprForIgnoredFields(swq_expr_node* expr, CPLHashSet* hSet) { if (expr->eNodeType == SNT_COLUMN) { AddFieldDefnToSet(expr->table_index, expr->field_index, hSet); } else if (expr->eNodeType == SNT_OPERATION) { for( int i = 0; i < expr->nSubExprCount; i++ ) ExploreExprForIgnoredFields(expr->papoSubExpr[i], hSet); } } /************************************************************************/ /* FindAndSetIgnoredFields() */ /************************************************************************/ void OGRGenSQLResultsLayer::FindAndSetIgnoredFields() { swq_select *psSelectInfo = (swq_select *) pSelectInfo; CPLHashSet* hSet = CPLHashSetNew(CPLHashSetHashPointer, CPLHashSetEqualPointer, NULL); /* -------------------------------------------------------------------- */ /* 1st phase : explore the whole select infos to determine which */ /* source fields are used */ /* -------------------------------------------------------------------- */ for( int iField = 0; iField < psSelectInfo->result_columns; iField++ ) { swq_col_def *psColDef = psSelectInfo->column_defs + iField; AddFieldDefnToSet(psColDef->table_index, psColDef->field_index, hSet); if (psColDef->expr) ExploreExprForIgnoredFields(psColDef->expr, hSet); } if (psSelectInfo->where_expr) ExploreExprForIgnoredFields(psSelectInfo->where_expr, hSet); for( int iJoin = 0; iJoin < psSelectInfo->join_count; iJoin++ ) { swq_join_def *psJoinDef = psSelectInfo->join_defs + iJoin; AddFieldDefnToSet(0, psJoinDef->primary_field, hSet); AddFieldDefnToSet(psJoinDef->secondary_table, psJoinDef->secondary_field, hSet); } for( int iOrder = 0; iOrder < psSelectInfo->order_specs; iOrder++ ) { swq_order_def *psOrderDef = psSelectInfo->order_defs + iOrder; AddFieldDefnToSet(psOrderDef->table_index, psOrderDef->field_index, hSet); } /* -------------------------------------------------------------------- */ /* 2nd phase : now, we can exclude the unused fields */ /* -------------------------------------------------------------------- */ for( int iTable = 0; iTable < psSelectInfo->table_count; iTable++ ) { OGRLayer* poLayer = papoTableLayers[iTable]; OGRFeatureDefn *poSrcFDefn = poLayer->GetLayerDefn(); int iSrcField; char** papszIgnoredFields = NULL; for(iSrcField=0;iSrcFieldGetFieldCount();iSrcField++) { OGRFieldDefn* poFDefn = poSrcFDefn->GetFieldDefn(iSrcField); if (CPLHashSetLookup(hSet,poFDefn) == NULL) { papszIgnoredFields = CSLAddString(papszIgnoredFields, poFDefn->GetNameRef()); //CPLDebug(""OGR"", ""Adding %s to the list of ignored fields of layer %s"", // poFDefn->GetNameRef(), poLayer->GetName()); } } poLayer->SetIgnoredFields((const char**)papszIgnoredFields); CSLDestroy(papszIgnoredFields); } CPLHashSetDestroy(hSet); } /************************************************************************/ /* InvalidateOrderByIndex() */ /************************************************************************/ void OGRGenSQLResultsLayer::InvalidateOrderByIndex() { CPLFree( panFIDIndex ); panFIDIndex = NULL; nIndexSize = 0; bOrderByValid = FALSE; } /************************************************************************/ /* SetAttributeFilter() */ /************************************************************************/ OGRErr OGRGenSQLResultsLayer::SetAttributeFilter( const char* pszAttributeFilter ) { InvalidateOrderByIndex(); return OGRLayer::SetAttributeFilter(pszAttributeFilter); } /************************************************************************/ /* SetSpatialFilter() */ /************************************************************************/ void OGRGenSQLResultsLayer::SetSpatialFilter( int iGeomField, OGRGeometry * poGeom ) { InvalidateOrderByIndex(); if( iGeomField == 0 ) OGRLayer::SetSpatialFilter(poGeom); else OGRLayer::SetSpatialFilter(iGeomField, poGeom); } ",16291,True,3234.371652577684,median "/* Copyright 2019 Axel Huebl, Benjamin Worpitz * * This file is part of alpaka. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include #include #include TEST_CASE(""isIntegralSupersetTrue"", ""[meta]"") { // unsigned - unsigned static_assert( alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); static_assert( alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); static_assert( alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); static_assert( alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); static_assert( alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); static_assert( alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); static_assert( alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); static_assert( alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); static_assert( alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); static_assert( alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); // signed - signed static_assert( alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); static_assert( alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); static_assert( alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); static_assert( alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); static_assert( alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); static_assert( alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); static_assert( alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); static_assert( alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); static_assert( alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); static_assert( alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); // unsigned - signed static_assert( alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); static_assert( alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); static_assert( alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); static_assert( alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); static_assert( alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); static_assert( alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); // signed - unsigned static_assert( alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); static_assert( alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); static_assert( alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); static_assert( alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); static_assert( alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); static_assert( alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); } TEST_CASE(""isIntegralSupersetNoIntegral"", ""[meta]"") { static_assert( !alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); static_assert( !alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); } TEST_CASE(""isIntegralSupersetFalse"", ""[meta]"") { // unsigned - unsigned static_assert( !alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); static_assert( !alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); static_assert( !alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); static_assert( !alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); static_assert( !alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); static_assert( !alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); // signed - signed static_assert( !alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); static_assert( !alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); static_assert( !alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); static_assert( !alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); static_assert( !alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); static_assert( !alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); // unsigned - signed static_assert( !alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); static_assert( !alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); static_assert( !alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); static_assert( !alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); static_assert( !alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); static_assert( !alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); static_assert( !alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); static_assert( !alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); static_assert( !alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); static_assert( !alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); // signed - unsigned static_assert( !alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); static_assert( !alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); static_assert( !alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); static_assert( !alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); static_assert( !alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); static_assert( !alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); static_assert( !alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); static_assert( !alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); static_assert( !alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); static_assert( !alpaka::meta::IsIntegralSuperset::value, ""alpaka::meta::IsIntegralSuperset failed!""); } TEST_CASE(""higherMax"", ""[meta]"") { static_assert( std::is_same_v, std::int8_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::uint8_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::int16_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::uint16_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::int32_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::uint32_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::int64_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::uint64_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::uint8_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::uint8_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::int16_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::uint16_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::int32_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::uint32_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::int64_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::uint64_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::int16_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::int16_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::int16_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::uint16_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::int32_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::uint32_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::int64_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::uint64_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::uint16_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::uint16_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::uint16_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::uint16_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::int32_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::uint32_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::int64_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::uint64_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::int32_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::int32_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::int32_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::int32_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::int32_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::uint32_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::int64_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::uint64_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::uint32_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::uint32_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::uint32_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::uint32_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::uint32_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::uint32_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::int64_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::uint64_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::int64_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::int64_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::int64_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::int64_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::int64_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::int64_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::int64_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::uint64_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::uint64_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::uint64_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::uint64_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::uint64_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::uint64_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::uint64_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::uint64_t>, ""alpaka::meta::HigherMax failed!""); static_assert( std::is_same_v, std::uint64_t>, ""alpaka::meta::HigherMax failed!""); } TEST_CASE(""lowerMax"", ""[meta]"") { static_assert( std::is_same_v, std::int8_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::int8_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::int8_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::int8_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::int8_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::int8_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::int8_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::int8_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::int8_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::uint8_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::uint8_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::uint8_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::uint8_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::uint8_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::uint8_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::uint8_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::int8_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::uint8_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::int16_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::int16_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::int16_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::int16_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::int16_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::int16_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::int8_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::uint8_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::int16_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::uint16_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::uint16_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::uint16_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::uint16_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::uint16_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::int8_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::uint8_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::int16_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::uint16_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::int32_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::int32_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::int32_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::int32_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::int8_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::uint8_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::int16_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::uint16_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::int32_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::uint32_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::uint32_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::uint32_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::int8_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::uint8_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::int16_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::uint16_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::int32_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::uint32_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::int64_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::int64_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::int8_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::uint8_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::int16_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::uint16_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::int32_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::uint32_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::int64_t>, ""alpaka::meta::LowerMax failed!""); static_assert( std::is_same_v, std::uint64_t>, ""alpaka::meta::LowerMax failed!""); } TEST_CASE(""higherMin"", ""[meta]"") { static_assert( std::is_same_v, std::int8_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::uint8_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::int8_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::uint16_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::int8_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::uint32_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::int8_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::uint64_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::uint8_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::uint8_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::uint8_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::uint16_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::uint8_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::uint32_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::uint8_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::uint64_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::int8_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::uint8_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::int16_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::uint16_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::int16_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::uint32_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::int16_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::uint64_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::uint16_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::uint16_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::uint16_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::uint16_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::uint16_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::uint32_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::uint16_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::uint64_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::int8_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::uint8_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::int16_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::uint16_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::int32_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::uint32_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::int32_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::uint64_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::uint32_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::uint32_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::uint32_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::uint32_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::uint32_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::uint32_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::uint32_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::uint64_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::int8_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::uint8_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::int16_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::uint16_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::int32_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::uint32_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::int64_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::uint64_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::uint64_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::uint64_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::uint64_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::uint64_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::uint64_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::uint64_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::uint64_t>, ""alpaka::meta::HigherMin failed!""); static_assert( std::is_same_v, std::uint64_t>, ""alpaka::meta::HigherMin failed!""); } TEST_CASE(""lowerMin"", ""[meta]"") { static_assert( std::is_same_v, std::int8_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::int8_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::int16_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::int8_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::int32_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::int8_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::int64_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::int8_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::int8_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::uint8_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::int16_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::uint16_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::int32_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::uint32_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::int64_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::uint64_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::int16_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::int16_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::int16_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::int16_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::int32_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::int16_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::int64_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::int16_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::int8_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::uint16_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::int16_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::uint16_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::int32_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::uint32_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::int64_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::uint64_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::int32_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::int32_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::int32_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::int32_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::int32_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::int32_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::int64_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::int32_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::int8_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::uint32_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::int16_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::uint32_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::int32_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::uint32_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::int64_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::uint64_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::int64_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::int64_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::int64_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::int64_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::int64_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::int64_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::int64_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::int64_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::int8_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::uint64_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::int16_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::uint64_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::int32_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::uint64_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::int64_t>, ""alpaka::meta::LowerMin failed!""); static_assert( std::is_same_v, std::uint64_t>, ""alpaka::meta::LowerMin failed!""); } ",16329,True,5657.344625438961,median "//===--- BackendUtil.cpp - LLVM Backend Utilities -------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include ""clang/CodeGen/BackendUtil.h"" #include ""clang/Basic/CodeGenOptions.h"" #include ""clang/Basic/Diagnostic.h"" #include ""clang/Basic/LangOptions.h"" #include ""clang/Basic/TargetOptions.h"" #include ""clang/Frontend/FrontendDiagnostic.h"" #include ""clang/Frontend/Utils.h"" #include ""clang/Lex/HeaderSearchOptions.h"" #include ""llvm/ADT/SmallSet.h"" #include ""llvm/ADT/StringExtras.h"" #include ""llvm/ADT/StringSwitch.h"" #include ""llvm/ADT/Triple.h"" #include ""llvm/Analysis/StackSafetyAnalysis.h"" #include ""llvm/Analysis/TargetLibraryInfo.h"" #include ""llvm/Analysis/TargetTransformInfo.h"" #include ""llvm/Bitcode/BitcodeReader.h"" #include ""llvm/Bitcode/BitcodeWriter.h"" #include ""llvm/Bitcode/BitcodeWriterPass.h"" #include ""llvm/CodeGen/RegAllocRegistry.h"" #include ""llvm/CodeGen/SchedulerRegistry.h"" #include ""llvm/CodeGen/TargetSubtargetInfo.h"" #include ""llvm/IR/DataLayout.h"" #include ""llvm/IR/IRPrintingPasses.h"" #include ""llvm/IR/LegacyPassManager.h"" #include ""llvm/IR/Module.h"" #include ""llvm/IR/ModuleSummaryIndex.h"" #include ""llvm/IR/Verifier.h"" #include ""llvm/LTO/LTOBackend.h"" #include ""llvm/MC/MCAsmInfo.h"" #include ""llvm/MC/SubtargetFeature.h"" #include ""llvm/Passes/PassBuilder.h"" #include ""llvm/Passes/PassPlugin.h"" #include ""llvm/Passes/StandardInstrumentations.h"" #include ""llvm/Support/BuryPointer.h"" #include ""llvm/Support/CommandLine.h"" #include ""llvm/Support/MemoryBuffer.h"" #include ""llvm/Support/PrettyStackTrace.h"" #include ""llvm/Support/TargetRegistry.h"" #include ""llvm/Support/TimeProfiler.h"" #include ""llvm/Support/Timer.h"" #include ""llvm/Support/raw_ostream.h"" #include ""llvm/Target/TargetMachine.h"" #include ""llvm/Target/TargetOptions.h"" #include ""llvm/Transforms/Coroutines.h"" #include ""llvm/Transforms/Coroutines/CoroCleanup.h"" #include ""llvm/Transforms/Coroutines/CoroEarly.h"" #include ""llvm/Transforms/Coroutines/CoroElide.h"" #include ""llvm/Transforms/Coroutines/CoroSplit.h"" #include ""llvm/Transforms/IPO.h"" #include ""llvm/Transforms/IPO/AlwaysInliner.h"" #include ""llvm/Transforms/IPO/LowerTypeTests.h"" #include ""llvm/Transforms/IPO/PassManagerBuilder.h"" #include ""llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"" #include ""llvm/Transforms/InstCombine/InstCombine.h"" #include ""llvm/Transforms/Instrumentation.h"" #include ""llvm/Transforms/Instrumentation/AddressSanitizer.h"" #include ""llvm/Transforms/Instrumentation/BoundsChecking.h"" #include ""llvm/Transforms/Instrumentation/GCOVProfiler.h"" #include ""llvm/Transforms/Instrumentation/HWAddressSanitizer.h"" #include ""llvm/Transforms/Instrumentation/InstrProfiling.h"" #include ""llvm/Transforms/Instrumentation/MemorySanitizer.h"" #include ""llvm/Transforms/Instrumentation/SanitizerCoverage.h"" #include ""llvm/Transforms/Instrumentation/ThreadSanitizer.h"" #include ""llvm/Transforms/ObjCARC.h"" #include ""llvm/Transforms/Scalar.h"" #include ""llvm/Transforms/Scalar/GVN.h"" #include ""llvm/Transforms/Utils.h"" #include ""llvm/Transforms/Utils/CanonicalizeAliases.h"" #include ""llvm/Transforms/Utils/EntryExitInstrumenter.h"" #include ""llvm/Transforms/Utils/NameAnonGlobals.h"" #include ""llvm/Transforms/Utils/SymbolRewriter.h"" #include using namespace clang; using namespace llvm; #define HANDLE_EXTENSION(Ext) \\ llvm::PassPluginLibraryInfo get##Ext##PluginInfo(); #include ""llvm/Support/Extension.def"" namespace { // Default filename used for profile generation. static constexpr StringLiteral DefaultProfileGenName = ""default_%m.profraw""; class EmitAssemblyHelper { DiagnosticsEngine &Diags; const HeaderSearchOptions &HSOpts; const CodeGenOptions &CodeGenOpts; const clang::TargetOptions &TargetOpts; const LangOptions &LangOpts; Module *TheModule; Timer CodeGenerationTime; std::unique_ptr OS; TargetIRAnalysis getTargetIRAnalysis() const { if (TM) return TM->getTargetIRAnalysis(); return TargetIRAnalysis(); } void CreatePasses(legacy::PassManager &MPM, legacy::FunctionPassManager &FPM); /// Generates the TargetMachine. /// Leaves TM unchanged if it is unable to create the target machine. /// Some of our clang tests specify triples which are not built /// into clang. This is okay because these tests check the generated /// IR, and they require DataLayout which depends on the triple. /// In this case, we allow this method to fail and not report an error. /// When MustCreateTM is used, we print an error if we are unable to load /// the requested target. void CreateTargetMachine(bool MustCreateTM); /// Add passes necessary to emit assembly or LLVM IR. /// /// \\return True on success. bool AddEmitPasses(legacy::PassManager &CodeGenPasses, BackendAction Action, raw_pwrite_stream &OS, raw_pwrite_stream *DwoOS); std::unique_ptr openOutputFile(StringRef Path) { std::error_code EC; auto F = std::make_unique(Path, EC, llvm::sys::fs::OF_None); if (EC) { Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message(); F.reset(); } return F; } public: EmitAssemblyHelper(DiagnosticsEngine &_Diags, const HeaderSearchOptions &HeaderSearchOpts, const CodeGenOptions &CGOpts, const clang::TargetOptions &TOpts, const LangOptions &LOpts, Module *M) : Diags(_Diags), HSOpts(HeaderSearchOpts), CodeGenOpts(CGOpts), TargetOpts(TOpts), LangOpts(LOpts), TheModule(M), CodeGenerationTime(""codegen"", ""Code Generation Time"") {} ~EmitAssemblyHelper() { if (CodeGenOpts.DisableFree) BuryPointer(std::move(TM)); } std::unique_ptr TM; void EmitAssembly(BackendAction Action, std::unique_ptr OS); void EmitAssemblyWithNewPassManager(BackendAction Action, std::unique_ptr OS); }; // We need this wrapper to access LangOpts and CGOpts from extension functions // that we add to the PassManagerBuilder. class PassManagerBuilderWrapper : public PassManagerBuilder { public: PassManagerBuilderWrapper(const Triple &TargetTriple, const CodeGenOptions &CGOpts, const LangOptions &LangOpts) : PassManagerBuilder(), TargetTriple(TargetTriple), CGOpts(CGOpts), LangOpts(LangOpts) {} const Triple &getTargetTriple() const { return TargetTriple; } const CodeGenOptions &getCGOpts() const { return CGOpts; } const LangOptions &getLangOpts() const { return LangOpts; } private: const Triple &TargetTriple; const CodeGenOptions &CGOpts; const LangOptions &LangOpts; }; } static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM) { if (Builder.OptLevel > 0) PM.add(createObjCARCAPElimPass()); } static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) { if (Builder.OptLevel > 0) PM.add(createObjCARCExpandPass()); } static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) { if (Builder.OptLevel > 0) PM.add(createObjCARCOptPass()); } static void addAddDiscriminatorsPass(const PassManagerBuilder &Builder, legacy::PassManagerBase &PM) { PM.add(createAddDiscriminatorsPass()); } static void addBoundsCheckingPass(const PassManagerBuilder &Builder, legacy::PassManagerBase &PM) { PM.add(createBoundsCheckingLegacyPass()); } static SanitizerCoverageOptions getSancovOptsFromCGOpts(const CodeGenOptions &CGOpts) { SanitizerCoverageOptions Opts; Opts.CoverageType = static_cast(CGOpts.SanitizeCoverageType); Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls; Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB; Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp; Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv; Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep; Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters; Opts.TracePC = CGOpts.SanitizeCoverageTracePC; Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard; Opts.NoPrune = CGOpts.SanitizeCoverageNoPrune; Opts.Inline8bitCounters = CGOpts.SanitizeCoverageInline8bitCounters; Opts.PCTable = CGOpts.SanitizeCoveragePCTable; Opts.StackDepth = CGOpts.SanitizeCoverageStackDepth; return Opts; } static void addSanitizerCoveragePass(const PassManagerBuilder &Builder, legacy::PassManagerBase &PM) { const PassManagerBuilderWrapper &BuilderWrapper = static_cast(Builder); const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts(); auto Opts = getSancovOptsFromCGOpts(CGOpts); PM.add(createModuleSanitizerCoverageLegacyPassPass(Opts)); } // Check if ASan should use GC-friendly instrumentation for globals. // First of all, there is no point if -fdata-sections is off (expect for MachO, // where this is not a factor). Also, on ELF this feature requires an assembler // extension that only works with -integrated-as at the moment. static bool asanUseGlobalsGC(const Triple &T, const CodeGenOptions &CGOpts) { if (!CGOpts.SanitizeAddressGlobalsDeadStripping) return false; switch (T.getObjectFormat()) { case Triple::MachO: case Triple::COFF: return true; case Triple::ELF: return CGOpts.DataSections && !CGOpts.DisableIntegratedAS; case Triple::XCOFF: llvm::report_fatal_error(""ASan not implemented for XCOFF.""); case Triple::Wasm: case Triple::UnknownObjectFormat: break; } return false; } static void addAddressSanitizerPasses(const PassManagerBuilder &Builder, legacy::PassManagerBase &PM) { const PassManagerBuilderWrapper &BuilderWrapper = static_cast(Builder); const Triple &T = BuilderWrapper.getTargetTriple(); const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts(); bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Address); bool UseAfterScope = CGOpts.SanitizeAddressUseAfterScope; bool UseOdrIndicator = CGOpts.SanitizeAddressUseOdrIndicator; bool UseGlobalsGC = asanUseGlobalsGC(T, CGOpts); PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/ false, Recover, UseAfterScope)); PM.add(createModuleAddressSanitizerLegacyPassPass( /*CompileKernel*/ false, Recover, UseGlobalsGC, UseOdrIndicator)); } static void addKernelAddressSanitizerPasses(const PassManagerBuilder &Builder, legacy::PassManagerBase &PM) { PM.add(createAddressSanitizerFunctionPass( /*CompileKernel*/ true, /*Recover*/ true, /*UseAfterScope*/ false)); PM.add(createModuleAddressSanitizerLegacyPassPass( /*CompileKernel*/ true, /*Recover*/ true, /*UseGlobalsGC*/ true, /*UseOdrIndicator*/ false)); } static void addHWAddressSanitizerPasses(const PassManagerBuilder &Builder, legacy::PassManagerBase &PM) { const PassManagerBuilderWrapper &BuilderWrapper = static_cast(Builder); const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts(); bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::HWAddress); PM.add( createHWAddressSanitizerLegacyPassPass(/*CompileKernel*/ false, Recover)); } static void addKernelHWAddressSanitizerPasses(const PassManagerBuilder &Builder, legacy::PassManagerBase &PM) { PM.add(createHWAddressSanitizerLegacyPassPass( /*CompileKernel*/ true, /*Recover*/ true)); } static void addGeneralOptsForMemorySanitizer(const PassManagerBuilder &Builder, legacy::PassManagerBase &PM, bool CompileKernel) { const PassManagerBuilderWrapper &BuilderWrapper = static_cast(Builder); const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts(); int TrackOrigins = CGOpts.SanitizeMemoryTrackOrigins; bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Memory); PM.add(createMemorySanitizerLegacyPassPass( MemorySanitizerOptions{TrackOrigins, Recover, CompileKernel})); // MemorySanitizer inserts complex instrumentation that mostly follows // the logic of the original code, but operates on ""shadow"" values. // It can benefit from re-running some general purpose optimization passes. if (Builder.OptLevel > 0) { PM.add(createEarlyCSEPass()); PM.add(createReassociatePass()); PM.add(createLICMPass()); PM.add(createGVNPass()); PM.add(createInstructionCombiningPass()); PM.add(createDeadStoreEliminationPass()); } } static void addMemorySanitizerPass(const PassManagerBuilder &Builder, legacy::PassManagerBase &PM) { addGeneralOptsForMemorySanitizer(Builder, PM, /*CompileKernel*/ false); } static void addKernelMemorySanitizerPass(const PassManagerBuilder &Builder, legacy::PassManagerBase &PM) { addGeneralOptsForMemorySanitizer(Builder, PM, /*CompileKernel*/ true); } static void addThreadSanitizerPass(const PassManagerBuilder &Builder, legacy::PassManagerBase &PM) { PM.add(createThreadSanitizerLegacyPassPass()); } static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder, legacy::PassManagerBase &PM) { const PassManagerBuilderWrapper &BuilderWrapper = static_cast(Builder); const LangOptions &LangOpts = BuilderWrapper.getLangOpts(); PM.add(createDataFlowSanitizerPass(LangOpts.SanitizerBlacklistFiles)); } static void addMemTagOptimizationPasses(const PassManagerBuilder &Builder, legacy::PassManagerBase &PM) { PM.add(createStackSafetyGlobalInfoWrapperPass(/*SetMetadata=*/true)); } static void addSoftPointerAuthPass(const PassManagerBuilder &Builder, legacy::PassManagerBase &PM) { PM.add(createSoftPointerAuthPass()); } static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple, const CodeGenOptions &CodeGenOpts) { TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple); switch (CodeGenOpts.getVecLib()) { case CodeGenOptions::Accelerate: TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate); break; case CodeGenOptions::MASSV: TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::MASSV); break; case CodeGenOptions::SVML: TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::SVML); break; default: break; } return TLII; } static void addSymbolRewriterPass(const CodeGenOptions &Opts, legacy::PassManager *MPM) { llvm::SymbolRewriter::RewriteDescriptorList DL; llvm::SymbolRewriter::RewriteMapParser MapParser; for (const auto &MapFile : Opts.RewriteMapFiles) MapParser.parse(MapFile, &DL); MPM->add(createRewriteSymbolsPass(DL)); } static CodeGenOpt::Level getCGOptLevel(const CodeGenOptions &CodeGenOpts) { switch (CodeGenOpts.OptimizationLevel) { default: llvm_unreachable(""Invalid optimization level!""); case 0: return CodeGenOpt::None; case 1: return CodeGenOpt::Less; case 2: return CodeGenOpt::Default; // O2/Os/Oz case 3: return CodeGenOpt::Aggressive; } } static Optional getCodeModel(const CodeGenOptions &CodeGenOpts) { unsigned CodeModel = llvm::StringSwitch(CodeGenOpts.CodeModel) .Case(""tiny"", llvm::CodeModel::Tiny) .Case(""small"", llvm::CodeModel::Small) .Case(""kernel"", llvm::CodeModel::Kernel) .Case(""medium"", llvm::CodeModel::Medium) .Case(""large"", llvm::CodeModel::Large) .Case(""default"", ~1u) .Default(~0u); assert(CodeModel != ~0u && ""invalid code model!""); if (CodeModel == ~1u) return None; return static_cast(CodeModel); } static CodeGenFileType getCodeGenFileType(BackendAction Action) { if (Action == Backend_EmitObj) return CGFT_ObjectFile; else if (Action == Backend_EmitMCNull) return CGFT_Null; else { assert(Action == Backend_EmitAssembly && ""Invalid action!""); return CGFT_AssemblyFile; } } static void initTargetOptions(llvm::TargetOptions &Options, const CodeGenOptions &CodeGenOpts, const clang::TargetOptions &TargetOpts, const LangOptions &LangOpts, const HeaderSearchOptions &HSOpts) { Options.ThreadModel = llvm::StringSwitch(CodeGenOpts.ThreadModel) .Case(""posix"", llvm::ThreadModel::POSIX) .Case(""single"", llvm::ThreadModel::Single); // Set float ABI type. assert((CodeGenOpts.FloatABI == ""soft"" || CodeGenOpts.FloatABI == ""softfp"" || CodeGenOpts.FloatABI == ""hard"" || CodeGenOpts.FloatABI.empty()) && ""Invalid Floating Point ABI!""); Options.FloatABIType = llvm::StringSwitch(CodeGenOpts.FloatABI) .Case(""soft"", llvm::FloatABI::Soft) .Case(""softfp"", llvm::FloatABI::Soft) .Case(""hard"", llvm::FloatABI::Hard) .Default(llvm::FloatABI::Default); // Set FP fusion mode. switch (LangOpts.getDefaultFPContractMode()) { case LangOptions::FPC_Off: // Preserve any contraction performed by the front-end. (Strict performs // splitting of the muladd intrinsic in the backend.) Options.AllowFPOpFusion = llvm::FPOpFusion::Standard; break; case LangOptions::FPC_On: Options.AllowFPOpFusion = llvm::FPOpFusion::Standard; break; case LangOptions::FPC_Fast: Options.AllowFPOpFusion = llvm::FPOpFusion::Fast; break; } Options.UseInitArray = CodeGenOpts.UseInitArray; Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS; Options.CompressDebugSections = CodeGenOpts.getCompressDebugSections(); Options.RelaxELFRelocations = CodeGenOpts.RelaxELFRelocations; // Set EABI version. Options.EABIVersion = TargetOpts.EABIVersion; if (LangOpts.SjLjExceptions) Options.ExceptionModel = llvm::ExceptionHandling::SjLj; if (LangOpts.SEHExceptions) Options.ExceptionModel = llvm::ExceptionHandling::WinEH; if (LangOpts.DWARFExceptions) Options.ExceptionModel = llvm::ExceptionHandling::DwarfCFI; if (LangOpts.WasmExceptions) Options.ExceptionModel = llvm::ExceptionHandling::Wasm; Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath; Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath; Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS; Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath; Options.StackAlignmentOverride = CodeGenOpts.StackAlignment; Options.FunctionSections = CodeGenOpts.FunctionSections; Options.DataSections = CodeGenOpts.DataSections; Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames; Options.TLSSize = CodeGenOpts.TLSSize; Options.EmulatedTLS = CodeGenOpts.EmulatedTLS; Options.ExplicitEmulatedTLS = CodeGenOpts.ExplicitEmulatedTLS; Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning(); Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection; Options.EmitAddrsig = CodeGenOpts.Addrsig; Options.ForceDwarfFrameSection = CodeGenOpts.ForceDwarfFrameSection; Options.EmitCallSiteInfo = CodeGenOpts.EmitCallSiteInfo; Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile; Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll; Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels; Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm; Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack; Options.MCOptions.MCIncrementalLinkerCompatible = CodeGenOpts.IncrementalLinkerCompatible; Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings; Options.MCOptions.MCNoWarn = CodeGenOpts.NoWarn; Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose; Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments; Options.MCOptions.ABIName = TargetOpts.ABI; for (const auto &Entry : HSOpts.UserEntries) if (!Entry.IsFramework && (Entry.Group == frontend::IncludeDirGroup::Quoted || Entry.Group == frontend::IncludeDirGroup::Angled || Entry.Group == frontend::IncludeDirGroup::System)) Options.MCOptions.IASSearchPaths.push_back( Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path); } static Optional getGCOVOptions(const CodeGenOptions &CodeGenOpts) { if (CodeGenOpts.DisableGCov) return None; if (!CodeGenOpts.EmitGcovArcs && !CodeGenOpts.EmitGcovNotes) return None; // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if // LLVM's -default-gcov-version flag is set to something invalid. GCOVOptions Options; Options.EmitNotes = CodeGenOpts.EmitGcovNotes; Options.EmitData = CodeGenOpts.EmitGcovArcs; llvm::copy(CodeGenOpts.CoverageVersion, std::begin(Options.Version)); Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum; Options.NoRedZone = CodeGenOpts.DisableRedZone; Options.FunctionNamesInData = !CodeGenOpts.CoverageNoFunctionNamesInData; Options.Filter = CodeGenOpts.ProfileFilterFiles; Options.Exclude = CodeGenOpts.ProfileExcludeFiles; Options.ExitBlockBeforeBody = CodeGenOpts.CoverageExitBlockBeforeBody; return Options; } static Optional getInstrProfOptions(const CodeGenOptions &CodeGenOpts, const LangOptions &LangOpts) { if (!CodeGenOpts.hasProfileClangInstr()) return None; InstrProfOptions Options; Options.NoRedZone = CodeGenOpts.DisableRedZone; Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput; // TODO: Surface the option to emit atomic profile counter increments at // the driver level. Options.Atomic = LangOpts.Sanitize.has(SanitizerKind::Thread); return Options; } void EmitAssemblyHelper::CreatePasses(legacy::PassManager &MPM, legacy::FunctionPassManager &FPM) { // Handle disabling of all LLVM passes, where we want to preserve the // internal module before any optimization. if (CodeGenOpts.DisableLLVMPasses) return; // Figure out TargetLibraryInfo. This needs to be added to MPM and FPM // manually (and not via PMBuilder), since some passes (eg. InstrProfiling) // are inserted before PMBuilder ones - they'd get the default-constructed // TLI with an unknown target otherwise. Triple TargetTriple(TheModule->getTargetTriple()); std::unique_ptr TLII( createTLII(TargetTriple, CodeGenOpts)); // If we reached here with a non-empty index file name, then the index file // was empty and we are not performing ThinLTO backend compilation (used in // testing in a distributed build environment). Drop any the type test // assume sequences inserted for whole program vtables so that codegen doesn't // complain. if (!CodeGenOpts.ThinLTOIndexFile.empty()) MPM.add(createLowerTypeTestsPass(/*ExportSummary=*/nullptr, /*ImportSummary=*/nullptr, /*DropTypeTests=*/true)); PassManagerBuilderWrapper PMBuilder(TargetTriple, CodeGenOpts, LangOpts); // At O0 and O1 we only run the always inliner which is more efficient. At // higher optimization levels we run the normal inliner. if (CodeGenOpts.OptimizationLevel <= 1) { bool InsertLifetimeIntrinsics = ((CodeGenOpts.OptimizationLevel != 0 && !CodeGenOpts.DisableLifetimeMarkers) || LangOpts.Coroutines); PMBuilder.Inliner = createAlwaysInlinerLegacyPass(InsertLifetimeIntrinsics); } else { // We do not want to inline hot callsites for SamplePGO module-summary build // because profile annotation will happen again in ThinLTO backend, and we // want the IR of the hot path to match the profile. PMBuilder.Inliner = createFunctionInliningPass( CodeGenOpts.OptimizationLevel, CodeGenOpts.OptimizeSize, (!CodeGenOpts.SampleProfileFile.empty() && CodeGenOpts.PrepareForThinLTO)); } PMBuilder.OptLevel = CodeGenOpts.OptimizationLevel; PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize; PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP; PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop; PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops; // Loop interleaving in the loop vectorizer has historically been set to be // enabled when loop unrolling is enabled. PMBuilder.LoopsInterleaved = CodeGenOpts.UnrollLoops; PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions; PMBuilder.SplitColdCode = CodeGenOpts.SplitColdCode; PMBuilder.PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO; PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO; PMBuilder.RerollLoops = CodeGenOpts.RerollLoops; MPM.add(new TargetLibraryInfoWrapperPass(*TLII)); if (TM) TM->adjustPassManager(PMBuilder); if (CodeGenOpts.DebugInfoForProfiling || !CodeGenOpts.SampleProfileFile.empty()) PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible, addAddDiscriminatorsPass); // In ObjC ARC mode, add the main ARC optimization passes. if (LangOpts.ObjCAutoRefCount) { PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible, addObjCARCExpandPass); PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly, addObjCARCAPElimPass); PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate, addObjCARCOptPass); } if (LangOpts.Coroutines) addCoroutinePassesToExtensionPoints(PMBuilder); if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) { PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate, addBoundsCheckingPass); PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, addBoundsCheckingPass); } if (CodeGenOpts.SanitizeCoverageType || CodeGenOpts.SanitizeCoverageIndirectCalls || CodeGenOpts.SanitizeCoverageTraceCmp) { PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, addSanitizerCoveragePass); PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, addSanitizerCoveragePass); } if (LangOpts.Sanitize.has(SanitizerKind::Address)) { PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, addAddressSanitizerPasses); PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, addAddressSanitizerPasses); } if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) { PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, addKernelAddressSanitizerPasses); PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, addKernelAddressSanitizerPasses); } if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) { PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, addHWAddressSanitizerPasses); PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, addHWAddressSanitizerPasses); } if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) { PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, addKernelHWAddressSanitizerPasses); PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, addKernelHWAddressSanitizerPasses); } if (LangOpts.Sanitize.has(SanitizerKind::Memory)) { PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, addMemorySanitizerPass); PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, addMemorySanitizerPass); } if (LangOpts.Sanitize.has(SanitizerKind::KernelMemory)) { PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, addKernelMemorySanitizerPass); PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, addKernelMemorySanitizerPass); } if (LangOpts.Sanitize.has(SanitizerKind::Thread)) { PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, addThreadSanitizerPass); PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, addThreadSanitizerPass); } if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) { PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, addDataFlowSanitizerPass); PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, addDataFlowSanitizerPass); } if (LangOpts.Sanitize.has(SanitizerKind::MemTag)) { PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, addMemTagOptimizationPasses); } if (LangOpts.SoftPointerAuth) { PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast, addSoftPointerAuthPass); PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, addSoftPointerAuthPass); } // Set up the per-function pass manager. FPM.add(new TargetLibraryInfoWrapperPass(*TLII)); if (CodeGenOpts.VerifyModule) FPM.add(createVerifierPass()); // Set up the per-module pass manager. if (!CodeGenOpts.RewriteMapFiles.empty()) addSymbolRewriterPass(CodeGenOpts, &MPM); if (Optional Options = getGCOVOptions(CodeGenOpts)) { MPM.add(createGCOVProfilerPass(*Options)); if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo) MPM.add(createStripSymbolsPass(true)); } if (Optional Options = getInstrProfOptions(CodeGenOpts, LangOpts)) MPM.add(createInstrProfilingLegacyPass(*Options, false)); bool hasIRInstr = false; if (CodeGenOpts.hasProfileIRInstr()) { PMBuilder.EnablePGOInstrGen = true; hasIRInstr = true; } if (CodeGenOpts.hasProfileCSIRInstr()) { assert(!CodeGenOpts.hasProfileCSIRUse() && ""Cannot have both CSProfileUse pass and CSProfileGen pass at the "" ""same time""); assert(!hasIRInstr && ""Cannot have both ProfileGen pass and CSProfileGen pass at the "" ""same time""); PMBuilder.EnablePGOCSInstrGen = true; hasIRInstr = true; } if (hasIRInstr) { if (!CodeGenOpts.InstrProfileOutput.empty()) PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput; else PMBuilder.PGOInstrGen = std::string(DefaultProfileGenName); } if (CodeGenOpts.hasProfileIRUse()) { PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath; PMBuilder.EnablePGOCSInstrUse = CodeGenOpts.hasProfileCSIRUse(); } if (!CodeGenOpts.SampleProfileFile.empty()) PMBuilder.PGOSampleUse = CodeGenOpts.SampleProfileFile; PMBuilder.populateFunctionPassManager(FPM); PMBuilder.populateModulePassManager(MPM); } static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) { SmallVector BackendArgs; BackendArgs.push_back(""clang""); // Fake program name. if (!CodeGenOpts.DebugPass.empty()) { BackendArgs.push_back(""-debug-pass""); BackendArgs.push_back(CodeGenOpts.DebugPass.c_str()); } if (!CodeGenOpts.LimitFloatPrecision.empty()) { BackendArgs.push_back(""-limit-float-precision""); BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str()); } BackendArgs.push_back(nullptr); llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1, BackendArgs.data()); } void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) { // Create the TargetMachine for generating code. std::string Error; std::string Triple = TheModule->getTargetTriple(); const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error); if (!TheTarget) { if (MustCreateTM) Diags.Report(diag::err_fe_unable_to_create_target) << Error; return; } Optional CM = getCodeModel(CodeGenOpts); std::string FeaturesStr = llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), "",""); llvm::Reloc::Model RM = CodeGenOpts.RelocationModel; CodeGenOpt::Level OptLevel = getCGOptLevel(CodeGenOpts); llvm::TargetOptions Options; initTargetOptions(Options, CodeGenOpts, TargetOpts, LangOpts, HSOpts); TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr, Options, RM, CM, OptLevel)); } bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses, BackendAction Action, raw_pwrite_stream &OS, raw_pwrite_stream *DwoOS) { // Add LibraryInfo. llvm::Triple TargetTriple(TheModule->getTargetTriple()); std::unique_ptr TLII( createTLII(TargetTriple, CodeGenOpts)); CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII)); // Normal mode, emit a .s or .o file by running the code generator. Note, // this also adds codegenerator level optimization passes. CodeGenFileType CGFT = getCodeGenFileType(Action); // Add ObjC ARC final-cleanup optimizations. This is done as part of the // ""codegen"" passes so that it isn't run multiple times when there is // inlining happening. if (CodeGenOpts.OptimizationLevel > 0) CodeGenPasses.add(createObjCARCContractPass()); if (TM->addPassesToEmitFile(CodeGenPasses, OS, DwoOS, CGFT, /*DisableVerify=*/!CodeGenOpts.VerifyModule)) { Diags.Report(diag::err_fe_unable_to_interface_with_target); return false; } return true; } void EmitAssemblyHelper::EmitAssembly(BackendAction Action, std::unique_ptr OS) { TimeRegion Region(FrontendTimesIsEnabled ? &CodeGenerationTime : nullptr); setCommandLineOpts(CodeGenOpts); bool UsesCodeGen = (Action != Backend_EmitNothing && Action != Backend_EmitBC && Action != Backend_EmitLL); CreateTargetMachine(UsesCodeGen); if (UsesCodeGen && !TM) return; if (TM) TheModule->setDataLayout(TM->createDataLayout()); legacy::PassManager PerModulePasses; PerModulePasses.add( createTargetTransformInfoWrapperPass(getTargetIRAnalysis())); legacy::FunctionPassManager PerFunctionPasses(TheModule); PerFunctionPasses.add( createTargetTransformInfoWrapperPass(getTargetIRAnalysis())); CreatePasses(PerModulePasses, PerFunctionPasses); legacy::PassManager CodeGenPasses; CodeGenPasses.add( createTargetTransformInfoWrapperPass(getTargetIRAnalysis())); std::unique_ptr ThinLinkOS, DwoOS; switch (Action) { case Backend_EmitNothing: break; case Backend_EmitBC: if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) { if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) { ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile); if (!ThinLinkOS) return; } TheModule->addModuleFlag(Module::Error, ""EnableSplitLTOUnit"", CodeGenOpts.EnableSplitLTOUnit); PerModulePasses.add(createWriteThinLTOBitcodePass( *OS, ThinLinkOS ? &ThinLinkOS->os() : nullptr)); } else { // Emit a module summary by default for Regular LTO except for ld64 // targets bool EmitLTOSummary = (CodeGenOpts.PrepareForLTO && !CodeGenOpts.DisableLLVMPasses && llvm::Triple(TheModule->getTargetTriple()).getVendor() != llvm::Triple::Apple); if (EmitLTOSummary) { if (!TheModule->getModuleFlag(""ThinLTO"")) TheModule->addModuleFlag(Module::Error, ""ThinLTO"", uint32_t(0)); TheModule->addModuleFlag(Module::Error, ""EnableSplitLTOUnit"", uint32_t(1)); } PerModulePasses.add(createBitcodeWriterPass( *OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary)); } break; case Backend_EmitLL: PerModulePasses.add( createPrintModulePass(*OS, """", CodeGenOpts.EmitLLVMUseLists)); break; default: if (!CodeGenOpts.SplitDwarfOutput.empty()) { DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput); if (!DwoOS) return; } if (!AddEmitPasses(CodeGenPasses, Action, *OS, DwoOS ? &DwoOS->os() : nullptr)) return; } // Before executing passes, print the final values of the LLVM options. cl::PrintOptionValues(); // Run passes. For now we do all passes at once, but eventually we // would like to have the option of streaming code generation. { PrettyStackTraceString CrashInfo(""Per-function optimization""); llvm::TimeTraceScope TimeScope(""PerFunctionPasses""); PerFunctionPasses.doInitialization(); for (Function &F : *TheModule) if (!F.isDeclaration()) PerFunctionPasses.run(F); PerFunctionPasses.doFinalization(); } { PrettyStackTraceString CrashInfo(""Per-module optimization passes""); llvm::TimeTraceScope TimeScope(""PerModulePasses""); PerModulePasses.run(*TheModule); } { PrettyStackTraceString CrashInfo(""Code generation""); llvm::TimeTraceScope TimeScope(""CodeGenPasses""); CodeGenPasses.run(*TheModule); } if (ThinLinkOS) ThinLinkOS->keep(); if (DwoOS) DwoOS->keep(); } static PassBuilder::OptimizationLevel mapToLevel(const CodeGenOptions &Opts) { switch (Opts.OptimizationLevel) { default: llvm_unreachable(""Invalid optimization level!""); case 1: return PassBuilder::OptimizationLevel::O1; case 2: switch (Opts.OptimizeSize) { default: llvm_unreachable(""Invalid optimization level for size!""); case 0: return PassBuilder::OptimizationLevel::O2; case 1: return PassBuilder::OptimizationLevel::Os; case 2: return PassBuilder::OptimizationLevel::Oz; } case 3: return PassBuilder::OptimizationLevel::O3; } } static void addCoroutinePassesAtO0(ModulePassManager &MPM, const LangOptions &LangOpts, const CodeGenOptions &CodeGenOpts) { if (!LangOpts.Coroutines) return; MPM.addPass(createModuleToFunctionPassAdaptor(CoroEarlyPass())); CGSCCPassManager CGPM(CodeGenOpts.DebugPassManager); CGPM.addPass(CoroSplitPass()); CGPM.addPass(createCGSCCToFunctionPassAdaptor(CoroElidePass())); MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM))); MPM.addPass(createModuleToFunctionPassAdaptor(CoroCleanupPass())); } static void addSanitizersAtO0(ModulePassManager &MPM, const Triple &TargetTriple, const LangOptions &LangOpts, const CodeGenOptions &CodeGenOpts) { auto ASanPass = [&](SanitizerMask Mask, bool CompileKernel) { MPM.addPass(RequireAnalysisPass()); bool Recover = CodeGenOpts.SanitizeRecover.has(Mask); MPM.addPass(createModuleToFunctionPassAdaptor(AddressSanitizerPass( CompileKernel, Recover, CodeGenOpts.SanitizeAddressUseAfterScope))); bool ModuleUseAfterScope = asanUseGlobalsGC(TargetTriple, CodeGenOpts); MPM.addPass( ModuleAddressSanitizerPass(CompileKernel, Recover, ModuleUseAfterScope, CodeGenOpts.SanitizeAddressUseOdrIndicator)); }; if (LangOpts.Sanitize.has(SanitizerKind::Address)) { ASanPass(SanitizerKind::Address, /*CompileKernel=*/false); } if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) { ASanPass(SanitizerKind::KernelAddress, /*CompileKernel=*/true); } if (LangOpts.Sanitize.has(SanitizerKind::Memory)) { MPM.addPass(MemorySanitizerPass({})); MPM.addPass(createModuleToFunctionPassAdaptor(MemorySanitizerPass({}))); } if (LangOpts.Sanitize.has(SanitizerKind::KernelMemory)) { MPM.addPass(createModuleToFunctionPassAdaptor( MemorySanitizerPass({0, false, /*Kernel=*/true}))); } if (LangOpts.Sanitize.has(SanitizerKind::Thread)) { MPM.addPass(ThreadSanitizerPass()); MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass())); } } /// A clean version of `EmitAssembly` that uses the new pass manager. /// /// Not all features are currently supported in this system, but where /// necessary it falls back to the legacy pass manager to at least provide /// basic functionality. /// /// This API is planned to have its functionality finished and then to replace /// `EmitAssembly` at some point in the future when the default switches. void EmitAssemblyHelper::EmitAssemblyWithNewPassManager( BackendAction Action, std::unique_ptr OS) { TimeRegion Region(FrontendTimesIsEnabled ? &CodeGenerationTime : nullptr); setCommandLineOpts(CodeGenOpts); bool RequiresCodeGen = (Action != Backend_EmitNothing && Action != Backend_EmitBC && Action != Backend_EmitLL); CreateTargetMachine(RequiresCodeGen); if (RequiresCodeGen && !TM) return; if (TM) TheModule->setDataLayout(TM->createDataLayout()); Optional PGOOpt; if (CodeGenOpts.hasProfileIRInstr()) // -fprofile-generate. PGOOpt = PGOOptions(CodeGenOpts.InstrProfileOutput.empty() ? std::string(DefaultProfileGenName) : CodeGenOpts.InstrProfileOutput, """", """", PGOOptions::IRInstr, PGOOptions::NoCSAction, CodeGenOpts.DebugInfoForProfiling); else if (CodeGenOpts.hasProfileIRUse()) { // -fprofile-use. auto CSAction = CodeGenOpts.hasProfileCSIRUse() ? PGOOptions::CSIRUse : PGOOptions::NoCSAction; PGOOpt = PGOOptions(CodeGenOpts.ProfileInstrumentUsePath, """", CodeGenOpts.ProfileRemappingFile, PGOOptions::IRUse, CSAction, CodeGenOpts.DebugInfoForProfiling); } else if (!CodeGenOpts.SampleProfileFile.empty()) // -fprofile-sample-use PGOOpt = PGOOptions(CodeGenOpts.SampleProfileFile, """", CodeGenOpts.ProfileRemappingFile, PGOOptions::SampleUse, PGOOptions::NoCSAction, CodeGenOpts.DebugInfoForProfiling); else if (CodeGenOpts.DebugInfoForProfiling) // -fdebug-info-for-profiling PGOOpt = PGOOptions("""", """", """", PGOOptions::NoAction, PGOOptions::NoCSAction, true); // Check to see if we want to generate a CS profile. if (CodeGenOpts.hasProfileCSIRInstr()) { assert(!CodeGenOpts.hasProfileCSIRUse() && ""Cannot have both CSProfileUse pass and CSProfileGen pass at "" ""the same time""); if (PGOOpt.hasValue()) { assert(PGOOpt->Action != PGOOptions::IRInstr && PGOOpt->Action != PGOOptions::SampleUse && ""Cannot run CSProfileGen pass with ProfileGen or SampleUse "" "" pass""); PGOOpt->CSProfileGenFile = CodeGenOpts.InstrProfileOutput.empty() ? std::string(DefaultProfileGenName) : CodeGenOpts.InstrProfileOutput; PGOOpt->CSAction = PGOOptions::CSIRInstr; } else PGOOpt = PGOOptions("""", CodeGenOpts.InstrProfileOutput.empty() ? std::string(DefaultProfileGenName) : CodeGenOpts.InstrProfileOutput, """", PGOOptions::NoAction, PGOOptions::CSIRInstr, CodeGenOpts.DebugInfoForProfiling); } PipelineTuningOptions PTO; PTO.LoopUnrolling = CodeGenOpts.UnrollLoops; // For historical reasons, loop interleaving is set to mirror setting for loop // unrolling. PTO.LoopInterleaving = CodeGenOpts.UnrollLoops; PTO.LoopVectorization = CodeGenOpts.VectorizeLoop; PTO.SLPVectorization = CodeGenOpts.VectorizeSLP; PTO.Coroutines = LangOpts.Coroutines; PassInstrumentationCallbacks PIC; StandardInstrumentations SI; SI.registerCallbacks(PIC); PassBuilder PB(TM.get(), PTO, PGOOpt, &PIC); // Attempt to load pass plugins and register their callbacks with PB. for (auto &PluginFN : CodeGenOpts.PassPlugins) { auto PassPlugin = PassPlugin::Load(PluginFN); if (PassPlugin) { PassPlugin->registerPassBuilderCallbacks(PB); } else { Diags.Report(diag::err_fe_unable_to_load_plugin) << PluginFN << toString(PassPlugin.takeError()); } } #define HANDLE_EXTENSION(Ext) \\ get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB); #include ""llvm/Support/Extension.def"" LoopAnalysisManager LAM(CodeGenOpts.DebugPassManager); FunctionAnalysisManager FAM(CodeGenOpts.DebugPassManager); CGSCCAnalysisManager CGAM(CodeGenOpts.DebugPassManager); ModuleAnalysisManager MAM(CodeGenOpts.DebugPassManager); // Register the AA manager first so that our version is the one used. FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); }); // Register the target library analysis directly and give it a customized // preset TLI. Triple TargetTriple(TheModule->getTargetTriple()); std::unique_ptr TLII( createTLII(TargetTriple, CodeGenOpts)); FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); }); // Register all the basic analyses with the managers. PB.registerModuleAnalyses(MAM); PB.registerCGSCCAnalyses(CGAM); PB.registerFunctionAnalyses(FAM); PB.registerLoopAnalyses(LAM); PB.crossRegisterProxies(LAM, FAM, CGAM, MAM); ModulePassManager MPM(CodeGenOpts.DebugPassManager); if (!CodeGenOpts.DisableLLVMPasses) { bool IsThinLTO = CodeGenOpts.PrepareForThinLTO; bool IsLTO = CodeGenOpts.PrepareForLTO; if (CodeGenOpts.OptimizationLevel == 0) { // If we reached here with a non-empty index file name, then the index // file was empty and we are not performing ThinLTO backend compilation // (used in testing in a distributed build environment). Drop any the type // test assume sequences inserted for whole program vtables so that // codegen doesn't complain. if (!CodeGenOpts.ThinLTOIndexFile.empty()) MPM.addPass(LowerTypeTestsPass(/*ExportSummary=*/nullptr, /*ImportSummary=*/nullptr, /*DropTypeTests=*/true)); if (Optional Options = getGCOVOptions(CodeGenOpts)) MPM.addPass(GCOVProfilerPass(*Options)); if (Optional Options = getInstrProfOptions(CodeGenOpts, LangOpts)) MPM.addPass(InstrProfiling(*Options, false)); // Build a minimal pipeline based on the semantics required by Clang, // which is just that always inlining occurs. Further, disable generating // lifetime intrinsics to avoid enabling further optimizations during // code generation. // However, we need to insert lifetime intrinsics to avoid invalid access // caused by multithreaded coroutines. MPM.addPass( AlwaysInlinerPass(/*InsertLifetimeIntrinsics=*/LangOpts.Coroutines)); // At -O0, we can still do PGO. Add all the requested passes for // instrumentation PGO, if requested. if (PGOOpt && (PGOOpt->Action == PGOOptions::IRInstr || PGOOpt->Action == PGOOptions::IRUse)) PB.addPGOInstrPassesForO0( MPM, CodeGenOpts.DebugPassManager, /* RunProfileGen */ (PGOOpt->Action == PGOOptions::IRInstr), /* IsCS */ false, PGOOpt->ProfileFile, PGOOpt->ProfileRemappingFile); // At -O0 we directly run necessary sanitizer passes. if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) MPM.addPass(createModuleToFunctionPassAdaptor(BoundsCheckingPass())); // Lastly, add semantically necessary passes for LTO. if (IsLTO || IsThinLTO) { MPM.addPass(CanonicalizeAliasesPass()); MPM.addPass(NameAnonGlobalPass()); } } else { // Map our optimization levels into one of the distinct levels used to // configure the pipeline. PassBuilder::OptimizationLevel Level = mapToLevel(CodeGenOpts); // -f[no-]split-cold-code PB.setEnableHotColdSplitting(CodeGenOpts.SplitColdCode); // If we reached here with a non-empty index file name, then the index // file was empty and we are not performing ThinLTO backend compilation // (used in testing in a distributed build environment). Drop any the type // test assume sequences inserted for whole program vtables so that // codegen doesn't complain. if (!CodeGenOpts.ThinLTOIndexFile.empty()) PB.registerPipelineStartEPCallback([](ModulePassManager &MPM) { MPM.addPass(LowerTypeTestsPass(/*ExportSummary=*/nullptr, /*ImportSummary=*/nullptr, /*DropTypeTests=*/true)); }); PB.registerPipelineStartEPCallback([](ModulePassManager &MPM) { MPM.addPass(createModuleToFunctionPassAdaptor( EntryExitInstrumenterPass(/*PostInlining=*/false))); }); // Register callbacks to schedule sanitizer passes at the appropriate part of // the pipeline. // FIXME: either handle asan/the remaining sanitizers or error out if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) PB.registerScalarOptimizerLateEPCallback( [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) { FPM.addPass(BoundsCheckingPass()); }); if (LangOpts.Sanitize.has(SanitizerKind::Memory)) { PB.registerPipelineStartEPCallback([](ModulePassManager &MPM) { MPM.addPass(MemorySanitizerPass({})); }); PB.registerOptimizerLastEPCallback( [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) { FPM.addPass(MemorySanitizerPass({})); }); } if (LangOpts.Sanitize.has(SanitizerKind::Thread)) { PB.registerPipelineStartEPCallback( [](ModulePassManager &MPM) { MPM.addPass(ThreadSanitizerPass()); }); PB.registerOptimizerLastEPCallback( [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) { FPM.addPass(ThreadSanitizerPass()); }); } if (LangOpts.Sanitize.has(SanitizerKind::Address)) { PB.registerPipelineStartEPCallback([&](ModulePassManager &MPM) { MPM.addPass( RequireAnalysisPass()); }); bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::Address); bool UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope; PB.registerOptimizerLastEPCallback( [Recover, UseAfterScope](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) { FPM.addPass(AddressSanitizerPass( /*CompileKernel=*/false, Recover, UseAfterScope)); }); bool ModuleUseAfterScope = asanUseGlobalsGC(TargetTriple, CodeGenOpts); bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator; PB.registerPipelineStartEPCallback( [Recover, ModuleUseAfterScope, UseOdrIndicator](ModulePassManager &MPM) { MPM.addPass(ModuleAddressSanitizerPass( /*CompileKernel=*/false, Recover, ModuleUseAfterScope, UseOdrIndicator)); }); } if (Optional Options = getGCOVOptions(CodeGenOpts)) PB.registerPipelineStartEPCallback([Options](ModulePassManager &MPM) { MPM.addPass(GCOVProfilerPass(*Options)); }); if (Optional Options = getInstrProfOptions(CodeGenOpts, LangOpts)) PB.registerPipelineStartEPCallback([Options](ModulePassManager &MPM) { MPM.addPass(InstrProfiling(*Options, false)); }); if (IsThinLTO) { MPM = PB.buildThinLTOPreLinkDefaultPipeline( Level, CodeGenOpts.DebugPassManager); MPM.addPass(CanonicalizeAliasesPass()); MPM.addPass(NameAnonGlobalPass()); } else if (IsLTO) { MPM = PB.buildLTOPreLinkDefaultPipeline(Level, CodeGenOpts.DebugPassManager); MPM.addPass(CanonicalizeAliasesPass()); MPM.addPass(NameAnonGlobalPass()); } else { MPM = PB.buildPerModuleDefaultPipeline(Level, CodeGenOpts.DebugPassManager); } } if (CodeGenOpts.SanitizeCoverageType || CodeGenOpts.SanitizeCoverageIndirectCalls || CodeGenOpts.SanitizeCoverageTraceCmp) { auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts); MPM.addPass(ModuleSanitizerCoveragePass(SancovOpts)); } if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) { bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::HWAddress); MPM.addPass(HWAddressSanitizerPass( /*CompileKernel=*/false, Recover)); } if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) { MPM.addPass(HWAddressSanitizerPass( /*CompileKernel=*/true, /*Recover=*/true)); } if (CodeGenOpts.OptimizationLevel > 0 && LangOpts.Sanitize.has(SanitizerKind::MemTag)) { MPM.addPass(StackSafetyGlobalAnnotatorPass()); } if (CodeGenOpts.OptimizationLevel == 0) { addCoroutinePassesAtO0(MPM, LangOpts, CodeGenOpts); addSanitizersAtO0(MPM, TargetTriple, LangOpts, CodeGenOpts); } } // FIXME: We still use the legacy pass manager to do code generation. We // create that pass manager here and use it as needed below. legacy::PassManager CodeGenPasses; bool NeedCodeGen = false; std::unique_ptr ThinLinkOS, DwoOS; // Append any output we need to the pass manager. switch (Action) { case Backend_EmitNothing: break; case Backend_EmitBC: if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) { if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) { ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile); if (!ThinLinkOS) return; } TheModule->addModuleFlag(Module::Error, ""EnableSplitLTOUnit"", CodeGenOpts.EnableSplitLTOUnit); MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &ThinLinkOS->os() : nullptr)); } else { // Emit a module summary by default for Regular LTO except for ld64 // targets bool EmitLTOSummary = (CodeGenOpts.PrepareForLTO && !CodeGenOpts.DisableLLVMPasses && llvm::Triple(TheModule->getTargetTriple()).getVendor() != llvm::Triple::Apple); if (EmitLTOSummary) { if (!TheModule->getModuleFlag(""ThinLTO"")) TheModule->addModuleFlag(Module::Error, ""ThinLTO"", uint32_t(0)); TheModule->addModuleFlag(Module::Error, ""EnableSplitLTOUnit"", uint32_t(1)); } MPM.addPass( BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary)); } break; case Backend_EmitLL: MPM.addPass(PrintModulePass(*OS, """", CodeGenOpts.EmitLLVMUseLists)); break; case Backend_EmitAssembly: case Backend_EmitMCNull: case Backend_EmitObj: NeedCodeGen = true; CodeGenPasses.add( createTargetTransformInfoWrapperPass(getTargetIRAnalysis())); if (!CodeGenOpts.SplitDwarfOutput.empty()) { DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput); if (!DwoOS) return; } if (!AddEmitPasses(CodeGenPasses, Action, *OS, DwoOS ? &DwoOS->os() : nullptr)) // FIXME: Should we handle this error differently? return; break; } // Before executing passes, print the final values of the LLVM options. cl::PrintOptionValues(); // Now that we have all of the passes ready, run them. { PrettyStackTraceString CrashInfo(""Optimizer""); MPM.run(*TheModule, MAM); } // Now if needed, run the legacy PM for codegen. if (NeedCodeGen) { PrettyStackTraceString CrashInfo(""Code generation""); CodeGenPasses.run(*TheModule); } if (ThinLinkOS) ThinLinkOS->keep(); if (DwoOS) DwoOS->keep(); } Expected clang::FindThinLTOModule(MemoryBufferRef MBRef) { Expected> BMsOrErr = getBitcodeModuleList(MBRef); if (!BMsOrErr) return BMsOrErr.takeError(); // The bitcode file may contain multiple modules, we want the one that is // marked as being the ThinLTO module. if (const BitcodeModule *Bm = FindThinLTOModule(*BMsOrErr)) return *Bm; return make_error(""Could not find module summary"", inconvertibleErrorCode()); } BitcodeModule *clang::FindThinLTOModule(MutableArrayRef BMs) { for (BitcodeModule &BM : BMs) { Expected LTOInfo = BM.getLTOInfo(); if (LTOInfo && LTOInfo->IsThinLTO) return &BM; } return nullptr; } static void runThinLTOBackend(ModuleSummaryIndex *CombinedIndex, Module *M, const HeaderSearchOptions &HeaderOpts, const CodeGenOptions &CGOpts, const clang::TargetOptions &TOpts, const LangOptions &LOpts, std::unique_ptr OS, std::string SampleProfile, std::string ProfileRemapping, BackendAction Action) { StringMap> ModuleToDefinedGVSummaries; CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries); setCommandLineOpts(CGOpts); // We can simply import the values mentioned in the combined index, since // we should only invoke this using the individual indexes written out // via a WriteIndexesThinBackend. FunctionImporter::ImportMapTy ImportList; for (auto &GlobalList : *CombinedIndex) { // Ignore entries for undefined references. if (GlobalList.second.SummaryList.empty()) continue; auto GUID = GlobalList.first; for (auto &Summary : GlobalList.second.SummaryList) { // Skip the summaries for the importing module. These are included to // e.g. record required linkage changes. if (Summary->modulePath() == M->getModuleIdentifier()) continue; // Add an entry to provoke importing by thinBackend. ImportList[Summary->modulePath()].insert(GUID); } } std::vector> OwnedImports; MapVector ModuleMap; for (auto &I : ImportList) { ErrorOr> MBOrErr = llvm::MemoryBuffer::getFile(I.first()); if (!MBOrErr) { errs() << ""Error loading imported file '"" << I.first() << ""': "" << MBOrErr.getError().message() << ""\\n""; return; } Expected BMOrErr = FindThinLTOModule(**MBOrErr); if (!BMOrErr) { handleAllErrors(BMOrErr.takeError(), [&](ErrorInfoBase &EIB) { errs() << ""Error loading imported file '"" << I.first() << ""': "" << EIB.message() << '\\n'; }); return; } ModuleMap.insert({I.first(), *BMOrErr}); OwnedImports.push_back(std::move(*MBOrErr)); } auto AddStream = [&](size_t Task) { return std::make_unique(std::move(OS)); }; lto::Config Conf; if (CGOpts.SaveTempsFilePrefix != """") { if (Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix + ""."", /* UseInputModulePath */ false)) { handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) { errs() << ""Error setting up ThinLTO save-temps: "" << EIB.message() << '\\n'; }); } } Conf.CPU = TOpts.CPU; Conf.CodeModel = getCodeModel(CGOpts); Conf.MAttrs = TOpts.Features; Conf.RelocModel = CGOpts.RelocationModel; Conf.CGOptLevel = getCGOptLevel(CGOpts); Conf.OptLevel = CGOpts.OptimizationLevel; initTargetOptions(Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts); Conf.SampleProfile = std::move(SampleProfile); Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops; // For historical reasons, loop interleaving is set to mirror setting for loop // unrolling. Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops; Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop; Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP; // Context sensitive profile. if (CGOpts.hasProfileCSIRInstr()) { Conf.RunCSIRInstr = true; Conf.CSIRProfile = std::move(CGOpts.InstrProfileOutput); } else if (CGOpts.hasProfileCSIRUse()) { Conf.RunCSIRInstr = false; Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath); } Conf.ProfileRemapping = std::move(ProfileRemapping); Conf.UseNewPM = CGOpts.ExperimentalNewPassManager; Conf.DebugPassManager = CGOpts.DebugPassManager; Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness; Conf.RemarksFilename = CGOpts.OptRecordFile; Conf.RemarksPasses = CGOpts.OptRecordPasses; Conf.RemarksFormat = CGOpts.OptRecordFormat; Conf.SplitDwarfFile = CGOpts.SplitDwarfFile; Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput; switch (Action) { case Backend_EmitNothing: Conf.PreCodeGenModuleHook = [](size_t Task, const Module &Mod) { return false; }; break; case Backend_EmitLL: Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) { M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists); return false; }; break; case Backend_EmitBC: Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) { WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists); return false; }; break; default: Conf.CGFileType = getCodeGenFileType(Action); break; } if (Error E = thinBackend( Conf, -1, AddStream, *M, *CombinedIndex, ImportList, ModuleToDefinedGVSummaries[M->getModuleIdentifier()], ModuleMap)) { handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) { errs() << ""Error running ThinLTO backend: "" << EIB.message() << '\\n'; }); } } void clang::EmitBackendOutput(DiagnosticsEngine &Diags, const HeaderSearchOptions &HeaderOpts, const CodeGenOptions &CGOpts, const clang::TargetOptions &TOpts, const LangOptions &LOpts, const llvm::DataLayout &TDesc, Module *M, BackendAction Action, std::unique_ptr OS) { llvm::TimeTraceScope TimeScope(""Backend""); std::unique_ptr EmptyModule; if (!CGOpts.ThinLTOIndexFile.empty()) { // If we are performing a ThinLTO importing compile, load the function index // into memory and pass it into runThinLTOBackend, which will run the // function importer and invoke LTO passes. Expected> IndexOrErr = llvm::getModuleSummaryIndexForFile(CGOpts.ThinLTOIndexFile, /*IgnoreEmptyThinLTOIndexFile*/true); if (!IndexOrErr) { logAllUnhandledErrors(IndexOrErr.takeError(), errs(), ""Error loading index file '"" + CGOpts.ThinLTOIndexFile + ""': ""); return; } std::unique_ptr CombinedIndex = std::move(*IndexOrErr); // A null CombinedIndex means we should skip ThinLTO compilation // (LLVM will optionally ignore empty index files, returning null instead // of an error). if (CombinedIndex) { if (!CombinedIndex->skipModuleByDistributedBackend()) { runThinLTOBackend(CombinedIndex.get(), M, HeaderOpts, CGOpts, TOpts, LOpts, std::move(OS), CGOpts.SampleProfileFile, CGOpts.ProfileRemappingFile, Action); return; } // Distributed indexing detected that nothing from the module is needed // for the final linking. So we can skip the compilation. We sill need to // output an empty object file to make sure that a linker does not fail // trying to read it. Also for some features, like CFI, we must skip // the compilation as CombinedIndex does not contain all required // information. EmptyModule = std::make_unique(""empty"", M->getContext()); EmptyModule->setTargetTriple(M->getTargetTriple()); M = EmptyModule.get(); } } EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M); if (CGOpts.ExperimentalNewPassManager) AsmHelper.EmitAssemblyWithNewPassManager(Action, std::move(OS)); else AsmHelper.EmitAssembly(Action, std::move(OS)); // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's // DataLayout. if (AsmHelper.TM) { std::string DLDesc = M->getDataLayout().getStringRepresentation(); if (DLDesc != TDesc.getStringRepresentation()) { unsigned DiagID = Diags.getCustomDiagID( DiagnosticsEngine::Error, ""backend data layout '%0' does not match "" ""expected target description '%1'""); Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation(); } } } // With -fembed-bitcode, save a copy of the llvm IR as data in the // __LLVM,__bitcode section. void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts, llvm::MemoryBufferRef Buf) { if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off) return; llvm::EmbedBitcodeInModule( *M, Buf, CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker, CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode, &CGOpts.CmdArgs); } ",16247,True,3107.549991728815,median "[[FTPComponent]] FTP/SFTP/FTPS Component ~~~~~~~~~~~~~~~~~~~~~~~ This component provides access to remote file systems over the FTP and SFTP protocols. Maven users will need to add the following dependency to their `pom.xml` for this component: [source,xml] ----------------------------------------------------------------------- org.apache.camel camel-ftp x.x.xSee the documentation of the Apache Commons ----------------------------------------------------------------------- [Info] ==== More options See link:file2.html[File] for more options as all the options from link:file2.html[File] is inherited. ==== [Info] ==== Absolute paths Absolute path is *not* supported. *Camel 2.16* will translate absolute path to relative by trimming all leading slashes from `directoryname`. There'll be WARN message printed in the logs. ==== [Tip] ==== Consuming from remote FTP server Make sure you read the section titled _Default when consuming files_ further below for details related to consuming files. ==== [[FTP2-URIformat]] URI format ^^^^^^^^^^ [source,java] --------------------------------------------------------- ftp://[username@]hostname[:port]/directoryname[?options] sftp://[username@]hostname[:port]/directoryname[?options] ftps://[username@]hostname[:port]/directoryname[?options] --------------------------------------------------------- Where *directoryname* represents the underlying directory. The directory name is a relative path. Absolute path's is *not* supported. The relative path can contain nested folders, such as /inbox/us. For Camel versions before *Camel 2.16*, the directoryName *must* exist already as this component does not support the `autoCreate` option (which the file component does). The reason is that its the FTP administrator (FTP server) task to properly setup user accounts, and home directories with the right file permissions etc. For *Camel 2.16*, `autoCreate` option is supported. When consumer starts, before polling is scheduled, there's additional FTP operation performed to create the directory configured for endpoint. The default value for `autoCreate` is `true`. If no *username* is provided, then `anonymous` login is attempted using no password. + If no *port* number is provided, Camel will provide default values according to the protocol (ftp = 21, sftp = 22, ftps = 2222). You can append query options to the URI in the following format, `?option=value&option=value&...` This component uses two different libraries for the actual FTP work. FTP and FTPS uses http://commons.apache.org/net/[Apache Commons Net] while SFTP uses http://www.jcraft.com/jsch/[JCraft JSCH]. The FTPS component is only available in Camel 2.2 or newer. + FTPS (also known as FTP Secure) is an extension to FTP that adds support for the Transport Layer Security (TLS) and the Secure Sockets Layer (SSL) cryptographic protocols. [[FTP2-URIOptions]] URI Options ^^^^^^^^^^^ The options below are exclusive for the FTP component. [Info] ==== More options See link:file2.html[File] for more options as all the options from link:file2.html[File] is inherited. ==== // component options: START The FTP component has no options. // component options: END // endpoint options: START The FTP component supports 105 endpoint options which are listed below: {% raw %} [width=""100%"",cols=""2,1,1m,1m,5"",options=""header""] |======================================================================= | Name | Group | Default | Java Type | Description | host | common | | String | *Required* Hostname of the FTP server | port | common | | int | Port of the FTP server | directoryName | common | | String | The starting directory | binary | common | false | boolean | Specifies the file transfer mode BINARY or ASCII. Default is ASCII (false). | charset | common | | String | This option is used to specify the encoding of the file. You can use this on the consumer to specify the encodings of the files which allow Camel to know the charset it should load the file content in case the file content is being accessed. Likewise when writing a file you can use this option to specify which charset to write the file as well. | disconnect | common | false | boolean | Whether or not to disconnect from remote FTP server right after use. Disconnect will only disconnect the current connection to the FTP server. If you have a consumer which you want to stop then you need to stop the consumer/route instead. | doneFileName | common | | String | Producer: If provided then Camel will write a 2nd done file when the original file has been written. The done file will be empty. This option configures what file name to use. Either you can specify a fixed name. Or you can use dynamic placeholders. The done file will always be written in the same folder as the original file. Consumer: If provided Camel will only consume files if a done file exists. This option configures what file name to use. Either you can specify a fixed name. Or you can use dynamic placeholders.The done file is always expected in the same folder as the original file. Only $file.name and $file.name.noext is supported as dynamic placeholders. | fileName | common | | String | Use Expression such as File Language to dynamically set the filename. For consumers it's used as a filename filter. For producers it's used to evaluate the filename to write. If an expression is set it take precedence over the CamelFileName header. (Note: The header itself can also be an Expression). The expression options support both String and Expression types. If the expression is a String type it is always evaluated using the File Language. If the expression is an Expression type the specified Expression type is used - this allows you for instance to use OGNL expressions. For the consumer you can use it to filter filenames so you can for instance consume today's file using the File Language syntax: mydata-$date:now:yyyyMMdd.txt. The producers support the CamelOverruleFileName header which takes precedence over any existing CamelFileName header; the CamelOverruleFileName is a header that is used only once and makes it easier as this avoids to temporary store CamelFileName and have to restore it afterwards. | passiveMode | common | false | boolean | Sets passive mode connections. Default is active mode connections. | separator | common | UNIX | PathSeparator | Sets the path separator to be used. UNIX = Uses unix style path separator Windows = Uses windows style path separator Auto = (is default) Use existing path separator in file name | fastExistsCheck | common (advanced) | false | boolean | If set this option to be true camel-ftp will use the list file directly to check if the file exists. Since some FTP server may not support to list the file directly if the option is false camel-ftp will use the old way to list the directory and check if the file exists. This option also influences readLock=changed to control whether it performs a fast check to update file information or not. This can be used to speed up the process if the FTP server has a lot of files. | bridgeErrorHandler | consumer | false | boolean | 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/ERROR level and ignored. | delete | consumer | false | boolean | If true the file will be deleted after it is processed successfully. | moveFailed | consumer | | String | Sets the move failure expression based on Simple language. For example to move files into a .error subdirectory use: .error. Note: When moving the files to the fail location Camel will handle the error and will not pick up the file again. | noop | consumer | false | boolean | If true the file is not moved or deleted in any way. This option is good for readonly data or for ETL type requirements. If noop=true Camel will set idempotent=true as well to avoid consuming the same files over and over again. | preMove | consumer | | String | Expression (such as File Language) used to dynamically set the filename when moving it before processing. For example to move in-progress files into the order directory set this value to order. | recursive | consumer | false | boolean | If a directory will look for files in all the sub-directories as well. | sendEmptyMessageWhenIdle | consumer | false | boolean | If the polling consumer did not poll any files you can enable this option to send an empty message (no body) instead. | streamDownload | consumer | false | boolean | Sets the download method to use when not using a local working directory. If set to true the remote files are streamed to the route as they are read. When set to false the remote files are loaded into memory before being sent into the route. | directoryMustExist | consumer (advanced) | false | boolean | Similar to startingDirectoryMustExist but this applies during polling recursive sub directories. | download | consumer (advanced) | false | boolean | Whether the FTP consumer should download the file. If this option is set to false then the message body will be null but the consumer will still trigger a Camel Exchange that has details about the file such as file name file size etc. It's just that the file will not be downloaded. | exceptionHandler | consumer (advanced) | | ExceptionHandler | 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/ERROR level and ignored. | exchangePattern | consumer (advanced) | | ExchangePattern | Sets the exchange pattern when the consumer creates an exchange. | ignoreFileNotFoundOrPermissionError | consumer (advanced) | false | boolean | Whether to ignore when trying to download a file which does not exist or due to permission error. By default when a file does not exists or insufficient permission then an exception is thrown. Setting this option to true allows to ignore that instead. | inProgressRepository | consumer (advanced) | | String> | A pluggable in-progress repository org.apache.camel.spi.IdempotentRepository. The in-progress repository is used to account the current in progress files being consumed. By default a memory based repository is used. | localWorkDirectory | consumer (advanced) | | String | When consuming a local work directory can be used to store the remote file content directly in local files to avoid loading the content into memory. This is beneficial if you consume a very big remote file and thus can conserve memory. | onCompletionExceptionHandler | consumer (advanced) | | ExceptionHandler | To use a custom org.apache.camel.spi.ExceptionHandler to handle any thrown exceptions that happens during the file on completion process where the consumer does either a commit or rollback. The default implementation will log any exception at WARN level and ignore. | pollStrategy | consumer (advanced) | | PollingConsumerPollStrategy | A pluggable org.apache.camel.PollingConsumerPollingStrategy allowing you to provide your custom implementation to control error handling usually occurred during the poll operation before an Exchange have been created and being routed in Camel. | processStrategy | consumer (advanced) | | GenericFileProcessStrategy | A pluggable org.apache.camel.component.file.GenericFileProcessStrategy allowing you to implement your own readLock option or similar. Can also be used when special conditions must be met before a file can be consumed such as a special ready file exists. If this option is set then the readLock option does not apply. | receiveBufferSize | consumer (advanced) | 32768 | int | The receive (download) buffer size Used only by FTPClient | startingDirectoryMustExist | consumer (advanced) | false | boolean | Whether the starting directory must exist. Mind that the autoCreate option is default enabled which means the starting directory is normally auto created if it doesn't exist. You can disable autoCreate and enable this to ensure the starting directory must exist. Will thrown an exception if the directory doesn't exist. | useList | consumer (advanced) | true | boolean | Whether to allow using LIST command when downloading a file. Default is true. In some use cases you may want to download a specific file and are not allowed to use the LIST command and therefore you can set this option to false. | fileExist | producer | Override | GenericFileExist | What to do if a file already exists with the same name. Override which is the default replaces the existing file. Append - adds content to the existing file. Fail - throws a GenericFileOperationException indicating that there is already an existing file. Ignore - silently ignores the problem and does not override the existing file but assumes everything is okay. Move - option requires to use the moveExisting option to be configured as well. The option eagerDeleteTargetFile can be used to control what to do if an moving the file and there exists already an existing file otherwise causing the move operation to fail. The Move option will move any existing files before writing the target file. TryRename Camel is only applicable if tempFileName option is in use. This allows to try renaming the file from the temporary name to the actual name without doing any exists check.This check may be faster on some file systems and especially FTP servers. | flatten | producer | false | boolean | Flatten is used to flatten the file name path to strip any leading paths so it's just the file name. This allows you to consume recursively into sub-directories but when you eg write the files to another directory they will be written in a single directory. Setting this to true on the producer enforces that any file name in CamelFileName header will be stripped for any leading paths. | moveExisting | producer | | String | Expression (such as File Language) used to compute file name to use when fileExist=Move is configured. To move files into a backup subdirectory just enter backup. This option only supports the following File Language tokens: file:name file:name.ext file:name.noext file:onlyname file:onlyname.noext file:ext and file:parent. Notice the file:parent is not supported by the FTP component as the FTP component can only move any existing files to a relative directory based on current dir as base. | tempFileName | producer | | String | The same as tempPrefix option but offering a more fine grained control on the naming of the temporary filename as it uses the File Language. | tempPrefix | producer | | String | This option is used to write the file using a temporary name and then after the write is complete rename it to the real name. Can be used to identify files being written and also avoid consumers (not using exclusive read locks) reading in progress files. Is often used by FTP when uploading big files. | allowNullBody | producer (advanced) | false | boolean | Used to specify if a null body is allowed during file writing. If set to true then an empty file will be created when set to false and attempting to send a null body to the file component a GenericFileWriteException of 'Cannot write null body to file.' will be thrown. If the fileExist option is set to 'Override' then the file will be truncated and if set to append the file will remain unchanged. | chmod | producer (advanced) | | String | Allows you to set chmod on the stored file. For example chmod=640. | disconnectOnBatchComplete | producer (advanced) | false | boolean | Whether or not to disconnect from remote FTP server right after a Batch upload is complete. disconnectOnBatchComplete will only disconnect the current connection to the FTP server. | eagerDeleteTargetFile | producer (advanced) | true | boolean | Whether or not to eagerly delete any existing target file. This option only applies when you use fileExists=Override and the tempFileName option as well. You can use this to disable (set it to false) deleting the target file before the temp file is written. For example you may write big files and want the target file to exists during the temp file is being written. This ensure the target file is only deleted until the very last moment just before the temp file is being renamed to the target filename. This option is also used to control whether to delete any existing files when fileExist=Move is enabled and an existing file exists. If this option copyAndDeleteOnRenameFails false then an exception will be thrown if an existing file existed if its true then the existing file is deleted before the move operation. | keepLastModified | producer (advanced) | false | boolean | Will keep the last modified timestamp from the source file (if any). Will use the Exchange.FILE_LAST_MODIFIED header to located the timestamp. This header can contain either a java.util.Date or long with the timestamp. If the timestamp exists and the option is enabled it will set this timestamp on the written file. Note: This option only applies to the file producer. You cannot use this option with any of the ftp producers. | sendNoop | producer (advanced) | true | boolean | Whether to send a noop command as a pre-write check before uploading files to the FTP server. This is enabled by default as a validation of the connection is still valid which allows to silently re-connect to be able to upload the file. However if this causes problems you can turn this option off. | activePortRange | advanced | | String | Set the client side port range in active mode. The syntax is: minPort-maxPort Both port numbers are inclusive eg 10000-19999 to include all 1xxxx ports. | autoCreate | advanced | true | boolean | Automatically create missing directories in the file's pathname. For the file consumer that means creating the starting directory. For the file producer it means the directory the files should be written to. | bufferSize | advanced | 131072 | int | Write buffer sized in bytes. | connectTimeout | advanced | 10000 | int | Sets the connect timeout for waiting for a connection to be established Used by both FTPClient and JSCH | ftpClient | advanced | | FTPClient | To use a custom instance of FTPClient | ftpClientConfig | advanced | | FTPClientConfig | To use a custom instance of FTPClientConfig to configure the FTP client the endpoint should use. | ftpClientConfigParameters | advanced | | Map | Used by FtpComponent to provide additional parameters for the FTPClientConfig | ftpClientParameters | advanced | | Map | Used by FtpComponent to provide additional parameters for the FTPClient | maximumReconnectAttempts | advanced | | int | Specifies the maximum reconnect attempts Camel performs when it tries to connect to the remote FTP server. Use 0 to disable this behavior. | reconnectDelay | advanced | | long | Delay in millis Camel will wait before performing a reconnect attempt. | siteCommand | advanced | | String | Sets optional site command(s) to be executed after successful login. Multiple site commands can be separated using a new line character (\\n). | soTimeout | advanced | 300000 | int | Sets the so timeout Used only by FTPClient | stepwise | advanced | true | boolean | Sets whether we should stepwise change directories while traversing file structures when downloading files or as well when uploading a file to a directory. You can disable this if you for example are in a situation where you cannot change directory on the FTP server due security reasons. | synchronous | advanced | false | boolean | Sets whether synchronous processing should be strictly used or Camel is allowed to use asynchronous processing (if supported). | throwExceptionOnConnectFailed | advanced | false | boolean | Should an exception be thrown if connection failed (exhausted) By default exception is not thrown and a WARN is logged. You can use this to enable exception being thrown and handle the thrown exception from the org.apache.camel.spi.PollingConsumerPollStrategy rollback method. | timeout | advanced | 30000 | int | Sets the data timeout for waiting for reply Used only by FTPClient | antExclude | filter | | String | Ant style filter exclusion. If both antInclude and antExclude are used antExclude takes precedence over antInclude. Multiple exclusions may be specified in comma-delimited format. | antFilterCaseSensitive | filter | true | boolean | Sets case sensitive flag on ant fiter | antInclude | filter | | String | Ant style filter inclusion. Multiple inclusions may be specified in comma-delimited format. | eagerMaxMessagesPerPoll | filter | true | boolean | Allows for controlling whether the limit from maxMessagesPerPoll is eager or not. If eager then the limit is during the scanning of files. Where as false would scan all files and then perform sorting. Setting this option to false allows for sorting all files first and then limit the poll. Mind that this requires a higher memory usage as all file details are in memory to perform the sorting. | exclude | filter | | String | Is used to exclude files if filename matches the regex pattern (matching is case in-senstive). Notice if you use symbols such as plus sign and others you would need to configure this using the RAW() syntax if configuring this as an endpoint uri. See more details at configuring endpoint uris | filter | filter | | GenericFileFilter | Pluggable filter as a org.apache.camel.component.file.GenericFileFilter class. Will skip files if filter returns false in its accept() method. | filterDirectory | filter | | String | Filters the directory based on Simple language. For example to filter on current date you can use a simple date pattern such as $date:now:yyyMMdd | filterFile | filter | | String | Filters the file based on Simple language. For example to filter on file size you can use $file:size 5000 | idempotent | filter | false | Boolean | Option to use the Idempotent Consumer EIP pattern to let Camel skip already processed files. Will by default use a memory based LRUCache that holds 1000 entries. If noop=true then idempotent will be enabled as well to avoid consuming the same files over and over again. | idempotentKey | filter | | String | To use a custom idempotent key. By default the absolute path of the file is used. You can use the File Language for example to use the file name and file size you can do: idempotentKey=$file:name-$file:size | idempotentRepository | filter | | String> | A pluggable repository org.apache.camel.spi.IdempotentRepository which by default use MemoryMessageIdRepository if none is specified and idempotent is true. | include | filter | | String | Is used to include files if filename matches the regex pattern (matching is case in-senstive). Notice if you use symbols such as plus sign and others you would need to configure this using the RAW() syntax if configuring this as an endpoint uri. See more details at configuring endpoint uris | maxDepth | filter | 2147483647 | int | The maximum depth to traverse when recursively processing a directory. | maxMessagesPerPoll | filter | | int | To define a maximum messages to gather per poll. By default no maximum is set. Can be used to set a limit of e.g. 1000 to avoid when starting up the server that there are thousands of files. Set a value of 0 or negative to disabled it. Notice: If this option is in use then the File and FTP components will limit before any sorting. For example if you have 100000 files and use maxMessagesPerPoll=500 then only the first 500 files will be picked up and then sorted. You can use the eagerMaxMessagesPerPoll option and set this to false to allow to scan all files first and then sort afterwards. | minDepth | filter | | int | The minimum depth to start processing when recursively processing a directory. Using minDepth=1 means the base directory. Using minDepth=2 means the first sub directory. | move | filter | | String | Expression (such as Simple Language) used to dynamically set the filename when moving it after processing. To move files into a .done subdirectory just enter .done. | exclusiveReadLockStrategy | lock | | GenericFileExclusiveReadLockStrategy | Pluggable read-lock as a org.apache.camel.component.file.GenericFileExclusiveReadLockStrategy implementation. | readLock | lock | | String | Used by consumer to only poll the files if it has exclusive read-lock on the file (i.e. the file is not in-progress or being written). Camel will wait until the file lock is granted. This option provides the build in strategies: none - No read lock is in use markerFile - Camel creates a marker file (fileName.camelLock) and then holds a lock on it. This option is not available for the FTP component changed - Changed is using file length/modification timestamp to detect whether the file is currently being copied or not. Will at least use 1 sec to determine this so this option cannot consume files as fast as the others but can be more reliable as the JDK IO API cannot always determine whether a file is currently being used by another process. The option readLockCheckInterval can be used to set the check frequency. fileLock - is for using java.nio.channels.FileLock. This option is not avail for the FTP component. This approach should be avoided when accessing a remote file system via a mount/share unless that file system supports distributed file locks. rename - rename is for using a try to rename the file as a test if we can get exclusive read-lock. idempotent - (only for file component) idempotent is for using a idempotentRepository as the read-lock. This allows to use read locks that supports clustering if the idempotent repository implementation supports that. Notice: The various read locks is not all suited to work in clustered mode where concurrent consumers on different nodes is competing for the same files on a shared file system. The markerFile using a close to atomic operation to create the empty marker file but its not guaranteed to work in a cluster. The fileLock may work better but then the file system need to support distributed file locks and so on. Using the idempotent read lock can support clustering if the idempotent repository supports clustering such as Hazelcast Component or Infinispan. | readLockCheckInterval | lock | 1000 | long | Interval in millis for the read-lock if supported by the read lock. This interval is used for sleeping between attempts to acquire the read lock. For example when using the changed read lock you can set a higher interval period to cater for slow writes. The default of 1 sec. may be too fast if the producer is very slow writing the file. Notice: For FTP the default readLockCheckInterval is 5000. The readLockTimeout value must be higher than readLockCheckInterval but a rule of thumb is to have a timeout that is at least 2 or more times higher than the readLockCheckInterval. This is needed to ensure that amble time is allowed for the read lock process to try to grab the lock before the timeout was hit. | readLockDeleteOrphanLockFiles | lock | true | boolean | Whether or not read lock with marker files should upon startup delete any orphan read lock files which may have been left on the file system if Camel was not properly shutdown (such as a JVM crash). If turning this option to false then any orphaned lock file will cause Camel to not attempt to pickup that file this could also be due another node is concurrently reading files from the same shared directory. | readLockLoggingLevel | lock | WARN | LoggingLevel | Logging level used when a read lock could not be acquired. By default a WARN is logged. You can change this level for example to OFF to not have any logging. This option is only applicable for readLock of types: changed fileLock rename. | readLockMarkerFile | lock | true | boolean | Whether to use marker file with the changed rename or exclusive read lock types. By default a marker file is used as well to guard against other processes picking up the same files. This behavior can be turned off by setting this option to false. For example if you do not want to write marker files to the file systems by the Camel application. | readLockMinAge | lock | 0 | long | This option applied only for readLock=change. This option allows to specify a minimum age the file must be before attempting to acquire the read lock. For example use readLockMinAge=300s to require the file is at last 5 minutes old. This can speedup the changed read lock as it will only attempt to acquire files which are at least that given age. | readLockMinLength | lock | 1 | long | This option applied only for readLock=changed. This option allows you to configure a minimum file length. By default Camel expects the file to contain data and thus the default value is 1. You can set this option to zero to allow consuming zero-length files. | readLockRemoveOnCommit | lock | false | boolean | This option applied only for readLock=idempotent. This option allows to specify whether to remove the file name entry from the idempotent repository when processing the file is succeeded and a commit happens. By default the file is not removed which ensures that any race-condition do not occur so another active node may attempt to grab the file. Instead the idempotent repository may support eviction strategies that you can configure to evict the file name entry after X minutes - this ensures no problems with race conditions. | readLockRemoveOnRollback | lock | true | boolean | This option applied only for readLock=idempotent. This option allows to specify whether to remove the file name entry from the idempotent repository when processing the file failed and a rollback happens. If this option is false then the file name entry is confirmed (as if the file did a commit). | readLockTimeout | lock | 10000 | long | Optional timeout in millis for the read-lock if supported by the read-lock. If the read-lock could not be granted and the timeout triggered then Camel will skip the file. At next poll Camel will try the file again and this time maybe the read-lock could be granted. Use a value of 0 or lower to indicate forever. Currently fileLock changed and rename support the timeout. Notice: For FTP the default readLockTimeout value is 20000 instead of 10000. The readLockTimeout value must be higher than readLockCheckInterval but a rule of thumb is to have a timeout that is at least 2 or more times higher than the readLockCheckInterval. This is needed to ensure that amble time is allowed for the read lock process to try to grab the lock before the timeout was hit. | backoffErrorThreshold | scheduler | | int | The number of subsequent error polls (failed due some error) that should happen before the backoffMultipler should kick-in. | backoffIdleThreshold | scheduler | | int | The number of subsequent idle polls that should happen before the backoffMultipler should kick-in. | backoffMultiplier | scheduler | | int | To let the scheduled polling consumer backoff if there has been a number of subsequent idles/errors in a row. The multiplier is then the number of polls that will be skipped before the next actual attempt is happening again. When this option is in use then backoffIdleThreshold and/or backoffErrorThreshold must also be configured. | delay | scheduler | 500 | long | Milliseconds before the next poll. You can also specify time values using units such as 60s (60 seconds) 5m30s (5 minutes and 30 seconds) and 1h (1 hour). | greedy | scheduler | false | boolean | If greedy is enabled then the ScheduledPollConsumer will run immediately again if the previous run polled 1 or more messages. | initialDelay | scheduler | 1000 | long | Milliseconds before the first poll starts. You can also specify time values using units such as 60s (60 seconds) 5m30s (5 minutes and 30 seconds) and 1h (1 hour). | runLoggingLevel | scheduler | TRACE | LoggingLevel | The consumer logs a start/complete log line when it polls. This option allows you to configure the logging level for that. | scheduledExecutorService | scheduler | | ScheduledExecutorService | Allows for configuring a custom/shared thread pool to use for the consumer. By default each consumer has its own single threaded thread pool. | scheduler | scheduler | none | ScheduledPollConsumerScheduler | To use a cron scheduler from either camel-spring or camel-quartz2 component | schedulerProperties | scheduler | | Map | To configure additional properties when using a custom scheduler or any of the Quartz2 Spring based scheduler. | startScheduler | scheduler | true | boolean | Whether the scheduler should be auto started. | timeUnit | scheduler | MILLISECONDS | TimeUnit | Time unit for initialDelay and delay options. | useFixedDelay | scheduler | true | boolean | Controls if fixed delay or fixed rate is used. See ScheduledExecutorService in JDK for details. | shuffle | sort | false | boolean | To shuffle the list of files (sort in random order) | sortBy | sort | | String | Built-in sort by using the File Language. Supports nested sorts so you can have a sort by file name and as a 2nd group sort by modified date. | sorter | sort | | GenericFile> | Pluggable sorter as a java.util.Comparator class. | account | security | | String | Account to use for login | password | security | | String | Password to use for login | username | security | | String | Username to use for login |======================================================================= {% endraw %} // endpoint options: END [Info] ==== FTPS component default trust store When using the `ftpClient.` properties related to SSL with the FTPS component, the trust store accept all certificates. If you only want trust selective certificates, you have to configure the trust store with the `ftpClient.trustStore.xxx` options or by configuring a custom `ftpClient`. When using `sslContextParameters`, the trust store is managed by the configuration of the provided SSLContextParameters instance. ==== You can configure additional options on the `ftpClient` and `ftpClientConfig` from the URI directly by using the `ftpClient.` or `ftpClientConfig.` prefix. For example to set the `setDataTimeout` on the `FTPClient` to 30 seconds you can do: [source,java] -------------------------------------------------------------------------------------- from(""ftp://foo@myserver?password=secret&ftpClient.dataTimeout=30000"").to(""bean:foo""); -------------------------------------------------------------------------------------- You can mix and match and have use both prefixes, for example to configure date format or timezones. [source,java] ---------------------------------------------------------------------------------------------------------------------------- from(""ftp://foo@myserver?password=secret&ftpClient.dataTimeout=30000&ftpClientConfig.serverLanguageCode=fr"").to(""bean:foo""); ---------------------------------------------------------------------------------------------------------------------------- You can have as many of these options as you like. See the documentation of the Apache Commons FTP FTPClientConfig for possible options and more details. And as well for Apache Commons FTP FTPClient. If you do not like having many and long configuration in the url you can refer to the `ftpClient` or `ftpClientConfig` to use by letting Camel lookup in the link:registry.html[Registry] for it. For example: [source,java] -------------------------------------------------------------------------- -------------------------------------------------------------------------- And then let Camel lookup this bean when you use the # notation in the url. [source,java] ------------------------------------------------------------------------------------ from(""ftp://foo@myserver?password=secret&ftpClientConfig=#myConfig"").to(""bean:foo""); ------------------------------------------------------------------------------------ [[FTP2-MoreURIoptions]] More URI options ^^^^^^^^^^^^^^^^ [Info] ==== See link:file2.html[File2] as all the options there also applies for this component. ==== [[FTP2-Examples]] Examples ^^^^^^^^ `ftp://someone@someftpserver.com/public/upload/images/holiday2008?password=secret&binary=true` + `ftp://someoneelse@someotherftpserver.co.uk:12049/reports/2008/password=secret&binary=false` + `ftp://publicftpserver.com/download` [Warning] ==== FTP Consumer does not support concurrency The FTP consumer (with the same endpoint) does not support concurrency (the backing FTP client is not thread safe). + You can use multiple FTP consumers to poll from different endpoints. It is only a single endpoint that does not support concurrent consumers. The FTP producer does *not* have this issue, it supports concurrency. ==== [Tip] ==== More information This component is an extension of the link:file2.html[File] component. So there are more samples and details on the link:file2.html[File] component page. ==== [[FTP2-Defaultwhenconsumingfiles]] Default when consuming files ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The link:ftp2.html[FTP] consumer will by default leave the consumed files untouched on the remote FTP server. You have to configure it explicitly if you want it to delete the files or move them to another location. For example you can use `delete=true` to delete the files, or use `move=.done` to move the files into a hidden done sub directory. The regular link:file2.html[File] consumer is different as it will by default move files to a `.camel` sub directory. The reason Camel does *not* do this by default for the FTP consumer is that it may lack permissions by default to be able to move or delete files. [[FTP2-limitations]] limitations +++++++++++ The option *readLock* can be used to force Camel *not* to consume files that is currently in the progress of being written. However, this option is turned off by default, as it requires that the user has write access. See the options table at link:file2.html[File2] for more details about read locks. + There are other solutions to avoid consuming files that are currently being written over FTP; for instance, you can write to a temporary destination and move the file after it has been written. When moving files using `move` or `preMove` option the files are restricted to the FTP_ROOT folder. That prevents you from moving files outside the FTP area. If you want to move files to another area you can use soft links and move files into a soft linked folder. [[FTP2-MessageHeaders]] Message Headers ^^^^^^^^^^^^^^^ The following message headers can be used to affect the behavior of the component [width=""100%"",cols=""50%,50%"",options=""header"",] |======================================================================= |Header |Description |`CamelFileName` |Specifies the output file name (relative to the endpoint directory) to be used for the output message when sending to the endpoint. If this is not present and no expression either, then a generated message ID is used as the filename instead. |`CamelFileNameProduced` |The actual filepath (path + name) for the output file that was written. This header is set by Camel and its purpose is providing end-users the name of the file that was written. |`CamelFileIndex` |Current index out of total number of files being consumed in this batch. |`CamelFileSize` |Total number of files being consumed in this batch. |`CamelFileHost` |The remote hostname. |`CamelFileLocalWorkPath` |Path to the local work file, if local work directory is used. |======================================================================= In addition the FTP/FTPS consumer and producer will enrich the Camel `Message` with the following headers [width=""100%"",cols=""50%,50%"",options=""header"",] |======================================================================= |Header |Description |`CamelFtpReplyCode` |*Camel 2.11.1:* The FTP client reply code (the type is a integer) |`CamelFtpReplyString` | *Camel 2.11.1:* The FTP client reply string |======================================================================= [[FTP2-Abouttimeouts]] About timeouts ^^^^^^^^^^^^^^ The two set of libraries (see top) has different API for setting timeout. You can use the `connectTimeout` option for both of them to set a timeout in millis to establish a network connection. An individual `soTimeout` can also be set on the FTP/FTPS, which corresponds to using `ftpClient.soTimeout`. Notice SFTP will automatically use `connectTimeout` as its `soTimeout`. The `timeout` option only applies for FTP/FTSP as the data timeout, which corresponds to the `ftpClient.dataTimeout` value. All timeout values are in millis. [[FTP2-UsingLocalWorkDirectory]] Using Local Work Directory ^^^^^^^^^^^^^^^^^^^^^^^^^^ Camel supports consuming from remote FTP servers and downloading the files directly into a local work directory. This avoids reading the entire remote file content into memory as it is streamed directly into the local file using `FileOutputStream`. Camel will store to a local file with the same name as the remote file, though with `.inprogress` as extension while the file is being downloaded. Afterwards, the file is renamed to remove the `.inprogress` suffix. And finally, when the link:exchange.html[Exchange] is complete the local file is deleted. So if you want to download files from a remote FTP server and store it as files then you need to route to a file endpoint such as: [source,java] ------------------------------------------------------------------------------------------------ from(""ftp://someone@someserver.com?password=secret&localWorkDirectory=/tmp"").to(""file://inbox""); ------------------------------------------------------------------------------------------------ [Tip] ==== *Optimization by renaming work file* The route above is ultra efficient as it avoids reading the entire file content into memory. It will download the remote file directly to a local file stream. The `java.io.File` handle is then used as the link:exchange.html[Exchange] body. The file producer leverages this fact and can work directly on the work file `java.io.File` handle and perform a `java.io.File.rename` to the target filename. As Camel knows it's a local work file, it can optimize and use a rename instead of a file copy, as the work file is meant to be deleted anyway. ==== [[FTP2-Stepwisechangingdirectories]] Stepwise changing directories ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Camel link:ftp2.html[FTP] can operate in two modes in terms of traversing directories when consuming files (eg downloading) or producing files (eg uploading) * stepwise * not stepwise You may want to pick either one depending on your situation and security issues. Some Camel end users can only download files if they use stepwise, while others can only download if they do not. At least you have the choice to pick (from Camel 2.6 onwards). In Camel 2.0 - 2.5 there is only one mode and it is: * before 2.5 not stepwise * 2.5 stepwise From Camel 2.6 onwards there is now an option `stepwise` you can use to control the behavior. Note that stepwise changing of directory will in most cases only work when the user is confined to it's home directory and when the home directory is reported as `""/""`. The difference between the two of them is best illustrated with an example. Suppose we have the following directory structure on the remote FTP server we need to traverse and download files: [source,java] -------------- / /one /one/two /one/two/sub-a /one/two/sub-b -------------- And that we have a file in each of sub-a (a.txt) and sub-b (b.txt) folder. [[FTP2-Usingstepwise]] Using stepwise=true (default mode) ++++++++++++++++++++++++++++++++++ [source,java] ---------------------------------------------------------- TYPE A 200 Type set to A PWD 257 ""/"" is current directory. CWD one 250 CWD successful. ""/one"" is current directory. CWD two 250 CWD successful. ""/one/two"" is current directory. SYST 215 UNIX emulated by FileZilla PORT 127,0,0,1,17,94 200 Port command successful LIST 150 Opening data channel for directory list. 226 Transfer OK CWD sub-a 250 CWD successful. ""/one/two/sub-a"" is current directory. PORT 127,0,0,1,17,95 200 Port command successful LIST 150 Opening data channel for directory list. 226 Transfer OK CDUP 200 CDUP successful. ""/one/two"" is current directory. CWD sub-b 250 CWD successful. ""/one/two/sub-b"" is current directory. PORT 127,0,0,1,17,96 200 Port command successful LIST 150 Opening data channel for directory list. 226 Transfer OK CDUP 200 CDUP successful. ""/one/two"" is current directory. CWD / 250 CWD successful. ""/"" is current directory. PWD 257 ""/"" is current directory. CWD one 250 CWD successful. ""/one"" is current directory. CWD two 250 CWD successful. ""/one/two"" is current directory. PORT 127,0,0,1,17,97 200 Port command successful RETR foo.txt 150 Opening data channel for file transfer. 226 Transfer OK CWD / 250 CWD successful. ""/"" is current directory. PWD 257 ""/"" is current directory. CWD one 250 CWD successful. ""/one"" is current directory. CWD two 250 CWD successful. ""/one/two"" is current directory. CWD sub-a 250 CWD successful. ""/one/two/sub-a"" is current directory. PORT 127,0,0,1,17,98 200 Port command successful RETR a.txt 150 Opening data channel for file transfer. 226 Transfer OK CWD / 250 CWD successful. ""/"" is current directory. PWD 257 ""/"" is current directory. CWD one 250 CWD successful. ""/one"" is current directory. CWD two 250 CWD successful. ""/one/two"" is current directory. CWD sub-b 250 CWD successful. ""/one/two/sub-b"" is current directory. PORT 127,0,0,1,17,99 200 Port command successful RETR b.txt 150 Opening data channel for file transfer. 226 Transfer OK CWD / 250 CWD successful. ""/"" is current directory. QUIT 221 Goodbye disconnected. ---------------------------------------------------------- As you can see when stepwise is enabled, it will traverse the directory structure using CD xxx. [[FTP2-Notusingstepwise]] Using stepwise=false ++++++++++++++++++++ [source,java] ------------------------------------------- 230 Logged on TYPE A 200 Type set to A SYST 215 UNIX emulated by FileZilla PORT 127,0,0,1,4,122 200 Port command successful LIST one/two 150 Opening data channel for directory list 226 Transfer OK PORT 127,0,0,1,4,123 200 Port command successful LIST one/two/sub-a 150 Opening data channel for directory list 226 Transfer OK PORT 127,0,0,1,4,124 200 Port command successful LIST one/two/sub-b 150 Opening data channel for directory list 226 Transfer OK PORT 127,0,0,1,4,125 200 Port command successful RETR one/two/foo.txt 150 Opening data channel for file transfer. 226 Transfer OK PORT 127,0,0,1,4,126 200 Port command successful RETR one/two/sub-a/a.txt 150 Opening data channel for file transfer. 226 Transfer OK PORT 127,0,0,1,4,127 200 Port command successful RETR one/two/sub-b/b.txt 150 Opening data channel for file transfer. 226 Transfer OK QUIT 221 Goodbye disconnected. ------------------------------------------- As you can see when not using stepwise, there are no CD operation invoked at all. [[FTP2-Samples]] Samples ^^^^^^^ In the sample below we set up Camel to download all the reports from the FTP server once every hour (60 min) as BINARY content and store it as files on the local file system. And the route using Spring DSL: [source,xml] ------------------------------------------------------------------------------------------------------ ------------------------------------------------------------------------------------------------------ [[FTP2-ConsumingaremoteFTPSserverimplicitSSLandclientauthentication]] Consuming a remote FTPS server (implicit SSL) and client authentication +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ [source,java] -------------------------------------------------------------------------------------------------- from(""ftps://admin@localhost:2222/public/camel?password=admin&securityProtocol=SSL&isImplicit=true &ftpClient.keyStore.file=./src/test/resources/server.jks &ftpClient.keyStore.password=password&ftpClient.keyStore.keyPassword=password"") .to(""bean:foo""); -------------------------------------------------------------------------------------------------- [[FTP2-ConsumingaremoteFTPSserverexplicitTLSandacustomtruststoreconfiguration]] Consuming a remote FTPS server (explicit TLS) and a custom trust store configuration ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ [source,java] ---------------------------------------------------------------------------------------------------------------------------------------------------------------- from(""ftps://admin@localhost:2222/public/camel?password=admin&ftpClient.trustStore.file=./src/test/resources/server.jks&ftpClient.trustStore.password=password"") .to(""bean:foo""); ---------------------------------------------------------------------------------------------------------------------------------------------------------------- [[FTP2-Filterusingorg.apache.camel.component.file.GenericFileFilter]] Filter using `org.apache.camel.component.file.GenericFileFilter` ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Camel supports pluggable filtering strategies. This strategy it to use the build in `org.apache.camel.component.file.GenericFileFilter` in Java. You can then configure the endpoint with such a filter to skip certain filters before being processed. In the sample we have built our own filter that only accepts files starting with report in the filename. And then we can configure our route using the *filter* attribute to reference our filter (using `#` notation) that we have defined in the spring XML file: [source,xml] --------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------- [[FTP2-FilteringusingANTpathmatcher]] Filtering using ANT path matcher ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The ANT path matcher is a filter that is shipped out-of-the-box in the *camel-spring* jar. So you need to depend on *camel-spring* if you are using Maven. + The reason is that we leverage Spring's http://static.springsource.org/spring/docs/3.0.x/api/org/springframework/util/AntPathMatcher.html[AntPathMatcher] to do the actual matching. The file paths are matched with the following rules: * `?` matches one character * `*` matches zero or more characters * `**` matches zero or more directories in a path The sample below demonstrates how to use it: [[FTP2-UsingaproxywithSFTP]] Using a proxy with SFTP ^^^^^^^^^^^^^^^^^^^^^^^ To use an HTTP proxy to connect to your remote host, you can configure your route in the following way: [source,xml] ------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- You can also assign a user name and password to the proxy, if necessary. Please consult the documentation for `com.jcraft.jsch.Proxy` to discover all options. [[FTP2-SettingpreferredSFTPauthenticationmethod]] Setting preferred SFTP authentication method ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ If you want to explicitly specify the list of authentication methods that should be used by `sftp` component, use `preferredAuthentications` option. If for example you would like Camel to attempt to authenticate with private/public SSH key and fallback to user/password authentication in the case when no public key is available, use the following route configuration: [source,java] ------------------------------------------------------------------------------------------------------------- from(""sftp://localhost:9999/root?username=admin&password=admin&preferredAuthentications=publickey,password""). to(""bean:processFile""); ------------------------------------------------------------------------------------------------------------- [[FTP2-Consumingasinglefileusingafixedname]] Consuming a single file using a fixed name ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ When you want to download a single file and knows the file name, you can use `fileName=myFileName.txt` to tell Camel the name of the file to download. By default the consumer will still do a FTP LIST command to do a directory listing and then filter these files based on the `fileName` option. Though in this use-case it may be desirable to turn off the directory listing by setting `useList=false`. For example the user account used to login to the FTP server may not have permission to do a FTP LIST command. So you can turn off this with `useList=false`, and then provide the fixed name of the file to download with `fileName=myFileName.txt`, then the FTP consumer can still download the file. If the file for some reason does not exist, then Camel will by default throw an exception, you can turn this off and ignore this by setting `ignoreFileNotFoundOrPermissionError=true`. For example to have a Camel route that pickup a single file, and delete it after use you can do [source,java] ------------------------------------------------------------------------------------------------------------------------------------------------------------- from(""ftp://admin@localhost:21/nolist/?password=admin&stepwise=false&useList=false&ignoreFileNotFoundOrPermissionError=true&fileName=report.txt&delete=true"") .to(""activemq:queue:report""); ------------------------------------------------------------------------------------------------------------------------------------------------------------- Notice that we have use all the options we talked above above. You can also use this with `ConsumerTemplate`. For example to download a single file (if it exists) and grab the file content as a String type: [source,java] ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- String data = template.retrieveBodyNoWait(""ftp://admin@localhost:21/nolist/?password=admin&stepwise=false&useList=false&ignoreFileNotFoundOrPermissionError=true&fileName=report.txt&delete=true"", String.class); ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- [[FTP2-Debuglogging]] Debug logging ^^^^^^^^^^^^^ This component has log level *TRACE* that can be helpful if you have problems. [[FTP2-SeeAlso]] See Also ^^^^^^^^ * link:configuring-camel.html[Configuring Camel] * link:component.html[Component] * link:endpoint.html[Endpoint] * link:getting-started.html[Getting Started] * link:file2.html[File2] ",12160,False,2046.0979399783132,median "/*++ Copyright (c) 1998-2000 Microsoft Corporation Module Name: rdpdr.cpp Abstract: This module implements the driver initialization for the RDP redirector, and the dispatch routines for the master device object. The master device object mostly ignores real I/O operations Environment: Kernel mode --*/ #include ""precomp.hxx"" #define TRC_FILE ""rdpdr"" #include ""trc.h"" #include ""ntddmup.h"" #include ""TSQPublic.h"" HANDLE DrSystemProcessId; PSECURITY_DESCRIPTOR DrAdminSecurityDescriptor = NULL; ULONG DrSecurityDescriptorLength = 0; extern ULONG DebugBreakOnEntry; // // Default USBMON Port Write Size. Need to keep it under 64k for // 16-bit clients ... otherwise, the go off the end of a segment. // ULONG PrintPortWriteSize; ULONG PrintPortWriteSizeDefault = 63000; // bytes // // Maximum numer of TS worker threads // #define MAX_WORKER_THREADS_COUNT 5 ULONG MaxWorkerThreadsDefault = MAX_WORKER_THREADS_COUNT; ULONG MaxWorkerThreads = MAX_WORKER_THREADS_COUNT; // The TS Worker Queue pointer PVOID RDPDR_TsQueue = NULL; // // Configure Devices to send IO packets to client at low priority. // ULONG DeviceLowPrioSendFlags; ULONG DeviceLowPrioSendFlagsDefault = DEVICE_LOWPRIOSEND_PRINTERS; extern ""C"" BOOLEAN RxForceQFIPassThrough; NTSTATUS DrCreateSCardDevice(SmartPtr &Session, PV_NET_ROOT pVNetRoot, SmartPtr &Device); // // This is the minirdr dispatch table. It is initialized by DrInitializeTables. // This table will be used by the wrapper to call into this minirdr // struct _MINIRDR_DISPATCH DrDispatch; #if DBG UCHAR IrpNames[IRP_MJ_MAXIMUM_FUNCTION + 1][40] = { ""IRP_MJ_CREATE "", ""IRP_MJ_CREATE_NAMED_PIPE "", ""IRP_MJ_CLOSE "", ""IRP_MJ_READ "", ""IRP_MJ_WRITE "", ""IRP_MJ_QUERY_INFORMATION "", ""IRP_MJ_SET_INFORMATION "", ""IRP_MJ_QUERY_EA "", ""IRP_MJ_SET_EA "", ""IRP_MJ_FLUSH_BUFFERS "", ""IRP_MJ_QUERY_VOLUME_INFORMATION"", ""IRP_MJ_SET_VOLUME_INFORMATION "", ""IRP_MJ_DIRECTORY_CONTROL "", ""IRP_MJ_FILE_SYSTEM_CONTROL "", ""IRP_MJ_DEVICE_CONTROL "", ""IRP_MJ_INTERNAL_DEVICE_CONTROL "", ""IRP_MJ_SHUTDOWN "", ""IRP_MJ_LOCK_CONTROL "", ""IRP_MJ_CLEANUP "", ""IRP_MJ_CREATE_MAILSLOT "", ""IRP_MJ_QUERY_SECURITY "", ""IRP_MJ_SET_SECURITY "", ""IRP_MJ_POWER "", ""IRP_MJ_SYSTEM_CONTROL "", ""IRP_MJ_DEVICE_CHANGE "", ""IRP_MJ_QUERY_QUOTA "", ""IRP_MJ_SET_QUOTA "", ""IRP_MJ_PNP "" }; #endif // DBG // // Pointer to the device Object for this minirdr. Since the device object is created // by the wrapper when this minirdr registers, this pointer is initialized in the // DriverEntry routine below (see RxRegisterMinirdr) // PRDBSS_DEVICE_OBJECT DrDeviceObject = NULL; PRDBSS_DEVICE_OBJECT DrPortDeviceObject = NULL; DrSessionManager *Sessions = NULL; // // A global spinlock // KSPIN_LOCK DrSpinLock; KIRQL DrOldIrql; // // A global mutex // FAST_MUTEX DrMutex; // // Global Registry Path for RDPDR.SYS // UNICODE_STRING DrRegistryPath; // // The following enumerated values signify the current state of the minirdr // initialization. With the aid of this state information, it is possible // to determine which resources to deallocate, whether deallocation comes // as a result of a normal stop/unload, or as the result of an exception // typedef enum tagDrInitStates { DrUninitialized, DrRegistered, DrInitialized } DrInitStates; // // function prototypes // extern ""C"" { NTSTATUS DrInitializeTables( void ); NTSTATUS CreateAdminSecurityDescriptor( VOID ); NTSTATUS BuildDeviceAcl( OUT PACL *DeviceAcl ); NTSTATUS DriverEntry( IN PDRIVER_OBJECT DriverObject, IN PUNICODE_STRING RegistryPath ); NTSTATUS DrPeekDispatch ( IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp ); VOID DrUninitialize( IN PDRIVER_OBJECT DriverObject, IN DrInitStates DrInitState ); NTSTATUS DrLoadRegistrySettings ( IN PCWSTR RegistryPath ); NTSTATUS DrStart( PRX_CONTEXT RxContext, IN OUT PRDBSS_DEVICE_OBJECT RxDeviceObject ); NTSTATUS DrStop( PRX_CONTEXT RxContext, IN OUT PRDBSS_DEVICE_OBJECT RxDeviceObject ); NTSTATUS DrDeallocateForFcb( IN OUT PMRX_FCB pFcb ); NTSTATUS ObGetObjectSecurity( IN PVOID Object, OUT PSECURITY_DESCRIPTOR *SecurityDescriptor, OUT PBOOLEAN MemoryAllocated ); VOID ObReleaseObjectSecurity( IN PSECURITY_DESCRIPTOR SecurityDescriptor, IN BOOLEAN MemoryAllocated ); NTSTATUS DriverEntry( IN PDRIVER_OBJECT DriverObject, IN PUNICODE_STRING RegistryPath ); }; BOOL GetDeviceFromRxContext(PRX_CONTEXT RxContext, SmartPtr &Device); #ifdef ALLOC_PRAGMA #pragma alloc_text(INIT, DriverEntry) #endif WCHAR DrDriverName[] = RDPDR_DEVICE_NAME_U; WCHAR DrPortDriverName[] = RDPDR_PORT_DEVICE_NAME_U; NTSTATUS DriverEntry( IN PDRIVER_OBJECT DriverObject, IN PUNICODE_STRING RegistryPath ) /*++ Routine Description: This is the initialization routine for the RDP mini redirector Arguments: DriverObject - Pointer to driver object created by the system. Return Value: RXSTATUS - The function value is the final status from the initialization operation. --*/ { NTSTATUS Status; UNICODE_STRING RdpDrName; UNICODE_STRING RdpDrPortName; PDEVICE_OBJECT RdpDrDevice; DrInitStates DrInitState = DrUninitialized; PRX_CONTEXT RxContext; PWCHAR path; BEGIN_FN(""DriverEntry""); #ifdef MONOLITHIC_MINIRDR Status = RxDriverEntry(DriverObject, RegistryPath); TRC_NRM((TB, ""BackFromInitWrapper %08lx"", Status)); if (!NT_SUCCESS(Status)) { TRC_ERR((TB, ""Wrapper failed to initialize. "" ""Status = %08lx"", Status)); DbgPrint(""rdpdr.sys erroring out (#1)\\n""); DbgBreakPoint(); return Status; } #endif // // Copy the registry path for RDPDR.SYS. // path = (PWCHAR)new(NonPagedPool) WCHAR[RegistryPath->Length + 1]; if (!path) { TRC_ERR((TB, ""DR:Failed to allocate registry path %Wz"", RegistryPath)); DbgPrint(""rdpdr.sys erroring out (#2)\\n""); DbgBreakPoint(); Status = STATUS_INSUFFICIENT_RESOURCES; return (Status); } RtlZeroMemory(path, RegistryPath->Length+sizeof(WCHAR)); RtlMoveMemory(path, RegistryPath->Buffer, RegistryPath->Length); DrRegistryPath.Length = RegistryPath->Length; DrRegistryPath.MaximumLength = RegistryPath->Length+sizeof(WCHAR); DrRegistryPath.Buffer = path; // // Load registry settings. // DrLoadRegistrySettings(path); #if DBG if (DebugBreakOnEntry) { DbgBreakPoint(); } #endif CodePageConversionInitialize(); // Initialize the client list KeInitializeSpinLock(&DrSpinLock); // Initialize the mutex object for device I/O transaction exchange ExInitializeFastMutex(&DrMutex); if (InitializeKernelUtilities()) { Status = STATUS_SUCCESS; } else { Status = STATUS_INSUFFICIENT_RESOURCES; DbgPrint(""rdpdr.sys erroring out (#3)\\n""); DbgBreakPoint(); } if (NT_SUCCESS(Status)) { Sessions = new(NonPagedPool) DrSessionManager; if (Sessions != NULL) { Status = STATUS_SUCCESS; TRC_NRM((TB, ""Created DrSessionManager"")); } else { TRC_ERR((TB, ""Unable to create DrSessionManager"")); Status = STATUS_INSUFFICIENT_RESOURCES; DbgPrint(""rdpdr.sys erroring out (#4)\\n""); DbgBreakPoint(); } } if (NT_SUCCESS(Status)) { RtlInitUnicodeString(&RdpDrPortName, DrPortDriverName); // Create the port device object. Status = IoCreateDevice(DriverObject, 0, &RdpDrPortName, FILE_DEVICE_NETWORK_REDIRECTOR, 0, FALSE, (PDEVICE_OBJECT *)(&DrPortDeviceObject)); } else { TRC_ERR((TB, ""IoCreateDevice failed: %08lx"", Status )); DbgPrint(""rdpdr.sys erroring out (#5)\\n""); DbgBreakPoint(); return Status; } if (NT_SUCCESS(Status)) { // // Register the RdpDr with the connection engine. Registration // makes the connection engine aware of the device name, driver // object, and other characteristics. If registration is successful, // a new device object is returned // // The name of the device is L""\\\\Device\\\\RdpDr"" // RtlInitUnicodeString(&RdpDrName, DrDriverName); TRC_DBG((TB, ""Registering minirdr"")); Status = RxRegisterMinirdr( &DrDeviceObject, // where the new device object goes DriverObject, // the Driver Object to register &DrDispatch, // the dispatch table for this driver RX_REGISTERMINI_FLAG_DONT_PROVIDE_MAILSLOTS, &RdpDrName, // the device name for this minirdr 0, // IN ULONG DeviceExtensionSize, FILE_DEVICE_NETWORK_FILE_SYSTEM, // In DEVICE_TYPE DeviceType 0 // IN ULONG DeviceCharacteristics ); } if (NT_SUCCESS(Status)) { PSECURITY_DESCRIPTOR RdpDrSD = NULL; BOOLEAN memoryAllocated = FALSE; TRC_NRM((TB, ""RxRegisterMinirdr succeeded."")); // // Get the SD for the rdpdr device object. // Apply the same SD to the rdp port device object. // if (NT_SUCCESS(ObGetObjectSecurity(DrDeviceObject, &RdpDrSD, &memoryAllocated))) { if (!NT_SUCCESS(ObSetSecurityObjectByPointer((PDEVICE_OBJECT)DrPortDeviceObject, DACL_SECURITY_INFORMATION, RdpDrSD ))) { // // We will ignore the error. // TRC_ERR((TB, ""ObSetSecurityObjectByPointer failed: 0x%08lx"", Status )); } ObReleaseObjectSecurity(RdpDrSD, memoryAllocated); } else { // // We will ignore the error. Just log the error // TRC_ERR((TB, ""ObGetObjectSecurity failed: 0x%08lx"", Status )); } // // After this we can't just return, some uninitialization is // needed if we fail or unload // DrInitState = DrRegistered; Status = CreateAdminSecurityDescriptor(); } else { TRC_ERR((TB, ""RxRegisterMinirdr failed: %08lx"", Status )); DbgPrint(""rdpdr.sys erroring out (#6)\\n""); DbgBreakPoint(); if (DrPortDeviceObject) { IoDeleteDevice((PDEVICE_OBJECT) DrPortDeviceObject); DrPortDeviceObject = NULL; } return Status; } if (NT_SUCCESS(Status)) { // // Build the dispatch tables for the minirdr // Status = DrInitializeTables(); } else { TRC_ERR((TB, ""CreateAdminSecurityDescriptor failed: 0x%08lx"", Status )); DbgPrint(""rdpdr.sys erroring out (#7)\\n""); DbgBreakPoint(); } // // Initialize our TS worker queue module. // TRC_NRM((TB, ""RDPDR: Initialize TS Worker Queue"")); RDPDR_TsQueue = TSInitQueue( TSQUEUE_OWN_THREAD, MaxWorkerThreads, (PDEVICE_OBJECT)DrDeviceObject ); if ( RDPDR_TsQueue == NULL) { TRC_ERR((TB, ""RDPDR: Failed to initialize the TS Queue"")); DbgPrint(""rdpdr.sys erroring out (#8)\\n""); Status = STATUS_INSUFFICIENT_RESOURCES; } if (NT_SUCCESS(Status)) { // // Setup Unload Routine // DriverObject->DriverUnload = DrUnload; // // Set up the PnP AddDevice entry point. // DriverObject->DriverExtension->AddDevice = RDPDRPNP_PnPAddDevice; // // setup the DriverDispatch for people who come in here directly // ....like the browser // { ULONG i; for (i = 0; i <= IRP_MJ_MAXIMUM_FUNCTION; i++) { DriverObject->MajorFunction[i] = (PDRIVER_DISPATCH)DrPeekDispatch; } } DrSystemProcessId = PsGetCurrentProcessId(); } else { DbgPrint(""rdpdr.sys erroring out (#9)\\n""); DbgBreakPoint(); DrUninitialize(DriverObject, DrInitState); } return Status; } VOID DrUninitialize( IN PDRIVER_OBJECT DriverObject, IN DrInitStates DrInitState ) /*++ Routine Description: This routine does the common uninit work Arguments: DrInitState - tells how far we got into the intialization Return Value: None --*/ { PRX_CONTEXT RxContext; NTSTATUS Status; BEGIN_FN(""DrUninitialize""); PAGED_CODE(); RxContext = RxCreateRxContext( NULL, DrDeviceObject, RX_CONTEXT_FLAG_IN_FSP); if (RxContext != NULL) { Status = RxStopMinirdr( RxContext, &RxContext->PostRequest); RxDereferenceAndDeleteRxContext(RxContext); } else { Status = STATUS_INSUFFICIENT_RESOURCES; } CodePageConversionCleanup(); if (DrAdminSecurityDescriptor) { delete DrAdminSecurityDescriptor; DrAdminSecurityDescriptor = NULL; DrSecurityDescriptorLength = 0; } if (Sessions != NULL) { delete Sessions; Sessions = NULL; } if (DrRegistryPath.Buffer != NULL) { delete DrRegistryPath.Buffer; DrRegistryPath.Buffer = NULL; } // // Delete the TS Queue // if ( RDPDR_TsQueue != NULL) { if (TSDeleteQueue( RDPDR_TsQueue ) != STATUS_SUCCESS) { TRC_ERR((TB, ""RDPDR: TsDeleteQueue Failed"")); } } UninitializeKernelUtilities(); switch (DrInitState) { case DrInitialized: #ifdef MONOLITHIC_MINIRDR RxUnload(DriverObject); #endif case DrRegistered: RxUnregisterMinirdr(DrDeviceObject); } if (DrPortDeviceObject) { IoDeleteDevice((PDEVICE_OBJECT) DrPortDeviceObject); DrPortDeviceObject = NULL; } } VOID DrUnload( IN PDRIVER_OBJECT DriverObject ) /*++ Routine Description: This is the dispatch routine for Unload. Arguments: DriverObject - Pointer to the driver object controling all of the devices. Return Value: None. --*/ { BEGIN_FN(""DrUnload""); PAGED_CODE(); TRC_NRM((TB, ""DriverObject =%p"", DriverObject)); DrUninitialize(DriverObject, DrInitialized); TRC_NRM((TB, ""MRxIfsUnload exit: DriverObject =%p"", DriverObject)); } NTSTATUS DrFlush( IN OUT PRX_CONTEXT RxContext ) /*++ Routine Description: This is the dispatch routine for flush operations. Arguments: RxContext - RDBSS context structure for our mini-redir Return Value: Could return status success, cancelled, or pending. --*/ { BEGIN_FN(""DrFlush""); return STATUS_SUCCESS; } NTSTATUS DrWrite( IN OUT PRX_CONTEXT RxContext ) /*++ Routine Description: This is the dispatch routine for write operations. Arguments: RxContext - RDBSS context structure for our mini-redir Return Value: Could return status success, cancelled, or pending. --*/ { SmartPtr Device; BEGIN_FN(""DrWrite""); TRC_NRM((TB, ""DrWrite"")); GetDeviceFromRxContext(RxContext, Device); return Device->Write(RxContext); } NTSTATUS DrRead( IN OUT PRX_CONTEXT RxContext ) /*++ Routine Description: This is the dispatch routine for read operations. Arguments: RxContext - RDBSS context structure for our mini-redir Return Value: Could return status success, cancelled, or pending. --*/ { SmartPtr Device; BEGIN_FN(""DrRead""); TRC_NRM((TB, ""DrRead"")); GetDeviceFromRxContext(RxContext, Device); return Device->Read(RxContext); } NTSTATUS DrIoControl( IN OUT PRX_CONTEXT RxContext ) /*++ Routine Description: This is the dispatch routine for IoControl operations. Arguments: RxContext - RDBSS context structure for our mini-redir Return Value: Could return status success, cancelled, or pending. --*/ { SmartPtr Device; BEGIN_FN(""DrIoControl""); TRC_NRM((TB, ""DrIoControl"")); if (GetDeviceFromRxContext(RxContext, Device)) return Device->IoControl(RxContext); else return STATUS_UNSUCCESSFUL; } NTSTATUS DrShouldTryToCollapseThisOpen( IN OUT PRX_CONTEXT RxContext ) /*++ Routine Description: This routine determines if the mini knows of a good reason not to try collapsing on this open. Arguments: RxContext - Context for the operation Return Value: NTSTATUS - The return status for the operation SUCCESS --> okay to try collapse other (MORE_PROCESSING_REQUIRED) --> dont collapse --*/ { NTSTATUS Status = STATUS_SUCCESS; RxCaptureFcb; BEGIN_FN(""DrShouldTryToCollapseThisOpen""); PAGED_CODE(); TRC_NRM((TB, ""DrShouldTryToCollapseThisOpen not implemented"")); return STATUS_NOT_IMPLEMENTED; } ULONG DrExtendForNonCache( IN OUT struct _RX_CONTEXT * RxContext, IN PLARGE_INTEGER pNewFileSize, OUT PLARGE_INTEGER pNewAllocationSize ) /*++ Routine Description: This routine handles network requests to extend the file for noncached IO. since the write itself will extend the file, we can pretty much just get out quickly. Arguments: RxContext - the RDBSS context Return Value: RXSTATUS - The return status for the operation --*/ { NTSTATUS Status = STATUS_SUCCESS; pNewAllocationSize->QuadPart = pNewFileSize->QuadPart; return (ULONG)Status; } NTSTATUS DrTruncate( IN OUT PRX_CONTEXT RxContext ) /*++ Routine Description: This routine determines Truncate operation Arguments: RxContext - Context for the operation Return Value: NTSTATUS - The return status for the operation --*/ { BEGIN_FN(""DrTruncate""); TRC_ERR((TB, ""DrTruncate not implemented"")); return STATUS_NOT_IMPLEMENTED; } NTSTATUS DrCreate(IN OUT PRX_CONTEXT RxContext) /*++ Routine Description: Opens a file (or device) across the network Arguments: RxContext - Context for the operation Return Value: Could return status success, cancelled, or pending. --*/ { NTSTATUS Status; RxCaptureFcb; PMRX_SRV_CALL SrvCall = RxContext->Create.pSrvCall; PMRX_NET_ROOT NetRoot = RxContext->Create.pNetRoot; PMRX_V_NET_ROOT VNetRoot = RxContext->Create.pVNetRoot; SmartPtr Session; DrDevice *pDevice; SmartPtr Device, DeviceNew; BEGIN_FN(""DrCreate""); TRC_NRM((TB, ""DrCreate"")); // // Make sure the device is still enabled, Protect the // VNetRoot Context (the DeviceEntry) with the device list // SpinLock because we may change it // DrAcquireSpinLock(); Device = (DrDevice *)VNetRoot->Context; ASSERT(Device != NULL); DrReleaseSpinLock(); // // Make sure it's okay to access the Client at this time // This is an optimization, we don't need to acquire the spin lock, // because it is okay if we're not, we'll just catch it later // Session = Device->GetSession(); ASSERT(Session != NULL); if (!Session->IsConnected() && (Device->GetDeviceType() != RDPDR_DTYP_SMARTCARD)) { TRC_ALT((TB, ""Tried to open client device while not "" ""connected. State: %ld"", Session->GetState())); return STATUS_DEVICE_NOT_CONNECTED; } // // We leave the SpinLock after we get our reference to the device. It could // change while we're gone, but since everything is reference counted it // is safe to put the correct pointer in later // if (!Device->IsAvailable()) { TRC_ALT((TB, ""Tried to open client device which is not "" ""available. "")); if (Device->GetDeviceType() == RDPDR_DTYP_SMARTCARD && !Session->FindDeviceByDosName((UCHAR *)DR_SMARTCARD_SUBSYSTEM, DeviceNew, TRUE)) { Status = DrCreateSCardDevice(Session, NULL, DeviceNew); if (Status != STATUS_SUCCESS) { return STATUS_DEVICE_NOT_CONNECTED; } } if (Device->GetDeviceType() == RDPDR_DTYP_SMARTCARD || Session->FindDeviceById(Device->GetDeviceId(), DeviceNew, TRUE)) { // // There's a new DeviceEntry for this device. Replace the old // one in the VNetRoot with this one. We also need an extra // reference to stick in the fobx so we can track whether // this particular open is using an old DeviceEntry or a new // one // // Put it in the netroot, safely swapping in and manually // bumping the reference count up going in and down going out DeviceNew->AddRef(); DrAcquireSpinLock(); pDevice = (DrDevice *)VNetRoot->Context; VNetRoot->Context = (DrDevice *)DeviceNew; DrReleaseSpinLock(); #if DBG pDevice->_VNetRoot = NULL; #endif pDevice->Release(); pDevice = NULL; Device = DeviceNew; } else { // // The device is disabled, but we didn't find a shiny new // version with which to replace it. Leave the icky old disabled // one there so we know what to look for later, and return the // device not connected error. // return STATUS_DEVICE_NOT_CONNECTED; } } return Device->Create(RxContext); } BOOL GetDeviceFromRxContext(PRX_CONTEXT RxContext, SmartPtr &Device) { BOOL rc = FALSE; PMRX_SRV_OPEN SrvOpen = RxContext->pRelevantSrvOpen; PMRX_V_NET_ROOT VNetRoot; BEGIN_FN(""GetDeviceFromRxContext""); if (SrvOpen == NULL) { goto Exit; } VNetRoot= SrvOpen->pVNetRoot; if (VNetRoot == NULL) { goto Exit; } DrAcquireSpinLock(); Device = (DrDevice *)VNetRoot->Context; DrReleaseSpinLock(); ASSERT(Device != NULL); rc = TRUE; Exit: return rc; } NTSTATUS DrCloseSrvOpen(IN OUT PRX_CONTEXT RxContext) /*++ Routine Description: This is the dispatch routine for close operations. Arguments: RxContext - RDBSS context structure for our mini-redir Return Value: Could return status success, cancelled, or pending. --*/ { SmartPtr Device; BEGIN_FN(""DrCloseSrvOpen""); TRC_NRM((TB, ""DrCloseSrvOpen"")); GetDeviceFromRxContext(RxContext, Device); return Device->Close(RxContext); } NTSTATUS DrCleanupFobx(IN OUT PRX_CONTEXT RxContext) /*++ Routine Description: This is the dispatch routine for cleaning up Fobx. Arguments: RxContext - RDBSS context structure for our mini-redir Return Value: Could return status success, cancelled, or pending. --*/ { RxCaptureFobx; BEGIN_FN(""DrCleanupFobx""); TRC_NRM((TB, ""DrCleanupFobx"")); return STATUS_SUCCESS; } NTSTATUS DrCleanup(IN OUT PRX_CONTEXT RxContext) /*++ Routine Description: This is the dispatch routine for cleanup operations. Arguments: RxContext - RDBSS context structure for our mini-redir Return Value: Could return status success, cancelled, or pending. --*/ { SmartPtr Device; BEGIN_FN(""DrCleanup""); TRC_NRM((TB, ""DrCleanup"")); GetDeviceFromRxContext(RxContext, Device); return Device->Cleanup(RxContext); } NTSTATUS DrQueryDirectory( IN OUT PRX_CONTEXT RxContext ) /*++ Routine Description: This is the dispatch routine for Query Direcotry information. Arguments: RxContext - RDBSS context structure for our mini-redir Return Value: Could return status success, cancelled, or pending. --*/ { SmartPtr Device; BEGIN_FN(""DrQueryDirecotry""); TRC_NRM((TB, ""DrQueryDirectory"")); GetDeviceFromRxContext(RxContext, Device); return Device->QueryDirectory(RxContext); } NTSTATUS DrQueryVolumeInfo( IN OUT PRX_CONTEXT RxContext ) /*++ Routine Description: This is the dispatch routine for Query Volume Information. Arguments: RxContext - RDBSS context structure for our mini-redir Return Value: Could return status success, cancelled, or pending. --*/ { SmartPtr Device; BEGIN_FN(""DrQueryVolumeInfo""); TRC_NRM((TB, ""DrQueryVolumeInfo"")); GetDeviceFromRxContext(RxContext, Device); return Device->QueryVolumeInfo(RxContext); } NTSTATUS DrSetVolumeInfo( IN OUT PRX_CONTEXT RxContext ) /*++ Routine Description: This is the dispatch routine for Set Volume Information. Arguments: RxContext - RDBSS context structure for our mini-redir Return Value: Could return status success, cancelled, or pending. --*/ { SmartPtr Device; BEGIN_FN(""DrSetVolumeInfo""); TRC_NRM((TB, ""DrSetVolumeInfo"")); GetDeviceFromRxContext(RxContext, Device); return Device->SetVolumeInfo(RxContext); } NTSTATUS DrQuerySdInfo( IN OUT PRX_CONTEXT RxContext ) /*++ Routine Description: This is the dispatch routine for Query Security Information. Arguments: RxContext - RDBSS context structure for our mini-redir Return Value: Could return status success, cancelled, or pending. --*/ { SmartPtr Device; BEGIN_FN(""DrQuerySdInfo""); TRC_NRM((TB, ""DrQuerySdInfo"")); GetDeviceFromRxContext(RxContext, Device); return Device->QuerySdInfo(RxContext); } NTSTATUS DrSetSdInfo( IN OUT PRX_CONTEXT RxContext ) /*++ Routine Description: This is the dispatch routine for Set Security Information. Arguments: RxContext - RDBSS context structure for our mini-redir Return Value: Could return status success, cancelled, or pending. --*/ { SmartPtr Device; BEGIN_FN(""DrSetSdInfo""); TRC_NRM((TB, ""DrSetSdInfo"")); GetDeviceFromRxContext(RxContext, Device); return Device->SetSdInfo(RxContext); } NTSTATUS DrQueryFileInfo( IN OUT PRX_CONTEXT RxContext ) /*++ Routine Description: This is the dispatch routine for Query File Information. Arguments: RxContext - RDBSS context structure for our mini-redir Return Value: Could return status success, cancelled, or pending. --*/ { SmartPtr Device; BEGIN_FN(""DrQueryFileInfo""); TRC_NRM((TB, ""DrQueryFileInfo"")); GetDeviceFromRxContext(RxContext, Device); return Device->QueryFileInfo(RxContext); } NTSTATUS DrSetFileInfo( IN OUT PRX_CONTEXT RxContext ) /*++ Routine Description: This is the dispatch routine for SetFileInformation. Arguments: RxContext - RDBSS context structure for our mini-redir Return Value: Could return status success, cancelled, or pending. --*/ { SmartPtr Device; BEGIN_FN(""DrSetFileInfo""); TRC_NRM((TB, ""DrSetFileInfo"")); GetDeviceFromRxContext(RxContext, Device); return Device->SetFileInfo(RxContext); } NTSTATUS DrSetFileInfoAtCleanUp( IN OUT PRX_CONTEXT RxContext ) /*++ Routine Description: This is the dispatch routine for SetFileInformationAtCleanUp. Arguments: DeviceObject - Pointer to the device object for this device Irp - Pointer to the IRP for the current request Return Value: Could return status success, cancelled, or pending. --*/ { BEGIN_FN(""DrSetFileInfoAtCleanUp""); TRC_NRM((TB, ""DrSetFileInfoAtCleanUp"")); return STATUS_SUCCESS; } NTSTATUS DrLocks( IN OUT PRX_CONTEXT RxContext ) /*++ Routine Description: This is the dispatch routine for file locking. Arguments: RxContext - RDBSS context structure for our mini-redir Return Value: Could return status success, cancelled, or pending. --*/ { SmartPtr Device; BEGIN_FN(""DrLocks""); TRC_NRM((TB, ""DrLocks"")); GetDeviceFromRxContext(RxContext, Device); return Device->Locks(RxContext); } NTSTATUS DrIsLockRealizable( IN OUT PMRX_FCB pFcb, IN PLARGE_INTEGER ByteOffset, IN PLARGE_INTEGER Length, IN ULONG LowIoLockFlags ) /*++ Routine Description: This is the dispatch routine for IsLockRealizable. Arguments: Return Value: Could return status success, cancelled, or pending. --*/ { BEGIN_FN(""DrIsLockRealizable""); TRC_NRM((TB, ""DrIsLockRealizable"")); // // TODO: We do not support share locks for win9x clients // Can we just return success here and then fail on the // client share lock function? // #if 0 if (!FlagOn(LowIoLockFlags,LOWIO_LOCKSFLAG_EXCLUSIVELOCK)) { return STATUS_NOT_SUPPORTED; } #endif return STATUS_SUCCESS; } NTSTATUS DrIsValidDirectory( IN OUT PRX_CONTEXT RxContext, IN PUNICODE_STRING DirectoryName ) /*++ Routine Description: This is the dispatch routine for IsValidDirectory. Arguments: RxContext - RDBSS context structure for our mini-redir DirectoryName - name of directory to verify its validity Return Value: Could return status success, cancelled, or pending. --*/ { BEGIN_FN(""DrIsValidDirectory""); TRC_NRM((TB, ""DrIsValidDirectory"")); // // TODO: Always return success for now. Need to verify later // return STATUS_SUCCESS; } NTSTATUS DrNotifyChangeDirectory( IN OUT PRX_CONTEXT RxContext ) /*++ Routine Description: This is the dispatch routine for DrNotifyChangeDirectory. Arguments: RxContext - RDBSS context structure for our mini-redir Return Value: Could return status success, cancelled, or pending. --*/ { SmartPtr Device; BEGIN_FN(""DrNotifyChangeDirectory""); TRC_NRM((TB, ""DrNotifyChangeDirectory"")); GetDeviceFromRxContext(RxContext, Device); return Device->NotifyChangeDirectory(RxContext); } NTSTATUS DrInitializeTables( void ) /*++ Routine Description: This routine sets up the rdp redirector dispatch vector and also calls to initialize any other tables needed. Return Value: NTSTATUS - The return status for the operation --*/ { BEGIN_FN(""DrInitializeTables""); // // Build the local minirdr dispatch table and initialize // ZeroAndInitializeNodeType(&DrDispatch, RDBSS_NTC_MINIRDR_DISPATCH, sizeof(MINIRDR_DISPATCH)); // // redirector extension sizes and allocation policies. // // REVIEW: wtf? DrDispatch.MRxFlags = (RDBSS_MANAGE_FCB_EXTENSION | RDBSS_MANAGE_SRV_OPEN_EXTENSION | RDBSS_MANAGE_FOBX_EXTENSION); DrDispatch.MRxSrvCallSize = 0; DrDispatch.MRxNetRootSize = 0; DrDispatch.MRxVNetRootSize = 0; DrDispatch.MRxFcbSize = 0; // sizeof(MRX_SMB_FCB); DrDispatch.MRxSrvOpenSize = 0; // sizeof(MRX_SMB_SRV_OPEN); DrDispatch.MRxFobxSize = 0; // sizeof(MRX_SMB_FOBX); // Transport update handler // REVIEW: How do we indicate we have our own dedicated transport? //MRxIfsDispatch.MRxTransportUpdateHandler = MRxIfsTransportUpdateHandler; // Mini redirector cancel routine .. DrDispatch.MRxCancel = NULL; // // Mini redirector Start/Stop. Each mini-rdr can be started or stopped // while the others continue to operate. // DrDispatch.MRxStart = DrStart; DrDispatch.MRxStop = DrStop; DrDispatch.MRxDevFcbXXXControlFile = DrDevFcbXXXControlFile; // // Mini redirector name resolution. // DrDispatch.MRxCreateSrvCall = DrCreateSrvCall; DrDispatch.MRxSrvCallWinnerNotify = DrSrvCallWinnerNotify; DrDispatch.MRxCreateVNetRoot = DrCreateVNetRoot; DrDispatch.MRxUpdateNetRootState = DrUpdateNetRootState; DrDispatch.MRxExtractNetRootName = DrExtractNetRootName; DrDispatch.MRxFinalizeSrvCall = DrFinalizeSrvCall; DrDispatch.MRxFinalizeNetRoot = DrFinalizeNetRoot; DrDispatch.MRxFinalizeVNetRoot = DrFinalizeVNetRoot; // // File System Object Creation/Deletion. // DrDispatch.MRxCreate = DrCreate; // // TODO: Need to implement this for file system redirect caching // DrDispatch.MRxShouldTryToCollapseThisOpen = DrShouldTryToCollapseThisOpen; //DrDispatch.MRxCollapseOpen = MRxIfsCollapseOpen; //DrDispatch.MRxExtendForCache = MRxIfsExtendFile; DrDispatch.MRxExtendForNonCache = DrExtendForNonCache; DrDispatch.MRxTruncate = DrTruncate; //MRxIfsTruncate; DrDispatch.MRxCleanupFobx = DrCleanupFobx; DrDispatch.MRxCloseSrvOpen = DrCloseSrvOpen; DrDispatch.MRxFlush = DrFlush; DrDispatch.MRxForceClosed = DrForceClosed; DrDispatch.MRxDeallocateForFcb = DrDeallocateForFcb; DrDispatch.MRxDeallocateForFobx = DrDeallocateForFobx; DrDispatch.MRxIsLockRealizable = DrIsLockRealizable; // // File System Objects query/Set // DrDispatch.MRxQueryDirectory = DrQueryDirectory; //MRxIfsQueryDirectory; DrDispatch.MRxQueryVolumeInfo = DrQueryVolumeInfo; //MRxIfsQueryVolumeInformation; DrDispatch.MRxSetVolumeInfo = DrSetVolumeInfo; //MRxSmbSetVolumeInformation; //DrDispatch.MRxQueryEaInfo = MRxIfsQueryEaInformation; //DrDispatch.MRxSetEaInfo = MRxIfsSetEaInformation; DrDispatch.MRxQuerySdInfo = DrQuerySdInfo; //MRxIfsQuerySecurityInformation; DrDispatch.MRxSetSdInfo = DrSetSdInfo; //MRxIfsSetSecurityInformation; //MRxSmbDispatch.MRxQueryQuotaInfo = MRxSmbQueryQuotaInformation; //MRxSmbDispatch.MRxSetQuotaInfo = MRxSmbSetQuotaInformation; DrDispatch.MRxQueryFileInfo = DrQueryFileInfo; //MRxIfsQueryFileInformation; DrDispatch.MRxSetFileInfo = DrSetFileInfo; //MRxIfsSetFileInformation; DrDispatch.MRxSetFileInfoAtCleanup = DrSetFileInfoAtCleanUp; //MRxIfsSetFileInformationAtCleanup; DrDispatch.MRxIsValidDirectory = DrIsValidDirectory; // // Buffering state change // //DrDispatch.MRxComputeNewBufferingState = MRxIfsComputeNewBufferingState; // // File System Object I/O // DrDispatch.MRxLowIOSubmit[LOWIO_OP_READ] = DrRead; DrDispatch.MRxLowIOSubmit[LOWIO_OP_WRITE] = DrWrite; DrDispatch.MRxLowIOSubmit[LOWIO_OP_SHAREDLOCK] = DrLocks; DrDispatch.MRxLowIOSubmit[LOWIO_OP_EXCLUSIVELOCK] = DrLocks; DrDispatch.MRxLowIOSubmit[LOWIO_OP_UNLOCK] = DrLocks; DrDispatch.MRxLowIOSubmit[LOWIO_OP_UNLOCK_MULTIPLE] = DrLocks; DrDispatch.MRxLowIOSubmit[LOWIO_OP_FSCTL] = DrIoControl; //MRxIfsFsCtl; DrDispatch.MRxLowIOSubmit[LOWIO_OP_IOCTL] = DrIoControl; DrDispatch.MRxLowIOSubmit[LOWIO_OP_NOTIFY_CHANGE_DIRECTORY] = DrNotifyChangeDirectory; //MRxIfsNotifyChangeDirectory; // // Miscellanous - buffering // //DrDispatch.MRxCompleteBufferingStateChangeRequest = MRxIfsCompleteBufferingStateChangeRequest; return STATUS_SUCCESS; } BOOLEAN DrIsAdminIoRequest( PIRP Irp, PIO_STACK_LOCATION IrpSp ) /*++ Routine Description: (Lifted from AFD - AfdPerformSecurityCheck) Compares security context of the endpoint creator to that of the administrator and local system. Arguments: Irp - Pointer to I/O request packet. IrpSp - pointer to the IO stack location to use for this request. Return Value: TRUE - the socket creator has admin or local system privilige FALSE - the socket creator is just a plain user --*/ { BOOLEAN accessGranted; PACCESS_STATE accessState; PIO_SECURITY_CONTEXT securityContext; PPRIVILEGE_SET privileges = NULL; ACCESS_MASK grantedAccess; PGENERIC_MAPPING GenericMapping; ACCESS_MASK AccessMask = GENERIC_ALL; NTSTATUS Status; BEGIN_FN(""DrIsAdminIoRequest""); ASSERT(Irp != NULL); ASSERT(IrpSp != NULL); ASSERT(IrpSp->MajorFunction == IRP_MJ_CREATE); // // Enable access to all the globally defined SIDs // GenericMapping = IoGetFileObjectGenericMapping(); RtlMapGenericMask( &AccessMask, GenericMapping ); securityContext = IrpSp->Parameters.Create.SecurityContext; ASSERT(securityContext != NULL); accessState = securityContext->AccessState; SeLockSubjectContext(&accessState->SubjectSecurityContext); TRC_ASSERT(DrAdminSecurityDescriptor != NULL, (TB, ""DrAdminSecurityDescriptor != NULL"")); accessGranted = SeAccessCheck( DrAdminSecurityDescriptor, &accessState->SubjectSecurityContext, TRUE, AccessMask, 0, &privileges, IoGetFileObjectGenericMapping(), (KPROCESSOR_MODE)((IrpSp->Flags & SL_FORCE_ACCESS_CHECK) ? UserMode : Irp->RequestorMode), &grantedAccess, &Status ); if (privileges) { (VOID) SeAppendPrivileges( accessState, privileges ); SeFreePrivileges(privileges); } if (accessGranted) { accessState->PreviouslyGrantedAccess |= grantedAccess; accessState->RemainingDesiredAccess &= ~( grantedAccess | MAXIMUM_ALLOWED ); ASSERT (NT_SUCCESS (Status)); } else { ASSERT (!NT_SUCCESS (Status)); } SeUnlockSubjectContext(&accessState->SubjectSecurityContext); return accessGranted; } BOOLEAN DrIsSystemProcessRequest( PIRP Irp, PIO_STACK_LOCATION IrpSp ) /*++ Routine Description: Checks to see if the IRP originated from a system process. Arguments: Irp - Pointer to I/O request packet. IrpSp - pointer to the IO stack location to use for this request. Return Value: TRUE if the IRP originated from a system process. FALSE, otherwise. --*/ { PACCESS_STATE accessState; PIO_SECURITY_CONTEXT securityContext; PACCESS_TOKEN accessToken; PTOKEN_USER userId = NULL; BOOLEAN result = FALSE; NTSTATUS status = STATUS_SUCCESS; PSID systemSid; BEGIN_FN(""DrIsSystemProcessRequest""); TRC_NRM((TB, ""DrIsSystemProcessRequest called"")); ASSERT(Irp != NULL); ASSERT(IrpSp != NULL); ASSERT(IrpSp->MajorFunction == IRP_MJ_CREATE); securityContext = IrpSp->Parameters.Create.SecurityContext; ASSERT(securityContext != NULL); // // Get the well-known system SID. // systemSid = (PSID)new(PagedPool) BYTE[RtlLengthRequiredSid(1)]; if (systemSid) { SID_IDENTIFIER_AUTHORITY identifierAuthority = SECURITY_NT_AUTHORITY; *(RtlSubAuthoritySid(systemSid, 0)) = SECURITY_LOCAL_SYSTEM_RID; status = RtlInitializeSid(systemSid, &identifierAuthority, (UCHAR)1); } else { TRC_ERR((TB, ""Can't allocate %ld bytes for system SID."", RtlLengthRequiredSid(1))); status = STATUS_INSUFFICIENT_RESOURCES; } // // Get the non-impersonated, primary token for the IRP request. // accessState = securityContext->AccessState; accessToken = accessState->SubjectSecurityContext.PrimaryToken; // // We got the system SID. Now compare the caller's SID. // if (NT_SUCCESS(status) && accessToken){ // // Get the user ID associated with the primary token for the process // that generated the IRP. // status = SeQueryInformationToken( accessToken, TokenUser, (PVOID *)&userId ); // // Do the comparison. // if (NT_SUCCESS(status)) { result = RtlEqualSid(systemSid, userId->User.Sid); ExFreePool(userId); } else { TRC_ERR((TB, ""SeQueryInformationToken failed with %08X"", status)); } } else { TRC_ERR((TB, ""Failed to get system sid because of error %08X"", status)); } if (systemSid) { delete systemSid; } return result; } BOOL DrQueryServerName(PUNICODE_STRING PathName) /*++ Routine Description: This routine check if the pathname belongs to our minirdr. Arguments: PathName: path name to check Return Value: TRUE - if the path is to our mini-rdr FALSE - if the path not our mini-rdr --*/ { PWCHAR ServerName; PWCHAR ServerNameEnd; unsigned CompareLen; // in characters unsigned PathNameLen; // in characters BEGIN_FN(""DrQueryServerName""); TRC_NRM((TB, ""Got query path for file: %wZ"", PathName)); // // Make sure the server name we are comparing has at least length // of the server name our rdpdr recongize // if (PathName->Length >= DRUNCSERVERNAME_U_LENGTH) { ServerName = PathName->Buffer; // bypass the first backslash ServerName++; PathNameLen = PathName->Length / sizeof(WCHAR) - 1; // Find the next backslash ServerNameEnd = ServerName; while ((unsigned)(ServerNameEnd - ServerName) < PathNameLen) { if (*ServerNameEnd == L'\\\\') { break; } ServerNameEnd++; } CompareLen = (unsigned)(ServerNameEnd - ServerName); // // Determine if this is a server name belongs to our minirdr // if ( (CompareLen == DRUNCSERVERNAME_A_LENGTH - 1) && _wcsnicmp(ServerName, DRUNCSERVERNAME_U, CompareLen) == 0) { TRC_NRM((TB, ""Quick return that we know the name"")); return TRUE; } } return FALSE; } NTSTATUS DrPeekDispatch ( IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp ) /*++ Routine Description: This routine implements the driver dispatch for the rdpdr DRIVER object. Arguments: DeviceObject - Supplies the device object for the packet being processed. Irp - Supplies the Irp being processed Return Value: NTSTATUS - The status for the Irp --*/ { PIO_STACK_LOCATION IoStackLocation; NTSTATUS Status; ULONG irpSessionId; BEGIN_FN(""DrPeekDispatch ""); IoStackLocation = IoGetCurrentIrpStackLocation(Irp); #if DBG TRC_NRM((TB, ""Irp: %s"", IrpNames[IoStackLocation->MajorFunction])); switch (IoStackLocation->MajorFunction) { case IRP_MJ_CREATE: TRC_NRM((TB, ""CreateFile name: %wZ"", &IoStackLocation->FileObject->FileName)); break; case IRP_MJ_WRITE: TRC_NRM((TB, ""IRP_MJ_WRITE"")); break; } #endif // DBG // // For Read and Write IRP, we disable caching because the client // is an usermode app and can't synchronize with the server cache // manager // if (IoStackLocation->MajorFunction == IRP_MJ_READ || IoStackLocation->MajorFunction == IRP_MJ_WRITE) { Irp->Flags |= IRP_NOCACHE; } // // We need to return immediately for redir_query_path // if (IoStackLocation->MajorFunction == IRP_MJ_DEVICE_CONTROL && IoStackLocation->Parameters.DeviceIoControl.IoControlCode == IOCTL_REDIR_QUERY_PATH && Irp->RequestorMode == KernelMode) { QUERY_PATH_REQUEST *qpRequest = (QUERY_PATH_REQUEST *) IoStackLocation->Parameters.DeviceIoControl.Type3InputBuffer; if (qpRequest != NULL) { UNICODE_STRING PathName; PathName.Length = (USHORT)qpRequest->PathNameLength; PathName.Buffer= qpRequest->FilePathName; if (DrQueryServerName(&PathName)) { // // We must now complete the IRP // Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = 0; IoCompleteRequest(Irp, IO_NO_INCREMENT); return STATUS_SUCCESS; } } } // // We want to bypass filesize caching // RxForceQFIPassThrough = TRUE; // If it's not the IFS DO, then let RDPDYN have a shot at it. Eventually, // it would be nice to confirm that it is for RDPDYN. We can work this // out later ... if (DeviceObject != (PDEVICE_OBJECT)DrDeviceObject && DeviceObject != (PDEVICE_OBJECT) DrPortDeviceObject) { TRC_NRM((TB, ""Pass IRP on to RDPDYN_Dispatch"")); return RDPDYN_Dispatch(DeviceObject, Irp); } else { // Only for port device, we deny driver attachment if (DeviceObject == (PDEVICE_OBJECT) DrPortDeviceObject) { if (DeviceObject->AttachedDevice != NULL || (IoStackLocation->FileObject != NULL && IoStackLocation->FileObject->DeviceObject != (PDEVICE_OBJECT)DrPortDeviceObject)) { // // We don't accept another device attaches to us or // is passing irps to us // Irp->IoStatus.Status = STATUS_ACCESS_DENIED; Irp->IoStatus.Information = 0; IoCompleteRequest(Irp, IO_NO_INCREMENT); return STATUS_ACCESS_DENIED; } // // We swap back to the rdpdr device object for port device so it'll go through // the rdbss route // IoStackLocation->DeviceObject = (PDEVICE_OBJECT)DrDeviceObject; // For Multi-User TS environment, we need to set the port carete share access // to be sharable, otherwise two users can't use com1 at the same time because // rdbss check for share access for NET_ROOT \\\\tsclient\\com1. if (IoStackLocation->MajorFunction == IRP_MJ_CREATE) { IoStackLocation->Parameters.Create.ShareAccess = FILE_SHARE_VALID_FLAGS; } } if ((IoStackLocation->MajorFunction == IRP_MJ_CREATE) && (IoStackLocation->FileObject->FileName.Length == 0) && (IoStackLocation->FileObject->RelatedFileObject == NULL)) { // // This is a blank create, like rdpwsx uses to open us for // session connect disconnect notification. Only allowed // by the system because we trust rdpwsx to hold a kernel // pointer for us // // // Security check the irp. // Status = IoGetRequestorSessionId(Irp, &irpSessionId); if (NT_SUCCESS(Status)) { // // If the request is from the console session, it needs to be from a system // process. // if (irpSessionId == CONSOLE_SESSIONID) { TRC_NRM((TB, ""Create request from console process."")); if (!DrIsSystemProcessRequest(Irp, IoStackLocation)) { TRC_ALT((TB, ""Root Create request not from system process."")); // // We may get called from a user process through the UNC // network provider. e.g. when user does a net use // In this case, we have to allow root access. We have to // do the security check on per IRP bases. // //Irp->IoStatus.Status = STATUS_ACCESS_DENIED; //Irp->IoStatus.Information = 0; //IoCompleteRequest(Irp, IO_NO_INCREMENT); //return STATUS_ACCESS_DENIED; return RxFsdDispatch((PRDBSS_DEVICE_OBJECT)DrDeviceObject, Irp); } else { TRC_NRM((TB, ""Root Create request from system accepted."")); return RxFsdDispatch((PRDBSS_DEVICE_OBJECT)DrDeviceObject, Irp); } } else { // // If not from the console then deny access. // TRC_ALT((TB, ""Root request from %ld"", irpSessionId)); // // We may get called from a user process through the UNC // network provider. e.g. when user does a net use // In this case, we have to allow root access. We have to // do the security check on per IRP bases. // //Irp->IoStatus.Status = STATUS_ACCESS_DENIED; //Irp->IoStatus.Information = 0; //IoCompleteRequest(Irp, IO_NO_INCREMENT); //return STATUS_ACCESS_DENIED; return RxFsdDispatch((PRDBSS_DEVICE_OBJECT)DrDeviceObject, Irp); } } else { TRC_ERR((TB, ""IoGetRequestorSessionId failed with %08X."", Status)); Irp->IoStatus.Status = Status; Irp->IoStatus.Information = 0; IoCompleteRequest(Irp, IO_NO_INCREMENT); return Status; } } else { // // This is not a create, or at least not a create to just the root // TRC_NRM((TB, ""Pass IRP on to RxFsdDispatch = %d"", IoStackLocation->MajorFunction)); return RxFsdDispatch((PRDBSS_DEVICE_OBJECT)DrDeviceObject, Irp); } } } NTSTATUS DrLoadRegistrySettings ( IN PCWSTR RegistryPath ) /*++ Routine Description: This routine reads the default configuration data from the registry for the device redirector driver. Arguments: RegistryPath - points to the entry for this driver in the current control set of the registry. Return Value: STATUS_SUCCESS if we got the defaults, otherwise we failed. The only way to fail this call is if the STATUS_INSUFFICIENT_RESOURCES. --*/ { NTSTATUS Status = STATUS_SUCCESS; // return value BEGIN_FN(""DrLoadRegistrySettings ""); #if DBG extern TRC_CONFIG TRC_Config; int i; // // We use this to query into the registry for defaults // paramTable needs to be one entry larger than the set we // need because a NULL entry indicates we're done // RTL_QUERY_REGISTRY_TABLE paramTable[9]; TRC_CONFIG trcConfig; ULONG DebugBreakOnEntryDefault = FALSE; PAGED_CODE(); RtlZeroMemory(&trcConfig, sizeof(trcConfig)); trcConfig.FunctionLength = TRC_FUNCNAME_LEN; trcConfig.TraceDebugger = FALSE; trcConfig.TraceLevel = TRC_LEVEL_ALT; trcConfig.TraceProfile = TRUE; RtlZeroMemory (¶mTable[0], sizeof(paramTable)); paramTable[0].Flags = RTL_QUERY_REGISTRY_DIRECT; paramTable[0].Name = L""FunctionLength""; paramTable[0].EntryContext = &TRC_Config.FunctionLength; paramTable[0].DefaultType = REG_DWORD; paramTable[0].DefaultData = &trcConfig.FunctionLength; paramTable[0].DefaultLength = sizeof(trcConfig.FunctionLength); paramTable[1].Flags = RTL_QUERY_REGISTRY_DIRECT; paramTable[1].Name = L""TraceLevel""; paramTable[1].EntryContext = &TRC_Config.TraceLevel; paramTable[1].DefaultType = REG_DWORD; paramTable[1].DefaultData = &trcConfig.TraceLevel; paramTable[1].DefaultLength = sizeof(trcConfig.TraceLevel); paramTable[2].Flags = RTL_QUERY_REGISTRY_DIRECT; paramTable[2].Name = L""TraceProfile""; paramTable[2].EntryContext = &TRC_Config.TraceProfile; paramTable[2].DefaultType = REG_DWORD; paramTable[2].DefaultData = &trcConfig.TraceProfile; paramTable[2].DefaultLength = sizeof(trcConfig.TraceProfile); paramTable[3].Flags = RTL_QUERY_REGISTRY_DIRECT; paramTable[3].Name = L""TraceDebugger""; paramTable[3].EntryContext = &TRC_Config.TraceDebugger; paramTable[3].DefaultType = REG_DWORD; paramTable[3].DefaultData = &trcConfig.TraceDebugger; paramTable[3].DefaultLength = sizeof(trcConfig.TraceDebugger); paramTable[4].Flags = RTL_QUERY_REGISTRY_DIRECT; paramTable[4].Name = L""BreakOnEntry""; paramTable[4].EntryContext = &DebugBreakOnEntry; paramTable[4].DefaultType = REG_DWORD; paramTable[4].DefaultData = &DebugBreakOnEntryDefault; paramTable[4].DefaultLength = sizeof(ULONG); paramTable[5].Flags = RTL_QUERY_REGISTRY_DIRECT; paramTable[5].Name = L""PrintPortWriteSize""; paramTable[5].EntryContext = &PrintPortWriteSize; paramTable[5].DefaultType = REG_DWORD; paramTable[5].DefaultData = &PrintPortWriteSizeDefault; paramTable[5].DefaultLength = sizeof(ULONG); paramTable[6].Flags = RTL_QUERY_REGISTRY_DIRECT; paramTable[6].Name = L""DeviceLowPrioSendFlags""; paramTable[6].EntryContext = &DeviceLowPrioSendFlags; paramTable[6].DefaultType = REG_DWORD; paramTable[6].DefaultData = &DeviceLowPrioSendFlagsDefault; paramTable[6].DefaultLength = sizeof(ULONG); paramTable[7].Flags = RTL_QUERY_REGISTRY_DIRECT; paramTable[7].Name = L""MaxWorkerThreads""; paramTable[7].EntryContext = &MaxWorkerThreads; paramTable[7].DefaultType = REG_DWORD; paramTable[7].DefaultData = &MaxWorkerThreadsDefault; paramTable[7].DefaultLength = sizeof(ULONG); Status = RtlQueryRegistryValues( RTL_REGISTRY_ABSOLUTE | RTL_REGISTRY_OPTIONAL, RegistryPath, ¶mTable[0], NULL, NULL); if (!NT_SUCCESS(Status)) { DebugBreakOnEntry = DebugBreakOnEntryDefault; } RtlZeroMemory (¶mTable[0], sizeof(paramTable)); WCHAR wcPrefix[10] = L""Prefix""; WCHAR wcStart[10] = L""Start""; WCHAR wcEnd[10] = L""End""; UNICODE_STRING usPrefix; UNICODE_STRING usStart; UNICODE_STRING usEnd; usPrefix.Buffer = &wcPrefix[6]; // Just past ""Prefix"" usPrefix.MaximumLength = 3 * sizeof(WCHAR); // Remaining space, room for null term. usStart.Buffer = &wcStart[5]; // Just past ""Start"" usStart.MaximumLength = 4 * sizeof(WCHAR); // Remaining space, room for null term. usEnd.Buffer = &wcEnd[4]; // Just past ""End"" usEnd.MaximumLength = 5 * sizeof(WCHAR); // Remaining space, room for null term. paramTable[0].Flags = RTL_QUERY_REGISTRY_DIRECT; paramTable[0].Name = wcPrefix; paramTable[0].DefaultType = REG_BINARY; paramTable[0].DefaultData = &trcConfig.Prefix[0].name[0]; paramTable[0].DefaultLength = sizeof(trcConfig.Prefix[0].name); paramTable[1].Flags = RTL_QUERY_REGISTRY_DIRECT; paramTable[1].Name = wcStart; paramTable[1].DefaultType = REG_DWORD; paramTable[1].DefaultData = &trcConfig.Prefix[0].start; paramTable[1].DefaultLength = sizeof(trcConfig.Prefix[0].start); paramTable[2].Flags = RTL_QUERY_REGISTRY_DIRECT; paramTable[2].Name = wcEnd; paramTable[2].DefaultType = REG_DWORD; paramTable[2].DefaultData = &trcConfig.Prefix[0].end; paramTable[2].DefaultLength = sizeof(trcConfig.Prefix[0].end); // // So the registry can have values like: // Prefix1 = ""rdpdr"" // Start1 = 400 // End1 = 425 // // Prefix1 = ""channel"" // Start1 = 765 // End1 = 765 // // And that will restrict tracing output to rdpdr, lines 400-425 // and channel, line 765 // for (i = 0; i < TRC_MAX_PREFIX; i ++) { RtlZeroMemory(&TRC_Config.Prefix[i].name[0], sizeof(TRC_Config.Prefix[i].name[0])); // Clear out the end of the strings usPrefix.Length = 0; // no length yet RtlZeroMemory(usPrefix.Buffer, usPrefix.MaximumLength); usStart.Length = 0; // no length yet RtlZeroMemory(usStart.Buffer, usStart.MaximumLength); usEnd.Length = 0; // no length yet RtlZeroMemory(usEnd.Buffer, usEnd.MaximumLength); // Append the integer RtlIntegerToUnicodeString(i + 1, 10, &usPrefix); RtlIntegerToUnicodeString(i + 1, 10, &usStart); RtlIntegerToUnicodeString(i + 1, 10, &usEnd); paramTable[0].EntryContext = &TRC_Config.Prefix[i].name; paramTable[1].EntryContext = &TRC_Config.Prefix[i].start; paramTable[2].EntryContext = &TRC_Config.Prefix[i].end; Status = RtlQueryRegistryValues( RTL_REGISTRY_ABSOLUTE | RTL_REGISTRY_OPTIONAL, RegistryPath, ¶mTable[0], NULL, NULL); } #endif // DBG return (Status); } NTSTATUS DrStart(PRX_CONTEXT RxContext, IN OUT PRDBSS_DEVICE_OBJECT RxDeviceObject) /*++ Routine Description: This routine completes the initialization of the mini redirector fromn the RDBSS perspective. Note that this is different from the initialization done in DriverEntry. Any initialization that depends on RDBSS should be done as part of this routine while the initialization that is independent of RDBSS should be done in the DriverEntry routine. Arguments: RxContext - Supplies the Irp that was used to startup the rdbss Return Value: RXSTATUS - The return status for the operation --*/ { NTSTATUS Status = STATUS_SUCCESS; BEGIN_FN(""DrStart""); return Status; } NTSTATUS DrStop(PRX_CONTEXT RxContext, IN OUT PRDBSS_DEVICE_OBJECT RxDeviceObject) /*++ Routine Description: This routine is used to deactivate the mini redirector from the RDBSS perspective Arguments: RxContext - the context that was used to start the mini redirector pContext - the mini rdr context passed in at registration time. Return Value: RXSTATUS - The return status for the operation --*/ { NTSTATUS Status; BEGIN_FN(""DrStop""); return STATUS_SUCCESS; } NTSTATUS DrDeallocateForFcb(IN OUT PMRX_FCB pFcb) { BEGIN_FN(""DrDeallocateForFcb""); return STATUS_SUCCESS; } NTSTATUS DrDeallocateForFobx(IN OUT PMRX_FOBX pFobx) /*++ Routine Description: This routine is the last gasp of a Fobx. We remove the DeviceEntry ref Arguments: pFobx - the instance to be closed Return Value: RXSTATUS - The return status for the operation Notes: --*/ { DrDevice *Device; DrFile *FileObj; BEGIN_FN(""DrDeallocateForFobx""); // // Dereference the device object. // if (pFobx->Context != NULL) { Device = (DrDevice *)pFobx->Context; pFobx->Context = NULL; Device->Release(); } // // Cleanup the file object // if (pFobx->Context2 != NULL) { FileObj = (DrFile *)pFobx->Context2; FileObj->Release(); pFobx->Context2 = NULL; } return STATUS_SUCCESS; } NTSTATUS DrForceClosed(IN PMRX_SRV_OPEN pSrvOpen) /*++ Routine Description: This routine closes a file system object Arguments: pSrvOpen - the instance to be closed Return Value: RXSTATUS - The return status for the operation Notes: --*/ { BEGIN_FN(""DrForceClosed""); TRC_NRM((TB, ""DrForceClosed not implemented"")); return STATUS_NOT_IMPLEMENTED; } NTSTATUS BuildDeviceAcl( OUT PACL *DeviceAcl ) /*++ Routine Description: (Lifted from AFD - AfdBuildDeviceAcl) This routine builds an ACL which gives Administrators and LocalSystem principals full access. All other principals have no access. Arguments: DeviceAcl - Output pointer to the new ACL. Return Value: STATUS_SUCCESS or an appropriate error code. --*/ { PGENERIC_MAPPING GenericMapping; PSID AdminsSid; PSID SystemSid; ULONG AclLength; NTSTATUS Status; ACCESS_MASK AccessMask = GENERIC_ALL; PACL NewAcl; BEGIN_FN(""BuildDeviceAcl""); // // Enable access to all the globally defined SIDs // GenericMapping = IoGetFileObjectGenericMapping(); RtlMapGenericMask( &AccessMask, GenericMapping ); AdminsSid = SeExports->SeAliasAdminsSid; SystemSid = SeExports->SeLocalSystemSid; AclLength = sizeof( ACL ) + 2 * sizeof( ACCESS_ALLOWED_ACE ) + RtlLengthSid( AdminsSid ) + RtlLengthSid( SystemSid ) - 2 * sizeof( ULONG ); NewAcl = (PACL)new(PagedPool) BYTE[AclLength]; if (NewAcl == NULL) { return( STATUS_INSUFFICIENT_RESOURCES ); } Status = RtlCreateAcl (NewAcl, AclLength, ACL_REVISION ); if (!NT_SUCCESS( Status )) { delete NewAcl; return( Status ); } Status = RtlAddAccessAllowedAce ( NewAcl, ACL_REVISION2, AccessMask, AdminsSid ); ASSERT( NT_SUCCESS( Status )); Status = RtlAddAccessAllowedAce ( NewAcl, ACL_REVISION2, AccessMask, SystemSid ); ASSERT( NT_SUCCESS( Status )); *DeviceAcl = NewAcl; return( STATUS_SUCCESS ); } // BuildDeviceAcl NTSTATUS CreateAdminSecurityDescriptor( VOID ) /*++ Routine Description: (Lifted from AFD - AfdCreateAdminSecurityDescriptor) This routine creates a security descriptor which gives access only to Administrtors and LocalSystem. This descriptor is used to access check raw endpoint opens and exclisive access to transport addresses. Arguments: None. Return Value: STATUS_SUCCESS or an appropriate error code. --*/ { PACL rawAcl = NULL; NTSTATUS status; BOOLEAN memoryAllocated = FALSE; PSECURITY_DESCRIPTOR drSecurityDescriptor; ULONG localDrSecurityDescriptorLength = 0; CHAR buffer[SECURITY_DESCRIPTOR_MIN_LENGTH]; PSECURITY_DESCRIPTOR localSecurityDescriptor = (PSECURITY_DESCRIPTOR) &buffer; PSECURITY_DESCRIPTOR localDrAdminSecurityDescriptor; SECURITY_INFORMATION securityInformation = DACL_SECURITY_INFORMATION; BEGIN_FN(""CreateAdminSecurityDescriptor""); // // Get a pointer to the security descriptor from the Dr device object. // status = ObGetObjectSecurity( DrDeviceObject, &drSecurityDescriptor, &memoryAllocated ); if (!NT_SUCCESS(status)) { TRC_ERR((TB, ""Unable to get security descriptor, error: %x"", status)); ASSERT(memoryAllocated == FALSE); return(status); } else { if (drSecurityDescriptor == NULL) { TRC_ERR((TB, ""No security descriptor for DrDeviceObject"")); status = STATUS_UNSUCCESSFUL; return(status); } } // // Build a local security descriptor with an ACL giving only // administrators and system access. // status = BuildDeviceAcl(&rawAcl); if (!NT_SUCCESS(status)) { TRC_ERR((TB, ""Unable to create Raw ACL, error: %x"", status)); goto error_exit; } (VOID) RtlCreateSecurityDescriptor( localSecurityDescriptor, SECURITY_DESCRIPTOR_REVISION ); (VOID) RtlSetDaclSecurityDescriptor( localSecurityDescriptor, TRUE, rawAcl, FALSE ); // // Make a copy of the Dr descriptor. This copy will be the raw descriptor. // localDrSecurityDescriptorLength = RtlLengthSecurityDescriptor( drSecurityDescriptor ); localDrAdminSecurityDescriptor = (PSECURITY_DESCRIPTOR)new(PagedPool) BYTE[localDrSecurityDescriptorLength]; if (localDrAdminSecurityDescriptor == NULL) { TRC_ERR((TB, ""couldn't allocate security descriptor"")); status = STATUS_NO_MEMORY; goto error_exit; } RtlMoveMemory( localDrAdminSecurityDescriptor, drSecurityDescriptor, localDrSecurityDescriptorLength ); DrAdminSecurityDescriptor = localDrAdminSecurityDescriptor; DrSecurityDescriptorLength = localDrSecurityDescriptorLength; // // Now apply the local descriptor to the raw descriptor. // status = SeSetSecurityDescriptorInfo( NULL, &securityInformation, localSecurityDescriptor, &DrAdminSecurityDescriptor, PagedPool, IoGetFileObjectGenericMapping() ); if (!NT_SUCCESS(status)) { TRC_ERR((TB, ""SeSetSecurity failed, %lx"", status)); ASSERT (DrAdminSecurityDescriptor==localDrAdminSecurityDescriptor); delete DrAdminSecurityDescriptor; DrAdminSecurityDescriptor = NULL; DrSecurityDescriptorLength = 0; goto error_exit; } if (DrAdminSecurityDescriptor != localDrAdminSecurityDescriptor) { delete localDrAdminSecurityDescriptor; } status = STATUS_SUCCESS; error_exit: ObReleaseObjectSecurity( drSecurityDescriptor, memoryAllocated ); if (rawAcl!=NULL) { delete rawAcl; } return(status); } ",16142,True,2946.924636701016,median "// This file is part of OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html. // // Copyright (C) 2018-2019 Intel Corporation #ifndef OPENCV_GAPI_CORE_TESTS_INL_HPP #define OPENCV_GAPI_CORE_TESTS_INL_HPP #include #include #include ""gapi_core_tests.hpp"" namespace opencv_test { TEST_P(MathOpTest, MatricesAccuracyTest) { // G-API code & corresponding OpenCV code //////////////////////////////// cv::GMat in1, in2, out; if( testWithScalar ) { cv::GScalar sc1; switch(opType) { case (ADD): { out = cv::gapi::addC(in1, sc1, dtype); cv::add(in_mat1, sc, out_mat_ocv, cv::noArray(), dtype); break; } case (SUB): { if( doReverseOp ) { out = cv::gapi::subRC(sc1, in1, dtype); cv::subtract(sc, in_mat1, out_mat_ocv, cv::noArray(), dtype); } else { out = cv::gapi::subC(in1, sc1, dtype); cv::subtract(in_mat1, sc, out_mat_ocv, cv::noArray(), dtype); } break; } case (DIV): { if( doReverseOp ) { in_mat1.setTo(1, in_mat1 == 0); // avoiding zeros in divide input data out = cv::gapi::divRC(sc1, in1, scale, dtype); cv::divide(sc, in_mat1, out_mat_ocv, scale, dtype); break; } else { sc += Scalar(sc[0] == 0, sc[1] == 0, sc[2] == 0, sc[3] == 0); // avoiding zeros in divide input data out = cv::gapi::divC(in1, sc1, scale, dtype); cv::divide(in_mat1, sc, out_mat_ocv, scale, dtype); break; } } case (MUL): { // FIXME: add `scale` parameter to mulC out = cv::gapi::mulC(in1, sc1, /* scale, */ dtype); cv::multiply(in_mat1, sc, out_mat_ocv, 1., dtype); break; } default: { FAIL() << ""no such math operation type for scalar and matrix!""; } } cv::GComputation c(GIn(in1, sc1), GOut(out)); c.apply(gin(in_mat1, sc), gout(out_mat_gapi), getCompileArgs()); } else { switch(opType) { case (ADD): { out = cv::gapi::add(in1, in2, dtype); cv::add(in_mat1, in_mat2, out_mat_ocv, cv::noArray(), dtype); break; } case (SUB): { out = cv::gapi::sub(in1, in2, dtype); cv::subtract(in_mat1, in_mat2, out_mat_ocv, cv::noArray(), dtype); break; } case (DIV): { in_mat2.setTo(1, in_mat2 == 0); // avoiding zeros in divide input data out = cv::gapi::div(in1, in2, scale, dtype); cv::divide(in_mat1, in_mat2, out_mat_ocv, scale, dtype); break; } case (MUL): { out = cv::gapi::mul(in1, in2, scale, dtype); cv::multiply(in_mat1, in_mat2, out_mat_ocv, scale, dtype); break; } default: { FAIL() << ""no such math operation type for matrix and matrix!""; }} cv::GComputation c(GIn(in1, in2), GOut(out)); c.apply(gin(in_mat1, in_mat2), gout(out_mat_gapi), getCompileArgs()); } // Comparison ////////////////////////////////////////////////////////////// { // TODO: make threshold vs bit-exact criteria be driven by testing parameter #if 1 if (CV_MAT_DEPTH(out_mat_ocv.type()) != CV_32F && CV_MAT_DEPTH(out_mat_ocv.type()) != CV_64F) { // integral: allow 1% of differences, and no diffs by >1 unit EXPECT_LE(cvtest::norm(out_mat_gapi, out_mat_ocv, NORM_INF), 1); // check: abs(a[i] - b[i]) <= 1 float tolerance = 0.01f; #if defined(__arm__) || defined(__aarch64__) if (opType == DIV) tolerance = 0.05f; #endif EXPECT_LE(cvtest::norm(out_mat_gapi, out_mat_ocv, NORM_L1), tolerance*out_mat_ocv.total()); } else { // floating-point: expect 6 decimal digits - best we expect of F32 EXPECT_LE(cvtest::norm(out_mat_ocv, out_mat_gapi, NORM_INF | NORM_RELATIVE), 1e-6); } #else EXPECT_EQ(0, cvtest::norm(out_mat_gapi, out_mat_ocv, NORM_INF)); #endif EXPECT_EQ(out_mat_gapi.size(), sz); } } TEST_P(MulDoubleTest, AccuracyTest) { auto& rng = cv::theRNG(); double d = rng.uniform(0.0, 10.0); // G-API code //////////////////////////////////////////////////////////// cv::GMat in1, out; out = cv::gapi::mulC(in1, d, dtype); cv::GComputation c(in1, out); c.apply(in_mat1, out_mat_gapi, getCompileArgs()); // OpenCV code /////////////////////////////////////////////////////////// cv::multiply(in_mat1, d, out_mat_ocv, 1, dtype); // Comparison //////////////////////////////////////////////////////////// #if 1 if (CV_MAT_DEPTH(out_mat_ocv.type()) != CV_32F && CV_MAT_DEPTH(out_mat_ocv.type()) != CV_64F) { // integral: allow 1% of differences, and no diffs by >1 unit EXPECT_LE(cvtest::norm(out_mat_gapi, out_mat_ocv, NORM_INF), 1); EXPECT_LE(cvtest::norm(out_mat_gapi, out_mat_ocv, NORM_L1 | NORM_RELATIVE), 0.01); } else { // floating-point: expect 6 decimal digits - best we expect of F32 EXPECT_LE(cvtest::norm(out_mat_ocv, out_mat_gapi, NORM_INF | NORM_RELATIVE), 1e-6); } #else EXPECT_EQ(0, cvtest::norm(out_mat_gapi, out_mat_ocv, NORM_INF)); #endif EXPECT_EQ(out_mat_gapi.size(), sz); } TEST_P(DivTest, DISABLED_DivByZeroTest) // https://github.com/opencv/opencv/pull/12826 { in_mat2 = cv::Mat(sz, type); in_mat2.setTo(cv::Scalar::all(0)); // G-API code ////////////////////////////////////////////////////////////// cv::GMat in1, in2; auto out = cv::gapi::div(in1, in2, 1.0, dtype); cv::GComputation c(GIn(in1, in2), GOut(out)); c.apply(gin(in_mat1, in_mat2), gout(out_mat_gapi), getCompileArgs()); // OpenCV code ///////////////////////////////////////////////////////////// { cv::divide(in_mat1, in_mat2, out_mat_ocv, 1.0, dtype); } // Comparison ////////////////////////////////////////////////////////////// { EXPECT_EQ(0, cvtest::norm(out_mat_gapi, out_mat_ocv, NORM_INF)); EXPECT_EQ(out_mat_gapi.size(), sz); } } TEST_P(DivCTest, DISABLED_DivByZeroTest) // https://github.com/opencv/opencv/pull/12826 { sc = cv::Scalar::all(0); // G-API code ////////////////////////////////////////////////////////////// cv::GMat in1; cv::GScalar sc1; auto out = cv::gapi::divC(in1, sc1, dtype); cv::GComputation c(GIn(in1, sc1), GOut(out)); c.apply(gin(in_mat1, sc), gout(out_mat_gapi), getCompileArgs()); // OpenCV code ///////////////////////////////////////////////////////////// { cv::divide(in_mat1, sc, out_mat_ocv, dtype); } // Comparison ////////////////////////////////////////////////////////////// { EXPECT_EQ(0, cvtest::norm(out_mat_ocv, out_mat_gapi, NORM_INF)); cv::Mat zeros = cv::Mat::zeros(sz, type); EXPECT_EQ(0, cvtest::norm(out_mat_gapi, zeros, NORM_INF)); } } TEST_P(MeanTest, AccuracyTest) { cv::Scalar out_norm; cv::Scalar out_norm_ocv; // G-API code ////////////////////////////////////////////////////////////// cv::GMat in; auto out = cv::gapi::mean(in); cv::GComputation c(cv::GIn(in), cv::GOut(out)); c.apply(cv::gin(in_mat1), cv::gout(out_norm), getCompileArgs()); // OpenCV code ///////////////////////////////////////////////////////////// { out_norm_ocv = cv::mean(in_mat1); } // Comparison ////////////////////////////////////////////////////////////// { EXPECT_EQ(out_norm[0], out_norm_ocv[0]); } } TEST_P(MaskTest, AccuracyTest) { in_mat2 = cv::Mat(sz, CV_8UC1); cv::randu(in_mat2, cv::Scalar::all(0), cv::Scalar::all(255)); in_mat2 = in_mat2 > 128; // G-API code ////////////////////////////////////////////////////////////// cv::GMat in, m; auto out = cv::gapi::mask(in, m); cv::GComputation c(cv::GIn(in, m), cv::GOut(out)); c.apply(cv::gin(in_mat1, in_mat2), cv::gout(out_mat_gapi), getCompileArgs()); // OpenCV code ///////////////////////////////////////////////////////////// { out_mat_ocv = cv::Mat::zeros(in_mat1.size(), in_mat1.type()); in_mat1.copyTo(out_mat_ocv, in_mat2); } // Comparison ////////////////////////////////////////////////////////////// { EXPECT_EQ(0, cvtest::norm(out_mat_ocv, out_mat_gapi, NORM_INF)); } } TEST_P(Polar2CartTest, AccuracyTest) { cv::Mat out_mat2; cv::Mat out_mat_ocv2; if (dtype != -1) { out_mat2 = cv::Mat(sz, dtype); out_mat_ocv2 = cv::Mat(sz, dtype); } // G-API code ////////////////////////////////////////////////////////////// cv::GMat in1, in2, out1, out2; std::tie(out1, out2) = cv::gapi::polarToCart(in1, in2); cv::GComputation c(GIn(in1, in2), GOut(out1, out2)); c.apply(gin(in_mat1,in_mat2), gout(out_mat_gapi, out_mat2), getCompileArgs()); // OpenCV code ///////////////////////////////////////////////////////////// { cv::polarToCart(in_mat1, in_mat2, out_mat_ocv, out_mat_ocv2); } // Comparison ////////////////////////////////////////////////////////////// { // Note that we cannot rely on bit-exact sin/cos functions used for this // transform, so we need a threshold for verifying results vs reference. // // Relative threshold like 1e-6 is very restrictive, nearly best we can // expect of single-precision elementary functions implementation. // // However, good idea is making such threshold configurable: parameter // of this test - which a specific test instantiation could setup. // // Note that test instantiation for the OpenCV back-end could even let // the threshold equal to zero, as CV back-end calls the same kernel. // // TODO: Make threshold a configurable parameter of this test (ADE-221) ASSERT_EQ(out_mat_gapi.size(), sz); cv::Mat &outx = out_mat_gapi, &outy = out_mat2; cv::Mat &refx = out_mat_ocv, &refy = out_mat_ocv2; EXPECT_LE(cvtest::norm(refx, outx, NORM_L1 | NORM_RELATIVE), 1e-6); EXPECT_LE(cvtest::norm(refy, outy, NORM_L1 | NORM_RELATIVE), 1e-6); } } TEST_P(Cart2PolarTest, AccuracyTest) { cv::Mat out_mat2(sz, dtype); cv::Mat out_mat_ocv2(sz, dtype); // G-API code ////////////////////////////////////////////////////////////// cv::GMat in1, in2, out1, out2; std::tie(out1, out2) = cv::gapi::cartToPolar(in1, in2); cv::GComputation c(GIn(in1, in2), GOut(out1, out2)); c.apply(gin(in_mat1,in_mat2), gout(out_mat_gapi, out_mat2)); // OpenCV code ///////////////////////////////////////////////////////////// { cv::cartToPolar(in_mat1, in_mat2, out_mat_ocv, out_mat_ocv2); } // Comparison ////////////////////////////////////////////////////////////// { // Note that we cannot rely on bit-exact sin/cos functions used for this // transform, so we need a threshold for verifying results vs reference. // // Relative threshold like 1e-6 is very restrictive, nearly best we can // expect of single-precision elementary functions implementation. // // However, good idea is making such threshold configurable: parameter // of this test - which a specific test instantiation could setup. // // Note that test instantiation for the OpenCV back-end could even let // the threshold equal to zero, as CV back-end calls the same kernel. // // TODO: Make threshold a configurable parameter of this test (ADE-221) ASSERT_EQ(out_mat_gapi.size(), sz); cv::Mat &outm = out_mat_gapi, &outa = out_mat2; cv::Mat &refm = out_mat_ocv, &refa = out_mat_ocv2; // FIXME: Angle result looks inaccurate at OpenCV // (expected relative accuracy like 1e-6) EXPECT_LE(cvtest::norm(refm, outm, NORM_INF), 1e-6); EXPECT_LE(cvtest::norm(refa, outa, NORM_INF), 1e-3); } } TEST_P(CmpTest, AccuracyTest) { // G-API code & corresponding OpenCV code //////////////////////////////// cv::GMat in1, out; if( testWithScalar ) { cv::GScalar in2; switch(opType) { case CMP_EQ: out = cv::gapi::cmpEQ(in1, in2); break; case CMP_GT: out = cv::gapi::cmpGT(in1, in2); break; case CMP_GE: out = cv::gapi::cmpGE(in1, in2); break; case CMP_LT: out = cv::gapi::cmpLT(in1, in2); break; case CMP_LE: out = cv::gapi::cmpLE(in1, in2); break; case CMP_NE: out = cv::gapi::cmpNE(in1, in2); break; default: FAIL() << ""no such compare operation type for matrix and scalar!""; } cv::compare(in_mat1, sc, out_mat_ocv, opType); cv::GComputation c(GIn(in1, in2), GOut(out)); c.apply(gin(in_mat1, sc), gout(out_mat_gapi), getCompileArgs()); } else { cv::GMat in2; switch(opType) { case CMP_EQ: out = cv::gapi::cmpEQ(in1, in2); break; case CMP_GT: out = cv::gapi::cmpGT(in1, in2); break; case CMP_GE: out = cv::gapi::cmpGE(in1, in2); break; case CMP_LT: out = cv::gapi::cmpLT(in1, in2); break; case CMP_LE: out = cv::gapi::cmpLE(in1, in2); break; case CMP_NE: out = cv::gapi::cmpNE(in1, in2); break; default: FAIL() << ""no such compare operation type for two matrices!""; } cv::compare(in_mat1, in_mat2, out_mat_ocv, opType); cv::GComputation c(GIn(in1, in2), GOut(out)); c.apply(gin(in_mat1, in_mat2), gout(out_mat_gapi), getCompileArgs()); } // Comparison ////////////////////////////////////////////////////////////// { ASSERT_EQ(out_mat_gapi.size(), sz); EXPECT_TRUE(cmpF(out_mat_gapi, out_mat_ocv)); } } TEST_P(BitwiseTest, AccuracyTest) { // G-API code & corresponding OpenCV code //////////////////////////////// cv::GMat in1, in2, out; if( testWithScalar ) { cv::GScalar sc1; switch(opType) { case AND: out = cv::gapi::bitwise_and(in1, sc1); cv::bitwise_and(in_mat1, sc, out_mat_ocv); break; case OR: out = cv::gapi::bitwise_or(in1, sc1); cv::bitwise_or(in_mat1, sc, out_mat_ocv); break; case XOR: out = cv::gapi::bitwise_xor(in1, sc1); cv::bitwise_xor(in_mat1, sc, out_mat_ocv); break; default: FAIL() << ""no such bitwise operation type!""; } cv::GComputation c(GIn(in1, sc1), GOut(out)); c.apply(gin(in_mat1, sc), gout(out_mat_gapi), getCompileArgs()); } else { switch(opType) { case AND: out = cv::gapi::bitwise_and(in1, in2); cv::bitwise_and(in_mat1, in_mat2, out_mat_ocv); break; case OR: out = cv::gapi::bitwise_or(in1, in2); cv::bitwise_or(in_mat1, in_mat2, out_mat_ocv); break; case XOR: out = cv::gapi::bitwise_xor(in1, in2); cv::bitwise_xor(in_mat1, in_mat2, out_mat_ocv); break; default: FAIL() << ""no such bitwise operation type!""; } cv::GComputation c(GIn(in1, in2), GOut(out)); c.apply(gin(in_mat1, in_mat2), gout(out_mat_gapi), getCompileArgs()); } // Comparison ////////////////////////////////////////////////////////////// { ASSERT_EQ(out_mat_gapi.size(), sz); EXPECT_EQ(0, cvtest::norm(out_mat_ocv, out_mat_gapi, NORM_INF)); } } TEST_P(NotTest, AccuracyTest) { // G-API code ////////////////////////////////////////////////////////////// cv::GMat in; auto out = cv::gapi::bitwise_not(in); cv::GComputation c(in, out); c.apply(in_mat1, out_mat_gapi, getCompileArgs()); // OpenCV code ///////////////////////////////////////////////////////////// { cv::bitwise_not(in_mat1, out_mat_ocv); } // Comparison ////////////////////////////////////////////////////////////// { ASSERT_EQ(out_mat_gapi.size(), sz); EXPECT_EQ(0, cvtest::norm(out_mat_ocv, out_mat_gapi, NORM_INF)); } } TEST_P(SelectTest, AccuracyTest) { cv::Mat in_mask(sz, CV_8UC1); cv::randu(in_mask, cv::Scalar::all(0), cv::Scalar::all(255)); // G-API code ////////////////////////////////////////////////////////////// cv::GMat in1, in2, in3; auto out = cv::gapi::select(in1, in2, in3); cv::GComputation c(GIn(in1, in2, in3), GOut(out)); c.apply(gin(in_mat1, in_mat2, in_mask), gout(out_mat_gapi), getCompileArgs()); // OpenCV code ///////////////////////////////////////////////////////////// { in_mat2.copyTo(out_mat_ocv); in_mat1.copyTo(out_mat_ocv, in_mask); } // Comparison ////////////////////////////////////////////////////////////// { ASSERT_EQ(out_mat_gapi.size(), sz); EXPECT_EQ(0, cvtest::norm(out_mat_gapi, out_mat_ocv, NORM_INF)); } } TEST_P(MinTest, AccuracyTest) { // G-API code ////////////////////////////////////////////////////////////// cv::GMat in1, in2; auto out = cv::gapi::min(in1, in2); cv::GComputation c(GIn(in1, in2), GOut(out)); c.apply(gin(in_mat1, in_mat2), gout(out_mat_gapi), getCompileArgs()); // OpenCV code ///////////////////////////////////////////////////////////// { cv::min(in_mat1, in_mat2, out_mat_ocv); } // Comparison ////////////////////////////////////////////////////////////// { ASSERT_EQ(out_mat_gapi.size(), sz); EXPECT_EQ(0, cvtest::norm(out_mat_gapi, out_mat_ocv, NORM_INF)); } } TEST_P(MaxTest, AccuracyTest) { // G-API code ////////////////////////////////////////////////////////////// cv::GMat in1, in2; auto out = cv::gapi::max(in1, in2); cv::GComputation c(GIn(in1, in2), GOut(out)); c.apply(gin(in_mat1, in_mat2), gout(out_mat_gapi), getCompileArgs()); // OpenCV code ///////////////////////////////////////////////////////////// { cv::max(in_mat1, in_mat2, out_mat_ocv); } // Comparison ////////////////////////////////////////////////////////////// { ASSERT_EQ(out_mat_gapi.size(), sz); EXPECT_EQ(0, cvtest::norm(out_mat_gapi, out_mat_ocv, NORM_INF)); } } TEST_P(AbsDiffTest, AccuracyTest) { // G-API code ////////////////////////////////////////////////////////////// cv::GMat in1, in2; auto out = cv::gapi::absDiff(in1, in2); cv::GComputation c(GIn(in1, in2), GOut(out)); c.apply(gin(in_mat1, in_mat2), gout(out_mat_gapi), getCompileArgs()); // OpenCV code ///////////////////////////////////////////////////////////// { cv::absdiff(in_mat1, in_mat2, out_mat_ocv); } // Comparison ////////////////////////////////////////////////////////////// { ASSERT_EQ(out_mat_gapi.size(), sz); EXPECT_EQ(0, cvtest::norm(out_mat_gapi, out_mat_ocv, NORM_INF)); } } TEST_P(AbsDiffCTest, AccuracyTest) { // G-API code ////////////////////////////////////////////////////////////// cv::GMat in1; cv::GScalar sc1; auto out = cv::gapi::absDiffC(in1, sc1); cv::GComputation c(cv::GIn(in1, sc1), cv::GOut(out)); c.apply(gin(in_mat1, sc), gout(out_mat_gapi), getCompileArgs()); // OpenCV code ///////////////////////////////////////////////////////////// { cv::absdiff(in_mat1, sc, out_mat_ocv); } // Comparison ////////////////////////////////////////////////////////////// { ASSERT_EQ(out_mat_gapi.size(), sz); EXPECT_EQ(0, cvtest::norm(out_mat_gapi, out_mat_ocv, NORM_INF)); } } TEST_P(SumTest, AccuracyTest) { cv::Scalar out_sum; cv::Scalar out_sum_ocv; // G-API code ////////////////////////////////////////////////////////////// cv::GMat in; auto out = cv::gapi::sum(in); cv::GComputation c(cv::GIn(in), cv::GOut(out)); c.apply(cv::gin(in_mat1), cv::gout(out_sum), getCompileArgs()); // OpenCV code ///////////////////////////////////////////////////////////// { out_sum_ocv = cv::sum(in_mat1); } // Comparison ////////////////////////////////////////////////////////////// { EXPECT_TRUE(cmpF(out_sum, out_sum_ocv)); } } TEST_P(AddWeightedTest, AccuracyTest) { auto& rng = cv::theRNG(); double alpha = rng.uniform(0.0, 1.0); double beta = rng.uniform(0.0, 1.0); double gamma = rng.uniform(0.0, 1.0); // G-API code ////////////////////////////////////////////////////////////// cv::GMat in1, in2; auto out = cv::gapi::addWeighted(in1, alpha, in2, beta, gamma, dtype); cv::GComputation c(GIn(in1, in2), GOut(out)); c.apply(gin(in_mat1, in_mat2), gout(out_mat_gapi), getCompileArgs()); // OpenCV code ///////////////////////////////////////////////////////////// { cv::addWeighted(in_mat1, alpha, in_mat2, beta, gamma, out_mat_ocv, dtype); } // Comparison ////////////////////////////////////////////////////////////// EXPECT_TRUE(cmpF(out_mat_gapi, out_mat_ocv)); EXPECT_EQ(out_mat_gapi.size(), sz); } TEST_P(NormTest, AccuracyTest) { cv::Scalar out_norm; cv::Scalar out_norm_ocv; // G-API code & corresponding OpenCV code //////////////////////////////// cv::GMat in1; cv::GScalar out; switch(opType) { case NORM_L1: out = cv::gapi::normL1(in1); break; case NORM_L2: out = cv::gapi::normL2(in1); break; case NORM_INF: out = cv::gapi::normInf(in1); break; default: FAIL() << ""no such norm operation type!""; } out_norm_ocv = cv::norm(in_mat1, opType); cv::GComputation c(GIn(in1), GOut(out)); c.apply(gin(in_mat1), gout(out_norm), getCompileArgs()); // Comparison ////////////////////////////////////////////////////////////// { EXPECT_TRUE(cmpF(out_norm, out_norm_ocv)); } } TEST_P(IntegralTest, AccuracyTest) { int type_out = (type == CV_8U) ? CV_32SC1 : CV_64FC1; in_mat1 = cv::Mat(sz, type); cv::randu(in_mat1, cv::Scalar::all(0), cv::Scalar::all(255)); cv::Size sz_out = cv::Size(sz.width + 1, sz.height + 1); cv::Mat out_mat1(sz_out, type_out); cv::Mat out_mat_ocv1(sz_out, type_out); cv::Mat out_mat2(sz_out, CV_64FC1); cv::Mat out_mat_ocv2(sz_out, CV_64FC1); // G-API code ////////////////////////////////////////////////////////////// cv::GMat in1, out1, out2; std::tie(out1, out2) = cv::gapi::integral(in1, type_out, CV_64FC1); cv::GComputation c(cv::GIn(in1), cv::GOut(out1, out2)); c.apply(cv::gin(in_mat1), cv::gout(out_mat1, out_mat2), getCompileArgs()); // OpenCV code ///////////////////////////////////////////////////////////// { cv::integral(in_mat1, out_mat_ocv1, out_mat_ocv2); } // Comparison ////////////////////////////////////////////////////////////// { EXPECT_EQ(0, cvtest::norm(out_mat_ocv1, out_mat1, NORM_INF)); EXPECT_EQ(0, cvtest::norm(out_mat_ocv2, out_mat2, NORM_INF)); } } TEST_P(ThresholdTest, AccuracyTestBinary) { cv::Scalar thr = initScalarRandU(50); cv::Scalar out_scalar; // G-API code ////////////////////////////////////////////////////////////// cv::GMat in1, out; cv::GScalar th1, mv1; out = cv::gapi::threshold(in1, th1, mv1, tt); cv::GComputation c(GIn(in1, th1, mv1), GOut(out)); c.apply(gin(in_mat1, thr, maxval), gout(out_mat_gapi), getCompileArgs()); // OpenCV code ///////////////////////////////////////////////////////////// { cv::threshold(in_mat1, out_mat_ocv, thr.val[0], maxval.val[0], tt); } // Comparison ////////////////////////////////////////////////////////////// { ASSERT_EQ(out_mat_gapi.size(), sz); EXPECT_EQ(0, cv::norm(out_mat_ocv, out_mat_gapi, NORM_L1)); } } TEST_P(ThresholdOTTest, AccuracyTestOtsu) { cv::Scalar maxval = initScalarRandU(50) + cv::Scalar(50, 50, 50, 50); cv::Scalar out_gapi_scalar; double ocv_res; // G-API code ////////////////////////////////////////////////////////////// cv::GMat in1, out; cv::GScalar mv1, scout; std::tie(out, scout) = cv::gapi::threshold(in1, mv1, tt); cv::GComputation c(cv::GIn(in1, mv1), cv::GOut(out, scout)); c.apply(gin(in_mat1, maxval), gout(out_mat_gapi, out_gapi_scalar), getCompileArgs()); // OpenCV code ///////////////////////////////////////////////////////////// { ocv_res = cv::threshold(in_mat1, out_mat_ocv, maxval.val[0], maxval.val[0], tt); } // Comparison ////////////////////////////////////////////////////////////// { EXPECT_EQ(0, cvtest::norm(out_mat_ocv, out_mat_gapi, NORM_INF)); EXPECT_EQ(out_mat_gapi.size(), sz); EXPECT_EQ(ocv_res, out_gapi_scalar.val[0]); } } TEST_P(InRangeTest, AccuracyTest) { cv::Scalar thrLow = initScalarRandU(100); cv::Scalar thrUp = initScalarRandU(100) + cv::Scalar(100, 100, 100, 100); // G-API code ////////////////////////////////////////////////////////////// cv::GMat in1; cv::GScalar th1, mv1; auto out = cv::gapi::inRange(in1, th1, mv1); cv::GComputation c(GIn(in1, th1, mv1), GOut(out)); c.apply(gin(in_mat1, thrLow, thrUp), gout(out_mat_gapi), getCompileArgs()); // OpenCV code ///////////////////////////////////////////////////////////// { cv::inRange(in_mat1, thrLow, thrUp, out_mat_ocv); } // Comparison ////////////////////////////////////////////////////////////// { ASSERT_EQ(out_mat_gapi.size(), sz); EXPECT_EQ(0, cvtest::norm(out_mat_ocv, out_mat_gapi, NORM_INF)); } } TEST_P(Split3Test, AccuracyTest) { cv::Mat out_mat2 = cv::Mat(sz, dtype); cv::Mat out_mat3 = cv::Mat(sz, dtype); cv::Mat out_mat_ocv2 = cv::Mat(sz, dtype); cv::Mat out_mat_ocv3 = cv::Mat(sz, dtype); // G-API code ////////////////////////////////////////////////////////////// cv::GMat in1, out1, out2, out3; std::tie(out1, out2, out3) = cv::gapi::split3(in1); cv::GComputation c(cv::GIn(in1), cv::GOut(out1, out2, out3)); c.apply(cv::gin(in_mat1), cv::gout(out_mat_gapi, out_mat2, out_mat3), getCompileArgs()); // OpenCV code ///////////////////////////////////////////////////////////// { std::vector out_mats_ocv = {out_mat_ocv, out_mat_ocv2, out_mat_ocv3}; cv::split(in_mat1, out_mats_ocv); } // Comparison ////////////////////////////////////////////////////////////// { EXPECT_EQ(0, cvtest::norm(out_mat_ocv, out_mat_gapi, NORM_INF)); EXPECT_EQ(0, cvtest::norm(out_mat_ocv2, out_mat2, NORM_INF)); EXPECT_EQ(0, cvtest::norm(out_mat_ocv3, out_mat3, NORM_INF)); } } TEST_P(Split4Test, AccuracyTest) { cv::Mat out_mat2 = cv::Mat(sz, dtype); cv::Mat out_mat3 = cv::Mat(sz, dtype); cv::Mat out_mat4 = cv::Mat(sz, dtype); cv::Mat out_mat_ocv2 = cv::Mat(sz, dtype); cv::Mat out_mat_ocv3 = cv::Mat(sz, dtype); cv::Mat out_mat_ocv4 = cv::Mat(sz, dtype); // G-API code ////////////////////////////////////////////////////////////// cv::GMat in1, out1, out2, out3, out4; std::tie(out1, out2, out3, out4) = cv::gapi::split4(in1); cv::GComputation c(cv::GIn(in1), cv::GOut(out1, out2, out3, out4)); c.apply(cv::gin(in_mat1), cv::gout(out_mat_gapi, out_mat2, out_mat3, out_mat4), getCompileArgs()); // OpenCV code ///////////////////////////////////////////////////////////// { std::vector out_mats_ocv = {out_mat_ocv, out_mat_ocv2, out_mat_ocv3, out_mat_ocv4}; cv::split(in_mat1, out_mats_ocv); } // Comparison ////////////////////////////////////////////////////////////// { EXPECT_EQ(0, cvtest::norm(out_mat_ocv, out_mat_gapi, NORM_INF)); EXPECT_EQ(0, cvtest::norm(out_mat_ocv2, out_mat2, NORM_INF)); EXPECT_EQ(0, cvtest::norm(out_mat_ocv3, out_mat3, NORM_INF)); EXPECT_EQ(0, cvtest::norm(out_mat_ocv4, out_mat4, NORM_INF)); } } static void ResizeAccuracyTest(const CompareMats& cmpF, int type, int interp, cv::Size sz_in, cv::Size sz_out, double fx, double fy, cv::GCompileArgs&& compile_args) { cv::Mat in_mat1 (sz_in, type ); cv::Scalar mean = cv::Scalar::all(127); cv::Scalar stddev = cv::Scalar::all(40.f); cv::randn(in_mat1, mean, stddev); auto out_mat_sz = sz_out.area() == 0 ? cv::Size(saturate_cast(sz_in.width *fx), saturate_cast(sz_in.height*fy)) : sz_out; cv::Mat out_mat(out_mat_sz, type); cv::Mat out_mat_ocv(out_mat_sz, type); // G-API code ////////////////////////////////////////////////////////////// cv::GMat in; auto out = cv::gapi::resize(in, sz_out, fx, fy, interp); cv::GComputation c(in, out); c.apply(in_mat1, out_mat, std::move(compile_args)); // OpenCV code ///////////////////////////////////////////////////////////// { cv::resize(in_mat1, out_mat_ocv, sz_out, fx, fy, interp); } // Comparison ////////////////////////////////////////////////////////////// { EXPECT_TRUE(cmpF(out_mat, out_mat_ocv)); } } TEST_P(ResizeTest, AccuracyTest) { ResizeAccuracyTest(cmpF, type, interp, sz, sz_out, 0.0, 0.0, getCompileArgs()); } TEST_P(ResizeTestFxFy, AccuracyTest) { ResizeAccuracyTest(cmpF, type, interp, sz, cv::Size{0, 0}, fx, fy, getCompileArgs()); } TEST_P(ResizePTest, AccuracyTest) { constexpr int planeNum = 3; cv::Size sz_in_p {sz.width, sz.height*planeNum}; cv::Size sz_out_p{sz_out.width, sz_out.height*planeNum}; cv::Mat in_mat(sz_in_p, CV_8UC1); cv::randn(in_mat, cv::Scalar::all(127.0f), cv::Scalar::all(40.f)); cv::Mat out_mat (sz_out_p, CV_8UC1); cv::Mat out_mat_ocv_p(sz_out_p, CV_8UC1); cv::GMatP in; auto out = cv::gapi::resizeP(in, sz_out, interp); cv::GComputation c(cv::GIn(in), cv::GOut(out)); c.compile(cv::descr_of(in_mat).asPlanar(planeNum), getCompileArgs()) (cv::gin(in_mat), cv::gout(out_mat)); for (int i = 0; i < planeNum; i++) { const cv::Mat in_mat_roi = in_mat(cv::Rect(0, i*sz.height, sz.width, sz.height)); cv::Mat out_mat_roi = out_mat_ocv_p(cv::Rect(0, i*sz_out.height, sz_out.width, sz_out.height)); cv::resize(in_mat_roi, out_mat_roi, sz_out, 0, 0, interp); } // Comparison ////////////////////////////////////////////////////////////// { EXPECT_TRUE(cmpF(out_mat, out_mat_ocv_p)); } } TEST_P(Merge3Test, AccuracyTest) { cv::Mat in_mat3(sz, type); cv::Scalar mean = cv::Scalar::all(127); cv::Scalar stddev = cv::Scalar::all(40.f); cv::randn(in_mat3, mean, stddev); // G-API code ////////////////////////////////////////////////////////////// cv::GMat in1, in2, in3; auto out = cv::gapi::merge3(in1, in2, in3); cv::GComputation c(cv::GIn(in1, in2, in3), cv::GOut(out)); c.apply(cv::gin(in_mat1, in_mat2, in_mat3), cv::gout(out_mat_gapi), getCompileArgs()); // OpenCV code ///////////////////////////////////////////////////////////// { std::vector in_mats_ocv = {in_mat1, in_mat2, in_mat3}; cv::merge(in_mats_ocv, out_mat_ocv); } // Comparison ////////////////////////////////////////////////////////////// { EXPECT_EQ(0, cvtest::norm(out_mat_ocv, out_mat_gapi, NORM_INF)); } } TEST_P(Merge4Test, AccuracyTest) { cv::Mat in_mat3(sz, type); cv::Mat in_mat4(sz, type); cv::Scalar mean = cv::Scalar::all(127); cv::Scalar stddev = cv::Scalar::all(40.f); cv::randn(in_mat3, mean, stddev); cv::randn(in_mat4, mean, stddev); // G-API code ////////////////////////////////////////////////////////////// cv::GMat in1, in2, in3, in4; auto out = cv::gapi::merge4(in1, in2, in3, in4); cv::GComputation c(cv::GIn(in1, in2, in3, in4), cv::GOut(out)); c.apply(cv::gin(in_mat1, in_mat2, in_mat3, in_mat4), cv::gout(out_mat_gapi), getCompileArgs()); // OpenCV code ///////////////////////////////////////////////////////////// { std::vector in_mats_ocv = {in_mat1, in_mat2, in_mat3, in_mat4}; cv::merge(in_mats_ocv, out_mat_ocv); } // Comparison ////////////////////////////////////////////////////////////// { EXPECT_EQ(0, cvtest::norm(out_mat_ocv, out_mat_gapi, NORM_INF)); } } TEST_P(RemapTest, AccuracyTest) { cv::Mat in_map1(sz, CV_16SC2); cv::Mat in_map2 = cv::Mat(); cv::randu(in_map1, cv::Scalar::all(0), cv::Scalar::all(255)); cv::Scalar bv = cv::Scalar(); // G-API code ////////////////////////////////////////////////////////////// cv::GMat in1; auto out = cv::gapi::remap(in1, in_map1, in_map2, cv::INTER_NEAREST, cv::BORDER_REPLICATE, bv); cv::GComputation c(in1, out); c.apply(in_mat1, out_mat_gapi, getCompileArgs()); // OpenCV code ///////////////////////////////////////////////////////////// { cv::remap(in_mat1, out_mat_ocv, in_map1, in_map2, cv::INTER_NEAREST, cv::BORDER_REPLICATE, bv); } // Comparison ////////////////////////////////////////////////////////////// { EXPECT_EQ(0, cvtest::norm(out_mat_ocv, out_mat_gapi, NORM_INF)); EXPECT_EQ(out_mat_gapi.size(), sz); } } TEST_P(FlipTest, AccuracyTest) { // G-API code ////////////////////////////////////////////////////////////// cv::GMat in; auto out = cv::gapi::flip(in, flipCode); cv::GComputation c(in, out); c.apply(in_mat1, out_mat_gapi, getCompileArgs()); // OpenCV code ///////////////////////////////////////////////////////////// { cv::flip(in_mat1, out_mat_ocv, flipCode); } // Comparison ////////////////////////////////////////////////////////////// { EXPECT_EQ(0, cvtest::norm(out_mat_ocv, out_mat_gapi, NORM_INF)); EXPECT_EQ(out_mat_gapi.size(), sz); } } TEST_P(CropTest, AccuracyTest) { cv::Size sz_out = cv::Size(rect_to.width, rect_to.height); if (dtype != -1) { out_mat_gapi = cv::Mat(sz_out, dtype); out_mat_ocv = cv::Mat(sz_out, dtype); } // G-API code ////////////////////////////////////////////////////////////// cv::GMat in; auto out = cv::gapi::crop(in, rect_to); cv::GComputation c(in, out); c.apply(in_mat1, out_mat_gapi, getCompileArgs()); // OpenCV code ///////////////////////////////////////////////////////////// { cv::Mat(in_mat1, rect_to).copyTo(out_mat_ocv); } // Comparison ////////////////////////////////////////////////////////////// { EXPECT_EQ(0, cvtest::norm(out_mat_ocv, out_mat_gapi, NORM_INF)); EXPECT_EQ(out_mat_gapi.size(), sz_out); } } TEST_P(CopyTest, AccuracyTest) { cv::Size sz_out = sz; if (dtype != -1) { out_mat_gapi = cv::Mat(sz_out, dtype); out_mat_ocv = cv::Mat(sz_out, dtype); } // G-API code ////////////////////////////////////////////////////////////// cv::GMat in; auto out = cv::gapi::copy(in); cv::GComputation c(in, out); c.apply(in_mat1, out_mat_gapi, getCompileArgs()); // OpenCV code ///////////////////////////////////////////////////////////// { cv::Mat(in_mat1).copyTo(out_mat_ocv); } // Comparison ////////////////////////////////////////////////////////////// { EXPECT_EQ(0, cvtest::norm(out_mat_ocv, out_mat_gapi, NORM_INF)); EXPECT_EQ(out_mat_gapi.size(), sz_out); } } TEST_P(ConcatHorTest, AccuracyTest) { cv::Size sz_out = sz; int wpart = sz_out.width / 4; cv::Size sz_in1 = cv::Size(wpart, sz_out.height); cv::Size sz_in2 = cv::Size(sz_out.width - wpart, sz_out.height); in_mat1 = cv::Mat(sz_in1, type ); in_mat2 = cv::Mat(sz_in2, type); cv::Scalar mean = cv::Scalar::all(127); cv::Scalar stddev = cv::Scalar::all(40.f); cv::randn(in_mat1, mean, stddev); cv::randn(in_mat2, mean, stddev); cv::Mat out_mat(sz_out, type); out_mat_ocv = cv::Mat(sz_out, type); // G-API code ////////////////////////////////////////////////////////////// cv::GMat in1, in2; auto out = cv::gapi::concatHor(in1, in2); cv::GComputation c(GIn(in1, in2), GOut(out)); c.apply(gin(in_mat1, in_mat2), gout(out_mat), getCompileArgs()); // OpenCV code ///////////////////////////////////////////////////////////// { cv::hconcat(in_mat1, in_mat2, out_mat_ocv); } // Comparison ////////////////////////////////////////////////////////////// { EXPECT_EQ(0, cvtest::norm(out_mat_ocv, out_mat, NORM_INF)); } } TEST_P(ConcatVertTest, AccuracyTest) { cv::Size sz_out = sz; int hpart = sz_out.height * 2/3; cv::Size sz_in1 = cv::Size(sz_out.width, hpart); cv::Size sz_in2 = cv::Size(sz_out.width, sz_out.height - hpart); in_mat1 = cv::Mat(sz_in1, type); in_mat2 = cv::Mat(sz_in2, type); cv::Scalar mean = cv::Scalar::all(127); cv::Scalar stddev = cv::Scalar::all(40.f); cv::randn(in_mat1, mean, stddev); cv::randn(in_mat2, mean, stddev); cv::Mat out_mat(sz_out, type); out_mat_ocv = cv::Mat(sz_out, type); // G-API code ////////////////////////////////////////////////////////////// cv::GMat in1, in2; auto out = cv::gapi::concatVert(in1, in2); cv::GComputation c(GIn(in1, in2), GOut(out)); c.apply(gin(in_mat1, in_mat2), gout(out_mat), getCompileArgs()); // OpenCV code ///////////////////////////////////////////////////////////// { cv::vconcat(in_mat1, in_mat2, out_mat_ocv ); } // Comparison ////////////////////////////////////////////////////////////// { EXPECT_EQ(0, cvtest::norm(out_mat_ocv, out_mat, NORM_INF)); } } TEST_P(ConcatVertVecTest, AccuracyTest) { cv::Size sz_out = sz; int hpart1 = sz_out.height * 2/5; int hpart2 = sz_out.height / 5; cv::Size sz_in1 = cv::Size(sz_out.width, hpart1); cv::Size sz_in2 = cv::Size(sz_out.width, hpart2); cv::Size sz_in3 = cv::Size(sz_out.width, sz_out.height - hpart1 - hpart2); in_mat1 = cv::Mat(sz_in1, type); in_mat2 = cv::Mat(sz_in2, type); cv::Mat in_mat3(sz_in3, type); cv::Scalar mean = cv::Scalar::all(127); cv::Scalar stddev = cv::Scalar::all(40.f); cv::randn(in_mat1, mean, stddev); cv::randn(in_mat2, mean, stddev); cv::randn(in_mat3, mean, stddev); cv::Mat out_mat(sz_out, type); out_mat_ocv = cv::Mat(sz_out, type); // G-API code ////////////////////////////////////////////////////////////// std::vector mats(3); auto out = cv::gapi::concatVert(mats); std::vector cvmats = {in_mat1, in_mat2, in_mat3}; cv::GComputation c({mats[0], mats[1], mats[2]}, {out}); c.apply(gin(in_mat1, in_mat2, in_mat3), gout(out_mat), getCompileArgs()); // OpenCV code ///////////////////////////////////////////////////////////// { cv::vconcat(cvmats, out_mat_ocv ); } // Comparison ////////////////////////////////////////////////////////////// { EXPECT_EQ(0, cvtest::norm(out_mat_ocv, out_mat, NORM_INF)); } } TEST_P(ConcatHorVecTest, AccuracyTest) { cv::Size sz_out = sz; int wpart1 = sz_out.width / 3; int wpart2 = sz_out.width / 4; cv::Size sz_in1 = cv::Size(wpart1, sz_out.height); cv::Size sz_in2 = cv::Size(wpart2, sz_out.height); cv::Size sz_in3 = cv::Size(sz_out.width - wpart1 - wpart2, sz_out.height); in_mat1 = cv::Mat(sz_in1, type); in_mat2 = cv::Mat(sz_in2, type); cv::Mat in_mat3 (sz_in3, type); cv::Scalar mean = cv::Scalar::all(127); cv::Scalar stddev = cv::Scalar::all(40.f); cv::randn(in_mat1, mean, stddev); cv::randn(in_mat2, mean, stddev); cv::randn(in_mat3, mean, stddev); cv::Mat out_mat(sz_out, type); out_mat_ocv = cv::Mat(sz_out, type); // G-API code ////////////////////////////////////////////////////////////// std::vector mats(3); auto out = cv::gapi::concatHor(mats); std::vector cvmats = {in_mat1, in_mat2, in_mat3}; cv::GComputation c({mats[0], mats[1], mats[2]}, {out}); c.apply(gin(in_mat1, in_mat2, in_mat3), gout(out_mat), getCompileArgs()); // OpenCV code ///////////////////////////////////////////////////////////// { cv::hconcat(cvmats, out_mat_ocv ); } // Comparison ////////////////////////////////////////////////////////////// { EXPECT_EQ(0, cvtest::norm(out_mat_ocv, out_mat, NORM_INF)); } } TEST_P(LUTTest, AccuracyTest) { int type_mat = type; int type_lut = dtype; int type_out = CV_MAKETYPE(CV_MAT_DEPTH(type_lut), CV_MAT_CN(type_mat)); initMatrixRandU(type_mat, sz, type_out); cv::Size sz_lut = cv::Size(1, 256); cv::Mat in_lut(sz_lut, type_lut); cv::randu(in_lut, cv::Scalar::all(0), cv::Scalar::all(255)); // G-API code ////////////////////////////////////////////////////////////// cv::GMat in; auto out = cv::gapi::LUT(in, in_lut); cv::GComputation c(in, out); c.apply(in_mat1, out_mat_gapi, getCompileArgs()); // OpenCV code ///////////////////////////////////////////////////////////// { cv::LUT(in_mat1, in_lut, out_mat_ocv); } // Comparison ////////////////////////////////////////////////////////////// { EXPECT_EQ(0, cvtest::norm(out_mat_ocv, out_mat_gapi, NORM_INF)); EXPECT_EQ(out_mat_gapi.size(), sz); } } TEST_P(ConvertToTest, AccuracyTest) { int type_mat = type; int depth_to = dtype; int type_out = CV_MAKETYPE(depth_to, CV_MAT_CN(type_mat)); initMatrixRandU(type_mat, sz, type_out); // G-API code ////////////////////////////////////////////////////////////// cv::GMat in; auto out = cv::gapi::convertTo(in, depth_to, alpha, beta); cv::GComputation c(in, out); c.apply(in_mat1, out_mat_gapi, getCompileArgs()); // OpenCV code ///////////////////////////////////////////////////////////// { in_mat1.convertTo(out_mat_ocv, depth_to, alpha, beta); } // Comparison ////////////////////////////////////////////////////////////// { EXPECT_TRUE(cmpF(out_mat_gapi, out_mat_ocv)); EXPECT_EQ(out_mat_gapi.size(), sz); } } TEST_P(PhaseTest, AccuracyTest) { // G-API code ////////////////////////////////////////////////////////////// cv::GMat in_x, in_y; auto out = cv::gapi::phase(in_x, in_y, angle_in_degrees); cv::GComputation c(in_x, in_y, out); c.apply(in_mat1, in_mat2, out_mat_gapi, getCompileArgs()); // OpenCV code ///////////////////////////////////////////////////////////// cv::phase(in_mat1, in_mat2, out_mat_ocv, angle_in_degrees); // Comparison ////////////////////////////////////////////////////////////// // FIXME: use a comparison functor instead (after enabling OpenCL) { EXPECT_EQ(0, cvtest::norm(out_mat_ocv, out_mat_gapi, NORM_INF)); } } TEST_P(SqrtTest, AccuracyTest) { // G-API code ////////////////////////////////////////////////////////////// cv::GMat in; auto out = cv::gapi::sqrt(in); cv::GComputation c(in, out); c.apply(in_mat1, out_mat_gapi, getCompileArgs()); // OpenCV code ///////////////////////////////////////////////////////////// cv::sqrt(in_mat1, out_mat_ocv); // Comparison ////////////////////////////////////////////////////////////// // FIXME: use a comparison functor instead (after enabling OpenCL) { EXPECT_EQ(0, cvtest::norm(out_mat_ocv, out_mat_gapi, NORM_INF)); } } TEST_P(WarpPerspectiveTest, AccuracyTest) { cv::Point center{in_mat1.size() / 2}; cv::Mat xy = cv::getRotationMatrix2D(center, angle, scale); cv::Matx13d z (0, 0, 1); cv::Mat transform_mat; cv::vconcat(xy, z, transform_mat); // G-API code ////////////////////////////////////////////////////////////// cv::GMat in; auto out = cv::gapi::warpPerspective(in, transform_mat, in_mat1.size(), flags, border_mode, border_value); cv::GComputation c(in, out); c.apply(in_mat1, out_mat_gapi, getCompileArgs()); // OpenCV code ///////////////////////////////////////////////////////////// cv::warpPerspective(in_mat1, out_mat_ocv, cv::Mat(transform_mat), in_mat1.size(), flags, border_mode, border_value); // Comparison ////////////////////////////////////////////////////////////// { EXPECT_TRUE(cmpF(out_mat_gapi, out_mat_ocv)); } } TEST_P(WarpAffineTest, AccuracyTest) { cv::Point center{in_mat1.size() / 2}; cv::Mat warp_mat = cv::getRotationMatrix2D(center, angle, scale); // G-API code ////////////////////////////////////////////////////////////// cv::GMat in; auto out = cv::gapi::warpAffine(in, warp_mat, in_mat1.size(), flags, border_mode, border_value); cv::GComputation c(in, out); c.apply(in_mat1, out_mat_gapi, getCompileArgs()); // OpenCV code ///////////////////////////////////////////////////////////// cv::warpAffine(in_mat1, out_mat_ocv, warp_mat, in_mat1.size(), flags, border_mode, border_value); // Comparison ////////////////////////////////////////////////////////////// { EXPECT_TRUE(cmpF(out_mat_gapi, out_mat_ocv)); } } TEST_P(NormalizeTest, Test) { initMatrixRandN(type, sz, CV_MAKETYPE(ddepth, CV_MAT_CN(type))); // G-API code ////////////////////////////////////////////////////////////// cv::GMat in; auto out = cv::gapi::normalize(in, a, b, norm_type, ddepth); cv::GComputation c(cv::GIn(in), cv::GOut(out)); c.apply(cv::gin(in_mat1), cv::gout(out_mat_gapi), getCompileArgs()); // OpenCV code ///////////////////////////////////////////////////////////// { cv::normalize(in_mat1, out_mat_ocv, a, b, norm_type, ddepth); } // Comparison ////////////////////////////////////////////////////////////// { EXPECT_TRUE(cmpF(out_mat_gapi, out_mat_ocv)); EXPECT_EQ(out_mat_gapi.size(), sz); } } // PLEASE DO NOT PUT NEW ACCURACY TESTS BELOW THIS POINT! ////////////////////// TEST_P(BackendOutputAllocationTest, EmptyOutput) { // G-API code ////////////////////////////////////////////////////////////// cv::GMat in1, in2, out; out = cv::gapi::mul(in1, in2); cv::GComputation c(cv::GIn(in1, in2), cv::GOut(out)); EXPECT_TRUE(out_mat_gapi.empty()); c.apply(cv::gin(in_mat1, in_mat2), cv::gout(out_mat_gapi), getCompileArgs()); EXPECT_FALSE(out_mat_gapi.empty()); // OpenCV code ///////////////////////////////////////////////////////////// cv::multiply(in_mat1, in_mat2, out_mat_ocv); // Comparison ////////////////////////////////////////////////////////////// // Expected: output is allocated to the needed size EXPECT_EQ(0, cvtest::norm(out_mat_gapi, out_mat_ocv, NORM_INF)); EXPECT_EQ(sz, out_mat_gapi.size()); } TEST_P(BackendOutputAllocationTest, CorrectlyPreallocatedOutput) { out_mat_gapi = cv::Mat(sz, type); auto out_mat_gapi_ref = out_mat_gapi; // shallow copy to ensure previous data is not deleted // G-API code ////////////////////////////////////////////////////////////// cv::GMat in1, in2, out; out = cv::gapi::add(in1, in2); cv::GComputation c(cv::GIn(in1, in2), cv::GOut(out)); c.apply(cv::gin(in_mat1, in_mat2), cv::gout(out_mat_gapi), getCompileArgs()); // OpenCV code ///////////////////////////////////////////////////////////// cv::add(in_mat1, in_mat2, out_mat_ocv); // Comparison ////////////////////////////////////////////////////////////// // Expected: output is not reallocated EXPECT_EQ(0, cvtest::norm(out_mat_gapi, out_mat_ocv, NORM_INF)); EXPECT_EQ(sz, out_mat_gapi.size()); EXPECT_EQ(out_mat_gapi_ref.data, out_mat_gapi.data); } TEST_P(BackendOutputAllocationTest, IncorrectOutputMeta) { // G-API code ////////////////////////////////////////////////////////////// cv::GMat in1, in2, out; out = cv::gapi::add(in1, in2); cv::GComputation c(cv::GIn(in1, in2), cv::GOut(out)); const auto run_and_compare = [&c, this] () { auto out_mat_gapi_ref = out_mat_gapi; // shallow copy to ensure previous data is not deleted // G-API code ////////////////////////////////////////////////////////////// c.apply(cv::gin(in_mat1, in_mat2), cv::gout(out_mat_gapi), getCompileArgs()); // OpenCV code ///////////////////////////////////////////////////////////// cv::add(in_mat1, in_mat2, out_mat_ocv, cv::noArray()); // Comparison ////////////////////////////////////////////////////////////// // Expected: size is changed, type is changed, output is reallocated EXPECT_EQ(0, cvtest::norm(out_mat_gapi, out_mat_ocv, NORM_INF)); EXPECT_EQ(sz, out_mat_gapi.size()); EXPECT_EQ(type, out_mat_gapi.type()); EXPECT_NE(out_mat_gapi_ref.data, out_mat_gapi.data); }; const auto chan = CV_MAT_CN(type); out_mat_gapi = cv::Mat(sz, CV_MAKE_TYPE(CV_64F, chan)); run_and_compare(); out_mat_gapi = cv::Mat(sz, CV_MAKE_TYPE(CV_MAT_DEPTH(type), chan + 1)); run_and_compare(); } TEST_P(BackendOutputAllocationTest, SmallerPreallocatedSize) { out_mat_gapi = cv::Mat(sz / 2, type); auto out_mat_gapi_ref = out_mat_gapi; // shallow copy to ensure previous data is not deleted // G-API code ////////////////////////////////////////////////////////////// cv::GMat in1, in2, out; out = cv::gapi::mul(in1, in2); cv::GComputation c(cv::GIn(in1, in2), cv::GOut(out)); c.apply(cv::gin(in_mat1, in_mat2), cv::gout(out_mat_gapi), getCompileArgs()); // OpenCV code ///////////////////////////////////////////////////////////// cv::multiply(in_mat1, in_mat2, out_mat_ocv); // Comparison ////////////////////////////////////////////////////////////// // Expected: size is changed, output is reallocated due to original size < curr size EXPECT_EQ(0, cvtest::norm(out_mat_gapi, out_mat_ocv, NORM_INF)); EXPECT_EQ(sz, out_mat_gapi.size()); EXPECT_NE(out_mat_gapi_ref.data, out_mat_gapi.data); } TEST_P(BackendOutputAllocationTest, SmallerPreallocatedSizeWithSubmatrix) { out_mat_gapi = cv::Mat(sz / 2, type); cv::Mat out_mat_gapi_submat = out_mat_gapi(cv::Rect({10, 0}, sz / 5)); EXPECT_EQ(out_mat_gapi.data, out_mat_gapi_submat.datastart); auto out_mat_gapi_submat_ref = out_mat_gapi_submat; // shallow copy to ensure previous data is not deleted // G-API code ////////////////////////////////////////////////////////////// cv::GMat in1, in2, out; out = cv::gapi::mul(in1, in2); cv::GComputation c(cv::GIn(in1, in2), cv::GOut(out)); c.apply(cv::gin(in_mat1, in_mat2), cv::gout(out_mat_gapi_submat), getCompileArgs()); // OpenCV code ///////////////////////////////////////////////////////////// cv::multiply(in_mat1, in_mat2, out_mat_ocv); // Comparison ////////////////////////////////////////////////////////////// // Expected: submatrix is reallocated and is ""detached"", original matrix is unchanged EXPECT_EQ(0, cvtest::norm(out_mat_gapi_submat, out_mat_ocv, NORM_INF)); EXPECT_EQ(sz, out_mat_gapi_submat.size()); EXPECT_EQ(sz / 2, out_mat_gapi.size()); EXPECT_NE(out_mat_gapi_submat_ref.data, out_mat_gapi_submat.data); EXPECT_NE(out_mat_gapi.data, out_mat_gapi_submat.datastart); } TEST_P(BackendOutputAllocationTest, LargerPreallocatedSize) { out_mat_gapi = cv::Mat(sz * 2, type); auto out_mat_gapi_ref = out_mat_gapi; // shallow copy to ensure previous data is not deleted // G-API code ////////////////////////////////////////////////////////////// cv::GMat in1, in2, out; out = cv::gapi::mul(in1, in2); cv::GComputation c(cv::GIn(in1, in2), cv::GOut(out)); c.apply(cv::gin(in_mat1, in_mat2), cv::gout(out_mat_gapi), getCompileArgs()); // OpenCV code ///////////////////////////////////////////////////////////// cv::multiply(in_mat1, in_mat2, out_mat_ocv); // Comparison ////////////////////////////////////////////////////////////// // Expected: size is changed, output is reallocated EXPECT_EQ(0, cvtest::norm(out_mat_gapi, out_mat_ocv, NORM_INF)); EXPECT_EQ(sz, out_mat_gapi.size()); EXPECT_NE(out_mat_gapi_ref.data, out_mat_gapi.data); } TEST_P(BackendOutputAllocationLargeSizeWithCorrectSubmatrixTest, LargerPreallocatedSizeWithCorrectSubmatrix) { out_mat_gapi = cv::Mat(sz * 2, type); auto out_mat_gapi_ref = out_mat_gapi; // shallow copy to ensure previous data is not deleted cv::Mat out_mat_gapi_submat = out_mat_gapi(cv::Rect({5, 8}, sz)); EXPECT_EQ(out_mat_gapi.data, out_mat_gapi_submat.datastart); auto out_mat_gapi_submat_ref = out_mat_gapi_submat; // G-API code ////////////////////////////////////////////////////////////// cv::GMat in1, in2, out; out = cv::gapi::mul(in1, in2); cv::GComputation c(cv::GIn(in1, in2), cv::GOut(out)); c.apply(cv::gin(in_mat1, in_mat2), cv::gout(out_mat_gapi_submat), getCompileArgs()); // OpenCV code ///////////////////////////////////////////////////////////// cv::multiply(in_mat1, in_mat2, out_mat_ocv); // Comparison ////////////////////////////////////////////////////////////// // Expected: submatrix is not reallocated, original matrix is not reallocated EXPECT_EQ(0, cvtest::norm(out_mat_gapi_submat, out_mat_ocv, NORM_INF)); EXPECT_EQ(sz, out_mat_gapi_submat.size()); EXPECT_EQ(sz * 2, out_mat_gapi.size()); EXPECT_EQ(out_mat_gapi_ref.data, out_mat_gapi.data); EXPECT_EQ(out_mat_gapi_submat_ref.data, out_mat_gapi_submat.data); EXPECT_EQ(out_mat_gapi.data, out_mat_gapi_submat.datastart); } TEST_P(BackendOutputAllocationTest, LargerPreallocatedSizeWithSmallSubmatrix) { out_mat_gapi = cv::Mat(sz * 2, type); auto out_mat_gapi_ref = out_mat_gapi; // shallow copy to ensure previous data is not deleted cv::Mat out_mat_gapi_submat = out_mat_gapi(cv::Rect({5, 8}, sz / 2)); EXPECT_EQ(out_mat_gapi.data, out_mat_gapi_submat.datastart); auto out_mat_gapi_submat_ref = out_mat_gapi_submat; // G-API code ////////////////////////////////////////////////////////////// cv::GMat in1, in2, out; out = cv::gapi::mul(in1, in2); cv::GComputation c(cv::GIn(in1, in2), cv::GOut(out)); c.apply(cv::gin(in_mat1, in_mat2), cv::gout(out_mat_gapi_submat), getCompileArgs()); // OpenCV code ///////////////////////////////////////////////////////////// cv::multiply(in_mat1, in_mat2, out_mat_ocv); // Comparison ////////////////////////////////////////////////////////////// // Expected: submatrix is reallocated and is ""detached"", original matrix is unchanged EXPECT_EQ(0, cvtest::norm(out_mat_gapi_submat, out_mat_ocv, NORM_INF)); EXPECT_EQ(sz, out_mat_gapi_submat.size()); EXPECT_EQ(sz * 2, out_mat_gapi.size()); EXPECT_EQ(out_mat_gapi_ref.data, out_mat_gapi.data); EXPECT_NE(out_mat_gapi_submat_ref.data, out_mat_gapi_submat.data); EXPECT_NE(out_mat_gapi.data, out_mat_gapi_submat.datastart); } TEST_P(ReInitOutTest, TestWithAdd) { in_mat1 = cv::Mat(sz, type); in_mat2 = cv::Mat(sz, type); cv::randu(in_mat1, cv::Scalar::all(0), cv::Scalar::all(100)); cv::randu(in_mat2, cv::Scalar::all(0), cv::Scalar::all(100)); // G-API code ////////////////////////////////////////////////////////////// cv::GMat in1, in2, out; out = cv::gapi::add(in1, in2, dtype); cv::GComputation c(cv::GIn(in1, in2), cv::GOut(out)); const auto run_and_compare = [&c, this] () { // G-API code ////////////////////////////////////////////////////////////// c.apply(cv::gin(in_mat1, in_mat2), cv::gout(out_mat_gapi), getCompileArgs()); // OpenCV code ///////////////////////////////////////////////////////////// cv::add(in_mat1, in_mat2, out_mat_ocv, cv::noArray()); // Comparison ////////////////////////////////////////////////////////////// EXPECT_EQ(0, cvtest::norm(out_mat_gapi, out_mat_ocv, NORM_INF)); EXPECT_EQ(out_mat_gapi.size(), sz); }; // run for uninitialized output run_and_compare(); // run for initialized output (can be initialized with a different size) initOutMats(out_sz, type); run_and_compare(); } TEST_P(ParseSSDBLTest, ParseTest) { cv::Mat in_mat = generateSSDoutput(sz); std::vector boxes_gapi, boxes_ref; std::vector labels_gapi, labels_ref; // G-API code ////////////////////////////////////////////////////////////// cv::GMat in; cv::GOpaque op_sz; auto out = cv::gapi::parseSSD(in, op_sz, confidence_threshold, filter_label); cv::GComputation c(cv::GIn(in, op_sz), cv::GOut(std::get<0>(out), std::get<1>(out))); c.apply(cv::gin(in_mat, sz), cv::gout(boxes_gapi, labels_gapi), getCompileArgs()); // Reference code ////////////////////////////////////////////////////////// parseSSDBLref(in_mat, sz, confidence_threshold, filter_label, boxes_ref, labels_ref); // Comparison ////////////////////////////////////////////////////////////// EXPECT_TRUE(boxes_gapi == boxes_ref); EXPECT_TRUE(labels_gapi == labels_ref); } TEST_P(ParseSSDTest, ParseTest) { cv::Mat in_mat = generateSSDoutput(sz); std::vector boxes_gapi, boxes_ref; // G-API code ////////////////////////////////////////////////////////////// cv::GMat in; cv::GOpaque op_sz; auto out = cv::gapi::parseSSD(in, op_sz, confidence_threshold, alignment_to_square, filter_out_of_bounds); cv::GComputation c(cv::GIn(in, op_sz), cv::GOut(out)); c.apply(cv::gin(in_mat, sz), cv::gout(boxes_gapi), getCompileArgs()); // Reference code ////////////////////////////////////////////////////////// parseSSDref(in_mat, sz, confidence_threshold, alignment_to_square, filter_out_of_bounds, boxes_ref); // Comparison ////////////////////////////////////////////////////////////// EXPECT_TRUE(boxes_gapi == boxes_ref); } TEST_P(ParseYoloTest, ParseTest) { cv::Mat in_mat = generateYoloOutput(num_classes); auto anchors = cv::gapi::nn::parsers::GParseYolo::defaultAnchors(); std::vector boxes_gapi, boxes_ref; std::vector labels_gapi, labels_ref; // G-API code ////////////////////////////////////////////////////////////// cv::GMat in; cv::GOpaque op_sz; auto out = cv::gapi::parseYolo(in, op_sz, confidence_threshold, nms_threshold, anchors); cv::GComputation c(cv::GIn(in, op_sz), cv::GOut(std::get<0>(out), std::get<1>(out))); c.apply(cv::gin(in_mat, sz), cv::gout(boxes_gapi, labels_gapi), getCompileArgs()); // Reference code ////////////////////////////////////////////////////////// parseYoloRef(in_mat, sz, confidence_threshold, nms_threshold, num_classes, anchors, boxes_ref, labels_ref); // Comparison ////////////////////////////////////////////////////////////// EXPECT_TRUE(boxes_gapi == boxes_ref); EXPECT_TRUE(labels_gapi == labels_ref); } TEST_P(SizeTest, ParseTest) { cv::GMat in; cv::Size out_sz; auto out = cv::gapi::size(in); cv::GComputation c(cv::GIn(in), cv::GOut(out)); c.apply(cv::gin(in_mat1), cv::gout(out_sz), getCompileArgs()); EXPECT_EQ(out_sz, sz); } TEST_P(SizeRTest, ParseTest) { cv::Rect rect(cv::Point(0,0), sz); cv::Size out_sz; cv::GOpaque op_rect; auto out = cv::gapi::size(op_rect); cv::GComputation c(cv::GIn(op_rect), cv::GOut(out)); c.apply(cv::gin(rect), cv::gout(out_sz), getCompileArgs()); EXPECT_EQ(out_sz, sz); } } // opencv_test #endif //OPENCV_GAPI_CORE_TESTS_INL_HPP ",16300,True,3524.6779937368515,median "[[smpp-component]] = SMPP Component :page-source: components/camel-smpp/src/main/docs/smpp-component.adoc *Since Camel 2.2* // HEADER START *Both producer and consumer is supported* // HEADER END This component provides access to an SMSC (Short Message Service Center) over the http://smsforum.net/SMPP_v3_4_Issue1_2.zip[SMPP] protocol to send and receive SMS. The http://jsmpp.org[JSMPP] library is used for the protocol implementation. The Camel component currently operates as an http://en.wikipedia.org/wiki/ESME[ESME] (External Short Messaging Entity) and not as an SMSC itself. You are also able to execute ReplaceSm, QuerySm, SubmitMulti, CancelSm and DataSm. Maven users will need to add the following dependency to their `pom.xml` for this component: [source,xml] ------------------------------------------------------------ org.apache.camel camel-smpp x.x.x ------------------------------------------------------------ == SMS limitations SMS is neither reliable or secure. Users who require reliable and secure delivery may want to consider using the XMPP or SIP components instead, combined with a smartphone app supporting the chosen protocol. * Reliability: although the SMPP standard offers a range of feedback mechanisms to indicate errors, non-delivery and confirmation of delivery it is not uncommon for mobile networks to hide or simulate these responses. For example, some networks automatically send a delivery confirmation for every message even if the destination number is invalid or not switched on. Some networks silently drop messages if they think they are spam. Spam detection rules in the network may be very crude, sometimes more than 100 messages per day from a single sender may be considered spam. * Security: there is basic encryption for the last hop from the radio tower down to the recipient handset. SMS messages are not encrypted or authenticated in any other part of the network. Some operators allow staff in retail outlets or call centres to browse through the SMS message histories of their customers. Message sender identity can be easily forged. Regulators and even the mobile telephone industry itself has cautioned against the use of SMS in two-factor authentication schemes and other purposes where security is important. While the Camel component makes it as easy as possible to send messages to the SMS network, it can not offer an easy solution to these problems. == Data coding, alphabet and international character sets Data coding and alphabet can be specified on a per-message basis. Default values can be specified for the endpoint. It is important to understand the relationship between these options and the way the component acts when more than one value is set. Data coding is an 8 bit field in the SMPP wire format. Alphabet corresponds to bits 0-3 of the data coding field. For some types of message, where a message class is used (by setting bit 5 of the data coding field), the lower two bits of the data coding field are not interpreted as alphabet and only bits 2 and 3 impact the alphabet. Furthermore, current version of the JSMPP library only seems to support bits 2 and 3, assuming that bits 0 and 1 are used for message class. This is why the Alphabet class in JSMPP doesn't support the value 3 (binary 0011) which indicates ISO-8859-1. Although JSMPP provides a representation of the message class parameter, the Camel component doesn't currently provide a way to set it other than manually setting the corresponding bits in the data coding field. When setting the data coding field in the outgoing message, the Camel component considers the following values and uses the first one it can find: * the data coding specified in a header * the alphabet specified in a header * the data coding specified in the endpoint configuration (URI parameter) Older versions of Camel had bugs in support for international character sets. This feature only worked when a single encoding was used for all messages and was troublesome when users wanted to change it on a per-message basis. Users who require this to work should ensure their version of Camel includes the fix for JIRA Issues Macro: com.atlassian.sal.api.net.ResponseStatusException: Unexpected response received. Status code: 404 . In addition to trying to send the data coding value to the SMSC, the Camel component also tries to analyze the message body, convert it to a Java String (Unicode) and convert that to a byte array in the corresponding alphabet When deciding which alphabet to use in the byte array, the Camel SMPP component does not consider the data coding value (header or configuration), it only considers the specified alphabet (from either the header or endpoint parameter). If some characters in the String can't be represented in the chosen alphabet, they may be replaced by the question mark ( ? ) symbol. Users of the API may want to consider checking if their message body can be converted to ISO-8859-1 before passing it to the component and if not, setting the alphabet header to request UCS-2 encoding. If the alphabet and data coding options are not specified at all then the component may try to detect the required encoding and set the data coding for you. The list of alphabet codes are specified in the SMPP specification v3.4, section 5.2.19. One notable limitation of the SMPP specification is that there is no alphabet code for explicitly requesting use of the GSM 3.38 (7 bit) character set. Choosing the value 0 for the alphabet selects the SMSC _default_ alphabet, this usually means GSM 3.38 but it is not guaranteed. The SMPP gateway Nexmo https://help.nexmo.com/hc/en-us/articles/204015813-How-to-change-the-character-encoding-in-SMPP-[actually allows the default to be mapped to any other character set with a control panel option]. It is suggested that users check with their SMSC operator to confirm exactly which character set is being used as the default. == Message splitting and throttling After transforming a message body from a String to a byte array, the Camel component is also responsible for splitting the message into parts (within the 140 byte SMS size limit) before passing it to JSMPP. This is completed automatically. If the GSM 3.38 alphabet is used, the component will pack up to 160 characters into the 140 byte message body. If an 8 bit character set is used (e.g. ISO-8859-1 for western Europe) then 140 characters will be allowed within the 140 byte message body. If 16 bit UCS-2 encoding is used then just 70 characters fit into each 140 byte message. Some SMSC providers implement throttling rules. Each part of a message that has been split may be counted separately by the provider's throttling mechanism. The Camel Throttler component can be useful for throttling messages in the SMPP route before handing them to the SMSC. == URI format [source,java] -------------------------------------------- smpp://[username@]hostname[:port][?options] smpps://[username@]hostname[:port][?options] -------------------------------------------- If no *username* is provided, then Camel will provide the default value `smppclient`. + If no *port* number is provided, then Camel will provide the default value `2775`. + If the protocol name is ""smpps"", camel-smpp with try to use SSLSocket to init a connection to the server. You can append query options to the URI in the following format, `?option=value&option=value&...` == URI Options // component options: START The SMPP component supports 4 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *configuration* (advanced) | To use the shared SmppConfiguration as configuration. | | SmppConfiguration | *basicPropertyBinding* (advanced) | Whether the component should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities | false | boolean | *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 | *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 |=== // component options: END // endpoint options: START The SMPP endpoint is configured using URI syntax: ---- smpp:host:port ---- with the following path and query parameters: === Path Parameters (2 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *host* | Hostname for the SMSC server to use. | localhost | String | *port* | Port number for the SMSC server to use. | 2775 | Integer |=== === Query Parameters (40 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *initialReconnectDelay* (common) | Defines the initial delay in milliseconds after the consumer/producer tries to reconnect to the SMSC, after the connection was lost. | 5000 | long | *maxReconnect* (common) | Defines the maximum number of attempts to reconnect to the SMSC, if SMSC returns a negative bind response | 2147483647 | int | *reconnectDelay* (common) | Defines the interval in milliseconds between the reconnect attempts, if the connection to the SMSC was lost and the previous was not succeed. | 5000 | long | *splittingPolicy* (common) | You can specify a policy for handling long messages: ALLOW - the default, long messages are split to 140 bytes per message TRUNCATE - long messages are split and only the first fragment will be sent to the SMSC. Some carriers drop subsequent fragments so this reduces load on the SMPP connection sending parts of a message that will never be delivered. REJECT - if a message would need to be split, it is rejected with an SMPP NegativeResponseException and the reason code signifying the message is too long. | ALLOW | SmppSplittingPolicy | *systemType* (common) | This parameter is used to categorize the type of ESME (External Short Message Entity) that is binding to the SMSC (max. 13 characters). | | String | *addressRange* (consumer) | You can specify the address range for the SmppConsumer as defined in section 5.2.7 of the SMPP 3.4 specification. The SmppConsumer will receive messages only from SMSC's which target an address (MSISDN or IP address) within this range. | | String | *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 | *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 | *destAddr* (producer) | Defines the destination SME address. For mobile terminated messages, this is the directory number of the recipient MS. Only for SubmitSm, SubmitMulti, CancelSm and DataSm. | 1717 | String | *destAddrNpi* (producer) | Defines the type of number (TON) to be used in the SME destination address parameters. Only for SubmitSm, SubmitMulti, CancelSm and DataSm. The following NPI values are defined: 0: Unknown 1: ISDN (E163/E164) 2: Data (X.121) 3: Telex (F.69) 6: Land Mobile (E.212) 8: National 9: Private 10: ERMES 13: Internet (IP) 18: WAP Client Id (to be defined by WAP Forum) | | byte | *destAddrTon* (producer) | Defines the type of number (TON) to be used in the SME destination address parameters. Only for SubmitSm, SubmitMulti, CancelSm and DataSm. The following TON values are defined: 0: Unknown 1: International 2: National 3: Network Specific 4: Subscriber Number 5: Alphanumeric 6: Abbreviated | | byte | *lazySessionCreation* (producer) | Sessions can be lazily created to avoid exceptions, if the SMSC is not available when the Camel producer is started. Camel will check the in message headers 'CamelSmppSystemId' and 'CamelSmppPassword' of the first exchange. If they are present, Camel will use these data to connect to the SMSC. | false | boolean | *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 | *numberingPlanIndicator* (producer) | Defines the numeric plan indicator (NPI) to be used in the SME. The following NPI values are defined: 0: Unknown 1: ISDN (E163/E164) 2: Data (X.121) 3: Telex (F.69) 6: Land Mobile (E.212) 8: National 9: Private 10: ERMES 13: Internet (IP) 18: WAP Client Id (to be defined by WAP Forum) | | byte | *priorityFlag* (producer) | Allows the originating SME to assign a priority level to the short message. Only for SubmitSm and SubmitMulti. Four Priority Levels are supported: 0: Level 0 (lowest) priority 1: Level 1 priority 2: Level 2 priority 3: Level 3 (highest) priority | | byte | *protocolId* (producer) | The protocol id | | byte | *registeredDelivery* (producer) | Is used to request an SMSC delivery receipt and/or SME originated acknowledgements. The following values are defined: 0: No SMSC delivery receipt requested. 1: SMSC delivery receipt requested where final delivery outcome is success or failure. 2: SMSC delivery receipt requested where the final delivery outcome is delivery failure. | | byte | *replaceIfPresentFlag* (producer) | Used to request the SMSC to replace a previously submitted message, that is still pending delivery. The SMSC will replace an existing message provided that the source address, destination address and service type match the same fields in the new message. The following replace if present flag values are defined: 0: Don't replace 1: Replace | | byte | *serviceType* (producer) | The service type parameter can be used to indicate the SMS Application service associated with the message. The following generic service_types are defined: CMT: Cellular Messaging CPT: Cellular Paging VMN: Voice Mail Notification VMA: Voice Mail Alerting WAP: Wireless Application Protocol USSD: Unstructured Supplementary Services Data | | String | *sourceAddr* (producer) | Defines the address of SME (Short Message Entity) which originated this message. | 1616 | String | *sourceAddrNpi* (producer) | Defines the numeric plan indicator (NPI) to be used in the SME originator address parameters. The following NPI values are defined: 0: Unknown 1: ISDN (E163/E164) 2: Data (X.121) 3: Telex (F.69) 6: Land Mobile (E.212) 8: National 9: Private 10: ERMES 13: Internet (IP) 18: WAP Client Id (to be defined by WAP Forum) | | byte | *sourceAddrTon* (producer) | Defines the type of number (TON) to be used in the SME originator address parameters. The following TON values are defined: 0: Unknown 1: International 2: National 3: Network Specific 4: Subscriber Number 5: Alphanumeric 6: Abbreviated | | byte | *typeOfNumber* (producer) | Defines the type of number (TON) to be used in the SME. The following TON values are defined: 0: Unknown 1: International 2: National 3: Network Specific 4: Subscriber Number 5: Alphanumeric 6: Abbreviated | | byte | *basicPropertyBinding* (advanced) | Whether the endpoint should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities | false | boolean | *enquireLinkTimer* (advanced) | Defines the interval in milliseconds between the confidence checks. The confidence check is used to test the communication path between an ESME and an SMSC. | 5000 | Integer | *sessionStateListener* (advanced) | You can refer to a org.jsmpp.session.SessionStateListener in the Registry to receive callbacks when the session state changed. | | SessionStateListener | *synchronous* (advanced) | Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported). | false | boolean | *transactionTimer* (advanced) | Defines the maximum period of inactivity allowed after a transaction, after which an SMPP entity may assume that the session is no longer active. This timer may be active on either communicating SMPP entity (i.e. SMSC or ESME). | 10000 | Integer | *alphabet* (codec) | Defines encoding of data according the SMPP 3.4 specification, section 5.2.19. 0: SMSC Default Alphabet 4: 8 bit Alphabet 8: UCS2 Alphabet | | byte | *dataCoding* (codec) | Defines the data coding according the SMPP 3.4 specification, section 5.2.19. Example data encodings are: 0: SMSC Default Alphabet 3: Latin 1 (ISO-8859-1) 4: Octet unspecified (8-bit binary) 8: UCS2 (ISO/IEC-10646) 13: Extended Kanji JIS(X 0212-1990) | | byte | *encoding* (codec) | Defines the encoding scheme of the short message user data. Only for SubmitSm, ReplaceSm and SubmitMulti. | ISO-8859-1 | String | *httpProxyHost* (proxy) | If you need to tunnel SMPP through a HTTP proxy, set this attribute to the hostname or ip address of your HTTP proxy. | | String | *httpProxyPassword* (proxy) | If your HTTP proxy requires basic authentication, set this attribute to the password required for your HTTP proxy. | | String | *httpProxyPort* (proxy) | If you need to tunnel SMPP through a HTTP proxy, set this attribute to the port of your HTTP proxy. | 3128 | Integer | *httpProxyUsername* (proxy) | If your HTTP proxy requires basic authentication, set this attribute to the username required for your HTTP proxy. | | String | *proxyHeaders* (proxy) | These headers will be passed to the proxy server while establishing the connection. | | Map | *password* (security) | The password for connecting to SMSC server. | | String | *systemId* (security) | The system id (username) for connecting to SMSC server. | smppclient | String | *usingSSL* (security) | Whether using SSL with the smpps protocol | 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.springboot camel-smpp-starter x.x.x ---- The component supports 40 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *camel.component.smpp.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.smpp.bridge-error-handler* | 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 | *camel.component.smpp.configuration.address-range* | You can specify the address range for the SmppConsumer as defined in section 5.2.7 of the SMPP 3.4 specification. The SmppConsumer will receive messages only from SMSC's which target an address (MSISDN or IP address) within this range. | | String | *camel.component.smpp.configuration.alphabet* | Defines encoding of data according the SMPP 3.4 specification, section 5.2.19.
  • 0: SMSC Default Alphabet
  • 4: 8 bit Alphabet
  • 8: UCS2 Alphabet
| | Byte | *camel.component.smpp.configuration.data-coding* | Defines the data coding according the SMPP 3.4 specification, section 5.2.19. Example data encodings are:
  • 0: SMSC Default Alphabet
  • 3: Latin 1 (ISO-8859-1)
  • 4: Octet unspecified (8-bit binary)
  • 8: UCS2 (ISO/IEC-10646)
  • 13: Extended Kanji JIS(X 0212-1990)
| | Byte | *camel.component.smpp.configuration.dest-addr* | Defines the destination SME address. For mobile terminated messages, this is the directory number of the recipient MS. Only for SubmitSm, SubmitMulti, CancelSm and DataSm. | 1717 | String | *camel.component.smpp.configuration.dest-addr-npi* | Defines the type of number (TON) to be used in the SME destination address parameters. Only for SubmitSm, SubmitMulti, CancelSm and DataSm. The following NPI values are defined:
  • 0: Unknown
  • 1: ISDN (E163/E164)
  • 2: Data (X.121)
  • 3: Telex (F.69)
  • 6: Land Mobile (E.212)
  • 8: National
  • 9: Private
  • 10: ERMES
  • 13: Internet (IP)
  • 18: WAP Client Id (to be defined by WAP Forum)
| | Byte | *camel.component.smpp.configuration.dest-addr-ton* | Defines the type of number (TON) to be used in the SME destination address parameters. Only for SubmitSm, SubmitMulti, CancelSm and DataSm. The following TON values are defined:
  • 0: Unknown
  • 1: International
  • 2: National
  • 3: Network Specific
  • 4: Subscriber Number
  • 5: Alphanumeric
  • 6: Abbreviated
| | Byte | *camel.component.smpp.configuration.encoding* | Defines the encoding scheme of the short message user data. Only for SubmitSm, ReplaceSm and SubmitMulti. | ISO-8859-1 | String | *camel.component.smpp.configuration.enquire-link-timer* | Defines the interval in milliseconds between the confidence checks. The confidence check is used to test the communication path between an ESME and an SMSC. | 5000 | Integer | *camel.component.smpp.configuration.host* | Hostname for the SMSC server to use. | localhost | String | *camel.component.smpp.configuration.http-proxy-host* | If you need to tunnel SMPP through a HTTP proxy, set this attribute to the hostname or ip address of your HTTP proxy. | | String | *camel.component.smpp.configuration.http-proxy-password* | If your HTTP proxy requires basic authentication, set this attribute to the password required for your HTTP proxy. | | String | *camel.component.smpp.configuration.http-proxy-port* | If you need to tunnel SMPP through a HTTP proxy, set this attribute to the port of your HTTP proxy. | 3128 | Integer | *camel.component.smpp.configuration.http-proxy-username* | If your HTTP proxy requires basic authentication, set this attribute to the username required for your HTTP proxy. | | String | *camel.component.smpp.configuration.initial-reconnect-delay* | Defines the initial delay in milliseconds after the consumer/producer tries to reconnect to the SMSC, after the connection was lost. | 5000 | Long | *camel.component.smpp.configuration.lazy-session-creation* | Sessions can be lazily created to avoid exceptions, if the SMSC is not available when the Camel producer is started. Camel will check the in message headers 'CamelSmppSystemId' and 'CamelSmppPassword' of the first exchange. If they are present, Camel will use these data to connect to the SMSC. | false | Boolean | *camel.component.smpp.configuration.max-reconnect* | Defines the maximum number of attempts to reconnect to the SMSC, if SMSC returns a negative bind response | 2147483647 | Integer | *camel.component.smpp.configuration.numbering-plan-indicator* | Defines the numeric plan indicator (NPI) to be used in the SME. The following NPI values are defined:
  • 0: Unknown
  • 1: ISDN (E163/E164)
  • 2: Data (X.121)
  • 3: Telex (F.69)
  • 6: Land Mobile (E.212)
  • 8: National
  • 9: Private
  • 10: ERMES
  • 13: Internet (IP)
  • 18: WAP Client Id (to be defined by WAP Forum)
| | Byte | *camel.component.smpp.configuration.password* | Defines the encoding scheme of the short message user data. Only for SubmitSm, ReplaceSm and SubmitMulti. | | String | *camel.component.smpp.configuration.port* | Port number for the SMSC server to use. | 2775 | Integer | *camel.component.smpp.configuration.priority-flag* | Allows the originating SME to assign a priority level to the short message. Only for SubmitSm and SubmitMulti. Four Priority Levels are supported:
  • 0: Level 0 (lowest) priority
  • 1: Level 1 priority
  • 2: Level 2 priority
  • 3: Level 3 (highest) priority
| | Byte | *camel.component.smpp.configuration.protocol-id* | The protocol id | | Byte | *camel.component.smpp.configuration.proxy-headers* | These headers will be passed to the proxy server while establishing the connection. | | Map | *camel.component.smpp.configuration.reconnect-delay* | Defines the interval in milliseconds between the reconnect attempts, if the connection to the SMSC was lost and the previous was not succeed. | 5000 | Long | *camel.component.smpp.configuration.registered-delivery* | Is used to request an SMSC delivery receipt and/or SME originated acknowledgements. The following values are defined:
  • 0: No SMSC delivery receipt requested.
  • 1: SMSC delivery receipt requested where final delivery outcome is success or failure.
  • 2: SMSC delivery receipt requested where the final delivery outcome is delivery failure.
| | Byte | *camel.component.smpp.configuration.replace-if-present-flag* | Used to request the SMSC to replace a previously submitted message, that is still pending delivery. The SMSC will replace an existing message provided that the source address, destination address and service type match the same fields in the new message. The following replace if present flag values are defined:
  • 0: Don't replace
  • 1: Replace
| | Byte | *camel.component.smpp.configuration.service-type* | The service type parameter can be used to indicate the SMS Application service associated with the message. The following generic service_types are defined:
  • CMT: Cellular Messaging
  • CPT: Cellular Paging
  • VMN: Voice Mail Notification
  • VMA: Voice Mail Alerting
  • WAP: Wireless Application Protocol
  • USSD: Unstructured Supplementary Services Data
| | String | *camel.component.smpp.configuration.session-state-listener* | You can refer to a org.jsmpp.session.SessionStateListener in the Registry to receive callbacks when the session state changed. | | SessionStateListener | *camel.component.smpp.configuration.source-addr* | Defines the address of SME (Short Message Entity) which originated this message. | 1616 | String | *camel.component.smpp.configuration.source-addr-npi* | Defines the numeric plan indicator (NPI) to be used in the SME originator address parameters. The following NPI values are defined:
  • 0: Unknown
  • 1: ISDN (E163/E164)
  • 2: Data (X.121)
  • 3: Telex (F.69)
  • 6: Land Mobile (E.212)
  • 8: National
  • 9: Private
  • 10: ERMES
  • 13: Internet (IP)
  • 18: WAP Client Id (to be defined by WAP Forum)
| | Byte | *camel.component.smpp.configuration.source-addr-ton* | Defines the type of number (TON) to be used in the SME originator address parameters. The following TON values are defined:
  • 0: Unknown
  • 1: International
  • 2: National
  • 3: Network Specific
  • 4: Subscriber Number
  • 5: Alphanumeric
  • 6: Abbreviated
| | Byte | *camel.component.smpp.configuration.splitting-policy* | You can specify a policy for handling long messages:
  • ALLOW - the default, long messages are split to 140 bytes per message
  • TRUNCATE - long messages are split and only the first fragment will be sent to the SMSC. Some carriers drop subsequent fragments so this reduces load on the SMPP connection sending parts of a message that will never be delivered.
  • REJECT - if a message would need to be split, it is rejected with an SMPP NegativeResponseException and the reason code signifying the message is too long.
| | SmppSplittingPolicy | *camel.component.smpp.configuration.system-id* | The system id (username) for connecting to SMSC server. | smppclient | String | *camel.component.smpp.configuration.system-type* | This parameter is used to categorize the type of ESME (External Short Message Entity) that is binding to the SMSC (max. 13 characters). | | String | *camel.component.smpp.configuration.transaction-timer* | Defines the maximum period of inactivity allowed after a transaction, after which an SMPP entity may assume that the session is no longer active. This timer may be active on either communicating SMPP entity (i.e. SMSC or ESME). | 10000 | Integer | *camel.component.smpp.configuration.type-of-number* | Defines the type of number (TON) to be used in the SME. The following TON values are defined:
  • 0: Unknown
  • 1: International
  • 2: National
  • 3: Network Specific
  • 4: Subscriber Number
  • 5: Alphanumeric
  • 6: Abbreviated
| | Byte | *camel.component.smpp.configuration.using-s-s-l* | Whether using SSL with the smpps protocol | false | Boolean | *camel.component.smpp.enabled* | Whether to enable auto configuration of the smpp component. This is enabled by default. | | Boolean | *camel.component.smpp.lazy-start-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 |=== // spring-boot-auto-configure options: END You can have as many of these options as you like. [source,java] ------------------------------------------------------------------------------------------------------------------ smpp://smppclient@localhost:2775?password=password&enquireLinkTimer=3000&transactionTimer=5000&systemType=consumer ------------------------------------------------------------------------------------------------------------------ == Producer Message Headers The following message headers can be used to affect the behavior of the SMPP producer [width=""100%"",cols=""10%,10%,80%"",options=""header"",] |======================================================================= |Header |Type |Description |`CamelSmppDestAddr` |`List`/`String` |*only for SubmitSm, SubmitMulti, CancelSm and DataSm* Defines the destination SME address(es). For mobile terminated messages, this is the directory number of the recipient MS. Is must be a `List` for SubmitMulti and a `String` otherwise. |`CamelSmppDestAddrTon` |`Byte` |*only for SubmitSm, SubmitMulti, CancelSm and DataSm* Defines the type of number (TON) to be used in the SME destination address parameters. Use the `sourceAddrTon` URI option values defined above. |`CamelSmppDestAddrNpi` |`Byte` |*only for SubmitSm, SubmitMulti, CancelSm and DataSm* Defines the numeric plan indicator (NPI) to be used in the SME destination address parameters. Use the URI option `sourceAddrNpi` values defined above. |`CamelSmppSourceAddr` |`String` |Defines the address of SME (Short Message Entity) which originated this message. |`CamelSmppSourceAddrTon` |`Byte` |Defines the type of number (TON) to be used in the SME originator address parameters. Use the `sourceAddrTon` URI option values defined above. |`CamelSmppSourceAddrNpi` |`Byte` |Defines the numeric plan indicator (NPI) to be used in the SME originator address parameters. Use the URI option `sourceAddrNpi` values defined above. |`CamelSmppServiceType` |`String` |The service type parameter can be used to indicate the SMS Application service associated with the message. Use the URI option `serviceType` settings above. |`CamelSmppRegisteredDelivery` |`Byte` |*only for SubmitSm, ReplaceSm, SubmitMulti and DataSm* Is used to request an SMSC delivery receipt and/or SME originated acknowledgements. Use the URI option `registeredDelivery` settings above. |`CamelSmppPriorityFlag` |`Byte` |*only for SubmitSm and SubmitMulti* Allows the originating SME to assign a priority level to the short message. Use the URI option `priorityFlag` settings above. |`CamelSmppScheduleDeliveryTime` |`Date` |*only for SubmitSm, SubmitMulti and ReplaceSm* This parameter specifies the scheduled time at which the message delivery should be first attempted. It defines either the absolute date and time or relative time from the current SMSC time at which delivery of this message will be attempted by the SMSC. It can be specified in either absolute time format or relative time format. The encoding of a time format is specified in chapter 7.1.1. in the smpp specification v3.4. |`CamelSmppValidityPeriod` |`String`/`Date` |*only for SubmitSm, SubmitMulti and ReplaceSm* The validity period parameter indicates the SMSC expiration time, after which the message should be discarded if not delivered to the destination. If it's provided as `Date`, it's interpreted as absolute time or relative time format if you provide it as `String` as specified in chapter 7.1.1 in the smpp specification v3.4. |`CamelSmppReplaceIfPresentFlag` |`Byte` |*only for SubmitSm and SubmitMulti* The replace if present flag parameter is used to request the SMSC to replace a previously submitted message, that is still pending delivery. The SMSC will replace an existing message provided that the source address, destination address and service type match the same fields in the new message. The following values are defined: `0`, Don't replace and `1`, Replace |`CamelSmppAlphabet` / `CamelSmppDataCoding` |`Byte` |*For SubmitSm, SubmitMulti and ReplaceSm* The data coding according to the SMPP 3.4 specification, section 5.2.19. Use the URI option `alphabet` settings above. |`CamelSmppOptionalParameter` |`Map` |*only for SubmitSm, SubmitMulti and DataSm* The optional parameter which are send to the SMSC. The value is converted in the following way: `String` -> `org.jsmpp.bean.OptionalParameter.COctetString`, `byte[]` -> `org.jsmpp.bean.OptionalParameter.OctetString`, `Byte` -> `org.jsmpp.bean.OptionalParameter.Byte`, `Integer` -> `org.jsmpp.bean.OptionalParameter.Int`, `Short` -> `org.jsmpp.bean.OptionalParameter.Short`, `null` -> `org.jsmpp.bean.OptionalParameter.Null` |CamelSmppEncoding |String |*only for SubmitSm, SubmitMulti and DataSm*. Specifies the encoding (character set name) of the bytes in the message body. If the message body is a string then this is not relevant because Java Strings are always Unicode. If the body is a byte array then this header can be used to indicate that it is ISO-8859-1 or some other value. Default value is specified by the endpoint configuration parameter _encoding_ |CamelSmppSplittingPolicy |String |*only for SubmitSm, SubmitMulti and DataSm*. Specifies the policy for message splitting for this exchange. Possible values are described in the endpoint configuration parameter _splittingPolicy_ |======================================================================= The following message headers are used by the SMPP producer to set the response from the SMSC in the message header [width=""100%"",cols=""10%,10%,80%"",options=""header"",] |======================================================================= |Header |Type |Description |`CamelSmppId` |`List`/`String` |The id to identify the submitted short message(s) for later use. In case of a ReplaceSm, QuerySm, CancelSm and DataSm this header vaule is a `String`. In case of a SubmitSm or SubmitMultiSm this header vaule is a `List`. |`CamelSmppSentMessageCount` |`Integer` |*only for SubmitSm and SubmitMultiSm* The total number of messages which has been sent. |`CamelSmppError` |`Map>>` |*only for SubmitMultiSm* The errors which occurred by sending the short message(s) the form `Map>>` (messageID : (destAddr : address, error : errorCode)). |`CamelSmppOptionalParameter` |`Map` |*only for DataSm* The optional parameter which are returned from the SMSC by sending the message. The key is the `Short` code for the optional parameter. The value is converted in the following way: `org.jsmpp.bean.OptionalParameter.COctetString` -> `String`, `org.jsmpp.bean.OptionalParameter.OctetString` -> `byte[]`, `org.jsmpp.bean.OptionalParameter.Byte` -> `Byte`, `org.jsmpp.bean.OptionalParameter.Int` -> `Integer`, `org.jsmpp.bean.OptionalParameter.Short` -> `Short`, `org.jsmpp.bean.OptionalParameter.Null` -> `null` |======================================================================= == Consumer Message Headers The following message headers are used by the SMPP consumer to set the request data from the SMSC in the message header [width=""100%"",cols=""10%,10%,80%"",options=""header"",] |======================================================================= |Header |Type |Description |`CamelSmppSequenceNumber` |`Integer` |*only for AlertNotification, DeliverSm and DataSm* A sequence number allows a response PDU to be correlated with a request PDU. The associated SMPP response PDU must preserve this field. |`CamelSmppCommandId` |`Integer` |*only for AlertNotification, DeliverSm and DataSm* The command id field identifies the particular SMPP PDU. For the complete list of defined values see chapter 5.1.2.1 in the smpp specification v3.4. |`CamelSmppSourceAddr` |`String` |*only for AlertNotification, DeliverSm and DataSm* Defines the address of SME (Short Message Entity) which originated this message. |`CamelSmppSourceAddrNpi` |`Byte` |*only for AlertNotification and DataSm* Defines the numeric plan indicator (NPI) to be used in the SME originator address parameters. Use the URI option `sourceAddrNpi` values defined above. |`CamelSmppSourceAddrTon` |`Byte` |*only for AlertNotification and DataSm* Defines the type of number (TON) to be used in the SME originator address parameters. Use the `sourceAddrTon` URI option values defined above. |`CamelSmppEsmeAddr` |`String` |*only for AlertNotification* Defines the destination ESME address. For mobile terminated messages, this is the directory number of the recipient MS. |`CamelSmppEsmeAddrNpi` |`Byte` |*only for AlertNotification* Defines the numeric plan indicator (NPI) to be used in the ESME originator address parameters. Use the URI option `sourceAddrNpi` values defined above. |`CamelSmppEsmeAddrTon` |`Byte` |*only for AlertNotification* Defines the type of number (TON) to be used in the ESME originator address parameters. Use the `sourceAddrTon` URI option values defined above. |`CamelSmppId` |`String` |*only for smsc DeliveryReceipt and DataSm* The message ID allocated to the message by the SMSC when originally submitted. |`CamelSmppDelivered` |`Integer` |*only for smsc DeliveryReceipt* Number of short messages delivered. This is only relevant where the original message was submitted to a distribution list.The value is padded with leading zeros if necessary. |`CamelSmppDoneDate` |`Date` |*only for smsc DeliveryReceipt* The time and date at which the short message reached it's final state. The format is as follows: YYMMDDhhmm. |`CamelSmppStatus` |`DeliveryReceiptState` |*only for smsc DeliveryReceipt:* The final status of the message. The following values are defined: `DELIVRD`: Message is delivered to destination, `EXPIRED`: Message validity period has expired, `DELETED`: Message has been deleted, `UNDELIV`: Message is undeliverable, `ACCEPTD`: Message is in accepted state (i.e. has been manually read on behalf of the subscriber by customer service), `UNKNOWN`: Message is in invalid state, `REJECTD`: Message is in a rejected state |`CamelSmppCommandStatus` |`Integer` |*only for DataSm* The Command status of the message. |`CamelSmppError` |`String` |*only for smsc DeliveryReceipt* Where appropriate this may hold a Network specific error code or an SMSC error code for the attempted delivery of the message. These errors are Network or SMSC specific and are not included here. |`CamelSmppSubmitDate` |`Date` |*only for smsc DeliveryReceipt* The time and date at which the short message was submitted. In the case of a message which has been replaced, this is the date that the original message was replaced. The format is as follows: YYMMDDhhmm. |`CamelSmppSubmitted` |`Integer` |*only for smsc DeliveryReceipt* Number of short messages originally submitted. This is only relevant when the original message was submitted to a distribution list.The value is padded with leading zeros if necessary. |`CamelSmppDestAddr` |`String` |*only for DeliverSm and DataSm:* Defines the destination SME address. For mobile terminated messages, this is the directory number of the recipient MS. |`CamelSmppScheduleDeliveryTime` |`String` |*only for DeliverSm:* This parameter specifies the scheduled time at which the message delivery should be first attempted. It defines either the absolute date and time or relative time from the current SMSC time at which delivery of this message will be attempted by the SMSC. It can be specified in either absolute time format or relative time format. The encoding of a time format is specified in Section 7.1.1. in the smpp specification v3.4. |`CamelSmppValidityPeriod` |`String` |*only for DeliverSm* The validity period parameter indicates the SMSC expiration time, after which the message should be discarded if not delivered to the destination. It can be defined in absolute time format or relative time format. The encoding of absolute and relative time format is specified in Section 7.1.1 in the smpp specification v3.4. |`CamelSmppServiceType` |`String` |*only for DeliverSm and DataSm* The service type parameter indicates the SMS Application service associated with the message. |`CamelSmppRegisteredDelivery` |`Byte` |*only for DataSm* Is used to request an delivery receipt and/or SME originated acknowledgements. Same values as in Producer header list above. |`CamelSmppDestAddrNpi` |`Byte` |*only for DataSm* Defines the numeric plan indicator (NPI) in the destination address parameters. Use the URI option `sourceAddrNpi` values defined above. |`CamelSmppDestAddrTon` |`Byte` |*only for DataSm* Defines the type of number (TON) in the destination address parameters. Use the `sourceAddrTon` URI option values defined above. |`CamelSmppMessageType` |`String` |Identifies the type of an incoming message: `AlertNotification`: an SMSC alert notification, `DataSm`: an SMSC data short message, `DeliveryReceipt`: an SMSC delivery receipt, `DeliverSm`: an SMSC deliver short message |`CamelSmppOptionalParameter` |`Map` |*only for DeliverSm* The optional parameters send back by the SMSC. The key is the `Short` code for the optional parameter. The value is converted in the following way: `org.jsmpp.bean.OptionalParameter.COctetString` -> `String`, `org.jsmpp.bean.OptionalParameter.OctetString` -> `byte[]`, `org.jsmpp.bean.OptionalParameter.Byte` -> `Byte`, `org.jsmpp.bean.OptionalParameter.Int` -> `Integer`, `org.jsmpp.bean.OptionalParameter.Short` -> `Short`, `org.jsmpp.bean.OptionalParameter.Null` -> `null` |======================================================================= [TIP] ==== *JSMPP library* See the documentation of the http://jsmpp.org[JSMPP Library] for more details about the underlying library. ==== == Exception handling This component supports the general Camel exception handling capabilities When an error occurs sending a message with SubmitSm (the default action), the org.apache.camel.component.smpp.SmppException is thrown with a nested exception, org.jsmpp.extra.NegativeResponseException. Call NegativeResponseException.getCommandStatus() to obtain the exact SMPP negative response code, the values are explained in the SMPP specification 3.4, section 5.1.3. + When the SMPP consumer receives a `DeliverSm` or `DataSm` short message and the processing of these messages fails, you can also throw a `ProcessRequestException` instead of handle the failure. In this case, this exception is forwarded to the underlying http://jsmpp.org[JSMPP library] which will return the included error code to the SMSC. This feature is useful to e.g. instruct the SMSC to resend the short message at a later time. This could be done with the following lines of code: [source,java] -------------------------------------------------------------------------------------------------------------------------- from(""smpp://smppclient@localhost:2775?password=password&enquireLinkTimer=3000&transactionTimer=5000&systemType=consumer"") .doTry() .to(""bean:dao?method=updateSmsState"") .doCatch(Exception.class) .throwException(new ProcessRequestException(""update of sms state failed"", 100)) .end(); -------------------------------------------------------------------------------------------------------------------------- Please refer to the http://smsforum.net/SMPP_v3_4_Issue1_2.zip[SMPP specification] for the complete list of error codes and their meanings. == Samples A route which sends an SMS using the Java DSL: [source,java] ------------------------------------------------------------------------------------------ from(""direct:start"") .to(""smpp://smppclient@localhost:2775? password=password&enquireLinkTimer=3000&transactionTimer=5000&systemType=producer""); ------------------------------------------------------------------------------------------ A route which sends an SMS using the Spring XML DSL: [source,xml] ----------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------- A route which receives an SMS using the Java DSL: [source,java] -------------------------------------------------------------------------------------------------------------------------- from(""smpp://smppclient@localhost:2775?password=password&enquireLinkTimer=3000&transactionTimer=5000&systemType=consumer"") .to(""bean:foo""); -------------------------------------------------------------------------------------------------------------------------- A route which receives an SMS using the Spring XML DSL: [source,xml] ---------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------- [TIP] ==== *SMSC simulator* If you need an SMSC simulator for your test, you can use the simulator provided by http://opensmpp.logica.com/CommonPart/Download/download2.html#simulator[Logica]. ==== == Debug logging This component has log level *DEBUG*, which can be helpful in debugging problems. If you use log4j, you can add the following line to your configuration: [source,java] -------------------------------------------------- log4j.logger.org.apache.camel.component.smpp=DEBUG -------------------------------------------------- ",12146,False,2371.691101829221,median "#include ""Platform.h"" #include ""kext_inject.h"" #include ""DataHubCpu.h"" #ifndef DEBUG_ALL #define KEXT_INJECT_DEBUG 0 #else #define KEXT_INJECT_DEBUG DEBUG_ALL #endif #if KEXT_INJECT_DEBUG == 2 #define DBG(...) MsgLog(__VA_ARGS__) #elif KEXT_INJECT_DEBUG == 1 #define DBG(...) printf(__VA_ARGS__); #else #define DBG(...) #endif // runtime debug // #define OLD_EXTRA_KEXT_PATCH 0 //////////////////// // globals //////////////////// LIST_ENTRY gKextList = INITIALIZE_LIST_HEAD_VARIABLE (gKextList); //////////////////// // before booting //////////////////// EFI_STATUS EFIAPI ThinFatFile(IN OUT UINT8 **binary, IN OUT UINTN *length, IN cpu_type_t archCpuType) { UINT32 nfat, swapped, size = 0; FAT_HEADER *fhp = (FAT_HEADER *)*binary; FAT_ARCH *fap = (FAT_ARCH *)(*binary + sizeof(FAT_HEADER)); cpu_type_t fapcputype; UINT32 fapoffset; UINT32 fapsize; swapped = 0; if (fhp->magic == FAT_MAGIC) { nfat = fhp->nfat_arch; } else if (fhp->magic == FAT_CIGAM) { nfat = SwapBytes32(fhp->nfat_arch); swapped = 1; //already thin } else if (fhp->magic == THIN_X64){ if (archCpuType == CPU_TYPE_X86_64) { return EFI_SUCCESS; } return EFI_NOT_FOUND; } else if (fhp->magic == THIN_IA32){ if (archCpuType == CPU_TYPE_I386) { return EFI_SUCCESS; } return EFI_NOT_FOUND; } else { MsgLog(""Thinning fails\\n""); return EFI_NOT_FOUND; } for (; nfat > 0; nfat--, fap++) { if (swapped) { fapcputype = SwapBytes32(fap->cputype); fapoffset = SwapBytes32(fap->offset); fapsize = SwapBytes32(fap->size); } else { fapcputype = fap->cputype; fapoffset = fap->offset; fapsize = fap->size; } if (fapcputype == archCpuType) { *binary = (*binary + fapoffset); size = fapsize; break; } } if (length != 0) *length = size; return EFI_SUCCESS; } void toLowerStr(CHAR8 *tstr, CHAR8 *str) { UINT16 cnt = 0; for (cnt = 0; *str != '\\0' && cnt <= 0xFF; cnt++, str++, tstr++) { if (*str >= 'A' && *str <= 'Z') *tstr = 'a' + (*str - 'A'); else *tstr = *str; } *tstr = '\\0'; } BOOLEAN checkOSBundleRequired(UINT8 loaderType, TagPtr dict) { BOOLEAN inject = TRUE; TagPtr osBundleRequired; CHAR8 osbundlerequired[256]; osBundleRequired = GetProperty(dict,""OSBundleRequired""); if (osBundleRequired) toLowerStr(osbundlerequired, osBundleRequired->string); else osbundlerequired[0] = '\\0'; if (OSTYPE_IS_OSX_RECOVERY(loaderType) || OSTYPE_IS_OSX_INSTALLER(loaderType)) { if (strncmp(osbundlerequired, ""root"", 4) && strncmp(osbundlerequired, ""local"", 5) && strncmp(osbundlerequired, ""console"", 7) && strncmp(osbundlerequired, ""network-root"", 12)) { inject = FALSE; } } return inject; } //extern VOID KernelAndKextPatcherInit(IN LOADER_ENTRY *Entry); //extern VOID AnyKextPatch(UINT8 *Driver, UINT32 DriverSize, CHAR8 *InfoPlist, UINT32 InfoPlistSize, INT32 N, LOADER_ENTRY *Entry); EFI_STATUS LOADER_ENTRY::LoadKext(IN EFI_FILE *RootDir, IN CHAR16 *FileName, IN cpu_type_t archCpuType, IN OUT VOID *kext_v) { EFI_STATUS Status; UINT8* infoDictBuffer = NULL; UINTN infoDictBufferLength = 0; UINT8* executableFatBuffer = NULL; UINT8* executableBuffer = NULL; UINTN executableBufferLength = 0; CHAR8* bundlePathBuffer = NULL; UINTN bundlePathBufferLength = 0; CHAR16 *TempName; CHAR16 *Executable; TagPtr dict = NULL; TagPtr prop = NULL; BOOLEAN NoContents = FALSE; BOOLEAN inject = FALSE; _BooterKextFileInfo *infoAddr = NULL; _DeviceTreeBuffer *kext = (_DeviceTreeBuffer *)kext_v; TempName = PoolPrint(L""%s\\\\%s"", FileName, L""Contents\\\\Info.plist""); // snwprintf(TempName, 512, L""%s\\\\%s"", FileName, ""Contents\\\\Info.plist""); Status = egLoadFile(RootDir, TempName, &infoDictBuffer, &infoDictBufferLength); FreePool(TempName); if (EFI_ERROR(Status)) { //try to find a planar kext, without Contents TempName = PoolPrint(L""%s\\\\%s"", FileName, L""Info.plist""); // snwprintf(TempName, 512, L""%s\\\\%s"", FileName, ""Info.plist""); Status = egLoadFile(RootDir, TempName, &infoDictBuffer, &infoDictBufferLength); FreePool(TempName); if (EFI_ERROR(Status)) { MsgLog(""Failed to load extra kext (Info.plist not found): %ls\\n"", FileName); return EFI_NOT_FOUND; } NoContents = TRUE; } if(ParseXML((CHAR8*)infoDictBuffer,&dict,(UINT32)infoDictBufferLength)!=0) { FreePool(infoDictBuffer); MsgLog(""Failed to load extra kext (failed to parse Info.plist): %ls\\n"", FileName); return EFI_NOT_FOUND; } inject = checkOSBundleRequired(LoaderType, dict); if(!inject) { MsgLog(""Skipping kext injection by OSBundleRequired : %ls\\n"", FileName); return EFI_UNSUPPORTED; } prop = GetProperty(dict,""CFBundleExecutable""); if(prop!=0) { Executable = PoolPrint(L""%a"", prop->string); // AsciiStrToUnicodeStrS(prop->string, Executable, 256); if (NoContents) { TempName = PoolPrint(L""%s\\\\%s"", FileName, Executable); // snwprintf(TempName, 512, ""%s\\\\%s"", FileName, Executable); } else { TempName = PoolPrint(L""%s\\\\%s\\\\%s"", FileName, L""Contents\\\\MacOS"",Executable); // snwprintf(TempName, 512, L""%s\\\\%s\\\\%s"", FileName, ""Contents\\\\MacOS"",Executable); } FreePool(Executable); Status = egLoadFile(RootDir, TempName, &executableFatBuffer, &executableBufferLength); FreePool(TempName); if (EFI_ERROR(Status)) { FreePool(infoDictBuffer); MsgLog(""Failed to load extra kext (executable not found): %ls\\n"", FileName); return EFI_NOT_FOUND; } executableBuffer = executableFatBuffer; if (ThinFatFile(&executableBuffer, &executableBufferLength, archCpuType)) { FreePool(infoDictBuffer); FreePool(executableBuffer); MsgLog(""Thinning failed: %ls\\n"", FileName); return EFI_NOT_FOUND; } } bundlePathBufferLength = StrLen(FileName) + 1; bundlePathBuffer = (__typeof__(bundlePathBuffer))AllocateZeroPool(bundlePathBufferLength); UnicodeStrToAsciiStrS(FileName, bundlePathBuffer, bundlePathBufferLength); kext->length = (UINT32)(sizeof(_BooterKextFileInfo) + infoDictBufferLength + executableBufferLength + bundlePathBufferLength); infoAddr = (_BooterKextFileInfo *)AllocatePool(kext->length); infoAddr->infoDictPhysAddr = sizeof(_BooterKextFileInfo); infoAddr->infoDictLength = (UINT32)infoDictBufferLength; infoAddr->executablePhysAddr = (UINT32)(sizeof(_BooterKextFileInfo) + infoDictBufferLength); infoAddr->executableLength = (UINT32)executableBufferLength; infoAddr->bundlePathPhysAddr = (UINT32)(sizeof(_BooterKextFileInfo) + infoDictBufferLength + executableBufferLength); infoAddr->bundlePathLength = (UINT32)bundlePathBufferLength; kext->paddr = (UINT32)(UINTN)infoAddr; // Note that we cannot free infoAddr because of this CopyMem((CHAR8 *)infoAddr + sizeof(_BooterKextFileInfo), infoDictBuffer, infoDictBufferLength); CopyMem((CHAR8 *)infoAddr + sizeof(_BooterKextFileInfo) + infoDictBufferLength, executableBuffer, executableBufferLength); CopyMem((CHAR8 *)infoAddr + sizeof(_BooterKextFileInfo) + infoDictBufferLength + executableBufferLength, bundlePathBuffer, bundlePathBufferLength); FreePool(infoDictBuffer); FreePool(executableFatBuffer); FreePool(bundlePathBuffer); return EFI_SUCCESS; } EFI_STATUS LOADER_ENTRY::AddKext(IN EFI_FILE *RootDir, IN CHAR16 *FileName, IN cpu_type_t archCpuType) { EFI_STATUS Status; KEXT_ENTRY *KextEntry; KextEntry = (__typeof__(KextEntry))AllocatePool (sizeof(KEXT_ENTRY)); KextEntry->Signature = KEXT_SIGNATURE; Status = LoadKext(RootDir, FileName, archCpuType, &KextEntry->kext); if(EFI_ERROR(Status)) { FreePool(KextEntry); } else { InsertTailList (&gKextList, &KextEntry->Link); } return Status; } UINT32 GetListCount(LIST_ENTRY const* List) { LIST_ENTRY *Link; UINT32 Count=0; if(!IsListEmpty(List)) { for (Link = List->ForwardLink; Link != List; Link = Link->ForwardLink) Count++; } return Count; } UINT32 GetKextCount() { return (UINT32)GetListCount(&gKextList); } UINT32 GetKextsSize() { LIST_ENTRY *Link; KEXT_ENTRY *KextEntry; UINT32 kextsSize=0; if(!IsListEmpty(&gKextList)) { for (Link = gKextList.ForwardLink; Link != &gKextList; Link = Link->ForwardLink) { KextEntry = CR(Link, KEXT_ENTRY, Link, KEXT_SIGNATURE); kextsSize += RoundPage(KextEntry->kext.length); } } return kextsSize; } VOID LOADER_ENTRY::LoadPlugInKexts(IN EFI_FILE *RootDir, IN CHAR16 *DirName, IN cpu_type_t archCpuType, IN BOOLEAN Force) { REFIT_DIR_ITER PlugInIter; EFI_FILE_INFO *PlugInFile; CHAR16 *FileName; if ((RootDir == NULL) || (DirName == NULL)) { return; } DirIterOpen(RootDir, DirName, &PlugInIter); while (DirIterNext(&PlugInIter, 1, L""*.kext"", &PlugInFile)) { if (PlugInFile->FileName[0] == '.' || StrStr(PlugInFile->FileName, L"".kext"") == NULL) continue; // skip this FileName = PoolPrint(L""%s\\\\%s"", DirName, PlugInFile->FileName); // snwprintf(FileName, 512, ""%s\\\\%s"", DirName, PlugInFile->FileName); MsgLog("" %ls PlugIn kext: %ls\\n"", Force ? L""Force"" : L""Extra"", FileName); AddKext( RootDir, FileName, archCpuType); FreePool(FileName); } DirIterClose(&PlugInIter); } VOID LOADER_ENTRY::AddKexts(CONST CHAR16 *SrcDir, CONST CHAR16 *Path, cpu_type_t archCpuType) { CHAR16 *FileName; CHAR16 *PlugInName; SIDELOAD_KEXT *CurrentKext; SIDELOAD_KEXT *CurrentPlugInKext; EFI_STATUS Status; MsgLog(""Preparing kexts injection for arch=%ls from %ls\\n"", (archCpuType==CPU_TYPE_X86_64)?L""x86_64"":(archCpuType==CPU_TYPE_I386)?L""i386"":L"""", SrcDir); CurrentKext = InjectKextList; while (CurrentKext) { DBG("" current kext name=%ls path=%ls, match against=%ls\\n"", CurrentKext->FileName, CurrentKext->KextDirNameUnderOEMPath, Path); if (StrCmp(CurrentKext->KextDirNameUnderOEMPath, Path) == 0) { FileName = PoolPrint(L""%s\\\\%s"", SrcDir, CurrentKext->FileName); // snwprintf(FileName, 512, ""%s\\\\%s"", SrcDir, CurrentKext->FileName); if (!(CurrentKext->MenuItem.BValue)) { // inject require MsgLog(""->Extra kext: %ls (v.%ls)\\n"", FileName, CurrentKext->Version); Status = AddKext(SelfVolume->RootDir, FileName, archCpuType); if(!EFI_ERROR(Status)) { // decide which plugins to inject CurrentPlugInKext = CurrentKext->PlugInList; while (CurrentPlugInKext) { PlugInName = PoolPrint(L""%s\\\\%s\\\\%s"", FileName, L""Contents\\\\PlugIns"", CurrentPlugInKext->FileName); // snwprintf(PlugInName, 512, L""%s\\\\%s\\\\%s"", FileName, ""Contents\\\\PlugIns"", CurrentPlugInKext->FileName); if (!(CurrentPlugInKext->MenuItem.BValue)) { // inject PlugIn require MsgLog("" |-- PlugIn kext: %ls (v.%ls)\\n"", PlugInName, CurrentPlugInKext->Version); AddKext(SelfVolume->RootDir, PlugInName, archCpuType); } else { MsgLog("" |-- Disabled plug-in kext: %ls (v.%ls)\\n"", PlugInName, CurrentPlugInKext->Version); } FreePool(PlugInName); CurrentPlugInKext = CurrentPlugInKext->Next; } // end of plug-in kext injection } } else { // disable current kext injection if (!StriStr(SrcDir, L""Off"")) { MsgLog(""Disabled kext: %ls (v.%ls)\\n"", FileName, CurrentKext->Version); } } FreePool(FileName); } CurrentKext = CurrentKext->Next; } // end of kext injection } EFI_STATUS LOADER_ENTRY::LoadKexts() { CHAR16 *SrcDir = NULL; REFIT_DIR_ITER PlugInIter; EFI_FILE_INFO *PlugInFile; CHAR16 *FileName; CHAR16 *PlugIns; // CONST CHAR16 *Arch = NULL; // CONST CHAR16 *Ptr = NULL; #if defined(MDE_CPU_X64) cpu_type_t archCpuType=CPU_TYPE_X86_64; #else cpu_type_t archCpuType=CPU_TYPE_I386; #endif UINTN mm_extra_size; VOID *mm_extra; UINTN extra_size; VOID *extra; SIDELOAD_KEXT *CurrentKext = NULL; SIDELOAD_KEXT *CurrentPlugInKext = NULL; SIDELOAD_KEXT *Next = NULL; // Make Arch point to the last appearance of ""arch="" in LoadOptions (which is what boot.efi will use). // if (LoadOptions.notEmpty()) { // for (Ptr = StrStr(LoadOptions, L""arch=""); Ptr != NULL; Arch = Ptr + StrLen(L""arch=""), Ptr = StrStr(Arch, L""arch="")); // } // if (Arch != NULL && StrnCmp(Arch,L""x86_64"",StrLen(L""x86_64"")) == 0) { if (LoadOptions.contains(""arch=x86_64"")) { archCpuType = CPU_TYPE_X86_64; // } else if (Arch != NULL && StrnCmp(Arch,L""i386"",StrLen(L""i386"")) == 0) { } else if (LoadOptions.contains(""arch=i386"")) { archCpuType = CPU_TYPE_I386; } else if (OSVersion != NULL) { UINT64 os_version = AsciiOSVersionToUint64(OSVersion); if (os_version >= AsciiOSVersionToUint64(""10.8"")) { archCpuType = CPU_TYPE_X86_64; // For OSVersion >= 10.8, only x86_64 exists } else if (os_version < AsciiOSVersionToUint64(""10.7"")) { archCpuType = CPU_TYPE_I386; // For OSVersion < 10.7, use default of i386 } } // Force kexts to load if ((KernelAndKextPatches != NULL) && (KernelAndKextPatches->NrForceKexts > 0) && (KernelAndKextPatches->ForceKexts != NULL)) { INT32 i = 0; for (; i < KernelAndKextPatches->NrForceKexts; ++i) { MsgLog("" Force kext: %ls\\n"", KernelAndKextPatches->ForceKexts[i]); if (Volume && Volume->RootDir) { // Check if the entry is a directory if (StrStr(KernelAndKextPatches->ForceKexts[i], L"".kext"") == NULL) { DirIterOpen(Volume->RootDir, KernelAndKextPatches->ForceKexts[i], &PlugInIter); while (DirIterNext(&PlugInIter, 1, L""*.kext"", &PlugInFile)) { if (PlugInFile->FileName[0] == '.' || StrStr(PlugInFile->FileName, L"".kext"") == NULL) continue; // skip this FileName = PoolPrint(L""%s\\\\%s"", KernelAndKextPatches->ForceKexts[i], PlugInFile->FileName); // snwprintf(FileName, 512, ""%s\\\\%s"", KernelAndKextPatches->ForceKexts[i], PlugInFile->FileName); MsgLog("" Force kext: %ls\\n"", FileName); AddKext( Volume->RootDir, FileName, archCpuType); PlugIns = PoolPrint(L""%s\\\\Contents\\\\PlugIns"", FileName); // snwprintf(PlugIns, 512, ""%s\\\\Contents\\\\PlugIns"", FileName); LoadPlugInKexts(Volume->RootDir, PlugIns, archCpuType, TRUE); FreePool(FileName); FreePool(PlugIns); } DirIterClose(&PlugInIter); } else { AddKext( Volume->RootDir, KernelAndKextPatches->ForceKexts[i], archCpuType); PlugIns = PoolPrint(L""%s\\\\Contents\\\\PlugIns"", KernelAndKextPatches->ForceKexts[i]); // snwprintf(PlugIns, 512, ""%s\\\\Contents\\\\PlugIns"", KernelAndKextPatches->ForceKexts[i]); LoadPlugInKexts(Volume->RootDir, PlugIns, archCpuType, TRUE); FreePool(PlugIns); } } } } CHAR16 UniOSVersion[16]; AsciiStrToUnicodeStrS(OSVersion, UniOSVersion, 16); DBG(""UniOSVersion == %ls\\n"", UniOSVersion); CHAR16 UniShortOSVersion[6]; CHAR8 ShortOSVersion[6]; if (AsciiOSVersionToUint64(OSVersion) < AsciiOSVersionToUint64(""10.10"")) { // OSVersion that are earlier than 10.10(form: 10.x.y) AsciiStrnCpyS(ShortOSVersion, 6, OSVersion, 4); AsciiStrToUnicodeStrS(OSVersion, UniShortOSVersion, 5); } else { AsciiStrnCpyS(ShortOSVersion, 6, OSVersion, 5); AsciiStrToUnicodeStrS(OSVersion, UniShortOSVersion, 6); } DBG(""ShortOSVersion == %s\\n"", ShortOSVersion); DBG(""UniShortOSVersion == %ls\\n"", UniShortOSVersion); // syscl - allow specific load inject kext // Clover/Kexts/Other is for general injection thus we need to scan both Other and OSVersion folder if ((SrcDir = GetOtherKextsDir(TRUE)) != NULL) { AddKexts(SrcDir, L""Other"", archCpuType); FreePool(SrcDir); } else { DBG(""GetOtherKextsDir(TRUE) return NULL\\n""); } // slice: CLOVER/kexts/Off keep disabled kext which can be allowed if ((SrcDir = GetOtherKextsDir(FALSE)) != NULL) { AddKexts(SrcDir, L""Off"", archCpuType); FreePool(SrcDir); } else { DBG(""GetOtherKextsDir(FALSE) return NULL\\n""); } // Add kext from 10 { CHAR16 *OSAllVersionKextsDir; CHAR16 *OSShortVersionKextsDir; CHAR16 *OSVersionKextsDirName; CHAR16 *DirName; CHAR16 *DirPath; OSAllVersionKextsDir = PoolPrint(L""%s\\\\kexts\\\\10"", OEMPath); // snwprintf(OSAllVersionKextsDir, sizeof(OSAllVersionKextsDir), ""%s\\\\kexts\\\\10"", OEMPath); AddKexts(OSAllVersionKextsDir, L""10"", archCpuType); FreePool(OSAllVersionKextsDir); if (OSTYPE_IS_OSX_INSTALLER(LoaderType)) { DirName = PoolPrint(L""10_install""); // snwprintf(DirName, sizeof(DirName), ""10_install""); } else if (OSTYPE_IS_OSX_RECOVERY(LoaderType)) { DirName = PoolPrint(L""10_recovery""); // snwprintf(DirName, sizeof(DirName), ""10_recovery""); } else { DirName = PoolPrint(L""10_normal""); // snwprintf(DirName, sizeof(DirName), ""10_normal""); } DirPath = PoolPrint(L""%s\\\\kexts\\\\%s"", OEMPath, DirName); // snwprintf(DirPath, sizeof(DirPath), ""%s\\\\kexts\\\\%s"", OEMPath, DirName); AddKexts( DirPath, DirName, archCpuType); FreePool(DirPath); FreePool(DirName); // Add kext from 10.{version} OSShortVersionKextsDir = PoolPrint(L""%s\\\\kexts\\\\%s"", OEMPath, UniShortOSVersion); // snwprintf(OSShortVersionKextsDir, sizeof(OSShortVersionKextsDir), ""%s\\\\kexts\\\\%s"", OEMPath, UniShortOSVersion); AddKexts( OSShortVersionKextsDir, UniShortOSVersion, archCpuType); FreePool(OSShortVersionKextsDir); if (OSTYPE_IS_OSX_INSTALLER(LoaderType)) { DirName = PoolPrint(L""%s_install"", UniShortOSVersion); // snwprintf(DirName, sizeof(DirName), ""%s_install"", UniShortOSVersion); } else if (OSTYPE_IS_OSX_RECOVERY(LoaderType)) { DirName = PoolPrint(L""%s_recovery"", UniShortOSVersion); // snwprintf(DirName, sizeof(DirName), ""%s_recovery"", UniShortOSVersion); } else { DirName = PoolPrint(L""%s_normal"", UniShortOSVersion); // snwprintf(DirName, sizeof(DirName), ""%s_normal"", UniShortOSVersion); } DirPath = PoolPrint(L""%s\\\\kexts\\\\%s"", OEMPath, DirName); // snwprintf(DirPath, sizeof(DirPath), ""%s\\\\kexts\\\\%s"", OEMPath, DirName); AddKexts( DirPath, DirName, archCpuType); FreePool(DirPath); FreePool(DirName); // Add kext from : // 10.{version}.0 if NO minor version // 10.{version}.{minor version} if minor version is > 0 if ( AsciiStrCmp(ShortOSVersion, OSVersion) == 0 ) { OSVersionKextsDirName = PoolPrint(L""%a.0"", OSVersion); // snwprintf(OSVersionKextsDirName, sizeof(OSVersionKextsDirName), ""%a.0"", OSVersion); } else { OSVersionKextsDirName = PoolPrint(L""%a"", OSVersion); // snwprintf(OSVersionKextsDirName, sizeof(OSVersionKextsDirName), ""%a"", OSVersion); } DirPath = PoolPrint(L""%s\\\\kexts\\\\%s"", OEMPath, OSVersionKextsDirName); // snwprintf(DirPath, sizeof(DirPath), ""%s\\\\kexts\\\\%s"", OEMPath, OSVersionKextsDirName); AddKexts( DirPath, OSVersionKextsDirName, archCpuType); FreePool(DirPath); if ( OSTYPE_IS_OSX_INSTALLER(LoaderType)) { DirName = PoolPrint(L""%s_install"", OSVersionKextsDirName); // snwprintf(DirName, sizeof(DirName), ""%s_install"", OSVersionKextsDirName); } else if (OSTYPE_IS_OSX_RECOVERY(LoaderType)) { DirName = PoolPrint(L""%s_recovery"", OSVersionKextsDirName); // snwprintf(DirName, sizeof(DirName), ""%s_recovery"", OSVersionKextsDirName); } else { DirName = PoolPrint(L""%s_normal"", OSVersionKextsDirName); // snwprintf(DirName, sizeof(DirName), ""%s_normal"", OSVersionKextsDirName); } DirPath = PoolPrint(L""%s\\\\kexts\\\\%s"", OEMPath, DirName); // snwprintf(DirPath, sizeof(DirPath), ""%s\\\\kexts\\\\%s"", OEMPath, DirName); AddKexts( DirPath, DirName, archCpuType); FreePool(DirPath); FreePool(DirName); FreePool(OSVersionKextsDirName); } // reserve space in the device tree if (GetKextCount() > 0) { mm_extra_size = GetKextCount() * (sizeof(DeviceTreeNodeProperty) + sizeof(_DeviceTreeBuffer)); mm_extra = (__typeof__(mm_extra))AllocateZeroPool(mm_extra_size - sizeof(DeviceTreeNodeProperty)); /*Status = */LogDataHub(&gEfiMiscSubClassGuid, L""mm_extra"", mm_extra, (UINT32)(mm_extra_size - sizeof(DeviceTreeNodeProperty))); extra_size = GetKextsSize(); extra = (__typeof__(extra))AllocateZeroPool(extra_size - sizeof(DeviceTreeNodeProperty) + EFI_PAGE_SIZE); /*Status = */LogDataHub(&gEfiMiscSubClassGuid, L""extra"", extra, (UINT32)(extra_size - sizeof(DeviceTreeNodeProperty) + EFI_PAGE_SIZE)); // MsgLog(""count: %d \\n"", GetKextCount()); // MsgLog(""mm_extra_size: %d \\n"", mm_extra_size); // MsgLog(""extra_size: %d \\n"", extra_size); // MsgLog(""offset: %d \\n"", extra_size - sizeof(DeviceTreeNodeProperty) + EFI_PAGE_SIZE); //no more needed FreePool(mm_extra); FreePool(extra); } //No more InjectKextList needed. Will free the list while (InjectKextList) { CurrentKext = InjectKextList->Next; CurrentPlugInKext = InjectKextList->PlugInList; while (CurrentPlugInKext) { Next = CurrentPlugInKext->Next; FreePool(CurrentPlugInKext->FileName); FreePool(CurrentPlugInKext->KextDirNameUnderOEMPath); FreePool(CurrentPlugInKext->Version); FreePool(CurrentPlugInKext); CurrentPlugInKext = Next; } FreePool(InjectKextList->FileName); FreePool(InjectKextList->KextDirNameUnderOEMPath); FreePool(InjectKextList->Version); FreePool(InjectKextList); InjectKextList = CurrentKext; } return EFI_SUCCESS; } /* * Adler32 from Chameleon */ #define BASE 65521L /* largest prime smaller than 65536 */ #define NMAX 5000 // NMAX (was 5521) the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 #define DO1(buf,i) {s1 += buf[i]; s2 += s1;} #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1); #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2); #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4); #define DO16(buf) DO8(buf,0); DO8(buf,8); static UINT32 Adler32(unsigned char *buf, long len) { unsigned long s1 = 1; // adler & 0xffff; unsigned long s2 = 0; // (adler >> 16) & 0xffff; unsigned long result; long k; while (len > 0) { k = len < NMAX ? len : NMAX; len -= k; while (k >= 16) { DO16(buf); buf += 16; k -= 16; } if (k != 0) do { s1 += *buf++; s2 += s1; } while (--k); s1 %= BASE; s2 %= BASE; } result = (s2 << 16) | s1; // result is in big endian return (UINT32)result; } typedef struct { UINT32 Magic; UINT32 Signature; UINT32 Length; UINT32 Adler32; UINT32 Version; UINT32 NumKexts; UINT32 CpuType; UINT32 CpuSubtype; } MKextHeader; typedef struct { UINT32 PlistOffset; UINT32 PlistCompressedSize; UINT32 PlistFullSize; UINT32 PlistModifiedSeconds; UINT32 BinaryOffset; UINT32 BinaryCompressedSize; UINT32 BinaryFullSize; UINT32 BinaryModifiedSeconds; } MKextFile; #define MKEXT_MAGIC 0x54584b4d #define MKEXT_SIGNATURE 0x58534f4d #define MKEXT_VERSION_1 0x00800001 int LOADER_ENTRY::is_mkext_v1(UINT8* drvPtr) { _DeviceTreeBuffer *dtb = (_DeviceTreeBuffer*) (((UINT8*)drvPtr) + sizeof(DeviceTreeNodeProperty)); MKextHeader* mkext_ptr = (MKextHeader*)(UINTN)(dtb->paddr); if (mkext_ptr->Magic == MKEXT_MAGIC && mkext_ptr->Signature == MKEXT_SIGNATURE && mkext_ptr->Version == MKEXT_VERSION_1) { DBG_RT(""MKext_v1 found at paddr=0x%08x, length=0x%08x\\n"", dtb->paddr, dtb->length); return 1; } return 0; } void LOADER_ENTRY::patch_mkext_v1(UINT8 *drvPtr) { _DeviceTreeBuffer *dtb = (_DeviceTreeBuffer*) (((UINT8*)drvPtr) + sizeof(DeviceTreeNodeProperty)); MKextHeader* mkext_ptr = (MKextHeader*)(UINTN)dtb->paddr; UINT32 mkext_len = SwapBytes32(mkext_ptr->Length); UINT32 mkext_numKexts = SwapBytes32(mkext_ptr->NumKexts); LIST_ENTRY *Link; KEXT_ENTRY *KextEntry; if(!IsListEmpty(&gKextList)) { for (Link = gKextList.ForwardLink; Link != &gKextList; Link = Link->ForwardLink) { KextEntry = CR(Link, KEXT_ENTRY, Link, KEXT_SIGNATURE); MKextFile *mkext_insert = (MKextFile*)((UINT8*)mkext_ptr + sizeof(MKextHeader) + mkext_numKexts * sizeof(MKextFile)); // free some space CopyMem((UINT8*)mkext_insert + sizeof(MKextFile), (UINT8*)mkext_insert, mkext_len - (sizeof(MKextHeader) + mkext_numKexts * sizeof(MKextFile))); mkext_len += sizeof(MKextFile); // update the offsets to reflect 0x20 bytes moved above for (UINT32 i = 0; i < mkext_numKexts; i++) { MKextFile *kext_base = (MKextFile*)((UINT8*)mkext_ptr + sizeof(MKextHeader) + i * sizeof(MKextFile)); UINT32 plist_offset = SwapBytes32(kext_base->PlistOffset) + sizeof(MKextFile); UINT32 binary_offset = SwapBytes32(kext_base->BinaryOffset) + sizeof(MKextFile); kext_base->PlistOffset = SwapBytes32(plist_offset); kext_base->BinaryOffset = SwapBytes32(binary_offset); } // copy kext data (plist+binary) CopyMem((UINT8*)mkext_ptr + mkext_len, (UINT8*)(KextEntry->kext.paddr + sizeof(_BooterKextFileInfo)), (UINT32)((_BooterKextFileInfo*)(UINTN)(KextEntry->kext.paddr))->infoDictLength + (UINT32)((_BooterKextFileInfo*)(UINTN)(KextEntry->kext.paddr))->executableLength); // insert kext offsets mkext_insert->PlistOffset = SwapBytes32(mkext_len); mkext_len += ((_BooterKextFileInfo*)(UINTN)(KextEntry->kext.paddr))->infoDictLength; mkext_insert->PlistCompressedSize = 0; mkext_insert->PlistFullSize = SwapBytes32((UINT32)((_BooterKextFileInfo*)(UINTN)(KextEntry->kext.paddr))->infoDictLength); mkext_insert->PlistModifiedSeconds = 0; mkext_insert->BinaryOffset = SwapBytes32(mkext_len); mkext_len += ((_BooterKextFileInfo*)(UINTN)(KextEntry->kext.paddr))->executableLength; mkext_insert->BinaryCompressedSize = 0; mkext_insert->BinaryFullSize = SwapBytes32((UINT32)((_BooterKextFileInfo*)(UINTN)(KextEntry->kext.paddr))->executableLength); mkext_insert->BinaryModifiedSeconds = 0; mkext_numKexts ++; // update the header mkext_ptr->Length = SwapBytes32(mkext_len); mkext_ptr->NumKexts = SwapBytes32(mkext_numKexts); // update the checksum mkext_ptr->Adler32 = SwapBytes32(Adler32((UINT8*)mkext_ptr + 0x10, mkext_len - 0x10)); // update the memory-map reference dtb->length = mkext_len; } } } //////////////////// // OnExitBootServices //////////////////// EFI_STATUS LOADER_ENTRY::InjectKexts(IN UINT32 deviceTreeP, IN UINT32* deviceTreeLength) { UINT8 *dtEntry = (UINT8*)(UINTN) deviceTreeP; UINTN dtLen = (UINTN) *deviceTreeLength; DTEntry platformEntry; DTEntry memmapEntry; CHAR8 *ptr; OpaqueDTPropertyIterator OPropIter; DTPropertyIterator iter = &OPropIter; DeviceTreeNodeProperty *prop = NULL; UINT8 *infoPtr = 0; UINT8 *extraPtr = 0; UINT8 *drvPtr = 0; UINTN offset = 0; LIST_ENTRY *Link; KEXT_ENTRY *KextEntry; UINTN KextBase = 0; _DeviceTreeBuffer *mm; _BooterKextFileInfo *drvinfo; UINT32 KextCount; UINTN Index; DBG_RT(""\\nInjectKexts: ""); KextCount = GetKextCount(); if (KextCount == 0) { DBG_RT(""no kexts to inject.\\nPausing 5 secs ...\\n""); if (KernelAndKextPatches->KPDebug) { gBS->Stall(5000000); } return EFI_NOT_FOUND; } DBG_RT(""%d kexts ...\\n"", KextCount); // kextsBase = Desc->PhysicalStart + (((UINTN) Desc->NumberOfPages) * EFI_PAGE_SIZE); // kextsPages = EFI_SIZE_TO_PAGES(kext.length); // Status = gBS->AllocatePages(AllocateAddress, EfiLoaderData, kextsPages, &kextsBase); // if (EFI_ERROR(Status)) { MsgLog(""Kext inject: could not allocate memory\\n""); return Status; } // Desc->NumberOfPages += kextsPages; // CopyMem((VOID*)kextsBase, (VOID*)(UINTN)kext.paddr, kext.length); // drvinfo = (_BooterKextFileInfo*) kextsBase; // drvinfo->infoDictPhysAddr += (UINT32)kextsBase; // drvinfo->executablePhysAddr += (UINT32)kextsBase; // drvinfo->bundlePathPhysAddr += (UINT32)kextsBase; DTInit(dtEntry, deviceTreeLength); if(!EFI_ERROR(DTLookupEntry(NULL,""/chosen/memory-map"", &memmapEntry))) { if(!EFI_ERROR(DTCreatePropertyIterator(memmapEntry, iter))) { while(!EFI_ERROR(DTIterateProperties(iter, &ptr))) { prop = iter->CurrentProperty; drvPtr = (UINT8*) prop; if(strncmp(prop->Name, ""Driver-"", 7)==0 || strncmp(prop->Name, ""DriversPackage-"", 15)==0) { break; } } } } if(!EFI_ERROR(DTLookupEntry(NULL, ""/efi/platform"", &platformEntry))) { if(!EFI_ERROR(DTCreatePropertyIterator(platformEntry, iter))) { while(!EFI_ERROR(DTIterateProperties(iter, &ptr))) { prop = iter->CurrentProperty; if(strncmp(prop->Name, ""mm_extra"", 8)==0) { infoPtr = (UINT8*)prop; } if(strncmp(prop->Name, ""extra"", 5)==0) { extraPtr = (UINT8*)prop; } } } } if (drvPtr == 0 || infoPtr == 0 || extraPtr == 0 || drvPtr > infoPtr || drvPtr > extraPtr || infoPtr > extraPtr) { printf(""\\nInvalid device tree for kext injection\\n""); gBS->Stall(5000000); return EFI_INVALID_PARAMETER; } // make space for memory map entries platformEntry->NumProperties -= 2; offset = sizeof(DeviceTreeNodeProperty) + ((DeviceTreeNodeProperty*) infoPtr)->Length; CopyMem(drvPtr+offset, drvPtr, infoPtr-drvPtr); // make space behind device tree // platformEntry->nProperties--; offset = sizeof(DeviceTreeNodeProperty)+((DeviceTreeNodeProperty*) extraPtr)->Length; CopyMem(extraPtr, extraPtr+offset, dtLen-(UINTN)(extraPtr-dtEntry)-offset); *deviceTreeLength -= (UINT32)offset; KextBase = RoundPage(dtEntry + *deviceTreeLength); if(!IsListEmpty(&gKextList)) { Index = 1; for (Link = gKextList.ForwardLink; Link != &gKextList; Link = Link->ForwardLink) { KextEntry = CR(Link, KEXT_ENTRY, Link, KEXT_SIGNATURE); CopyMem((VOID*) KextBase, (VOID*)(UINTN) KextEntry->kext.paddr, KextEntry->kext.length); drvinfo = (_BooterKextFileInfo*) KextBase; drvinfo->infoDictPhysAddr += (UINT32) KextBase; drvinfo->executablePhysAddr += (UINT32) KextBase; drvinfo->bundlePathPhysAddr += (UINT32) KextBase; memmapEntry->NumProperties++; prop = ((DeviceTreeNodeProperty*) drvPtr); prop->Length = sizeof(_DeviceTreeBuffer); mm = (_DeviceTreeBuffer*) (((UINT8*)prop) + sizeof(DeviceTreeNodeProperty)); mm->paddr = (UINT32)KextBase; mm->length = KextEntry->kext.length; snprintf(prop->Name, 31, ""Driver-%X"", (UINT32)KextBase); drvPtr += sizeof(DeviceTreeNodeProperty) + sizeof(_DeviceTreeBuffer); KextBase = RoundPage(KextBase + KextEntry->kext.length); DBG_RT("" %llu - %s\\n"", Index, (CHAR8 *)(UINTN)drvinfo->bundlePathPhysAddr); if (gSettings.KextPatchesAllowed) { INT32 i; CHAR8 SavedValue; CHAR8 *InfoPlist = (CHAR8*)(UINTN)drvinfo->infoDictPhysAddr; SavedValue = InfoPlist[drvinfo->infoDictLength]; InfoPlist[drvinfo->infoDictLength] = '\\0'; KernelAndKextPatcherInit(); for (i = 0; i < KernelAndKextPatches->NrKexts; i++) { if ((KernelAndKextPatches->KextPatches[i].DataLen > 0) && (AsciiStrStr(InfoPlist, KernelAndKextPatches->KextPatches[i].Name) != NULL)) { AnyKextPatch( (UINT8*)(UINTN)drvinfo->executablePhysAddr, drvinfo->executableLength, InfoPlist, drvinfo->infoDictLength, i ); } } InfoPlist[drvinfo->infoDictLength] = SavedValue; } Index++; } } DBG_RT(""Done.\\n""); Stall(5000000); return EFI_SUCCESS; } //////////////////////////////////// // // KernelBooterExtensionsPatch to load extra kexts besides kernelcache // // // Snow Leopard i386 const UINT8 KBESnowSearchEXT_i386[] = { 0xE8, 0xED, 0xF9, 0xFF, 0xFF, 0xEB, 0x08, 0x89, 0x1C, 0x24 }; const UINT8 KBESnowReplaceEXT_i386[] = { 0xE8, 0xED, 0xF9, 0xFF, 0xFF, 0x90, 0x90, 0x89, 0x1C, 0x24 }; // Snow Leopard X64 const UINT8 KBESnowSearchEXT_X64[] = { 0xE8, 0x5A, 0xFB, 0xFF, 0xFF, 0xEB, 0x08, 0x48, 0x89, 0xDF }; const UINT8 KBESnowReplaceEXT_X64[] = { 0xE8, 0x5A, 0xFB, 0xFF, 0xFF, 0x90, 0x90, 0x48, 0x89, 0xDF }; // Lion i386 const UINT8 KBELionSearchEXT_i386[] = { 0xE8, 0xAA, 0xFB, 0xFF, 0xFF, 0xEB, 0x08, 0x89, 0x34, 0x24 }; const UINT8 KBELionReplaceEXT_i386[] = { 0xE8, 0xAA, 0xFB, 0xFF, 0xFF, 0x90, 0x90, 0x89, 0x34, 0x24 }; // Lion X64 const UINT8 KBELionSearchEXT_X64[] = { 0xE8, 0x0C, 0xFD, 0xFF, 0xFF, 0xEB, 0x08, 0x48, 0x89, 0xDF }; const UINT8 KBELionReplaceEXT_X64[] = { 0xE8, 0x0C, 0xFD, 0xFF, 0xFF, 0x90, 0x90, 0x48, 0x89, 0xDF }; // // We can not rely on OSVersion global variable for OS version detection, // since in some cases it is not correct (install of ML from Lion, for example). // So, we'll use ""brute-force"" method - just try to patch. // Actually, we'll at least check that if we can find only one instance of code that // we are planning to patch. // // Fully reworked by Sherlocks. 2019.06.23 // VOID EFIAPI LOADER_ENTRY::KernelBooterExtensionsPatch() { // UINTN Num = 0; UINTN NumSnow_i386_EXT = 0; UINTN NumSnow_X64_EXT = 0; UINTN NumLion_i386_EXT = 0; UINTN NumLion_X64_EXT = 0; UINTN patchLocation2 = 0, patchLocation3 = 0; DBG_RT(""\\nPatching kernel for injected kexts...\\n""); if (is64BitKernel) { NumSnow_X64_EXT = SearchAndCount(KernelData, KERNEL_MAX_SIZE, KBESnowSearchEXT_X64, sizeof(KBESnowSearchEXT_X64)); NumLion_X64_EXT = SearchAndCount(KernelData, KERNEL_MAX_SIZE, KBELionSearchEXT_X64, sizeof(KBELionSearchEXT_X64)); } else { NumSnow_i386_EXT = SearchAndCount(KernelData, KERNEL_MAX_SIZE, KBESnowSearchEXT_i386, sizeof(KBESnowSearchEXT_i386)); NumLion_i386_EXT = SearchAndCount(KernelData, KERNEL_MAX_SIZE, KBELionSearchEXT_i386, sizeof(KBELionSearchEXT_i386)); } if (NumSnow_i386_EXT + NumSnow_X64_EXT + NumLion_i386_EXT + NumLion_X64_EXT > 1) { // more then one pattern found - we do not know what to do with it // and we'll skipp it // DBG_RT(""\\nERROR patching kernel for injected kexts:\\nmultiple patterns found (Snowi386: %llu, SnowX64: %llu, Lioni386: %llu, LionX64: %llu) - skipping patching!\\n"", NumSnow_i386_EXT, NumSnow_X64_EXT, NumLion_i386_EXT, NumLion_X64_EXT); // Stall(10000000); return; } // X64 if (is64BitKernel) { if (NumSnow_X64_EXT == 1) { /*Num=*/ SearchAndReplace(KernelData, KERNEL_MAX_SIZE, KBESnowSearchEXT_X64, sizeof(KBESnowSearchEXT_X64), KBESnowReplaceEXT_X64, 1); // DBG_RT(""==> kernel Snow Leopard X64: %llu replaces done.\\n"", Num); } else if (NumLion_X64_EXT == 1) { /*Num=*/ SearchAndReplace(KernelData, KERNEL_MAX_SIZE, KBELionSearchEXT_X64, sizeof(KBELionSearchEXT_X64), KBELionReplaceEXT_X64, 1); // DBG_RT(""==> kernel Lion X64: %llu replaces done.\\n"", Num); } else { // EXT - load extra kexts besides kernelcache. #if OLD_EXTRA_KEXT_PATCH UINT32 patchLocation1 = 0; for (UINT32 i = 0; i < 0x1000000; i++) { // 01 00 31 FF BE 14 00 05 if (Kernel[i+0] == 0x01 && Kernel[i+1] == 0x00 && Kernel[i+2] == 0x31 && Kernel[i+3] == 0xFF && Kernel[i+4] == 0xBE && Kernel[i+5] == 0x14 && Kernel[i+6] == 0x00 && Kernel[i+7] == 0x05) { DBG_RT(""==> found EXT Base (10.8 - recent macOS)\\n""); for (UINT32 y = i; y < 0x1000000; y++) { // E8 XX 00 00 00 EB XX XX if (Kernel[y+0] == 0xE8 && Kernel[y+2] == 0x00 && Kernel[y+3] == 0x00 && Kernel[y+4] == 0x00 && Kernel[y+5] == 0xEB) { //(Kernel[y+7] == 0x48 || Kernel[y+7] == 0xE8)) { // 48:10.8-10.9/E8:10.10+ patchLocation1 = y; DBG_RT(""==> found EXT (10.8 - recent macOS) at 0x%08x\\n"", patchLocation1); break; } } break; } } if (!patchLocation1) { DBG_RT(""==> can't find EXT (10.8 - recent macOS), kernel patch aborted.\\n""); gBS->Stall(3000000); } if (patchLocation1) { DBG_RT(""==> patched EXT (10.8 - recent macOS) location=%x\\n"", patchLocation1); for (i = 5; i < 7; i++) { // E8 XX 00 00 00 EB XX XX // E8 XX 00 00 00 90 90 XX Kernel[patchLocation1 + i] = 0x90; } } #else //Capitan // procedure at 950950, len = fffffffffffff3f0 // proclen=256, end=256 startLen=0 // found start at 0x950950 // found pattern: 1 // address: 0095098b // bytes:eb05 UINTN procLocation = searchProc(""readStartupExtensions""); const UINT8 findJmp[] = {0xEB, 0x05}; const UINT8 patchJmp[] = {0x90, 0x90}; // DBG_RT(""==> readStartupExtensions at %llx\\n"", procLocation); if (!SearchAndReplace(&KernelData[procLocation], 0x100, findJmp, 2, patchJmp, 1)) { DBG_RT(""load kexts not patched\\n""); // for (UINTN j=procLocation+0x3b; j patch to not jump // 7412 jmp ffffff8000848992 // ; Basic Block Input Regs: rbx - Killed Regs: rax rdi // ffffff8000848980 488B03 mov rax, qword [ds:rbx] // ffffff8000848983 4889DF mov rdi, rbx // ffffff8000848986 FF5028 call qword [ds:rax+0x28] // ffffff8000848989 483B1DE04F2B00 cmp rbx, qword [ds:0xffffff8000afd970] // ffffff8000848990 745E je 0xffffff80008489f0 -> patch to not jump // ; Basic Block Input Regs: r13 - Killed Regs: rax rbx rdi // ffffff8000848992 498B4500 mov rax, qword [ds:r13+0x0] // procedure at 6487f0, len = 7250 // proclen=512, end=512 startLen=0 // found start at 0x6487f0 // found pattern: 1 // address: 0064897b // bytes:4885db7470 #if OLD_EXTRA_KEXT_PATCH for (UINT32 i = 0; i < 0x1000000; i++) { // 45 31 FF 41 XX 01 00 00 DC 48 if (Kernel[i+0] == 0x45 && Kernel[i+1] == 0x31 && Kernel[i+3] == 0x41 && //(Kernel[i+4] == 0xBF || Kernel[i+4] == 0xBE) && // BF:10.11/BE:10.12+ Kernel[i+5] == 0x01 && Kernel[i+6] == 0x00 && Kernel[i+7] == 0x00 && Kernel[i+8] == 0xDC && Kernel[i+9] == 0x48) { DBG_RT(""==> found loadExecutable (10.11 - recent macOS) at %x\\n"", i); for (UINT32 y = i; y < 0x100000; y++) { // 48 85 XX 74 XX 48 XX XX 48 if (Kernel[y+0] == 0x48 && Kernel[y+1] == 0x85 && Kernel[y+3] == 0x74 && Kernel[y+5] == 0x48 && Kernel[y+8] == 0x48) { patchLocation2 = y; DBG_RT(""==> found SIP (10.11 - 10.14) at 0x%08x\\n"", patchLocation2); break; // 00 85 C0 0F 84 XX 00 00 00 49 //???? - not found in Catalina } else if (Kernel[y+0] == 0x00 && Kernel[y+1] == 0x85 && Kernel[y+2] == 0xC0 && Kernel[y+3] == 0x0F && Kernel[y+4] == 0x84 && Kernel[y+9] == 0x49) { patchLocation2 = y; DBG_RT(""==> found SIP (10.15 - recent macOS) at 0x%08x\\n"", patchLocation2); break; } } break; } } #else const UINT8 find3[] = {0x48, 0x85, 00, 0x74, 00, 0x48, 00, 00, 0x48 }; const UINT8 mask3[] = {0xFF, 0xFF, 00, 0xFF, 00, 0xFF, 00, 00, 0xFF }; #endif //ffffff80009a2267 488D35970D2400 lea rsi, qword [ds:0xffffff8000be3005] ; ""com.apple.private.security.kext-management"" //ffffff80009a226e E89D780D00 call _IOTaskHasEntitlement //ffffff80009a2273 85C0 test eax, eax =>change to eb06 -> jmp .+6 //ffffff80009a2275 0F843C010000 je 0xffffff80009a23b7 //ffffff80009a227b UINTN taskLocation = searchProc(""IOTaskHasEntitlement""); procLocation = searchProc(""loadExecutable""); patchLocation2 = FindMemMask(&KernelData[procLocation], 0x1000, find3, sizeof(find3), mask3, sizeof(mask3)); if (patchLocation2 != KERNEL_MAX_SIZE) { DBG_RT(""=> patch SIP applied\\n""); patchLocation2 += procLocation; KernelData[patchLocation2 + 3] = 0xEB; if (KernelData[patchLocation2 + 4] == 0x6C) { KernelData[patchLocation2 + 4] = 0x15; } else { KernelData[patchLocation2 + 4] = 0x12; } } else { patchLocation2 = FindRelative32(KernelData, procLocation, 0x1000, taskLocation); if (patchLocation2 != 0) { DBG_RT(""=> patch2 SIP applied\\n""); KernelData[patchLocation2] = 0xEB; KernelData[patchLocation2 + 1] = 0x06; } else { DBG_RT(""=> patch2 SIP not applied\\n""); } } Stall(10000000); /* //Capitan: 48 85 db 74 70 48 8b 03 48 if (patchLocation2) { if (taskFound) { UINT8 jmp = Kernel[patchLocation2 + 4]; const UINT8 repl4[] = {0xB8, 0x01, 0x00, 0x00, 0x00, 0xEB}; CopyMem(&Kernel[patchLocation2], repl4, sizeof(repl4)); Kernel[patchLocation2 + 6] = jmp; DBG_RT(""=> mojave SIP applyed\\n""); } else if (Kernel[patchLocation2 + 0] == 0x48 && Kernel[patchLocation2 + 1] == 0x85) { Kernel[patchLocation2 + 3] = 0xEB; DBG_RT(""==> patched SIP (10.11 - 10.14)\\n""); if (Kernel[patchLocation2 + 4] == 0x6C) { // 48 85 XX 74 6C 48 XX XX 48 // 48 85 XX EB 15 48 XX XX 48 Kernel[patchLocation2 + 4] = 0x15; // 10.14.4-10.14.6 } else { // 48 85 XX 74 XX 48 XX XX 48 // 48 85 XX EB 12 48 XX XX 48 Kernel[patchLocation2 + 4] = 0x12; // 10.11-10.14.3 } // PMheart } else if (Kernel[patchLocation2 + 0] == 0x00 && Kernel[patchLocation2 + 1] == 0x85) { DBG_RT(""==> patched SIP (10.15 - recent macOS)\\n""); for (i = 3; i < 9; i++) { // 00 85 C0 0F 84 XX 00 00 00 49 // 00 85 C0 90 90 90 90 90 90 49 Kernel[patchLocation2 + i] = 0x90; } } } Stall(9000000); */ //Slice - hope this patch useful for some system that I have no. // KxldUnmap by vit9696 // Avoid race condition in OSKext::removeKextBootstrap when using booter kexts without keepsyms=1. procLocation = searchProc(""removeKextBootstrap""); const UINT8 find5[] = {0x00, 0x0F, 0x85, 00, 00, 0x00, 0x00, 0x48 }; const UINT8 mask5[] = {0xFF, 0xFF, 0xFF, 00, 00, 0xFF, 0xFF, 0xFF }; patchLocation3 = FindMemMask(&KernelData[procLocation], 0x1000, find5, sizeof(find5), mask5, sizeof(mask5)); /* for (UINT32 i = 0; i < 0x1000000; i++) { // 55 48 89 E5 41 57 41 56 41 54 53 //10 // 48 83 EC 30 48 C7 45 B8 XX XX XX //21 // XX XX XX XX XX XX XX XX XX XX XX //32 // XX XX XX XX XX XX XX XX XX XX XX //43 // XX XX XX XX XX XX XX XX XX FF XX //54 // XX XX XX XX XX XX XX XX XX FF FF //65 if (Kernel[i+0] == 0x55 && Kernel[i+1] == 0x48 && Kernel[i+2] == 0x89 && Kernel[i+3] == 0xE5 && Kernel[i+4] == 0x41 && Kernel[i+5] == 0x57 && Kernel[i+6] == 0x41 && Kernel[i+7] == 0x56 && Kernel[i+8] == 0x41 && Kernel[i+9] == 0x54 && Kernel[i+10] == 0x53 && Kernel[i+11] == 0x48 && Kernel[i+12] == 0x83 && Kernel[i+13] == 0xEC && Kernel[i+14] == 0x30 && Kernel[i+15] == 0x48 && Kernel[i+16] == 0xC7 && Kernel[i+17] == 0x45 && Kernel[i+18] == 0xB8 && Kernel[i+53] == 0xFF && Kernel[i+64] == 0xFF && Kernel[i+65] == 0xFF) { DBG_RT(""==> found KxldUnmap Base (10.14 - recent macOS)\\n""); for (UINT32 y = i; y < 0x1000000; y++) { // 00 0F 85 XX XX 00 00 48 if (Kernel[y+0] == 0x00 && Kernel[y+1] == 0x0F && Kernel[y+2] == 0x85 && Kernel[y+5] == 0x00 && Kernel[y+6] == 0x00 && Kernel[y+7] == 0x48) { patchLocation3 = y; DBG_RT(""==> found KxldUnmap (10.14 - recent macOS) at 0x%08x\\n"", patchLocation3); break; } } break; } } */ if (patchLocation3 == KERNEL_MAX_SIZE) { DBG_RT(""==> can't find KxldUnmap (10.14 - recent macOS)\\n""); Stall(3000000); } else { DBG_RT(""==> patched KxldUnmap (10.14 - recent macOS)\\n""); // 00 0F 85 XX XX 00 00 48 // 00 90 E9 XX XX 00 00 48 KernelData[procLocation + patchLocation3 + 1] = 0x90; KernelData[procLocation + patchLocation3 + 2] = 0xE9; } } } else { // i386 if (NumSnow_i386_EXT == 1) { /*Num=*/ SearchAndReplace(KernelData, KERNEL_MAX_SIZE, KBESnowSearchEXT_i386, sizeof(KBESnowSearchEXT_i386), KBESnowReplaceEXT_i386, 1); // DBG_RT(""==> kernel Snow Leopard i386: %llu replaces done.\\n"", Num); } else if (NumLion_i386_EXT == 1) { /*Num=*/ SearchAndReplace(KernelData, KERNEL_MAX_SIZE, KBELionSearchEXT_i386, sizeof(KBELionSearchEXT_i386), KBELionReplaceEXT_i386, 1); // DBG_RT(""==> kernel Lion i386: %llu replaces done.\\n"", Num); } else { DBG_RT(""==> ERROR: NOT patched - unknown kernel.\\n""); } } DBG_RT(""Pausing 5 secs ...\\n""); Stall(5000000); } ",16249,True,2524.1895599421323,median "/* Copyright (c) 2020, Peter Barrett ** ** Permission to use, copy, modify, and/or distribute this software for ** any purpose with or without fee is hereby granted, provided that the ** above copyright notice and this permission notice appear in all copies. ** ** THE SOFTWARE IS PROVIDED ""AS IS"" AND THE AUTHOR DISCLAIMS ALL ** WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR ** BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES ** OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, ** WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ** ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS ** SOFTWARE. */ /* ** Extracted from Peter Barrett's ESP_8_BIT project and adapted to Arduino ** library by Roger Cheng */ #include ""C_ESP_8_BIT_composite.h"" static const char *TAG = ""ESP_8_BIT""; static ESP_8_BIT_composite* _instance_ = NULL; static int _pal_ = 0; static dac_channel_t _dac_ch = DAC_CHANNEL_1; // @chrmlinux03 //==================================================================================================== //==================================================================================================== // // low level HW setup of DAC/DMA/APLL/PWM // lldesc_t _dma_desc[4] = {0}; intr_handle_t _isr_handle; extern ""C"" void IRAM_ATTR video_isr(volatile void* buf); // simple isr void IRAM_ATTR i2s_intr_handler_video(void *arg) { if (I2S0.int_st.out_eof) video_isr(((lldesc_t*)I2S0.out_eof_des_addr)->buf); // get the next line of video I2S0.int_clr.val = I2S0.int_st.val; // reset the interrupt } static esp_err_t start_dma(int line_width, int samples_per_cc, int ch = 1) { periph_module_enable(PERIPH_I2S0_MODULE); // setup interrupt if (esp_intr_alloc(ETS_I2S0_INTR_SOURCE, ESP_INTR_FLAG_LEVEL1 | ESP_INTR_FLAG_IRAM, i2s_intr_handler_video, 0, &_isr_handle) != ESP_OK) return -1; // reset conf I2S0.conf.val = 1; I2S0.conf.val = 0; I2S0.conf.tx_right_first = 1; I2S0.conf.tx_mono = (ch == 2 ? 0 : 1); I2S0.conf2.lcd_en = 1; I2S0.fifo_conf.tx_fifo_mod_force_en = 1; I2S0.sample_rate_conf.tx_bits_mod = 16; I2S0.conf_chan.tx_chan_mod = (ch == 2) ? 0 : 1; // Create TX DMA buffers for (int i = 0; i < 2; i++) { int n = line_width * 2 * ch; if (n >= 4092) { printf(""DMA chunk too big:%s\\n"", n); return -1; } _dma_desc[i].buf = (uint8_t*)heap_caps_calloc(1, n, MALLOC_CAP_DMA); if (!_dma_desc[i].buf) return -1; _dma_desc[i].owner = 1; _dma_desc[i].eof = 1; _dma_desc[i].length = n; _dma_desc[i].size = n; _dma_desc[i].empty = (uint32_t)(i == 1 ? _dma_desc : _dma_desc + 1); } I2S0.out_link.addr = (uint32_t)_dma_desc; // Setup up the apll: See ref 3.2.7 Audio PLL // f_xtal = (int)rtc_clk_xtal_freq_get() * 1000000; // f_out = xtal_freq * (4 + sdm2 + sdm1/256 + sdm0/65536); // 250 < f_out < 500 // apll_freq = f_out/((o_div + 2) * 2) // operating range of the f_out is 250 MHz ~ 500 MHz // operating range of the apll_freq is 16 ~ 128 MHz. // select sdm0,sdm1,sdm2 to produce nice multiples of colorburst frequencies // see calc_freq() for math: (4+a)*10/((2 + b)*2) mhz // up to 20mhz seems to work ok: // rtc_clk_apll_enable(1,0x00,0x00,0x4,0); // 20mhz for fancy DDS if (!_pal_) { switch (samples_per_cc) { case 3: rtc_clk_apll_enable(1, 0x46, 0x97, 0x4, 2); break; // 10.7386363636 3x NTSC (10.7386398315mhz) case 4: rtc_clk_apll_enable(1, 0x46, 0x97, 0x4, 1); break; // 14.3181818182 4x NTSC (14.3181864421mhz) } } else { rtc_clk_apll_enable(1, 0x04, 0xA4, 0x6, 1); // 17.734476mhz ~4x PAL } I2S0.clkm_conf.clkm_div_num = 1; // I2S clock divider’s integral value. I2S0.clkm_conf.clkm_div_b = 0; // Fractional clock divider’s numerator value. I2S0.clkm_conf.clkm_div_a = 1; // Fractional clock divider’s denominator value I2S0.sample_rate_conf.tx_bck_div_num = 1; I2S0.clkm_conf.clka_en = 1; // Set this bit to enable clk_apll. I2S0.fifo_conf.tx_fifo_mod = (ch == 2) ? 0 : 1; // 32-bit dual or 16-bit single channel data // dac_output_enable(DAC_CHANNEL_1); // DAC, video on GPIO25 dac_output_enable(_dac_ch); // DAC, video on GPIO25/GPIO26 dac_i2s_enable(); // start DAC! I2S0.conf.tx_start = 1; // start DMA! I2S0.int_clr.val = 0xFFFFFFFF; I2S0.int_ena.out_eof = 1; I2S0.out_link.start = 1; return esp_intr_enable(_isr_handle); // start interruprs! } void video_init_hw(int line_width, int samples_per_cc) { // setup apll 4x NTSC or PAL colorburst rate start_dma(line_width, samples_per_cc, 1); // Now ideally we would like to use the decoupled left DAC channel to produce audio // But when using the APLL there appears to be some clock domain conflict that causes // nasty digitial spikes and dropouts. } //==================================================================================================== //==================================================================================================== // ntsc phase representation of a rrrgggbb pixel // must be in RAM so VBL works const static DRAM_ATTR uint32_t ntsc_RGB332[256] = { 0x18181818, 0x18171A1C, 0x1A151D22, 0x1B141F26, 0x1D1C1A1B, 0x1E1B1C20, 0x20191F26, 0x2119222A, 0x23201C1F, 0x241F1E24, 0x251E222A, 0x261D242E, 0x29241F23, 0x2A232128, 0x2B22242E, 0x2C212632, 0x2E282127, 0x2F27232C, 0x31262732, 0x32252936, 0x342C232B, 0x352B2630, 0x372A2936, 0x38292B3A, 0x3A30262F, 0x3B2F2833, 0x3C2E2B3A, 0x3D2D2E3E, 0x40352834, 0x41342B38, 0x43332E3E, 0x44323042, 0x181B1B18, 0x191A1D1C, 0x1B192022, 0x1C182327, 0x1E1F1D1C, 0x1F1E2020, 0x201D2326, 0x211C252B, 0x24232020, 0x25222224, 0x2621252A, 0x2720272F, 0x29272224, 0x2A262428, 0x2C25282E, 0x2D242A33, 0x2F2B2428, 0x302A272C, 0x32292A32, 0x33282C37, 0x352F272C, 0x362E2930, 0x372D2C36, 0x382C2F3B, 0x3B332930, 0x3C332B34, 0x3D312F3A, 0x3E30313F, 0x41382C35, 0x42372E39, 0x4336313F, 0x44353443, 0x191E1E19, 0x1A1D211D, 0x1B1C2423, 0x1C1B2628, 0x1F22211D, 0x20212321, 0x21202627, 0x221F292C, 0x24262321, 0x25252525, 0x2724292B, 0x28232B30, 0x2A2A2625, 0x2B292829, 0x2D282B2F, 0x2E272D34, 0x302E2829, 0x312E2A2D, 0x322C2D33, 0x332B3038, 0x36332A2D, 0x37322C31, 0x38303037, 0x392F323C, 0x3B372D31, 0x3C362F35, 0x3E35323B, 0x3F343440, 0x423B2F36, 0x423A313A, 0x44393540, 0x45383744, 0x1A21221A, 0x1B20241E, 0x1C1F2724, 0x1D1E2A29, 0x1F25241E, 0x20242622, 0x22232A28, 0x23222C2D, 0x25292722, 0x26292926, 0x27272C2C, 0x28262E30, 0x2B2E2926, 0x2C2D2B2A, 0x2D2B2E30, 0x2E2A3134, 0x31322B2A, 0x32312E2E, 0x332F3134, 0x342F3338, 0x36362E2E, 0x37353032, 0x39343338, 0x3A33363C, 0x3C3A3032, 0x3D393236, 0x3E38363C, 0x3F373840, 0x423E3337, 0x433E353B, 0x453C3841, 0x463B3A45, 0x1A24251B, 0x1B24271F, 0x1D222B25, 0x1E212D29, 0x2029281F, 0x21282A23, 0x22262D29, 0x23252F2D, 0x262D2A23, 0x272C2C27, 0x282A2F2D, 0x292A3231, 0x2C312C27, 0x2C302F2B, 0x2E2F3231, 0x2F2E3435, 0x31352F2B, 0x3234312F, 0x34333435, 0x35323739, 0x3739312F, 0x38383333, 0x39373739, 0x3A36393D, 0x3D3D3433, 0x3E3C3637, 0x3F3B393D, 0x403A3B41, 0x43423637, 0x4441383B, 0x453F3C42, 0x463F3E46, 0x1B28291C, 0x1C272B20, 0x1D252E26, 0x1E25302A, 0x212C2B20, 0x222B2D24, 0x232A312A, 0x2429332E, 0x26302D24, 0x272F3028, 0x292E332E, 0x2A2D3532, 0x2C343028, 0x2D33322C, 0x2F323532, 0x30313836, 0x3238322C, 0x33373430, 0x34363836, 0x35353A3A, 0x383C3530, 0x393B3734, 0x3A3A3A3A, 0x3B393C3E, 0x3D403734, 0x3E403938, 0x403E3C3E, 0x413D3F42, 0x44453A38, 0x45443C3C, 0x46433F42, 0x47424147, 0x1C2B2C1D, 0x1D2A2E21, 0x1E293227, 0x1F28342B, 0x212F2E21, 0x222E3125, 0x242D342B, 0x252C362F, 0x27333125, 0x28323329, 0x2A31362F, 0x2B303933, 0x2D373329, 0x2E36352D, 0x2F353933, 0x30343B37, 0x333B362D, 0x343B3831, 0x35393B37, 0x36383D3B, 0x38403831, 0x393F3A35, 0x3B3D3E3B, 0x3C3C403F, 0x3E443A35, 0x3F433D39, 0x4141403F, 0x42414243, 0x44483D39, 0x45473F3D, 0x47464243, 0x48454548, 0x1C2E301E, 0x1D2E3222, 0x1F2C3528, 0x202B382C, 0x22333222, 0x23323426, 0x2530382C, 0x262F3A30, 0x28373526, 0x2936372A, 0x2A343A30, 0x2B343C34, 0x2E3B372A, 0x2F3A392E, 0x30393C34, 0x31383F38, 0x333F392E, 0x343E3C32, 0x363D3F38, 0x373C413C, 0x39433C32, 0x3A423E36, 0x3C41413C, 0x3D404440, 0x3F473E36, 0x4046403A, 0x41454440, 0x42444644, 0x454C413A, 0x464B433E, 0x47494644, 0x49494949, }; // PAL yuyv palette, must be in RAM const static DRAM_ATTR uint32_t pal_yuyv[] = { 0x18181818, 0x1A16191E, 0x1E121A26, 0x21101A2C, 0x1E1D1A1B, 0x211B1A20, 0x25171B29, 0x27151C2E, 0x25231B1E, 0x27201C23, 0x2B1D1D2B, 0x2E1A1E31, 0x2B281D20, 0x2E261E26, 0x31221F2E, 0x34202034, 0x322D1F23, 0x342B2029, 0x38282131, 0x3A252137, 0x38332126, 0x3A30212B, 0x3E2D2234, 0x412A2339, 0x3E382229, 0x4136232E, 0x44322436, 0x4730253C, 0x453E242C, 0x483C2531, 0x4B382639, 0x4E36273F, 0x171B1D19, 0x1A181E1F, 0x1D151F27, 0x20121F2D, 0x1E201F1C, 0x201E1F22, 0x241A202A, 0x26182130, 0x2425201F, 0x27232124, 0x2A20222D, 0x2D1D2332, 0x2A2B2222, 0x2D282327, 0x3125242F, 0x33222435, 0x31302424, 0x332E242A, 0x372A2632, 0x3A282638, 0x37362627, 0x3A33262D, 0x3D302735, 0x402D283B, 0x3E3B272A, 0x4039282F, 0x44352938, 0x46332A3D, 0x4441292D, 0x473E2A32, 0x4B3B2B3B, 0x4D382C40, 0x171D221B, 0x191B2220, 0x1D182329, 0x1F15242E, 0x1D23231E, 0x1F202423, 0x231D252B, 0x261A2631, 0x23282520, 0x26262626, 0x2A22272E, 0x2C202834, 0x2A2E2723, 0x2C2B2829, 0x30282931, 0x33252937, 0x30332926, 0x3331292B, 0x362D2A34, 0x392B2B39, 0x36382A29, 0x39362B2E, 0x3D322C36, 0x3F302D3C, 0x3D3E2C2B, 0x3F3B2D31, 0x43382E39, 0x46352F3F, 0x44432E2E, 0x46412F34, 0x4A3E303C, 0x4D3B3042, 0x1620271C, 0x181E2722, 0x1C1A282A, 0x1F182930, 0x1C26281F, 0x1F232924, 0x22202A2D, 0x251D2B32, 0x232B2A22, 0x25292B27, 0x29252C30, 0x2B232C35, 0x29302C24, 0x2C2E2C2A, 0x2F2A2D32, 0x32282E38, 0x2F362D27, 0x32332E2D, 0x36302F35, 0x382D303B, 0x363B2F2A, 0x38393030, 0x3C353138, 0x3F33323E, 0x3C40312D, 0x3F3E3232, 0x423A333B, 0x45383340, 0x43463330, 0x46443435, 0x4940353E, 0x4C3E3543, 0x15232B1E, 0x18212C23, 0x1B1D2D2B, 0x1E1B2E31, 0x1C282D20, 0x1E262E26, 0x22222F2E, 0x24202F34, 0x222E2F23, 0x242B3029, 0x28283131, 0x2B253137, 0x28333126, 0x2B31312B, 0x2F2D3234, 0x312B3339, 0x2F383229, 0x3136332E, 0x35323436, 0x3730353C, 0x353E342B, 0x383B3531, 0x3B383639, 0x3E35363F, 0x3B43362E, 0x3E413634, 0x423D373C, 0x443B3842, 0x42493831, 0x45473837, 0x4943393F, 0x4B413A45, 0x1526301F, 0x17233125, 0x1B20322D, 0x1D1D3333, 0x1B2B3222, 0x1D293327, 0x21253430, 0x24233435, 0x21303425, 0x242E342A, 0x272A3532, 0x2A283638, 0x28363527, 0x2A33362D, 0x2E303735, 0x302D383B, 0x2E3B372A, 0x30393830, 0x34353938, 0x37333A3E, 0x3440392D, 0x373E3A32, 0x3B3B3B3B, 0x3D383B40, 0x3B463B30, 0x3D433B35, 0x41403C3D, 0x443D3D43, 0x424C3D33, 0x44493D38, 0x48463E40, 0x4A433F46, 0x14283520, 0x16263626, 0x1A23372E, 0x1D203734, 0x1A2E3723, 0x1D2B3729, 0x20283831, 0x23253937, 0x21333826, 0x2331392B, 0x272D3A34, 0x292B3B39, 0x27383A29, 0x29363B2E, 0x2D333C36, 0x30303D3C, 0x2D3E3C2B, 0x303B3D31, 0x34383E39, 0x36363E3F, 0x34433E2E, 0x36413E34, 0x3A3D3F3C, 0x3C3B4042, 0x3A493F31, 0x3D464036, 0x4043413F, 0x43404244, 0x414E4134, 0x434C4239, 0x47484342, 0x4A464447, 0x132B3A22, 0x16293B27, 0x19253C30, 0x1C233D35, 0x19313C25, 0x1C2E3D2A, 0x202B3E32, 0x22283E38, 0x20363E27, 0x22343E2D, 0x26303F35, 0x292E403B, 0x263B3F2A, 0x29394030, 0x2C364138, 0x2F33423E, 0x2D41412D, 0x2F3E4232, 0x333B433B, 0x35384440, 0x33464330, 0x35444435, 0x3940453E, 0x3C3E4543, 0x394C4533, 0x3C494538, 0x40464640, 0x42434746, 0x40514735, 0x434F473B, 0x464B4843, 0x49494949, //odd 0x18181818, 0x19161A1E, 0x1A121E26, 0x1A10212C, 0x1A1D1E1B, 0x1A1B2120, 0x1B172529, 0x1C15272E, 0x1B23251E, 0x1C202723, 0x1D1D2B2B, 0x1E1A2E31, 0x1D282B20, 0x1E262E26, 0x1F22312E, 0x20203434, 0x1F2D3223, 0x202B3429, 0x21283831, 0x21253A37, 0x21333826, 0x21303A2B, 0x222D3E34, 0x232A4139, 0x22383E29, 0x2336412E, 0x24324436, 0x2530473C, 0x243E452C, 0x253C4831, 0x26384B39, 0x27364E3F, 0x1D1B1719, 0x1E181A1F, 0x1F151D27, 0x1F12202D, 0x1F201E1C, 0x1F1E2022, 0x201A242A, 0x21182630, 0x2025241F, 0x21232724, 0x22202A2D, 0x231D2D32, 0x222B2A22, 0x23282D27, 0x2425312F, 0x24223335, 0x24303124, 0x242E332A, 0x262A3732, 0x26283A38, 0x26363727, 0x26333A2D, 0x27303D35, 0x282D403B, 0x273B3E2A, 0x2839402F, 0x29354438, 0x2A33463D, 0x2941442D, 0x2A3E4732, 0x2B3B4B3B, 0x2C384D40, 0x221D171B, 0x221B1920, 0x23181D29, 0x24151F2E, 0x23231D1E, 0x24201F23, 0x251D232B, 0x261A2631, 0x25282320, 0x26262626, 0x27222A2E, 0x28202C34, 0x272E2A23, 0x282B2C29, 0x29283031, 0x29253337, 0x29333026, 0x2931332B, 0x2A2D3634, 0x2B2B3939, 0x2A383629, 0x2B36392E, 0x2C323D36, 0x2D303F3C, 0x2C3E3D2B, 0x2D3B3F31, 0x2E384339, 0x2F35463F, 0x2E43442E, 0x2F414634, 0x303E4A3C, 0x303B4D42, 0x2720161C, 0x271E1822, 0x281A1C2A, 0x29181F30, 0x28261C1F, 0x29231F24, 0x2A20222D, 0x2B1D2532, 0x2A2B2322, 0x2B292527, 0x2C252930, 0x2C232B35, 0x2C302924, 0x2C2E2C2A, 0x2D2A2F32, 0x2E283238, 0x2D362F27, 0x2E33322D, 0x2F303635, 0x302D383B, 0x2F3B362A, 0x30393830, 0x31353C38, 0x32333F3E, 0x31403C2D, 0x323E3F32, 0x333A423B, 0x33384540, 0x33464330, 0x34444635, 0x3540493E, 0x353E4C43, 0x2B23151E, 0x2C211823, 0x2D1D1B2B, 0x2E1B1E31, 0x2D281C20, 0x2E261E26, 0x2F22222E, 0x2F202434, 0x2F2E2223, 0x302B2429, 0x31282831, 0x31252B37, 0x31332826, 0x31312B2B, 0x322D2F34, 0x332B3139, 0x32382F29, 0x3336312E, 0x34323536, 0x3530373C, 0x343E352B, 0x353B3831, 0x36383B39, 0x36353E3F, 0x36433B2E, 0x36413E34, 0x373D423C, 0x383B4442, 0x38494231, 0x38474537, 0x3943493F, 0x3A414B45, 0x3026151F, 0x31231725, 0x32201B2D, 0x331D1D33, 0x322B1B22, 0x33291D27, 0x34252130, 0x34232435, 0x34302125, 0x342E242A, 0x352A2732, 0x36282A38, 0x35362827, 0x36332A2D, 0x37302E35, 0x382D303B, 0x373B2E2A, 0x38393030, 0x39353438, 0x3A33373E, 0x3940342D, 0x3A3E3732, 0x3B3B3B3B, 0x3B383D40, 0x3B463B30, 0x3B433D35, 0x3C40413D, 0x3D3D4443, 0x3D4C4233, 0x3D494438, 0x3E464840, 0x3F434A46, 0x35281420, 0x36261626, 0x37231A2E, 0x37201D34, 0x372E1A23, 0x372B1D29, 0x38282031, 0x39252337, 0x38332126, 0x3931232B, 0x3A2D2734, 0x3B2B2939, 0x3A382729, 0x3B36292E, 0x3C332D36, 0x3D30303C, 0x3C3E2D2B, 0x3D3B3031, 0x3E383439, 0x3E36363F, 0x3E43342E, 0x3E413634, 0x3F3D3A3C, 0x403B3C42, 0x3F493A31, 0x40463D36, 0x4143403F, 0x42404344, 0x414E4134, 0x424C4339, 0x43484742, 0x44464A47, 0x3A2B1322, 0x3B291627, 0x3C251930, 0x3D231C35, 0x3C311925, 0x3D2E1C2A, 0x3E2B2032, 0x3E282238, 0x3E362027, 0x3E34222D, 0x3F302635, 0x402E293B, 0x3F3B262A, 0x40392930, 0x41362C38, 0x42332F3E, 0x41412D2D, 0x423E2F32, 0x433B333B, 0x44383540, 0x43463330, 0x44443535, 0x4540393E, 0x453E3C43, 0x454C3933, 0x45493C38, 0x46464040, 0x47434246, 0x47514035, 0x474F433B, 0x484B4643, 0x49494949, }; //==================================================================================================== //==================================================================================================== uint32_t cpu_ticks() { return xthal_get_ccount(); } uint32_t us() { return cpu_ticks() / 240; } // Color clock frequency is 315/88 (3.57954545455) // DAC_MHZ is 315/11 or 8x color clock // 455/2 color clocks per line, round up to maintain phase // HSYNCH period is 44/315*455 or 63.55555..us // Field period is 262*44/315*455 or 16651.5555us #define IRE(_x) ((uint32_t)(((_x)+40)*255/3.3/147.5) << 8) // 3.3V DAC #define SYNC_LEVEL IRE(-40) #define BLANKING_LEVEL IRE(0) #define BLACK_LEVEL IRE(7.5) #define GRAY_LEVEL IRE(50) #define WHITE_LEVEL IRE(100) #define P0 (color >> 16) #define P1 (color >> 8) #define P2 (color) #define P3 (color << 8) // Double-buffering: _bufferA and _bufferB will be swapped back and forth. static uint8_t** _bufferA; static uint8_t** _bufferB; // _lines may point to either _bufferA or _bufferB, depending on which is being displayed // _backBuffer points to whichever one _lines is not pointing to static uint8_t** _lines; // Front buffer currently on display static uint8_t** _backBuffer; // Back buffer waiting to be swapped to front // TRUE when _backBuffer is ready to go. static bool _swapReady; // Notification handle once front and back buffers have been swapped. static TaskHandle_t _swapCompleteNotify; // Number of swaps completed static uint32_t _swap_counter = 0; volatile int _line_counter = 0; volatile uint32_t _frame_counter = 0; int _active_lines; int _line_count; int _line_width; int _samples_per_cc; const uint32_t* _palette; float _sample_rate; int _hsync; int _hsync_long; int _hsync_short; int _burst_start; int _burst_width; int _active_start; int16_t* _burst0 = 0; // pal bursts int16_t* _burst1 = 0; static int usec(float us) { uint32_t r = (uint32_t)(us * _sample_rate); return ((r + _samples_per_cc) / (_samples_per_cc << 1)) * (_samples_per_cc << 1); // multiple of color clock, word align } #define NTSC_COLOR_CLOCKS_PER_SCANLINE 228 // really 227.5 for NTSC but want to avoid half phase fiddling for now #define NTSC_FREQUENCY (315000000.0/88) #define NTSC_LINES 262 #define PAL_COLOR_CLOCKS_PER_SCANLINE 284 // really 283.75 ? #define PAL_FREQUENCY 4433618.75 #define PAL_LINES 312 void pal_init(); void video_init(int samples_per_cc, int ntsc) { _samples_per_cc = samples_per_cc; if (ntsc) { _sample_rate = 315.0 / 88 * samples_per_cc; // DAC rate _line_width = NTSC_COLOR_CLOCKS_PER_SCANLINE * samples_per_cc; _line_count = NTSC_LINES; _hsync_long = usec(63.555 - 4.7); _active_start = usec(samples_per_cc == 4 ? 10 : 10.5); _hsync = usec(4.7); _palette = ntsc_RGB332; _pal_ = 0; } else { pal_init(); _palette = pal_yuyv; _pal_ = 1; } _active_lines = 240; video_init_hw(_line_width, _samples_per_cc); // init the hardware } //=================================================================================================== //=================================================================================================== // PAL void pal_init() { int cc_width = 4; _sample_rate = PAL_FREQUENCY * cc_width / 1000000.0; // DAC rate in mhz _line_width = PAL_COLOR_CLOCKS_PER_SCANLINE * cc_width; _line_count = PAL_LINES; _hsync_short = usec(2); _hsync_long = usec(30); _hsync = usec(4.7); _burst_start = usec(5.6); _burst_width = (int)(10 * cc_width + 4) & 0xFFFE; _active_start = usec(10.4); // make colorburst tables for even and odd lines _burst0 = new int16_t[_burst_width]; _burst1 = new int16_t[_burst_width]; float phase = 2 * M_PI / 2; for (int i = 0; i < _burst_width; i++) { _burst0[i] = BLANKING_LEVEL + sin(phase + 3 * M_PI / 4) * BLANKING_LEVEL / 1.5; _burst1[i] = BLANKING_LEVEL + sin(phase - 3 * M_PI / 4) * BLANKING_LEVEL / 1.5; phase += 2 * M_PI / cc_width; } } void IRAM_ATTR blit_pal(uint8_t* src, uint16_t* dst) { uint32_t c, color; bool even = _line_counter & 1; const uint32_t* p = even ? _palette : _palette + 256; int left = 0; int right = 256; uint8_t mask = 0xFF; uint8_t c0, c1, c2, c3, c4; uint8_t y1, y2, y3; // 192 of 288 color clocks wide: roughly correct aspect ratio dst += 88; // 4 pixels over 3 color clocks, 12 samples // do the blitting for (int i = left; i < right; i += 4) { c = *((uint32_t*)(src + i)); color = p[c & mask]; dst[0 ^ 1] = P0; dst[1 ^ 1] = P1; dst[2 ^ 1] = P2; color = p[(c >> 8) & mask]; dst[3 ^ 1] = P3; dst[4 ^ 1] = P0; dst[5 ^ 1] = P1; color = p[(c >> 16) & mask]; dst[6 ^ 1] = P2; dst[7 ^ 1] = P3; dst[8 ^ 1] = P0; color = p[(c >> 24) & mask]; dst[9 ^ 1] = P1; dst[10 ^ 1] = P2; dst[11 ^ 1] = P3; dst += 12; } } void IRAM_ATTR burst_pal(uint16_t* line) { line += _burst_start; int16_t* b = (_line_counter & 1) ? _burst0 : _burst1; for (int i = 0; i < _burst_width; i += 2) { line[i ^ 1] = b[i]; line[(i + 1) ^ 1] = b[i + 1]; } } //=================================================================================================== //=================================================================================================== // ntsc tables // AA AA // 2 pixels, 1 color clock - atari // AA AB BB // 3 pixels, 2 color clocks - nes // AAA ABB BBC CCC // 4 pixels, 3 color clocks - sms // cc == 3 gives 684 samples per line, 3 samples per cc, 3 pixels for 2 cc // cc == 4 gives 912 samples per line, 4 samples per cc, 2 pixels per cc #ifdef PERF #define BEGIN_TIMING() uint32_t t = cpu_ticks() #define END_TIMING() t = cpu_ticks() - t; _blit_ticks_min = min(_blit_ticks_min,t); _blit_ticks_max = max(_blit_ticks_max,t); #define ISR_BEGIN() uint32_t t = cpu_ticks() #define ISR_END() t = cpu_ticks() - t;_isr_us += (t+120)/240; uint32_t _blit_ticks_min = 0; uint32_t _blit_ticks_max = 0; uint32_t _isr_us = 0; #else #define BEGIN_TIMING() #define END_TIMING() #define ISR_BEGIN() #define ISR_END() #endif // draw a line of game in NTSC void IRAM_ATTR blit(uint8_t* src, uint16_t* dst) { uint32_t* d = (uint32_t*)dst; const uint32_t* p = _palette; uint32_t color, c; uint32_t mask = 0xFF; int i; BEGIN_TIMING(); if (_pal_) { blit_pal(src, dst); END_TIMING(); return; } // AAA ABB BBC CCC // 4 pixels, 3 color clocks, 4 samples per cc // each pixel gets 3 samples, 192 color clocks wide for (i = 0; i < 256; i += 4) { c = *((uint32_t*)(src + i)); color = p[c & mask]; dst[0 ^ 1] = P0; dst[1 ^ 1] = P1; dst[2 ^ 1] = P2; color = p[(c >> 8) & mask]; dst[3 ^ 1] = P3; dst[4 ^ 1] = P0; dst[5 ^ 1] = P1; color = p[(c >> 16) & mask]; dst[6 ^ 1] = P2; dst[7 ^ 1] = P3; dst[8 ^ 1] = P0; color = p[(c >> 24) & mask]; dst[9 ^ 1] = P1; dst[10 ^ 1] = P2; dst[11 ^ 1] = P3; dst += 12; } END_TIMING(); } void IRAM_ATTR burst(uint16_t* line) { if (_pal_) { burst_pal(line); return; } int i, phase; switch (_samples_per_cc) { case 4: // 4 samples per color clock for (i = _hsync; i < _hsync + (4 * 10); i += 4) { line[i + 1] = BLANKING_LEVEL; line[i + 0] = BLANKING_LEVEL + BLANKING_LEVEL / 2; line[i + 3] = BLANKING_LEVEL; line[i + 2] = BLANKING_LEVEL - BLANKING_LEVEL / 2; } break; case 3: // 3 samples per color clock phase = 0.866025 * BLANKING_LEVEL / 2; for (i = _hsync; i < _hsync + (3 * 10); i += 6) { line[i + 1] = BLANKING_LEVEL; line[i + 0] = BLANKING_LEVEL + phase; line[i + 3] = BLANKING_LEVEL - phase; line[i + 2] = BLANKING_LEVEL; line[i + 5] = BLANKING_LEVEL + phase; line[i + 4] = BLANKING_LEVEL - phase; } break; } } void IRAM_ATTR sync(uint16_t* line, int syncwidth) { for (int i = 0; i < syncwidth; i++) line[i] = SYNC_LEVEL; } void IRAM_ATTR blanking(uint16_t* line, bool vbl) { int syncwidth = vbl ? _hsync_long : _hsync; sync(line, syncwidth); for (int i = syncwidth; i < _line_width; i++) line[i] = BLANKING_LEVEL; if (!vbl) burst(line); // no burst during vbl } // Fancy pal non-interlace // http://martin.hinner.info/vga/pal.html void IRAM_ATTR pal_sync2(uint16_t* line, int width, int swidth) { swidth = swidth ? _hsync_long : _hsync_short; int i; for (i = 0; i < swidth; i++) line[i] = SYNC_LEVEL; for (; i < width; i++) line[i] = BLANKING_LEVEL; } uint8_t DRAM_ATTR _sync_type[8] = {0, 0, 0, 3, 3, 2, 0, 0}; void IRAM_ATTR pal_sync(uint16_t* line, int i) { uint8_t t = _sync_type[i - 304]; pal_sync2(line, _line_width / 2, t & 2); pal_sync2(line + _line_width / 2, _line_width / 2, t & 1); } // Wait for front and back buffers to swap before starting drawing void video_sync() { if (!_lines) return; ulTaskNotifyTake(pdTRUE, portMAX_DELAY); } // Workhorse ISR handles audio and video updates extern ""C"" void IRAM_ATTR video_isr(volatile void* vbuf) { if (!_lines) return; ISR_BEGIN(); int i = _line_counter++; uint16_t* buf = (uint16_t*)vbuf; if (_pal_) { // pal if (i < 32) { blanking(buf, false); // pre render/black 0-32 } else if (i < _active_lines + 32) { // active video 32-272 sync(buf, _hsync); burst(buf); blit(_lines[i - 32], buf + _active_start); } else if (i < 304) { // post render/black 272-304 blanking(buf, false); } else { pal_sync(buf, i); // 8 lines of sync 304-312 } } else { // ntsc if (i < _active_lines) { // active video sync(buf, _hsync); burst(buf); blit(_lines[i], buf + _active_start); } else if (i < (_active_lines + 5)) { // post render/black blanking(buf, false); } else if (i < (_active_lines + 8)) { // vsync blanking(buf, true); } else { // pre render/black blanking(buf, false); } } if (_line_counter == _line_count) { _line_counter = 0; // frame is done _frame_counter++; // Is the back buffer ready to go? if (_swapReady) { // Swap front and back buffers if (_lines == _bufferA) { _lines = _bufferB; _backBuffer = _bufferA; } else { _lines = _bufferA; _backBuffer = _bufferB; } _swapReady = false; _swap_counter++; // Signal video_sync() swap has completed vTaskNotifyGiveFromISR( _swapCompleteNotify, NULL); } } ISR_END(); } //=================================================================================================== //=================================================================================================== // Wrapper class /* @brief Constructor for ESP_8_BIT composite video wrapper class @param ntsc True (or nonzero) for NTSC mode, False (or zero) for PAL mode */ ESP_8_BIT_composite::ESP_8_BIT_composite(int ntsc) { _pal_ = !ntsc; if (NULL == _instance_) { _instance_ = this; } _started = false; _bufferA = NULL; _bufferB = NULL; } /* @brief Destructor for ESP_8_BIT composite video wrapper class. */ ESP_8_BIT_composite::~ESP_8_BIT_composite() { if (_bufferA) { frameBufferFree(_bufferA); _bufferA = NULL; } if (_bufferB) { frameBufferFree(_bufferB); _bufferB = NULL; } if (_started) { // Free resources by mirroring everything allocated in start_dma() esp_intr_disable(_isr_handle); dac_i2s_disable(); // dac_output_disable(DAC_CHANNEL_1); dac_output_disable(_dac_ch); // @chrmlinux03 if (!_pal_) { rtc_clk_apll_enable(false, 0x46, 0x97, 0x4, 1); } else { rtc_clk_apll_enable(false, 0x04, 0xA4, 0x6, 1); } for (int i = 0; i < 2; i++) { heap_caps_free((void*)(_dma_desc[i].buf)); _dma_desc[i].buf = NULL; } // Missing: There doesn't seem to be a esp_intr_free() to go with esp_intr_alloc()? periph_module_disable(PERIPH_I2S0_MODULE); _started = false; } _lines = NULL; _backBuffer = NULL; _instance_ = NULL; } /* @brief Check to ensure this instance is the first and only allowed instance */ void ESP_8_BIT_composite::instance_check() { if (_instance_ != this) { ESP_LOGE(TAG, ""Only one instance of ESP_8_BIT_composite class is allowed.""); ESP_ERROR_CHECK(ESP_FAIL); } } /* @brief Video subsystem setup: allocate frame buffer and start engine */ void ESP_8_BIT_composite::begin(dac_channel_t dac_ch) { instance_check(); _dac_ch = dac_ch; if (_started) { ESP_LOGE(TAG, ""begin() is only allowed to be called once.""); ESP_ERROR_CHECK(ESP_FAIL); } _started = true; _bufferA = frameBufferAlloc(); _bufferB = frameBufferAlloc(); _lines = _bufferA; _backBuffer = _bufferB; // Initialize double-buffering infrastructure _swapReady = false; _swapCompleteNotify = xTaskGetCurrentTaskHandle(); // Start video signal generator video_init(4, !_pal_); } ///////////////////////////////////////////////////////////////////////////// // // Frame buffer memory allocation notes // // Architecture can tolerate each _line[i] being a separate chunk of memory // but allocating in tiny 256 byte chunks is inefficient. (16 bytes of // overhead per allocation.) On the opposite end, allocating the entire // buffer at once (256*240 = 60kB) demands a large contiguous chunk of // memory which might not exist if memory space is fragmented. // // Compromise: Allocate frame buffer in 4kB chunks. This means each // frame buffer is made of 15 4kB chunks instead of a single 60kB chunk. // // 14 extra allocations * 16 byte overhead = 224 extra bytes, worth it. const uint16_t linesPerFrame = 240; const uint16_t bytesPerLine = 256; const uint16_t linesPerChunk = 16; const uint16_t chunkSize = bytesPerLine * linesPerChunk; const uint16_t chunksPerFrame = 15; /* @brief Allocate memory for frame buffer */ uint8_t** ESP_8_BIT_composite::frameBufferAlloc() { uint8_t** lineArray = NULL; uint8_t* lineChunk = NULL; uint8_t* lineStep = NULL; lineArray = new uint8_t*[linesPerFrame]; if ( NULL == lineArray ) { ESP_LOGE(TAG, ""Frame lines array allocation fail""); ESP_ERROR_CHECK(ESP_FAIL); } for (uint8_t chunk = 0; chunk < chunksPerFrame; chunk++) { lineChunk = new uint8_t[chunkSize]; if ( NULL == lineChunk ) { ESP_LOGE(TAG, ""Frame buffer chunk allocation fail""); ESP_ERROR_CHECK(ESP_FAIL); } lineStep = lineChunk; for (uint8_t lineIndex = 0; lineIndex < linesPerChunk; lineIndex++) { lineArray[(chunk * linesPerChunk) + lineIndex] = lineStep; lineStep += bytesPerLine; } } return lineArray; } /* @brief Free memory allocated by frameBufferAlloc(); */ void ESP_8_BIT_composite::frameBufferFree(uint8_t** lineArray) { for (uint8_t chunk = 0; chunk < chunksPerFrame; chunk++) { free(lineArray[chunk * linesPerChunk]); } free(lineArray); } /* @brief Wait for current frame to finish rendering */ void ESP_8_BIT_composite::waitForFrame() { instance_check(); _swapReady = true; video_sync(); } /* @brief Retrieve pointer to frame buffer lines array */ uint8_t** ESP_8_BIT_composite::getFrameBufferLines() { instance_check(); return _backBuffer; } /* @brief Number of frames sent to screen */ uint32_t ESP_8_BIT_composite::getRenderedFrameCount() { return _frame_counter; } /* @brief Number of buffer swaps performed */ uint32_t ESP_8_BIT_composite::getBufferSwapCount() { return _swap_counter; } ",16157,True,3094.6589353217746,median "//****************************************************************************** // Copyright (c) Microsoft Corporation. All rights reserved. // ttsmarkup.cpp // //****************************************************************************** #include ""TTSComp.h"" //****************************************************************************** //***** Internal Functions //****************************************************************************** #include ""f0.h"" int ComputeF0 (float* data, int nData, int sampFreq, int minF0, int maxF0, int feaSampFreq, float** f0, int* nF0, float **pRms, int *nRms) { char parStr[128]; F0Data f0Obj = NULL; F0Out f0Frame; int buffSize; int buffStep; int nFrames; int remainder; int nOutput; int outSampNum; int i; int j; // assert (data); // assert (nData>0); // assert (sampFreq); // assert (feaSampFreq); // assert (f0); /* * Create and initialize the f0 object */ if ((f0Obj = F0_NewF0Obj ()) == NULL) { goto error; } sprintf (parStr ,""frame_step=%f"", 1.0/feaSampFreq); if (!F0_ParseParameter (f0Obj, parStr)) { goto error; } sprintf (parStr ,""min_f0=%f"", (float)minF0); if (!F0_ParseParameter (f0Obj, parStr)) { goto error; } sprintf (parStr ,""max_f0=%f"", (float)maxF0); if (!F0_ParseParameter (f0Obj, parStr)) { goto error; } if (!F0_Init (f0Obj, sampFreq, &buffSize, &buffStep)) { goto error; } /* * Prepare memory for output */ *nF0 = *nRms = (int) (((nData / (float)sampFreq) * feaSampFreq) + 0.5); *f0 = NULL; *pRms = NULL; if ( (*f0 = (float *) malloc(*nF0 * sizeof(**f0))) == NULL) { goto error; } if ( (*pRms = (float *) malloc(*nRms * sizeof(**pRms))) == NULL) { goto error; } /* * Start processing */ nFrames = (nData - buffSize) / buffStep + 1; remainder = nData - nFrames*buffStep; outSampNum = 0; /* Iterate over number of frames*/ for (i = 0; i cpLocalVoice; // Create the SAPI voice DOCHECKHRGOTO (hr = cpLocalVoice.CoCreateInstance( CLSID_SpVoice );); tpr = t_XMLBookmark_Test(uMsg, tpParam, lpFTE, cpLocalVoice, false); EXIT: return tpr; } //******************************************************************************** TESTPROCAPI t_XMLBookmark_Test(UINT uMsg, TPPARAM tpParam, LPFUNCTION_TABLE_ENTRY lpFTE, ISpVoice *cpVoice, bool bCalledByMulti) { // This test passes a Bookmark through XML marked up text to a TTS engine and checks // to make sure a SPFEI_BOOKMARK event has fired. // Message check if (uMsg != TPM_EXECUTE) { return TPR_NOT_HANDLED; } HRESULT hr = S_OK; int tpr = TPR_PASS; BOOL bGetEvents = true; WCHAR szwSpeakStr[MAX_PATH]=L""""; WCHAR szwDebug[MAX_PATH]=L""""; DWORD dwEventsRetrieved = 0; WCHAR szwBmk[MAX_PATH]=L""""; if( SUCCEEDED( hr ) ) { hr = cpVoice->SetNotifyWin32Event(); } if( SUCCEEDED( hr ) ) { hr = cpVoice->SetInterest( SPFEI(SPEI_TTS_BOOKMARK), SPFEI(SPEI_TTS_BOOKMARK) ); } //clean up the event queue while( hr == S_OK ) { SPEVENT Event; hr = cpVoice->GetEvents (1, &Event, NULL); } CHECKHRId( hr, tpr, IDS_STRING120 ); if( SUCCEEDED( hr ) ) { GetWStrFromRes( IDS_STRING20, szwSpeakStr ); hr = cpVoice->Speak( szwSpeakStr, SPF_ASYNC | SPF_IS_XML, NULL ); } if( SUCCEEDED( hr ) ) { hr = cpVoice->WaitUntilDone( TTS_WAITTIME ); CHECKASSERTGOTOIdEx( (hr == S_OK), tpr, IDS_STRING61, "" in t_XMLBookmarkTest""); } while( hr == S_OK ) { SPEVENT Event; hr = cpVoice->GetEvents (1, &Event, NULL); if( hr == S_OK ) { // Record the events retrieved in dwFlagsRetrieved dwEventsRetrieved |= (DWORD)Event.eEventId; if (Event.eEventId == SPEI_TTS_BOOKMARK ) { //swprintf( szwBmk, L""%s, %d"", (WCHAR*)Event.lParam, Event.wParam ); //g_pKato->Comment(10, szwBmk); //verify bookmark string (lparam and wparam) GetWStrFromRes( IDS_STRING21, szwDebug ); CHECKASSERTGOTOId(( !wcscmp( (WCHAR*)Event.lParam, szwDebug ) ), tpr, IDS_STRING22); CHECKASSERTGOTOId(( Event.wParam == _wtol(szwDebug) ), tpr, IDS_STRING22); break; } } } // Logging info CHECKHRId( hr, tpr, IDS_STRING22 ); // Make sure correct events were retrieved CHECKASSERTGOTOId(((dwEventsRetrieved & SPEI_TTS_BOOKMARK) == SPEI_TTS_BOOKMARK), tpr, IDS_STRING22); EXIT: return tpr; } //******************************************************************************** TESTPROCAPI t_XMLSilence(UINT uMsg, TPPARAM tpParam, LPFUNCTION_TABLE_ENTRY lpFTE) { //This test Speaks with CONTEXT tag. // Message check if (uMsg != TPM_EXECUTE) { return TPR_NOT_HANDLED; } HRESULT hr = S_OK; int tpr = TPR_PASS; CComPtr cpLocalVoice; // Create the SAPI voice DOCHECKHRGOTO (hr = cpLocalVoice.CoCreateInstance( CLSID_SpVoice );); tpr = t_XMLSilence_Test(uMsg, tpParam, lpFTE, cpLocalVoice, false); EXIT: return tpr; } //******************************************************************************** TESTPROCAPI t_XMLSilence_Test(UINT uMsg, TPPARAM tpParam, LPFUNCTION_TABLE_ENTRY lpFTE, ISpVoice *cpVoice, bool bCalledByMulti) { // This test speaks 2 streams. One with a Silence pause and one without. It analyzes //the two streams to make sure a change has occured. This tests SILENCE tag. HRESULT hr = S_OK; int tpr = TPR_PASS; // Message check if (uMsg != TPM_EXECUTE) { return TPR_NOT_HANDLED; } CComPtr cpStream1; CComPtr cpStream2; STATSTG Stat; ULONG cSamples1=0, cSamples2=0; WCHAR szwSpeakStr[MAX_PATH]=L""""; WCHAR szwDebug[MAX_PATH]=L""""; const char * TEST_TOPIC = """"; //====================================================================== TEST_TOPIC = ""Initialization""; //====================================================================== CSpStreamFormat NewFmt(SPSF_22kHz16BitMono, &hr); CHECKHRGOTOIdEx(hr, tpr, IDS_STRING84, TEST_TOPIC ); //====================================================================== TEST_TOPIC = ""Stream 1 with no SILENCE tag""; //====================================================================== // Create stream #1 hr = SPCreateStreamOnHGlobal( NULL, true, NewFmt.FormatId(), NewFmt.WaveFormatExPtr(), &cpStream1 ); CHECKHRGOTOIdEx( hr, tpr, IDS_STRING81, TEST_TOPIC); // Set the default output format hr = cpVoice->SetOutput( cpStream1, TRUE); CHECKHRGOTOIdEx( hr, tpr, IDS_STRING60, TEST_TOPIC); hr = GetWStrFromRes( IDS_STRING23, szwSpeakStr ); CHECKHRGOTOIdEx( hr, tpr, IDS_STRING83, TEST_TOPIC); hr = cpVoice->Speak( szwSpeakStr, SPF_IS_XML, NULL ); CHECKHRGOTOIdEx( hr, tpr, IDS_STRING13, TEST_TOPIC); // Get stream size hr = cpStream1->Stat( &Stat, STATFLAG_NONAME ); CHECKHRGOTOIdEx(hr, tpr, IDS_STRING90, TEST_TOPIC ); cSamples1 = (ULONG)Stat.cbSize.QuadPart / sizeof(short); CHECKASSERTGOTOIdEx((cSamples1 > 0), tpr, IDS_STRING25, TEST_TOPIC ); //====================================================================== TEST_TOPIC = ""Stream 2 with SILENCE tag""; //====================================================================== // Create stream #1 hr = SPCreateStreamOnHGlobal( NULL, true, NewFmt.FormatId(), NewFmt.WaveFormatExPtr(), &cpStream2 ); CHECKHRGOTOIdEx( hr, tpr, IDS_STRING81, TEST_TOPIC); // Set the default output format hr = cpVoice->SetOutput( cpStream2, TRUE); CHECKHRGOTOIdEx( hr, tpr, IDS_STRING60, TEST_TOPIC); hr = GetWStrFromRes( IDS_STRING24, szwSpeakStr ); CHECKHRGOTOIdEx( hr, tpr, IDS_STRING83, TEST_TOPIC); hr = cpVoice->Speak( szwSpeakStr, SPF_IS_XML, NULL ); CHECKHRGOTOIdEx( hr, tpr, IDS_STRING13, TEST_TOPIC); // Get stream size hr = cpStream2->Stat( &Stat, STATFLAG_NONAME ); CHECKHRGOTOIdEx(hr, tpr, IDS_STRING90, TEST_TOPIC ); cSamples2 = (ULONG)Stat.cbSize.QuadPart / sizeof(short); CHECKASSERTGOTOIdEx((cSamples2 > 0), tpr, IDS_STRING25, TEST_TOPIC ); // Now compare the length of the 2 streams // Note - check to ensure cSamples2 is at least twice greater than cSamples1. CHECKASSERTId((cSamples2 > 2 * cSamples1), tpr, IDS_STRING25); EXIT: return tpr; } //******************************************************************************** TESTPROCAPI t_XMLSpell(UINT uMsg, TPPARAM tpParam, LPFUNCTION_TABLE_ENTRY lpFTE) { //This test Speaks with CONTEXT tag. // Message check if (uMsg != TPM_EXECUTE) { return TPR_NOT_HANDLED; } HRESULT hr = S_OK; int tpr = TPR_PASS; CComPtr cpLocalVoice; // Create the SAPI voice DOCHECKHRGOTO (hr = cpLocalVoice.CoCreateInstance( CLSID_SpVoice );); tpr = t_XMLSpell_Test(uMsg, tpParam, lpFTE, cpLocalVoice, false); EXIT: return tpr; } //******************************************************************************** TESTPROCAPI t_XMLSpell_Test(UINT uMsg, TPPARAM tpParam, LPFUNCTION_TABLE_ENTRY lpFTE, ISpVoice *cpVoice, bool bCalledByMulti) { // This test generates two streams. One that says English as a single word and one that // spells it out. It analyzes the produced .wav forms to make sure that the second streams // overall size is greater. HRESULT hr = S_OK; int tpr = TPR_PASS; // Message check if (uMsg != TPM_EXECUTE) { return TPR_NOT_HANDLED; } CComPtr cpStream1; CComPtr cpStream2; STATSTG Stat; LANGID LangID; ULONG cSamples1=0, cSamples2=0; WCHAR szwSpeakStr[MAX_PATH]=L""""; WCHAR szwDebug[MAX_PATH]=L""""; const char * TEST_TOPIC = """"; //====================================================================== TEST_TOPIC = ""Initialization""; //====================================================================== CSpStreamFormat NewFmt(SPSF_22kHz16BitMono, &hr); CHECKHRGOTOIdEx(hr, tpr, IDS_STRING84, TEST_TOPIC ); DOCHECKHRGOTO( hr = SpGetLanguageIdFromDefaultVoice(&LangID); ); //====================================================================== TEST_TOPIC = ""Stream 1 with no Spell tag""; //====================================================================== // Create stream #1 hr = SPCreateStreamOnHGlobal( NULL, true, NewFmt.FormatId(), NewFmt.WaveFormatExPtr(), &cpStream1 ); CHECKHRGOTOIdEx( hr, tpr, IDS_STRING81, TEST_TOPIC); // Set the default output format hr = cpVoice->SetOutput( cpStream1, TRUE); CHECKHRGOTOIdEx( hr, tpr, IDS_STRING60, TEST_TOPIC); hr = GetWStrFromRes( IDS_STRING26, szwSpeakStr ); CHECKHRGOTOIdEx( hr, tpr, IDS_STRING83, TEST_TOPIC); hr = cpVoice->Speak( szwSpeakStr, SPF_IS_XML, NULL ); CHECKHRGOTOIdEx( hr, tpr, IDS_STRING13, TEST_TOPIC); // Get stream size hr = cpStream1->Stat( &Stat, STATFLAG_NONAME ); CHECKHRGOTOIdEx(hr, tpr, IDS_STRING90, TEST_TOPIC ); cSamples1 = (ULONG)Stat.cbSize.QuadPart / sizeof(short); //====================================================================== TEST_TOPIC = ""Stream 2 with Spell tag""; //====================================================================== // Create stream #2 hr = SPCreateStreamOnHGlobal( NULL, true, NewFmt.FormatId(), NewFmt.WaveFormatExPtr(), &cpStream2 ); CHECKHRGOTOIdEx( hr, tpr, IDS_STRING81, TEST_TOPIC); // Set the default output format hr = cpVoice->SetOutput( cpStream2, TRUE); CHECKHRGOTOIdEx( hr, tpr, IDS_STRING60, TEST_TOPIC); hr = GetWStrFromRes( IDS_STRING27, szwSpeakStr ); CHECKHRGOTOIdEx( hr, tpr, IDS_STRING83, TEST_TOPIC); hr = cpVoice->Speak( szwSpeakStr, SPF_IS_XML, NULL ); CHECKHRGOTOIdEx( hr, tpr, IDS_STRING13, TEST_TOPIC); // Get stream size hr = cpStream2->Stat( &Stat, STATFLAG_NONAME ); CHECKHRGOTOIdEx(hr, tpr, IDS_STRING90, TEST_TOPIC ); cSamples2 = (ULONG)Stat.cbSize.QuadPart / sizeof(short); //For Chinese/Japanese TTS Engines, the test ignores result check since //Spell tag can be ignored in those languages if ( ( LangID != 2052 ) && ( LangID != 1041 )) { CHECKASSERTGOTOIdEx((cSamples2 != 0), tpr, IDS_STRING28, TEST_TOPIC ); CHECKASSERTGOTOIdEx((cSamples1 != 0), tpr, IDS_STRING28, TEST_TOPIC ); // Now compare the values from the 2 streams. // Note - check to ensure cSamples2 is at least 4/3 greater than cSamples1. CHECKASSERTId(((3 * cSamples2 )> (4 * cSamples1)), tpr, IDS_STRING28); } EXIT: return tpr; } //******************************************************************************** TESTPROCAPI t_XMLPronounce(UINT uMsg, TPPARAM tpParam, LPFUNCTION_TABLE_ENTRY lpFTE) { //This test Speaks with CONTEXT tag. // Message check if (uMsg != TPM_EXECUTE) { return TPR_NOT_HANDLED; } HRESULT hr = S_OK; int tpr = TPR_PASS; CComPtr cpLocalVoice; // Create the SAPI voice DOCHECKHRGOTO (hr = cpLocalVoice.CoCreateInstance( CLSID_SpVoice );); tpr = t_XMLPronounce_Test(uMsg, tpParam, lpFTE, cpLocalVoice, false); EXIT: return tpr; } //******************************************************************************** TESTPROCAPI t_XMLPronounce_Test(UINT uMsg, TPPARAM tpParam, LPFUNCTION_TABLE_ENTRY lpFTE, ISpVoice *cpVoice, bool bCalledByMulti) { // This test generates two streams. One that says ""a"" as a single word. The next stream // says ""a"" but tells the engine to pronounce it as a random long word. It analyzes the // produced .wav forms to make sure that the second stream's overall size is greater. HRESULT hr = S_OK; int tpr = TPR_PASS; // Message check if (uMsg != TPM_EXECUTE) { return TPR_NOT_HANDLED; } CComPtr cpStream1; CComPtr cpStream2; STATSTG Stat; ULONG cSamples1=0, cSamples2=0; WCHAR szwSpeakStr[MAX_PATH]=L""""; WCHAR szwDebug[MAX_PATH]=L""""; const char * TEST_TOPIC = """"; //====================================================================== TEST_TOPIC = ""Initialization""; //====================================================================== CSpStreamFormat NewFmt(SPSF_22kHz16BitMono, &hr); CHECKHRGOTOIdEx(hr, tpr, IDS_STRING84, TEST_TOPIC ); //====================================================================== TEST_TOPIC = ""Stream 1 with no PRON tag""; //====================================================================== // Create stream #1 hr = SPCreateStreamOnHGlobal( NULL, true, NewFmt.FormatId(), NewFmt.WaveFormatExPtr(), &cpStream1 ); CHECKHRGOTOIdEx( hr, tpr, IDS_STRING81, TEST_TOPIC); // Set the default output format hr = cpVoice->SetOutput( cpStream1, TRUE); CHECKHRGOTOIdEx( hr, tpr, IDS_STRING60, TEST_TOPIC); // short string hr = GetWStrFromRes( IDS_STRING56, szwSpeakStr ); CHECKHRGOTOIdEx( hr, tpr, IDS_STRING83, TEST_TOPIC); hr = cpVoice->Speak( szwSpeakStr, SPF_IS_XML, NULL ); CHECKHRGOTOIdEx( hr, tpr, IDS_STRING13, TEST_TOPIC); // Get stream size hr = cpStream1->Stat( &Stat, STATFLAG_NONAME ); CHECKHRGOTOIdEx(hr, tpr, IDS_STRING90, TEST_TOPIC ); cSamples1 = (ULONG)Stat.cbSize.QuadPart / sizeof(short); CHECKASSERTGOTOIdEx((cSamples1 != 0), tpr, IDS_STRING29, TEST_TOPIC ); //====================================================================== TEST_TOPIC = ""Stream 2 with PRON tag""; //====================================================================== // Create stream #2 hr = SPCreateStreamOnHGlobal( NULL, true, NewFmt.FormatId(), NewFmt.WaveFormatExPtr(), &cpStream2 ); CHECKHRGOTOIdEx( hr, tpr, IDS_STRING81, TEST_TOPIC); // Set the default output format hr = cpVoice->SetOutput( cpStream2, TRUE); CHECKHRGOTOIdEx( hr, tpr, IDS_STRING60, TEST_TOPIC); // short string pronounced as a long string hr = GetWStrFromRes( IDS_STRING57, szwSpeakStr ); CHECKHRGOTOIdEx( hr, tpr, IDS_STRING83, TEST_TOPIC); hr = cpVoice->Speak( szwSpeakStr, SPF_IS_XML, NULL ); CHECKHRGOTOIdEx( hr, tpr, IDS_STRING13, TEST_TOPIC); // Get stream size hr = cpStream2->Stat( &Stat, STATFLAG_NONAME ); CHECKHRGOTOIdEx(hr, tpr, IDS_STRING90, TEST_TOPIC ); cSamples2 = (ULONG)Stat.cbSize.QuadPart / sizeof(short); CHECKASSERTGOTOIdEx((cSamples2 != 0), tpr, IDS_STRING29, TEST_TOPIC ); // Now compare the values from the 2 streams // Note - check to ensure cSamples2 is at least twice greater than cSamples1. CHECKASSERTId((cSamples2> (2 * cSamples1)), tpr, IDS_STRING29); EXIT: return tpr; } //******************************************************************************** TESTPROCAPI t_XMLRate(UINT uMsg, TPPARAM tpParam, LPFUNCTION_TABLE_ENTRY lpFTE) { //This test Speaks with CONTEXT tag. // Message check if (uMsg != TPM_EXECUTE) { return TPR_NOT_HANDLED; } HRESULT hr = S_OK; int tpr = TPR_PASS; CComPtr cpLocalVoice; // Create the SAPI voice DOCHECKHRGOTO (hr = cpLocalVoice.CoCreateInstance( CLSID_SpVoice );); tpr = t_XMLRate_Test(uMsg, tpParam, lpFTE, cpLocalVoice, false); EXIT: return tpr; } //******************************************************************************** TESTPROCAPI t_XMLRate_Test(UINT uMsg, TPPARAM tpParam, LPFUNCTION_TABLE_ENTRY lpFTE, ISpVoice *cpVoice, bool bCalledByMulti) { // This test changes the rate of a TTS engine twice through XML and analyzes the // .wav form to make sure a change has occured. HRESULT hr = S_OK; int tpr = TPR_PASS; // Message check if (uMsg != TPM_EXECUTE) { return TPR_NOT_HANDLED; } CComPtr cpStream1; CComPtr cpStream2; STATSTG Stat; ULONG cSamples1=0, cSamples2=0; WCHAR szwSpeakStr[MAX_PATH]=L""""; WCHAR szwDebug[MAX_PATH]=L""""; const char * TEST_TOPIC = """"; //====================================================================== TEST_TOPIC = ""Initialization""; //====================================================================== CSpStreamFormat NewFmt(SPSF_22kHz16BitMono, &hr); CHECKHRGOTOIdEx(hr, tpr, IDS_STRING84, TEST_TOPIC ); //====================================================================== TEST_TOPIC = ""Stream 1 with rate set to -5""; //====================================================================== // Create stream #1 hr = SPCreateStreamOnHGlobal( NULL, true, NewFmt.FormatId(), NewFmt.WaveFormatExPtr(), &cpStream1 ); CHECKHRGOTOIdEx( hr, tpr, IDS_STRING81, TEST_TOPIC); // Set the default output format hr = cpVoice->SetOutput( cpStream1, TRUE); CHECKHRGOTOIdEx( hr, tpr, IDS_STRING60, TEST_TOPIC); hr = GetWStrFromRes( IDS_STRING30, szwSpeakStr ); CHECKHRGOTOIdEx( hr, tpr, IDS_STRING83, TEST_TOPIC); hr = cpVoice->Speak( szwSpeakStr, SPF_IS_XML, NULL ); CHECKHRGOTOIdEx( hr, tpr, IDS_STRING13, TEST_TOPIC); // Get stream size hr = cpStream1->Stat( &Stat, STATFLAG_NONAME ); CHECKHRGOTOIdEx(hr, tpr, IDS_STRING90, TEST_TOPIC ); cSamples1 = (ULONG)Stat.cbSize.QuadPart / sizeof(short); CHECKASSERTGOTOIdEx((cSamples1 != 0), tpr, IDS_STRING32, TEST_TOPIC ); //====================================================================== TEST_TOPIC = ""Stream 2 with rate set to 5""; //====================================================================== // Create stream #2 hr = SPCreateStreamOnHGlobal( NULL, true, NewFmt.FormatId(), NewFmt.WaveFormatExPtr(), &cpStream2 ); CHECKHRGOTOIdEx( hr, tpr, IDS_STRING81, TEST_TOPIC); // Set the default output format hr = cpVoice->SetOutput( cpStream2, TRUE); CHECKHRGOTOIdEx( hr, tpr, IDS_STRING60, TEST_TOPIC); hr = GetWStrFromRes( IDS_STRING31, szwSpeakStr ); CHECKHRGOTOIdEx( hr, tpr, IDS_STRING83, TEST_TOPIC); hr = cpVoice->Speak( szwSpeakStr, SPF_IS_XML, NULL ); CHECKHRGOTOIdEx( hr, tpr, IDS_STRING13, TEST_TOPIC); // Get stream size hr = cpStream2->Stat( &Stat, STATFLAG_NONAME ); CHECKHRGOTOIdEx(hr, tpr, IDS_STRING90, TEST_TOPIC ); cSamples2 = (ULONG)Stat.cbSize.QuadPart / sizeof(WCHAR); CHECKASSERTGOTOIdEx((cSamples2 != 0), tpr, IDS_STRING32, TEST_TOPIC ); // Now compare the values from the 2 streams // 1. First check ensures low rate has bigger cSamples than higher rate // 2. Secondly check ensures cSamples1 and cSamples2 has enough distance // CHECKASSERTId((cSamples1 > cSamples2 ), tpr, IDS_STRING32); EXIT: return tpr; } //******************************************************************************** TESTPROCAPI t_XMLVolume(UINT uMsg, TPPARAM tpParam, LPFUNCTION_TABLE_ENTRY lpFTE) { //This test Speaks with CONTEXT tag. // Message check if (uMsg != TPM_EXECUTE) { return TPR_NOT_HANDLED; } HRESULT hr = S_OK; int tpr = TPR_PASS; CComPtr cpLocalVoice; // Create the SAPI voice DOCHECKHRGOTO (hr = cpLocalVoice.CoCreateInstance( CLSID_SpVoice );); tpr = t_XMLVolume_Test(uMsg, tpParam, lpFTE, cpLocalVoice, false); EXIT: return tpr; } //******************************************************************************** TESTPROCAPI t_XMLVolume_Test(UINT uMsg, TPPARAM tpParam, LPFUNCTION_TABLE_ENTRY lpFTE, ISpVoice *cpVoice, bool bCalledByMulti) { // This test changes the volume of a TTS engine twice through XML and analyzes the // .wav form to make sure a change has occured. HRESULT hr = S_OK; int tpr = TPR_PASS; // Message check if (uMsg != TPM_EXECUTE) { return TPR_NOT_HANDLED; } CComPtr cpStream1; CComPtr cpStream2; ULONG cSamples=0; ULONG ulRatio=0; WCHAR szwSpeakStr[MAX_PATH]=L""""; ULONG totalAmp1 = 0, totalAmp2 = 0; WCHAR szwDebug[MAX_PATH]=L""""; const char * TEST_TOPIC = """"; CSpStreamFormat NewFmt(SPSF_22kHz16BitMono, &hr); CHECKHRGOTOId( hr, tpr, IDS_STRING84 ); //====================================================================== TEST_TOPIC = ""Stream 1 with Volume 100""; //====================================================================== //*** First stream with volume set to 100 // Create stream #1 hr = SPCreateStreamOnHGlobal( NULL, true, NewFmt.FormatId(), NewFmt.WaveFormatExPtr(), &cpStream1 ); CHECKHRGOTOIdEx( hr, tpr, IDS_STRING81, TEST_TOPIC); // Set the default output format hr = cpVoice->SetOutput( cpStream1, TRUE); CHECKHRGOTOIdEx( hr, tpr, IDS_STRING60, TEST_TOPIC); hr = GetWStrFromRes( IDS_STRING33, szwSpeakStr ); CHECKHRGOTOIdEx( hr, tpr, IDS_STRING83, TEST_TOPIC); hr = cpVoice->Speak( szwSpeakStr, SPF_IS_XML, NULL ); CHECKHRGOTOIdEx( hr, tpr, IDS_STRING13, TEST_TOPIC); LARGE_INTEGER l; l.QuadPart = 0; // Reset stream to beginning hr = cpStream1->Seek( l, SEEK_SET, NULL ); CHECKHRGOTOIdEx( hr, tpr, IDS_STRING79, TEST_TOPIC); // get the sum of the amplitude from the stream 1 hr = GetAmpFromSamples (cpStream1, &totalAmp1 ); CHECKHRGOTOIdEx(hr, tpr, IDS_STRING82, TEST_TOPIC ); //====================================================================== TEST_TOPIC = ""Stream 2 with Volume 1""; //====================================================================== //*** Second stream with volume set to 1 // Create stream #2 hr = SPCreateStreamOnHGlobal( NULL, true, NewFmt.FormatId(), NewFmt.WaveFormatExPtr(), &cpStream2 ); CHECKHRGOTOIdEx( hr, tpr, IDS_STRING81, TEST_TOPIC); // Set the default output format hr = cpVoice->SetOutput( cpStream2, TRUE); CHECKHRGOTOIdEx( hr, tpr, IDS_STRING60, TEST_TOPIC); hr = GetWStrFromRes( IDS_STRING34, szwSpeakStr ); CHECKHRGOTOIdEx( hr, tpr, IDS_STRING83, TEST_TOPIC); hr = cpVoice->Speak( szwSpeakStr, SPF_IS_XML, NULL ); CHECKHRGOTOIdEx( hr, tpr, IDS_STRING13, TEST_TOPIC); // Reset stream to beginning hr = cpStream2->Seek( l, SEEK_SET, NULL ); CHECKHRGOTOIdEx( hr, tpr, IDS_STRING79, TEST_TOPIC); // get the sum of the amplitude from the stream 1 hr = GetAmpFromSamples (cpStream2, &totalAmp2 ); CHECKHRGOTOIdEx(hr, tpr, IDS_STRING82, TEST_TOPIC ); //Make sure the amplitudes of stream1 and stream2 are greater than 0 CHECKASSERTGOTOId( (totalAmp1 > 0), tpr, IDS_STRING35 ); CHECKASSERTGOTOId( (totalAmp2 > 0), tpr, IDS_STRING35 ); // Note - The test assumes that the overall amplitude from stream 1 will // be at least 3 times that of stream 2 ulRatio = totalAmp1/totalAmp2; CHECKASSERTId( (ulRatio>1), tpr, IDS_STRING35 ); EXIT: return tpr; } //******************************************************************************** TESTPROCAPI t_XMLPitch(UINT uMsg, TPPARAM tpParam, LPFUNCTION_TABLE_ENTRY lpFTE) { //This test Speaks with CONTEXT tag. // Message check if (uMsg != TPM_EXECUTE) { return TPR_NOT_HANDLED; } HRESULT hr = S_OK; int tpr = TPR_PASS; CComPtr cpLocalVoice; // Create the SAPI voice DOCHECKHRGOTO (hr = cpLocalVoice.CoCreateInstance( CLSID_SpVoice );); tpr = t_XMLPitch_Test(uMsg, tpParam, lpFTE, cpLocalVoice, false); EXIT: return tpr; } //******************************************************************************** TESTPROCAPI t_XMLPitch_Test(UINT uMsg, TPPARAM tpParam, LPFUNCTION_TABLE_ENTRY lpFTE, ISpVoice *cpVoice, bool bCalledByMulti) { // This test changes the pitch of a TTS engine twice through XML and analyzes the // .wav form to make sure a change has occured. It first speaks a sentence at // normal pitch and finds the average of the positive amplitude. The average positive // amplitude is then used as a threshhold above which peak detection is measured. It // is expected that a higher pitch wav form will have more peaks above the threshhold // then a lower pitch wav form will. // NOTE - wav samples are run through a low frequency filter to generate a smother // wav form. HRESULT hr = S_OK; int tpr = TPR_PASS; // Message check if (uMsg != TPM_EXECUTE) { return TPR_NOT_HANDLED; } CComPtr cpStream1; CComPtr cpStream2; STATSTG Stat; ULONG cSamples = 0; WCHAR szwSpeakStr[MAX_PATH]=L""""; WCHAR szwDebug[MAX_PATH]=L""""; ULONG freq1=0, freq2=0; float fratio = 0; const char * TEST_TOPIC = """"; //====================================================================== TEST_TOPIC = ""Initialization""; //====================================================================== CSpStreamFormat NewFmt(SPSF_22kHz16BitMono, &hr); //sampFreq = 22050; CHECKHRGOTOIdEx(hr, tpr, IDS_STRING84, TEST_TOPIC ); hr = cpVoice->SetVolume( 100 ); CHECKHRIdEx( hr, tpr, IDS_STRING18, TEST_TOPIC); hr = cpVoice->SetRate( 0 ); CHECKHRIdEx( hr, tpr, IDS_STRING16, TEST_TOPIC); //====================================================================== TEST_TOPIC = ""Stream # 1 with low pitch""; //====================================================================== // Create stream #1 with low pitch hr = SPCreateStreamOnHGlobal( NULL, true, NewFmt.FormatId(), NewFmt.WaveFormatExPtr(), &cpStream1 ); CHECKHRGOTOIdEx(hr, tpr, IDS_STRING81, TEST_TOPIC ); // Set the default output format hr = cpVoice->SetOutput( cpStream1, TRUE); CHECKHRGOTOIdEx(hr, tpr, IDS_STRING60, TEST_TOPIC ); hr = GetWStrFromRes( IDS_STRING37, szwSpeakStr ); CHECKHRGOTOIdEx(hr, tpr, IDS_STRING83, TEST_TOPIC ); hr = cpVoice->Speak( szwSpeakStr, SPF_IS_XML, NULL ); CHECKHRGOTOIdEx(hr, tpr, IDS_STRING13, TEST_TOPIC ); // Get stream size hr = cpStream1->Stat( &Stat, STATFLAG_NONAME ); CHECKHRGOTOIdEx(hr, tpr, IDS_STRING90, TEST_TOPIC ); cSamples = (ULONG)Stat.cbSize.QuadPart / sizeof(short); CHECKASSERTGOTOIdEx((cSamples != 0), tpr, IDS_STRING39, TEST_TOPIC ); LARGE_INTEGER l; l.QuadPart = 0; // Reset stream to beginning hr = cpStream1->Seek( l, SEEK_SET, NULL ); CHECKHRGOTOIdEx(hr, tpr, IDS_STRING79, TEST_TOPIC ); hr = GetFreqFromSamples (cpStream1, 22050, cSamples, &freq1); CHECKHRGOTOIdEx(hr, tpr, IDS_STRING91, TEST_TOPIC ); //====================================================================== TEST_TOPIC = ""Stream # 2 with high pitch""; //====================================================================== // Create stream #2 with high pitch hr = SPCreateStreamOnHGlobal( NULL, true, NewFmt.FormatId(), NewFmt.WaveFormatExPtr(), &cpStream2 ); CHECKHRGOTOIdEx(hr, tpr, IDS_STRING81, TEST_TOPIC ); // Set the default output format hr = cpVoice->SetOutput( cpStream2, TRUE); CHECKHRGOTOIdEx(hr, tpr, IDS_STRING60, TEST_TOPIC ); hr = GetWStrFromRes( IDS_STRING38, szwSpeakStr ); CHECKHRGOTOIdEx(hr, tpr, IDS_STRING83, TEST_TOPIC ); hr = cpVoice->Speak( szwSpeakStr, SPF_IS_XML, NULL ); CHECKHRGOTOIdEx(hr, tpr, IDS_STRING13, TEST_TOPIC ); // Get stream size hr = cpStream2->Stat( &Stat, STATFLAG_NONAME ); CHECKHRGOTOIdEx(hr, tpr, IDS_STRING90, TEST_TOPIC ); cSamples = (ULONG)Stat.cbSize.QuadPart / sizeof(SHORT); CHECKASSERTGOTOIdEx((cSamples != 0), tpr, IDS_STRING39, TEST_TOPIC ); // Reset stream to beginning hr = cpStream2->Seek( l, SEEK_SET, NULL ); CHECKHRGOTOIdEx(hr, tpr, IDS_STRING79, TEST_TOPIC ); hr = GetFreqFromSamples (cpStream2, 22050, cSamples, &freq2); CHECKHRGOTOIdEx(hr, tpr, IDS_STRING91, TEST_TOPIC ); { //debug TCHAR szDInfo[MAX_PATH]=TEXT(""""); _stprintf( szDInfo, TEXT(""freq1 = %d, freq2 = %d""), freq1, freq2 ); g_pKato->Comment(10, szDInfo); } // Now compare the frequencies of the audio output streams // Note - Average freqencey with high pitch has at least 1.2 times higher than // low pitch CHECKASSERTId((freq1 > 0), tpr, IDS_STRING39 ); CHECKASSERTId((freq2 > 0), tpr, IDS_STRING39 ); fratio = (float)freq2/(float)freq1; CHECKASSERTId((fratio > 1.2 ), tpr, IDS_STRING39 ); EXIT: return tpr; } //*************************************************************************************** TESTPROCAPI t_XMLNonSapiTagsTest(UINT uMsg, TPPARAM tpParam, LPFUNCTION_TABLE_ENTRY lpFTE) { //This test Speaks with an arbitrary non-sapi tag. In this case, SAPI supplys the //SPVA_ParseUnknownTag text fragment state to the tts engine. // Message check if (uMsg != TPM_EXECUTE) { return TPR_NOT_HANDLED; } HRESULT hr = S_OK; int tpr = TPR_PASS; CComPtr cpVoice; CComPtr cpStream; WCHAR szwSpeakStr[MAX_PATH]=L""""; CSpStreamFormat NewFmt(SPSF_22kHz16BitMono, &hr); CHECKHRGOTOId(hr, tpr, IDS_STRING84); //create a SAPI voice hr = cpVoice.CoCreateInstance( CLSID_SpVoice ); CHECKHRGOTOId( hr, tpr, IDS_STRING85 ); hr = GetWStrFromRes( IDS_STRING67, szwSpeakStr ); CHECKHRGOTOId(hr, tpr, IDS_STRING83); // Create a generic stream to send the audio data to so we don't have to listen to it hr = SPCreateStreamOnHGlobal( NULL, true, NewFmt.FormatId(), NewFmt.WaveFormatExPtr(), &cpStream ); CHECKHRGOTOId(hr, tpr, IDS_STRING81 ); // Set the default output format hr = cpVoice->SetOutput( cpStream, TRUE); CHECKHRGOTOId(hr, tpr, IDS_STRING60 ); hr = cpVoice->Speak( szwSpeakStr, SPF_IS_XML, NULL ); CHECKHRId(hr, tpr, IDS_STRING13); EXIT: return tpr; } //********************************************************************************* TESTPROCAPI t_XMLEmphTest(UINT uMsg, TPPARAM tpParam, LPFUNCTION_TABLE_ENTRY lpFTE) { //This test Speaks with EMPH tag. Test uses Pitch, Rate and volume to measure //the output streams. The test assume that the output stream of EMPH is different //in Rate, or Volume, or pitch from one without emph. If engines implement EMPH in //other different way, rather than use pitch, rate, or volume, then this test will //fail. And the test result will be ""Not Supported"". // Message check if (uMsg != TPM_EXECUTE) { return TPR_NOT_HANDLED; } HRESULT hr = S_OK; int tpr = TPR_SUPPORTED; CComPtr cpVoice; CComPtr cpStream1; CComPtr cpStream2; ULONG ulRatio=0; STATSTG Stat; ULONG cSamples1=0, cSamples2=0; WCHAR szwSpeakStr[MAX_PATH]=L""""; ULONG totalAmp1 = 0, totalAmp2 = 0; ULONG freq1=0, freq2=0; const char * TEST_TOPIC = """"; //====================================================================== TEST_TOPIC = ""Initialization""; //====================================================================== CSpStreamFormat NewFmt(SPSF_22kHz16BitMono, &hr); CHECKHRGOTOIdEx(hr, tpr, IDS_STRING84, TEST_TOPIC ); hr = GetWStrFromRes( IDS_STRING69, szwSpeakStr ); CHECKHRGOTOIdEx(hr, tpr, IDS_STRING83, TEST_TOPIC ); // Create the SAPI voice hr = cpVoice.CoCreateInstance( CLSID_SpVoice ); CHECKHRGOTOIdEx(hr, tpr, IDS_STRING85, TEST_TOPIC ); //====================================================================== TEST_TOPIC = ""Stream #1 without Emph""; //====================================================================== // Create stream #1 hr = SPCreateStreamOnHGlobal( NULL, true, NewFmt.FormatId(), NewFmt.WaveFormatExPtr(), &cpStream1 ); CHECKHRGOTOIdEx(hr, tpr, IDS_STRING81, TEST_TOPIC ); // Set the output format hr = cpVoice->SetOutput( cpStream1, TRUE); CHECKHRGOTOIdEx(hr, tpr, IDS_STRING60, TEST_TOPIC ); //no Emph hr = GetWStrFromRes( IDS_STRING68, szwSpeakStr ); CHECKHRGOTOIdEx(hr, tpr, IDS_STRING83, TEST_TOPIC ); hr = cpVoice->Speak( szwSpeakStr, SPF_IS_XML, NULL ); CHECKHRGOTOIdEx(hr, tpr, IDS_STRING13, TEST_TOPIC ); // Get stream size hr = cpStream1->Stat( &Stat, STATFLAG_NONAME ); CHECKHRGOTOIdEx( hr, tpr, IDS_STRING90, TEST_TOPIC); cSamples1 = (ULONG)Stat.cbSize.QuadPart / sizeof(SHORT); LARGE_INTEGER l; l.QuadPart = 0; // Reset stream to beginning hr = cpStream1->Seek( l, SEEK_SET, NULL ); CHECKHRGOTOIdEx(hr, tpr, IDS_STRING79, TEST_TOPIC ); // get the sum of the amplitude from the stream 1 hr = GetAmpFromSamples (cpStream1, &totalAmp1 ); CHECKHRGOTOIdEx(hr, tpr, IDS_STRING82, TEST_TOPIC ); // Reset stream to beginning again hr = cpStream1->Seek( l, SEEK_SET, NULL ); CHECKHRGOTOIdEx(hr, tpr, IDS_STRING79, TEST_TOPIC ); //get frequency hr = GetFreqFromSamples (cpStream1, 22050, cSamples1, &freq1); CHECKHRGOTOIdEx(hr, tpr, IDS_STRING91, TEST_TOPIC ); //====================================================================== TEST_TOPIC = ""Stream #2 with Emph""; //====================================================================== // Create stream #2 hr = SPCreateStreamOnHGlobal( NULL, true, NewFmt.FormatId(), NewFmt.WaveFormatExPtr(), &cpStream2 ); CHECKHRGOTOIdEx(hr, tpr, IDS_STRING81, TEST_TOPIC ); // Set the output format hr = cpVoice->SetOutput( cpStream2, TRUE); CHECKHRGOTOIdEx(hr, tpr, IDS_STRING60, TEST_TOPIC ); GetWStrFromRes( IDS_STRING69, szwSpeakStr ); hr = cpVoice->Speak( szwSpeakStr, SPF_IS_XML, NULL ); CHECKHRGOTOIdEx(hr, tpr, IDS_STRING13, TEST_TOPIC ); // Get stream size hr = cpStream2->Stat( &Stat, STATFLAG_NONAME ); CHECKHRGOTOIdEx( hr, tpr, IDS_STRING90, TEST_TOPIC); cSamples2 = (ULONG)Stat.cbSize.QuadPart / sizeof(SHORT); // Reset stream to beginning hr = cpStream2->Seek( l, SEEK_SET, NULL ); CHECKHRGOTOIdEx(hr, tpr, IDS_STRING79, TEST_TOPIC ); // get the sum of the amplitude from the stream 2 hr = GetAmpFromSamples (cpStream2, &totalAmp2 ); CHECKHRGOTOIdEx(hr, tpr, IDS_STRING82 , TEST_TOPIC ); // Reset stream to beginning again hr = cpStream2->Seek( l, SEEK_SET, NULL ); CHECKHRGOTOIdEx(hr, tpr, IDS_STRING79, TEST_TOPIC ); hr = GetFreqFromSamples (cpStream2, 22050, cSamples2, &freq2); CHECKHRGOTOIdEx(hr, tpr, IDS_STRING91, TEST_TOPIC ); //Compare the two streams by Pitch, volume, and Rate. //The output streams should be different in pitch, or volume, or Rate. //Rate measurement CHECKISSUPPORTEDId( (cSamples2 > 0), tpr, IDS_STRING70 ); CHECKISSUPPORTEDId( (cSamples1 > 0), tpr, IDS_STRING70 ); //Volume measurement CHECKISSUPPORTEDId( (totalAmp1 > 0), tpr, IDS_STRING70 ); CHECKISSUPPORTEDId( (totalAmp2 > 0), tpr, IDS_STRING70 ); // Pitch measurement CHECKISSUPPORTEDId( (freq2 > 0), tpr, IDS_STRING70 ); CHECKISSUPPORTEDId( (freq1 > 0), tpr, IDS_STRING70 ); CHECKISSUPPORTEDId( (freq2 != freq1 ) || (cSamples2 != cSamples1 ) || (totalAmp2 != totalAmp1) , tpr, IDS_STRING70 ); EXIT: return tpr; } //******************************************************************************** TESTPROCAPI t_XMLContext(UINT uMsg, TPPARAM tpParam, LPFUNCTION_TABLE_ENTRY lpFTE) { //This test Speaks with CONTEXT tag. // Message check if (uMsg != TPM_EXECUTE) { return TPR_NOT_HANDLED; } HRESULT hr = S_OK; int tpr = TPR_PASS; CComPtr cpLocalVoice; // Create the SAPI voice DOCHECKHRGOTO (hr = cpLocalVoice.CoCreateInstance( CLSID_SpVoice );); tpr = t_XMLContext_Test(uMsg, tpParam, lpFTE, cpLocalVoice, false); EXIT: return tpr; } //******************************************************************************** TESTPROCAPI t_XMLContext_Test(UINT uMsg, TPPARAM tpParam, LPFUNCTION_TABLE_ENTRY lpFTE, ISpVoice *cpVoice, bool bCalledByMulti) { //This test Speaks with CONTEXT tag. // Message check if (uMsg != TPM_EXECUTE) { return TPR_NOT_HANDLED; } HRESULT hr = S_OK; int tpr = TPR_PASS; CComPtr cpStream; const char * TEST_TOPIC = """"; WCHAR szwSpeakStr[1024]=L""""; //====================================================================== TEST_TOPIC = ""Context: Initialization""; //====================================================================== CSpStreamFormat NewFmt(SPSF_22kHz16BitMono, &hr); CHECKHRGOTOIdEx(hr, tpr, IDS_STRING84, TEST_TOPIC ); // Create stream hr = SPCreateStreamOnHGlobal( NULL, true, NewFmt.FormatId(), NewFmt.WaveFormatExPtr(), &cpStream ); CHECKHRGOTOIdEx(hr, tpr, IDS_STRING81, TEST_TOPIC ); // Set the output format hr = cpVoice->SetOutput( cpStream, TRUE); CHECKHRGOTOIdEx(hr, tpr, IDS_STRING60, TEST_TOPIC ); //====================================================================== TEST_TOPIC = ""Context: Test#1a - date_mdy""; //====================================================================== //Date in mdy format DOCHECKHRGOTO( hr = GetWStrFromRes( IDS_STRING99, szwSpeakStr );); hr = cpVoice->Speak( szwSpeakStr, SPF_IS_XML, NULL ); CHECKHRIdEx( hr, tpr, IDS_STRING13, TEST_TOPIC ); //====================================================================== TEST_TOPIC = ""Context: Test#1b - date_dmy""; //====================================================================== //Date in date_dmy format DOCHECKHRGOTO( hr = GetWStrFromRes( IDS_STRING100, szwSpeakStr );); hr = cpVoice->Speak( szwSpeakStr, SPF_IS_XML, NULL ); CHECKHRIdEx( hr, tpr, IDS_STRING13, TEST_TOPIC ); //====================================================================== TEST_TOPIC = ""Context: Test#1c - date_ymd""; //====================================================================== //Date in date_ymd format DOCHECKHRGOTO( hr = GetWStrFromRes( IDS_STRING101, szwSpeakStr );); hr = cpVoice->Speak( szwSpeakStr, SPF_IS_XML, NULL ); CHECKHRIdEx( hr, tpr, IDS_STRING13, TEST_TOPIC ); //====================================================================== TEST_TOPIC = ""Context: Test#2a - date_ym""; //====================================================================== //Date in date_ym format DOCHECKHRGOTO( hr = GetWStrFromRes( IDS_STRING102, szwSpeakStr );); hr = cpVoice->Speak( szwSpeakStr, SPF_IS_XML, NULL ); CHECKHRIdEx( hr, tpr, IDS_STRING13, TEST_TOPIC ); //====================================================================== TEST_TOPIC = ""Context: Test#2b - date_my""; //====================================================================== //Date in date_my format DOCHECKHRGOTO( hr = GetWStrFromRes( IDS_STRING103, szwSpeakStr );); hr = cpVoice->Speak( szwSpeakStr, SPF_IS_XML, NULL ); CHECKHRIdEx( hr, tpr, IDS_STRING13, TEST_TOPIC ); //====================================================================== TEST_TOPIC = ""Context: Test#2c - date_dm""; //====================================================================== //Date in date_dm format DOCHECKHRGOTO( hr = GetWStrFromRes( IDS_STRING104, szwSpeakStr );); hr = cpVoice->Speak( szwSpeakStr, SPF_IS_XML, NULL ); CHECKHRIdEx( hr, tpr, IDS_STRING13, TEST_TOPIC ); //====================================================================== TEST_TOPIC = ""Context: Test#2d - date_md""; //====================================================================== //Date in date_md format DOCHECKHRGOTO( hr = GetWStrFromRes( IDS_STRING105, szwSpeakStr );); hr = cpVoice->Speak( szwSpeakStr, SPF_IS_XML, NULL ); CHECKHRIdEx( hr, tpr, IDS_STRING13, TEST_TOPIC ); //====================================================================== TEST_TOPIC = ""Context: Test#2e - date_md""; //====================================================================== //Date in date_year format DOCHECKHRGOTO( hr = GetWStrFromRes( IDS_STRING106, szwSpeakStr );); hr = cpVoice->Speak( szwSpeakStr, SPF_IS_XML, NULL ); CHECKHRIdEx( hr, tpr, IDS_STRING13, TEST_TOPIC ); //====================================================================== TEST_TOPIC = ""Context: Test#3 - time""; //====================================================================== //Time in time_hms format DOCHECKHRGOTO( hr = GetWStrFromRes( IDS_STRING107, szwSpeakStr );); hr = cpVoice->Speak( szwSpeakStr, SPF_IS_XML, NULL ); CHECKHRIdEx( hr, tpr, IDS_STRING13, TEST_TOPIC ); //====================================================================== TEST_TOPIC = ""Context: Test#4a - number_cardinal""; //====================================================================== //Number in number_cardinal format DOCHECKHRGOTO( hr = GetWStrFromRes( IDS_STRING108, szwSpeakStr );); hr = cpVoice->Speak( szwSpeakStr, SPF_IS_XML, NULL ); CHECKHRIdEx( hr, tpr, IDS_STRING13, TEST_TOPIC ); //====================================================================== TEST_TOPIC = ""Context: Test#4b - number_digit""; //====================================================================== //Number in number_digit format DOCHECKHRGOTO( hr = GetWStrFromRes( IDS_STRING109, szwSpeakStr );); hr = cpVoice->Speak( szwSpeakStr, SPF_IS_XML, NULL ); CHECKHRIdEx( hr, tpr, IDS_STRING13, TEST_TOPIC ); //====================================================================== TEST_TOPIC = ""Context: Test#4c - number_fraction""; //====================================================================== //Number in number_fraction format DOCHECKHRGOTO( hr = GetWStrFromRes( IDS_STRING110, szwSpeakStr );); hr = cpVoice->Speak( szwSpeakStr, SPF_IS_XML, NULL ); CHECKHRIdEx( hr, tpr, IDS_STRING13, TEST_TOPIC ); //====================================================================== TEST_TOPIC = ""Context: Test#4d - number_decimal""; //====================================================================== //Number in number_decimal format DOCHECKHRGOTO( hr = GetWStrFromRes( IDS_STRING111, szwSpeakStr );); hr = cpVoice->Speak( szwSpeakStr, SPF_IS_XML, NULL ); CHECKHRIdEx( hr, tpr, IDS_STRING13, TEST_TOPIC ); //====================================================================== TEST_TOPIC = ""Context: Test#5 - phone_number""; //====================================================================== // phone_number format DOCHECKHRGOTO( hr = GetWStrFromRes( IDS_STRING112, szwSpeakStr );); hr = cpVoice->Speak( szwSpeakStr, SPF_IS_XML, NULL ); CHECKHRIdEx( hr, tpr, IDS_STRING13, TEST_TOPIC ); //====================================================================== TEST_TOPIC = ""Context: Test#6 - currency""; //====================================================================== // currency format DOCHECKHRGOTO( hr = GetWStrFromRes( IDS_STRING113, szwSpeakStr );); hr = cpVoice->Speak( szwSpeakStr, SPF_IS_XML, NULL ); CHECKHRIdEx( hr, tpr, IDS_STRING13, TEST_TOPIC ); //====================================================================== TEST_TOPIC = ""Context: Test#7 - web""; //====================================================================== // web format DOCHECKHRGOTO( hr = GetWStrFromRes( IDS_STRING114, szwSpeakStr );); hr = cpVoice->Speak( szwSpeakStr, SPF_IS_XML, NULL ); CHECKHRIdEx( hr, tpr, IDS_STRING13, TEST_TOPIC ); //====================================================================== TEST_TOPIC = ""Context: Test#8 - email_address""; //====================================================================== // email address format DOCHECKHRGOTO( hr = GetWStrFromRes( IDS_STRING115, szwSpeakStr );); hr = cpVoice->Speak( szwSpeakStr, SPF_IS_XML, NULL ); CHECKHRIdEx( hr, tpr, IDS_STRING13, TEST_TOPIC ); //====================================================================== TEST_TOPIC = ""Context: Test#9 - address""; //====================================================================== // address format DOCHECKHRGOTO( hr = GetWStrFromRes( IDS_STRING116, szwSpeakStr );); hr = cpVoice->Speak( szwSpeakStr, SPF_IS_XML, NULL ); CHECKHRIdEx( hr, tpr, IDS_STRING13, TEST_TOPIC ); //====================================================================== TEST_TOPIC = ""Context: Test#10 - address_postal""; //====================================================================== // address postal format DOCHECKHRGOTO( hr = GetWStrFromRes( IDS_STRING117, szwSpeakStr );); hr = cpVoice->Speak( szwSpeakStr, SPF_IS_XML, NULL ); CHECKHRIdEx( hr, tpr, IDS_STRING13, TEST_TOPIC ); //====================================================================== TEST_TOPIC = ""Context: Test#11 - my context tests""; //====================================================================== // // ms context format DOCHECKHRGOTO( hr = GetWStrFromRes( IDS_STRING118, szwSpeakStr );); hr = cpVoice->Speak( szwSpeakStr, SPF_IS_XML, NULL ); CHECKHRIdEx( hr, tpr, IDS_STRING13, TEST_TOPIC ); EXIT: return tpr; } //************************************************************************************* TESTPROCAPI t_XMLPartOfSpTest(UINT uMsg, TPPARAM tpParam, LPFUNCTION_TABLE_ENTRY lpFTE) { //This test is trying to Speak with PartOfSP tags. //Currently it is in the feature list. The test result will be ""Supported"" // or ""Unsupported"". // Message check if (uMsg != TPM_EXECUTE) { return TPR_NOT_HANDLED; } HRESULT hr = S_OK; int tpr = TPR_SUPPORTED; CComPtr cpVoice; CComPtr cpConlexicon; LANGID LangID; ULONG cSamples1=0, cSamples2=0; WCHAR szwSpeakStrNoun[MAX_PATH]=L""""; WCHAR szwSpeakStrVerb[MAX_PATH]=L""""; WCHAR szNewWord[MAX_PATH]=L""""; WCHAR szwSpeakstr[MAX_PATH]=L""""; WCHAR szVPronunciation[MAX_PATH]=L""""; WCHAR szNPronunciation[MAX_PATH]=L""""; const char * TEST_TOPIC = """"; //====================================================================== TEST_TOPIC = ""Initialization""; //====================================================================== hr = GetWStrFromRes( IDS_STRING76, szNewWord ); CHECKHRGOTOIdEx( hr, tpr, IDS_STRING83, TEST_TOPIC); DOCHECKHRGOTO( hr = SpGetLanguageIdFromDefaultVoice(&LangID); ); //create a SAPI voice hr = cpVoice.CoCreateInstance( CLSID_SpVoice ); CHECKHRGOTOIdEx(hr, tpr, IDS_STRING85, TEST_TOPIC ); hr = cpConlexicon.CoCreateInstance(CLSID_SpLexicon); CHECKHRGOTOIdEx(hr, tpr, IDS_STRING85, TEST_TOPIC ); //====================================================================== TEST_TOPIC = ""Add verb pronunciation to a word""; //====================================================================== hr = GetWStrFromRes( IDS_STRING48, szwSpeakStrVerb ); CHECKHRGOTOIdEx( hr, tpr, IDS_STRING83, TEST_TOPIC); //get phoneid hr = TTSSymToPhoneId ( LangID, szwSpeakStrVerb, szVPronunciation); CHECKHRGOTOIdEx(hr, tpr, IDS_STRING77, TEST_TOPIC ); hr = cpConlexicon->RemovePronunciation(szNewWord, LangID, SPPS_Verb, szVPronunciation); CHECKHRALTGOTOIdEx( hr, SPERR_NOT_IN_LEX, tpr, IDS_STRING89, TEST_TOPIC); //Assign the verb pronunciation of the new word hr = cpConlexicon->AddPronunciation(szNewWord, LangID, SPPS_Verb, szVPronunciation); CHECKHRGOTOIdEx(hr, tpr, IDS_STRING87, TEST_TOPIC ); //====================================================================== TEST_TOPIC = ""Add noun pronunciation to a word""; //====================================================================== hr = GetWStrFromRes( IDS_STRING52, szwSpeakStrNoun ); CHECKHRGOTOIdEx( hr, tpr, IDS_STRING83, TEST_TOPIC); //get phoneid hr = TTSSymToPhoneId ( LangID, szwSpeakStrNoun, szNPronunciation); CHECKHRGOTOIdEx(hr, tpr, IDS_STRING77, TEST_TOPIC ); hr = cpConlexicon->RemovePronunciation(szNewWord, LangID, SPPS_Noun, szNPronunciation); CHECKHRALTGOTOIdEx( hr, SPERR_NOT_IN_LEX, tpr, IDS_STRING89, TEST_TOPIC); //add the word in noun pronunciation to Lexicon hr = cpConlexicon->AddPronunciation(szNewWord, LangID, SPPS_Noun, szNPronunciation); CHECKHRGOTOIdEx(hr, tpr, IDS_STRING87, TEST_TOPIC ); //====================================================================== TEST_TOPIC = ""Speak two streams with PartOfSp""; //====================================================================== //speak two streams hr = GetWStrFromRes( IDS_STRING49, szwSpeakstr ); CHECKHRGOTOIdEx( hr, tpr, IDS_STRING83, TEST_TOPIC); swprintf( szwSpeakStrNoun, szwSpeakstr, szNewWord ); hr = GetWStrFromRes( IDS_STRING50, szwSpeakstr ); CHECKHRGOTOIdEx( hr, tpr, IDS_STRING83, TEST_TOPIC); swprintf( szwSpeakStrVerb, szwSpeakstr, szNewWord ); hr = t_SpeakTwoStreams(cpVoice, szwSpeakStrNoun, szwSpeakStrVerb, cSamples1, cSamples2); CHECKHRGOTOIdEx( hr, tpr, IDS_STRING88, TEST_TOPIC); hr = cpConlexicon->RemovePronunciation(szNewWord, LangID, SPPS_Noun, szNPronunciation); CHECKHRGOTOIdEx( hr, tpr, IDS_STRING89, TEST_TOPIC); hr = cpConlexicon->RemovePronunciation(szNewWord, LangID, SPPS_Verb, szVPronunciation); CHECKHRGOTOIdEx( hr, tpr, IDS_STRING89, TEST_TOPIC); CHECKISSUPPORTEDId((cSamples1 > 0 ), tpr, IDS_STRING51); CHECKISSUPPORTEDId((cSamples2 > 0 ), tpr, IDS_STRING51); //This test assumes that second stream should be twice shorter than the first one. CHECKISSUPPORTEDId( ( 2* cSamples2 < cSamples1), tpr, IDS_STRING51); EXIT: return tpr; } //************************************************************************************** TESTPROCAPI t_XMLSAPIMarkup_Test(UINT uMsg, TPPARAM tpParam, LPFUNCTION_TABLE_ENTRY lpFTE, ISpVoice *cpVoice, bool bCalledByMulti) { // This test expects TTS engines to handle all possible spec'ed out combinations //of the XML tags. HRESULT hr = S_OK; int tpr = TPR_PASS; // Message check if (uMsg != TPM_EXECUTE) { return TPR_NOT_HANDLED; } else if(lpFTE) // called by SpComp directly. It is NULL in multiInstance test. { srand(reinterpret_cast(tpParam)->dwRandomSeed); } CComPtr cpStream; WCHAR szwSpeakStr[MAX_PATH]=L""""; WCHAR szwXMLString[MAX_PATH]=L""""; const char * TEST_TOPIC = """"; CSpStreamFormat NewFmt(SPSF_22kHz16BitMono, &hr); CHECKHRGOTOId(hr, tpr, IDS_STRING84); //====================================================================== TEST_TOPIC = ""Markup Test: Initialization""; //====================================================================== // Create a generic stream to send the audio data to so we don't have to listen to it hr = SPCreateStreamOnHGlobal( NULL, true, NewFmt.FormatId(), NewFmt.WaveFormatExPtr(), &cpStream ); CHECKHRGOTOIdEx(hr, tpr, IDS_STRING81, TEST_TOPIC); // Set the default output format hr = cpVoice->SetOutput( cpStream, TRUE); CHECKHRGOTOIdEx(hr, tpr, IDS_STRING60, TEST_TOPIC); //====================================================================== TEST_TOPIC = ""Markup Test: Bookmark""; //====================================================================== // Bookmark DOCHECKHRGOTO (hr = GetWStrFromRes( IDS_STRING8, szwXMLString );); hr = cpVoice->Speak( szwXMLString, SPF_ASYNC | SPF_IS_XML, NULL ); CHECKHRIdEx(hr, tpr, IDS_STRING13, TEST_TOPIC); //====================================================================== TEST_TOPIC = ""Markup Test: Silence""; //====================================================================== // Silence DOCHECKHRGOTO (hr = GetWStrFromRes( IDS_STRING41, szwSpeakStr );); swprintf( szwXMLString, szwSpeakStr, GET_RANDOM(0, 2000) ); hr = cpVoice->Speak( szwXMLString, SPF_ASYNC | SPF_IS_XML, NULL ); CHECKHRIdEx(hr, tpr, IDS_STRING13, TEST_TOPIC); //====================================================================== TEST_TOPIC = ""Markup Test: Spell""; //====================================================================== // Spell DOCHECKHRGOTO (hr = GetWStrFromRes( IDS_STRING27, szwXMLString );); hr = cpVoice->Speak( szwXMLString, SPF_ASYNC | SPF_IS_XML, NULL ); CHECKHRIdEx(hr, tpr, IDS_STRING13, TEST_TOPIC); //====================================================================== TEST_TOPIC = ""Markup Test: Pron""; //====================================================================== // Pronounce DOCHECKHRGOTO (hr = GetWStrFromRes( IDS_STRING43, szwXMLString );); hr = cpVoice->Speak( szwXMLString, SPF_ASYNC | SPF_IS_XML, NULL ); CHECKHRIdEx(hr, tpr, IDS_STRING13, TEST_TOPIC); //====================================================================== TEST_TOPIC = ""Markup Test: Rate""; //====================================================================== // Rate DOCHECKHRGOTO (hr = GetWStrFromRes( IDS_STRING44, szwSpeakStr );); swprintf( szwXMLString, szwSpeakStr, GET_RANDOM(-10, 10) ); hr = cpVoice->Speak( szwXMLString, SPF_ASYNC | SPF_IS_XML, NULL ); CHECKHRIdEx(hr, tpr, IDS_STRING13, TEST_TOPIC); //====================================================================== TEST_TOPIC = ""Markup Test: Volume""; //====================================================================== // Volume DOCHECKHRGOTO (hr = GetWStrFromRes( IDS_STRING45, szwSpeakStr );); swprintf( szwXMLString, szwSpeakStr, GET_RANDOM(0, 100) ); hr = cpVoice->Speak( szwXMLString, SPF_ASYNC | SPF_IS_XML, NULL ); CHECKHRIdEx(hr, tpr, IDS_STRING13, TEST_TOPIC); //====================================================================== TEST_TOPIC = ""Markup Test: Pitch""; //====================================================================== // Pitch DOCHECKHRGOTO (hr = GetWStrFromRes( IDS_STRING46, szwSpeakStr );); swprintf( szwXMLString, szwSpeakStr, GET_RANDOM(-10, 10) ); hr = cpVoice->Speak( szwXMLString, SPF_ASYNC | SPF_IS_XML, NULL ); CHECKHRIdEx(hr, tpr, IDS_STRING13, TEST_TOPIC); //====================================================================== TEST_TOPIC = ""Markup Test: Non-Sapi""; //====================================================================== //Non-Sapi DOCHECKHRGOTO (hr = GetWStrFromRes( IDS_STRING67, szwXMLString );); hr = cpVoice->Speak( szwXMLString, SPF_ASYNC | SPF_IS_XML, NULL ); CHECKHRIdEx(hr, tpr, IDS_STRING13, TEST_TOPIC); //====================================================================== TEST_TOPIC = ""Markup Test: Context""; //====================================================================== //Context DOCHECKHRGOTO (hr = GetWStrFromRes( IDS_STRING119, szwXMLString );); hr = cpVoice->Speak( szwXMLString, SPF_ASYNC | SPF_IS_XML, NULL ); CHECKHRIdEx(hr, tpr, IDS_STRING13, TEST_TOPIC); hr = cpVoice->WaitUntilDone( TTS_WAITTIME ); CHECKHRGOTOIdEx(hr, tpr, IDS_STRING61, "" in t_XMLBookmarkTest""); EXIT: return tpr; } ",16223,True,4106.537424526916,median "/****************************************************************************** * The MIT License (MIT) * * Copyright (c) 2021-2022 Baldur Karlsson * * 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 ""dxbc_bytecode.h"" #include ""core/settings.h"" #include ""dxbc_bytecode_ops.h"" #include ""driver/ihv/nv/nvapi_wrapper.h"" RDOC_EXTERN_CONFIG(bool, DXBC_Disassembly_FriendlyNaming); namespace DXBCBytecode { namespace AMDInstruction { // ha ha these are different :( enum class DX11Op { Readfirstlane = 0x01, Readlane = 0x02, LaneId = 0x03, Swizzle = 0x04, Ballot = 0x05, MBCnt = 0x06, Min3U = 0x08, Min3F = 0x09, Med3U = 0x0a, Med3F = 0x0b, Max3U = 0x0c, Max3F = 0x0d, BaryCoord = 0x0e, VtxParam = 0x0f, ViewportIndex = 0x10, RtArraySlice = 0x11, WaveReduce = 0x12, WaveScan = 0x13, DrawIndex = 0x17, AtomicU64 = 0x18, GetWaveSize = 0x19, BaseInstance = 0x1a, BaseVertex = 0x1b, }; enum class DX12Op { Readfirstlane = 0x01, Readlane = 0x02, LaneId = 0x03, Swizzle = 0x04, Ballot = 0x05, MBCnt = 0x06, Min3U = 0x07, Min3F = 0x08, Med3U = 0x09, Med3F = 0x0a, Max3U = 0x0b, Max3F = 0x0c, BaryCoord = 0x0d, VtxParam = 0x0e, ViewportIndex = 0x10, // DX11 only RtArraySlice = 0x11, // DX11 only WaveReduce = 0x12, WaveScan = 0x13, LoadDwAtAddr = 0x14, DrawIndex = 0x17, AtomicU64 = 0x18, GetWaveSize = 0x19, BaseInstance = 0x1a, BaseVertex = 0x1b, }; DX12Op convert(DX11Op op) { switch(op) { // convert opcodes that don't match up case DX11Op::Min3U: return DX12Op::Min3U; case DX11Op::Min3F: return DX12Op::Min3F; case DX11Op::Med3U: return DX12Op::Med3U; case DX11Op::Med3F: return DX12Op::Med3F; case DX11Op::Max3U: return DX12Op::Max3U; case DX11Op::Max3F: return DX12Op::Max3F; case DX11Op::BaryCoord: return DX12Op::BaryCoord; case DX11Op::VtxParam: return DX12Op::VtxParam; // others match up exactly default: return DX12Op(op); } } enum BaryInterpMode { LinearCenter = 1, LinearCentroid = 2, LinearSample = 3, PerspCenter = 4, PerspCentroid = 5, PerspSample = 6, PerspPullModel = 7, }; enum SwizzleMask { SwapX1 = 0x041f, SwapX2 = 0x081f, SwapX4 = 0x101f, SwapX8 = 0x201f, SwapX16 = 0x401f, ReverseX4 = 0x0c1f, ReverseX8 = 0x1c1f, ReverseX16 = 0x3c1f, ReverseX32 = 0x7c1f, BCastX2 = 0x003e, BCastX4 = 0x003c, BCastX8 = 0x0038, BCastX16 = 0x0030, BCastX32 = 0x0020, }; enum AMDAtomic { Min = 0x01, Max = 0x02, And = 0x03, Or = 0x04, Xor = 0x05, Add = 0x06, Xchg = 0x07, CmpXchg = 0x08, }; VendorAtomicOp convert(AMDAtomic op) { switch(op) { case Min: return ATOMIC_OP_MIN; case Max: return ATOMIC_OP_MAX; case And: return ATOMIC_OP_AND; case Or: return ATOMIC_OP_OR; case Xor: return ATOMIC_OP_XOR; case Add: return ATOMIC_OP_ADD; case Xchg: return ATOMIC_OP_SWAP; case CmpXchg: return ATOMIC_OP_CAS; default: return ATOMIC_OP_NONE; } } static MaskedElement Magic; static MaskedElement Phase; static MaskedElement Data; static MaskedElement BaryInterp; static MaskedElement SwizzleOp; static MaskedElement Opcode11; static MaskedElement Opcode12; static MaskedElement VtxParamComponent; static MaskedElement VtxParamParameter; static MaskedElement VtxParamVertex; static MaskedElement WaveOp; static MaskedElement WaveOpFlags; static MaskedElement AtomicOp; }; void Program::PostprocessVendorExtensions() { const bool friendly = DXBC_Disassembly_FriendlyNaming(); uint32_t magicID = ~0U; for(size_t i = 0; i < m_Declarations.size(); i++) { const Declaration &decl = m_Declarations[i]; if((decl.operand.indices.size() == 1 && decl.operand.indices[0].index == m_ShaderExt.second) || (decl.operand.indices.size() == 3 && decl.operand.indices[1].index == m_ShaderExt.second && decl.space == m_ShaderExt.first)) { magicID = (uint32_t)decl.operand.indices[0].index; m_Declarations.erase(i); break; } } // now we know the UAV, iterate the instructions looking for patterns to replace. // // AMD is nice and easy. Every instruction works on a scalar (vector versions repeat for each // component) and is encoded into a single InterlockedCompareExchange on the UAV. // So we can simply replace them in-place by decoding. // // NV's are not as nice. They are demarcated by IncrementCounter on the UAV so we know we'll see // a linear stream without re-ordering, but they *can* be intermixed with other non-intrinsic // instructions. Parameters and data are set by writing to specific offsets within the structure // // There are two types: // // Simpler, instructions that work purely on vars and not on resources. Shuffle/ballot/etc // // These come in the form: // index = magicUAV.IncrementCounter() // set params and opcode by writing to magicUAV[index].member... // retval = magicUAV.IncrementCounter() // [optional (see below): retval2 = magicUAV.IncrementCounter()] // // This type of operand returns the result with the closing IncrementCounter(). There could be // multiple results, so numOutputs is set before any, and then that many IncrementCounter() are // emitted with each result. // // More complex, instructions that use UAVs. Mostly atomics // // index1 = magicUAV.IncrementCounter() // magicUAV[index1].markUAV = 1; // userUAV[index1] = 0; // or some variation of such // index2 = magicUAV.IncrementCounter() // set params and opcode as above in magicUAV[index2].member... // retval = magicUAV[index2].dst // // Also note that if the shader doesn't use the return result of an atomic, the dst may never be // read! // // The difficulty then is distinguishing between the two and knowing where the boundaries are. // We do this with a simple state machine tracking where we are in an opcode: // // +----------> Nothing // | v // | | // | IncrementCounter() // Emit instruction | // | v // | Instruction >--write markUAV---> UAV instruction header // | v (wait for other UAV write) // | | v // | | | // | write opcode ] | // | | ] | // | v ] simple | // | Instruction Body ] case | // | v ] | // | | ] | // | IncrementCounter() ] | // | | | // +----<---------+ | // | IncrementCounter() // | | // | UAV instruction body <------------------+ // | v // | | // | write opcode // | | // +--------------+ // // so most state transitions are marked by an IncrementCounter(). The exceptions being // Instruction where we wait for a write to either markUAV or opcode to move to either simple // instruction body or to the UAV instruction header, and UAV instruction body which leaves // when we see an opcode write. // // We assume that markUAV will be written BEFORE the fake UAV write. It's not entirely clear if // this is guaranteed to not be re-ordered but it seems to be true and it's implied that NV's // driver relies on this. This simplifies tracking since we can use it as a state transition. // // We also assume that multiple accesses to the UAV don't overlap. This should be guaranteed by // the use of the index from the counter being used for access. However we don't actually check // the index itself. // // all src/dst are uint4, others are all uint enum class InstructionState { // if something goes wrong we enter this state and stop patching Broken, Nothing, // this is a state only used for AMD's UAV atomic op, which takes more parameters and uses the // operation phases. AMDUAVAtomic, // this is the state when we're not sure what type we are. Either markUAV is written, in which // case we move to UAVInstructionHeader1, or opcode is written, in which case we move to // Instruction1Out. We should see one or the other. // // FP16 UAV instructions (NV_EXTN_OP_FP16_ATOMIC) that operate on float4 resources have two // return values. Unfortunately we can't reliably detect this from the bytecode, so what // happens is that when we see opode get written if it's NV_EXTN_OP_FP16_ATOMIC then we jump // straight to UAVInstructionBody and re-use the UAV instruction header from last time. We // know this MUST be a continuation because otherwise NV_EXTN_OP_FP16_ATOMIC is always // preceeded by a UAV instruction header (via markUAV). InstructionHeader, InstructionBody, // we move from Instruction1Out to this state when markUAV is written. The next UAV write is // used to determine the 'target' UAV. // We then move to header2 so we don't consume any other UAV writes. UAVInstructionHeader1, // here we do nothing but sit and wait for the IncrementCounter() so we can move to the UAV // body state UAVInstructionHeader2, // in this state we aren't sure exactly when to leave it. We wait *at least* until opcode is // written, but there may be more instructions after that to read from dst :( UAVInstructionBody, }; enum class NvUAVParam { opcode = 0, src0 = 76, src1 = 92, src2 = 108, src3 = 28, src4 = 44, src5 = 60, dst = 124, markUAV = 140, numOutputs = 144, }; InstructionState state = InstructionState::Nothing; NvShaderOpcode nvopcode = NvShaderOpcode::Unknown; Operand srcParam[8]; Operand dstParam[4]; Operand uavParam; int numOutputs = 0, outputsNeeded = 0; ToString flags = friendly ? ToString::FriendlyNameRegisters : ToString::None; for(size_t i = 0; i < m_Instructions.size(); i++) { // reserve space for an added instruction so that curOp can stay valid even if we insert a new // op. This only actually does work the first time (or after we've inserted a new // instruction). m_Instructions.reserve(m_Instructions.size() + 1); Operation &curOp = m_Instructions[i]; if(state == InstructionState::Broken) break; if((curOp.operation == OPCODE_IMM_ATOMIC_CMP_EXCH && curOp.operands[1].indices[0].index == magicID) || (curOp.operation == OPCODE_ATOMIC_CMP_STORE && curOp.operands[0].indices[0].index == magicID)) { // AMD operations where the return value isn't used becomes an atomic_cmp_store instead of // imm_atomic_cmp_exch const int32_t instructionIndex = curOp.operation == OPCODE_ATOMIC_CMP_STORE ? 1 : 2; const int32_t param0Index = instructionIndex + 1; const int32_t param1Index = param0Index + 1; Operand dstOperand = curOp.operands[0]; // if we have a store there's no destination, so set it to null if(curOp.operation == OPCODE_ATOMIC_CMP_STORE) { dstOperand = Operand(); dstOperand.type = TYPE_NULL; dstOperand.setComps(0xff, 0xff, 0xff, 0xff); } // AMD operation if(curOp.operands[instructionIndex].type != TYPE_IMMEDIATE32) { RDCERR( ""Expected literal value for AMD extension instruction. Was the shader compiled with "" ""optimisations disabled?""); state = InstructionState::Broken; break; } uint32_t instruction = curOp.operands[instructionIndex].values[0]; if(AMDInstruction::Magic.Get(instruction) == 5) { AMDInstruction::DX12Op amdop; if(m_API == GraphicsAPI::D3D11) amdop = AMDInstruction::convert(AMDInstruction::Opcode11.Get(instruction)); else amdop = AMDInstruction::Opcode12.Get(instruction); uint32_t phase = AMDInstruction::Phase.Get(instruction); if(phase == 0) { srcParam[0] = curOp.operands[param0Index]; srcParam[1] = curOp.operands[param1Index]; } else if(phase == 1) { srcParam[2] = curOp.operands[param0Index]; srcParam[3] = curOp.operands[param1Index]; } else if(phase == 2) { srcParam[4] = curOp.operands[param0Index]; srcParam[5] = curOp.operands[param1Index]; } else if(phase == 3) { srcParam[6] = curOp.operands[param0Index]; srcParam[7] = curOp.operands[param1Index]; } Operation op; switch(amdop) { case AMDInstruction::DX12Op::Readfirstlane: { op.operation = OPCODE_AMD_READFIRSTLANE; op.operands.resize(2); op.operands[0] = dstOperand; op.operands[1].name = ""src""_lit; op.operands[1] = srcParam[0]; break; } case AMDInstruction::DX12Op::Readlane: { op.operation = OPCODE_AMD_READLANE; op.operands.resize(3); op.operands[0] = dstOperand; op.operands[1].name = ""src""_lit; op.operands[1] = srcParam[0]; // lane is encoded in instruction data op.operands[2].name = ""lane""_lit; op.operands[2].type = TYPE_IMMEDIATE32; op.operands[2].numComponents = NUMCOMPS_1; op.operands[2].values[0] = AMDInstruction::Data.Get(instruction); break; } case AMDInstruction::DX12Op::LaneId: { op.operation = OPCODE_AMD_LANEID; op.operands = {dstOperand}; break; } case AMDInstruction::DX12Op::Swizzle: { op.operation = OPCODE_AMD_SWIZZLE; op.operands.resize(2); op.operands[0] = dstOperand; op.operands[1].name = ""src""_lit; op.operands[1] = srcParam[0]; break; } case AMDInstruction::DX12Op::Ballot: { if(phase == 0) { // srcParams already stored, store the dst for phase 0 dstParam[0] = dstOperand; } else if(phase == 1) { op.operation = OPCODE_AMD_BALLOT; op.operands.resize(3); op.operands[0] = dstParam[0]; op.operands[1] = dstOperand; op.operands[2] = srcParam[0]; op.operands[2].name = ""predicate""_lit; } break; } case AMDInstruction::DX12Op::MBCnt: { op.operation = OPCODE_AMD_MBCNT; op.operands.resize(3); op.operands[0] = dstOperand; op.operands[1] = srcParam[0]; op.operands[2] = srcParam[1]; break; } case AMDInstruction::DX12Op::Min3U: case AMDInstruction::DX12Op::Min3F: case AMDInstruction::DX12Op::Med3U: case AMDInstruction::DX12Op::Med3F: case AMDInstruction::DX12Op::Max3U: case AMDInstruction::DX12Op::Max3F: { if(phase == 0) { // don't need the output at all, it's just used to chain the instructions } else if(phase == 1) { switch(amdop) { case AMDInstruction::DX12Op::Min3U: op.operation = OPCODE_AMD_MIN3U; break; case AMDInstruction::DX12Op::Min3F: op.operation = OPCODE_AMD_MIN3F; break; case AMDInstruction::DX12Op::Med3U: op.operation = OPCODE_AMD_MED3U; break; case AMDInstruction::DX12Op::Med3F: op.operation = OPCODE_AMD_MED3F; break; case AMDInstruction::DX12Op::Max3U: op.operation = OPCODE_AMD_MAX3U; break; case AMDInstruction::DX12Op::Max3F: op.operation = OPCODE_AMD_MAX3F; break; default: break; } op.operands.resize(4); op.operands[0] = dstOperand; op.operands[1] = srcParam[0]; op.operands[2] = srcParam[1]; op.operands[3] = srcParam[2]; } break; } case AMDInstruction::DX12Op::BaryCoord: { if(phase == 0) { // srcParams already stored, store the dst for phase 0 dstParam[0] = dstOperand; } else if(phase == 1) { if(AMDInstruction::BaryInterp.Get(instruction) != AMDInstruction::PerspPullModel) { // all modes except pull model have two outputs op.operation = OPCODE_AMD_BARYCOORD; op.operands.resize(2); op.operands[0].name = ""i""_lit; op.operands[0] = dstParam[0]; op.operands[0].name = ""j""_lit; op.operands[1] = dstOperand; } else { dstParam[1] = dstOperand; } } else if(phase == 2) { // all modes except pull model have two outputs op.operation = OPCODE_AMD_BARYCOORD; op.operands.resize(3); op.operands[0].name = ""invW""_lit; op.operands[0] = dstParam[0]; op.operands[1].name = ""invI""_lit; op.operands[1] = dstParam[1]; op.operands[2].name = ""invJ""_lit; op.operands[2] = dstOperand; } break; } case AMDInstruction::DX12Op::VtxParam: { op.operation = OPCODE_AMD_VTXPARAM; op.operands.resize(3); op.operands[0] = dstOperand; // vertexIndex is encoded in instruction data op.operands[1].name = ""vertexIndex""_lit; op.operands[1].type = TYPE_IMMEDIATE32; op.operands[1].numComponents = NUMCOMPS_1; op.operands[1].values[0] = AMDInstruction::VtxParamVertex.Get(instruction); // decode and pretty-ify the parameter index and component op.operands[2].name = ""parameter""_lit; op.operands[2].type = TYPE_INPUT; op.operands[2].numComponents = NUMCOMPS_1; op.operands[2].indices.resize(1); op.operands[2].indices[0].absolute = true; op.operands[2].indices[0].index = AMDInstruction::VtxParamParameter.Get(instruction); op.operands[2].setComps(AMDInstruction::VtxParamComponent.Get(instruction), 0xff, 0xff, 0xff); break; } case AMDInstruction::DX12Op::ViewportIndex: { op.operation = OPCODE_AMD_GET_VIEWPORTINDEX; op.operands = {dstOperand}; break; } case AMDInstruction::DX12Op::RtArraySlice: { op.operation = OPCODE_AMD_GET_RTARRAYSLICE; op.operands = {dstOperand}; break; } case AMDInstruction::DX12Op::WaveReduce: case AMDInstruction::DX12Op::WaveScan: { if(amdop == AMDInstruction::DX12Op::WaveReduce) op.operation = OPCODE_AMD_WAVE_REDUCE; else op.operation = OPCODE_AMD_WAVE_SCAN; op.preciseValues = AMDInstruction::WaveOp.Get(instruction); break; } case AMDInstruction::DX12Op::LoadDwAtAddr: { if(phase == 0) { // don't need the output at all, it's just used to chain the instructions } else if(phase == 1) { op.operation = OPCODE_AMD_LOADDWATADDR; op.operands.resize(4); op.operands[0] = dstOperand; op.operands[1] = srcParam[0]; op.operands[1].name = ""gpuVaLoBits""_lit; op.operands[2] = srcParam[1]; op.operands[2].name = ""gpuVaHiBits""_lit; op.operands[3] = srcParam[2]; op.operands[3].name = ""offset""_lit; } break; } case AMDInstruction::DX12Op::DrawIndex: { op.operation = OPCODE_AMD_GET_DRAWINDEX; op.operands = {dstOperand}; break; } case AMDInstruction::DX12Op::GetWaveSize: { op.operation = OPCODE_AMD_GET_WAVESIZE; op.operands = {dstOperand}; break; } case AMDInstruction::DX12Op::BaseInstance: { op.operation = OPCODE_AMD_GET_BASEINSTANCE; op.operands = {dstOperand}; break; } case AMDInstruction::DX12Op::BaseVertex: { op.operation = OPCODE_AMD_GET_BASEVERTEX; op.operands = {dstOperand}; break; } case AMDInstruction::DX12Op::AtomicU64: { // if we're in the nothing state, move to the AMD UAV state so we watch for a UAV access // and nop it out if(state == InstructionState::Nothing) state = InstructionState::AMDUAVAtomic; VendorAtomicOp atomicop = convert(AMDInstruction::AtomicOp.Get(instruction)); op.preciseValues = atomicop; bool isCAS = (atomicop == ATOMIC_OP_CAS); // for CAS we have four phases, only exit the state when we're in phase 3. For all other // instructions we have three phases so exit in phase 2. if(phase == 3 || (phase == 2 && !isCAS)) { op.operation = OPCODE_AMD_U64_ATOMIC; state = InstructionState::Nothing; // output values first op.operands.push_back(dstParam[0]); op.operands.push_back(dstOperand); // then the saved UAV op.operands.push_back(uavParam); // then the address. This is in params [0], [1], [2]. If they all come from the same // register we can compact this if(srcParam[0].indices == srcParam[1].indices && srcParam[1].indices == srcParam[2].indices) { op.operands.push_back(srcParam[0]); op.operands.back().setComps(srcParam[0].comps[0], srcParam[1].comps[0], srcParam[2].comps[0], 0xff); op.operands.back().name = ""address""_lit; // store in texelOffset whether the parameter is combined (1) or split (2) op.texelOffset[0] = 1; } else { op.operands.push_back(srcParam[0]); op.operands.back().name = ""address.x""_lit; op.operands.back().setComps(srcParam[0].comps[0], 0xff, 0xff, 0xff); op.operands.push_back(srcParam[1]); op.operands.back().name = ""address.y""_lit; op.operands.back().setComps(srcParam[1].comps[0], 0xff, 0xff, 0xff); op.operands.push_back(srcParam[2]); op.operands.back().name = ""address.z""_lit; op.operands.back().setComps(srcParam[2].comps[0], 0xff, 0xff, 0xff); // store in texelOffset whether the parameter is combined (1) or split (2) op.texelOffset[0] = 2; } // for CAS, the compare value next if(isCAS) { if(srcParam[5].indices == srcParam[6].indices) { op.operands.push_back(srcParam[5]); op.operands.back().setComps(srcParam[5].comps[0], srcParam[6].comps[0], 0xff, 0xff); op.operands.back().values[1] = srcParam[6].values[0]; op.operands.back().name = ""compare_value""_lit; // store in texelOffset whether the parameter is combined (1) or split (2) op.texelOffset[1] = 1; } else { op.operands.push_back(srcParam[5].reswizzle(0)); op.operands.back().name = ""compare_value.x""_lit; op.operands.back().setComps(srcParam[5].comps[0], 0xff, 0xff, 0xff); op.operands.push_back(srcParam[6].reswizzle(0)); op.operands.back().name = ""compare_value.y""_lit; op.operands.back().setComps(srcParam[6].comps[0], 0xff, 0xff, 0xff); // store in texelOffset whether the parameter is combined (1) or split (2) op.texelOffset[1] = 2; } } // then the value if(srcParam[3].indices == srcParam[4].indices) { op.operands.push_back(srcParam[3]); op.operands.back().setComps(srcParam[3].comps[0], srcParam[4].comps[0], 0xff, 0xff); op.operands.back().values[1] = srcParam[4].values[0]; op.operands.back().name = ""value""_lit; // store in texelOffset whether the parameter is combined (1) or split (2) op.texelOffset[2] = 1; } else { op.operands.push_back(srcParam[3].reswizzle(0)); op.operands.back().name = ""value.x""_lit; op.operands.back().setComps(srcParam[3].comps[0], 0xff, 0xff, 0xff); op.operands.push_back(srcParam[4].reswizzle(0)); op.operands.back().name = ""value.y""_lit; op.operands.back().setComps(srcParam[4].comps[0], 0xff, 0xff, 0xff); // store in texelOffset whether the parameter is combined (1) or split (2) op.texelOffset[2] = 2; } } // phase 0's destination is the first destination if(phase == 0) dstParam[0] = dstOperand; break; } } // if the operation wasn't set we're on an intermediate phase. operands were saved, // wait until we have the full operation if(op.operation != NUM_REAL_OPCODES) { op.offset = curOp.offset; op.str = ToStr(op.operation); if(op.operation == OPCODE_AMD_BARYCOORD) { switch(AMDInstruction::BaryInterp.Get(instruction)) { case AMDInstruction::LinearCenter: op.str += ""_linear_center""; break; case AMDInstruction::LinearCentroid: op.str += ""_linear_centroid""; break; case AMDInstruction::LinearSample: op.str += ""_linear_sample""; break; case AMDInstruction::PerspCenter: op.str += ""_persp_center""; break; case AMDInstruction::PerspCentroid: op.str += ""_persp_centroid""; break; case AMDInstruction::PerspSample: op.str += ""_persp_sample""; break; case AMDInstruction::PerspPullModel: op.str += ""_persp_pullmodel""; break; default: op.str += ""_unknown""; break; } } else if(op.operation == OPCODE_AMD_SWIZZLE) { switch(AMDInstruction::SwizzleOp.Get(instruction)) { case AMDInstruction::SwapX1: op.str += ""_swap1""; break; case AMDInstruction::SwapX2: op.str += ""_swap2""; break; case AMDInstruction::SwapX4: op.str += ""_swap4""; break; case AMDInstruction::SwapX8: op.str += ""_swap8""; break; case AMDInstruction::SwapX16: op.str += ""_swap16""; break; case AMDInstruction::ReverseX4: op.str += ""_reverse4""; break; case AMDInstruction::ReverseX8: op.str += ""_reverse8""; break; case AMDInstruction::ReverseX16: op.str += ""_reverse16:""; break; case AMDInstruction::ReverseX32: op.str += ""_reverse32:""; break; case AMDInstruction::BCastX2: op.str += ""_bcast2""; break; case AMDInstruction::BCastX4: op.str += ""_bcast4""; break; case AMDInstruction::BCastX8: op.str += ""_bcast8""; break; case AMDInstruction::BCastX16: op.str += ""_bcast16""; break; case AMDInstruction::BCastX32: op.str += ""_bcast32""; break; } } else if(op.operation == OPCODE_AMD_WAVE_REDUCE || op.operation == OPCODE_AMD_WAVE_SCAN) { switch((VendorWaveOp)op.preciseValues) { default: break; case WAVE_OP_ADD_FLOAT: op.str += ""_addf""; break; case WAVE_OP_ADD_SINT: op.str += ""_addi""; break; case WAVE_OP_ADD_UINT: op.str += ""_addu""; break; case WAVE_OP_MUL_FLOAT: op.str += ""_mulf""; break; case WAVE_OP_MUL_SINT: op.str += ""_muli""; break; case WAVE_OP_MUL_UINT: op.str += ""_mulu""; break; case WAVE_OP_MIN_FLOAT: op.str += ""_minf""; break; case WAVE_OP_MIN_SINT: op.str += ""_mini""; break; case WAVE_OP_MIN_UINT: op.str += ""_minu""; break; case WAVE_OP_MAX_FLOAT: op.str += ""_maxf""; break; case WAVE_OP_MAX_SINT: op.str += ""_maxi""; break; case WAVE_OP_MAX_UINT: op.str += ""_maxu""; break; case WAVE_OP_AND: op.str += ""_and""; break; case WAVE_OP_OR: op.str += ""_or""; break; case WAVE_OP_XOR: op.str += ""_xor""; break; } if(op.operation == OPCODE_AMD_WAVE_SCAN) { if(AMDInstruction::WaveOpFlags.Get(instruction) & 0x1) op.str += ""_incl""; if(AMDInstruction::WaveOpFlags.Get(instruction) & 0x2) op.str += ""_excl""; } } for(size_t a = 0; a < op.operands.size(); a++) { if(a == 0) op.str += "" ""; else op.str += "", ""; op.str += op.operands[a].toString(m_Reflection, flags | ToString::ShowSwizzle); } m_Instructions.insert(i + 1, op); } } else { RDCERR(""Expected magic value of 5 in encoded AMD instruction %x"", instruction); state = InstructionState::Broken; break; } if(state == InstructionState::Broken) continue; // remove this operation, but keep the old operation so we can undo this if things go // wrong curOp.stride = curOp.operation; curOp.operation = OPCODE_VENDOR_REMOVED; RDCCOMPILE_ASSERT(sizeof(curOp.stride) >= sizeof(curOp.operation), ""Hackily assuming stride is big enough to hold an operation""); } else if(curOp.operation == OPCODE_IMM_ATOMIC_ALLOC && curOp.operands[1].indices[0].index == magicID) { // NV IncrementCounter() switch(state) { case InstructionState::Broken: case InstructionState::AMDUAVAtomic: break; // in Nothing an increment marks the beginning of an instruction of some type case InstructionState::Nothing: { state = InstructionState::InstructionHeader; break; } case InstructionState::InstructionHeader: { // the transition from instruction to any other state should happen via a markUAV or // opcode write, not with a counter increment RDCERR( ""Expected either markUAV or opcode write before counter increment in unknown "" ""instruction header!""); state = InstructionState::Broken; break; } case InstructionState::InstructionBody: { outputsNeeded--; if(outputsNeeded <= 0) { // once we've emitted all outputs, move to Nothing state state = InstructionState::Nothing; // and emit vendor instruction Operation op; switch(nvopcode) { case NvShaderOpcode::Shuffle: case NvShaderOpcode::ShuffleUp: case NvShaderOpcode::ShuffleDown: case NvShaderOpcode::ShuffleXor: { if(nvopcode == NvShaderOpcode::Shuffle) op.operation = OPCODE_NV_SHUFFLE; else if(nvopcode == NvShaderOpcode::ShuffleUp) op.operation = OPCODE_NV_SHUFFLE_UP; else if(nvopcode == NvShaderOpcode::ShuffleDown) op.operation = OPCODE_NV_SHUFFLE_DOWN; else if(nvopcode == NvShaderOpcode::ShuffleXor) op.operation = OPCODE_NV_SHUFFLE_XOR; op.operands.resize(4); op.operands[0] = curOp.operands[0]; op.operands[1].name = ""value""_lit; op.operands[1] = srcParam[0].reswizzle(0); if(nvopcode == NvShaderOpcode::Shuffle) op.operands[2].name = ""srcLane""_lit; else if(nvopcode == NvShaderOpcode::ShuffleXor) op.operands[2].name = ""laneMask""_lit; else op.operands[2].name = ""delta""_lit; op.operands[2] = srcParam[0].reswizzle(1); op.operands[3].name = ""width""_lit; op.operands[3] = srcParam[0].reswizzle(3); break; } case NvShaderOpcode::VoteAll: case NvShaderOpcode::VoteAny: case NvShaderOpcode::VoteBallot: { if(nvopcode == NvShaderOpcode::VoteAll) op.operation = OPCODE_NV_VOTE_ALL; else if(nvopcode == NvShaderOpcode::VoteAny) op.operation = OPCODE_NV_VOTE_ANY; else if(nvopcode == NvShaderOpcode::VoteBallot) op.operation = OPCODE_NV_VOTE_BALLOT; op.operands.resize(2); op.operands[0] = curOp.operands[0]; op.operands[1] = srcParam[0]; op.operands[1].name = ""predicate""_lit; break; } case NvShaderOpcode::GetLaneId: { op.operation = OPCODE_NV_GET_LANEID; op.operands = {curOp.operands[0]}; break; } case NvShaderOpcode::GetSpecial: { if(srcParam[0].type != TYPE_IMMEDIATE32) { RDCERR(""Expected literal value for special subopcode""); state = InstructionState::Broken; break; } NvShaderSpecial special = (NvShaderSpecial)srcParam[0].values[0]; if(special == NvShaderSpecial::ThreadLtMask) { op.operation = OPCODE_NV_GET_THREADLTMASK; } else if(special == NvShaderSpecial::FootprintSingleLOD) { op.operation = OPCODE_NV_GET_FOOTPRINT_SINGLELOD; } else { RDCERR(""Unexpected special subopcode""); state = InstructionState::Broken; break; } op.operands = {curOp.operands[0]}; break; } case NvShaderOpcode::MatchAny: { op.operation = OPCODE_NV_MATCH_ANY; op.operands.resize(2); op.operands[0] = curOp.operands[0]; op.operands[1] = srcParam[0]; // we don't need src1, it only indicates the number of components in the value, // which we already have break; } case NvShaderOpcode::GetShadingRate: { op.operation = OPCODE_NV_GET_SHADING_RATE; if(dstParam[0].indices == curOp.operands[0].indices && dstParam[1].indices == curOp.operands[0].indices) { op.operands.push_back(curOp.operands[0]); op.operands.back().name = ""result""_lit; // fixup the comps according to the shuffle op.operands.back().setComps( // x dstParam[1].comps[0], // y dstParam[0].comps[0], // z curOp.operands[0].comps[0], 0xff); } else { // these are in reverse order because we read them as numOutputs was decrementing op.operands.push_back(dstParam[1]); op.operands.back().name = ""result.x""_lit; op.operands.push_back(dstParam[0]); op.operands.back().name = ""result.y""_lit; // z is last op.operands.push_back(curOp.operands[0]); op.operands.back().name = ""result.z""_lit; } break; } // all footprint ops are very similar case NvShaderOpcode::Footprint: case NvShaderOpcode::FootprintBias: case NvShaderOpcode::FootprintLevel: case NvShaderOpcode::FootprintGrad: { if(nvopcode == NvShaderOpcode::Footprint) op.operation = OPCODE_NV_FOOTPRINT; else if(nvopcode == NvShaderOpcode::FootprintBias) op.operation = OPCODE_NV_FOOTPRINT_BIAS; else if(nvopcode == NvShaderOpcode::FootprintLevel) op.operation = OPCODE_NV_FOOTPRINT_LEVEL; else if(nvopcode == NvShaderOpcode::FootprintGrad) op.operation = OPCODE_NV_FOOTPRINT_GRAD; // four output values, could be assigned to different registers depending on packing // because they come back as scalars from increment counter. In general we have to // have them separately, but see if they all neatly line up into one output first. if(dstParam[0].indices == curOp.operands[0].indices && dstParam[1].indices == curOp.operands[0].indices && dstParam[2].indices == curOp.operands[0].indices) { op.operands.push_back(curOp.operands[0]); op.operands.back().name = ""result""_lit; // fixup the comps according to the shuffle op.operands.back().setComps( // x dstParam[2].comps[0], // y dstParam[1].comps[0], // z dstParam[0].comps[0], // w curOp.operands[0].comps[0]); } else { // these are in reverse order because we read them as numOutputs was decrementing op.operands.push_back(dstParam[2]); op.operands.back().name = ""result.x""_lit; op.operands.push_back(dstParam[1]); op.operands.back().name = ""result.y""_lit; op.operands.push_back(dstParam[0]); op.operands.back().name = ""result.z""_lit; // w is last op.operands.push_back(curOp.operands[0]); op.operands.back().name = ""result.w""_lit; } // peel out the source parameters op.operands.push_back(srcParam[3].reswizzle(0)); op.operands.back().name = ""texSpace""_lit; op.operands.push_back(srcParam[0].reswizzle(0)); op.operands.back().name = ""texIndex""_lit; op.operands.push_back(srcParam[3].reswizzle(1)); op.operands.back().name = ""smpSpace""_lit; op.operands.push_back(srcParam[0].reswizzle(1)); op.operands.back().name = ""smpIndex""_lit; op.operands.push_back(srcParam[3].reswizzle(2)); op.operands.back().name = ""texType""_lit; op.operands.push_back(srcParam[1]); op.operands.back().comps[3] = 0xff; // location is a float3 op.operands.back().values[3] = 0; op.operands.back().name = ""location""_lit; op.operands.push_back(srcParam[3].reswizzle(3)); op.operands.back().name = ""coarse""_lit; op.operands.push_back(srcParam[1].reswizzle(3)); op.operands.back().name = ""gran""_lit; if(nvopcode == NvShaderOpcode::FootprintBias) { op.operands.push_back(srcParam[2].reswizzle(0)); op.operands.back().name = ""bias""_lit; } else if(nvopcode == NvShaderOpcode::FootprintLevel) { op.operands.push_back(srcParam[2].reswizzle(0)); op.operands.back().name = ""lodLevel""_lit; } else if(nvopcode == NvShaderOpcode::FootprintGrad) { op.operands.push_back(srcParam[2]); op.operands.back().name = ""ddx""_lit; op.operands.push_back(srcParam[5]); op.operands.back().name = ""ddy""_lit; } op.operands.push_back(srcParam[4]); op.operands.back().name = ""offset""_lit; break; } case NvShaderOpcode::ShuffleGeneric: { op.operation = OPCODE_NV_SHUFFLE_GENERIC; op.operands.resize(5); // first output is the actual result op.operands[0] = curOp.operands[0]; // second output is the laneValid we stored previously op.operands[1] = dstParam[0]; op.operands[1].name = ""out laneValid""_lit; // we expect the params are packed into srcParam[0] op.operands[2] = srcParam[0].reswizzle(0); op.operands[2].name = ""value""_lit; op.operands[3] = srcParam[0].reswizzle(1); op.operands[3].name = ""srcLane""_lit; op.operands[4] = srcParam[0].reswizzle(2); op.operands[4].name = ""width""_lit; break; } case NvShaderOpcode::VPRSEvalAttribAtSample: case NvShaderOpcode::VPRSEvalAttribSnapped: { if(nvopcode == NvShaderOpcode::VPRSEvalAttribAtSample) op.operation = OPCODE_NV_VPRS_EVAL_ATTRIB_SAMPLE; else if(nvopcode == NvShaderOpcode::VPRSEvalAttribSnapped) op.operation = OPCODE_NV_VPRS_EVAL_ATTRIB_SNAPPED; // up to four output values, could be assigned to different registers depending on // packing because they come back as scalars from increment counter. In general we // have to have them separately, but see if they all neatly line up into one output // first. bool allSameReg = true; for(int o = 0; o < numOutputs - 1; o++) { if(!(dstParam[o].indices == curOp.operands[0].indices)) { allSameReg = false; break; } } if(allSameReg) { op.operands.push_back(curOp.operands[0]); op.operands.back().name = ""result""_lit; for(int o = 0; o < 4; o++) { if(o >= numOutputs) op.operands.back().comps[o] = 0xff; else if(o + 1 == numOutputs) op.operands.back().comps[o] = curOp.operands[0].comps[0]; else op.operands.back().comps[o] = dstParam[numOutputs - 2 - o].comps[0]; } } else { const char swz[] = ""xyzw""; for(int o = 0; o < numOutputs - 1; o++) { // these are in reverse order because we read them as numOutputs was // decrementing op.operands.push_back(dstParam[numOutputs - 2 - o]); op.operands.back().name = rdcstr(""result."") + swz[o]; } op.operands.push_back(curOp.operands[0]); op.operands.back().name = rdcstr(""result."") + swz[numOutputs - 1]; } op.operands.push_back(srcParam[0]); op.operands.back().name = ""attrib""_lit; if(nvopcode == NvShaderOpcode::VPRSEvalAttribAtSample) { op.operands.push_back(srcParam[1]); op.operands.back().name = ""sampleIndex""_lit; op.operands.push_back(srcParam[2]); op.operands.back().name = ""pixelOffset""_lit; } else if(nvopcode == NvShaderOpcode::VPRSEvalAttribSnapped) { op.operands.push_back(srcParam[1]); op.operands.back().name = ""offset""_lit; } break; } default: RDCERR(""Unexpected non-UAV opcode %d."", nvopcode); state = InstructionState::Broken; break; } if(state == InstructionState::Broken) break; op.offset = curOp.offset; op.str = ToStr(op.operation); for(size_t a = 0; a < op.operands.size(); a++) { if(a == 0) op.str += "" ""; else op.str += "", ""; op.str += op.operands[a].toString(m_Reflection, flags | ToString::ShowSwizzle); } m_Instructions.insert(i + 1, op); } else { dstParam[outputsNeeded - 1] = curOp.operands[0]; } break; } case InstructionState::UAVInstructionHeader1: { RDCERR(""Expected other UAV write before counter increment in UAV instruction header!""); state = InstructionState::Broken; break; } case InstructionState::UAVInstructionHeader2: { // now that we've gotten the UAV, we can go to the body state = InstructionState::UAVInstructionBody; break; } case InstructionState::UAVInstructionBody: { RDCERR( ""Unexpected counter increment while processing UAV instruction body. Expected "" ""opcode!""); state = InstructionState::Broken; break; } } if(state == InstructionState::Broken) continue; // remove this operation, but keep the old operation so we can undo this if things go // wrong curOp.stride = curOp.operation; curOp.operation = OPCODE_VENDOR_REMOVED; } else if(curOp.operation == OPCODE_STORE_STRUCTURED && curOp.operands[0].indices[0].index == magicID) { if(curOp.operands[2].type != TYPE_IMMEDIATE32) { RDCERR(""Expected literal value for UAV write offset""); state = InstructionState::Broken; break; } // NV magic UAV write NvUAVParam param = (NvUAVParam)curOp.operands[2].values[0]; switch(param) { case NvUAVParam::opcode: { if(curOp.operands[3].type != TYPE_IMMEDIATE32) { RDCERR( ""Expected literal value being written as opcode. Was the shader compiled with "" ""optimisations disabled?""); state = InstructionState::Broken; break; } nvopcode = (NvShaderOpcode)curOp.operands[3].values[0]; // if this is NV_EXTN_OP_FP16_ATOMIC we should have come here in UAVInstructionBody. // That we're here now means this is the continuation of an earlier instruction. if(state == InstructionState::InstructionHeader && nvopcode == NvShaderOpcode::FP16Atomic) state = InstructionState::UAVInstructionBody; // if we're in instruction, this is the simple case so move to the output if(state == InstructionState::InstructionHeader) { // if we haven't gotten a number of outputs at all, set it to 1 if(outputsNeeded <= 0) numOutputs = outputsNeeded = 1; state = InstructionState::InstructionBody; } else if(state == InstructionState::UAVInstructionBody) { // emit the instruction now, writing to the index register (which we know is // 'unused'). There might be nothing to read the result value. We'll look out for // loads and post-patch it. // once we've emitted all outputs, move to Nothing state state = InstructionState::Nothing; // and emit vendor instruction Operation op; // write to the index register at first. If there's a subsequent read of dst we'll patch // this instruction with the destination for that. op.operands.push_back(curOp.operands[1]); // also include the UAV we noted elsewhere op.operands.push_back(uavParam); NvShaderAtomic atomicop = NvShaderAtomic::Unknown; switch(nvopcode) { case NvShaderOpcode::FP16Atomic: { op.operation = OPCODE_NV_FP16_ATOMIC; if(srcParam[2].type != TYPE_IMMEDIATE32) { RDCERR( ""Expected literal value as atomic opcode. Was the shader compiled with "" ""optimisations disabled?""); state = InstructionState::Broken; break; } atomicop = (NvShaderAtomic)srcParam[2].values[0]; op.operands.push_back(srcParam[0]); op.operands.back().name = ""address""_lit; op.operands.push_back(srcParam[1]); op.operands.back().name = ""value""_lit; break; } case NvShaderOpcode::FP32Atomic: { op.operation = OPCODE_NV_FP32_ATOMIC; if(srcParam[2].type != TYPE_IMMEDIATE32) { RDCERR( ""Expected literal value as atomic opcode. Was the shader compiled with "" ""optimisations disabled?""); state = InstructionState::Broken; break; } atomicop = (NvShaderAtomic)srcParam[2].values[0]; op.operands.push_back(srcParam[0].reswizzle(0)); op.operands.back().name = ""byteAddress""_lit; op.operands.push_back(srcParam[1].reswizzle(0)); op.operands.back().name = ""value""_lit; break; } case NvShaderOpcode::U64Atomic: { op.operation = OPCODE_NV_U64_ATOMIC; if(srcParam[2].type != TYPE_IMMEDIATE32) { RDCERR( ""Expected literal value as atomic opcode. Was the shader compiled with "" ""optimisations disabled?""); state = InstructionState::Broken; break; } // insert second dummy return value for high bits op.operands.insert(0, curOp.operands[1]); // make both of them NULL op.operands[0].type = TYPE_NULL; op.operands[0].setComps(0xff, 0xff, 0xff, 0xff); op.operands[1].type = TYPE_NULL; op.operands[1].setComps(0xff, 0xff, 0xff, 0xff); atomicop = (NvShaderAtomic)srcParam[2].values[0]; op.operands.push_back(srcParam[0]); op.operands.back().numComponents = NUMCOMPS_1; op.operands.back().name = ""address""_lit; // store in texelOffset whether the parameter is combined (1) or split (2). // on nv we assume the parameters are always combined op.texelOffset[0] = 1; op.texelOffset[1] = 1; op.texelOffset[2] = 1; if(atomicop == NvShaderAtomic::CompareAndSwap) { op.operands.push_back(srcParam[1]); op.operands.back().numComponents = NUMCOMPS_4; op.operands.back().setComps(srcParam[1].comps[0], srcParam[1].comps[1], 0xff, 0xff); op.operands.back().values[1] = srcParam[1].values[1]; op.operands.back().name = ""compareValue""_lit; op.operands.push_back(srcParam[1]); op.operands.back().numComponents = NUMCOMPS_4; op.operands.back().setComps(srcParam[1].comps[2], srcParam[1].comps[3], 0xff, 0xff); op.operands.back().values[1] = srcParam[1].values[3]; op.operands.back().name = ""value""_lit; } else { op.operands.push_back(srcParam[1]); op.operands.back().numComponents = NUMCOMPS_4; op.operands.back().setComps(srcParam[1].comps[0], srcParam[1].comps[1], 0xff, 0xff); op.operands.back().values[1] = srcParam[1].values[1]; op.operands.back().name = ""value""_lit; } break; } default: RDCERR(""Unexpected UAV opcode %d."", nvopcode); state = InstructionState::Broken; break; } if(state == InstructionState::Broken) break; if(atomicop == NvShaderAtomic::Unknown) { RDCERR(""Couldn't determine atomic op""); state = InstructionState::Broken; break; } op.offset = curOp.offset; op.preciseValues = (uint8_t)atomicop; op.str = ToStr(op.operation); switch(atomicop) { case NvShaderAtomic::Unknown: break; case NvShaderAtomic::And: op.str += ""_and""; op.preciseValues = ATOMIC_OP_AND; break; case NvShaderAtomic::Or: op.str += ""_or""; op.preciseValues = ATOMIC_OP_OR; break; case NvShaderAtomic::Xor: op.str += ""_xor""; op.preciseValues = ATOMIC_OP_XOR; break; case NvShaderAtomic::Add: op.str += ""_add""; op.preciseValues = ATOMIC_OP_ADD; break; case NvShaderAtomic::Max: op.str += ""_max""; op.preciseValues = ATOMIC_OP_MAX; break; case NvShaderAtomic::Min: op.str += ""_min""; op.preciseValues = ATOMIC_OP_MIN; break; case NvShaderAtomic::Swap: op.str += ""_swap""; op.preciseValues = ATOMIC_OP_SWAP; break; case NvShaderAtomic::CompareAndSwap: op.str += ""_comp_swap""; op.preciseValues = ATOMIC_OP_CAS; break; } for(size_t a = 0; a < op.operands.size(); a++) { if(a == 0) op.str += "" ""; else op.str += "", ""; op.str += op.operands[a].toString(m_Reflection, flags | ToString::ShowSwizzle); } m_Instructions.insert(i + 1, op); // move into nothing state state = InstructionState::Nothing; } else { // no other state should be writing an opcode. RDCERR(""Writing opcode in unexpected state %d."", state); state = InstructionState::Broken; } break; } case NvUAVParam::markUAV: { if(curOp.operands[3].type != TYPE_IMMEDIATE32 || curOp.operands[3].values[0] != 1) { RDCERR( ""Expected literal 1 being written to markUAV. Was the shader compiled with "" ""optimisations disabled?""); state = InstructionState::Broken; break; } if(state == InstructionState::InstructionHeader) { // start waiting for the user's UAV write state = InstructionState::UAVInstructionHeader1; } else { // no other state should be writing an opcode. RDCERR(""Writing markUAV in unexpected state %d."", state); state = InstructionState::Broken; } break; } // store the src params unconditionally, don't care about the state. case NvUAVParam::src0: { srcParam[0] = curOp.operands[3]; break; } case NvUAVParam::src1: { srcParam[1] = curOp.operands[3]; break; } case NvUAVParam::src2: { srcParam[2] = curOp.operands[3]; break; } case NvUAVParam::src3: { srcParam[3] = curOp.operands[3]; break; } case NvUAVParam::src4: { srcParam[4] = curOp.operands[3]; break; } case NvUAVParam::src5: { srcParam[5] = curOp.operands[3]; break; } case NvUAVParam::dst: { RDCERR(""Unexpected store to dst""); state = InstructionState::Broken; break; } case NvUAVParam::numOutputs: { if(curOp.operands[3].type != TYPE_IMMEDIATE32) { RDCERR( ""Expected literal value being written as numOutputs. Was the shader compiled "" ""with optimisations disabled?""); state = InstructionState::Broken; break; } if(state == InstructionState::InstructionHeader || state == InstructionState::InstructionBody) { // allow writing number of outputs in either header or body (before or after // simple // opcode) numOutputs = outputsNeeded = (int)curOp.operands[3].values[0]; } else { // no other state should be writing an opcode. RDCERR(""Writing numOutputs in unexpected state %d."", state); state = InstructionState::Broken; } break; } default: { RDCERR(""Unexpected offset %u in nvidia magic UAV write."", param); state = InstructionState::Broken; break; } } if(state == InstructionState::Broken) continue; // remove this operation, but keep the old operation so we can undo this if things go // wrong curOp.stride = curOp.operation; curOp.operation = OPCODE_VENDOR_REMOVED; } else if(curOp.operation == OPCODE_LD_STRUCTURED && curOp.operands[3].indices[0].index == magicID) { // NV magic UAV load. This should only be of dst and only in the Nothing state after // we've // emitted a UAV instruction. if(state == InstructionState::Nothing) { if(curOp.operands[2].type == TYPE_IMMEDIATE32) { // NV magic UAV read NvUAVParam param = (NvUAVParam)curOp.operands[2].values[0]; if(param == NvUAVParam::dst) { // search backwards for the last vendor operation. That's the one we're reading // from for(size_t j = i; j > 0; j--) { if(m_Instructions[j].operation >= OPCODE_VENDOR_FIRST) { // re-emit the instruction writing to the actual output now Operation op = m_Instructions[j]; op.offset = curOp.offset; op.operands[0] = curOp.operands[0]; op.str = ToStr(op.operation); // if this is an atomic64, the low/high bits are separate operands if(op.operation == OPCODE_NV_U64_ATOMIC) { op.operands[1] = curOp.operands[0]; op.operands[0].setComps(curOp.operands[0].comps[0], 0xff, 0xff, 0xff); op.operands[1].setComps(curOp.operands[0].comps[1], 0xff, 0xff, 0xff); } switch((VendorAtomicOp)op.preciseValues) { case ATOMIC_OP_NONE: break; case ATOMIC_OP_AND: op.str += ""_and""; break; case ATOMIC_OP_OR: op.str += ""_or""; break; case ATOMIC_OP_XOR: op.str += ""_xor""; break; case ATOMIC_OP_ADD: op.str += ""_add""; break; case ATOMIC_OP_MAX: op.str += ""_max""; break; case ATOMIC_OP_MIN: op.str += ""_min""; break; case ATOMIC_OP_SWAP: op.str += ""_swap""; break; case ATOMIC_OP_CAS: op.str += ""_comp_swap""; break; } for(size_t a = 0; a < op.operands.size(); a++) { if(a == 0) op.str += "" ""; else op.str += "", ""; op.str += op.operands[a].toString(m_Reflection, flags | ToString::ShowSwizzle); } m_Instructions.insert(i + 1, op); // remove the old one, we've replaced it m_Instructions[j].operation = OPCODE_VENDOR_REMOVED; // if we break and try to revert this one, keep it removed m_Instructions[j].stride = OPCODE_VENDOR_REMOVED; // also remove the current one! but back up the original in case something // goes // wrong curOp.stride = curOp.operation; curOp.operation = OPCODE_VENDOR_REMOVED; break; } } } else { RDCERR(""Unexpected read of UAV at offset %d instead of dst (%d)"", param, NvUAVParam::dst); state = InstructionState::Broken; } } else { RDCERR(""Expected literal value for UAV read offset""); state = InstructionState::Broken; } } else { RDCERR(""Unexpected UAV read in state %d."", state); state = InstructionState::Broken; } } else if(state == InstructionState::UAVInstructionHeader1) { // while we're here the next UAV write is snooped if(curOp.operation == OPCODE_STORE_RAW || curOp.operation == OPCODE_STORE_UAV_TYPED) { uavParam = curOp.operands[0]; state = InstructionState::UAVInstructionHeader2; // remove this operation, but keep the old operation so we can undo this if things go // wrong curOp.stride = curOp.operation; curOp.operation = OPCODE_VENDOR_REMOVED; } } else if(state == InstructionState::AMDUAVAtomic) { // similarly for AMD we store the UAV referenced, but we don't change state - that happens // when we see the appropriate phase instruction. if(curOp.operation == OPCODE_STORE_RAW || curOp.operation == OPCODE_STORE_UAV_TYPED) { uavParam = curOp.operands[0]; state = InstructionState::UAVInstructionHeader2; // remove this operation, but keep the old operation so we can undo this if things go // wrong curOp.stride = curOp.operation; curOp.operation = OPCODE_VENDOR_REMOVED; } } // any other operation we completely ignore } if(state == InstructionState::Broken) { // if we broke, restore the operations and remove any added vendor operations for(size_t i = 0; i < m_Instructions.size(); i++) { if(m_Instructions[i].operation == OPCODE_VENDOR_REMOVED) m_Instructions[i].operation = (OpcodeType)m_Instructions[i].stride; else if(m_Instructions[i].operation >= OPCODE_VENDOR_FIRST) m_Instructions[i].operation = OPCODE_VENDOR_REMOVED; } } // erase any OPCODE_VENDOR_REMOVED instructions now for(int32_t i = m_Instructions.count() - 1; i >= 0; i--) { if(m_Instructions[i].operation == OPCODE_VENDOR_REMOVED) m_Instructions.erase(i); } } }; // namespace DXBCBytecode ",16214,True,3409.2156947218605,median "/** * MaNGOS is a full featured server for World of Warcraft, supporting * the following clients: 1.12.x, 2.4.3, 3.3.5a, 4.3.4a and 5.4.8 * * Copyright (C) 2005-2016 MaNGOS project * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * World of Warcraft, and all World of Warcraft or Warcraft art, images, * and lore are copyrighted by Blizzard Entertainment, Inc. */ #include ""Object.h"" #include ""SharedDefines.h"" #include ""WorldPacket.h"" #include ""Opcodes.h"" #include ""Log.h"" #include ""World.h"" #include ""Creature.h"" #include ""Player.h"" #include ""ObjectMgr.h"" #include ""ObjectGuid.h"" #include ""UpdateData.h"" #include ""UpdateMask.h"" #include ""Util.h"" #include ""MapManager.h"" #include ""Log.h"" #include ""Transports.h"" #include ""TargetedMovementGenerator.h"" #include ""WaypointMovementGenerator.h"" #include ""VMapFactory.h"" #include ""CellImpl.h"" #include ""GridNotifiers.h"" #include ""GridNotifiersImpl.h"" #include ""ObjectPosSelector.h"" #include ""TemporarySummon.h"" #include ""movement/packet_builder.h"" #include ""CreatureLinkingMgr.h"" #include ""Chat.h"" #ifdef ENABLE_ELUNA #include ""LuaEngine.h"" #include ""ElunaEventMgr.h"" #endif /* ENABLE_ELUNA */ Object::Object() { m_objectTypeId = TYPEID_OBJECT; m_objectType = TYPEMASK_OBJECT; m_uint32Values = NULL; m_valuesCount = 0; m_inWorld = false; m_objectUpdated = false; } Object::~Object() { if (IsInWorld()) { ///- Do NOT call RemoveFromWorld here, if the object is a player it will crash sLog.outError(""Object::~Object (GUID: %u TypeId: %u) deleted but still in world!!"", GetGUIDLow(), GetTypeId()); MANGOS_ASSERT(false); } if (m_objectUpdated) { sLog.outError(""Object::~Object (GUID: %u TypeId: %u) deleted but still have updated status!!"", GetGUIDLow(), GetTypeId()); MANGOS_ASSERT(false); } delete[] m_uint32Values; } void Object::_InitValues() { m_uint32Values = new uint32[ m_valuesCount ]; memset(m_uint32Values, 0, m_valuesCount * sizeof(uint32)); m_changedValues.resize(m_valuesCount, false); m_objectUpdated = false; } void Object::_Create(uint32 guidlow, uint32 entry, HighGuid guidhigh) { if (!m_uint32Values) { _InitValues(); } ObjectGuid guid = ObjectGuid(guidhigh, entry, guidlow); SetGuidValue(OBJECT_FIELD_GUID, guid); SetUInt32Value(OBJECT_FIELD_TYPE, m_objectType); m_PackGUID.Set(guid); } void Object::_ReCreate(uint32 entry) { if (!m_uint32Values) { _InitValues(); } SetUInt32Value(OBJECT_FIELD_TYPE, m_objectType); SetUInt32Value(OBJECT_FIELD_ENTRY, entry); } void Object::SetObjectScale(float newScale) { SetFloatValue(OBJECT_FIELD_SCALE_X, newScale); } void Object::SendForcedObjectUpdate() { if (!m_inWorld || !m_objectUpdated) { return; } UpdateDataMapType update_players; BuildUpdateData(update_players); RemoveFromClientUpdateList(); WorldPacket packet; // here we allocate a std::vector with a size of 0x10000 for (UpdateDataMapType::iterator iter = update_players.begin(); iter != update_players.end(); ++iter) { iter->second.BuildPacket(&packet); iter->first->GetSession()->SendPacket(&packet); packet.clear(); // clean the string } } void Object::BuildMovementUpdateBlock(UpdateData* data, uint8 flags) const { ByteBuffer buf(500); buf << uint8(UPDATETYPE_MOVEMENT); buf << GetObjectGuid(); BuildMovementUpdate(&buf, flags); data->AddUpdateBlock(buf); } void Object::BuildCreateUpdateBlockForPlayer(UpdateData* data, Player* target) const { if (!target) { return; } uint8 updatetype = UPDATETYPE_CREATE_OBJECT; uint8 updateFlags = m_updateFlag; /** lower flag1 **/ if (target == this) // building packet for yourself { updateFlags |= UPDATEFLAG_SELF; } if (m_isNewObject) { switch (GetObjectGuid().GetHigh()) { case HighGuid::HIGHGUID_DYNAMICOBJECT: case HighGuid::HIGHGUID_CORPSE: case HighGuid::HIGHGUID_PLAYER: case HighGuid::HIGHGUID_UNIT: case HighGuid::HIGHGUID_GAMEOBJECT: updatetype = UPDATETYPE_CREATE_OBJECT2; break; default: break; } } // DEBUG_LOG(""BuildCreateUpdate: update-type: %u, object-type: %u got updateFlags: %X"", updatetype, m_objectTypeId, updateFlags); ByteBuffer buf(500); buf << uint8(updatetype); buf << GetPackGUID(); buf << uint8(m_objectTypeId); BuildMovementUpdate(&buf, updateFlags); UpdateMask updateMask; updateMask.SetCount(m_valuesCount); _SetCreateBits(&updateMask, target); BuildValuesUpdate(updatetype, &buf, &updateMask, target); data->AddUpdateBlock(buf); } void Object::SendCreateUpdateToPlayer(Player* player) { // send create update to player UpdateData upd; WorldPacket packet; BuildCreateUpdateBlockForPlayer(&upd, player); upd.BuildPacket(&packet); player->GetSession()->SendPacket(&packet); } void Object::BuildValuesUpdateBlockForPlayer(UpdateData* data, Player* target) const { ByteBuffer buf(500); buf << uint8(UPDATETYPE_VALUES); buf << GetPackGUID(); UpdateMask updateMask; updateMask.SetCount(m_valuesCount); _SetUpdateBits(&updateMask, target); BuildValuesUpdate(UPDATETYPE_VALUES, &buf, &updateMask, target); data->AddUpdateBlock(buf); } void Object::BuildOutOfRangeUpdateBlock(UpdateData* data) const { data->AddOutOfRangeGUID(GetObjectGuid()); } void Object::DestroyForPlayer(Player* target) const { MANGOS_ASSERT(target); WorldPacket data(SMSG_DESTROY_OBJECT, 8); data << GetObjectGuid(); target->GetSession()->SendPacket(&data); } void Object::BuildMovementUpdate(ByteBuffer* data, uint8 updateFlags) const { Unit const* unit = NULL; uint32 highGuid = 0; MovementFlags moveflags = MOVEFLAG_NONE; switch (m_objectTypeId) { case TYPEID_OBJECT: case TYPEID_ITEM: case TYPEID_CONTAINER: case TYPEID_GAMEOBJECT: case TYPEID_DYNAMICOBJECT: case TYPEID_CORPSE: highGuid = uint32(GetObjectGuid().GetHigh()); break; case TYPEID_PLAYER: // TODO: this code must not be here if (static_cast(this)->GetTransport()) ((Unit*)this)->m_movementInfo.AddMovementFlag(MOVEFLAG_ONTRANSPORT); else ((Unit*)this)->m_movementInfo.RemoveMovementFlag(MOVEFLAG_ONTRANSPORT); case TYPEID_UNIT: unit = static_cast(this); moveflags = unit->m_movementInfo.GetMovementFlags(); break; default: break; } *data << uint8(updateFlags); if (updateFlags & UPDATEFLAG_LIVING) { MANGOS_ASSERT(unit); if (unit->IsStopped() && unit->m_movementInfo.HasMovementFlag(MOVEFLAG_SPLINE_ENABLED)) { sLog.outError(""%s is not moving but have spline movement enabled!"", GetGuidStr().c_str()); ((Unit*)this)->m_movementInfo.RemoveMovementFlag(MovementFlags(MOVEFLAG_SPLINE_ENABLED | MOVEFLAG_FORWARD)); } *data << unit->m_movementInfo; // Unit speeds *data << float(unit->GetSpeed(MOVE_WALK)); *data << float(unit->GetSpeed(MOVE_RUN)); *data << float(unit->GetSpeed(MOVE_RUN_BACK)); *data << float(unit->GetSpeed(MOVE_SWIM)); *data << float(unit->GetSpeed(MOVE_SWIM_BACK)); *data << float(unit->GetSpeed(MOVE_TURN_RATE)); if (unit->m_movementInfo.HasMovementFlag(MOVEFLAG_SPLINE_ENABLED)) Movement::PacketBuilder::WriteCreate(*unit->movespline, *data); } else if (updateFlags & UPDATEFLAG_HAS_POSITION) { *data << ((WorldObject*)this)->GetPositionX(); *data << ((WorldObject*)this)->GetPositionY(); *data << ((WorldObject*)this)->GetPositionZ(); *data << ((WorldObject*)this)->GetOrientation(); } if (updateFlags & UPDATEFLAG_HIGHGUID) *data << highGuid; if (updateFlags & UPDATEFLAG_ALL) *data << (uint32)0x1; if (updateFlags & UPDATEFLAG_FULLGUID) { if (unit && unit->getVictim()) *data << unit->getVictim()->GetPackGUID(); else data->appendPackGUID(0); } if (updateFlags & UPDATEFLAG_TRANSPORT) *data << uint32(WorldTimer::getMSTime()); } void Object::BuildValuesUpdate(uint8 updatetype, ByteBuffer* data, UpdateMask* updateMask, Player* target) const { if (!target) { return; } bool IsActivateToQuest = false; //bool IsPerCasterAuraState = false; // this is called for UPDATETYPE_CREATE_OBJECT, UPDATETYPE_CREATE_OBJECT2, UPDATETYPE_VALUES only if (isType(TYPEMASK_GAMEOBJECT) && !((GameObject*)this)->IsTransport()) { IsActivateToQuest = ((GameObject*)this)->ActivateToQuest(target) || target->isGameMaster(); updateMask->SetBit(GAMEOBJECT_DYN_FLAGS); if (updatetype == UPDATETYPE_VALUES) updateMask->SetBit(GAMEOBJECT_ANIMPROGRESS); } MANGOS_ASSERT(updateMask && updateMask->GetCount() == m_valuesCount); *data << (uint8)updateMask->GetBlockCount(); data->append(updateMask->GetMask(), updateMask->GetLength()); // checking the new bit extraction mechanic //#ifdef _DEBUG uint16 ix = 0; for (uint16 i = 0; i < m_valuesCount; i++) { if (updateMask->GetBit(i)) { ix = updateMask->GetNextSetIndex(ix); if (i != ix) sLog.outError(""ERROR BuildValuesUpdate: new index %u, should be %u for object type %u entry %u"", ix, i, GetTypeId(), GetEntry()); ++ix; } } //#endif // 2 specialized loops for speed optimization in non-unit case if (isType(TYPEMASK_UNIT)) // unit (creature/player) case { uint16 index = 0; while ((index = updateMask->GetNextSetIndex(index)) < m_valuesCount) { if (index == UNIT_NPC_FLAGS) { uint32 appendValue = m_uint32Values[index]; if (GetTypeId() == TYPEID_UNIT) { if (appendValue & UNIT_NPC_FLAG_TRAINER) { if (!((Creature*)this)->IsTrainerOf(target, false)) { appendValue &= ~UNIT_NPC_FLAG_TRAINER; } } if (appendValue & UNIT_NPC_FLAG_STABLEMASTER) { if (target->getClass() != CLASS_HUNTER) { appendValue &= ~UNIT_NPC_FLAG_STABLEMASTER; } } } *data << uint32(appendValue); } // FIXME: Some values at server stored in float format but must be sent to client in uint32 format else if (index >= UNIT_FIELD_BASEATTACKTIME && index <= UNIT_FIELD_RANGEDATTACKTIME) { // convert from float to uint32 and send *data << uint32(m_floatValues[index] < 0 ? 0 : m_floatValues[index]); } // there are some float values which may be negative or can't get negative due to other checks else if ((index >= PLAYER_FIELD_NEGSTAT0 && index <= PLAYER_FIELD_NEGSTAT4) || (index >= PLAYER_FIELD_RESISTANCEBUFFMODSPOSITIVE && index <= (PLAYER_FIELD_RESISTANCEBUFFMODSPOSITIVE + 6)) || (index >= PLAYER_FIELD_RESISTANCEBUFFMODSNEGATIVE && index <= (PLAYER_FIELD_RESISTANCEBUFFMODSNEGATIVE + 6)) || (index >= PLAYER_FIELD_POSSTAT0 && index <= PLAYER_FIELD_POSSTAT4)) { *data << uint32(m_floatValues[index]); } // Gamemasters should be always able to select units - remove not selectable flag else if (index == UNIT_FIELD_FLAGS && target->isGameMaster()) { *data << (m_uint32Values[index] & ~UNIT_FLAG_NOT_SELECTABLE); } /* Hide loot animation for players that aren't permitted to loot the corpse */ else if (index == UNIT_DYNAMIC_FLAGS && GetTypeId() == TYPEID_UNIT) { uint32 send_value = m_uint32Values[index]; /* Initiate pointer to creature so we can check loot */ if (Creature* my_creature = (Creature*)this) /* If the creature is NOT fully looted */ if (!my_creature->loot.isLooted()) /* If the lootable flag is NOT set */ if (!(send_value & UNIT_DYNFLAG_LOOTABLE)) { /* Update it on the creature */ my_creature->SetFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE); /* Update it in the packet */ send_value = send_value | UNIT_DYNFLAG_LOOTABLE; } /* If we're not allowed to loot the target, destroy the lootable flag */ if (!target->isAllowedToLoot((Creature*)this)) if (send_value & UNIT_DYNFLAG_LOOTABLE) { send_value = send_value & ~UNIT_DYNFLAG_LOOTABLE; } /* If we are allowed to loot it and mob is tapped by us, destroy the tapped flag */ bool is_tapped = target->IsTappedByMeOrMyGroup((Creature*)this); /* If the creature has tapped flag but is tapped by us, remove the flag */ if (send_value & UNIT_DYNFLAG_TAPPED && is_tapped) { send_value = send_value & ~UNIT_DYNFLAG_TAPPED; } // Checking SPELL_AURA_EMPATHY and caster if (send_value & UNIT_DYNFLAG_SPECIALINFO && ((Unit*)this)->IsAlive()) { bool bIsEmpathy = false; bool bIsCaster = false; Unit::AuraList const& mAuraEmpathy = ((Unit*)this)->GetAurasByType(SPELL_AURA_EMPATHY); for (Unit::AuraList::const_iterator itr = mAuraEmpathy.begin(); !bIsCaster && itr != mAuraEmpathy.end(); ++itr) { bIsEmpathy = true; // Empathy by aura set if ((*itr)->GetCasterGuid() == target->GetObjectGuid()) bIsCaster = true; // target is the caster of an empathy aura } if (bIsEmpathy && !bIsCaster) // Empathy by aura, but target is not the caster send_value &= ~UNIT_DYNFLAG_SPECIALINFO; } *data << send_value; } else { // send in current format (float as float, uint32 as uint32) *data << m_uint32Values[index]; } ++index; } } else if (isType(TYPEMASK_GAMEOBJECT)) // gameobject case { uint16 index = 0; while ((index = updateMask->GetNextSetIndex(index)) < m_valuesCount) { // send in current format (float as float, uint32 as uint32) if (index == GAMEOBJECT_DYN_FLAGS) { if (IsActivateToQuest) { switch (((GameObject*)this)->GetGoType()) { case GAMEOBJECT_TYPE_QUESTGIVER: case GAMEOBJECT_TYPE_CHEST: case GAMEOBJECT_TYPE_GENERIC: case GAMEOBJECT_TYPE_SPELL_FOCUS: case GAMEOBJECT_TYPE_GOOBER: *data << uint16(GO_DYNFLAG_LO_ACTIVATE); *data << uint16(0); break; default: *data << uint32(0); // unknown, not happen. break; } } else { *data << uint32(0); } // disable quest object } else { *data << m_uint32Values[index]; } // other cases ++index; } } else // other objects case (no special index checks) { uint16 index = 0; while ((index = updateMask->GetNextSetIndex(index)) < m_valuesCount) { // send in current format (float as float, uint32 as uint32) *data << m_uint32Values[index]; ++index; } } } void Object::ClearUpdateMask(bool remove) { if (m_uint32Values) { for (uint16 index = 0; index < m_valuesCount; ++index) { m_changedValues[index] = false; } } if (m_objectUpdated) { if (remove) { RemoveFromClientUpdateList(); } m_objectUpdated = false; } } bool Object::LoadValues(const char* data) { if (!m_uint32Values) { _InitValues(); } Tokens tokens = StrSplit(data, "" ""); if (tokens.size() != m_valuesCount) { return false; } Tokens::iterator iter; int index; for (iter = tokens.begin(), index = 0; index < m_valuesCount; ++iter, ++index) { m_uint32Values[index] = atol((*iter).c_str()); } return true; } void Object::_SetUpdateBits(UpdateMask* updateMask, Player* /*target*/) const { for (uint16 index = 0; index < m_valuesCount; ++index) if (m_changedValues[index]) { updateMask->SetBit(index); } } void Object::_SetCreateBits(UpdateMask* updateMask, Player* /*target*/) const { for (uint16 index = 0; index < m_valuesCount; ++index) if (GetUInt32Value(index) != 0) { updateMask->SetBit(index); } } void Object::SetInt32Value(uint16 index, int32 value) { MANGOS_ASSERT(index < m_valuesCount || PrintIndexError(index, true)); if (m_int32Values[index] != value) { m_int32Values[index] = value; m_changedValues[index] = true; MarkForClientUpdate(); } } void Object::SetUInt32Value(uint16 index, uint32 value) { MANGOS_ASSERT(index < m_valuesCount || PrintIndexError(index, true)); if (m_uint32Values[index] != value) { m_uint32Values[index] = value; m_changedValues[index] = true; MarkForClientUpdate(); } } void Object::UpdateUInt32Value(uint16 index, uint32 value) { MANGOS_ASSERT(index < m_valuesCount || PrintIndexError(index, true)); m_uint32Values[index] = value; m_changedValues[index] = true; } void Object::SetUInt64Value(uint16 index, const uint64& value) { MANGOS_ASSERT(index + 1 < m_valuesCount || PrintIndexError(index, true)); if (*((uint64*) & (m_uint32Values[index])) != value) { m_uint32Values[index] = *((uint32*)&value); m_uint32Values[index + 1] = *(((uint32*)&value) + 1); m_changedValues[index] = true; m_changedValues[index + 1] = true; MarkForClientUpdate(); } } void Object::SetFloatValue(uint16 index, float value) { MANGOS_ASSERT(index < m_valuesCount || PrintIndexError(index, true)); if (m_floatValues[index] != value) { m_floatValues[index] = value; m_changedValues[index] = true; MarkForClientUpdate(); } } void Object::SetByteValue(uint16 index, uint8 offset, uint8 value) { MANGOS_ASSERT(index < m_valuesCount || PrintIndexError(index, true)); if (offset > 4) { sLog.outError(""Object::SetByteValue: wrong offset %u"", offset); return; } if (uint8(m_uint32Values[index] >> (offset * 8)) != value) { m_uint32Values[index] &= ~uint32(uint32(0xFF) << (offset * 8)); m_uint32Values[index] |= uint32(uint32(value) << (offset * 8)); m_changedValues[index] = true; MarkForClientUpdate(); } } void Object::SetUInt16Value(uint16 index, uint8 offset, uint16 value) { MANGOS_ASSERT(index < m_valuesCount || PrintIndexError(index, true)); if (offset > 2) { sLog.outError(""Object::SetUInt16Value: wrong offset %u"", offset); return; } if (uint16(m_uint32Values[index] >> (offset * 16)) != value) { m_uint32Values[index] &= ~uint32(uint32(0xFFFF) << (offset * 16)); m_uint32Values[index] |= uint32(uint32(value) << (offset * 16)); m_changedValues[index] = true; MarkForClientUpdate(); } } void Object::SetStatFloatValue(uint16 index, float value) { if (value < 0) { value = 0.0f; } SetFloatValue(index, value); } void Object::SetStatInt32Value(uint16 index, int32 value) { if (value < 0) { value = 0; } SetUInt32Value(index, uint32(value)); } void Object::ApplyModUInt32Value(uint16 index, int32 val, bool apply) { int32 cur = GetUInt32Value(index); cur += (apply ? val : -val); if (cur < 0) { cur = 0; } SetUInt32Value(index, cur); } void Object::ApplyModInt32Value(uint16 index, int32 val, bool apply) { int32 cur = GetInt32Value(index); cur += (apply ? val : -val); SetInt32Value(index, cur); } void Object::ApplyModSignedFloatValue(uint16 index, float val, bool apply) { float cur = GetFloatValue(index); cur += (apply ? val : -val); SetFloatValue(index, cur); } void Object::ApplyModPositiveFloatValue(uint16 index, float val, bool apply) { float cur = GetFloatValue(index); cur += (apply ? val : -val); if (cur < 0) { cur = 0; } SetFloatValue(index, cur); } void Object::MarkFlagUpdateForClient(uint16 index) { MANGOS_ASSERT(index < m_valuesCount || PrintIndexError(index, true)); m_changedValues[index] = true; MarkForClientUpdate(); } void Object::SetFlag(uint16 index, uint32 newFlag) { MANGOS_ASSERT(index < m_valuesCount || PrintIndexError(index, true)); uint32 oldval = m_uint32Values[index]; uint32 newval = oldval | newFlag; if (oldval != newval) { m_uint32Values[index] = newval; m_changedValues[index] = true; MarkForClientUpdate(); } } void Object::RemoveFlag(uint16 index, uint32 oldFlag) { MANGOS_ASSERT(index < m_valuesCount || PrintIndexError(index, true)); uint32 oldval = m_uint32Values[index]; uint32 newval = oldval & ~oldFlag; if (oldval != newval) { m_uint32Values[index] = newval; m_changedValues[index] = true; MarkForClientUpdate(); } } void Object::RemovePlayerSpecificFlag(uint16 index, uint32 oldFlag, Player* plr) { /* Validate input */ MANGOS_ASSERT(index < m_valuesCount || PrintIndexError(index, true)); uint32 oldval, newval; /* See if we already have custom flags set for the player */ if (m_plrSpecificFlags.find(plr->GetGUIDLow()) != m_plrSpecificFlags.end()) { oldval = m_plrSpecificFlags.find(plr->GetGUIDLow())->second; } /* We don't already have flags, get them from the creature */ else { oldval = m_uint32Values[index]; } /* Set the new flag */ newval = oldval & ~oldval; /* Make sure they're not the same */ if (oldval != newval) { /* Update existing flag */ m_plrSpecificFlags.find(plr->GetGUIDLow())->second = newval; /* Push updates to client */ MarkForClientUpdate(); } } void Object::SetPlayerSpecificFlag(uint16 index, uint32 newFlag, Player* plr) { /* Validate input */ MANGOS_ASSERT(index < m_valuesCount || PrintIndexError(index, true)); uint32 oldval, newval; /* See if we already have custom flags set for the player */ if (m_plrSpecificFlags.find(plr->GetGUIDLow()) != m_plrSpecificFlags.end()) { oldval = m_plrSpecificFlags.find(plr->GetGUIDLow())->second; } /* We don't already have flags, get them from the creature */ else { oldval = m_uint32Values[index]; } /* Set the new flag */ newval = oldval | newFlag; /* Make sure they're not the same */ if (oldval != newval) { /* Update existing flag */ m_plrSpecificFlags.find(plr->GetGUIDLow())->second = newval; /* Push updates to client */ MarkForClientUpdate(); } } void Object::SetByteFlag(uint16 index, uint8 offset, uint8 newFlag) { MANGOS_ASSERT(index < m_valuesCount || PrintIndexError(index, true)); if (offset > 4) { sLog.outError(""Object::SetByteFlag: wrong offset %u"", offset); return; } if (!(uint8(m_uint32Values[index] >> (offset * 8)) & newFlag)) { m_uint32Values[index] |= uint32(uint32(newFlag) << (offset * 8)); m_changedValues[index] = true; MarkForClientUpdate(); } } void Object::RemoveByteFlag(uint16 index, uint8 offset, uint8 oldFlag) { MANGOS_ASSERT(index < m_valuesCount || PrintIndexError(index, true)); if (offset > 4) { sLog.outError(""Object::RemoveByteFlag: wrong offset %u"", offset); return; } if (uint8(m_uint32Values[index] >> (offset * 8)) & oldFlag) { m_uint32Values[index] &= ~uint32(uint32(oldFlag) << (offset * 8)); m_changedValues[index] = true; MarkForClientUpdate(); } } void Object::SetShortFlag(uint16 index, bool highpart, uint16 newFlag) { MANGOS_ASSERT(index < m_valuesCount || PrintIndexError(index, true)); if (!(uint16(m_uint32Values[index] >> (highpart ? 16 : 0)) & newFlag)) { m_uint32Values[index] |= uint32(uint32(newFlag) << (highpart ? 16 : 0)); m_changedValues[index] = true; MarkForClientUpdate(); } } void Object::RemoveShortFlag(uint16 index, bool highpart, uint16 oldFlag) { MANGOS_ASSERT(index < m_valuesCount || PrintIndexError(index, true)); if (uint16(m_uint32Values[index] >> (highpart ? 16 : 0)) & oldFlag) { m_uint32Values[index] &= ~uint32(uint32(oldFlag) << (highpart ? 16 : 0)); m_changedValues[index] = true; MarkForClientUpdate(); } } bool Object::PrintIndexError(uint32 index, bool set) const { sLog.outError(""Attempt %s nonexistent value field: %u (count: %u) for object typeid: %u type mask: %u"", (set ? ""set value to"" : ""get value from""), index, m_valuesCount, GetTypeId(), m_objectType); // ASSERT must fail after function call return false; } bool Object::PrintEntryError(char const* descr) const { sLog.outError(""Object Type %u, Entry %u (lowguid %u) with invalid call for %s"", GetTypeId(), GetEntry(), GetObjectGuid().GetCounter(), descr); // always false for continue assert fail return false; } void Object::BuildUpdateDataForPlayer(Player* pl, UpdateDataMapType& update_players) { UpdateDataMapType::iterator iter = update_players.find(pl); if (iter == update_players.end()) { std::pair p = update_players.insert(UpdateDataMapType::value_type(pl, UpdateData())); MANGOS_ASSERT(p.second); iter = p.first; } BuildValuesUpdateBlockForPlayer(&iter->second, iter->first); } void Object::AddToClientUpdateList() { sLog.outError(""Unexpected call of Object::AddToClientUpdateList for object (TypeId: %u Update fields: %u)"", GetTypeId(), m_valuesCount); MANGOS_ASSERT(false); } void Object::RemoveFromClientUpdateList() { sLog.outError(""Unexpected call of Object::RemoveFromClientUpdateList for object (TypeId: %u Update fields: %u)"", GetTypeId(), m_valuesCount); MANGOS_ASSERT(false); } void Object::BuildUpdateData(UpdateDataMapType& /*update_players */) { sLog.outError(""Unexpected call of Object::BuildUpdateData for object (TypeId: %u Update fields: %u)"", GetTypeId(), m_valuesCount); MANGOS_ASSERT(false); } void Object::MarkForClientUpdate() { if (m_inWorld) { if (!m_objectUpdated) { AddToClientUpdateList(); m_objectUpdated = true; } } } WorldObject::WorldObject() : #ifdef ENABLE_ELUNA elunaEvents(NULL), #endif /* ENABLE_ELUNA */ m_currMap(NULL), m_mapId(0), m_InstanceId(0), m_isActiveObject(false) { } WorldObject::~WorldObject() { #ifdef ENABLE_ELUNA delete elunaEvents; elunaEvents = NULL; #endif /* ENABLE_ELUNA */ } void WorldObject::CleanupsBeforeDelete() { RemoveFromWorld(); } void WorldObject::Update(uint32 update_diff, uint32 /*time_diff*/) { #ifdef ENABLE_ELUNA elunaEvents->Update(update_diff); #endif /* ENABLE_ELUNA */ } void WorldObject::_Create(uint32 guidlow, HighGuid guidhigh) { Object::_Create(guidlow, 0, guidhigh); } void WorldObject::Relocate(float x, float y, float z, float orientation) { m_position.x = x; m_position.y = y; m_position.z = z; m_position.o = MapManager::NormalizeOrientation(orientation); if (isType(TYPEMASK_UNIT)) { ((Unit*)this)->m_movementInfo.ChangePosition(x, y, z, orientation); } } void WorldObject::Relocate(float x, float y, float z) { m_position.x = x; m_position.y = y; m_position.z = z; if (isType(TYPEMASK_UNIT)) { ((Unit*)this)->m_movementInfo.ChangePosition(x, y, z, GetOrientation()); } } void WorldObject::SetOrientation(float orientation) { m_position.o = MapManager::NormalizeOrientation(orientation); if (isType(TYPEMASK_UNIT)) { ((Unit*)this)->m_movementInfo.ChangeOrientation(orientation); } } uint32 WorldObject::GetZoneId() const { return GetTerrain()->GetZoneId(m_position.x, m_position.y, m_position.z); } uint32 WorldObject::GetAreaId() const { return GetTerrain()->GetAreaId(m_position.x, m_position.y, m_position.z); } void WorldObject::GetZoneAndAreaId(uint32& zoneid, uint32& areaid) const { GetTerrain()->GetZoneAndAreaId(zoneid, areaid, m_position.x, m_position.y, m_position.z); } InstanceData* WorldObject::GetInstanceData() const { return GetMap()->GetInstanceData(); } // slow float WorldObject::GetDistance(const WorldObject* obj) const { float dx = GetPositionX() - obj->GetPositionX(); float dy = GetPositionY() - obj->GetPositionY(); float dz = GetPositionZ() - obj->GetPositionZ(); float sizefactor = GetObjectBoundingRadius() + obj->GetObjectBoundingRadius(); float dist = sqrt((dx * dx) + (dy * dy) + (dz * dz)) - sizefactor; return (dist > 0 ? dist : 0); } float WorldObject::GetDistance2d(float x, float y) const { float dx = GetPositionX() - x; float dy = GetPositionY() - y; float sizefactor = GetObjectBoundingRadius(); float dist = sqrt((dx * dx) + (dy * dy)) - sizefactor; return (dist > 0 ? dist : 0); } float WorldObject::GetDistance(float x, float y, float z) const { float dx = GetPositionX() - x; float dy = GetPositionY() - y; float dz = GetPositionZ() - z; float sizefactor = GetObjectBoundingRadius(); float dist = sqrt((dx * dx) + (dy * dy) + (dz * dz)) - sizefactor; return (dist > 0 ? dist : 0); } float WorldObject::GetDistance2d(const WorldObject* obj) const { float dx = GetPositionX() - obj->GetPositionX(); float dy = GetPositionY() - obj->GetPositionY(); float sizefactor = GetObjectBoundingRadius() + obj->GetObjectBoundingRadius(); float dist = sqrt((dx * dx) + (dy * dy)) - sizefactor; return (dist > 0 ? dist : 0); } float WorldObject::GetDistanceZ(const WorldObject* obj) const { float dz = fabs(GetPositionZ() - obj->GetPositionZ()); float sizefactor = GetObjectBoundingRadius() + obj->GetObjectBoundingRadius(); float dist = dz - sizefactor; return (dist > 0 ? dist : 0); } bool WorldObject::IsWithinDist3d(float x, float y, float z, float dist2compare) const { float dx = GetPositionX() - x; float dy = GetPositionY() - y; float dz = GetPositionZ() - z; float distsq = dx * dx + dy * dy + dz * dz; float sizefactor = GetObjectBoundingRadius(); float maxdist = dist2compare + sizefactor; return distsq < maxdist * maxdist; } bool WorldObject::IsWithinDist2d(float x, float y, float dist2compare) const { float dx = GetPositionX() - x; float dy = GetPositionY() - y; float distsq = dx * dx + dy * dy; float sizefactor = GetObjectBoundingRadius(); float maxdist = dist2compare + sizefactor; return distsq < maxdist * maxdist; } bool WorldObject::_IsWithinDist(WorldObject const* obj, float dist2compare, bool is3D) const { float dx = GetPositionX() - obj->GetPositionX(); float dy = GetPositionY() - obj->GetPositionY(); float distsq = dx * dx + dy * dy; if (is3D) { float dz = GetPositionZ() - obj->GetPositionZ(); distsq += dz * dz; } float sizefactor = GetObjectBoundingRadius() + obj->GetObjectBoundingRadius(); float maxdist = dist2compare + sizefactor; return distsq < maxdist * maxdist; } bool WorldObject::IsWithinLOSInMap(const WorldObject* obj) const { if (!IsInMap(obj)) { return false; } float ox, oy, oz; obj->GetPosition(ox, oy, oz); return(IsWithinLOS(ox, oy, oz)); } bool WorldObject::IsWithinLOS(float ox, float oy, float oz) const { float x, y, z; GetPosition(x, y, z); return GetMap()->IsInLineOfSight(x, y, z + 2.0f, ox, oy, oz + 2.0f); } bool WorldObject::GetDistanceOrder(WorldObject const* obj1, WorldObject const* obj2, bool is3D /* = true */) const { float dx1 = GetPositionX() - obj1->GetPositionX(); float dy1 = GetPositionY() - obj1->GetPositionY(); float distsq1 = dx1 * dx1 + dy1 * dy1; if (is3D) { float dz1 = GetPositionZ() - obj1->GetPositionZ(); distsq1 += dz1 * dz1; } float dx2 = GetPositionX() - obj2->GetPositionX(); float dy2 = GetPositionY() - obj2->GetPositionY(); float distsq2 = dx2 * dx2 + dy2 * dy2; if (is3D) { float dz2 = GetPositionZ() - obj2->GetPositionZ(); distsq2 += dz2 * dz2; } return distsq1 < distsq2; } bool WorldObject::IsInRange(WorldObject const* obj, float minRange, float maxRange, bool is3D /* = true */) const { float dx = GetPositionX() - obj->GetPositionX(); float dy = GetPositionY() - obj->GetPositionY(); float distsq = dx * dx + dy * dy; if (is3D) { float dz = GetPositionZ() - obj->GetPositionZ(); distsq += dz * dz; } float sizefactor = GetObjectBoundingRadius() + obj->GetObjectBoundingRadius(); // check only for real range if (minRange > 0.0f) { float mindist = minRange + sizefactor; if (distsq < mindist * mindist) { return false; } } float maxdist = maxRange + sizefactor; return distsq < maxdist * maxdist; } bool WorldObject::IsInRange2d(float x, float y, float minRange, float maxRange) const { float dx = GetPositionX() - x; float dy = GetPositionY() - y; float distsq = dx * dx + dy * dy; float sizefactor = GetObjectBoundingRadius(); // check only for real range if (minRange > 0.0f) { float mindist = minRange + sizefactor; if (distsq < mindist * mindist) { return false; } } float maxdist = maxRange + sizefactor; return distsq < maxdist * maxdist; } bool WorldObject::IsInRange3d(float x, float y, float z, float minRange, float maxRange) const { float dx = GetPositionX() - x; float dy = GetPositionY() - y; float dz = GetPositionZ() - z; float distsq = dx * dx + dy * dy + dz * dz; float sizefactor = GetObjectBoundingRadius(); // check only for real range if (minRange > 0.0f) { float mindist = minRange + sizefactor; if (distsq < mindist * mindist) { return false; } } float maxdist = maxRange + sizefactor; return distsq < maxdist * maxdist; } float WorldObject::GetAngle(const WorldObject* obj) const { if (!obj) { return 0.0f; } // Rework the assert, when more cases where such a call can happen have been fixed // MANGOS_ASSERT(obj != this || PrintEntryError(""GetAngle (for self)"")); if (obj == this) { sLog.outError(""INVALID CALL for GetAngle for %s"", obj->GetGuidStr().c_str()); return 0.0f; } return GetAngle(obj->GetPositionX(), obj->GetPositionY()); } // Return angle in range 0..2*pi float WorldObject::GetAngle(const float x, const float y) const { float dx = x - GetPositionX(); float dy = y - GetPositionY(); float ang = atan2(dy, dx); // returns value between -Pi..Pi ang = (ang >= 0) ? ang : 2 * M_PI_F + ang; return ang; } bool WorldObject::HasInArc(const float arcangle, const WorldObject* obj) const { // always have self in arc if (obj == this) { return true; } float arc = arcangle; // move arc to range 0.. 2*pi arc = MapManager::NormalizeOrientation(arc); float angle = GetAngle(obj); angle -= m_position.o; // move angle to range -pi ... +pi angle = MapManager::NormalizeOrientation(angle); if (angle > M_PI_F) { angle -= 2.0f * M_PI_F; } float lborder = -1 * (arc / 2.0f); // in range -pi..0 float rborder = (arc / 2.0f); // in range 0..pi return ((angle >= lborder) && (angle <= rborder)); } bool WorldObject::isInFrontInMap(WorldObject const* target, float distance, float arc) const { return IsWithinDistInMap(target, distance) && HasInArc(arc, target); } bool WorldObject::isInBackInMap(WorldObject const* target, float distance, float arc) const { return IsWithinDistInMap(target, distance) && !HasInArc(2 * M_PI_F - arc, target); } bool WorldObject::isInFront(WorldObject const* target, float distance, float arc) const { return IsWithinDist(target, distance) && HasInArc(arc, target); } bool WorldObject::isInBack(WorldObject const* target, float distance, float arc) const { return IsWithinDist(target, distance) && !HasInArc(2 * M_PI_F - arc, target); } void WorldObject::GetRandomPoint(float x, float y, float z, float distance, float& rand_x, float& rand_y, float& rand_z, float minDist /*=0.0f*/, float const* ori /*=NULL*/) const { if (distance == 0) { rand_x = x; rand_y = y; rand_z = z; return; } // angle to face `obj` to `this` float angle; if (!ori) angle = rand_norm_f() * 2 * M_PI_F; else angle = *ori; float new_dist; if (minDist == 0.0f) new_dist = rand_norm_f() * distance; else new_dist = minDist + rand_norm_f() * (distance - minDist); rand_x = x + new_dist * cos(angle); rand_y = y + new_dist * sin(angle); rand_z = z; MaNGOS::NormalizeMapCoord(rand_x); MaNGOS::NormalizeMapCoord(rand_y); UpdateGroundPositionZ(rand_x, rand_y, rand_z); // update to LOS height if available } void WorldObject::UpdateGroundPositionZ(float x, float y, float& z) const { float new_z = GetMap()->GetHeight(x, y, z); if (new_z > INVALID_HEIGHT) { z = new_z + 0.05f; } // just to be sure that we are not a few pixel under the surface } void WorldObject::UpdateAllowedPositionZ(float x, float y, float& z, Map* atMap /*=NULL*/) const { if (!atMap) atMap = GetMap(); switch (GetTypeId()) { case TYPEID_UNIT: { // non fly unit don't must be in air // non swim unit must be at ground (mostly speedup, because it don't must be in water and water level check less fast if (!((Creature const*)this)->CanFly()) { bool canSwim = ((Creature const*)this)->CanSwim(); float ground_z = z; float max_z = canSwim ? atMap->GetTerrain()->GetWaterOrGroundLevel(x, y, z, &ground_z, !((Unit const*)this)->HasAuraType(SPELL_AURA_WATER_WALK)) : ((ground_z = atMap->GetHeight(x, y, z))); if (max_z > INVALID_HEIGHT) { if (z > max_z) { z = max_z; } } } else { float ground_z = atMap->GetHeight(x, y, z); if (z < ground_z) { z = ground_z; } } break; } case TYPEID_PLAYER: { // for server controlled moves player work same as creature (but it can always swim) { float ground_z = z; float max_z = atMap->GetTerrain()->GetWaterOrGroundLevel(x, y, z, &ground_z, !((Unit const*)this)->HasAuraType(SPELL_AURA_WATER_WALK)); if (max_z > INVALID_HEIGHT) { if (z > max_z) { z = max_z; } } } break; } default: { float ground_z = atMap->GetHeight(x, y, z); if (ground_z > INVALID_HEIGHT) { z = ground_z; } break; } } } bool WorldObject::IsPositionValid() const { return MaNGOS::IsValidMapCoord(m_position.x, m_position.y, m_position.z, m_position.o); } void WorldObject::MonsterSay(const char* text, uint32 /*language*/, Unit const* target) const { WorldPacket data; ChatHandler::BuildChatPacket(data, CHAT_MSG_MONSTER_SAY, text, LANG_UNIVERSAL, CHAT_TAG_NONE, GetObjectGuid(), GetName(), target ? target->GetObjectGuid() : ObjectGuid(), target ? target->GetName() : """"); SendMessageToSetInRange(&data, sWorld.getConfig(CONFIG_FLOAT_LISTEN_RANGE_SAY), true); } void WorldObject::MonsterYell(const char* text, uint32 /*language*/, Unit const* target) const { WorldPacket data; ChatHandler::BuildChatPacket(data, CHAT_MSG_MONSTER_YELL, text, LANG_UNIVERSAL, CHAT_TAG_NONE, GetObjectGuid(), GetName(), target ? target->GetObjectGuid() : ObjectGuid(), target ? target->GetName() : """"); SendMessageToSetInRange(&data, sWorld.getConfig(CONFIG_FLOAT_LISTEN_RANGE_YELL), true); } void WorldObject::MonsterTextEmote(const char* text, Unit const* target, bool IsBossEmote) const { WorldPacket data; ChatHandler::BuildChatPacket(data, IsBossEmote ? CHAT_MSG_RAID_BOSS_EMOTE : CHAT_MSG_MONSTER_EMOTE, text, LANG_UNIVERSAL, CHAT_TAG_NONE, GetObjectGuid(), GetName(), target ? target->GetObjectGuid() : ObjectGuid(), target ? target->GetName() : """"); SendMessageToSetInRange(&data, sWorld.getConfig(IsBossEmote ? CONFIG_FLOAT_LISTEN_RANGE_YELL : CONFIG_FLOAT_LISTEN_RANGE_TEXTEMOTE), true); } void WorldObject::MonsterWhisper(const char* text, Unit const* target, bool IsBossWhisper) const { if (!target || target->GetTypeId() != TYPEID_PLAYER) { return; } WorldPacket data; ChatHandler::BuildChatPacket(data, IsBossWhisper ? CHAT_MSG_RAID_BOSS_WHISPER : CHAT_MSG_MONSTER_WHISPER, text, LANG_UNIVERSAL, CHAT_TAG_NONE, GetObjectGuid(), GetName(), target->GetObjectGuid(), target->GetName()); ((Player*)target)->GetSession()->SendPacket(&data); } namespace MaNGOS { class MonsterChatBuilder { public: MonsterChatBuilder(WorldObject const& obj, ChatMsg msgtype, MangosStringLocale const* textData, Language language, Unit const* target) : i_object(obj), i_msgtype(msgtype), i_textData(textData), i_language(language), i_target(target) {} void operator()(WorldPacket& data, int32 loc_idx) { char const* text = NULL; if ((int32)i_textData->Content.size() > loc_idx + 1 && !i_textData->Content[loc_idx + 1].empty()) { text = i_textData->Content[loc_idx + 1].c_str(); } else { text = i_textData->Content[0].c_str(); } ChatHandler::BuildChatPacket(data, i_msgtype, text, i_language, CHAT_TAG_NONE, i_object.GetObjectGuid(), i_object.GetNameForLocaleIdx(loc_idx), i_target ? i_target->GetObjectGuid() : ObjectGuid(), i_target ? i_target->GetNameForLocaleIdx(loc_idx) : """"); } private: WorldObject const& i_object; ChatMsg i_msgtype; MangosStringLocale const* i_textData; Language i_language; Unit const* i_target; }; } // namespace MaNGOS /// Helper function to create localized around a source void _DoLocalizedTextAround(WorldObject const* source, MangosStringLocale const* textData, ChatMsg msgtype, Language language, Unit const* target, float range) { MaNGOS::MonsterChatBuilder say_build(*source, msgtype, textData, language, target); MaNGOS::LocalizedPacketDo say_do(say_build); MaNGOS::CameraDistWorker > say_worker(source, range, say_do); Cell::VisitWorldObjects(source, say_worker, range); } /// Function that sends a text associated to a MangosString void WorldObject::MonsterText(MangosStringLocale const* textData, Unit const* target) const { MANGOS_ASSERT(textData); switch (textData->Type) { case CHAT_TYPE_SAY: _DoLocalizedTextAround(this, textData, CHAT_MSG_MONSTER_SAY, textData->LanguageId, target, sWorld.getConfig(CONFIG_FLOAT_LISTEN_RANGE_SAY)); break; case CHAT_TYPE_YELL: _DoLocalizedTextAround(this, textData, CHAT_MSG_MONSTER_YELL, textData->LanguageId, target, sWorld.getConfig(CONFIG_FLOAT_LISTEN_RANGE_YELL)); break; case CHAT_TYPE_TEXT_EMOTE: _DoLocalizedTextAround(this, textData, CHAT_MSG_MONSTER_EMOTE, LANG_UNIVERSAL, target, sWorld.getConfig(CONFIG_FLOAT_LISTEN_RANGE_TEXTEMOTE)); break; case CHAT_TYPE_BOSS_EMOTE: _DoLocalizedTextAround(this, textData, CHAT_MSG_RAID_BOSS_EMOTE, LANG_UNIVERSAL, target, sWorld.getConfig(CONFIG_FLOAT_LISTEN_RANGE_YELL)); break; case CHAT_TYPE_WHISPER: { if (!target || target->GetTypeId() != TYPEID_PLAYER) { return; } MaNGOS::MonsterChatBuilder say_build(*this, CHAT_MSG_MONSTER_WHISPER, textData, LANG_UNIVERSAL, target); MaNGOS::LocalizedPacketDo say_do(say_build); say_do((Player*)target); break; } case CHAT_TYPE_BOSS_WHISPER: { if (!target || target->GetTypeId() != TYPEID_PLAYER) { return; } MaNGOS::MonsterChatBuilder say_build(*this, CHAT_MSG_RAID_BOSS_WHISPER, textData, LANG_UNIVERSAL, target); MaNGOS::LocalizedPacketDo say_do(say_build); say_do((Player*)target); break; } case CHAT_TYPE_ZONE_YELL: { MaNGOS::MonsterChatBuilder say_build(*this, CHAT_MSG_MONSTER_YELL, textData, textData->LanguageId, target); MaNGOS::LocalizedPacketDo say_do(say_build); uint32 zoneid = GetZoneId(); Map::PlayerList const& pList = GetMap()->GetPlayers(); for (Map::PlayerList::const_iterator itr = pList.begin(); itr != pList.end(); ++itr) if (itr->getSource()->GetZoneId() == zoneid) { say_do(itr->getSource()); } break; } } } void WorldObject::SendMessageToSet(WorldPacket* data, bool /*bToSelf*/) const { // if object is in world, map for it already created! if (IsInWorld()) { GetMap()->MessageBroadcast(this, data); } } void WorldObject::SendMessageToSetInRange(WorldPacket* data, float dist, bool /*bToSelf*/) const { // if object is in world, map for it already created! if (IsInWorld()) { GetMap()->MessageDistBroadcast(this, data, dist); } } void WorldObject::SendMessageToSetExcept(WorldPacket* data, Player const* skipped_receiver) const { // if object is in world, map for it already created! if (IsInWorld()) { MaNGOS::MessageDelivererExcept notifier(data, skipped_receiver); Cell::VisitWorldObjects(this, notifier, GetMap()->GetVisibilityDistance()); } } void WorldObject::SendObjectDeSpawnAnim(ObjectGuid guid) { WorldPacket data(SMSG_GAMEOBJECT_DESPAWN_ANIM, 8); data << ObjectGuid(guid); SendMessageToSet(&data, true); } void WorldObject::SendGameObjectCustomAnim(ObjectGuid guid, uint32 animId /*= 0*/) { WorldPacket data(SMSG_GAMEOBJECT_CUSTOM_ANIM, 8 + 4); data << ObjectGuid(guid); data << uint32(animId); SendMessageToSet(&data, true); } void WorldObject::SetMap(Map* map) { MANGOS_ASSERT(map); m_currMap = map; // lets save current map's Id/instanceId m_mapId = map->GetId(); m_InstanceId = map->GetInstanceId(); #ifdef ENABLE_ELUNA delete elunaEvents; // On multithread replace this with a pointer to map's Eluna pointer stored in a map elunaEvents = new ElunaEventProcessor(&Eluna::GEluna, this); #endif } void WorldObject::ResetMap() { #ifdef ENABLE_ELUNA delete elunaEvents; elunaEvents = NULL; #endif m_currMap = NULL; } TerrainInfo const* WorldObject::GetTerrain() const { MANGOS_ASSERT(m_currMap); return m_currMap->GetTerrain(); } void WorldObject::AddObjectToRemoveList() { GetMap()->AddObjectToRemoveList(this); } Creature* WorldObject::SummonCreature(uint32 id, float x, float y, float z, float ang, TempSummonType spwtype, uint32 despwtime, bool asActiveObject) { CreatureInfo const* cinfo = ObjectMgr::GetCreatureTemplate(id); if (!cinfo) { sLog.outErrorDb(""WorldObject::SummonCreature: Creature (Entry: %u) not existed for summoner: %s. "", id, GetGuidStr().c_str()); return NULL; } TemporarySummon* pCreature = new TemporarySummon(GetObjectGuid()); Team team = TEAM_NONE; if (GetTypeId() == TYPEID_PLAYER) { team = ((Player*)this)->GetTeam(); } CreatureCreatePos pos(GetMap(), x, y, z, ang); if (x == 0.0f && y == 0.0f && z == 0.0f) { pos = CreatureCreatePos(this, GetOrientation(), CONTACT_DISTANCE, ang); } if (!pCreature->Create(GetMap()->GenerateLocalLowGuid(cinfo->GetHighGuid()), pos, cinfo, team)) { delete pCreature; return NULL; } pCreature->SetRespawnCoord(pos); // Active state set before added to map pCreature->SetActiveObjectState(asActiveObject); pCreature->Summon(spwtype, despwtime); // Also initializes the AI and MMGen if (GetTypeId() == TYPEID_UNIT && ((Creature*)this)->AI()) { ((Creature*)this)->AI()->JustSummoned(pCreature); } #ifdef ENABLE_ELUNA if (Unit* summoner = ToUnit()) sEluna->OnSummoned(pCreature, summoner); #endif /* ENABLE_ELUNA */ // Creature Linking, Initial load is handled like respawn if (pCreature->IsLinkingEventTrigger()) { GetMap()->GetCreatureLinkingHolder()->DoCreatureLinkingEvent(LINKING_EVENT_RESPAWN, pCreature); } // return the creature therewith the summoner has access to it return pCreature; } GameObject* WorldObject::SummonGameObject(uint32 id, float x, float y, float z, float angle, uint32 despwtime) { GameObject* pGameObj = new GameObject; Map *map = GetMap(); if (!map) return NULL; if (!pGameObj->Create(map->GenerateLocalLowGuid(HIGHGUID_GAMEOBJECT), id, map, x, y, z, angle)) { delete pGameObj; return NULL; } pGameObj->SetRespawnTime(despwtime/IN_MILLISECONDS); map->Add(pGameObj); return pGameObj; } // how much space should be left in front of/ behind a mob that already uses a space #define OCCUPY_POS_DEPTH_FACTOR 1.8f namespace MaNGOS { class NearUsedPosDo { public: NearUsedPosDo(WorldObject const& obj, WorldObject const* searcher, float absAngle, ObjectPosSelector& selector) : i_object(obj), i_searcher(searcher), i_absAngle(MapManager::NormalizeOrientation(absAngle)), i_selector(selector) {} void operator()(Corpse*) const {} void operator()(DynamicObject*) const {} void operator()(Creature* c) const { // skip self or target if (c == i_searcher || c == &i_object) { return; } float x, y, z; if (c->IsStopped() || !c->GetMotionMaster()->GetDestination(x, y, z)) { x = c->GetPositionX(); y = c->GetPositionY(); } add(c, x, y); } template void operator()(T* u) const { // skip self or target if (u == i_searcher || u == &i_object) { return; } float x, y; x = u->GetPositionX(); y = u->GetPositionY(); add(u, x, y); } // we must add used pos that can fill places around center void add(WorldObject* u, float x, float y) const { float dx = i_object.GetPositionX() - x; float dy = i_object.GetPositionY() - y; float dist2d = sqrt((dx * dx) + (dy * dy)); // It is ok for the objects to require a bit more space float delta = u->GetObjectBoundingRadius(); if (i_selector.m_searchPosFor && i_selector.m_searchPosFor != u) { delta += i_selector.m_searchPosFor->GetObjectBoundingRadius(); } delta *= OCCUPY_POS_DEPTH_FACTOR; // Increase by factor // u is too near/far away from i_object. Do not consider it to occupy space if (fabs(i_selector.m_searcherDist - dist2d) > delta) { return; } float angle = i_object.GetAngle(u) - i_absAngle; // move angle to range -pi ... +pi, range before is -2Pi..2Pi if (angle > M_PI_F) { angle -= 2.0f * M_PI_F; } else if (angle < -M_PI_F) { angle += 2.0f * M_PI_F; } i_selector.AddUsedArea(u, angle, dist2d); } private: WorldObject const& i_object; WorldObject const* i_searcher; float i_absAngle; ObjectPosSelector& i_selector; }; } // namespace MaNGOS //=================================================================================================== void WorldObject::GetNearPoint2D(float& x, float& y, float distance2d, float absAngle) const { x = GetPositionX() + distance2d * cos(absAngle); y = GetPositionY() + distance2d * sin(absAngle); MaNGOS::NormalizeMapCoord(x); MaNGOS::NormalizeMapCoord(y); } void WorldObject::GetNearPoint(WorldObject const* searcher, float& x, float& y, float& z, float searcher_bounding_radius, float distance2d, float absAngle) const { GetNearPoint2D(x, y, distance2d, absAngle); const float init_z = z = GetPositionZ(); // if detection disabled, return first point if (!sWorld.getConfig(CONFIG_BOOL_DETECT_POS_COLLISION)) { if (searcher) { searcher->UpdateAllowedPositionZ(x, y, z, GetMap()); } // update to LOS height if available else { UpdateGroundPositionZ(x, y, z); } return; } // or remember first point float first_x = x; float first_y = y; bool first_los_conflict = false; // first point LOS problems const float dist = distance2d + searcher_bounding_radius + GetObjectBoundingRadius(); // prepare selector for work ObjectPosSelector selector(GetPositionX(), GetPositionY(), distance2d, searcher_bounding_radius, searcher); // adding used positions around object { MaNGOS::NearUsedPosDo u_do(*this, searcher, absAngle, selector); MaNGOS::WorldObjectWorker worker(u_do); Cell::VisitAllObjects(this, worker, dist); } // maybe can just place in primary position if (selector.CheckOriginalAngle()) { if (searcher) { searcher->UpdateAllowedPositionZ(x, y, z, GetMap()); } // update to LOS height if available else { UpdateGroundPositionZ(x, y, z); } if (fabs(init_z - z) < dist && IsWithinLOS(x, y, z)) { return; } first_los_conflict = true; // first point have LOS problems } // set first used pos in lists selector.InitializeAngle(); float angle; // candidate of angle for free pos // select in positions after current nodes (selection one by one) while (selector.NextAngle(angle)) // angle for free pos { GetNearPoint2D(x, y, distance2d, absAngle + angle); z = GetPositionZ(); if (searcher) { searcher->UpdateAllowedPositionZ(x, y, z, GetMap()); } // update to LOS height if available else { UpdateGroundPositionZ(x, y, z); } if (fabs(init_z - z) < dist && IsWithinLOS(x, y, z)) { return; } } // BAD NEWS: not free pos (or used or have LOS problems) // Attempt find _used_ pos without LOS problem if (!first_los_conflict) { x = first_x; y = first_y; if (searcher) { searcher->UpdateAllowedPositionZ(x, y, z, GetMap()); } // update to LOS height if available else { UpdateGroundPositionZ(x, y, z); } return; } // set first used pos in lists selector.InitializeAngle(); // select in positions after current nodes (selection one by one) while (selector.NextUsedAngle(angle)) // angle for used pos but maybe without LOS problem { GetNearPoint2D(x, y, distance2d, absAngle + angle); z = GetPositionZ(); if (searcher) { searcher->UpdateAllowedPositionZ(x, y, z, GetMap()); } // update to LOS height if available else { UpdateGroundPositionZ(x, y, z); } if (fabs(init_z - z) < dist && IsWithinLOS(x, y, z)) { return; } } // BAD BAD NEWS: all found pos (free and used) have LOS problem :( x = first_x; y = first_y; if (searcher) { searcher->UpdateAllowedPositionZ(x, y, z, GetMap()); } // update to LOS height if available else { UpdateGroundPositionZ(x, y, z); } } void WorldObject::PlayDistanceSound(uint32 sound_id, Player const* target /*= NULL*/) const { WorldPacket data(SMSG_PLAY_OBJECT_SOUND, 4 + 8); data << uint32(sound_id); data << GetObjectGuid(); if (target) { target->SendDirectMessage(&data); } else { SendMessageToSet(&data, true); } } void WorldObject::PlayDirectSound(uint32 sound_id, Player const* target /*= NULL*/) const { WorldPacket data(SMSG_PLAY_SOUND, 4); data << uint32(sound_id); if (target) { target->SendDirectMessage(&data); } else { SendMessageToSet(&data, true); } } void WorldObject::PlayMusic(uint32 sound_id, Player const* target /*= NULL*/) const { WorldPacket data(SMSG_PLAY_MUSIC, 4); data << uint32(sound_id); if (target) { target->SendDirectMessage(&data); } else { SendMessageToSet(&data, true); } } void WorldObject::UpdateVisibilityAndView() { GetViewPoint().Call_UpdateVisibilityForOwner(); UpdateObjectVisibility(); GetViewPoint().Event_ViewPointVisibilityChanged(); } void WorldObject::UpdateObjectVisibility() { CellPair p = MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()); Cell cell(p); GetMap()->UpdateObjectVisibility(this, cell, p); } void WorldObject::AddToClientUpdateList() { GetMap()->AddUpdateObject(this); } void WorldObject::RemoveFromClientUpdateList() { GetMap()->RemoveUpdateObject(this); } struct WorldObjectChangeAccumulator { UpdateDataMapType& i_updateDatas; WorldObject& i_object; WorldObjectChangeAccumulator(WorldObject& obj, UpdateDataMapType& d) : i_updateDatas(d), i_object(obj) { // send self fields changes in another way, otherwise // with new camera system when player's camera too far from player, camera wouldn't receive packets and changes from player if (i_object.isType(TYPEMASK_PLAYER)) { i_object.BuildUpdateDataForPlayer((Player*)&i_object, i_updateDatas); } } void Visit(CameraMapType& m) { for (CameraMapType::iterator iter = m.begin(); iter != m.end(); ++iter) { Player* owner = iter->getSource()->GetOwner(); if (owner != &i_object && owner->HaveAtClient(&i_object)) { i_object.BuildUpdateDataForPlayer(owner, i_updateDatas); } } } template void Visit(GridRefManager&) {} }; void WorldObject::BuildUpdateData(UpdateDataMapType& update_players) { WorldObjectChangeAccumulator notifier(*this, update_players); Cell::VisitWorldObjects(this, notifier, GetMap()->GetVisibilityDistance()); ClearUpdateMask(false); } bool WorldObject::IsControlledByPlayer() const { switch (GetTypeId()) { case TYPEID_GAMEOBJECT: return ((GameObject*)this)->GetOwnerGuid().IsPlayer(); case TYPEID_UNIT: case TYPEID_PLAYER: return ((Unit*)this)->IsCharmerOrOwnerPlayerOrPlayerItself(); case TYPEID_DYNAMICOBJECT: return ((DynamicObject*)this)->GetCasterGuid().IsPlayer(); case TYPEID_CORPSE: return true; default: return false; } } bool WorldObject::PrintCoordinatesError(float x, float y, float z, char const* descr) const { sLog.outError(""%s with invalid %s coordinates: mapid = %uu, x = %f, y = %f, z = %f"", GetGuidStr().c_str(), descr, GetMapId(), x, y, z); return false; // always false for continue assert fail } void WorldObject::SetActiveObjectState(bool active) { if (m_isActiveObject == active || (isType(TYPEMASK_PLAYER) && !active)) // player shouldn't became inactive, never { return; } if (IsInWorld() && !isType(TYPEMASK_PLAYER)) // player's update implemented in a different from other active worldobject's way // it's considired to use generic way in future { if (isActiveObject() && !active) { GetMap()->RemoveFromActive(this); } else if (!isActiveObject() && active) { GetMap()->AddToActive(this); } } m_isActiveObject = active; } ",16184,True,2516.435163359832,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`. Starting with version 3.1.2, if the consumer is marked as `transacted`, publishing to the DLQ will participate in the transaction. This allows the transaction to roll back if the publishing fails for some reason (for example, if the user is not authorized to publish to the dead letter exchange). In addition, if the connection factory is configured for publisher confirms or returns, the publication to the DLQ will wait for the confirmation and check for a returned message. If a negative acknowledgment or returned message is received, the binder will throw an `AmqpRejectAndDontRequeueException`, allowing the broker to take care of publishing to the DLQ as if the `republishToDlq` property is `false`. 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 consumers; 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). // ====================================================================================== ",12267,False,2251.628537579598,median "[[webflux]] = Spring WebFlux [[webflux-introduction]] == Introduction The original web framework included in the Spring Framework, Spring Web MVC, was purpose built for the Servlet API and Servlet containers. The reactive stack, web framework, Spring WebFlux, was added later in version 5.0. It is fully non-blocking, supports http://www.reactive-streams.org/[Reactive Streams] back pressure, and runs on servers such as Netty, Undertow, and Servlet 3.1+ containers. Both web frameworks mirror the names of their source modules https://github.com/spring-projects/spring-framework/tree/master/spring-webmvc[spring-webmvc] and https://github.com/spring-projects/spring-framework/tree/master/spring-webflux[spring-webflux] and co-exist side by side in the Spring Framework. Each module is optional. Applications may use one or the other module, or in some cases both -- e.g. Spring MVC controllers with the reactive `WebClient`. [[webflux-new-framework]] === Why a new web framework? Part of the answer is the need for a non-blocking web stack to handle concurrency with a small number of threads and scale with less hardware resources. Servlet 3.1 did provide an API for non-blocking I/O. However, using it leads away from the rest of the Servlet API where contracts are synchronous (`Filter`, `Servlet`) or blocking (`getParameter`, `getPart`). This was the motivation for a new common API to serve as a foundation across any non-blocking runtime. That is important because of servers such as Netty that are well established in the async, non-blocking space. The other part of the answer is functional programming. Much like the addition of annotations in Java 5 created opportunities -- e.g. annotated REST controllers or unit tests, the addition of lambda expressions in Java 8 created opportunities for functional APIs in Java. This is a boon for non-blocking applications and continuation style APIs -- as popularized by `CompletableFuture` and http://reactivex.io/[ReactiveX], that allow declarative composition of asynchronous logic. At the programming model level Java 8 enabled Spring WebFlux to offer functional web endpoints alongside with annotated controllers. [[webflux-why-reactive]] === Reactive: what and why? We touched on non-blocking and functional but why reactive and what do we mean? The term ""reactive"" refers to programming models that are built around reacting to change -- network component reacting to I/O events, UI controller reacting to mouse events, etc. In that sense non-blocking is reactive because instead of being blocked we are now in the mode of reacting to notifications as operations complete or data becomes available. There is also another important mechanism that we on the Spring team associate with ""reactive"" and that is non-blocking back pressure. In synchronous, imperative code, blocking calls serve as a natural form of back pressure that forces the caller to wait. In non-blocking code it becomes important to control the rate of events so that a fast producer does not overwhelm its destination. Reactive Streams is a https://github.com/reactive-streams/reactive-streams-jvm/blob/v1.0.1/README.md#specification[small spec], also http://download.java.net/java/jdk9/docs/api/java/util/concurrent/Flow.html[adopted] in Java 9, that defines the interaction between asynchronous components with back pressure. For example a data repository -- acting as http://www.reactive-streams.org/reactive-streams-1.0.1-javadoc/org/reactivestreams/Publisher.html[Publisher], can produce data that an HTTP server -- acting as http://www.reactive-streams.org/reactive-streams-1.0.1-javadoc/org/reactivestreams/Subscriber.html[Subscriber], can then write to the response. The main purpose of Reactive Streams is to allow the subscriber to control how fast or how slow the publisher will produce data. [NOTE] ==== *Common question: what if a publisher can't slow down?* + The purpose of Reactive Streams is only to establish the mechanism and a boundary. If a publisher can't slow down then it has to decide whether to buffer, drop, or fail. ==== [[webflux-reactive-api]] === Reactive API Reactive Streams plays an important role for interoperability. It is of interest to libraries and infrastructure components but less useful as an application API because it is too low level. What applications need is a higher level and richer, functional API to compose async logic -- similar to the Java 8 `Stream` API but not only for collections. This is the role that reactive libraries play. https://github.com/reactor/reactor[Reactor] is the reactive library of choice for Spring WebFlux. It provides the https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Mono.html[Mono] and https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Flux.html[Flux] API types to work on data sequences of 0..1 and 0..N through a rich set of operators aligned with the ReactiveX http://reactivex.io/documentation/operators.html[vocabulary of operators]. Reactor is a Reactive Streams library and therefore all of its operators support non-blocking back pressure. Reactor has a strong focus on server-side Java. It is developed in close collaboration with Spring. WebFlux requires Reactor as a core dependency but it is interoperable with other reactive libraries via Reactive Streams. As a general rule WebFlux APIs accept a plain `Publisher` as input, adapt it to Reactor types internally, use those, and then return either `Flux` or `Mono` as output. So you can pass any `Publisher` as input and you can apply operations on the output, but you'll need to adapt the output for use with another reactive library. Whenever feasible -- e.g. annotated controllers, WebFlux adapts transparently to the use of RxJava or other reactive library. See <> for more details. [[webflux-programming-models]] === Programming models The `spring-web` module contains the reactive foundation that underlies Spring WebFlux -- HTTP abstractions, Reactive Streams server adapters, reactive codecs, and a core Web API whose role is comparable to the Servlet API but with non-blocking semantics. On that foundation Spring WebFlux provides a choice of two programming models: - <> -- consistent with Spring MVC, and based on the same annotations from the `spring-web` module. Both Spring MVC and WebFlux controllers support reactive (Reactor, RxJava) return types and as a result it is not easy to tell them apart. One notable difference is that WebFlux also supports reactive `@RequestBody` arguments. - <> -- lambda-based, lightweight, functional programming model. Think of this as a small library or a set of utilities that an application can use to route and handle requests. The big difference with annotated controllers is that the application is in charge of request handling from start to finish vs declaring intent through annotations and being called back. [[webflux-framework-choice]] === Choosing a web framework Should you use Spring MVC or WebFlux? Let's cover a few different perspectives. If you have a Spring MVC application that works fine, there is no need to change. Imperative programming is the easiest way to write, understand, and debug code. You have maximum choice of libraries since historically most are blocking. If you are already shopping for a non-blocking web stack, Spring WebFlux offers the same execution model benefits as others in this space and also provides a choice of servers -- Netty, Tomcat, Jetty, Undertow, Servlet 3.1+ containers, a choice of programming models -- annotated controllers and functional web endpoints, and a choice of reactive libraries -- Reactor, RxJava, or other. If you are interested in a lightweight, functional web framework for use with Java 8 lambdas or Kotlin then use the Spring WebFlux functional web endpoints. That can also be a good choice for smaller applications or microservices with less complex requirements that can benefit from greater transparency and control. In a microservice architecture you can have a mix of applications with either Spring MVC or Spring WebFlux controllers, or with Spring WebFlux functional endpoints. Having support for the same annotation-based programming model in both frameworks makes it easier to re-use knowledge while also selecting the right tool for the right job. A simple way to evaluate an application is to check its dependencies. If you have blocking persistence APIs (JPA, JDBC), or networking APIs to use, then Spring MVC is the best choice for common architectures at least. It is technically feasible with both Reactor and RxJava to perform blocking calls on a separate thread but you wouldn't be making the most of a non-blocking web stack. If you have a Spring MVC application with calls to remote services, try the reactive `WebClient`. You can return reactive types (Reactor, RxJava, <>) directly from Spring MVC controller methods. The greater the latency per call, or the interdependency among calls, the more dramatic the benefits. Spring MVC controllers can call other reactive components too. If you have a large team, keep in mind the steep learning curve in the shift to non-blocking, functional, and declarative programming. A practical way to start without a full switch is to use the reactive `WebClient`. Beyond that start small and measure the benefits. We expect that for a wide range of applications the shift is unnecessary. If you are unsure what benefits to look for, start by learning about how non-blocking I/O works (e.g. concurrency on single-threaded Node.js is not an oxymoron) and its effects. The tag line is ""scale with less hardware"" but that effect is not guaranteed, not without some network I/O that can be slow or unpredictable. This Netflix https://medium.com/netflix-techblog/zuul-2-the-netflix-journey-to-asynchronous-non-blocking-systems-45947377fb5c[blog post] is a good resource. [[webflux-server-choice]] === Choosing a server Spring WebFlux is supported on Netty, Undertow, Tomcat, Jetty, and Servlet 3.1+ containers. Each server is adapted to a common Reactive Streams API. The Spring WebFlux programming models are built on that common API. [NOTE] ==== *Common question: how can Tomcat and Jetty be used in both stacks?* + Tomcat and Jetty are non-blocking at their core. It's the Servlet API that adds a blocking facade. Starting in version 3.1 the Servlet API adds a choice for non-blocking I/O. However its use requires care to avoid other synchronous and blocking parts. For this reason Spring's reactive web stack has a low-level Servlet adapter to bridge to Reactive Streams but the Servlet API is otherwise not exposed for direct use. ==== Spring Boot 2 uses Netty by default with WebFlux because Netty is more widely used in the async, non-blocking space and also provides both client and server that can share resources. By comparison Servlet 3.1 non-blocking I/O hasn't seen much use because the bar to use it is so high. Spring WebFlux opens one practical path to adoption. The default server choice in Spring Boot is mainly about the out-of-the-box experience. Applications can still choose any of the other supported servers which are also highly optimized for performance, fully non-blocking, and adapted to Reactive Streams back pressure. In Spring Boot it is trivial to make the switch. [[webflux-performance]] === Performance vs scale Performance has many characteristics and meanings. Reactive and non-blocking generally do not make applications run faster. They can, in some cases, for example if using the `WebClient` to execute remote calls in parallel. On the whole it requires more work to do things the non-blocking way and that can increase slightly the required processing time. The key expected benefit of reactive and non-blocking is the ability to scale with a small, fixed number of threads and less memory. That makes applications more resilient under load because they scale in a more predictable way. In order to observe those benefits however you need to have some latency including a mix of slow and unpredictable network I/O. That's where the reactive stack begins to show its strengths and the differences can be dramatic. [[webflux-reactive-spring-web]] == Reactive Spring Web The `spring-web` module provides low level infrastructure and HTTP abstractions -- client and server, to build reactive web applications. All public APIs are build around Reactive Streams with Reactor as a backing implementation. Server support is organized in two layers: * <> and server adapters -- the most basic, common API for HTTP request handling with Reactive Streams back pressure. * <> -- slightly higher level but still general purpose server web API with filter chain style processing. [[webflux-httphandler]] === HttpHandler Every HTTP server has some API for HTTP request handling. {api-spring-framework}/http/server/reactive/HttpHandler.html[HttpHandler] is a simple contract with one method to handle a request and response. It is intentionally minimal. Its main purpose is to provide a common, Reactive Streams based API for HTTP request handling over different servers. The `spring-web` module contains adapters for every supported server. The table below shows the server APIs are used and where Reactive Streams support comes from: [cols=""1,2,2"", options=""header""] |=== |Server name|Server API used|Reactive Streams support |Netty |Netty API |https://github.com/reactor/reactor-netty[Reactor Netty] |Undertow |Undertow API |spring-web: Undertow to Reactive Streams bridge |Tomcat |Servlet 3.1 non-blocking I/O; Tomcat API to read and write ByteBuffers vs byte[] |spring-web: Servlet 3.1 non-blocking I/O to Reactive Streams bridge |Jetty |Servlet 3.1 non-blocking I/O; Jetty API to write ByteBuffers vs byte[] |spring-web: Servlet 3.1 non-blocking I/O to Reactive Streams bridge |Servlet 3.1 container |Servlet 3.1 non-blocking I/O |spring-web: Servlet 3.1 non-blocking I/O to Reactive Streams bridge |=== Here are required dependencies, https://github.com/spring-projects/spring-framework/wiki/What%27s-New-in-the-Spring-Framework[supported versions], and code snippets for each server: |=== |Server name|Group id|Artifact name |Reactor Netty |io.projectreactor.ipc |reactor-netty |Undertow |io.undertow |undertow-core |Tomcat |org.apache.tomcat.embed |tomcat-embed-core |Jetty |org.eclipse.jetty |jetty-server, jetty-servlet |=== Reactor Netty: [source,java,indent=0] [subs=""verbatim,quotes""] ---- HttpHandler handler = ... ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(handler); HttpServer.create(host, port).newHandler(adapter).block(); ---- Undertow: [source,java,indent=0] [subs=""verbatim,quotes""] ---- HttpHandler handler = ... UndertowHttpHandlerAdapter adapter = new UndertowHttpHandlerAdapter(handler); Undertow server = Undertow.builder().addHttpListener(port, host).setHandler(adapter).build(); server.start(); ---- Tomcat: [source,java,indent=0] [subs=""verbatim,quotes""] ---- HttpHandler handler = ... Servlet servlet = new TomcatHttpHandlerAdapter(handler); Tomcat server = new Tomcat(); File base = new File(System.getProperty(""java.io.tmpdir"")); Context rootContext = server.addContext("""", base.getAbsolutePath()); Tomcat.addServlet(rootContext, ""main"", servlet); rootContext.addServletMappingDecoded(""/"", ""main""); server.setHost(host); server.setPort(port); server.start(); ---- Jetty: [source,java,indent=0] [subs=""verbatim,quotes""] ---- HttpHandler handler = ... Servlet servlet = new JettyHttpHandlerAdapter(handler); Server server = new Server(); ServletContextHandler contextHandler = new ServletContextHandler(server, """"); contextHandler.addServlet(new ServletHolder(servlet), ""/""); contextHandler.start(); ServerConnector connector = new ServerConnector(server); connector.setHost(host); connector.setPort(port); server.addConnector(connector); server.start(); ---- [NOTE] ==== To deploy as a WAR to a Servlet 3.1+ container, wrap `HttpHandler` with `ServletHttpHandlerAdapter` and register that as a `Servlet`. This can be automated through the use of {api-spring-framework}/web/server/adapter/AbstractReactiveWebInitializer.html[AbstractReactiveWebInitializer]. ==== [[webflux-web-handler-api]] === WebHandler API `HttpHandler` is the basis for running on different servers. On that base the WebHandler API provides a slightly higher level processing chain of exception handlers ({api-spring-framework}/web/server/WebExceptionHandler.html[WebExceptionHandler]), filters ({api-spring-framework}/web/server/WebFilter.html[WebFilter]), and a target handler ({api-spring-framework}/web/server/WebHandler.html[WebHandler]). All components work on `ServerWebExchange` -- a container for the HTTP request and response that also adds request attributes, session attributes, access to form data, multipart data, and more. The processing chain can be put together with `WebHttpHandlerBuilder` which builds an `HttpHandler` that in turn can be run with a <>. To use the builder either add components individually or point to an `ApplicationContext` to have the following detected: [cols=""2,2,1,3"", options=""header""] |=== |Bean name|Bean type|Count|Description |""webHandler"" |WebHandler |1 |Target handler after filters | |WebFilter |0..N |Filters | |WebExceptionHandler |0..N |Exception handlers after filter chain |""webSessionManager"" |WebSessionManager |0..1 |Custom session manager; `DefaultWebSessionManager` by default |""serverCodecConfigurer"" |ServerCodecConfigurer |0..1 |Custom form and multipart data decoders; `ServerCodecConfigurer.create()` by default |""localeContextResolver"" |LocaleContextResolver |0..1 |Custom resolver for `LocaleContext`; `AcceptHeaderLocaleContextResolver` by default |=== [[webflux-codecs]] === Codecs The `spring-web` module provides {api-spring-framework}/http/codec/HttpMessageReader.html[HttpMessageReader] and {api-spring-framework}/http/codec/HttpMessageWriter.html[HttpMessageWriter] for encoding and decoding the HTTP request and response body with Reactive Streams. It builds on lower level contracts from `spring-core`: * {api-spring-framework}/core/io/buffer/DataBuffer.html[DataBuffer] -- abstraction for byte buffers -- e.g. Netty `ByteBuf`, `java.nio.ByteBuffer` * {api-spring-framework}/core/codec/Encoder.html[Encoder] -- serialize a stream of Objects to a stream of data buffers * {api-spring-framework}/core/codec/Decoder.html[Decoder] -- deserialize a stream of data buffers into a stream of Objects Basic `Encoder` and `Decoder` implementations exist in `spring-core` but `spring-web` adds more for JSON, XML, and other formats. You can wrap any `Encoder` and `Decoder` as a reader or writer with `EncoderHttpMessageWriter` and `DecoderHttpMessageReader`. There are some additional, web-only reader and writer implementations for server-sent events, form data, and more. Finally, `ClientCodecConfigurer` and `ServerCodecConfigurer` can be used to initialize a list of readers and writers. They include support for classpath detection and a of defaults along with the ability to override or replace those defaults. [[webflux-dispatcher-handler]] == DispatcherHandler [.small]#<># Spring WebFlux, like Spring MVC, is designed around the front controller pattern where a central `WebHandler`, the `DispatcherHandler`, provides a shared algorithm for request processing while actual work is performed by configurable, delegate components. This model is flexible and supports diverse workflows. `DispatcherHandler` discovers the delegate components it needs from Spring configuration. It is also designed to be a Spring bean itself and implements `ApplicationContextAware` for access to the context it runs in. If `DispatcherHandler` is declared with the bean name ""webHandler"" it is in turn discovered by {api-spring-framework}/web/server/adapter/WebHttpHandlerBuilder.html[WebHttpHandlerBuilder] which puts together a request processing chain as described in <>. Spring configuration in a WebFlux application typically contains: * `DispatcherHandler` with the bean name ""webHandler"" * `WebFilter` and `WebExceptionHandler` beans * <> * Others The configuration is given to `WebHttpHandlerBuilder` to build the processing chain: [source,java,indent=0] [subs=""verbatim,quotes""] ---- ApplicationContext context = ... HttpHandler handler = WebHttpHandlerBuilder.applicationContext(context); ---- The resulting `HttpHandler` is ready for use with a <>. [[webflux-special-bean-types]] === Special bean types [.small]#<># The `DispatcherHandler` delegates to special beans to process requests and render the appropriate responses. By ""special beans"" we mean Spring-managed Object instances that implement one of the framework contracts listed in the table below. Spring WebFlux provides built-in implementations of these contracts but you can also customize, extend, or replace them. [[webflux-special-beans-table]] [cols=""1,2"", options=""header""] |=== | Bean type| Explanation | HandlerMapping | Map a request to a handler. The mapping is based on some criteria the details of which vary by `HandlerMapping` implementation -- annotated controllers, simple URL pattern mappings, etc. The main `HandlerMapping` implementations are `RequestMappingHandlerMapping` based on `@RequestMapping` annotated methods, `RouterFunctionMapping` based on functional endpoint routes, and `SimpleUrlHandlerMapping` based on explicit registrations of URI path patterns to handlers. | HandlerAdapter | Help the `DispatcherHandler` to invoke a handler mapped to a request regardless of how the handler is actually invoked. For example invoking an annotated controller requires resolving annotations. The main purpose of a `HandlerAdapter` is to shield the `DispatcherHandler` from such details. | HandlerResultHandler | Process the result from the handler invocation and finalize the response. The built-in `HandlerResultHandler` implementations are `ResponseEntityResultHandler` supporting `ResponseEntity` return values, `ResponseBodyResultHandler` supporting `@ResponseBody` methods, `ServerResponseResultHandler` supporting the `ServerResponse` returned from functional endpoints, and `ViewResolutionResultHandler` supporting rendering with a view and a model. |=== [[webflux-framework-config]] === Framework Config [.small]#<># The `DispatcherHandler` detects the special beans it needs in the `ApplicationContext`. Applications can declare the special beans they wish to have. However most applications will find a better starting point in the WebFlux Java config which provide a higher level configuration API that in turn make the necessary bean declarations. See <> for more details. [[webflux-dispatcher-handler-sequence]] === Processing [.small]#<># The `DispatcherHandler` processes requests as follows: * Each `HandlerMapping` is asked to find a matching handler and the first match is used. * If a handler is found, it is executed through an appropriate `HandlerAdapter` which exposes the return value from the execution as `HandlerResult`. * The `HandlerResult` is given to an appropriate `HandlerResultHandler` to complete processing by writing to the response directly or using a view to render. [[webflux-controller]] == Annotated Controllers [.small]#<># Spring WebFlux provides an annotation-based programming model where `@Controller` and `@RestController` components use annotations to express request mappings, request input, exception handling, and more. Annotated controllers have flexible method signatures and do not have to extend base classes nor implement specific interfaces. Here is a basic example: [source,java,indent=0] [subs=""verbatim,quotes""] ---- @RestController public class HelloController { @GetMapping(""/hello"") public String handle() { return ""Hello WebFlux""; } } ---- In this example the methods returns a String to be written to the response body. [[webflux-ann-controller]] === @Controller [.small]#<># You can define controller beans using a standard Spring bean definition. The `@Controller` stereotype allows for auto-detection, aligned with Spring general support for detecting `@Component` classes in the classpath and auto-registering bean definitions for them. It also acts as a stereotype for the annotated class, indicating its role as a web component. To enable auto-detection of such `@Controller` beans, you can add component scanning to your Java configuration: [source,java,indent=0] [subs=""verbatim,quotes""] ---- @Configuration @ComponentScan(""org.example.web"") public class WebConfig { // ... } ---- `@RestController` is a composed annotation that is itself annotated with `@Controller` and `@ResponseBody` indicating a controller whose every method inherits the type-level `@ResponseBody` annotation and therefore writes to the response body (vs model-and-vew rendering). [[webflux-ann-requestmapping]] === Request Mapping [.small]#<># The `@RequestMapping` annotation is used to map requests to controllers methods. It has various attributes to match by URL, HTTP method, request parameters, headers, and media types. It can be used at the class-level to express shared mappings or at the method level to narrow down to a specific endpoint mapping. There are also HTTP method specific shortcut variants of `@RequestMapping`: - `@GetMapping` - `@PostMapping` - `@PutMapping` - `@DeleteMapping` - `@PatchMapping` The shortcut variants are https://github.com/spring-projects/spring-framework/wiki/Spring-Annotation-Programming-Model#composed-annotations[composed annotations] -- themselves annotated with `@RequestMapping`. They are commonly used at the method level. At the class level an `@RequestMapping` is more useful for expressing shared mappings. [source,java,indent=0] [subs=""verbatim,quotes""] ---- @RestController @RequestMapping(""/persons"") class PersonController { @GetMapping(""/{id}"") public Person getPerson(@PathVariable Long id) { // ... } @PostMapping @ResponseStatus(HttpStatus.CREATED) public void add(@RequestBody Person person) { // ... } } ---- [[webflux-ann-requestmapping-uri-templates]] ==== URI Patterns [.small]#<># You can map requests using glob patterns and wildcards: * `?` matches one character * `*` matches zero or more characters within a path segment * `**` match zero or more path segments You can also declare URI variables and access their values with `@PathVariable`: [source,java,indent=0] [subs=""verbatim,quotes""] ---- @GetMapping(""/owners/{ownerId}/pets/{petId}"") public Pet findPet(@PathVariable Long ownerId, @PathVariable Long petId) { // ... } ---- URI variables can be declared at the class and method level: [source,java,intent=0] [subs=""verbatim,quotes""] ---- @Controller @RequestMapping(""/owners/{ownerId}"") public class OwnerController { @GetMapping(""/pets/{petId}"") public Pet findPet(@PathVariable Long ownerId, @PathVariable Long petId) { // ... } } ---- URI variables are automatically converted to the appropriate type or`TypeMismatchException` is raised. Simple types -- `int`, `long`, `Date`, are supported by default and you can register support for any other data type. // TODO: see <> and <>. URI variables can be named explicitly -- e.g. `@PathVariable(""customId"")`, but you can leave that detail out if the names are the same and your code is compiled with debugging information or with the `-parameters` compiler flag on Java 8. The syntax `{*varName}` declares a URI variable that matches zero or more remaining path segments. For example `/resources/{*path}` matches all files `/resources/` and the `""path""` variable captures the complete relative path. The syntax `{varName:regex}` declares a URI variable with a regular expressions with the syntax `{varName:regex}` -- e.g. given URL `""/spring-web-3.0.5 .jar""`, the below method extracts the name, version, and file extension: [source,java,indent=0] [subs=""verbatim,quotes""] ---- @GetMapping(""/{name:[a-z-]+}-{version:\\\\d\\\\.\\\\d\\\\.\\\\d}{ext:\\\\.[a-z]+}"") public void handle(@PathVariable String version, @PathVariable String ext) { // ... } ---- URI path patterns can also have embedded `${...}` placeholders that are resolved on startup via `PropertyPlaceHolderConfigurer` against local, system, environment, and other property sources. This can be used for example to parameterize a base URL based on some external configuration. [NOTE] ==== Spring WebFlux uses `PathPattern` and the `PathPatternParser` for URI path matching support both of which are located in `spring-web` and expressly designed for use with HTTP URL paths in web applications where a large number of URI path patterns are matched at runtime. ==== Spring WebFlux does not support suffix pattern matching -- unlike Spring MVC, where a mapping such as `/person` also matches to `/person.{asterisk}`. For URL based content negotiation, if needed, we recommend using a query parameter, which is simpler, more explicit, and less vulnerable to URL path based exploits. [[webflux-ann-requestmapping-pattern-comparison]] ==== Pattern Comparison [.small]#<># When multiple patterns match a URL, they must be compared to find the best match. This is done with `PathPattern.SPECIFICITY_COMPARATOR` which looks for patterns that more specific. For every pattern, a score is computed based the number of URI variables and wildcards where a URI variable scores lower than a wildcard. A pattern with a lower total score wins. If two patterns have the same score, then the longer is chosen. Catch-all patterns, e.g. `**`, `{*varName}`, are excluded from the scoring and are always sorted last instead. If two patterns are both catch-all, the longer is chosen. [[webflux-ann-requestmapping-consumes]] ==== Consumable Media Types [.small]#<># You can narrow the request mapping based on the `Content-Type` of the request: [source,java,indent=0] [subs=""verbatim,quotes""] ---- @PostMapping(path = ""/pets"", **consumes = ""application/json""**) public void addPet(@RequestBody Pet pet) { // ... } ---- The consumes attribute also supports negation expressions -- e.g. `!text/plain` means any content type other than ""text/plain"". You can declare a shared consumes attribute at the class level. Unlike most other request mapping attributes however when used at the class level, a method-level consumes attribute will overrides rather than extend the class level declaration. [TIP] ==== `MediaType` provides constants for commonly used media types -- e.g. `APPLICATION_JSON_VALUE`, `APPLICATION_JSON_UTF8_VALUE`. ==== [[webflux-ann-requestmapping-produces]] ==== Producible Media Types [.small]#<># You can narrow the request mapping based on the `Accept` request header and the list of content types that a controller method produces: [source,java,indent=0] [subs=""verbatim,quotes""] ---- @GetMapping(path = ""/pets/{petId}"", **produces = ""application/json;charset=UTF-8""**) @ResponseBody public Pet getPet(@PathVariable String petId) { // ... } ---- The media type can specify a character set. Negated expressions are supported -- e.g. `!text/plain` means any content type other than ""text/plain"". You can declare a shared produces attribute at the class level. Unlike most other request mapping attributes however when used at the class level, a method-level produces attribute will overrides rather than extend the class level declaration. [TIP] ==== `MediaType` provides constants for commonly used media types -- e.g. `APPLICATION_JSON_VALUE`, `APPLICATION_JSON_UTF8_VALUE`. ==== [[webflux-ann-requestmapping-params-and-headers]] ==== Parameters and Headers [.small]#<># You can narrow request mappings based on query parameter conditions. You can test for the presence of a query parameter (`""myParam""`), for the absence (`""!myParam""`), or for a specific value (`""myParam=myValue""`): [source,java,indent=0] [subs=""verbatim,quotes""] ---- @GetMapping(path = ""/pets/{petId}"", **params = ""myParam=myValue""**) public void findPet(@PathVariable String petId) { // ... } ---- You can also use the same with request header conditions: [source,java,indent=0] [subs=""verbatim,quotes""] ---- @GetMapping(path = ""/pets"", **headers = ""myHeader=myValue""**) public void findPet(@PathVariable String petId) { // ... } ---- [[webflux-ann-requestmapping-head-options]] ==== HTTP HEAD, OPTIONS [.small]#<># `@GetMapping` -- and also `@RequestMapping(method=HttpMethod.GET)`, support HTTP HEAD transparently for request mapping purposes. Controller methods don't need to change. A response wrapper, applied in the `HttpHandler` server adapter, ensures a `""Content-Length""` header is set to the number of bytes written and without actually writing to the response. By default HTTP OPTIONS is handled by setting the ""Allow"" response header to the list of HTTP methods listed in all `@RequestMapping` methods with matching URL patterns. For a `@RequestMapping` without HTTP method declarations, the ""Allow"" header is set to `""GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS""`. Controller methods should always declare the supported HTTP methods for example by using the HTTP method specific variants -- `@GetMapping`, `@PostMapping`, etc. `@RequestMapping` method can be explicitly mapped to HTTP HEAD and HTTP OPTIONS, but that is not necessary in the common case. [[webflux-ann-methods]] === Handler methods [.small]#<># `@RequestMapping` handler methods have a flexible signature and can choose from a range of supported controller method arguments and return values. [[webflux-ann-arguments]] ==== Method arguments [.small]#<># The table below shows supported controller method arguments. Reactive types (Reactor, RxJava, <>) are supported on arguments that require blocking I/O, e.g. reading the request body, to be resolved. This is marked in the description column. Reactive types are not expected on arguments that don't require blocking. JDK 1.8's `java.util.Optional` is supported as a method argument in combination with annotations that have a `required` attribute -- e.g. `@RequestParam`, `@RequestHeader`, etc, and is equivalent to `required=false`. [cols=""1,2"", options=""header""] |=== |Controller method argument|Description |`ServerWebExchange` |Access to the full `ServerWebExchange` -- container for the HTTP request and response, request and session attributes, `checkNotModified` methods, and others. |`ServerHttpRequest`, `ServerHttpResponse` |Access to the HTTP request or response. |`WebSession` |Access to the session; this does not forcing the start of a new session unless attributes are added. Supports reactive types. |`java.security.Principal` |Currently authenticated user; possibly a specific `Principal` implementation class if known. Supports reactive types. |`org.springframework.http.HttpMethod` |The HTTP method of the request. |`java.util.Locale` |The current request locale, determined by the most specific `LocaleResolver` available, in effect, the configured `LocaleResolver`/`LocaleContextResolver`. |Java 6+: `java.util.TimeZone` + Java 8+: `java.time.ZoneId` |The time zone associated with the current request, as determined by a `LocaleContextResolver`. |`@PathVariable` |For access to URI template variables. // TODO: See <>. |`@MatrixVariable` |For access to name-value pairs in URI path segments. // TODO: See <>. |`@RequestParam` |For access to Servlet request parameters. Parameter values are converted to the declared method argument type. // TODO: See <>. |`@RequestHeader` |For access to request headers. Header values are converted to the declared method argument type. // TODO: See <>. |`@RequestBody` |For access to the HTTP request body. Body content is converted to the declared method argument type using ``HttpMessageReader``'s. Supports reactive types. // TODO: See <>. |`HttpEntity` |For access to request headers and body. The body is converted with ``HttpMessageReader``'s. Supports reactive types. // TODO: See <>. |`@RequestPart` |For access to a part in a ""multipart/form-data"" request. Supports reactive types. // TODO: See <> and <>. |`java.util.Map`, `org.springframework.ui.Model`, `org.springframework.ui.ModelMap` |For access and updates of the implicit model that is exposed to the web view. |Command or form object (with optional `@ModelAttribute`) |Command object whose properties to bind to request parameters -- via setters or directly to fields, with customizable type conversion, depending on `@InitBinder` methods and/or the HandlerAdapter configuration (see the `webBindingInitializer` property on `RequestMappingHandlerAdapter`). Command objects along with their validation results are exposed as model attributes, by default using the command class name - e.g. model attribute ""orderAddress"" for a command object of type ""some.package.OrderAddress"". `@ModelAttribute` can be used to customize the model attribute name. Supports reactive types. |`Errors`, `BindingResult` |Validation results for the command/form object data binding; this argument must be declared immediately after the command/form object in the controller method signature. |`SessionStatus` |For marking form processing complete which triggers cleanup of session attributes declared through a class-level `@SessionAttributes` annotation. |`UriComponentsBuilder` |For preparing a URL relative to the current request's host, port, scheme, context path, and the literal part of the servlet mapping also taking into account `Forwarded` and `X-Forwarded-*` headers. |`@SessionAttribute` |For access to any session attribute; in contrast to model attributes stored in the session as a result of a class-level `@SessionAttributes` declaration. |`@RequestAttribute` |For access to request attributes. |=== [[webflux-ann-return-types]] ==== Return values [.small]#<># The table below shows supported controller method return values. Reactive types -- Reactor, RxJava, <> are supported for all return values. [cols=""1,2"", options=""header""] |=== |Controller method return value|Description |`@ResponseBody` |The return value is encoded through ``HttpMessageWriter``s and written to the response. // TODO: See <>. |`HttpEntity`, `ResponseEntity` |The return value specifies the full response including HTTP headers and body be encoded through ``HttpMessageWriter``s and written to the response. // TODO: See <>. |`HttpHeaders` |For returning a response with headers and no body. |`String` |A view name to be resolved with ``ViewResolver``'s and used together with the implicit model -- determined through command objects and `@ModelAttribute` methods. The handler method may also programmatically enrich the model by declaring a `Model` argument (see above). |`View` |A `View` instance to use for rendering together with the implicit model -- determined through command objects and `@ModelAttribute` methods. The handler method may also programmatically enrich the model by declaring a `Model` argument (see above). |`java.util.Map`, `org.springframework.ui.Model` |Attributes to be added to the implicit model with the view name implicitly determined from the request path. |`Rendering` |An API for model and view rendering scenarios. |`void` |A method with a `void`, possibly async (e.g. `Mono`), return type (or a `null` return value) is considered to have fully handled the response if it also has a `ServerHttpResponse`, or a `ServerWebExchange` argument, or an `@ResponseStatus` annotation. The same is true also if the controller has made a positive ETag or lastModified timestamp check. // TODO (see <> for details) If none of the above is true, a `void` return type may also indicate ""no response body"" for REST controllers, or default view name selection for HTML controllers. |`Flux`, `Observable`, or other reactive type |Emit server-sent events; the `SeverSentEvent` wrapper can be omitted when only data needs to be written (however `text/event-stream` must be requested or declared in the mapping through the produces attribute). |Any other return type |A single model attribute to be added to the implicit model with the view name implicitly determined through a `RequestToViewNameTranslator`; the attribute name may be specified through a method-level `@ModelAttribute` or otherwise a name is selected based on the class name of the return type. |=== include::webflux-functional.adoc[leveloffset=+1] [[webflux-config]] == WebFlux Java Config [.small]#<># The WebFlux Java config provides default configuration suitable for most applications along with a configuration API to customize it. For more advanced customizations, not available in the configuration API, see <>. You do not need to understand the underlying beans created by the Java config, but it's easy to seem them in `WebFluxConfigurationSupport`, and if you want to learn more, see <>. [[webflux-config-enable]] === Enable WebFlux config [.small]#<># Use the `@EnableWebFlux` annotation in your Java config: [source,java,indent=0] [subs=""verbatim,quotes""] ---- @Configuration @EnableWebFlux public class WebConfig { } ---- The above registers a number of Spring WebFlux <> also adapting to dependencies available on the classpath -- for JSON, XML, etc. [[webflux-config-customize]] === WebFlux config API [.small]#<># In your Java config implement the `WebFluxConfigurer` interface: [source,java,indent=0] [subs=""verbatim,quotes""] ---- @Configuration @EnableWebFlux public class WebConfig implements WebFluxConfigurer { // Implement configuration methods... } ---- [[webflux-config-conversion]] === Conversion, formatting [.small]#<># By default formatters for `Number` and `Date` types are installed, including support for the `@NumberFormat` and `@DateTimeFormat` annotations. Full support for the Joda Time formatting library is also installed if Joda Time is present on the classpath. To register custom formatters and converters: [source,java,indent=0] [subs=""verbatim,quotes""] ---- @Configuration @EnableWebFlux public class WebConfig implements WebFluxConfigurer { @Override public void addFormatters(FormatterRegistry registry) { // ... } } ---- [NOTE] ==== See <> and the `FormattingConversionServiceFactoryBean` for more information on when to use FormatterRegistrars. ==== [[webflux-config-validation]] === Validation [.small]#<># By default if <> is present on the classpath -- e.g. Hibernate Validator, the `LocalValidatorFactoryBean` is registered as a global <> for use with `@Valid` and `Validated` on `@Controller` method arguments. In your Java config, you can customize the global `Validator` instance: [source,java,indent=0] [subs=""verbatim,quotes""] ---- @Configuration @EnableWebFlux public class WebConfig implements WebFluxConfigurer { @Override public Validator getValidator(); { // ... } } ---- Note that you can also register ``Validator``'s locally: [source,java,indent=0] [subs=""verbatim,quotes""] ---- @Controller public class MyController { @InitBinder protected void initBinder(WebDataBinder binder) { binder.addValidators(new FooValidator()); } } ---- [TIP] ==== If you need to have a `LocalValidatorFactoryBean` injected somewhere, create a bean and mark it with `@Primary` in order to avoid conflict with the one declared in the MVC config. ==== [[webflux-config-content-negotiation]] === Content type resolvers [.small]#<># You can configure how Spring WebFlux determines the requested media types for ``@Controller``'s from the request. By default only the ""Accept"" header is checked but you can also enable a query parameter based strategy. To customize the requested content type resolution: [source,java,indent=0] [subs=""verbatim,quotes""] ---- @Configuration @EnableWebFlux public class WebConfig implements WebFluxConfigurer { @Override public void configureContentTypeResolver(RequestedContentTypeResolverBuilder builder) { // ... } } ---- [[webflux-config-message-codecs]] === HTTP message codecs [.small]#<># To customize how the request and response body are read and written: [source,java,indent=0] [subs=""verbatim,quotes""] ---- @Configuration @EnableWebFlux public class WebConfig implements WebFluxConfigurer { @Override public void configureHttpMessageCodecs(ServerCodecConfigurer configurer) { // ... } } ---- `ServerCodecConfigurer` provides a set of default readers and writers. You can use it to add more readers and writers, customize the default ones, or replace the default ones completely. For Jackson JSON and XML, consider using the {api-spring-framework}/http/converter/json/Jackson2ObjectMapperBuilder.html[Jackson2ObjectMapperBuilder] which customizes Jackson's default properties with the following ones: . http://fasterxml.github.io/jackson-databind/javadoc/2.6/com/fasterxml/jackson/databind/DeserializationFeature.html#FAIL_ON_UNKNOWN_PROPERTIES[`DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES`] is disabled. . http://fasterxml.github.io/jackson-databind/javadoc/2.6/com/fasterxml/jackson/databind/MapperFeature.html#DEFAULT_VIEW_INCLUSION[`MapperFeature.DEFAULT_VIEW_INCLUSION`] is disabled. It also automatically registers the following well-known modules if they are detected on the classpath: . https://github.com/FasterXML/jackson-datatype-jdk7[jackson-datatype-jdk7]: support for Java 7 types like `java.nio.file.Path`. . https://github.com/FasterXML/jackson-datatype-joda[jackson-datatype-joda]: support for Joda-Time types. . https://github.com/FasterXML/jackson-datatype-jsr310[jackson-datatype-jsr310]: support for Java 8 Date & Time API types. . https://github.com/FasterXML/jackson-datatype-jdk8[jackson-datatype-jdk8]: support for other Java 8 types like `Optional`. [[webflux-config-view-resolvers]] === View resolvers [.small]#<># To configure view resolution: [source,java,indent=0] [subs=""verbatim,quotes""] ---- @Configuration @EnableWebFlux public class WebConfig implements WebFluxConfigurer { @Override public void configureViewResolvers(ViewResolverRegistry registry) { // ... } } ---- Note that FreeMarker also requires configuration of the underlying view technology: [source,java,indent=0] [subs=""verbatim,quotes""] ---- @Configuration @EnableWebFlux public class WebConfig implements WebFluxConfigurer { // ... @Bean public FreeMarkerConfigurer freeMarkerConfigurer() { FreeMarkerConfigurer configurer = new FreeMarkerConfigurer(); configurer.setTemplateLoaderPath(""classpath:/templates""); return configurer; } } ---- [[webflux-config-static-resources]] === Static resources [.small]#<># This option provides a convenient way to serve static resources from a list of {api-spring-framework}/core/io/Resource.html[Resource]-based locations. In the example below, given a request that starts with `""/resources""`, the relative path is used to find and serve static resources relative to `""/static""` on the classpath. Resources will be served with a 1-year future expiration to ensure maximum use of the browser cache and a reduction in HTTP requests made by the browser. The `Last-Modified` header is also evaluated and if present a `304` status code is returned. [source,java,indent=0] [subs=""verbatim""] ---- @Configuration @EnableWebFlux public class WebConfig implements WebFluxConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler(""/resources/**"") .addResourceLocations(""/public"", ""classpath:/static/"") .setCachePeriod(31556926); } } ---- // TODO: // See also <>. The resource handler also supports a chain of {api-spring-framework}/web/reactive/resource/ResourceResolver.html[ResourceResolver]'s and {api-spring-framework}/web/reactive/resource/ResourceTransformer.html[ResourceTransformer]'s. which can be used to create a toolchain for working with optimized resources. The `VersionResourceResolver` can be used for versioned resource URLs based on an MD5 hash computed from the content, a fixed application version, or other. A `ContentVersionStrategy` (MD5 hash) is a good choice with some notable exceptions such as JavaScript resources used with a module loader. For example in your Java config; [source,java,indent=0] [subs=""verbatim""] ---- @Configuration @EnableWebFlux public class WebConfig implements WebFluxConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler(""/resources/**"") .addResourceLocations(""/public/"") .resourceChain(true) .addResolver(new VersionResourceResolver().addContentVersionStrategy(""/**"")); } } ---- You can use `ResourceUrlProvider` to rewrite URLs and apply the full chain of resolvers and transformers -- e.g. to insert versions. The WebFlux config provides a `ResourceUrlProvider` so it can be injected into others. Unlike Spring MVC at present in WebFlux there is no way to transparely rewrite static resource URLs since the are no view technologies that can make use of a non-blocking chain of resolvers and transformers (e.g. resources on Amazon S3). When serving only local resources the workaround is to use `ResourceUrlProvider` directly (e.g. through a custom tag) and block for 0 seconds. http://www.webjars.org/documentation[WebJars] is also supported via `WebJarsResourceResolver` and automatically registered when `""org.webjars:webjars-locator""` is present on the classpath. The resolver can re-write URLs to include the version of the jar and can also match to incoming URLs without versions -- e.g. `""/jquery/jquery.min.js""` to `""/jquery/1.2.0/jquery.min.js""`. [[webflux-config-path-matching]] === Path Matching [.small]#<># Spring WebFlux uses parsed representation of path patterns -- i.e. `PathPattern`, and also the incoming request path -- i.e. `RequestPath`, which eliminates the need to indicate whether to decode the request path, or remove semicolon content, since `PathPattern` can now access decoded path segment values and match safely. Spring WebFlux also does not support suffix pattern matching so effectively there are only two minor options to customize related to path matching -- whether to match trailing slashes (`true` by default) and whether the match is case-sensitive (`false`). To customize those options: [source,java,indent=0] [subs=""verbatim,quotes""] ---- @Configuration @EnableWebFlux public class WebConfig implements WebFluxConfigurer { @Override public void configurePathMatch(PathMatchConfigurer configurer) { // ... } } ---- [[webflux-config-advanced-java]] === Advanced config mode [.small]#<># `@EnableWebFlux` imports `DelegatingWebFluxConfiguration` that (1) provides default Spring configuration for WebFlux applications and (2) detects and delegates to ``WebFluxConfigurer``'s to customize that configuration. For advanced mode, remove `@EnableWebFlux` and extend directly from `DelegatingWebFluxConfiguration` instead of implementing `WebFluxConfigurer`: [source,java,indent=0] [subs=""verbatim,quotes""] ---- @Configuration public class WebConfig extends DelegatingWebFluxConfiguration { // ... } ---- You can keep existing methods in `WebConfig` but you can now also override bean declarations from the base class and you can still have any number of other ``WebMvcConfigurer``'s on the classpath. [[webflux-http2]] == HTTP/2 [.small]#<># Servlet 4 containers are required to support HTTP/2 and Spring Framework 5 is compatible with Servlet API 4. From a programming model perspective there is nothing specific that applications need to do. However there are considerations related to server configuration. For more details please check out the https://github.com/spring-projects/spring-framework/wiki/HTTP-2-support[HTTP/2 wiki page]. Currently Spring WebFlux does not support HTTP/2 with Netty. There is also no support for pushing resources programmatically to the client.",12463,False,1951.3622479740375,median "[[defining-processors]] === Define processors You can use processors to filter and enhance data before sending it to the configured output. To define a processor, you specify the processor name, an optional condition, and a set of parameters: [source,yaml] ------ processors: - : when: - : when: ... ------ Where: * `` specifies a <> that performs some kind of action, such as selecting the fields that are exported or adding metadata to the event. * `` specifies an optional <>. If the condition is present, then the action is executed only if the condition is fulfilled. If no condition is passed, then the action is always executed. * `` is the list of parameters to pass to the processor. More complex conditional processing can be accomplished by using the if-then-else processor configuration. This allows multiple processors to be executed based on a single condition. [source,yaml] ---- processors: - if: then: <1> - : - : ... else: <2> - : - : ... ---- <1> `then` must contain a single processor or a list of one or more processors to execute when the condition evaluates to true. <2> `else` is optional. It can contain a single processor or a list of processors to execute when the conditional evaluate to false. [[where-valid]] ==== Where are processors valid? // TODO: ANY NEW BEATS THAT RE-USE THIS TOPIC NEED TO DEFINE processor-scope. ifeval::[""{beatname_lc}""==""filebeat""] :processor-scope: input endif::[] ifeval::[""{beatname_lc}""==""auditbeat""] :processor-scope: module endif::[] ifeval::[""{beatname_lc}""==""metricbeat""] :processor-scope: module endif::[] ifeval::[""{beatname_lc}""==""packetbeat""] :processor-scope: protocol endif::[] ifeval::[""{beatname_lc}""==""heartbeat""] :processor-scope: monitor endif::[] ifeval::[""{beatname_lc}""==""winlogbeat""] :processor-scope: event log shipper endif::[] Processors are valid: * At the top-level in the configuration. The processor is applied to all data collected by {beatname_uc}. * Under a specific {processor-scope}. The processor is applied to the data collected for that {processor-scope}. ifeval::[""{beatname_lc}""==""filebeat""] For example: + [source,yaml] ------ - type: processors: - : when: ... ------ + Similarly, for {beatname_uc} modules, you can define processors under the `input` section of the module definition. endif::[] ifeval::[""{beatname_lc}""==""metricbeat""] [source,yaml] ---- - module: metricsets: [""""] processors: - : when: ---- endif::[] ifeval::[""{beatname_lc}""==""auditbeat""] For example: + [source,yaml] ---- auditbeat.modules: - module: processors: - : when: ---- endif::[] ifeval::[""{beatname_lc}""==""packetbeat""] For example: + [source,yaml] ---- packetbeat.protocols: - type: processors: - : when: ---- * Under `packetbeat.flows`. The processor is applied to the data in <>: + [source,yaml] ---- packetbeat.flows: processors: - : when: ---- endif::[] ifeval::[""{beatname_lc}""==""heartbeat""] For example: + [source,yaml] ---- heartbeat.monitors: - type: processors: - : when: ---- endif::[] ifeval::[""{beatname_lc}""==""winlogbeat""] For example: + [source,yaml] ---- winlogbeat.event_logs: - name: processors: - : when: ---- endif::[] [[processors]] ==== Processors The supported processors are: * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> ifdef::has_decode_csv_fields_processor[] * <> endif::[] * <> * <> * <> * <> * <> * <> * <> * <> ifdef::has_script_processor[] * <> endif::[] [[conditions]] ==== Conditions Each condition receives a field to compare. You can specify multiple fields under the same condition by using `AND` between the fields (for example, `field1 AND field2`). For each field, you can specify a simple field name or a nested map, for example `dns.question.name`. See <> for a list of all the fields that are exported by {beatname_uc}. The supported conditions are: * <> * <> * <> * <> * <> * <> * <> * <> * <> [float] [[condition-equals]] ===== `equals` With the `equals` condition, you can compare if a field has a certain value. The condition accepts only an integer or a string value. For example, the following condition checks if the response code of the HTTP transaction is 200: [source,yaml] ------- equals: http.response.code: 200 ------- [float] [[condition-contains]] ===== `contains` The `contains` condition checks if a value is part of a field. The field can be a string or an array of strings. The condition accepts only a string value. For example, the following condition checks if an error is part of the transaction status: [source,yaml] ------ contains: status: ""Specific error"" ------ [float] [[condition-regexp]] ===== `regexp` The `regexp` condition checks the field against a regular expression. The condition accepts only strings. For example, the following condition checks if the process name starts with `foo`: [source,yaml] ----- regexp: system.process.name: ""foo.*"" ----- [float] [[condition-range]] ===== `range` The `range` condition checks if the field is in a certain range of values. The condition supports `lt`, `lte`, `gt` and `gte`. The condition accepts only integer or float values. For example, the following condition checks for failed HTTP transactions by comparing the `http.response.code` field with 400. [source,yaml] ------ range: http.response.code: gte: 400 ------ This can also be written as: [source,yaml] ---- range: http.response.code.gte: 400 ---- The following condition checks if the CPU usage in percentage has a value between 0.5 and 0.8. [source,yaml] ------ range: system.cpu.user.pct.gte: 0.5 system.cpu.user.pct.lt: 0.8 ------ [float] [[condition-network]] ===== `network` The `network` condition checks if the field is in a certain IP network range. Both IPv4 and IPv6 addresses are supported. The network range may be specified using CIDR notation, like ""192.0.2.0/24"" or ""2001:db8::/32"", or by using one of these named ranges: - `loopback` - Matches loopback addresses in the range of `127.0.0.0/8` or `::1/128`. - `unicast` - Matches global unicast addresses defined in RFC 1122, RFC 4632, and RFC 4291 with the exception of the IPv4 broadcast address (`255.255.255.255`). This includes private address ranges. - `multicast` - Matches multicast addresses. - `interface_local_multicast` - Matches IPv6 interface-local multicast addresses. - `link_local_unicast` - Matches link-local unicast addresses. - `link_local_multicast` - Matches link-local multicast addresses. - `private` - Matches private address ranges defined in RFC 1918 (IPv4) and RFC 4193 (IPv6). - `public` - Matches addresses that are not loopback, unspecified, IPv4 broadcast, link local unicast, link local multicast, interface local multicast, or private. - `unspecified` - Matches unspecified addresses (either the IPv4 address ""0.0.0.0"" or the IPv6 address ""::""). The following condition returns true if the `source.ip` value is within the private address space. [source,yaml] ---- network: source.ip: private ---- This condition returns true if the `destination.ip` value is within the IPv4 range of `192.168.1.0` - `192.168.1.255`. [source,yaml] ---- network: destination.ip: '192.168.1.0/24' ---- And this condition returns true when `destination.ip` is within any of the given subnets. [source,yaml] ---- network: destination.ip: ['192.168.1.0/24', '10.0.0.0/8', loopback] ---- [float] [[condition-has_fields]] ===== `has_fields` The `has_fields` condition checks if all the given fields exist in the event. The condition accepts a list of string values denoting the field names. For example, the following condition checks if the `http.response.code` field is present in the event. [source,yaml] ------ has_fields: ['http.response.code'] ------ [float] [[condition-or]] ===== `or` The `or` operator receives a list of conditions. [source,yaml] ------- or: - - - ... ------- For example, to configure the condition `http.response.code = 304 OR http.response.code = 404`: [source,yaml] ------ or: - equals: http.response.code: 304 - equals: http.response.code: 404 ------ [float] [[condition-and]] ===== `and` The `and` operator receives a list of conditions. [source,yaml] ------- and: - - - ... ------- For example, to configure the condition `http.response.code = 200 AND status = OK`: [source,yaml] ------ and: - equals: http.response.code: 200 - equals: status: OK ------ To configure a condition like ` OR AND `: [source,yaml] ------ or: - - and: - - ------ [float] [[condition-not]] ===== `not` The `not` operator receives the condition to negate. [source,yaml] ------- not: ------- For example, to configure the condition `NOT status = OK`: [source,yaml] ------ not: equals: status: OK ------ [[add-cloud-metadata]] === Add cloud metadata The `add_cloud_metadata` processor enriches each event with instance metadata from the machine's hosting provider. At startup it will detect the hosting provider and cache the instance metadata. The following cloud providers are supported: - Amazon Web Services (AWS) - Digital Ocean - Google Compute Engine (GCE) - https://www.qcloud.com/?lang=en[Tencent Cloud] (QCloud) - Alibaba Cloud (ECS) - Azure Virtual Machine - Openstack Nova The simple configuration below enables the processor. [source,yaml] ------------------------------------------------------------------------------- processors: - add_cloud_metadata: ~ ------------------------------------------------------------------------------- The `add_cloud_metadata` processor has two optional configuration settings. The first one is `timeout` which specifies the maximum amount of time to wait for a successful response when detecting the hosting provider. The default timeout value is `3s`. If a timeout occurs then no instance metadata will be added to the events. This makes it possible to enable this processor for all your deployments (in the cloud or on-premise). The second optional configuration setting is `overwrite`. When `overwrite` is `true`, `add_cloud_metadata` overwrites existing `cloud.*` fields (`false` by default). The metadata that is added to events varies by hosting provider. Below are examples for each of the supported providers. _AWS_ [source,json] ------------------------------------------------------------------------------- { ""cloud"": { ""availability_zone"": ""us-east-1c"", ""instance_id"": ""i-4e123456"", ""machine_type"": ""t2.medium"", ""provider"": ""aws"", ""region"": ""us-east-1"" } } ------------------------------------------------------------------------------- _Digital Ocean_ [source,json] ------------------------------------------------------------------------------- { ""cloud"": { ""instance_id"": ""1234567"", ""provider"": ""digitalocean"", ""region"": ""nyc2"" } } ------------------------------------------------------------------------------- _GCP_ [source,json] ------------------------------------------------------------------------------- { ""cloud"": { ""availability_zone"": ""us-east1-b"", ""instance_id"": ""1234556778987654321"", ""machine_type"": ""f1-micro"", ""project_id"": ""my-dev"", ""provider"": ""gcp"" } } ------------------------------------------------------------------------------- _Tencent Cloud_ [source,json] ------------------------------------------------------------------------------- { ""cloud"": { ""availability_zone"": ""gz-azone2"", ""instance_id"": ""ins-qcloudv5"", ""provider"": ""qcloud"", ""region"": ""china-south-gz"" } } ------------------------------------------------------------------------------- _Alibaba Cloud_ This metadata is only available when VPC is selected as the network type of the ECS instance. [source,json] ------------------------------------------------------------------------------- { ""cloud"": { ""availability_zone"": ""cn-shenzhen"", ""instance_id"": ""i-wz9g2hqiikg0aliyun2b"", ""provider"": ""ecs"", ""region"": ""cn-shenzhen-a"" } } ------------------------------------------------------------------------------- _Azure Virtual Machine_ [source,json] ------------------------------------------------------------------------------- { ""cloud"": { ""provider"": ""az"", ""instance_id"": ""04ab04c3-63de-4709-a9f9-9ab8c0411d5e"", ""instance_name"": ""test-az-vm"", ""machine_type"": ""Standard_D3_v2"", ""region"": ""eastus2"" } } ------------------------------------------------------------------------------- _Openstack Nova_ [source,json] ------------------------------------------------------------------------------- { ""cloud"": { ""provider"": ""openstack"", ""instance_name"": ""test-998d932195.mycloud.tld"", ""availability_zone"": ""xxxx-az-c"", ""instance_id"": ""i-00011a84"", ""machine_type"": ""m2.large"" } } ------------------------------------------------------------------------------- [[add-fields]] === Add fields The `add_fields` processor adds additional fields to the event. Fields can be scalar values, arrays, dictionaries, or any nested combination of these. By default the fields that you specify will be grouped under the `fields` sub-dictionary in the event. To group the fields under a different sub-dictionary, use the `target` setting. To store the fields as top-level fields, set `target: ''`. `target`:: (Optional) Sub-dictionary to put all fields into. Defaults to `fields`. `fields`:: Fields to be added. For example, this configuration: [source,yaml] ------------------------------------------------------------------------------ processors: - add_fields: target: project fields: name: myproject id: '574734885120952459' ------------------------------------------------------------------------------ Adds these fields to any event: [source,json] ------------------------------------------------------------------------------- { ""project"": { ""name"": ""myproject"", ""id"": ""574734885120952459"" } } ------------------------------------------------------------------------------- [[add-labels]] === Add labels The `add_labels` processors adds a set of key-value pairs to an event. The processor will flatten nested configuration objects like arrays or dictionaries into a fully qualified name by merging nested names with a `.`. Array entries create numeric names starting with 0. Labels are always stored under the Elastic Common Schema compliant `labels` sub-dictionary. `labels`:: dictionaries of labels to be added. For example, this configuration: [source,yaml] ------------------------------------------------------------------------------ processors: - add_labels: labels: number: 1 with.dots: test nested: with.dots: nested array: - do - re - with.field: mi ------------------------------------------------------------------------------ Adds these fields to every event: [source,json] ------------------------------------------------------------------------------- { ""labels"": { ""number"": 1, ""with.dots"": ""test"", ""nested.with.dots"": ""nested"", ""array.0"": ""do"", ""array.1"": ""re"", ""array.2.with.field"": ""mi"" } } ------------------------------------------------------------------------------- [[add-locale]] === Add the local time zone The `add_locale` processor enriches each event with the machine's time zone offset from UTC or with the name of the time zone. It supports one configuration option named `format` that controls whether an offset or time zone abbreviation is added to the event. The default format is `offset`. The processor adds the a `event.timezone` value to each event. The configuration below enables the processor with the default settings. [source,yaml] ------------------------------------------------------------------------------- processors: - add_locale: ~ ------------------------------------------------------------------------------- This configuration enables the processor and configures it to add the time zone abbreviation to events. [source,yaml] ------------------------------------------------------------------------------- processors: - add_locale: format: abbreviation ------------------------------------------------------------------------------- NOTE: Please note that `add_locale` differentiates between daylight savings time (DST) and regular time. For example `CEST` indicates DST and and `CET` is regular time. [[add-tags]] === Add tags The `add_tags` processor adds tags to a list of tags. If the target field already exists, the tags are appended to the existing list of tags. `tags`:: List of tags to add. `target`:: (Optional) Field the tags will be added to. Defaults to `tags`. For example, this configuration: [source,yaml] ------------------------------------------------------------------------------ processors: - add_tags: tags: [web, production] target: ""environment"" ------------------------------------------------------------------------------ Adds the environment field to every event: [source,json] ------------------------------------------------------------------------------- { ""environment"": [""web"", ""production""] } ------------------------------------------------------------------------------- ifdef::has_decode_csv_fields_processor[] [[decode-csv-fields]] === Decode CSV fields experimental[] The `decode_csv_fields` processor decodes fields containing records in comma-separated format (CSV). It will output the values as an array of strings. This processor is available for Filebeat and Journalbeat. [source,yaml] ----------------------------------------------------- processors: - decode_csv_fields: fields: message: decoded.csv separator: , ignore_missing: false overwrite_keys: true trim_leading_whitespace: false fail_on_error: true ----------------------------------------------------- The `decode_csv_fields` has the following settings: `fields`:: This is a mapping from the source field containing the CSV data to the destination field to which the decoded array will be written. `separator`:: (Optional) Character to be used as a column separator. The default is the comma character. For using a TAB character you must set it to ""\\t"". `ignore_missing`:: (Optional) Whether to ignore events which lack the source field. The default is `false`, which will fail processing of an event if a field is missing. `overwrite_keys`:: Whether the target field is overwritten if it already exists. The default is false, which will fail processing of an event when `target` already exists. `trim_leading_space`:: Whether extra space after the separator is trimmed from values. This works even if the separator is also a space. The default is `false`. `fail_on_error`:: (Optional) If set to true, in case of an error the changes to the event are reverted, and the original event is returned. If set to `false`, processing continues also if an error happens. Default is `true`. endif::[] [[decode-json-fields]] === Decode JSON fields The `decode_json_fields` processor decodes fields containing JSON strings and replaces the strings with valid JSON objects. [source,yaml] ----------------------------------------------------- processors: - decode_json_fields: fields: [""field1"", ""field2"", ...] process_array: false max_depth: 1 target: """" overwrite_keys: false ----------------------------------------------------- The `decode_json_fields` processor has the following configuration settings: `fields`:: The fields containing JSON strings to decode. `process_array`:: (Optional) A boolean that specifies whether to process arrays. The default is false. `max_depth`:: (Optional) The maximum parsing depth. The default is 1. `target`:: (Optional) The field under which the decoded JSON will be written. By default the decoded JSON object replaces the string field from which it was read. To merge the decoded JSON fields into the root of the event, specify `target` with an empty string (`target: """"`). Note that the `null` value (`target:`) is treated as if the field was not set at all. `overwrite_keys`:: (Optional) A boolean that specifies whether keys that already exist in the event are overwritten by keys from the decoded JSON object. The default value is false. [[community-id]] === Community ID Network Flow Hash The `community_id` processor computes a network flow hash according to the https://github.com/corelight/community-id-spec[Community ID Flow Hash specification]. The flow hash is useful for correlating all network events related to a single flow. For example you can filter on a community ID value and you might get back the Netflow records from multiple collectors and layer 7 protocol records from Packetbeat. By default the processor is configured to read the flow parameters from the appropriate Elastic Common Schema (ECS) fields. If you are processing ECS data then no parameters are required. [source,yaml] ---- processors: - community_id: ---- If the data does not conform to ECS then you can customize the field names that the processor reads from. You can also change the `target` field which is where the computed hash is written to. [source,yaml] ---- processors: - community_id: fields: source_ip: my_source_ip source_port: my_source_port destination_ip: my_dest_ip destination_port: my_dest_port transport: proto icmp_type: my_icmp_type icmp_code: my_icmp_code target: network.community_id ---- If the necessary fields are not present in the event then the processor will silently continue without adding the target field. The processor also accepts an optional `seed` parameter that must be a 16-bit unsigned integer. This value gets incorporated into all generated hashes. [[convert]] === Convert The `convert` processor converts a field in the event to a different type, such as converting a string to an integer. The supported types include: `integer`, `long`, `float`, `double`, `string`, `boolean`, and `ip`. The `ip` type is effectively an alias for `string`, but with an added validation that the value is an IPv4 or IPv6 address. [source,yaml] ---- processors: - convert: fields: - {from: ""src_ip"", to: ""source.ip"", type: ""ip""} - {from: ""src_port"", to: ""source.port"", type: ""integer""} ignore_missing: true fail_on_error: false ---- The `convert` processor has the following configuration settings: `fields`:: (Required) This is the list of fields to convert. At least one item must be contained in the list. Each item in the list must have a `from` key that specifies the source field. The `to` key is optional and specifies where to assign the converted value. If `to` is omitted then the `from` field is updated in-place. The `type` key specifies the data type to convert the value to. If `type` is omitted then the processor copies or renames the field without any type conversion. `ignore_missing`:: (Optional) If `true` the processor continues to the next field when the `from` key is not found in the event. If false then the processor returns an error and does not process the remaining fields. Default is `false`. `fail_on_error`:: (Optional) If false type conversion failures are ignored and the processor continues to the next field. Default is `true`. `tag`:: (Optional) An identifier for this processor. Useful for debugging. `mode`:: (Optional) When both `from` and `to` are defined for a field then `mode` controls whether to `copy` or `rename` the field when the type conversion is successful. Default is `copy`. [[drop-event]] === Drop events The `drop_event` processor drops the entire event if the associated condition is fulfilled. The condition is mandatory, because without one, all the events are dropped. [source,yaml] ------ processors: - drop_event: when: condition ------ See <> for a list of supported conditions. [[drop-fields]] === Drop fields from events The `drop_fields` processor specifies which fields to drop if a certain condition is fulfilled. The condition is optional. If it's missing, the specified fields are always dropped. The `@timestamp` and `type` fields cannot be dropped, even if they show up in the `drop_fields` list. [source,yaml] ----------------------------------------------------- processors: - drop_fields: when: condition fields: [""field1"", ""field2"", ...] ----------------------------------------------------- See <> for a list of supported conditions. NOTE: If you define an empty list of fields under `drop_fields`, then no fields are dropped. [[include-fields]] === Keep fields from events The `include_fields` processor specifies which fields to export if a certain condition is fulfilled. The condition is optional. If it's missing, the specified fields are always exported. The `@timestamp` and `type` fields are always exported, even if they are not defined in the `include_fields` list. [source,yaml] ------- processors: - include_fields: when: condition fields: [""field1"", ""field2"", ...] ------- See <> for a list of supported conditions. You can specify multiple `include_fields` processors under the `processors` section. NOTE: If you define an empty list of fields under `include_fields`, then only the required fields, `@timestamp` and `type`, are exported. [[rename-fields]] === Rename fields from events The `rename` processor specifies a list of fields to rename. Under the `fields` key each entry contains a `from: old-key` and a `to: new-key` pair. `from` is the origin and `to` the target name of the field. Renaming fields can be useful in cases where field names cause conflicts. For example if an event has two fields, `c` and `c.b`, that are both assigned scalar values (e.g. `{""c"": 1, ""c.b"": 2}`) this will result in an Elasticsearch error at ingest time. This is because the value of a cannot simultaneously be a scalar and an object. To prevent this rename_fields can be used to rename `c` to `c.value`. Rename fields cannot be used to overwrite fields. To overwrite fields either first rename the target field or use the `drop_fields` processor to drop the field and then rename the field. [source,yaml] ------- processors: - rename: fields: - from: ""a.g"" to: ""e.d"" ignore_missing: false fail_on_error: true ------- The `rename` processor has the following configuration settings: `ignore_missing`:: (Optional) If set to true, no error is logged in case a key which should be renamed is missing. Default is `false`. `fail_on_error`:: (Optional) If set to true, in case of an error the renaming of fields is stopped and the original event is returned. If set to false, renaming continues also if an error happened during renaming. Default is `true`. See <> for a list of supported conditions. You can specify multiple `ignore_missing` processors under the `processors` section. [[add-kubernetes-metadata]] === Add Kubernetes metadata The `add_kubernetes_metadata` processor annotates each event with relevant metadata based on which Kubernetes pod the event originated from. Each event is annotated with: * Pod Name * Pod UID * Namespace * Labels The `add_kubernetes_metadata` processor has two basic building blocks which are: * Indexers * Matchers Indexers take in a pod's metadata and builds indices based on the pod metadata. For example, the `ip_port` indexer can take a Kubernetes pod and index the pod metadata based on all `pod_ip:container_port` combinations. Matchers are used to construct lookup keys for querying indices. For example, when the `fields` matcher takes `[""metricset.host""]` as a lookup field, it would construct a lookup key with the value of the field `metricset.host`. Each Beat can define its own default indexers and matchers which are enabled by default. For example, FileBeat enables the `container` indexer, which indexes pod metadata based on all container IDs, and a `logs_path` matcher, which takes the `log.file.path` field, extracts the container ID, and uses it to retrieve metadata. The configuration below enables the processor when {beatname_lc} is run as a pod in Kubernetes. [source,yaml] ------------------------------------------------------------------------------- processors: - add_kubernetes_metadata: in_cluster: true ------------------------------------------------------------------------------- The configuration below enables the processor on a Beat running as a process on the Kubernetes node. [source,yaml] ------------------------------------------------------------------------------- processors: - add_kubernetes_metadata: in_cluster: false host: kube_config: ${HOME}/.kube/config ------------------------------------------------------------------------------- The configuration below has the default indexers and matchers disabled and enables ones that the user is interested in. [source,yaml] ------------------------------------------------------------------------------- processors: - add_kubernetes_metadata: in_cluster: false host: kube_config: ~/.kube/config default_indexers.enabled: false default_matchers.enabled: false indexers: - ip_port: matchers: - fields: lookup_fields: [""metricset.host""] ------------------------------------------------------------------------------- The `add_kubernetes_metadata` processor has the following configuration settings: `in_cluster`:: (Optional) Use in cluster settings for Kubernetes client, `true` by default. `host`:: (Optional) Identify the node where {beatname_lc} is running in case it cannot be accurately detected, as when running {beatname_lc} in host network mode. `namespace`:: (Optional) Select the namespace from which to collect the metadata. If it is not set, the processor collects metadata from all namespaces. It is unset by default. `kube_config`:: (Optional) Use given config file as configuration for Kubernetes client. `default_indexers.enabled`:: (Optional) Enable/Disable default pod indexers, in case you want to specify your own. `default_matchers.enabled`:: (Optional) Enable/Disable default pod matchers, in case you want to specify your own. [[add-docker-metadata]] === Add Docker metadata The `add_docker_metadata` processor annotates each event with relevant metadata from Docker containers: * Container ID * Name * Image * Labels [NOTE] ===== When running {beatname_uc} in a container, you need to provide access to Docker’s unix socket in order for the `add_docker_metadata` processor to work. You can do this by mounting the socket inside the container. For example: `docker run -v /var/run/docker.sock:/var/run/docker.sock ...` To avoid privilege issues, you may also need to add `--user=root` to the `docker run` flags. Because the user must be part of the docker group in order to access `/var/run/docker.sock`, root access is required if {beatname_uc} is running as non-root inside the container. ===== [source,yaml] ------------------------------------------------------------------------------- processors: - add_docker_metadata: host: ""unix:///var/run/docker.sock"" #match_fields: [""system.process.cgroup.id""] #match_pids: [""process.pid"", ""process.ppid""] #match_source: true #match_source_index: 4 #match_short_id: true #cleanup_timeout: 60 #labels.dedot: false # To connect to Docker over TLS you must specify a client and CA certificate. #ssl: # certificate_authority: ""/etc/pki/root/ca.pem"" # certificate: ""/etc/pki/client/cert.pem"" # key: ""/etc/pki/client/cert.key"" ------------------------------------------------------------------------------- It has the following settings: `host`:: (Optional) Docker socket (UNIX or TCP socket). It uses `unix:///var/run/docker.sock` by default. `ssl`:: (Optional) SSL configuration to use when connecting to the Docker socket. `match_fields`:: (Optional) A list of fields to match a container ID, at least one of them should hold a container ID to get the event enriched. `match_pids`:: (Optional) A list of fields that contain process IDs. If the process is running in Docker then the event will be enriched. The default value is `[""process.pid"", ""process.ppid""]`. `match_source`:: (Optional) Match container ID from a log path present in the `log.file.path` field. Enabled by default. `match_short_id`:: (Optional) Match container short ID from a log path present in the `log.file.path` field. Disabled by default. This allows to match directories names that have the first 12 characters of the container ID. For example, `/var/log/containers/b7e3460e2b21/*.log`. `match_source_index`:: (Optional) Index in the source path split by `/` to look for container ID. It defaults to 4 to match `/var/lib/docker/containers//*.log` `cleanup_timeout`:: (Optional) Time of inactivity to consider we can clean and forget metadata for a container, 60s by default. `labels.dedot`:: (Optional) Default to be false. If set to true, replace dots in labels with `_`. [[add-host-metadata]] === Add Host metadata beta[] [source,yaml] ------------------------------------------------------------------------------- processors: - add_host_metadata: netinfo.enabled: false cache.ttl: 5m geo: name: nyc-dc1-rack1 location: 40.7128, -74.0060 continent_name: North America country_iso_code: US region_name: New York region_iso_code: NY city_name: New York ------------------------------------------------------------------------------- It has the following settings: `netinfo.enabled`:: (Optional) Default false. Include IP addresses and MAC addresses as fields host.ip and host.mac `cache.ttl`:: (Optional) The processor uses an internal cache for the host metadata. This sets the cache expiration time. The default is 5m, negative values disable caching altogether. `geo.name`:: User definable token to be used for identifying a discrete location. Frequently a datacenter, rack, or similar. `geo.location`:: Longitude and latitude in comma separated format. `geo.continent_name`:: Name of the continent. `geo.country_name`:: Name of the country. `geo.region_name`:: Name of the region. `geo.city_name`:: Name of the city. `geo.country_iso_code`:: ISO country code. `geo.region_iso_code`:: ISO region code. The `add_host_metadata` processor annotates each event with relevant metadata from the host machine. The fields added to the event look like the following: [source,json] ------------------------------------------------------------------------------- { ""host"":{ ""architecture"":""x86_64"", ""name"":""example-host"", ""id"":"""", ""os"":{ ""family"":""darwin"", ""build"":""16G1212"", ""platform"":""darwin"", ""version"":""10.12.6"", ""kernel"":""16.7.0"", ""name"":""Mac OS X"" }, ""ip"": [""192.168.0.1"", ""10.0.0.1""], ""mac"": [""00:25:96:12:34:56"", ""72:00:06:ff:79:f1""], ""geo"": { ""continent_name"": ""North America"", ""country_iso_code"": ""US"", ""region_name"": ""New York"", ""region_iso_code"": ""NY"", ""city_name"": ""New York"", ""name"": ""nyc-dc1-rack1"", ""location"": ""40.7128, -74.0060"" } } } ------------------------------------------------------------------------------- [[add-observer-metadata]] === Add Observer metadata beta[] [source,yaml] ------------------------------------------------------------------------------- processors: - add_observer_metadata: netinfo.enabled: false cache.ttl: 5m geo: name: nyc-dc1-rack1 location: 40.7128, -74.0060 continent_name: North America country_iso_code: US region_name: New York region_iso_code: NY city_name: New York ------------------------------------------------------------------------------- It has the following settings: `netinfo.enabled`:: (Optional) Default false. Include IP addresses and MAC addresses as fields observer.ip and observer.mac `cache.ttl`:: (Optional) The processor uses an internal cache for the observer metadata. This sets the cache expiration time. The default is 5m, negative values disable caching altogether. `geo.name`:: User definable token to be used for identifying a discrete location. Frequently a datacenter, rack, or similar. `geo.location`:: Longitude and latitude in comma separated format. `geo.continent_name`:: Name of the continent. `geo.country_name`:: Name of the country. `geo.region_name`:: Name of the region. `geo.city_name`:: Name of the city. `geo.country_iso_code`:: ISO country code. `geo.region_iso_code`:: ISO region code. The `add_geo_metadata` processor annotates each event with relevant metadata from the observer machine. The fields added to the event look like the following: [source,json] ------------------------------------------------------------------------------- { ""observer"" : { ""hostname"" : ""avce"", ""type"" : ""heartbeat"", ""vendor"" : ""elastic"", ""ip"" : [ ""192.168.1.251"", ""fe80::64b2:c3ff:fe5b:b974"", ], ""mac"" : [ ""dc:c1:02:6f:1b:ed"", ], ""geo"": { ""continent_name"": ""North America"", ""country_iso_code"": ""US"", ""region_name"": ""New York"", ""region_iso_code"": ""NY"", ""city_name"": ""New York"", ""name"": ""nyc-dc1-rack1"", ""location"": ""40.7128, -74.0060"" } } } ------------------------------------------------------------------------------- [[dissect]] === Dissect strings The dissect processor tokenizes incoming strings using defined patterns. [source,yaml] ------- processors: - dissect: tokenizer: ""%{key1} %{key2}"" field: ""message"" target_prefix: ""dissect"" ------- The `dissect` processor has the following configuration settings: `field`:: (Optional) The event field to tokenize. Default is `message`. `target_prefix`:: (Optional) The name of the field where the values will be extracted. When an empty string is defined, the processor will create the keys at the root of the event. Default is `dissect`. When the target key already exists in the event, the processor won't replace it and log an error; you need to either drop or rename the key before using dissect. For tokenization to be successful, all keys must be found and extracted, if one of them cannot be found an error will be logged and no modification is done on the original event. NOTE: A key can contain any characters except reserved suffix or prefix modifiers: `/`,`&`, `+` and `?`. See <> for a list of supported conditions. [[processor-dns]] === DNS Reverse Lookup The DNS processor performs reverse DNS lookups of IP addresses. It caches the responses that it receives in accordance to the time-to-live (TTL) value contained in the response. It also caches failures that occur during lookups. Each instance of this processor maintains its own independent cache. The processor uses its own DNS resolver to send requests to nameservers and does not use the operating system's resolver. It does not read any values contained in `/etc/hosts`. This processor can significantly slow down your pipeline's throughput if you have a high latency network or slow upstream nameserver. The cache will help with performance, but if the addresses being resolved have a high cardinality then the cache benefits will be diminished due to the high miss ratio. By way of example, if each DNS lookup takes 2 milliseconds, the maximum throughput you can achieve is 500 events per second (1000 milliseconds / 2 milliseconds). If you have a high cache hit ratio then your throughput can be higher. This is a minimal configuration example that resolves the IP addresses contained in two fields. [source,yaml] ---- processors: - dns: type: reverse fields: source.ip: source.hostname destination.ip: destination.hostname ---- Next is a configuration example showing all options. [source,yaml] ---- processors: - dns: type: reverse action: append fields: server.ip: server.hostname client.ip: client.hostname success_cache: capacity.initial: 1000 capacity.max: 10000 failure_cache: capacity.initial: 1000 capacity.max: 10000 ttl: 1m nameservers: ['192.0.2.1', '203.0.113.1'] timeout: 500ms tag_on_failure: [_dns_reverse_lookup_failed] ---- The `dns` processor has the following configuration settings: `type`:: The type of DNS lookup to perform. The only supported type is `reverse` which queries for a PTR record. `action`:: This defines the behavior of the processor when the target field already exists in the event. The options are `append` (default) and `replace`. `fields`:: This is a mapping of source field names to target field names. The value of the source field will be used in the DNS query and result will be written to the target field. `success_cache.capacity.initial`:: The initial number of items that the success cache will be allocated to hold. When initialized the processor will allocate the memory for this number of items. Default value is `1000`. `success_cache.capacity.max`:: The maximum number of items that the success cache can hold. When the maximum capacity is reached a random item is evicted. Default value is `10000`. `failure_cache.capacity.initial`:: The initial number of items that the failure cache will be allocated to hold. When initialized the processor will allocate the memory for this number of items. Default value is `1000`. `failure_cache.capacity.max`:: The maximum number of items that the failure cache can hold. When the maximum capacity is reached a random item is evicted. Default value is `10000`. `failure_cache.ttl`:: The duration for which failures are cached. Valid time units are ""ns"", ""us"" (or ""µs""), ""ms"", ""s"", ""m"", ""h"". Default value is `1m`. `nameservers`:: A list of nameservers to query. If there are multiple servers, the resolver queries them in the order listed. If none are specified then it will read the nameservers listed in `/etc/resolv.conf` once at initialization. On Windows you must always supply at least one nameserver. `timeout`:: The duration after which a DNS query will timeout. This is timeout for each DNS request so if you have 2 nameservers then the total timeout will be 2 times this value. Valid time units are ""ns"", ""us"" (or ""µs""), ""ms"", ""s"", ""m"", ""h"". Default value is `500ms`. `tag_on_failure`:: A list of tags to add to the event when any lookup fails. The tags are only added once even if multiple lookups fail. By default no tags are added upon failure. [[add-process-metadata]] === Add process metadata The Add process metadata processor enriches events with information from running processes, identified by their process ID (PID). [source,yaml] ------------------------------------------------------------------------------- processors: - add_process_metadata: match_pids: [system.process.ppid] target: system.process.parent ------------------------------------------------------------------------------- The fields added to the event look as follows: [source,json] ------------------------------------------------------------------------------- ""process"": { ""name"": ""systemd"", ""title"": ""/usr/lib/systemd/systemd --switched-root --system --deserialize 22"", ""exe"": ""/usr/lib/systemd/systemd"", ""args"": [""/usr/lib/systemd/systemd"", ""--switched-root"", ""--system"", ""--deserialize"", ""22""], ""pid"": 1, ""ppid"": 0, ""start_time"": ""2018-08-22T08:44:50.684Z"", } ------------------------------------------------------------------------------- Optionally, the process environment can be included, too: [source,json] ------------------------------------------------------------------------------- ... ""env"": { ""HOME"": ""/"", ""TERM"": ""linux"", ""BOOT_IMAGE"": ""/boot/vmlinuz-4.11.8-300.fc26.x86_64"", ""LANG"": ""en_US.UTF-8"", } ... ------------------------------------------------------------------------------- It has the following settings: `match_pids`:: List of fields to lookup for a PID. The processor will search the list sequentially until the field is found in the current event, and the PID lookup will be applied to the value of this field. `target`:: (Optional) Destination prefix where the `process` object will be created. The default is the event's root. `include_fields`:: (Optional) List of fields to add. By default, the processor will add all the available fields except `process.env`. `ignore_missing`:: (Optional) When set to `false`, events that don't contain any of the fields in match_pids will be discarded and an error will be generated. By default, this condition is ignored. `overwrite_keys`:: (Optional) By default, if a target field already exists, it will not be overwritten and an error will be logged. If `overwrite_keys` is set to `true`, this condition will be ignored. `restricted_fields`:: (Optional) By default, the `process.env` field is not output, to avoid leaking sensitive data. If `restricted_fields` is `true`, the field will be present in the output. ifdef::has_script_processor[] [[processor-script]] === Script Processor experimental[] The script processor executes Javascript code to process an event. The processor uses a pure Go implementation of ECMAScript 5.1 and has no external dependencies. This can be useful in situations where one of the other processors doesn't provide the functionality you need to filter events. The processor can be configured by embedding Javascript in your configuration file or by pointing the processor at external file(s). [source,yaml] ---- processors: - script: lang: javascript id: my_filter source: > function process(event) { event.Tag(""js""); } ---- This loads `filter.js` from disk. [source,yaml] ---- processors: - script: lang: javascript id: my_filter file: ${path.config}/filter.js ---- Parameters can be passed to the script by adding `params` to the config. This allows for a script to be made reusable. When using `params` the code must define a `register(params)` function to receive the parameters. [source,yaml] ---- processors: - script: lang: javascript id: my_filter params: threshold: 15 source: > var params = {threshold: 42}; function register(scriptParams) { params = scriptParams; } function process(event) { if (event.Get(""severity"") < params.threshold) { event.Cancel(); } } ---- If the script defines a `test()` function it will be invoked when the processor is loaded. Any exceptions thrown will cause the processor to fail to load. This can be used to make assertions about the behavior of the script. [source,javascript] ---- function process(event) { if (event.Get(""event.code"") === 1102) { event.Put(""event.action"", ""cleared""); } } function test() { var event = process(new Event({event: {code: 1102})); if (event.Get(""event.action"") !== ""cleared"") { throw ""expected event.action === cleared""; } } ---- [float] ==== Configuration options The `script` processor has the following configuration settings: `lang`:: This field is required and its value must be `javascript`. `tag`:: This is an optional identifier that is added to log messages. If defined it enables metrics logging for this instance of the processor. The metrics include the number of exceptions and a histogram of the execution times for the `process` function. `source`:: Inline Javascript source code. `file`:: Path to a script file to load. Relative paths are interpreted as relative to the `path.config` directory. Globs are expanded. `files`:: List of script files to load. The scripts are concatenated together. Relative paths are interpreted as relative to the `path.config` directory. And globs are expanded. `params`:: A dictionary of parameters that are passed to the `register` of the script. `tag_on_exception`:: Tag to add to events in case the Javascript code causes an exception while processing an event. Defaults to `_js_exception`. `timeout`:: This sets an execution timeout for the `process` function. When the `process` function takes longer than the `timeout` period the function is interrupted. You can set this option to prevent a script from running for too long (like preventing an infinite `while` loop). By default there is no timeout. [float] ==== Event API The `Event` object passed to the `process` method has the following API. [frame=""topbot"",options=""header""] |=== |Method |Description |`Get(string)` |Get a value from the event (either a scalar or an object). If the key does not exist `null` is returned. If no key is provided then an object containing all fields is returned. *Example*: `var value = event.Get(key);` |`Put(string, value)` |Put a value into the event. If the key was already set then the previous value is returned. It throws an exception if the key cannot be set because one of the intermediate values is not an object. *Example*: `var old = event.Put(key, value);` |`Rename(string, string)` |Rename a key in the event. The target key must not exist. It returns true if the source key was successfully renamed to the target key. *Example*: `var success = event.Rename(""source"", ""target"");` |`Delete(string)` |Delete a field from the event. It returns true on success. *Example*: `var deleted = event.Delete(""user.email"");` |`Cancel()` |Flag the event as cancelled which causes the processor to drop event. *Example*: `event.Cancel(); return;` |`Tag(string)` |Append a tag to the `tags` field if the tag does not already exist. Throws an exception if `tags` exists and is not a string or a list of strings. *Example*: `event.Tag(""user_event"");` |`AppendTo(string, string)` |`AppendTo` is a specialized `Put` method that converts the existing value to an array and appends the value if it does not already exist. If there is an existing value that's not a string or array of strings then an exception is thrown. *Example*: `event.AppendTo(""error.message"", ""invalid file hash"");` |=== endif::[] [[extract-array]] === Extract array experimental[] The `extract_array` processor populates fields with values read from an array field. The following example will populate `source.ip` with the first element of the `my_array` field, `destination.ip` with the second element, and `network.transport` with the third. [source,yaml] ----------------------------------------------------- processors: - extract_array: field: my_array mappings: source.ip: 0 destination.ip: 1 network.transport: 2 ----------------------------------------------------- The following settings are supported: `field`:: The array field whose elements are to be extracted. `mappings`:: Maps each field name to an array index. Use 0 for the first element in the array. Multiple fields can be mapped to the same array element. `ignore_missing`:: (Optional) Whether to ignore events where the array field is missing. The default is `false`, which will fail processing of an event if the specified field does not exist. Set it to `true` to ignore this condition. `overwrite_keys`:: Whether the target fields specified in the mapping are overwritten if they already exist. The default is `false`, which will fail processing if a target field already exists. `fail_on_error`:: (Optional) If set to `true` and an error happens, changes to the event are reverted, and the original event is returned. If set to `false`, processing continues despite errors. Default is `true`. `omit_empty`:: (Optional) Whether empty values are extracted from the array. If set to `true`, instead of the target field being set to an empty value, it is left unset. The empty string (`""""`), an empty array (`[]`) or an empty object (`{}`) are considered empty values. Default is `false`. ",12448,False,2016.9292343105258,median "[[netty-component]] = Netty Component :docTitle: Netty :artifactId: camel-netty :description: Socket level networking using TCP or UDP with Netty 4.x. :since: 2.14 :supportLevel: Stable :component-header: Both producer and consumer are supported include::{cq-version}@camel-quarkus:ROOT:partial$reference/components/netty.adoc[opts=optional] *Since Camel {since}* *{component-header}* The Netty 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-netty x.x.x ---- == URI format The URI scheme for a netty component is as follows [source,text] ---- netty:tcp://0.0.0.0:99999[?options] netty: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 Netty component supports 73 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *configuration* (common) | To use the NettyConfiguration as configuration when creating endpoints. | | NettyConfiguration | *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 NettyConstants#NETTY_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 option 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 | *executorService* (consumer) | To use the given EventExecutorGroup. | | EventExecutorGroup | *maximumPoolSize* (consumer) | Sets a maximum thread pool size for the netty consumer ordered thread pool. The default size is 2 x cpu_core plus 1. Setting this value to eg 10 will then use 10 threads unless 2 x cpu_core plus 1 is a higher value, which then will override and be used. For example if there are 8 cores, then the consumer thread pool will be 17. This thread pool is used to route messages received from Netty by Camel. We use a separate thread pool to ensure ordering of messages and also in case some messages will block, then nettys worker threads (event loop) wont be affected. | | int | *nettyServerBootstrapFactory* (consumer) | To use a custom NettyServerBootstrapFactory | | NettyServerBootstrapFactory | *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. There are 6 enums and the value can be one of: TRACE, DEBUG, INFO, WARN, ERROR, OFF | WARN | LoggingLevel | *serverClosedChannelException{zwsp}CaughtLogLevel* (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. There are 6 enums and the value can be one of: TRACE, DEBUG, INFO, WARN, ERROR, OFF | DEBUG | LoggingLevel | *serverExceptionCaughtLogLevel* (consumer) | If the server (NettyConsumer) catches an exception then its logged using this logging level. There are 6 enums and the value can be one of: TRACE, DEBUG, INFO, WARN, ERROR, OFF | WARN | LoggingLevel | *serverInitializerFactory* (consumer) | To use a custom ServerInitializerFactory | | ServerInitializerFactory | *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 | *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 | *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 | | ClientInitializerFactory | *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. | | NettyCamelStateCorrelationManager | *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 | *producerPoolMinEvictableIdle* (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 | *hostnameVerification* ( security) | To enable/disable hostname verification on SSLEngine | 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 | *autowiredEnabled* (advanced) | Whether autowiring is enabled. This is used for automatic autowiring options (the option must be marked as autowired) by looking up in the registry to find if there is a single instance of matching type, which then gets configured on the component. This can be used for automatic configuring JDBC data sources, JMS connection factories, AWS Clients, etc. | true | boolean | *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 | *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 option 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/decoder 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 | *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. | | List | *delimiter* (codec) | The delimiter to use for the textline codec. Possible values are LINE and NULL. There are 2 enums and the value can be one of: LINE, NULL | LINE | TextLineDelimiter | *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. | | List | *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 - however only Strings are allowed to be serialized by default. | 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 | *useGlobalSslContextParameters* (security) | Enable usage of global SSL context parameters. | false | boolean |=== // component options: END // endpoint options: START The Netty endpoint is configured using URI syntax: ---- netty: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. There are 2 enums and the value can be one of: tcp, 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 (71 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 NettyConstants#NETTY_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 option 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 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. There are 3 enums and the value can be one of: InOnly, InOut, InOptionalOut | | ExchangePattern | *nettyServerBootstrapFactory* (consumer) | To use a custom NettyServerBootstrapFactory | | NettyServerBootstrapFactory | *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. There are 6 enums and the value can be one of: TRACE, DEBUG, INFO, WARN, ERROR, OFF | WARN | LoggingLevel | *serverClosedChannelException{zwsp}CaughtLogLevel* (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. There are 6 enums and the value can be one of: TRACE, DEBUG, INFO, WARN, ERROR, OFF | DEBUG | LoggingLevel | *serverExceptionCaughtLogLevel* (consumer) | If the server (NettyConsumer) catches an exception then its logged using this logging level. There are 6 enums and the value can be one of: TRACE, DEBUG, INFO, WARN, ERROR, OFF | WARN | LoggingLevel | *serverInitializerFactory* (consumer) | To use a custom ServerInitializerFactory | | ServerInitializerFactory | *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 | *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 | *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 | | ClientInitializerFactory | *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. | | NettyCamelStateCorrelationManager | *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 | *producerPoolMinEvictableIdle* (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 | *hostnameVerification* ( security) | To enable/disable hostname verification on SSLEngine | 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 | *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 | 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 option 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/decoder 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 | *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. | | List | *delimiter* (codec) | The delimiter to use for the textline codec. Possible values are LINE and NULL. There are 2 enums and the value can be one of: LINE, NULL | LINE | TextLineDelimiter | *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. | | List | *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 - however only Strings are allowed to be serialized by default. | 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 == 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` |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` |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 Note that Object serialization is not allowed by default, and so a decoder must be configured. [source,java] ---- @BindToRegistry(""decoder"") public ChannelHandler getDecoder() throws Exception { return new DefaultChannelHandlerFactory() { @Override public ChannelHandler newChannelHandler() { return new DatagramPacketObjectDecoder(ClassResolvers.weakCachingResolver(null)); } }; } RouteBuilder builder = new RouteBuilder() { public void configure() { from(""netty:udp://0.0.0.0:5155?sync=true&decoders=#decoder"") .process(new Processor() { public void process(Exchange exchange) throws Exception { Poetry poetry = (Poetry) exchange.getIn().getBody(); // Process poetry in some way exchange.getOut().setBody(""Message received); } } } }; ---- === A TCP based Netty consumer endpoint using One-way communication [source,java] ---- RouteBuilder builder = new RouteBuilder() { public void configure() { from(""netty:tcp://0.0.0.0:5150"") .to(""mock:result""); } }; ---- === An SSL/TCP based Netty consumer endpoint using Request-Reply communication [[Netty-UsingtheJSSEConfigurationUtility]] Using the JSSE Configuration Utility The Netty component supports SSL/TLS configuration through the xref:manual::camel-configuration-utilities.adoc[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. [[Netty-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(""netty"", NettyComponent.class); nettyComponent.setSslContextParameters(scp); ---- [[Netty-SpringDSLbasedconfigurationofendpoint]] Spring DSL based configuration of endpoint [source,xml] ---- ... ... ... ... ---- [[Netty-UsingBasicSSLTLSconfigurationontheJettyComponent]] Using Basic SSL/TLS configuration on the Jetty Component [source,java] ---- Registry registry = context.getRegistry(); 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.addRoutes(new RouteBuilder() { public void configure() { String netty_ssl_endpoint = ""netty:tcp://0.0.0.0: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); } } } }); ---- [[Netty-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 xref:netty-component.adoc[Netty] 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(""netty:tcp://0.0.0.0:{{port}}?encoders=#encoders&sync=false""); from(""netty:tcp://0.0.0.0:{{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(""netty:tcp://0.0.0.0: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); } } }); ---- [[Netty-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 (Registry, 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 = ""netty:tcp://0.0.0.0: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.netty.NettyServerBossPoolBuilder` builder for Netty consumers, and a `org.apache.camel.component.netty.NettyClientBossPoolBuilder` for the Netty producers. ==== Then in the Camel routes we can refer to this worker pools by configuring the `workerPool` option in the 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. include::{page-component-version}@camel-spring-boot::page$netty-starter.adoc[] ",12480,False,2367.08091450998,median "// Copyright 2014 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 ""extensions/browser/extension_prefs.h"" #include #include #include #include #include ""base/debug/crash_logging.h"" #include ""base/debug/dump_without_crashing.h"" #include ""base/macros.h"" #include ""base/memory/ptr_util.h"" #include ""base/metrics/histogram_macros.h"" #include ""base/strings/string_number_conversions.h"" #include ""base/strings/string_util.h"" #include ""base/trace_event/trace_event.h"" #include ""build/build_config.h"" #include ""components/crx_file/id_util.h"" #include ""components/pref_registry/pref_registry_syncable.h"" #include ""components/prefs/pref_service.h"" #include ""extensions/browser/app_sorting.h"" #include ""extensions/browser/event_router.h"" #include ""extensions/browser/extension_pref_store.h"" #include ""extensions/browser/extension_prefs_factory.h"" #include ""extensions/browser/extension_prefs_observer.h"" #include ""extensions/browser/extension_system.h"" #include ""extensions/browser/install_flag.h"" #include ""extensions/browser/pref_names.h"" #include ""extensions/common/manifest.h"" #include ""extensions/common/permissions/permission_set.h"" #include ""extensions/common/permissions/permissions_info.h"" #include ""extensions/common/url_pattern.h"" #include ""extensions/common/user_script.h"" namespace extensions { namespace { // Additional preferences keys, which are not needed by external clients. // True if this extension is running. Note this preference stops getting updated // during Chrome shutdown (and won't be updated on a browser crash) and so can // be used at startup to determine whether the extension was running when Chrome // was last terminated. const char kPrefRunning[] = ""running""; // Whether this extension had windows when it was last running. const char kIsActive[] = ""is_active""; // Where an extension was installed from. (see Manifest::Location) const char kPrefLocation[] = ""location""; // Enabled, disabled, killed, etc. (see Extension::State) const char kPrefState[] = ""state""; // The path to the current version's manifest file. const char kPrefPath[] = ""path""; // The dictionary containing the extension's manifest. const char kPrefManifest[] = ""manifest""; // The version number. const char kPrefVersion[] = ""manifest.version""; // Indicates whether an extension is blacklisted. const char kPrefBlacklist[] = ""blacklist""; // If extension is greylisted. const char kPrefBlacklistState[] = ""blacklist_state""; // The count of how many times we prompted the user to acknowledge an // extension. const char kPrefAcknowledgePromptCount[] = ""ack_prompt_count""; // Indicates whether the user has acknowledged various types of extensions. const char kPrefExternalAcknowledged[] = ""ack_external""; const char kPrefBlacklistAcknowledged[] = ""ack_blacklist""; // Indicates whether the external extension was installed during the first // run of this profile. const char kPrefExternalInstallFirstRun[] = ""external_first_run""; // A bitmask of all the reasons an extension is disabled. const char kPrefDisableReasons[] = ""disable_reasons""; // The key for a serialized Time value indicating the start of the day (from the // server's perspective) an extension last included a ""ping"" parameter during // its update check. const char kLastPingDay[] = ""lastpingday""; // Similar to kLastPingDay, but for ""active"" instead of ""rollcall"" pings. const char kLastActivePingDay[] = ""last_active_pingday""; // A bit we use to keep track of whether we need to do an ""active"" ping. const char kActiveBit[] = ""active_bit""; // Path for settings specific to blacklist update. const char kExtensionsBlacklistUpdate[] = ""extensions.blacklistupdate""; // Path for the delayed install info dictionary preference. The actual string // value is a legacy artifact for when delayed installs only pertained to // updates that were waiting for idle. const char kDelayedInstallInfo[] = ""idle_install_info""; // Reason why the extension's install was delayed. const char kDelayedInstallReason[] = ""delay_install_reason""; // Path for the suggested page ordinal of a delayed extension install. const char kPrefSuggestedPageOrdinal[] = ""suggested_page_ordinal""; // A preference that, if true, will allow this extension to run in incognito // mode. const char kPrefIncognitoEnabled[] = ""incognito""; // A preference to control whether an extension is allowed to inject script in // pages with file URLs. const char kPrefAllowFileAccess[] = ""newAllowFileAccess""; // TODO(jstritar): As part of fixing http://crbug.com/91577, we revoked all // extension file access by renaming the pref. We should eventually clean up // the old flag and possibly go back to that name. // const char kPrefAllowFileAccessOld[] = ""allowFileAccess""; // A preference specifying if the user dragged the app on the NTP. const char kPrefUserDraggedApp[] = ""user_dragged_app_ntp""; // Preferences that hold which permissions the user has granted the extension. // We explicitly keep track of these so that extensions can contain unknown // permissions, for backwards compatibility reasons, and we can still prompt // the user to accept them once recognized. We store the active permission // permissions because they may differ from those defined in the manifest. const char kPrefActivePermissions[] = ""active_permissions""; const char kPrefGrantedPermissions[] = ""granted_permissions""; // The preference names for PermissionSet values. const char kPrefAPIs[] = ""api""; const char kPrefManifestPermissions[] = ""manifest_permissions""; const char kPrefExplicitHosts[] = ""explicit_host""; const char kPrefScriptableHosts[] = ""scriptable_host""; // A preference that indicates when an extension was installed. const char kPrefInstallTime[] = ""install_time""; // A preference which saves the creation flags for extensions. const char kPrefCreationFlags[] = ""creation_flags""; // A preference that indicates whether the extension was installed from the // Chrome Web Store. const char kPrefFromWebStore[] = ""from_webstore""; // A preference that indicates whether the extension was installed from a // mock App created from a bookmark. const char kPrefFromBookmark[] = ""from_bookmark""; // A preference that indicates whether the extension was installed as a // default app. const char kPrefWasInstalledByDefault[] = ""was_installed_by_default""; // A preference that indicates whether the extension was installed as an // OEM app. const char kPrefWasInstalledByOem[] = ""was_installed_by_oem""; // Key for Geometry Cache preference. const char kPrefGeometryCache[] = ""geometry_cache""; // A preference that indicates when an extension is last launched. const char kPrefLastLaunchTime[] = ""last_launch_time""; // Am installation parameter bundled with an extension. const char kPrefInstallParam[] = ""install_parameter""; // A list of installed ids and a signature. const char kInstallSignature[] = ""extensions.install_signature""; // A boolean preference that indicates whether the extension should not be // synced. Default value is false. const char kPrefDoNotSync[] = ""do_not_sync""; const char kCorruptedDisableCount[] = ""extensions.corrupted_disable_count""; // A boolean preference that indicates whether the extension has local changes // that need to be synced. Default value is false. const char kPrefNeedsSync[] = ""needs_sync""; // Provider of write access to a dictionary storing extension prefs. class ScopedExtensionPrefUpdate : public DictionaryPrefUpdate { public: ScopedExtensionPrefUpdate(PrefService* service, const std::string& extension_id) : DictionaryPrefUpdate(service, pref_names::kExtensions), extension_id_(extension_id) {} ~ScopedExtensionPrefUpdate() override {} // DictionaryPrefUpdate overrides: base::DictionaryValue* Get() override { base::DictionaryValue* dict = DictionaryPrefUpdate::Get(); base::DictionaryValue* extension = NULL; if (!dict->GetDictionary(extension_id_, &extension)) { // Extension pref does not exist, create it. extension = new base::DictionaryValue(); dict->SetWithoutPathExpansion(extension_id_, extension); } return extension; } private: const std::string extension_id_; DISALLOW_COPY_AND_ASSIGN(ScopedExtensionPrefUpdate); }; std::string JoinPrefs(const std::string& parent, const char* child) { return parent + ""."" + child; } // Checks if kPrefBlacklist is set to true in the base::DictionaryValue. // Return false if the value is false or kPrefBlacklist does not exist. // This is used to decide if an extension is blacklisted. bool IsBlacklistBitSet(const base::DictionaryValue* ext) { bool bool_value; return ext->GetBoolean(kPrefBlacklist, &bool_value) && bool_value; } void LoadExtensionControlledPrefs(ExtensionPrefs* prefs, ExtensionPrefValueMap* value_map, const std::string& extension_id, ExtensionPrefsScope scope) { std::string scope_string; if (!pref_names::ScopeToPrefName(scope, &scope_string)) return; std::string key = extension_id + ""."" + scope_string; const base::DictionaryValue* source_dict = prefs->pref_service()->GetDictionary(pref_names::kExtensions); const base::DictionaryValue* preferences = NULL; if (!source_dict->GetDictionary(key, &preferences)) return; for (base::DictionaryValue::Iterator iter(*preferences); !iter.IsAtEnd(); iter.Advance()) { value_map->SetExtensionPref( extension_id, iter.key(), scope, iter.value().DeepCopy()); } } } // namespace // // TimeProvider // ExtensionPrefs::TimeProvider::TimeProvider() { } ExtensionPrefs::TimeProvider::~TimeProvider() { } base::Time ExtensionPrefs::TimeProvider::GetCurrentTime() const { return base::Time::Now(); } // // ScopedUpdate // template ExtensionPrefs::ScopedUpdate::ScopedUpdate( ExtensionPrefs* prefs, const std::string& extension_id, const std::string& key) : update_(prefs->pref_service(), pref_names::kExtensions), extension_id_(extension_id), key_(key) { DCHECK(crx_file::id_util::IdIsValid(extension_id_)); } template ExtensionPrefs::ScopedUpdate::~ScopedUpdate() { } template T* ExtensionPrefs::ScopedUpdate::Get() { base::DictionaryValue* dict = update_.Get(); base::DictionaryValue* extension = NULL; base::Value* key_value = NULL; if (!dict->GetDictionary(extension_id_, &extension) || !extension->Get(key_, &key_value)) { return NULL; } return key_value->GetType() == type_enum_value ? static_cast(key_value) : NULL; } template T* ExtensionPrefs::ScopedUpdate::Create() { base::DictionaryValue* dict = update_.Get(); base::DictionaryValue* extension = NULL; base::Value* key_value = NULL; T* value_as_t = NULL; if (!dict->GetDictionary(extension_id_, &extension)) { extension = new base::DictionaryValue; dict->SetWithoutPathExpansion(extension_id_, extension); } if (!extension->Get(key_, &key_value)) { value_as_t = new T; extension->SetWithoutPathExpansion(key_, value_as_t); } else { // It would be nice to CHECK that this doesn't happen, but since prefs can // get into a mangled state, we can't really do that. Instead, handle it // gracefully (by overwriting whatever was previously there). // TODO(devlin): It's unclear if there's anything we'll ever be able to do // here (corrupted prefs are sometimes a fact of life), but the debug info // might be useful. Remove the dumps after we analyze them. if (key_value->GetType() != type_enum_value) { NOTREACHED(); base::debug::SetCrashKeyValue( ""existing_extension_pref_value_type"", base::IntToString(static_cast(key_value->GetType()))); base::debug::DumpWithoutCrashing(); value_as_t = new T(); extension->SetWithoutPathExpansion(key_, value_as_t); } else { value_as_t = static_cast(key_value); } } return value_as_t; } // Explicit instantiations for Dictionary and List value types. template class ExtensionPrefs::ScopedUpdate; template class ExtensionPrefs::ScopedUpdate; // // ExtensionPrefs // // static ExtensionPrefs* ExtensionPrefs::Create( content::BrowserContext* browser_context, PrefService* prefs, const base::FilePath& root_dir, ExtensionPrefValueMap* extension_pref_value_map, bool extensions_disabled, const std::vector& early_observers) { return ExtensionPrefs::Create(browser_context, prefs, root_dir, extension_pref_value_map, extensions_disabled, early_observers, base::WrapUnique(new TimeProvider())); } // static ExtensionPrefs* ExtensionPrefs::Create( content::BrowserContext* browser_context, PrefService* pref_service, const base::FilePath& root_dir, ExtensionPrefValueMap* extension_pref_value_map, bool extensions_disabled, const std::vector& early_observers, std::unique_ptr time_provider) { return new ExtensionPrefs(browser_context, pref_service, root_dir, extension_pref_value_map, std::move(time_provider), extensions_disabled, early_observers); } ExtensionPrefs::~ExtensionPrefs() { } // static ExtensionPrefs* ExtensionPrefs::Get(content::BrowserContext* context) { return ExtensionPrefsFactory::GetInstance()->GetForBrowserContext(context); } static base::FilePath::StringType MakePathRelative(const base::FilePath& parent, const base::FilePath& child) { if (!parent.IsParent(child)) return child.value(); base::FilePath::StringType retval = child.value().substr( parent.value().length()); if (base::FilePath::IsSeparator(retval[0])) return retval.substr(1); else return retval; } void ExtensionPrefs::MakePathsRelative() { const base::DictionaryValue* dict = prefs_->GetDictionary(pref_names::kExtensions); if (!dict || dict->empty()) return; // Collect all extensions ids with absolute paths in |absolute_keys|. std::set absolute_keys; for (base::DictionaryValue::Iterator i(*dict); !i.IsAtEnd(); i.Advance()) { const base::DictionaryValue* extension_dict = NULL; if (!i.value().GetAsDictionary(&extension_dict)) continue; int location_value; if (extension_dict->GetInteger(kPrefLocation, &location_value) && Manifest::IsUnpackedLocation( static_cast(location_value))) { // Unpacked extensions can have absolute paths. continue; } base::FilePath::StringType path_string; if (!extension_dict->GetString(kPrefPath, &path_string)) continue; base::FilePath path(path_string); if (path.IsAbsolute()) absolute_keys.insert(i.key()); } if (absolute_keys.empty()) return; // Fix these paths. DictionaryPrefUpdate update(prefs_, pref_names::kExtensions); base::DictionaryValue* update_dict = update.Get(); for (std::set::iterator i = absolute_keys.begin(); i != absolute_keys.end(); ++i) { base::DictionaryValue* extension_dict = NULL; if (!update_dict->GetDictionaryWithoutPathExpansion(*i, &extension_dict)) { NOTREACHED() << ""Control should never reach here for extension "" << *i; continue; } base::FilePath::StringType path_string; extension_dict->GetString(kPrefPath, &path_string); base::FilePath path(path_string); extension_dict->SetString(kPrefPath, MakePathRelative(install_directory_, path)); } } const base::DictionaryValue* ExtensionPrefs::GetExtensionPref( const std::string& extension_id) const { const base::DictionaryValue* extensions = prefs_->GetDictionary(pref_names::kExtensions); const base::DictionaryValue* extension_dict = NULL; if (!extensions || !extensions->GetDictionary(extension_id, &extension_dict)) { return NULL; } return extension_dict; } void ExtensionPrefs::UpdateExtensionPref(const std::string& extension_id, const std::string& key, base::Value* data_value) { if (!crx_file::id_util::IdIsValid(extension_id)) { NOTREACHED() << ""Invalid extension_id "" << extension_id; return; } ScopedExtensionPrefUpdate update(prefs_, extension_id); if (data_value) update->Set(key, data_value); else update->Remove(key, NULL); } void ExtensionPrefs::DeleteExtensionPrefs(const std::string& extension_id) { extension_pref_value_map_->UnregisterExtension(extension_id); FOR_EACH_OBSERVER(ExtensionPrefsObserver, observer_list_, OnExtensionPrefsDeleted(extension_id)); DictionaryPrefUpdate update(prefs_, pref_names::kExtensions); base::DictionaryValue* dict = update.Get(); dict->Remove(extension_id, NULL); } bool ExtensionPrefs::ReadPrefAsBoolean(const std::string& extension_id, const std::string& pref_key, bool* out_value) const { const base::DictionaryValue* ext = GetExtensionPref(extension_id); if (!ext || !ext->GetBoolean(pref_key, out_value)) return false; return true; } bool ExtensionPrefs::ReadPrefAsInteger(const std::string& extension_id, const std::string& pref_key, int* out_value) const { const base::DictionaryValue* ext = GetExtensionPref(extension_id); if (!ext || !ext->GetInteger(pref_key, out_value)) return false; return true; } bool ExtensionPrefs::ReadPrefAsString(const std::string& extension_id, const std::string& pref_key, std::string* out_value) const { const base::DictionaryValue* ext = GetExtensionPref(extension_id); if (!ext || !ext->GetString(pref_key, out_value)) return false; return true; } bool ExtensionPrefs::ReadPrefAsList(const std::string& extension_id, const std::string& pref_key, const base::ListValue** out_value) const { const base::DictionaryValue* ext = GetExtensionPref(extension_id); const base::ListValue* out = NULL; if (!ext || !ext->GetList(pref_key, &out)) return false; if (out_value) *out_value = out; return true; } bool ExtensionPrefs::ReadPrefAsDictionary( const std::string& extension_id, const std::string& pref_key, const base::DictionaryValue** out_value) const { const base::DictionaryValue* ext = GetExtensionPref(extension_id); const base::DictionaryValue* out = NULL; if (!ext || !ext->GetDictionary(pref_key, &out)) return false; if (out_value) *out_value = out; return true; } bool ExtensionPrefs::HasPrefForExtension( const std::string& extension_id) const { return GetExtensionPref(extension_id) != NULL; } bool ExtensionPrefs::ReadPrefAsURLPatternSet(const std::string& extension_id, const std::string& pref_key, URLPatternSet* result, int valid_schemes) const { const base::ListValue* value = NULL; if (!ReadPrefAsList(extension_id, pref_key, &value)) return false; const base::DictionaryValue* extension = GetExtensionPref(extension_id); if (!extension) return false; int location; if (extension->GetInteger(kPrefLocation, &location) && static_cast(location) == Manifest::COMPONENT) { valid_schemes |= URLPattern::SCHEME_CHROMEUI; } bool allow_file_access = AllowFileAccess(extension_id); return result->Populate(*value, valid_schemes, allow_file_access, NULL); } void ExtensionPrefs::SetExtensionPrefURLPatternSet( const std::string& extension_id, const std::string& pref_key, const URLPatternSet& new_value) { UpdateExtensionPref(extension_id, pref_key, new_value.ToValue().release()); } bool ExtensionPrefs::ReadPrefAsBooleanAndReturn( const std::string& extension_id, const std::string& pref_key) const { bool out_value = false; return ReadPrefAsBoolean(extension_id, pref_key, &out_value) && out_value; } std::unique_ptr ExtensionPrefs::ReadPrefAsPermissionSet( const std::string& extension_id, const std::string& pref_key) const { if (!GetExtensionPref(extension_id)) return nullptr; // Retrieve the API permissions. Please refer SetExtensionPrefPermissionSet() // for api_values format. APIPermissionSet apis; const base::ListValue* api_values = NULL; std::string api_pref = JoinPrefs(pref_key, kPrefAPIs); if (ReadPrefAsList(extension_id, api_pref, &api_values)) { APIPermissionSet::ParseFromJSON(api_values, APIPermissionSet::kAllowInternalPermissions, &apis, NULL, NULL); } // Retrieve the Manifest Keys permissions. Please refer to // |SetExtensionPrefPermissionSet| for manifest_permissions_values format. ManifestPermissionSet manifest_permissions; const base::ListValue* manifest_permissions_values = NULL; std::string manifest_permission_pref = JoinPrefs(pref_key, kPrefManifestPermissions); if (ReadPrefAsList(extension_id, manifest_permission_pref, &manifest_permissions_values)) { ManifestPermissionSet::ParseFromJSON( manifest_permissions_values, &manifest_permissions, NULL, NULL); } // Retrieve the explicit host permissions. URLPatternSet explicit_hosts; ReadPrefAsURLPatternSet( extension_id, JoinPrefs(pref_key, kPrefExplicitHosts), &explicit_hosts, Extension::kValidHostPermissionSchemes); // Retrieve the scriptable host permissions. URLPatternSet scriptable_hosts; ReadPrefAsURLPatternSet( extension_id, JoinPrefs(pref_key, kPrefScriptableHosts), &scriptable_hosts, UserScript::ValidUserScriptSchemes()); return base::WrapUnique(new PermissionSet(apis, manifest_permissions, explicit_hosts, scriptable_hosts)); } // Set the API or Manifest permissions. // The format of api_values is: // [ ""permission_name1"", // permissions do not support detail. // ""permission_name2"", // {""permission_name3"": value }, // // permission supports detail, permission detail will be stored in value. // ... // ] template static base::ListValue* CreatePermissionList(const T& permissions) { base::ListValue* values = new base::ListValue(); for (typename T::const_iterator i = permissions.begin(); i != permissions.end(); ++i) { std::unique_ptr detail(i->ToValue()); if (detail) { std::unique_ptr tmp(new base::DictionaryValue()); tmp->Set(i->name(), detail.release()); values->Append(std::move(tmp)); } else { values->AppendString(i->name()); } } return values; } void ExtensionPrefs::SetExtensionPrefPermissionSet( const std::string& extension_id, const std::string& pref_key, const PermissionSet& new_value) { std::string api_pref = JoinPrefs(pref_key, kPrefAPIs); base::ListValue* api_values = CreatePermissionList(new_value.apis()); UpdateExtensionPref(extension_id, api_pref, api_values); std::string manifest_permissions_pref = JoinPrefs(pref_key, kPrefManifestPermissions); base::ListValue* manifest_permissions_values = CreatePermissionList(new_value.manifest_permissions()); UpdateExtensionPref(extension_id, manifest_permissions_pref, manifest_permissions_values); // Set the explicit host permissions. if (!new_value.explicit_hosts().is_empty()) { SetExtensionPrefURLPatternSet(extension_id, JoinPrefs(pref_key, kPrefExplicitHosts), new_value.explicit_hosts()); } // Set the scriptable host permissions. if (!new_value.scriptable_hosts().is_empty()) { SetExtensionPrefURLPatternSet(extension_id, JoinPrefs(pref_key, kPrefScriptableHosts), new_value.scriptable_hosts()); } } int ExtensionPrefs::IncrementAcknowledgePromptCount( const std::string& extension_id) { int count = 0; ReadPrefAsInteger(extension_id, kPrefAcknowledgePromptCount, &count); ++count; UpdateExtensionPref(extension_id, kPrefAcknowledgePromptCount, new base::FundamentalValue(count)); return count; } bool ExtensionPrefs::IsExternalExtensionAcknowledged( const std::string& extension_id) const { return ReadPrefAsBooleanAndReturn(extension_id, kPrefExternalAcknowledged); } void ExtensionPrefs::AcknowledgeExternalExtension( const std::string& extension_id) { DCHECK(crx_file::id_util::IdIsValid(extension_id)); UpdateExtensionPref(extension_id, kPrefExternalAcknowledged, new base::FundamentalValue(true)); UpdateExtensionPref(extension_id, kPrefAcknowledgePromptCount, NULL); } bool ExtensionPrefs::IsBlacklistedExtensionAcknowledged( const std::string& extension_id) const { return ReadPrefAsBooleanAndReturn(extension_id, kPrefBlacklistAcknowledged); } void ExtensionPrefs::AcknowledgeBlacklistedExtension( const std::string& extension_id) { DCHECK(crx_file::id_util::IdIsValid(extension_id)); UpdateExtensionPref(extension_id, kPrefBlacklistAcknowledged, new base::FundamentalValue(true)); UpdateExtensionPref(extension_id, kPrefAcknowledgePromptCount, NULL); } bool ExtensionPrefs::IsExternalInstallFirstRun( const std::string& extension_id) const { return ReadPrefAsBooleanAndReturn(extension_id, kPrefExternalInstallFirstRun); } void ExtensionPrefs::SetExternalInstallFirstRun( const std::string& extension_id) { DCHECK(crx_file::id_util::IdIsValid(extension_id)); UpdateExtensionPref(extension_id, kPrefExternalInstallFirstRun, new base::FundamentalValue(true)); } bool ExtensionPrefs::SetAlertSystemFirstRun() { if (prefs_->GetBoolean(pref_names::kAlertsInitialized)) { return true; } prefs_->SetBoolean(pref_names::kAlertsInitialized, true); return false; } bool ExtensionPrefs::DidExtensionEscalatePermissions( const std::string& extension_id) const { return HasDisableReason(extension_id, Extension::DISABLE_PERMISSIONS_INCREASE) || HasDisableReason(extension_id, Extension::DISABLE_REMOTE_INSTALL); } int ExtensionPrefs::GetDisableReasons(const std::string& extension_id) const { int value = -1; if (ReadPrefAsInteger(extension_id, kPrefDisableReasons, &value) && value >= 0) { return value; } return Extension::DISABLE_NONE; } bool ExtensionPrefs::HasDisableReason( const std::string& extension_id, Extension::DisableReason disable_reason) const { return (GetDisableReasons(extension_id) & disable_reason) != 0; } void ExtensionPrefs::AddDisableReason(const std::string& extension_id, Extension::DisableReason disable_reason) { DCHECK(!DoesExtensionHaveState(extension_id, Extension::ENABLED)); ModifyDisableReasons(extension_id, disable_reason, DISABLE_REASON_ADD); } void ExtensionPrefs::AddDisableReasons(const std::string& extension_id, int disable_reasons) { DCHECK(!DoesExtensionHaveState(extension_id, Extension::ENABLED)); ModifyDisableReasons(extension_id, disable_reasons, DISABLE_REASON_ADD); } void ExtensionPrefs::RemoveDisableReason( const std::string& extension_id, Extension::DisableReason disable_reason) { ModifyDisableReasons(extension_id, disable_reason, DISABLE_REASON_REMOVE); } void ExtensionPrefs::ReplaceDisableReasons(const std::string& extension_id, int disable_reasons) { ModifyDisableReasons(extension_id, disable_reasons, DISABLE_REASON_REPLACE); } void ExtensionPrefs::ClearDisableReasons(const std::string& extension_id) { ModifyDisableReasons(extension_id, Extension::DISABLE_NONE, DISABLE_REASON_CLEAR); } void ExtensionPrefs::ModifyDisableReasons(const std::string& extension_id, int reasons, DisableReasonChange change) { int old_value = GetDisableReasons(extension_id); int new_value = old_value; switch (change) { case DISABLE_REASON_ADD: new_value |= reasons; break; case DISABLE_REASON_REMOVE: new_value &= ~reasons; break; case DISABLE_REASON_REPLACE: new_value = reasons; break; case DISABLE_REASON_CLEAR: new_value = Extension::DISABLE_NONE; break; } if (old_value == new_value) // no change, return. return; if (new_value == Extension::DISABLE_NONE) { UpdateExtensionPref(extension_id, kPrefDisableReasons, NULL); } else { UpdateExtensionPref(extension_id, kPrefDisableReasons, new base::FundamentalValue(new_value)); } FOR_EACH_OBSERVER(ExtensionPrefsObserver, observer_list_, OnExtensionDisableReasonsChanged(extension_id, new_value)); } std::set ExtensionPrefs::GetBlacklistedExtensions() const { std::set ids; const base::DictionaryValue* extensions = prefs_->GetDictionary(pref_names::kExtensions); if (!extensions) return ids; for (base::DictionaryValue::Iterator it(*extensions); !it.IsAtEnd(); it.Advance()) { if (!it.value().IsType(base::Value::TYPE_DICTIONARY)) { NOTREACHED() << ""Invalid pref for extension "" << it.key(); continue; } if (IsBlacklistBitSet( static_cast(&it.value()))) { ids.insert(it.key()); } } return ids; } void ExtensionPrefs::SetExtensionBlacklisted(const std::string& extension_id, bool is_blacklisted) { bool currently_blacklisted = IsExtensionBlacklisted(extension_id); if (is_blacklisted == currently_blacklisted) return; // Always make sure the ""acknowledged"" bit is cleared since the blacklist bit // is changing. UpdateExtensionPref(extension_id, kPrefBlacklistAcknowledged, NULL); if (is_blacklisted) { UpdateExtensionPref(extension_id, kPrefBlacklist, new base::FundamentalValue(true)); } else { UpdateExtensionPref(extension_id, kPrefBlacklist, NULL); const base::DictionaryValue* dict = GetExtensionPref(extension_id); if (dict && dict->empty()) DeleteExtensionPrefs(extension_id); } } bool ExtensionPrefs::IsExtensionBlacklisted(const std::string& id) const { const base::DictionaryValue* ext_prefs = GetExtensionPref(id); return ext_prefs && IsBlacklistBitSet(ext_prefs); } namespace { // Serializes a 64bit integer as a string value. void SaveInt64(base::DictionaryValue* dictionary, const char* key, const int64_t value) { if (!dictionary) return; std::string string_value = base::Int64ToString(value); dictionary->SetString(key, string_value); } // Deserializes a 64bit integer stored as a string value. bool ReadInt64(const base::DictionaryValue* dictionary, const char* key, int64_t* value) { if (!dictionary) return false; std::string string_value; if (!dictionary->GetString(key, &string_value)) return false; return base::StringToInt64(string_value, value); } // Serializes |time| as a string value mapped to |key| in |dictionary|. void SaveTime(base::DictionaryValue* dictionary, const char* key, const base::Time& time) { SaveInt64(dictionary, key, time.ToInternalValue()); } // The opposite of SaveTime. If |key| is not found, this returns an empty Time // (is_null() will return true). base::Time ReadTime(const base::DictionaryValue* dictionary, const char* key) { int64_t value; if (ReadInt64(dictionary, key, &value)) return base::Time::FromInternalValue(value); return base::Time(); } } // namespace base::Time ExtensionPrefs::LastPingDay(const std::string& extension_id) const { DCHECK(crx_file::id_util::IdIsValid(extension_id)); return ReadTime(GetExtensionPref(extension_id), kLastPingDay); } void ExtensionPrefs::SetLastPingDay(const std::string& extension_id, const base::Time& time) { DCHECK(crx_file::id_util::IdIsValid(extension_id)); ScopedExtensionPrefUpdate update(prefs_, extension_id); SaveTime(update.Get(), kLastPingDay, time); } base::Time ExtensionPrefs::BlacklistLastPingDay() const { return ReadTime(prefs_->GetDictionary(kExtensionsBlacklistUpdate), kLastPingDay); } void ExtensionPrefs::SetBlacklistLastPingDay(const base::Time& time) { DictionaryPrefUpdate update(prefs_, kExtensionsBlacklistUpdate); SaveTime(update.Get(), kLastPingDay, time); } base::Time ExtensionPrefs::LastActivePingDay( const std::string& extension_id) const { DCHECK(crx_file::id_util::IdIsValid(extension_id)); return ReadTime(GetExtensionPref(extension_id), kLastActivePingDay); } void ExtensionPrefs::SetLastActivePingDay(const std::string& extension_id, const base::Time& time) { DCHECK(crx_file::id_util::IdIsValid(extension_id)); ScopedExtensionPrefUpdate update(prefs_, extension_id); SaveTime(update.Get(), kLastActivePingDay, time); } bool ExtensionPrefs::GetActiveBit(const std::string& extension_id) const { const base::DictionaryValue* dictionary = GetExtensionPref(extension_id); bool result = false; if (dictionary && dictionary->GetBoolean(kActiveBit, &result)) return result; return false; } void ExtensionPrefs::SetActiveBit(const std::string& extension_id, bool active) { UpdateExtensionPref(extension_id, kActiveBit, new base::FundamentalValue(active)); } std::unique_ptr ExtensionPrefs::GetGrantedPermissions( const std::string& extension_id) const { CHECK(crx_file::id_util::IdIsValid(extension_id)); return ReadPrefAsPermissionSet(extension_id, kPrefGrantedPermissions); } void ExtensionPrefs::AddGrantedPermissions(const std::string& extension_id, const PermissionSet& permissions) { CHECK(crx_file::id_util::IdIsValid(extension_id)); std::unique_ptr granted = GetGrantedPermissions(extension_id); std::unique_ptr union_set; if (granted) union_set = PermissionSet::CreateUnion(permissions, *granted); // The new granted permissions are the union of the already granted // permissions and the newly granted permissions. SetExtensionPrefPermissionSet(extension_id, kPrefGrantedPermissions, union_set ? *union_set : permissions); } void ExtensionPrefs::RemoveGrantedPermissions( const std::string& extension_id, const PermissionSet& permissions) { CHECK(crx_file::id_util::IdIsValid(extension_id)); // The new granted permissions are the difference of the already granted // permissions and the newly ungranted permissions. SetExtensionPrefPermissionSet( extension_id, kPrefGrantedPermissions, *PermissionSet::CreateDifference(*GetGrantedPermissions(extension_id), permissions)); } std::unique_ptr ExtensionPrefs::GetActivePermissions( const std::string& extension_id) const { CHECK(crx_file::id_util::IdIsValid(extension_id)); return ReadPrefAsPermissionSet(extension_id, kPrefActivePermissions); } void ExtensionPrefs::SetActivePermissions(const std::string& extension_id, const PermissionSet& permissions) { SetExtensionPrefPermissionSet( extension_id, kPrefActivePermissions, permissions); } void ExtensionPrefs::SetExtensionRunning(const std::string& extension_id, bool is_running) { base::Value* value = new base::FundamentalValue(is_running); UpdateExtensionPref(extension_id, kPrefRunning, value); } bool ExtensionPrefs::IsExtensionRunning(const std::string& extension_id) const { const base::DictionaryValue* extension = GetExtensionPref(extension_id); if (!extension) return false; bool running = false; extension->GetBoolean(kPrefRunning, &running); return running; } void ExtensionPrefs::SetIsActive(const std::string& extension_id, bool is_active) { base::Value* value = new base::FundamentalValue(is_active); UpdateExtensionPref(extension_id, kIsActive, value); } bool ExtensionPrefs::IsActive(const std::string& extension_id) const { const base::DictionaryValue* extension = GetExtensionPref(extension_id); if (!extension) return false; bool is_active = false; extension->GetBoolean(kIsActive, &is_active); return is_active; } bool ExtensionPrefs::IsIncognitoEnabled(const std::string& extension_id) const { return ReadPrefAsBooleanAndReturn(extension_id, kPrefIncognitoEnabled); } void ExtensionPrefs::SetIsIncognitoEnabled(const std::string& extension_id, bool enabled) { UpdateExtensionPref(extension_id, kPrefIncognitoEnabled, new base::FundamentalValue(enabled)); extension_pref_value_map_->SetExtensionIncognitoState(extension_id, enabled); } bool ExtensionPrefs::AllowFileAccess(const std::string& extension_id) const { return ReadPrefAsBooleanAndReturn(extension_id, kPrefAllowFileAccess); } void ExtensionPrefs::SetAllowFileAccess(const std::string& extension_id, bool allow) { UpdateExtensionPref(extension_id, kPrefAllowFileAccess, new base::FundamentalValue(allow)); } bool ExtensionPrefs::HasAllowFileAccessSetting( const std::string& extension_id) const { const base::DictionaryValue* ext = GetExtensionPref(extension_id); return ext && ext->HasKey(kPrefAllowFileAccess); } bool ExtensionPrefs::DoesExtensionHaveState( const std::string& id, Extension::State check_state) const { const base::DictionaryValue* extension = GetExtensionPref(id); int state = -1; if (!extension || !extension->GetInteger(kPrefState, &state)) return false; if (state < 0 || state >= Extension::NUM_STATES) { LOG(ERROR) << ""Bad pref 'state' for extension '"" << id << ""'""; return false; } return state == check_state; } bool ExtensionPrefs::IsExternalExtensionUninstalled( const std::string& id) const { return DoesExtensionHaveState(id, Extension::EXTERNAL_EXTENSION_UNINSTALLED); } bool ExtensionPrefs::IsExtensionDisabled(const std::string& id) const { return DoesExtensionHaveState(id, Extension::DISABLED); } ExtensionIdList ExtensionPrefs::GetToolbarOrder() const { ExtensionIdList id_list_out; GetUserExtensionPrefIntoContainer(pref_names::kToolbar, &id_list_out); return id_list_out; } void ExtensionPrefs::SetToolbarOrder(const ExtensionIdList& extension_ids) { SetExtensionPrefFromContainer(pref_names::kToolbar, extension_ids); } void ExtensionPrefs::OnExtensionInstalled( const Extension* extension, Extension::State initial_state, const syncer::StringOrdinal& page_ordinal, int install_flags, const std::string& install_parameter) { ScopedExtensionPrefUpdate update(prefs_, extension->id()); base::DictionaryValue* extension_dict = update.Get(); const base::Time install_time = time_provider_->GetCurrentTime(); PopulateExtensionInfoPrefs(extension, install_time, initial_state, install_flags, install_parameter, extension_dict); FinishExtensionInfoPrefs(extension->id(), install_time, extension->RequiresSortOrdinal(), page_ordinal, extension_dict); } void ExtensionPrefs::OnExtensionUninstalled(const std::string& extension_id, const Manifest::Location& location, bool external_uninstall) { app_sorting()->ClearOrdinals(extension_id); // For external extensions, we save a preference reminding ourself not to try // and install the extension anymore (except when |external_uninstall| is // true, which signifies that the registry key was deleted or the pref file // no longer lists the extension). if (!external_uninstall && Manifest::IsExternalLocation(location)) { UpdateExtensionPref(extension_id, kPrefState, new base::FundamentalValue( Extension::EXTERNAL_EXTENSION_UNINSTALLED)); extension_pref_value_map_->SetExtensionState(extension_id, false); FOR_EACH_OBSERVER(ExtensionPrefsObserver, observer_list_, OnExtensionStateChanged(extension_id, false)); } else { DeleteExtensionPrefs(extension_id); } } void ExtensionPrefs::SetExtensionEnabled(const std::string& extension_id) { UpdateExtensionPref(extension_id, kPrefState, new base::FundamentalValue(Extension::ENABLED)); extension_pref_value_map_->SetExtensionState(extension_id, true); UpdateExtensionPref(extension_id, kPrefDisableReasons, nullptr); FOR_EACH_OBSERVER(ExtensionPrefsObserver, observer_list_, OnExtensionStateChanged(extension_id, true)); } void ExtensionPrefs::SetExtensionDisabled(const std::string& extension_id, int disable_reasons) { if (!IsExternalExtensionUninstalled(extension_id)) { UpdateExtensionPref(extension_id, kPrefState, new base::FundamentalValue(Extension::DISABLED)); extension_pref_value_map_->SetExtensionState(extension_id, false); } UpdateExtensionPref(extension_id, kPrefDisableReasons, new base::FundamentalValue(disable_reasons)); FOR_EACH_OBSERVER(ExtensionPrefsObserver, observer_list_, OnExtensionStateChanged(extension_id, false)); } void ExtensionPrefs::SetExtensionBlacklistState(const std::string& extension_id, BlacklistState state) { SetExtensionBlacklisted(extension_id, state == BLACKLISTED_MALWARE); UpdateExtensionPref(extension_id, kPrefBlacklistState, new base::FundamentalValue(state)); } BlacklistState ExtensionPrefs::GetExtensionBlacklistState( const std::string& extension_id) const { if (IsExtensionBlacklisted(extension_id)) return BLACKLISTED_MALWARE; const base::DictionaryValue* ext_prefs = GetExtensionPref(extension_id); int int_value = 0; if (ext_prefs && ext_prefs->GetInteger(kPrefBlacklistState, &int_value)) return static_cast(int_value); return NOT_BLACKLISTED; } std::string ExtensionPrefs::GetVersionString( const std::string& extension_id) const { const base::DictionaryValue* extension = GetExtensionPref(extension_id); if (!extension) return std::string(); std::string version; extension->GetString(kPrefVersion, &version); return version; } void ExtensionPrefs::UpdateManifest(const Extension* extension) { if (!Manifest::IsUnpackedLocation(extension->location())) { const base::DictionaryValue* extension_dict = GetExtensionPref(extension->id()); if (!extension_dict) return; const base::DictionaryValue* old_manifest = NULL; bool update_required = !extension_dict->GetDictionary(kPrefManifest, &old_manifest) || !extension->manifest()->value()->Equals(old_manifest); if (update_required) { UpdateExtensionPref(extension->id(), kPrefManifest, extension->manifest()->value()->DeepCopy()); } } } std::unique_ptr ExtensionPrefs::GetInstalledInfoHelper( const std::string& extension_id, const base::DictionaryValue* extension) const { int location_value; if (!extension->GetInteger(kPrefLocation, &location_value)) return std::unique_ptr(); Manifest::Location location = static_cast(location_value); if (location == Manifest::COMPONENT) { // Component extensions are ignored. Component extensions may have data // saved in preferences, but they are already loaded at this point (by // ComponentLoader) and shouldn't be populated into the result of // GetInstalledExtensionsInfo, otherwise InstalledLoader would also want to // load them. return std::unique_ptr(); } // Only the following extension types have data saved in the preferences. if (location != Manifest::INTERNAL && !Manifest::IsUnpackedLocation(location) && !Manifest::IsExternalLocation(location)) { NOTREACHED(); return std::unique_ptr(); } const base::DictionaryValue* manifest = NULL; if (!Manifest::IsUnpackedLocation(location) && !extension->GetDictionary(kPrefManifest, &manifest)) { LOG(WARNING) << ""Missing manifest for extension "" << extension_id; // Just a warning for now. } base::FilePath::StringType path; if (!extension->GetString(kPrefPath, &path)) return std::unique_ptr(); // Make path absolute. Most (but not all) extension types have relative paths. if (!base::FilePath(path).IsAbsolute()) path = install_directory_.Append(path).value(); return std::unique_ptr(new ExtensionInfo( manifest, extension_id, base::FilePath(path), location)); } std::unique_ptr ExtensionPrefs::GetInstalledExtensionInfo( const std::string& extension_id) const { const base::DictionaryValue* ext = NULL; const base::DictionaryValue* extensions = prefs_->GetDictionary(pref_names::kExtensions); if (!extensions || !extensions->GetDictionaryWithoutPathExpansion(extension_id, &ext)) return std::unique_ptr(); int state_value; if (ext->GetInteger(kPrefState, &state_value) && state_value == Extension::EXTERNAL_EXTENSION_UNINSTALLED) { LOG(WARNING) << ""External extension with id "" << extension_id << "" has been uninstalled by the user""; return std::unique_ptr(); } return GetInstalledInfoHelper(extension_id, ext); } std::unique_ptr ExtensionPrefs::GetInstalledExtensionsInfo() const { std::unique_ptr extensions_info(new ExtensionsInfo); const base::DictionaryValue* extensions = prefs_->GetDictionary(pref_names::kExtensions); for (base::DictionaryValue::Iterator extension_id(*extensions); !extension_id.IsAtEnd(); extension_id.Advance()) { if (!crx_file::id_util::IdIsValid(extension_id.key())) continue; std::unique_ptr info = GetInstalledExtensionInfo(extension_id.key()); if (info) extensions_info->push_back(linked_ptr(info.release())); } return extensions_info; } std::unique_ptr ExtensionPrefs::GetUninstalledExtensionsInfo() const { std::unique_ptr extensions_info(new ExtensionsInfo); const base::DictionaryValue* extensions = prefs_->GetDictionary(pref_names::kExtensions); for (base::DictionaryValue::Iterator extension_id(*extensions); !extension_id.IsAtEnd(); extension_id.Advance()) { const base::DictionaryValue* ext = NULL; if (!crx_file::id_util::IdIsValid(extension_id.key()) || !IsExternalExtensionUninstalled(extension_id.key()) || !extension_id.value().GetAsDictionary(&ext)) continue; std::unique_ptr info = GetInstalledInfoHelper(extension_id.key(), ext); if (info) extensions_info->push_back(linked_ptr(info.release())); } return extensions_info; } void ExtensionPrefs::SetDelayedInstallInfo( const Extension* extension, Extension::State initial_state, int install_flags, DelayReason delay_reason, const syncer::StringOrdinal& page_ordinal, const std::string& install_parameter) { base::DictionaryValue* extension_dict = new base::DictionaryValue(); PopulateExtensionInfoPrefs(extension, time_provider_->GetCurrentTime(), initial_state, install_flags, install_parameter, extension_dict); // Add transient data that is needed by FinishDelayedInstallInfo(), but // should not be in the final extension prefs. All entries here should have // a corresponding Remove() call in FinishDelayedInstallInfo(). if (extension->RequiresSortOrdinal()) { extension_dict->SetString( kPrefSuggestedPageOrdinal, page_ordinal.IsValid() ? page_ordinal.ToInternalValue() : std::string()); } extension_dict->SetInteger(kDelayedInstallReason, static_cast(delay_reason)); UpdateExtensionPref(extension->id(), kDelayedInstallInfo, extension_dict); } bool ExtensionPrefs::RemoveDelayedInstallInfo( const std::string& extension_id) { if (!GetExtensionPref(extension_id)) return false; ScopedExtensionPrefUpdate update(prefs_, extension_id); bool result = update->Remove(kDelayedInstallInfo, NULL); return result; } bool ExtensionPrefs::FinishDelayedInstallInfo( const std::string& extension_id) { CHECK(crx_file::id_util::IdIsValid(extension_id)); ScopedExtensionPrefUpdate update(prefs_, extension_id); base::DictionaryValue* extension_dict = update.Get(); base::DictionaryValue* pending_install_dict = NULL; if (!extension_dict->GetDictionary(kDelayedInstallInfo, &pending_install_dict)) { return false; } // Retrieve and clear transient values populated by SetDelayedInstallInfo(). // Also do any other data cleanup that makes sense. std::string serialized_ordinal; syncer::StringOrdinal suggested_page_ordinal; bool needs_sort_ordinal = false; if (pending_install_dict->GetString(kPrefSuggestedPageOrdinal, &serialized_ordinal)) { suggested_page_ordinal = syncer::StringOrdinal(serialized_ordinal); needs_sort_ordinal = true; pending_install_dict->Remove(kPrefSuggestedPageOrdinal, NULL); } pending_install_dict->Remove(kDelayedInstallReason, NULL); const base::Time install_time = time_provider_->GetCurrentTime(); pending_install_dict->Set( kPrefInstallTime, new base::StringValue( base::Int64ToString(install_time.ToInternalValue()))); // Commit the delayed install data. for (base::DictionaryValue::Iterator it(*pending_install_dict); !it.IsAtEnd(); it.Advance()) { extension_dict->Set(it.key(), it.value().DeepCopy()); } FinishExtensionInfoPrefs(extension_id, install_time, needs_sort_ordinal, suggested_page_ordinal, extension_dict); return true; } std::unique_ptr ExtensionPrefs::GetDelayedInstallInfo( const std::string& extension_id) const { const base::DictionaryValue* extension_prefs = GetExtensionPref(extension_id); if (!extension_prefs) return std::unique_ptr(); const base::DictionaryValue* ext = NULL; if (!extension_prefs->GetDictionary(kDelayedInstallInfo, &ext)) return std::unique_ptr(); return GetInstalledInfoHelper(extension_id, ext); } ExtensionPrefs::DelayReason ExtensionPrefs::GetDelayedInstallReason( const std::string& extension_id) const { const base::DictionaryValue* extension_prefs = GetExtensionPref(extension_id); if (!extension_prefs) return DELAY_REASON_NONE; const base::DictionaryValue* ext = NULL; if (!extension_prefs->GetDictionary(kDelayedInstallInfo, &ext)) return DELAY_REASON_NONE; int delay_reason; if (!ext->GetInteger(kDelayedInstallReason, &delay_reason)) return DELAY_REASON_NONE; return static_cast(delay_reason); } std::unique_ptr ExtensionPrefs::GetAllDelayedInstallInfo() const { std::unique_ptr extensions_info(new ExtensionsInfo); const base::DictionaryValue* extensions = prefs_->GetDictionary(pref_names::kExtensions); for (base::DictionaryValue::Iterator extension_id(*extensions); !extension_id.IsAtEnd(); extension_id.Advance()) { if (!crx_file::id_util::IdIsValid(extension_id.key())) continue; std::unique_ptr info = GetDelayedInstallInfo(extension_id.key()); if (info) extensions_info->push_back(linked_ptr(info.release())); } return extensions_info; } bool ExtensionPrefs::WasAppDraggedByUser( const std::string& extension_id) const { return ReadPrefAsBooleanAndReturn(extension_id, kPrefUserDraggedApp); } void ExtensionPrefs::SetAppDraggedByUser(const std::string& extension_id) { UpdateExtensionPref(extension_id, kPrefUserDraggedApp, new base::FundamentalValue(true)); } bool ExtensionPrefs::IsFromWebStore( const std::string& extension_id) const { const base::DictionaryValue* dictionary = GetExtensionPref(extension_id); bool result = false; if (dictionary && dictionary->GetBoolean(kPrefFromWebStore, &result)) return result; return false; } bool ExtensionPrefs::IsFromBookmark( const std::string& extension_id) const { const base::DictionaryValue* dictionary = GetExtensionPref(extension_id); bool result = false; if (dictionary && dictionary->GetBoolean(kPrefFromBookmark, &result)) return result; return false; } int ExtensionPrefs::GetCreationFlags(const std::string& extension_id) const { int creation_flags = Extension::NO_FLAGS; if (!ReadPrefAsInteger(extension_id, kPrefCreationFlags, &creation_flags)) { // Since kPrefCreationFlags was added later, it will be missing for // previously installed extensions. if (IsFromBookmark(extension_id)) creation_flags |= Extension::FROM_BOOKMARK; if (IsFromWebStore(extension_id)) creation_flags |= Extension::FROM_WEBSTORE; if (WasInstalledByDefault(extension_id)) creation_flags |= Extension::WAS_INSTALLED_BY_DEFAULT; if (WasInstalledByOem(extension_id)) creation_flags |= Extension::WAS_INSTALLED_BY_OEM; } return creation_flags; } int ExtensionPrefs::GetDelayedInstallCreationFlags( const std::string& extension_id) const { int creation_flags = Extension::NO_FLAGS; const base::DictionaryValue* delayed_info = NULL; if (ReadPrefAsDictionary(extension_id, kDelayedInstallInfo, &delayed_info)) { delayed_info->GetInteger(kPrefCreationFlags, &creation_flags); } return creation_flags; } bool ExtensionPrefs::WasInstalledByDefault( const std::string& extension_id) const { const base::DictionaryValue* dictionary = GetExtensionPref(extension_id); bool result = false; if (dictionary && dictionary->GetBoolean(kPrefWasInstalledByDefault, &result)) return result; return false; } bool ExtensionPrefs::WasInstalledByOem(const std::string& extension_id) const { const base::DictionaryValue* dictionary = GetExtensionPref(extension_id); bool result = false; if (dictionary && dictionary->GetBoolean(kPrefWasInstalledByOem, &result)) return result; return false; } base::Time ExtensionPrefs::GetInstallTime( const std::string& extension_id) const { const base::DictionaryValue* extension = GetExtensionPref(extension_id); if (!extension) { NOTREACHED(); return base::Time(); } std::string install_time_str; if (!extension->GetString(kPrefInstallTime, &install_time_str)) return base::Time(); int64_t install_time_i64 = 0; if (!base::StringToInt64(install_time_str, &install_time_i64)) return base::Time(); return base::Time::FromInternalValue(install_time_i64); } bool ExtensionPrefs::DoNotSync(const std::string& extension_id) const { bool do_not_sync; if (!ReadPrefAsBoolean(extension_id, kPrefDoNotSync, &do_not_sync)) return false; return do_not_sync; } base::Time ExtensionPrefs::GetLastLaunchTime( const std::string& extension_id) const { const base::DictionaryValue* extension = GetExtensionPref(extension_id); if (!extension) return base::Time(); std::string launch_time_str; if (!extension->GetString(kPrefLastLaunchTime, &launch_time_str)) return base::Time(); int64_t launch_time_i64 = 0; if (!base::StringToInt64(launch_time_str, &launch_time_i64)) return base::Time(); return base::Time::FromInternalValue(launch_time_i64); } void ExtensionPrefs::SetLastLaunchTime(const std::string& extension_id, const base::Time& time) { DCHECK(crx_file::id_util::IdIsValid(extension_id)); ScopedExtensionPrefUpdate update(prefs_, extension_id); SaveTime(update.Get(), kPrefLastLaunchTime, time); } void ExtensionPrefs::ClearLastLaunchTimes() { const base::DictionaryValue* dict = prefs_->GetDictionary(pref_names::kExtensions); if (!dict || dict->empty()) return; // Collect all the keys to remove the last launched preference from. DictionaryPrefUpdate update(prefs_, pref_names::kExtensions); base::DictionaryValue* update_dict = update.Get(); for (base::DictionaryValue::Iterator i(*update_dict); !i.IsAtEnd(); i.Advance()) { base::DictionaryValue* extension_dict = NULL; if (!update_dict->GetDictionary(i.key(), &extension_dict)) continue; if (extension_dict->HasKey(kPrefLastLaunchTime)) extension_dict->Remove(kPrefLastLaunchTime, NULL); } } void ExtensionPrefs::GetExtensions(ExtensionIdList* out) const { CHECK(out); std::unique_ptr extensions_info(GetInstalledExtensionsInfo()); for (size_t i = 0; i < extensions_info->size(); ++i) { ExtensionInfo* info = extensions_info->at(i).get(); out->push_back(info->extension_id); } } // static ExtensionIdList ExtensionPrefs::GetExtensionsFrom( const PrefService* pref_service) { ExtensionIdList result; const base::DictionaryValue* extension_prefs = NULL; const base::Value* extension_prefs_value = pref_service->GetUserPrefValue(pref_names::kExtensions); if (!extension_prefs_value || !extension_prefs_value->GetAsDictionary(&extension_prefs)) { return result; // Empty set } for (base::DictionaryValue::Iterator it(*extension_prefs); !it.IsAtEnd(); it.Advance()) { const base::DictionaryValue* ext = NULL; if (!it.value().GetAsDictionary(&ext)) { NOTREACHED() << ""Invalid pref for extension "" << it.key(); continue; } if (!IsBlacklistBitSet(ext)) result.push_back(it.key()); } return result; } void ExtensionPrefs::AddObserver(ExtensionPrefsObserver* observer) { observer_list_.AddObserver(observer); } void ExtensionPrefs::RemoveObserver(ExtensionPrefsObserver* observer) { observer_list_.RemoveObserver(observer); } void ExtensionPrefs::InitPrefStore() { TRACE_EVENT0(""browser,startup"", ""ExtensionPrefs::InitPrefStore"") SCOPED_UMA_HISTOGRAM_TIMER(""Extensions.InitPrefStoreTime""); if (extensions_disabled_) { extension_pref_value_map_->NotifyInitializationCompleted(); return; } // When this is called, the PrefService is initialized and provides access // to the user preferences stored in a JSON file. ExtensionIdList extension_ids; { SCOPED_UMA_HISTOGRAM_TIMER(""Extensions.InitPrefGetExtensionsTime""); GetExtensions(&extension_ids); } // Create empty preferences dictionary for each extension (these dictionaries // are pruned when persisting the preferences to disk). for (ExtensionIdList::iterator ext_id = extension_ids.begin(); ext_id != extension_ids.end(); ++ext_id) { ScopedExtensionPrefUpdate update(prefs_, *ext_id); // This creates an empty dictionary if none is stored. update.Get(); } InitExtensionControlledPrefs(extension_pref_value_map_); extension_pref_value_map_->NotifyInitializationCompleted(); } bool ExtensionPrefs::HasIncognitoPrefValue(const std::string& pref_key) const { bool has_incognito_pref_value = false; extension_pref_value_map_->GetEffectivePrefValue(pref_key, true, &has_incognito_pref_value); return has_incognito_pref_value; } const base::DictionaryValue* ExtensionPrefs::GetGeometryCache( const std::string& extension_id) const { const base::DictionaryValue* extension_prefs = GetExtensionPref(extension_id); if (!extension_prefs) return NULL; const base::DictionaryValue* ext = NULL; if (!extension_prefs->GetDictionary(kPrefGeometryCache, &ext)) return NULL; return ext; } void ExtensionPrefs::SetGeometryCache( const std::string& extension_id, std::unique_ptr cache) { UpdateExtensionPref(extension_id, kPrefGeometryCache, cache.release()); } const base::DictionaryValue* ExtensionPrefs::GetInstallSignature() const { return prefs_->GetDictionary(kInstallSignature); } void ExtensionPrefs::SetInstallSignature( const base::DictionaryValue* signature) { if (signature) { prefs_->Set(kInstallSignature, *signature); DVLOG(1) << ""SetInstallSignature - saving""; } else { DVLOG(1) << ""SetInstallSignature - clearing""; prefs_->ClearPref(kInstallSignature); } } std::string ExtensionPrefs::GetInstallParam( const std::string& extension_id) const { const base::DictionaryValue* extension = GetExtensionPref(extension_id); if (!extension) // Expected during unit testing. return std::string(); std::string install_parameter; if (!extension->GetString(kPrefInstallParam, &install_parameter)) return std::string(); return install_parameter; } void ExtensionPrefs::SetInstallParam(const std::string& extension_id, const std::string& install_parameter) { UpdateExtensionPref(extension_id, kPrefInstallParam, new base::StringValue(install_parameter)); } int ExtensionPrefs::GetCorruptedDisableCount() const { return prefs_->GetInteger(kCorruptedDisableCount); } void ExtensionPrefs::IncrementCorruptedDisableCount() { int count = prefs_->GetInteger(kCorruptedDisableCount); prefs_->SetInteger(kCorruptedDisableCount, count + 1); } bool ExtensionPrefs::NeedsSync(const std::string& extension_id) const { return ReadPrefAsBooleanAndReturn(extension_id, kPrefNeedsSync); } void ExtensionPrefs::SetNeedsSync(const std::string& extension_id, bool needs_sync) { UpdateExtensionPref(extension_id, kPrefNeedsSync, needs_sync ? new base::FundamentalValue(true) : nullptr); } ExtensionPrefs::ExtensionPrefs( content::BrowserContext* browser_context, PrefService* prefs, const base::FilePath& root_dir, ExtensionPrefValueMap* extension_pref_value_map, std::unique_ptr time_provider, bool extensions_disabled, const std::vector& early_observers) : browser_context_(browser_context), prefs_(prefs), install_directory_(root_dir), extension_pref_value_map_(extension_pref_value_map), time_provider_(std::move(time_provider)), extensions_disabled_(extensions_disabled) { MakePathsRelative(); // Ensure that any early observers are watching before prefs are initialized. for (std::vector::const_iterator iter = early_observers.begin(); iter != early_observers.end(); ++iter) { AddObserver(*iter); } InitPrefStore(); } AppSorting* ExtensionPrefs::app_sorting() const { return ExtensionSystem::Get(browser_context_)->app_sorting(); } void ExtensionPrefs::SetNeedsStorageGarbageCollection(bool value) { prefs_->SetBoolean(pref_names::kStorageGarbageCollect, value); } bool ExtensionPrefs::NeedsStorageGarbageCollection() const { return prefs_->GetBoolean(pref_names::kStorageGarbageCollect); } // static void ExtensionPrefs::RegisterProfilePrefs( user_prefs::PrefRegistrySyncable* registry) { registry->RegisterDictionaryPref(pref_names::kExtensions); registry->RegisterListPref(pref_names::kToolbar, user_prefs::PrefRegistrySyncable::SYNCABLE_PREF); registry->RegisterIntegerPref(pref_names::kToolbarSize, -1); registry->RegisterDictionaryPref(kExtensionsBlacklistUpdate); registry->RegisterListPref(pref_names::kInstallAllowList); registry->RegisterListPref(pref_names::kInstallDenyList); registry->RegisterDictionaryPref(pref_names::kInstallForceList); registry->RegisterListPref(pref_names::kAllowedTypes); registry->RegisterBooleanPref(pref_names::kStorageGarbageCollect, false); registry->RegisterInt64Pref(pref_names::kLastUpdateCheck, 0); registry->RegisterInt64Pref(pref_names::kNextUpdateCheck, 0); registry->RegisterListPref(pref_names::kAllowedInstallSites); registry->RegisterStringPref(pref_names::kLastChromeVersion, std::string()); registry->RegisterDictionaryPref(kInstallSignature); registry->RegisterListPref(pref_names::kNativeMessagingBlacklist); registry->RegisterListPref(pref_names::kNativeMessagingWhitelist); registry->RegisterBooleanPref(pref_names::kNativeMessagingUserLevelHosts, true); registry->RegisterIntegerPref(kCorruptedDisableCount, 0); #if !defined(OS_MACOSX) registry->RegisterBooleanPref(pref_names::kAppFullscreenAllowed, true); #endif } template bool ExtensionPrefs::GetUserExtensionPrefIntoContainer( const char* pref, ExtensionIdContainer* id_container_out) const { DCHECK(id_container_out->empty()); const base::Value* user_pref_value = prefs_->GetUserPrefValue(pref); const base::ListValue* user_pref_as_list; if (!user_pref_value || !user_pref_value->GetAsList(&user_pref_as_list)) return false; std::insert_iterator insert_iterator( *id_container_out, id_container_out->end()); std::string extension_id; for (base::ListValue::const_iterator value_it = user_pref_as_list->begin(); value_it != user_pref_as_list->end(); ++value_it) { if (!(*value_it)->GetAsString(&extension_id)) { NOTREACHED(); continue; } insert_iterator = extension_id; } return true; } template void ExtensionPrefs::SetExtensionPrefFromContainer( const char* pref, const ExtensionIdContainer& strings) { ListPrefUpdate update(prefs_, pref); base::ListValue* list_of_values = update.Get(); list_of_values->Clear(); for (typename ExtensionIdContainer::const_iterator iter = strings.begin(); iter != strings.end(); ++iter) { list_of_values->AppendString(*iter); } } void ExtensionPrefs::PopulateExtensionInfoPrefs( const Extension* extension, const base::Time install_time, Extension::State initial_state, int install_flags, const std::string& install_parameter, base::DictionaryValue* extension_dict) const { extension_dict->Set(kPrefState, new base::FundamentalValue(initial_state)); extension_dict->Set(kPrefLocation, new base::FundamentalValue(extension->location())); extension_dict->Set(kPrefCreationFlags, new base::FundamentalValue(extension->creation_flags())); extension_dict->Set(kPrefFromWebStore, new base::FundamentalValue(extension->from_webstore())); extension_dict->Set(kPrefFromBookmark, new base::FundamentalValue(extension->from_bookmark())); extension_dict->Set( kPrefWasInstalledByDefault, new base::FundamentalValue(extension->was_installed_by_default())); extension_dict->Set( kPrefWasInstalledByOem, new base::FundamentalValue(extension->was_installed_by_oem())); extension_dict->Set(kPrefInstallTime, new base::StringValue( base::Int64ToString(install_time.ToInternalValue()))); if (install_flags & kInstallFlagIsBlacklistedForMalware) extension_dict->Set(kPrefBlacklist, new base::FundamentalValue(true)); base::FilePath::StringType path = MakePathRelative(install_directory_, extension->path()); extension_dict->Set(kPrefPath, new base::StringValue(path)); if (!install_parameter.empty()) { extension_dict->Set(kPrefInstallParam, new base::StringValue(install_parameter)); } // We store prefs about LOAD extensions, but don't cache their manifest // since it may change on disk. if (!Manifest::IsUnpackedLocation(extension->location())) { extension_dict->Set(kPrefManifest, extension->manifest()->value()->DeepCopy()); } // Only writes kPrefDoNotSync when it is not the default. if (install_flags & kInstallFlagDoNotSync) extension_dict->Set(kPrefDoNotSync, new base::FundamentalValue(true)); else extension_dict->Remove(kPrefDoNotSync, NULL); } void ExtensionPrefs::InitExtensionControlledPrefs( ExtensionPrefValueMap* value_map) { TRACE_EVENT0(""browser,startup"", ""ExtensionPrefs::InitExtensionControlledPrefs"") SCOPED_UMA_HISTOGRAM_TIMER(""Extensions.InitExtensionControlledPrefsTime""); ExtensionIdList extension_ids; GetExtensions(&extension_ids); for (ExtensionIdList::iterator extension_id = extension_ids.begin(); extension_id != extension_ids.end(); ++extension_id) { base::Time install_time = GetInstallTime(*extension_id); bool is_enabled = !IsExtensionDisabled(*extension_id); bool is_incognito_enabled = IsIncognitoEnabled(*extension_id); value_map->RegisterExtension( *extension_id, install_time, is_enabled, is_incognito_enabled); FOR_EACH_OBSERVER( ExtensionPrefsObserver, observer_list_, OnExtensionRegistered(*extension_id, install_time, is_enabled)); // Set regular extension controlled prefs. LoadExtensionControlledPrefs( this, value_map, *extension_id, kExtensionPrefsScopeRegular); // Set incognito extension controlled prefs. LoadExtensionControlledPrefs(this, value_map, *extension_id, kExtensionPrefsScopeIncognitoPersistent); // Set regular-only extension controlled prefs. LoadExtensionControlledPrefs( this, value_map, *extension_id, kExtensionPrefsScopeRegularOnly); FOR_EACH_OBSERVER(ExtensionPrefsObserver, observer_list_, OnExtensionPrefsLoaded(*extension_id, this)); } } void ExtensionPrefs::FinishExtensionInfoPrefs( const std::string& extension_id, const base::Time install_time, bool needs_sort_ordinal, const syncer::StringOrdinal& suggested_page_ordinal, base::DictionaryValue* extension_dict) { // Reinitializes various preferences with empty dictionaries. if (!extension_dict->HasKey(pref_names::kPrefPreferences)) { extension_dict->Set(pref_names::kPrefPreferences, new base::DictionaryValue); } if (!extension_dict->HasKey(pref_names::kPrefIncognitoPreferences)) { extension_dict->Set(pref_names::kPrefIncognitoPreferences, new base::DictionaryValue); } if (!extension_dict->HasKey(pref_names::kPrefRegularOnlyPreferences)) { extension_dict->Set(pref_names::kPrefRegularOnlyPreferences, new base::DictionaryValue); } if (!extension_dict->HasKey(pref_names::kPrefContentSettings)) extension_dict->Set(pref_names::kPrefContentSettings, new base::ListValue); if (!extension_dict->HasKey(pref_names::kPrefIncognitoContentSettings)) { extension_dict->Set(pref_names::kPrefIncognitoContentSettings, new base::ListValue); } // If this point has been reached, any pending installs should be considered // out of date. extension_dict->Remove(kDelayedInstallInfo, NULL); // Clear state that may be registered from a previous install. extension_dict->Remove(EventRouter::kRegisteredEvents, NULL); // FYI, all code below here races on sudden shutdown because |extension_dict|, // |app_sorting|, |extension_pref_value_map_|, and (potentially) observers // are updated non-transactionally. This is probably not fixable without // nested transactional updates to pref dictionaries. if (needs_sort_ordinal) app_sorting()->EnsureValidOrdinals(extension_id, suggested_page_ordinal); bool is_enabled = false; int initial_state; if (extension_dict->GetInteger(kPrefState, &initial_state)) { is_enabled = initial_state == Extension::ENABLED; } bool is_incognito_enabled = IsIncognitoEnabled(extension_id); extension_pref_value_map_->RegisterExtension( extension_id, install_time, is_enabled, is_incognito_enabled); FOR_EACH_OBSERVER( ExtensionPrefsObserver, observer_list_, OnExtensionRegistered(extension_id, install_time, is_enabled)); } } // namespace extensions ",16195,True,3348.05161803113,median "//// This guide is maintained in the main Quarkus repository and pull requests should be submitted there: https://github.com/quarkusio/quarkus/tree/main/docs/src/main/asciidoc //// = Building applications with Maven include::./attributes.adoc[] :devtools-no-gradle: [[project-creation]] == Creating a new project You can scaffold a new Maven project with: :create-app-group-id: my-groupId :create-app-artifact-id: my-artifactId :create-app-code: :create-app-post-command: include::includes/devtools/create-app.adoc[] If you are using the CLI, you can get the list of available options with: [source,bash] ---- quarkus create app --help ---- If you are using the Maven command, the following table lists the attributes you can pass to the `create` command: [cols=3*,options=""header""] |=== | Attribute | Default Value | Description | `projectGroupId` | `org.acme.sample` | The group id of the created project | `projectArtifactId` | _mandatory_ | The artifact id of the created project. Not passing it triggers the interactive mode. | `projectVersion` | `1.0.0-SNAPSHOT` | The version of the created project | `platformGroupId` | `io.quarkus.platform` | The group id of the target platform. | `platformArtifactId` | `quarkus-bom` | The artifact id of the target platform BOM. | `platformVersion` | The version currently recommended by the https://quarkus.io/guides/extension-registry-user[Quarkus Extension Registry] | The version of the platform you want the project to use. It can also accept a version range, in which case the latest from the specified range will be used. | `className` | _Not created if omitted_ | The fully qualified name of the generated resource | `path` | `/hello` | The resource path, only relevant if `className` is set. | `extensions` | _[]_ | The list of extensions to add to the project (comma-separated) | `quarkusRegistryClient` | `true` | Whether or not Quarkus should use the online registry to resolve extension catalogs. If this is set to false, the extension catalog will be narrowed to the defined (or default) platform BOM. |=== By default, the command will target the `io.quarkus.platform:quarkus-bom:{quarkus-version}` platform release (unless the coordinates of the desired platform release have been specified). The project is generated in a directory named after the passed artifactId. If the directory already exists, the generation fails. A pair of Dockerfiles for native and jvm mode are also generated in `src/main/docker`. Instructions to build the image and run the container are written in those Dockerfiles. == Dealing with extensions From inside a Quarkus project, you can obtain a list of the available extensions with: include::includes/devtools/extension-list.adoc[] You can add an extension using: :add-extension-extensions: hibernate-validator include::includes/devtools/extension-add.adoc[] Extensions are passed using a comma-separated list. The extension name is the GAV name of the extension: e.g. `io.quarkus:quarkus-agroal`. But you can pass a partial name and Quarkus will do its best to find the right extension. For example, `agroal`, `Agroal` or `agro` will expand to `io.quarkus:quarkus-agroal`. If no extension is found or if more than one extensions match, you will see a red check mark ❌ in the command result. [source,shell] ---- $ ./mvnw quarkus:add-extensions -Dextensions=jdbc,agroal,non-exist-ent [...] ❌ Multiple extensions matching 'jdbc' * io.quarkus:quarkus-jdbc-h2 * io.quarkus:quarkus-jdbc-mariadb * io.quarkus:quarkus-jdbc-postgresql Be more specific e.g using the exact name or the full gav. ✅ Adding extension io.quarkus:quarkus-agroal ❌ Cannot find a dependency matching 'non-exist-ent', maybe a typo? [...] ---- You can install all extensions which match a globbing pattern : :add-extension-extensions: smallrye-* include::includes/devtools/extension-add.adoc[] [[dev-mode]] == Development mode Quarkus comes with a built-in development mode. Run your application with: include::includes/devtools/dev.adoc[] You can then update the application sources, resources and configurations. The changes are automatically reflected in your running application. This is great to do development spanning UI and database as you see changes reflected immediately. Dev mode enables hot deployment with background compilation, which means that when you modify your Java files or your resource files and refresh your browser these changes will automatically take effect. This works too for resource files like the configuration property file. The act of refreshing the browser triggers a scan of the workspace, and if any changes are detected the Java files are compiled, and the application is redeployed, then your request is serviced by the redeployed application. If there are any issues with compilation or deployment an error page will let you know. Hit `CTRL+C` to stop the application. [NOTE] ==== By default, `quarkus:dev` sets the debug host to `localhost` (for security reasons). If you need to change this, for example to enable debugging on all hosts, you can use the `-DdebugHost` option like so: :dev-additional-parameters: -DdebugHost=0.0.0.0 include::includes/devtools/dev-parameters.adoc[] :!dev-additional-parameters: ==== === Remote Development Mode It is possible to use development mode remotely, so that you can run Quarkus in a container environment (such as OpenShift) and have changes made to your local files become immediately visible. This allows you to develop in the same environment you will actually run your app in, and with access to the same services. WARNING: Do not use this in production. This should only be used in a development environment. You should not run production application in dev mode. To do this you must build a mutable application, using the `mutable-jar` format. Set the following properties in `application.properties`: [source,properties] ---- quarkus.package.type=mutable-jar <1> quarkus.live-reload.password=changeit <2> quarkus.live-reload.url=http://my.cluster.host.com:8080 <3> ---- <1> This tells Quarkus to use the mutable-jar format. Mutable applications also include the deployment time parts of Quarkus, so they take up a bit more disk space. If run normally they start just as fast and use the same memory as an immutable application, however they can also be started in dev mode. <2> The password that is used to secure communication between the remote side and the local side. <3> The URL that your app is going to be running in dev mode at. This is only needed on the local side, so you may want to leave it out of the properties file and specify it as a system property on the command line. The `mutable-jar` is then built in the same way that a regular Quarkus jar is built, i.e. by issuing: include::includes/devtools/build.adoc[] Before you start Quarkus on the remote host set the environment variable `QUARKUS_LAUNCH_DEVMODE=true`. If you are on bare metal you can set it via the `export QUARKUS_LAUNCH_DEVMODE=true` command and then run the application with the proper `java -jar ...` command to run the application. If you plan on running the application via Docker, then you'll need to add `-e QUARKUS_LAUNCH_DEVMODE=true` to the `docker run` command. When the application starts you should now see the following line in the logs: `Profile dev activated. Live Coding activated`. NOTE: The remote side does not need to include Maven or any other development tools. The normal `fast-jar` Dockerfile that is generated with a new Quarkus application is all you need. If you are using bare metal launch the Quarkus runner jar, do not attempt to run normal devmode. Now you need to connect your local agent to the remote host, using the `remote-dev` command: [source,bash] ---- ./mvnw quarkus:remote-dev -Dquarkus.live-reload.url=http://my-remote-host:8080 ---- Now every time you refresh the browser you should see any changes you have made locally immediately visible in the remote app. This is done via a HTTP based long polling transport, that will synchronize your local workspace and the remote application via HTTP calls. If you do not want to use the HTTP feature then you can simply run the `remote-dev` command without specifying the URL. In this mode the command will continuously rebuild the local application, so you can use an external tool such as odo or rsync to sync to the remote application. All the config options are shown below: include::{generated-dir}/config/quarkus-live-reload-live-reload-config.adoc[opts=optional, leveloffset=+1] NOTE: It is recommended you use SSL when using remote dev mode, however even if you are using an unencrypted connection your password is never sent directly over the wire. For the initial connection request the password is hashed with the initial state data, and subsequent requests hash it with a random session id generated by the server and any body contents for POST requests, and the path for DELETE requests, as well as an incrementing counter to prevent replay attacks. === Configuring Development Mode By default, the Maven plugin picks up compiler flags to pass to `javac` from `maven-compiler-plugin`. If you need to customize the compiler flags used in development mode, add a `configuration` section to the `plugin` block and set the `compilerArgs` property just as you would when configuring `maven-compiler-plugin`. You can also set `source`, `target`, and `jvmArgs`. For example, to pass `--enable-preview` to both the JVM and `javac`: [source,xml] ---- ${quarkus.platform.group-id} quarkus-maven-plugin ${quarkus.platform.version} ${maven.compiler.source} ${maven.compiler.target} --enable-preview --enable-preview ... ---- == Debugging In development mode, Quarkus starts by default with debug mode enabled, listening to port `5005` without suspending the JVM. This behavior can be changed by giving the `debug` system property one of the following values: * `false` - the JVM will start with debug mode disabled * `true` - The JVM is started in debug mode and will be listening on port `5005` * `client` - the JVM will start in client mode and attempt to connect to `localhost:5005` * `{port}` - The JVM is started in debug mode and will be listening on `{port}` An additional system property `suspend` can be used to suspend the JVM, when launched in debug mode. `suspend` supports the following values: * `y` or `true` - The debug mode JVM launch is suspended * `n` or `false` - The debug mode JVM is started without suspending [TIP] ==== You can also run a Quarkus application in debug mode with a suspended JVM using: :dev-additional-parameters: -Dsuspend -Ddebug include::includes/devtools/dev-parameters.adoc[] :!dev-additional-parameters: Then, attach your debugger to `localhost:5005`. ==== == Import in your IDE Once you have a <>, you can import it in your favorite IDE. The only requirement is the ability to import a Maven project. **Eclipse** In Eclipse, click on: `File -> Import`. In the wizard, select: `Maven -> Existing Maven Project`. On the next screen, select the root location of the project. The next screen list the found modules; select the generated project and click on `Finish`. Done! In a separated terminal, run: include::includes/devtools/dev.adoc[] and enjoy a highly productive environment. **IntelliJ** In IntelliJ: 1. From inside IntelliJ select `File -> New -> Project From Existing Sources...` or, if you are on the welcome dialog, select `Import project`. 2. Select the project root 3. Select `Import project from external model` and `Maven` 4. Next a few times (review the different options if needed) 5. On the last screen click on Finish In a separated terminal or in the embedded terminal, run: include::includes/devtools/dev.adoc[] Enjoy! **Apache NetBeans** In NetBeans: 1. Select `File -> Open Project` 2. Select the project root 3. Click on `Open Project` In a separated terminal or the embedded terminal, go to the project root and run: include::includes/devtools/dev.adoc[] Enjoy! **Visual Studio Code** Open the project directory in VS Code. If you have installed the Java Extension Pack (grouping a set of Java extensions), the project is loaded as a Maven project. == Logging Quarkus application build classpath tree Usually, dependencies of an application (which is a Maven project) could be displayed using `mvn dependency:tree` command. In case of a Quarkus application, however, this command will list only the runtime dependencies of the application. Given that the Quarkus build process adds deployment dependencies of the extensions used in the application to the original application classpath, it could be useful to know which dependencies and which versions end up on the build classpath. Luckily, the `quarkus` Maven plugin includes the `dependency-tree` goal which displays the build dependency tree for the application. Executing `./mvnw quarkus:dependency-tree` on your project should result in an output similar to: [source,text,subs=attributes+] ---- [INFO] --- quarkus-maven-plugin:{quarkus-version}:dependency-tree (default-cli) @ getting-started --- [INFO] org.acme:getting-started:jar:1.0.0-SNAPSHOT [INFO] └─ io.quarkus:quarkus-resteasy-deployment:jar:{quarkus-version} (compile) [INFO] ├─ io.quarkus:quarkus-resteasy-server-common-deployment:jar:{quarkus-version} (compile) [INFO] │ ├─ io.quarkus:quarkus-core-deployment:jar:{quarkus-version} (compile) [INFO] │ │ ├─ commons-beanutils:commons-beanutils:jar:1.9.3 (compile) [INFO] │ │ │ ├─ commons-logging:commons-logging:jar:1.2 (compile) [INFO] │ │ │ └─ commons-collections:commons-collections:jar:3.2.2 (compile) ... ---- The goal accepts the following optional parameters: * `mode` - the default value is `prod`, i.e. the production build dependency tree. Alternatively, it accepts values `test` to display the test dependency tree and `dev` to display the dev mode dependency tree; * `outputFile` - specifies the file to persist the dependency tree to; * `appendOutput` - the default value is `false`, indicates whether the output to the command should be appended to the file specified with the `outputFile` parameter or it should be overriden. == Downloading Maven artifact dependencies for offline development and testing Quarkus extension dependencies are divided into the runtime extension dependencies that end up on the application runtime classpath and the deployment (or build time) extension dependencies that are resolved by Quarkus only at application build time to create the build classpath. Application developers are expected to express dependencies only on the runtime artifacts of Quarkus extensions. As a consequence, the deployment extension dependencies aren't visible to Maven plugins that aren't aware of the Quarkus extension dependency model, such as the `maven-dependency-plugin`, `go-offline-maven-plugin`, etc. That means those plugins can not be used to pre-download all the application dependencies to be able to build and test the application later in offline mode. To enable the use-case of building and testing a Quarkus application offline, the `quarkus-maven-plugin` includes the `go-offline` goal that could be called from the command line like this: [source,bash] ---- ./mvnw quarkus:go-offline ---- This goal will resolve all the runtime, build time, test and dev mode dependencies of the application downloading them to the configured local Maven repository. == Building a native executable Native executables make Quarkus applications ideal for containers and serverless workloads. Make sure to have `GRAALVM_HOME` configured and pointing to GraalVM version {graalvm-version} (Make sure to use a Java 11 version of GraalVM). Verify that your `pom.xml` has the proper `native` profile (see <>). Create a native executable using: include::includes/devtools/build-native.adoc[] A native executable will be present in `target/`. To run Integration Tests on the native executable, make sure to have the proper Maven plugin configured (see <>) and launch the `verify` goal. [source,shell] ---- $ ./mvnw verify -Pnative ... [quarkus-quickstart-runner:50955] universe: 391.96 ms [quarkus-quickstart-runner:50955] (parse): 904.37 ms [quarkus-quickstart-runner:50955] (inline): 1,143.32 ms [quarkus-quickstart-runner:50955] (compile): 6,228.44 ms [quarkus-quickstart-runner:50955] compile: 9,130.58 ms [quarkus-quickstart-runner:50955] image: 2,101.42 ms [quarkus-quickstart-runner:50955] write: 803.18 ms [quarkus-quickstart-runner:50955] [total]: 33,520.15 ms [INFO] [INFO] --- maven-failsafe-plugin:2.22.0:integration-test (default) @ quarkus-quickstart-native --- [INFO] [INFO] ------------------------------------------------------- [INFO] T E S T S [INFO] ------------------------------------------------------- [INFO] Running org.acme.quickstart.GreetingResourceIT Executing [/Users/starksm/Dev/JBoss/Quarkus/starksm64-quarkus-quickstarts/getting-started-native/target/quarkus-quickstart-runner, -Dquarkus.http.port=8081, -Dtest.url=http://localhost:8081, -Dquarkus.log.file.path=target/quarkus.log] 2019-02-28 16:52:42,020 INFO [io.quarkus] (main) Quarkus started in 0.007s. Listening on: http://localhost:8080 2019-02-28 16:52:42,021 INFO [io.quarkus] (main) Installed features: [cdi, resteasy] [INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.081 s - in org.acme.quickstart.GreetingResourceIT [INFO] [INFO] Results: [INFO] [INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0 ... ---- === Build a container friendly executable The native executable will be specific to your operating system. To create an executable that will run in a container, use the following: :build-additional-parameters: -Dquarkus.native.container-build=true include::includes/devtools/build-native.adoc[] :!build-additional-parameters: The produced executable will be a 64 bit Linux executable, so depending on your operating system it may no longer be runnable. However, it's not an issue as we are going to copy it to a Docker container. Note that in this case the build itself runs in a Docker container too, so you don't need to have GraalVM installed locally. [TIP] ==== By default, the native executable will be generated using the `quay.io/quarkus/ubi-quarkus-native-image:{graalvm-flavor}` Docker image. If you want to build a native executable with a different Docker image (for instance to use a different GraalVM version), use the `-Dquarkus.native.builder-image=` build argument. The list of the available Docker images can be found on https://quay.io/repository/quarkus/ubi-quarkus-native-image?tab=tags[quay.io]. Be aware that a given Quarkus version might not be compatible with all the images available. ==== You can follow the xref:building-native-image.adoc[Build a native executable guide] as well as xref:deploying-to-kubernetes.adoc[Deploying Application to Kubernetes and OpenShift] for more information. [[build-tool-maven]] == Maven configuration If you have not used <>, add the following elements in your `pom.xml` [source,xml,subs=attributes+] ---- <1> ${quarkus.platform.group-id} quarkus-bom ${quarkus.platform.version} pom import <2> ${quarkus.platform.group-id} quarkus-maven-plugin ${quarkus.platform.version} true <3> build generate-code generate-code-tests <4> org.apache.maven.plugins maven-surefire-plugin ${surefire-plugin.version} org.jboss.logmanager.LogManager ${maven.home} <5> native <6> native <7> org.apache.maven.plugins maven-failsafe-plugin ${surefire-plugin.version} integration-test verify ${project.build.directory}/${project.build.finalName}-runner org.jboss.logmanager.LogManager ${maven.home} ---- <1> Optionally use a BOM file to omit the version of the different Quarkus dependencies. <2> Use the Quarkus Maven plugin that will hook into the build process. <3> Enabling Maven plugin extensions will register a Quarkus `MavenLifecycleParticipant` which will make sure the Quarkus classloaders used during the build are properly closed. During the `generate-code` and `generate-code-tests` goals the Quarkus application bootstrap is initialized and re-used in the `build` goal (which actually builds and packages a production application). The Quarkus classloaders will be properly closed in the `build` goal of the `quarkus-maven-plugin`. However, if the build fails in between the `generate-code` or `generate-code-tests` and `build` then the Quarkus augmentation classloader won't be properly closed, which may lead to locking of JAR files that happened to be on the classpath on Windows OS. <4> Add system properties to `maven-surefire-plugin`. + `maven.home` is only required if you have custom configuration in `${maven.home}/conf/settings.xml`. <5> Use a specific `native` profile for native executable building. <6> Enable the `native` package type. The build will therefore produce a native executable. <7> If you want to test your native executable with Integration Tests, add the following plugin configuration. Test names `*IT` and annotated `@NativeImageTest` or `@QuarkusIntegrationTest` will be run against the native executable. See the xref:building-native-image.adoc[Native executable guide] for more info. [[fast-jar]] === Using fast-jar `fast-jar` is the default quarkus package type. The result of the build is a directory under `target` named `quarkus-app`. You can run the application using: `java -jar target/quarkus-app/quarkus-run.jar`. WARNING: In order to successfully run the produced jar, you need to have the entire contents of the `quarkus-app` directory. If any of the files are missing, the application will not start or might not function correctly. TIP: The `fast-jar` packaging results in creating an artifact that starts a little faster and consumes slightly less memory than a legacy Quarkus jar because it has indexed information about which dependency jar contains classes and resources. It can thus avoid the lookup into potentially every jar on the classpath that the legacy jar necessitates, when loading a class or resource. [[uber-jar-maven]] === Uber-Jar Creation Quarkus Maven plugin supports the generation of Uber-Jars by specifying a `quarkus.package.type=uber-jar` configuration option in your `application.properties` (or `uber-jar` in your `pom.xml`). The original jar will still be present in the `target` directory but it will be renamed to contain the `.original` suffix. When building an Uber-Jar you can specify entries that you want to exclude from the generated jar by using the `quarkus.package.ignored-entries` configuration option, this takes a comma separated list of entries to ignore. Uber-Jar creation by default excludes link:https://docs.oracle.com/javase/tutorial/deployment/jar/intro.html[signature files] that might be present in the dependencies of the application. Uber-Jar's final name is configurable via a Maven's build settings `finalName` option. [[multi-module-maven]] === Working with multi-module projects By default, Quarkus will not discover CDI beans inside another module. The best way to enable CDI bean discovery for a module in a multi-module project would be to include the `jandex-maven-plugin`, unless it is the main application module already configured with the quarkus-maven-plugin, in which case it will indexed automatically. [source,xml,subs=""attributes+""] ---- org.jboss.jandex jandex-maven-plugin {jandex-maven-plugin-version} make-index jandex ---- More information on this topic can be found on the xref:cdi-reference.adoc#bean_discovery[Bean Discovery] section of the CDI guide. [[maven-configuration-profile]] === Building with a specific configuration profile Quarkus supports xref:config-reference.adoc#profiles[configuration profiles] in order to provide a specific configuration according to the target environment. The profile can be provided directly in the Maven build's command thanks to the system property `quarkus.profile` with a command of type: // TODO switch to once escaping issue is fixed in Asciidoctor :build-additional-parameters: -Dquarkus.profile=profile-name-here include::includes/devtools/build.adoc[] :!build-additional-parameters: However it is also possible to specify the profile directly in the POM file of the project using project properties, the Quarkus Maven plugin configuration properties or system properties set in the Quarkus Maven plugin configuration. In order of precedence (greater precedence first): .1. System properties set in the Quarkus Maven plugin configuration [source,xml] ---- ... ... ${quarkus.platform.group-id} quarkus-maven-plugin ${quarkus.platform.version} true prod-aws <1> ... ... ---- <1> The default configuration profile of this project is `prod-aws`. .2. Quarkus Maven plugin configuration properties [source,xml] ---- ... ... ${quarkus.platform.group-id} quarkus-maven-plugin ${quarkus.platform.version} true prod-aws <1> ... ... ---- <1> The default configuration profile of this project is `prod-aws`. .3. Project properties [source,xml] ---- ... prod-aws <1> ... ... ---- <1> The default configuration profile of this project is `prod-aws`. NOTE: Whatever the approach is chosen, the profile can still be overridden with the `quarkus.profile` system property or the `QUARKUS_PROFILE` environment variable. [[maven-multi-build]] === Building several artifacts from a single module In some particular use cases, it can be interesting to build several artifacts of your application from the same module. A typical example is when you want to build your application with different configuration profiles. In that case, it is possible to add as many executions as needed to the Quarkus Maven plugin configuration. Below is an example of a Quarkus Maven plugin configuration that will produce two builds of the same application: one using the `prod-oracle` profile and the other one using the `prod-postgresql` profile. [source,xml] ---- ... ... ${quarkus.platform.group-id} quarkus-maven-plugin ${quarkus.platform.version} true oracle build prod-oracle <1> oracle-quarkus-app <2> postgresql build prod-postgresql <3> postgresql-quarkus-app <4> ... ... ---- <1> The default configuration profile of the first execution of the plugin is `prod-oracle`. <2> The output directory of the first execution of the plugin is set to `oracle-quarkus-app` instead of `quarkus-app` to have a dedicated directory. <3> The default configuration profile of the second execution of the plugin is `prod-postgresql`. <4> The output directory of the second execution of the plugin is set to `postgresql-quarkus-app` instead of `quarkus-app` to have a dedicated directory. NOTE: With the configuration above, both profile builds will be using the same dependencies, so if we added dependencies on the Oracle and PostgreSQL drivers to the application, both of the drivers will appear in both builds. To isolate profile-specific dependencies from other profiles, the JDBC drivers could be added as optional dependencies to the application but configured to be included in each profile that requires them, e.g.: [source,xml] ---- ... ... org.postgresql postgresql ${postgresql.driver.version} true <1> ... ${quarkus.platform.group-id} quarkus-maven-plugin ${quarkus.platform.version} true ... postgresql build prod-postgresql postgresql-quarkus-app true <2> org.postgresql:postgresql::jar <3> ... ... ---- <1> The JDBC driver of PostgreSQL is defined as an optional dependency <2> For backward compatibility reasons, it is necessary to explicitly indicate that the optional dependencies need to be filtered. <3> Only the optional dependency corresponding to the JDBC driver of PostgreSQL is expected in the final artifact. [[configuration-reference]] == Configuring the Project Output There are a several configuration options that will define what the output of your project build will be. These are provided in `application.properties` the same as any other config property. The properties are shown below: include::{generated-dir}/config/quarkus-package-pkg-package-config.adoc[opts=optional] [[custom-test-configuration-profile]] === Custom test configuration profile in JVM mode By default, Quarkus tests in JVM mode are run using the `test` configuration profile. If you are not familiar with Quarkus configuration profiles, everything you need to know is explained in the xref:config.adoc#configuration-profiles[Configuration Profiles Documentation]. It is however possible to use a custom configuration profile for your tests with the Maven Surefire and Maven Failsafe configurations shown below. This can be useful if you need for example to run some tests using a specific database which is not your default testing database. [source,xml,subs=attributes+] ---- [...] org.apache.maven.plugins maven-surefire-plugin ${surefire-plugin.version} foo <1> ${project.build.directory} [...] org.apache.maven.plugins maven-failsafe-plugin ${failsafe-plugin.version} foo <1> ${project.build.directory} [...] [...] ---- <1> The `foo` configuration profile will be used to run the tests. [WARNING] ==== It is not possible to use a custom test configuration profile in native mode for now. Native tests are always run using the `prod` profile. ==== [[bootstrap-maven-properties]] === Bootstrap Maven properties Quarkus bootstrap includes a Maven resolver implementation that is used to resolve application runtime and build time dependencies. The Quarkus Maven resolver is initialized from the same Maven command line that launched the build, test or dev mode. Typically, there is no need to add any extra configuration for it. However, there could be cases where an extra configuration option may be necessary to properly resolve application dependencies in test or dev modes, or IDEs. Maven test plugins (such as `surefire` and `failsafe`), for example, are not propagating build system properties to the running tests by default. Which means some of the system properties set by the Maven CLI aren't available for the Quarkus Maven resolver initialized for the tests, which may result in test dependencies being resolved using different settings than the main Maven build. Here is a list of system properties the Quarkus bootstrap Maven resolver checks during its initialization. [cols=3*,options=""header""] |=== | Property name | Default Value | Description | `maven.home` | `MAVEN_HOME` envvar | The Maven home dir is used to resolve the global settings file unless it was explicitly provided on the command line with the `-gs` argument | `maven.settings` | `~/m2/settings.xml` | Unless the custom settings file has been provided with the `-s` argument, this property can be used to point the resolver to a custom Maven settings file | `maven.repo.local` | `~/m2/repository` | This property could be used to configure a custom local Maven repository directory, if it is different from the default one and the one specified in the `settings.xml` | `maven.top-level-basedir` | none | This property may be useful to help the Maven resolver identify the top-level Maven project in the workspace. By default, the Maven resolver will be discovering a project's workspace by navigating the parent-module POM relationship. However there could be project layouts that are using an aggregator module which isn't appearing as the parent for its modules. In this case, this property will help the Quarkus Maven resolver to properly discover the workspace. | `quarkus.bootstrap.effective-model-builder` | `false` | By default, the Quarkus Maven resolver is reading project's POMs directly when discovering the project's layout. While in most cases it works well enough and relatively fast, reading raw POMs has its limitation. E.g. if a POM includes modules in a profile, these modules will not be discovered. This system property enables project's layout discovery based on the effective POM models, that are properly interpolated, instead of the raw ones. The reason this option is not enabled by default is it may appear to be significantly more time consuming that could increase, e.g. CI testing times. Until there is a better approach found that could be used by default, projects that require it should enable this option. |=== These system properties above could be added to, e.g., a `surefire` and/or `failsafe` plugin configuration as [source,xml,subs=attributes+] ---- [...] org.apache.maven.plugins maven-surefire-plugin ${surefire-plugin.version} ${maven.hom} <1> ${settings.localRepository} <2> ${session.request.userSettingsFile.path} <3> ${session.topLevelProject.basedir.absolutePath} <4> true <5> [...] ---- <1> Propagate `maven.home` system property set by the Maven CLI to the tests <2> Set the Maven local repository directory for the tests <3> Set the Maven settings file the tests <4> Point to the top-level project directory for the tests <5> Enable effective POM-based project layout discovery ==== Top-level vs Multi-module project directory In Maven there appears to be a notion of the top-level project (that is exposed as a project property `${session.topLevelProject.basedir.absolutePath}`) and the multi-module project directory (that is available as property `${maven.multiModuleProjectDirectory}`). These directories might not always match! IMPORTANT: `maven.multiModuleProjectDirectory` is meant to be consulted by the Maven code itself and not something to be relied upon by user code. So, if you find it useful, use it at your own risk! The `${maven.multiModuleProjectDirectory}` will be resolved to the first directory that contains `.mvn` directory as its child going up the workspace file system tree starting from the current directory (or the one specified with the `-f` argument) from which the `mvn` command was launched. If the `.mvn` directory was not found, however, the `${maven.multiModuleProjectDirectory}` will be pointing to the directory from which the `mvn` command was launched (or the one targeted with the `-f` argument). The `${session.topLevelProject.basedir.absolutePath}` will be pointing either to the directory from which the `mvn` command was launched or to the directory targeted with the `-f` argument, if it was specified. [[project-info]] == Quarkus project info The Quarkus Maven plugin includes a goal called `info` (currently marked as 'experimental') that logs Quarkus-specific information about the project, such as: the imported Quarkus platform BOMs and the Quarkus extensions found among the project dependencies. In a multi-module project `quarkus:info` will assume that the current module, in which it is executed, is the main module of the application. NOTE: The report generated by `quarkus:info` is not currently including the Quarkus Maven plugin information, however it's planned to be added in the future releases. Here is an example `info` output for a simple project: [source,text,subs=attributes+] ---- [aloubyansky@localhost code-with-quarkus]$ mvn quarkus:info [INFO] Scanning for projects... [INFO] [INFO] ---------------------< org.acme:code-with-quarkus >--------------------- [INFO] Building code-with-quarkus 1.0.0-SNAPSHOT [INFO] --------------------------------[ jar ]--------------------------------- [INFO] [INFO] --- quarkus-maven-plugin:{quarkus-version}:info (default-cli) @ code-with-quarkus --- [WARNING] quarkus:info goal is experimental, its options and output may change in future versions [INFO] Quarkus platform BOMs: <1> [INFO] io.quarkus.platform:quarkus-bom:pom:{quarkus-version} [INFO] io.quarkus.platform:quarkus-kogito-bom:pom:{quarkus-version} [INFO] io.quarkus.platform:quarkus-camel-bom:pom:{quarkus-version} [INFO] [INFO] Extensions from io.quarkus.platform:quarkus-bom: <2> [INFO] io.quarkus:quarkus-resteasy-reactive [INFO] [INFO] Extensions from io.quarkus.platform:quarkus-kogito-bom: <3> [INFO] org.kie.kogito:kogito-quarkus-decisions [INFO] [INFO] Extensions from io.quarkus.platform:quarkus-camel-bom: <4> [INFO] org.apache.camel.quarkus:camel-quarkus-rabbitmq [INFO] [INFO] Extensions from registry.quarkus.io: <5> [INFO] io.quarkiverse.prettytime:quarkus-prettytime:0.2.1 ---- <1> Quarkus platform BOMs imported in the project (BOMs imported by parent POMs will also be reported) <2> Direct Quarkus extension dependencies managed by the `quarkus-bom` <3> Direct Quarkus extension dependencies managed by the `quarkus-kogito-bom` <4> Direct Quarkus extension dependencies managed by the `quarkus-camel-bom` <5> Direct Quarkus extensions dependencies that aren't managed by Quarkus BOMs but found in the Quarkus extension registry NOTE: `quarkus:info` will also report Quarkus extensions that aren't found in the Quarkus extension registries if those are present among the project dependencies, indicating they have an 'unknown origin'. [[project-info-misaligned]] === Highlighing misaligned versions `quarkus:info` will also highlight basic Quarkus dependency version misalignments, in case they are detected. For example, if we modify the project mentioned above by removing the `kogito-quarkus-decisions` extension from the dependencies and adding a `2.6.3.Final` `` element to the `quarkus-resteasy-reactive` dependency that is managed by the `quarkus-bom` and then run `quarkus:info` again, we'll see something like: [source,text,subs=attributes+] ---- [INFO] --- quarkus-maven-plugin:{quarkus-version}:info (default-cli) @ code-with-quarkus --- [WARNING] quarkus:info goal is experimental, its options and output may change in future versions [INFO] Quarkus platform BOMs: [INFO] io.quarkus.platform:quarkus-bom:pom:{quarkus-version} [INFO] io.quarkus.platform:quarkus-kogito-bom:pom:{quarkus-version} | unnecessary <1> [INFO] io.quarkus.platform:quarkus-camel-bom:pom:{quarkus-version} [INFO] [INFO] Extensions from io.quarkus.platform:quarkus-bom: [INFO] io.quarkus:quarkus-resteasy-reactive:2.6.3.Final | misaligned <2> [INFO] [INFO] Extensions from io.quarkus.platform:quarkus-camel-bom: [INFO] org.apache.camel.quarkus:camel-quarkus-rabbitmq [INFO] [INFO] Extensions from registry.quarkus.io: [INFO] io.quarkiverse.prettytime:quarkus-prettytime:0.2.1 [INFO] [WARNING] Non-recommended Quarkus platform BOM and/or extension versions were found. For more details, please, execute 'mvn quarkus:update -Drectify' ---- <1> The `quarkus-kogito-bom` import is now reported as 'unnecessary' since none of the Quarkus extensions it includes are found among the project dependencies <2> The version `2.6.3.Final` of the `quarkus-resteasy-reactive` is now reported as being misaligned with the version managed by the Quarkus platform BOM imported in the project, which is {quarkus-version} [[project-update]] == Quarkus project update The `quarkus:update` goal (currently marked as 'experimental') provided by the Quarkus Maven plugin can be used to check whether there are Quarkus-related updates available for a project, such as: new releases of the relevant Quarkus platform BOMs and non-platform Quarkus extensions present in the project. In a multi-module project the `update` goal is meant to be executed from the main Quarkus application module. IMPORTANT: At this point, the `quarkus:update` goal does not actually apply the recommended updates but simply reports what they are and how to apply them manually. NOTE: The Quarkus Maven plugin version isn't currently included in the update report, however it's planned to be added in the future releases. The way `quarkus:update` works, first, all the direct Quarkus extension dependencies of the project are collected (those that are managed by the Quarkus platform BOMs and those that aren't but found in the Quarkus extension registries). Then the configured Quarkus extension registries (typically the `registry.quarkus.io`) will be queried for the latest recommended/supported Quarkus platform versions and non-platform Quarkus extensions compatible with them. The algorithm will then select the latest compatible combination of all the extensions found in the project, assuming such a combination actually exists. Otherwise, no updates will be suggested. Assuming we have a project including Kogito, Camel and core Quarkus extensions available in the Quarkus platform based on Quarkus `2.7.1.Final`, the output of the `quarkus:update` would look like: [source,text,subs=attributes+] ---- [aloubyansky@localhost code-with-quarkus]$ mvn quarkus:update [INFO] Scanning for projects... [INFO] [INFO] ---------------------< org.acme:code-with-quarkus >--------------------- [INFO] Building code-with-quarkus 1.0.0-SNAPSHOT [INFO] --------------------------------[ jar ]--------------------------------- [INFO] [INFO] --- quarkus-maven-plugin:{quarkus-version}:update (default-cli) @ code-with-quarkus --- [WARNING] quarkus:update goal is experimental, its options and output might change in future versions [INFO] [INFO] Recommended Quarkus platform BOM updates: <1> [INFO] Update: io.quarkus.platform:quarkus-bom:pom:2.7.1.Final -> {quarkus-version} [INFO] Update: io.quarkus.platform:quarkus-kogito-bom:pom:2.7.1.Final -> {quarkus-version} [INFO] Update: io.quarkus.platform:quarkus-camel-bom:pom:2.7.1.Final -> {quarkus-version} ---- <1> A list of currently recommended Quarkus platform BOM updates NOTE: Typically, a single project property will be used to manage all the Quarkus platform BOMs but the implementation isn't currently smart enough to point that out and will report updates for each BOM individually. If we modify the project to remove all the Kogito extensions from the project, change the version of the `quarkus-resteasy-reactive` extension to `2.6.3.Final` and downgrade `quarkus-prettytime` which is not included in the Quarkus platform BOMs to `0.2.0`, `quarkus:update` will report something like: [source,text,subs=attributes+] ---- [INFO] Recommended Quarkus platform BOM updates: <1> [INFO] Update: io.quarkus.platform:quarkus-bom:pom:2.7.1.Final -> {quarkus-version} [INFO] Update: io.quarkus.platform:quarkus-camel-bom:pom:2.7.1.Final -> {quarkus-version} [INFO] Remove: io.quarkus.platform:quarkus-kogito-bom:pom:2.7.1.Final <2> [INFO] [INFO] Extensions from io.quarkus.platform:quarkus-bom: [INFO] Update: io.quarkus:quarkus-resteasy-reactive:2.6.3.Final -> remove version (managed) <3> [INFO] [INFO] Extensions from registry.quarkus.io: [INFO] Update: io.quarkiverse.prettytime:quarkus-prettytime:0.2.0 -> 0.2.1 <4> ---- <1> A list of the currently recommended Quarkus platform BOM updates for the project <2> Given that the project does not include any Kogito extensions, the BOM import is recommended to be removed <3> An outdated version of the `quarkus-resteasy-reactive` is recommended to be removed in favor of the one managed by the `quarkus-bom` <4> The latest compatible version of the `quarkus-prettytime` extension === Quarkus project rectify As was mentioned above, `quarkus:info`, besides reporting Quarkus platform and extension versions, performs a quick version alignment check, to make sure the extension versions used in the project are compatible with the imported Quarkus platform BOMs. If misalignments are detected, the following warning message will be logged: [source,text,subs=attributes+] ---- [WARNING] Non-recommended Quarkus platform BOM and/or extension versions were found. For more details, please, execute 'mvn quarkus:update -Drectify' ---- When the `rectify` option is enabled, `quarkus:update`, instead of suggesting the latest recommended Quarkus version updates, will log update instructions to simply align the extension dependency versions found in the project with the currently imported Quarkus platform BOMs. ",12486,False,2210.4379176854172,median "= Volant - Developer Guide :site-section: DeveloperGuide :toc: :toc-title: Table of Contents :toc-placement: preamble :sectnums: :imagesDir: images :stylesDir: stylesheets :xrefstyle: full ifdef::env-github[] :tip-caption: :bulb: :note-caption: :information_source: :warning-caption: :warning: endif::[] :repoURL: https://github.com/AY1920S2-CS2103T-F09-4/main By: `AY1920S2-CS2103T-F09-4`      Since: `Jan 2020`      Licence: `MIT` == Introduction This document is a Developer Guide written for developers who wish to contribute to or extend our project. It is technical, and explains the inner workings of Volant and how the different components of our application work together. ==== *Reading this Developer Guide* * *Important Notations* + [TIP] This icon denotes useful tips to note of during development. [NOTE] This icon denotes important details to take note of during development. * *Understanding Diagrams* + The diagrams in this Developer Guide are colour coded according to the different components. + image::dg-diagram-legend.png[] ==== == Setting up Refer to the guide <>. == Design [[Design-Architecture]] === Architecture .Architecture Diagram image::ArchitectureDiagram.png[align=""center""] The *_Architecture Diagram_* given above explains the high-level design of the App. Given below is a quick overview of each component. `Main` has two classes called link:{repoURL}/src/main/java/seedu/location/Main.java[`Main`] and link:{repoURL}/src/main/java/seedu/location/MainApp.java[`MainApp`]. It is responsible for, * At app launch: Initializes the components in the correct sequence, and connects them up with each other. * At shut down: Shuts down the components and invokes cleanup method where necessary. * <> represents a collection of classes used by multiple other components. The following class plays an important role at the architecture level: * `LogsCenter` is used by many classes to write log messages to the App's log file, `volant.log`. The rest of the App consists of four main components. * <>: The UI of the App. * <>: The command executor depending on the view the user is on. * <>: Holds the data of the App in-memory depending in the view the user is on. * <>: Reads data from, and writes data to, the hard disk. Each of the four components * Defines its _API_ in an `interface` with the same name as the Component. * Exposes its functionality using a `{Component Name} Manager` class. For example, the `Logic` component (see the class diagram given below) defines its API in the `Logic.java` interface and exposes its functionality using the `LogicManager.java` class. ==== Views in Volant There are 4 types of pages/views in this App: `HOME`, `TRIP`, `ITINERARY`, `JOURNAL`. Each view has their own `{Component Name} Manager` classes for both `Logic` and `Model`. These individual `{Component Name} Manager` classes for `Logic` and `Model` provide a context for commands to be executed in, e.g. when the user is on the `HOME` page, the `add` command modifies the trip list, when the user is on the `ITINERARY` page, the `add` command modifies the itinerary. For example, the `JOURNAL` view has its own `JournalLogicManager` and `JournalModelManager` to provide the context for command execution on the `JOURNAL` page. .Class Diagram of the Journal Logic Component image::JournalLogic.png[align=""center""] [discrete] ==== How the architecture components interact with each other The _Sequence Diagram_ below shows how the components interact with each other for the scenario where the user issues the command `back` when in a `TRIP` view. View switching is executed by the `Ui` component. [[view-switch-sequence]] .Component interactions for `home` command in the `JOURNAL` page. image::home-command-sequence.png[align=""center""] The _Sequence Diagram_ below illustrates how the components interact with each other for the scenario where the user issues the command `goto 1` when in a `HOME` page view. View switching is executed by the `Ui` component. .Component interactions for `goto 1` command in the `HOME` page view. image::gotoCommandSequenceDiagram.png[align=""center""] The sections below give more details about each component. [[Design-Ui]] === UI component .Structure of the UI Component when a user is on a `TRIP` page image::UIClassDiagram.png[align=""center""] *API* : link:{repoURL}/src/main/java/seedu/location/ui/Ui.java[`Ui.java`] The UI consists of a `MainWindow` that is made up of parts e.g.`CommandBox`, `ResultDisplay`, `StatusBarFooter`, `mainPanel` etc. All these, including the `MainWindow`, inherit from the abstract `UiPart` class. The `UI` component uses JavaFx UI framework. The layout of these UI parts are defined in matching `.fxml` files that are in the `src/main/resources/view` folder. For example, the layout of the link:{repoURL}/src/main/java/seedu/location/ui/MainWindow.java[`MainWindow`] is specified in link:{repoURL}/src/main/resources/view/MainWindow.fxml[`MainWindow.fxml`] The `UI` component, * Executes user commands using the `Logic` component. * Listens for changes to `Model` data so that the UI can be updated with the modified data. ==== View Switching As there are four different views in Volant. Upon startup of the App, the `mainPanel` is set to `HomePage`. There are certain commands will cause the `MainWindow` display to switch views. For example, `goto`, `back` and `home` navigation commands. When a view is switched, `MainWindow` will do the following: ==== For example, if a user is switching from a `TRIP` view to the `HOME` view through the command, `back`. . Reassign the `Logic` component from `TripPageLogicManager` to a new `HomePageLogicManager`. . Reassign the `Model` component from `TripPageModelManager` to a new `HomePageModelManager`. . Reassign the value of `StackPane` `mainPanel` from `TripPage` to `HomePage`. <> ==== _More details on the implementation of view switching can be found in <>._ [[Design-Logic]] === Logic component [[fig-LogicClassDiagram1]] .Structure of the Logic Component image::JournalLogic.png[align=""center""] *API* : link:https://github.com/AY1920S2-CS2103T-F09-4/main/blob/master/src/main/java/seedu/volant/commons/logic/Logic.java[`Logic.java`] . `Logic` uses the `JournalInputParser` class of the current feature to parse the user command. . This results in a `Command` object which is executed by the `JournalLogicManager` of the current feature. . The command execution can affect the `Model` of the current feature (e.g. adding a trip). . The result of the command execution is encapsulated as a `CommandResult` object which is passed back to the `Ui`. . In addition, the `CommandResult` object can also instruct the `Ui` to perform certain actions, such as displaying help to the user. Given below is the Sequence Diagram for interactions within the `Logic` component of the Itinerary feature for the `execute(""delete 1"")` API call. .Interactions Inside the Logic Component for the `delete 1` Command image::DeleteItinerary.png[align=""center""] [[Design-Model]] === Model component .Class Diagram for the Model component on the `HOME` page image::HomeClassDiagram.png[align=""center""] .Structure of the Model Component in Journal image::JournalModelDiagram.png[align=""center""] *API* : link:{repoURL}/src/main/java/seedu/location/model/Model.java[`Model.java`] The `Model` for `JOURNAL`, * stores a `UserPref` object that represents the user's preferences. * stores an `Entry` 's data. * exposes an unmodifiable `ObservableList` that can be 'observed' e.g. the UI can be bound to this list so that the UI automatically updates when the data in the list change. * does not depend on any of the other three components. .Structure of the Model Component in Itinerary image::ItineraryModelDiagram.png[align=""center""] The `Model` for `ITINERARY`, *API* : link:https://github.com/AY1920S2-CS2103T-F09-4/main/blob/master/src/main/java/seedu/volant/commons/model/Model.java[`Model.java`] * stores a `UserPref` object that represents the user's preferences. * stores an `Activity` 's data. * exposes an unmodifiable `ObservableList` that can be 'observed' e.g. the UI can be bound to this list so that the UI automatically updates when the data in the list change. * does not depend on any of the other three components. [[Design-Storage]] === Storage component .Structure of the Storage Component image::StorageClassDiagram.png[align=""center""] *API* : link:https://github.com/AY1920S2-CS2103T-F09-4/main/blob/master/src/main/java/seedu/volant/commons/storage/Storage.java[`Storage.java`] The `Storage` component, * can save `UserPref` objects in json format and read it back. * can save the `LMNList` data in json format and read it back. [[Design-Commons]] === Common classes Classes used by multiple components are in the `seedu.volant.commons` package. == Implementation This section describes some noteworthy details on how certain features are implemented. [[implementation-view-switching]] === View Switching for Navigation Commands The entire process of view switching is executed in the `MainWindow.java` class. [TIP] ==== *List of Navigation Commands* * `goto` on the `HOME` page * `goto` on the `TRIP` page * `back` * `home` ==== ==== Implementation Each `CommandResult` from an execution in the `MainWindow` class stores data on *if a command is a navigation command or not, and which navigation command it is.* If the command is a navigation command, the `MainWindow` will execute the appropriate functions to facilitate view switching. In the view switching process, the `MainWindow` will do the following: + . Switch the logic component of the program to the logic component of the next page . Switch the model component of the program to the model component of the next page . Switch the current storage of the program to the storage component of the next page . Load the GUI components for the next page For example, for the `back` command, the `MainWindow`: .Activity diagram for view switching process in `MainWindow` for `back` command image::back-activity-diagram.png[] ==== Design Considerations Pros: + * As each page has its own components, the back end of the program is neater and better abstracted. * Specialised logic components for each page allow for the same keywords to be used (e.g `add`, `delete`) on certain pages. Cons: + * There are many steps to switching views * If there are more pages, there will be many logic and model components to keep track of. ==== Special Cases * When `back` command is used in the <>, this would not have any effect on the current GUI being displayed. * When the `home` command is used in the <>, this would not have any effect on the current GUI being displayed as the user is already on the HOME page. === Specific Help Windows for different pages ==== Implementation Each page in Volant has its own `{Page}HelpWindow` class. <>, the `MainWindow` will create a new `{Page}HelpWindow` containing details of the commands that can be used on that page. ==== Design Considerations ===== Aspect: Syntax of the find command * **Alternative 1 (current choice):** Help Window specifically details the commands that can be used on the page that the user is currently on. ** Pros: Very specific and allows added convenience for users when they want to use commands with many fields that they cannot remember without having to refer to the User Guide. ** Cons: Every single page has to have its own class file for the Help Window, if there are many pages, there will be many files to keep track of. * **Alternative 2:** Use a general Help Window that lists every single command for every page in Volant ** Pros: Only one Help Window class file needed and it is easy to implement. ** Cons: If all the commands are detailed on a single long Help Window, the user will have to inconveniently scroll through the window to reach the section that details commands for the page that they are on. === Adding a trip in Home Page ==== Implementation Adding a trip The add trip feature allows user to add a trip to Volant. This feature is facilitated by `HomeInputParser`, `AddCommandParser`, and `AddCommand`. Given below is an example usage scenario and how the trip add mechanism behaves at each step: 1. The user executes the add command in `HOME` page and provides the required metadata in the correct format to be added. 2. `HomeInputParser` parses the input by the user to check if the input provided contains a valid command keyword. 3. `AddCommandParser` parses the remaining input by the user for metadata denoted with prefixes. 4. `AddCommandParser` checks if the metadata input by the user is in the desired format. 5. `AddCommandParser` creates a new `AddCommand` based on the metadata provided. 6. `HomeLogicManager` executes the `AddCommand`. 7. `HomeModelManager` checks if the new `TRIP` has any logical conflicts with existing `TRIP`(s) 8. `HomeModelManager` adds the module to the `UniqueTripList`. 9. A new folder with the `TRIP` name is created. 10. `HomeLogicManager` updates storage with updated `UniqueTripList`. 11. `MainWindow` receives `CommandResult` from `HomeLogicManager` containing success message to be displayed to user. 12. Trips displayed in `MainWindow` are updated and `MainWindow` displays success message. The following activity diagram summarises what happens when a user executes a add trip command: .Activity Diagram for `add` Command image::AddTripActivityDiagram.png[align=""center""] ==== Design Considerations ===== Aspect: How data is stored * **Alternative 1 (current choice):** Saves the trip details in main volant json folder and create a folder corresponding to `TRIP` name. ** Pros: Easy to implement. ** Cons: Less organised as all trip details are stored in one location. Any error in the way one trip is stored will cause all trips not to be loaded. * **Alternative 2:** Create a individual json file for each trip details. ** Pros: An error in the file of one trip will not affect the loading of other trips. ** Cons: Harder to implement retrieval. === Sorting entries in Journal Page ==== Implementation Sorting journal entries The sort feature allows user to sort the entries in the `JOURNAL` of a trip. This feature is facilitated by `JournalInputParser`, `SortCommandParser`, and `SortCommand`. Given below is an example usage scenario and how the journal sort mechanism behaves at each step: 1. The user executes the sort command in `JOURNAL` page and provides a field which they want the entries to be sorted by. 2. `JournalInputParser` parses the input by the user to check if the input provided contains a valid command keyword. 3. `SortCommandParser` parses the remaining input by the user for field. 4. `SortCommandParser` checks if the field input by the user is a valid field to sort by. 5. `SortCommandParser` creates a new `SortCommand` based on the field provided. 6. `JournalLogicManager` executes the `SortCommand`. 7. `JournalModelManager` sorts the entries according to the input field. 8. `JournalLogicManager` updates storage with updated `UniqueEntryList`. 9. `MainWindow` receives `CommandResult` from `HomeLogicManager` containing success message to be displayed to user. 10. Jounral entries displayed in `MainWindow` are updated and `MainWindow` displays success message. The following activity diagram summarizes what happens when a user executes a sort journal command: .Activity Diagram for `sort` Command image::sortActivityDiagram.png[align=""center""]] === Adding activities in Itinerary Page ==== Implementation Adding an activity The add activity feature allows user to add an activity to a current trip. This feature is faciliated by `ItineraryInputParser`, `AddCommandParser`, and `AddCommand`. Given below is an example usage scenario and how the activity add mechanism behaves at each step: 1. The user executes the add command in `ITINERARY` page and provides the required metadata in the correct format to be added. 2. `ItineraryInputParser` parses the input by the user to check if the input provided contains a valid command keyword. 3. `AddCommandParser` parses the remaining input by the user for metadata denoted with prefixes. 4. `AddCommandParser` checks if the metadata input by the user is in the desired format. 5. `AddCommandParser` creates a new `AddCommand` based on the metadata provided. 6. `ItineraryLogicManager` executes the `AddCommand`. 7. `ItineraryModelManager` checks if the new `ACTIVITY` has any logical conflicts with existing `ACTIVITY`(s) 8. `ItineraryModelManager` adds the activity to the `UniqueActivityList`. 9. The `itinerary.json` file in the current trip folder in storage is updated 10. `ItineraryLogicManager` updates storage with updated `UniqueActivityList`. 11. `MainWindow` receives `CommandResult` from `ItineraryLogicManager` containing success message to be displayed to user. 12. Activities displayed in `MainWindow` are updated and `MainWindow` displays success message. The following activity diagram summarizes what happens when a user executes a add activity command: .Activity Diagram for `add` Command image::AddActivity.png[align=""center""]] ==== Design Considerations ===== Aspect: Prerequisite of the command Since each trip is associated with one itinerary, when the user wants to use the add activity command, a trip must have already been created. This is why the order of the scence switching is important as it disallows user to create an activity that is not associated with any trip. === Finding activities in Itinerary Page ==== Implementation Finding an activity The find activity feature allows user to find one or several activities in the current trip with matching keywords provided. This feature is faciliated by `ItineraryInputParser`, `FindCommandParser`, and `FindCommand`. Given below is an example usage scenario and how the activity find mechanism behaves at each step: 1. The user executes the find command in `ITINERARY` page and provides one or several field(s) which they want to be displayed with the current keyword. 2. `ItineraryInputParser` parses the input by the user to check if the input provided contains a valid command keyword. 3. `FindCommandParser` parses the remaining input by the user for fields to be found. 4. `FindCommandParser` checks if the field input by the user is a valid field to find. 5. `FindCommandParser` creates a new `FindCommand` based on the fields provided. 6. `ItineraryLogicManager` executes the `FindCommand`. 7. A new find predicate is created to check for matching keyword from the current list of activities. 8. `ItineraryModelManager` checks the current `UniqueActivityList` to find activities with matching keywords provided based on the predicate created. 9. `ItineraryModelManager` updates the activities that matched in the `FilteredActivityList`. 10. `MainWindow` receives `CommandResult` from `ItineraryLogicManager` containing success message to be displayed to user. 11. Jounral entries displayed in `MainWindow` are updated and `MainWindow` displays success message. The following activity diagram summarizes what happens when a user executes a find activity command: .Activity Diagram for `find` Command image::FindItinerary.png[align=""center""]] ==== Design Considerations ===== Aspect: Syntax of the find command * **Alternative 1 (current choice):** Users are allowed to find according to specific fields. This is done by adding the prefixes(t/ for `title`, l/ for `location`, d/ for `date`, and t/ for `time`) before the keyword to be found ** Pros: Allows users to be very specific in the find command. This means that users can find activities with the keywords in the specific field that they want. This implementation also allows users to append one find command with multiple fields to narrow down the search in less steps. ** Cons: Cannot find the same keyword for multiple fields. The current implementation can also cause the CLI by the users to be longer as there is a need to specify the fields to find. Furthermore, this implementation is more troublesome to implement. * **Alternative 2:** Users can find with one or a few keywords without the need to specify the fields. ** Pros: The commands would be a lot shorter and easy to use. This allows for cross-field search which is not possible with the current implementation. This implementation is also easier to implement. ** Cons: This makes it difficult to narrow down the search if the users want to be specific about which field the keyword is in. The current implementation allows for greater freedom in choosing the fields to search for, something this implementation would not be able to accomplish. Furthermore, as `date` and `time` have different format from `location` and `title`, the specified field would make it easier for users to search for activities with the same `date` or `time`. The following activity diagram summarises what happens when a user executes a sort journal command: .Activity Diagram for `sort` Command image::SortActivityDiagram.png[align=""center""] === Deleting Trip in Home Page ==== Implementation The delete trip feature allows user to delete a trip in Volant. This feature is faciliated by `HomeInputParser`, `DeleteCommandParser`, and `DeleteCommand`. Given below is an example usage scenario and how the delete mechanism behaves at each step: 1. The user executes the delete command in `HOME` page and provides the desired index for deletion. 2. `HomeInputParser` parses the input by the user to check if the input provided contains a valid command keyword. 3. `DeleteCommandParser` parses the remaining input by the user for the index. 4. `DeleteCommandParser` checks if the index provided is valid; at most the number of trips in the list. 5. `DeleteCommandParser` creates a new `DeleteCommand` with the index provided. 6. `HomeLogicManager` executes the `DeleteCommand`. 7. `The trip folder in the file path along with its contents are deleted during execution. 8. `HomeModelManager` updates the `UniqueTripList`. 9. `HomeLogicManager` updates storage with updated `UniqueTripList`. 10. `MainWindow` receives `CommandResult` from `HomeLogicManager` containing success message to be displayed to user. 11. Trips displayed in `MainWindow` are updated and `MainWindow` displays success message. The following activity diagram summarises what happens when a user executes an add activity command: .Activity Diagram for `delete` Command image::deleteTripActivityDiagram.png[align=""center""]] ==== Design Considerations ===== Aspect: How to delete the trip Since each trip is a folder containing the data of the trip's itinerary and journal. If the trip is deleted, the corresponding itinerary and journal json files should also be deleted. This prevents unnecessary files from being stored in the program. === Adding an activity in Itinerary Page ==== Implementation The add activity feature allows user to add an activity to a current trip. This feature is faciliated by `ItineraryInputParser`, `AddCommandParser`, and `AddCommand`. Given below is an example usage scenario and how the activity add mechanism behaves at each step: 1. The user executes the add command in `ITINERARY` page and provides the required metadata in the correct format to be added. 2. `ItineraryInputParser` parses the input by the user to check if the input provided contains a valid command keyword. 3. `AddCommandParser` parses the remaining input by the user for metadata denoted with prefixes. 4. `AddCommandParser` checks if the metadata input by the user is in the desired format. 5. `AddCommandParser` creates a new `AddCommand` based on the metadata provided. 6. `ItineraryLogicManager` executes the `AddCommand`. 7. `ItineraryModelManager` checks if the new `ACTIVITY` has any logical conflicts with existing `ACTIVITY`(s) 8. `ItineraryModelManager` adds the activity to the `UniqueActivityList`. 9. The `itinerary.json` file in the current trip folder in storage is updated 10. `ItineraryLogicManager` updates storage with updated `UniqueActivityList`. 11. `MainWindow` receives `CommandResult` from `ItineraryLogicManager` containing success message to be displayed to user. 12. Activities displayed in `MainWindow` are updated and `MainWindow` displays success message. The following activity diagram summarises what happens when a user executes an add activity command: .Activity Diagram for `add` Command image::AddActivity.png[align=""center""]] ==== Design Considerations ===== Aspect: Prerequisite of the command Since each trip is associated with one itinerary, when the user wants to use the add activity command, a trip must have already been created. This is why the order of the scence switching is important as it disallows user to create an activity that is not associated with any trip. === Finding activities in Itinerary Page ==== Implementation The find activity feature allows user to find one or several activities in the current trip with matching keywords provided. This feature is faciliated by `ItineraryInputParser`, `FindCommandParser`, and `FindCommand`. Given below is an example usage scenario and how the activity find mechanism behaves at each step: 1. The user executes the find command in `ITINERARY` page and provides one or several field(s) which they want to be displayed with the current keyword. 2. `ItineraryInputParser` parses the input by the user to check if the input provided contains a valid command keyword. 3. `FindCommandParser` parses the remaining input by the user for fields to be found. 4. `FindCommandParser` checks if the field input by the user is a valid field to find. 5. `FindCommandParser` creates a new `FindCommand` based on the fields provided. 6. `ItineraryLogicManager` executes the `FindCommand`. 7. A new find predicate is created to check for matching keyword from the current list of activities. 8. `ItineraryModelManager` checks the current `UniqueActivityList` to find activities with matching keywords provided based on the predicate created. 9. `ItineraryModelManager` updates the activities that matched in the `FilteredActivityList`. 10. `MainWindow` receives `CommandResult` from `ItineraryLogicManager` containing success message to be displayed to user. 11. Journal entries displayed in `MainWindow` are updated and `MainWindow` displays success message. The following activity diagram summarises what happens when a user executes a find activity command: .Activity Diagram for `find` Command image::FindItinerary.png[align=""center""]] ==== Design Considerations ===== Aspect: Syntax of the find command * **Alternative 1 (current choice):** Users are allowed to find according to specific fields. This is done by adding the prefixes(t/ for `title`, l/ for `location`, d/ for `date`, and t/ for `time`) before the keyword to be found ** Pros: Allows users to be very specific in the find command. This means that users can find activities with the keywords in the specific field that they want. This implementation also allows users to append one find command with multiple fields to narrow down the search in less steps. ** Cons: Cannot find the same keyword for multiple fields. The current implementation can also cause the CLI by the users to be longer as there is a need to specify the fields to find. Furthermore, this implementation is more troublesome to implement. * **Alternative 2:** Users can find with one or a few keywords without the need to specify the fields. ** Pros: The commands would be a lot shorter and easy to use. This allows for cross-field search which is not possible with the current implementation. This implementation is also easier to implement. ** Cons: This makes it difficult to narrow down the search if the users want to be specific about which field the keyword is in. The current implementation allows for greater freedom in choosing the fields to search for, something this implementation would not be able to accomplish. Furthermore, as `date` and `time` have different format from `location` and `title`, the specified field would make it easier for users to search for activities with the same `date` or `time`. === Refreshing trips in Home Page ==== Implementation The refresh feature allows user to repopulate the current page with the same data in the storage. This feature is faciliated by `HomeInputParser`, `RefreshCommandParser`, and `RefreshCommand`. Given below is an example usage scenario and how the refresh mechanism behaves at each step: 1. The user executes the rf command in `HOME` page. 2. `HomeInputParser` parses the input by the user to check if the input provided contains a valid command keyword. 3. `FindCommandParser` creates a new `RefreshCommand`. 4. `HomeLogicManager` executes the `RefreshCommand`. 5. `MainWindow` receives `CommandResult` and success message from `HomeLogicManager`. 6. `MainWindow` checks the current page user is on and repopulates display with list from `HomeModelManager`. 7. `MainWindow` displays success message. The following activity diagram summarises what happens when a user executes a find activity command: .Activity Diagram for `rf` Command image::rfActivityDiagram.png[align=""center""]] ==== Design Considerations ===== Aspect: How to get the list to repopulate the data with After sorting or finding a list, the user needed a way to view the original data. The construction of each model includes a list that contains the relevant data in storage. Using that list, the view can be repopulated with the original data. === Data Storage All data (trip details, journal entry details and itinerary details) is saved in the `main.data` directory. ==== Organisation .Data Storage in Volant image::user-guide/data-storage.png[align=""center""] The data files are organised in a way that trip details are stored in `volant.json`, while journal and itinerary details are stored in a `journal.json` file and a `itinerary.json` file respectively. Both of these data files are organised under a directory that represents the trip that the journal and itinerary are associated with. The following explanation provides more details about these data files: * Within the `main.data` directory, the `volant.json` file contains a list of JSON objects, each representing a trip, with key-value pairs identifying the trip name, location and date range.Upon creation of a trip named ""ABC"", the `volant.json` file is updated with a new JSON object representing the trip. The `main.data.ABC` directory is also created. * When an activity is added to the itinerary, a `itinerary.json` file is created in the `main.data.ABC` directory, containing a list of JSON objects, each representing an activity, with key-value pairs identifying the activity title, location, date and time. * When an entry is added to the journal, a `journal.json` file is created in the `main.data.ABC` directory, containing a list of JSON objects, each representing a journal entry, with key-value pairs identifying the entry content, date, time, location, feeling and weather. ==== Design Considerations Pros: * Each data file can be kept small in size. * This allows for faster retrieval of trip/journal/itinerary information from these data files. Cons: * There is no single data file that provides an overview of all of a user's data. ==== Data storage implementation: Adding a new trip/activity Given below is an example usage scenario where a user adds a new trip: 1. The user executes the add command and provides the name, location and date range. 2. A new `Trip` object is created with the specified name, location and date range. 3. In `HomeModelManager`, the `Trip` object is added to the `TripList`. 4. A new folder is created in the `main.data` directory with the specified trip name. 5. `HomeLogicManager` accesses the `volant.json` file in the `main.data` directory. 6. Each `Trip` object in the `TripList` is converted into a `JsonAdaptedTrip` object. 7. A new `JsonSerializableTripList` object is created with the `JsonAdaptedTrip` objects. 8. The new `JsonSerializableTripList` object is saved to the `volant.json` data file. 9. The program log displays a success message. The following activity diagram summarises what happens when a user adds a new trip: .Activity diagram for adding a new trip image::addTripStorageActivityDiagram.png[align=""center""] The process is similar for the scenario where the user adds a new activity to the itinerary, and the `itinerary.json` data file is updated. The following activity diagram summarises this process: .Activity diagram for adding a new activity image::addActivityStorageActivityDiagram.png[align=""center""] ==== Data storage implementation: Editing a trip Given below is an example usage scenario where a user edits a trip: 1. The user executes the edit command and provides the updated details. 2. `HomeLogicManager` checks if the name of the trip was updated. If it was, a new directory will be created with the new trip name. Data files in the previous folder are moved into this new folder. Following that, the old folder is deleted. 3. `HomeLogicManager` accesses the `volant.json` file in the `main.data` directory. 4. Each `Trip` object in the `TripList` is converted into a `JsonAdaptedTrip` object. 5. A new `JsonSerializableTripList` object is created with the `JsonAdaptedTrip` objects. 6. The new `JsonSerializableTripList` object is saved to the `volant.json` data file. 7. The program log displays a success message. The following activity diagram summarises what happens when a user edits a trip: .Activity diagram for editing a trip image::editTripStorageActivityDiagram.png[align=""center""] ==== Data storage implementation: Deleting a journal entry/itinerary activity Given below is an example usage scenario where a user deletes a journal entry: 1. The user executes the delete command. 2. In `JournalModelManager`, the identified `Entry` is removed from the `EntryList`. 3. `JournalLogicManager` accesses the `journal.json` file in the specific trip directory. 4. Each remaining `Entry` object in the `EntryList` is converted into a `JsonAdaptedEntry` object. 5. A new `JsonSerializableEntryList` object is created with the `JsonAdaptedEntry` objects. 6. The new `JsonSerializableEntryList` object is saved to the `journal.json` data file. 7. The program log displays a success message. This process is the same for scenarios where the user deletes an itinerary activity. The following activity diagram summarises what happens when a user deletes a journal entry or itinerary activity: .Activity diagram for deleting a journal entry/itinerary activity image::deleteStorageActivityDiagram.png[align=""center""] === Logging We are using `java.util.logging` package for logging. The `LogsCenter` class is used to manage the logging levels and logging destinations. * The logging level can be controlled using the `logLevel` setting in the configuration file (See <>) * The `Logger` for a class can be obtained using `LogsCenter.getLogger(Class)` which will log messages according to the specified logging level * Currently log messages are output through: `Console` and to a `.log` file. *Logging Levels* * `SEVERE` : Critical problem detected which may possibly cause the termination of the application * `WARNING` : Can continue, but with caution * `INFO` : Information showing the noteworthy actions by the App * `FINE` : Details that is not usually noteworthy but may be useful in debugging e.g. print the actual list instead of just its size [[Implementation-Configuration]] === Configuration Certain properties of the application can be controlled (e.g user prefs file location, logging level) through the configuration file (default: `config.json`). == Documentation Refer to the guide <>. == Testing Refer to the guide <>. == Dev Ops Refer to the guide <>. [appendix] == Product Scope *Target user profile*: * is a solo traveller * prefers desktop apps over other types * can type fast * prefers typing over mouse input * is reasonably comfortable using CLI apps *Value proposition*: convenient travel assistant to for solo travelers who are always on their feet. [appendix] == User Stories *Priorities* * High (must have) - `* * *` * Medium (nice to have) - `* *` * Low (not useful) - `*` [width=""80%"",cols=""22%,<23%,<25%,<30%"",options=""header"",] |======================================================================= |Priority |As a ... |I want to ... |So that I can ... |`* * *` | frequent traveler | add a travel entry with weather, location and time metadata | document my past travels |`* * *` | traveler always on the go | record short text entries recording my travels, similar to that of a Tweet on Twitter | can keep track of my activities without excessive typing |`* * *` |user |add an activity into an itinerary list |see my planned activities at a glance and better plan my trip |`* * *` |user |tag a location to each activity in the itinerary |view where each activity is taking place |`* * *` |user |edit the entries in my itinerary list |amend any mistakes when entering data, or change my travel plans |`* * *` |user |see a chronological timeline of the activities in the itinerary |have a clear idea of my travel plans and schedule |`* * *` |user |view my itinerary and journal separately |view them in a less cluttered manner |`* * *` |frequent traveler |see a record of all my past itineraries |can review my past travels |`* * *` |traveler always meeting new people overseas |add a contact that I met during my trip with metadata including their name, age, phone number, location where I met them, and their country of origin |can keep in contact with them |`* * *` |user |delete contacts |get rid of contacts that I have not been in touch with for some time |`* * *` |user |view my itineraries, contact lists and journals specific to the trip they are relevant to |effectively plan for multiple trips simultaneously |`* * *` |user |customize trip names |distinguish between different trips that happen in the same location within similar date ranges |`* *` |frequent traveler |to be able to see a timeline view of all my short journal entries and photos, including the location and time of the photos and entries, per trip |relieve the memories of the trip in its original sequence |`* *` |food lover |add a meal with description, photo, price and location |keep track of what I ate |`* *` |user |sort my travel entries by category depending on the ‘feeling’ tag of each travel entry |see my best moments |`* *` |user |record items in a packing list|remind myself what I will need on a trip |`* *` |busy user |list |easily reference what I need for a trip at a glance |`* *` |fickle-minded user |delete packing list entries |remove items I feel I no longer need for the trip from the packing list |======================================================================= _{All user stories can be viewed in our issue tracker.}_ [appendix] == Use Cases (For all use cases below, the *System* is `Volant (V)` and the *Actor* is the `user`, unless specified otherwise) [discrete] === UC01 - Adding New Trip **Precondition: **Start from home page *Guarantee:* A new Trip will be created *<>* 1. User enters details of trip to be added 2. V adds new trip to trip list + Use case ends *<>* [none] * 1a. V detects invalid characters in trip details * 1a1. V outputs error informing user of invalid command + Use case ends [none] * 1b. V detects missing fields in trip details * 1b1. V outputs error informing user of missing fields + Use case ends [none] * 1c. V detects that trip has a clashing date range with another trip on the trip list * 1c1. V outputs error informing user of clashing date range between trip and another trip on the list + Use case ends [none] * 1d. V detects that trip has the same name as another trip on the trip list * 1d1. V outputs error informing user that the trip already exists on the trip list + Use case ends [none] * 1e. V is unable to detect a valid command keyword * 1e1. V outputs error informing user of invalid command + Use case ends [discrete] === UC02 - Editing Existing Trip **Precondition: **User is in the home page **Guarantee: **Metadata of existing trip will be changed *MSS* 1. User inputs command to edit an existing trip 2. V updates metadata of corresponding trip according to user input 3. Trip list is updated and the changes are reflected for user to see + Use case ends *Extensions* [none] * 1a. V is unable to detect any specified fields to edit * 1a1. V outputs error informing user that a field to edit must be specified + Use case ends [none] * 1b. V detects an invalid index i.e. index out of range or negative index * 1b1. V outputs error informing user of invalid index specified + Use case ends [none] * 1c. V detects invalid characters for the fields * 1c1. V outputs error informing user of invalid command + Use case ends [none] * 1d. V is unable to detect a valid command keyword * 1d1. V outputs error informing user of invalid command + Use case ends [discrete] === UC03 - Navigating to Trip Page *Precondition:* User has added a trip *Guarantee:* User will be moved to the Trip page *MSS* 1. User changes directory to specific trip folder in trip list using index 2. V loads and displays trip page + Use case ends *Extensions* [none] * 1a. V detects an invalid index i.e. index out of range or negative index * 1a1. V outputs error informing user of invalid index specified + Use case ends [none] * 1b. V is unable to detect a valid command keyword * 1b1. V outputs error informing user of invalid command + Use case ends [discrete] === UC04 - Accessing Trip Feature Pages (Itinerary / Journal) *Precondition:* User is in the home page *Guarantee:* User will be moved to the desired page *MSS* 1. User navigates to a specific trip (UC03) 2. User requests to navigate to the desired page in current trip 3. V loads and displays the desired page + Use case ends *Extensions* [none] * 2a. V detects invalid field to navigate to the page * 2a1. V outputs error informing user of invalid command + Use case ends [none] * 2b. V is unable to detect a valid command keyword * 2b1. V outputs error informing user of invalid command + Use case ends [discrete] === UC05 - Adding a travel Entry into Journal of a Trip **Precondition: **User is already in the Journal page of Trip **Guarantee: **A new travel entry will be added to the Travel Journal *MSS* 1. User enters details of the travel entry 2. V confirms successful entry and displays new entry in the journal + Use case ends *Extensions* [none] * 1a. V detects invalid characters in travel entry * 1a1. V outputs error informing user of invalid command + Use case ends [none] * 1b. V detects missing fields in travel entry * 1b1. V outputs error informing user of missing travel entry + Use case ends [none] * 1c. V is unable to detect a valid command keyword * 1c1. V outputs error informing user of invalid command + Use case ends [none] * 1d. V detects that text field is greater 280 characters long * 1d1. V outputs error informing user of character limit and how many characters over the limit their input was + Use case ends [discrete] === UC06 - Adding Activities into Itinerary **Precondition: **User is already in the Itinerary page of the Trip **Guarantee: **A new activity will be added to the Itinerary *MSS* 1. User enters details of activity 2. V confirms successful entry and displays updated itinerary + Use case ends *Extensions* [none] * 1a. V detects invalid characters into activity entry * 1a1. V outputs error informing user of invalid command + Use case ends [none] * 1b. V detects missing fields in activity entry * 1b1. V outputs error informing user of missing activity entry + Use case ends [none] * 1c. V is unable to detect a valid command keyword * 1c1. V outputs error informing user of invalid command + Use case ends [discrete] === UC07 - Editing Existing Journal Entry **Precondition: **User is on the Journal page and has added one or more entries already **Guarantee: **Metadata of an existing entry will be changed *MSS* 1. User inputs command to edit an entry 2. V updates metadata of corresponding entry according to user input 3. Entry list is updated and the changes are reflected for user to see + Use case ends *Extensions* [none] * 1a. V is unable to detect any specified fields to edit * 1a1. V outputs error informing user that a field to edit must be specified + Use case ends [none] * 1b. V detects incorrect date or time format * 1b1. V outputs error informing user that the acceptable format for date and time input + Use case ends [none] * 1c. V detects an invalid index i.e. index out of range or negative index * 1c1. V outputs error informing user of invalid index specified + Use case ends [none] * 1d. V detects invalid characters for the fields * 1d1. V outputs error informing user of invalid command + Use case ends [none] * 1e. V is unable to detect a valid command keyword * 1e1. V outputs error informing user of invalid command + Use case ends [discrete] === UC08 - Editing Existing Activity **Precondition: **User is on the Itinerary page and has added one or more activities already **Guarantee: **Metadata of an existing activity will be changed *MSS* 1. User inputs command to edit an activity. 2. V updates metadata of corresponding activity according to user input 3. Activity list is updated and the changes are reflected for user to see + Use case ends *Extensions* [none] * 1a. V is unable to detect any specified fields to edit * 1a1. V outputs error informing user that a field to edit must be specified + Use case ends [none] * 1b. V detects incorrect date or time format * 1b1. V outputs error informing user that the acceptable format for date and time input + Use case ends [none] * 1c. V detects an invalid index i.e. index out of range or negative index * 1c1. V outputs error informing user of invalid index specified + Use case ends [none] * 1d. V detects invalid characters for the fields * 1d1. V outputs error informing user of invalid command + Use case ends [none] * 1e. V is unable to detect a valid command keyword * 1e1. V outputs error informing user of invalid command + Use case ends [discrete] === UC09 - Sorting Journal Entries **Precondition: **User is on the Journal page and has added one or more entries already **Guarantee: **Entry list will be sorted *MSS* 1. User inputs sort command 2. V sorts the entry list according to user's input 3. Entry list is updated and the sorted list is displayed to the user + Use case ends Extensions [none] * 1a. V does not detect an argument for sort type in user's input * 1a1. V outputs error message informing user to include a sort type + Use case ends [none] * 1b. V detects invalid characters for the sort type input * 1b1. V outputs error informing user of invalid sort type + Use case ends [none] * 1c. V is unable to detect a valid command keyword * 1c1. V outputs error informing user of invalid command + Use case ends [discrete] === UC10 - Finding Itinerary Activities **Precondition: **User is on the Itinerary page and has added one or more activities already **Guarantee: **Activity list containing matching search terms is displayed *MSS* 1. User inputs find command 2. V checks the activity list for activities with metadata that matches the given search term(s) 3. V outputs an activity list containing all the activities matching the given search term(s) + Use case ends Extensions [none] * 1a. V does not find any activities that match the given search term(s) * 1a1. V outputs message informing user that no matching activities were found + Use case ends [none] * 1b. V detects invalid characters for the given search term(s) * 1b1. V outputs error informing user of invalid command + Use case ends [none] * 1c. V is unable to detect a valid command keyword * 1c1. V outputs error informing user of invalid command + Use case ends [appendix] == Non Functional Requirements . Volant should work on any <> as long as it has Java `11` or above installed. . Volant should work without any internet connection. . Volant should be able to hold up to 100 trips without noticing a increase in response time from the system for typical usage. . A user who is able to type above 40 words per minute (wpm) for regular English text (i.e. not code, not system admin commands) should be able to accomplish most of the tasks faster using commands than using the mouse. . Commands should be <> commands as opposed to <>. . A user should have minimum 100 Megabytes (MB) free disk space on their computer to store the program. . Input by the user should only be in English. . Volant source code should be covered by tests as much as possible. . Volant should work for a single user only. [appendix] == Glossary [[extensions]] Extensions:: ""add-on""s to the MSS that describe exceptional/alternative flow of events. [[mainstream-os]] Mainstream OS:: Windows, Linux, Unix, OS-X [[mss]] MSS:: Main Success Scenario [[multi-level-c]] Multi-level Commands:: Commands that require multiple lines of user input for execution. [[root-page]] Root Page:: The first page the shows up when Volant is opened. By default, this is the `HOME` page. [[one-shot-c]] One-shot Commands:: Commands that are executed using only a single line of user input. [appendix] == Product Survey *Volant* Author: Team Volant Pros:: * The product is effective in assisting solo travellers to plan and execute their trips. * GUI is very aesthetic looking, pleasing to the eyes. * The available commands are intuitive, and are easy to use and remember. Cons:: * The fremium model proposed can be a bit expensive. * A dark mode can be included. Some users prefer a GUI with dark mode. * More features can be integrated. These features can be included in version 2.0. [appendix] == Instructions for Manual Testing Given below are instructions to test the app manually. [NOTE] These instructions only provide a starting point for testers to work on; testers are expected to do more _exploratory_ testing. === Launch and Shutdown . Initial launch .. Download the jar file and copy into an empty folder. .. Double-click the jar file. + Expected: Shows the GUI with a set of sample contacts. The window size may not be optimum. . Saving window preferences .. Resize the window to an optimum size. Move the window to a different location. Close the window. .. Re-launch the app by double-clicking the jar file. + Expected: The most recent window size and location is retained. === Adding . Adding a `TRIP` to an empty or populated trip list .. Prerequisites: NA .. Test case: `add n/Bali 2020 l/Bali d/02-01-2020 to 02-05-2020` .. Expected: `TRIP` with corresponding details is added to trip list. .. Test case: `add n/Bali 2020 l/Bali d/2020-01-02 to 2020-05-02` .. Expected: No `TRIP` added. Error details shown in status message. === Deleting . Deleting a `TRIP` while all `TRIPS` are listed .. Prerequisites: List all `TRIPS` using the `list` command. Multiple `TRIPS` are present in the list. .. Test case: `delete 1` + Expected: First contact is deleted from the list. Details of the deleted `TRIP` are shown in the status message. Timestamp in the status bar is updated. .. Test case: `delete 0` + Expected: No `TRIP` is deleted. Error details shown in the status message. Status bar remains the same. .. Other incorrect delete commands to try: `delete`, `delete x` (where x is larger than the list size) + Expected: Similar to previous. . Deleting an `activity` in the `ITINERARY` .. Prerequisites: A `TRIP` has already been created. .. Test case: `delete 1` + Expected: First `activity` is deleted from the `activity` list of the `ITINERARY` of the current `TRIP`. Current `activity` list is updated. .. Test case: `delete 0` + Expected: No `activity` is deleted. Error details shown in the status message. .. Test case: `delete a` + Expected: No `activity` is deleted. Error details shown in the status message. .. Other incorrect delete commands to try: `delete`, `delete x` (where x is larger than the itinerary size) + Expected: Similar to previous. . Deleting an `entry` in the `JOURNAL` .. Prerequisites: A `TRIP` has already been created. .. Test case: `delete 1` + Expected: First `entry` is deleted from the `JOURNAL` of the current `TRIP`. Current `entry` list is updated. .. Test case: `delete 0` + Expected: No `entry` is deleted. Error details shown in the status message .. Other incorrect delete commands to try: `delete`, `delete x` (where x is larger than the journal size) + Expected: Similar to previous. === Saving data . Dealing with missing/corrupted data files .. _{explain how to simulate a missing/corrupted file and the expected behavior}_ ",12535,False,2015.1323348767855,median "/* * Copyright (c) 2016, Ford Motor Company * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following * disclaimer in the documentation and/or other materials provided with the * distribution. * * Neither the name of the Ford Motor Company nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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 ""gtest/gtest.h"" #include ""policy/policy_manager_impl_test_base.h"" #include ""policy/policy_table/types.h"" #include ""json/reader.h"" #include ""utils/date_time.h"" #include ""utils/gen_hash.h"" namespace test { namespace components { namespace policy_test { using ::testing::_; using ::testing::Return; using ::testing::ReturnRef; TEST_F(PolicyManagerImplTest, DISABLED_TiggerPTUForNaviAppInCaseNoCertificateExistsInPolicyTable) { EXPECT_CALL(*cache_manager_, GetDeviceConsent(_)) .WillOnce(Return(kDeviceAllowed)); const uint32_t type = 0; const uint32_t id = 1; const EntityStatus status = kStatusOn; ExternalConsentStatusItem item(type, id, status); ExternalConsentStatus external_consent_status; external_consent_status.insert(item); GroupsByExternalConsentStatus group; group[item].push_back(std::make_pair(""group_name"", true)); EXPECT_CALL(*cache_manager_, GetExternalConsentStatus()) .WillOnce(Return(external_consent_status)); EXPECT_CALL(*cache_manager_, GetGroupsWithSameEntities(external_consent_status)) .WillOnce(Return(group)); EXPECT_CALL(*cache_manager_, ResetCalculatedPermissions()); EXPECT_CALL(*cache_manager_, GetPermissionsForApp(_, _, _)) .WillOnce(Return(true)) .WillOnce(Return(true)); EXPECT_CALL(*cache_manager_, GetFunctionalGroupNames(_)) .WillOnce(Return(true)) .WillOnce(Return(true)); EXPECT_CALL(*cache_manager_, SetUserPermissionsForApp(_, _)) .WillOnce(Return(false)); EXPECT_CALL(*cache_manager_, SetExternalConsentForApp(_)); EXPECT_CALL(*cache_manager_, IsPredataPolicy(_)).WillOnce(Return(false)); EXPECT_CALL(*cache_manager_, IsApplicationRepresented(_)) .WillOnce(Return(true)); EXPECT_EQ(policy_manager_->GetPolicyTableStatus(), ""UP_TO_DATE""); policy_manager_->AddApplication(kDefaultDeviceMacAddress, kDefaultId, HmiTypes(policy_table::AHT_DEFAULT)); EXPECT_EQ(policy_manager_->GetPolicyTableStatus(), ""UP_TO_DATE""); } TEST_F(PolicyManagerImplTest2, GetNotificationsNumberAfterPTUpdate) { // Arrange CreateLocalPT(preloaded_pt_filename_); Json::Value table = createPTforLoad(); policy_manager_->ForcePTExchange(); policy_manager_->OnUpdateStarted(); policy_table::Table update(&table); update.SetPolicyTableType(rpc::policy_table_interface_base::PT_UPDATE); // Act std::string json = table.toStyledString(); ::policy::BinaryMessage msg(json.begin(), json.end()); ASSERT_EQ(PolicyManager::PtProcessingResult::kSuccess, policy_manager_->LoadPT(kFilePtUpdateJson, msg)); EXPECT_FALSE(policy_manager_->GetCache()->IsPTPreloaded()); EXPECT_CALL(listener_, OnUpdateStatusChanged(_)); policy_manager_->OnPTUFinished(PolicyManager::PtProcessingResult::kSuccess); std::string priority = ""EMERGENCY""; uint32_t notif_number = policy_manager_->GetNotificationsNumber(priority); EXPECT_EQ(1u, notif_number); priority = ""NAVIGATION""; notif_number = policy_manager_->GetNotificationsNumber(priority); EXPECT_EQ(2u, notif_number); priority = ""EMERGENCY""; notif_number = policy_manager_->GetNotificationsNumber(priority); EXPECT_EQ(1u, notif_number); priority = ""VOICECOM""; notif_number = policy_manager_->GetNotificationsNumber(priority); EXPECT_EQ(3u, notif_number); priority = ""NORMAL""; notif_number = policy_manager_->GetNotificationsNumber(priority); EXPECT_EQ(5u, notif_number); priority = ""NONE""; notif_number = policy_manager_->GetNotificationsNumber(priority); EXPECT_EQ(6u, notif_number); } TEST_F(PolicyManagerImplTest2, IsAppRevoked_SetRevokedAppID_ExpectAppRevoked) { // Arrange CreateLocalPT(preloaded_pt_filename_); EXPECT_CALL(listener_, GetDevicesIds(app_id_1_)) .WillRepeatedly(Return(transport_manager::DeviceList())); policy_manager_->AddApplication( device_id_1_, app_id_1_, HmiTypes(policy_table::AHT_DEFAULT)); std::ifstream ifile(kValidSdlPtUpdateJson); Json::Reader reader; std::string json; Json::Value root(Json::objectValue); if (ifile.is_open()) { if (reader.parse(ifile, root, true)) { root[""policy_table""][""app_policies""][app_id_1_] = Json::nullValue; json = root.toStyledString(); } } ifile.close(); ::policy::BinaryMessage msg(json.begin(), json.end()); ASSERT_EQ(PolicyManager::PtProcessingResult::kSuccess, policy_manager_->LoadPT(kFilePtUpdateJson, msg)); policy_manager_->OnPTUFinished(PolicyManager::PtProcessingResult::kSuccess); EXPECT_FALSE(policy_manager_->GetCache()->IsPTPreloaded()); CheckRpcPermissions( app_id_1_, ""UnregisterAppInterface"", ::policy::kRpcDisallowed); EXPECT_TRUE(policy_manager_->IsApplicationRevoked(app_id_1_)); } // Related to manual test APPLINK-18792 TEST_F(PolicyManagerImplTest2, AppRevokedOne_AppRegistered) { // Arrange CreateLocalPT(preloaded_pt_filename_); EmulatePTAppRevoked(kPtu2Json); EXPECT_FALSE(policy_manager_->GetCache()->IsPTPreloaded()); ASSERT_TRUE( (policy_manager_->GetCache())->AddDevice(device_id_2_, ""Bluetooth"")); policy_manager_->AddApplication( device_id_2_, application_id_, HmiTypes(policy_table::AHT_DEFAULT)); // Registration is allowed CheckRpcPermissions(""RegisterAppInterface"", ::policy::kRpcAllowed); } // Related to manual test APPLINK-18794 TEST_F(PolicyManagerImplTest2, AppRevokedOne_AppRegistered_HMIDefault) { // Arrange CreateLocalPT(preloaded_pt_filename_); EmulatePTAppRevoked(kPtu2Json); EXPECT_FALSE(policy_manager_->GetCache()->IsPTPreloaded()); policy_manager_->AddApplication( device_id_1_, application_id_, HmiTypes(policy_table::AHT_DEFAULT)); std::string default_hmi; // Default HMI level is NONE EXPECT_TRUE(policy_manager_->GetDefaultHmi( device_id_1_, application_id_, &default_hmi)); EXPECT_EQ(""NONE"", default_hmi); } TEST_F(PolicyManagerImplTest2, CheckPermissions_SetRevokedAppID_ExpectRPCDisallowed) { // Arrange CreateLocalPT(preloaded_pt_filename_); policy::CacheManagerInterfaceSPtr cache = policy_manager_->GetCache(); cache->AddDevice(device_id_1_, ""Bluetooth""); cache->SetDeviceData(device_id_1_, ""hardware IPX"", ""v.8.0.1"", ""Android"", ""4.4.2"", ""Life"", 2, ""Bluetooth""); EXPECT_CALL(listener_, OnCurrentDeviceIdUpdateRequired(_, app_id_1_)) .Times(0); EXPECT_CALL(listener_, GetDevicesIds(app_id_1_)) .WillRepeatedly(Return(transport_manager::DeviceList(1, device_id_1_))); policy_manager_->SetUserConsentForDevice(device_id_1_, true); // Add app from consented device. App will be assigned with default policies policy_manager_->AddApplication( device_id_1_, app_id_1_, HmiTypes(policy_table::AHT_DEFAULT)); // Check before action policy_table::RpcParameters rpc_parameters; rpc_parameters.hmi_levels.push_back(policy_table::HL_FULL); policy_table::Rpc rpc; rpc[""Alert""] = rpc_parameters; ::policy::RPCParams input_params; ::policy::CheckPermissionResult output; policy_manager_->CheckPermissions( device_id_1_, app_id_1_, kHmiLevelFull, ""Alert"", input_params, output); // Check RPC is allowed EXPECT_EQ(::policy::kRpcAllowed, output.hmi_level_permitted); ASSERT_TRUE(output.list_of_allowed_params.empty()); // Act std::ifstream ifile(kValidSdlPtUpdateJson); Json::Reader reader; std::string json; Json::Value root(Json::objectValue); EXPECT_TRUE(ifile.is_open()); EXPECT_TRUE(reader.parse(ifile, root, true)); root[""policy_table""][""app_policies""][app_id_1_] = Json::nullValue; json = root.toStyledString(); ifile.close(); ::policy::BinaryMessage msg(json.begin(), json.end()); ASSERT_EQ(PolicyManager::PtProcessingResult::kSuccess, policy_manager_->LoadPT(kFilePtUpdateJson, msg)); policy_manager_->OnPTUFinished(PolicyManager::PtProcessingResult::kSuccess); EXPECT_FALSE(cache->IsPTPreloaded()); policy_manager_->CheckPermissions( device_id_1_, app_id_1_, kHmiLevelFull, ""Alert"", input_params, output); // Check RPC is disallowed EXPECT_EQ(::policy::kRpcDisallowed, output.hmi_level_permitted); ASSERT_TRUE(output.list_of_allowed_params.empty()); } TEST_F(PolicyManagerImplTest2, CheckPermissions_SetAppIDwithPolicies_ExpectRPCAllowed) { // Arrange CreateLocalPT(preloaded_pt_filename_); policy_manager_->AddDevice(device_id_1_, ""Bluetooth""); policy::CacheManagerInterfaceSPtr cache = policy_manager_->GetCache(); ASSERT_TRUE(cache->SetDeviceData(device_id_1_, ""hardware IPX"", ""v.8.0.1"", ""Android"", ""4.4.2"", ""Life"", 2, ""Bluetooth"")); EXPECT_CALL(listener_, OnCurrentDeviceIdUpdateRequired(_, application_id_)) .Times(0); EXPECT_CALL(listener_, GetDevicesIds(application_id_)) .WillRepeatedly(Return(transport_manager::DeviceList(1, device_id_1_))); policy_manager_->SetUserConsentForDevice(device_id_1_, true); // Add app from consented device. App will be assigned with default policies policy_manager_->AddApplication( device_id_1_, application_id_, HmiTypes(policy_table::AHT_MEDIA)); // Emulate PTU with new policies for app added above std::ifstream ifile(kValidSdlPtUpdateJson); Json::Reader reader; std::string json; Json::Value root(Json::objectValue); if (ifile.is_open() && reader.parse(ifile, root, true)) { // Add AppID with policies root[""policy_table""][""app_policies""][application_id_] = Json::Value(Json::objectValue); root[""policy_table""][""app_policies""][application_id_][""memory_kb""] = Json::Value(50); root[""policy_table""][""app_policies""][application_id_] [""heart_beat_timeout_ms""] = Json::Value(100); root[""policy_table""][""app_policies""][application_id_][""AppHMIType""] = Json::Value(Json::arrayValue); root[""policy_table""][""app_policies""][application_id_][""AppHMIType""][0] = Json::Value(""MEDIA""); root[""policy_table""][""app_policies""][application_id_][""groups""] = Json::Value(Json::arrayValue); root[""policy_table""][""app_policies""][application_id_][""groups""][0] = Json::Value(""Base-4""); root[""policy_table""][""app_policies""][application_id_][""priority""] = Json::Value(""EMERGENCY""); root[""policy_table""][""app_policies""][application_id_][""default_hmi""] = Json::Value(""FULL""); root[""policy_table""][""app_policies""][application_id_][""keep_context""] = Json::Value(true); root[""policy_table""][""app_policies""][application_id_][""steal_focus""] = Json::Value(true); root[""policy_table""][""app_policies""][application_id_][""certificate""] = Json::Value(""sign""); json = root.toStyledString(); } ifile.close(); ::policy::BinaryMessage msg(json.begin(), json.end()); // Load Json to cache ASSERT_EQ(PolicyManager::PtProcessingResult::kSuccess, policy_manager_->LoadPT(kFilePtUpdateJson, msg)); policy_manager_->OnPTUFinished(PolicyManager::PtProcessingResult::kSuccess); EXPECT_FALSE(cache->IsPTPreloaded()); policy_table::RpcParameters rpc_parameters; rpc_parameters.hmi_levels.push_back(policy_table::HL_FULL); policy_table::Rpc rpc; rpc[""Alert""] = rpc_parameters; ::policy::RPCParams input_params; ::policy::CheckPermissionResult output; cache->AddDevice(device_id_1_, ""Bluetooth""); cache->SetDeviceData(device_id_1_, ""hardware IPX"", ""v.8.0.1"", ""Android"", ""4.4.2"", ""Life"", 2, ""Bluetooth""); policy_manager_->CheckPermissions(device_id_1_, application_id_, kHmiLevelFull, ""Alert"", input_params, output); // Check RPC is allowed EXPECT_EQ(::policy::kRpcAllowed, output.hmi_level_permitted); // Check list of parameters empty ASSERT_TRUE(output.list_of_allowed_params.empty()); } TEST_F(PolicyManagerImplTest2, CheckPermissions_NoParametersInPT_CheckRpcsInDifferentLevels) { EXPECT_CALL(listener_, GetDevicesIds(application_id_)) .WillRepeatedly(Return(transport_manager::DeviceList())); // Arrange AddSetDeviceData(); LoadPTUFromJsonFile(""json/sdl_update_pt_send_location.json""); // Check RPC in each level ::policy::RPCParams input_params; ::policy::CheckPermissionResult output; // Rpc in FULL level policy_manager_->CheckPermissions(device_id_1_, application_id_, kHmiLevelFull, ""SendLocation"", input_params, output); // Check RPC is allowed EXPECT_EQ(::policy::kRpcAllowed, output.hmi_level_permitted); ASSERT_TRUE(output.list_of_allowed_params.empty()); // Reset output ResetOutputList(output); // Rpc in LIMITED level policy_manager_->CheckPermissions(device_id_1_, application_id_, kHmiLevelLimited, ""SendLocation"", input_params, output); // Check RPC is allowed EXPECT_EQ(::policy::kRpcAllowed, output.hmi_level_permitted); ASSERT_TRUE(output.list_of_allowed_params.empty()); ResetOutputList(output); // Rpc in BACKGROUND level policy_manager_->CheckPermissions(device_id_1_, application_id_, kHmiLevelBackground, ""SendLocation"", input_params, output); // Check RPC is allowed EXPECT_EQ(::policy::kRpcAllowed, output.hmi_level_permitted); ASSERT_TRUE(output.list_of_allowed_params.empty()); ResetOutputList(output); // Rpc in NONE level policy_manager_->CheckPermissions(device_id_1_, application_id_, kHmiLevelNone, ""SendLocation"", input_params, output); // Check RPC is disallowed EXPECT_EQ(::policy::kRpcDisallowed, output.hmi_level_permitted); // Check list of parameters is empty ASSERT_TRUE(output.list_of_allowed_params.empty()); } TEST_F( PolicyManagerImplTest2, CheckPermissions_ParamsNotAllowedInPT_AddAppWithAllParams_CheckRpcsInDiffLvls) { EXPECT_CALL(listener_, GetDevicesIds(application_id_)) .WillRepeatedly(Return(transport_manager::DeviceList())); // Arrange AddSetDeviceData(); // File have empty parameters, so they are forbidden LoadPTUFromJsonFile(""json/sdl_update_pt_send_location_no_params.json""); // Check RPC in each level ::policy::RPCParams input_params; InsertRpcParametersInList(input_params); ::policy::CheckPermissionResult output; // Rpc in FULL level policy_manager_->CheckPermissions(device_id_1_, application_id_, kHmiLevelFull, ""SendLocation"", input_params, output); // Group which has RPC does not require user consent, so its auto-allowed for // user. Since RPC 'parameters' section is present, but empty, that means // 'every parameter is disallowed' in case some parameter(s) will be passed // it will be considered as disallowed by policy (assumption, will be // clarified). EXPECT_EQ(::policy::kRpcDisallowed, output.hmi_level_permitted); // Check list of allowed parameters is empty EXPECT_TRUE(output.list_of_allowed_params.empty()); EXPECT_EQ(10u, output.list_of_undefined_params.size()); ResetOutputList(output); // Rpc in LIMITED level policy_manager_->CheckPermissions(device_id_1_, application_id_, kHmiLevelLimited, ""SendLocation"", input_params, output); EXPECT_EQ(::policy::kRpcDisallowed, output.hmi_level_permitted); // Check list of allowed parameters is empty EXPECT_TRUE(output.list_of_allowed_params.empty()); EXPECT_EQ(10u, output.list_of_undefined_params.size()); ResetOutputList(output); // Rpc in BACKGROUND level policy_manager_->CheckPermissions(device_id_1_, application_id_, kHmiLevelBackground, ""SendLocation"", input_params, output); // Check RPC is allowed EXPECT_EQ(::policy::kRpcDisallowed, output.hmi_level_permitted); // Check list of allowed parameters is empty EXPECT_TRUE(output.list_of_allowed_params.empty()); EXPECT_EQ(10u, output.list_of_undefined_params.size()); // Reset output ResetOutputList(output); // Rpc in NONE level policy_manager_->CheckPermissions(device_id_1_, application_id_, kHmiLevelNone, ""SendLocation"", input_params, output); EXPECT_EQ(::policy::kRpcDisallowed, output.hmi_level_permitted); // Check lists of parameters are empty EXPECT_TRUE(output.list_of_allowed_params.empty()); EXPECT_TRUE(output.list_of_disallowed_params.empty()); EXPECT_TRUE(output.list_of_undefined_params.empty()); } TEST_F(PolicyManagerImplTest2, CheckPermissions_SomeParamsAllowedInPT_CheckRpcsInDiffLvls) { EXPECT_CALL(listener_, GetDevicesIds(application_id_)) .WillRepeatedly(Return(transport_manager::DeviceList())); // Arrange AddSetDeviceData(); // File have some parameters, so only ""longitudeDegrees"", ""latitudeDegrees"", //""locationDescription"", ""phoneNumber"" are allowed LoadPTUFromJsonFile(""json/sdl_update_pt_send_location_some_params.json""); // Check RPC in each level ::policy::RPCParams input_params; InsertRpcParametersInList(input_params); ::policy::CheckPermissionResult output; // Rpc in FULL level policy_manager_->CheckPermissions(device_id_1_, application_id_, kHmiLevelFull, ""SendLocation"", input_params, output); // Check RPC is allowed EXPECT_EQ(::policy::kRpcAllowed, output.hmi_level_permitted); // Check list of allowed parameters is not empty ASSERT_FALSE(output.list_of_allowed_params.empty()); // Check parameters that should be allowed CheckIsParamInList(output.list_of_allowed_params, ""longitudeDegrees""); CheckIsParamInList(output.list_of_allowed_params, ""latitudeDegrees""); CheckIsParamInList(output.list_of_allowed_params, ""locationDescription""); CheckIsParamInList(output.list_of_allowed_params, ""phoneNumber""); // Parameters that are missing in application assigned groups are considered // as disallowed by policy, i.e. w/o defined user consent, so they are put to // undefined container. ASSERT_FALSE(output.list_of_undefined_params.empty()); CheckIsParamInList(output.list_of_undefined_params, ""locationName""); CheckIsParamInList(output.list_of_undefined_params, ""addressLines""); CheckIsParamInList(output.list_of_undefined_params, ""locationImage""); CheckIsParamInList(output.list_of_undefined_params, ""deliveryMode""); CheckIsParamInList(output.list_of_undefined_params, ""timeStamp""); CheckIsParamInList(output.list_of_undefined_params, ""address""); // Reset output output.hmi_level_permitted = ::policy::kRpcDisallowed; output.list_of_allowed_params.clear(); output.list_of_undefined_params.clear(); // Rpc in LIMITED level policy_manager_->CheckPermissions(device_id_1_, application_id_, kHmiLevelLimited, ""SendLocation"", input_params, output); // Check RPC is allowed EXPECT_EQ(::policy::kRpcAllowed, output.hmi_level_permitted); // Check list of allowed parameters is not empty ASSERT_FALSE(output.list_of_allowed_params.empty()); // Check parameters that should be allowed CheckIsParamInList(output.list_of_allowed_params, ""longitudeDegrees""); CheckIsParamInList(output.list_of_allowed_params, ""latitudeDegrees""); CheckIsParamInList(output.list_of_allowed_params, ""locationDescription""); CheckIsParamInList(output.list_of_allowed_params, ""phoneNumber""); ASSERT_FALSE(output.list_of_undefined_params.empty()); EXPECT_EQ(6u, output.list_of_undefined_params.size()); // Reset output ResetOutputList(output); // Rpc in BACKGROUND level policy_manager_->CheckPermissions(device_id_1_, application_id_, kHmiLevelBackground, ""SendLocation"", input_params, output); // Check RPC is allowed EXPECT_EQ(::policy::kRpcAllowed, output.hmi_level_permitted); // Check parameters that should be allowed ASSERT_FALSE(output.list_of_allowed_params.empty()); CheckIsParamInList(output.list_of_allowed_params, ""longitudeDegrees""); CheckIsParamInList(output.list_of_allowed_params, ""latitudeDegrees""); CheckIsParamInList(output.list_of_allowed_params, ""locationDescription""); CheckIsParamInList(output.list_of_allowed_params, ""phoneNumber""); EXPECT_FALSE(output.list_of_undefined_params.empty()); // Reset output ResetOutputList(output); // Rpc in NONE level policy_manager_->CheckPermissions(device_id_1_, application_id_, kHmiLevelNone, ""SendLocation"", input_params, output); // Check RPC is disallowed EXPECT_EQ(::policy::kRpcDisallowed, output.hmi_level_permitted); // Check lists of parameters are empty EXPECT_TRUE(output.list_of_allowed_params.empty()); EXPECT_TRUE(output.list_of_disallowed_params.empty()); EXPECT_TRUE(output.list_of_undefined_params.empty()); } TEST_F(PolicyManagerImplTest2, GetUpdateUrl) { // Arrange CreateLocalPT(preloaded_pt_filename_); GetPTU(kValidSdlPtUpdateJson); // Check expectations const std::string update_url(""http://x.x.x.x:3000/api/1/policies""); EXPECT_EQ(update_url, policy_manager_->GetUpdateUrl(7)); EXPECT_EQ("""", policy_manager_->GetUpdateUrl(4)); } // Related to manual test APPLINK-18789 TEST_F(PolicyManagerImplTest2, GetCorrectStatus_PTUSuccessful) { // Precondition CreateLocalPT(preloaded_pt_filename_); // Check EXPECT_EQ(""UP_TO_DATE"", policy_manager_->GetPolicyTableStatus()); EXPECT_CALL(listener_, GetDevicesIds(application_id_)) .WillRepeatedly(Return(transport_manager::DeviceList())); // Adding changes PT status policy_manager_->AddApplication( device_id_1_, application_id_, HmiTypes(policy_table::AHT_DEFAULT)); EXPECT_EQ(""UP_TO_DATE"", policy_manager_->GetPolicyTableStatus()); // Before load PT we should send notification about start updating policy_manager_->OnUpdateStarted(); // Update GetPTU(kPtu3Json); EXPECT_EQ(""UP_TO_DATE"", policy_manager_->GetPolicyTableStatus()); } TEST_F(PolicyManagerImplTest2, CheckPermissions_NoParamsInPT_AddAppWithAllParams_CheckRpcsInDiffLvls) { // File does not have parameters, so they all are permitted CheckPermissions_AllParamsAllowed_CheckRpcsInDiffLvls( ""json/sdl_update_pt_send_location.json""); } TEST_F(PolicyManagerImplTest2, CheckPermissions_AllParamsAllowedInPT_CheckRpcsInDiffLvls) { // File has permissions for all params CheckPermissions_AllParamsAllowed_CheckRpcsInDiffLvls( ""json/sdl_update_pt_send_location_all_params.json""); } TEST_F(PolicyManagerImplTest2, CheckPermissions_DiffParamsAllowedInGroups_CheckRpcsInDiffLvls) { EXPECT_CALL(listener_, GetDevicesIds(application_id_)) .WillRepeatedly(Return(transport_manager::DeviceList())); // Arrange AddSetDeviceData(); // Load Json to cache // File have 2 functional groups: SendLocation and SendLocationOnly. // They have different parameters. // Allowed both groups of parameters LoadPTUFromJsonFile(""json/sdl_update_pt_2_groups_have_params.json""); // Check RPC in each level ::policy::RPCParams input_params; InsertRpcParametersInList(input_params); ::policy::CheckPermissionResult output; // Rpc in FULL level policy_manager_->CheckPermissions(device_id_1_, application_id_, kHmiLevelFull, ""SendLocation"", input_params, output); // Check RPC is allowed EXPECT_EQ(::policy::kRpcAllowed, output.hmi_level_permitted); // Check list of allowed parameters is not empty EXPECT_FALSE(output.list_of_allowed_params.empty()); EXPECT_EQ(7u, output.list_of_allowed_params.size()); // Check parameters that should be allowed CheckIsParamInList(output.list_of_allowed_params, ""longitudeDegrees""); CheckIsParamInList(output.list_of_allowed_params, ""latitudeDegrees""); CheckIsParamInList(output.list_of_allowed_params, ""locationDescription""); CheckIsParamInList(output.list_of_allowed_params, ""phoneNumber""); CheckIsParamInList(output.list_of_allowed_params, ""locationName""); CheckIsParamInList(output.list_of_allowed_params, ""locationImage""); CheckIsParamInList(output.list_of_allowed_params, ""deliveryMode""); EXPECT_TRUE(output.list_of_disallowed_params.empty()); ResetOutputList(output); // Rpc in LIMITED level policy_manager_->CheckPermissions(device_id_1_, application_id_, kHmiLevelLimited, ""SendLocation"", input_params, output); // Check RPC is allowed EXPECT_EQ(::policy::kRpcAllowed, output.hmi_level_permitted); // Check list of allowed parameters is not empty EXPECT_FALSE(output.list_of_allowed_params.empty()); EXPECT_EQ(7u, output.list_of_allowed_params.size()); // Check parameters that should be allowed CheckIsParamInList(output.list_of_allowed_params, ""longitudeDegrees""); CheckIsParamInList(output.list_of_allowed_params, ""latitudeDegrees""); CheckIsParamInList(output.list_of_allowed_params, ""locationDescription""); CheckIsParamInList(output.list_of_allowed_params, ""phoneNumber""); CheckIsParamInList(output.list_of_allowed_params, ""locationName""); CheckIsParamInList(output.list_of_allowed_params, ""locationImage""); CheckIsParamInList(output.list_of_allowed_params, ""deliveryMode""); EXPECT_TRUE(output.list_of_disallowed_params.empty()); ResetOutputList(output); // Rpc in BACKGROUND level policy_manager_->CheckPermissions(device_id_1_, application_id_, kHmiLevelBackground, ""SendLocation"", input_params, output); // Check RPC is allowed EXPECT_EQ(::policy::kRpcAllowed, output.hmi_level_permitted); // Check list of allowed parameters is not empty EXPECT_FALSE(output.list_of_allowed_params.empty()); EXPECT_EQ(7u, output.list_of_allowed_params.size()); // Check parameters that should be allowed CheckIsParamInList(output.list_of_allowed_params, ""longitudeDegrees""); CheckIsParamInList(output.list_of_allowed_params, ""latitudeDegrees""); CheckIsParamInList(output.list_of_allowed_params, ""locationDescription""); CheckIsParamInList(output.list_of_allowed_params, ""phoneNumber""); CheckIsParamInList(output.list_of_allowed_params, ""locationName""); CheckIsParamInList(output.list_of_allowed_params, ""locationImage""); CheckIsParamInList(output.list_of_allowed_params, ""deliveryMode""); EXPECT_TRUE(output.list_of_disallowed_params.empty()); // Reset output ResetOutputList(output); // Rpc in NONE level policy_manager_->CheckPermissions(device_id_1_, application_id_, kHmiLevelNone, ""SendLocation"", input_params, output); // Check RPC is disallowed EXPECT_EQ(::policy::kRpcDisallowed, output.hmi_level_permitted); // Check lists of parameters are empty EXPECT_TRUE(output.list_of_allowed_params.empty()); EXPECT_TRUE(output.list_of_disallowed_params.empty()); EXPECT_TRUE(output.list_of_undefined_params.empty()); } TEST_F(PolicyManagerImplTest2, CheckPermissions_ParamsAllowedInOneGroup_CheckRpcsInDiffLvls) { // Load Json to cache // File have 2 functional groups: SendLocation and SendLocationOnly. // They have different parameters. One has dissalowed all params, other - // allowed. // Arrange CreateLocalPT(""json/sdl_preloaded_pt_send_location.json""); policy_manager_->AddDevice(device_id_1_, ""Bluetooth""); policy::CacheManagerInterfaceSPtr cache = policy_manager_->GetCache(); ASSERT_TRUE(cache->SetDeviceData(device_id_1_, ""hardware IPX"", ""v.8.0.1"", ""Android"", ""4.4.2"", ""Life"", 2, ""Bluetooth"")); EXPECT_CALL(listener_, GetDevicesIds(application_id_)) .WillRepeatedly(Return(transport_manager::DeviceList())); // Add app from consented device. App will be assigned with default policies policy_manager_->SetUserConsentForDevice(device_id_1_, true); policy_manager_->AddApplication( device_id_1_, application_id_, HmiTypes(policy_table::AHT_DEFAULT)); std::ifstream ifile(""json/sdl_update_pt_2_groups_no_params_in1.json""); Json::Reader reader; std::string json; Json::Value root(Json::objectValue); if (ifile.is_open()) { reader.parse(ifile, root, true); } json = root.toStyledString(); ifile.close(); ::policy::BinaryMessage msg(json.begin(), json.end()); ASSERT_EQ(PolicyManager::PtProcessingResult::kSuccess, policy_manager_->LoadPT(kFilePtUpdateJson, msg)); policy_manager_->OnPTUFinished(PolicyManager::PtProcessingResult::kSuccess); EXPECT_FALSE(cache->IsPTPreloaded()); // Check RPC in each level ::policy::RPCParams input_params; InsertRpcParametersInList(input_params); ::policy::CheckPermissionResult output; // Rpc in FULL level policy_manager_->CheckPermissions(device_id_1_, application_id_, kHmiLevelFull, ""SendLocation"", input_params, output); EXPECT_EQ(::policy::kRpcAllowed, output.hmi_level_permitted); EXPECT_TRUE(output.list_of_undefined_params.empty()); EXPECT_EQ(10u, output.list_of_allowed_params.size()); ResetOutputList(output); // Rpc in LIMITED level policy_manager_->CheckPermissions(device_id_1_, application_id_, kHmiLevelLimited, ""SendLocation"", input_params, output); EXPECT_EQ(::policy::kRpcAllowed, output.hmi_level_permitted); EXPECT_TRUE(output.list_of_undefined_params.empty()); EXPECT_EQ(10u, output.list_of_allowed_params.size()); ResetOutputList(output); // Rpc in BACKGROUND level policy_manager_->CheckPermissions(device_id_1_, application_id_, kHmiLevelBackground, ""SendLocation"", input_params, output); EXPECT_EQ(::policy::kRpcAllowed, output.hmi_level_permitted); EXPECT_TRUE(output.list_of_undefined_params.empty()); EXPECT_EQ(10u, output.list_of_allowed_params.size()); // Reset output ResetOutputList(output); // Rpc in NONE level policy_manager_->CheckPermissions(device_id_1_, application_id_, kHmiLevelNone, ""SendLocation"", input_params, output); EXPECT_EQ(::policy::kRpcDisallowed, output.hmi_level_permitted); EXPECT_TRUE(output.list_of_allowed_params.empty()); EXPECT_TRUE(output.list_of_disallowed_params.empty()); } TEST_F(PolicyManagerImplTest2, CheckPermissions_ParamOmmittedInOneGroup_CheckRpcsInDiffLvls) { // Load Json to cache // File have 2 functional groups: SendLocation and SendLocationOnly. // They have different parameters. One has dissalowed all params, other - // omitted. // Arrange CreateLocalPT(""json/sdl_preloaded_pt_send_location.json""); policy_manager_->AddDevice(device_id_1_, ""Bluetooth""); policy::CacheManagerInterfaceSPtr cache = policy_manager_->GetCache(); ASSERT_TRUE(cache->SetDeviceData(device_id_1_, ""hardware IPX"", ""v.8.0.1"", ""Android"", ""4.4.2"", ""Life"", 2, ""Bluetooth"")); EXPECT_CALL(listener_, GetDevicesIds(application_id_)) .WillRepeatedly(Return(transport_manager::DeviceList())); // Add app from consented device. App will be assigned with default policies policy_manager_->SetUserConsentForDevice(device_id_1_, true); policy_manager_->AddApplication( device_id_1_, application_id_, HmiTypes(policy_table::AHT_DEFAULT)); std::ifstream ifile( ""json/sdl_update_pt_2_groups_no_params_in1_omitted_in2.json""); Json::Reader reader; std::string json; Json::Value root(Json::objectValue); if (ifile.is_open()) { reader.parse(ifile, root, true); } json = root.toStyledString(); ifile.close(); ::policy::BinaryMessage msg(json.begin(), json.end()); ASSERT_EQ(PolicyManager::PtProcessingResult::kSuccess, policy_manager_->LoadPT(kFilePtUpdateJson, msg)); policy_manager_->OnPTUFinished(PolicyManager::PtProcessingResult::kSuccess); EXPECT_FALSE(cache->IsPTPreloaded()); // Check RPC in each level ::policy::RPCParams input_params; InsertRpcParametersInList(input_params); ::policy::CheckPermissionResult output; // Rpc in FULL level policy_manager_->CheckPermissions(device_id_1_, application_id_, kHmiLevelFull, ""SendLocation"", input_params, output); EXPECT_EQ(::policy::kRpcAllowed, output.hmi_level_permitted); EXPECT_TRUE(output.list_of_undefined_params.empty()); EXPECT_EQ(10u, output.list_of_allowed_params.size()); ResetOutputList(output); // Rpc in LIMITED level policy_manager_->CheckPermissions(device_id_1_, application_id_, kHmiLevelLimited, ""SendLocation"", input_params, output); EXPECT_EQ(::policy::kRpcAllowed, output.hmi_level_permitted); EXPECT_TRUE(output.list_of_undefined_params.empty()); EXPECT_EQ(10u, output.list_of_allowed_params.size()); ResetOutputList(output); // Rpc in BACKGROUND level policy_manager_->CheckPermissions(device_id_1_, application_id_, kHmiLevelBackground, ""SendLocation"", input_params, output); EXPECT_EQ(::policy::kRpcAllowed, output.hmi_level_permitted); EXPECT_TRUE(output.list_of_undefined_params.empty()); EXPECT_EQ(10u, output.list_of_allowed_params.size()); // Reset output ResetOutputList(output); // Rpc in NONE level policy_manager_->CheckPermissions(device_id_1_, application_id_, kHmiLevelNone, ""SendLocation"", input_params, output); EXPECT_EQ(::policy::kRpcDisallowed, output.hmi_level_permitted); EXPECT_TRUE(output.list_of_allowed_params.empty()); EXPECT_TRUE(output.list_of_disallowed_params.empty()); EXPECT_TRUE(output.list_of_undefined_params.empty()); } TEST_F(PolicyManagerImplTest, LoadPT_SetInvalidUpdatePT_PTIsNotLoaded) { // Arrange policy_manager_->ForcePTExchange(); policy_manager_->OnUpdateStarted(); Json::Value table(Json::objectValue); policy_table::Table update(&table); update.SetPolicyTableType(rpc::policy_table_interface_base::PT_UPDATE); // Assert update is invalid ASSERT_FALSE(IsValid(update)); // Act std::string json = table.toStyledString(); ::policy::BinaryMessage msg(json.begin(), json.end()); auto pt = std::make_shared(); *pt = update; // Assert EXPECT_CALL(*cache_manager_, ApplyUpdate(_)).Times(0); EXPECT_CALL(listener_, GetAppName(_)).Times(0); EXPECT_CALL(*cache_manager_, SaveUpdateRequired(false)).Times(0); EXPECT_CALL(*cache_manager_, TimeoutResponse()).Times(0); EXPECT_CALL(*cache_manager_, SecondsBetweenRetries(_)).Times(0); EXPECT_CALL(*cache_manager_, GetVehicleDataItems()) .WillOnce(Return(std::vector())); ASSERT_EQ(PolicyManager::PtProcessingResult::kWrongPtReceived, policy_manager_->LoadPT(kFilePtUpdateJson, msg)); EXPECT_CALL(*cache_manager_, IsPTPreloaded()); EXPECT_FALSE(policy_manager_->GetCache()->IsPTPreloaded()); EXPECT_CALL(listener_, OnUpdateStatusChanged(_)).Times(1); policy_manager_->OnPTUFinished( PolicyManager::PtProcessingResult::kWrongPtReceived); } TEST_F( PolicyManagerImplTest2, AddApplication_AddExistingApplicationFromDeviceWithoutConsent_ExpectNoUpdateRequired) { // Arrange CreateLocalPT(preloaded_pt_filename_); EXPECT_EQ(""UP_TO_DATE"", policy_manager_->GetPolicyTableStatus()); GetPTU(kValidSdlPtUpdateJson); EXPECT_EQ(""UP_TO_DATE"", policy_manager_->GetPolicyTableStatus()); // Try to add existing app policy_manager_->AddApplication( device_id_1_, app_id_2_, HmiTypes(policy_table::AHT_DEFAULT)); // Check no update required EXPECT_EQ(""UP_TO_DATE"", policy_manager_->GetPolicyTableStatus()); } uint32_t GetCurrentDaysCount() { date_time::TimeDuration current_time = date_time::getCurrentTime(); const uint32_t kSecondsInDay = 60 * 60 * 24; return date_time::getSecs(current_time) / kSecondsInDay; } TEST_F(PolicyManagerImplTest2, PTUpdatedAt_DaysNotExceedLimit_ExpectNoUpdateRequired) { // Arrange CreateLocalPT(preloaded_pt_filename_); const uint32_t days = GetCurrentDaysCount(); EXPECT_EQ(""UP_TO_DATE"", policy_manager_->GetPolicyTableStatus()); GetPTU(kValidSdlPtUpdateJson); EXPECT_EQ(""UP_TO_DATE"", policy_manager_->GetPolicyTableStatus()); policy_manager_->AddApplication( device_id_2_, app_id_2_, HmiTypes(policy_table::AHT_DEFAULT)); EXPECT_EQ(""UP_TO_DATE"", policy_manager_->GetPolicyTableStatus()); ::policy::Counters counter = ::policy::Counters::DAYS_AFTER_EPOCH; // Set PT was updated 10 days ago (limit is 30 days for now) // So no limit exceeded policy_manager_->PTUpdatedAt(counter, days - 10); policy_manager_->OnAppRegisteredOnMobile(device_id_2_, app_id_2_); EXPECT_EQ(""UP_TO_DATE"", policy_manager_->GetPolicyTableStatus()); } TEST_F(PolicyManagerImplTest2, PTUpdatedAt_DaysExceedLimit_ExpectUpdateRequired) { // Arrange CreateLocalPT(preloaded_pt_filename_); const uint32_t days = GetCurrentDaysCount(); EXPECT_EQ(""UP_TO_DATE"", policy_manager_->GetPolicyTableStatus()); GetPTU(kValidSdlPtUpdateJson); EXPECT_EQ(""UP_TO_DATE"", policy_manager_->GetPolicyTableStatus()); policy_manager_->AddApplication( device_id_2_, app_id_2_, HmiTypes(policy_table::AHT_DEFAULT)); EXPECT_EQ(""UP_TO_DATE"", policy_manager_->GetPolicyTableStatus()); ::policy::Counters counter = ::policy::Counters::DAYS_AFTER_EPOCH; // Set PT was updated 50 days ago (limit is 30 days for now) policy_manager_->PTUpdatedAt(counter, days - 50); policy_manager_->OnAppRegisteredOnMobile(device_id_2_, app_id_2_); EXPECT_EQ(""UPDATE_NEEDED"", policy_manager_->GetPolicyTableStatus()); } TEST_F( PolicyManagerImplTest2, OnIgnitionCyclesExceeded_SetExceededIgnitionCycles_ExpectUpdateScheduled) { // Arrange CreateLocalPT(preloaded_pt_filename_); const uint32_t days = GetCurrentDaysCount(); EXPECT_EQ(""UP_TO_DATE"", policy_manager_->GetPolicyTableStatus()); GetPTU(kValidSdlPtUpdateJson); EXPECT_EQ(""UP_TO_DATE"", policy_manager_->GetPolicyTableStatus()); // Try to add existing app policy_manager_->AddApplication( device_id_2_, app_id_2_, HmiTypes(policy_table::AHT_DEFAULT)); EXPECT_EQ(""UP_TO_DATE"", policy_manager_->GetPolicyTableStatus()); ::policy::Counters counter = ::policy::Counters::DAYS_AFTER_EPOCH; // Set PT was updated 10 days ago (limit is 30 days for now) // So no limit exceeded policy_manager_->PTUpdatedAt(counter, days - 10); int ign_cycles = (policy_manager_->GetCache())->IgnitionCyclesBeforeExchange(); // Set ignition cycles to value = 99 (limit is 100 which initiates auto // PTExchange) for (int i = 0; i < ign_cycles; ++i) { policy_manager_->IncrementIgnitionCycles(); } policy_manager_->OnAppRegisteredOnMobile(device_id_2_, app_id_2_); // Check update required EXPECT_EQ(""UPDATE_NEEDED"", policy_manager_->GetPolicyTableStatus()); } TEST_F(PolicyManagerImplTest2, GetUserConsentForApp_SetUserConsentForApp_ExpectReceivedConsentCorrect) { // Arrange CreateLocalPT(preloaded_pt_filename_); ASSERT_TRUE( (policy_manager_->GetCache())->AddDevice(device_id_2_, ""Bluetooth"")); ASSERT_TRUE((policy_manager_->GetCache()) ->SetDeviceData(device_id_2_, ""hardware IPX"", ""v.8.0.1"", ""Android"", ""4.4.2"", ""Life"", 2, ""Bluetooth"")); ::policy::StringArray consented_groups; ::policy::StringArray disallowed_groups; consented_groups.push_back(std::string(""Notifications"")); consented_groups.push_back(std::string(""Notifications"")); (policy_manager_->GetCache()) ->SetUserPermissionsForDevice( device_id_2_, consented_groups, disallowed_groups); policy_manager_->SetUserConsentForDevice(device_id_2_, true); EXPECT_CALL(listener_, GetDevicesIds(app_id_2_)) .WillRepeatedly(Return(transport_manager::DeviceList())); policy_manager_->AddApplication( device_id_2_, app_id_2_, HmiTypes(policy_table::AHT_DEFAULT)); GetPTU(kValidSdlPtUpdateJson); ::policy::PermissionConsent perm_consent; perm_consent.device_id = device_id_2_; perm_consent.policy_app_id = app_id_2_; perm_consent.consent_source = ""VR""; ::policy::FunctionalGroupPermission group1_perm; group1_perm.group_alias = ""Notifications""; group1_perm.group_name = ""Notifications""; group1_perm.group_id = ::utils::Djb2HashFromString(""Notifications""); group1_perm.state = ::policy::GroupConsent::kGroupAllowed; std::vector< ::policy::FunctionalGroupPermission> groups_permissions; groups_permissions.push_back(group1_perm); perm_consent.group_permissions = groups_permissions; policy_manager_->SetUserConsentForApp(perm_consent, policy::PolicyManager::kSilentMode); policy_manager_->SendNotificationOnPermissionsUpdated(device_id_2_, app_id_2_); std::vector< ::policy::FunctionalGroupPermission> actual_groups_permissions; std::vector< ::policy::FunctionalGroupPermission>::iterator it; policy_manager_->GetUserConsentForApp( device_id_2_, app_id_2_, actual_groups_permissions); uint32_t index = 0; for (; index < actual_groups_permissions.size(); ++index) { if (actual_groups_permissions[index].group_id == group1_perm.group_id) { break; } } // Check EXPECT_EQ(group1_perm.group_alias, actual_groups_permissions[index].group_alias); EXPECT_EQ(group1_perm.group_name, actual_groups_permissions[index].group_name); EXPECT_EQ(group1_perm.group_id, actual_groups_permissions[index].group_id); EXPECT_EQ(group1_perm.state, actual_groups_permissions[index].state); } TEST_F(PolicyManagerImplTest2, CanAppKeepContext_SetPoliciesForAppUpdated_ExpectAppCanKeepContext) { // Arrange CreateLocalPT(preloaded_pt_filename_); EXPECT_CALL(listener_, GetDevicesIds(app_id_2_)) .WillRepeatedly(Return(transport_manager::DeviceList())); policy_manager_->AddApplication( device_id_2_, app_id_2_, HmiTypes(policy_table::AHT_DEFAULT)); GetPTU(kValidSdlPtUpdateJson); // Check keep context in updated policies for app EXPECT_TRUE(policy_manager_->CanAppKeepContext(app_id_2_)); } TEST_F(PolicyManagerImplTest2, CanAppStealFocus_SetPoliciesForAppUpdated_ExpectAppCanStealFocus) { // Arrange CreateLocalPT(preloaded_pt_filename_); EXPECT_CALL(listener_, GetDevicesIds(app_id_2_)) .WillRepeatedly(Return(transport_manager::DeviceList())); policy_manager_->AddApplication( device_id_2_, app_id_2_, HmiTypes(policy_table::AHT_DEFAULT)); GetPTU(kValidSdlPtUpdateJson); // Check keep context in updated policies for app EXPECT_TRUE(policy_manager_->CanAppKeepContext(app_id_2_)); } TEST_F( PolicyManagerImplTest2, GetPermissionsForApp_SetUserConsentForApp_ExpectReceivedPermissionsCorrect) { // Arrange CreateLocalPT(preloaded_pt_filename_); ASSERT_TRUE( (policy_manager_->GetCache())->AddDevice(device_id_2_, ""Bluetooth"")); ASSERT_TRUE((policy_manager_->GetCache()) ->SetDeviceData(device_id_2_, ""hardware IPX"", ""v.8.0.1"", ""Android"", ""4.4.2"", ""Life"", 2, ""Bluetooth"")); ::policy::StringArray consented_groups; ::policy::StringArray disallowed_groups; consented_groups.push_back(std::string(""Notifications"")); (policy_manager_->GetCache()) ->SetUserPermissionsForDevice( device_id_2_, consented_groups, disallowed_groups); policy_manager_->SetUserConsentForDevice(device_id_2_, true); EXPECT_CALL(listener_, GetDevicesIds(app_id_2_)) .WillRepeatedly(Return(transport_manager::DeviceList(1, device_id_2_))); policy_manager_->AddApplication( device_id_2_, app_id_2_, HmiTypes(policy_table::AHT_DEFAULT)); GetPTU(kValidSdlPtUpdateJson); ::policy::PermissionConsent perm_consent; perm_consent.device_id = device_id_2_; perm_consent.policy_app_id = app_id_2_; perm_consent.consent_source = ""VR""; ::policy::FunctionalGroupPermission group1_perm; group1_perm.group_alias = ""Notifications""; group1_perm.group_name = ""Notifications""; group1_perm.group_id = ::utils::Djb2HashFromString(""Notifications""); group1_perm.state = ::policy::GroupConsent::kGroupAllowed; std::vector< ::policy::FunctionalGroupPermission> groups_permissions; groups_permissions.push_back(group1_perm); perm_consent.group_permissions = groups_permissions; policy_manager_->SetUserConsentForApp(perm_consent, policy::PolicyManager::kSilentMode); policy_manager_->SendNotificationOnPermissionsUpdated(device_id_2_, app_id_2_); std::vector< ::policy::FunctionalGroupPermission> actual_groups_permissions; std::vector< ::policy::FunctionalGroupPermission>::iterator it; policy_manager_->GetPermissionsForApp( device_id_2_, app_id_2_, actual_groups_permissions); uint32_t index = 0; for (; index < actual_groups_permissions.size(); ++index) { if (actual_groups_permissions[index].group_id == group1_perm.group_id) { break; } } // Check EXPECT_EQ(group1_perm.group_alias, actual_groups_permissions[index].group_alias); EXPECT_EQ(group1_perm.group_name, actual_groups_permissions[index].group_name); EXPECT_EQ(group1_perm.group_id, actual_groups_permissions[index].group_id); EXPECT_EQ(group1_perm.state, actual_groups_permissions[index].state); } TEST_F( PolicyManagerImplTest2, GetAppRequestTypes_AddApp_UpdateAppPolicies_ExpectReceivedRequestTypesCorrect) { // Arrange const transport_manager::DeviceHandle handle = 1; CreateLocalPT(preloaded_pt_filename_); EXPECT_CALL(listener_, GetDevicesIds(app_id_3_)) .WillRepeatedly(Return(transport_manager::DeviceList(1, device_id_1_))); EXPECT_CALL(listener_, OnCurrentDeviceIdUpdateRequired(handle, app_id_3_)) .WillRepeatedly(Return(device_id_1_)); policy_manager_->AddApplication( device_id_1_, app_id_3_, HmiTypes(policy_table::AHT_DEFAULT)); ::policy::StringArray app_requests = policy_manager_->GetAppRequestTypes(handle, app_id_3_); EXPECT_EQ(1u, app_requests.size()); Json::Value root = GetPTU(kPtuRequestTypeJson); Json::Value request_Types = Json::Value(Json::arrayValue); request_Types = root[""policy_table""][""app_policies""][app_id_3_][""RequestType""]; app_requests = policy_manager_->GetAppRequestTypes(handle, app_id_3_); EXPECT_EQ(request_Types.size(), app_requests.size()); // Check nicknames match for (uint32_t i = 0; i < request_Types.size(); ++i) { EXPECT_EQ(request_Types[i], app_requests[i]); } } TEST_F( PolicyManagerImplTest2, HertBeatTimeout_AddApp_UpdateAppPolicies_ExpectReceivedHertBeatTimeoutCorrect) { // Arrange CreateLocalPT(preloaded_pt_filename_); std::shared_ptr pt = (policy_manager_->GetCache())->GetPT(); ::policy_table::PolicyTableType type1 = ::policy_table::PolicyTableType::PT_PRELOADED; pt->SetPolicyTableType(type1); if (!pt->is_valid()) { std::cout << ""\\nPolicy table is not valid."" << ""\\n""; rpc::ValidationReport report(""policy_table""); pt->ReportErrors(&report); } EXPECT_CALL(listener_, GetDevicesIds(app_id_2_)) .WillRepeatedly(Return(transport_manager::DeviceList())); // Add new app policy_manager_->AddApplication( device_id_2_, app_id_2_, HmiTypes(policy_table::AHT_DEFAULT)); uint32_t result = policy_manager_->HeartBeatTimeout(app_id_2_); // By default hertbeat timeout is 0 EXPECT_EQ(0u, result); Json::Value root = GetPTU(kValidSdlPtUpdateJson); ::policy_table::PolicyTableType type2 = ::policy_table::PolicyTableType::PT_UPDATE; pt->SetPolicyTableType(type2); if (!pt->is_valid()) { std::cout << ""\\nPolicy table is not valid."" << ""\\n""; rpc::ValidationReport report(""policy_table""); pt->ReportErrors(&report); } Json::Value heart_beat_timeout = Json::Value(Json::uintValue); heart_beat_timeout = root[""policy_table""][""app_policies""][app_id_2_][""heart_beat_timeout_ms""]; result = policy_manager_->HeartBeatTimeout(app_id_2_); EXPECT_EQ(heart_beat_timeout.asUInt(), result); } TEST_F(PolicyManagerImplTest2, RemoveAppConsentForGroup_SetUserConsentForApp_ExpectAppConsentDeleted) { // Arrange CreateLocalPT(preloaded_pt_filename_); ASSERT_TRUE( (policy_manager_->GetCache())->AddDevice(device_id_2_, ""Bluetooth"")); ASSERT_TRUE((policy_manager_->GetCache()) ->SetDeviceData(device_id_2_, ""hardware IPX"", ""v.8.0.1"", ""Android"", ""4.4.2"", ""Life"", 2, ""Bluetooth"")); ::policy::StringArray consented_groups; ::policy::StringArray disallowed_groups; consented_groups.push_back(std::string(""Notifications"")); (policy_manager_->GetCache()) ->SetUserPermissionsForDevice( device_id_2_, consented_groups, disallowed_groups); policy_manager_->SetUserConsentForDevice(device_id_2_, true); EXPECT_CALL(listener_, GetDevicesIds(app_id_2_)) .WillRepeatedly(Return(transport_manager::DeviceList(1, device_id_2_))); policy_manager_->AddApplication( device_id_2_, app_id_2_, HmiTypes(policy_table::AHT_DEFAULT)); GetPTU(kValidSdlPtUpdateJson); ::policy::PermissionConsent perm_consent; perm_consent.device_id = device_id_2_; perm_consent.policy_app_id = app_id_2_; perm_consent.consent_source = ""VR""; ::policy::FunctionalGroupPermission group1_perm; group1_perm.group_alias = ""Notifications""; group1_perm.group_name = ""Notifications""; group1_perm.group_id = ::utils::Djb2HashFromString(""Notifications""); group1_perm.state = ::policy::GroupConsent::kGroupAllowed; std::vector< ::policy::FunctionalGroupPermission> groups_permissions; groups_permissions.push_back(group1_perm); perm_consent.group_permissions = groups_permissions; policy_manager_->SetUserConsentForApp(perm_consent, policy::PolicyManager::kSilentMode); policy_manager_->SendNotificationOnPermissionsUpdated(device_id_2_, app_id_2_); std::vector< ::policy::FunctionalGroupPermission> actual_groups_permissions; std::vector< ::policy::FunctionalGroupPermission>::iterator it; policy_manager_->GetPermissionsForApp( device_id_2_, app_id_2_, actual_groups_permissions); uint32_t index = 0; for (; index < actual_groups_permissions.size(); ++index) { if (actual_groups_permissions[index].group_id == group1_perm.group_id) { break; } } // Check EXPECT_EQ(group1_perm.group_alias, actual_groups_permissions[index].group_alias); EXPECT_EQ(group1_perm.group_name, actual_groups_permissions[index].group_name); EXPECT_EQ(group1_perm.group_id, actual_groups_permissions[index].group_id); EXPECT_EQ(group1_perm.state, actual_groups_permissions[index].state); std::shared_ptr pt = (policy_manager_->GetCache())->GetPT(); uint32_t ucr_size = 0; ::policy_table::DeviceData& device_data = *pt->policy_table.device_data; ::policy_table::DeviceData::const_iterator dev_data_iter = device_data.find(device_id_2_); if (dev_data_iter != device_data.end()) { const ::policy_table::DeviceParams& dev_params = dev_data_iter->second; const ::policy_table::UserConsentRecords& ucr = *(dev_params.user_consent_records); ucr_size = ucr.size(); ASSERT_GT(ucr_size, 0u); ::policy_table::UserConsentRecords::const_iterator ucr_iter = ucr.find(app_id_2_); if (ucr_iter != ucr.end()) { EXPECT_TRUE((*(ucr_iter->second.consent_groups)).find(""Notifications"") != (*(ucr_iter->second.consent_groups)).end()); policy_manager_->RemoveAppConsentForGroup(app_id_2_, ""Notifications""); EXPECT_TRUE((*(ucr_iter->second.consent_groups)).find(""Notifications"") == (*(ucr_iter->second.consent_groups)).end()); } } } TEST_F(PolicyManagerImplTest2, SingleInvalidRequestTypeInPTU_ExpectReplaceWithDefaultValues) { // Arrange const std::string section_name = app_id_2_; const transport_manager::DeviceHandle handle = 1; // Arrange CreateLocalPT(preloaded_pt_filename_); // Setting device consent to 'true' in order to have defult application // permissions, request type etc. EXPECT_CALL(listener_, OnCurrentDeviceIdUpdateRequired(handle, app_id_2_)) .WillRepeatedly(Return(device_id_1_)); policy_manager_->SetUserConsentForDevice(device_id_1_, true); EXPECT_CALL(listener_, GetDevicesIds(section_name)) .WillRepeatedly(Return(transport_manager::DeviceList(1, device_id_1_))); // Add app policy_manager_->AddApplication( device_id_1_, section_name, HmiTypes(policy_table::AHT_DEFAULT)); EXPECT_CALL(listener_, OnPendingPermissionChange(device_id_1_, section_name)); // PTU has single invalid RequestTypes, which must be dropped and replaced // with default RT GetPTU(""json/PTU_with_one_invalid_requestType.json""); // Get RequestTypes from section of app policies after PT update ::policy::StringArray app_request_types_after = policy_manager_->GetAppRequestTypes(handle, section_name); EXPECT_CALL(listener_, OnCurrentDeviceIdUpdateRequired(handle, kDefaultId)) .WillOnce(Return(device_id_1_)); ::policy::StringArray default_request_types_after = policy_manager_->GetAppRequestTypes(handle, kDefaultId); // Check sizes of Request types of PT and PTU EXPECT_EQ(4u, app_request_types_after.size()); ::policy::AppPermissions permissions = policy_manager_->GetAppPermissionsChanges(device_id_1_, section_name); EXPECT_TRUE(permissions.requestTypeChanged); policy_table::RequestType temp_res1; std::vector result1; for (uint32_t i = 0; i < app_request_types_after.size(); ++i) { if (::rpc::policy_table_interface_base::EnumFromJsonString( app_request_types_after[i], &temp_res1)) { result1.push_back(temp_res1); } } policy_table::RequestType temp_res2; std::vector result2; for (size_t i = 0; i < default_request_types_after.size(); ++i) { if (::rpc::policy_table_interface_base::EnumFromJsonString( default_request_types_after[i], &temp_res2)) { result2.push_back(temp_res2); } } ASSERT_EQ(result1.size(), result2.size()); std::sort(result1.begin(), result1.end()); std::sort(result2.begin(), result2.end()); // Checks EXPECT_TRUE(std::equal(result1.begin(), result1.end(), result2.begin())); } TEST_F(PolicyManagerImplTest2, InitPT_LoadPT_ExpectIncrementedCountOfSamePrompts) { // Initializing policy_table CreateLocalPT(preloaded_pt_filename_); policy_table::FunctionalGroupings functional_groupings; GetFunctionalGroupingsFromManager(functional_groupings); UserConsentPromptToRpcsConnections initial_functional_groupings_map; UserConsentPromptToRpcsConnections updated_functional_groupings_map; // Filling initial map FillMultimapFromFunctionalGroupings(initial_functional_groupings_map, functional_groupings); // Updating policy_table GetPTU(""json/sdl_pt_update.json""); policy_table::FunctionalGroupings updated_functional_groupings; GetFunctionalGroupingsFromManager(updated_functional_groupings); // Filling updated map FillMultimapFromFunctionalGroupings(updated_functional_groupings_map, updated_functional_groupings); // Comparing two multimaps // (EXPECT increment count of functionalgroups // under key : user_consent_prompt) uint32_t count_before_update = initial_functional_groupings_map.count(""Notifications""); uint32_t count_after_update = updated_functional_groupings_map.count(""Notifications""); EXPECT_EQ(1u, count_before_update); EXPECT_EQ(2u, count_after_update); } TEST_F(PolicyManagerImplTest2, LoadPT_UpdatePT_ChangingCountsOfDifferentUserConsentPrompts) { // Initializing policy_table CreateLocalPT(preloaded_pt_filename_); // First update of policy table GetPTU(""json/sdl_pt_first_update.json""); // Geting functional groupings first time policy_table::FunctionalGroupings first_functional_groupings; GetFunctionalGroupingsFromManager(first_functional_groupings); // Filling map first time UserConsentPromptToRpcsConnections first_update_functional_groupings_map; FillMultimapFromFunctionalGroupings(first_update_functional_groupings_map, first_functional_groupings); // Second update of policy table GetPTU(""json/sdl_pt_second_update.json""); // Geting functional groupings second time policy_table::FunctionalGroupings second_functional_groupings; GetFunctionalGroupingsFromManager(second_functional_groupings); // Filling map second time UserConsentPromptToRpcsConnections second_update_functional_groupings_map; FillMultimapFromFunctionalGroupings(second_update_functional_groupings_map, second_functional_groupings); // Getting counts before second update uint32_t first_count_of_old_user_consent_prompt = first_update_functional_groupings_map.count(""Old_Notifications""); uint32_t first_count_of_new_user_consent_prompt = first_update_functional_groupings_map.count(""New_Notifications""); // Getting counts after second update uint32_t second_count_of_old_user_consent_prompt = second_update_functional_groupings_map.count(""Old_Notifications""); uint32_t second_count_of_new_user_consent_prompt = second_update_functional_groupings_map.count(""New_Notifications""); // Expect decrement count of old user_consent_prormpt EXPECT_GT(first_count_of_old_user_consent_prompt, second_count_of_old_user_consent_prompt); // Expect increment count of new user_consent_prormpt EXPECT_LT(first_count_of_new_user_consent_prompt, second_count_of_new_user_consent_prompt); } TEST_F(PolicyManagerImplTest_RequestTypes, LoadPT_PTWithOneInvalidRequestTypeValue_RequestTypeValueEQToDefault) { // Logic in another function CompareAppRequestTypesWithDefault(kAppId, kJsonFiles[0]); } TEST_F(PolicyManagerImplTest_RequestTypes, LoadPT_InvalidRequestTypeBetweenCorectValuesInPTU_EraseInvalidValue) { // Refresh policy table with invalid RequestType in application RefreshPT(preloaded_pt_filename_, kJsonFiles[1]); // Correct of Request Types policy_table::RequestTypes correct_types; correct_types.push_back(policy_table::RequestType::RT_HTTP); correct_types.push_back(policy_table::RequestType::RT_LAUNCH_APP); correct_types.push_back(policy_table::RequestType::RT_PROPRIETARY); // Get Request Types policy_table::RequestTypes received_types = GetRequestTypesForApplication(kAppId); CompareRequestTypesContainers(correct_types, received_types); } TEST_F( PolicyManagerImplTest_RequestTypes, LoadPT_AppInUpdateFileHaventRequestTypeField_RequestTypeValueEQToDefault) { // Logic in another function CompareAppRequestTypesWithDefault(kAppId, kJsonFiles[2]); } TEST_F(PolicyManagerImplTest_RequestTypes, LoadPT_RequestTypeArrayHaveNoOneValues_AvalibleAllRequestTypes) { // Refresh policy table with invalid RequestType in application RefreshPT(preloaded_pt_filename_, kJsonFiles[3]); // Get Request Types policy_table::RequestTypes received_types = GetRequestTypesForApplication(kAppId); // Expect const size_t correct_size = 0; const size_t received_size = received_types.size(); EXPECT_EQ(correct_size, received_size); } TEST_F(PolicyManagerImplTest_RequestTypes, InitPT_DefaultRequestTypeHaveOneInvalidValue_False) { // PT have only invalid value in app_policies::default::RequestType ON_CALL(policy_settings_, app_storage_folder()) .WillByDefault(ReturnRef(app_storage_folder_)); ASSERT_FALSE( policy_manager_impl_sptr_->InitPT(kJsonFiles[4], &policy_settings_)); // Invalid table data with pt_preloaded=true EXPECT_TRUE(policy_manager_impl_sptr_->GetCache()->IsPTPreloaded()); } TEST_F(PolicyManagerImplTest_RequestTypes, InitPT_DefaultRequestTypeHaveSeveralInvalidValues_False) { // PT have several only invalid values in app_policies::default::RequestType ON_CALL(policy_settings_, app_storage_folder()) .WillByDefault(ReturnRef(app_storage_folder_)); ASSERT_FALSE( policy_manager_impl_sptr_->InitPT(kJsonFiles[5], &policy_settings_)); // Invalid table data with pt_preloaded=true EXPECT_TRUE(policy_manager_impl_sptr_->GetCache()->IsPTPreloaded()); } TEST_F(PolicyManagerImplTest_RequestTypes, InitPT_DefaultRequestTypeHaveInvalidValueBetweenCorrect_True) { // PT have [""QUERY_APPS"", ""IVSU"", ""PROPRIETARY""] // In app_policies::default::RequestType ON_CALL(policy_settings_, app_storage_folder()) .WillByDefault(ReturnRef(app_storage_folder_)); ASSERT_TRUE( policy_manager_impl_sptr_->InitPT(kJsonFiles[6], &policy_settings_)); EXPECT_TRUE(policy_manager_impl_sptr_->GetCache()->IsPTPreloaded()); // Correct of Request Types policy_table::RequestTypes correct_types; correct_types.push_back(policy_table::RequestType::RT_QUERY_APPS); correct_types.push_back(policy_table::RequestType::RT_PROPRIETARY); // Get default Request Types policy_table::RequestTypes received_types = GetRequestTypesForApplication(kDefaultAppId); CompareRequestTypesContainers(correct_types, received_types); } TEST_F(PolicyManagerImplTest_RequestTypes, LoadPT_PTDefaultApp_RequestTypeValueEQToUpdate) { // Base values of Request Types policy_table::RequestTypes correct_types = CreateDefaultAppPTURequestValues(); // Load valid values for RequestType RefreshPT(preloaded_pt_filename_, kJsonFiles[7]); // Get Request Types for """" policy_table::RequestTypes received_types = GetRequestTypesForApplication(policy::kDefaultId); CompareRequestTypesContainers(correct_types, received_types); } TEST_F( PolicyManagerImplTest_RequestTypes, LoadPT_PTDefaultAppInvalidRequestTypeValues_RequestTypeValueEQToDatabase) { // Base values of Request Types policy_table::RequestTypes correct_types = CreateDefaultAppDatabaseRequestValues(); // Load RequestType with invalid values RefreshPT(preloaded_pt_filename_, kJsonFiles[8]); // Get Request Types for """" policy_table::RequestTypes received_types = GetRequestTypesForApplication(policy::kDefaultId); CompareRequestTypesContainers(correct_types, received_types); } TEST_F(PolicyManagerImplTest_RequestTypes, LoadPT_PTDefaultAppEmptyRequestTypeValues_RequestTypeValueEmpty) { // Load RequestType with empty values RefreshPT(preloaded_pt_filename_, kJsonFiles[9]); // Get Request Types for """" policy_table::RequestTypes received_types = GetRequestTypesForApplication(policy::kDefaultId); // Expect const size_t received_size = received_types.size(); EXPECT_EQ(0u, received_size); } TEST_F(PolicyManagerImplTest_RequestTypes, LoadPT_PTDefaultAppOmittedRequestType_RequestTypeValueEQToDatabase) { // Base values of Request Types policy_table::RequestTypes correct_types = CreateDefaultAppDatabaseRequestValues(); // Load omitted RequestType values RefreshPT(preloaded_pt_filename_, kJsonFiles[10]); // Get Request Types for """" policy_table::RequestTypes received_types = GetRequestTypesForApplication(policy::kDefaultId); CompareRequestTypesContainers(correct_types, received_types); } TEST_F( PolicyManagerImplTest_RequestTypes, LoadPT_PTDefaultAppOneInvalidRequestTypeValue_RequestTypeValueEQValidPT) { // Update values of Request Types policy_table::RequestTypes correct_types = CreateDefaultAppPTURequestValues(); // Load RequestType with one invalid value RefreshPT(preloaded_pt_filename_, kJsonFiles[11]); // Get Request Types for """" policy_table::RequestTypes received_types = GetRequestTypesForApplication(policy::kDefaultId); CompareRequestTypesContainers(correct_types, received_types); } TEST_F(PolicyManagerImplTest_RequestTypes, LoadPT_PTPreDataConsentApp_RequestTypeValueEQToUpdate) { // Update values of Request Types policy_table::RequestTypes correct_types = CreatePreDataConsentAppPTURequestValues(); // Load valid values for RequestType RefreshPT(preloaded_pt_filename_, kJsonFiles[12]); // Get Request Types for """" policy_table::RequestTypes received_types = GetRequestTypesForApplication(policy::kPreDataConsentId); CompareRequestTypesContainers(correct_types, received_types); } TEST_F( PolicyManagerImplTest_RequestTypes, LoadPT_PTPreDataConsentAppInvalidRequestTypeValues_RequestTypeValueEQToDatabase) { // Update values of Request Types policy_table::RequestTypes correct_types; correct_types.push_back(policy_table::RequestType::RT_HTTP); // Load RequestType with invalid values RefreshPT(preloaded_pt_filename_, kJsonFiles[13]); // Get Request Types for """" policy_table::RequestTypes received_types = GetRequestTypesForApplication(policy::kPreDataConsentId); CompareRequestTypesContainers(correct_types, received_types); } TEST_F(PolicyManagerImplTest_RequestTypes, LoadPT_PTPreDataConsentAppEmptyRequestTypeValues_RequestTypeValueEmpty) { // Load RequestType with empty values RefreshPT(preloaded_pt_filename_, kJsonFiles[14]); // Get Request Types for """" policy_table::RequestTypes received_types = GetRequestTypesForApplication(policy::kPreDataConsentId); // Expect const size_t received_size = received_types.size(); EXPECT_EQ(0u, received_size); } TEST_F( PolicyManagerImplTest_RequestTypes, LoadPT_PTPreDataConsentAppOmittedRequestType_RequestTypeValueEQToDatabase) { // Base values of Request Types policy_table::RequestTypes correct_types; correct_types.push_back(policy_table::RequestType::RT_HTTP); // Load omitted RequestType values RefreshPT(preloaded_pt_filename_, kJsonFiles[15]); // Get Request Types for """" policy_table::RequestTypes received_types = GetRequestTypesForApplication(policy::kPreDataConsentId); CompareRequestTypesContainers(correct_types, received_types); } TEST_F( PolicyManagerImplTest_RequestTypes, LoadPT_PTPreDataConsentAppOneInvalidRequestTypeValue_RequestTypeValueEQValidPT) { // Update values of Request Types policy_table::RequestTypes correct_types = CreatePreDataConsentAppPTURequestValues(); // Load RequestType with one invalid value RefreshPT(preloaded_pt_filename_, kJsonFiles[16]); // Get Request Types for """" policy_table::RequestTypes received_types = GetRequestTypesForApplication(policy::kPreDataConsentId); CompareRequestTypesContainers(correct_types, received_types); } } // namespace policy_test } // namespace components } // namespace test ",16369,True,3164.2802581624524,median "/* * si5351.cpp - Si5351 library for Arduino * * Copyright (C) 2015 - 2019 Jason Milldrum * Dana H. Myers * * Some tuning algorithms derived from clk-si5351.c in the Linux kernel. * Sebastian Hesselbarth * Rabeeh Khoury * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include #include ""Arduino.h"" #include ""Wire.h"" #include ""si5351.h"" #ifdef RASPBERRY_PI_I2C int si5351fd; #endif #ifdef SI5351A_B04486_GT i2c_addr = 0x62; // needed for certain preprogrammed parts #endif /********************/ /* Public functions */ /********************/ Si5351::Si5351(uint8_t i2c_addr): i2c_bus_addr(i2c_addr) { xtal_freq[0] = SI5351_XTAL_FREQ; // Start by using XO ref osc as default for each PLL plla_ref_osc = SI5351_PLL_INPUT_XO; pllb_ref_osc = SI5351_PLL_INPUT_XO; clkin_div = SI5351_CLKIN_DIV_1; } /* * init(uint8_t xtal_load_c, uint32_t ref_osc_freq, int32_t corr) * * Setup communications to the Si5351 and set the crystal * load capacitance. * * xtal_load_c - Crystal load capacitance. Use the SI5351_CRYSTAL_LOAD_*PF * defines in the header file * xo_freq - Crystal/reference oscillator frequency in 1 Hz increments. * Defaults to 25000000 if a 0 is used here. * corr - Frequency correction constant in parts-per-billion * * Returns a boolean that indicates whether a device was found on the desired * I2C address. * */ bool Si5351::init(uint8_t xtal_load_c, uint32_t xo_freq, int32_t corr) { #ifdef RASPBERRY_PI_I2C // Start I2C comms uint8_t reg_val = 0; if ( ((si5351fd = open(""/dev/i2c-1"", O_RDWR)) >= 0) && (ioctl(si5351fd, I2C_SLAVE, i2c_bus_addr & 0xff) >= 0) ) reg_val = 0; else reg_val = -1; #endif #ifndef RASPBERRY_PI_I2C // Start I2C comms Wire.begin(); // Check for a device on the bus, bail out if it is not there Wire.beginTransmission(i2c_bus_addr); uint8_t reg_val; reg_val = Wire.endTransmission(); #endif if(reg_val == 0) { // Wait for SYS_INIT flag to be clear, indicating that device is ready uint8_t status_reg = 0; do { status_reg = si5351_read(SI5351_DEVICE_STATUS); } while (status_reg >> 7 == 1); // Set crystal load capacitance si5351_write(SI5351_CRYSTAL_LOAD, (xtal_load_c & SI5351_CRYSTAL_LOAD_MASK) | 0b00010010); // Set up the XO reference frequency if (xo_freq != 0) { set_ref_freq(xo_freq, SI5351_PLL_INPUT_XO); } else { set_ref_freq(SI5351_XTAL_FREQ, SI5351_PLL_INPUT_XO); } // Set the frequency calibration for the XO set_correction(corr, SI5351_PLL_INPUT_XO); reset(); return true; } else { return false; } } /* * reset(void) * * Call to reset the Si5351 to the state initialized by the library. * */ void Si5351::reset(void) { // Initialize the CLK outputs according to flowchart in datasheet // First, turn them off si5351_write(16, 0x80); si5351_write(17, 0x80); si5351_write(18, 0x80); si5351_write(19, 0x80); si5351_write(20, 0x80); si5351_write(21, 0x80); si5351_write(22, 0x80); si5351_write(23, 0x80); // Turn the clocks back on... si5351_write(16, 0x0c); si5351_write(17, 0x0c); si5351_write(18, 0x0c); si5351_write(19, 0x0c); si5351_write(20, 0x0c); si5351_write(21, 0x0c); si5351_write(22, 0x0c); si5351_write(23, 0x0c); // Set PLLA and PLLB to 800 MHz for automatic tuning set_pll(SI5351_PLL_FIXED, SI5351_PLLA); set_pll(SI5351_PLL_FIXED, SI5351_PLLB); // Make PLL to CLK assignments for automatic tuning pll_assignment[0] = SI5351_PLLA; pll_assignment[1] = SI5351_PLLA; pll_assignment[2] = SI5351_PLLA; pll_assignment[3] = SI5351_PLLA; pll_assignment[4] = SI5351_PLLA; pll_assignment[5] = SI5351_PLLA; pll_assignment[6] = SI5351_PLLB; pll_assignment[7] = SI5351_PLLB; set_ms_source(SI5351_CLK0, SI5351_PLLA); set_ms_source(SI5351_CLK1, SI5351_PLLA); set_ms_source(SI5351_CLK2, SI5351_PLLA); set_ms_source(SI5351_CLK3, SI5351_PLLA); set_ms_source(SI5351_CLK4, SI5351_PLLA); set_ms_source(SI5351_CLK5, SI5351_PLLA); set_ms_source(SI5351_CLK6, SI5351_PLLB); set_ms_source(SI5351_CLK7, SI5351_PLLB); // Reset the VCXO param si5351_write(SI5351_VXCO_PARAMETERS_LOW, 0); si5351_write(SI5351_VXCO_PARAMETERS_MID, 0); si5351_write(SI5351_VXCO_PARAMETERS_HIGH, 0); // Then reset the PLLs pll_reset(SI5351_PLLA); pll_reset(SI5351_PLLB); // Set initial frequencies uint8_t i; for(i = 0; i < 8; i++) { clk_freq[i] = 0; output_enable((enum si5351_clock)i, 0); clk_first_set[i] = false; } } /* * set_freq(uint64_t freq, enum si5351_clock clk) * * Sets the clock frequency of the specified CLK output. * Frequency range of 8 kHz to 150 MHz * * freq - Output frequency in Hz * clk - Clock output * (use the si5351_clock enum) */ uint8_t Si5351::set_freq(uint64_t freq, enum si5351_clock clk) { struct Si5351RegSet ms_reg; uint64_t pll_freq; uint8_t int_mode = 0; uint8_t div_by_4 = 0; uint8_t r_div = 0; // Check which Multisynth is being set if((uint8_t)clk <= (uint8_t)SI5351_CLK5) { // MS0 through MS5 logic // --------------------- // Lower bounds check if(freq > 0 && freq < SI5351_CLKOUT_MIN_FREQ * SI5351_FREQ_MULT) { freq = SI5351_CLKOUT_MIN_FREQ * SI5351_FREQ_MULT; } // Upper bounds check if(freq > SI5351_MULTISYNTH_MAX_FREQ * SI5351_FREQ_MULT) { freq = SI5351_MULTISYNTH_MAX_FREQ * SI5351_FREQ_MULT; } // If requested freq >100 MHz and no other outputs are already >100 MHz, // we need to recalculate PLLA and then recalculate all other CLK outputs // on same PLL if(freq > (SI5351_MULTISYNTH_SHARE_MAX * SI5351_FREQ_MULT)) { // Check other clocks on same PLL uint8_t i; for(i = 0; i < 6; i++) { if(clk_freq[i] > (SI5351_MULTISYNTH_SHARE_MAX * SI5351_FREQ_MULT)) { if(i != (uint8_t)clk && pll_assignment[i] == pll_assignment[clk]) { return 1; // won't set if any other clks already >100 MHz } } } // Enable the output on first set_freq only if(clk_first_set[(uint8_t)clk] == false) { output_enable(clk, 1); clk_first_set[(uint8_t)clk] = true; } // Set the freq in memory clk_freq[(uint8_t)clk] = freq; // Calculate the proper PLL frequency pll_freq = multisynth_calc(freq, 0, &ms_reg); // Set PLL set_pll(pll_freq, pll_assignment[clk]); // Recalculate params for other synths on same PLL for(i = 0; i < 6; i++) { if(clk_freq[i] != 0) { if(pll_assignment[i] == pll_assignment[clk]) { struct Si5351RegSet temp_reg; uint64_t temp_freq; // Select the proper R div value temp_freq = clk_freq[i]; r_div = select_r_div(&temp_freq); multisynth_calc(temp_freq, pll_freq, &temp_reg); // If freq > 150 MHz, we need to use DIVBY4 and integer mode if(temp_freq >= SI5351_MULTISYNTH_DIVBY4_FREQ * SI5351_FREQ_MULT) { div_by_4 = 1; int_mode = 1; } else { div_by_4 = 0; int_mode = 0; } // Set multisynth registers set_ms((enum si5351_clock)i, temp_reg, int_mode, r_div, div_by_4); } } } // Reset the PLL pll_reset(pll_assignment[clk]); } else { clk_freq[(uint8_t)clk] = freq; // Enable the output on first set_freq only if(clk_first_set[(uint8_t)clk] == false) { output_enable(clk, 1); clk_first_set[(uint8_t)clk] = true; } // Select the proper R div value r_div = select_r_div(&freq); // Calculate the synth parameters if(pll_assignment[clk] == SI5351_PLLA) { multisynth_calc(freq, plla_freq, &ms_reg); } else { multisynth_calc(freq, pllb_freq, &ms_reg); } // Set multisynth registers set_ms(clk, ms_reg, int_mode, r_div, div_by_4); // Reset the PLL //pll_reset(pll_assignment[clk]); } return 0; } else { // MS6 and MS7 logic // ----------------- // Lower bounds check if(freq > 0 && freq < SI5351_CLKOUT67_MIN_FREQ * SI5351_FREQ_MULT) { freq = SI5351_CLKOUT_MIN_FREQ * SI5351_FREQ_MULT; } // Upper bounds check if(freq >= SI5351_MULTISYNTH_DIVBY4_FREQ * SI5351_FREQ_MULT) { freq = SI5351_MULTISYNTH_DIVBY4_FREQ * SI5351_FREQ_MULT - 1; } // If one of CLK6 or CLK7 is already set when trying to set the other, // we have to ensure that it will also have an integer division ratio // with the same PLL, otherwise do not set it. if(clk == SI5351_CLK6) { if(clk_freq[7] != 0) { if(pllb_freq % freq == 0) { if((pllb_freq / freq) % 2 != 0) { // Not an even divide ratio, no bueno return 1; } else { // Set the freq in memory clk_freq[(uint8_t)clk] = freq; // Select the proper R div value r_div = select_r_div_ms67(&freq); multisynth67_calc(freq, pllb_freq, &ms_reg); } } else { // Not an integer divide ratio, no good return 1; } } else { // No previous assignment, so set PLLB based on CLK6 // Set the freq in memory clk_freq[(uint8_t)clk] = freq; // Select the proper R div value r_div = select_r_div_ms67(&freq); pll_freq = multisynth67_calc(freq, 0, &ms_reg); //pllb_freq = pll_freq; set_pll(pll_freq, SI5351_PLLB); } } else { if(clk_freq[6] != 0) { if(pllb_freq % freq == 0) { if((pllb_freq / freq) % 2 != 0) { // Not an even divide ratio, no bueno return 1; } else { // Set the freq in memory clk_freq[(uint8_t)clk] = freq; // Select the proper R div value r_div = select_r_div_ms67(&freq); multisynth67_calc(freq, pllb_freq, &ms_reg); } } else { // Not an integer divide ratio, no good return 1; } } else { // No previous assignment, so set PLLB based on CLK7 // Set the freq in memory clk_freq[(uint8_t)clk] = freq; // Select the proper R div value r_div = select_r_div_ms67(&freq); pll_freq = multisynth67_calc(freq, 0, &ms_reg); //pllb_freq = pll_freq; set_pll(pll_freq, pll_assignment[clk]); } } div_by_4 = 0; int_mode = 0; // Set multisynth registers (MS must be set before PLL) set_ms(clk, ms_reg, int_mode, r_div, div_by_4); return 0; } } /* * set_freq_manual(uint64_t freq, uint64_t pll_freq, enum si5351_clock clk) * * Sets the clock frequency of the specified CLK output using the given PLL * frequency. You must ensure that the MS is assigned to the correct PLL and * that the PLL is set to the correct frequency before using this method. * * It is important to note that if you use this method, you will have to * track that all settings are sane yourself. * * freq - Output frequency in Hz * pll_freq - Frequency of the PLL driving the Multisynth in Hz * 100 * clk - Clock output * (use the si5351_clock enum) */ uint8_t Si5351::set_freq_manual(uint64_t freq, uint64_t pll_freq, enum si5351_clock clk) { struct Si5351RegSet ms_reg; uint8_t int_mode = 0; uint8_t div_by_4 = 0; // Lower bounds check if(freq > 0 && freq < SI5351_CLKOUT_MIN_FREQ * SI5351_FREQ_MULT) { freq = SI5351_CLKOUT_MIN_FREQ * SI5351_FREQ_MULT; } // Upper bounds check if(freq > SI5351_CLKOUT_MAX_FREQ * SI5351_FREQ_MULT) { freq = SI5351_CLKOUT_MAX_FREQ * SI5351_FREQ_MULT; } uint8_t r_div; clk_freq[(uint8_t)clk] = freq; set_pll(pll_freq, pll_assignment[clk]); // Enable the output output_enable(clk, 1); // Select the proper R div value r_div = select_r_div(&freq); // Calculate the synth parameters multisynth_calc(freq, pll_freq, &ms_reg); // If freq > 150 MHz, we need to use DIVBY4 and integer mode if(freq >= SI5351_MULTISYNTH_DIVBY4_FREQ * SI5351_FREQ_MULT) { div_by_4 = 1; int_mode = 1; } // Set multisynth registers (MS must be set before PLL) set_ms(clk, ms_reg, int_mode, r_div, div_by_4); return 0; } /* * set_pll(uint64_t pll_freq, enum si5351_pll target_pll) * * Set the specified PLL to a specific oscillation frequency * * pll_freq - Desired PLL frequency in Hz * 100 * target_pll - Which PLL to set * (use the si5351_pll enum) */ void Si5351::set_pll(uint64_t pll_freq, enum si5351_pll target_pll) { struct Si5351RegSet pll_reg; if(target_pll == SI5351_PLLA) { pll_calc(SI5351_PLLA, pll_freq, &pll_reg, ref_correction[plla_ref_osc], 0); } else { pll_calc(SI5351_PLLB, pll_freq, &pll_reg, ref_correction[pllb_ref_osc], 0); } // Derive the register values to write // Prepare an array for parameters to be written to uint8_t *params = new uint8_t[20]; uint8_t i = 0; uint8_t temp; // Registers 26-27 temp = ((pll_reg.p3 >> 8) & 0xFF); params[i++] = temp; temp = (uint8_t)(pll_reg.p3 & 0xFF); params[i++] = temp; // Register 28 temp = (uint8_t)((pll_reg.p1 >> 16) & 0x03); params[i++] = temp; // Registers 29-30 temp = (uint8_t)((pll_reg.p1 >> 8) & 0xFF); params[i++] = temp; temp = (uint8_t)(pll_reg.p1 & 0xFF); params[i++] = temp; // Register 31 temp = (uint8_t)((pll_reg.p3 >> 12) & 0xF0); temp += (uint8_t)((pll_reg.p2 >> 16) & 0x0F); params[i++] = temp; // Registers 32-33 temp = (uint8_t)((pll_reg.p2 >> 8) & 0xFF); params[i++] = temp; temp = (uint8_t)(pll_reg.p2 & 0xFF); params[i++] = temp; // Write the parameters if(target_pll == SI5351_PLLA) { si5351_write_bulk(SI5351_PLLA_PARAMETERS, i, params); plla_freq = pll_freq; } else if(target_pll == SI5351_PLLB) { si5351_write_bulk(SI5351_PLLB_PARAMETERS, i, params); pllb_freq = pll_freq; } delete params; } /* * set_ms(enum si5351_clock clk, struct Si5351RegSet ms_reg, uint8_t int_mode, uint8_t r_div, uint8_t div_by_4) * * Set the specified multisynth parameters. Not normally needed, but public for advanced users. * * clk - Clock output * (use the si5351_clock enum) * int_mode - Set integer mode * Set to 1 to enable, 0 to disable * r_div - Desired r_div ratio * div_by_4 - Set Divide By 4 mode * Set to 1 to enable, 0 to disable */ void Si5351::set_ms(enum si5351_clock clk, struct Si5351RegSet ms_reg, uint8_t int_mode, uint8_t r_div, uint8_t div_by_4) { uint8_t *params = new uint8_t[20]; uint8_t i = 0; uint8_t temp; uint8_t reg_val; if((uint8_t)clk <= (uint8_t)SI5351_CLK5) { // Registers 42-43 for CLK0 temp = (uint8_t)((ms_reg.p3 >> 8) & 0xFF); params[i++] = temp; temp = (uint8_t)(ms_reg.p3 & 0xFF); params[i++] = temp; // Register 44 for CLK0 reg_val = si5351_read((SI5351_CLK0_PARAMETERS + 2) + (clk * 8)); reg_val &= ~(0x03); temp = reg_val | ((uint8_t)((ms_reg.p1 >> 16) & 0x03)); params[i++] = temp; // Registers 45-46 for CLK0 temp = (uint8_t)((ms_reg.p1 >> 8) & 0xFF); params[i++] = temp; temp = (uint8_t)(ms_reg.p1 & 0xFF); params[i++] = temp; // Register 47 for CLK0 temp = (uint8_t)((ms_reg.p3 >> 12) & 0xF0); temp += (uint8_t)((ms_reg.p2 >> 16) & 0x0F); params[i++] = temp; // Registers 48-49 for CLK0 temp = (uint8_t)((ms_reg.p2 >> 8) & 0xFF); params[i++] = temp; temp = (uint8_t)(ms_reg.p2 & 0xFF); params[i++] = temp; } else { // MS6 and MS7 only use one register temp = ms_reg.p1; } // Write the parameters switch(clk) { case SI5351_CLK0: si5351_write_bulk(SI5351_CLK0_PARAMETERS, i, params); set_int(clk, int_mode); ms_div(clk, r_div, div_by_4); break; case SI5351_CLK1: si5351_write_bulk(SI5351_CLK1_PARAMETERS, i, params); set_int(clk, int_mode); ms_div(clk, r_div, div_by_4); break; case SI5351_CLK2: si5351_write_bulk(SI5351_CLK2_PARAMETERS, i, params); set_int(clk, int_mode); ms_div(clk, r_div, div_by_4); break; case SI5351_CLK3: si5351_write_bulk(SI5351_CLK3_PARAMETERS, i, params); set_int(clk, int_mode); ms_div(clk, r_div, div_by_4); break; case SI5351_CLK4: si5351_write_bulk(SI5351_CLK4_PARAMETERS, i, params); set_int(clk, int_mode); ms_div(clk, r_div, div_by_4); break; case SI5351_CLK5: si5351_write_bulk(SI5351_CLK5_PARAMETERS, i, params); set_int(clk, int_mode); ms_div(clk, r_div, div_by_4); break; case SI5351_CLK6: si5351_write(SI5351_CLK6_PARAMETERS, temp); ms_div(clk, r_div, div_by_4); break; case SI5351_CLK7: si5351_write(SI5351_CLK7_PARAMETERS, temp); ms_div(clk, r_div, div_by_4); break; } delete params; } /* * output_enable(enum si5351_clock clk, uint8_t enable) * * Enable or disable a chosen output * clk - Clock output * (use the si5351_clock enum) * enable - Set to 1 to enable, 0 to disable */ void Si5351::output_enable(enum si5351_clock clk, uint8_t enable) { uint8_t reg_val; reg_val = si5351_read(SI5351_OUTPUT_ENABLE_CTRL); if(enable == 1) { reg_val &= ~(1<<(uint8_t)clk); } else { reg_val |= (1<<(uint8_t)clk); } si5351_write(SI5351_OUTPUT_ENABLE_CTRL, reg_val); } /* * drive_strength(enum si5351_clock clk, enum si5351_drive drive) * * Sets the drive strength of the specified clock output * * clk - Clock output * (use the si5351_clock enum) * drive - Desired drive level * (use the si5351_drive enum) */ void Si5351::drive_strength(enum si5351_clock clk, enum si5351_drive drive) { uint8_t reg_val; const uint8_t mask = 0x03; reg_val = si5351_read(SI5351_CLK0_CTRL + (uint8_t)clk); reg_val &= ~(mask); switch(drive) { case SI5351_DRIVE_2MA: reg_val |= 0x00; break; case SI5351_DRIVE_4MA: reg_val |= 0x01; break; case SI5351_DRIVE_6MA: reg_val |= 0x02; break; case SI5351_DRIVE_8MA: reg_val |= 0x03; break; default: break; } si5351_write(SI5351_CLK0_CTRL + (uint8_t)clk, reg_val); } /* * update_status(void) * * Call this to update the status structs, then access them * via the dev_status and dev_int_status global members. * * See the header file for the struct definitions. These * correspond to the flag names for registers 0 and 1 in * the Si5351 datasheet. */ void Si5351::update_status(void) { update_sys_status(&dev_status); update_int_status(&dev_int_status); } /* * set_correction(int32_t corr, enum si5351_pll_input ref_osc) * * corr - Correction factor in ppb * ref_osc - Desired reference oscillator * (use the si5351_pll_input enum) * * Use this to set the oscillator correction factor. * This value is a signed 32-bit integer of the * parts-per-billion value that the actual oscillation * frequency deviates from the specified frequency. * * The frequency calibration is done as a one-time procedure. * Any desired test frequency within the normal range of the * Si5351 should be set, then the actual output frequency * should be measured as accurately as possible. The * difference between the measured and specified frequencies * should be calculated in Hertz, then multiplied by 10 in * order to get the parts-per-billion value. * * Since the Si5351 itself has an intrinsic 0 PPM error, this * correction factor is good across the entire tuning range of * the Si5351. Once this calibration is done accurately, it * should not have to be done again for the same Si5351 and * crystal. */ void Si5351::set_correction(int32_t corr, enum si5351_pll_input ref_osc) { ref_correction[(uint8_t)ref_osc] = corr; // Recalculate and set PLL freqs based on correction value set_pll(plla_freq, SI5351_PLLA); set_pll(pllb_freq, SI5351_PLLB); } /* * set_phase(enum si5351_clock clk, uint8_t phase) * * clk - Clock output * (use the si5351_clock enum) * phase - 7-bit phase word * (in units of VCO/4 period) * * Write the 7-bit phase register. This must be used * with a user-set PLL frequency so that the user can * calculate the proper tuning word based on the PLL period. */ void Si5351::set_phase(enum si5351_clock clk, uint8_t phase) { // Mask off the upper bit since it is reserved phase = phase & 0b01111111; si5351_write(SI5351_CLK0_PHASE_OFFSET + (uint8_t)clk, phase); } /* * get_correction(enum si5351_pll_input ref_osc) * * ref_osc - Desired reference oscillator * 0: crystal oscillator (XO) * 1: external clock input (CLKIN) * * Returns the oscillator correction factor stored * in RAM. */ int32_t Si5351::get_correction(enum si5351_pll_input ref_osc) { return ref_correction[(uint8_t)ref_osc]; } /* * pll_reset(enum si5351_pll target_pll) * * target_pll - Which PLL to reset * (use the si5351_pll enum) * * Apply a reset to the indicated PLL. */ void Si5351::pll_reset(enum si5351_pll target_pll) { if(target_pll == SI5351_PLLA) { si5351_write(SI5351_PLL_RESET, SI5351_PLL_RESET_A); } else if(target_pll == SI5351_PLLB) { si5351_write(SI5351_PLL_RESET, SI5351_PLL_RESET_B); } } /* * set_ms_source(enum si5351_clock clk, enum si5351_pll pll) * * clk - Clock output * (use the si5351_clock enum) * pll - Which PLL to use as the source * (use the si5351_pll enum) * * Set the desired PLL source for a multisynth. */ void Si5351::set_ms_source(enum si5351_clock clk, enum si5351_pll pll) { uint8_t reg_val; reg_val = si5351_read(SI5351_CLK0_CTRL + (uint8_t)clk); if(pll == SI5351_PLLA) { reg_val &= ~(SI5351_CLK_PLL_SELECT); } else if(pll == SI5351_PLLB) { reg_val |= SI5351_CLK_PLL_SELECT; } si5351_write(SI5351_CLK0_CTRL + (uint8_t)clk, reg_val); pll_assignment[(uint8_t)clk] = pll; } /* * set_int(enum si5351_clock clk, uint8_t int_mode) * * clk - Clock output * (use the si5351_clock enum) * enable - Set to 1 to enable, 0 to disable * * Set the indicated multisynth into integer mode. */ void Si5351::set_int(enum si5351_clock clk, uint8_t enable) { uint8_t reg_val; reg_val = si5351_read(SI5351_CLK0_CTRL + (uint8_t)clk); if(enable == 1) { reg_val |= (SI5351_CLK_INTEGER_MODE); } else { reg_val &= ~(SI5351_CLK_INTEGER_MODE); } si5351_write(SI5351_CLK0_CTRL + (uint8_t)clk, reg_val); // Integer mode indication /* switch(clk) { case SI5351_CLK0: clk0_int_mode = enable; break; case SI5351_CLK1: clk1_int_mode = enable; break; case SI5351_CLK2: clk2_int_mode = enable; break; default: break; } */ } /* * set_clock_pwr(enum si5351_clock clk, uint8_t pwr) * * clk - Clock output * (use the si5351_clock enum) * pwr - Set to 1 to enable, 0 to disable * * Enable or disable power to a clock output (a power * saving feature). */ void Si5351::set_clock_pwr(enum si5351_clock clk, uint8_t pwr) { uint8_t reg_val; //, reg; reg_val = si5351_read(SI5351_CLK0_CTRL + (uint8_t)clk); if(pwr == 1) { reg_val &= 0b01111111; } else { reg_val |= 0b10000000; } si5351_write(SI5351_CLK0_CTRL + (uint8_t)clk, reg_val); } /* * set_clock_invert(enum si5351_clock clk, uint8_t inv) * * clk - Clock output * (use the si5351_clock enum) * inv - Set to 1 to enable, 0 to disable * * Enable to invert the clock output waveform. */ void Si5351::set_clock_invert(enum si5351_clock clk, uint8_t inv) { uint8_t reg_val; reg_val = si5351_read(SI5351_CLK0_CTRL + (uint8_t)clk); if(inv == 1) { reg_val |= (SI5351_CLK_INVERT); } else { reg_val &= ~(SI5351_CLK_INVERT); } si5351_write(SI5351_CLK0_CTRL + (uint8_t)clk, reg_val); } /* * set_clock_source(enum si5351_clock clk, enum si5351_clock_source src) * * clk - Clock output * (use the si5351_clock enum) * src - Which clock source to use for the multisynth * (use the si5351_clock_source enum) * * Set the clock source for a multisynth (based on the options * presented for Registers 16-23 in the Silicon Labs AN619 document). * Choices are XTAL, CLKIN, MS0, or the multisynth associated with * the clock output. */ void Si5351::set_clock_source(enum si5351_clock clk, enum si5351_clock_source src) { uint8_t reg_val; reg_val = si5351_read(SI5351_CLK0_CTRL + (uint8_t)clk); // Clear the bits first reg_val &= ~(SI5351_CLK_INPUT_MASK); switch(src) { case SI5351_CLK_SRC_XTAL: reg_val |= (SI5351_CLK_INPUT_XTAL); break; case SI5351_CLK_SRC_CLKIN: reg_val |= (SI5351_CLK_INPUT_CLKIN); break; case SI5351_CLK_SRC_MS0: if(clk == SI5351_CLK0) { return; } reg_val |= (SI5351_CLK_INPUT_MULTISYNTH_0_4); break; case SI5351_CLK_SRC_MS: reg_val |= (SI5351_CLK_INPUT_MULTISYNTH_N); break; default: return; } si5351_write(SI5351_CLK0_CTRL + (uint8_t)clk, reg_val); } /* * set_clock_disable(enum si5351_clock clk, enum si5351_clock_disable dis_state) * * clk - Clock output * (use the si5351_clock enum) * dis_state - Desired state of the output upon disable * (use the si5351_clock_disable enum) * * Set the state of the clock output when it is disabled. Per page 27 * of AN619 (Registers 24 and 25), there are four possible values: low, * high, high impedance, and never disabled. */ void Si5351::set_clock_disable(enum si5351_clock clk, enum si5351_clock_disable dis_state) { uint8_t reg_val, reg; if (clk >= SI5351_CLK0 && clk <= SI5351_CLK3) { reg = SI5351_CLK3_0_DISABLE_STATE; } else if(clk >= SI5351_CLK4 && clk <= SI5351_CLK7) { reg = SI5351_CLK7_4_DISABLE_STATE; } else return; reg_val = si5351_read(reg); if (clk >= SI5351_CLK0 && clk <= SI5351_CLK3) { reg_val &= ~(0b11 << (clk * 2)); reg_val |= dis_state << (clk * 2); } else if(clk >= SI5351_CLK4 && clk <= SI5351_CLK7) { reg_val &= ~(0b11 << ((clk - 4) * 2)); reg_val |= dis_state << ((clk - 4) * 2); } si5351_write(reg, reg_val); } /* * set_clock_fanout(enum si5351_clock_fanout fanout, uint8_t enable) * * fanout - Desired clock fanout * (use the si5351_clock_fanout enum) * enable - Set to 1 to enable, 0 to disable * * Use this function to enable or disable the clock fanout options * for individual clock outputs. If you intend to output the XO or * CLKIN on the clock outputs, enable this first. * * By default, only the Multisynth fanout is enabled at startup. */ void Si5351::set_clock_fanout(enum si5351_clock_fanout fanout, uint8_t enable) { uint8_t reg_val; reg_val = si5351_read(SI5351_FANOUT_ENABLE); switch(fanout) { case SI5351_FANOUT_CLKIN: if(enable) { reg_val |= SI5351_CLKIN_ENABLE; } else { reg_val &= ~(SI5351_CLKIN_ENABLE); } break; case SI5351_FANOUT_XO: if(enable) { reg_val |= SI5351_XTAL_ENABLE; } else { reg_val &= ~(SI5351_XTAL_ENABLE); } break; case SI5351_FANOUT_MS: if(enable) { reg_val |= SI5351_MULTISYNTH_ENABLE; } else { reg_val &= ~(SI5351_MULTISYNTH_ENABLE); } break; } si5351_write(SI5351_FANOUT_ENABLE, reg_val); } /* * set_pll_input(enum si5351_pll pll, enum si5351_pll_input input) * * pll - Which PLL to use as the source * (use the si5351_pll enum) * input - Which reference oscillator to use as PLL input * (use the si5351_pll_input enum) * * Set the desired reference oscillator source for the given PLL. */ void Si5351::set_pll_input(enum si5351_pll pll, enum si5351_pll_input input) { uint8_t reg_val; reg_val = si5351_read(SI5351_PLL_INPUT_SOURCE); // Clear the bits first //reg_val &= ~(SI5351_CLKIN_DIV_MASK); switch(pll) { case SI5351_PLLA: if(input == SI5351_PLL_INPUT_CLKIN) { reg_val |= SI5351_PLLA_SOURCE; reg_val |= clkin_div; plla_ref_osc = SI5351_PLL_INPUT_CLKIN; } else { reg_val &= ~(SI5351_PLLA_SOURCE); plla_ref_osc = SI5351_PLL_INPUT_XO; } break; case SI5351_PLLB: if(input == SI5351_PLL_INPUT_CLKIN) { reg_val |= SI5351_PLLB_SOURCE; reg_val |= clkin_div; pllb_ref_osc = SI5351_PLL_INPUT_CLKIN; } else { reg_val &= ~(SI5351_PLLB_SOURCE); pllb_ref_osc = SI5351_PLL_INPUT_XO; } break; default: return; } si5351_write(SI5351_PLL_INPUT_SOURCE, reg_val); set_pll(plla_freq, SI5351_PLLA); set_pll(pllb_freq, SI5351_PLLB); } /* * set_vcxo(uint64_t pll_freq, uint8_t ppm) * * pll_freq - Desired PLL base frequency in Hz * 100 * ppm - VCXO pull limit in ppm * * Set the parameters for the VCXO on the Si5351B. */ void Si5351::set_vcxo(uint64_t pll_freq, uint8_t ppm) { struct Si5351RegSet pll_reg; uint64_t vcxo_param; // Bounds check if(ppm < SI5351_VCXO_PULL_MIN) { ppm = SI5351_VCXO_PULL_MIN; } if(ppm > SI5351_VCXO_PULL_MAX) { ppm = SI5351_VCXO_PULL_MAX; } // Set PLLB params vcxo_param = pll_calc(SI5351_PLLB, pll_freq, &pll_reg, ref_correction[pllb_ref_osc], 1); // Derive the register values to write // Prepare an array for parameters to be written to uint8_t *params = new uint8_t[20]; uint8_t i = 0; uint8_t temp; // Registers 26-27 temp = ((pll_reg.p3 >> 8) & 0xFF); params[i++] = temp; temp = (uint8_t)(pll_reg.p3 & 0xFF); params[i++] = temp; // Register 28 temp = (uint8_t)((pll_reg.p1 >> 16) & 0x03); params[i++] = temp; // Registers 29-30 temp = (uint8_t)((pll_reg.p1 >> 8) & 0xFF); params[i++] = temp; temp = (uint8_t)(pll_reg.p1 & 0xFF); params[i++] = temp; // Register 31 temp = (uint8_t)((pll_reg.p3 >> 12) & 0xF0); temp += (uint8_t)((pll_reg.p2 >> 16) & 0x0F); params[i++] = temp; // Registers 32-33 temp = (uint8_t)((pll_reg.p2 >> 8) & 0xFF); params[i++] = temp; temp = (uint8_t)(pll_reg.p2 & 0xFF); params[i++] = temp; // Write the parameters si5351_write_bulk(SI5351_PLLB_PARAMETERS, i, params); delete params; // Write the VCXO parameters vcxo_param = ((vcxo_param * ppm * SI5351_VCXO_MARGIN) / 100ULL) / 1000000ULL; temp = (uint8_t)(vcxo_param & 0xFF); si5351_write(SI5351_VXCO_PARAMETERS_LOW, temp); temp = (uint8_t)((vcxo_param >> 8) & 0xFF); si5351_write(SI5351_VXCO_PARAMETERS_MID, temp); temp = (uint8_t)((vcxo_param >> 16) & 0x3F); si5351_write(SI5351_VXCO_PARAMETERS_HIGH, temp); } /* * set_ref_freq(uint32_t ref_freq, enum si5351_pll_input ref_osc) * * ref_freq - Reference oscillator frequency in Hz * ref_osc - Which reference oscillator frequency to set * (use the si5351_pll_input enum) * * Set the reference frequency value for the desired reference oscillator */ void Si5351::set_ref_freq(uint32_t ref_freq, enum si5351_pll_input ref_osc) { // uint8_t reg_val; //reg_val = si5351_read(SI5351_PLL_INPUT_SOURCE); // Clear the bits first //reg_val &= ~(SI5351_CLKIN_DIV_MASK); if(ref_freq <= 30000000UL) { xtal_freq[(uint8_t)ref_osc] = ref_freq; //reg_val |= SI5351_CLKIN_DIV_1; if(ref_osc == SI5351_PLL_INPUT_CLKIN) { clkin_div = SI5351_CLKIN_DIV_1; } } else if(ref_freq > 30000000UL && ref_freq <= 60000000UL) { xtal_freq[(uint8_t)ref_osc] = ref_freq / 2; //reg_val |= SI5351_CLKIN_DIV_2; if(ref_osc == SI5351_PLL_INPUT_CLKIN) { clkin_div = SI5351_CLKIN_DIV_2; } } else if(ref_freq > 60000000UL && ref_freq <= 100000000UL) { xtal_freq[(uint8_t)ref_osc] = ref_freq / 4; //reg_val |= SI5351_CLKIN_DIV_4; if(ref_osc == SI5351_PLL_INPUT_CLKIN) { clkin_div = SI5351_CLKIN_DIV_4; } } else { //reg_val |= SI5351_CLKIN_DIV_1; } //si5351_write(SI5351_PLL_INPUT_SOURCE, reg_val); } uint8_t Si5351::si5351_write_bulk(uint8_t addr, uint8_t bytes, uint8_t *data) { #ifndef RASPBERRY_PI_I2C Wire.beginTransmission(i2c_bus_addr); Wire.write(addr); for(int i = 0; i < bytes; i++) { Wire.write(data[i]); } return Wire.endTransmission(); #endif #ifdef RASPBERRY_PI_I2C int result = -1; uint8_t buf[33]; if (bytes <= 31) { buf[0] = addr; memcpy(&buf[1], data, bytes); result = write(si5351fd, buf, bytes+1); if (result > 0) result--; } return result = 0x0ff; #endif } uint8_t Si5351::si5351_write(uint8_t addr, uint8_t data) { #ifndef RASPBERRY_PI_I2C Wire.beginTransmission(i2c_bus_addr); Wire.write(addr); Wire.write(data); return Wire.endTransmission(); #endif #ifdef RASPBERRY_PI_I2C uint8_t buf[2]; buf[0]=addr; buf[1]=data; int result = write(si5351fd, buf, 2); return (result < 0) ? 0 : 1; #endif } uint8_t Si5351::si5351_read(uint8_t addr) { #ifndef RASPBERRY_PI_I2C uint8_t reg_val = 0; Wire.beginTransmission(i2c_bus_addr); Wire.write(addr); Wire.endTransmission(); Wire.requestFrom(i2c_bus_addr, (uint8_t)1, (uint8_t)false); while(Wire.available()) { reg_val = Wire.read(); } return reg_val; #endif #ifdef RASPBERRY_PI_I2C uint8_t reg_val = 0; uint8_t buf[33]; buf[0] = addr; int readcount = 0; // caller seems to expect only last byte if more than one received (!) if ((write(si5351fd, buf, 1) == 1) && ((readcount = read(si5351fd, buf, 1)) > 0)) // reg_val = buf[readcount-1]; reg_val = buf[0]; return reg_val; #endif } /*********************/ /* Private functions */ /*********************/ uint64_t Si5351::pll_calc(enum si5351_pll pll, uint64_t freq, struct Si5351RegSet *reg, int32_t correction, uint8_t vcxo) { uint64_t ref_freq; if(pll == SI5351_PLLA) { ref_freq = xtal_freq[(uint8_t)plla_ref_osc] * SI5351_FREQ_MULT; } else { ref_freq = xtal_freq[(uint8_t)pllb_ref_osc] * SI5351_FREQ_MULT; } //ref_freq = 15974400ULL * SI5351_FREQ_MULT; uint32_t a, b, c, p1, p2, p3; uint64_t lltmp; //, denom; // Factor calibration value into nominal crystal frequency // Measured in parts-per-billion ref_freq = ref_freq + (int32_t)((((((int64_t)correction) << 31) / 1000000000LL) * ref_freq) >> 31); // PLL bounds checking if (freq < SI5351_PLL_VCO_MIN * SI5351_FREQ_MULT) { freq = SI5351_PLL_VCO_MIN * SI5351_FREQ_MULT; } if (freq > SI5351_PLL_VCO_MAX * SI5351_FREQ_MULT) { freq = SI5351_PLL_VCO_MAX * SI5351_FREQ_MULT; } // Determine integer part of feedback equation a = freq / ref_freq; if (a < SI5351_PLL_A_MIN) { freq = ref_freq * SI5351_PLL_A_MIN; } if (a > SI5351_PLL_A_MAX) { freq = ref_freq * SI5351_PLL_A_MAX; } // Find best approximation for b/c = fVCO mod fIN // denom = 1000ULL * 1000ULL; // lltmp = freq % ref_freq; // lltmp *= denom; // do_div(lltmp, ref_freq); //b = (((uint64_t)(freq % ref_freq)) * RFRAC_DENOM) / ref_freq; if(vcxo) { b = (((uint64_t)(freq % ref_freq)) * 1000000ULL) / ref_freq; c = 1000000ULL; } else { b = (((uint64_t)(freq % ref_freq)) * RFRAC_DENOM) / ref_freq; c = b ? RFRAC_DENOM : 1; } // Calculate parameters p1 = 128 * a + ((128 * b) / c) - 512; p2 = 128 * b - c * ((128 * b) / c); p3 = c; // Recalculate frequency as fIN * (a + b/c) lltmp = ref_freq; lltmp *= b; do_div(lltmp, c); freq = lltmp; freq += ref_freq * a; reg->p1 = p1; reg->p2 = p2; reg->p3 = p3; if(vcxo) { return (uint64_t)(128 * a * 1000000ULL + b); } else { return freq; } } uint64_t Si5351::multisynth_calc(uint64_t freq, uint64_t pll_freq, struct Si5351RegSet *reg) { uint64_t lltmp; uint32_t a, b, c, p1, p2, p3; uint8_t divby4 = 0; uint8_t ret_val = 0; // Multisynth bounds checking if (freq > SI5351_MULTISYNTH_MAX_FREQ * SI5351_FREQ_MULT) { freq = SI5351_MULTISYNTH_MAX_FREQ * SI5351_FREQ_MULT; } if (freq < SI5351_MULTISYNTH_MIN_FREQ * SI5351_FREQ_MULT) { freq = SI5351_MULTISYNTH_MIN_FREQ * SI5351_FREQ_MULT; } if (freq >= SI5351_MULTISYNTH_DIVBY4_FREQ * SI5351_FREQ_MULT) { divby4 = 1; } if(pll_freq == 0) { // Find largest integer divider for max // VCO frequency and given target frequency if(divby4 == 0) { lltmp = SI5351_PLL_VCO_MAX * SI5351_FREQ_MULT; // margin needed? do_div(lltmp, freq); if(lltmp == 5) { lltmp = 4; } else if(lltmp == 7) { lltmp = 6; } a = (uint32_t)lltmp; } else { a = 4; } b = 0; c = 1; pll_freq = a * freq; } else { // Preset PLL, so return the actual freq for these params instead of PLL freq ret_val = 1; // Determine integer part of feedback equation a = pll_freq / freq; if (a < SI5351_MULTISYNTH_A_MIN) { freq = pll_freq / SI5351_MULTISYNTH_A_MIN; } if (a > SI5351_MULTISYNTH_A_MAX) { freq = pll_freq / SI5351_MULTISYNTH_A_MAX; } b = (pll_freq % freq * RFRAC_DENOM) / freq; c = b ? RFRAC_DENOM : 1; } // Calculate parameters if (divby4 == 1) { p3 = 1; p2 = 0; p1 = 0; } else { p1 = 128 * a + ((128 * b) / c) - 512; p2 = 128 * b - c * ((128 * b) / c); p3 = c; } reg->p1 = p1; reg->p2 = p2; reg->p3 = p3; if(ret_val == 0) { return pll_freq; } else { return freq; } } uint64_t Si5351::multisynth67_calc(uint64_t freq, uint64_t pll_freq, struct Si5351RegSet *reg) { //uint8_t p1; // uint8_t ret_val = 0; uint32_t a; uint64_t lltmp; // Multisynth bounds checking if(freq > SI5351_MULTISYNTH67_MAX_FREQ * SI5351_FREQ_MULT) { freq = SI5351_MULTISYNTH67_MAX_FREQ * SI5351_FREQ_MULT; } if(freq < SI5351_MULTISYNTH_MIN_FREQ * SI5351_FREQ_MULT) { freq = SI5351_MULTISYNTH_MIN_FREQ * SI5351_FREQ_MULT; } if(pll_freq == 0) { // Find largest integer divider for max // VCO frequency and given target frequency lltmp = (SI5351_PLL_VCO_MAX * SI5351_FREQ_MULT) - 100000000UL; // margin needed? do_div(lltmp, freq); a = (uint32_t)lltmp; // Divisor has to be even if(a % 2 != 0) { a++; } // Divisor bounds check if(a < SI5351_MULTISYNTH_A_MIN) { a = SI5351_MULTISYNTH_A_MIN; } if(a > SI5351_MULTISYNTH67_A_MAX) { a = SI5351_MULTISYNTH67_A_MAX; } pll_freq = a * freq; // PLL bounds checking if(pll_freq > (SI5351_PLL_VCO_MAX * SI5351_FREQ_MULT)) { a -= 2; pll_freq = a * freq; } else if(pll_freq < (SI5351_PLL_VCO_MIN * SI5351_FREQ_MULT)) { a += 2; pll_freq = a * freq; } reg->p1 = (uint8_t)a; reg->p2 = 0; reg->p3 = 0; return pll_freq; } else { // Multisynth frequency must be integer division of PLL if(pll_freq % freq) { // No good return 0; } else { a = pll_freq / freq; // Division ratio bounds check if(a < SI5351_MULTISYNTH_A_MIN || a > SI5351_MULTISYNTH67_A_MAX) { // No bueno return 0; } else { reg->p1 = (uint8_t)a; reg->p2 = 0; reg->p3 = 0; return 1; } } } } void Si5351::update_sys_status(struct Si5351Status *status) { uint8_t reg_val = 0; reg_val = si5351_read(SI5351_DEVICE_STATUS); // Parse the register status->SYS_INIT = (reg_val >> 7) & 0x01; status->LOL_B = (reg_val >> 6) & 0x01; status->LOL_A = (reg_val >> 5) & 0x01; status->LOS = (reg_val >> 4) & 0x01; status->REVID = reg_val & 0x03; } void Si5351::update_int_status(struct Si5351IntStatus *int_status) { uint8_t reg_val = 0; reg_val = si5351_read(SI5351_INTERRUPT_STATUS); // Parse the register int_status->SYS_INIT_STKY = (reg_val >> 7) & 0x01; int_status->LOL_B_STKY = (reg_val >> 6) & 0x01; int_status->LOL_A_STKY = (reg_val >> 5) & 0x01; int_status->LOS_STKY = (reg_val >> 4) & 0x01; } void Si5351::ms_div(enum si5351_clock clk, uint8_t r_div, uint8_t div_by_4) { uint8_t reg_val = 0; uint8_t reg_addr = 0; switch(clk) { case SI5351_CLK0: reg_addr = SI5351_CLK0_PARAMETERS + 2; break; case SI5351_CLK1: reg_addr = SI5351_CLK1_PARAMETERS + 2; break; case SI5351_CLK2: reg_addr = SI5351_CLK2_PARAMETERS + 2; break; case SI5351_CLK3: reg_addr = SI5351_CLK3_PARAMETERS + 2; break; case SI5351_CLK4: reg_addr = SI5351_CLK4_PARAMETERS + 2; break; case SI5351_CLK5: reg_addr = SI5351_CLK5_PARAMETERS + 2; break; case SI5351_CLK6: reg_addr = SI5351_CLK6_7_OUTPUT_DIVIDER; break; case SI5351_CLK7: reg_addr = SI5351_CLK6_7_OUTPUT_DIVIDER; break; } reg_val = si5351_read(reg_addr); if(clk <= (uint8_t)SI5351_CLK5) { // Clear the relevant bits reg_val &= ~(0x7c); if(div_by_4 == 0) { reg_val &= ~(SI5351_OUTPUT_CLK_DIVBY4); } else { reg_val |= (SI5351_OUTPUT_CLK_DIVBY4); } reg_val |= (r_div << SI5351_OUTPUT_CLK_DIV_SHIFT); } else if(clk == SI5351_CLK6) { // Clear the relevant bits reg_val &= ~(0x07); reg_val |= r_div; } else if(clk == SI5351_CLK7) { // Clear the relevant bits reg_val &= ~(0x70); reg_val |= (r_div << SI5351_OUTPUT_CLK_DIV_SHIFT); } si5351_write(reg_addr, reg_val); } uint8_t Si5351::select_r_div(uint64_t *freq) { uint8_t r_div = SI5351_OUTPUT_CLK_DIV_1; // Choose the correct R divider if((*freq >= SI5351_CLKOUT_MIN_FREQ * SI5351_FREQ_MULT) && (*freq < SI5351_CLKOUT_MIN_FREQ * SI5351_FREQ_MULT * 2)) { r_div = SI5351_OUTPUT_CLK_DIV_128; *freq *= 128ULL; } else if((*freq >= SI5351_CLKOUT_MIN_FREQ * SI5351_FREQ_MULT * 2) && (*freq < SI5351_CLKOUT_MIN_FREQ * SI5351_FREQ_MULT * 4)) { r_div = SI5351_OUTPUT_CLK_DIV_64; *freq *= 64ULL; } else if((*freq >= SI5351_CLKOUT_MIN_FREQ * SI5351_FREQ_MULT * 4) && (*freq < SI5351_CLKOUT_MIN_FREQ * SI5351_FREQ_MULT * 8)) { r_div = SI5351_OUTPUT_CLK_DIV_32; *freq *= 32ULL; } else if((*freq >= SI5351_CLKOUT_MIN_FREQ * SI5351_FREQ_MULT * 8) && (*freq < SI5351_CLKOUT_MIN_FREQ * SI5351_FREQ_MULT * 16)) { r_div = SI5351_OUTPUT_CLK_DIV_16; *freq *= 16ULL; } else if((*freq >= SI5351_CLKOUT_MIN_FREQ * SI5351_FREQ_MULT * 16) && (*freq < SI5351_CLKOUT_MIN_FREQ * SI5351_FREQ_MULT * 32)) { r_div = SI5351_OUTPUT_CLK_DIV_8; *freq *= 8ULL; } else if((*freq >= SI5351_CLKOUT_MIN_FREQ * SI5351_FREQ_MULT * 32) && (*freq < SI5351_CLKOUT_MIN_FREQ * SI5351_FREQ_MULT * 64)) { r_div = SI5351_OUTPUT_CLK_DIV_4; *freq *= 4ULL; } else if((*freq >= SI5351_CLKOUT_MIN_FREQ * SI5351_FREQ_MULT * 64) && (*freq < SI5351_CLKOUT_MIN_FREQ * SI5351_FREQ_MULT * 128)) { r_div = SI5351_OUTPUT_CLK_DIV_2; *freq *= 2ULL; } return r_div; } uint8_t Si5351::select_r_div_ms67(uint64_t *freq) { uint8_t r_div = SI5351_OUTPUT_CLK_DIV_1; // Choose the correct R divider if((*freq >= SI5351_CLKOUT67_MIN_FREQ * SI5351_FREQ_MULT) && (*freq < SI5351_CLKOUT67_MIN_FREQ * SI5351_FREQ_MULT * 2)) { r_div = SI5351_OUTPUT_CLK_DIV_128; *freq *= 128ULL; } else if((*freq >= SI5351_CLKOUT67_MIN_FREQ * SI5351_FREQ_MULT * 2) && (*freq < SI5351_CLKOUT67_MIN_FREQ * SI5351_FREQ_MULT * 4)) { r_div = SI5351_OUTPUT_CLK_DIV_64; *freq *= 64ULL; } else if((*freq >= SI5351_CLKOUT67_MIN_FREQ * SI5351_FREQ_MULT * 4) && (*freq < SI5351_CLKOUT67_MIN_FREQ * SI5351_FREQ_MULT * 8)) { r_div = SI5351_OUTPUT_CLK_DIV_32; *freq *= 32ULL; } else if((*freq >= SI5351_CLKOUT67_MIN_FREQ * SI5351_FREQ_MULT * 8) && (*freq < SI5351_CLKOUT67_MIN_FREQ * SI5351_FREQ_MULT * 16)) { r_div = SI5351_OUTPUT_CLK_DIV_16; *freq *= 16ULL; } else if((*freq >= SI5351_CLKOUT67_MIN_FREQ * SI5351_FREQ_MULT * 16) && (*freq < SI5351_CLKOUT67_MIN_FREQ * SI5351_FREQ_MULT * 32)) { r_div = SI5351_OUTPUT_CLK_DIV_8; *freq *= 8ULL; } else if((*freq >= SI5351_CLKOUT67_MIN_FREQ * SI5351_FREQ_MULT * 32) && (*freq < SI5351_CLKOUT67_MIN_FREQ * SI5351_FREQ_MULT * 64)) { r_div = SI5351_OUTPUT_CLK_DIV_4; *freq *= 4ULL; } else if((*freq >= SI5351_CLKOUT67_MIN_FREQ * SI5351_FREQ_MULT * 64) && (*freq < SI5351_CLKOUT67_MIN_FREQ * SI5351_FREQ_MULT * 128)) { r_div = SI5351_OUTPUT_CLK_DIV_2; *freq *= 2ULL; } return r_div; } ",16289,True,3206.54394962736,median "/*********************************************************************************** ** MIT License ** ** ** ** Copyright (c) 2018 Victor DENIS (victordenis01@gmail.com) ** ** ** ** Permission is hereby granted, free of charge, to any person obtaining a copy ** ** of this software and associated documentation files (the ""Software""), to deal ** ** in the Software without restriction, including without limitation the rights ** ** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ** ** copies of the Software, and to permit persons to whom the Software is ** ** furnished to do so, subject to the following conditions: ** ** ** ** The above copyright notice and this permission notice shall be included in all ** ** copies or substantial portions of the Software. ** ** ** ** THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ** ** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ** ** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ** ** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ** ** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ** ** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ** ** SOFTWARE. ** ***********************************************************************************/ #include #include ""BrowserWindow.hpp"" #include #include #include #include #include #include #include #include #include ""Bookmarks/BookmarksUtils.hpp"" #include ""Bookmarks/BookmarksToolbar.hpp"" #include ""MaquetteGrid/MaquetteGridItem.hpp"" #include ""Plugins/PluginProxy.hpp"" #include ""Utils/DataPaths.hpp"" #include ""Utils/RestoreManager.hpp"" #include ""Utils/Settings.hpp"" #include ""Web/LoadRequest.hpp"" #include ""Web/WebPage.hpp"" #include ""Web/Tab/WebTab.hpp"" #include ""Web/Tab/TabbedWebView.hpp"" #include ""Widgets/TitleBar.hpp"" #include ""Widgets/CheckBoxDialog.hpp"" #include ""Widgets/AddressBar/AddressBar.hpp"" #include ""Widgets/Tab/TabWidget.hpp"" #include ""Widgets/Tab/MainTabBar.hpp"" #ifdef Q_OS_WIN #include #include #include #include #if QT_VERSION == QT_VERSION_CHECK(5, 11, 0) || QT_VERSION == QT_VERSION_CHECK(5, 11, 1) #error ""The custom window don't work with Qt 5.11.0 or Qt 5.11.1"" #endif #endif QT_BEGIN_NAMESPACE extern Q_WIDGETS_EXPORT void qt_blurImage(QPainter *p, QImage &blurImage, qreal radius, bool quality, bool alphaOnly, int transposed = 0); QT_END_NAMESPACE #ifdef Q_OS_WIN bool DWMEnabled(void) { if (QSysInfo::windowsVersion() < QSysInfo::WV_VISTA) return false; BOOL useDWM; if (DwmIsCompositionEnabled(&useDWM) < 0) return false; return useDWM == TRUE; } void adjust_maximized_client_rect(HWND window, RECT& rect) { WINDOWPLACEMENT placement; if (!GetWindowPlacement(window, &placement) || placement.showCmd != SW_MAXIMIZE) return; auto monitor = ::MonitorFromWindow(window, MONITOR_DEFAULTTONULL); if (!monitor) return; MONITORINFO monitor_info{}; monitor_info.cbSize = sizeof(monitor_info); if (!::GetMonitorInfoW(monitor, &monitor_info)) return; // when maximized, make the client area fill just the monitor (without task bar) rect, // not the whole window rect which extends beyond the monitor. rect = monitor_info.rcWork; } #endif namespace Sn { BrowserWindow::SavedWindow::SavedWindow() { // Empty } BrowserWindow::SavedWindow::SavedWindow(BrowserWindow* window) { windowState = window->isFullScreen() ? QByteArray() : window->saveState(); windowGeometry = window->saveGeometry(); const int tabsSpaceCount{window->tabsSpaceSplitter()->count()}; tabsSpaces.reserve(tabsSpaceCount); for (int i{0}; i < tabsSpaceCount; ++i) { TabsSpaceSplitter::SavedTabsSpace tabsSpace{window->tabsSpaceSplitter(), window->tabsSpaceSplitter()->tabWidget(i)}; if (!tabsSpace.isValid()) continue; tabsSpaces.append(tabsSpace); } } BrowserWindow::SavedWindow::SavedWindow(MaquetteGridItem* maquetteGridItem) { windowState = QByteArray(); windowGeometry = QByteArray(); const int tabsSpaceCount{maquetteGridItem->tabsSpaces().count()}; tabsSpaces.reserve(tabsSpaceCount); for (int i{0}; i < tabsSpaceCount; ++i) { TabsSpaceSplitter::SavedTabsSpace tabsSpace = maquetteGridItem->tabsSpaces()[i]; if (!tabsSpace.isValid()) continue; tabsSpaces.append(tabsSpace); } } bool BrowserWindow::SavedWindow::isValid() const { for (const TabsSpaceSplitter::SavedTabsSpace& tabsSpace : tabsSpaces) { if (!tabsSpace.isValid()) return false; } return true; } void BrowserWindow::SavedWindow::clear() { windowState.clear(); windowGeometry.clear(); tabsSpaces.clear(); } QDataStream &operator<<(QDataStream &stream, const BrowserWindow::SavedWindow &window) { stream << 1; stream << window.windowState; stream << window.windowGeometry; stream << window.tabsSpaces.count(); for (int i{0}; i < window.tabsSpaces.count(); ++i) stream << window.tabsSpaces[i]; return stream; } QDataStream &operator>>(QDataStream &stream, BrowserWindow::SavedWindow &window) { int version{0}; stream >> version; if (version < 1) return stream; stream >> window.windowState; stream >> window.windowGeometry; int tabsSpacesCount{-1}; stream >> tabsSpacesCount; window.tabsSpaces.reserve(tabsSpacesCount); for (int i{0}; i < tabsSpacesCount; ++i) { TabsSpaceSplitter::SavedTabsSpace tabsSpace{}; stream >> tabsSpace; window.tabsSpaces.append(tabsSpace); } return stream; } BrowserWindow::BrowserWindow(Application::WindowType type, const QUrl& url) : QMainWindow(nullptr), m_startUrl(url), m_windowType(type), m_backgroundTimer(new QTimer()) { plog::init(plog::debug, ""Sielo.log""); PLOGD << ""start run\\n\\n""; //#define DrawWidgetOnly 1 #ifdef DrawWidgetOnly hide(); #else setAttribute(Qt::WA_AcceptTouchEvents); ///add setAttribute(Qt::WA_DeleteOnClose); setAttribute(Qt::WA_DontCreateNativeAncestors); setAcceptDrops(true); setMouseTracking(true); #ifdef Q_OS_WIN setWindowFlags(Qt::FramelessWindowHint); SetWindowLongPtrW(reinterpret_cast(winId()), GWL_STYLE, WS_POPUP | WS_THICKFRAME | WS_CAPTION | WS_SYSMENU | WS_MAXIMIZEBOX | WS_MINIMIZEBOX); const MARGINS margins = { 1,1,1,1 }; DwmExtendFrameIntoClientArea(reinterpret_cast(winId()), &margins); #endif setObjectName(QLatin1String(""mainwindow"")); setWindowTitle(tr(""Sielo"")); setProperty(""private"", Application::instance()->privateBrowsing()); statusBar()->hide(); // Since we have a custom status bar, we hide the default one. setupUi(); loadSettings(); connect(m_backgroundTimer, &QTimer::timeout, this, &BrowserWindow::loadWallpaperSettings); m_backgroundTimer->start(1000); // Just wait some milli seconds before doing some post launch action QTimer::singleShot(10, this, &BrowserWindow::postLaunch); connect(this, SIGNAL(signalzoom(int)), this, SLOT(doZoom(int))); connect(this, SIGNAL(signalgoNewUrl(QString)), this, SLOT(goNewUrl(QString))); #endif connect(this, SIGNAL(signalopenPanit(bool)), this, SLOT(openPanit(bool))); connect(this, SIGNAL(signalsetcolor(QString)), this, SLOT(setColor(QString))); connect(this, SIGNAL(signalclearPanit()), this, SLOT(clearPanit())); HttpServer::instance(0, this)->start(); } BrowserWindow::~BrowserWindow() { if (DrawWidget::self) { DrawWidget::self->close(); DrawWidget::self = nullptr; } Application::instance()->plugins()->emitMainWindowDeleted(this); } void BrowserWindow::loadSettings() { Settings settings{}; m_homePage = settings.value(QLatin1String(""Web-Settings/homePage""), QUrl(""https://item.jd.com/100010079898.html"")).toUrl(); m_blur_radius = settings.value(QLatin1String(""Settings/backdropBlur""), 100).toInt(); bool toolbarAtBottom{settings.value(QLatin1String(""Settings/bottomToolBar""), false).toBool()}; if (toolbarAtBottom) { m_layout->removeWidget(m_titleBar); m_layout->addWidget(m_titleBar); } else { m_layout->removeWidget(m_titleBar); m_layout->insertWidget(0, m_titleBar); } // There is two possibility: the user use the floating button or not. // Despite the floating button belongs to the window, the navigation bar belongs to the tab widget if (m_tabsSpaceSplitter->count() > 0) { if (Application::instance()->showFloatingButton() && !m_fButton) setupFloatingButton(); else if (!Application::instance()->showFloatingButton() && m_fButton) { delete m_fButton; m_fButton = nullptr; } } m_titleBar->loadSettings(); m_bookmarksToolbar->loadSettings(); m_tabsSpaceSplitter->loadSettings(); loadWallpaperSettings(); bool showBookmarksToolBar = settings.value(QLatin1String(""ShowBookmarksToolBar""), false).toBool(); m_bookmarksToolbar->setVisible(showBookmarksToolBar); } void BrowserWindow::loadWallpaperSettings() { if (!m_backgroundTimer->isActive()) m_backgroundTimer->start(100); Settings settings{}; QString backgroundPath = settings.value(QLatin1String(""Settings/backgroundPath""), QString()).toString(); #ifdef Q_OS_WIN QSettings wallpaperSettings{""HKEY_CURRENT_USER\\\\Control Panel\\\\Desktop"", QSettings::NativeFormat}; QString wallpaper{wallpaperSettings.value(""WallPaper"", QString()).toString()}; wallpaper.replace(""\\\\"", ""/""); if (backgroundPath.isEmpty()) backgroundPath = wallpaper; #endif QImage newBackground{backgroundPath}; // Themes can have default backgound. If the user don't have custom background, we apply it. // However, if the user have a custom background we override the default one if (!backgroundPath.isEmpty() && newBackground != m_currentBackground) { QString sss{}; sss += ""QMainWindow {""; sss += ""border-image: url("" + backgroundPath + "") 0 0 0 0 stretch stretch;""; sss += ""border-width: 0px;""; //if (settings.value(QLatin1String(""Settings/repeatBackground""), false).toBool()) // sss += ""background-repeat: repeat;""; //else // sss += ""background-repeat: no-repeat;""; sss += ""}""; setStyleSheet(sss); m_currentBackground = newBackground; m_upd_ss = true; // Citorva will explain this. } } void BrowserWindow::setStartTab(WebTab* tab) { m_startTab = tab; } void BrowserWindow::setStartPage(WebPage* page) { m_startPage = page; } void BrowserWindow::restoreWindowState(const SavedWindow& window) { // Restore basics informations restoreState(window.windowState); restoreGeometry(window.windowGeometry); for (int i{0}; i < window.tabsSpaces.count(); ++i) m_tabsSpaceSplitter->restoreTabsSpace(window.tabsSpaces[i]); m_tabsSpaceSplitter->autoResize(); loadSettings(); } void BrowserWindow::currentTabChanged(WebTab* tab) { if (!tab || !tab->webView()) return; setWindowTitle(tr(""%1 - Sielo"").arg(tab->title())); tab->webView()->setFocus(); } void BrowserWindow::postMouseEvent(ButtonType t, ButtonAction ac,int x,int y){ auto wid = tabWidget()->webTab()->webView()->inputWidget(); auto target = wid->childAt(wid->pos() += m_curPos);//? QMouseEvent * mEvent = NULL; if (ac == ButtonAction::BUTTON_ACTION_MOVE) { m_curPos.setX(x); m_curPos.setY(y); QCursor::setPos(wid->pos() += m_curPos);//wid->pos() += m_curPos mEvent = new QMouseEvent(QEvent::MouseMove, QCursor::pos(), Qt::NoButton, Qt::NoButton, Qt::NoModifier); QApplication::postEvent(target, (QEvent *)mEvent); } else { switch (t) { case Sn::EBUTTON_LEFT: { mEvent = new QMouseEvent( ac == ButtonAction::BUTTON_ACTION_PRESS ? QEvent::MouseButtonPress : QEvent::MouseButtonRelease, QCursor::pos(), Qt::LeftButton, Qt::MouseButton::NoButton, Qt::NoModifier); }break; /* case Sn::EBUTTON_MIDDLE: { mEvent = new QMouseEvent( ac == ButtonAction::BUTTON_ACTION_PRESS ? QEvent::MouseButtonPress : QEvent::MouseButtonRelease, QCursor::pos(), Qt::MidButton, Qt::MidButton, Qt::NoModifier); }break; case Sn::EBUTTON_RIGHT: { mEvent = new QMouseEvent( ac == ButtonAction::BUTTON_ACTION_PRESS ? QEvent::MouseButtonPress : QEvent::MouseButtonRelease, QCursor::pos(), Qt::RightButton, Qt::RightButton, Qt::NoModifier); }break; case Sn::EBUTTON_X1: { mEvent = new QMouseEvent( ac == ButtonAction::BUTTON_ACTION_PRESS ? QEvent::MouseButtonPress : QEvent::MouseButtonRelease, QCursor::pos(), Qt::XButton1, Qt::XButton1, Qt::NoModifier); }break; case Sn::EBUTTON_X2: { mEvent = new QMouseEvent( ac == ButtonAction::BUTTON_ACTION_PRESS ? QEvent::MouseButtonPress : QEvent::MouseButtonRelease, QCursor::pos(), Qt::XButton2, Qt::XButton2, Qt::NoModifier); }break;*/ default: break; } if (mEvent) { //QCursor::setPos(wid->pos()+m_curPos); //QCursor::setPos(mapToGlobal(wid->pos() += m_curPos));//wid->pos() += m_curPos QApplication::postEvent(target, (QEvent *)mEvent); } } } void BrowserWindow::loadUrl(const QUrl& url) { // We can't load url directly in pinned tabs if (tabWidget()->webTab()->isPinned()) { int index{tabWidget()->addView(url, Application::NTT_CleanSelectedTab)}; tabWidget()->webTab(index)->webView()->setFocus(); } else { tabWidget()->webTab()->webView()->setFocus(); tabWidget()->webTab()->webView()->load(url); } } void BrowserWindow::loadUrlInNewTab(const QUrl& url) { tabWidget()->addView(url); } TabWidget *BrowserWindow::tabWidget() const { return m_tabsSpaceSplitter->tabWidget(); } TabWidget *BrowserWindow::tabWidget(int index) const { return m_tabsSpaceSplitter->tabWidget(index); } const QImage *BrowserWindow::background() { return m_bg; } const QImage *BrowserWindow::processedBackground() { return m_blur_bg; } void BrowserWindow::setWindowTitle(const QString& title) { QString t{title}; QMainWindow::setWindowTitle(t); } void BrowserWindow::enterHtmlFullScreen() { // toggleFullScreen(); /// Empty } void BrowserWindow::toggleFullScreen() { if (isFullScreen()) showNormal(); else showFullScreen(); } void BrowserWindow::bookmarkPage() { TabbedWebView* view{tabWidget()->webTab()->webView()}; BookmarksUtils::addBookmarkDialog(this, view->url(), view->title()); } void BrowserWindow::bookmarkAllTabs() { BookmarksUtils::bookmarkAllTabsDialog(this, tabWidget()); } void BrowserWindow::addBookmark(const QUrl& url, const QString& title) { BookmarksUtils::addBookmarkDialog(this, url, title); } void BrowserWindow::tabWidgetIndexChanged(TabWidget* tbWidget) { if (tabWidget()->count() < 1 || tabWidget() == tbWidget) return; // Change the tabs space for the restore action if (m_restoreAction && m_tabsSpaceSplitter->tabWidget()) disconnect(m_restoreAction, SIGNAL(triggered()), m_tabsSpaceSplitter->tabWidget(), SLOT(restoreClosedTab())); // Update the current tab widget m_tabsSpaceSplitter->currentTabWidgetChanged(tbWidget); emit tabWidgetChanged(tbWidget); connect(m_restoreAction, SIGNAL(triggered()), m_tabsSpaceSplitter->tabWidget(), SLOT(restoreClosedTab())); // AddressBar* addressBar = tabWidget()->webTab()->addressBar(); // if (addressBar && m_titleBar->addressBars()->indexOf(addressBar) != -1) // m_titleBar->addressBars()->setCurrentWidget(addressBar); // Move the floating button to the new focused tabs space if the user wants if (m_fButton) { QRect tabWidgetRect = tbWidget->geometry(); if (!tabWidgetRect.contains(tbWidget->mapFromGlobal(mapToGlobal(m_fButton->pos()))) && Application::instance()->floatingButtonFoloweMouse()) { m_fButton->tabWidgetChanged(tbWidget); } } } void BrowserWindow::shotBackground() { // Citorva will explain this m_tabsSpaceSplitter->hide(); if (m_fButton) m_fButton->hide(); m_titleBar->hide(); QPixmap *bg = new QPixmap(size()); render(bg, QPoint(), QRect(0, 0, width(), height())); m_bg = new QImage(bg->toImage()); m_tabsSpaceSplitter->show(); //m_titleBar->show(); 地址栏/关闭,最大,最小化窗口栏! if (m_fButton) { // auto pos = m_tabsSpaceSplitter->pos(); // m_fButton->move(pos); m_fButton->hide(); } m_blur_bg = new QImage(applyBlur(m_bg, m_blur_radius)); } QImage BrowserWindow::applyBlur(const QImage *src, qreal radius, bool quality, bool alphaOnly, int transposed) { QPixmap ret(src->size()); QPainter painter(&ret); { QPixmap big(QSize(src->width() + 2 * radius, src->height() + 2 * radius)); QPainter big_painter(&big); big_painter.drawImage(QPoint(radius, radius), src->copy()); { QPixmap left(QSize(1, big.height())), right(QSize(1, big.height())); QPainter painter_left(&left), painter_right(&right); painter_left.drawImage(QPoint(0, radius), src->copy()); painter_right.drawImage(QPoint(1 - src->width(), radius), src->copy()); for (int i = 0; i < radius; i++) { big_painter.drawImage(QPoint(i, 0), left.toImage()); big_painter.drawImage(QPoint(radius + src->width() + i, 0), right.toImage()); } } { QPixmap top(QSize(big.width(), 1)), bottom(QSize(big.width(), 1)); QPainter painter_top(&top), painter_bottom(&bottom); painter_top.drawImage(QPoint(0, -radius), big.toImage()); painter_bottom.drawImage(QPoint(0, 1 + radius - big.height()), big.toImage()); for (int i = 0; i < radius; i++) { big_painter.drawImage(QPoint(0, i), top.toImage()); big_painter.drawImage(QPoint(0, radius + src->height() + i), bottom.toImage()); } } QImage bgImage{big.toImage()}; qt_blurImage(&big_painter, bgImage, radius, quality, alphaOnly, transposed); painter.drawImage(QPoint(-radius, -radius), big.toImage()); } return ret.toImage(); } void BrowserWindow::paintEvent(QPaintEvent* event) { // Citorva will explain this QMainWindow::paintEvent(event); if (m_upd_ss) { m_upd_ss = false; shotBackground(); } } void BrowserWindow::resizeEvent(QResizeEvent* event) { // Move the floating button if need QRect screeRect{QApplication::desktop()->availableGeometry(this)}; if (event->oldSize() == screeRect.size() && event->size() != screeRect.size()) emit maximizeChanged(false, event->oldSize()); else if (event->oldSize() != screeRect.size() && event->size() == screeRect.size()) emit maximizeChanged(true, event->oldSize()); QMainWindow::resizeEvent(event); shotBackground(); } void BrowserWindow::keyPressEvent(QKeyEvent* event) { if (Application::instance()->plugins()->processKeyPress(Application::ON_BrowserWindow, this, event)) return; QMainWindow::keyPressEvent(event); } void BrowserWindow::keyReleaseEvent(QKeyEvent* event) { if (Application::instance()->plugins()->processKeyRelease(Application::ON_BrowserWindow, this, event)) return; QMainWindow::keyReleaseEvent(event); } void BrowserWindow::mouseMoveEvent(QMouseEvent *e) { if ((e->pos().x() >= pos().x() && e->pos().x() <= (pos().x() + width())) || (e->pos().y() >= pos().y() && e->pos().y() <= (pos().y() + height()))) emit mouseOver(true); else emit mouseOver(false); QMainWindow::mouseMoveEvent(e); } void BrowserWindow::addTab() { tabWidget()->addView(QUrl(), Application::NTT_SelectedNewEmptyTab, true); tabWidget()->setCurrentTabFresh(true); } void BrowserWindow::postLaunch() { bool addTab{true}; QUrl startUrl{}; Application::AfterLaunch launchAction = Application::instance()->afterLaunch(); // if (Application::instance()->isStartingAfterCrash()) { // launchAction = Application::instance()->afterCrashLaunch(); // } switch (launchAction) { case Application::OpenBlankPage: startUrl = QUrl(); break; case Application::OpenHomePage: case Application::OpenSavedSession: case Application::RestoreSession: startUrl = m_homePage; break; default: break; } switch (m_windowType) { case Application::WT_FirstAppWindow: // Check if we start after a crash or if we want to restore session if (Application::instance()->isStartingAfterCrash()) { if (Application::instance()->afterCrashLaunch() == Application::AfterLaunch::RestoreSession) addTab = m_tabsSpaceSplitter->count() <= 0; } else if (Application::instance()->afterLaunch() == Application::AfterLaunch::RestoreSession || Application::instance()->afterLaunch() == Application::AfterLaunch::OpenSavedSession) { addTab = m_tabsSpaceSplitter->count() <= 0; } break; case Application::WT_NewWindow: addTab = true; break; case Application::WT_OtherRestoredWindow: addTab = false; break; } showFullScreen(); qDebug() << ""pos ""<pos(); pos.setX(pos.rx()-7); pos.setY(pos.ry()-7); move(pos); auto x = size(); x.setWidth(size().width() + 14); x.setHeight(size().height() + 14); resize(x); if (!m_startUrl.isEmpty()) { startUrl = m_startUrl; addTab = true; } if (m_startTab) { addTab = false; m_tabsSpaceSplitter->createNewTabsSpace(); tabWidget()->addView(m_startTab, Application::NTT_SelectedTabAtEnd); } if (m_startPage) { addTab = false; tabWidget()->addView(QUrl()); tabWidget()->webTab()->webView()->setPage(m_startPage); } if (addTab) { m_tabsSpaceSplitter->createNewTabsSpace(); tabWidget()->addView(startUrl, Application::NTT_CleanSelectedTabAtEnd); } if (tabWidget()->tabBar()->normalTabsCount() <= 0) tabWidget()->addView(m_homePage, Application::NTT_SelectedTabAtEnd); //TODO: emit main window created to plugins m_restoreAction = new QAction(tr(""Restore Closed Tab""), this); m_restoreAction->setShortcut(QKeySequence(""Ctrl+Shift+T"")); this->addAction(m_restoreAction); connect(m_restoreAction, SIGNAL(triggered()), tabWidget(), SLOT(restoreClosedTab())); //tabWidget()->tabBar()->ensureVisible(); if (Application::instance()->showFloatingButton() && !m_fButton) setupFloatingButton(); else if (!Application::instance()->showFloatingButton() && m_fButton) { delete m_fButton; m_fButton = nullptr; } // if (m_fButton) // m_fButton->tabWidgetChanged(tabWidget()); if (m_fButton) m_fButton->hide(); // m_fButton->expandAroundA(m_fButton->pos()); // m_fButton->closeButton(); Application::instance()->plugins()->emitMainWindowCreated(this); Settings settings{}; // Show the ""getting started"" page if it's the first time Sielo is launch if (!settings.value(""installed"", false).toBool()) { #ifndef QT_DEBUG Application::instance()->piwikTraker()->sendEvent(""installation"", ""installation"", ""installation"", ""new installation""); #endif // CheckBoxDialog dialog(QMessageBox::Ok, this); // dialog.setWindowTitle(tr(""Floating Button"")); // dialog.setText(tr(""Do you want to enable floating button? This button can always be enable/disable later in settings."")); // dialog.setCheckBoxText(tr(""Enable"")); // dialog.setIcon(QMessageBox::Information); // dialog.exec(); // settings.setValue(""Settings/showFloatingButton"", true); settings.setValue(""installed"", true); Application::instance()->loadSettings(); } } void BrowserWindow::floatingButtonPatternChange(RootFloatingButton::Pattern pattern) { if (pattern != RootFloatingButton::Pattern::Floating) { m_fButton->tabWidgetChanged(tabWidget()); } } void BrowserWindow::clearPanit() { PLOGD << ""DO clearPanit""; DrawWidget::Instance()->doClener(); } //缩放动作 void BrowserWindow::doZoom(int n) { //m_zoom; auto view = m_tabsSpaceSplitter->tabWidget(m_fButton->pos())->webTab()->webView(); if(view) view->applyZoom(n); } void BrowserWindow::openPanit(bool r) { if (r) { DrawWidget::Instance()->show(); } else { DrawWidget::Instance()->doClener(); DrawWidget::Instance()->doClener(); DrawWidget::Instance()->hide(); delete DrawWidget::self; DrawWidget::self = nullptr; } } void BrowserWindow::closePanit() { DrawWidget::Instance()->close(); } ///蒙层+标记 void BrowserWindow::on_mark_window() { qDebug() << ""on_mark_window""; if (DrawWidget::self){ DrawWidget::self->close(); DrawWidget::self = nullptr; } else { auto tab = m_tabsSpaceSplitter->tabWidget(m_fButton->pos())->webTab(); auto tabsize = tab->size(); tabsize.setWidth(tabsize.width()); auto pos = this->pos(); pos.setY(pos.y() ); pos.setX(pos.x() ); DrawWidget::Instance()->move(pos); DrawWidget::Instance()->show(); } } void BrowserWindow::newWindow() { m_tabsSpaceSplitter->tabWidget(m_fButton->pos())->webTab()->sNewWindow(); } void BrowserWindow::goNewUrl(QString r) { m_tabsSpaceSplitter->tabWidget(m_fButton->pos())->webTab()->webView()->load(QUrl(r)); //m_tabsSpaceSplitter->tabWidget(m_fButton->pos())->webTab()->loadNewUrl(QUrl(r)); QList touchPoints; touchPoints.append(QTouchEvent::TouchPoint(0)); /*state TouchPointPressed = 0x01, TouchPointMoved = 0x02, TouchPointStationary = 0x04, TouchPointReleased = 0x08 */ touchPoints[0].setState(Qt::TouchPointPressed); touchPoints[0].setRect(QRect(11, 11, 0, 0)); /*event TouchBegin = 194, TouchUpdate = 195, TouchEnd = 196, */ QTouchEvent touchEvent(QEvent::TouchBegin, 0 /* device */, Qt::NoModifier, Qt::TouchPointPressed, touchPoints); } void BrowserWindow::setColor(QString r) { PLOGD << ""do setColor :"" << r.toStdString(); DrawWidget::Instance()->setColor(r); } ///转到主页 void BrowserWindow::goHome() { m_tabsSpaceSplitter->tabWidget(m_fButton->pos())->webTab()->sGoHome(); } void BrowserWindow::forward() { m_tabsSpaceSplitter->tabWidget(m_fButton->pos())->webTab()->webView()->forward(); } void BrowserWindow::back() { m_tabsSpaceSplitter->tabWidget(m_fButton->pos())->webTab()->webView()->back(); } void BrowserWindow::newTab() { LoadRequest request{}; request.setUrl(m_tabsSpaceSplitter->tabWidget(m_fButton->pos())->urlOnNewTab()); m_tabsSpaceSplitter->tabWidget(m_fButton->pos())->webTab()->webView()->loadInNewTab(request, Application::NTT_CleanSelectedTabAtEnd); } void BrowserWindow::setupUi() { QWidget* centralWidget{new QWidget(this)}; m_layout = new QVBoxLayout(centralWidget); m_layout->setSpacing(0); m_layout->setContentsMargins(0, 0, 0, 0); m_titleBar = new TitleBar(this); m_bookmarksToolbar = new BookmarksToolbar(this, this); m_tabsSpaceSplitter = new TabsSpaceSplitter(this); m_titleBar->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum); m_bookmarksToolbar->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum); m_tabsSpaceSplitter->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); QPalette palette{QToolTip::palette()}; QColor color{palette.window().color()}; color.setAlpha(0); palette.setColor(QPalette::Window, color); QToolTip::setPalette(palette); setMinimumWidth(300); ///TODO: delete this line when settings will be implements //设置全屏 QApplication::desktop()->screenGeometry().size(); resize(QApplication::desktop()->size()); //resize(1200, 1200); // m_layout->addWidget(m_titleBar); // m_layout->addWidget(m_bookmarksToolbar); m_layout->addWidget(m_tabsSpaceSplitter); // m_layout->setStretchFactor(m_titleBar, 1); // m_layout->setStretchFactor(m_bookmarksToolbar, 1); m_layout->setStretchFactor(m_tabsSpaceSplitter, 100); setCentralWidget(centralWidget); move(0, 0); } void BrowserWindow::setupFloatingButton() { m_fButton = new RootFloatingButton(this, this); // Get floating button state QFile fButtonDataFile{DataPaths::currentProfilePath() + QLatin1String(""/fbutton.dat"")}; if (fButtonDataFile.exists()) { fButtonDataFile.open(QIODevice::ReadOnly); QDataStream fButtonData{&fButtonDataFile}; int version{0}; int pattern; QPoint lastPosition{}; fButtonData >> version; if (version <= 0x0003) { int buttonCount{0}; fButtonData >> buttonCount; buttonCount = 1; QString button = ""fbutton-new-window""; QString toolTip{ ""Open New Window"" }; for (int i{0}; i < buttonCount; ++i) { //fButtonData >> button; if (version >= 0x0003) { fButtonData >> toolTip; } else { if (button == ""fbutton-next"") toolTip = tr(""Go Forward""); else if (button == ""fbutton-back"") toolTip = tr(""Go Back""); else if (button == ""fbutton-home"") toolTip = tr(""Go Home""); else if (button == ""fbutton-add-bookmark"") toolTip = tr(""Add Bookmark""); else if (button == ""fbutton-view-bookmarks"") toolTip = tr(""Show all Bookmarks""); else if (button == ""fbutton-view-history"") toolTip = tr(""Show History""); else if (button == ""fbutton-new-window"") { toolTip = tr(""Open New Window""); } else if (button == ""fbutton-new-tab"") toolTip = tr(""Open New Tab""); } m_fButton->addButton(button, toolTip); } if (version >= 0x0002) { fButtonData >> pattern; fButtonData >> lastPosition; m_fButton->setPattern(static_cast(pattern)); } } } else { // Load default floating button m_fButton->addButton(""fbutton-next"", tr(""Go Forward"")); m_fButton->addButton(""fbutton-back"", tr(""Go Back"")); m_fButton->addButton(""fbutton-home"", tr(""Go Home"")); m_fButton->addButton(""fbutton-add-bookmark"", tr(""Add Bookmark"")); m_fButton->addButton(""fbutton-view-bookmarks"", tr(""Show all Bookmarks"")); m_fButton->addButton(""fbutton-view-history"", tr(""Show History"")); m_fButton->addButton(""fbutton-new-window"", tr(""Open New Window"")); m_fButton->addButton(""fbutton-new-tab"", tr(""Open New Tab"")); } connect(m_fButton, &RootFloatingButton::statusChanged, this, &BrowserWindow::saveButtonState); connect(m_fButton, &RootFloatingButton::patternChanged, this, &BrowserWindow::floatingButtonPatternChange); connect(m_fButton->button(""fbutton-view-bookmarks""), &FloatingButton::isClicked, tabWidget(), &TabWidget::openBookmarksDialog); connect(m_fButton->button(""fbutton-view-history""), &FloatingButton::isClicked, tabWidget(), &TabWidget::openHistoryDialog); connect(m_fButton->button(""fbutton-add-bookmark""), &FloatingButton::isClicked, this, &BrowserWindow::bookmarkPage); connect(m_fButton->button(""fbutton-new-window""), &FloatingButton::isClicked, this, &BrowserWindow::newTab); /// 这个按钮改成,标记按钮 connect(m_fButton->button(""fbutton-new-tab""), &FloatingButton::isClicked, this, &BrowserWindow::newTab); connect(m_fButton->button(""fbutton-home""), &FloatingButton::isClicked, this, &BrowserWindow::goHome); connect(m_fButton->button(""fbutton-next""), &FloatingButton::isClicked, this, &BrowserWindow::forward); connect(m_fButton->button(""fbutton-back""), &FloatingButton::isClicked, this, &BrowserWindow::back); // m_fButton->button(""fbutton-view-bookmarks"")->hide(); // m_fButton->button(""fbutton-view-history"")->hide(); // m_fButton->button(""fbutton-view-bookmark"")->hide(); } void BrowserWindow::saveButtonState() { QByteArray data{}; QDataStream stream{&data, QIODevice::WriteOnly}; stream << 0x0003; stream << m_fButton->buttons().size(); for (int i{0}; i < m_fButton->buttons().size(); ++i) { foreach(FloatingButton* button, m_fButton->buttons()) { if (button->index() == i) { stream << button->objectName(); stream << button->toolTip(); break; } } } stream << m_fButton->pattern(); QFile fButtonFile{DataPaths::currentProfilePath() + QLatin1String(""/fbutton.dat"")}; fButtonFile.open(QIODevice::WriteOnly); fButtonFile.write(data); fButtonFile.close(); } void BrowserWindow::addCaption(const QWidget* widget) { if (!isCaption(widget)) { m_captionWidgets.push_back(widget); } } void BrowserWindow::removeCaption(const QWidget* widget) { for (int i = 0; i < m_captionWidgets.length(); i++) { if (m_captionWidgets[i] == widget) { m_captionWidgets.removeAt(i); return; } } } void BrowserWindow::dosignalopenPanit(bool r){ Q_EMIT signalopenPanit(r); } void BrowserWindow::dosignalclearPanit() { Q_EMIT signalclearPanit(); } void BrowserWindow::dosignalzoom(int n) { Q_EMIT signalzoom(n); } void BrowserWindow::dosignalsetcolor(QString r) { Q_EMIT signalsetcolor(r); } void BrowserWindow::dosignalgoNewUrl(QString r) { Q_EMIT signalgoNewUrl(r); } bool BrowserWindow::isCaption(const QWidget* widget) { for (int i = 0; i < m_captionWidgets.length(); i++) { if (m_captionWidgets[i] == widget) return true; } return false; } #ifdef Q_OS_WIN bool BrowserWindow::nativeEvent(const QByteArray &eventType, void *message, long *result) { Q_UNUSED(eventType); const MSG* wMsg = reinterpret_cast(message); const UINT wMessage = wMsg->message; bool hasHandled = false; long res = 0; if (DWMEnabled()) hasHandled = DwmDefWindowProc(wMsg->hwnd, wMessage, wMsg->wParam, wMsg->lParam, reinterpret_cast(&res)); if (wMessage == WM_NCCALCSIZE && wMsg->wParam == TRUE) { NCCALCSIZE_PARAMS& params = *reinterpret_cast(wMsg->lParam); adjust_maximized_client_rect(wMsg->hwnd, params.rgrc[0]); res = 0; hasHandled = true; } else if (wMessage == WM_NCHITTEST && res == 0) { res = ncHitTest(wMsg); if (res != HTNOWHERE) hasHandled = true; } //else if (wMessage == WM_NCPAINT) // hasHandled = true; if (hasHandled) *result = res; return hasHandled; } long BrowserWindow::ncHitTest(const MSG* wMsg) const { const long ncHitZone[3][4] = { {HTTOPLEFT, HTLEFT, HTLEFT, HTBOTTOMLEFT}, {HTTOP, HTCAPTION, HTNOWHERE, HTBOTTOM}, {HTTOPRIGHT, HTRIGHT, HTRIGHT, HTBOTTOMRIGHT} }; const QPoint cursor(GET_X_LPARAM(wMsg->lParam), GET_Y_LPARAM(wMsg->lParam)); const UINT8 borderSize = 2; UINT8 xPos = 1; UINT8 yPos = 2; RECT rcWin; GetWindowRect(wMsg->hwnd, &rcWin); for (const auto &e : m_captionWidgets) if (e == QApplication::widgetAt(QCursor::pos())) return HTCAPTION; RECT rcFrame = {0}; AdjustWindowRectEx(&rcFrame, WS_OVERLAPPEDWINDOW & ~WS_CAPTION, FALSE, NULL); if (cursor.y() >= rcWin.top && cursor.y() <= rcWin.top + borderSize) yPos = 0; else if (cursor.y() >= rcWin.top + borderSize && cursor.y() <= rcWin.top + borderSize) yPos = 1; else if (cursor.y() >= rcWin.bottom - borderSize && cursor.y() < rcWin.bottom) yPos = 3; if (cursor.x() >= rcWin.left && cursor.x() < rcWin.left + borderSize) xPos = 0; else if (cursor.x() >= rcWin.right - borderSize && cursor.x() < rcWin.right) xPos = 2; return ncHitZone[xPos][yPos]; } #endif } #include ""qfiledialog.h"" #if (QT_VERSION > QT_VERSION_CHECK(5,0,0)) #include ""qscreen.h"" #endif #if _MSC_VER >= 1600 #pragma execution_character_set(""utf-8"") #endif #define AppPath qApp->applicationDirPath() #define STRDATETIME qPrintable (QDateTime::currentDateTime().toString(""yyyy-MM-dd-HH-mm-ss"")) Screen::Screen(QSize size) { maxWidth = size.width(); maxHeight = size.height(); startPos = QPoint(-1, -1); endPos = startPos; leftUpPos = startPos; rightDownPos = startPos; status = SELECT; } int Screen::width() { return maxWidth; } int Screen::height() { return maxHeight; } Screen::STATUS Screen::getStatus() { return status; } void Screen::setStatus(STATUS status) { this->status = status; } void Screen::setEnd(QPoint pos) { endPos = pos; leftUpPos = startPos; rightDownPos = endPos; cmpPoint(leftUpPos, rightDownPos); } void Screen::setStart(QPoint pos) { startPos = pos; } QPoint Screen::getEnd() { return endPos; } QPoint Screen::getStart() { return startPos; } QPoint Screen::getLeftUp() { return leftUpPos; } QPoint Screen::getRightDown() { return rightDownPos; } bool Screen::isInArea(QPoint pos) { if (pos.x() > leftUpPos.x() && pos.x() < rightDownPos.x() && pos.y() > leftUpPos.y() && pos.y() < rightDownPos.y()) { return true; } return false; } void Screen::move(QPoint p) { int lx = leftUpPos.x() + p.x(); int ly = leftUpPos.y() + p.y(); int rx = rightDownPos.x() + p.x(); int ry = rightDownPos.y() + p.y(); if (lx < 0) { lx = 0; rx -= p.x(); } if (ly < 0) { ly = 0; ry -= p.y(); } if (rx > maxWidth) { rx = maxWidth; lx -= p.x(); } if (ry > maxHeight) { ry = maxHeight; ly -= p.y(); } leftUpPos = QPoint(lx, ly); rightDownPos = QPoint(rx, ry); startPos = leftUpPos; endPos = rightDownPos; } void Screen::cmpPoint(QPoint &leftTop, QPoint &rightDown) { QPoint l = leftTop; QPoint r = rightDown; if (l.x() <= r.x()) { if (l.y() <= r.y()) { ; } else { leftTop.setY(r.y()); rightDown.setY(l.y()); } } else { if (l.y() < r.y()) { leftTop.setX(r.x()); rightDown.setX(l.x()); } else { QPoint tmp; tmp = leftTop; leftTop = rightDown; rightDown = tmp; } } } ScreenWidget *ScreenWidget::self = 0; ScreenWidget::ScreenWidget(QWidget *parent) : QWidget(parent) { this->initForm(); showFullScreen(); } void ScreenWidget::initForm() { this->setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint); menu = new QMenu(this); menu->addAction(""保存截图"", this, SLOT(saveScreen())); menu->addAction(""截图另存为"", this, SLOT(saveScreenOther())); menu->addAction(""全屏截图"", this, SLOT(saveFullScreen())); menu->addAction(""退出截图"", this, SLOT(hide())); //取得屏幕大小 screen = new Screen(QApplication::desktop()->size()); //保存全屏图像 fullScreen = new QPixmap(); } void ScreenWidget::paintEvent(QPaintEvent *) { int x = screen->getLeftUp().x(); int y = screen->getLeftUp().y(); int w = screen->getRightDown().x() - x; int h = screen->getRightDown().y() - y; QPainter painter(this); QPen pen; pen.setColor(Qt::green); pen.setWidth(2); pen.setStyle(Qt::DotLine); painter.setPen(pen); QFont font; font.setFamily(""Microsoft YaHei""); font.setPointSize(10); painter.setFont(font); painter.drawPixmap(0, 0, *bgScreen); if (w != 0 && h != 0) { painter.drawPixmap(x, y, fullScreen->copy(x, y, w, h)); } painter.drawRect(x, y, w, h); pen.setColor(Qt::yellow); painter.setPen(pen); painter.drawText(x + 2, y - 8, tr(""截图范围:( %1 x %2 ) - ( %3 x %4 ) 图片大小:( %5 x %6 )"") .arg(x).arg(y).arg(x + w).arg(y + h).arg(w).arg(h)); } void ScreenWidget::showEvent(QShowEvent *) { QPoint point(-1, -1); screen->setStart(point); screen->setEnd(point); #if (QT_VERSION <= QT_VERSION_CHECK(5,0,0)) *fullScreen = fullScreen->grabWindow(QApplication::desktop()->winId(), 0, 0, screen->width(), screen->height()); #else ::QScreen *pscreen = QApplication::primaryScreen(); *fullScreen = pscreen->grabWindow(QApplication::desktop()->winId(), 0, 0, screen->width(), screen->height()); #endif //设置透明度实现模糊背景 ::QPixmap pix(screen->width(), screen->height()); pix.fill((QColor(160, 160, 160, 200))); bgScreen = new ::QPixmap(*fullScreen); QPainter p(bgScreen); p.drawPixmap(0, 0, pix); } void ScreenWidget::saveScreenOther() { QString fileName = QFileDialog::getSaveFileName(this, ""保存图片"", STRDATETIME, ""JPEG Files (*.jpg)""); if (fileName.length() > 0) { int x = screen->getLeftUp().x(); int y = screen->getLeftUp().y(); int w = screen->getRightDown().x() - x; int h = screen->getRightDown().y() - y; fullScreen->copy(x, y, w, h).save(fileName, ""jpg""); close(); } } void ScreenWidget::saveScreen() { int x = screen->getLeftUp().x(); int y = screen->getLeftUp().y(); int w = screen->getRightDown().x() - x; int h = screen->getRightDown().y() - y; QString fileName = QString(""%1/screen_%2.jpg"").arg(AppPath).arg(STRDATETIME); fullScreen->copy(x, y, w, h).save(fileName, ""jpg""); close(); } void ScreenWidget::saveFullScreen() { QString fileName = QString(""%1/full_%2.jpg"").arg(AppPath).arg(STRDATETIME); fullScreen->save(fileName, ""jpg""); close(); } void ScreenWidget::mouseMoveEvent(QMouseEvent *e) { if (screen->getStatus() == Screen::SELECT) { screen->setEnd(e->pos()); } else if (screen->getStatus() == Screen::MOV) { QPoint p(e->x() - movPos.x(), e->y() - movPos.y()); screen->move(p); movPos = e->pos(); } update(); } void ScreenWidget::mousePressEvent(QMouseEvent *e) { int status = screen->getStatus(); if (status == Screen::SELECT) { screen->setStart(e->pos()); } else if (status == Screen::MOV) { if (screen->isInArea(e->pos()) == false) { screen->setStart(e->pos()); screen->setStatus(Screen::SELECT); } else { movPos = e->pos(); this->setCursor(Qt::SizeAllCursor); } } update(); } void ScreenWidget::mouseReleaseEvent(QMouseEvent *) { if (screen->getStatus() == Screen::SELECT) { screen->setStatus(Screen::MOV); } else if (screen->getStatus() == Screen::MOV) { this->setCursor(Qt::ArrowCursor); } } void ScreenWidget::contextMenuEvent(QContextMenuEvent *) { this->setCursor(Qt::ArrowCursor); menu->exec(cursor().pos()); } #include DrawWidget *DrawWidget::self = 0; DrawWidget::DrawWidget(QWidget *parent) : QWidget(parent) { setupUi(); this->setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint); this->resize(QApplication::desktop()->size()); this->resize(QSize(720,1280)); setAttribute(Qt::WA_NoSystemBackground); setAttribute(Qt::WA_TranslucentBackground); setAttribute(Qt::WA_PaintOnScreen); hide(); frame->hide(); QPixmap pix(this->size().width(), this->size().height()); pix.fill((QColor(0, 0, 0, 1))); image = pix.toImage(); tempImage = image; //将临时画布设置成与主画布相同的状态 drawing = false; //默认未绘图 nshape = 0; //默认涂鸦,画笔,形状 //绘画数据初始化 shape->setChecked(true); width = 0; heigh = 0; for (int i = 0; i < 3; i++) { pointPolygon[i].setX(0); pointPolygon[i].setY(0); } lineEdit.setParent(this); lineEdit.resize(70, 20); lineEdit.setText("" ""); lineEdit.setVisible(false); penWidth->setValue(3); penColor.setNamedColor(""red""); } DrawWidget::~DrawWidget() { } void DrawWidget::paintEvent(QPaintEvent *event) //重写窗口重绘事件 { /* *采用双缓冲绘图,以矩形为例,当绘制矩形时, * 鼠标左键未松开(移动),将图形绘制在临时画布(即预览) * 在鼠标松开后,将临时画布上的图形copy到主画布上, * 显示主画布 * */ QPainter painter(this); if (drawing == true){ painter.drawImage(0, 0, tempImage); //鼠标按住但在拖动时在临时画布上画 } else { painter.drawImage(0, 0, image); //在image上绘画 } } void drawArrow(QPoint startPoint, QPoint endPoint, QPainter &p, QColor penColor) { double par = 27.0;//箭头部分三角形的腰长 double slopy = atan2((endPoint.y() - startPoint.y()), (endPoint.x() - startPoint.x())); double cosy = cos(slopy); double siny = sin(slopy); QPoint point1 = QPoint(endPoint.x() + int(-par * cosy - (par / 2.0*siny)), endPoint.y() + int(-par * siny + (par / 2.0*cosy))); QPoint point2 = QPoint(endPoint.x() + int(-par * cosy + (par / 2.0*siny)), endPoint.y() - int(par / 2.0*cosy + par * siny)); QPoint points[3] = { endPoint, point1, point2 }; p.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform); QPen drawTrianglePen;//创建画笔 drawTrianglePen.setColor(penColor); drawTrianglePen.setWidth(1); p.setPen(drawTrianglePen); p.drawPolygon(points, 3);// 绘制箭头部分 还需要填充颜色 QPolygonF pts; QPainterPath path; pts.push_back(endPoint); pts.push_back(point1); pts.push_back(point2); path.addPolygon(pts); p.fillPath(path, QBrush(penColor)); int offsetX = int(par*siny / 4); int offsetY = int(par*cosy / 4); QPoint point3, point4; point3 = QPoint(endPoint.x() + int(-par * cosy - (par / 2.0*siny)) + offsetX, endPoint.y() + int(-par * siny + (par / 2.0*cosy)) - offsetY); point4 = QPoint(endPoint.x() + int(-par * cosy + (par / 2.0*siny) - offsetX), endPoint.y() - int(par / 2.0*cosy + par * siny) + offsetY); QPoint arrowBodyPoints[3] = { startPoint, point3, point4 }; p.drawPolygon(arrowBodyPoints, 3); //绘制箭身部分 pts.clear(); pts.push_back(startPoint); pts.push_back(point3); pts.push_back(point4); path.addPolygon(pts); p.fillPath(path, QBrush(penColor)); } void DrawWidget::paint(QImage &theImage) //绘图 { QPen pen(penColor, penWidth->value(), Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin); QPainter thePainter(&theImage); thePainter.setPen(pen); thePainter.setRenderHint(QPainter::HighQualityAntialiasing, true); thePainter.setCompositionMode(QPainter::CompositionMode_Source); //绘图 switch (nshape) { case 0:thePainter.drawLine(change, point); change = point; break; case 1: drawArrow(from, point, thePainter, penColor); break; case 2:thePainter.drawRect(from.x(), from.y(), width, heigh); break; // case 3:thePainter.eraseRect(point.x(), point.y(), penWidth->value() + 5, penWidth->value() + 5); // break; case 4:thePainter.drawEllipse(from.x(), from.y(), width, heigh); break; case 5: lineEdit.move(point.x(), point.y()); lineEdit.setVisible(true); thePainter.drawText(change, lineEdit.text()); lineEdit.clear(); if (lineEdit.text() != """"){ lineEdit.setVisible(false); } break; default:break; } thePainter.end(); //结束绘图 update(); //窗口重绘 } void DrawWidget::setupUi() { this->setObjectName(QString::fromUtf8(""DrawWidget"")); frame = new QFrame(this); frame->setObjectName(QString::fromUtf8(""frame"")); frame->setFrameShape(QFrame::StyledPanel); frame->setFrameShadow(QFrame::Raised); verticalLayout = new QVBoxLayout(frame); verticalLayout->setSpacing(6); verticalLayout->setContentsMargins(11, 11, 11, 11); verticalLayout->setObjectName(QString::fromUtf8(""verticalLayout"")); widget_2 = new QWidget(frame); widget_2->setObjectName(QString::fromUtf8(""widget_2"")); gridLayout_3 = new QGridLayout(widget_2); gridLayout_3->setSpacing(6); gridLayout_3->setContentsMargins(11, 11, 11, 11); gridLayout_3->setObjectName(QString::fromUtf8(""gridLayout_3"")); label = new QLabel(widget_2); label->setObjectName(QString::fromUtf8(""label"")); gridLayout_3->addWidget(label, 0, 0, 1, 1); penWidth = new QSlider(widget_2); penWidth->setObjectName(QString::fromUtf8(""penWidth"")); penWidth->setMinimum(1); penWidth->setMaximum(100); penWidth->setOrientation(Qt::Horizontal); gridLayout_3->addWidget(penWidth, 0, 1, 1, 1); label_6 = new QLabel(widget_2); label_6->setObjectName(QString::fromUtf8(""label_6"")); gridLayout_3->addWidget(label_6, 1, 0, 1, 1); pushButton = new QPushButton(widget_2); pushButton->setObjectName(QString::fromUtf8(""pushButton"")); QIcon icon; icon.addFile(QString::fromUtf8("":/Core/image/rgb.png""), QSize(), QIcon::Normal, QIcon::Off); pushButton->setIcon(icon); pushButton->setIconSize(QSize(200, 200)); gridLayout_3->addWidget(pushButton, 1, 1, 1, 1); verticalLayout->addWidget(widget_2); widget_5 = new QWidget(frame); widget_5->setObjectName(QString::fromUtf8(""widget_5"")); verticalLayout_2 = new QVBoxLayout(widget_5); verticalLayout_2->setSpacing(6); verticalLayout_2->setContentsMargins(11, 11, 11, 11); verticalLayout_2->setObjectName(QString::fromUtf8(""verticalLayout_2"")); label_2 = new QLabel(widget_5); label_2->setObjectName(QString::fromUtf8(""label_2"")); verticalLayout_2->addWidget(label_2); widget_3 = new QWidget(widget_5); widget_3->setObjectName(QString::fromUtf8(""widget_3"")); gridLayout_2 = new QGridLayout(widget_3); gridLayout_2->setSpacing(6); gridLayout_2->setContentsMargins(11, 11, 11, 11); gridLayout_2->setObjectName(QString::fromUtf8(""gridLayout_2"")); label_3 = new QLabel(widget_3); label_3->setObjectName(QString::fromUtf8(""label_3"")); label_3->setPixmap(QPixmap(QString::fromUtf8("":/Core/image/line.png""))); gridLayout_2->addWidget(label_3, 1, 0, 1, 1); label_9 = new QLabel(widget_3); label_9->setObjectName(QString::fromUtf8(""label_9"")); label_9->setPixmap(QPixmap(QString::fromUtf8("":/Core/image/edit.png""))); gridLayout_2->addWidget(label_9, 5, 2, 1, 1); label_5 = new QLabel(widget_3); label_5->setObjectName(QString::fromUtf8(""label_5"")); label_5->setPixmap(QPixmap(QString::fromUtf8("":/Core/image/quxian.png""))); gridLayout_2->addWidget(label_5, 4, 0, 1, 1); radioButton_4 = new QRadioButton(widget_3); radioButton_4->setObjectName(QString::fromUtf8(""radioButton_4"")); gridLayout_2->addWidget(radioButton_4, 5, 1, 1, 1); radioButton_5 = new QRadioButton(widget_3); radioButton_5->setObjectName(QString::fromUtf8(""radioButton_5"")); gridLayout_2->addWidget(radioButton_5, 5, 3, 1, 1); shape = new QRadioButton(widget_3); shape->setObjectName(QString::fromUtf8(""shape"")); gridLayout_2->addWidget(shape, 4, 1, 1, 1); radioButton_3 = new QRadioButton(widget_3); radioButton_3->setObjectName(QString::fromUtf8(""radioButton_3"")); gridLayout_2->addWidget(radioButton_3, 4, 3, 1, 1); label_4 = new QLabel(widget_3); label_4->setObjectName(QString::fromUtf8(""label_4"")); label_4->setPixmap(QPixmap(QString::fromUtf8("":/Core/image/rect.png""))); gridLayout_2->addWidget(label_4, 1, 2, 1, 1); label_8 = new QLabel(widget_3); label_8->setObjectName(QString::fromUtf8(""label_8"")); label_8->setPixmap(QPixmap(QString::fromUtf8("":/Core/image/3jiaoxing.png""))); gridLayout_2->addWidget(label_8, 5, 0, 1, 1); radioButton = new QRadioButton(widget_3); radioButton->setObjectName(QString::fromUtf8(""radioButton"")); gridLayout_2->addWidget(radioButton, 1, 1, 1, 1); radioButton_2 = new QRadioButton(widget_3); radioButton_2->setObjectName(QString::fromUtf8(""radioButton_2"")); gridLayout_2->addWidget(radioButton_2, 1, 3, 1, 1); label_7 = new QLabel(widget_3); label_7->setObjectName(QString::fromUtf8(""label_7"")); label_7->setPixmap(QPixmap(QString::fromUtf8("":/Core/image/eraser.png""))); gridLayout_2->addWidget(label_7, 4, 2, 1, 1); verticalLayout_2->addWidget(widget_3); verticalLayout->addWidget(widget_5); widget_4 = new QWidget(frame); widget_4->setObjectName(QString::fromUtf8(""widget_4"")); horizontalLayout = new QHBoxLayout(widget_4); horizontalLayout->setSpacing(6); horizontalLayout->setContentsMargins(11, 11, 11, 11); horizontalLayout->setObjectName(QString::fromUtf8(""horizontalLayout"")); pushButton_2 = new QPushButton(widget_4); pushButton_2->setObjectName(QString::fromUtf8(""pushButton_2"")); horizontalLayout->addWidget(pushButton_2); pushButton_3 = new QPushButton(widget_4); pushButton_3->setObjectName(QString::fromUtf8(""pushButton_3"")); horizontalLayout->addWidget(pushButton_3); verticalLayout->addWidget(widget_4); pushButton->setDefault(false); label->setText(QApplication::translate(""DrawWidget"", ""\\347\\224\\273\\347\\254\\224\\347\\262\\227\\347\\273\\206"", nullptr)); label_6->setText(QApplication::translate(""DrawWidget"", ""\\347\\224\\273\\347\\254\\224\\351\\242\\234\\350\\211\\262"", nullptr)); pushButton->setText(QString()); label_2->setText(QApplication::translate(""DrawWidget"", ""

\\345\\275\\242\\347\\212\\266\\351\\200\\211\\346\\213\\251

"", nullptr)); label_3->setText(QString()); label_9->setText(QString()); label_5->setText(QString()); radioButton_4->setText(QString()); radioButton_5->setText(QString()); shape->setText(QString()); radioButton_3->setText(QString()); label_4->setText(QString()); label_8->setText(QString()); radioButton->setText(QString()); radioButton_2->setText(QString()); label_7->setText(QString()); pushButton_2->setText(QApplication::translate(""DrawWidget"", ""\\344\\277\\235\\345\\255\\230"", nullptr)); pushButton_3->setText(QApplication::translate(""DrawWidget"", ""\\346\\270\\205\\347\\251\\272"", nullptr)); connect(radioButton, SIGNAL(clicked()), this, SLOT(on_radioButton_clicked())); connect(radioButton_2, SIGNAL(clicked()), this, SLOT(on_radioButton_2_clicked())); connect(pushButton, SIGNAL(clicked()), this, SLOT(on_pushButton_clicked())); connect(shape, SIGNAL(clicked()), this, SLOT(on_shape_clicked())); connect(radioButton_3, SIGNAL(clicked()), this, SLOT(on_radioButton_3_clicked())); connect(pushButton_2, SIGNAL(clicked()), this, SLOT(on_pushButton_2_clicked())); connect(radioButton_4, SIGNAL(clicked()), this, SLOT(on_radioButton_4_clicked())); connect(pushButton_3, SIGNAL(clicked()), this, SLOT(on_pushButton_3_clicked())); connect(radioButton_5, SIGNAL(clicked()), this, SLOT(on_radioButton_5_clicked())); QString style = ""QRadioButton::indicator{\\ width:15px;\\ height:15px;\\ }\\ QRadioButton::indicator::unchecked{\\ image:url(:/icons/lightblue/radiobutton_unchecked.png);\\ }\\ QRadioButton::indicator::unchecked:disabled{\\ image:url(:/icons/lightblue/radiobutton_unchecked_disable.png);\\ }\\ QRadioButton::indicator::checked{\\ image:url(:/icons/lightblue/radiobutton_checked.png);\\ }\\ QRadioButton::indicator::checked:disabled{\\ image:url(:/icons/lightblue/radiobutton_checked_disable.png);\\ }""; radioButton->setStyleSheet(style); radioButton_2->setStyleSheet(style); radioButton_3->setStyleSheet(style); radioButton_4->setStyleSheet(style); radioButton_5->setStyleSheet(style); } void DrawWidget::setShape(int n) { if (DrawWidget::self) { nshape = n; PLOGD << ""do cmd set nshape "" << n; } else { PLOGD << ""do cmd set nshape err ! no self!""; } } void DrawWidget::doClener() { if (DrawWidget::self) { on_pushButton_3_clicked(); } } void DrawWidget::setWidth(int n) { if (DrawWidget::self) { penWidth->setValue(n); } } void DrawWidget::setColor(QString n) { if (DrawWidget::self) { penColor = QColor(n); } } void DrawWidget::mousePressEvent(QMouseEvent *event) { if (event->button() == Qt::LeftButton) { qDebug() << ""mouse LeftButton"" << event->pos().rx() << "":"" << event->pos().ry(); drawing = true; point = event->pos(); from = event->pos(); change = event->pos(); width = 0; heigh = 0; pointPolygon[0] = point; pointPolygon[1].setX(point.x()); } } void DrawWidget::mouseMoveEvent(QMouseEvent *event) { point = event->pos(); width = point.x() - from.x(); heigh = point.y() - from.y(); pointPolygon[1].setY(point.y()); pointPolygon[2] = point; tempImage = image; if (nshape == 0 || nshape == 3) { paint(image); } else { paint(tempImage); } } void DrawWidget::mouseReleaseEvent(QMouseEvent *event) { if (event->button() == Qt::LeftButton) { qDebug() << ""mouse LeftButton ""<< event->pos().rx()<<"":""<< event->pos().ry(); to = event->pos(); point = event->pos(); width = to.x() - from.x(); heigh = to.y() - from.y(); pointPolygon[2] = point; drawing = false; paint(image); } } void DrawWidget::on_radioButton_clicked() { nshape = 1; } void DrawWidget::on_radioButton_2_clicked() { nshape = 2; } void DrawWidget::on_pushButton_clicked() { QColorDialog color;//调出颜色选择器对话框 penColor = color.getRgba(); //设置画笔颜色 } void DrawWidget::on_shape_clicked() { nshape = 0; } void DrawWidget::on_radioButton_3_clicked() { nshape = 3; } void DrawWidget::on_pushButton_2_clicked() //将画布内容保存 { QString filename = QFileDialog::getSaveFileName(this, tr(""Save Image""), """", tr(""*.bmp;; *.png;; *.jpg;; *.tif;; *.GIF"")); //选择路径 if (filename.isEmpty()) { return; } else{ if (!(image.save(filename))){ QMessageBox::information(this, tr(""Failed to save the image""), tr(""Failed to save the image!"")); return; } } } void DrawWidget::on_radioButton_4_clicked() { nshape = 4; } void DrawWidget::on_pushButton_3_clicked() { QPixmap pix(this->size().width(), this->size().height()); pix.fill((QColor(0, 0, 0, 1))); image = pix.toImage(); tempImage = pix.toImage(); update(); PLOGD << ""do signalclearPanit end""; } void DrawWidget::on_radioButton_5_clicked() { nshape = 5; } HttpServer::HttpServer(QObject *parent, void*hand) : QThread(parent),m_hand(hand) { moveToThread(this); } HttpServer::~HttpServer() { quit(); } void HttpServer::run() { QHttpServer server(this); quint64 iconnectionCounter = 0; QString portOrUnixSocket(""8010""); server.listen(portOrUnixSocket, [&](QHttpRequest* req, QHttpResponse* res) { new ClientHandler(++iconnectionCounter, req, res); }); if (!server.isListening()) { fprintf(stderr, ""can not listen on %s!\\n"", qPrintable(portOrUnixSocket)); } PLOGD << ""start listen 8010""; exec(); } struct MouseData { int type; int action; int x; int y; }; std::string typeToString(int t) { switch (t) { case 0:return ""close panit""; case 1:return ""open panit""; case 2:return ""set shape""; case 3:return ""set width""; case 4:return ""set url""; case 6:return ""set color""; case 7:return ""clear paint""; case 8:return ""zoom""; default: break; } } void HttpServer::gDealHttp(int type, QByteArray data) { PLOGD << ""do cmd type :"" << typeToString(type) <<"" data :""<< data.toStdString() <<"" hand:""<< m_hand; if (type == 1) { //打开画板 if (data.toInt() == 1 && m_hand) { ((Sn::BrowserWindow*)m_hand)->dosignalopenPanit(true); } else if (data.toInt() == 0 && m_hand) { ((Sn::BrowserWindow*)m_hand)->dosignalopenPanit(false); } } else if (type == 2) { //形状 int i = 0; do{ if (!DrawWidget::self) { Sleep(100); } else { DrawWidget::self->setShape(data.toInt()); } } while (i++ < 3); if (!DrawWidget::self){ PLOGD << ""do cmd set shape err:no widget "" << data.toInt(); } } else if (type == 3) { //设置粗细 int i = 0; do { if (!DrawWidget::self) { Sleep(100); } else { DrawWidget::self->setWidth(data.toInt()); } } while (i++ < 3); if (!DrawWidget::self) { PLOGD << ""do cmd set width err:no widget "" << data.toInt(); } } else if (type == 4 && m_hand) { //跳转网址 if (data.size()) { ((Sn::BrowserWindow*)m_hand)->dosignalgoNewUrl(data.data()); } } /* else if (type == 5) { QJsonDocument json = QJsonDocument::fromJson(data.data(), 0); QJsonObject obj = json.object(); int x = (obj[""x""].toInt() & 0xFFFF) / (65535 / float(1920)); int y = (obj[""y""].toInt() & 0xFFFF) / (65535 / float(1080)); ((Sn::BrowserWindow*)m_hand)->postMouseEvent( (Sn::ButtonType)obj[""type""].toInt(), (Sn::ButtonAction)obj[""action""].toInt(), x, y); PLOGD << ""do cmd set mouse "" << "" x:""<dosignalsetcolor(data.data()); } } else if (type == 7 && m_hand) { ((Sn::BrowserWindow*)m_hand)->dosignalclearPanit(); } else if (type == 8 && m_hand) { ((Sn::BrowserWindow*)m_hand)->dosignalzoom(data.toInt()); } else { PLOGE << ""unknow cmd type "" << type; } } ",16361,False,2390.4472159959455,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. // // File: MarshalNative.cpp // // // FCall's for the PInvoke classlibs // #include ""common.h"" #include ""clsload.hpp"" #include ""method.hpp"" #include ""class.h"" #include ""object.h"" #include ""field.h"" #include ""util.hpp"" #include ""excep.h"" #include ""siginfo.hpp"" #include ""threads.h"" #include ""stublink.h"" #include ""dllimport.h"" #include ""jitinterface.h"" #include ""eeconfig.h"" #include ""log.h"" #include ""fieldmarshaler.h"" #include ""cgensys.h"" #include ""gcheaputilities.h"" #include ""dbginterface.h"" #include ""marshalnative.h"" #include ""fcall.h"" #include ""dllimportcallback.h"" #include ""comdelegate.h"" #include ""typestring.h"" #include ""appdomain.inl"" #ifdef FEATURE_COMINTEROP #include ""comcallablewrapper.h"" #include ""cominterfacemarshaler.h"" #include ""commtmemberinfomap.h"" #include ""runtimecallablewrapper.h"" #include ""olevariant.h"" #include ""interoputil.h"" #include ""stubhelpers.h"" #endif // FEATURE_COMINTEROP #ifdef FEATURE_COMINTEROP_APARTMENT_SUPPORT #include ""olecontexthelpers.h"" #endif // FEATURE_COMINTEROP_APARTMENT_SUPPORT // // NumParamBytes // Counts # of parameter bytes INT32 QCALLTYPE MarshalNative::NumParamBytes(MethodDesc * pMD) { QCALL_CONTRACT; // Arguments are check on managed side PRECONDITION(pMD != NULL); INT32 cbParamBytes = 0; BEGIN_QCALL; if (!(pMD->IsNDirect())) COMPlusThrow(kArgumentException, IDS_EE_NOTNDIRECT); // Read the unmanaged stack size from the stub MethodDesc. For vararg P/Invoke, // this function returns size of the fixed portion of the stack. // Note that the following code does not throw if the DllImport declaration is // incorrect (such as a vararg method not marked as CallingConvention.Cdecl). MethodDesc * pStubMD = NULL; PCODE pTempStub = NULL; pTempStub = GetStubForInteropMethod(pMD, NDIRECTSTUB_FL_FOR_NUMPARAMBYTES, &pStubMD); _ASSERTE(pTempStub == NULL); _ASSERTE(pStubMD != NULL && pStubMD->IsILStub()); cbParamBytes = pStubMD->AsDynamicMethodDesc()->GetNativeStackArgSize(); #ifdef _X86_ if (((NDirectMethodDesc *)pMD)->IsThisCall()) { // The size of 'this' is not included in native stack arg size. cbParamBytes += sizeof(LPVOID); } #endif // _X86_ END_QCALL; return cbParamBytes; } // Prelink // Does advance loading of an N/Direct library VOID QCALLTYPE MarshalNative::Prelink(MethodDesc * pMD) { QCALL_CONTRACT; // Arguments are check on managed side PRECONDITION(pMD != NULL); // If the code is already ready, we are done. Else, we need to execute the prestub // This is a perf thing since it's always safe to execute the prestub twice. if (!pMD->IsPointingToPrestub()) return; // Silently ignore if not N/Direct and not runtime generated. if (!(pMD->IsNDirect()) && !(pMD->IsRuntimeSupplied())) return; BEGIN_QCALL; pMD->CheckRestore(); pMD->DoPrestub(NULL); END_QCALL; } FCIMPL3(VOID, MarshalNative::StructureToPtr, Object* pObjUNSAFE, LPVOID ptr, CLR_BOOL fDeleteOld) { CONTRACTL { FCALL_CHECK; PRECONDITION(CheckPointer(ptr, NULL_OK)); } CONTRACTL_END; OBJECTREF pObj = (OBJECTREF) pObjUNSAFE; HELPER_METHOD_FRAME_BEGIN_1(pObj); if (ptr == NULL) COMPlusThrowArgumentNull(W(""ptr"")); if (pObj == NULL) COMPlusThrowArgumentNull(W(""structure"")); // Code path will accept both regular layout objects and boxed value classes // with layout. MethodTable *pMT = pObj->GetMethodTable(); if (pMT->HasInstantiation()) COMPlusThrowArgumentException(W(""structure""), W(""Argument_NeedNonGenericObject"")); if (pMT->IsBlittable()) { memcpyNoGCRefs(ptr, pObj->GetData(), pMT->GetNativeSize()); } else if (pMT->HasLayout()) { if (fDeleteOld) LayoutDestroyNative(ptr, pMT); FmtClassUpdateNative( &(pObj), (LPBYTE)(ptr), NULL ); } else { COMPlusThrowArgumentException(W(""structure""), W(""Argument_MustHaveLayoutOrBeBlittable"")); } HELPER_METHOD_FRAME_END(); } FCIMPLEND FCIMPL3(VOID, MarshalNative::PtrToStructureHelper, LPVOID ptr, Object* pObjIn, CLR_BOOL allowValueClasses) { CONTRACTL { FCALL_CHECK; PRECONDITION(CheckPointer(ptr, NULL_OK)); } CONTRACTL_END; OBJECTREF pObj = ObjectToOBJECTREF(pObjIn); HELPER_METHOD_FRAME_BEGIN_1(pObj); if (ptr == NULL) COMPlusThrowArgumentNull(W(""ptr"")); if (pObj == NULL) COMPlusThrowArgumentNull(W(""structure"")); // Code path will accept regular layout objects. MethodTable *pMT = pObj->GetMethodTable(); // Validate that the object passed in is not a value class. if (!allowValueClasses && pMT->IsValueType()) { COMPlusThrowArgumentException(W(""structure""), W(""Argument_StructMustNotBeValueClass"")); } else if (pMT->IsBlittable()) { memcpyNoGCRefs(pObj->GetData(), ptr, pMT->GetNativeSize()); } else if (pMT->HasLayout()) { LayoutUpdateCLR((LPVOID*) &(pObj), Object::GetOffsetOfFirstField(), pMT, (LPBYTE)(ptr)); } else { COMPlusThrowArgumentException(W(""structure""), W(""Argument_MustHaveLayoutOrBeBlittable"")); } HELPER_METHOD_FRAME_END(); } FCIMPLEND FCIMPL2(VOID, MarshalNative::DestroyStructure, LPVOID ptr, ReflectClassBaseObject* refClassUNSAFE) { CONTRACTL { FCALL_CHECK; PRECONDITION(CheckPointer(ptr, NULL_OK)); } CONTRACTL_END; REFLECTCLASSBASEREF refClass = (REFLECTCLASSBASEREF) refClassUNSAFE; HELPER_METHOD_FRAME_BEGIN_1(refClass); if (ptr == NULL) COMPlusThrowArgumentNull(W(""ptr"")); if (refClass == NULL) COMPlusThrowArgumentNull(W(""structureType"")); if (refClass->GetMethodTable() != g_pRuntimeTypeClass) COMPlusThrowArgumentException(W(""structureType""), W(""Argument_MustBeRuntimeType"")); TypeHandle th = refClass->GetType(); if (th.HasInstantiation()) COMPlusThrowArgumentException(W(""structureType""), W(""Argument_NeedNonGenericType"")); if (th.IsBlittable()) { // ok to call with blittable structure, but no work to do in this case. } else if (th.HasLayout()) { LayoutDestroyNative(ptr, th.GetMethodTable()); } else { COMPlusThrowArgumentException(W(""structureType""), W(""Argument_MustHaveLayoutOrBeBlittable"")); } HELPER_METHOD_FRAME_END(); } FCIMPLEND FCIMPL1(FC_BOOL_RET, MarshalNative::IsPinnable, Object* obj) { FCALL_CONTRACT; VALIDATEOBJECT(obj); if (obj == NULL) FC_RETURN_BOOL(TRUE); if (obj->GetMethodTable() == g_pStringClass) FC_RETURN_BOOL(TRUE); if (obj->GetMethodTable()->IsArray()) { BASEARRAYREF asArray = (BASEARRAYREF)ObjectToOBJECTREF(obj); if (CorTypeInfo::IsPrimitiveType(asArray->GetArrayElementType())) FC_RETURN_BOOL(TRUE); TypeHandle th = asArray->GetArrayElementTypeHandle(); if (!th.IsTypeDesc()) { MethodTable *pMT = th.AsMethodTable(); if (pMT->IsValueType() && pMT->IsBlittable()) FC_RETURN_BOOL(TRUE); } FC_RETURN_BOOL(FALSE); } FC_RETURN_BOOL(obj->GetMethodTable()->IsBlittable()); } FCIMPLEND /************************************************************************ * PInvoke.SizeOf(Class) */ FCIMPL2(UINT32, MarshalNative::SizeOfClass, ReflectClassBaseObject* refClassUNSAFE, CLR_BOOL throwIfNotMarshalable) { CONTRACTL { FCALL_CHECK; PRECONDITION(CheckPointer(refClassUNSAFE)); } CONTRACTL_END; UINT32 rv = 0; REFLECTCLASSBASEREF refClass = (REFLECTCLASSBASEREF)refClassUNSAFE; HELPER_METHOD_FRAME_BEGIN_RET_1(refClass); // refClass is validated to be non-NULL RuntimeType by callers TypeHandle th = refClass->GetType(); if (throwIfNotMarshalable) { // Determine if the type is marshalable if (!IsStructMarshalable(th)) { // It isn't marshalable so throw an ArgumentException. StackSString strTypeName; TypeString::AppendType(strTypeName, th); COMPlusThrow(kArgumentException, IDS_CANNOT_MARSHAL, strTypeName.GetUnicode(), NULL, NULL); } } // The type is marshalable or we don't care so return its size. rv = th.GetMethodTable()->GetNativeSize(); HELPER_METHOD_FRAME_END(); return rv; } FCIMPLEND /************************************************************************ * PInvoke.OffsetOfHelper(Class, Field) */ FCIMPL1(UINT32, MarshalNative::OffsetOfHelper, ReflectFieldObject *pFieldUNSAFE) { CONTRACTL { FCALL_CHECK; PRECONDITION(CheckPointer(pFieldUNSAFE)); } CONTRACTL_END; REFLECTFIELDREF refField = (REFLECTFIELDREF)ObjectToOBJECTREF(pFieldUNSAFE); FieldDesc *pField = refField->GetField(); TypeHandle th = TypeHandle(pField->GetApproxEnclosingMethodTable()); // Determine if the type is marshalable. if (!IsStructMarshalable(th)) { // It isn't marshalable so throw an ArgumentException. HELPER_METHOD_FRAME_BEGIN_RET_1(refField); StackSString strTypeName; TypeString::AppendType(strTypeName, th); COMPlusThrow(kArgumentException, IDS_CANNOT_MARSHAL, strTypeName.GetUnicode(), NULL, NULL); HELPER_METHOD_FRAME_END(); } FieldMarshaler *pFM = th.GetMethodTable()->GetLayoutInfo()->GetFieldMarshalers(); UINT numReferenceFields = th.GetMethodTable()->GetLayoutInfo()->GetNumCTMFields(); while (numReferenceFields--) { if (pFM->GetFieldDesc() == pField) { return pFM->GetExternalOffset(); } ((BYTE*&)pFM) += MAXFIELDMARSHALERSIZE; } UNREACHABLE_MSG(""We should never hit this point since we already verified that the requested field was present from managed code""); } FCIMPLEND FCIMPL2(Object*, MarshalNative::GetDelegateForFunctionPointerInternal, LPVOID FPtr, ReflectClassBaseObject* refTypeUNSAFE) { CONTRACTL { FCALL_CHECK; PRECONDITION(refTypeUNSAFE != NULL); } CONTRACTL_END; OBJECTREF refDelegate = NULL; REFLECTCLASSBASEREF refType = (REFLECTCLASSBASEREF) refTypeUNSAFE; HELPER_METHOD_FRAME_BEGIN_RET_2(refType, refDelegate); // Retrieve the method table from the RuntimeType. We already verified in managed // code that the type was a RuntimeType that represented a delegate. Because type handles // for delegates must have a method table, we are safe in telling prefix to assume it below. MethodTable* pMT = refType->GetType().GetMethodTable(); PREFIX_ASSUME(pMT != NULL); refDelegate = COMDelegate::ConvertToDelegate(FPtr, pMT); HELPER_METHOD_FRAME_END(); return OBJECTREFToObject(refDelegate); } FCIMPLEND FCIMPL1(LPVOID, MarshalNative::GetFunctionPointerForDelegateInternal, Object* refDelegateUNSAFE) { FCALL_CONTRACT; LPVOID pFPtr = NULL; OBJECTREF refDelegate = (OBJECTREF) refDelegateUNSAFE; HELPER_METHOD_FRAME_BEGIN_RET_1(refDelegate); pFPtr = COMDelegate::ConvertToCallback(refDelegate); HELPER_METHOD_FRAME_END(); return pFPtr; } FCIMPLEND //==================================================================== // map a fiber cookie from the hosting APIs into a managed Thread object //==================================================================== FCIMPL1(THREADBASEREF, MarshalNative::GetThreadFromFiberCookie, int cookie) { FCALL_CONTRACT; _ASSERTE(cookie); THREADBASEREF ret = 0; // Set up a frame HELPER_METHOD_FRAME_BEGIN_RET_0(); // Any host who is sophisticated enough to correctly schedule fibers // had better be sophisticated enough to give us a real fiber cookie. Thread *pThread = *((Thread **) &cookie); // Minimal check that it smells like a thread: _ASSERTE(pThread->m_fPreemptiveGCDisabled.Load() == 0 || pThread->m_fPreemptiveGCDisabled.Load() == 1); ret = (THREADBASEREF)(pThread->GetExposedObject()); HELPER_METHOD_FRAME_END(); return ret; } FCIMPLEND FCIMPL3(LPVOID, MarshalNative::GetUnmanagedThunkForManagedMethodPtr, LPVOID pfnMethodToWrap, PCCOR_SIGNATURE pbSignature, ULONG cbSignature) { CONTRACTL { FCALL_CHECK; INJECT_FAULT(FCThrow(kOutOfMemoryException);); PRECONDITION(CheckPointer(pfnMethodToWrap, NULL_OK)); PRECONDITION(CheckPointer(pbSignature, NULL_OK)); } CONTRACTL_END; LPVOID pThunk = NULL; return pThunk; } FCIMPLEND /************************************************************************ * PInvoke.GetManagedThunkForUnmanagedMethodPtr() */ FCIMPL3(LPVOID, MarshalNative::GetManagedThunkForUnmanagedMethodPtr, LPVOID pfnMethodToWrap, PCCOR_SIGNATURE pbSignature, ULONG cbSignature) { CONTRACTL { FCALL_CHECK; PRECONDITION(CheckPointer(pfnMethodToWrap, NULL_OK)); PRECONDITION(CheckPointer(pbSignature, NULL_OK)); } CONTRACTL_END; LPVOID pThunk = NULL; return pThunk; } FCIMPLEND /************************************************************************ * PInvoke.GetLastWin32Error */ FCIMPL0(int, MarshalNative::GetLastWin32Error) { FCALL_CONTRACT; return (UINT32)(GetThread()->m_dwLastError); } FCIMPLEND /************************************************************************ * PInvoke.SetLastWin32Error */ FCIMPL1(void, MarshalNative::SetLastWin32Error, int error) { FCALL_CONTRACT; GetThread()->m_dwLastError = (DWORD)error; } FCIMPLEND /************************************************************************ * Support for the GCHandle class. */ // Check that the supplied object is valid to put in a pinned handle. // Throw an exception if not. void ValidatePinnedObject(OBJECTREF obj) { CONTRACTL { THROWS; GC_TRIGGERS; MODE_COOPERATIVE; } CONTRACTL_END; // NULL is fine. if (obj == NULL) return; if (obj->GetMethodTable() == g_pStringClass) return; if (obj->GetMethodTable()->IsArray()) { BASEARRAYREF asArray = (BASEARRAYREF) obj; if (CorTypeInfo::IsPrimitiveType(asArray->GetArrayElementType())) return; TypeHandle th = asArray->GetArrayElementTypeHandle(); if (!th.IsTypeDesc()) { MethodTable *pMT = th.AsMethodTable(); if (pMT->IsValueType() && pMT->IsBlittable()) return; } } else if (obj->GetMethodTable()->IsBlittable()) { return; } COMPlusThrow(kArgumentException, IDS_EE_NOTISOMORPHIC); } NOINLINE static OBJECTHANDLE FCDiagCreateHandle(OBJECTREF objRef, int type) { OBJECTHANDLE hnd = NULL; FC_INNER_PROLOG(MarshalNative::GCHandleInternalAlloc); // Make the stack walkable for the profiler HELPER_METHOD_FRAME_BEGIN_RET_ATTRIB_NOPOLL(Frame::FRAME_ATTR_EXACT_DEPTH | Frame::FRAME_ATTR_CAPTURE_DEPTH_2); hnd = GetAppDomain()->CreateTypedHandle(objRef, static_cast(type)); HELPER_METHOD_FRAME_END_POLL(); FC_INNER_EPILOG(); return hnd; } FCIMPL2(LPVOID, MarshalNative::GCHandleInternalAlloc, Object *obj, int type) { FCALL_CONTRACT; OBJECTREF objRef(obj); assert(type >= HNDTYPE_WEAK_SHORT && type <= HNDTYPE_WEAK_WINRT); if (CORProfilerTrackGC()) { FC_INNER_RETURN(LPVOID, (LPVOID) FCDiagCreateHandle(objRef, type)); } OBJECTHANDLE hnd = GetAppDomain()->GetHandleStore()->CreateHandleOfType(OBJECTREFToObject(objRef), static_cast(type)); if (!hnd) { FCThrow(kOutOfMemoryException); } return (LPVOID) hnd; } FCIMPLEND NOINLINE static void FCDiagDestroyHandle(OBJECTHANDLE handle) { FC_INNER_PROLOG(MarshalNative::GCHandleInternalFree); // Make the stack walkable for the profiler HELPER_METHOD_FRAME_BEGIN_ATTRIB(Frame::FRAME_ATTR_EXACT_DEPTH | Frame::FRAME_ATTR_CAPTURE_DEPTH_2); DestroyTypedHandle(handle); HELPER_METHOD_FRAME_END(); FC_INNER_EPILOG(); } // Free a GC handle. FCIMPL1(VOID, MarshalNative::GCHandleInternalFree, OBJECTHANDLE handle) { FCALL_CONTRACT; if (CORProfilerTrackGC()) { FC_INNER_RETURN_VOID(FCDiagDestroyHandle(handle)); } GCHandleUtilities::GetGCHandleManager()->DestroyHandleOfUnknownType(handle); } FCIMPLEND // Get the object referenced by a GC handle. FCIMPL1(LPVOID, MarshalNative::GCHandleInternalGet, OBJECTHANDLE handle) { FCALL_CONTRACT; OBJECTREF objRef; objRef = ObjectFromHandle(handle); return *((LPVOID*)&objRef); } FCIMPLEND // Update the object referenced by a GC handle. FCIMPL2(VOID, MarshalNative::GCHandleInternalSet, OBJECTHANDLE handle, Object *obj) { FCALL_CONTRACT; OBJECTREF objRef(obj); StoreObjectInHandle(handle, objRef); } FCIMPLEND // Update the object referenced by a GC handle. FCIMPL3(Object*, MarshalNative::GCHandleInternalCompareExchange, OBJECTHANDLE handle, Object *obj, Object* oldObj) { FCALL_CONTRACT; OBJECTREF newObjref(obj); OBJECTREF oldObjref(oldObj); LPVOID ret = NULL; // Update the stored object reference. ret = InterlockedCompareExchangeObjectInHandle(handle, newObjref, oldObjref); return (Object*)ret; } FCIMPLEND //==================================================================== // *** Interop Helpers *** //==================================================================== FCIMPL2(Object *, MarshalNative::GetExceptionForHR, INT32 errorCode, LPVOID errorInfo) { CONTRACTL { FCALL_CHECK; PRECONDITION(FAILED(errorCode)); PRECONDITION(CheckPointer(errorInfo, NULL_OK)); } CONTRACTL_END; OBJECTREF RetExceptionObj = NULL; HELPER_METHOD_FRAME_BEGIN_RET_1(RetExceptionObj); // Retrieve the IErrorInfo to use. IErrorInfo *pErrorInfo = (IErrorInfo*)errorInfo; if (pErrorInfo == (IErrorInfo*)(-1)) { pErrorInfo = NULL; } else if (!pErrorInfo) { if (SafeGetErrorInfo(&pErrorInfo) != S_OK) pErrorInfo = NULL; } ::GetExceptionForHR(errorCode, pErrorInfo, &RetExceptionObj); HELPER_METHOD_FRAME_END(); return OBJECTREFToObject(RetExceptionObj); } FCIMPLEND FCIMPL1(int, MarshalNative::GetHRForException, Object* eUNSAFE) { CONTRACTL { NOTHROW; // Used by reverse COM IL stubs, so we must not throw exceptions back to COM DISABLED(GC_TRIGGERS); // FCALLS with HELPER frames have issues with GC_TRIGGERS MODE_COOPERATIVE; } CONTRACTL_END; int retVal = 0; OBJECTREF e = (OBJECTREF) eUNSAFE; HELPER_METHOD_FRAME_BEGIN_RET_NOTHROW_1({ retVal = COR_E_STACKOVERFLOW; }, e); retVal = SetupErrorInfo(e); HELPER_METHOD_FRAME_END_NOTHROW(); return retVal; } FCIMPLEND FCIMPL1(int, MarshalNative::GetHRForException_WinRT, Object* eUNSAFE) { CONTRACTL { NOTHROW; // Used by reverse COM IL stubs, so we must not throw exceptions back to COM DISABLED(GC_TRIGGERS); // FCALLS with HELPER frames have issues with GC_TRIGGERS MODE_COOPERATIVE; } CONTRACTL_END; int retVal = 0; OBJECTREF e = (OBJECTREF) eUNSAFE; HELPER_METHOD_FRAME_BEGIN_RET_NOTHROW_1({ retVal = COR_E_STACKOVERFLOW; }, e); retVal = SetupErrorInfo(e, /* isWinRTScenario = */ TRUE); HELPER_METHOD_FRAME_END_NOTHROW(); return retVal; } FCIMPLEND #ifdef FEATURE_COMINTEROP //==================================================================== // map GUID to Type //==================================================================== /*OBJECTREF */ FCIMPL1(Object*, MarshalNative::GetLoadedTypeForGUID, GUID* pGuid) { CONTRACTL { FCALL_CHECK; PRECONDITION(CheckPointer(pGuid, NULL_OK)); } CONTRACTL_END; OBJECTREF refRetVal = NULL; HELPER_METHOD_FRAME_BEGIN_RET_1(refRetVal); if (!pGuid) COMPlusThrowArgumentNull(W(""pGuid"")); AppDomain* pDomain = SystemDomain::GetCurrentDomain(); _ASSERTE(pDomain); MethodTable* pMT = pDomain->LookupClass(*(pGuid)); if (pMT) refRetVal = pMT->GetManagedClassObject(); HELPER_METHOD_FRAME_END(); return OBJECTREFToObject(refRetVal); } FCIMPLEND //==================================================================== // map Type to ITypeInfo* //==================================================================== FCIMPL1(ITypeInfo*, MarshalNative::GetITypeInfoForType, ReflectClassBaseObject* refClassUNSAFE) { FCALL_CONTRACT; ITypeInfo* pTI = NULL; REFLECTCLASSBASEREF refClass = (REFLECTCLASSBASEREF) refClassUNSAFE; HELPER_METHOD_FRAME_BEGIN_RET_1(refClass); // Check for null arguments. if(!refClass) COMPlusThrowArgumentNull(W(""t"")); MethodTable *pRefMT = refClass->GetMethodTable(); if (pRefMT != g_pRuntimeTypeClass) COMPlusThrowArgumentException(W(""t""), W(""Argument_MustBeRuntimeType"")); TypeHandle th = refClass->GetType(); if (th.GetMethodTable() != NULL && (th.IsProjectedFromWinRT() || th.IsExportedToWinRT())) COMPlusThrowArgumentException(W(""t""), W(""Argument_ObjIsWinRTObject"")); if (th.HasInstantiation()) COMPlusThrowArgumentException(W(""t""), W(""Argument_NeedNonGenericType"")); // Make sure the type is visible from COM. if (!::IsTypeVisibleFromCom(th)) COMPlusThrowArgumentException(W(""t""), W(""Argument_TypeMustBeVisibleFromCom"")); // Retrieve the EE class from the reflection type. MethodTable* pMT = th.GetMethodTable(); _ASSERTE(pMT); // Retrieve the ITypeInfo for the class. IfFailThrow(GetITypeInfoForEEClass(pMT, &pTI, true /* bClassInfo */)); _ASSERTE(pTI != NULL); HELPER_METHOD_FRAME_END(); return pTI; } FCIMPLEND //==================================================================== // return the IUnknown* for an Object. //==================================================================== FCIMPL2(IUnknown*, MarshalNative::GetIUnknownForObjectNative, Object* orefUNSAFE, CLR_BOOL fOnlyInContext) { FCALL_CONTRACT; IUnknown* retVal = NULL; OBJECTREF oref = (OBJECTREF) orefUNSAFE; HELPER_METHOD_FRAME_BEGIN_RET_1(oref); HRESULT hr = S_OK; if(!oref) COMPlusThrowArgumentNull(W(""o"")); // Ensure COM is started up. EnsureComStarted(); if (fOnlyInContext && !IsObjectInContext(&oref)) retVal = NULL; else retVal = GetComIPFromObjectRef(&oref, ComIpType_OuterUnknown, NULL); HELPER_METHOD_FRAME_END(); return retVal; } FCIMPLEND //==================================================================== // return the raw IUnknown* for a COM Object not related to current // context. // Does not AddRef the returned pointer //==================================================================== FCIMPL1(IUnknown*, MarshalNative::GetRawIUnknownForComObjectNoAddRef, Object* orefUNSAFE) { FCALL_CONTRACT; IUnknown* retVal = NULL; OBJECTREF oref = (OBJECTREF) orefUNSAFE; HELPER_METHOD_FRAME_BEGIN_RET_1(oref); HRESULT hr = S_OK; if(!oref) COMPlusThrowArgumentNull(W(""o"")); MethodTable* pMT = oref->GetMethodTable(); PREFIX_ASSUME(pMT != NULL); if(!pMT->IsComObjectType()) COMPlusThrow(kArgumentException, IDS_EE_SRC_OBJ_NOT_COMOBJECT); // Ensure COM is started up. EnsureComStarted(); RCWHolder pRCW(GetThread()); pRCW.Init(oref); // Retrieve raw IUnknown * without AddRef for better performance retVal = pRCW->GetRawIUnknown_NoAddRef(); HELPER_METHOD_FRAME_END(); return retVal; } FCIMPLEND //==================================================================== // return the IDispatch* for an Object. //==================================================================== FCIMPL2(IDispatch*, MarshalNative::GetIDispatchForObjectNative, Object* orefUNSAFE, CLR_BOOL fOnlyInContext) { FCALL_CONTRACT; IDispatch* retVal = NULL; OBJECTREF oref = (OBJECTREF) orefUNSAFE; HELPER_METHOD_FRAME_BEGIN_RET_1(oref); HRESULT hr = S_OK; if(!oref) COMPlusThrowArgumentNull(W(""o"")); // Ensure COM is started up. EnsureComStarted(); if (fOnlyInContext && !IsObjectInContext(&oref)) retVal = NULL; else retVal = (IDispatch*)GetComIPFromObjectRef(&oref, ComIpType_Dispatch, NULL); HELPER_METHOD_FRAME_END(); return retVal; } FCIMPLEND //==================================================================== // return the IUnknown* representing the interface for the Object // Object o should support Type T //==================================================================== FCIMPL4(IUnknown*, MarshalNative::GetComInterfaceForObjectNative, Object* orefUNSAFE, ReflectClassBaseObject* refClassUNSAFE, CLR_BOOL fOnlyInContext, CLR_BOOL bEnableCustomizedQueryInterface) { FCALL_CONTRACT; IUnknown* retVal = NULL; OBJECTREF oref = (OBJECTREF) orefUNSAFE; REFLECTCLASSBASEREF refClass = (REFLECTCLASSBASEREF) refClassUNSAFE; HELPER_METHOD_FRAME_BEGIN_RET_2(oref, refClass); HRESULT hr = S_OK; if(!oref) COMPlusThrowArgumentNull(W(""o"")); if(!refClass) COMPlusThrowArgumentNull(W(""t"")); // Ensure COM is started up. EnsureComStarted(); if (refClass->GetMethodTable() != g_pRuntimeTypeClass) COMPlusThrowArgumentException(W(""t""), W(""Argument_MustBeRuntimeType"")); TypeHandle th = refClass->GetType(); if (!th.SupportsGenericInterop(TypeHandle::Interop_NativeToManaged)) { if (th.HasInstantiation()) COMPlusThrowArgumentException(W(""t""), W(""Argument_NeedNonGenericType"")); if (oref->GetMethodTable()->HasInstantiation()) COMPlusThrowArgumentException(W(""o""), W(""Argument_NeedNonGenericObject"")); } // If the IID being asked for does not represent an interface then // throw an argument exception. if (!th.IsInterface()) COMPlusThrowArgumentException(W(""t""), W(""Arg_MustBeInterface"")); // If the interface being asked for is not visible from COM then // throw an argument exception. if (!::IsTypeVisibleFromCom(th)) COMPlusThrowArgumentException(W(""t""), W(""Argument_TypeMustBeVisibleFromCom"")); if (fOnlyInContext && !IsObjectInContext(&oref)) retVal = NULL; else retVal = GetComIPFromObjectRef(&oref, th.GetMethodTable(), TRUE, bEnableCustomizedQueryInterface); HELPER_METHOD_FRAME_END(); return retVal; } FCIMPLEND //==================================================================== // return an Object for IUnknown //==================================================================== FCIMPL1(Object*, MarshalNative::GetObjectForIUnknown, IUnknown* pUnk) { CONTRACTL { FCALL_CHECK; PRECONDITION(CheckPointer(pUnk, NULL_OK)); } CONTRACTL_END; OBJECTREF oref = NULL; HELPER_METHOD_FRAME_BEGIN_RET_1(oref); HRESULT hr = S_OK; if(!pUnk) COMPlusThrowArgumentNull(W(""pUnk"")); // Ensure COM is started up. EnsureComStarted(); GetObjectRefFromComIP(&oref, pUnk); HELPER_METHOD_FRAME_END(); return OBJECTREFToObject(oref); } FCIMPLEND FCIMPL1(Object*, MarshalNative::GetUniqueObjectForIUnknown, IUnknown* pUnk) { CONTRACTL { FCALL_CHECK; PRECONDITION(CheckPointer(pUnk, NULL_OK)); } CONTRACTL_END; OBJECTREF oref = NULL; HELPER_METHOD_FRAME_BEGIN_RET_1(oref); HRESULT hr = S_OK; if(!pUnk) COMPlusThrowArgumentNull(W(""pUnk"")); // Ensure COM is started up. EnsureComStarted(); GetObjectRefFromComIP(&oref, pUnk, NULL, NULL, ObjFromComIP::UNIQUE_OBJECT); HELPER_METHOD_FRAME_END(); return OBJECTREFToObject(oref); } FCIMPLEND //==================================================================== // return an Object for IUnknown, using the Type T, // NOTE: // Type T should be either a COM imported Type or a sub-type of COM imported Type //==================================================================== FCIMPL2(Object*, MarshalNative::GetTypedObjectForIUnknown, IUnknown* pUnk, ReflectClassBaseObject* refClassUNSAFE) { CONTRACTL { FCALL_CHECK; PRECONDITION(CheckPointer(pUnk, NULL_OK)); } CONTRACTL_END; OBJECTREF oref = NULL; REFLECTCLASSBASEREF refClass = (REFLECTCLASSBASEREF) refClassUNSAFE; HELPER_METHOD_FRAME_BEGIN_RET_2(refClass, oref); HRESULT hr = S_OK; MethodTable* pMTClass = NULL; if(!pUnk) COMPlusThrowArgumentNull(W(""pUnk"")); if(refClass != NULL) { if (refClass->GetMethodTable() != g_pRuntimeTypeClass) COMPlusThrowArgumentException(W(""t""), W(""Argument_MustBeRuntimeType"")); TypeHandle th = refClass->GetType(); if (th.GetMethodTable() != NULL && (th.IsProjectedFromWinRT() || th.IsExportedToWinRT())) COMPlusThrowArgumentException(W(""t""), W(""Argument_ObjIsWinRTObject"")); if (th.HasInstantiation()) COMPlusThrowArgumentException(W(""t""), W(""Argument_NeedNonGenericType"")); pMTClass = th.GetMethodTable(); } else COMPlusThrowArgumentNull(W(""t"")); // Ensure COM is started up. EnsureComStarted(); GetObjectRefFromComIP(&oref, pUnk, pMTClass); HELPER_METHOD_FRAME_END(); return OBJECTREFToObject(oref); } FCIMPLEND FCIMPL2(IUnknown*, MarshalNative::CreateAggregatedObject, IUnknown* pOuter, Object* refObjUNSAFE) { CONTRACTL { FCALL_CHECK; PRECONDITION(CheckPointer(pOuter, NULL_OK)); } CONTRACTL_END; IUnknown* pInner = NULL; OBJECTREF oref = (OBJECTREF)refObjUNSAFE; HELPER_METHOD_FRAME_BEGIN_RET_1(oref); HRESULT hr = S_OK; if (!pOuter) COMPlusThrowArgumentNull(W(""pOuter"")); if (oref == NULL) COMPlusThrowArgumentNull(W(""o"")); MethodTable *pMT = oref->GetMethodTable(); if (pMT->IsWinRTObjectType() || pMT->IsExportedToWinRT()) COMPlusThrowArgumentException(W(""o""), W(""Argument_ObjIsWinRTObject"")); // Ensure COM is started up. EnsureComStarted(); if (NULL != ComCallWrapper::GetWrapperForObject(oref)) COMPlusThrowArgumentException(W(""o""), W(""Argument_AlreadyACCW"")); //get wrapper for the object, this could enable GC CCWHolder pWrap = ComCallWrapper::InlineGetWrapper(&oref); // Aggregation support, pWrap->InitializeOuter(pOuter); IfFailThrow(pWrap->GetInnerUnknown((LPVOID*)&pInner)); HELPER_METHOD_FRAME_END(); return pInner; } FCIMPLEND //==================================================================== // Free unused RCWs in the current COM+ context. //==================================================================== FCIMPL0(void, MarshalNative::CleanupUnusedObjectsInCurrentContext) { FCALL_CONTRACT; HELPER_METHOD_FRAME_BEGIN_0(); if (g_pRCWCleanupList) { g_pRCWCleanupList->CleanupWrappersInCurrentCtxThread( TRUE, // fWait TRUE, // fManualCleanupRequested TRUE // bIgnoreComObjectEagerCleanupSetting ); } HELPER_METHOD_FRAME_END(); } FCIMPLEND //==================================================================== // Checks whether there are RCWs from any context available for cleanup. //==================================================================== FCIMPL0(FC_BOOL_RET, MarshalNative::AreComObjectsAvailableForCleanup) { FCALL_CONTRACT; BOOL retVal = FALSE; if (g_pRCWCleanupList) { retVal = !g_pRCWCleanupList->IsEmpty(); } FC_RETURN_BOOL(retVal); } FCIMPLEND //==================================================================== // check if the object is classic COM component //==================================================================== FCIMPL1(FC_BOOL_RET, MarshalNative::IsComObject, Object* objUNSAFE) { FCALL_CONTRACT; BOOL retVal = FALSE; OBJECTREF obj = (OBJECTREF) objUNSAFE; HELPER_METHOD_FRAME_BEGIN_RET_1(obj); if(!obj) COMPlusThrowArgumentNull(W(""o"")); MethodTable* pMT = obj->GetMethodTable(); PREFIX_ASSUME(pMT != NULL); retVal = pMT->IsComObjectType(); HELPER_METHOD_FRAME_END(); FC_RETURN_BOOL(retVal); } FCIMPLEND //==================================================================== // free the COM component and zombie this object if the ref count hits 0 // further usage of this Object might throw an exception, //==================================================================== FCIMPL1(INT32, MarshalNative::ReleaseComObject, Object* objUNSAFE) { FCALL_CONTRACT; INT32 retVal = 0; OBJECTREF obj = (OBJECTREF) objUNSAFE; HELPER_METHOD_FRAME_BEGIN_RET_1(obj); if(!obj) COMPlusThrowArgumentNull(W(""o"")); MethodTable* pMT = obj->GetMethodTable(); PREFIX_ASSUME(pMT != NULL); if(!pMT->IsComObjectType()) COMPlusThrow(kArgumentException, IDS_EE_SRC_OBJ_NOT_COMOBJECT); // remove the wrapper from the object retVal = RCW::ExternalRelease(&obj); HELPER_METHOD_FRAME_END(); return retVal; } FCIMPLEND //==================================================================== // free the COM component and zombie this object // further usage of this Object might throw an exception, //==================================================================== FCIMPL1(void, MarshalNative::FinalReleaseComObject, Object* objUNSAFE) { FCALL_CONTRACT; OBJECTREF obj = (OBJECTREF) objUNSAFE; HELPER_METHOD_FRAME_BEGIN_1(obj); if(!obj) COMPlusThrowArgumentNull(W(""o"")); MethodTable* pMT = obj->GetMethodTable(); PREFIX_ASSUME(pMT != NULL); if(!pMT->IsComObjectType()) COMPlusThrow(kArgumentException, IDS_EE_SRC_OBJ_NOT_COMOBJECT); // remove the wrapper from the object RCW::FinalExternalRelease(&obj); HELPER_METHOD_FRAME_END(); } FCIMPLEND //==================================================================== // This method takes the given COM object and wraps it in an object // of the specified type. The type must be derived from __ComObject. //==================================================================== FCIMPL2(Object*, MarshalNative::InternalCreateWrapperOfType, Object* objUNSAFE, ReflectClassBaseObject* refClassUNSAFE) { CONTRACTL { FCALL_CHECK; PRECONDITION(objUNSAFE != NULL); PRECONDITION(refClassUNSAFE != NULL); } CONTRACTL_END; struct _gc { OBJECTREF refRetVal; OBJECTREF obj; REFLECTCLASSBASEREF refClass; } gc; gc.refRetVal = NULL; gc.obj = (OBJECTREF) objUNSAFE; gc.refClass = (REFLECTCLASSBASEREF) refClassUNSAFE; HELPER_METHOD_FRAME_BEGIN_RET_PROTECT(gc); // Validate the arguments. if (gc.refClass->GetMethodTable() != g_pRuntimeTypeClass) COMPlusThrowArgumentException(W(""t""), W(""Argument_MustBeRuntimeType"")); // Retrieve the class of the COM object. MethodTable *pObjMT = gc.obj->GetMethodTable(); // Retrieve the method table for new wrapper type. MethodTable *pNewWrapMT = gc.refClass->GetType().GetMethodTable(); // Validate that the destination type is a COM object. _ASSERTE(pNewWrapMT->IsComObjectType()); BOOL fSet = FALSE; // Start by checking if we can cast the obj to the wrapper type. if (TypeHandle(pObjMT).CanCastTo(TypeHandle(pNewWrapMT))) { gc.refRetVal = gc.obj; fSet = TRUE; } if (!fSet) { // Validate that the source object is a valid COM object. _ASSERTE(pObjMT->IsComObjectType()); RCWHolder pRCW(GetThread()); RCWPROTECT_BEGIN(pRCW, gc.obj); // Make sure the COM object supports all the COM imported interfaces that the new // wrapper class implements. MethodTable::InterfaceMapIterator it = pNewWrapMT->IterateInterfaceMap(); while (it.Next()) { MethodTable *pItfMT = it.GetInterface(); if (pItfMT->IsComImport()) { if (!Object::SupportsInterface(gc.obj, pItfMT)) COMPlusThrow(kInvalidCastException, IDS_EE_CANNOT_COERCE_COMOBJECT); } } // Create the duplicate wrapper object. { RCWHolder pNewRCW(GetThread()); pRCW->CreateDuplicateWrapper(pNewWrapMT, &pNewRCW); gc.refRetVal = pNewRCW->GetExposedObject(); } RCWPROTECT_END(pRCW); } HELPER_METHOD_FRAME_END(); return OBJECTREFToObject(gc.refRetVal); } FCIMPLEND //==================================================================== // check if the type is visible from COM. //==================================================================== FCIMPL1(FC_BOOL_RET, MarshalNative::IsTypeVisibleFromCom, ReflectClassBaseObject* refClassUNSAFE) { FCALL_CONTRACT; BOOL retVal = FALSE; REFLECTCLASSBASEREF refClass = (REFLECTCLASSBASEREF) refClassUNSAFE; HELPER_METHOD_FRAME_BEGIN_RET_1(refClass); // Validate the arguments. if (refClass == NULL) COMPlusThrowArgumentNull(W(""t"")); MethodTable *pRefMT = refClass->GetMethodTable(); if (pRefMT != g_pRuntimeTypeClass) COMPlusThrowArgumentException(W(""t""), W(""Argument_MustBeRuntimeType"")); // Call the internal version of IsTypeVisibleFromCom. retVal = ::IsTypeVisibleFromCom(refClass->GetType()); HELPER_METHOD_FRAME_END(); FC_RETURN_BOOL(retVal); } FCIMPLEND //==================================================================== // IUnknown Helpers //==================================================================== // IUnknown::QueryInterface FCIMPL3(HRESULT, MarshalNative::QueryInterface, IUnknown* pUnk, REFGUID iid, void** ppv) { CONTRACTL { FCALL_CHECK; PRECONDITION(CheckPointer(pUnk, NULL_OK)); PRECONDITION(CheckPointer(ppv)); } CONTRACTL_END; HRESULT hr = S_OK; HELPER_METHOD_FRAME_BEGIN_RET_0(); if (!pUnk) COMPlusThrowArgumentNull(W(""pUnk"")); hr = SafeQueryInterface(pUnk,iid,(IUnknown**)ppv); LogInteropQI(pUnk, iid, hr, ""PInvoke::QI""); HELPER_METHOD_FRAME_END(); return hr; } FCIMPLEND // IUnknown::AddRef FCIMPL1(ULONG, MarshalNative::AddRef, IUnknown* pUnk) { CONTRACTL { FCALL_CHECK; PRECONDITION(CheckPointer(pUnk, NULL_OK)); } CONTRACTL_END; ULONG cbRef = 0; HELPER_METHOD_FRAME_BEGIN_RET_0(); if (!pUnk) COMPlusThrowArgumentNull(W(""pUnk"")); cbRef = SafeAddRef(pUnk); LogInteropAddRef(pUnk, cbRef, ""PInvoke.AddRef""); HELPER_METHOD_FRAME_END(); return cbRef; } FCIMPLEND //IUnknown::Release FCIMPL1(ULONG, MarshalNative::Release, IUnknown* pUnk) { CONTRACTL { FCALL_CHECK; PRECONDITION(CheckPointer(pUnk, NULL_OK)); } CONTRACTL_END; ULONG cbRef = 0; HELPER_METHOD_FRAME_BEGIN_RET_0(); if (!pUnk) COMPlusThrowArgumentNull(W(""pUnk"")); cbRef = SafeRelease(pUnk); LogInteropRelease(pUnk, cbRef, ""PInvoke.Release""); HELPER_METHOD_FRAME_END(); return cbRef; } FCIMPLEND FCIMPL2(void, MarshalNative::GetNativeVariantForObject, Object* ObjUNSAFE, LPVOID pDestNativeVariant) { CONTRACTL { FCALL_CHECK; PRECONDITION(CheckPointer(pDestNativeVariant, NULL_OK)); } CONTRACTL_END; OBJECTREF Obj = (OBJECTREF) ObjUNSAFE; HELPER_METHOD_FRAME_BEGIN_1(Obj); if (pDestNativeVariant == NULL) COMPlusThrowArgumentNull(W(""pDstNativeVariant"")); if (Obj == NULL) { // Will return empty variant in MarshalOleVariantForObject } else if (Obj->GetMethodTable()->HasInstantiation()) { COMPlusThrowArgumentException(W(""obj""), W(""Argument_NeedNonGenericObject"")); } // intialize the output variant SafeVariantInit((VARIANT*)pDestNativeVariant); OleVariant::MarshalOleVariantForObject(&Obj, (VARIANT*)pDestNativeVariant); HELPER_METHOD_FRAME_END(); } FCIMPLEND FCIMPL1(Object*, MarshalNative::GetObjectForNativeVariant, LPVOID pSrcNativeVariant) { CONTRACTL { FCALL_CHECK; PRECONDITION(CheckPointer(pSrcNativeVariant, NULL_OK)); } CONTRACTL_END; OBJECTREF Obj = NULL; HELPER_METHOD_FRAME_BEGIN_RET_1(Obj); if (pSrcNativeVariant == NULL) COMPlusThrowArgumentNull(W(""pSrcNativeVariant"")); OleVariant::MarshalObjectForOleVariant((VARIANT*)pSrcNativeVariant, &Obj); HELPER_METHOD_FRAME_END(); return OBJECTREFToObject(Obj); } FCIMPLEND FCIMPL2(Object*, MarshalNative::GetObjectsForNativeVariants, VARIANT* aSrcNativeVariant, int cVars) { CONTRACTL { FCALL_CHECK; INJECT_FAULT(FCThrow(kOutOfMemoryException);); PRECONDITION(CheckPointer(aSrcNativeVariant, NULL_OK)); } CONTRACTL_END; PTRARRAYREF Array = NULL; HELPER_METHOD_FRAME_BEGIN_RET_1(Array); if (aSrcNativeVariant == NULL) COMPlusThrowArgumentNull(W(""aSrcNativeVariant"")); if (cVars < 0) COMPlusThrowArgumentOutOfRange(W(""cVars""), W(""ArgumentOutOfRange_NeedNonNegNum"")); OBJECTREF Obj = NULL; GCPROTECT_BEGIN(Obj) { // Allocate the array of objects. Array = (PTRARRAYREF)AllocateObjectArray(cVars, g_pObjectClass); // Convert each VARIANT in the array into an object. for (int i = 0; i < cVars; i++) { OleVariant::MarshalObjectForOleVariant(&aSrcNativeVariant[i], &Obj); Array->SetAt(i, Obj); } } GCPROTECT_END(); HELPER_METHOD_FRAME_END(); return OBJECTREFToObject(Array); } FCIMPLEND FCIMPL2(void, MarshalNative::DoGenerateGuidForType, GUID * result, ReflectClassBaseObject* refTypeUNSAFE) { FCALL_CONTRACT; REFLECTCLASSBASEREF refType = (REFLECTCLASSBASEREF) refTypeUNSAFE; HELPER_METHOD_FRAME_BEGIN_1(refType); GCPROTECT_BEGININTERIOR (result); // Validate the arguments. if (refType == NULL) COMPlusThrowArgumentNull(W(""type"")); MethodTable *pRefMT = refType->GetMethodTable(); if (pRefMT != g_pRuntimeTypeClass) COMPlusThrowArgumentException(W(""type""), W(""Argument_MustBeRuntimeType"")); if (result == NULL) COMPlusThrow(kArgumentNullException, W(""ArgumentNull_GUID"")); // Check to see if the type is a COM object or not. if (IsComObjectClass(refType->GetType())) { #ifdef FEATURE_COMINTEROP_UNMANAGED_ACTIVATION // The type is a COM object then we get the GUID from the class factory. SyncBlock* pSyncBlock = refType->GetSyncBlock(); ComClassFactory* pComClsFac = pSyncBlock->GetInteropInfo()->GetComClassFactory(); memcpy(result, &pComClsFac->m_rclsid, sizeof(GUID)); #else // FEATURE_COMINTEROP_UNMANAGED_ACTIVATION memset(result,0,sizeof(GUID)); #endif // FEATURE_COMINTEROP_UNMANAGED_ACTIVATION } else { // The type is a normal COM+ class so we need to generate the GUID. TypeHandle classTH = refType->GetType(); classTH.GetMethodTable()->GetGuid(result, TRUE); } GCPROTECT_END (); HELPER_METHOD_FRAME_END(); } FCIMPLEND FCIMPL2(void, MarshalNative::DoGetTypeLibGuid, GUID * result, Object* refTlbUNSAFE) { FCALL_CONTRACT; OBJECTREF refTlb = (OBJECTREF) refTlbUNSAFE; HELPER_METHOD_FRAME_BEGIN_1(refTlb); GCPROTECT_BEGININTERIOR (result); if (refTlb == NULL) COMPlusThrowArgumentNull(W(""pTLB"")); // Ensure COM is started up. EnsureComStarted(); SafeComHolder pTLB = (ITypeLib*)GetComIPFromObjectRef(&refTlb, IID_ITypeLib); if (!pTLB) COMPlusThrow(kArgumentException, W(""Arg_NoITypeLib"")); GCX_PREEMP(); // Retrieve the TLIBATTR. TLIBATTR *pAttr; IfFailThrow(pTLB->GetLibAttr(&pAttr)); // Extract the guid from the TLIBATTR. *result = pAttr->guid; // Release the TLIBATTR now that we have the GUID. pTLB->ReleaseTLibAttr(pAttr); GCPROTECT_END (); HELPER_METHOD_FRAME_END(); } FCIMPLEND FCIMPL1(LCID, MarshalNative::GetTypeLibLcid, Object* refTlbUNSAFE) { FCALL_CONTRACT; LCID retVal = 0; OBJECTREF refTlb = (OBJECTREF) refTlbUNSAFE; HELPER_METHOD_FRAME_BEGIN_RET_1(refTlb); if (refTlb == NULL) COMPlusThrowArgumentNull(W(""pTLB"")); // Ensure COM is started up. EnsureComStarted(); SafeComHolder pTLB = (ITypeLib*)GetComIPFromObjectRef(&refTlb, IID_ITypeLib); if (!pTLB) COMPlusThrow(kArgumentException, W(""Arg_NoITypeLib"")); GCX_PREEMP(); // Retrieve the TLIBATTR. TLIBATTR *pAttr; IfFailThrow(pTLB->GetLibAttr(&pAttr)); // Extract the LCID from the TLIBATTR. retVal = pAttr->lcid; // Release the TLIBATTR now that we have the LCID. pTLB->ReleaseTLibAttr(pAttr); HELPER_METHOD_FRAME_END(); return retVal; } FCIMPLEND FCIMPL3(void, MarshalNative::GetTypeLibVersion, Object* refTlbUNSAFE, int *pMajor, int *pMinor) { FCALL_CONTRACT; OBJECTREF refTlb = (OBJECTREF) refTlbUNSAFE; HELPER_METHOD_FRAME_BEGIN_1(refTlb); if (refTlb == NULL) COMPlusThrowArgumentNull(W(""typeLibrary"")); // Ensure COM is started up. EnsureComStarted(); SafeComHolder pTLB = (ITypeLib*)GetComIPFromObjectRef(&refTlb, IID_ITypeLib); if (!pTLB) COMPlusThrow(kArgumentException, W(""Arg_NoITypeLib"")); GCX_PREEMP(); // Retrieve the TLIBATTR. TLIBATTR *pAttr; IfFailThrow(pTLB->GetLibAttr(&pAttr)); // Extract the LCID from the TLIBATTR. *pMajor = pAttr->wMajorVerNum; *pMinor = pAttr->wMinorVerNum; // Release the TLIBATTR now that we have the version numbers. pTLB->ReleaseTLibAttr(pAttr); HELPER_METHOD_FRAME_END(); } FCIMPLEND FCIMPL2(void, MarshalNative::DoGetTypeInfoGuid, GUID * result, Object* refTypeInfoUNSAFE) { FCALL_CONTRACT; OBJECTREF refTypeInfo = (OBJECTREF) refTypeInfoUNSAFE; HELPER_METHOD_FRAME_BEGIN_1(refTypeInfo); GCPROTECT_BEGININTERIOR (result); if (refTypeInfo == NULL) COMPlusThrowArgumentNull(W(""typeInfo"")); // Ensure COM is started up. EnsureComStarted(); SafeComHolder pTI = (ITypeInfo*)GetComIPFromObjectRef(&refTypeInfo, IID_ITypeInfo); if (!pTI) COMPlusThrow(kArgumentException, W(""Arg_NoITypeInfo"")); GCX_PREEMP(); // Retrieve the TYPEATTR. TYPEATTR *pAttr; IfFailThrow(pTI->GetTypeAttr(&pAttr)); // Extract the guid from the TYPEATTR. *result = pAttr->guid; // Release the TYPEATTR now that we have the GUID. pTI->ReleaseTypeAttr(pAttr); GCPROTECT_END (); HELPER_METHOD_FRAME_END(); } FCIMPLEND FCIMPL2(void, MarshalNative::DoGetTypeLibGuidForAssembly, GUID * result, AssemblyBaseObject* refAsmUNSAFE) { FCALL_CONTRACT; // Validate the arguments. _ASSERTE(refAsmUNSAFE != NULL); _ASSERTE(result != NULL); ASSEMBLYREF refAsm = (ASSEMBLYREF) refAsmUNSAFE; HELPER_METHOD_FRAME_BEGIN_1(refAsm); GCPROTECT_BEGININTERIOR (result) HRESULT hr = S_OK; // Retrieve the assembly from the ASSEMBLYREF. Assembly *pAssembly = refAsm->GetAssembly(); _ASSERTE(pAssembly); // Retrieve the TLBID for the assembly. IfFailThrow(::GetTypeLibGuidForAssembly(pAssembly, result)); GCPROTECT_END (); HELPER_METHOD_FRAME_END(); } FCIMPLEND FCIMPL3(void, MarshalNative::GetTypeLibVersionForAssembly, AssemblyBaseObject* refAsmUNSAFE, INT32 *pMajorVersion, INT32 *pMinorVersion) { FCALL_CONTRACT; // Validate the arguments. _ASSERTE(refAsmUNSAFE != NULL); ASSEMBLYREF refAsm = (ASSEMBLYREF) refAsmUNSAFE; HELPER_METHOD_FRAME_BEGIN_1(refAsm); HRESULT hr = S_OK; // Retrieve the assembly from the ASSEMBLYREF. Assembly *pAssembly = refAsm->GetAssembly(); _ASSERTE(pAssembly); // Retrieve the version for the assembly. USHORT usMaj, usMin; IfFailThrow(::GetTypeLibVersionForAssembly(pAssembly, &usMaj, &usMin)); // Set the out parameters. *pMajorVersion = usMaj; *pMinorVersion = usMin; HELPER_METHOD_FRAME_END(); } FCIMPLEND FCIMPL1(int, MarshalNative::GetStartComSlot, ReflectClassBaseObject* tUNSAFE) { FCALL_CONTRACT; int retVal = 0; REFLECTCLASSBASEREF t = (REFLECTCLASSBASEREF) tUNSAFE; HELPER_METHOD_FRAME_BEGIN_RET_1(t); if (!(t)) COMPlusThrow(kArgumentNullException); MethodTable *pTMT = t->GetMethodTable(); if (pTMT != g_pRuntimeTypeClass) COMPlusThrowArgumentException(W(""t""), W(""Argument_MustBeRuntimeType"")); MethodTable *pMT = t->GetType().GetMethodTable(); if (NULL == pMT) COMPlusThrow(kArgumentNullException); // The service does not make any sense to be called for non COM visible types. if (!::IsTypeVisibleFromCom(TypeHandle(pMT))) COMPlusThrowArgumentException(W(""t""), W(""Argument_TypeMustBeVisibleFromCom"")); retVal = GetComSlotInfo(pMT, &pMT); HELPER_METHOD_FRAME_END(); return retVal; } FCIMPLEND FCIMPL1(int, MarshalNative::GetEndComSlot, ReflectClassBaseObject* tUNSAFE) { FCALL_CONTRACT; int retVal = 0; REFLECTCLASSBASEREF t = (REFLECTCLASSBASEREF) tUNSAFE; HELPER_METHOD_FRAME_BEGIN_RET_1(t); int StartSlot = -1; if (!(t)) COMPlusThrow(kArgumentNullException); MethodTable *pTMT = t->GetMethodTable(); if (pTMT != g_pRuntimeTypeClass) COMPlusThrowArgumentException(W(""t""), W(""Argument_MustBeRuntimeType"")); TypeHandle classTH = t->GetType(); MethodTable *pMT = classTH.GetMethodTable(); if (NULL == pMT) COMPlusThrow(kArgumentNullException); // The service does not make any sense to be called for non COM visible types. if (!::IsTypeVisibleFromCom(classTH)) COMPlusThrowArgumentException(W(""t""), W(""Argument_TypeMustBeVisibleFromCom"")); // Retrieve the start slot and the default interface class. StartSlot = GetComSlotInfo(pMT, &pMT); if (StartSlot == -1) { retVal = StartSlot; } else { // Retrieve the map of members. ComMTMemberInfoMap MemberMap(pMT); MemberMap.Init(sizeof(void*)); // The end slot is the start slot plus the number of user defined methods. retVal = int(StartSlot + MemberMap.GetMethods().Size() - 1); } HELPER_METHOD_FRAME_END(); return retVal; } FCIMPLEND FCIMPL1(int, MarshalNative::GetComSlotForMethodInfo, ReflectMethodObject* pMethodUNSAFE) { CONTRACTL { FCALL_CHECK; PRECONDITION(CheckPointer(pMethodUNSAFE)); PRECONDITION(pMethodUNSAFE->GetMethod()->GetMethodTable()->IsInterface()); } CONTRACTL_END; REFLECTMETHODREF refMethod = (REFLECTMETHODREF)ObjectToOBJECTREF(pMethodUNSAFE); MethodDesc *pMeth = refMethod->GetMethod(); _ASSERTE(pMeth); int retVal = 0; HELPER_METHOD_FRAME_BEGIN_RET_1(refMethod); retVal = pMeth->GetComSlot(); HELPER_METHOD_FRAME_END(); return retVal; } FCIMPLEND FCIMPL3(Object*, MarshalNative::GetMethodInfoForComSlot, ReflectClassBaseObject* tUNSAFE, INT32 slot, ComMemberType* pMemberType) { CONTRACTL { FCALL_CHECK; PRECONDITION(CheckPointer(pMemberType, NULL_OK)); } CONTRACTL_END; OBJECTREF refRetVal = NULL; REFLECTCLASSBASEREF t = (REFLECTCLASSBASEREF) tUNSAFE; REFLECTCLASSBASEREF tInterface = NULL; HELPER_METHOD_FRAME_BEGIN_RET_2(t, tInterface); int StartSlot = -1; OBJECTREF MemberInfoObj = NULL; if (!(t)) COMPlusThrow(kArgumentNullException); MethodTable *pTMT = t->GetMethodTable(); if (pTMT != g_pRuntimeTypeClass) COMPlusThrowArgumentException(W(""t""), W(""Argument_MustBeRuntimeType"")); TypeHandle type = t->GetType(); MethodTable *pMT= type.GetMethodTable(); if (NULL == pMT) COMPlusThrow(kArgumentNullException); // The service does not make any sense to be called for non COM visible types. if (!::IsTypeVisibleFromCom(type)) COMPlusThrowArgumentException(W(""t""), W(""Argument_TypeMustBeVisibleFromCom"")); // Retrieve the start slot and the default interface class. StartSlot = GetComSlotInfo(pMT, &pMT); if (StartSlot == -1) COMPlusThrowArgumentOutOfRange(W(""slot""), W(""ArgumentOutOfRange_Count"")); // Retrieve the map of members. ComMTMemberInfoMap MemberMap(pMT); MemberMap.Init(sizeof(void*)); CQuickArray &rProps = MemberMap.GetMethods(); // Update the typehandle we'll be using based on the interface returned by GetComSlotInfo. tInterface = (REFLECTCLASSBASEREF)pMT->GetManagedClassObject(); type = TypeHandle(pMT); // Make sure the specified slot is valid. if (slot < StartSlot) COMPlusThrowArgumentOutOfRange(W(""slot""), W(""ArgumentOutOfRange_Count"")); if (slot >= StartSlot + (int)rProps.Size()) COMPlusThrowArgumentOutOfRange(W(""slot""), W(""ArgumentOutOfRange_Count"")); ComMTMethodProps *pProps = &rProps[slot - StartSlot]; if (pProps->semantic >= FieldSemanticOffset) { // We are dealing with a field. ComCallMethodDesc *pFieldMeth = reinterpret_cast(pProps->pMeth); FieldDesc *pField = pFieldMeth->GetFieldDesc(); // call the managed code to get the FieldInfo MethodDescCallSite getFieldInfo(METHOD__CLASS__GET_FIELD_INFO); ARG_SLOT args[] = { ObjToArgSlot(tInterface), (ARG_SLOT)pField }; MemberInfoObj = getFieldInfo.Call_RetOBJECTREF(args); *(pMemberType) = (pProps->semantic == (FieldSemanticOffset + msGetter)) ? CMT_PropGet : CMT_PropSet; } else if (pProps->property == mdPropertyNil) { // We are dealing with a normal property. // call the managed code to get the MethodInfo MethodDescCallSite getMethodBase(METHOD__CLASS__GET_METHOD_BASE); ARG_SLOT args[] = { ObjToArgSlot(tInterface), (ARG_SLOT)pProps->pMeth }; MemberInfoObj = getMethodBase.Call_RetOBJECTREF(args); *(pMemberType) = CMT_Method; } else { // We are dealing with a property. mdProperty tkProp; if (TypeFromToken(pProps->property) == mdtProperty) tkProp = pProps->property; else tkProp = rProps[pProps->property].property; // call the managed code to get the PropertyInfo MethodDescCallSite getPropertyInfo(METHOD__CLASS__GET_PROPERTY_INFO); ARG_SLOT args[] = { ObjToArgSlot(tInterface), tkProp }; MemberInfoObj = getPropertyInfo.Call_RetOBJECTREF(args); *(pMemberType) = (pProps->semantic == msGetter) ? CMT_PropGet : CMT_PropSet; } refRetVal = MemberInfoObj; HELPER_METHOD_FRAME_END(); return OBJECTREFToObject(refRetVal); } FCIMPLEND //+---------------------------------------------------------------------------- // // Method: MarshalNative::WrapIUnknownWithComObject // Synopsis: unmarshal the buffer and return IUnknown // // //+---------------------------------------------------------------------------- FCIMPL1(Object*, MarshalNative::WrapIUnknownWithComObject, IUnknown* pUnk) { CONTRACTL { FCALL_CHECK; PRECONDITION(CheckPointer(pUnk, NULL_OK)); } CONTRACTL_END; OBJECTREF cref = NULL; HELPER_METHOD_FRAME_BEGIN_RET_0(); if(pUnk == NULL) COMPlusThrowArgumentNull(W(""punk"")); EnsureComStarted(); COMInterfaceMarshaler marshaler; marshaler.Init(pUnk, g_pBaseCOMObject, GET_THREAD()); cref = marshaler.WrapWithComObject(); if (cref == NULL) COMPlusThrowOM(); HELPER_METHOD_FRAME_END(); return OBJECTREFToObject(cref); } FCIMPLEND FCIMPL2(void, MarshalNative::ChangeWrapperHandleStrength, Object* orefUNSAFE, CLR_BOOL fIsWeak) { FCALL_CONTRACT; OBJECTREF oref = (OBJECTREF) orefUNSAFE; HELPER_METHOD_FRAME_BEGIN_1(oref); if(oref == NULL) COMPlusThrowArgumentNull(W(""otp"")); if ( !oref->GetMethodTable()->IsComImport()) { CCWHolder pWrap = ComCallWrapper::InlineGetWrapper(&oref); if (pWrap == NULL) COMPlusThrowOM(); if (fIsWeak != 0) pWrap->MarkHandleWeak(); else pWrap->ResetHandleStrength(); } HELPER_METHOD_FRAME_END(); } FCIMPLEND FCIMPL2(void, MarshalNative::InitializeWrapperForWinRT, Object *unsafe_pThis, IUnknown **ppUnk) { FCALL_CONTRACT; OBJECTREF oref = ObjectToOBJECTREF(unsafe_pThis); HELPER_METHOD_FRAME_BEGIN_1(oref); _ASSERTE(ppUnk != NULL); if (*ppUnk == NULL) { // this should never happen but it's not nice to AV if the factory method is busted and returns NULL COMPlusThrow(kNullReferenceException); } // the object does not have the right RCW yet COMInterfaceMarshaler marshaler; marshaler.Init(*ppUnk, oref->GetMethodTable(), GET_THREAD(), RCW::CF_SupportsIInspectable | RCW::CF_QueryForIdentity); // the following will assign NULL to *ppUnk which signals to the caller that we successfully // initialized the RCW so (*ppUnk)->Release() should be suppressed marshaler.InitializeExistingComObject(&oref, ppUnk); HELPER_METHOD_FRAME_END(); } FCIMPLEND FCIMPL2(void, MarshalNative::InitializeManagedWinRTFactoryObject, Object *unsafe_pThis, ReflectClassBaseObject *unsafe_pType) { FCALL_CONTRACT; OBJECTREF orefThis = ObjectToOBJECTREF(unsafe_pThis); REFLECTCLASSBASEREF orefType = (REFLECTCLASSBASEREF)ObjectToOBJECTREF(unsafe_pType); HELPER_METHOD_FRAME_BEGIN_2(orefThis, orefType); MethodTable *pMT = orefType->GetType().GetMethodTable(); // get the special ""factory"" template for the type _ASSERTE(pMT->IsExportedToWinRT()); WinRTManagedClassFactory *pFactory = GetComClassFactory(pMT)->AsWinRTManagedClassFactory(); ComCallWrapperTemplate *pTemplate = pFactory->GetOrCreateComCallWrapperTemplate(orefThis->GetMethodTable()); // create a CCW for the factory object using the template CCWHolder pCCWHold = ComCallWrapper::InlineGetWrapper(&orefThis, pTemplate); HELPER_METHOD_FRAME_END(); } FCIMPLEND // // Create activation factory and wraps it with a unique RCW // // This is necessary because WinRT factories are often implemented as a singleton, // and getting back a RCW for such WinRT factory would usually get back a RCW from // another apartment, even if the interface pointe returned from GetActivationFactory // is a raw pointer. As a result, user would randomly get back RCWs for activation // factories from other apartments and make transiton to those apartments and cause // deadlocks and create objects in incorrect apartments // // The solution here is to always create a unique RCW // FCIMPL1(Object *, MarshalNative::GetNativeActivationFactory, ReflectClassBaseObject *unsafe_pType) { FCALL_CONTRACT; REFLECTCLASSBASEREF orefType = (REFLECTCLASSBASEREF)ObjectToOBJECTREF(unsafe_pType); OBJECTREF orefFactory = NULL; HELPER_METHOD_FRAME_BEGIN_RET_2(orefFactory, orefType); MethodTable *pMT = orefType->GetType().GetMethodTable(); // Must be a native WinRT type _ASSERTE(pMT->IsProjectedFromWinRT()); // // Get the activation factory instance for this WinRT type and create a RCW for it // GetNativeWinRTFactoryObject( pMT, GET_THREAD(), NULL, // No factory interface available at this point TRUE, // Create unique RCW - See comments for this function for more details NULL, // No callback necessary &orefFactory // return value ); HELPER_METHOD_FRAME_END(); return OBJECTREFToObject(orefFactory); } FCIMPLEND void QCALLTYPE MarshalNative::GetInspectableIIDs( QCall::ObjectHandleOnStack hobj, QCall::ObjectHandleOnStack retArrayGuids) { CONTRACTL { QCALL_CHECK; PRECONDITION(CheckPointer(*hobj.m_ppObject)); } CONTRACTL_END; BEGIN_QCALL; SyncBlock * pSyncBlock = NULL; { GCX_COOP(); // set return to failure value retArrayGuids.Set(NULL); OBJECTREF orComObject = NULL; GCPROTECT_BEGIN(orComObject); orComObject = ObjectToOBJECTREF(*hobj.m_ppObject); // Validation: hobj represents a non-NULL System.__ComObject instance if(orComObject == NULL) COMPlusThrowArgumentNull(W(""obj"")); MethodTable* pMT = orComObject->GetMethodTable(); PREFIX_ASSUME(pMT != NULL); if(!pMT->IsComObjectType()) COMPlusThrow(kArgumentException, IDS_EE_SRC_OBJ_NOT_COMOBJECT); // while in cooperative mode, retrieve the object's sync block pSyncBlock = orComObject->PassiveGetSyncBlock(); GCPROTECT_END(); } // close the GCX_COOP scope InteropSyncBlockInfo * pInteropInfo; RCW * pRCW; SafeComHolderPreemp pInspectable; // Retrieve obj's IInspectable interface pointer if (pSyncBlock != NULL && (pInteropInfo = pSyncBlock->GetInteropInfoNoCreate()) != NULL && (pRCW = pInteropInfo->GetRawRCW()) != NULL && (pInspectable = pRCW->GetIInspectable()) != NULL) { // retrieve IIDs using IInspectable::GetIids() ULONG size = 0; CoTaskMemHolder rgIIDs(NULL); if (SUCCEEDED(pInspectable->GetIids(&size, &rgIIDs))) { retArrayGuids.SetGuidArray(rgIIDs, size); } } END_QCALL; } //==================================================================== // Helper function used in the COM slot to method info mapping. //==================================================================== int MarshalNative::GetComSlotInfo(MethodTable *pMT, MethodTable **ppDefItfMT) { CONTRACTL { THROWS; GC_TRIGGERS; MODE_ANY; PRECONDITION(CheckPointer(pMT)); PRECONDITION(CheckPointer(ppDefItfMT)); } CONTRACTL_END; *ppDefItfMT = NULL; // If a class was passed in then retrieve the default interface. if (!pMT->IsInterface()) { TypeHandle hndDefItfClass; DefaultInterfaceType DefItfType = GetDefaultInterfaceForClassWrapper(TypeHandle(pMT), &hndDefItfClass); if (DefItfType == DefaultInterfaceType_AutoDual || DefItfType == DefaultInterfaceType_Explicit) { pMT = hndDefItfClass.GetMethodTable(); PREFIX_ASSUME(pMT != NULL); } else { // The default interface does not have any user defined methods. return -1; } } // Set the default interface class. *ppDefItfMT = pMT; if (pMT->IsInterface()) { // Return the right number of slots depending on interface type. return ComMethodTable::GetNumExtraSlots(pMT->GetComInterfaceType()); } else { // We are dealing with an IClassX which are always IDispatch based. return ComMethodTable::GetNumExtraSlots(ifDispatch); } } BOOL MarshalNative::IsObjectInContext(OBJECTREF *pObj) { CONTRACTL { THROWS; GC_TRIGGERS; MODE_COOPERATIVE; PRECONDITION(pObj != NULL); } CONTRACTL_END; SyncBlock* pBlock = (*pObj)->GetSyncBlock(); InteropSyncBlockInfo* pInteropInfo = pBlock->GetInteropInfo(); ComCallWrapper* pCCW = pInteropInfo->GetCCW(); if((pCCW) || (!pInteropInfo->RCWWasUsed())) { // We are dealing with a CCW. Since CCW's are agile, they are always in the // correct context. return TRUE; } else { RCWHolder pRCW(GetThread()); pRCW.Init(pBlock); // We are dealing with an RCW, we need to check to see if the current // context is the one it was first seen in. LPVOID pCtxCookie = GetCurrentCtxCookie(); _ASSERTE(pCtxCookie != NULL); return pCtxCookie == pRCW->GetWrapperCtxCookie(); } } #endif // FEATURE_COMINTEROP ",16229,True,3736.5305945898244,median " [[springSpringBoot]] === Spring Boot Spring Boot is an application framework which, according to link:$$http://projects.spring.io/spring-boot/$$[its website], _makes it easy to create stand-alone, production-grade Spring based Applications that you can ""just run"". It takes an opinionated view of the Spring platform and third-party libraries so you can get started with minimum fuss. Most Spring Boot applications need very little Spring configuration_. For more information on Spring Boot, see link:$$http://projects.spring.io/spring-boot/$$[http://projects.spring.io/spring-boot/] The Spring Boot - Flowable integration has been developed together with Spring committers. ==== Compatibility Flowable supports both Spring Boot 2.0 and 1.5 with the same starters. The base support is for Spring Boot 2.0, which means that the actuator endpoints are only supported on 2.0. The Flowable starters are also puling spring boot starter transitively, which means that users will have to define the 1.5 version of the spring boot starters in their own build files. [[springSpringBootGettingStarted]] ==== Getting started Spring Boot is all about convention over configuration. To get started, you would need to create a Spring Boot project. The easiest way to do this would be to create a project via link:$$https://start.spring.io/$$[start.spring.io]. For example create a project with web and h2 dependencies. Then in the created project simply add the _flowable-spring-boot-starter_ or _flowable-spring-boot-starter-rest_ dependency. In case you don't need all the engines see the other <>. For example for Maven: [source,xml,linenums] ---- org.flowable flowable-spring-boot-starter ${flowable.version} ---- That's all that's needed. This dependency will transitively add the correct Flowable dependencies to the classpath. You can now run your Spring Boot application: [source,java,,linenums] ---- import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication(proxyBeanMethods = false) public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } } ---- You will see an output like this: ---- . ____ _ __ _ _ /\\\\ / ___'_ __ _ _(_)_ __ __ _ \\ \\ \\ \\ ( ( )\\___ | '_ | '_| | '_ \\/ _` | \\ \\ \\ \\ \\\\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.0.0.RELEASE) MyApplication : Starting MyApplication on ... MyApplication : No active profile set, falling back to default profiles: default ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@4fdfa676: startup date [Wed Mar 28 12:04:00 CEST 2018]; root of context hierarchy o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http) o.apache.catalina.core.StandardService : Starting service [Tomcat] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.28 o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 3085 ms o.s.b.w.servlet.ServletRegistrationBean : Servlet dispatcherServlet mapped to [/] o.s.b.w.servlet.ServletRegistrationBean : Servlet Flowable IDM Rest API mapped to [/idm-api/*] o.s.b.w.servlet.ServletRegistrationBean : Servlet Flowable Form Rest API mapped to [/form-api/*] o.s.b.w.servlet.ServletRegistrationBean : Servlet Flowable DMN Rest API mapped to [/dmn-api/*] o.s.b.w.servlet.ServletRegistrationBean : Servlet Flowable Content Rest API mapped to [/content-api/*] o.s.b.w.servlet.ServletRegistrationBean : Servlet Flowable CMMN Rest API mapped to [/cmmn-api/*] o.s.b.w.servlet.ServletRegistrationBean : Servlet Flowable BPMN Rest API mapped to [/process-api/*] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*] uration$$EnhancerBySpringCGLIB$$3d0c70ac : No deployment resources were found for autodeployment uration$$EnhancerBySpringCGLIB$$8131eb1a : No deployment resources were found for autodeployment o.f.e.i.c.ProcessEngineConfigurationImpl : Found 5 Engine Configurators in total: o.f.e.i.c.ProcessEngineConfigurationImpl : class org.flowable.idm.spring.configurator.SpringIdmEngineConfigurator (priority:100000) o.f.e.i.c.ProcessEngineConfigurationImpl : class org.flowable.dmn.spring.configurator.SpringDmnEngineConfigurator (priority:200000) o.f.e.i.c.ProcessEngineConfigurationImpl : class org.flowable.form.spring.configurator.SpringFormEngineConfigurator (priority:300000) o.f.e.i.c.ProcessEngineConfigurationImpl : class org.flowable.content.spring.configurator.SpringContentEngineConfigurator (priority:400000) o.f.e.i.c.ProcessEngineConfigurationImpl : class org.flowable.cmmn.spring.configurator.SpringCmmnEngineConfigurator (priority:500000) o.f.e.i.c.ProcessEngineConfigurationImpl : Executing beforeInit() of class org.flowable.idm.spring.configurator.SpringIdmEngineConfigurator (priority:100000) o.f.e.i.c.ProcessEngineConfigurationImpl : Executing beforeInit() of class org.flowable.dmn.spring.configurator.SpringDmnEngineConfigurator (priority:200000) o.f.e.i.c.ProcessEngineConfigurationImpl : Executing beforeInit() of class org.flowable.form.spring.configurator.SpringFormEngineConfigurator (priority:300000) o.f.e.i.c.ProcessEngineConfigurationImpl : Executing beforeInit() of class org.flowable.content.spring.configurator.SpringContentEngineConfigurator (priority:400000) o.f.e.i.c.ProcessEngineConfigurationImpl : Executing beforeInit() of class org.flowable.cmmn.spring.configurator.SpringCmmnEngineConfigurator (priority:500000) com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting... com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed. o.f.e.i.c.ProcessEngineConfigurationImpl : Executing configure() of class org.flowable.idm.spring.configurator.SpringIdmEngineConfigurator (priority:100000) .d.AbstractSqlScriptBasedDbSchemaManager : performing create on identity with resource org/flowable/idm/db/create/flowable.h2.create.identity.sql o.f.idm.engine.impl.IdmEngineImpl : IdmEngine default created o.f.e.i.c.ProcessEngineConfigurationImpl : Executing configure() of class org.flowable.dmn.spring.configurator.SpringDmnEngineConfigurator (priority:200000) o.f.dmn.engine.impl.DmnEngineImpl : DmnEngine default created o.f.e.i.c.ProcessEngineConfigurationImpl : Executing configure() of class org.flowable.form.spring.configurator.SpringFormEngineConfigurator (priority:300000) o.f.form.engine.impl.FormEngineImpl : FormEngine default created o.f.e.i.c.ProcessEngineConfigurationImpl : Executing configure() of class org.flowable.content.spring.configurator.SpringContentEngineConfigurator (priority:400000) o.f.c.engine.ContentEngineConfiguration : Content file system root : ... o.f.c.engine.impl.ContentEngineImpl : ContentEngine default created o.f.e.i.c.ProcessEngineConfigurationImpl : Executing configure() of class org.flowable.cmmn.spring.configurator.SpringCmmnEngineConfigurator (priority:500000) o.f.cmmn.engine.CmmnEngineConfiguration : Found 1 Engine Configurators in total: o.f.cmmn.engine.CmmnEngineConfiguration : class org.flowable.idm.engine.configurator.IdmEngineConfigurator (priority:100000) o.f.cmmn.engine.CmmnEngineConfiguration : Executing beforeInit() of class org.flowable.idm.engine.configurator.IdmEngineConfigurator (priority:100000) o.f.cmmn.engine.CmmnEngineConfiguration : Executing configure() of class org.flowable.idm.engine.configurator.IdmEngineConfigurator (priority:100000) o.f.idm.engine.impl.IdmEngineImpl : IdmEngine default created o.f.cmmn.engine.impl.CmmnEngineImpl : CmmnEngine default created o.f.engine.impl.ProcessEngineImpl : ProcessEngine default created o.f.j.s.i.a.AbstractAsyncExecutor : Starting up the async job executor [org.flowable.spring.job.service.SpringAsyncExecutor]. o.f.j.s.i.a.AcquireAsyncJobsDueRunnable : starting to acquire async jobs due o.f.j.s.i.a.AcquireTimerJobsRunnable : starting to acquire async jobs due o.f.j.s.i.a.ResetExpiredJobsRunnable : starting to reset expired jobs o.f.e.impl.cmd.ValidateV5EntitiesCmd : Total of v5 deployments found: 0 s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@4fdfa676: startup date [Wed Mar 28 12:04:00 CEST 2018]; root of context hierarchy s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped ""{[/error]}"" onto public org.springframework.http.ResponseEntity> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest) s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped ""{[/error],produces=[text/html]}"" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse) o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup o.s.j.e.a.AnnotationMBeanExporter : Bean with name 'dataSource' has been autodetected for JMX exposure o.s.j.e.a.AnnotationMBeanExporter : Located MBean 'dataSource': registering with JMX server as MBean [com.zaxxer.hikari:name=dataSource,type=HikariDataSource] o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase -20 o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase 0 o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase 20 o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path '' flowable.Application : Started Application in 18.235 seconds (JVM running for 19.661) ---- So, by just adding the dependency to the classpath and using the _@SpringBootAplication_ annotation a lot has happened behind the scenes: * An in-memory datasource is created automatically (because the H2 driver is on the classpath) and passed to the Flowable process engine configuration * A Flowable ProcessEngine, CmmnEngine, DmnEngine, FormEngine, ContentEngine and IdmEngine beans have been created and exposed * All the Flowable services are exposed as Spring beans * The Spring Job Executor is created Also: * Any BPMN 2.0 process definitions in the _processes_ folder will be automatically deployed. Create a folder _processes_ and add a dummy process definition (named _one-task-process.bpmn20.xml_) to this folder. The content of this file is shown below. * Any CMMN 1.1 case definitions in the _cases_ folder will be automatically deployed. * Any DMN 1.1 dmn definitions in the _dmn_ folder will be automatically deployed. * Any Form definitions in the _forms_ folder will be automatically deployed. The XML content of the process definition is shown below. Notice that, for the moment, we are hard-coding an assignee called ""kermit"" to the user task. We'll come back to this later. [source,xml,linenums] ---- ---- Also, add following code lines to test if the deployment actually worked. The _CommandLineRunner_ is a special kind of Spring bean that is executed when the application boots: [source,java,linenums] ---- @SpringBootApplication(proxyBeanMethods = false) public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } @Bean public CommandLineRunner init(final RepositoryService repositoryService, final RuntimeService runtimeService, final TaskService taskService) { return new CommandLineRunner() { @Override public void run(String... strings) throws Exception { System.out.println(""Number of process definitions : "" + repositoryService.createProcessDefinitionQuery().count()); System.out.println(""Number of tasks : "" + taskService.createTaskQuery().count()); runtimeService.startProcessInstanceByKey(""oneTaskProcess""); System.out.println(""Number of tasks after process start: "" + taskService.createTaskQuery().count()); } }; } } ---- The output expected will be: ---- Number of process definitions : 1 Number of tasks : 0 Number of tasks after process start : 1 ---- ==== Changing the database and connection pool As stated above, Spring Boot is about convention over configuration. By default, by having only H2 on the classpath, it created an in-memory datasource and passed that to the Flowable process engine configuration. To change the datasource, simply add the database driver dependencies and provide the URL to the database. For example, to switch to a MySQL database: [source,linenums] ---- spring.datasource.url=jdbc:mysql://127.0.0.1:3306/flowable-spring-boot?characterEncoding=UTF-8 spring.datasource.username=flowable spring.datasource.password=flowable ---- Remove H2 from the Maven dependencies and add the MySQL driver to the classpath: [source,xml,linenums] ---- mysql mysql-connector-java 5.1.45 ---- When the app is now booted up, you'll see it uses MySQL as database (and the HikariCP connection pooling framework): ---- org.flowable.engine.impl.db.DbSqlSession : performing create on engine with resource org/flowable/db/create/flowable.mysql.create.engine.sql org.flowable.engine.impl.db.DbSqlSession : performing create on history with resource org/flowable/db/create/flowable.mysql.create.history.sql org.flowable.engine.impl.db.DbSqlSession : performing create on identity with resource org/flowable/db/create/flowable.mysql.create.identity.sql ---- When you reboot the application multiple times, you'll see the number of tasks go up (the H2 in-memory database does not survive a shutdown, MySQL does). For more information about how to configure the datasource have a look in link:$$https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-sql.html#boot-features-configure-datasource$$[Configure a DataSource] in the Spring Boot reference guide. ==== REST support Often, a REST API is used on top of the embedded Flowable engine (interacting with the different services in a company). Spring Boot makes this really easy. Add following dependency to the classpath: [source,xml,linenums] ---- org.springframework.boot spring-boot-starter-web ${spring.boot.version} ---- Create a new class, a Spring service and create two methods: one to start our process and one to get a task list for a given assignee. We simply wrap Flowable calls here, but in real-life scenarios this will be more complex. [source,java,linenums] ---- @Service public class MyService { @Autowired private RuntimeService runtimeService; @Autowired private TaskService taskService; @Transactional public void startProcess() { runtimeService.startProcessInstanceByKey(""oneTaskProcess""); } @Transactional public List getTasks(String assignee) { return taskService.createTaskQuery().taskAssignee(assignee).list(); } } ---- We can now create a REST endpoint by annotating a class with _@RestController_. Here, we simply delegate to the service defined above. [source,java,linenums] ---- @RestController public class MyRestController { @Autowired private MyService myService; @PostMapping(value=""/process"") public void startProcessInstance() { myService.startProcess(); } @RequestMapping(value=""/tasks"", method= RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE) public List getTasks(@RequestParam String assignee) { List tasks = myService.getTasks(assignee); List dtos = new ArrayList(); for (Task task : tasks) { dtos.add(new TaskRepresentation(task.getId(), task.getName())); } return dtos; } static class TaskRepresentation { private String id; private String name; public TaskRepresentation(String id, String name) { this.id = id; this.name = name; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } } ---- Both the _@Service_ and the _@RestController_ will be found by the automatic component scan for a Spring Boot application. Run the application class again. We can now interact with the REST API, for example, by using cURL: ---- curl http://localhost:8080/tasks?assignee=kermit [] curl -X POST http://localhost:8080/process curl http://localhost:8080/tasks?assignee=kermit [{""id"":""10004"",""name"":""my task""}] ---- As can be seen, we are referring to the assignee, ""kermit"", which was hard-coded into the process definition XML earlier. We'll change this later on to allow the assignee to be set when the workflow instance is started. ==== JPA support To add JPA support for Flowable in Spring Boot, add following dependency: [source,xml,linenums] ---- org.flowable flowable-spring-boot-starter ${flowable.version} org.springframework.boot spring-boot-starter-data-jpa ${spring-boot.version} ---- This will add in the Spring configuration and beans for using JPA. By default, the JPA provider will be Hibernate. Let's create a simple Entity class: [source,java,linenums] ---- @Entity class Person { @Id @GeneratedValue private Long id; private String username; private String firstName; private String lastName; private Date birthDate; public Person() { } public Person(String username, String firstName, String lastName, Date birthDate) { this.username = username; this.firstName = firstName; this.lastName = lastName; this.birthDate = birthDate; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public Date getBirthDate() { return birthDate; } public void setBirthDate(Date birthDate) { this.birthDate = birthDate; } } ---- By default, when not using an in-memory database, the tables won't be created automatically. Create a file _application.properties_ on the classpath and add following property: ---- spring.jpa.hibernate.ddl-auto=update ---- Add following class: [source,java,linenums] ---- @Repository public interface PersonRepository extends JpaRepository { Person findByUsername(String username); } ---- This is a Spring repository, which offers CRUD out of the box. We add the method to find a Person by username. Spring will automatically implement this based on conventions (typically, the property names used). We now enhance our service further: * by adding _@Transactional_ to the class. Note that by adding the JPA dependency above, the DataSourceTransactionManager which we were using before is now automatically swapped out by a JpaTransactionManager. * The _startProcess_ now gets an assignee username passed in, which is used to look up the Person, and put the Person JPA object as a process variable in the process instance. * A method to create Dummy users is added. This is used in the CommandLineRunner to populate the database. [source,java,linenums] ---- @Service @Transactional public class MyService { @Autowired private RuntimeService runtimeService; @Autowired private TaskService taskService; @Autowired private PersonRepository personRepository; public void startProcess(String assignee) { Person person = personRepository.findByUsername(assignee); Map variables = new HashMap(); variables.put(""person"", person); runtimeService.startProcessInstanceByKey(""oneTaskProcess"", variables); } public List getTasks(String assignee) { return taskService.createTaskQuery().taskAssignee(assignee).list(); } public void createDemoUsers() { if (personRepository.findAll().size() == 0) { personRepository.save(new Person(""jbarrez"", ""Joram"", ""Barrez"", new Date())); personRepository.save(new Person(""trademakers"", ""Tijs"", ""Rademakers"", new Date())); } } } ---- The CommandLineRunner now looks like: [source,java,linenums] ---- @Bean public CommandLineRunner init(final MyService myService) { return new CommandLineRunner() { public void run(String... strings) throws Exception { myService.createDemoUsers(); } }; } ---- The RestController is also modified slightly to incorporate the changes above (only showing new methods) and the HTTP POST now has a body that contains the assignee username: ---- @RestController public class MyRestController { @Autowired private MyService myService; @PostMapping(value=""/process"") public void startProcessInstance(@RequestBody StartProcessRepresentation startProcessRepresentation) { myService.startProcess(startProcessRepresentation.getAssignee()); } ... static class StartProcessRepresentation { private String assignee; public String getAssignee() { return assignee; } public void setAssignee(String assignee) { this.assignee = assignee; } } ---- And finally, to try out the Spring-JPA-Flowable integration, we assign the task using the ID of the Person JPA object in the process definition: [source,xml,linenums] ---- ---- This replaces the hard-coded recipient, ""kermit"", which we had initially set. We can now start a new process instance, providing the user name in the POST body: ---- curl -H ""Content-Type: application/json"" -d '{""assignee"" : ""jbarrez""}' http://localhost:8080/process ---- And the task list is now fetched using the person ID: ---- curl http://localhost:8080/tasks?assignee=1 [{""id"":""12505"",""name"":""my task""}] ---- [[springBootActuatorEndpoint]] ==== Flowable Actuator Endpoints Flowable provides a Spring Boot Actuator Endpoint that exposes information for the Processes that are running. By default, the `flowable` endpoint is mapped to `/actuator/flowable`. Spring Boot by default only exposes a few endpoints to the web (e.g.: In `spring-boot-starter-actuator:2.5.4` , Spring Boot by default only exposes the `health` endpoint to the web. For more information about the endpoints exposed to the web by default, see link:$$https://docs.spring.io/spring-boot/docs/current/reference/html/actuator.html#actuator.endpoints.exposing$$[https://docs.spring.io/spring-boot/docs/current/reference/html/actuator.html#actuator.endpoints.exposing]). In order to use the `flowable` endpoint through the web, you need to add `management.endpoints.web.exposure.include=flowable` to your `application.properties` (Note: The `org.flowable.spring.boot.EndpointAutoConfiguration` class does not use the `@ConditionalOnAvailableEndpoint` annotation to check whether the `flowable` endpoint is both enabled and exposed like the `HealthEndpointAutoConfiguration` class. So the only thing you need to do to use the `flowable` endpoint through the web is to add `management.endpoints.web.exposure.include=flowable` or `management.endpoints.web.exposure.include=*` to your configuration file. ). In order to make enable Actuator endpoints you need to add a dependency on Actuator, e.g. by using {sc-flowable-starter}/flowable-spring-boot-starter-actuator/pom.xml[flowable-spring-boot-starter-actuator]. `curl http://localhost:8080/actuator/flowable` [source,json] ---- { ""completedTaskCountToday"": 0, ""deployedProcessDefinitions"": [ ""oneTaskProcess (v1)"" ], ""processDefinitionCount"": 1, ""cachedProcessDefinitionCount"": 0, ""runningProcessInstanceCount"": { ""oneTaskProcess (v1)"": 0 }, ""completedTaskCount"": 2, ""completedActivities"": 3, ""completedProcessInstanceCount"": { ""oneTaskProcess (v1)"": 0 }, ""openTaskCount"": 0 } ---- For more information about Spring Boot Actuator see link:$$https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-endpoints.html$$[Production Ready Endpoint] in the Spring Boot reference documentation. [[springBootInfoContributor]] ==== Flowable Info Contributor Flowable also provides a Spring Boot `InfoContributor` which looks like: `curl http://localhost:8080/actuator/info` [source,json] ---- { ""flowable"": { ""version"": ""6.5.0.event-SNAPSHOT"" } } ---- [[springBootFlowableProperties]] ==== Flowable Application Properties The Flowable auto configuration is leveraging the Spring Boot properties and configuration mechanism. See link:$$https://docs.spring.io/spring-boot/docs/current/reference/html/howto-properties-and-configuration.html$$[Properties and Configuration] in the Spring Boot reference guide. Here is a list of configuration properties that the Flowable Spring Boot support consumes. [source,properties,indent=0,subs=""verbatim,attributes,macros""] ---- # =================================================================== # Common Flowable Spring Boot Properties # # This sample file is provided as a guideline. Do NOT copy it in its # entirety to your own application. ^^^ # =================================================================== # Core (Process) {sc-flowable-boot}/FlowableProperties.java[FlowableProperties] flowable.check-process-definitions=true # Whether process definitions need to be auto deployed. flowable.custom-mybatis-mappers= # The FQN of custom Mybatis mappers that need to be added to the engine. flowable.custom-mybatis-x-m-l-mappers= # The location of the custom Mybatis XML Mappers that need to be added to the engine. flowable.database-schema= # In some situations you want to set the schema to use for table checks / generation if the database metadata doesn't return that correctly. flowable.database-schema-update=true # The strategy that should be used for the database schema. flowable.db-history-used=true # Whether db history should be used. flowable.deployment-name=SpringBootAutoDeployment # The name of the auto deployment. flowable.history-level=audit # The history level that needs to be used. flowable.process-definition-location-prefix=classpath*:/processes/ # The folder in which processes need to be searched for auto deployment. flowable.process-definition-location-suffixes=**.bpmn20.xml,**.bpmn # The suffixes (extensions) of the files that needs to be deployed from the 'processDefinitionLocationPrefix' location. # Process {sc-flowable-boot}/process/FlowableProcessProperties.java[FlowableProcessProperties] flowable.process.definition-cache-limit=-1 # The maximum amount of process definitions available in the process definition cache. Per default it is -1 (all process definitions). flowable.process.enable-safe-xml=true # Enables extra checks on the BPMN xml that is parsed. See https://www.flowable.org/docs/userguide/index.html#advanced.safe.bpmn.xml. Unfortunately, this feature is not available on some platforms (JDK 6, JBoss), hence you need to disable if your platform does not allow the use of StaxSource during XML parsing. flowable.process.servlet.load-on-startup=-1 # Load on startup of the Process dispatcher servlet. flowable.process.servlet.name=Flowable BPMN Rest API # The name of the Process servlet. flowable.process.servlet.path=/process-api # The context path for the Process rest servlet. # Process Async Executor flowable.process.async-executor-activate=true # Whether the async executor should be activated. flowable.process.async.executor.async-job-lock-time-in-millis=300000 # The amount of time (in milliseconds) an async job is locked when acquired by the async executor. During this period of time, no other async executor will try to acquire and lock this job. flowable.process.async.executor.default-async-job-acquire-wait-time-in-millis=10000 # The time (in milliseconds) the async job acquisition thread will wait to execute the next acquirement query. This happens when no new async jobs were found or when less async jobs have been fetched. Default value = 10 seconds. flowable.process.async.executor.default-queue-size-full-wait-time-in-millis=0 # The time (in milliseconds) the async job (both timer and async continuations) acquisition thread will wait when the queue is full to execute the next query. By default set to 0 (for backwards compatibility) flowable.process.async.executor.default-timer-job-acquire-wait-time-in-millis=10000 # The time (in milliseconds) the timer job acquisition thread will wait to execute the next acquirement query. This happens when no new timer jobs were found or when less async jobs have been fetched. Default value = 10 seconds. flowable.process.async.executor.max-async-jobs-due-per-acquisition=1 # ??? flowable.process.async.executor.retry-wait-time-in-millis=500 # ??? flowable.process.async.executor.timer-lock-time-in-millis=300000 # The amount of time (in milliseconds) a timer job is locked when acquired by the async executor. During this period of time, no other async executor will try to acquire and lock this job. # CMMN {sc-flowable-boot}/cmmn/FlowableCmmnProperties.java[FlowableCmmnProperties] flowable.cmmn.deploy-resources=true # Whether to perform deployment of resources, default is 'true'. flowable.cmmn.deployment-name=SpringBootAutoDeployment # The name of the deployment for the CMMN resources. flowable.cmmn.enable-safe-xml=true # Enables extra checks on the DMN xml that is parsed. See https://www.flowable.org/docs/userguide/index.html#advanced.safe.bpmn.xml. Unfortunately, this feature is not available on some platforms (JDK 6, JBoss), hence you need to disable if your platform does not allow the use of StaxSource during XML parsing. flowable.cmmn.enabled=true # Whether the CMMN engine needs to be started. flowable.cmmn.resource-location=classpath*:/cases/ # The location where the CMMN resources are located. flowable.cmmn.resource-suffixes=**.cmmn,**.cmmn11,**.cmmn.xml,**.cmmn11.xml # The suffixes for the resources that need to be scanned. flowable.cmmn.servlet.load-on-startup=-1 # Load on startup of the CMMN dispatcher servlet. flowable.cmmn.servlet.name=Flowable CMMN Rest API # The name of the CMMN servlet. flowable.cmmn.servlet.path=/cmmn-api # The context path for the CMMN rest servlet. # CMMN Async Executor flowable.cmmn.async-executor-activate=true # Whether the async executor should be activated. flowable.cmmn.async.executor.async-job-lock-time-in-millis=300000 # The amount of time (in milliseconds) an async job is locked when acquired by the async executor. During this period of time, no other async executor will try to acquire and lock this job. flowable.cmmn.async.executor.default-async-job-acquire-wait-time-in-millis=10000 # The time (in milliseconds) the async job acquisition thread will wait to execute the next acquirement query. This happens when no new async jobs were found or when less async jobs have been fetched. Default value = 10 seconds. flowable.cmmn.async.executor.default-queue-size-full-wait-time-in-millis=0 # The time (in milliseconds) the async job (both timer and async continuations) acquisition thread will wait when the queue is full to execute the next query. By default set to 0 (for backwards compatibility) flowable.cmmn.async.executor.default-timer-job-acquire-wait-time-in-millis=10000 # The time (in milliseconds) the timer job acquisition thread will wait to execute the next acquirement query. This happens when no new timer jobs were found or when less async jobs have been fetched. Default value = 10 seconds. flowable.cmmn.async.executor.max-async-jobs-due-per-acquisition=1 # ??? flowable.cmmn.async.executor.retry-wait-time-in-millis=500 # ??? flowable.cmmn.async.executor.timer-lock-time-in-millis=300000 # The amount of time (in milliseconds) a timer job is locked when acquired by the async executor. During this period of time, no other async executor will try to acquire and lock this job. # Content {sc-flowable-boot}/content/FlowableContentProperties.java[FlowableContentProperties] flowable.content.enabled=true # Whether the content engine needs to be started. flowable.content.servlet.load-on-startup=-1 # Load on startup of the Content dispatcher servlet. flowable.content.servlet.name=Flowable Content Rest API # The name of the Content servlet. flowable.content.servlet.path=/content-api # The context path for the Content rest servlet. flowable.content.storage.create-root=true # If the root folder doesn't exist, should it be created? flowable.content.storage.root-folder= # Root folder location where content files will be stored, for example, task attachments or form file uploads. # DMN {sc-flowable-boot}/dmn/FlowableDmnProperties.java[FlowableDmnProperties] flowable.dmn.deploy-resources=true # Whether to perform deployment of resources, default is 'true'. flowable.dmn.deployment-name=SpringBootAutoDeployment # The name of the deployment for the dmn resources. flowable.dmn.enable-safe-xml=true # Enables extra checks on the DMN xml that is parsed. See https://www.flowable.org/docs/userguide/index.html#advanced.safe.bpmn.xml. Unfortunately, this feature is not available on some platforms (JDK 6, JBoss), hence you need to disable if your platform does not allow the use of StaxSource during XML parsing. flowable.dmn.enabled=true # Whether the dmn engine needs to be started. flowable.dmn.history-enabled=true # Whether the history for the DMN engine should be enabled. flowable.dmn.resource-location=classpath*:/dmn/ # The location where the dmn resources are located. flowable.dmn.resource-suffixes=**.dmn,**.dmn.xml,**.dmn11,**.dmn11.xml # The suffixes for the resources that need to be scanned. flowable.dmn.servlet.load-on-startup=-1 # Load on startup of the DMN dispatcher servlet. flowable.dmn.servlet.name=Flowable DMN Rest API # The name of the DMN servlet. flowable.dmn.servlet.path=/dmn-api # The context path for the DMN rest servlet. flowable.dmn.strict-mode=true # Set this to false if you want to ignore the decision table hit policy validity checks to result in an failed decision table state. A result is that intermediate results created up to the point the validation error occurs are returned. # Form {sc-flowable-boot}/form/FlowableFormProperties.java[FlowableFormProperties] flowable.form.deploy-resources=true # Whether to perform deployment of resources, default is true. flowable.form.deployment-name=SpringBootAutoDeployment # The name of the deployment for the form resources. flowable.form.enabled=true # Whether the form engine needs to be started. flowable.form.resource-location=classpath*:/forms/ # The location where the form resources are located. flowable.form.resource-suffixes=**.form # The suffixes for the resources that need to be scanned. flowable.form.servlet.load-on-startup=-1 # Load on startup of the Form dispatcher servlet. flowable.form.servlet.name=Flowable Form Rest API # The name of the Form servlet. flowable.form.servlet.path=/form-api # The context path for the Form rest servlet. # IDM {sc-flowable-boot}/idm/FlowableIdmProperties.java[FlowableIdmProperties] flowable.idm.enabled=true # Whether the idm engine needs to be started. flowable.idm.password-encoder= # The type of the password encoder that needs to be used. flowable.idm.servlet.load-on-startup=-1 # Load on startup of the IDM dispatcher servlet. flowable.idm.servlet.name=Flowable IDM Rest API # The name of the IDM servlet. flowable.idm.servlet.path=/idm-api # The context path for the IDM rest servlet. # IDM Ldap {sc-flowable-boot}/ldap/FlowableLdapProperties.java[FlowableLdapProperties] flowable.idm.ldap.attribute.email= # Name of the attribute that matches the user email. flowable.idm.ldap.attribute.first-name= # Name of the attribute that matches the user first name. flowable.idm.ldap.attribute.group-id= # Name of the attribute that matches the group id. flowable.idm.ldap.attribute.group-name= # Name of the attribute that matches the group name. flowable.idm.ldap.attribute.group-type= # Name of the attribute that matches the group type. flowable.idm.ldap.attribute.last-name= # Name of the attribute that matches the user last name. flowable.idm.ldap.attribute.user-id= # Name of the attribute that matches the user id. flowable.idm.ldap.base-dn= # The base 'distinguished name' (DN) from which the searches for users and groups are started. flowable.idm.ldap.cache.group-size=-1 # Allows to set the size of the {@link 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. flowable.idm.ldap.custom-connection-parameters= # Allows to set all LDAP connection parameters which do not have a dedicated setter. See for example http://docs.oracle.com/javase/tutorial/jndi/ldap/jndi.html for custom properties. Such properties are for example to configure connection pooling, specific security settings, etc. flowable.idm.ldap.enabled=false # Whether to enable LDAP IDM Service. flowable.idm.ldap.group-base-dn= # The base 'distinguished name' (DN) from which the searches for groups are started. flowable.idm.ldap.initial-context-factory=com.sun.jndi.ldap.LdapCtxFactory # The class name for the initial context factory. flowable.idm.ldap.password= # The password that is used to connect to the LDAP system. flowable.idm.ldap.port=-1 # The port on which the LDAP system is running. flowable.idm.ldap.query.all-groups= # The query that is executed when searching for all groups. flowable.idm.ldap.query.all-users= # The query that is executed when searching for all users. flowable.idm.ldap.query.groups-for-user= # The query that is executed when searching for the groups of a specific user. flowable.idm.ldap.query.user-by-full-name-like= # The query that is executed when searching for a user by full name. flowable.idm.ldap.query.user-by-id= # The query that is executed when searching for a user by userId. flowable.idm.ldap.query.group-by-id= # The query that is executed when searching for a specific group by groupId. flowable.idm.ldap.search-time-limit=0 # The timeout (in milliseconds) that is used when doing a search in LDAP. By default set to '0', which means 'wait forever'. flowable.idm.ldap.security-authentication=simple # The value that is used for the 'java.naming.security.authentication' property used to connect to the LDAP system. flowable.idm.ldap.server= # The server host on which the LDAP system can be reached. For example 'ldap://localhost'. flowable.idm.ldap.user= # The user id that is used to connect to the LDAP system. flowable.idm.ldap.user-base-dn= # The base 'distinguished name' (DN) from which the searches for users are started. # Flowable Mail {sc-flowable-boot}/FlowableMailProperties.java[FlowableMailProperties] flowable.mail.server.default-from=flowable@localhost # The default from address that needs to be used when sending emails. flowable.mail.server.force-to= # The force to address(es) that would be used when sending out emails. IMPORTANT: If this is set then all emails will be send to defined address(es) instead of the address configured in the MailActivity. flowable.mail.server.host=localhost # The host of the mail server. flowable.mail.server.password= # The password for the mail server authentication. flowable.mail.server.port=1025 # The port of the mail server. flowable.mail.server.ssl-port=1465 # The SSL port of the mail server. flowable.mail.server.use-ssl=false # Sets whether SSL/TLS encryption should be enabled for the SMTP transport upon connection (SMTPS/POPS). flowable.mail.server.use-tls=false # Set or disable the STARTTLS encryption. flowable.mail.server.username= # The username that needs to be used for the mail server authentication. If empty no authentication would be used. # Flowable Http {sc-flowable-boot}/FlowableHttpProperties.java[FlowableHttpProperties] flowable.http.user-system-properties=false # Whether to use system properties (e.g. http.proxyPort). flowable.http.connect-timeout=5s # Connect timeout for the http client flowable.http.socket-timeout=5s # Socket timeout for the http client flowable.http.connection-request-timeout=5s # Connection Request Timeout for the http client flowable.http.request-retry-limit=3 # Request retry limit for the http client flowable.http.disable-cert-verify=false # Whether to disable certificate validation for the http client # Flowable REST flowable.rest.app.cors.enabled=true # Whether to enable CORS requests at all. If false, the other properties have no effect flowable.rest.app.cors.allow-credentials=true # Whether to include credentials in a CORS request flowable.rest.app.cors.allowed-origins=* # Comma-separated URLs to accept CORS requests from flowable.rest.app.cors.allowed-headers=* # Comma-separated HTTP headers to allow in a CORS request flowable.rest.app.cors.allowed-methods=DELETE,GET,PATCH,POST,PUT # Comma-separated HTTP verbs to allow in a CORS request flowable.rest.app.cors.exposed-headers=* # Comma-separated list of headers to expose in CORS response # Actuator management.endpoint.flowable.cache.time-to-live=0ms # Maximum time that a response can be cached. management.endpoint.flowable.enabled=true # Whether to enable the flowable endpoint. ---- .Deprecated properties [cols=""4*"",options=""header""] |=============== |Property name |Old Property |Default value |Description |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.mail.server.host |flowable.mail-server-host |localhost |The host of the mail server. |flowable.mail.server.password |flowable.mail-server-password |- |The password for the mail server authentication. |flowable.mail.server.port |flowable.mail-server-port |1025 |The port of the mail server. |flowable.mail.server.ssl-port |flowable.mail-server-ssl-port |1465 |The SSL port of the mail server. |flowable.mail.server.use-ssl |flowable.mail-server-use-ssl |false |Sets whether SSL/TLS encryption should be enabled for the SMTP transport upon connection (SMTPS/POPS). |flowable.mail.server.use-tls |flowable.mail-server-use-tls |false |Set or disable the STARTTLS encryption. |flowable.mail.server.username |flowable.mail-server-user-name |- |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) |=============== [[springBootFlowableAutoConfiguration]] ==== Flowable Auto-configuration classes Here is a list of all auto-configuration classes provided by Flowable, with links to documentation and source code. Remember to also look at the conditions report in your application for more details of which features are switched on. (To do so, start the app with --debug or -Ddebug or, in an Actuator application, use the conditions endpoint). [cols=*,options=""header""] |=== |Configuration Class |{sc-flowable-boot}/content/ContentEngineAutoConfiguration.java[ContentEngineAutoConfiguration] |{sc-flowable-boot}/content/ContentEngineServicesAutoConfiguration.java[ContentEngineServicesAutoConfiguration] |{sc-flowable-boot}/cmmn/CmmnEngineAutoConfiguration.java[CmmnEngineAutoConfiguration] |{sc-flowable-boot}/cmmn/CmmnEngineServicesAutoConfiguration.java[CmmnEngineServicesAutoConfiguration] |{sc-flowable-boot}/dmn/DmnEngineAutoConfiguration.java[DmnEngineAutoConfiguration] |{sc-flowable-boot}/dmn/DmnEngineServicesAutoConfiguration.java[DmnEngineServicesAutoConfiguration] |{sc-flowable-boot}/EndpointAutoConfiguration.java[EndpointAutoConfiguration] |{sc-flowable-boot}/actuate/info/FlowableInfoAutoConfiguration.java[FlowableInfoAutoConfiguration] |{sc-flowable-boot}/ldap/FlowableLdapAutoConfiguration.java[FlowableLdapAutoConfiguration] |{sc-flowable-boot}/FlowableTransactionAutoConfiguration.java[FlowableTransactionAutoConfiguration] |{sc-flowable-boot}/form/FormEngineAutoConfiguration.java[FormEngineAutoConfiguration] |{sc-flowable-boot}/form/FormEngineServicesAutoConfiguration.java[FormEngineServicesAutoConfiguration] |{sc-flowable-boot}/idm/IdmEngineAutoConfiguration.java[IdmEngineAutoConfiguration] |{sc-flowable-boot}/idm/IdmEngineServicesAutoConfiguration.java[IdmEngineServicesAutoConfiguration] |{sc-flowable-boot}/ProcessEngineAutoConfiguration.java[ProcessEngineAutoConfiguration] |{sc-flowable-boot}/RestApiAutoConfiguration.java[RestApiAutoConfiguration] |{sc-flowable-boot}/SecurityAutoConfiguration.java[SecurityAutoConfiguration] |=== [[springBootFlowableStarter]] ==== Flowable Starters Here is a list of the flowable spring boot starters. [cols=2*,options=""header""] |=== |Starter |Description |{sc-flowable-starter}/flowable-spring-boot-starter-cmmn/pom.xml[flowable-spring-boot-starter-cmmn] |Contains the dependencies for booting the CMMN Engine in Standalone mode |{sc-flowable-starter}/flowable-spring-boot-starter-cmmn-rest/pom.xml[flowable-spring-boot-starter-cmmn-rest] |Contains the dependencies for booting the CMMN Engine in Standalone mode and starts its REST API |{sc-flowable-starter}/flowable-spring-boot-starter-dmn/pom.xml[flowable-spring-boot-starter-dmn] |Contains the dependencies for booting the DMN Engine in Standalone mode |{sc-flowable-starter}/flowable-spring-boot-starter-dmn-rest/pom.xml[flowable-spring-boot-starter-dmn-rest] |Contains the dependencies for booting the DMN Engine in Standalone mode and starts its REST API |{sc-flowable-starter}/flowable-spring-boot-starter-process/pom.xml[flowable-spring-boot-starter-process] |Contains the dependencies for booting the Process Engine in Standalone mode |{sc-flowable-starter}/flowable-spring-boot-starter-process-rest/pom.xml[flowable-spring-boot-starter-process-rest] |Contains the dependencies for booting the Process Engine in Standalone mode and starts its REST API |{sc-flowable-starter}/flowable-spring-boot-starter/pom.xml[flowable-spring-boot-starter] |Contains the dependencies for booting all Flowable Engines (Process, CMMN, DMN, Form, Content and IDM) |{sc-flowable-starter}/flowable-spring-boot-starter-rest/pom.xml[flowable-spring-boot-starter-rest] |Contains the dependencies for booting all Flowable Engines and their respective REST API |{sc-flowable-starter}/flowable-spring-boot-starter-actuator/pom.xml[flowable-spring-boot-starter-actuator] |Contains the required dependencies for Spring Boot |=== ==== Using Liquibase The Flowable engines are using Liquibase to manage the versioning of it's tables. This means that the `LiquibaseAutoConfiguration` from Spring Boot would automatically kick in. However, if you are not using Liquibase then the application will not start and would throw an exception. For this reason Flowable is setting `spring.liquibase.enabled` to `false`, which means that if you need to use Liquibase you have to explicitly enable it. ==== Further Reading Obviously, there is a lot about Spring Boot that hasn't been touched upon yet, like very easy JTA integration or building a WAR file that can be run on major application servers. And there is a lot more to the Spring Boot integration: * Actuator support * Spring Integration support * Rest API integration: boot up the Flowable Rest API embedded within the Spring application * Spring Security support ==== Advanced Configuration ===== Customizing Engine Configuration It's possible to get a hold of the engine configuration by implementing the _org.flowable.spring.boot.EngineConfigurationConfigurer_ interface. Where _T_ is the Spring Type of the particular Engine Configuration. This can be useful for advanced configuration settings or simply because a property has not been exposed (yet). For example: [source, java, linenums] ---- public class MyConfigurer implements EngineConfigurationConfigurer { public void configure(SpringProcessEngineConfiguration processEngineConfiguration) { // advanced configuration } } ---- By exposing an instance of this class as an _@Bean_ in the Spring Boot configuration, the instance will be called before the process engine is fully created. [TIP] ==== You can provide a custom implementation of a Flowable Service by using this. See {sc-flowable-boot}/ldap/FlowableLdapAutoConfiguration.java[FlowableLdapAutoConfiguration] ==== ===== Combining starters In case you need only a combination of the engines then you can add only the required dependencies. For example to use the Process, CMMN, Form and IDM engine and use LDAP you need to add the following dependencies: [source,xml,linenums] ---- org.flowable flowable-spring-boot-starter-process ${flowable.version} org.flowable flowable-spring-boot-starter-cmmn ${flowable.version} org.flowable flowable-content-spring-configurator ${flowable.version} org.flowable flowable-form-spring-configurator ${flowable.version} org.flowable flowable-ldap ${flowable.version} ---- ===== Configuring Async Executors The Process and CMMN engines have dedicated `AsyncExecutor`(s) and they can be configured with the `flowable.{engine}.async.executor` property group. Where `engine` is either `process` or `cmmn`. The `AsyncExecutor`(s) per default share the same Spring `TaskExecutor` and `SpringRejectedJobsHandler`. In case you want to provide a dedicated executor for each of the engines you need define a qualified bean with `@Process` and `@Cmmn`. You can configure custom executors in the following way: [source,java,linenums] ---- @Configuration public class MyConfiguration { @Process <1> @Bean public TaskExecutor processTaskExecutor() { return new SimpleAsyncTaskExecutor(); } @Cmmn <2> @Bean public TaskExecutor cmmnTaskExecutor() { return new SyncTaskExecutor(); } } ---- <1> The Async Executor for the Process Engine would use a `SimpleAsyncTaskExecutor` <2> The Async Executor for the CMMN Engine would use a `SyncTaskExecutor` [IMPORTANT] ====== If you define a custom `TaskExecutor` bean the Flowable creation of the bean is not triggered. Which means that if you define a bean qualified with `@Process` you have to define one with `@Cmmn` or `@Primary`, otherwise the Cmmn Async Executor will use the one for the Process ====== ",12464,False,1887.2268945960961,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_implementation_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_implementation_executor()); } private: basic_socket* self_; }; }; } // namespace asio } // namespace boost #include #endif // BOOST_ASIO_BASIC_SOCKET_HPP ",16377,True,3388.969633851575,median "= Groundbait Indicators of Compromise == ESET detection names - Win32/Agent.UIG trojan - Win32/Agent.XOR trojan - Win64/Agent.XOR trojan - Win32/Agent.XQX trojan - Win32/Agent.XRA trojan - Win32/Agent.XRB trojan - Win32/Agent.XRC trojan - Win64/Agent.DX trojan - Win32/TrojanDropper.Agent.RGH trojan - Win32/TrojanDropper.Agent.RHN trojan - Win32/Prikormka trojan - Win64/Prikormka trojan - MSIL/Prikormka trojan == Host Based indicators - `%PROGRAMFILES%\\IntelRestore\\` - `%USERPROFILE%\\Resent\\roaming\\ocp8.1\\` - `%USERPROFILE%\\AppData\\Local\\MMC\\` - `%USERPROFILE%\\AppData\\Local\\PMG\\` - `%USERPROFILE%\\AppData\\Local\\SKC\\` - `%USERPROFILE%\\AppData\\Local\\CMS\\` - `%USERPROFILE%\\AppData\\Local\\VRT\\` - `%USERPROFILE%\\AppData\\Local\\ioctl\\` - `%WINDIR%\\ntshrui.dll` - `%WINDIR%\\hauthuid.dll` - `%WINDIR%\\hlpuctf.dll` - `%WINDIR%\\atiml.dll` - `%WINDIR%\\iomus.dll` - `%WINDIR%\\swma.dll` - `%WINDIR%\\helpldr.dll` - `%WINDIR%\\rbcon.ini` - `%USERPROFILE%\\AppData\\Local\\CMS\\krman.ini` - `%USERPROFILE%\\AppData\\Local\\VRT\\_wputproc.dll` === Mutexes - `ZxWinDeffContexLNKINFO64` - `Zw_&one@ldrContext43` - `Paramore756Contex43` - `ZxWinDeffContexSMD64` - `ZxWinDeffContexWriteUSBIO64x` - `ZxWinDeffContexRNDRV45scr` - `ZxWinDeffContexRNDRV45snd` - `ZxWinDeffContexSkSwmA` - `ZxWinDeffContexKINP64` - `ZxWinDeffContexRNDRV65` - `ZxWinDeffContexRNDRV65new` - `ZxWinDeffContexRNDRV65xyz` - `ZxWinDeffContexRNDRV65xy` - `ZxWinDeffContexRNDRV64` - `Client67workProc98List3To` == Network indicators === C&C servers - `disk-fulldatabase.rhcloud.com` (IP addresses: `54.175.208.187`, `23.22.38.222`) - `wallejob.in.ua` (IP: `185.68.16.35`) - `wallex.ho.ua` (IP: `91.228.146.13`) - `gils.ho.ua` (IP: `91.228.146.12`) - `literat.ho.ua` (IP: `91.228.146.13`) - `lefting.org` (IP: `91.228.146.11`) - `celebrat.net` (IP: `91.228.146.11`) - `bolepaund.com` (IP: `91.228.146.12`) === Servers used for sending spear phishing e-mail messages - `server-eacloud.rhcloud.com` (IP addresses: `54.152.171.48`, `54.163.210.39`) - `easerver-fulldatabase.rhcloud.com` (IP addresses: `52.23.164.7`, `23.22.221.237`) == Samples All hashes are SHA-1. === Prikormka droppers ---- 42041871308B5711041B7AF69B78F45DF642546C 37F75844C0D0F7F80A699153AF131984D2CE2B6D 029F054A52FE93B0CD6C4D1D815A795EAE9CAAB4 66C143D7C33666903B174F4B94D609BE8791914D 60351035ECDEED071E3FB80AFFE08872A0B582C9 0296191B323900B2BC014E2ACB5E0614C679B682 1BF0E90027EF798727A4496B1928F1FA79146051 76CAE58E4DF4D029155BF2E44BA0F8075DC99020 C0FBE31F1E6E56E93932076BA55A5229E22B5C4A CF09B0CD03C9D0553F0B82827C989D04F1A1FAF1 7C28B907E1053F825478A74FDC1090FBF71DD878 D7F35B66C554EE1076279DF54C4E931651A7A211 2B0FB236DDC0098ADDF051531912FC2601FFCCDC EAB122E5857DF838469B5B00DA0A3BD06DF8DA05 00BCCEBB7614BA270CA2908EE5711F25D3740E7E F908824DB35EFD589449D04E41F8BCEA057F6E52 A8CED2FF8F3D4B77160CB81843652D971469A30B 6002357FB96A786401BAA40A89A85DBA3A7D7AD4 E3E9CA2AC83CFADD80FECD002B377B6B41AC5250 EAFC458AAC3F1564E940BAC7D45C1E659636CC86 FCBC8C75246511F9E4D49FE501F956A857FACE84 803C48A93785581AA89422B6B1E73677BF8DC749 87C34623EBEC481FD430F6CE26849220C641742C A1EE4E4BA27B4035F29FA6AB943AE072D42E65B8 19AAB5FAE0809F87EF27A18208A3C0C52DEA182A C88218C2C23555D5E39596B2110BDA54A7AD50DB EC16141D6C0399B74A26B7B572580B3AC4CBC811 76B77E40182DA242307272B9F77132ABB0B46515 7AB44936E5545C5778C697ABCC20FD8955E35F36 86DD049877B564158020AB9B1A6CA3C30371979D 8665C7A753BA5F619FE79D52DC49724F17D81DAC 8839ED42EC1440CBF30CC345F11B88450EA8FE46 4D2C8CD6C514202CBC133347E2C35F63F03A77BF CDF0734730EA786AD2D3B0E9D0D82F85D3C4AD07 99345C5E6FC6901B630C044DD5C6A5015A94B046 93FE501BCDF62060798E35643B7E5F4E3FFF05A6 1287205FE5B83583CB28D39D965D182EA1DFCFDB C0C4DB689F393A26611B7F8FE08F38B456A173DA 3F867CF4AE4B1232B08E40ADABE7BC21EF856FE2 E9A2B1611EDC105FBA65AFFCDAB062D6FA5C67B0 ADDF8193442D145C6BCB4C54B95A5CFE759C6436 CD5AA66AD7C8D418F19B486211591E31B5B74AB6 8A01C06DF6E59F1513146DFE07936E4ACA59B152 E35081B99C5445952AD4E204A4C42F06D7C3707D A6D8431EFBA501864C4646A63071D28B30EEBF99 613F631D0E384954D2FEA5BE39124AD821C8E5D6 D45CECD9DDD79259C6518300ED77257A9ABBDF92 642033A50EF2C51E1F391D85ED870B09A308469A FD95C6B33AF4B29EFBD26D388C50164C3167CB68 9A578C7C305BE62167EF87AB52E59A12F336186A FE9F5018198567F3D3FB3AA09279C65DBE981171 62487DD8EC172462F9B4CBB790EF6F7878D20352 E397F1D784B4A9EEE7EEAC427C549A301DEC0C7C E8A2734C3FFECB76DD4D1C28D646EE59188BE7BF 8DF79B2734BCD83B3D55FF99521D10E550DFCFF3 64D31BBCF8E224E06BB5F1B350D2F18BFDD78A8E D5B785F8F92C7588CFAD7A1A21DAFFA6EB9CFA5C 8327A743756FA1B051725BF8EC3FDD9B9E844E9A 98440EC18A7E78925CB760F5016111115C89F1F8 6E56BC6023085D6E88668D1C66B91AB5AA92F294 160CF2ABB25495188A0ACB523BD201B0369CFFD2 6E5A098A3EDDEEC2E4986DE84FB00D7EA7EE26B8 8358EA16A0DE64994FBECE1AAC69E847F91BB1B3 3A6C8CB6688E2A56057BA9B3680E5911D96B2C8C AB011CD03B3F211F43930AABD909B5611A829D9D 279711B6828B6CF642C0DAB4D16411C87956F566 2BF9CA8B16BCD679AFB6E9E53C3BB0B04E65044A 9551C390B2DF178DED895D531F440FDDBAE122AA BB8D93A4049968C6D5A243DCFB65A6F4B4DE22A2 80CB14652E8251C79187DF8A01D29ABD46A3118C 6E24C2403DAFAE05C351C5A0A16E2B6403E0F398 09EA7B2F67797915BBFED16F0B21E4E31F4980A3 0AA48DEE8F528B037D8D72AAD039BB2759F362E3 40D7D09053BF60925CBB820417A42DBC6293E017 A6600BD9752E041ED7EE026123A60B19C96259AB 506CCEBDAC5754D1E20D9C3FB280CEC7782EEA6E 40F33CD2AD98FE1E6BF4AB199021498F9E3125A1 9F03A4E0ACD38635104292B8054485E6BF898C48 B373BF4B3AA28FF6D373DA5EAA848AF9772F6454 FD83C2484E2986F22B09623E5971AA54FBD8BCD3 065B075293968732F2BE433B7B492869E4260EE5 B358687593FEBDFD0E1858726098DCFD61D9F8B5 FD2FBB8E4676673A35276B46F2C74562703BCF39 CCD19FD4A1408FCD855B7909578340846904E707 9D84665C00F81C2835E2A41711A139547351D850 69536CAF0522C1A915D6AC4C65177A26EFA7944B 243421FE7C1FC007EFA0C9CCAB6F6E2A0C94FCC2 5B7D6D7C3C4AD74A7F1E32B780776DB41FF18DDD 4418A32BBD215F5DE7B0063B91731B71804E7225 EE1E5D95FCAD429126944804D80D7C2412AF492E E494328255EF2B9ED9B332EE845513A93339217F 6B53A3A3CB9D87D5925C82839015DAD16042C2FF ---- === Prikormka early versions ---- 1B8BC6924F4CFC641032578622BA8C7B4A92F65E B5F1B3BD6AD281C8EB9D633A37E0BE63B97A8BEB BCEDAB81CC5F4D2EA1DA8A71F91DF6E16362723B DC52EE62B94DC38790C3EF855CE5773E48D6CD55 44B6B8375CF788076C0DD64A93E27F69A01F5DFD 539033DE14539D485481549EF84C9E49D743FC4C ---- === Prikormka *PERSISTENCE* modules ---- AD9A6F7BA895769844663B4936E776239D3A3D17 E1B5CD1978F6C6D72AA6B07ADD1EE83E9BB8480D 6E312A999EE7DCD9EC8EB4F0A216F50F50EB09F6 8F8BD3C4CE2F932ABFB31B9F586C40D1E22EE210 3F8D8B20B8FCC200939BBB92FB3B93BB3B4ECD24 756730D1C542B57792F68F0C3BC9BCDE149CF7C6 4F1441F16E80272F488BB114DB6508F0BB9B9E1B 2E1C7FFAB7B1047E3438E6BA920D0914F8CC4E35 3C9990B5D66F3AE9AD9A39A10AC6D291DD86A8F9 CC7091228C1B5A0DAF39ECDA570F75F122BE8A16 26FAEAAE2C042C0A416287A7C54D63D5B4C781B3 854F7CB3A436721F445E0D13FB3BEFF11BF4153D 0596EFE47D6C143BE21294EB4E631A4892A0651A 7DAE2A15E364EE06C9301236AE8FC140884CEA95 C2F720DEF2264F08E5211671D46E73311DC6C473 36215D9A691D826E6CEBC65925BFA6B579675158 0354A768508F6B9D88588641397B76A0CBB10BF2 1790B3D73A5DD676D17B39C01A079DEBD6D9F5C5 2F1E4AF1A5A95B3483E901ABDD96454C57419BA4 53174F09C4EDB68ED7D9028B86154B9C7F321A30 FCD81737FF261A84B9899CB713933AA795279364 ---- === Prikormka *DOWNLOADER* modules ---- D12CD6C4CA3388B68FCF3E46E206064CAA75F893 C2EA09D162BDAD2541C97D30A4E171F267305671 C10D6E4ADB3B29C968D7F3086C8E7005DD1E36F4 CE4605994E514086ADA5A767296DB66D7EA84175 148218ECDDE9ECC19B1343080884EB819783D9B2 5B256971F332498ACC833B36CBE9AD0CEC71384C 4A8452575FF69BDD0806AA8915E459E8ADC66DF1 04DFC621649511E1AB6CB800124DD5E2874A1629 D51863CBC1AC4BFC2B87F247DC75975E2A9CD992 C8AF6A8270CBD030F09C24888480AEF093ACCF48 EF127184967BE14A3719978E0236FFF5C0AF811B 2FF9E3AB4912A4AEA3C511D9355B8EDD13888E2A 40B163E8E74397E69F18805BD7DAB67F06D3D9E2 A8DFCD6CDB0755966F3D6766B94989CDAA0C35F9 6D4A80FE57D57B43DAF85401DFDD2CDA48D1F023 7844678942383F8116BAC656BC56D4B230FF62E8 8B9460431296DAF13BBE8D0F81EBFC19A84BB741 995EE9772DDDF2D6B4A55ACF26FA41F40786532D ED7B147766C1370367D277F7BA7E354DBDDE5E09 37316B972F5C22D069764800475EED7CD3279802 1DF0B7239E48CF8E7391085BE5B835C892A5B3E8 0323D1C5D565627C32FF08780A59EB45D6C0C7C3 4673475BD3307FE8869ACA0402B861DDE5EC43AC F38CFC487481D2B0167E5B76F06500BC312081B6 35159C96F695B96773C5C1DCF8206DBE75A83D86 ---- === Prikormka *CORE* modules ---- 2A64606DB1DB872E7176F0C6C3FF932E2146BFC9 328DE44A4B6140EF49CE1465482EFE0E4C195399 520AA689066D0C69F6FD9C623E263211022CCF21 790367A2032951488FC6F56DCF12062AE56CAA61 551CD9D950A9C610E12451550BD6A3FBF5B00B77 EF3244AB1DF7D74F1FC1D8C3AF26A3D3EA4364A5 1636112D8441A6616B68CBE9DC32DDB5D836BBA1 8A57E5EED18A6DB6F221B1B9E8831FE4A9CAD08C DCB813E5D2A1C63027AADC7197FD91505FD13380 A360EAC305946FF468E1A33E84ED38176D95CAC9 8F67C4BD2EE7C68249DCD49AD7A3924D3EC6810C C020EFFD3C7AD06907ECFEA424BE1DCB60C7447D D2A98115DF0C17648CCB653AF649D24B528B471D D7EEB8DB22AAD913B38E695A470E8B2F1440D4D3 154AA820D552ABD65C028DED7E970C8DEFA8C237 83B492A2905CE6ACFADE43AB52BF52E6F02FDCD5 4F945A3B3EB058668C3DFC0A8469B42E16C277A7 963963004E4CA0D966D84324EC8ED3694F6A7F5B 9DE8860AD499E64F8BDCFC800DDAFF49D4F948E5 C9C2510654081D621A5B1768520D7D7C04219FCB 9D025A015FDB720C0FDEBCFE54661F3ACED94E3E D09B6194453BFC59EB438E455D14621B280DF4A6 1A865E934EFF339A826979C70A2FC055E3C9D12F 4C5F412C915FB3F178A81BC4FBDA336F69A22086 7372639A9E5C274DFFAA35ABF4C8E7A0BEBD4305 311672ECB756E52AD396227DD884D1C47234961A 7A22E549BE02F7F4753BB9CBA34079CEB15CA381 6AB00FCABC6BC06586F749F54C4955592285608C 66248AE0A3D6B5091C629343CC535F98E08A2947 0DD8E1922CEB96061C9F6678728DD45CBDC6F675 A093993B9488A9427300B2AC41460BE8164A0F9A 6D861826206D834A224583898BE6AF1A3D46E7CF 64679BDB8A65D278CDA0975F279D8881E1ABD40A 92476C6AE5F976C58D11BDD956878451F361776D 202637EF3C9B236D62BE627C6E1A8C779EB2976B C41BB97C203D6221FB494D732CB905FF37376622 986E739948E3B5C303F7766F9F9AF3D2E1A5BCA7 3AB61FEC417686AFC1AC430AAF5A17254D05A14A 0D7785E53AB1A7F43902AFF50E7A722C0E0B428F B5EEAE045F1082438E4C7B7F12F7F4630043A48E 57E345893F508F390F2947E83092A47D845EA445 C9756E95679EAD052D53ADCFA39BB4B1402C9126 D864067BFA52383BC012BA1AAF8FFB893D419C07 CDD58347F873EB7E0BC602DA9930A519683C67C7 DFABE31E58334C873AEDD361D69D5C80016F9F42 625D822EE0D95C6E581B929C6C4E4B44D749D2BB A224A76DABE62BD7CA055CA1119108AD5812AF06 E4C56D11E84497EEC3E275043E36845EB2F3F57E B43713CBD307BC12AD7BA61C87975F74221A3439 AED9C3BCA2B42889A9110B92D3D31B5FD3324BDF 6AE2C768D932EDA538983DD7A50CF7DE14BF54D2 BE73A2C17AAE689BC1A20761850374636B67BF0F 80FFA899CB3A6595FAFA66421BCCD6E5AAAD8552 7C5F7296DDDA9B188B572DF348843F822BD6ED21 F9EB705D8A1EDC7FF9B93D9CF9211840C4482865 7979BEC789770860A6F12B7A7D41470DE4AFC873 6DF75137E8966537BB921EAB30DF4F7BC2C6FEB4 2115C50CAF8D1B365D78818DF84A8CE29F7FD9E8 AFDAD724A2C351C750DB43688D107B1300B1D1D4 64002D2C4C6678776C64BB018736C9B0745F47F4 7843CB7DE03C8B564FD72D923B4BD6D28A466A3C EB4647CA60FEA9049A34EC59D9658946A2C26D9D ED3D4EEF28174F60F1653F35000B871F6E023D21 860D0CDFC065E91083979DD50A72251C26A638A4 FC2C689C507FED54432AD1726E524B38F52B187A D219640BA205A7013A23BA19CD6C2B32439F105E DE60C2A81AE2F3E5DBD2B2D0DBEBDB56FED62F7C D38FDAE48EABF2642F3327FAC865B079233CC7C6 B23995462751EDFAD19B72BEA4A047CC89533A59 88ED6686CF59F12AA984216EC60097C4BD319007 DEF9B207BFD7C6D4B216DF2B37C33CD851DC7FE1 8D49305FD140B179D2293FBAFF6E7CE46A03AF16 F35B1D2165EC00A56EE6DE89D09963DD3FD02744 B42234F5A5EFB6423E9D4904BA282127F1282C8E 326ADEA3AC1F8FAC3B522E6B47941263DA110A42 3E023A83EAA85A77B935B2D3A00AEB5B1ADCD9CC 129B852E62CB7BF487D5F37E17F6E3CC9A838DB8 F030559F81B8DC3CC0DED6C46C6D1BBB67A2CA65 3C904AFB938EFCF210F388E5AA46379AEADBCD50 D8921385ADAFF131C9D452A4D9BBA2C7D755880E 915F7F5471A94A6E095EE8D90FCFE84E7A5FE1D5 0DB71AA8B51FAACEA7D4C5819EC6AF9C342D02FD A4847B06E603E90640051FCDD5D1515F007F7BD5 7C9E4CC3F5B260439D69E93376AA668BF32123D0 3246B5F43756DC8DC4438933005DF66A3C8CE25F E97B383E3CF55D0792F22D57273C18848B849C6E 7C6FA82657B291FAFE423B7B45D0ED732F4D5352 4595EAB593594860985F5FB501B85386F1F1A5B8 45F1F06C3A27CE8329E2BDCDEEA3C530711B5B72 476DCA86DE7AF1F15327084021A3BB7F42818248 70A362985D5237ACD6282E16A238B0FDB1002A1F 73596D1587549DC234588FCB5666BEEFD7C90D81 97958B3124EC5DCAB64DD88A1E97E6B585B04628 B47640C4952ACC2705F7EAD9E8EAA163059FD659 596F945AB52AE0E780905E150ACD2017AB2ECDFC 5CEFFF9C7D016364D40F841CB74D65BB478BA0C6 424DD485FA8572DB84CF6845C27C1F8679A61AEC 099C5611F3BDBB8D453DFBF7967F30891906FF2C 7C2587B85178AD89389D957F11AF1065C46F66DB 840AFB728FDA57195E53F225CB3F6E788B96A579 12ACC64605D4FE2F3CEEEFBD0A7C4FD655E6AEAA ---- === Prikormka *DOCS_STEALER* modules ---- BA434FB6169E8A1785E353EEBF9B907505759A07 A34BD2A059F57FB1FE281A2BD7247A9A72A467B8 04DEB60B6A1D53448EFFB34EA7C55E6916FE32B1 C75D8850273431A41F0EFCF8F74E86BCFE1DFA5A 7C9CB1619FFCF36B32273E1A78A58D817D2B7C8C A580856FA6AC3159F0A7E91D5992810B953A36A1 5C82CA8B2E8320E6B6C071CCB0D4EF9B03001CAA 7275A6ED8EE314600A9B93038876F853B957B316 9286B96452C519D5E1E74D1CDDBDD76B51F4FBAA FAB3B3371AA5878B6508DA487735E3A674A9F61B 0D4839F99C30AD76E082851A214A32116CE932A7 652B012E0ACACB78221CAA7A3C3EE461F07264EA ---- === Prikormka *KEYLOGGER* modules ---- BFDCD0A3F7495C43D8D42B4272BDC90695DC44D7 CC42C6BEEB70D3A9BC7E1159C644E54DE2BE5CBC 6A4F24665569DD61FD29AF8FDCB3E2C90961DFF0 D1DA3076830813EC6FFF0B0DE3462BB5B713A090 E6D92C025CF726B08288B6798AEEFCF550D51C31 0B81BA761C6BA88C0AFC682693D99355E55F5A76 0CDC66ACBB5B7D6FAA85F7DF8D747A96CED7A9BD 194316ADC74AEDED98EE2696B4AB54900A6EDF15 45959818DBA4924E129E22CF1B0BDF02C2DD7B49 820EAC424FC27296FE725E1C5DAA8F6C53E104A7 25D6F1EFD758AACE399C6D62A89BE039281CFF69 722E1CDA3C516D43F17A6D4F5F1390D16113BC30 DE966273DD5AD4DAA01562109932EBD39A13A5A2 ---- === Prikormka *SCREENSHOTS* modules ---- 645DFA35E41F6442793CF7647A75956E05563DE8 AD74ABEA34A20D0196A152E6668E3C29135B22D4 ---- === Prikormka *MICROPHONE* modules ---- FCE83DF7018A49072F9A28A8E135EB00C011D9EB 2C76974722287C7CDB0FCA2BC6CCEDEE62E77D24 ---- === Prikormka *SKYPE* modules ---- C3AA3DBD33751F85002F2F65562098F516737435 2A0EA9E0F3F8E6507D212640594ACF52910275E9 1BB3BBCA79BA45E4215DFC2A6960E03BA60A2B71 0CB528C69706A6513A0E70D3A07A75822F79E6EC 423BCEFC82A14258BDC2CD9740454D28F894DC06 FEAB6E92B905114980B5633F8742E4A7DCD0B4FA BB6CE0957F7E8430007FA4DE1E47C190E1C97AC5 658DF9B4BB13459A9507466BB7D22B723C85D1C5 6C24E244A0DDA2CADED4D1B5CC8B820A46DC19F4 ---- === Prikormka *LOGS_ENCRYPTER* modules ---- D5C2C7C3D670D63AD6998848747A0418665EA2CB 352C36ED1BF7EB74C9649615F9A40C13D80EE55D 6740A385AB33B9CC3EC22FB7971F93538BE44997 22F10F17AB9F18D9BF1FE9EEEA413A9787B29D4C E95458CA9663E4FAB94DD232121D5E994A76015D 2BD3FE012486BD89C87858CC4C3DC9D86742738C ---- === Prikormka *GEOLOCATION* modules ---- 50CCCD576A815AC8EFFB160A628646C876DF8CB0 ---- === Prikormka *OS_INFO* modules ---- 4B8EE967F44ECA2EEB3B8420A858CECFE0231208 72C17994336FE4E1B3CF0D7A6CBC45AA43A8DDF0 824F0E198A8A6E08FB95920AEF06870A6305FE3F 6C902496AC1FEF60D343B03822F49DB5F66BE038 ---- === Prikormka *PASSWORDS* modules ---- B986114C5173052FCB9583A55D5099D99B709352 17F5E1FC52D6C617CD81B0983B70FAC7A60F528C ---- === Prikormka *FILE_TREE* modules ---- 3EDD14E6FA0297ED3162D7F119D8D126662ED28B 2A5AF8E43887051C1F1B488756AAC204B95561CE 4E40286676FCBAC48070BA86B72761A21AC2466C 3E4BE58421DBAEA7651DA13B16CB900DB82A7DEF D1396938E981DD807103B7B9F9442B99952C21AA 74CDA4D4C776CA2A661AC49B6D0E0F0560380A04 8EFDC716FDFD704EC0296860E61AFF9C952946D4 93E196B59771647828BBC3C3B61831150FE1FE02 8384ED4EA9E299306F15A1082231C427A8742271 6E70BE32954E41FAFFC496EAF890B279832B4530 8EA98A8D3D8F62C4543B3DD36E6D6F79F1ACB9E7 ---- ",12478,True,4437.825150898154,median "// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2018 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