OpenSDN source code
sandesh_http.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 //
7 // sandesh_http.cc
8 //
9 // Implementation of SandeshHttp
10 //
11 // - Register each .sandesh file for generating webpage with all Requests
12 // - API for Registering Sandesh Requests so they can be served by HttpServer
13 // - Init and Uninit of HttpServer
14 //
15 
16 #include <cstring>
17 #include <cstdlib>
18 #include <mutex>
19 
20 #include "io/event_manager.h"
21 #include "http/http_server.h"
22 #include <boost/bind/bind.hpp>
23 #include <boost/tokenizer.hpp>
24 
25 #include <sandesh/sandesh_types.h>
26 #include <sandesh/sandesh.h>
27 #include <sandesh/sandesh_http.h>
28 #include <sandesh/transport/TBufferTransports.h>
29 #include <sandesh/protocol/TXMLProtocol.h>
30 #include "sandesh_client.h"
31 #include <sandesh/sandesh_trace.h>
32 #include <sandesh/sandesh_trace_types.h>
33 
34 #include "http/http_request.h"
35 #include "http/http_server.h"
36 #include "http/http_session.h"
37 
38 #include "css_bootstrap_min_css.cpp"
39 #include "css_DT_bootstrap_css.cpp"
40 #include "css_images_sort_asc_png.cpp"
41 #include "css_images_sort_asc_disabled_png.cpp"
42 #include "css_images_sort_both_png.cpp"
43 #include "css_images_sort_desc_png.cpp"
44 #include "css_images_sort_desc_disabled_png.cpp"
45 #include "css_style_css.cpp"
46 #include "js_bootstrap_min_js.cpp"
47 #include "js_DT_bootstrap_js.cpp"
48 #include "js_jquery_2_0_3_min_js.cpp"
49 #include "js_jquery_dataTables_min_js.cpp"
50 #include "js_util_js.cpp"
51 #include "universal_parse_xsl.cpp"
52 
53 
54 static int kEncodeBufferSize = 4096;
55 
56 using namespace contrail::sandesh::protocol;
57 using namespace std;
58 using namespace boost::placeholders;
59 
61 
66 
67 
68 #define SESSION_SEND(buf) \
69  HttpSession::SendSession(context,reinterpret_cast<const u_int8_t *>(buf), strlen(buf), NULL)
70 
75  HXMLMax
76 };
77 
78 // Helper function for forming HTTP headers and sending a bytestream
79 // for XML
80 //
81 // Arguments:
82 // context : handle to Session on which to send bytestream
83 // buf : Buffer that contains XML payload
84 // len : length of buffer
85 // name : Name of Sandesh Module
86 // more : This is true if there is more content coming for this response
87 //
88 static void
89 HttpSendXML(const std::string& context, const u_int8_t * buf, uint32_t len,
90  const char * name, bool more) {
91 
92  char buffer_str[100];
93  char length_str[80];
94  static const char xsl_response[] =
95 "HTTP/1.1 200 OK\r\n"
96 "Content-Type: text/xml\r\n"
97 ;
98  static const char chunk_response[] =
99 "HTTP/1.1 200 OK\r\n"
100 "Content-Type: text/xml\r\n"
101 "Transfer-Encoding: chunked\r\n\r\n"
102 ;
103  char resp_name[40];
104  int loc = strcspn(reinterpret_cast<const char *>(buf)," ");
105  strncpy(resp_name, reinterpret_cast<const char *>(buf + 1), loc - 1);
106  resp_name[loc - 1] = 0;
107 
108  static std::mutex hmutex;
109  static int seq = 0;
110  std::scoped_lock lock(hmutex);
111  std::string client_ctx;
112  seq++;
113 
114  client_ctx = HttpSession::get_client_context(context);
115  HttpXMLState state;
116 
117  // Calculate current state;
118  if (!client_ctx.empty()) {
119  state = HXMLIncomplete;
120  } else {
121  state = HXMLNew;
122  client_ctx = resp_name;
123 
124  // If the session is gone, we can stop processing.
125  if (!HttpSession::set_client_context(context, client_ctx))
126  return;
127  }
128 
129  if ((HXMLNew == state) && (!more)) {
130  // This is the first and last chunk of this response
131 
132  SESSION_SEND(xsl_response);
133 
134  size_t total_len = len;
135  sprintf(buffer_str,
136  "<?xml-stylesheet type=\"text/xsl\" href=\"/universal_parse.xsl\"?>"
137  );
138  sprintf(length_str,
139  "Content-Length: %zu\r\n\r\n", total_len + strlen(buffer_str));
140  SESSION_SEND(length_str);
141  SESSION_SEND(buffer_str);
142 
143  HttpSession::SendSession(context, buf, len, NULL);
144 
145  } else if ((HXMLNew == state) && more) {
146  // This is the first chunk of this response
147  SESSION_SEND(chunk_response);
148 
149  // Calculation for Header
150  sprintf(buffer_str,
151  "<?xml-stylesheet type=\"text/xsl\" href=\"/universal_parse.xsl\"?>"
152  );
153  int hdr_len = strlen(buffer_str);
154  sprintf(buffer_str,
155  "<__%s_list type=\"slist\">\r\n", client_ctx.c_str());
156  hdr_len += (strlen(buffer_str) - 2);
157 
158  sprintf(length_str, "%x\r\n", hdr_len);
159  SESSION_SEND(length_str);
160 
161  sprintf(buffer_str,
162  "<?xml-stylesheet type=\"text/xsl\" href=\"/universal_parse.xsl\"?>"
163  );
164  SESSION_SEND(buffer_str);
165 
166  sprintf(buffer_str,
167  "<__%s_list type=\"slist\">\r\n", client_ctx.c_str());
168  SESSION_SEND(buffer_str);
169 
170 
171  // Calculation for Data
172  sprintf(length_str, "%x\r\n", len);
173  SESSION_SEND(length_str);
174 
175  HttpSession::SendSession(context, buf, len, NULL);
176 
177  sprintf(buffer_str,"\r\n");
178  SESSION_SEND(buffer_str);
179 
180  } else if ((HXMLIncomplete == state) && !more) {
181  // This is the last chunk of this response
182 
183  // Calculation for Data
184  sprintf(length_str, "%x\r\n", len);
185  SESSION_SEND(length_str);
186 
187  HttpSession::SendSession(context, buf, len, NULL);
188 
189  sprintf(buffer_str,"\r\n");
190  SESSION_SEND(buffer_str);
191 
192  //Calculation for Footer
193  sprintf(buffer_str,"</__%s_list>\r\n", client_ctx.c_str());
194  sprintf(length_str, "%zx\r\n", strlen(buffer_str) - 2);
195  SESSION_SEND(length_str);
196  SESSION_SEND(buffer_str);
197 
198  sprintf(length_str, "0\r\n\r\n");
199  SESSION_SEND(length_str);
200  } else if ((HXMLIncomplete == state) && more) {
201  // This is a middle chunk of the response
202 
203  // Calculation for Data
204  sprintf(length_str, "%x\r\n", len);
205  SESSION_SEND(length_str);
206 
207  HttpSession::SendSession(context, buf, len, NULL);
208 
209  sprintf(buffer_str,"\r\n");
210  SESSION_SEND(buffer_str);
211  }
212  // Update context for other users
213  if (!more) {
214  client_ctx = resp_name;
216  }
217 
218 }
219 
220 // Function for HTTP Server to call when HTTP Client Requests a .sandesh module
221 // or it's stylesheet
222 //
223 // Arguments:
224 // hti : Buffer Ptr and length of HTTP payload to send
225 // session : HttpSession on which to send
226 // request : Contains the URL that was sent by the Client
227 //
228 static void
230  HttpSession *session,
231  const HttpRequest *request) {
232 
233  char length_str[80];
234  static const char html_response[] =
235 "HTTP/1.1 200 OK\r\n"
236 ;
237  static const char json_response[] =
238 "HTTP/1.1 200 OK\r\n"
239 "Content-Type: application/json\r\n"
240 ;
241  static const char xsl_response[] =
242 "HTTP/1.1 200 OK\r\n"
243 "Content-Type: text/xsl\r\n"
244 ;
245  static const char xml_response[] =
246 "HTTP/1.1 200 OK\r\n"
247 "Content-Type: text/xml\r\n"
248 ;
249  static const char css_response[] =
250 "HTTP/1.1 200 OK\r\n"
251 "Content-Type: text/css\r\n"
252 ;
253  const char * response =
254  ((request->UrlPath().find(".js")!=string::npos) ?
255  json_response : ((request->UrlPath().find(".xsl")!=string::npos) ?
256  xsl_response : ((request->UrlPath().find(".css")!=string::npos) ?
257  css_response : ((request->UrlPath().find(".xml")!=string::npos) ?
258  xml_response : html_response))));
259 
260  sprintf(length_str,
261  "Content-Length: %d\r\n\r\n", hti->html_len());
262  session->Send(reinterpret_cast<const u_int8_t *>(response),
263  strlen(response), NULL);
264  session->Send(reinterpret_cast<const u_int8_t *>(length_str),
265  strlen(length_str), NULL);
266  session->Send(hti->html_str(), hti->html_len(), NULL);
267  delete request;
268 }
269 
271 
272 // Function for HTTP Server to call when HTTP Client sends a Sandesh Request
273 //
274 // Arguments:
275 // hs : Ptr to the HTTP Server
276 // session : HttpSession on which to send
277 // request : Contains the URL that was sent by the Client
278 // This URL encodes the attributes of the Sandesh Request
279 //
280 static void
282  HttpSession *session,
283  const HttpRequest *request) {
284 
285  string snh_name = request->UrlPath().substr(5);
287  if (sandesh == NULL) {
288  SANDESH_LOG(DEBUG, __func__ << " Unknown sandesh:" <<
289  snh_name << std::endl);
290  return;
291  }
292  SandeshRequest *rsnh = dynamic_cast<SandeshRequest *>(sandesh);
293  assert(rsnh);
294  rsnh->RequestFromHttp(session->get_context(), request->UrlQuery());
295  httpreqcb(rsnh);
296  delete request;
297 }
298 
299 // This function is called by the Sandesh Response handling code
300 // if the "context" of the Originating Sandesh Request indicates
301 // that the Request came from the HTTP Server
302 // We will form a HTTP/XML payload to send the contents of the Sandesh
303 // response back to the HTTP Client
304 //
305 // Arguments:
306 // snh : Sandesh Response to send to the HTTP Client (base class)
307 // context: Context that was in the Sandesh Request.
308 // All HTTP Server-originated contexts start with "http%"
309 //
310 void
311 SandeshHttp::Response(Sandesh *snh, std::string context) {
312  bool more = false;
313 
314  SandeshResponse * rsnh = dynamic_cast<SandeshResponse *>(snh);
315  if (rsnh) {
316  more = rsnh->get_more();
317  } else {
318  SandeshTrace * tsnh = dynamic_cast<SandeshTrace *>(snh);
319  if (tsnh) {
320  more = tsnh->get_more();
321  } else {
322  SandeshUVE * usnh = dynamic_cast<SandeshUVE *>(snh);
323  assert(usnh);
324  more = usnh->get_more();
325  }
326  }
327  std::stringstream ss;
328  uint8_t *buffer;
329  uint32_t xfer = 0, offset;
330 
331  boost::shared_ptr<TMemoryBuffer> btrans =
332  boost::shared_ptr<TMemoryBuffer>(
334  boost::shared_ptr<TXMLProtocol> prot =
335  boost::shared_ptr<TXMLProtocol>(
336  new TXMLProtocol(btrans));
337  // Write the sandesh
338  xfer += snh->Write(prot);
339  // Get the buffer
340  btrans->getBuffer(&buffer, &offset);
341  HttpSendXML(context, buffer, offset, snh->ModuleName().c_str(), more);
342  buffer[offset] = 0;
343  snh->Release();
344 }
345 
346 // This function should be called during Sandesh Generator Initialization
347 // It initializes the HTTP Server and Registers callbacks for sandesh modules
348 // and sandesh requests.
349 //
350 // Arguments:
351 // evm : EventManager that should be used by the HTTP Server
352 // module : Name of module
353 // port : Port number for HTTP Server (e.g. 8080)
354 //
355 bool
356 SandeshHttp::Init(EventManager *evm, const string module,
357  short port, RequestCallbackFn reqcb, int *hport, const SandeshConfig &config) {
358  if (hServ_) {
359  *hport = hServ_->GetPort();
360  return true;
361  }
362  ostringstream index_ss;
363 
364  SandeshTraceBufferPtr httpbuf(SandeshTraceBufferCreate("httpbuf", 100));
365  SANDESH_TRACE_TEXT_TRACE(httpbuf, "<Initializing httpbuf");
366  SANDESH_TRACE_TEXT_TRACE(httpbuf, "Size 100");
367 
368  uint8_t dscp = 0;
369  SandeshClient *client = Sandesh::client();
370  if (client) {
371  dscp = client->dscp_value();
372  }
373  struct SslConfig sslConfig;
374  sslConfig.ssl_enabled = config.introspect_ssl_enable;
375  sslConfig.ca_cert = config.ca_cert;
376  sslConfig.certfile = config.server_certfile;
377  sslConfig.keyfile = config.server_keyfile;
378  sslConfig.ssl_insecure = config.introspect_ssl_insecure;
379  hServ_ = new HttpServer(evm, sslConfig, dscp);
380  httpreqcb = reqcb;
381  index_ss << "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"" <<
382  " \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">" << endl;
383  index_ss << "<html xmlns=\"http://www.w3.org/1999/xhtml\">" << endl;
384  index_ss << "<head>" <<
385  "<link href=\"css/style.css\" rel=\"stylesheet\" type=\"text/css\"/>" <<
386  "<title>" << module << "</title></head><body>" << endl;
387  index_ss << "<h1>Modules for " << module << "</h1>" << endl;
388 
389  for (map_type::iterator it=map_->begin(); it!=map_->end(); it++) {
390  std::string regString = "/" + it->first;
391  hServ_->RegisterHandler(regString.c_str(),
392  boost::bind(&HttpSandeshFileCallback, &it->second, _1, _2));
393  if (it->first.find(".xml")!=string::npos) {
394  index_ss << "<a href=\"" << it->first << "\">" <<
395  it->first << "</a><br/>" << endl;
396  }
397  }
398  index_ss << "</body></html>" << endl;
399 
400  index_str_ = index_ss.str();
401  const char * index_str = index_str_.c_str();
402  SANDESH_LOG(DEBUG, "HTTP Introspect Init");
403 
404  index_hti_ = new HtmlInfo(reinterpret_cast<const unsigned char *>(
405  index_str),strlen(index_str));
406  hServ_->RegisterHandler("/index.html",
407  boost::bind(&HttpSandeshFileCallback, index_hti_, _1, _2));
408  hServ_->RegisterHandler("/",
409  boost::bind(&HttpSandeshFileCallback, index_hti_, _1, _2));
410 
411  SandeshBaseFactory::map_type::const_iterator it= SandeshBaseFactory::Begin();
412  for (; it!=SandeshBaseFactory::End(); it++) {
413  std::string regString = "/Snh_" + (*it).first;
414  hServ_->RegisterHandler(regString.c_str(),
415  boost::bind(&HttpSandeshRequestCallback, hServ_, _1, _2));
416  }
417 
418  boost::system::error_code ec;
419  bool success;
420  IpAddress http_ip =
421  boost::asio::ip::address::from_string(config.http_server_ip, ec);
422  if (!ec) {
423  success = hServ_->Initialize(port, http_ip);
424  } else {
425  success = hServ_->Initialize(port);
426  }
427  hServ_->SetSocketOptions(config);
428  if (success) {
429  int lport(hServ_->GetPort());
430  SANDESH_LOG(DEBUG, "Sandesh Http Server Port: " << lport);
431  *hport = lport;
432  return true;
433  } else {
434  SANDESH_LOG(ERROR, "Failed to initialize Sandesh Http Server Port: "
435  << port);
436  return false;
437  }
438  if (dscp) {
439  hServ_->SetListenSocketDscp(dscp);
440  }
441 }
442 
443 // Function to shut down HTTP Server
444 void
446  if (!hServ_) return;
447 
448  index_str_.clear();
449  delete index_hti_;
450 
451  hServ_->Shutdown();
452  hServ_->ClearSessions();
453  hServ_->WaitForEmpty();
454 
455  //
456  // TODO TcpServer delete can only happen after all inflight sessions
457  // have been properly deleted. ASIO threads can hold reference to
458  // HttpSession objects
459  //
461  hServ_ = NULL;
462 }
463 
464 void
465 SandeshHttp::UpdateDscp(uint8_t dscp) {
466  if (!hServ_) return;
467  hServ_->UpdateDscp(dscp);
468  hServ_->UpdateSessionsDscp(dscp);
469 }
boost::asio::ip::address IpAddress
Definition: address.h:14
std::string UrlQuery() const
Definition: http_request.cc:37
std::string UrlPath() const
Definition: http_request.cc:26
static map_type::const_iterator End()
Definition: cpp/sandesh.h:647
static map_type::const_iterator Begin()
Definition: cpp/sandesh.h:646
static Sandesh * CreateInstance(std::string const &s)
Definition: cpp/sandesh.h:626
uint8_t dscp_value() const
unsigned int html_len() const
Definition: sandesh_http.h:42
const unsigned char * html_str() const
Definition: sandesh_http.h:41
static HttpServer * hServ_
Definition: sandesh_http.h:72
static std::string index_str_
Definition: sandesh_http.h:73
static void UpdateDscp(uint8_t dscp)
static HtmlInfo * index_hti_
Definition: sandesh_http.h:74
static void Response(Sandesh *snh, std::string context)
boost::function< int32_t(SandeshRequest *)> RequestCallbackFn
Definition: sandesh_http.h:28
static bool Init(EventManager *evm, const std::string module, short port, RequestCallbackFn reqcb, int *hport, const SandeshConfig &config=SandeshConfig())
static void Uninit(void)
static map_type * map_
Definition: sandesh_http.h:71
std::map< std::string, HtmlInfo > map_type
Definition: sandesh_http.h:62
virtual bool RequestFromHttp(const std::string &ctx, const std::string &snh_query)=0
virtual const bool get_more() const =0
const bool get_more() const
Definition: cpp/sandesh.h:535
const bool get_more() const
Definition: cpp/sandesh.h:574
virtual int32_t Write(boost::shared_ptr< contrail::sandesh::protocol::TProtocol > oprot) const =0
virtual void Release()
Definition: cpp/sandesh.h:269
static SandeshClient * client()
Definition: cpp/sandesh.h:309
virtual std::string ModuleName() const =0
static void DeleteServer(TcpServer *server)
Definition: tcp_server.cc:659
virtual bool Send(const uint8_t *data, size_t size, size_t *sent)
Definition: tcp_session.cc:430
static EventManager evm
#define SANDESH_LOG(_Level, _Msg)
Definition: cpp/sandesh.h:477
static int kEncodeBufferSize
Definition: sandesh_http.cc:54
static void HttpSandeshRequestCallback(HttpServer *hs, HttpSession *session, const HttpRequest *request)
SandeshHttp::RequestCallbackFn httpreqcb
static void HttpSandeshFileCallback(SandeshHttp::HtmlInfo *hti, HttpSession *session, const HttpRequest *request)
HttpXMLState
Definition: sandesh_http.cc:71
@ HXMLInvalid
Definition: sandesh_http.cc:72
@ HXMLNew
Definition: sandesh_http.cc:73
@ HXMLMax
Definition: sandesh_http.cc:75
@ HXMLIncomplete
Definition: sandesh_http.cc:74
static void HttpSendXML(const std::string &context, const u_int8_t *buf, uint32_t len, const char *name, bool more)
Definition: sandesh_http.cc:89
#define SESSION_SEND(buf)
Definition: sandesh_http.cc:68
boost::shared_ptr< TraceBuffer< SandeshTrace > > SandeshTraceBufferPtr
Definition: sandesh_trace.h:19
SandeshTraceBufferPtr SandeshTraceBufferCreate(const std::string &buf_name, size_t buf_size, bool trace_enable=true)
Definition: sandesh_trace.h:47
static bool set_client_context(std::string const &s, const std::string &ctx)
Definition: http_session.h:41
const std::string get_client_context()
Definition: http_session.h:81
static bool SendSession(std::string const &s, const uint8_t *data, size_t size, size_t *sent)
Definition: http_session.h:30
const std::string get_context()
Definition: http_session.h:28
std::string server_keyfile
bool introspect_ssl_insecure
std::string server_certfile
std::string http_server_ip
std::string ca_cert
bool introspect_ssl_enable
std::string ca_cert
Definition: http_server.h:25
std::string certfile
Definition: http_server.h:24
bool ssl_enabled
Definition: http_server.h:26
std::string keyfile
Definition: http_server.h:23
bool ssl_insecure
Definition: http_server.h:27