• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2022 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <functional>
18 #include <map>
19 #include <mutex>
20 
21 #include <fruit/fruit.h>
22 
23 #include "common/libs/fs/epoll.h"
24 #include "common/libs/fs/shared_fd.h"
25 #include "common/libs/utils/result.h"
26 
27 #pragma once
28 
29 namespace cuttlefish {
30 
31 using EpollCallback = std::function<Result<void>(EpollEvent)>;
32 
33 class EpollPool {
34  public:
35   INJECT(EpollPool());
36 
37   /**
38    * The `callback` function will be invoked with an EpollEvent containing `fd`
39    * and a subset of the bits in `events` matching which events were actually
40    * observed. The callback is invoked exactly once (enforced via EPOLLONESHOT)
41    * and must be re-`Register`ed to receive events again. This can be done
42    * in the callback implementation. Callbacks are invoked by callers of the
43    * `HandleEvent` function, and any errors produced by the callback function
44    * will manifest there. Callbacks that return errors will not be automatically
45    * re-registered.
46    */
47   Result<void> Register(SharedFD fd, uint32_t events, EpollCallback callback);
48   Result<void> HandleEvent();
49   Result<void> Remove(SharedFD fd);
50 
51  private:
52   Epoll epoll_;
53   std::mutex callbacks_mutex_;
54   std::map<SharedFD, EpollCallback> callbacks_;
55 };
56 
57 fruit::Component<EpollPool> EpollLoopComponent();
58 
59 }  // namespace cuttlefish
60