Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reduce memory usage for raster source handling. #5572

Merged
merged 16 commits into from
Nov 14, 2019
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
- CHANGED: allow routing past `barrier=arch` [#5352](https://github.com/Project-OSRM/osrm-backend/pull/5352)
- CHANGED: default car weight was reduced to 2000 kg. [#5371](https://github.com/Project-OSRM/osrm-backend/pull/5371)
- CHANGED: default car height was reduced to 2 meters. [#5389](https://github.com/Project-OSRM/osrm-backend/pull/5389)
- Misc:
- CHANGED: Reduce memory usage for raster source handling. [#5572](https://github.com/Project-OSRM/osrm-backend/pull/5572)

# 5.21.0
- Changes from 5.20.0
Expand Down
77 changes: 51 additions & 26 deletions include/extractor/raster_source.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,23 @@
#include "util/coordinate.hpp"
#include "util/exception.hpp"

#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/assert.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/foreach.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/qi_int.hpp>

#include <storage/io.hpp>

#include <iostream>
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

seems the header is not used. Is this a left-over from debugging?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for your check and comment.
I will remove it after confirmation.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi, Mr. DennisOSRM,
Thanks for your strong support.
May I ask you to proceed reviewing?
I have already modified the code and committed.
Best Regards,
Tomonobu Saito

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looks good from my side 👍

#include <iterator>
#include <list>
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

seems the header is not used. Is this a left-over from debugging?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for your check and comment.
I will remove it after confirmation.

#include <string>
#include <unordered_map>
using namespace std;

namespace osrm
{
Expand Down Expand Up @@ -43,37 +50,31 @@ class RasterGrid
xdim = _xdim;
ydim = _ydim;
_data.reserve(ydim * xdim);
BOOST_ASSERT(ydim * xdim <= _data.capacity());

// Construct FileReader
storage::io::FileReader file_reader(filepath, storage::io::FileReader::HasNoFingerprint);

std::string buffer;
buffer.resize(file_reader.GetSize());

BOOST_ASSERT(buffer.size() > 1);

file_reader.ReadInto(&buffer[0], buffer.size());

boost::algorithm::trim(buffer);

auto itr = buffer.begin();
auto end = buffer.end();

bool r = false;
try
{
r = boost::spirit::qi::parse(
itr, end, +boost::spirit::qi::int_ % +boost::spirit::qi::space, _data);
}
catch (std::exception const &ex)
{
throw util::exception("Failed to read from raster source " + filepath.string() + ": " +
ex.what() + SOURCE_REF);
}
buffer.resize(xdim * 11); // INT32_MAX = 2147483647 = 10 chars + 1 white space = 11
BOOST_ASSERT(xdim * 11 <= buffer.size());

if (!r || itr != end)
for (unsigned int y = 0; y < ydim; y++)
{
throw util::exception("Failed to parse raster source: " + filepath.string() +
SOURCE_REF);
// read one line from file.
file_reader.ReadLine(&buffer[0], xdim * 11);
boost::algorithm::trim(buffer);

std::vector<std::string> result;
boost::split(
result, buffer, boost::is_any_of(" \r\n\0"), boost::algorithm::token_compress_on);
unsigned int x = 0;
for (const auto &s : result)
{
if (x < xdim)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi!
Do we need this check if we will cover it with BOOST_ASSERT(x == xdim); ? Maybe this check can also be assertion?
I'm not confident with the file format and maybe it is normal to have more values in row than we expect in header: then assertion is not valid.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi,
Thanks for your comment.

I afraid the difference of width (= the number of pixels) between actual raster file and setting in lua.
Especially, if (width of actual file) < (setting in lua) then we will face buffer overflow reading.
As you know, the result is not defined (beyond of control).

To avoid this situation, I put the if (x < xdim) checking, just in case.
If you prefer to remove this checking, I can remove.

Which do you prefer?
a) leave if (x < xdim) just in case.
b) remove. we believe user's setting in lua :)

Best Regards,
Tomonobu Saito

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

HI! Thank you for the explanation.
Now I understand that we got xdim setting from the lua profile and it can be a source of mistakes.
I think we should keep this check.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi,
Thanks for your comment.
OK, I keep this modification.

_data[(y * xdim) + x] = atoi(s.c_str());
++x;
}
BOOST_ASSERT(x == xdim);
}
}

Expand Down Expand Up @@ -143,8 +144,32 @@ class RasterContainer
RasterDatum GetRasterInterpolateFromSource(unsigned int source_id, double lon, double lat);

private:
};

// << singletone >> RasterCache
class RasterCache
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do you design this class as a singleton?
It seems that it will be used only inside the RasterContainer. And RasterContainer has one instance in Lua scripting environment. I think you can make it as a regular class or even implement this logic in RasterContainer class.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi,
Thanks for your check and comment.

This is most important point of my pull request.
In original code, LoadedSources and LoadedSourcePaths are owned by RasterContainer class.
osrm-extract create more than one RasterContainer instances, and this causes more than one time to load same raster file (with rasterbot.lua).
My first idea is to change LoadesSources and LoadedSourcePaths to static.
But this cases "double free" problem. see error log at below URL, you can find "double free or corrption (fasttop)" error.
https://travis-ci.org/Project-OSRM/osrm-backend/jobs/593429031?utm_medium=notification&utm_source=github_status
This is the reason I introduce the singletone pattern.
Singletone can solve these two problems.

  • Multiple load of same raster file.
  • Double free error.

Best Regards,
Tomonobu Saito

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi!
Thank you for the detailed explanation.

It seems that RasterContainer binds directly to the lua functions https://github.com/Project-OSRM/osrm-backend/blob/master/src/extractor/scripting_environment_lua.cpp#L188
So isn't it a lua problem that the profile creates several containers?

Copy link
Author

@Tomonobu3110 Tomonobu3110 Nov 8, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi,
Thanks for your comment.

This is usage of raster:load in the lua file (rasterbot.lua).
https://github.com/Project-OSRM/osrm-backend/blob/master/profiles/rasterbot.lua

I think we cannot avoid to create more than one RasterContainer instance, since setup() is called more than one time during osrm-extract (according to checking the log of osrm-extract).
But, just in case, I will check the possibility to avoid creating multiple RasterContainer by lua file.
Then, I will update the comment.

Best Regards,
Tomonobu Saito.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi,

The instance of RasterContainer is created at here.
https://github.com/Project-OSRM/osrm-backend/blob/master/include/extractor/scripting_environment_lua.hpp#L38

So, we cannot control the creation of RasterContainer instance in lua files (such as rasterbot.lua).

Best Regards,
Tomonobu Saito.

Copy link
Author

@Tomonobu3110 Tomonobu3110 Nov 8, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi,

I briefly checked scripting_environment_lua.{hpp|cpp}.
I think one LuaScriptingContext instance is created for every threads.
So, the number of instance of LuaScriptingContext is equal to the number of threads osrm-extract uses.
RasterContainer is member of LuaScriptingContext.
There is no doubt the number of RasterContainer is equal to the number of LuaScriptingContext.
This cannot control in lua file (such as rasterbot.lua).

If we want to avoid multiple load of same raster file, there are two strategies.
A) Use singletone pattern to reuse same resource from multiple thread. (This is my strategy.)
B) Share single LuaScriptingContext by all threads.
I think B has very big impact for current architecture design.

Best Regards,
Tomonobu Saito.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi,

thank you for this research. Now I am not against A) strategy. Can you add a briefly comment before this class to avoid confusion of future readers?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi,
Thanks for your checking and comment.
Yes, I will add a comment then commit again.

{
public:
// class method to get the instance
static RasterCache &getInstance()
{
if (NULL == g_instance)
{
g_instance = new RasterCache();
gardster marked this conversation as resolved.
Show resolved Hide resolved
}
return *g_instance;
}
// get reference of cache
std::vector<RasterSource> &getLoadedSources() { return LoadedSources; }
std::unordered_map<std::string, int> &getLoadedSourcePaths() { return LoadedSourcePaths; }
private:
// constructor
RasterCache() = default;
// member
std::vector<RasterSource> LoadedSources;
std::unordered_map<std::string, int> LoadedSourcePaths;
// the instance
static RasterCache *g_instance;
};
}
}
Expand Down
35 changes: 17 additions & 18 deletions include/storage/io.hpp
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
#include "util/log.hpp"
#include "util/version.hpp"

#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/iostreams/device/array.hpp>
#include <boost/iostreams/seek.hpp>
Expand Down Expand Up @@ -60,29 +61,27 @@ class FileReader

std::size_t GetSize()
{
const boost::filesystem::ifstream::pos_type position = input_stream.tellg();
input_stream.seekg(0, std::ios::end);
const boost::filesystem::ifstream::pos_type file_size = input_stream.tellg();

if (file_size == boost::filesystem::ifstream::pos_type(-1))
const boost::filesystem::path path(filepath);
try
{
throw util::RuntimeError("Unable to determine file size for " +
std::string(filepath.string()),
ErrorCode::FileIOError,
SOURCE_REF,
std::strerror(errno));
return std::size_t(boost::filesystem::file_size(path)) -
((fingerprint == FingerprintFlag::VerifyFingerprint) ? sizeof(util::FingerPrint)
: 0);
}

// restore the current position
input_stream.seekg(position, std::ios::beg);

if (fingerprint == FingerprintFlag::VerifyFingerprint)
catch (boost::filesystem::filesystem_error &ex)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

consider adding const

Copy link
Author

@Tomonobu3110 Tomonobu3110 Nov 8, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi, thanks for your comment.
I will add const (since ex should be read-only).

{
return std::size_t(file_size) - sizeof(util::FingerPrint);
std::cout << ex.what() << std::endl;
throw;
}
else
}

/* Read one line */
template <typename T> void ReadLine(T *dest, const std::size_t count)
{
if (0 < count)
{
return file_size;
memset(dest, 0, count * sizeof(T));
input_stream.getline(reinterpret_cast<char *>(dest), count * sizeof(T));
}
}

Expand Down
26 changes: 15 additions & 11 deletions src/extractor/raster_source.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -92,15 +92,15 @@ int RasterContainer::LoadRasterSource(const std::string &path_string,
const auto _ymin = static_cast<std::int32_t>(util::toFixed(util::FloatLatitude{ymin}));
const auto _ymax = static_cast<std::int32_t>(util::toFixed(util::FloatLatitude{ymax}));

const auto itr = LoadedSourcePaths.find(path_string);
if (itr != LoadedSourcePaths.end())
const auto itr = RasterCache::getInstance().getLoadedSourcePaths().find(path_string);
if (itr != RasterCache::getInstance().getLoadedSourcePaths().end())
{
util::Log() << "[source loader] Already loaded source '" << path_string << "' at source_id "
<< itr->second;
return itr->second;
}

int source_id = static_cast<int>(LoadedSources.size());
int source_id = static_cast<int>(RasterCache::getInstance().getLoadedSources().size());

util::Log() << "[source loader] Loading from " << path_string << " ... ";
TIMER_START(loading_source);
Expand All @@ -116,8 +116,8 @@ int RasterContainer::LoadRasterSource(const std::string &path_string,

RasterSource source{std::move(rasterData), ncols, nrows, _xmin, _xmax, _ymin, _ymax};
TIMER_STOP(loading_source);
LoadedSourcePaths.emplace(path_string, source_id);
LoadedSources.push_back(std::move(source));
RasterCache::getInstance().getLoadedSourcePaths().emplace(path_string, source_id);
RasterCache::getInstance().getLoadedSources().push_back(std::move(source));

util::Log() << "[source loader] ok, after " << TIMER_SEC(loading_source) << "s";

Expand All @@ -127,10 +127,11 @@ int RasterContainer::LoadRasterSource(const std::string &path_string,
// External function for looking up nearest data point from a specified source
RasterDatum RasterContainer::GetRasterDataFromSource(unsigned int source_id, double lon, double lat)
{
if (LoadedSources.size() < source_id + 1)
if (RasterCache::getInstance().getLoadedSources().size() < source_id + 1)
{
throw util::exception("Attempted to access source " + std::to_string(source_id) +
", but there are only " + std::to_string(LoadedSources.size()) +
", but there are only " +
std::to_string(RasterCache::getInstance().getLoadedSources().size()) +
" loaded" + SOURCE_REF);
}

Expand All @@ -139,7 +140,7 @@ RasterDatum RasterContainer::GetRasterDataFromSource(unsigned int source_id, dou
BOOST_ASSERT(lon < 180);
BOOST_ASSERT(lon > -180);

const auto &found = LoadedSources[source_id];
const auto &found = RasterCache::getInstance().getLoadedSources()[source_id];
return found.GetRasterData(static_cast<std::int32_t>(util::toFixed(util::FloatLongitude{lon})),
static_cast<std::int32_t>(util::toFixed(util::FloatLatitude{lat})));
}
Expand All @@ -148,10 +149,11 @@ RasterDatum RasterContainer::GetRasterDataFromSource(unsigned int source_id, dou
RasterDatum
RasterContainer::GetRasterInterpolateFromSource(unsigned int source_id, double lon, double lat)
{
if (LoadedSources.size() < source_id + 1)
if (RasterCache::getInstance().getLoadedSources().size() < source_id + 1)
{
throw util::exception("Attempted to access source " + std::to_string(source_id) +
", but there are only " + std::to_string(LoadedSources.size()) +
", but there are only " +
std::to_string(RasterCache::getInstance().getLoadedSources().size()) +
" loaded" + SOURCE_REF);
}

Expand All @@ -160,10 +162,12 @@ RasterContainer::GetRasterInterpolateFromSource(unsigned int source_id, double l
BOOST_ASSERT(lon < 180);
BOOST_ASSERT(lon > -180);

const auto &found = LoadedSources[source_id];
const auto &found = RasterCache::getInstance().getLoadedSources()[source_id];
return found.GetRasterInterpolate(
static_cast<std::int32_t>(util::toFixed(util::FloatLongitude{lon})),
static_cast<std::int32_t>(util::toFixed(util::FloatLatitude{lat})));
}

RasterCache *RasterCache::g_instance = NULL;
}
}