src/cli/MeasureManager.cpp
| Line | Branch | Exec | Source |
|---|---|---|---|
| 1 | /*********************************************************************************************************************** | ||
| 2 | * OpenStudio(R), Copyright (c) Alliance for Energy Innovation, LLC. | ||
| 3 | * See also https://openstudio.net/license | ||
| 4 | ***********************************************************************************************************************/ | ||
| 5 | |||
| 6 | #include "MeasureManager.hpp" | ||
| 7 | #include "../utilities/bcl/RemoteBCL.hpp" | ||
| 8 | #include "../utilities/bcl/BCLMeasure.hpp" | ||
| 9 | #include "../utilities/core/Checksum.hpp" | ||
| 10 | #include "../utilities/core/Filesystem.hpp" | ||
| 11 | #include "../utilities/core/FilesystemHelpers.hpp" | ||
| 12 | #include "../utilities/core/StringHelpers.hpp" | ||
| 13 | #include "../utilities/time/DateTime.hpp" | ||
| 14 | #include "../osversion/VersionTranslator.hpp" | ||
| 15 | #include "../energyplus/ForwardTranslator.hpp" | ||
| 16 | #include "../utilities/bcl/LocalBCL.hpp" | ||
| 17 | #include "../utilities/idf/ValidityEnums.hpp" | ||
| 18 | #include <utilities/idd/IddEnums.hxx> | ||
| 19 | #include "../measure/OSMeasure.hpp" | ||
| 20 | #include "../measure/ModelMeasure.hpp" | ||
| 21 | #include "../measure/EnergyPlusMeasure.hpp" | ||
| 22 | #include "../measure/ReportingMeasure.hpp" | ||
| 23 | #include "../measure/OSArgument.hpp" | ||
| 24 | #include "../measure/OSOutput.hpp" | ||
| 25 | #include "../measure/OSRunner.hpp" | ||
| 26 | #include "../measure/OSMeasureInfoGetter.hpp" | ||
| 27 | #include "../model/Model_Impl.hpp" // For casting | ||
| 28 | #include "../../ruby/interpreter/RubyException.hpp" | ||
| 29 | |||
| 30 | #include <json/json.h> | ||
| 31 | #include <fmt/format.h> | ||
| 32 | #include <httplib.h> | ||
| 33 | #include <json/value.h> | ||
| 34 | #include <pugixml.hpp> | ||
| 35 | |||
| 36 | #include <sstream> | ||
| 37 | #include <utility> // make_pair | ||
| 38 | #include <cstdio> | ||
| 39 | |||
| 40 | namespace openstudio { | ||
| 41 | |||
| 42 | namespace { | ||
| 43 | |||
| 44 | ✗ | std::string toJSONString(const Json::Value& json) { | |
| 45 | ✗ | Json::StreamWriterBuilder builder; | |
| 46 | ✗ | builder["indentation"] = ""; | |
| 47 | ✗ | builder["commentStyle"] = "None"; | |
| 48 | ✗ | return Json::writeString(builder, json); | |
| 49 | ✗ | } | |
| 50 | |||
| 51 | ✗ | std::string toJSONString(const std::string& s) { | |
| 52 | ✗ | return toJSONString(Json::Value(s)); | |
| 53 | } | ||
| 54 | |||
| 55 | // This just participates in overload resolution, otherwise it's ambiguous since Json::Value and std::string are constructible from char * | ||
| 56 | ✗ | std::string toJSONString(const char* s) { | |
| 57 | ✗ | return toJSONString(Json::Value(s)); | |
| 58 | } | ||
| 59 | |||
| 60 | ✗ | Json::Value parseJsonBody(const std::string& body_str) { | |
| 61 | ✗ | Json::Value result; | |
| 62 | ✗ | if (!body_str.empty()) { | |
| 63 | ✗ | Json::CharReaderBuilder reader; | |
| 64 | ✗ | std::string errs; | |
| 65 | ✗ | std::istringstream ss(body_str); | |
| 66 | ✗ | Json::parseFromStream(reader, ss, &result, &errs); | |
| 67 | ✗ | } | |
| 68 | ✗ | return result; | |
| 69 | ✗ | } | |
| 70 | |||
| 71 | template <typename T> | ||
| 72 | boost::optional<T> get_field(const Json::Value& body, const std::string& field_name); | ||
| 73 | |||
| 74 | template <> | ||
| 75 | ✗ | boost::optional<std::string> get_field(const Json::Value& body, const std::string& field_name) { | |
| 76 | ✗ | if (body.isMember(field_name) && body[field_name].isString()) { | |
| 77 | ✗ | return body[field_name].asString(); | |
| 78 | } | ||
| 79 | ✗ | return boost::none; | |
| 80 | } | ||
| 81 | |||
| 82 | template <> | ||
| 83 | ✗ | boost::optional<openstudio::path> get_field(const Json::Value& body, const std::string& field_name) { | |
| 84 | ✗ | if (body.isMember(field_name) && body[field_name].isString()) { | |
| 85 | ✗ | return openstudio::path(body[field_name].asString()); | |
| 86 | } | ||
| 87 | ✗ | return boost::none; | |
| 88 | } | ||
| 89 | |||
| 90 | template <> | ||
| 91 | ✗ | [[maybe_unused]] boost::optional<bool> get_field(const Json::Value& body, const std::string& field_name) { | |
| 92 | ✗ | if (body.isMember(field_name) && body[field_name].isBool()) { | |
| 93 | ✗ | return body[field_name].asBool(); | |
| 94 | } | ||
| 95 | ✗ | return boost::none; | |
| 96 | } | ||
| 97 | |||
| 98 | template <typename T> | ||
| 99 | T get_field(const Json::Value& body, const std::string& field_name, const T& defaultValue); | ||
| 100 | |||
| 101 | template <> | ||
| 102 | ✗ | std::string get_field(const Json::Value& body, const std::string& field_name, const std::string& defaultValue) { | |
| 103 | ✗ | if (body.isMember(field_name) && body[field_name].isString()) { | |
| 104 | ✗ | return body[field_name].asString(); | |
| 105 | } | ||
| 106 | ✗ | return defaultValue; | |
| 107 | } | ||
| 108 | |||
| 109 | template <> | ||
| 110 | ✗ | openstudio::path get_field(const Json::Value& body, const std::string& field_name, const openstudio::path& defaultValue) { | |
| 111 | ✗ | if (body.isMember(field_name) && body[field_name].isString()) { | |
| 112 | ✗ | return openstudio::path(body[field_name].asString()); | |
| 113 | } | ||
| 114 | ✗ | return defaultValue; | |
| 115 | } | ||
| 116 | |||
| 117 | template <> | ||
| 118 | ✗ | bool get_field(const Json::Value& body, const std::string& field_name, const bool& defaultValue) { | |
| 119 | ✗ | if (body.isMember(field_name) && body[field_name].isBool()) { | |
| 120 | ✗ | return body[field_name].asBool(); | |
| 121 | } | ||
| 122 | ✗ | return defaultValue; | |
| 123 | } | ||
| 124 | |||
| 125 | } // namespace | ||
| 126 | |||
| 127 | ✗ | MeasureManager::MeasureManager(ScriptEngineInstance& t_rubyEngine, ScriptEngineInstance& t_pythonEngine) | |
| 128 | ✗ | : rubyEngine(t_rubyEngine), pythonEngine(t_pythonEngine) { | |
| 129 | // rubyEngine->exec("puts 'Hello from ruby'"); | ||
| 130 | // pythonEngine->exec("print('Hello from python')"); | ||
| 131 | ✗ | } | |
| 132 | // : | ||
| 133 | // #if USE_RUBY_ENGINE | ||
| 134 | // rubyEngine(t_rubyEngine), | ||
| 135 | // #endif | ||
| 136 | // #if USE_PYTHON_ENGINE | ||
| 137 | // pythonEngine(t_pythonEngine) | ||
| 138 | // #endif | ||
| 139 | // { | ||
| 140 | // } | ||
| 141 | |||
| 142 | ✗ | Json::Value MeasureManager::internalState() const { | |
| 143 | ✗ | Json::Value result(Json::objectValue); | |
| 144 | |||
| 145 | ✗ | Json::Value osms(Json::arrayValue); | |
| 146 | ✗ | for (const auto& [k, v] : m_osms) { | |
| 147 | ✗ | Json::Value osmInfo(Json::objectValue); | |
| 148 | ✗ | osmInfo["osm_path"] = k.generic_string(); | |
| 149 | ✗ | osmInfo["checksum"] = v.checksum; | |
| 150 | ✗ | osms.append(std::move(osmInfo)); | |
| 151 | ✗ | } | |
| 152 | ✗ | result["osms"] = std::move(osms); | |
| 153 | |||
| 154 | ✗ | Json::Value idfs(Json::arrayValue); | |
| 155 | ✗ | for (const auto& [k, v] : m_idfs) { | |
| 156 | ✗ | Json::Value idfInfo(Json::objectValue); | |
| 157 | ✗ | idfInfo["idf_path"] = k.generic_string(); | |
| 158 | ✗ | idfInfo["checksum"] = v.checksum; | |
| 159 | ✗ | idfs.append(std::move(idfInfo)); | |
| 160 | ✗ | } | |
| 161 | ✗ | result["idfs"] = std::move(idfs); | |
| 162 | |||
| 163 | // Json::Value measures(Json::arrayValue); | ||
| 164 | ✗ | auto& measures = result["measures"]; | |
| 165 | ✗ | measures = Json::arrayValue; | |
| 166 | ✗ | for (const auto& [measureDirPath, bclMeasureInfo] : m_measures) { | |
| 167 | ✗ | Json::Value mInfo(Json::objectValue); | |
| 168 | ✗ | measures.append(bclMeasureInfo.measure.toJSON()); | |
| 169 | ✗ | } | |
| 170 | |||
| 171 | ✗ | auto& measureInfos = result["measure_info"]; | |
| 172 | ✗ | measureInfos = Json::arrayValue; | |
| 173 | // Json::Value measureInfos(Json::arrayValue); | ||
| 174 | ✗ | for (const auto& [measureDirPath, bclMeasureInfo] : m_measures) { | |
| 175 | ✗ | for (const auto& [osmOrIdfPath, measureInfo] : bclMeasureInfo.measureInfos) { | |
| 176 | ✗ | Json::Value mInfo(Json::objectValue); | |
| 177 | ✗ | mInfo["measureDirPath"] = measureDirPath.generic_string(); | |
| 178 | ✗ | mInfo["osm_path"] = osmOrIdfPath.generic_string(); | |
| 179 | ✗ | auto& args = mInfo["arguments"]; | |
| 180 | ✗ | for (const auto& arg : measureInfo.bclMeasureArguments()) { | |
| 181 | ✗ | args.append(arg.toJSON()); | |
| 182 | ✗ | } | |
| 183 | |||
| 184 | ✗ | measureInfos.append(std::move(mInfo)); | |
| 185 | ✗ | } | |
| 186 | } | ||
| 187 | // result["measure_info"] = std::move(measureInfos); | ||
| 188 | |||
| 189 | ✗ | return result; | |
| 190 | ✗ | } | |
| 191 | |||
| 192 | ✗ | size_t MeasureManager::clearMeasureInfoForOsmorIdfPath(const openstudio::path& osmOrIdfPath) { | |
| 193 | ✗ | size_t totalRemoved = 0; | |
| 194 | ✗ | for (auto& [key, value] : m_measures) { | |
| 195 | ✗ | totalRemoved += value.measureInfos.erase(osmOrIdfPath); | |
| 196 | } | ||
| 197 | ✗ | return totalRemoved; | |
| 198 | } | ||
| 199 | |||
| 200 | ✗ | boost::optional<OSMInfo> MeasureManager::getModel(const openstudio::path& osmPath, bool force_reload) { | |
| 201 | |||
| 202 | ✗ | if (!openstudio::filesystem::is_regular_file(osmPath)) { | |
| 203 | ✗ | fmt::print("Model '{}' does not exist\n", osmPath.generic_string()); | |
| 204 | ✗ | m_osms.erase(osmPath); | |
| 205 | ✗ | clearMeasureInfoForOsmorIdfPath(osmPath); | |
| 206 | ✗ | return boost::none; | |
| 207 | } | ||
| 208 | |||
| 209 | ✗ | OSMInfo current; | |
| 210 | ✗ | current.checksum = openstudio::checksum(osmPath); | |
| 211 | |||
| 212 | ✗ | if (!force_reload) { | |
| 213 | ✗ | auto it = m_osms.find(osmPath); | |
| 214 | ✗ | if (it != m_osms.end()) { | |
| 215 | ✗ | auto& cached = it->second; | |
| 216 | ✗ | if (current.checksum == cached.checksum) { | |
| 217 | ✗ | fmt::print("Using cached model {}\n", osmPath.generic_string()); | |
| 218 | ✗ | return cached; | |
| 219 | } else { | ||
| 220 | ✗ | fmt::print("Checksum of cached model does not match current checksum for '{}'\n", osmPath.generic_string()); | |
| 221 | } | ||
| 222 | } | ||
| 223 | } | ||
| 224 | |||
| 225 | ✗ | clearMeasureInfoForOsmorIdfPath(osmPath); | |
| 226 | |||
| 227 | ✗ | fmt::print("Attempting to load model '{}'\n", osmPath.generic_string()); | |
| 228 | ✗ | openstudio::osversion::VersionTranslator vt; | |
| 229 | ✗ | if (auto model_ = vt.loadModel(osmPath)) { | |
| 230 | ✗ | fmt::print("Successfully loaded model '{}'\n", osmPath.generic_string()); | |
| 231 | ✗ | current.model = std::move(*model_); | |
| 232 | ✗ | openstudio::energyplus::ForwardTranslator ft; | |
| 233 | ✗ | current.workspace = ft.translateModel(current.model); | |
| 234 | ✗ | auto [it, ok] = m_osms.insert_or_assign(osmPath, std::move(current)); | |
| 235 | ✗ | return it->second; | |
| 236 | ✗ | } | |
| 237 | |||
| 238 | ✗ | fmt::print("Failed to load model '{}'\n", osmPath.generic_string()); | |
| 239 | ✗ | m_osms.erase(osmPath); | |
| 240 | |||
| 241 | ✗ | return boost::none; | |
| 242 | ✗ | } | |
| 243 | |||
| 244 | ✗ | boost::optional<IDFInfo> MeasureManager::getIdf(const openstudio::path& idfPath, bool force_reload) { | |
| 245 | |||
| 246 | ✗ | if (!openstudio::filesystem::is_regular_file(idfPath)) { | |
| 247 | ✗ | fmt::print("Idf '{}' does not exist\n", idfPath.generic_string()); | |
| 248 | ✗ | m_idfs.erase(idfPath); | |
| 249 | ✗ | clearMeasureInfoForOsmorIdfPath(idfPath); | |
| 250 | ✗ | return boost::none; | |
| 251 | } | ||
| 252 | |||
| 253 | ✗ | IDFInfo current; | |
| 254 | ✗ | current.checksum = openstudio::checksum(idfPath); | |
| 255 | |||
| 256 | ✗ | if (!force_reload) { | |
| 257 | ✗ | auto it = m_idfs.find(idfPath); | |
| 258 | ✗ | if (it != m_idfs.end()) { | |
| 259 | ✗ | auto& cached = it->second; | |
| 260 | ✗ | if (current.checksum == cached.checksum) { | |
| 261 | ✗ | fmt::print("Using cached workspace {}\n", idfPath.generic_string()); | |
| 262 | ✗ | return cached; | |
| 263 | } else { | ||
| 264 | ✗ | fmt::print("Checksum of cached workspace does not match current checksum for '{}'\n", idfPath.generic_string()); | |
| 265 | } | ||
| 266 | } | ||
| 267 | } | ||
| 268 | |||
| 269 | ✗ | clearMeasureInfoForOsmorIdfPath(idfPath); | |
| 270 | |||
| 271 | ✗ | fmt::print("Attempting to load idf '{}'\n", idfPath.generic_string()); | |
| 272 | ✗ | if (auto workspace_ = openstudio::Workspace::load(idfPath, openstudio::IddFileType::EnergyPlus)) { | |
| 273 | ✗ | fmt::print("Successfully loaded idf '{}'\n", idfPath.generic_string()); | |
| 274 | |||
| 275 | ✗ | if (workspace_->isValid(openstudio::StrictnessLevel::Draft)) { | |
| 276 | ✗ | current.workspace = std::move(*workspace_); | |
| 277 | ✗ | auto [it, ok] = m_idfs.insert_or_assign(idfPath, std::move(current)); | |
| 278 | ✗ | return it->second; | |
| 279 | } else { | ||
| 280 | ✗ | fmt::print("Workspace loaded from '{}' is not valid to Draft StrictnessLevel\n", idfPath.generic_string()); | |
| 281 | } | ||
| 282 | } else { | ||
| 283 | ✗ | fmt::print("Failed to load idf '{}'\n", idfPath.generic_string()); | |
| 284 | ✗ | } | |
| 285 | |||
| 286 | ✗ | m_idfs.erase(idfPath); | |
| 287 | |||
| 288 | ✗ | return boost::none; | |
| 289 | ✗ | } | |
| 290 | |||
| 291 | ✗ | boost::optional<BCLMeasure> MeasureManager::getMeasure(const openstudio::path& measureDirPath, bool force_reload) { | |
| 292 | |||
| 293 | ✗ | const auto& measureDirPathStr = measureDirPath.string(); | |
| 294 | |||
| 295 | // check if measure exists on disk | ||
| 296 | ✗ | if (!openstudio::filesystem::is_directory(measureDirPath)) { | |
| 297 | ✗ | fmt::print("Measure '{}' does not exist.\n", measureDirPathStr); | |
| 298 | ✗ | m_measures.erase(measureDirPath); | |
| 299 | ✗ | return boost::none; | |
| 300 | } | ||
| 301 | ✗ | if (!openstudio::filesystem::is_regular_file(measureDirPath / "measure.xml")) { | |
| 302 | ✗ | fmt::print("Measure directory '{}' exists but does not have a measure.xml.\n", measureDirPathStr); | |
| 303 | ✗ | m_measures.erase(measureDirPath); | |
| 304 | ✗ | return boost::none; | |
| 305 | } | ||
| 306 | |||
| 307 | ✗ | BCLMeasureInfo* measureInfo_ = nullptr; | |
| 308 | ✗ | if (!force_reload) { | |
| 309 | ✗ | auto it = m_measures.find(measureDirPath); | |
| 310 | ✗ | if (it != m_measures.end()) { | |
| 311 | ✗ | measureInfo_ = &(it->second); | |
| 312 | ✗ | fmt::print("Using cached measure {}\n", measureDirPath.generic_string()); | |
| 313 | } | ||
| 314 | } | ||
| 315 | |||
| 316 | ✗ | if (!measureInfo_) { | |
| 317 | ✗ | m_measures.erase(measureDirPath); | |
| 318 | |||
| 319 | // load from disk | ||
| 320 | ✗ | fmt::print("Attempting to load measure '{}'\n", measureDirPathStr); | |
| 321 | |||
| 322 | ✗ | boost::optional<BCLMeasure> measure_ = openstudio::BCLMeasure::load(measureDirPath); | |
| 323 | |||
| 324 | ✗ | if (!measure_) { | |
| 325 | ✗ | fmt::print("Failed to load measure '{}'\n", measureDirPathStr); | |
| 326 | ✗ | return boost::none; | |
| 327 | } | ||
| 328 | ✗ | fmt::print("Successfully loaded measure '{}'\n", measureDirPathStr); | |
| 329 | ✗ | auto [it, ok] = m_measures.insert({measureDirPath, BCLMeasureInfo{std::move(*measure_)}}); | |
| 330 | ✗ | measureInfo_ = &(it->second); | |
| 331 | ✗ | } | |
| 332 | |||
| 333 | ✗ | auto& measure = measureInfo_->measure; | |
| 334 | |||
| 335 | // see if there are updates, want to make sure to perform both checks so do outside of conditional | ||
| 336 | ✗ | bool file_updates = measure.checkForUpdatesFiles(); // checks if any files have been updated | |
| 337 | ✗ | bool xml_updates = measure.checkForUpdatesXML(); // only checks if xml as loaded has been changed since last save | |
| 338 | |||
| 339 | ✗ | auto readmeInPath = measureDirPath / "README.md.erb"; | |
| 340 | ✗ | auto readmeOutPath = measureDirPath / "README.md"; | |
| 341 | |||
| 342 | ✗ | const bool hasReadmeIn = openstudio::filesystem::is_regular_file(readmeInPath); | |
| 343 | ✗ | const bool hasReadmeOut = openstudio::filesystem::is_regular_file(readmeOutPath); | |
| 344 | ✗ | const bool readme_out_of_date = hasReadmeIn && !hasReadmeOut; | |
| 345 | |||
| 346 | // TODO: try catch like in measure_manager.rb? | ||
| 347 | ✗ | bool missing_fields = measure.missingRequiredFields(); | |
| 348 | |||
| 349 | ✗ | if (file_updates || xml_updates || missing_fields || readme_out_of_date) { | |
| 350 | ✗ | fmt::print("Changes detected, updating '{}'\n", measureDirPathStr); | |
| 351 | |||
| 352 | // Clear cache before calling getMeasureInfo | ||
| 353 | ✗ | measureInfo_->measureInfos.clear(); | |
| 354 | |||
| 355 | ✗ | openstudio::measure::OSMeasureInfo info = getMeasureInfo(measureDirPath, measure, openstudio::path{}); | |
| 356 | ✗ | info.update(measure); | |
| 357 | |||
| 358 | ✗ | if (hasReadmeIn) { | |
| 359 | ✗ | if (hasReadmeOut) { | |
| 360 | ✗ | openstudio::filesystem::remove(readmeOutPath); | |
| 361 | } | ||
| 362 | ✗ | ScriptObject measureInfoBindingObject; | |
| 363 | try { | ||
| 364 | ✗ | measureInfoBindingObject = rubyEngine->eval("OpenStudio::Measure::RubyMeasureInfoBinding.new()"); | |
| 365 | ✗ | } catch (const RubyException& e) { | |
| 366 | ✗ | auto msg = fmt::format("Failed to instantiate a RubyMeasureInfoBinding: {}\nlocation={}", e.what(), e.location()); | |
| 367 | ✗ | fmt::print(stderr, "{}\n", msg); | |
| 368 | ✗ | LOG_AND_THROW(msg); | |
| 369 | ✗ | } | |
| 370 | ✗ | auto* measureInfoBindingPtr = rubyEngine->getAs<openstudio::measure::MeasureInfoBinding*>(measureInfoBindingObject); | |
| 371 | ✗ | measureInfoBindingPtr->setMeasureInfo(info); | |
| 372 | ✗ | const bool result = measureInfoBindingPtr->renderFile(readmeInPath.generic_string()); | |
| 373 | ✗ | if (result) { | |
| 374 | // check for file updates again | ||
| 375 | ✗ | file_updates = measure.checkForUpdatesFiles(); | |
| 376 | } else { | ||
| 377 | ✗ | fmt::print(stderr, "Failed to generate the README.md via ERB\n"); | |
| 378 | } | ||
| 379 | ✗ | } | |
| 380 | |||
| 381 | // Save the xml file with changes triggered by checkForUpdatesFiles() / checkForUpdatesXML() above | ||
| 382 | ✗ | measure.save(); | |
| 383 | ✗ | } | |
| 384 | |||
| 385 | ✗ | return measure; | |
| 386 | ✗ | } | |
| 387 | |||
| 388 | ✗ | openstudio::measure::OSMeasureInfo MeasureManager::getMeasureInfo(const openstudio::path& measureDirPath, const BCLMeasure& measure, | |
| 389 | const openstudio::path& osmOrIdfPath, const boost::optional<model::Model>& model_, | ||
| 390 | const boost::optional<Workspace>& workspace_) { | ||
| 391 | |||
| 392 | ✗ | if (!m_measures.contains(measureDirPath)) { | |
| 393 | ✗ | LOG_AND_THROW("Measure isn't recorded in m_measures, that should NOT happen"); | |
| 394 | } | ||
| 395 | ✗ | auto& bclMeasureInfo = m_measures.at(measureDirPath); | |
| 396 | ✗ | auto it2 = bclMeasureInfo.measureInfos.find(osmOrIdfPath); | |
| 397 | ✗ | if (it2 != bclMeasureInfo.measureInfos.end()) { | |
| 398 | ✗ | fmt::print("Using cached OSMeasureInfo for '{}', '{}'\n", measureDirPath.generic_string(), osmOrIdfPath.generic_string()); | |
| 399 | ✗ | return it2->second; | |
| 400 | } | ||
| 401 | |||
| 402 | ✗ | auto scriptPath_ = measure.primaryScriptPath(); | |
| 403 | ✗ | if (!scriptPath_) { | |
| 404 | throw std::runtime_error( | ||
| 405 | ✗ | fmt::format("Unable to locate primary Ruby script path for BCLMeasure '{}' located at '{}'", measure.name(), measureDirPath.generic_string())); | |
| 406 | } | ||
| 407 | |||
| 408 | ✗ | auto getOrCreateModel = [this, &model_, &osmOrIdfPath]() -> openstudio::model::Model { | |
| 409 | ✗ | if (model_) { | |
| 410 | // model should already have been cloned in the endpoint, so no need to do it twice | ||
| 411 | ✗ | return *model_; // _->clone(true).cast<openstudio::model::Model>(); | |
| 412 | ✗ | } else if (!osmOrIdfPath.empty()) { | |
| 413 | // TODO: not sure we want to keep this here or not.. | ||
| 414 | ✗ | if (auto osmInfo_ = getModel(osmOrIdfPath)) { | |
| 415 | ✗ | return osmInfo_->model.clone().cast<openstudio::model::Model>(); | |
| 416 | } else { | ||
| 417 | ✗ | LOG_AND_THROW("Failed to load the Model at " << osmOrIdfPath); | |
| 418 | ✗ | } | |
| 419 | } else { | ||
| 420 | ✗ | return {}; | |
| 421 | } | ||
| 422 | ✗ | }; | |
| 423 | |||
| 424 | ✗ | auto getOrCreateWorkspace = [this, &workspace_, &osmOrIdfPath]() -> openstudio::Workspace { | |
| 425 | ✗ | if (workspace_) { | |
| 426 | ✗ | return *workspace_; // ->clone(true); | |
| 427 | ✗ | } else if (!osmOrIdfPath.empty()) { | |
| 428 | ✗ | if (auto idfInfo_ = getIdf(osmOrIdfPath)) { | |
| 429 | ✗ | return idfInfo_->workspace.clone(); | |
| 430 | } else { | ||
| 431 | ✗ | LOG_AND_THROW("Failed to load the Model at " << osmOrIdfPath); | |
| 432 | ✗ | } | |
| 433 | } else { | ||
| 434 | ✗ | return {openstudio::StrictnessLevel::Draft, openstudio::IddFileType::EnergyPlus}; | |
| 435 | } | ||
| 436 | ✗ | }; | |
| 437 | |||
| 438 | ✗ | ScriptEngineInstance* thisEngine = nullptr; | |
| 439 | ✗ | const MeasureLanguage measureLanguage = measure.measureLanguage(); | |
| 440 | ✗ | if (measureLanguage == MeasureLanguage::Ruby) { | |
| 441 | ✗ | thisEngine = &rubyEngine; | |
| 442 | ✗ | } else if (measureLanguage == MeasureLanguage::Python) { | |
| 443 | ✗ | thisEngine = &pythonEngine; | |
| 444 | } | ||
| 445 | |||
| 446 | ✗ | std::string className = (*thisEngine)->inferMeasureClassName(*scriptPath_); | |
| 447 | ✗ | fmt::print("className={}\n", className); | |
| 448 | ✗ | if (className.empty()) { | |
| 449 | // TODO: could also just fallback on trusting the BCLXML is up to date with respect to the class name and use BCLMeasure::className() | ||
| 450 | ✗ | auto msg = fmt::format("Failed to infer measure name from '{}'", scriptPath_->generic_string()); | |
| 451 | ✗ | fmt::print(stderr, "{}\n", msg); | |
| 452 | ✗ | return openstudio::measure::OSMeasureInfo(msg); | |
| 453 | ✗ | } | |
| 454 | ✗ | ScriptObject measureScriptObject = (*thisEngine)->loadMeasure(*scriptPath_, className); | |
| 455 | ✗ | if (measureScriptObject.empty()) { | |
| 456 | ✗ | auto msg = fmt::format("Failed to load measure '{}' from '{}'\n", className, scriptPath_->generic_string()); | |
| 457 | ✗ | fmt::print(stderr, "{}\n", msg); | |
| 458 | ✗ | return openstudio::measure::OSMeasureInfo(msg); | |
| 459 | ✗ | } | |
| 460 | |||
| 461 | ✗ | MeasureType measureType; | |
| 462 | |||
| 463 | ✗ | std::string name; | |
| 464 | ✗ | std::string description; | |
| 465 | ✗ | std::string taxonomy; | |
| 466 | ✗ | std::string modelerDescription; | |
| 467 | |||
| 468 | ✗ | std::vector<measure::OSArgument> arguments; | |
| 469 | ✗ | std::vector<measure::OSOutput> outputs; | |
| 470 | |||
| 471 | try { | ||
| 472 | ✗ | auto* osMeasurePtr = (*thisEngine)->getAs<openstudio::measure::OSMeasure*>(measureScriptObject); | |
| 473 | ✗ | measureType = osMeasurePtr->measureType(); | |
| 474 | ✗ | fmt::print("measureType={}\n", measureType.valueName()); | |
| 475 | |||
| 476 | ✗ | if (measureType == MeasureType::ModelMeasure) { | |
| 477 | ✗ | auto* measurePtr = static_cast<openstudio::measure::ModelMeasure*>(osMeasurePtr); | |
| 478 | ✗ | name = measurePtr->name(); | |
| 479 | ✗ | description = measurePtr->description(); | |
| 480 | ✗ | taxonomy = measurePtr->taxonomy(); | |
| 481 | ✗ | modelerDescription = measurePtr->modeler_description(); | |
| 482 | |||
| 483 | ✗ | auto model = getOrCreateModel(); | |
| 484 | ✗ | arguments = measurePtr->arguments(model); | |
| 485 | ✗ | outputs = measurePtr->outputs(); | |
| 486 | |||
| 487 | ✗ | } else if (measureType == MeasureType::EnergyPlusMeasure) { | |
| 488 | ✗ | auto* measurePtr = static_cast<openstudio::measure::EnergyPlusMeasure*>(osMeasurePtr); | |
| 489 | ✗ | name = measurePtr->name(); | |
| 490 | ✗ | description = measurePtr->description(); | |
| 491 | ✗ | taxonomy = measurePtr->taxonomy(); | |
| 492 | ✗ | modelerDescription = measurePtr->modeler_description(); | |
| 493 | |||
| 494 | ✗ | auto workspace = getOrCreateWorkspace(); | |
| 495 | ✗ | arguments = measurePtr->arguments(workspace); | |
| 496 | ✗ | outputs = measurePtr->outputs(); | |
| 497 | ✗ | } else if (measureType == MeasureType::ReportingMeasure) { | |
| 498 | ✗ | auto* measurePtr = static_cast<openstudio::measure::ReportingMeasure*>(osMeasurePtr); | |
| 499 | ✗ | name = measurePtr->name(); | |
| 500 | ✗ | description = measurePtr->description(); | |
| 501 | ✗ | taxonomy = measurePtr->taxonomy(); | |
| 502 | ✗ | modelerDescription = measurePtr->modeler_description(); | |
| 503 | |||
| 504 | // TODO: for ruby at least, need to try the arity... model was added later, at 3.0.0 | ||
| 505 | ✗ | const int numArgs = (*thisEngine)->numberOfArguments(measureScriptObject, "arguments"); | |
| 506 | // fmt::print("numArgs={}\n", numArgs); | ||
| 507 | ✗ | if (numArgs == 0) { | |
| 508 | auto msg = fmt::format("Reporting Measure at '{}' is using the old format where the 'arguments' method does not take model. " | ||
| 509 | " Please consider updating this to `def arguments(model)`.", | ||
| 510 | ✗ | scriptPath_->generic_string()); | |
| 511 | ✗ | fmt::print("{}\n", msg); | |
| 512 | ✗ | if (measureLanguage == MeasureLanguage::Ruby) { | |
| 513 | auto patchArgumentsCmd = fmt::format(R"ruby( | ||
| 514 | module {0}Extensions | ||
| 515 | def arguments(model) | ||
| 516 | super() | ||
| 517 | end | ||
| 518 | end | ||
| 519 | |||
| 520 | class {0} | ||
| 521 | prepend {0}Extensions # the only change to above: prepend instead of include | ||
| 522 | end | ||
| 523 | )ruby", | ||
| 524 | ✗ | className); | |
| 525 | ✗ | rubyEngine->exec(patchArgumentsCmd); | |
| 526 | ✗ | arguments = measurePtr->arguments(openstudio::model::Model{}); | |
| 527 | ✗ | rubyEngine->exec(fmt::format("Object.send(:remove_const, :{}Extensions)", className)); | |
| 528 | ✗ | } else { | |
| 529 | auto msg = | ||
| 530 | ✗ | fmt::format("Wrong number of parameters for method `arguments`in measure '{}' from '{}'\n", className, scriptPath_->generic_string()); | |
| 531 | ✗ | fmt::print(stderr, "{}\n", msg); | |
| 532 | ✗ | return openstudio::measure::OSMeasureInfo(msg); | |
| 533 | ✗ | } | |
| 534 | ✗ | } else { | |
| 535 | ✗ | auto model = getOrCreateModel(); | |
| 536 | ✗ | arguments = measurePtr->arguments(model); | |
| 537 | ✗ | } | |
| 538 | ✗ | outputs = measurePtr->outputs(); | |
| 539 | |||
| 540 | } else { | ||
| 541 | ✗ | throw std::runtime_error("Unknown"); | |
| 542 | } | ||
| 543 | ✗ | } catch (const std::exception& e) { | |
| 544 | ✗ | auto msg = fmt::format("Failed to query information from measure '{}' from '{}': {}\n", className, scriptPath_->generic_string(), e.what()); | |
| 545 | ✗ | fmt::print(stderr, "{}\n", msg); | |
| 546 | ✗ | return openstudio::measure::OSMeasureInfo(msg); | |
| 547 | ✗ | } | |
| 548 | |||
| 549 | ✗ | if (name.empty()) { | |
| 550 | ✗ | name = className; | |
| 551 | } | ||
| 552 | |||
| 553 | ✗ | if (measureLanguage == MeasureLanguage::Ruby) { | |
| 554 | ✗ | rubyEngine->exec(fmt::format("Object.send(:remove_const, :{})", className)); | |
| 555 | } | ||
| 556 | |||
| 557 | ✗ | openstudio::measure::OSMeasureInfo info(measureType, className, name, description, taxonomy, modelerDescription, arguments, outputs); | |
| 558 | ✗ | auto [it, ok] = bclMeasureInfo.measureInfos.insert({osmOrIdfPath, std::move(info)}); | |
| 559 | ✗ | return it->second; | |
| 560 | ✗ | } | |
| 561 | |||
| 562 | ✗ | void MeasureManager::reset() { | |
| 563 | ✗ | m_osms.clear(); | |
| 564 | ✗ | m_idfs.clear(); | |
| 565 | ✗ | m_measures.clear(); | |
| 566 | ✗ | } | |
| 567 | |||
| 568 | ✗ | MeasureManagerServer::~MeasureManagerServer() { | |
| 569 | ✗ | close(); | |
| 570 | ✗ | } | |
| 571 | |||
| 572 | ✗ | MeasureManagerServer::MeasureManagerServer(unsigned port, ScriptEngineInstance& rubyEngine, ScriptEngineInstance& pythonEngine) | |
| 573 | ✗ | : m_measureManager(rubyEngine, pythonEngine), | |
| 574 | ✗ | m_url(fmt::format("http://localhost:{}/", port)), | |
| 575 | ✗ | m_port(port), | |
| 576 | ✗ | my_measures_dir(openstudio::filesystem::home_path() / "OpenStudio/Measures") { | |
| 577 | |||
| 578 | #if (defined(_WIN32) || defined(_WIN64)) | ||
| 579 | // localhost May be slower on Windows due to DNS resolution delays: https://github.com/yhirose/cpp-httplib/#performance-note-for-local-connections | ||
| 580 | m_host = "127.0.0.1"; | ||
| 581 | #else | ||
| 582 | // Works for 127.0.0.1, 0.0.0.0 and localhost on TCP4 | ||
| 583 | ✗ | m_host = "127.0.0.1"; | |
| 584 | #endif | ||
| 585 | |||
| 586 | ✗ | m_server = std::make_unique<httplib::Server>(); | |
| 587 | // Single-threaded pool ensures serial execution — Ruby/Python engines are not thread-safe | ||
| 588 | ✗ | m_server->new_task_queue = [] { return new httplib::ThreadPool(1, 1); }; | |
| 589 | ✗ | m_server->Get(".*", [this](const httplib::Request& req, httplib::Response& res) { handle_get(req, res); }); | |
| 590 | ✗ | m_server->Post(".*", [this](const httplib::Request& req, httplib::Response& res) { handle_post(req, res); }); | |
| 591 | ✗ | } | |
| 592 | |||
| 593 | ✗ | bool MeasureManagerServer::open() { | |
| 594 | ✗ | return m_server->bind_to_port(m_host, static_cast<int>(m_port)); | |
| 595 | } | ||
| 596 | |||
| 597 | ✗ | bool MeasureManagerServer::close() { | |
| 598 | ✗ | m_server->stop(); | |
| 599 | ✗ | return true; | |
| 600 | } | ||
| 601 | |||
| 602 | ✗ | void MeasureManagerServer::unknown_endpoint(const httplib::Request& req, httplib::Response& res) { | |
| 603 | ✗ | res.status = httplib::StatusCode::NotFound_404; | |
| 604 | ✗ | res.set_content(toJSONString(fmt::format("Error, unknown path '{}'", req.path)), "application/json"); | |
| 605 | ✗ | } | |
| 606 | |||
| 607 | ✗ | void MeasureManagerServer::handle_get(const httplib::Request& req, httplib::Response& res) { | |
| 608 | ✗ | const std::string& uri = req.path; | |
| 609 | |||
| 610 | ✗ | if (uri == "/") { | |
| 611 | ✗ | handle_request(req, res, Json::Value{}, &MeasureManagerServer::status); | |
| 612 | ✗ | return; | |
| 613 | } | ||
| 614 | |||
| 615 | // Cpprestsdk has it's own json implementation..... | ||
| 616 | ✗ | if (uri == "/internal_state") { | |
| 617 | ✗ | handle_request(req, res, Json::Value{}, &MeasureManagerServer::internal_state); | |
| 618 | ✗ | return; | |
| 619 | } | ||
| 620 | |||
| 621 | ✗ | unknown_endpoint(req, res); | |
| 622 | } | ||
| 623 | |||
| 624 | ✗ | void MeasureManagerServer::handle_post(const httplib::Request& req, httplib::Response& res) { | |
| 625 | ✗ | const std::string& uri = req.path; | |
| 626 | |||
| 627 | ✗ | if (uri == "/reset") { | |
| 628 | ✗ | handle_request(req, res, Json::Value{}, &MeasureManagerServer::reset); | |
| 629 | ✗ | return; | |
| 630 | } | ||
| 631 | |||
| 632 | ✗ | if (uri == "/set") { | |
| 633 | // curl -H "Content-Type: application/json" -X POST --data '{"my_measures_dir": "/Users/julien/OpenStudio/Measures"}' http://localhost:8090/set | ||
| 634 | ✗ | auto body = parseJsonBody(req.body); | |
| 635 | ✗ | handle_request(req, res, body, &MeasureManagerServer::set); | |
| 636 | ✗ | return; | |
| 637 | ✗ | } | |
| 638 | |||
| 639 | ✗ | if (uri == "/download_bcl_measure") { | |
| 640 | ✗ | auto body = parseJsonBody(req.body); | |
| 641 | ✗ | handle_request(req, res, body, &MeasureManagerServer::download_bcl_measure); | |
| 642 | ✗ | return; | |
| 643 | ✗ | } | |
| 644 | |||
| 645 | // TODO: for testing only, remove | ||
| 646 | ✗ | if (uri == "/get_model") { | |
| 647 | ✗ | auto body = parseJsonBody(req.body); | |
| 648 | ✗ | handle_request(req, res, body, &MeasureManagerServer::get_model); | |
| 649 | ✗ | return; | |
| 650 | ✗ | } | |
| 651 | |||
| 652 | ✗ | if (uri == "/bcl_measures") { | |
| 653 | ✗ | handle_request(req, res, Json::Value{}, &MeasureManagerServer::bcl_measures); | |
| 654 | ✗ | return; | |
| 655 | } | ||
| 656 | |||
| 657 | ✗ | if (uri == "/update_measures") { | |
| 658 | ✗ | auto body = parseJsonBody(req.body); | |
| 659 | ✗ | handle_request(req, res, body, &MeasureManagerServer::update_measures); | |
| 660 | ✗ | return; | |
| 661 | ✗ | } | |
| 662 | |||
| 663 | ✗ | if (uri == "/compute_arguments") { | |
| 664 | ✗ | auto body = parseJsonBody(req.body); | |
| 665 | ✗ | handle_request(req, res, body, &MeasureManagerServer::compute_arguments); | |
| 666 | ✗ | return; | |
| 667 | ✗ | } | |
| 668 | |||
| 669 | ✗ | if (uri == "/create_measure") { | |
| 670 | ✗ | auto body = parseJsonBody(req.body); | |
| 671 | ✗ | handle_request(req, res, body, &MeasureManagerServer::create_measure); | |
| 672 | ✗ | return; | |
| 673 | ✗ | } | |
| 674 | |||
| 675 | ✗ | if (uri == "/duplicate_measure") { | |
| 676 | ✗ | auto body = parseJsonBody(req.body); | |
| 677 | ✗ | handle_request(req, res, body, &MeasureManagerServer::duplicate_measure); | |
| 678 | ✗ | return; | |
| 679 | ✗ | } | |
| 680 | |||
| 681 | ✗ | unknown_endpoint(req, res); | |
| 682 | } | ||
| 683 | |||
| 684 | ✗ | MeasureManagerServer::ResponseType MeasureManagerServer::status([[maybe_unused]] const Json::Value& body) { | |
| 685 | ✗ | Json::Value result; | |
| 686 | ✗ | result["status"] = "running"; | |
| 687 | ✗ | result["my_measures_dir"] = my_measures_dir.generic_string(); | |
| 688 | ✗ | return {httplib::StatusCode::OK_200, toJSONString(result)}; | |
| 689 | ✗ | } | |
| 690 | |||
| 691 | ✗ | MeasureManagerServer::ResponseType MeasureManagerServer::internal_state([[maybe_unused]] const Json::Value& body) { | |
| 692 | ✗ | Json::Value result; | |
| 693 | ✗ | result["status"] = "running"; | |
| 694 | ✗ | result["my_measures_dir"] = my_measures_dir.generic_string(); | |
| 695 | |||
| 696 | ✗ | auto internalState = m_measureManager.internalState(); | |
| 697 | ✗ | for (const auto& key : internalState.getMemberNames()) { | |
| 698 | ✗ | result[key] = internalState[key]; | |
| 699 | ✗ | } | |
| 700 | |||
| 701 | ✗ | return {httplib::StatusCode::OK_200, toJSONString(result)}; | |
| 702 | ✗ | } | |
| 703 | |||
| 704 | ✗ | MeasureManagerServer::ResponseType MeasureManagerServer::reset([[maybe_unused]] const Json::Value& body) { | |
| 705 | ✗ | m_measureManager.reset(); | |
| 706 | ✗ | return {httplib::StatusCode::OK_200, toJSONString("Resetting internal state")}; | |
| 707 | ✗ | } | |
| 708 | |||
| 709 | ✗ | MeasureManagerServer::ResponseType MeasureManagerServer::set(const Json::Value& body) { | |
| 710 | ✗ | if (auto p_ = get_field<openstudio::path>(body, "my_measures_dir")) { | |
| 711 | ✗ | if (!openstudio::filesystem::is_directory(*p_)) { | |
| 712 | // Issue an error message | ||
| 713 | return {httplib::StatusCode::BadRequest_400, | ||
| 714 | ✗ | toJSONString(fmt::format("Error, my_measures_dir '{}' is a not a valid directory", p_->generic_string()))}; | |
| 715 | } | ||
| 716 | ✗ | this->my_measures_dir = std::move(*p_); | |
| 717 | ✗ | return {httplib::StatusCode::OK_200, toJSONString(Json::Value{})}; | |
| 718 | } else { | ||
| 719 | ✗ | return {httplib::StatusCode::BadRequest_400, toJSONString("Missing the my_measures_dir in the post data")}; | |
| 720 | ✗ | } | |
| 721 | ✗ | } | |
| 722 | |||
| 723 | ✗ | MeasureManagerServer::ResponseType MeasureManagerServer::download_bcl_measure(const Json::Value& body) { // NOLINT | |
| 724 | ✗ | if (auto uid_ = get_field<std::string>(body, "uid")) { | |
| 725 | ✗ | const RemoteBCL r; | |
| 726 | ✗ | if (auto bclMeasure_ = r.getMeasure(*uid_)) { | |
| 727 | ✗ | return {httplib::StatusCode::OK_200, toJSONString(bclMeasure_->toJSON())}; | |
| 728 | } else { | ||
| 729 | ✗ | return {httplib::StatusCode::BadRequest_400, toJSONString(fmt::format("Cannot find measure with uid='{}'", *uid_))}; | |
| 730 | ✗ | } | |
| 731 | ✗ | } else { | |
| 732 | ✗ | fmt::print("Missing the uid in the post data\n"); | |
| 733 | ✗ | return {httplib::StatusCode::BadRequest_400, toJSONString("Missing the uid in the post data")}; | |
| 734 | ✗ | } | |
| 735 | ✗ | } | |
| 736 | |||
| 737 | ✗ | MeasureManagerServer::ResponseType MeasureManagerServer::get_model(const Json::Value& body) { | |
| 738 | ✗ | if (auto osmPath_ = get_field<openstudio::path>(body, "osm_path")) { | |
| 739 | ✗ | auto osmInfo_ = m_measureManager.getModel(*osmPath_); | |
| 740 | ✗ | if (osmInfo_) { | |
| 741 | ✗ | return {httplib::StatusCode::OK_200, toJSONString(fmt::format("OK, loaded model with checksum {}", osmInfo_->checksum))}; | |
| 742 | } else { | ||
| 743 | ✗ | return {httplib::StatusCode::BadRequest_400, toJSONString(fmt::format("Wrong osm path: '{}'", osmPath_->generic_string()))}; | |
| 744 | } | ||
| 745 | ✗ | } else { | |
| 746 | ✗ | return {httplib::StatusCode::BadRequest_400, toJSONString("The 'osm_path' (string/path) must be in the post data")}; | |
| 747 | ✗ | } | |
| 748 | ✗ | } | |
| 749 | |||
| 750 | ✗ | MeasureManagerServer::ResponseType MeasureManagerServer::bcl_measures([[maybe_unused]] const Json::Value& body) { | |
| 751 | ✗ | const bool force_reload = false; // Not supposed to mess with the BCL Measures! | |
| 752 | ✗ | auto& localBCL = openstudio::LocalBCL::instance(); | |
| 753 | ✗ | Json::Value result(Json::arrayValue); | |
| 754 | ✗ | for (auto& measure : localBCL.measures()) { | |
| 755 | ✗ | auto measureDir = measure.directory(); | |
| 756 | ✗ | if (boost::optional<BCLMeasure> measure_ = m_measureManager.getMeasure(measureDir, force_reload)) { | |
| 757 | ✗ | result.append(measure_->toJSON()); | |
| 758 | } else { | ||
| 759 | ✗ | fmt::print("Directory '{}' is not a measure\n", measureDir.generic_string()); | |
| 760 | ✗ | } | |
| 761 | ✗ | } | |
| 762 | |||
| 763 | ✗ | return {httplib::StatusCode::OK_200, toJSONString(result)}; | |
| 764 | ✗ | } | |
| 765 | |||
| 766 | ✗ | MeasureManagerServer::ResponseType MeasureManagerServer::update_measures(const Json::Value& body) { | |
| 767 | ✗ | auto measuresDir = get_field<openstudio::path>(body, "measures_dir", my_measures_dir); | |
| 768 | ✗ | const bool force_reload = get_field<bool>(body, "force_reload", false); | |
| 769 | |||
| 770 | // Scan the directory for measures | ||
| 771 | ✗ | Json::Value result(Json::arrayValue); | |
| 772 | ✗ | for (const auto& dirEnt : openstudio::filesystem::directory_iterator{measuresDir}) { | |
| 773 | ✗ | if (openstudio::filesystem::is_directory(dirEnt)) { | |
| 774 | ✗ | const auto& measureDir = dirEnt.path(); | |
| 775 | ✗ | if (boost::optional<BCLMeasure> measure_ = m_measureManager.getMeasure(measureDir, force_reload)) { | |
| 776 | ✗ | result.append(measure_->toJSON()); | |
| 777 | } else { | ||
| 778 | ✗ | fmt::print("Directory '{}' is not a measure\n", measureDir.generic_string()); | |
| 779 | ✗ | } | |
| 780 | } | ||
| 781 | ✗ | } | |
| 782 | |||
| 783 | ✗ | return {httplib::StatusCode::OK_200, toJSONString(result)}; | |
| 784 | ✗ | } | |
| 785 | |||
| 786 | ✗ | MeasureManagerServer::ResponseType MeasureManagerServer::compute_arguments(const Json::Value& body) { | |
| 787 | ✗ | openstudio::path measureDir; | |
| 788 | ✗ | if (boost::optional<openstudio::path> p_ = get_field<openstudio::path>(body, "measure_dir")) { // Not passing a default value => optional | |
| 789 | ✗ | measureDir = std::move(*p_); | |
| 790 | } else { | ||
| 791 | ✗ | return {httplib::StatusCode::BadRequest_400, toJSONString("The 'measure_dir' (string) must be in the post data")}; | |
| 792 | ✗ | } | |
| 793 | |||
| 794 | // NOTE: this endpoint expects an OSM (even if it's an EnergyPlusMeasure), NOT an OSM or IDF like the CLI --compute_arguments flag does | ||
| 795 | ✗ | const openstudio::path osmPath = get_field<openstudio::path>(body, "osm_path", {}); // defaults to an empty path | |
| 796 | ✗ | bool has_valid_osm_path = false; | |
| 797 | ✗ | if (!osmPath.empty()) { | |
| 798 | ✗ | if (osmPath.extension() != ".osm") { | |
| 799 | auto msg = | ||
| 800 | ✗ | fmt::format("For /compute_arguments endpoint, parameter 'osm_path' must always be an '.osm' file, not '{}'", osmPath.generic_string()); | |
| 801 | ✗ | fmt::print(stderr, "{}\n", msg); | |
| 802 | ✗ | return {httplib::StatusCode::BadRequest_400, toJSONString(msg)}; | |
| 803 | ✗ | } | |
| 804 | ✗ | has_valid_osm_path = true; | |
| 805 | } | ||
| 806 | |||
| 807 | ✗ | const bool force_reload = get_field<bool>(body, "force_reload", false); | |
| 808 | |||
| 809 | ✗ | auto measure_ = m_measureManager.getMeasure(measureDir, force_reload); | |
| 810 | ✗ | if (!measure_) { | |
| 811 | ✗ | auto msg = fmt::format("Cannot load measure at '{}'", measureDir.generic_string()); | |
| 812 | ✗ | fmt::print(stderr, "{}\n", msg); | |
| 813 | ✗ | return {httplib::StatusCode::BadRequest_400, toJSONString(msg)}; | |
| 814 | ✗ | } | |
| 815 | |||
| 816 | ✗ | boost::optional<model::Model> model_; | |
| 817 | ✗ | boost::optional<Workspace> workspace_; | |
| 818 | |||
| 819 | ✗ | if (has_valid_osm_path) { | |
| 820 | ✗ | if (auto osmInfo_ = m_measureManager.getModel(osmPath, force_reload)) { | |
| 821 | // Clone and keep handles | ||
| 822 | ✗ | model_ = osmInfo_->model.clone(true).cast<openstudio::model::Model>(); | |
| 823 | ✗ | workspace_ = osmInfo_->workspace.clone(true); | |
| 824 | } else { | ||
| 825 | ✗ | auto msg = fmt::format("Cannot load model at '{}'", osmPath.generic_string()); | |
| 826 | ✗ | fmt::print(stderr, "{}\n", msg); | |
| 827 | ✗ | return {httplib::StatusCode::BadRequest_400, toJSONString(msg)}; | |
| 828 | ✗ | } | |
| 829 | } | ||
| 830 | |||
| 831 | ✗ | const openstudio::measure::OSMeasureInfo info = m_measureManager.getMeasureInfo(measureDir, *measure_, osmPath, model_, workspace_); | |
| 832 | ✗ | if (auto errorString_ = info.error()) { | |
| 833 | ✗ | return {httplib::StatusCode::OK_200, toJSONString(*errorString_)}; | |
| 834 | ✗ | } | |
| 835 | |||
| 836 | // TODO: maybe I should write an OSMeasureInfo::toJSON() method, but that'd be duplicating the code in BCLMeasure (BCLXML to be exact). | ||
| 837 | // So since the only thing that's different is the OSArgument (OSMeasureInfo) versus BCLMeasureArgument (BCLMeasure), we just override | ||
| 838 | ✗ | auto result = measure_->toJSON(); | |
| 839 | ✗ | if (has_valid_osm_path) { | |
| 840 | ✗ | auto& arguments = result["arguments"]; | |
| 841 | ✗ | arguments.clear(); | |
| 842 | ✗ | for (const measure::OSArgument& argument : info.arguments()) { | |
| 843 | ✗ | arguments.append(argument.toJSON()); | |
| 844 | ✗ | } | |
| 845 | } | ||
| 846 | |||
| 847 | ✗ | return {httplib::StatusCode::OK_200, toJSONString(result)}; | |
| 848 | ✗ | } | |
| 849 | |||
| 850 | ✗ | MeasureManagerServer::ResponseType MeasureManagerServer::create_measure(const Json::Value& body) { | |
| 851 | static const std::array<std::string, 7> requiredParams = { | ||
| 852 | "measure_dir", "display_name", "class_name", "taxonomy_tag", "measure_type", "description", "modeler_description", | ||
| 853 | ✗ | }; | |
| 854 | ✗ | for (const auto& requiredParam : requiredParams) { | |
| 855 | ✗ | if (!body.isMember(requiredParam) || !body[requiredParam].isString()) { | |
| 856 | ✗ | auto msg = fmt::format("The '{}' (string) must be in the post data.", requiredParam); | |
| 857 | ✗ | fmt::print("{}\n", msg); | |
| 858 | ✗ | return {httplib::StatusCode::BadRequest_400, toJSONString(msg)}; | |
| 859 | ✗ | } | |
| 860 | } | ||
| 861 | |||
| 862 | ✗ | MeasureType measureType = MeasureType::ModelMeasure; | |
| 863 | ✗ | auto measureTypeString = get_field<std::string>(body, "measure_type", "ModelMeasure"); | |
| 864 | try { | ||
| 865 | ✗ | measureType = MeasureType(measureTypeString); | |
| 866 | ✗ | } catch (const std::exception& e) { | |
| 867 | ✗ | auto msg = fmt::format("Couldn't convert '{}' to a MeasureType: {}", measureTypeString, e.what()); | |
| 868 | ✗ | fmt::print("{}\n", msg); | |
| 869 | ✗ | return {httplib::StatusCode::BadRequest_400, toJSONString(msg)}; | |
| 870 | ✗ | } | |
| 871 | |||
| 872 | ✗ | MeasureLanguage measureLanguage = MeasureLanguage::Ruby; | |
| 873 | ✗ | if (auto measureLanguageString_ = get_field<std::string>(body, "measure_language")) { | |
| 874 | try { | ||
| 875 | ✗ | measureLanguage = MeasureLanguage(*measureLanguageString_); | |
| 876 | ✗ | } catch (const std::exception& e) { | |
| 877 | ✗ | auto msg = fmt::format("Couldn't convert '{}' to a MeasureLanguage: {}", *measureLanguageString_, e.what()); | |
| 878 | ✗ | fmt::print("{}\n", msg); | |
| 879 | ✗ | return {httplib::StatusCode::BadRequest_400, toJSONString(msg)}; | |
| 880 | ✗ | } | |
| 881 | ✗ | } | |
| 882 | |||
| 883 | ✗ | const openstudio::path measureDir = get_field<openstudio::path>(body, "measure_dir", ""); | |
| 884 | // This is throwy when the directory already exists | ||
| 885 | ✗ | if (openstudio::filesystem::is_directory(measureDir)) { | |
| 886 | ✗ | auto msg = fmt::format("The directory already exists at '{}'.", measureDir.generic_string()); | |
| 887 | ✗ | fmt::print("{}\n", msg); | |
| 888 | ✗ | return {httplib::StatusCode::BadRequest_400, toJSONString(msg)}; | |
| 889 | ✗ | } | |
| 890 | ✗ | const BCLMeasure measure(get_field<std::string>(body, "display_name", "DisplayName"), get_field<std::string>(body, "class_name", "ClassName"), | |
| 891 | ✗ | measureDir, get_field<std::string>(body, "taxonomy_tag", "taxonomy.tag"), measureType, | |
| 892 | ✗ | get_field<std::string>(body, "description", "Description"), | |
| 893 | ✗ | get_field<std::string>(body, "modeler_description", "ModelerDescription"), measureLanguage); | |
| 894 | |||
| 895 | ✗ | if (boost::optional<BCLMeasure> measure_ = m_measureManager.getMeasure(measureDir, true)) { | |
| 896 | ✗ | return {httplib::StatusCode::OK_200, toJSONString(measure_->toJSON())}; | |
| 897 | } else { | ||
| 898 | ✗ | fmt::print("Failed to update measure after creation, this shouldn't happen."); | |
| 899 | ✗ | return {httplib::StatusCode::BadRequest_400, toJSONString(measure.toJSON())}; | |
| 900 | ✗ | } | |
| 901 | ✗ | } | |
| 902 | |||
| 903 | ✗ | MeasureManagerServer::ResponseType MeasureManagerServer::duplicate_measure(const Json::Value& body) { | |
| 904 | // Required parameters: | ||
| 905 | ✗ | openstudio::path oldMeasureDir; | |
| 906 | ✗ | if (auto oldMeasureDir_ = get_field<openstudio::path>(body, "old_measure_dir")) { | |
| 907 | ✗ | oldMeasureDir = std::move(*oldMeasureDir_); | |
| 908 | } else { | ||
| 909 | ✗ | return {httplib::StatusCode::BadRequest_400, toJSONString("The 'old_measure_dir' (string) must be in the post data")}; | |
| 910 | ✗ | } | |
| 911 | |||
| 912 | ✗ | openstudio::path newMeasureDir; | |
| 913 | ✗ | if (auto newMeasureDir_ = get_field<openstudio::path>(body, "measure_dir")) { | |
| 914 | ✗ | newMeasureDir = std::move(*newMeasureDir_); | |
| 915 | } else { | ||
| 916 | ✗ | return {httplib::StatusCode::BadRequest_400, toJSONString("The 'measure_dir' (string) must be in the post data")}; | |
| 917 | ✗ | } | |
| 918 | |||
| 919 | ✗ | const bool force_reload = get_field<bool>(body, "force_reload", false); | |
| 920 | |||
| 921 | ✗ | boost::optional<BCLMeasure> oldMeasure_ = m_measureManager.getMeasure(oldMeasureDir, force_reload); | |
| 922 | ✗ | if (!oldMeasure_) { | |
| 923 | ✗ | auto msg = fmt::format("Cannot load measure at '{}'.", oldMeasureDir.generic_string()); | |
| 924 | ✗ | fmt::print("{}\n", msg); | |
| 925 | ✗ | return {httplib::StatusCode::BadRequest_400, toJSONString(msg)}; | |
| 926 | ✗ | } | |
| 927 | |||
| 928 | ✗ | auto& oldMeasure = *oldMeasure_; | |
| 929 | |||
| 930 | ✗ | auto newMeasure_ = oldMeasure.clone(newMeasureDir); | |
| 931 | ✗ | if (!newMeasure_) { | |
| 932 | ✗ | auto msg = fmt::format("Cannot copy measure from '{}' to {}'", oldMeasureDir.generic_string(), newMeasureDir.generic_string()); | |
| 933 | ✗ | fmt::print("{}\n", msg); | |
| 934 | ✗ | return {httplib::StatusCode::BadRequest_400, toJSONString(msg)}; | |
| 935 | ✗ | } | |
| 936 | ✗ | auto& newMeasure = *newMeasure_; | |
| 937 | // Force updating the UID | ||
| 938 | ✗ | newMeasure.changeUID(); | |
| 939 | ✗ | newMeasure.incrementVersionId(); | |
| 940 | |||
| 941 | ✗ | if (auto val_ = get_field<std::string>(body, "display_name")) { | |
| 942 | ✗ | newMeasure.setDisplayName(*val_); | |
| 943 | ✗ | } | |
| 944 | ✗ | if (auto val_ = get_field<std::string>(body, "class_name")) { | |
| 945 | ✗ | newMeasure.setName(openstudio::toUnderscoreCase(*val_)); | |
| 946 | ✗ | newMeasure.setClassName(*val_); | |
| 947 | ✗ | } | |
| 948 | ✗ | if (auto val_ = get_field<std::string>(body, "taxonomy_tag")) { | |
| 949 | ✗ | newMeasure.setTaxonomyTag(*val_); | |
| 950 | ✗ | } | |
| 951 | |||
| 952 | // Changing the measure Language is not supported! | ||
| 953 | ✗ | auto newMeasureLanguage = oldMeasure.measureLanguage(); | |
| 954 | // if (body.has_field("measure_language") && body.at("measure_language").is_string()) { | ||
| 955 | // auto measureLanguageString = body.at("measure_type").as_string(); | ||
| 956 | // try { | ||
| 957 | // newMeasureLanguage = MeasureLanguage(measureLanguageString); | ||
| 958 | // newMeasure.setMeasureLanguage(measureLanguage); | ||
| 959 | // } catch (...) { | ||
| 960 | // fmt::print("Couldn't convert '{}' to a MeasureLanguage", measureLanguageString); | ||
| 961 | // } | ||
| 962 | // } | ||
| 963 | |||
| 964 | // Changing the measure Type should maybe not be supported either, the method signatures will be wrong and it might be missing | ||
| 965 | // energyPlusOutputRequests | ||
| 966 | ✗ | auto newMeasureType = oldMeasure.measureType(); | |
| 967 | ✗ | if (auto measureTypeString_ = get_field<std::string>(body, "measure_type")) { | |
| 968 | try { | ||
| 969 | ✗ | newMeasureType = MeasureType(*measureTypeString_); | |
| 970 | ✗ | newMeasure.setMeasureType(newMeasureType); | |
| 971 | ✗ | } catch (...) { | |
| 972 | ✗ | fmt::print("Couldn't convert '{}' to a MeasureType", *measureTypeString_); | |
| 973 | ✗ | } | |
| 974 | ✗ | } | |
| 975 | |||
| 976 | ✗ | if (auto val_ = get_field<std::string>(body, "description")) { | |
| 977 | ✗ | newMeasure.setDescription(*val_); | |
| 978 | ✗ | } | |
| 979 | |||
| 980 | ✗ | if (auto val_ = get_field<std::string>(body, "modeler_description")) { | |
| 981 | ✗ | newMeasure.setModelerDescription(*val_); | |
| 982 | ✗ | } | |
| 983 | |||
| 984 | ✗ | newMeasure.updateMeasureScript(oldMeasure.measureType(), newMeasureType, oldMeasure.measureLanguage(), newMeasureLanguage, oldMeasure.className(), | |
| 985 | ✗ | newMeasure.className(), newMeasure.displayName(), newMeasure.description(), newMeasure.modelerDescription()); | |
| 986 | ✗ | newMeasure.updateMeasureTests(oldMeasure.className(), newMeasure.className()); | |
| 987 | |||
| 988 | ✗ | fmt::print("Cloned the {} {} with class name '{}' from '{}' to '{}'\n", oldMeasure.measureLanguage().valueName(), | |
| 989 | ✗ | oldMeasure.measureType().valueName(), oldMeasure.className(), | |
| 990 | ✗ | openstudio::toString(openstudio::filesystem::canonical(oldMeasure.directory())), | |
| 991 | ✗ | openstudio::toString(openstudio::filesystem::canonical(newMeasure.directory()))); | |
| 992 | |||
| 993 | ✗ | newMeasure.checkForUpdatesFiles(); | |
| 994 | ✗ | newMeasure.checkForUpdatesXML(); | |
| 995 | ✗ | newMeasure.save(); | |
| 996 | |||
| 997 | ✗ | if (boost::optional<BCLMeasure> measure_ = m_measureManager.getMeasure(newMeasureDir, true)) { | |
| 998 | ✗ | return {httplib::StatusCode::OK_200, toJSONString(measure_->toJSON())}; | |
| 999 | } else { | ||
| 1000 | ✗ | fmt::print("Failed to update measure after duplication, this shouldn't happen."); | |
| 1001 | ✗ | return {httplib::StatusCode::BadRequest_400, toJSONString(newMeasure.toJSON())}; | |
| 1002 | ✗ | } | |
| 1003 | ✗ | } | |
| 1004 | |||
| 1005 | ✗ | void MeasureManagerServer::handle_request(const httplib::Request& req, httplib::Response& res, const Json::Value& body, | |
| 1006 | memRequestHandlerFunPtr request_handler) { | ||
| 1007 | |||
| 1008 | ✗ | int status_code = httplib::StatusCode::Created_201; | |
| 1009 | try { | ||
| 1010 | ✗ | auto result = (this->*request_handler)(body); | |
| 1011 | ✗ | status_code = result.status_code; | |
| 1012 | ✗ | res.status = status_code; | |
| 1013 | ✗ | res.set_content(result.body, "application/json"); | |
| 1014 | ✗ | } catch (const std::exception& e) { | |
| 1015 | ✗ | constexpr auto msg = "MeasureManager Server encountered an error:\n\"{}\"\n"; | |
| 1016 | ✗ | fmt::print(msg, e.what()); | |
| 1017 | ✗ | status_code = httplib::StatusCode::InternalServerError_500; | |
| 1018 | ✗ | res.status = status_code; | |
| 1019 | ✗ | res.set_content(fmt::format(msg, e.what()), "text/plain"); | |
| 1020 | ✗ | } | |
| 1021 | ✗ | } | |
| 1022 | |||
| 1023 | ✗ | void MeasureManagerServer::do_tasks_forever() { | |
| 1024 | ✗ | fmt::print("MeasureManager Ready\n"); | |
| 1025 | ✗ | fmt::print("Accepting requests on: {}\n", m_url); | |
| 1026 | ✗ | std::fflush(stdout); | |
| 1027 | |||
| 1028 | // Print the request to the console (stdout if Ok, stderr otherwise) | ||
| 1029 | // [2024-11-14T10:21:46+01:00] "POST /reset HTTP/1.1" 200 (OK) | ||
| 1030 | // [2024-11-14T10:22:09+01:00] "GET /dsd HTTP/1.1" 404 (Not Found) | ||
| 1031 | ✗ | m_server->set_logger([](const httplib::Request& req, const httplib::Response& res) { | |
| 1032 | ✗ | fmt::print(res.status == httplib::StatusCode::OK_200 ? stdout : stderr, "[{}] \"{} {} {}\" {} ({})\n", | |
| 1033 | ✗ | openstudio::DateTime::now().toXsdDateTime(), req.method, req.path, req.version, res.status, httplib::status_message(res.status)); | |
| 1034 | ✗ | }); | |
| 1035 | ✗ | m_server->set_error_logger([](const httplib::Error& err, const httplib::Request* req) { | |
| 1036 | ✗ | if (req) { | |
| 1037 | ✗ | fmt::print(stderr, "error_logger: [{}] \"{} {} {}\" {} ({})\n", openstudio::DateTime::now().toXsdDateTime(), req->method, req->path, | |
| 1038 | ✗ | req->version, static_cast<int>(err), httplib::to_string(err)); | |
| 1039 | } else { | ||
| 1040 | ✗ | fmt::print(stderr, "[{}] MeasureManager Server encountered an error: {} ({})\n", openstudio::DateTime::now().toXsdDateTime(), | |
| 1041 | ✗ | static_cast<int>(err), httplib::to_string(err)); | |
| 1042 | } | ||
| 1043 | ✗ | }); | |
| 1044 | |||
| 1045 | ✗ | m_server->listen_after_bind(); | |
| 1046 | ✗ | } | |
| 1047 | |||
| 1048 | } // namespace openstudio | ||
| 1049 |