|
| 1 | +import { permissions, sbvrUtils, tasks } from '@balena/pinejs'; |
| 2 | +import _ from 'lodash'; |
| 3 | +import { generateToken } from '../../registry/registry.js'; |
| 4 | +import { |
| 5 | + ASYNC_TASK_DELETE_REGISTRY_IMAGES_BATCH_SIZE, |
| 6 | + REGISTRY2_HOST, |
| 7 | +} from '../../../lib/config.js'; |
| 8 | +import { requestAsync } from '../../../infra/request-promise/index.js'; |
| 9 | +import { setTimeout } from 'node:timers/promises'; |
| 10 | + |
| 11 | +const { api } = sbvrUtils; |
| 12 | + |
| 13 | +// For registry API requests |
| 14 | +const DELAY = 200; |
| 15 | +const RATE_LIMIT_DELAY_BASE = 1000; |
| 16 | +const RATE_LIMIT_RETRIES = 5; |
| 17 | + |
| 18 | +const schema = { |
| 19 | + type: 'object', |
| 20 | + properties: { |
| 21 | + images: { |
| 22 | + type: 'array', |
| 23 | + items: { |
| 24 | + type: 'array', |
| 25 | + items: { |
| 26 | + type: 'string', |
| 27 | + }, |
| 28 | + maxItems: 2, |
| 29 | + minItems: 2, |
| 30 | + }, |
| 31 | + }, |
| 32 | + }, |
| 33 | + required: ['images'], |
| 34 | +}; |
| 35 | + |
| 36 | +export type DeleteRegistryImagesTaskParams = { |
| 37 | + images: Array<[repo: string, hash: string]>; |
| 38 | +}; |
| 39 | + |
| 40 | +const handlerName = 'delete_registry_images'; |
| 41 | +const logHeader = handlerName.replace(/_/g, '-'); |
| 42 | +tasks.addTaskHandler( |
| 43 | + handlerName, |
| 44 | + async (options) => { |
| 45 | + try { |
| 46 | + const images = |
| 47 | + (options.params as DeleteRegistryImagesTaskParams).images ?? []; |
| 48 | + if (images.length === 0) { |
| 49 | + return { |
| 50 | + status: 'succeeded', |
| 51 | + }; |
| 52 | + } |
| 53 | + |
| 54 | + // Chunk by batch size in case we need to tune after tasks have been created |
| 55 | + for (const chunk of _.chunk( |
| 56 | + images, |
| 57 | + ASYNC_TASK_DELETE_REGISTRY_IMAGES_BATCH_SIZE, |
| 58 | + )) { |
| 59 | + // Avoid deleting any blobs that are still referenced by other images |
| 60 | + // This shouldn't normally be necessary as is_stored_at__image_location |
| 61 | + // should be enforced as unique at the database level, but just in case |
| 62 | + const stillReferenced = await api.resin.get({ |
| 63 | + resource: 'image', |
| 64 | + passthrough: { req: permissions.rootRead }, |
| 65 | + options: { |
| 66 | + $select: ['id', 'is_stored_at__image_location', 'content_hash'], |
| 67 | + $filter: |
| 68 | + chunk.length === 1 |
| 69 | + ? { |
| 70 | + is_stored_at__image_location: chunk[0][0], |
| 71 | + content_hash: chunk[0][1], |
| 72 | + } |
| 73 | + : { |
| 74 | + $or: chunk.map(([repo, hash]) => ({ |
| 75 | + is_stored_at__image_location: repo, |
| 76 | + content_hash: hash, |
| 77 | + })), |
| 78 | + }, |
| 79 | + }, |
| 80 | + }); |
| 81 | + const safeToDelete = chunk.filter( |
| 82 | + ([repo, hash]) => |
| 83 | + !stillReferenced.some( |
| 84 | + (image) => |
| 85 | + image.is_stored_at__image_location === repo && |
| 86 | + image.content_hash === hash, |
| 87 | + ), |
| 88 | + ); |
| 89 | + for (const [repo, hash] of safeToDelete) { |
| 90 | + if (repo === '' || hash === '') { |
| 91 | + console.warn( |
| 92 | + `[${logHeader}] Skipping deletion of image with empty repo or hash: ${repo}/${hash}`, |
| 93 | + ); |
| 94 | + continue; |
| 95 | + } |
| 96 | + await markForDeletion(repo, hash); |
| 97 | + } |
| 98 | + } |
| 99 | + |
| 100 | + return { |
| 101 | + status: 'succeeded', |
| 102 | + }; |
| 103 | + } catch (e) { |
| 104 | + console.error(`[${logHeader}] Error marking images for deletion: ${e}`); |
| 105 | + return { |
| 106 | + error: `${e}`, |
| 107 | + status: 'failed', |
| 108 | + }; |
| 109 | + } |
| 110 | + }, |
| 111 | + schema, |
| 112 | +); |
| 113 | + |
| 114 | +// Make an API call to the registry service to mark images for deletion on next garbage collection |
| 115 | +async function markForDeletion(repo: string, hash: string) { |
| 116 | + // Generate an admin-level token with delete permission |
| 117 | + const token = generateToken('admin', REGISTRY2_HOST, [ |
| 118 | + { |
| 119 | + name: repo, |
| 120 | + type: 'repository', |
| 121 | + actions: ['delete'], |
| 122 | + }, |
| 123 | + ]); |
| 124 | + |
| 125 | + // Need to make requests one image at a time, no batch endpoint available |
| 126 | + for (let retries = 0; retries < RATE_LIMIT_RETRIES; retries++) { |
| 127 | + const [{ statusCode, statusMessage, headers }] = await requestAsync({ |
| 128 | + url: `https://${REGISTRY2_HOST}/v2/${repo}/manifests/${hash}`, |
| 129 | + headers: { Authorization: `Bearer ${token}` }, |
| 130 | + method: 'DELETE', |
| 131 | + }); |
| 132 | + |
| 133 | + // Return on success or not found |
| 134 | + if (statusCode === 202 || statusCode === 404) { |
| 135 | + await setTimeout(DELAY); |
| 136 | + return; |
| 137 | + } else if (statusCode === 429) { |
| 138 | + // Default delay value to exponential backoff |
| 139 | + let delay = RATE_LIMIT_DELAY_BASE * Math.pow(2, retries); |
| 140 | + |
| 141 | + // Use the retry-after header value if available |
| 142 | + const retryAfterHeader = headers?.['retry-after']; |
| 143 | + if (retryAfterHeader) { |
| 144 | + const headerDelay = parseInt(retryAfterHeader, 10); |
| 145 | + if (!isNaN(headerDelay)) { |
| 146 | + delay = headerDelay * 1000; |
| 147 | + } else { |
| 148 | + const retryDate = Date.parse(retryAfterHeader); |
| 149 | + const waitMillis = retryDate - Date.now(); |
| 150 | + if (waitMillis > 0) { |
| 151 | + delay = waitMillis; |
| 152 | + } |
| 153 | + } |
| 154 | + } |
| 155 | + |
| 156 | + // Apply some jitter for good measure |
| 157 | + delay += Math.random() * 1000; |
| 158 | + |
| 159 | + console.warn( |
| 160 | + `[${logHeader}] Received 429 for ${repo}/${hash}. Retrying in ${delay}ms...`, |
| 161 | + ); |
| 162 | + await setTimeout(delay); |
| 163 | + } else { |
| 164 | + throw new Error( |
| 165 | + `Failed to mark ${repo}/${hash} for deletion: [${statusCode}] ${statusMessage}`, |
| 166 | + ); |
| 167 | + } |
| 168 | + |
| 169 | + // If we get here, it means we ran out of retries due to rate limiting |
| 170 | + throw new Error( |
| 171 | + `Failed to mark ${repo}/${hash} for deletion: exceeded retry limit due to rate limiting`, |
| 172 | + ); |
| 173 | + } |
| 174 | +} |
0 commit comments