Skip to content

Refactor GraphHopper class #1895

Open
Open

Description

@karussell

Requirements:

  • avoid inheritance
  • avoid mutability
  • better extension possibilities (no inheritance needed, see proposal)
  • better support public transit use case
  • separate reader and writer to easier support two scenarios of 1. create and query and 2. load and query
  • allow to add CH/LM profiles even after import (no need for upfront config)
  • simpler LM/CHPreparationHandler
  • view storage not as cache but more as database and also be able to load config from this database?

First proposal: https://github.com/graphhopper/graphhopper/compare/experiment_gh_class

Related: #1492

Activity

  1. added this to the 2.0 milestone on Feb 10, 2020
  2. easbar commented on Feb 12, 2020

    @easbar
    Member

    separate reader and writer to easier support two scenarios of 1. create and query and 2. load and query

    I am not sure if this is the optimal separation. I think what should be separated from each other is creating/loading the graph&preparations and using the graph (routing). For example LM/CHPreparationHandler mixes both: Its partly about creating the preparations (reading prepare.ch/lm.weightings configuration, creating CH/LMProfile, creating the PrepareLandmark/ContractionHierarchies classes and even doing the actual preparation (using thread executioner etc.). And then they are used also to create the algorithms which is something different imo. In many cases you probably do the import/preparation once and from this point you are just loading the graph and use it to do the routing. In a Desktop/mobile setup you might even do this on two different devices (import server and mobile app). So in my opinion this is where we should start splitting the code into two different parts. Starting with PrepareLandmark/PrepareContractionHierarchies and LM/CHPreparationHandler and then extracting a class from GraphHopper that receives the loaded graph+preparations and just does the routing. I started doing this here #1901

  3. modified the milestones: 2.0, 3.0 on Sep 29, 2020
  4. removed this from the 3.0 milestone on Feb 10, 2021
  5. easbar commented on Oct 21, 2021

    @easbar
    Member

    Disclaimer: Thinking out loud and writing down a few findings for later reference here

    I think the next thing that we need to fix is that GraphHopper uses the same code for importing a new graph and loading an existing one. Take a look at what we currently do:

    First we call GraphHopper#init() or GraphHopper#setXYZ. These are the two ways we can use to initialize a GraphHopper instance. This is probably also something that we should change, but not the main issue IMO. Mixing these two is not supported (even though this is not really enforced), except a few exceptions. For example we have to use the setter to set the TagParserFactory even when we use init() for everything else. An important detail is that init() builds the EncodingManager, but when we use the setters it is built later in load().

    Next we call importOrLoad (or just load). There is no import() method yet. But let's take a look at what importOrLoad does: if (!load()) process(false). So let's take a closer look at load() and process:

    public boolean load() {
    if (isEmpty(ghLocation))
    throw new IllegalStateException("GraphHopperLocation is not specified. Call setGraphHopperLocation or init before");
    if (fullyLoaded)
    throw new IllegalStateException("graph is already successfully loaded");

    Ok (whatever...)

    File tmpFileOrFolder = new File(ghLocation);
    if (!tmpFileOrFolder.isDirectory() && tmpFileOrFolder.exists()) {
    throw new IllegalArgumentException("GraphHopperLocation cannot be an existing file. Has to be either non-existing or a folder.");
    } else {
    File compressed = new File(ghLocation + ".ghz");
    if (compressed.exists() && !compressed.isDirectory()) {
    try {
    new Unzipper().unzip(compressed.getAbsolutePath(), ghLocation, removeZipped);
    } catch (IOException ex) {
    throw new RuntimeException("Couldn't extract file " + compressed.getAbsolutePath()
    + " to " + ghLocation, ex);
    }
    }
    }

    If the ghLocation is a .ghz file we unpack it. Skipping the discussion whether this feature is needed here or not, note that this only makes sense if we are loading, but at this point we don't know whether we are loading or importing, so we need to write code that handles both situations. Imagine we wanted to add a forceOverwrite option to delete and overwrite an existing -gh folder instead of throwing an error in case the given folder already existed. If we knew that we were on the 'import path' this would totally make sense, but on the 'loading path' this parameter would be pointless. And there are many more such parameters that only make sense for one of the two cases as we will see.

    if (!allowWrites && dataAccessType.isMMap())
    dataAccessType = DAType.MMAP_RO;

    Not entirely sure about this one, but if we knew we would be loading anything other than read-only would not make sense anyway, and if we knew we were importing read-only, or allowWrites=false would be non-sensical.

    if (encodingManager == null) {
    StorableProperties properties = new StorableProperties(new GHDirectory(ghLocation, dataAccessType));
    encodingManager = properties.loadExisting()
    ? EncodingManager.create(emBuilder, encodedValueFactory, flagEncoderFactory, properties)
    : buildEncodingManager(new GraphHopperConfig());
    }

    Now it gets interesting: First of all the encodingManager == null check is equivalent to checking whether or not init() was called or not. So staring at this code we not only have to consider the two scenarios (load or import), but we also need to consider whether we used the init() method or not (and probably used the various setters instead). The properties.loadExisting check is used to find out whether we are importing or loading. We could easily get rid of this if we knew what we were doing. Also note that in case we did use init() we completely ignore the properties file up until now and then need to check whether the 'encoding matches' later... Why? Because we run init() again not knowing whether we do an import or we are loading an existing graph. There is more to discuss about this code, c.f. #2438, but let's continue.

    GHDirectory dir = new GHDirectory(ghLocation, dataAccessType);
    ghStorage = new GraphHopperStorage(dir, encodingManager, hasElevation(), encodingManager.needsTurnCostsSupport(), defaultSegmentSize);
    checkProfilesConsistency();
    // todo: move this after base graph loading/import, just like for LM. there is no real reason we have to setup CH before
    if (chPreparationHandler.isEnabled()) {
    List<CHConfig> chConfigs = createCHConfigs(chPreparationHandler.getCHProfiles());
    ghStorage.addCHGraphs(chConfigs);
    }

    hasElevation() only depends on the GraphHopper configuration and ignores whether or not a (possibly) existing graph is 3D or not. If we knew whether we were importing or loading we could decide whether the stored elevation or the configured value should be used. Better yet, if we knew we were loading there should not even be a hasElevation configuration flag in the configuration, because this can not be changed anymore anyway. Same with turn cost support and segment size. We are loading data from disk that has this information, but we have to provide that information so it matches the existing data. Unfortunately this situation occurs frequently in GraphHopper code. Let's ignore the todo here as this is again something else to discuss (see #2388).

    if (!new File(ghLocation).exists())
    return false;

    Oh, we are in the load method and after doing all of the above, we now realize there is nothing to load. So let's take a little detour: We return from this method and go back to importOrLoad where we call process. process is rather straight-forward (in the context of what I am explaining here), it basically runs the OSM import and calls postProcessing.

    Meanwhile in load (in case there was something to load) we do:

    GHLock lock = null;
    try {
    // create locks only if writes are allowed, if they are not allowed a lock cannot be created
    // (e.g. on a read only filesystem locks would fail)
    if (ghStorage.getDirectory().getDefaultType().isStoring() && isAllowWrites()) {
    lockFactory.setLockDir(new File(ghLocation));
    lock = lockFactory.create(fileLockName, false);
    if (!lock.tryLock())
    throw new RuntimeException("To avoid reading partial data we need to obtain the read lock but it failed. In " + ghLocation, lock.getObtainFailedReason());
    }
    if (!ghStorage.loadExisting())
    return false;

    Ignoring the lockfile, we basically load the existing graph data (makes sense, because we already checked we are not running a fresh import before).

    Now the 'import' and 'load' paths are back together in postProcessing and we have to keep on writing code that handles both situations:

    protected void postProcessing(boolean closeEarly) {
    initLocationIndex();
    importPublicTransit();
    if (lmPreparationHandler.isEnabled())
    loadOrPrepareLM(closeEarly);
    if (chPreparationHandler.isEnabled())
    chPreparationHandler.createPreparations(ghStorage);
    if (isCHPrepared()) {
    // check loaded profiles
    for (CHProfile profile : chPreparationHandler.getCHProfiles()) {
    if (!getProfileVersion(profile.getProfile()).equals("" + profilesByName.get(profile.getProfile()).getVersion()))
    throw new IllegalArgumentException("CH preparation of " + profile.getProfile() + " already exists in storage and doesn't match configuration");
    }
    } else {
    prepareCH(closeEarly);
    }
    }

    initLocationIndex, importPublicTransit, loadOrPrepareLM all apply some kind of "if there is data already do this and otherwise do that" logic, with the same consequences that I mentioned above: At any point of the code we have to keep in mind that we might be on one or the other code path and there are lots of parameters, objects etc. around that only make sense in one of the two cases.

    It is basically impossible to read/understand this code without reading it line by line and considering what has happened before we got to a certain line. And really I see no reason why we have to do this. The code paths should just be separated from the very beginning:

    if (GH exists)
       load()
    else
       import()

    This is the one thing I think we should be aiming for right now when we consider refactoring the GraphHopper class. Once we have this it should be trivial to export an Importer class that just gets an import configuration and does the import and some code that loads an existing -gh folder. And once we have this I think the GraphHopper class will be so trivial that we can either delete it entirely or use it as minimal high-level convenience code with hardly any functionality. To do this the biggest tasks will probably be splitting 'loading' from 'importing' code in EncodingManager, FlagEncoder, CH/LMPreparationHandler and GraphHopperStorage. So far I think we can at least achieve this without touching the create/loadExisting() pattern in DataAccess, but eventually I like to get rid of the 'import or load' theme on this level as well.

  6. easbar commented on Jun 20, 2022

    @easbar
    Member

    This is also something that needs to be fixed:

    c79bb96

    We should either remove all the setters and initialize the import (or router) using a configuration object (GraphHopperConfig currently), or we should provide setters (or similar) for everything and use some code snippet that reads the config file and translates this into calls of these setters.

    And actually we are making progress here. I think once we stop building the encoding manager in init() here: #2607 it should be possible to split GraphHopper into Importer and Loader.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions