views.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. #!/usr/bin/env python
  2. # Licensed to Cloudera, Inc. under one
  3. # or more contributor license agreements. See the NOTICE file
  4. # distributed with this work for additional information
  5. # regarding copyright ownership. Cloudera, Inc. licenses this file
  6. # to you under the Apache License, Version 2.0 (the
  7. # "License"); you may not use this file except in compliance
  8. # with the License. You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing, software
  13. # distributed under the License is distributed on an "AS IS" BASIS,
  14. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. # See the License for the specific language governing permissions and
  16. # limitations under the License.
  17. import logging
  18. import os
  19. import sys
  20. import tempfile
  21. import time
  22. import traceback
  23. import zipfile
  24. from django.shortcuts import render_to_response
  25. from django.http import HttpResponse
  26. from django.core.servers.basehttp import FileWrapper
  27. import django.views.debug
  28. from desktop.lib import django_mako
  29. from desktop.lib.django_util import login_notrequired, render_json, render, render_to_string
  30. from desktop.lib.paths import get_desktop_root
  31. from desktop.log.access import access_log_level, access_warn
  32. from desktop.models import UserPreferences
  33. from desktop import appmanager
  34. import desktop.conf
  35. import desktop.log.log_buffer
  36. from django.utils.translation import ugettext as _
  37. LOG = logging.getLogger(__name__)
  38. @access_log_level(logging.WARN)
  39. def log_view(request):
  40. """
  41. We have a log handler that retains the last X characters of log messages.
  42. If it is attached to the root logger, this view will display that history,
  43. otherwise it will report that it can't be found.
  44. """
  45. l = logging.getLogger()
  46. for h in l.handlers:
  47. if isinstance(h, desktop.log.log_buffer.FixedBufferHandler):
  48. return render('logs.mako', request, dict(log=[l for l in h.buf]))
  49. return render('logs.mako', request, dict(log=[_("No logs found!")]))
  50. @access_log_level(logging.WARN)
  51. def download_log_view(request):
  52. """
  53. Zip up the log buffer and then return as a file attachment.
  54. """
  55. l = logging.getLogger()
  56. for h in l.handlers:
  57. if isinstance(h, desktop.log.log_buffer.FixedBufferHandler):
  58. try:
  59. # We want to avoid doing a '\n'.join of the entire log in memory
  60. # in case it is rather big. So we write it to a file line by line
  61. # and pass that file to zipfile, which might follow a more efficient path.
  62. tmp = tempfile.NamedTemporaryFile()
  63. log_tmp = tempfile.NamedTemporaryFile("w+t")
  64. for l in h.buf:
  65. log_tmp.write(l + '\n')
  66. # This is not just for show - w/out flush, we often get truncated logs
  67. log_tmp.flush()
  68. t = time.time()
  69. zip = zipfile.ZipFile(tmp, "w", zipfile.ZIP_DEFLATED)
  70. zip.write(log_tmp.name, "hue-logs/hue-%s.log" % t)
  71. zip.close()
  72. length = tmp.tell()
  73. # if we don't seek to start of file, no bytes will be written
  74. tmp.seek(0)
  75. wrapper = FileWrapper(tmp)
  76. response = HttpResponse(wrapper,content_type="application/zip")
  77. response['Content-Disposition'] = 'attachment; filename=hue-logs-%s.zip' % t
  78. response['Content-Length'] = length
  79. return response
  80. except Exception, e:
  81. logging.exception("Couldn't construct zip file to write logs to!")
  82. return log_view(request)
  83. return render_to_response("logs.mako", dict(log=[_("No logs found!")]))
  84. @access_log_level(logging.DEBUG)
  85. def prefs(request, key=None):
  86. """Get or set preferences."""
  87. if key is None:
  88. d = dict( (x.key, x.value) for x in UserPreferences.objects.filter(user=request.user))
  89. return render_json(d)
  90. else:
  91. if "set" in request.REQUEST:
  92. try:
  93. x = UserPreferences.objects.get(user=request.user, key=key)
  94. except UserPreferences.DoesNotExist:
  95. x = UserPreferences(user=request.user, key=key)
  96. x.value = request.REQUEST["set"]
  97. x.save()
  98. return render_json(True)
  99. if "delete" in request.REQUEST:
  100. try:
  101. x = UserPreferences.objects.get(user=request.user, key=key)
  102. x.delete()
  103. return render_json(True)
  104. except UserPreferences.DoesNotExist:
  105. return render_json(False)
  106. else:
  107. try:
  108. x = UserPreferences.objects.get(user=request.user, key=key)
  109. return render_json(x.value)
  110. except UserPreferences.DoesNotExist:
  111. return render_json(None)
  112. def bootstrap(request):
  113. """Concatenates bootstrap.js files from all installed Hue apps."""
  114. # Has some None's for apps that don't have bootsraps.
  115. all_bootstraps = [ (app, app.get_bootstrap_file()) for app in appmanager.DESKTOP_APPS if request.user.has_hue_permission(action="access", app=app.name) ]
  116. # Iterator over the streams.
  117. concatenated = [ "\n/* %s */\n%s" % (app.name, b.read()) for app, b in all_bootstraps if b is not None ]
  118. # HttpResponse can take an iteratable as the first argument, which
  119. # is what happens here.
  120. return HttpResponse(concatenated, mimetype='text/javascript')
  121. _status_bar_views = []
  122. def register_status_bar_view(view):
  123. global _status_bar_views
  124. _status_bar_views.append(view)
  125. @access_log_level(logging.DEBUG)
  126. def status_bar(request):
  127. """
  128. Concatenates multiple views together to build up a "status bar"/"status_bar".
  129. These views are registered using register_status_bar_view above.
  130. """
  131. resp = ""
  132. for view in _status_bar_views:
  133. try:
  134. r = view(request)
  135. if r.status_code == 200:
  136. resp += r.content
  137. else:
  138. LOG.warning("Failed to execute status_bar view %s" % (view,))
  139. except:
  140. LOG.exception("Failed to execute status_bar view %s" % (view,))
  141. return HttpResponse(resp)
  142. def dump_config(request):
  143. # Note that this requires login (as do most apps).
  144. show_private = False
  145. conf_dir = os.path.realpath(get_desktop_root('conf'))
  146. if not request.user.is_superuser:
  147. return HttpResponse(_("You must be a superuser."))
  148. if request.GET.get("private"):
  149. show_private = True
  150. return render("dump_config.mako", request, dict(
  151. show_private=show_private,
  152. top_level=desktop.lib.conf.GLOBAL_CONFIG,
  153. conf_dir=conf_dir,
  154. apps=appmanager.DESKTOP_MODULES))
  155. if sys.version_info[0:2] <= (2,4):
  156. def _threads():
  157. import threadframe
  158. return threadframe.dict().iteritems()
  159. else:
  160. def _threads():
  161. return sys._current_frames().iteritems()
  162. @access_log_level(logging.WARN)
  163. def threads(request):
  164. """Dumps out server threads. Useful for debugging."""
  165. if not request.user.is_superuser:
  166. return HttpResponse(_("You must be a superuser."))
  167. out = []
  168. for thread_id, stack in _threads():
  169. out.append("Thread id: %s" % thread_id)
  170. for filename, lineno, name, line in traceback.extract_stack(stack):
  171. out.append(" %-20s %s(%d)" % (name, filename, lineno))
  172. out.append(" %-80s" % (line))
  173. out.append("")
  174. return HttpResponse("\n".join(out), content_type="text/plain")
  175. @login_notrequired
  176. def index(request):
  177. return render("index.mako", request, dict(
  178. feedback_url=desktop.conf.FEEDBACK_URL.get(),
  179. send_dbug_messages=desktop.conf.SEND_DBUG_MESSAGES.get()
  180. ))
  181. def serve_404_error(request, *args, **kwargs):
  182. """Registered handler for 404. We just return a simple error"""
  183. access_warn(request, "404 not found")
  184. return render("404.mako", request, dict(uri=request.build_absolute_uri()))
  185. def serve_500_error(request, *args, **kwargs):
  186. """Registered handler for 500. We use the debug view to make debugging easier."""
  187. if desktop.conf.HTTP_500_DEBUG_MODE.get():
  188. return django.views.debug.technical_500_response(request, *sys.exc_info())
  189. return render("500.mako", request, {'traceback': traceback.extract_tb(sys.exc_info()[2])})
  190. _LOG_LEVELS = {
  191. "critical": logging.CRITICAL,
  192. "error": logging.ERROR,
  193. "warning": logging.WARNING,
  194. "info": logging.INFO,
  195. "debug": logging.DEBUG
  196. }
  197. _MAX_LOG_FRONTEND_EVENT_LENGTH = 1024
  198. _LOG_FRONTEND_LOGGER = logging.getLogger("desktop.views.log_frontend_event")
  199. @login_notrequired
  200. def log_frontend_event(request):
  201. """
  202. Logs arguments to server's log. Returns an
  203. empty string.
  204. Parameters (specified via either GET or POST) are
  205. "logname", "level" (one of "debug", "info", "warning",
  206. "error", or "critical"), and "message".
  207. """
  208. def get(param, default=None):
  209. return request.REQUEST.get(param, default)
  210. level = _LOG_LEVELS.get(get("level"), logging.INFO)
  211. msg = "Untrusted log event from user %s: %s" % (
  212. request.user,
  213. get("message", "")[:_MAX_LOG_FRONTEND_EVENT_LENGTH])
  214. _LOG_FRONTEND_LOGGER.log(level, msg)
  215. return HttpResponse("")
  216. def who_am_i(request):
  217. """
  218. Returns username and FS username, and optionally sleeps.
  219. """
  220. try:
  221. sleep = float(request.REQUEST.get("sleep") or 0.0)
  222. except ValueError:
  223. sleep = 0.0
  224. time.sleep(sleep)
  225. return HttpResponse(request.user.username + "\t" + request.fs.user + "\n")
  226. def commonheader(title, section, user, padding="60px"):
  227. """
  228. Returns the rendered common header
  229. """
  230. apps_list = sorted(appmanager.get_apps(user), key=lambda app: app.menu_index)
  231. return django_mako.render_to_string("common_header.mako", dict(
  232. apps=apps_list,
  233. title=title,
  234. section=section,
  235. padding=padding,
  236. user=user
  237. ))
  238. def commonfooter(messages=None):
  239. """
  240. Returns the rendered common footer
  241. """
  242. if messages is None:
  243. messages = {}
  244. return render_to_string("common_footer.html", {'messages': messages})
  245. # If the app's conf.py has a config_validator() method, call it.
  246. CONFIG_VALIDATOR = 'config_validator'
  247. #
  248. # Cache config errors because (1) they mostly don't go away until restart,
  249. # and (2) they can be costly to compute. So don't stress the system just because
  250. # the dock bar wants to refresh every n seconds.
  251. #
  252. # The actual viewing of all errors may choose to disregard the cache.
  253. #
  254. _CONFIG_ERROR_LIST = None
  255. def _get_config_errors(cache=True):
  256. """Returns a list of (confvar, err_msg) tuples."""
  257. global _CONFIG_ERROR_LIST
  258. if not cache or _CONFIG_ERROR_LIST is None:
  259. error_list = [ ]
  260. for module in appmanager.DESKTOP_MODULES:
  261. # Get the config_validator() function
  262. try:
  263. validator = getattr(module.conf, CONFIG_VALIDATOR)
  264. except AttributeError:
  265. continue
  266. if not callable(validator):
  267. LOG.warn("Auto config validation: %s.%s is not a function" %
  268. (module.conf.__name__, CONFIG_VALIDATOR))
  269. continue
  270. try:
  271. error_list.extend(validator())
  272. except Exception, ex:
  273. LOG.exception("Error in config validation by %s: %s" % (module.nice_name, ex))
  274. _CONFIG_ERROR_LIST = error_list
  275. return _CONFIG_ERROR_LIST
  276. def check_config(request):
  277. """Check config and view for the list of errors"""
  278. if not request.user.is_superuser:
  279. return HttpResponse(_("You must be a superuser."))
  280. conf_dir = os.path.realpath(get_desktop_root('conf'))
  281. return render('check_config.mako', request, dict(
  282. error_list=_get_config_errors(cache=False),
  283. conf_dir=conf_dir))
  284. def check_config_ajax(request):
  285. """Alert administrators about configuration problems."""
  286. if not request.user.is_superuser:
  287. return HttpResponse('')
  288. error_list = _get_config_errors()
  289. if not error_list:
  290. # Return an empty response, rather than using the mako template, for performance.
  291. return HttpResponse('')
  292. return render('config_alert_dock.mako',
  293. request,
  294. dict(error_list=error_list),
  295. force_template=True)
  296. register_status_bar_view(check_config_ajax)