/
P2TargetUtils.java
1669 lines (1526 loc) · 63.4 KB
/
P2TargetUtils.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*******************************************************************************
* Copyright (c) 2010, 2018 EclipseSource Inc. and others.
*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License 2.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* EclipseSource Inc. - initial API and implementation
* IBM Corporation - ongoing enhancements
* Manumitting Technologies Inc - Bug 437726
* Lars Vogel <Lars.Vogel@vogella.com> - Bug 477527
*******************************************************************************/
package org.eclipse.pde.internal.core.target;
import java.io.File;
import java.net.URI;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
import java.util.concurrent.ConcurrentHashMap;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubMonitor;
import org.eclipse.core.runtime.URIUtil;
import org.eclipse.core.runtime.preferences.IPreferencesService;
import org.eclipse.equinox.internal.p2.director.PermissiveSlicer;
import org.eclipse.equinox.internal.p2.garbagecollector.GarbageCollector;
import org.eclipse.equinox.internal.p2.repository.helpers.RepositoryHelper;
import org.eclipse.equinox.p2.core.IAgentLocation;
import org.eclipse.equinox.p2.core.IProvisioningAgent;
import org.eclipse.equinox.p2.core.IProvisioningAgentProvider;
import org.eclipse.equinox.p2.core.ProvisionException;
import org.eclipse.equinox.p2.engine.IEngine;
import org.eclipse.equinox.p2.engine.IPhaseSet;
import org.eclipse.equinox.p2.engine.IProfile;
import org.eclipse.equinox.p2.engine.IProfileRegistry;
import org.eclipse.equinox.p2.engine.IProvisioningPlan;
import org.eclipse.equinox.p2.engine.PhaseSetFactory;
import org.eclipse.equinox.p2.engine.ProvisioningContext;
import org.eclipse.equinox.p2.engine.query.IUProfilePropertyQuery;
import org.eclipse.equinox.p2.engine.spi.ProvisioningAction;
import org.eclipse.equinox.p2.metadata.IArtifactKey;
import org.eclipse.equinox.p2.metadata.IInstallableUnit;
import org.eclipse.equinox.p2.metadata.IProvidedCapability;
import org.eclipse.equinox.p2.metadata.IRequirement;
import org.eclipse.equinox.p2.metadata.MetadataFactory;
import org.eclipse.equinox.p2.metadata.MetadataFactory.InstallableUnitDescription;
import org.eclipse.equinox.p2.metadata.Version;
import org.eclipse.equinox.p2.planner.IPlanner;
import org.eclipse.equinox.p2.planner.IProfileChangeRequest;
import org.eclipse.equinox.p2.query.IQuery;
import org.eclipse.equinox.p2.query.IQueryResult;
import org.eclipse.equinox.p2.query.IQueryable;
import org.eclipse.equinox.p2.query.QueryUtil;
import org.eclipse.equinox.p2.repository.IRepository;
import org.eclipse.equinox.p2.repository.IRepositoryManager;
import org.eclipse.equinox.p2.repository.IRepositoryReference;
import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository;
import org.eclipse.equinox.p2.repository.artifact.IArtifactRepositoryManager;
import org.eclipse.equinox.p2.repository.artifact.IArtifactRequest;
import org.eclipse.equinox.p2.repository.artifact.IFileArtifactRepository;
import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository;
import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager;
import org.eclipse.pde.core.target.ITargetDefinition;
import org.eclipse.pde.core.target.ITargetHandle;
import org.eclipse.pde.core.target.ITargetLocation;
import org.eclipse.pde.core.target.ITargetPlatformService;
import org.eclipse.pde.core.target.NameVersionDescriptor;
import org.eclipse.pde.internal.core.PDECore;
import org.osgi.framework.BundleContext;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
public class P2TargetUtils {
private static final String SOURCE_IU_ID = "org.eclipse.pde.core.target.source.bundles"; //$NON-NLS-1$
/**
* URI to the local directory where the p2 agent keeps its information.
*/
public static URI AGENT_LOCATION;
static {
try {
AGENT_LOCATION = URIUtil.fromString("file:" + PDECore.getDefault().getStateLocation().append(".p2")); //$NON-NLS-1$//$NON-NLS-2$
} catch (Exception e) {
// should never happen
}
}
/**
* Path to the local directory where the local bundle pool is stored for p2 profile
* based targets.
*/
public static final IPath BUNDLE_POOL = PDECore.getDefault().getStateLocation().append(".bundle_pool"); //$NON-NLS-1$
/**
* Path to the local directory where install folders are created for p2 profile
* based targets.
*/
static final IPath INSTALL_FOLDERS = PDECore.getDefault().getStateLocation().append(".install_folders"); //$NON-NLS-1$
/**
* Prefix for all profiles ID's associated with target definitions
*/
static final String PROFILE_ID_PREFIX = "TARGET_DEFINITION:"; //$NON-NLS-1$
/**
* Installable unit property to mark IU's that have been installed in a profile by
* a bundle container (rather than as a secondary/required IU).
*/
static final String PROP_INSTALLED_IU = PDECore.PLUGIN_ID + ".installed_iu"; //$NON-NLS-1$
/**
* Profile property that keeps track of provisioning mode for the target
* (slice versus plan).
*/
static final String PROP_PROVISION_MODE = PDECore.PLUGIN_ID + ".provision_mode"; //$NON-NLS-1$
/**
* Profile property that keeps track of provisioning mode for the target
* (all environments/true versus false).
*/
static final String PROP_ALL_ENVIRONMENTS = PDECore.PLUGIN_ID + ".all_environments"; //$NON-NLS-1$
/**
* Profile property that keeps track of the target sequence number
*/
static final String PROP_SEQUENCE_NUMBER = PDECore.PLUGIN_ID + ".sequence"; //$NON-NLS-1$
/**
* Profile property that tracks whether or not source to be auto-included
*/
static final String PROP_AUTO_INCLUDE_SOURCE = PDECore.PLUGIN_ID + ".autoIncludeSource"; //$NON-NLS-1$
/**
* Profile property that tracks whether or not the configuration phase should be executed when installing
*/
static final String PROP_INCLUDE_CONFIGURE_PHASE = PDECore.PLUGIN_ID + ".includeConfigure"; //$NON-NLS-1$
/**
* Table mapping {@link ITargetDefinition} to synchronizer (P2TargetUtils) instance.
*/
private static Map<ITargetDefinition, P2TargetUtils> synchronizers = new WeakHashMap<>();
/**
* Table mapping of ITargetDefinition and IFileArtifactRepository
*/
public static Map<ITargetDefinition, IFileArtifactRepository> fgTargetArtifactRepo = new ConcurrentHashMap<>();
/**
* Table mapping IArtifactKey to table map of IFileArtifactRepository and IFileArtifactRepository
*/
public static Map<IArtifactKey, Map<IFileArtifactRepository, File>> fgArtifactKeyRepoFile = new ConcurrentHashMap<>();
/**
* The profile to be synchronized
*/
private IProfile fProfile;
/**
* Whether this container must have all required IUs of the selected IUs available and included
* in the target to resolve successfully. If this option is true, the planner will be used to resolve
* otherwise the slicer is used. The planner can describe any missing requirements as errors.
* <p>
* <code>true</code> by default
* </p>
*/
private boolean fIncludeAllRequired = true;
/**
* Whether this container should download and include environment (platform) specific units for all
* available platforms (vs only the current target definition's environment settings). Only supported
* by the slicer so {@link IUBundleContainer#INCLUDE_REQUIRED} must be turned off for this setting to be used.
* <p>
* <code>false</code> by default
* </p>
*/
private boolean fIncludeMultipleEnvironments = false;
/**
* Whether this container should download and include source bundles for the selected units if the associated
* source is available in the repository.
* <p>
* <code>false</code> by default
* </p>
*/
private boolean fIncludeSource = false;
/**
* Whether this container should execute the configure phase when installing the IUs
* <p>
* <code>false</code> by default
* </p>
*/
private boolean fIncludeConfigurePhase = false;
/**
* Deletes any profiles associated with target definitions that no longer exist
* and returns a list of profile identifiers that were deleted.
*/
public static List<String> cleanOrphanedTargetDefinitionProfiles() throws CoreException {
List<String> list = new ArrayList<>();
IProfileRegistry registry = getProfileRegistry();
ITargetPlatformService tps = TargetPlatformService.getDefault();
if (registry != null && tps != null) {
IProfile[] profiles = registry.getProfiles();
for (IProfile profile : profiles) {
String id = profile.getProfileId();
if (id.startsWith(PROFILE_ID_PREFIX)) {
String memento = id.substring(PROFILE_ID_PREFIX.length());
try {
ITargetHandle handle = tps.getTarget(memento);
if (handle.exists()) {
continue;
}
} catch (CoreException e) {
// don't break the chain here, but delete the profile as
// it seems to be invalid now
}
deleteProfileWithId(id);
list.add(id);
}
}
}
return list;
}
/**
* Recursively deletes folder and files.
*/
private static void delete(File folder) {
File[] files = folder.listFiles();
for (File file : files) {
if (file.isDirectory()) {
delete(file);
}
file.delete();
}
folder.delete();
}
/**
* Deletes the profile associated with this target handle, if any. Returns
* <code>true</code> if a profile existed and was deleted, otherwise <code>false</code>.
*
* @throws CoreException if unable to delete the profile
*/
public static void deleteProfile(ITargetHandle handle) throws CoreException {
deleteProfileWithId(getProfileId(handle));
}
private static void deleteProfileWithId(String profileId) throws CoreException {
IProfileRegistry registry = getProfileRegistry();
if (registry != null) {
IProfile profile = registry.getProfile(profileId);
if (profile != null) {
String location = profile.getProperty(IProfile.PROP_INSTALL_FOLDER);
registry.removeProfile(profileId);
if (location != null && location.length() > 0) {
File folder = new File(location);
if (folder.exists()) {
delete(folder);
}
}
}
}
}
@SuppressWarnings("restriction")
public static void forceCheckTarget(final ITargetDefinition target) {
final P2TargetUtils result = getSynchronizer(target);
if (result.fProfile instanceof org.eclipse.equinox.internal.p2.engine.Profile) {
((org.eclipse.equinox.internal.p2.engine.Profile) result.fProfile).setProperty(PROP_SEQUENCE_NUMBER, "-1"); //$NON-NLS-1$
}
}
/**
* Performs garbage collection based on remaining profiles. Should be called to avoid
* having PDE's bundle pool area grow unbounded.
*/
public static void garbageCollect() {
try {
IProfile[] profiles = getProfileRegistry().getProfiles();
for (IProfile profile : profiles) {
if (profile.getProfileId().startsWith(PROFILE_ID_PREFIX)) {
getGarbageCollector().runGC(profile);
}
}
} catch (CoreException e) {
// XXX likely should log something here.
return;
}
}
/**
* Generates the environment properties string for this target definition's p2 profile.
*
* @return environment properties
*/
private String generateEnvironmentProperties(ITargetDefinition target) {
// TODO: are there constants for these keys?
StringBuilder env = new StringBuilder();
String ws = target.getWS();
if (ws == null) {
ws = Platform.getWS();
}
env.append("osgi.ws="); //$NON-NLS-1$
env.append(ws);
env.append(","); //$NON-NLS-1$
String os = target.getOS();
if (os == null) {
os = Platform.getOS();
}
env.append("osgi.os="); //$NON-NLS-1$
env.append(os);
env.append(","); //$NON-NLS-1$
String arch = target.getArch();
if (arch == null) {
arch = Platform.getOSArch();
}
env.append("osgi.arch="); //$NON-NLS-1$
env.append(arch);
return env.toString();
}
/**
* Generates the NL property for this target definition's p2 profile.
*
* @return NL profile property
*/
private String generateNLProperty(ITargetDefinition target) {
String nl = target.getNL();
if (nl == null) {
nl = Platform.getNL();
}
return nl;
}
public static IProvisioningAgent getAgent() throws CoreException {
//Is there already an agent for this location?
String filter = "(locationURI=" + AGENT_LOCATION + ")"; //$NON-NLS-1$//$NON-NLS-2$
ServiceReference<IProvisioningAgent> reference = null;
BundleContext context = PDECore.getDefault().getBundleContext();
try {
Collection<ServiceReference<IProvisioningAgent>> serviceReferences = context
.getServiceReferences(IProvisioningAgent.class, filter);
if (!serviceReferences.isEmpty()) {
reference = serviceReferences.iterator().next();
return context.getService(reference);
}
} catch (InvalidSyntaxException e) {
// ignore
} finally {
if (reference != null) {
context.ungetService(reference);
}
}
IProvisioningAgentProvider provider = PDECore.getDefault().acquireService(IProvisioningAgentProvider.class);
try {
if (provider == null) {
throw new CoreException(Status.error(Messages.IUBundleContainer_7));
}
IProvisioningAgent agent = provider.createAgent(AGENT_LOCATION);
if (agent == null) {
throw new CoreException(Status.error(Messages.IUBundleContainer_7));
}
// turn off the garbage collector for the PDE agent. GC is managed on a coarser grain
GarbageCollector garbageCollector = (GarbageCollector) agent.getService(GarbageCollector.class.getName());
if (garbageCollector != null) {
garbageCollector.stop();
}
return agent;
} catch (ProvisionException e) {
throw new CoreException(Status.error(Messages.IUBundleContainer_7, e));
}
}
/**
* Returns the global p2 provisioning agent. This is useful when looking to inherit or use
* some settings from the global p2 world.
*
* @return the global p2 provisioning agent
*/
public static IProvisioningAgent getGlobalAgent() throws CoreException {
IProvisioningAgent agent = PDECore.getDefault().acquireService(IProvisioningAgent.class);
if (agent == null) {
throw new CoreException(Status.error(Messages.IUBundleContainer_11));
}
return agent;
}
/**
* Returns the provisioning agent location service.
*
* @return provisioning agent location service
* @throws CoreException if none
*/
public static IAgentLocation getAgentLocation() throws CoreException {
IAgentLocation result = (IAgentLocation) getAgent().getService(IAgentLocation.SERVICE_NAME);
if (result == null) {
throw new CoreException(Status.error(Messages.IUBundleContainer_10));
}
return result;
}
/**
* Returns the provisioning engine service.
*
* @return provisioning engine
* @throws CoreException if none
*/
public static IArtifactRepositoryManager getArtifactRepositoryManager() throws CoreException {
IArtifactRepositoryManager manager = (IArtifactRepositoryManager) getAgent().getService(IArtifactRepositoryManager.class.getName());
if (manager == null) {
throw new CoreException(Status.error(Messages.IUBundleContainer_3));
}
return manager;
}
/**
* Returns the local bundle pool (repository) where bundles are stored
*
* @return local file artifact repository
*/
public static IFileArtifactRepository getBundlePool() throws CoreException {
URI uri = BUNDLE_POOL.toFile().toURI();
IArtifactRepositoryManager manager = getArtifactRepositoryManager();
try {
if (manager.contains(uri)) {
return (IFileArtifactRepository) manager.loadRepository(uri, null);
}
} catch (CoreException e) {
// could not load or there wasn't one, fall through to create
}
String repoName = "PDE Target Bundle Pool"; //$NON-NLS-1$
IArtifactRepository result = manager.createRepository(uri, repoName, IArtifactRepositoryManager.TYPE_SIMPLE_REPOSITORY, null);
return (IFileArtifactRepository) result;
}
/**
* Returns the provisioning engine service.
*
* @return provisioning engine
* @throws CoreException if none
*/
public static IEngine getEngine() throws CoreException {
IEngine engine = (IEngine) getAgent().getService(IEngine.class.getName());
if (engine == null) {
throw new CoreException(Status.error(Messages.IUBundleContainer_4));
}
return engine;
}
/**
* Returns the p2 garbage collector
*
* @return p2 garbage collector
* @throws CoreException if none
*/
public static GarbageCollector getGarbageCollector() throws CoreException {
GarbageCollector engine = (GarbageCollector) getAgent().getService(GarbageCollector.class.getName());
if (engine == null) {
throw new CoreException(Status.error(Messages.IUBundleContainer_9));
}
return engine;
}
/**
* Returns the provisioning planner.
*
* @return provisioning planner
* @throws CoreException if none
*/
public static IPlanner getPlanner() throws CoreException {
IPlanner planner = (IPlanner) getAgent().getService(IPlanner.class.getName());
if (planner == null) {
throw new CoreException(Status.error(Messages.IUBundleContainer_5));
}
return planner;
}
/**
* Returns the preferences service.
*
* @return preferences service or null if none
*/
public static IPreferencesService getPreferences() {
return PDECore.getDefault().acquireService(IPreferencesService.class);
}
/**
* Returns whether the contents of the profile matches the expected contents of the target definition
*
* @return whether or not the profile and target definitions match
* @throws CoreException in unable to retrieve profile
*/
private boolean checkProfile(ITargetDefinition target) throws CoreException {
// make sure we have a profile to validate
if (fProfile == null) {
return false;
}
// check that the target and profiles are in sync. If they are then life is good.
// If they are not equal, there is still a chance that everything is ok.
String profileNumber = fProfile.getProperty(PROP_SEQUENCE_NUMBER);
if (Integer.toString(((TargetDefinition) target).getSequenceNumber()).equals(profileNumber)) {
return true;
}
// check if all environments setting is the same
boolean all = false;
String value = fProfile.getProperty(PROP_ALL_ENVIRONMENTS);
if (value != null) {
all = Boolean.parseBoolean(value);
if (!Boolean.toString(getIncludeAllEnvironments()).equals(value)) {
return false;
}
}
// ensure environment & NL settings are still the same (else we need a new profile)
String property = null;
if (!all) {
property = generateEnvironmentProperties(target);
value = fProfile.getProperty(IProfile.PROP_ENVIRONMENTS);
if (!property.equals(value)) {
return false;
}
}
property = generateNLProperty(target);
value = fProfile.getProperty(IProfile.PROP_NL);
if (!property.equals(value)) {
return false;
}
// check provisioning mode: slice versus plan
if (!getProvisionMode(target).equals(fProfile.getProperty(PROP_PROVISION_MODE))) {
return false;
}
// check that the include source flag matches what the profile represents
if (getIncludeSource() != Boolean.parseBoolean(fProfile.getProperty(PROP_AUTO_INCLUDE_SOURCE))) {
return false;
}
if (getIncludeConfigurePhase() != Boolean.parseBoolean(fProfile.getProperty(PROP_INCLUDE_CONFIGURE_PHASE))) {
return false;
}
// check top level IU's. If any have been removed from the containers that are
// still in the profile, we need to recreate (rather than uninstall)
IUProfilePropertyQuery propertyQuery = new IUProfilePropertyQuery(PROP_INSTALLED_IU, Boolean.toString(true));
IQueryResult<IInstallableUnit> queryResult = fProfile.query(propertyQuery, null);
Iterator<IInstallableUnit> iterator = queryResult.iterator();
Set<NameVersionDescriptor> installedIUs = new HashSet<>();
while (iterator.hasNext()) {
IInstallableUnit unit = iterator.next();
installedIUs.add(new NameVersionDescriptor(unit.getId(), unit.getVersion().toString()));
}
ITargetLocation[] containers = target.getTargetLocations();
if (containers == null) {
return installedIUs.isEmpty();
}
for (ITargetLocation container : containers) {
if (container instanceof IUBundleContainer bc) {
String[] ids = bc.getIds();
Version[] versions = bc.getVersions();
for (int j = 0; j < versions.length; j++) {
// if there is something in a container but not in the profile, recreate
if (!installedIUs.remove(new NameVersionDescriptor(ids[j], versions[j].toString()))) {
return false;
}
}
}
}
if (!installedIUs.isEmpty()) {
return false;
}
// Phew! seems like the profile checks out.
return true;
}
/**
* Sets whether all required units must be available to resolve this container. When <code>true</code>
* the resolve operation will use the planner to determine the complete set of IUs required to
* make the selected IUs runnable. If any dependencies are missing, the resolve operation will return an
* error explaining what problems exist. When <code>false</code> the resolve operation will use the slicer
* to determine what units to include. Any required units that are not available in the repositories will
* be ignored.
* <p>
* Since there is only one profile per target and the planner and slicer resolve methods are incompatible.
* </p>
* @param value whether all required units must be available to resolve this container
*/
public void setIncludeAllRequired(boolean value) {
fIncludeAllRequired = value;
}
/**
* Returns whether all required units must be available to resolve this container. When <code>true</code>
* the resolve operation will use the planner to determine the complete set of IUs required to
* make the selected IUs runnable. If any dependencies are missing, the resolve operation will return an
* error explaining what problems exist. When <code>false</code> the resolve operation will use the slicer
* to determine what units to include. Any required units that are not available in the repositories will
* be ignored.
*
* @return whether all required units must be available to resolve this container
*/
public boolean getIncludeAllRequired() {
return fIncludeAllRequired;
}
/**
* Sets whether all environment (platform) specific installable units should
* be included in this container when it is resolved. This feature is not supported
* by the planner so will only have an effect if the include all required setting
* is turned off ({@link #getIncludeAllRequired()}).
* <p>
* There is only one profile per target and this setting can only be set for the
* entire target definition.
* </p>
* @param value whether environment specific units should be included
*/
public void setIncludeAllEnvironments(boolean value) {
fIncludeMultipleEnvironments = value;
}
/**
* Returns whether all environment (platform) specific installable units should
* be included in this container when it is resolved. This feature is not supported
* by the planner so will only have an effect if the include all required setting
* is turned off ({@link #getIncludeAllRequired()}).
*
* @return whether environment specific units should be included
*/
public boolean getIncludeAllEnvironments() {
return fIncludeMultipleEnvironments;
}
/**
* Set whether or not the source bundles corresponding to any binary bundles should
* be automatically included in the target.
*
* @param value whether or not to include source
*/
public void setIncludeSource(boolean value) {
fIncludeSource = value;
}
/**
* Returns whether or not source bundles corresponding to selected binary bundles
* are automatically included in the target.
*
* @return whether or not source is included automatically
*/
public boolean getIncludeSource() {
return fIncludeSource;
}
/**
* Set whether or not the configuration phase should be executed when installing the IUs
*
* @param value whether or not to execute configuration phase
*/
public void setIncludeConfigurePhase(boolean value) {
fIncludeConfigurePhase = value;
}
/**
* Returns whether or not the configuration phase should be executed when installing the IUs
*
* @return whether or not to execute configuration phase
*/
public boolean getIncludeConfigurePhase() {
return fIncludeConfigurePhase;
}
/**
* Return whether or not the given target has a matching profile that is in sync
* @param target the target to check
* @return whether or not the target has been resolved at the p2 level
*/
public static boolean isResolved(ITargetDefinition target) {
P2TargetUtils synchronizer = getSynchronizer(target);
if (synchronizer == null) {
return false;
}
try {
return synchronizer.checkProfile(target);
} catch (CoreException e) {
return false;
}
}
/**
* Return whether or not the given target's matching profile is in sync
* @param target the target to check
* @return whether or not the target has been resolved at the p2 level
*/
public static boolean isProfileValid(ITargetDefinition target) {
P2TargetUtils synchronizer = getSynchronizer(target);
if (synchronizer == null) {
return false;
}
try {
synchronizer.updateProfileFromRegistry(target);
return synchronizer.checkProfile(target);
} catch (CoreException e) {
return false;
}
}
private void updateProfileFromRegistry(ITargetDefinition target) {
if (fProfile == null) {
try {
fProfile = getProfileRegistry().getProfile(getProfileId(target));
} catch (CoreException e) {
}
}
}
/**
* Get the synchronizer to use for the given target. If there is already one on a
* container in the target, use that one. Otherwise, create a new one. Either way,
* ensure that all other IU containers in the target are using the same synchronizer.
* <p>
* The synchronizer is an instance of {@link P2TargetUtils} that has access to the
* profile and other p2 bits for the target.
* </p>
*
* @param target the target for which we are getting the synchronizer
* @return the discovered or created synchronizer
*/
static synchronized P2TargetUtils getSynchronizer(ITargetDefinition target) {
P2TargetUtils result = synchronizers.get(target);
if (result != null) {
return result;
}
result = new P2TargetUtils();
synchronizers.put(target, result);
return result;
}
/**
* Return the set of IUs in all IU containers associated with this synchronizer.
* This is a helper method so we don't have to expose the profile itself.
*
* @param target the target definition to query
* @param monitor the progress monitor to use
* @return the set of associated IUs
* @throws CoreException if there is a problem discovering the IUs
*/
public static IQueryResult<IInstallableUnit> getIUs(ITargetDefinition target, IProgressMonitor monitor)
throws CoreException {
P2TargetUtils synchronizer = getSynchronizer(target);
if (synchronizer == null) {
return null;
}
synchronizer.synchronize(target, monitor);
return synchronizer.getProfile().query(QueryUtil.createIUAnyQuery(), null);
}
/**
* Synchronize the profile and the target definition managed by this synchronizer. On return the profile will
* be resolved and correctly match the given target. The IUBundleContainers associated with
* the target will be notified of any changes in the underlying p2 profile and given an
* opportunity to update themselves accordingly.
*
* NOTE: this is a potentially *very* heavyweight operation.
*
* NOTE: this method is synchronized as it is effectively a "test and set" caching method. Two
* threads getting the profile at the same time should not execute concurrently or the profiles
* will get out of sync.
*
* @throws CoreException if there was a problem synchronizing
*/
public synchronized void synchronize(ITargetDefinition target, IProgressMonitor monitor) throws CoreException {
SubMonitor progress = SubMonitor.convert(monitor, 100);
// Happiness if we have a profile and it checks out or if we can load one and it checks out.
if (fProfile == null) {
fProfile = getProfileRegistry().getProfile(getProfileId(target));
}
if (fProfile != null && checkProfile(target)) {
// always push the changes to the target because there can be many target objects
// for the same synchronizer (doh!)
notify(target, progress.split(25));
return;
}
// Either no profile was found or it was stale. Delete the current profile and recreate.
// This keeps the internal agent data clean and does not cost us much.
deleteProfile(target.getHandle());
createProfile(target);
if (progress.isCanceled()) {
return;
}
progress.setWorkRemaining(75);
try {
// Now resolve the profile and refresh the relate IU containers
if (getIncludeAllRequired()) {
resolveWithPlanner(target, progress.split(60));
} else {
resolveWithSlicer(target, progress.split(60));
}
// If we are updating a profile then delete the old snapshot on success.
notify(target, progress.split(15));
} catch (CoreException e) {
// There was at least one problem getting the contents, delete the profile so we don't cache in a bad state, Bug 439034
// TODO ALL we really want to delete is the sequence property, so that checkProfile will compare settings and contents
try {
deleteProfile(target.getHandle());
} catch (CoreException e2) {
PDECore.log(e2.getStatus());
}
throw e;
}
}
private void createProfile(ITargetDefinition target) throws CoreException, ProvisionException {
// create a new profile
IProfileRegistry registry = getProfileRegistry();
if (registry == null) {
throw new CoreException(Status.error(Messages.AbstractTargetHandle_0));
}
Map<String, String> properties = new HashMap<>();
properties.put(IProfile.PROP_INSTALL_FOLDER, INSTALL_FOLDERS.append(Long.toString(LocalTargetHandle.nextTimeStamp())).toOSString());
properties.put(IProfile.PROP_CACHE, BUNDLE_POOL.toOSString());
properties.put(IProfile.PROP_INSTALL_FEATURES, Boolean.TRUE.toString());
properties.put(IProfile.PROP_ENVIRONMENTS, generateEnvironmentProperties(target));
properties.put(IProfile.PROP_NL, generateNLProperty(target));
properties.put(PROP_SEQUENCE_NUMBER, Integer.toString(((TargetDefinition) target).getSequenceNumber()));
properties.put(PROP_PROVISION_MODE, getProvisionMode(target));
properties.put(PROP_ALL_ENVIRONMENTS, Boolean.toString(getIncludeAllEnvironments()));
properties.put(PROP_AUTO_INCLUDE_SOURCE, Boolean.toString(getIncludeSource()));
properties.put(PROP_INCLUDE_CONFIGURE_PHASE, Boolean.toString(getIncludeConfigurePhase()));
fProfile = registry.addProfile(getProfileId(target), properties);
}
/**
* Signal the relevant bundle containers that the given profile has changed.
*/
private void notify(ITargetDefinition target, IProgressMonitor monitor) {
// flush the target caches first since some of them are used in rebuilding
// the container caches (e.g., featureModels)
((TargetDefinition) target).flushCaches(P2TargetUtils.BUNDLE_POOL.toOSString());
// Now proactively recompute all the related container caches.
ITargetLocation[] containers = target.getTargetLocations();
if (containers != null) {
for (ITargetLocation container : containers) {
if (container instanceof IUBundleContainer) {
((IUBundleContainer) container).synchronizerChanged(target);
}
}
}
}
/**
* Returns the profile identifier for this target handle. There is one profile
* per target definition.
*
* @return profile identifier
* @throws CoreException in unable to generate identifier
*/
private static String getProfileId(ITargetHandle handle) throws CoreException {
String memento = handle.getMemento();
return PROFILE_ID_PREFIX + getProfileSuffix(memento);
}
/**
* Returns the potentially shortened profile identifier based on the given
* memento.
*
* @param memento
* the ITargetHandle memento as the basis of the ID.
* @return an ID string short enough that it does not exceed the max file
* length.
*/
private static String getProfileSuffix(String memento) {
// Memento strings can be very long and exceed max filename lengths,
// trim down to 200 + prefix + hashcode, considering also how the ID
// will
// be encoded.
// org.eclipse.equinox.internal.p2.engine.SimpleProfileRegistry.escape(String)
int escapedLength = 0;
int length = memento.length();
// length * 4 > 200
if (length > 50) {
for (int i = length - 1; i >= 0; --i) {
switch (memento.charAt(i))
{
case '\\':
case '/':
case ':':
case '*':
case '?':
case '"':
case '<':
case '>':
case '|':
case '%': {
escapedLength += 4;
}
default: {
escapedLength += 1;
}
}
if (escapedLength > 200) {
return memento.substring(i + 1) + memento.hashCode();
}
}
}
return memento;
}
/**
* Returns the profile identifier for this target handle. There is one profile
* per target definition.
*
* @return definition the target to lookup
*/
public static String getProfileId(ITargetDefinition definition) {
try {
return getProfileId(definition.getHandle());
} catch (CoreException e) {
// gotta make sure that this never happens. all we're doing here is computing a string.
return null;
}
}
/**
* Returns the profile registry or <code>null</code>
*
* @return profile registry or <code>null</code>
*/
public static IProfileRegistry getProfileRegistry() throws CoreException {
IProfileRegistry result = (IProfileRegistry) getAgent().getService(IProfileRegistry.SERVICE_NAME);
if (result == null) {
throw new CoreException(Status.error(Messages.IUBundleContainer_8));
}
return result;
}
/**
* Returns the mode used to provision this target - slice versus plan or <code>null</code> if
* this target has no software sites.
*
* @return provisioning mode or <code>null</code>
*/
private String getProvisionMode(ITargetDefinition target) {
return getIncludeAllRequired() ? TargetDefinitionPersistenceHelper.MODE_PLANNER : TargetDefinitionPersistenceHelper.MODE_SLICER;
}
/**
* Returns the metadata repository manager.
*
* @return metadata repository manager
* @throws CoreException if none
*/
public static IMetadataRepositoryManager getRepoManager() throws CoreException {
IMetadataRepositoryManager manager = (IMetadataRepositoryManager) getAgent().getService(IMetadataRepositoryManager.SERVICE_NAME);
if (manager == null) {
throw new CoreException(Status.error(Messages.IUBundleContainer_2));
}
return manager;
}
/**
* Return a queryable on the metadata defined in the given repo locations
*
* @param repos the repos to lookup
* @param monitor the progress monitor
* @return the set of metadata repositories found