• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

Commonjava / indy-tracking-service / 44786446415

20 Nov 2026 05:46PM UTC coverage: 37.562% (-29.5%) from 67.036%
44786446415

push

github

rnc
Bump org.commonjava.atlas:atlas-relationships-api from 1.2.2 to 1.2.3

Bumps [org.commonjava.atlas:atlas-relationships-api](https://github.com/Commonjava/atlas) from 1.2.2 to 1.2.3.
- [Release notes](https://github.com/Commonjava/atlas/releases)
- [Commits](https://github.com/Commonjava/atlas/compare/atlas-parent-1.2.2...atlas-parent-1.2.3)

---
updated-dependencies:
- dependency-name: org.commonjava.atlas:atlas-relationships-api
  dependency-version: 1.2.3
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

678 of 1805 relevant lines covered (37.56%)

0.75 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

10.58
/src/main/java/org/commonjava/indy/service/tracking/controller/AdminController.java
1
/**
2
 * Copyright (C) 2022-2023 Red Hat, Inc. (https://github.com/Commonjava/indy-tracking-service)
3
 *
4
 * Licensed under the Apache License, Version 2.0 (the "License");
5
 * you may not use this file except in compliance with the License.
6
 * You may obtain a copy of the License at
7
 *
8
 *         http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 * Unless required by applicable law or agreed to in writing, software
11
 * distributed under the License is distributed on an "AS IS" BASIS,
12
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 * See the License for the specific language governing permissions and
14
 * limitations under the License.
15
 */
16
package org.commonjava.indy.service.tracking.controller;
17

18
import org.commonjava.indy.service.tracking.Constants;
19
import org.commonjava.indy.service.tracking.client.content.BatchDeleteRequest;
20
import org.commonjava.indy.service.tracking.client.content.ContentService;
21
import org.commonjava.indy.service.tracking.client.promote.PathsPromoteTrackingRecords;
22
import org.commonjava.indy.service.tracking.client.promote.PromoteService;
23
import org.commonjava.indy.service.tracking.config.IndyTrackingConfiguration;
24
import org.commonjava.indy.service.tracking.data.cassandra.CassandraTrackingQuery;
25
import org.commonjava.indy.service.tracking.exception.ContentException;
26
import org.commonjava.indy.service.tracking.exception.IndyWorkflowException;
27
import org.commonjava.indy.service.tracking.jaxrs.DTOStreamingOutput;
28
import org.commonjava.indy.service.tracking.model.StoreKey;
29
import org.commonjava.indy.service.tracking.model.TrackedContent;
30
import org.commonjava.indy.service.tracking.model.TrackedContentEntry;
31
import org.commonjava.indy.service.tracking.model.TrackingKey;
32
import org.commonjava.indy.service.tracking.model.dto.ContentDTO;
33
import org.commonjava.indy.service.tracking.model.dto.ContentEntryDTO;
34
import org.commonjava.indy.service.tracking.model.dto.ContentTransferDTO;
35
import org.commonjava.indy.service.tracking.model.dto.TrackedContentDTO;
36
import org.commonjava.indy.service.tracking.model.dto.TrackedContentEntryDTO;
37
import org.commonjava.indy.service.tracking.model.dto.TrackingIdsDTO;
38
import org.commonjava.indy.service.tracking.util.UrlUtils;
39
import org.eclipse.microprofile.rest.client.inject.RestClient;
40
import org.slf4j.Logger;
41
import org.slf4j.LoggerFactory;
42

43
import jakarta.enterprise.context.ApplicationScoped;
44
import jakarta.inject.Inject;
45
import jakarta.ws.rs.core.Response;
46
import java.io.File;
47
import java.io.IOException;
48
import java.io.InputStream;
49
import java.net.MalformedURLException;
50
import java.nio.file.Paths;
51
import java.util.HashSet;
52
import java.util.Map;
53
import java.util.Set;
54
import java.util.TreeSet;
55
import java.util.concurrent.atomic.AtomicBoolean;
56
import java.util.stream.Collectors;
57

58
import static org.commonjava.indy.service.tracking.util.TrackingUtils.readZipInputStreamAnd;
59
import static org.commonjava.indy.service.tracking.util.TrackingUtils.zipTrackedContent;
60
import org.commonjava.indy.service.tracking.client.storage.StorageBatchDeleteRequest;
61
import org.commonjava.indy.service.tracking.client.storage.StorageService;
62

63
@ApplicationScoped
64
public class AdminController
65
{
66
    public static final String FOLO_DIR = "folo";
67

68
    public static final String FOLO_SEALED_ZIP = "folo-sealed.zip";
69

70
    private final Logger logger = LoggerFactory.getLogger( getClass() );
2 ✔
71

72
    @Inject
73
    @RestClient
74
    ContentService contentService;
75

76
    @Inject
77
    @RestClient
78
    PromoteService promoteService;
79

80
    @Inject
81
    @RestClient
82
    StorageService storageService;
83

84
    @Inject
85
    private IndyTrackingConfiguration config;
86

87
    @Inject
88
    private CassandraTrackingQuery recordManager;
89

90
    protected AdminController()
91
    {
2 ✔
92
    }
2 ✔
93

94
    public AdminController( final CassandraTrackingQuery recordManager )
95
    {
2 ✔
96
        this.recordManager = recordManager;
2 ✔
97
    }
2 ✔
98

99
    public TrackedContentDTO seal( final String id, final String baseUrl )
100
    {
101
        TrackingKey tk = new TrackingKey( id );
×
102
        return constructContentDTO( recordManager.seal( tk ), baseUrl );
×
103
    }
104

105
    public void importRecordZip( InputStream stream ) throws IndyWorkflowException
106
    {
107
        try
108
        {
109
            int count = readZipInputStreamAnd( stream, ( record ) -> recordManager.addSealedRecord( record ) );
2 ✔
110
            logger.debug( "Import records done, size: {}", count );
2 ✔
111
        }
112
        catch ( Exception e )
×
113
        {
114
            throw new IndyWorkflowException( "Failed to import zip file", e );
×
115
        }
2 ✔
116
    }
2 ✔
117

118
    public File renderReportZip() throws IndyWorkflowException
119
    {
120
        Set<TrackedContent> sealed = recordManager.getSealed(); // only care about sealed records
×
121
        try
122
        {
123
            File file = Paths.get( config.baseDir().getAbsolutePath(), FOLO_DIR, FOLO_SEALED_ZIP ).toFile();
×
124
            if ( file.exists() )
×
125
            {
126
                file.delete();
×
127
            }
128
            file.getParentFile().mkdirs(); // make dirs if not exist
×
129

130
            zipTrackedContent( file, sealed );
×
131

132
            return file;
×
133
        }
134
        catch ( IOException e )
×
135
        {
136
            throw new IndyWorkflowException( "Failed to create zip file", e );
×
137
        }
138
    }
139

140
    public TrackedContentDTO getRecord( final String id, String baseUrl ) throws IndyWorkflowException
141
    {
142
        final TrackingKey tk = new TrackingKey( id );
2 ✔
143
        return constructContentDTO( recordManager.get( tk ), baseUrl );
×
144
    }
145

146
    public TrackedContentDTO getLegacyRecord( final String id, String baseUrl ) throws IndyWorkflowException
147
    {
148
        final TrackingKey tk = new TrackingKey( id );
×
149
        return constructContentDTO( recordManager.getLegacy( tk ), baseUrl );
×
150
    }
151

152
    public void clearRecord( final String id ) throws ContentException
153
    {
154
        final TrackingKey tk = new TrackingKey( id );
×
155
        recordManager.delete( tk );
×
156
    }
×
157

158
    private TrackedContentDTO constructContentDTO( final TrackedContent content, final String baseUrl )
159
    {
160
        if ( content == null )
×
161
        {
162
            return null;
×
163
        }
164
        final Set<TrackedContentEntryDTO> uploads = new TreeSet<>();
×
165
        for ( TrackedContentEntry entry : content.getUploads() )
×
166
        {
167
            uploads.add( constructContentEntryDTO( entry, baseUrl ) );
×
168
        }
×
169

170
        final Set<TrackedContentEntryDTO> downloads = new TreeSet<>();
×
171
        for ( TrackedContentEntry entry : content.getDownloads() )
×
172
        {
173
            downloads.add( constructContentEntryDTO( entry, baseUrl ) );
×
174
        }
×
175
        return new TrackedContentDTO( content.getKey(), uploads, downloads );
×
176
    }
177

178
    private TrackedContentEntryDTO constructContentEntryDTO( final TrackedContentEntry entry, String apiBaseUrl )
179
    {
180
        if ( entry == null )
×
181
        {
182
            return null;
×
183
        }
184
        TrackedContentEntryDTO entryDTO =
×
185
                        new TrackedContentEntryDTO( entry.getStoreKey(), entry.getAccessChannel(), entry.getPath() );
×
186

187
        try
188
        {
189
            entryDTO.setLocalUrl( UrlUtils.buildUrl( apiBaseUrl, "content", entryDTO.getStoreKey().getPackageType(),
×
190
                                                     entryDTO.getStoreKey().getType().singularEndpointName(),
×
191
                                                     entryDTO.getStoreKey().getName(), entryDTO.getPath() ) );
×
192
        }
193
        catch ( MalformedURLException e )
×
194
        {
195
            logger.warn( String.format( "Cannot formulate local URL!\n  Base URL: %s"
×
196
                                                        + "\n  Store: %s\n  Path: %s\n  Record: %s\n  Reason: %s",
197
                                        apiBaseUrl, entry.getStoreKey(), entry.getPath(), entry.getTrackingKey(),
×
198
                                        e.getMessage() ), e );
×
199
        }
×
200

201
        entryDTO.setOriginUrl( entry.getOriginUrl() );
×
202
        entryDTO.setMd5( entry.getMd5() );
×
203
        entryDTO.setSha1( entry.getSha1() );
×
204
        entryDTO.setSha256( entry.getSha256() );
×
205
        entryDTO.setSize( entry.getSize() );
×
206
        entryDTO.setTimestamps( entry.getTimestamps() );
×
207
        return entryDTO;
×
208
    }
209

210
    private Set<ContentTransferDTO> constructTransferDTOSet( final Set<TrackedContentEntry> entries )
211
    {
212
        if ( entries == null )
×
213
        {
214
            return null;
×
215
        }
216
        Set<ContentTransferDTO> cut_entries = new HashSet<>();
×
217
        for ( TrackedContentEntry entry : entries )
×
218
        {
219
            ContentTransferDTO cut_entry = new ContentTransferDTO( entry.getStoreKey(), entry.getTrackingKey(),
×
220
                                                                   entry.getAccessChannel(), entry.getPath(),
×
221
                                                                   entry.getOriginUrl(), entry.getEffect() );
×
222
            cut_entries.add( cut_entry );
×
223
        }
×
224

225
        return cut_entries;
×
226
    }
227

228
    private ContentDTO convertToContentDTO( final TrackedContent record )
229
    {
230
        ContentDTO dto = new ContentDTO();
×
231
        dto.setKey( record.getKey() );
×
232
        Set<ContentEntryDTO> uploads = new HashSet<>();
×
233
        Set<ContentEntryDTO> downloads = new HashSet<>();
×
234
        for ( TrackedContentEntry entry : record.getUploads() )
×
235
        {
236
            uploads.add( convertToCOntentEntryDTO( entry ) );
×
237
        }
×
238
        for ( TrackedContentEntry entry : record.getDownloads() )
×
239
        {
240
            downloads.add( convertToCOntentEntryDTO( entry ) );
×
241
        }
×
242
        dto.setUploads( uploads );
×
243
        dto.getDownloads( downloads );
×
244
        return dto;
×
245
    }
246

247
    private ContentEntryDTO convertToCOntentEntryDTO( TrackedContentEntry entry )
248
    {
249
        ContentEntryDTO entryDTO = new ContentEntryDTO();
×
250
        entryDTO.setStoreKey( entry.getStoreKey() );
×
251
        entryDTO.setPath( entry.getPath() );
×
252
        return entryDTO;
×
253
    }
254

255
    public TrackingIdsDTO getLegacyTrackingIds()
256
    {
257
        logger.info( "Get legacy folo ids" );
2 ✔
258
        TrackingIdsDTO ret = null;
2 ✔
259
        Set<String> sealed = recordManager.getLegacyTrackingKeys()
×
260
                                          .stream()
×
261
                                          .map( TrackingKey::getId )
×
262
                                          .collect( Collectors.toSet() );
×
263
        if ( sealed != null )
×
264
        {
265
            ret = new TrackingIdsDTO();
×
266
            ret.setSealed( sealed );
×
267
        }
268
        return ret;
×
269
    }
270

271
    public TrackingIdsDTO getTrackingIds( final Set<Constants.TRACKING_TYPE> types )
272
    {
273

274
        Set<String> inProgress = null;
2 ✔
275
        if ( types.contains( Constants.TRACKING_TYPE.IN_PROGRESS ) )
2 ✔
276
        {
277
            inProgress = recordManager.getInProgressTrackingKey()
×
278
                                      .stream()
×
279
                                      .map( TrackingKey::getId )
×
280
                                      .collect( Collectors.toSet() );
×
281
        }
282

283
        Set<String> sealed = null;
2 ✔
284
        if ( types.contains( Constants.TRACKING_TYPE.SEALED ) )
2 ✔
285
        {
286
            sealed = recordManager.getSealedTrackingKey()
×
287
                                  .stream()
×
288
                                  .map( TrackingKey::getId )
×
289
                                  .collect( Collectors.toSet() );
×
290
        }
291

292
        if ( ( inProgress != null && !inProgress.isEmpty() ) || ( sealed != null && !sealed.isEmpty() ) )
×
293
        {
294
            return new TrackingIdsDTO( inProgress, sealed );
×
295
        }
296
        return null;
×
297
    }
298

299
    public TrackedContentDTO recalculateRecord( final String id, final String baseUrl ) throws IndyWorkflowException
300
    {
301
        TrackingKey trackingKey = new TrackingKey( id );
2 ✔
302
        TrackedContent record = recordManager.get( trackingKey );
×
303

304
        if ( record == null )
×
305
        {
306
            return null;
×
307
        }
308

309
        AtomicBoolean failed = new AtomicBoolean( false );
×
310

311
        Set<TrackedContentEntry> recalculatedUploads = recalculateEntrySet( record.getUploads(), failed );
×
312
        Set<TrackedContentEntry> recalculatedDownloads = null;
×
313
        if ( !failed.get() )
×
314
        {
315
            recalculatedDownloads = recalculateEntrySet( record.getDownloads(), failed );
×
316
        }
317

318
        if ( failed.get() )
×
319
        {
320
            throw new IndyWorkflowException(
×
321
                            "Failed to recalculate tracking record: %s. See Indy logs for more information", id );
322
        }
323

324
        TrackedContent recalculated = new TrackedContent( record.getKey(), recalculatedUploads, recalculatedDownloads );
×
325
        recordManager.replaceTrackingRecord( recalculated );
×
326

327
        return constructContentDTO( recalculated, baseUrl );
×
328
    }
329

330
    private Set<TrackedContentEntry> recalculateEntrySet( final Set<TrackedContentEntry> entries,
331
                                                          final AtomicBoolean failed )
332
    {
333
        Set<ContentTransferDTO> transfer_entries = constructTransferDTOSet( entries );
×
334
        try (Response response = contentService.recalculateEntrySet( transfer_entries ))
×
335
        {
336
            return (Set<TrackedContentEntry>) response.readEntity( DTOStreamingOutput.class ).getDto();
×
337
        }
338
        catch ( Exception e )
×
339
        {
340
            failed.set( true );
×
341
            return null;
×
342
        }
343
    }
344

345
    public File getZipRepository( String id )
346
    {
347
        final TrackingKey tk = new TrackingKey( id );
2 ✔
348
        final TrackedContent record = recordManager.get( tk );
×
349
        ContentDTO dto = convertToContentDTO( record );
×
350
        return contentService.getZipRepository( dto );
×
351
    }
352

353
    public boolean recordArtifact( TrackedContentEntry contentEntry )
354
    {
355
        boolean isRecorded = false;
2 ✔
356
        try
357
        {
358
            isRecorded = recordManager.recordArtifact( contentEntry );
×
359
        }
360
        catch ( final ContentException | IndyWorkflowException e )
×
361
        {
362
            logger.error( "Failed to record entry: {}.", contentEntry, e );
×
363
        }
×
364
        return isRecorded;
×
365
    }
366

367
    /**
368
     * Additional check for batch deletion. It retrieves the promotion record by the trackingID
369
     * to find the target store associated with the promotion. If the target store does not match given store,
370
     * return failed delete validation result.
371
     */
372
    public boolean deletionAdditionalGuardCheck( BatchDeleteRequest deleteRequest )
373
    {
374
        if ( !config.deletionAdditionalGuardCheck() )
×
375
        {
376
            return true; // as passed if guard check is not enabled
×
377
        }
378

379
        String trackingID = deleteRequest.getTrackingID();
×
380
        final StoreKey givenStore = deleteRequest.getStoreKey();
×
381
        final AtomicBoolean isOk = new AtomicBoolean(false);
×
382
        try
383
        {
384
            Response resp = promoteService.getPromoteRecords( trackingID );
×
385
            if (!isSuccess(resp))
×
386
            {
387
                if ( resp.getStatus() == Response.Status.NOT_FOUND.getStatusCode() )
×
388
                {
389
                    // Record not exists. It is common because the guide check can not cover old artifacts. Old
390
                    // artifacts were promoted without tracking. We just print a log and allow it.
391
                    logger.info("Promote tracking record not found but allow deletion, trackingID: {}", trackingID);
×
392
                    return true;
×
393
                }
394
                logger.warn( "Deletion guard check failed, status:" + resp.getStatus() );
×
395
                return false;
×
396
            }
397
            PathsPromoteTrackingRecords promoteTrackingRecords = resp.readEntity(PathsPromoteTrackingRecords.class);
×
398
            Map<String, PathsPromoteTrackingRecords.PathsPromoteResult> resultMap = promoteTrackingRecords.getResultMap();
×
399
            if ( resultMap != null )
×
400
            {
401
                resultMap.forEach( (k,v) -> {
×
402
                    if (v.getRequest().getTarget().equals(givenStore))
×
403
                    {
404
                        isOk.set(true); // set true if any match found
×
405
                    }
406
                });
×
407
            }
408
        }
409
        catch (Exception e)
×
410
        {
411
            logger.warn("Deletion guard check failed", e);
×
412
            return false;
×
413
        }
×
414
        logger.info("Deletion guard check, trackingID: {}, passed: {}", trackingID, isOk.get());
×
415
        return isOk.get();
×
416
    }
417

418
    /**
419
     * Post-action after successful batch delete: cleans up empty parent folders.
420
     * <p>
421
     * For each deleted path, collects its immediate parent folder (one level up).
422
     * Then calls the storage service to clean up these folders, relying on the
423
     * storage API to handle ancestor folders as needed.
424
     * </p>
425
     *
426
     * @param trackingID
427
     * @param filesystem the target filesystem/storeKey as a string
428
     * @param paths the set of deleted file paths
429
     */
430
    public void cleanupEmptyFolders( String trackingID, String filesystem, Set<String> paths )
431
    {
432
        logger.info("Post-action: cleanupEmptyFolder, trackingID={}, filesystem={}, paths={}",
×
433
                    trackingID, filesystem, paths);
434
        if (paths == null || paths.isEmpty()) {
×
435
            logger.info("No paths to process for cleanup.");
×
436
            return;
×
437
        }
438
        Set<String> folders = new HashSet<>();
×
439
        for (String path : paths) {
×
440
            int idx = path.lastIndexOf('/');
×
441
            if (idx > 0) {
×
442
                String folder = path.substring(0, idx);
×
443
                folders.add(folder);
×
444
            }
445
        }
×
446
        StorageBatchDeleteRequest req = new StorageBatchDeleteRequest();
×
447
        req.setInternalId( trackingID );
×
448
        req.setFilesystem(filesystem);
×
449
        req.setPaths(folders);
×
450
        try {
451
            Response resp = storageService.cleanupEmptyFolders(req);
×
452
            logger.info("Cleanup empty folders done, req: {}, status {}", req, resp.getStatus());
×
453
        } catch (Exception e) {
×
454
            logger.warn("Failed to cleanup folders, request: {}, error: {}", req, e.getMessage(), e);
×
455
        }
×
456
    }
×
457

458
    private boolean isSuccess(Response resp) {
459
        return Response.Status.fromStatusCode(resp.getStatus()).getFamily()
×
460
                == Response.Status.Family.SUCCESSFUL;
461
    }
462
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc