rccontroller.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. /*
  2. * Copyright (c) Contributors to the Open 3D Engine Project.
  3. * For complete copyright and license terms please see the LICENSE at the root of this distribution.
  4. *
  5. * SPDX-License-Identifier: Apache-2.0 OR MIT
  6. *
  7. */
  8. #include "rccontroller.h"
  9. #include <native/resourcecompiler/RCCommon.h>
  10. #include <QTimer>
  11. #include <QThreadPool>
  12. namespace AssetProcessor
  13. {
  14. RCController::RCController(int cfg_minJobs, int cfg_maxJobs, QObject* parent)
  15. : QObject(parent)
  16. , m_dispatchingJobs(false)
  17. , m_shuttingDown(false)
  18. {
  19. AssetProcessorPlatformBus::Handler::BusConnect();
  20. // Determine a good starting value for max jobs
  21. int maxJobs = QThread::idealThreadCount();
  22. if (maxJobs == -1)
  23. {
  24. maxJobs = 3;
  25. }
  26. maxJobs = qMax<int>(maxJobs - 1, 1);
  27. // if the user has specified max jobs in the cfg file, then we obey their request
  28. // regardless of whether they have chosen something bad or not - they would have had to explicitly
  29. // pick this value (we ship with default 0 meaning auto), so if they've changed it, they intend it that way
  30. m_maxJobs = cfg_maxJobs ? qMax(cfg_minJobs, cfg_maxJobs) : maxJobs;
  31. m_RCQueueSortModel.AttachToModel(&m_RCJobListModel);
  32. // make sure that the global thread pool has enough slots to accomidate your request though, since
  33. // by default, the global thread pool has idealThreadCount() slots only.
  34. // leave an extra slot for non-job work.
  35. int currentMaxThreadCount = QThreadPool::globalInstance()->maxThreadCount();
  36. int newMaxThreadCount = qMax<int>(currentMaxThreadCount, m_maxJobs + 1);
  37. QThreadPool::globalInstance()->setMaxThreadCount(newMaxThreadCount);
  38. QObject::connect(this, &RCController::EscalateJobs, &m_RCQueueSortModel, &AssetProcessor::RCQueueSortModel::OnEscalateJobs);
  39. }
  40. RCController::~RCController()
  41. {
  42. AssetProcessorPlatformBus::Handler::BusDisconnect();
  43. m_RCQueueSortModel.AttachToModel(nullptr);
  44. }
  45. RCJobListModel* RCController::GetQueueModel()
  46. {
  47. return &m_RCJobListModel;
  48. }
  49. void RCController::StartJob(RCJob* rcJob)
  50. {
  51. Q_ASSERT(rcJob);
  52. // request to be notified when job is done
  53. QObject::connect(rcJob, &RCJob::Finished, this, [this, rcJob]()
  54. {
  55. FinishJob(rcJob);
  56. }, Qt::QueuedConnection);
  57. // Mark as "being processed" by moving to Processing list
  58. m_RCJobListModel.markAsProcessing(rcJob);
  59. m_RCJobListModel.markAsStarted(rcJob);
  60. Q_EMIT JobStatusChanged(rcJob->GetJobEntry(), AzToolsFramework::AssetSystem::JobStatus::InProgress);
  61. rcJob->Start();
  62. Q_EMIT JobStarted(rcJob->GetJobEntry().m_sourceAssetReference.RelativePath().c_str(), QString::fromUtf8(rcJob->GetPlatformInfo().m_identifier.c_str()));
  63. }
  64. void RCController::QuitRequested()
  65. {
  66. m_shuttingDown = true;
  67. // cancel all jobs:
  68. AssetBuilderSDK::JobCommandBus::Broadcast(&AssetBuilderSDK::JobCommandBus::Events::Cancel);
  69. if (m_RCJobListModel.jobsInFlight() == 0)
  70. {
  71. Q_EMIT ReadyToQuit(this);
  72. return;
  73. }
  74. QTimer::singleShot(10, this, SLOT(QuitRequested()));
  75. }
  76. int RCController::NumberOfPendingCriticalJobsPerPlatform(QString platform)
  77. {
  78. return m_pendingCriticalJobsPerPlatform[platform.toLower()];
  79. }
  80. int RCController::NumberOfPendingJobsPerPlatform(QString platform)
  81. {
  82. return m_jobsCountPerPlatform[platform.toLower()];
  83. }
  84. void RCController::FinishJob(RCJob* rcJob)
  85. {
  86. m_RCQueueSortModel.RemoveJobIdEntry(rcJob);
  87. QString platform = rcJob->GetPlatformInfo().m_identifier.c_str();
  88. auto found = m_jobsCountPerPlatform.find(platform);
  89. if (found != m_jobsCountPerPlatform.end())
  90. {
  91. int prevCount = found.value();
  92. if (prevCount > 0)
  93. {
  94. int newCount = prevCount - 1;
  95. m_jobsCountPerPlatform[platform] = newCount;
  96. Q_EMIT JobsInQueuePerPlatform(platform, newCount);
  97. }
  98. }
  99. if (rcJob->IsCritical())
  100. {
  101. int criticalJobsCount = m_pendingCriticalJobsPerPlatform[platform.toLower()] - 1;
  102. m_pendingCriticalJobsPerPlatform[platform.toLower()] = criticalJobsCount;
  103. }
  104. if (rcJob->GetState() == RCJob::cancelled)
  105. {
  106. Q_EMIT FileCancelled(rcJob->GetJobEntry());
  107. }
  108. else if (rcJob->GetState() != RCJob::completed)
  109. {
  110. Q_EMIT FileFailed(rcJob->GetJobEntry());
  111. Q_EMIT JobStatusChanged(rcJob->GetJobEntry(), AzToolsFramework::AssetSystem::JobStatus::Failed);
  112. }
  113. else
  114. {
  115. Q_EMIT FileCompiled(rcJob->GetJobEntry(), AZStd::move(rcJob->GetProcessJobResponse()));
  116. Q_EMIT JobStatusChanged(rcJob->GetJobEntry(), AzToolsFramework::AssetSystem::JobStatus::Completed);
  117. }
  118. // Move to Completed list which will mark as "completed"
  119. // unless a different state has been set.
  120. m_RCJobListModel.markAsCompleted(rcJob);
  121. if (!m_dispatchingPaused)
  122. {
  123. Q_EMIT ActiveJobsCountChanged(aznumeric_cast<unsigned int>(m_RCJobListModel.itemCount()));
  124. }
  125. if (!m_shuttingDown)
  126. {
  127. // Start next job only if we are not shutting down
  128. DispatchJobs();
  129. // if there is no next job, and nothing is in flight, we are done.
  130. if (IsIdle())
  131. {
  132. Q_EMIT BecameIdle();
  133. }
  134. }
  135. }
  136. bool RCController::IsIdle()
  137. {
  138. return ((!m_RCQueueSortModel.GetNextPendingJob()) && (m_RCJobListModel.jobsInFlight() == 0));
  139. }
  140. void RCController::JobSubmitted(JobDetails details)
  141. {
  142. AssetProcessor::QueueElementID checkFile(details.m_jobEntry.m_sourceAssetReference,
  143. details.m_jobEntry.m_platformInfo.m_identifier.c_str(),
  144. details.m_jobEntry.m_jobKey);
  145. bool cancelJob = false;
  146. bool markCancelledJobAsFinished = false;
  147. RCJob* existingJob = nullptr;
  148. int existingJobIndex = -1;
  149. if (m_RCJobListModel.isInQueue(checkFile))
  150. {
  151. existingJobIndex = m_RCJobListModel.GetIndexOfJobByState(checkFile, RCJob::pending);
  152. if (existingJobIndex != -1)
  153. {
  154. existingJob = m_RCJobListModel.getItem(existingJobIndex);
  155. // The job status has changed
  156. if (existingJob->HasMissingSourceDependency() != details.m_hasMissingSourceDependency)
  157. {
  158. AZ_TracePrintf(
  159. AssetProcessor::DebugChannel,
  160. "Cancelling Job [%s, %s, %s] missing source dependency status has changed.\n",
  161. checkFile.GetSourceAssetReference().AbsolutePath().c_str(),
  162. checkFile.GetPlatform().toUtf8().data(),
  163. checkFile.GetJobDescriptor().toUtf8().data());
  164. cancelJob = true;
  165. markCancelledJobAsFinished = existingJob->GetState() == RCJob::JobState::pending;
  166. }
  167. }
  168. if (!cancelJob)
  169. {
  170. AZ_TracePrintf(
  171. AssetProcessor::DebugChannel,
  172. "Job is already in queue and has not started yet - ignored [%s, %s, %s]\n",
  173. checkFile.GetSourceAssetReference().AbsolutePath().c_str(),
  174. checkFile.GetPlatform().toUtf8().data(),
  175. checkFile.GetJobDescriptor().toUtf8().data());
  176. // Don't just discard the job, we need to let APM know so it can keep track of the number of jobs that are pending/finished
  177. AssetBuilderSDK::JobCommandBus::Event(details.m_jobEntry.m_jobRunKey, &AssetBuilderSDK::JobCommandBus::Events::Cancel);
  178. Q_EMIT FileCancelled(details.m_jobEntry);
  179. return;
  180. }
  181. }
  182. if (m_RCJobListModel.isInFlight(checkFile))
  183. {
  184. // if the computed fingerprint is the same as the fingerprint of the in-flight job, this is okay.
  185. existingJobIndex = m_RCJobListModel.GetIndexOfJobByState(checkFile, RCJob::processing);
  186. if (existingJobIndex != -1)
  187. {
  188. existingJob = m_RCJobListModel.getItem(existingJobIndex);
  189. // This does not set markCanceledJobAsFinished to true in either case the job is cancelled, because the job will
  190. // have FinishJob called once through the callback in RCController::StartJob. FinishJob should not be called more than once.
  191. if (existingJob->GetJobEntry().m_computedFingerprint != details.m_jobEntry.m_computedFingerprint)
  192. {
  193. AZ_TracePrintf(
  194. AssetProcessor::DebugChannel,
  195. "Cancelling Job [%s, %s, %s] with old FP %u, replacing with new FP %u \n",
  196. checkFile.GetSourceAssetReference().AbsolutePath().c_str(),
  197. checkFile.GetPlatform().toUtf8().data(),
  198. checkFile.GetJobDescriptor().toUtf8().data(),
  199. existingJob->GetJobEntry().m_computedFingerprint,
  200. details.m_jobEntry.m_computedFingerprint);
  201. cancelJob = true;
  202. }
  203. else if (!existingJob->GetJobDependencies().empty())
  204. {
  205. // If a job has dependencies, it's very likely it was re-queued as a result of a dependency being changed
  206. // The in-flight job is probably going to fail at best, or use old data at worst, so cancel the in-flight job
  207. AZ_TracePrintf(AssetProcessor::DebugChannel, "Cancelling Job with dependencies [%s, %s, %s], replacing with re-queued job\n",
  208. checkFile.GetSourceAssetReference().AbsolutePath().c_str(), checkFile.GetPlatform().toUtf8().data(), checkFile.GetJobDescriptor().toUtf8().data());
  209. cancelJob = true;
  210. }
  211. else
  212. {
  213. AZ_TracePrintf(
  214. AssetProcessor::DebugChannel,
  215. "Job is already in progress but has the same computed fingerprint (%u) - ignored [%s, %s, %s]\n",
  216. details.m_jobEntry.m_computedFingerprint,
  217. checkFile.GetSourceAssetReference().AbsolutePath().c_str(),
  218. checkFile.GetPlatform().toUtf8().data(),
  219. checkFile.GetJobDescriptor().toUtf8().data());
  220. // Don't just discard the job, we need to let APM know so it can keep track of the number of jobs that are
  221. // pending/finished
  222. AssetBuilderSDK::JobCommandBus::Event(details.m_jobEntry.m_jobRunKey, &AssetBuilderSDK::JobCommandBus::Events::Cancel);
  223. Q_EMIT FileCancelled(details.m_jobEntry);
  224. return;
  225. }
  226. }
  227. }
  228. if (cancelJob && existingJob && existingJobIndex != -1)
  229. {
  230. existingJob->SetState(RCJob::JobState::cancelled);
  231. // If the job was pending, mark it as finished, so asset processor can clean up the interface for this job and update tracking info.
  232. if (markCancelledJobAsFinished)
  233. {
  234. FinishJob(existingJob);
  235. }
  236. AssetBuilderSDK::JobCommandBus::Event(existingJob->GetJobEntry().m_jobRunKey, &AssetBuilderSDK::JobCommandBus::Events::Cancel);
  237. m_RCJobListModel.UpdateRow(existingJobIndex);
  238. }
  239. RCJob* rcJob = new RCJob(&m_RCJobListModel);
  240. rcJob->Init(details); // note - move operation. From this point on you must use the job details to refer to it.
  241. m_RCQueueSortModel.AddJobIdEntry(rcJob);
  242. m_RCJobListModel.addNewJob(rcJob);
  243. QString platformName = rcJob->GetPlatformInfo().m_identifier.c_str();// we need to get the actual platform from the rcJob
  244. if (rcJob->IsCritical())
  245. {
  246. int criticalJobsCount = m_pendingCriticalJobsPerPlatform[platformName.toLower()] + 1;
  247. m_pendingCriticalJobsPerPlatform[platformName.toLower()] = criticalJobsCount;
  248. }
  249. auto found = m_jobsCountPerPlatform.find(platformName);
  250. if (found != m_jobsCountPerPlatform.end())
  251. {
  252. int newCount = found.value() + 1;
  253. m_jobsCountPerPlatform[platformName] = newCount;
  254. }
  255. else
  256. {
  257. m_jobsCountPerPlatform[platformName] = 1;
  258. }
  259. Q_EMIT JobsInQueuePerPlatform(platformName, m_jobsCountPerPlatform[platformName]);
  260. Q_EMIT JobStatusChanged(rcJob->GetJobEntry(), AzToolsFramework::AssetSystem::JobStatus::Queued);
  261. if (!m_dispatchingPaused)
  262. {
  263. Q_EMIT ActiveJobsCountChanged(aznumeric_cast<unsigned int>(m_RCJobListModel.itemCount()));
  264. }
  265. // Start the job we just received if no job currently running
  266. if ((!m_shuttingDown) && (!m_dispatchingJobs))
  267. {
  268. DispatchJobs();
  269. }
  270. }
  271. void RCController::SetDispatchPaused(bool pause)
  272. {
  273. if (m_dispatchingPaused != pause)
  274. {
  275. m_dispatchingPaused = pause;
  276. if (!pause)
  277. {
  278. if ((!m_shuttingDown) && (!m_dispatchingJobs))
  279. {
  280. DispatchJobs();
  281. Q_EMIT ActiveJobsCountChanged(aznumeric_cast<unsigned int>(m_RCJobListModel.itemCount()));
  282. }
  283. }
  284. }
  285. }
  286. void RCController::DispatchJobsImpl()
  287. {
  288. m_dispatchJobsQueued = false;
  289. if (!m_dispatchingJobs)
  290. {
  291. m_dispatchingJobs = true;
  292. RCJob* rcJob = m_RCQueueSortModel.GetNextPendingJob();
  293. while (m_RCJobListModel.jobsInFlight() < m_maxJobs && rcJob && !m_shuttingDown)
  294. {
  295. if (m_dispatchingPaused)
  296. {
  297. // note, even if dispatching is "paused" we start all "auto fail jobs" so that user gets instant feedback on failure.
  298. if (!rcJob->IsAutoFail())
  299. {
  300. break;
  301. }
  302. }
  303. StartJob(rcJob);
  304. rcJob = m_RCQueueSortModel.GetNextPendingJob();
  305. }
  306. m_dispatchingJobs = false;
  307. }
  308. }
  309. void RCController::DispatchJobs()
  310. {
  311. if (!m_dispatchJobsQueued)
  312. {
  313. m_dispatchJobsQueued = true;
  314. QMetaObject::invokeMethod(this, "DispatchJobsImpl", Qt::QueuedConnection);
  315. }
  316. }
  317. void RCController::OnRequestCompileGroup(AssetProcessor::NetworkRequestID groupID, QString platform, QString searchTerm, AZ::Data::AssetId assetId, bool isStatusRequest, int searchType)
  318. {
  319. // someone has asked for a compile group to be created that conforms to that search term.
  320. // the goal here is to use a heuristic to find any assets that match the search term and place them in a new group
  321. // then respond with the appropriate response.
  322. // lets do some minimal processing on the search term
  323. AssetProcessor::JobIdEscalationList escalationList;
  324. QSet<AssetProcessor::QueueElementID> results;
  325. if (assetId.IsValid())
  326. {
  327. m_RCJobListModel.PerformUUIDSearch(assetId.m_guid, platform, results, escalationList, isStatusRequest);
  328. }
  329. else
  330. {
  331. m_RCJobListModel.PerformHeuristicSearch(AssetUtilities::NormalizeAndRemoveAlias(searchTerm), platform, results, escalationList, isStatusRequest, searchType);
  332. }
  333. if (results.isEmpty())
  334. {
  335. // nothing found
  336. AZ_Info(
  337. AssetProcessor::DebugChannel,
  338. "OnRequestCompileGroup: %s - %s requested, but no matching source assets found.\n",
  339. searchTerm.toUtf8().constData(),
  340. assetId.ToString<AZStd::string>().c_str());
  341. Q_EMIT CompileGroupCreated(groupID, AzFramework::AssetSystem::AssetStatus_Unknown);
  342. }
  343. else
  344. {
  345. AZ_Info(
  346. AssetProcessor::DebugChannel,
  347. "GetAssetStatus: OnRequestCompileGroup: %s - %s requested and queued, found %d results.\n",
  348. searchTerm.toUtf8().constData(),
  349. assetId.ToFixedString().c_str(), results.size());
  350. // it is not necessary to denote the search terms or list of results here because
  351. // PerformHeursticSearch already prints out the results.
  352. m_RCQueueSortModel.OnEscalateJobs(escalationList);
  353. m_activeCompileGroups.push_back(AssetCompileGroup());
  354. m_activeCompileGroups.back().m_groupMembers.swap(results);
  355. m_activeCompileGroups.back().m_requestID = groupID;
  356. Q_EMIT CompileGroupCreated(groupID, AzFramework::AssetSystem::AssetStatus_Queued);
  357. }
  358. }
  359. void RCController::OnEscalateJobsBySearchTerm(QString platform, QString searchTerm)
  360. {
  361. AssetProcessor::JobIdEscalationList escalationList;
  362. QSet<AssetProcessor::QueueElementID> results;
  363. m_RCJobListModel.PerformHeuristicSearch(AssetUtilities::NormalizeAndRemoveAlias(searchTerm), platform, results, escalationList, true);
  364. if (!results.isEmpty())
  365. {
  366. // it is not necessary to denote the search terms or list of results here because
  367. // PerformHeursticSearch already prints out the results.
  368. m_RCQueueSortModel.OnEscalateJobs(escalationList);
  369. }
  370. // do not print a warning out when this fails, its fine for things to escalate jobs as a matter of course just to "make sure" they are escalated
  371. // and its fine if none are in the build queue.
  372. }
  373. void RCController::OnEscalateJobsBySourceUUID(QString platform, AZ::Uuid sourceUuid)
  374. {
  375. AssetProcessor::JobIdEscalationList escalationList;
  376. QSet<AssetProcessor::QueueElementID> results;
  377. m_RCJobListModel.PerformUUIDSearch(sourceUuid, platform, results, escalationList, true);
  378. if (!results.isEmpty())
  379. {
  380. #if defined(AZ_ENABLE_TRACING)
  381. for (const AssetProcessor::QueueElementID& result : results)
  382. {
  383. AZ_TracePrintf(AssetProcessor::DebugChannel, "OnEscalateJobsBySourceUUID: %s --> %s\n", sourceUuid.ToString<AZStd::string>().c_str(), result.GetSourceAssetReference().AbsolutePath().c_str());
  384. }
  385. #endif
  386. m_RCQueueSortModel.OnEscalateJobs(escalationList);
  387. }
  388. // do not print a warning out when this fails, its fine for things to escalate jobs as a matter of course just to "make sure" they are escalated
  389. // and its fine if none are in the build queue.
  390. }
  391. void RCController::OnJobComplete(JobEntry completeEntry, AzToolsFramework::AssetSystem::JobStatus state)
  392. {
  393. if (m_activeCompileGroups.empty())
  394. {
  395. return;
  396. }
  397. QueueElementID jobQueueId(completeEntry.m_sourceAssetReference, completeEntry.m_platformInfo.m_identifier.c_str(), completeEntry.m_jobKey);
  398. // only the 'completed' status means success:
  399. bool statusSucceeded = (state == AzToolsFramework::AssetSystem::JobStatus::Completed);
  400. // start at the end so that we can actually erase the compile groups and not skip any:
  401. for (int groupIdx = m_activeCompileGroups.size() - 1; groupIdx >= 0; --groupIdx)
  402. {
  403. AssetCompileGroup& compileGroup = m_activeCompileGroups[groupIdx];
  404. auto it = compileGroup.m_groupMembers.find(jobQueueId);
  405. if (it != compileGroup.m_groupMembers.end())
  406. {
  407. compileGroup.m_groupMembers.erase(it);
  408. if ((compileGroup.m_groupMembers.isEmpty()) || (!statusSucceeded))
  409. {
  410. // if we get here, we're either empty (and succeeded) or we failed one and have now failed
  411. Q_EMIT CompileGroupFinished(compileGroup.m_requestID, statusSucceeded ? AzFramework::AssetSystem::AssetStatus_Compiled: AzFramework::AssetSystem::AssetStatus_Failed);
  412. m_activeCompileGroups.removeAt(groupIdx);
  413. }
  414. }
  415. }
  416. }
  417. void RCController::RemoveJobsBySource(const SourceAssetReference& sourceAsset)
  418. {
  419. // some jobs may have not been started yet, these need to be removed manually
  420. AZStd::vector<RCJob*> pendingJobs;
  421. m_RCJobListModel.EraseJobs(sourceAsset, pendingJobs);
  422. // force finish all pending jobs
  423. for (auto* rcJob : pendingJobs)
  424. {
  425. FinishJob(rcJob);
  426. }
  427. }
  428. void RCController::OnAddedToCatalog(JobEntry jobEntry)
  429. {
  430. AssetProcessor::QueueElementID checkFile(jobEntry.m_sourceAssetReference, jobEntry.m_platformInfo.m_identifier.c_str(), jobEntry.m_jobKey);
  431. m_RCJobListModel.markAsCataloged(checkFile);
  432. DispatchJobs();
  433. }
  434. } // Namespace AssetProcessor