From a5f2e260951edfea837c31bd615ee0cae543b75b Mon Sep 17 00:00:00 2001 From: "James E. Blair" Date: Sun, 10 Feb 2019 10:04:44 -0800 Subject: [PATCH] Add LRU cache --- zuul-preview/main.cc | 66 ++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 64 insertions(+), 2 deletions(-) diff --git a/zuul-preview/main.cc b/zuul-preview/main.cc index fb497bf..be74564 100644 --- a/zuul-preview/main.cc +++ b/zuul-preview/main.cc @@ -20,6 +20,7 @@ #include #include #include +#include using namespace std; @@ -34,16 +35,73 @@ vector split(const string &in) return parts; } +class Cache { + list> queue; + unordered_map>::iterator> map; + uint size; + +public: + string notfound = ""; + + Cache(uint s) + : queue {}, map {}, size(0) + { + size = s; + } + + string get(string key) + { + auto location = map.find(key); + if (location == map.end()) + return notfound; + + pair val = *(location->second); + queue.erase(location->second); + queue.push_front(val); + cout << "get push " << val.second << endl; + return val.second; + } + + void put(string key, string value) + { + auto location = map.find(key); + if (location != map.end()) + return; + + if (queue.size() == size) { + pair last = queue.back(); + cout << "put pop " << last.second << endl; + queue.pop_back(); + map.erase(last.first); + } + + cout << "put push " << value << endl; + queue.push_front(make_pair(key, value)); + map[key] = queue.begin(); + } +}; + + int main(int, char**) { web::http::client::http_client client("https://zuul.opendev.org"); string hostname; + Cache cache = Cache(2); while (getline(cin, hostname)) { // Expected hostname: // site.75031cad206c4014ad7a3387091d15ab.openstack.preview.opendev.org // Apache will drop "preview.opendev.org", so our expected input will be: // site.75031cad206c4014ad7a3387091d15ab.openstack + // site.7c16d914db5a4c4b91cd9a31d119dd48.openstack + // site.688b70499b9a41a08f498ed6e932960c.openstack + // site.dbefc23dcc594577a8bfa4db4f9b0a8f.openstack + + string val = cache.get(hostname); + if (val != cache.notfound) { + cout << val << endl; + continue; + } auto parts = split(hostname); if (parts.size() < 3) { @@ -53,9 +111,11 @@ int main(int, char**) auto artifact = parts[0]; auto buildid = parts[1]; auto tenant = parts[2]; + /* cout << artifact << endl << buildid << endl << tenant << endl; + */ // 75031cad206c4014ad7a3387091d15ab auto uri = web::uri_builder("/api/tenant/" + tenant + "/build"); @@ -64,11 +124,13 @@ int main(int, char**) web::http::methods::GET, uri.to_string()).get(); // body is a web::json::value auto body = response.extract_json().get(); - cout << response.status_code() << endl; - cout << body.serialize() << endl; + //cout << response.status_code() << endl; + //cout << body.serialize() << endl; // TODO: use artifact // body["log_url"].as_string() returns a const std::string& cout << body["log_url"].as_string() << endl; + + cache.put(hostname, body["log_url"].as_string()); } }