accept_server.h
1 // Copyright 2020, Beeri 15. All rights reserved.
2 // Author: Roman Gershman (romange@gmail.com)
3 //
4 
5 #pragma once
6 
7 #include <functional>
8 #include <vector>
9 
10 #include "util/fibers/fibers_ext.h"
11 #include "util/uring/connection.h"
12 #include "util/uring/fiber_socket.h"
13 
14 namespace util {
15 namespace uring {
16 
17 class Proactor;
18 class ProactorPool;
19 class Connection;
20 class ListenerInterface;
21 
22 class AcceptServer {
23  public:
24  explicit AcceptServer(ProactorPool* pool, bool break_on_int = true);
25  ~AcceptServer();
26 
27  void Run();
28 
29  // If wait is false - does not wait for the server to stop.
30  // Then you need to run Wait() to wait for proper shutdown.
31  void Stop(bool wait = false);
32 
33  void Wait();
34 
35  // Returns the port number to which the listener was bound.
36  unsigned short AddListener(unsigned short port, ListenerInterface* cf);
37 
38  void TriggerOnBreakSignal(std::function<void()> f) {
39  on_break_hook_ = std::move(f);
40  }
41 
42  void set_back_log(uint16_t backlog) {
43  backlog_ = backlog;
44  }
45 
46  private:
47 
48  void BreakListeners();
49 
50  ProactorPool* pool_;
51 
52  // Called if a termination signal has been caught (SIGTERM/SIGINT).
53  std::function<void()> on_break_hook_;
54 
55  std::vector<std::unique_ptr<ListenerInterface>> list_interface_;
56  fibers_ext::BlockingCounter ref_bc_; // to synchronize listener threads during the shutdown.
57 
58  bool was_run_ = false;
59  bool break_ = false;
60 
61  uint16_t backlog_ = 128;
62 };
63 
64 
70  public:
71  virtual ~ListenerInterface();
72 
73  void RegisterPool(ProactorPool* pool);
74 
77  virtual Connection* NewConnection(Proactor* context) = 0;
78 
81  virtual void PreAcceptLoop(Proactor* owner) {}
82 
83  // Called by AcceptServer when shutting down start and before all connections are closed.
84  virtual void PreShutdown() {
85  }
86 
87  // Called by AcceptServer when shutting down finalized and after all connections are closed.
88  virtual void PostShutdown() {
89  }
90 
91  virtual uint32_t GetSockOptMask() const { return 1 << SO_REUSEADDR; }
92 
93  protected:
94  ProactorPool* pool() {
95  return pool_;
96  }
97 
98  FiberSocket* listener() { return &listener_;}
99 
100  private:
101  struct SafeConnList;
102 
103  void RunAcceptLoop();
104  static void RunSingleConnection(Connection* conn, SafeConnList* list);
105 
106  FiberSocket listener_;
107 
108  ProactorPool* pool_ = nullptr;
109  friend class AcceptServer;
110 };
111 
112 } // namespace uring
113 } // namespace util
virtual Connection * NewConnection(Proactor *context)=0
virtual void PreAcceptLoop(Proactor *owner)
Definition: accept_server.h:81
Abstracts away connections implementation and their life-cycle.
Definition: accept_server.h:69