-
Notifications
You must be signed in to change notification settings - Fork 921
Refactor makeAndroidAppAvailable to use staggered job queuing #47880
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
ksykulev
wants to merge
3
commits into
main
Choose a base branch
from
47543-android-job-refactor
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+270
−174
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| - Refactored `makeAndroidAppAvailable` to use staggered job queuing instead of sleeping between batches inside a single worker job. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -36,6 +36,7 @@ func (v *SoftwareWorker) Name() string { | |
| const ( | ||
| makeAndroidAppsAvailableForHostTask SoftwareWorkerTask = "make_android_apps_available_for_host" // deprecated | ||
| makeAndroidAppAvailableTask SoftwareWorkerTask = "make_android_app_available" | ||
| makeAndroidAppAvailableBatchTask SoftwareWorkerTask = "make_android_app_available_batch" | ||
| makeAndroidAppUnavailableTask SoftwareWorkerTask = "make_android_app_unavailable" | ||
| runAndroidSetupExperienceTask SoftwareWorkerTask = "run_android_setup_experience" | ||
| bulkSetAndroidAppsAvailableForHostTask SoftwareWorkerTask = "bulk_set_android_apps_available_for_host" | ||
|
|
@@ -97,6 +98,14 @@ func (v *SoftwareWorker) Run(ctx context.Context, argsJSON json.RawMessage) erro | |
| makeAndroidAppAvailableTask, | ||
| ) | ||
|
|
||
| case makeAndroidAppAvailableBatchTask: | ||
| return ctxerr.Wrapf( | ||
| ctx, | ||
| v.makeAndroidAppAvailableBatch(ctx, args.ApplicationID, args.AppTeamID, args.HostUUIDToPolicyID, args.EnterpriseName, args.AppConfigChanged), | ||
| "running %s task", | ||
| makeAndroidAppAvailableBatchTask, | ||
| ) | ||
|
|
||
| case makeAndroidAppUnavailableTask: | ||
| return ctxerr.Wrapf( | ||
| ctx, | ||
|
|
@@ -144,137 +153,104 @@ func (v *SoftwareWorker) makeAndroidAppAvailable(ctx context.Context, applicatio | |
| if err != nil { | ||
| return ctxerr.Wrap(ctx, err, "add app store app: getting android hosts in scope") | ||
| } | ||
| if len(hosts) == 0 { | ||
| return nil | ||
| } | ||
|
|
||
| // Queue staggered batch jobs. The phase-2 handler handles per-host | ||
| // variable substitution within each batch, so we always chunk the same way. | ||
| batchSize := v.AndroidBatchSize | ||
| if batchSize <= 0 { | ||
| batchSize = defaultAndroidBatchSize | ||
| } | ||
| batches := splitHostMap(hosts, batchSize) | ||
| for i, batch := range batches { | ||
| delay := time.Duration(i) * androidSoftwareInstallStaggerInterval | ||
| if err := queueMakeAndroidAppAvailableBatch(ctx, v.Datastore, applicationID, appTeamID, batch, enterpriseName, appConfigChanged, delay); err != nil { | ||
| return ctxerr.Wrap(ctx, err, "queue batch for make android app available") | ||
| } | ||
| } | ||
|
|
||
| return nil | ||
| } | ||
|
|
||
| func (v *SoftwareWorker) makeAndroidAppAvailableBatch(ctx context.Context, applicationID string, appTeamID uint, hostUUIDToPolicyID map[string]string, enterpriseName string, appConfigChanged bool) error { | ||
| config, err := v.Datastore.GetAndroidAppConfigurationByAppTeamID(ctx, appTeamID) | ||
| if err != nil && !fleet.IsNotFound(err) { | ||
| return ctxerr.Wrap(ctx, err, "get android app configuration") | ||
| } | ||
| var configByAppID map[string][]byte | ||
| if config != nil { | ||
| configByAppID = map[string][]byte{ | ||
| applicationID: config, | ||
| } | ||
| configByAppID = map[string][]byte{applicationID: config} | ||
| } | ||
|
|
||
| needsPerHostSubstitution := config != nil && variables.ContainsBytes(config) | ||
|
|
||
| if needsPerHostSubstitution { | ||
| return v.makeAndroidAppAvailablePerHost(ctx, applicationID, configByAppID, hosts, enterpriseName, appConfigChanged) | ||
| } | ||
|
|
||
| appPolicies, err := buildApplicationPolicyWithConfig(ctx, []string{applicationID}, configByAppID, "AVAILABLE") | ||
| if err != nil { | ||
| return ctxerr.Wrap(ctx, err, "building application policies with config") | ||
| } | ||
|
|
||
| // Process hosts in batches to avoid overwhelming the AMAPI. ~10K hosts max | ||
| batches := splitHostMap(hosts, v.AndroidBatchSize) | ||
| for i, batch := range batches { | ||
| if i > 0 { | ||
| timer := time.NewTimer(androidSoftwareInstallStaggerInterval) | ||
| select { | ||
| case <-ctx.Done(): | ||
| timer.Stop() | ||
| return ctxerr.Wrap(ctx, ctx.Err(), "context done between batches") | ||
| case <-timer.C: | ||
| } | ||
| hostUUIDs := make([]string, 0, len(hostUUIDToPolicyID)) | ||
| for uuid := range hostUUIDToPolicyID { | ||
| hostUUIDs = append(hostUUIDs, uuid) | ||
| } | ||
|
|
||
| policyRequestsByHost, err := v.AndroidModule.AddAppsToAndroidPolicy(ctx, enterpriseName, appPolicies, batch) | ||
| filter := fleet.TeamFilter{User: &fleet.User{GlobalRole: new("admin")}} | ||
|
ksykulev marked this conversation as resolved.
|
||
| hostDetails, err := v.Datastore.ListHostsLiteByUUIDs(ctx, filter, hostUUIDs) | ||
| if err != nil { | ||
| return ctxerr.Wrap(ctx, err, "add app store app: add app to android policy") | ||
| return ctxerr.Wrap(ctx, err, "batch fetch host details for variable substitution") | ||
| } | ||
|
|
||
| // if this is called from an UPDATE (config changed), mark existing installs | ||
| // as "pending" (unless already "failed") and with the correct policy version to verify | ||
| if appConfigChanged { | ||
| for hostUUID, policyRequest := range policyRequestsByHost { | ||
| err := v.Datastore.SetAndroidAppInstallPendingApplyConfig(ctx, hostUUID, applicationID, policyRequest.PolicyVersion.V) | ||
| if err != nil { | ||
| return ctxerr.Wrapf(ctx, err, "set android app install pending apply config for host %s and app %s", hostUUID, applicationID) | ||
| } | ||
| } | ||
| hostByUUID := make(map[string]*fleet.Host, len(hostDetails)) | ||
| for _, h := range hostDetails { | ||
| hostByUUID[h.UUID] = h | ||
| } | ||
| } | ||
|
|
||
| return nil | ||
| } | ||
| for hostUUID := range hostUUIDToPolicyID { | ||
| h, ok := hostByUUID[hostUUID] | ||
| if !ok { | ||
| continue // host deleted since the job was queued | ||
| } | ||
|
|
||
| // makeAndroidAppAvailablePerHost handles the case where the app config | ||
| // contains $FLEET_VAR_HOST_* tokens that must be substituted per-host. | ||
| func (v *SoftwareWorker) makeAndroidAppAvailablePerHost( | ||
| ctx context.Context, | ||
| applicationID string, | ||
| configByAppID map[string][]byte, | ||
| hosts map[string]string, | ||
| enterpriseName string, | ||
| appConfigChanged bool, | ||
| ) error { | ||
| // Batch-fetch host details for substitution. | ||
| hostUUIDs := make([]string, 0, len(hosts)) | ||
| for uuid := range hosts { | ||
| hostUUIDs = append(hostUUIDs, uuid) | ||
| } | ||
| filter := fleet.TeamFilter{User: &fleet.User{GlobalRole: new("admin")}} | ||
| hostDetails, err := v.Datastore.ListHostsLiteByUUIDs(ctx, filter, hostUUIDs) | ||
| if err != nil { | ||
| return ctxerr.Wrap(ctx, err, "list hosts lite by uuids for fleet var substitution") | ||
| } | ||
| hostByUUID := make(map[string]*fleet.Host, len(hostDetails)) | ||
| for _, h := range hostDetails { | ||
| hostByUUID[h.UUID] = h | ||
| } | ||
| subHost := profiles.AndroidAppConfigSubstitutionHost{ | ||
| UUID: h.UUID, | ||
| HardwareSerial: h.HardwareSerial, | ||
| Platform: h.Platform, | ||
| } | ||
| substituted, err := v.substituteFleetVarsInConfigs(ctx, configByAppID, subHost) | ||
| if err != nil { | ||
| return ctxerr.Wrapf(ctx, err, "substitute fleet vars for host %s", hostUUID) | ||
| } | ||
|
|
||
| // TODO(#47543): refactor to use staggered job queuing instead of in-job sleep. | ||
| batchSize := v.AndroidBatchSize | ||
| if batchSize <= 0 { | ||
| batchSize = len(hostByUUID) | ||
| } | ||
| hostCount := 0 | ||
| for hostUUID := range hosts { | ||
| h, ok := hostByUUID[hostUUID] | ||
| if !ok { | ||
| continue // host may have been deleted since the job was queued | ||
| } | ||
|
|
||
| if hostCount > 0 && hostCount%batchSize == 0 { | ||
| timer := time.NewTimer(androidSoftwareInstallStaggerInterval) | ||
| select { | ||
| case <-ctx.Done(): | ||
| timer.Stop() | ||
| return ctxerr.Wrap(ctx, ctx.Err(), "context done between batches") | ||
| case <-timer.C: | ||
| appPolicies, err := buildApplicationPolicyWithConfig(ctx, []string{applicationID}, substituted, "AVAILABLE") | ||
| if err != nil { | ||
| return ctxerr.Wrapf(ctx, err, "building application policies with config for host %s", hostUUID) | ||
| } | ||
| } | ||
| hostCount++ | ||
|
|
||
| subHost := profiles.AndroidAppConfigSubstitutionHost{ | ||
| UUID: h.UUID, | ||
| HardwareSerial: h.HardwareSerial, | ||
| Platform: h.Platform, | ||
| } | ||
| singleHost := map[string]string{hostUUID: hostUUIDToPolicyID[hostUUID]} | ||
| policyRequestsByHost, err := v.AndroidModule.AddAppsToAndroidPolicy(ctx, enterpriseName, appPolicies, singleHost) | ||
| if err != nil { | ||
| return ctxerr.Wrapf(ctx, err, "add app to android policy for host %s", hostUUID) | ||
| } | ||
|
|
||
| substituted, err := v.substituteFleetVarsInConfigs(ctx, configByAppID, subHost) | ||
| if err != nil { | ||
| return ctxerr.Wrapf(ctx, err, "substitute fleet vars for host %s", hostUUID) | ||
| if appConfigChanged { | ||
| for uuid, policyRequest := range policyRequestsByHost { | ||
| if err := v.Datastore.SetAndroidAppInstallPendingApplyConfig(ctx, uuid, applicationID, policyRequest.PolicyVersion.V); err != nil { | ||
| return ctxerr.Wrapf(ctx, err, "set android app install pending apply config for host %s and app %s", uuid, applicationID) | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| appPolicies, err := buildApplicationPolicyWithConfig(ctx, []string{applicationID}, substituted, "AVAILABLE") | ||
| } else { | ||
| appPolicies, err := buildApplicationPolicyWithConfig(ctx, []string{applicationID}, configByAppID, "AVAILABLE") | ||
| if err != nil { | ||
| return ctxerr.Wrapf(ctx, err, "building application policies with config for host %s", hostUUID) | ||
| return ctxerr.Wrap(ctx, err, "building application policies with config") | ||
| } | ||
|
|
||
| singleHost := map[string]string{hostUUID: hosts[hostUUID]} | ||
| policyRequestsByHost, err := v.AndroidModule.AddAppsToAndroidPolicy(ctx, enterpriseName, appPolicies, singleHost) | ||
| policyRequestsByHost, err := v.AndroidModule.AddAppsToAndroidPolicy(ctx, enterpriseName, appPolicies, hostUUIDToPolicyID) | ||
| if err != nil { | ||
| return ctxerr.Wrapf(ctx, err, "add app to android policy for host %s", hostUUID) | ||
| return ctxerr.Wrap(ctx, err, "add app store app: add app to android policy") | ||
| } | ||
|
|
||
| if appConfigChanged { | ||
| for uuid, policyRequest := range policyRequestsByHost { | ||
| err := v.Datastore.SetAndroidAppInstallPendingApplyConfig(ctx, uuid, applicationID, policyRequest.PolicyVersion.V) | ||
| if err != nil { | ||
| return ctxerr.Wrapf(ctx, err, "set android app install pending apply config for host %s and app %s", uuid, applicationID) | ||
| for hostUUID, policyRequest := range policyRequestsByHost { | ||
| if err := v.Datastore.SetAndroidAppInstallPendingApplyConfig(ctx, hostUUID, applicationID, policyRequest.PolicyVersion.V); err != nil { | ||
| return ctxerr.Wrapf(ctx, err, "set android app install pending apply config for host %s and app %s", hostUUID, applicationID) | ||
| } | ||
| } | ||
| } | ||
|
|
@@ -283,6 +259,19 @@ func (v *SoftwareWorker) makeAndroidAppAvailablePerHost( | |
| return nil | ||
| } | ||
|
|
||
| func queueMakeAndroidAppAvailableBatch(ctx context.Context, ds fleet.Datastore, applicationID string, appTeamID uint, hostUUIDToPolicyID map[string]string, enterpriseName string, appConfigChanged bool, delay time.Duration) error { | ||
| args := &softwareWorkerArgs{ | ||
| Task: makeAndroidAppAvailableBatchTask, | ||
| ApplicationID: applicationID, | ||
| AppTeamID: appTeamID, | ||
| HostUUIDToPolicyID: hostUUIDToPolicyID, | ||
| EnterpriseName: enterpriseName, | ||
| AppConfigChanged: appConfigChanged, | ||
| } | ||
| _, err := QueueJobWithDelay(ctx, ds, softwareWorkerJobName, args, delay) | ||
| return err | ||
| } | ||
|
|
||
| // this is called when an app is removed from Fleet. | ||
| func (v *SoftwareWorker) makeAndroidAppUnavailable(ctx context.Context, applicationID string, hostUUIDToPolicyID map[string]string, enterpriseName string) error { | ||
| // Update Android MDM policy to remove the app from the hosts | ||
|
|
@@ -759,7 +748,10 @@ func (v *SoftwareWorker) bulkSetAndroidAppsAvailableForHosts(ctx context.Context | |
| return nil | ||
| } | ||
|
|
||
| const androidSoftwareInstallStaggerInterval = 60 * time.Second | ||
| const ( | ||
| androidSoftwareInstallStaggerInterval = 60 * time.Second | ||
| defaultAndroidBatchSize = 1000 | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Given current rate limits should this batch size perhaps be smaller? Feels like this leaves little overhead |
||
| ) | ||
|
|
||
| func QueueBulkSetAndroidAppsAvailableForHosts( | ||
| ctx context.Context, | ||
|
|
||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.