2 * Copyright (C) 2018 Cisco Inc.
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License, version 2,
6 * as published by the Free Software Foundation.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 // @author Changxue Deng <chadeng@cisco.com>
21 #include "resource_pool.h"
22 #include "mabain_consts.h"
23 #include "mmap_file.h"
28 ResourcePool::ResourcePool()
30 pthread_mutex_init(&pool_mutex, NULL);
33 ResourcePool::~ResourcePool()
35 pthread_mutex_destroy(&pool_mutex);
38 void ResourcePool::RemoveAll()
40 pthread_mutex_lock(&pool_mutex);
42 pthread_mutex_unlock(&pool_mutex);
45 // check if a in-memory db already exists
46 bool ResourcePool::CheckExistence(const std::string &header_path)
48 pthread_mutex_lock(&pool_mutex);
49 auto search = file_pool.find(header_path);
50 pthread_mutex_unlock(&pool_mutex);
52 return (search != file_pool.end());
55 void ResourcePool::RemoveResourceByPath(const std::string &path)
57 pthread_mutex_lock(&pool_mutex);
58 file_pool.erase(path);
59 pthread_mutex_unlock(&pool_mutex);
62 void ResourcePool::RemoveResourceByDB(const std::string &db_path)
64 pthread_mutex_lock(&pool_mutex);
66 for(auto it = file_pool.begin(); it != file_pool.end();)
68 if(it->first.compare(0, db_path.size(), db_path) == 0)
69 it = file_pool.erase(it);
74 pthread_mutex_unlock(&pool_mutex);
77 std::shared_ptr<MmapFileIO> ResourcePool::OpenFile(const std::string &fpath,
83 std::shared_ptr<MmapFileIO> mmap_file;
85 pthread_mutex_lock(&pool_mutex);
87 auto search = file_pool.find(fpath);
88 if(search == file_pool.end())
93 if(mode & CONSTS::MEMORY_ONLY_MODE)
94 flags |= MMAP_ANONYMOUS_MODE;
96 mmap_file = std::shared_ptr<MmapFileIO>
101 mode & CONSTS::SYNC_ON_WRITE)
105 if(mmap_file->MapFile(file_size, 0) != NULL)
107 if(!(mode & CONSTS::MEMORY_ONLY_MODE))
116 file_pool[fpath] = mmap_file;
120 mmap_file = search->second;
123 pthread_mutex_unlock(&pool_mutex);
127 int ResourcePool::AddResourceByPath(const std::string &path, std::shared_ptr<MmapFileIO> resource)
129 int rval = MBError::IN_DICT;
131 pthread_mutex_lock(&pool_mutex);
132 auto search = file_pool.find(path);
133 if(search == file_pool.end())
135 file_pool[path] = resource;
136 rval = MBError::SUCCESS;
138 pthread_mutex_unlock(&pool_mutex);