OpenSDN source code
dhcp_proto.cc
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
3  * Copyright Contributors to the OpenSDN project
4  */
5 
6 #include <boost/filesystem.hpp>
7 #include "base/timer.h"
8 #include "cmn/agent_cmn.h"
9 #include "init/agent_param.h"
10 #include "oper/vn.h"
11 #include "services/dhcp_proto.h"
12 #include "services/dhcp_lease_db.h"
13 #include "services/services_types.h"
14 #include "services/services_init.h"
15 #include "pkt/pkt_init.h"
16 
17 using namespace boost::asio;
18 using boost::asio::ip::udp;
19 
20 DhcpProto::DhcpProto(Agent *agent, boost::asio::io_context &io,
21  bool run_with_vrouter) :
22  Proto(agent, "Agent::Services", PktHandler::DHCP, io),
23  run_with_vrouter_(run_with_vrouter), ip_fabric_interface_(NULL),
24  ip_fabric_interface_index_(-1), pkt_interface_index_(-1),
25  dhcp_server_socket_(io), dhcp_server_read_buf_(NULL),
26  gateway_delete_seqno_(0) {
27  // limit the number of entries in the workqueue
29  work_queue_.SetBounded(true);
30 
32  if (dhcp_relay_mode_) {
33  boost::system::error_code ec;
34  dhcp_server_socket_.open(udp::v4(), ec);
35  assert(!ec);
36  dhcp_server_socket_.bind(udp::endpoint(udp::v4(), DHCP_SERVER_PORT), ec);
37  if (ec) {
38  DHCP_TRACE(Error, "Error creating DHCP socket : " << ec);
39  }
40 
41  // For DHCP requests coming from VMs in default VRF, when the IP received
42  // from Nova is 0, DHCP module acts DHCP relay and relays the request onto
43  // the fabric VRF. Vrouter sends responses for these to vhost0 interface.
44  // We listen on DHCP server port to receive these responses (check option 82
45  // header to decide that it is a response for a relayed request) and send
46  // the response to the VM.
47  AsyncRead();
48  }
49 
51  boost::bind(&DhcpProto::ItfNotify, this, _2));
53  boost::bind(&DhcpProto::VnNotify, this, _2));
54 
56  TimerManager::CreateTimer(io, "DhcpLeaseFileCleanupTimer",
57  TaskScheduler::GetInstance()->GetTaskId("Agent::Services"),
59 }
60 
62 }
63 
65  if (dhcp_relay_mode_) {
66  boost::system::error_code ec;
67  dhcp_server_socket_.shutdown(udp::socket::shutdown_both, ec);
68  if (ec) {
69  DHCP_TRACE(Error, "Error shutting down DHCP socket : " << ec);
70  }
71  dhcp_server_socket_.close (ec);
72  if (ec) {
73  DHCP_TRACE(Error, "Error closing DHCP socket : " << ec);
74  }
75  }
81 }
82 
85  dhcp_server_socket_.async_receive_from(
86  boost::asio::buffer(dhcp_server_read_buf_, kDhcpMaxPacketSize),
88  boost::bind(&DhcpProto::ReadHandler, this,
89  boost::asio::placeholders::error,
90  boost::asio::placeholders::bytes_transferred));
91 }
92 
93 void DhcpProto::ReadHandler(const boost::system::error_code &error,
94  std::size_t len) {
95  if (!error) {
97  } else {
98  DHCP_TRACE(Error, "Error reading packet <" + error.message() + ">");
99  if (error == boost::system::errc::operation_canceled) {
100  return;
101  }
102  delete [] dhcp_server_read_buf_;
103  dhcp_server_read_buf_ = NULL;
104  }
105 
106  AsyncRead();
107 }
108 
109 void DhcpProto::SendDhcpIpc(uint8_t *dhcp, std::size_t len) {
110  DhcpVhostMsg *ipc = new DhcpVhostMsg(dhcp, len);
112 }
113 
114 ProtoHandler *DhcpProto::AllocProtoHandler(boost::shared_ptr<PktInfo> info,
115  boost::asio::io_context &io) {
116  return new DhcpHandler(agent(), info, io);
117 }
118 
120  Interface *itf = static_cast<Interface *>(entry);
121  if (entry->IsDeleted()) {
122  if (itf->type() == Interface::PHYSICAL &&
123  itf->name() == agent_->fabric_interface_name()) {
126  } else if (itf->type() == Interface::PACKET) {
128  } else if (itf->type() == Interface::VM_INTERFACE) {
129  VmInterface *vmi = static_cast<VmInterface *>(itf);
130  if (gw_vmi_list_.erase(vmi)) {
131  DHCP_TRACE(Trace, "Gateway interface deleted: " << itf->name());
133  }
134  DeleteLeaseDb(vmi);
135  }
136  } else {
137  if (itf->type() == Interface::PHYSICAL &&
138  itf->name() == agent_->fabric_interface_name()) {
141  if (run_with_vrouter_) {
143  } else {
145  }
146  } else if (itf->type() == Interface::PACKET) {
147  set_pkt_interface_index(itf->id());
148  } else if (itf->type() == Interface::VM_INTERFACE) {
149  VmInterface *vmi = static_cast<VmInterface *>(itf);
150  if (vmi->vmi_type() == VmInterface::GATEWAY) {
151  DHCP_TRACE(Trace, "Gateway interface added: " << itf->name());
152  gw_vmi_list_.insert(vmi);
153  CreateLeaseDb(vmi);
154  }
155  }
156  }
157 }
158 
160  const Ip4Address &subnet = vmi->subnet();
161  if (vmi->vn() == NULL || subnet.to_ulong() == 0) {
162  DeleteLeaseDb(vmi);
163  DHCP_TRACE(Trace, "DHCP Lease DB not created - config not present : " <<
164  vmi->subnet().to_string());
165  return;
166  }
167 
168  const IpAddress address(subnet);
169  const VnIpam *vn_ipam = vmi->vn()->GetIpam(address);
170  if (!vn_ipam) {
171  DeleteLeaseDb(vmi);
172  DHCP_TRACE(Trace, "DHCP Lease DB not created for subnet " <<
173  vmi->subnet().to_string() << " - IPAM not available");
174  return;
175  }
176 
177  std::string res;
178  std::vector<Ip4Address> reserve_list;
179  if (vmi->primary_ip_addr().to_ulong()) {
180  reserve_list.push_back(vmi->primary_ip_addr());
181  res = vmi->primary_ip_addr().to_string() + ", ";
182  }
183  reserve_list.push_back(vn_ipam->default_gw.to_v4());
184  reserve_list.push_back(vn_ipam->dns_server.to_v4());
185  res += vn_ipam->default_gw.to_v4().to_string() + ", ";
186  res += vn_ipam->dns_server.to_v4().to_string();
187  LeaseManagerMap::iterator it = lease_manager_.find(vmi);
188  if (it == lease_manager_.end()) {
189  DHCP_TRACE(Trace, "Created new DHCP Lease DB : " <<
190  vmi->name() << " " << vmi->subnet().to_string() << "/" <<
191  vmi->subnet_plen() << "; Reserved : " << res);
192  DhcpLeaseDb *lease_db = new DhcpLeaseDb(vmi->subnet(),
193  vmi->subnet_plen(),
194  reserve_list,
195  GetLeaseFileName(vmi),
196  io_);
197  lease_manager_.insert(LeaseManagerPair(vmi, lease_db));
198  } else {
199  DHCP_TRACE(Trace, "Updated DHCP Lease DB : " <<
200  vmi->subnet().to_string() << "/" <<
201  vmi->subnet_plen() << "; Reserved : " << res);
202  it->second->Update(vmi->subnet(), vmi->subnet_plen(),
203  reserve_list);
204  }
205 }
206 
208  LeaseManagerMap::iterator it = lease_manager_.find(vmi);
209  if (it != lease_manager_.end()) {
210  delete it->second;
211  lease_manager_.erase(it);
212  DHCP_TRACE(Trace, "Deleted DHCP Lease DB : " << vmi->name());
213  }
214 }
215 
217  VnEntry *vn = static_cast<VnEntry *>(entry);
218  for (std::set<VmInterface *>::iterator it = gw_vmi_list_.begin();
219  it != gw_vmi_list_.end(); ++it) {
220  VmInterface *vmi = *it;
221  if (vmi->vn() != vn)
222  continue;
223  CreateLeaseDb(*it);
224  }
225 }
226 
228  LeaseManagerMap::iterator it = lease_manager_.find(intrface);
229  if (it != lease_manager_.end())
230  return it->second;
231 
232  return NULL;
233 }
234 
235 std::string DhcpProto::GetLeaseFileName(const VmInterface *vmi) {
236  if (!run_with_vrouter_)
237  return "./dhcp." + UuidToString(vmi->GetUuid()) + ".leases";
238 
239  boost::filesystem::path dir(agent()->params()->agent_base_dir() + "/dhcp");
240  boost::system::error_code ec;
241  if (!boost::filesystem::exists(dir, ec)) {
242  boost::filesystem::create_directory(dir, ec);
243  // boost::filesystem::permissions(dir, boost::filesystem::remove_perms |
244  // boost::filesystem::others_all, ec);
245  if (ec) {
246  DHCP_TRACE(Error, "Cannot create DHCP Lease directory : " << dir);
247  }
248  }
249 
250  return dir.string() + "/dhcp." + UuidToString(vmi->GetUuid()) + ".leases";
251 }
252 
258  this, gateway_delete_seqno_));
259 }
260 
261 bool DhcpProto::LeaseFileCleanupExpiry(uint32_t seqno) {
262  if (seqno == gateway_delete_seqno_ && !gw_vmi_list_.empty()) {
263  // get valid file list
264  std::set<std::string> filelist;
265  for (std::set<VmInterface *>::const_iterator it = gw_vmi_list_.begin();
266  it != gw_vmi_list_.end(); ++it) {
267  filelist.insert(GetLeaseFileName(*it));
268  }
269 
270  // delete unused files
271  boost::system::error_code ec;
272  boost::filesystem::path dir(agent()->params()->agent_base_dir() +
273  "/dhcp");
274  if (boost::filesystem::exists(dir, ec) &&
275  boost::filesystem::is_directory(dir, ec)) {
276  for (boost::filesystem::directory_iterator it(dir);
277  it != boost::filesystem::directory_iterator(); ++it) {
278  std::string filename = it->path().string();
279  if (boost::filesystem::is_regular_file(it->status()) &&
280  filelist.find(filename) == filelist.end()) {
281  DHCP_TRACE(Trace, "Removing DHCP Lease file : " << filename);
282  remove(filename.c_str()); // doesnt invalidate iterator
283  }
284  }
285  }
286  }
287 
288  return false;
289 }
boost::asio::ip::address IpAddress
Definition: address.h:14
boost::asio::ip::address_v4 Ip4Address
Definition: address.h:15
uint32_t services_queue_limit()
Definition: agent_param.h:416
bool dhcp_relay_mode() const
Definition: agent_param.h:265
Definition: agent.h:361
InterfaceTable * interface_table() const
Definition: agent.h:468
AgentParam * params() const
Definition: agent.h:1227
VnTable * vn_table() const
Definition: agent.h:498
const std::string & fabric_interface_name() const
Definition: agent.h:1132
PktModule * pkt() const
Definition: agent.cc:969
bool IsDeleted() const
Definition: db_entry.h:49
ListenerId Register(ChangeCallback callback, const std::string &name="unspecified")
Definition: db_table.cc:208
void Unregister(ListenerId listener)
Definition: db_table.cc:213
bool dhcp_relay_mode_
Definition: dhcp_proto.h:135
void Shutdown()
Definition: dhcp_proto.cc:64
static const uint32_t kDhcpMaxPacketSize
Definition: dhcp_proto.h:26
void ItfNotify(DBEntryBase *entry)
Definition: dhcp_proto.cc:119
void DeleteLeaseDb(VmInterface *vmi)
Definition: dhcp_proto.cc:207
ProtoHandler * AllocProtoHandler(boost::shared_ptr< PktInfo > info, boost::asio::io_context &io)
Definition: dhcp_proto.cc:114
void AsyncRead()
Definition: dhcp_proto.cc:83
uint32_t gateway_delete_seqno_
Definition: dhcp_proto.h:150
virtual ~DhcpProto()
Definition: dhcp_proto.cc:61
boost::asio::ip::udp::socket dhcp_server_socket_
Definition: dhcp_proto.h:144
LeaseManagerMap lease_manager_
Definition: dhcp_proto.h:149
Timer * lease_file_cleanup_timer_
Definition: dhcp_proto.h:151
void StartLeaseFileCleanupTimer()
Definition: dhcp_proto.cc:253
DBTableBase::ListenerId vnid_
Definition: dhcp_proto.h:141
std::pair< Interface *, DhcpLeaseDb * > LeaseManagerPair
Definition: dhcp_proto.h:34
bool LeaseFileCleanupExpiry(uint32_t seqno)
Definition: dhcp_proto.cc:261
DBTableBase::ListenerId iid_
Definition: dhcp_proto.h:140
void VnNotify(DBEntryBase *entry)
Definition: dhcp_proto.cc:216
bool run_with_vrouter_
Definition: dhcp_proto.h:134
void ReadHandler(const boost::system::error_code &error, std::size_t len)
Definition: dhcp_proto.cc:93
void set_ip_fabric_interface(Interface *itf)
Definition: dhcp_proto.h:81
uint8_t * dhcp_server_read_buf_
Definition: dhcp_proto.h:146
void set_ip_fabric_interface_mac(const MacAddress &mac)
Definition: dhcp_proto.h:97
DhcpLeaseDb * GetLeaseDb(Interface *intrface)
Definition: dhcp_proto.cc:227
std::set< VmInterface * > gw_vmi_list_
Definition: dhcp_proto.h:148
boost::asio::ip::udp::endpoint remote_endpoint_
Definition: dhcp_proto.h:145
static const uint32_t kDhcpLeaseFileDeleteTimeout
Definition: dhcp_proto.h:27
void set_ip_fabric_interface_index(uint32_t ind)
Definition: dhcp_proto.h:85
DhcpProto(Agent *agent, boost::asio::io_context &io, bool run_with_vrouter)
Definition: dhcp_proto.cc:20
std::string GetLeaseFileName(const VmInterface *vmi)
Definition: dhcp_proto.cc:235
void SendDhcpIpc(uint8_t *dhcp, std::size_t len)
Definition: dhcp_proto.cc:109
void set_pkt_interface_index(uint32_t ind)
Definition: dhcp_proto.h:91
void CreateLeaseDb(VmInterface *vmi)
Definition: dhcp_proto.cc:159
@ VM_INTERFACE
Definition: interface.h:38
@ PHYSICAL
Definition: interface.h:32
const MacAddress & mac() const
Definition: interface.h:134
const std::string & name() const
Definition: interface.h:117
const boost::uuids::uuid & GetUuid() const
Definition: interface.h:116
Type type() const
Definition: interface.h:115
const uint32_t id() const
Definition: interface.h:126
void SendMessage(PktModuleName mod, InterTaskMsg *msg)
PktHandler * pkt_handler() const
Definition: pkt_init.h:32
boost::asio::io_context & io_
static TaskScheduler * GetInstance()
Definition: task.cc:574
static bool DeleteTimer(Timer *Timer)
Definition: timer.cc:222
static Timer * CreateTimer(boost::asio::io_context &service, const std::string &name, int task_id=Timer::GetTimerTaskId(), int task_instance=Timer::GetTimerInstanceId(), bool delete_on_completion=false)
Definition: timer.cc:201
bool Cancel()
Definition: timer.cc:150
bool Start(int time, Handler handler, ErrorHandler error_handler=NULL)
Definition: timer.cc:108
Definition: trace.h:289
VmInterface::VmiType vmi_type() const
const uint8_t subnet_plen() const
const VnEntry * vn() const
const Ip4Address & primary_ip_addr() const
const Ip4Address & subnet() const
Definition: vn.h:152
const VnIpam * GetIpam(const IpAddress &ip) const
Definition: vn.cc:653
void SetBounded(bool bounded)
Definition: queue_task.h:201
void SetSize(size_t size)
Definition: queue_task.h:197
#define DHCP_TRACE(obj, arg)
Definition: dhcp_proto.h:12
Definition: io_utils.cc:12
#define DHCP_SERVER_PORT
Definition: pkt_handler.h:29
static std::string UuidToString(const boost::uuids::uuid &id)
Definition: string_util.h:139
Definition: vn.h:29
IpAddress dns_server
Definition: vn.h:34
IpAddress default_gw
Definition: vn.h:32