001package org.hl7.fhir.utilities.npm;
002
003import java.io.*;
004
005import java.util.*;
006
007import javax.annotation.Nonnull;
008import javax.annotation.Nullable;
009
010import lombok.Getter;
011import lombok.Setter;
012import lombok.With;
013import org.apache.commons.io.FileUtils;
014import org.hl7.fhir.exceptions.FHIRException;
015import org.hl7.fhir.utilities.*;
016import org.hl7.fhir.utilities.filesystem.ManagedFileAccess;
017import org.hl7.fhir.utilities.http.HTTPResult;
018import org.hl7.fhir.utilities.http.ManagedWebAccess;
019import org.hl7.fhir.utilities.json.model.JsonObject;
020import org.hl7.fhir.utilities.json.parser.JsonParser;
021import org.hl7.fhir.utilities.npm.PackageList.PackageListEntry;
022import org.hl7.fhir.utilities.settings.FhirSettings;
023import org.slf4j.Logger;
024import org.slf4j.LoggerFactory;
025
026/*
027  Copyright (c) 2011+, HL7, Inc.
028  All rights reserved.
029  
030  Redistribution and use in source and binary forms, with or without modification, 
031  are permitted provided that the following conditions are met:
032    
033   * Redistributions of source code must retain the above copyright notice, this 
034     list of conditions and the following disclaimer.
035   * Redistributions in binary form must reproduce the above copyright notice, 
036     this list of conditions and the following disclaimer in the documentation 
037     and/or other materials provided with the distribution.
038   * Neither the name of HL7 nor the names of its contributors may be used to 
039     endorse or promote products derived from this software without specific 
040     prior written permission.
041  
042  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
043  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
044  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
045  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
046  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 
047  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 
048  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
049  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
050  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
051  POSSIBILITY OF SUCH DAMAGE.
052  
053 */
054
055/**
056 * This is a package cache manager implementation that uses a local disk cache
057 *
058 * <p>
059 * API:
060 * <p>
061 * constructor
062 * getPackageUrl
063 * getPackageId
064 * findPackageCache
065 * addPackageToCache
066 *
067 * @author Grahame Grieve
068 */
069public class FilesystemPackageCacheManager extends BasePackageCacheManager implements IPackageCacheManager {
070
071  private final FilesystemPackageCacheManagerLocks locks;
072
073  private final FilesystemPackageCacheManagerLocks.LockParameters lockParameters;
074
075  // When running in testing mode, some packages are provided from the test case repository rather than by the normal means
076  // the PackageProvider is responsible for this. if no package provider is defined, or it declines to handle the package, 
077  // then the normal means will be used
078  public interface IPackageProvider {
079    boolean handlesPackage(String id, String version);
080    InputStreamWithSrc provide(String id, String version) throws IOException;
081  }
082
083  private static IPackageProvider packageProvider;
084  public static final String PACKAGE_REGEX = "^[a-zA-Z][A-Za-z0-9\\_\\-]*(\\.[A-Za-z0-9\\_\\-]+)+$";
085  public static final String PACKAGE_VERSION_REGEX = "^[A-Za-z][A-Za-z0-9\\_\\-]*(\\.[A-Za-z0-9\\_\\-]+)+\\#[A-Za-z0-9\\-\\_\\$]+(\\.[A-Za-z0-9\\-\\_\\$]+)*$";
086  public static final String PACKAGE_VERSION_REGEX_OPT = "^[A-Za-z][A-Za-z0-9\\_\\-]*(\\.[A-Za-z0-9\\_\\-]+)+(\\#[A-Za-z0-9\\-\\_]+(\\.[A-Za-z0-9\\-\\_]+)*)?$";
087  private static final Logger ourLog = LoggerFactory.getLogger(FilesystemPackageCacheManager.class);
088  private static final String CACHE_VERSION = "3"; // second version - see wiki page
089
090  @Getter
091  private final CIBuildClient ciBuildClient;
092
093  @Nonnull
094  private final File cacheFolder;
095
096  private final List<NpmPackage> temporaryPackages = new ArrayList<>();
097
098  private boolean suppressErrors;
099
100  @Setter
101  @Getter
102  private boolean minimalMemory;
103
104  public static class Builder {
105
106    @Getter
107    private final File cacheFolder;
108
109    @With
110    @Getter
111    private final List<PackageServer> packageServers;
112
113    @With
114    @Getter
115    private final CIBuildClient ciBuildClient;
116
117    @With
118    @Getter
119    private final FilesystemPackageCacheManagerLocks.LockParameters lockParameters;
120
121    public Builder() throws IOException {
122      this.cacheFolder = getUserCacheFolder();
123      this.packageServers = getPackageServersFromFHIRSettings();
124      this.lockParameters = null;
125      this.ciBuildClient = new CIBuildClient();
126    }
127
128    private Builder(File cacheFolder, List<PackageServer> packageServers, CIBuildClient ciBuildClient, FilesystemPackageCacheManagerLocks.LockParameters lockParameters) {
129      this.cacheFolder = cacheFolder;
130      this.packageServers = packageServers;
131      this.ciBuildClient = ciBuildClient;
132      this.lockParameters = lockParameters;
133    }
134
135    private File getUserCacheFolder() throws IOException {
136      return ManagedFileAccess.file(Utilities.path(System.getProperty("user.home"), ".fhir", "packages"));
137    }
138
139    private List<PackageServer> getPackageServersFromFHIRSettings() {
140      List<PackageServer> packageServers = new ArrayList<>(getConfiguredServers());
141      if (!isIgnoreDefaultPackageServers()) {
142        packageServers.addAll(getDefaultServers());
143      }
144      return packageServers;
145    }
146
147    protected boolean isIgnoreDefaultPackageServers() {
148      return FhirSettings.isIgnoreDefaultPackageServers();
149    }
150
151    @Nonnull
152    protected List<PackageServer> getDefaultServers() {
153      return PackageServer.defaultServers();
154    }
155
156    protected List<PackageServer> getConfiguredServers() {
157      return PackageServer.getConfiguredServers();
158    }
159
160    public Builder withCacheFolder(String cacheFolderPath) throws IOException {
161      File cacheFolder = ManagedFileAccess.file(cacheFolderPath);
162      if (!cacheFolder.exists()) {
163        throw new FHIRException("The folder '" + cacheFolder + "' could not be found");
164      }
165      return new Builder(cacheFolder, this.packageServers, this.ciBuildClient, this.lockParameters);
166    }
167
168    public Builder withSystemCacheFolder() throws IOException {
169      final File systemCacheFolder;
170      if (Utilities.isWindows()) {
171        systemCacheFolder = ManagedFileAccess.file(Utilities.path(System.getenv("ProgramData"), ".fhir", "packages"));
172      } else {
173        systemCacheFolder = ManagedFileAccess.file(Utilities.path("/var", "lib", ".fhir", "packages"));
174      }
175      return new Builder(systemCacheFolder,  this.packageServers, this.ciBuildClient, this.lockParameters);
176    }
177
178    public Builder withTestingCacheFolder() throws IOException {
179      return new Builder(ManagedFileAccess.file(Utilities.path("[tmp]", ".fhir", "packages")), this.packageServers, this.ciBuildClient, this.lockParameters);
180    }
181
182    public FilesystemPackageCacheManager build() throws IOException {
183      final FilesystemPackageCacheManagerLocks locks;
184      try {
185        locks = FilesystemPackageCacheManagerLocks.getFilesystemPackageCacheManagerLocks(cacheFolder);
186      } catch (RuntimeException e) {
187        if (e.getCause() instanceof IOException) {
188          throw (IOException) e.getCause();
189        } else {
190          throw e;
191        }
192      }
193      return new FilesystemPackageCacheManager(cacheFolder, packageServers, ciBuildClient, locks, lockParameters);
194    }
195  }
196
197  private FilesystemPackageCacheManager(@Nonnull File cacheFolder, @Nonnull List<PackageServer> packageServers, CIBuildClient ciBuildClient, @Nonnull FilesystemPackageCacheManagerLocks locks, @Nullable FilesystemPackageCacheManagerLocks.LockParameters lockParameters) throws IOException {
198    super(packageServers);
199    this.cacheFolder = cacheFolder;
200    this.ciBuildClient = ciBuildClient;
201    this.locks = locks;
202    this.lockParameters = lockParameters;
203    prepareCacheFolder();
204  }
205
206  /**
207   * Check if the cache folder exists and is valid.
208   * <p>
209   * If it doesn't exist, create it.
210   * <p>
211   * If it does exist and isn't valid, delete it and create a new one.
212   * <p>
213   * If it does exist and is valid, just do some cleanup (delete temp download directories, etc.)
214   *
215   * @throws IOException if the cache folder can't be created
216   */
217  protected void prepareCacheFolder() throws IOException {
218    locks.getCacheLock().doWriteWithLock(() -> {
219
220      if (!(cacheFolder.exists())) {
221        FileUtilities.createDirectory(cacheFolder.getAbsolutePath());
222        createIniFile();
223      } else {
224        if (!iniFileExists()) {
225          createIniFile();
226        }
227        if (!isIniFileCurrentVersion()) {
228          clearCache();
229          createIniFile();
230        }
231        deleteOldTempDirectories();
232        cleanUpCorruptPackages();
233      }
234      return null;
235    });
236  }
237
238  /*
239    Look for .lock files that are not actively held by a process. If found, delete the lock file, and the package
240    referenced.
241   */
242  protected void cleanUpCorruptPackages() throws IOException {
243    for (File file : Objects.requireNonNull(cacheFolder.listFiles())) {
244      if (file.getName().endsWith(".lock")) {
245        if (locks.getCacheLock().canLockFileBeHeldByThisProcess(file)) {
246          String packageDirectoryName = file.getName().substring(0, file.getName().length() - 5);
247          log("Detected potential incomplete package installed in cache: " + packageDirectoryName + ". Attempting to delete");
248
249          File packageDirectory = ManagedFileAccess.file(Utilities.path(cacheFolder, packageDirectoryName));
250          if (packageDirectory.exists()) {
251            FileUtilities.clearDirectory(packageDirectory.getAbsolutePath());
252            packageDirectory.delete();
253          }
254          file.delete();
255          log("Deleted potential incomplete package: " + packageDirectoryName);
256        }
257      }
258    }
259  }
260
261  private boolean iniFileExists() throws IOException {
262    String iniPath = getPackagesIniPath();
263    File iniFile = ManagedFileAccess.file(iniPath);
264    return iniFile.exists();
265  }
266
267  private boolean isIniFileCurrentVersion() throws IOException {
268    String iniPath = getPackagesIniPath();
269    IniFile ini = new IniFile(iniPath);
270    String version = ini.getStringProperty("cache", "version");
271    return CACHE_VERSION.equals(version);
272  }
273
274  private void deleteOldTempDirectories() throws IOException {
275    for (File f : Objects.requireNonNull(cacheFolder.listFiles())) {
276      if (f.isDirectory() && UUIDUtilities.isValidUUID(f.getName())) {
277        FileUtilities.clearDirectory(f.getAbsolutePath());
278        f.delete();
279      }
280    }
281  }
282
283  public String getFolder() {
284    return cacheFolder.getAbsolutePath();
285  }
286
287  private NpmPackage loadPackageInfo(String path) throws IOException {
288    return minimalMemory ? NpmPackage.fromFolderMinimal(path, false) : NpmPackage.fromFolder(path, false);
289  }
290
291  private void clearCache() throws IOException {
292    for (File f : Objects.requireNonNull(cacheFolder.listFiles())) {
293      if (f.isDirectory()) {
294        FileUtilities.atomicDeleteDirectory(f.getAbsolutePath());
295
296      } else if (!f.getName().equals("packages.ini")) {
297        FileUtils.forceDelete(f);
298      }
299
300    }
301  }
302
303  private void createIniFile() throws IOException {
304    IniFile ini = new IniFile(getPackagesIniPath());
305    ini.setStringProperty("cache", "version", CACHE_VERSION, null);
306    ini.save();
307  }
308
309  private String getPackagesIniPath() throws IOException {
310    return Utilities.path(cacheFolder, "packages.ini");
311  }
312
313  private void checkValidVersionString(String version, String id) {
314    if (Utilities.noString(version)) {
315      throw new FHIRException("Cannot add package " + id + " to the package cache - a version must be provided");
316    }
317    if (version.startsWith("file:")) {
318      throw new FHIRException("Cannot add package " + id + " to the package cache - the version '" + version + "' is illegal in this context");
319    }
320    for (char ch : version.toCharArray()) {
321      if (!Character.isAlphabetic(ch) && !Character.isDigit(ch) && !Utilities.existsInList(ch, '.', '-', '$')) {
322        throw new FHIRException("Cannot add package " + id + " to the package cache - the version '" + version + "' is illegal (ch '" + ch + "'");
323      }
324    }
325  }
326
327  protected InputStreamWithSrc loadFromPackageServer(String id, String version) {
328    InputStreamWithSrc retVal = super.loadFromPackageServer(id, version);
329    if (retVal != null) {
330      return retVal;
331    }
332
333    retVal = super.loadFromPackageServer(id, VersionUtilities.getMajMin(version) + ".x");
334    if (retVal != null) {
335      return retVal;
336    }
337
338    // ok, well, we'll try the old way
339    return fetchTheOldWay(id, version);
340  }
341
342  public String getLatestVersion(String id) throws IOException {
343    for (PackageServer nextPackageServer : getPackageServers()) {
344      // special case:
345      if (!(Utilities.existsInList(id, CommonPackages.ID_PUBPACK, "hl7.terminology.r5") && PackageServer.SECONDARY_SERVER.equals(nextPackageServer.getUrl()))) {
346        PackageClient pc = new PackageClient(nextPackageServer);
347        try {
348          return pc.getLatestVersion(id);
349        } catch (IOException e) {
350          ourLog.info("Failed to determine latest version of package {} from server: {}", id, nextPackageServer.toString());
351        }
352      }
353    }
354    try {
355      return fetchVersionTheOldWay(id);
356    } catch (Exception e) {
357      ourLog.info("Failed to determine latest version of package {} from server: {}", id, "build.fhir.org");
358    }
359    // still here? use the latest version we previously found or at least, is in the cache
360
361    String version = getLatestVersionFromCache(id);
362    if (version != null) {
363      return version;
364    }
365    throw new FHIRException("Unable to find the last version for package " + id + ": no local copy, and no network access");
366  }
367
368  public String getLatestVersionFromCache(String id) throws IOException {
369    for (String f : Utilities.reverseSorted(cacheFolder.list())) {
370      File cf = ManagedFileAccess.file(Utilities.path(cacheFolder, f));
371      if (cf.isDirectory()) {
372        if (f.startsWith(id + "#")) {
373          String ver = f.substring(f.indexOf("#") + 1);
374          ourLog.info("Latest version of package {} found locally is {} - using that", id, ver);
375          return ver;
376        }
377      }
378    }
379    return null;
380  }
381
382  private NpmPackage loadPackageFromFile(String id, String folder) throws IOException {
383    File f = ManagedFileAccess.file(Utilities.path(folder, id));
384    if (!f.exists()) {
385      throw new FHIRException("Package '" + id + "  not found in folder " + folder);
386    }
387    if (!f.isDirectory()) {
388      throw new FHIRException("File for '" + id + "  found in folder " + folder + ", not a folder");
389    }
390    File fp = ManagedFileAccess.file(Utilities.path(folder, id, "package", "package.json"));
391    if (!fp.exists()) {
392      throw new FHIRException("Package '" + id + "  found in folder " + folder + ", but does not contain a package.json file in /package");
393    }
394    return NpmPackage.fromFolder(f.getAbsolutePath());
395  }
396
397  /**
398   * Clear the cache
399   *
400   * @throws IOException If the cache cannot be cleared
401   */
402  public void clear() throws IOException {
403    this.locks.getCacheLock().doWriteWithLock(() -> {
404      clearCache();
405      return null;
406    });
407  }
408
409  // ========================= Utilities ============================================================================
410
411  /**
412   * Remove a particular package from the cache
413   *
414   * @param id The id of the package to remove
415   * @param version The literal version of the package to remove. Values such as 'current' and 'dev' are not allowed.
416   * @throws IOException If the package cannot be removed
417   */
418  public void removePackage(String id, String version) throws IOException {
419    locks.getPackageLock(id + "#" + version).doWriteWithLock(() -> {
420
421      String f = Utilities.path(cacheFolder, id + "#" + version);
422        File ff = ManagedFileAccess.file(f);
423        if (ff.exists()) {
424          FileUtilities.atomicDeleteDirectory(f);
425        }
426      return null;
427    }, lockParameters);
428  }
429
430  /**
431   * Load the identified package from the cache - if it exists
432   * <p/>
433   * This is for special purpose only (testing, control over speed of loading).
434   * <p/>
435   * Generally, use the loadPackage method
436   *
437   * @param id The id of the package to load
438   * @param version The version of the package to load. Values such as 'current' and 'dev' are allowed.
439   * @return The package, or null if it is not found
440   * @throws IOException If the package cannot be loaded
441   */
442  @Override
443  public NpmPackage loadPackageFromCacheOnly(String id, @Nullable String version) throws IOException {
444
445    if (!Utilities.noString(version) && version.startsWith("file:")) {
446      return loadPackageFromFile(id, version.substring(5));
447    }
448
449    for (NpmPackage p : temporaryPackages) {
450      if (p.name().equals(id) && ("current".equals(version) || "dev".equals(version) || p.version().equals(version))) {
451        return p;
452      }
453      if (p.name().equals(id) && Utilities.noString(version)) {
454        return p;
455      }
456    }
457
458    String foundPackageFolder = findPackageFolder(id, version);
459    if (foundPackageFolder != null) {
460      NpmPackage foundPackage = locks.getPackageLock(foundPackageFolder).doReadWithLock(() -> {
461        String path = Utilities.path(cacheFolder, foundPackageFolder);
462        File directory = ManagedFileAccess.file(path);
463
464        /* Check if the directory still exists now that we have a read lock. findPackageFolder does no locking in order
465        to avoid locking every potential package directory, so it's possible that a package deletion has occurred.
466        * */
467        if (!directory.exists()) {
468          return null;
469        }
470        return loadPackageInfo(path);
471      }, lockParameters);
472      if (foundPackage != null) {
473        if (foundPackage.isIndexed()){
474          return foundPackage;
475        } else {
476          return locks.getPackageLock(foundPackageFolder).doWriteWithLock(() -> {
477            File directory = ManagedFileAccess.file(foundPackage.getPath());
478
479        /* Check if the directory still exists now that we have a write lock. findPackageFolder does no locking in order
480        to avoid locking every potential package directory, so it's possible that a package deletion has occurred.
481        * */
482            if (!directory.exists()) {
483              return null;
484            }
485
486            // Since another thread may have already indexed the package since our read, we need to check again
487            NpmPackage output = loadPackageInfo(foundPackage.getPath());
488            if (output.isIndexed()) {
489              return output;
490            }
491            String path = Utilities.path(cacheFolder, foundPackageFolder);
492            output.checkIndexed(path);
493            return output;
494          }, lockParameters);
495          }
496      }
497    }
498    if ("dev".equals(version))
499      return loadPackageFromCacheOnly(id, "current");
500    else
501      return null;
502  }
503
504  private String findPackageFolder(String id, String version) throws IOException {
505    String foundPackageFolder = null;
506    String foundVersion = null;
507    for (String currentPackageFolder : Utilities.reverseSorted(cacheFolder.list())) {
508      File cf = ManagedFileAccess.file(Utilities.path(cacheFolder, currentPackageFolder));
509      if (cf.isDirectory()) {
510        if (currentPackageFolder.equals(id + "#" + version) || (Utilities.noString(version) && currentPackageFolder.startsWith(id + "#"))) {
511          return currentPackageFolder;
512        }
513        if (version != null && !version.equals("current") && (version.endsWith(".x") || Utilities.charCount(version, '.') < 2) && currentPackageFolder.contains("#")) {
514          String[] parts = currentPackageFolder.split("#");
515          if (parts[0].equals(id) && VersionUtilities.isMajMinOrLaterPatch((foundVersion != null ? foundVersion : version), parts[1])) {
516            foundVersion = parts[1];
517            foundPackageFolder = currentPackageFolder;
518          }
519        }
520      }
521    }
522    return foundPackageFolder;
523  }
524
525  /**
526   * Add an already fetched package to the cache
527   */
528  @Override
529  public NpmPackage addPackageToCache(final String id, final String version, final InputStream packageTgzInputStream, final String sourceDesc) throws IOException {
530    checkValidVersionString(version, id);
531    return locks.getPackageLock(id + "#" + version).doWriteWithLock(() -> {
532
533      String tempDir = Utilities.generateUniqueRandomUUIDPath(cacheFolder.getAbsolutePath());
534
535      NpmPackage extractedNpm = NpmPackage.extractFromTgz(packageTgzInputStream, sourceDesc, tempDir, minimalMemory);
536
537      log("");
538      log("Installing " + id + "#" + version);
539
540      if ((extractedNpm.name() != null && id != null && !id.equalsIgnoreCase(extractedNpm.name()))) {
541        if (!suppressErrors && (!id.equals("hl7.fhir.r5.core") && !id.equals("hl7.fhir.us.immds"))) {// temporary work around
542          throw new IOException("Attempt to import a mis-identified package. Expected " + id + ", got " + extractedNpm.name());
543        }
544      }
545
546      NpmPackage npmPackage;
547      String packageRoot = Utilities.path(cacheFolder, id + "#" + version);
548      try {
549        if (!id.equals(extractedNpm.getNpm().asString("name")) || !version.equals(extractedNpm.getNpm().asString("version"))) {
550          if (!id.equals(extractedNpm.getNpm().asString("name"))) {
551            extractedNpm.getNpm().add("original-name", extractedNpm.getNpm().asString("name"));
552            extractedNpm.getNpm().remove("name");
553            extractedNpm.getNpm().add("name", id);
554          }
555          if (!version.equals(extractedNpm.getNpm().asString("version"))) {
556            extractedNpm.getNpm().add("original-version", extractedNpm.getNpm().asString("version"));
557            extractedNpm.getNpm().remove("version");
558            extractedNpm.getNpm().add("version", version);
559          }
560          FileUtilities.stringToFile(JsonParser.compose(extractedNpm.getNpm(), true), Utilities.path(tempDir, "package", "package.json"));
561        }
562
563        final NpmPackage tempPackage = loadPackageInfo(tempDir);
564        if (tempPackage != null && !tempPackage.isIndexed()) {
565          tempPackage.checkIndexed(packageRoot);
566        }
567
568        if (!ManagedFileAccess.file(packageRoot).exists() || Utilities.existsInList(version, "current", "dev")) {
569          FileUtilities.createDirectory(packageRoot);
570          try {
571            FileUtilities.clearDirectory(packageRoot);
572          } catch (Throwable t) {
573            log("Unable to clear directory: " + packageRoot + ": " + t.getMessage() + " - this may cause problems later");
574          }
575          FileUtilities.renameDirectory(tempDir, packageRoot);
576
577          npmPackage = loadPackageInfo(packageRoot);
578
579          log(" done.");
580        } else {
581          FileUtilities.clearDirectory(tempDir);
582          ManagedFileAccess.file(tempDir).delete();
583        }
584        npmPackage = loadPackageInfo(packageRoot);
585
586      } catch (Exception e) {
587        try {
588          // don't leave a half extracted package behind
589          log("Clean up package " + packageRoot + " because installation failed: " + e.getMessage());
590          e.printStackTrace();
591          FileUtilities.clearDirectory(packageRoot);
592          ManagedFileAccess.file(packageRoot).delete();
593        } catch (Exception ignored) {
594          // nothing
595        }
596        throw e;
597      }
598      return npmPackage;
599    }, lockParameters);
600  }
601
602  private void log(String s) {
603    if (!silent) {
604      System.out.println(s);
605    }
606  }
607
608  @Override
609  public String getPackageUrl(String packageId) throws IOException {
610    String result = super.getPackageUrl(packageId);
611    if (result == null) {
612      result = ciBuildClient.getPackageUrl(packageId);
613    }
614    return result;
615  }
616
617  /**
618   * do not use this in minimal memory mode
619   * @param packagesFolder
620   * @throws IOException
621   */
622  public void loadFromFolder(String packagesFolder) throws IOException {
623    assert !minimalMemory;
624
625    File[] files = ManagedFileAccess.file(packagesFolder).listFiles();
626    if (files != null) {
627      for (File f : files) {
628        if (f.getName().endsWith(".tgz")) {
629          FileInputStream fs = ManagedFileAccess.inStream(f);
630          try {
631            temporaryPackages.add(NpmPackage.fromPackage(fs));
632          } finally {
633            fs.close();
634          }
635        }
636      }
637    }
638  }
639
640  @Override
641  public NpmPackage loadPackage(String id, String version) throws FHIRException, IOException {
642    //ok, try to resolve locally
643    if (!Utilities.noString(version) && version.startsWith("file:")) {
644      return loadPackageFromFile(id, version.substring(5));
645    }
646
647    if (version == null && id.contains("#")) {
648      version = id.substring(id.indexOf("#") + 1);
649      id = id.substring(0, id.indexOf("#"));
650    }
651
652    if (version == null) {
653      try {
654        version = getLatestVersion(id);
655      } catch (Exception e) {
656        version = null;
657      }
658    }
659    NpmPackage p = loadPackageFromCacheOnly(id, version);
660    if (p != null) {
661      if ("current".equals(version)) {
662        p = nullIfNotCurrentPackage(id, p);
663      }
664      if (p != null)
665        return p;
666    }
667
668    if ("dev".equals(version)) {
669      p = loadPackageFromCacheOnly(id, "current");
670      p = nullIfNotCurrentPackage(id, p);
671      if (p != null)
672        return p;
673      version = "current";
674    }
675
676    log("Installing " + id + "#" + (version == null ? "?" : version) + " to the package cache");
677    log("  Fetching:");
678
679    // nup, don't have it locally (or it's expired)
680    FilesystemPackageCacheManager.InputStreamWithSrc source;
681    if (false && packageProvider != null && packageProvider.handlesPackage(id, version)) {
682      source = packageProvider.provide(id, version);
683    } else if (Utilities.isAbsoluteUrl(version)) {
684      source = fetchSourceFromUrlSpecific(version);
685    } else if ("current".equals(version) || (version != null && version.startsWith("current$"))) {
686      // special case - fetch from ci-build server
687      source = ciBuildClient.loadFromCIBuild(id, version.startsWith("current$") ? version.substring(8) : null);
688    } else {
689      source = loadFromPackageServer(id, version);
690    }
691    if (source == null) {
692      throw new FHIRException("Unable to find package " + id + "#" + version);
693    }
694    return addPackageToCache(id, source.version, source.stream, source.url);
695  }
696
697  private InputStreamWithSrc fetchSourceFromUrlSpecific(String url) {
698    return new InputStreamWithSrc(fetchFromUrlSpecific(url, false), url, "current");
699  }
700
701  private InputStream fetchFromUrlSpecific(String source, boolean optional) throws FHIRException {
702    try {
703      HTTPResult res = ManagedWebAccess.get(Arrays.asList("web"), source);
704      res.checkThrowException();
705      return new ByteArrayInputStream(res.getContent());
706    } catch (Exception e) {
707      if (optional)
708        return null;
709      else
710        throw new FHIRException("Unable to fetch: " + e.getMessage(), e);
711    }
712  }
713
714
715
716  @Override
717  public String getPackageId(String canonicalUrl) throws IOException {
718    String retVal = findCanonicalInLocalCache(canonicalUrl);
719
720    if (retVal == null) {
721      retVal = super.getPackageId(canonicalUrl);
722    }
723
724    if (retVal == null) {
725      retVal = ciBuildClient.getPackageId(canonicalUrl);
726    }
727
728    return retVal;
729  }
730
731
732  public String findCanonicalInLocalCache(String canonicalUrl) {
733    try {
734      for (String pf : listPackages()) {
735        if (ManagedFileAccess.file(Utilities.path(cacheFolder, pf, "package", "package.json")).exists()) {
736          JsonObject npm = JsonParser.parseObjectFromFile(Utilities.path(cacheFolder, pf, "package", "package.json"));
737          if (canonicalUrl.equals(npm.asString("canonical"))) {
738            return npm.asString("name");
739          }
740        }
741      }
742    } catch (IOException e) {
743    }
744    return null;
745  }
746
747  // ========================= Package Mgmt API =======================================================================
748
749  /**
750   * Checks https://
751   *
752   * @param id
753   * @param npmPackage
754   * @return
755   */
756  private NpmPackage nullIfNotCurrentPackage(String id, NpmPackage npmPackage) {
757    // special case: current versions roll over, and we have to check their currency
758    try {
759      return ciBuildClient.isCurrent(id, npmPackage) ? npmPackage : null;
760    } catch (Exception e) {
761      log("Unable to check package currency: " + id + ": " + id);
762    }
763    return npmPackage;
764  }
765
766  // ----- the old way, from before package server, while everything gets onto the package server
767  private InputStreamWithSrc fetchTheOldWay(String id, String v) {
768    String url = getUrlForPackage(id);
769    if (url == null) {
770      try {
771        url = ciBuildClient.getPackageUrl(id);
772      } catch (Exception ignored) {
773
774      }
775    }
776    if (url == null) {
777      throw new FHIRException("Unable to resolve package id " + id + "#" + v);
778    }
779    if (url.contains("/ImplementationGuide/")) {
780      url = url.substring(0, url.indexOf("/ImplementationGuide/"));
781    }
782    String pu = Utilities.pathURL(url, "package-list.json");
783
784    PackageList pl;
785    try {
786      pl = PackageList.fromUrl(pu);
787    } catch (Exception e) {
788      String pv = Utilities.pathURL(url, v, "package.tgz");
789      try {
790        return new InputStreamWithSrc(fetchFromUrlSpecific(pv, false), pv, v);
791      } catch (Exception e1) {
792        throw new FHIRException("Error fetching package directly (" + pv + "), or fetching package list for " + id + " from " + pu + ": " + e1.getMessage(), e1);
793      }
794    }
795    if (!id.equals(pl.pid()))
796      throw new FHIRException("Package ids do not match in " + pu + ": " + id + " vs " + pl.pid());
797    for (PackageListEntry vo : pl.versions()) {
798      if (v.equals(vo.version())) {
799
800        String u = Utilities.pathURL(vo.path(), "package.tgz");
801        return new InputStreamWithSrc(fetchFromUrlSpecific(u, true), u, v);
802      }
803    }
804
805    return null;
806  }
807
808
809  // ---------- Current Build SubSystem --------------------------------------------------------------------------------------
810
811  private String fetchVersionTheOldWay(String id) throws IOException {
812    String url = getUrlForPackage(id);
813    if (url == null) {
814      try {
815        url = ciBuildClient.getPackageUrl(id);
816      } catch (Exception e) {
817        url = null;
818      }
819    }
820    if (url == null) {
821      throw new FHIRException("Unable to resolve package id " + id);
822    }
823    PackageList pl = PackageList.fromUrl(Utilities.pathURL(url, "package-list.json"));
824    if (!id.equals(pl.pid()))
825      throw new FHIRException("Package ids do not match in " + pl.source() + ": " + id + " vs " + pl.pid());
826    for (PackageListEntry vo : pl.versions()) {
827      if (vo.current()) {
828        return vo.version();
829      }
830    }
831
832    return null;
833  }
834
835  private String getUrlForPackage(String id) {
836    if (CommonPackages.ID_XVER.equals(id)) {
837      return "https://fhir.org/packages/hl7.fhir.xver-extensions";
838    }
839    return null;
840  }
841
842  public List<String> listPackages() {
843    List<String> res = new ArrayList<>();
844    for (File f : cacheFolder.listFiles()) {
845      if (f.isDirectory() && f.getName().contains("#")) {
846        res.add(f.getName());
847      }
848    }
849    return res;
850  }
851
852  public interface CacheLockFunction<T> {
853    T get() throws IOException;
854  }
855
856
857
858
859
860  public boolean packageExists(String id, String ver) throws IOException {
861    if (packageInstalled(id, ver)) {
862      return true;
863    }
864    for (PackageServer s : getPackageServers()) {
865      if (new PackageClient(s).exists(id, ver)) {
866        return true;
867      }
868    }
869    return false;
870  }
871
872  public boolean packageInstalled(String id, String version) {
873    for (NpmPackage p : temporaryPackages) {
874      if (p.name().equals(id) && ("current".equals(version) || "dev".equals(version) || p.version().equals(version))) {
875        return true;
876      }
877      if (p.name().equals(id) && Utilities.noString(version)) {
878        return true;
879      }
880    }
881
882    for (String f : Utilities.sorted(cacheFolder.list())) {
883      if (f.equals(id + "#" + version) || (Utilities.noString(version) && f.startsWith(id + "#"))) {
884        return true;
885      }
886    }
887    if ("dev".equals(version))
888      return packageInstalled(id, "current");
889    else
890      return false;
891  }
892
893  public boolean isSuppressErrors() {
894    return suppressErrors;
895  }
896
897  public void setSuppressErrors(boolean suppressErrors) {
898    this.suppressErrors = suppressErrors;
899  }
900
901  public static IPackageProvider getPackageProvider() {
902    return packageProvider;
903  }
904
905  public static void setPackageProvider(IPackageProvider packageProvider) {
906    FilesystemPackageCacheManager.packageProvider = packageProvider;
907  }
908
909
910}