1 /*
2  * Copyright (c) 2021 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #ifndef PLUGIN_MANAGER_H
17 #define PLUGIN_MANAGER_H
18 
19 #include <map>
20 #include <memory>
21 #include <mutex>
22 
23 #include "plugin/i_plugin.h"
24 #include "plugin_manager/include/i_plugin_manager.h"
25 #include "plugin_manager/include/plugin.h"
26 #include "utils/aie_macros.h"
27 
28 namespace OHOS {
29 namespace AI {
30 class IPlugin;
31 
32 struct PluginKey {
33     std::string aid;
34     long long version;
35 
PluginKeyPluginKey36     PluginKey(const std::string &aid, long long version)
37         : aid(aid), version(version)
38     {
39     }
40 
41     inline bool operator< (const PluginKey& another) const
42     {
43         if (aid < another.aid) {
44             return true;
45         }
46         if (aid == another.aid && version < another.version) {
47             return true;
48         }
49 
50         return false;
51     }
52 };
53 
54 typedef std::map<PluginKey, std::shared_ptr<Plugin>> PluginMap;
55 
56 class PluginManager : public IPluginManager {
57     FORBID_COPY_AND_ASSIGN(PluginManager);
58     FORBID_CREATE_BY_SELF(PluginManager);
59 public:
60     static PluginManager *GetInstance();
61     void Destroy() override;
62     int GetPlugin(const std::string &aid, long long version, std::shared_ptr<Plugin> &plugin) override;
63     void UnloadPlugin(const std::string &aid, long long version) override;
64 
65 private:
66     std::shared_ptr<Plugin> FindPlugin(const PluginKey &pluginKey);
67     void AddPlugin(const PluginKey &pluginKey, const std::shared_ptr<Plugin> &pluginValue);
68     void DelPlugin(const PluginKey &pluginKey);
69     void DelPluginByAID(const std::string &aid);
70     int LoadPlugin(const std::string &aid, long long version, std::shared_ptr<Plugin> &plugin);
71 
72 private:
73     static std::mutex instanceLock_;
74     static PluginManager *instance_;
75 
76 private:
77     std::mutex mutex4Interface_;
78     std::mutex mutex_;
79     PluginMap pluginMap_;
80 };
81 } // namespace AI
82 } // namespace OHOS
83 
84 #endif // PLUGIN_MANAGER_H