Menu

[r8622]: / trunk / gui / system / views.py  Maximize  Restore  History

Download this file

408 lines (344 with data), 14.3 kB

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
#+
# Copyright 2010 iXsystems, Inc.
# All rights reserved
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted providing that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
# STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
# IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# $FreeBSD$
#####################################################################
import commands
import os
import shutil
import subprocess
import time
from django.contrib.auth import login, get_backends
from django.contrib.auth.models import User
from django.core.servers.basehttp import FileWrapper
from django.http import HttpResponse
from django.shortcuts import render
from django.template.loader import render_to_string
from django.utils import simplejson
from django.utils.translation import ugettext as _
from django.core.urlresolvers import reverse
from freenasUI.common.system import get_sw_name, get_sw_version, send_mail
from freenasUI.freeadmin.views import JsonResponse
from freenasUI.middleware.notifier import notifier
from freenasUI.network.models import GlobalConfiguration
from freenasUI.system import forms, models
from freenasUI.system.terminal import Terminal, Multiplex
GRAPHS_DIR = '/var/db/graphs'
VERSION_FILE = '/etc/version'
DEBUG_TEMP = '/tmp/debug.txt'
def _system_info():
# OS, hostname, release
__, hostname, __ = os.uname()[0:3]
platform = subprocess.check_output(['sysctl', '-n', 'hw.model'])
physmem = str(int(int(subprocess.check_output(['sysctl', '-n', 'hw.physmem'])) / 1048576)) + 'MB'
# All this for a timezone, because time.asctime() doesn't add it in.
date = time.strftime('%a %b %d %H:%M:%S %Z %Y') + '\n'
uptime = commands.getoutput("env -u TZ uptime | awk -F', load averages:' '{ print $1 }'")
loadavg = "%.2f, %.2f, %.2f" % os.getloadavg()
freenas_build = "Unrecognized build (%s missing?)" % VERSION_FILE
try:
with open(VERSION_FILE) as d:
freenas_build = d.read()
except:
pass
return {
'hostname': hostname,
'platform': platform,
'physmem': physmem,
'date': date,
'uptime': uptime,
'loadavg': loadavg,
'freenas_build': freenas_build,
}
def system_info(request):
sysinfo = _system_info()
return render(request, 'system/system_info.html', sysinfo)
def config_restore(request):
if request.method == "POST":
notifier().config_restore()
user = User.objects.all()[0]
backend = get_backends()[0]
user.backend = "%s.%s" % (backend.__module__,
backend.__class__.__name__)
login(request, user)
return render(request, 'system/config_ok2.html')
return render(request, 'system/config_restore.html')
def config_upload(request):
if request.method == "POST":
form = forms.ConfigUploadForm(request.POST, request.FILES)
variables = {
'form': form,
}
if form.is_valid():
if not notifier().config_upload(request.FILES['config']):
form._errors['__all__'] = \
form.error_class([_('The uploaded file is not valid.'),])
else:
return render(request, 'system/config_ok.html', variables)
if request.GET.has_key('iframe'):
return HttpResponse('<html><body><textarea>' +
render_to_string('system/config_upload.html',
variables) +
'</textarea></boby></html>')
else:
return render(request, 'system/config_upload.html', variables)
else:
FIRMWARE_DIR = '/var/tmp/firmware'
if os.path.exists(FIRMWARE_DIR):
if os.path.islink(FIRMWARE_DIR):
os.unlink(FIRMWARE_DIR)
if os.path.isdir(FIRMWARE_DIR):
shutil.rmtree(FIRMWARE_DIR + '/')
os.mkdir(FIRMWARE_DIR)
os.chmod(FIRMWARE_DIR, 01777)
form = forms.ConfigUploadForm()
return render(request, 'system/config_upload.html', {
'form': form,
})
def config_save(request):
from django.core.servers.basehttp import FileWrapper
from network.models import GlobalConfiguration
hostname = GlobalConfiguration.objects.all().order_by('-id')[0].gc_hostname
filename = '/data/freenas-v1.db'
wrapper = FileWrapper(file(filename))
freenas_build = "UNKNOWN"
try:
with open(VERSION_FILE) as d:
freenas_build = d.read().strip()
except:
pass
response = HttpResponse(wrapper, content_type='application/octet-stream')
response['Content-Length'] = os.path.getsize(filename)
response['Content-Disposition'] = \
'attachment; filename=%s-%s-%s.db' % (hostname.encode('utf-8'), freenas_build, time.strftime('%Y%m%d%H%M%S'))
return response
def reporting(request):
graphs = {}
for gtype in ('hourly', 'daily', 'weekly', 'monthly', 'yearly', ):
graphs_dir = os.path.join(GRAPHS_DIR, gtype)
if os.path.isdir(graphs_dir):
graphs[gtype] = os.listdir(graphs_dir)
else:
graphs[gtype] = None
return render(request, 'system/reporting.html', {
'graphs': graphs,
})
def settings(request):
settings = models.Settings.objects.order_by("-id")[0].id
email = models.Email.objects.order_by("-id")[0].id
ssl = models.SSL.objects.order_by("-id")[0].id
advanced = models.Advanced.objects.order_by("-id")[0].id
return render(request, 'system/settings.html', {
'settings': settings,
'email': email,
'ssl': ssl,
'advanced': advanced,
})
def advanced(request):
extra_context = {}
advanced = forms.AdvancedForm(data = models.Advanced.objects.order_by("-id").values()[0], auto_id=False)
if request.method == 'POST':
advanced = forms.AdvancedForm(request.POST, auto_id=False)
if advanced.is_valid():
advanced.save()
extra_context['saved'] = True
extra_context.update({
'advanced': advanced,
})
return render(request, 'system/advanced.html', extra_context)
def varlogmessages(request, lines):
if lines is None:
lines = 3
msg = os.popen('tail -n %s /var/log/messages' % int(lines)).read().strip()
return render(request, 'system/status/msg.xml', {
'msg': msg,
}, content_type='text/xml')
def top(request):
top_pipe = os.popen('top')
try:
top_output = top_pipe.read()
finally:
top_pipe.close()
return render(request, 'system/status/top.xml', {
'focused_tab' : 'system',
'top': top_output,
}, content_type='text/xml')
def reboot(request):
""" reboots the system """
return render(request, 'system/reboot.html', {
'sw_name': get_sw_name(),
'sw_version': get_sw_version(),
})
def reboot_run(request):
notifier().restart("system")
return HttpResponse('OK')
def shutdown(request):
""" shuts down the system and powers off the system """
return render(request, 'system/shutdown.html', {
'sw_name': get_sw_name(),
'sw_version': get_sw_version(),
})
def shutdown_run(request):
notifier().stop("system")
return HttpResponse('OK')
def testmail(request):
error = False
if request.is_ajax():
sw_name = get_sw_name()
error, errmsg = send_mail(subject=_('Test message from %s'
% (sw_name)),
text=_('This is a message test from %s'
% (sw_name, )))
if error:
errmsg = _("Your test email could not be sent: %s") % errmsg
else:
errmsg = _('Your test email has been sent!')
return JsonResponse(error=error, message=errmsg)
def clearcache(request):
error = False
errmsg = ''
os.system("(/usr/local/bin/python /usr/local/www/freenasUI/tools/cachetool.py expire >/dev/null 2>&1 && /usr/local/bin/python /usr/local/www/freenasUI/tools/cachetool.py fill >/dev/null 2>&1) &")
return HttpResponse(simplejson.dumps({
'error': error,
'errmsg': errmsg,
}))
class DojoFileStore(object):
def __init__(self, path, dirsonly=False):
from storage.models import MountPoint
self.mp = [os.path.abspath(mp.mp_path) for mp in MountPoint.objects.filter(mp_volume__vol_fstype__in=('ZFS','UFS'))]
self.path = path.replace("..", "")
if not self.path.startswith('/mnt/'):
self.path = '/mnt/'+self.path
self.path = os.path.abspath(self.path)
self.dirsonly = dirsonly
self._lookupurl = 'system_dirbrowser' if self.dirsonly else 'system_filebrowser'
def items(self):
if self.path == '/mnt':
return self.children(self.path)
node = self._item(self.path, self.path)
if node['directory']:
node['children'] = self.children(self.path)
return node
def children(self, entry):
_children = [self._item(self.path, entry) for entry in os.listdir(entry) if len([f for f in self.mp if os.path.join(self.path, entry).startswith(f + '/') or os.path.join(self.path, entry) == f]) > 0]
if self.dirsonly:
_children = [child for child in _children if child['directory']]
return _children
def _item(self, path, entry):
full_path = os.path.join(path, entry)
isdir = os.path.isdir(full_path)
item = {
'name': os.path.basename(entry),
'directory': isdir,
'path': full_path,
}
if isdir:
item['children'] = True
item['$ref'] = os.path.abspath(reverse(self._lookupurl,
kwargs={ 'path' : full_path }))
item['id'] = item['$ref']
return item
def directory_browser(request, path='/'):
""" This view provides the ajax driven directory browser callback """
if not path.startswith('/'):
path = '/%s' % path
directories = DojoFileStore(path, dirsonly=True).items()
context = directories
content = simplejson.dumps(context)
return HttpResponse(content, mimetype='application/json')
def file_browser(request, path='/'):
""" This view provides the ajax driven directory browser callback """
if not path.startswith('/'):
path = '/%s' % path
directories = DojoFileStore(path, dirsonly=False).items()
context = directories
content = simplejson.dumps(context)
return HttpResponse(content, mimetype='application/json')
def cronjobs(request):
crons = models.CronJob.objects.all().order_by('id')
return render(request, "system/cronjob.html", {
'cronjobs': crons,
})
def smarttests(request):
tests = models.SMARTTest.objects.all().order_by('id')
return render(request, "system/smarttest.html", {
'smarttests': tests,
})
def rsyncs(request):
syncs = models.Rsync.objects.all().order_by('id')
return render(request, 'system/rsync.html', {
'rsyncs': syncs,
})
def sysctls(request):
sysctls = models.Sysctl.objects.all().order_by('id')
return render(request, 'system/sysctl.html', {
'sysctls': sysctls,
})
def loaders(request):
loaders = models.Loader.objects.all().order_by('id')
return render(request, 'system/loader.html', {
'loaders': loaders,
})
def restart_httpd(request):
""" restart httpd """
notifier().restart("http")
return HttpResponse('OK')
def debug(request):
"""Save freenas-debug output to DEBUG_TEMP"""
p1 = subprocess.Popen(["/usr/local/bin/freenas-debug", "-a", "-g", "-h", "-l", "-n", "-s", "-y", "-t", "-z"], stdout=subprocess.PIPE)
debug = p1.communicate()[0]
with open(DEBUG_TEMP, 'w') as f:
f.write(debug)
return render(request, 'system/debug.html')
def debug_save(request):
hostname = GlobalConfiguration.objects.all().order_by('-id')[0].gc_hostname
wrapper = FileWrapper(file(DEBUG_TEMP))
response = HttpResponse(wrapper, content_type='application/octet-stream')
response['Content-Length'] = os.path.getsize(DEBUG_TEMP)
response['Content-Disposition'] = \
'attachment; filename=debug-%s-%s.txt' % (hostname.encode('utf-8'), time.strftime('%Y%m%d%H%M%S'))
return response
multiplex = Multiplex("bash", "xterm-color")
def terminal(request):
try:
sid = int(request.GET.get("s"))
k = request.GET.get("k")
w = int(request.GET.get("w"))
h = int(request.GET.get("h"))
if multiplex.proc_keepalive(sid, w, h):
if k:
multiplex.proc_write(sid, k)
time.sleep(0.002)
content_data = '<?xml version="1.0" encoding="UTF-8"?>' + multiplex.proc_dump(sid)
response = HttpResponse(content_data, content_type='text/xml')
return response
else:
response = HttpResponse('Disconnected')
response.status_code = 400
return response
except (KeyError, ValueError, IndexError):
response = HttpResponse('Invalid parameters')
response.status_code = 400
return response
Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.