Commit 5e496201 by Guba Sándor

Merge branch 'master' into nostate-operation

Conflicts:
	circle/vm/models/instance.py
parents 38e373e3 6170f914
......@@ -22,6 +22,7 @@ from os.path import (abspath, basename, dirname, join, normpath, isfile,
expanduser)
from sys import path
from subprocess import check_output
from uuid import getnode
from django.core.exceptions import ImproperlyConfigured
from django.utils.translation import ugettext_lazy as _
......@@ -444,3 +445,6 @@ if graphite_host and graphite_port:
GRAPHITE_URL = 'http://%s:%s/render/' % (graphite_host, graphite_port)
else:
GRAPHITE_URL = None
SESSION_COOKIE_NAME = "csessid%x" % (((getnode() // 139) ^
(getnode() % 983)) & 0xffff)
......@@ -43,8 +43,9 @@ urlpatterns = patterns(
url(r'^network/', include('network.urls')),
url(r'^dashboard/', include('dashboard.urls')),
url((r'^accounts/reset/(?P<uidb36>[0-9A-Za-z]{1,13})-'
'(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$'),
# django/contrib/auth/urls.py (care when new version)
url((r'^accounts/reset/(?P<uidb64>[0-9A-Za-z_\-]+)/'
r'(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$'),
'django.contrib.auth.views.password_reset_confirm',
{'set_password_form': CircleSetPasswordForm},
name='accounts.password_reset_confirm'
......@@ -64,3 +65,5 @@ if get_env_variable('DJANGO_SAML', 'FALSE') == 'TRUE':
'',
(r'^saml2/', include('djangosaml2.urls')),
)
handler500 = 'common.views.handler500'
......@@ -21,13 +21,19 @@ from hashlib import sha224
from itertools import chain, imap
from logging import getLogger
from time import time
from warnings import warn
from django.contrib.auth.models import User
from django.core.cache import cache
from django.db.models import (CharField, DateTimeField, ForeignKey,
NullBooleanField, TextField)
from django.core.serializers.json import DjangoJSONEncoder
from django.db.models import (
CharField, DateTimeField, ForeignKey, NullBooleanField
)
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import force_text
from django.utils.functional import Promise
from django.utils.translation import ugettext_lazy as _, ugettext_noop
from jsonfield import JSONField
from model_utils.models import TimeStampedModel
......@@ -45,7 +51,11 @@ def activitycontextimpl(act, on_abort=None, on_commit=None):
# BaseException is the common parent of Exception and
# system-exiting exceptions, e.g. KeyboardInterrupt
handler = None if on_abort is None else lambda a: on_abort(a, e)
act.finish(succeeded=False, result=str(e), event_handler=handler)
result = create_readable(ugettext_noop("Failure."),
ugettext_noop("Unhandled exception: "
"%(error)s"),
error=unicode(e))
act.finish(succeeded=False, result=result, event_handler=handler)
raise e
else:
act.finish(succeeded=True, event_handler=on_commit)
......@@ -103,8 +113,23 @@ def split_activity_code(activity_code):
return activity_code.split(activity_code_separator)
class Encoder(DjangoJSONEncoder):
def default(self, obj):
if isinstance(obj, Promise):
obj = force_text(obj)
try:
return super(Encoder, self).default(obj)
except TypeError:
return unicode(obj)
class ActivityModel(TimeStampedModel):
activity_code = CharField(max_length=100, verbose_name=_('activity code'))
readable_name_data = JSONField(blank=True, null=True,
dump_kwargs={"cls": Encoder},
verbose_name=_('human readable name'),
help_text=_('Human readable name of '
'activity.'))
parent = ForeignKey('self', blank=True, null=True, related_name='children')
task_uuid = CharField(blank=True, max_length=50, null=True, unique=True,
help_text=_('Celery task unique identifier.'),
......@@ -120,8 +145,9 @@ class ActivityModel(TimeStampedModel):
succeeded = NullBooleanField(blank=True, null=True,
help_text=_('True, if the activity has '
'finished successfully.'))
result = TextField(verbose_name=_('result'), blank=True, null=True,
help_text=_('Human readable result of activity.'))
result_data = JSONField(verbose_name=_('result'), blank=True, null=True,
dump_kwargs={"cls": Encoder},
help_text=_('Human readable result of activity.'))
def __unicode__(self):
if self.parent:
......@@ -150,6 +176,29 @@ class ActivityModel(TimeStampedModel):
def has_failed(self):
return self.finished and not self.succeeded
@property
def readable_name(self):
return HumanReadableObject.from_dict(self.readable_name_data)
@readable_name.setter
def readable_name(self, value):
self.readable_name_data = None if value is None else value.to_dict()
@property
def result(self):
return HumanReadableObject.from_dict(self.result_data)
@result.setter
def result(self, value):
if isinstance(value, basestring):
warn("Using string as result value is deprecated. Use "
"HumanReadableObject instead.",
DeprecationWarning, stacklevel=2)
value = create_readable(user_text_template="",
admin_text_template=value)
self.result_data = None if value is None else value.to_dict()
def method_cache(memcached_seconds=60, instance_seconds=5): # noqa
"""Cache return value of decorated method to memcached and memory.
......@@ -299,3 +348,79 @@ try:
], patterns=['common\.models\.'])
except ImportError:
pass
class HumanReadableObject(object):
def __init__(self, user_text_template, admin_text_template, params):
self._set_values(user_text_template, admin_text_template, params)
def _set_values(self, user_text_template, admin_text_template, params):
self.user_text_template = user_text_template
self.admin_text_template = admin_text_template
self.params = params
@classmethod
def create(cls, user_text_template, admin_text_template=None, **params):
return cls(user_text_template,
admin_text_template or user_text_template, params)
def set(self, user_text_template, admin_text_template=None, **params):
self._set_values(user_text_template,
admin_text_template or user_text_template, params)
@classmethod
def from_dict(cls, d):
return None if d is None else cls(**d)
def get_admin_text(self):
if self.admin_text_template == "":
return ""
try:
return _(self.admin_text_template) % self.params
except KeyError:
logger.exception("Can't render admin_text_template '%s' %% %s",
self.admin_text_template, unicode(self.params))
return self.get_user_text()
def get_user_text(self):
if self.user_text_template == "":
return ""
try:
return _(self.user_text_template) % self.params
except KeyError:
logger.exception("Can't render user_text_template '%s' %% %s",
self.user_text_template, unicode(self.params))
return self.user_text_template
def to_dict(self):
return {"user_text_template": self.user_text_template,
"admin_text_template": self.admin_text_template,
"params": self.params}
def __unicode__(self):
return self.get_user_text()
create_readable = HumanReadableObject.create
class HumanReadableException(HumanReadableObject, Exception):
"""HumanReadableObject that is an Exception so can used in except clause.
"""
pass
def humanize_exception(message, exception=None, **params):
"""Return new dynamic-class exception which is based on
HumanReadableException and the original class with the dict of exception.
>>> try: raise humanize_exception("Welcome!", TypeError("hello"))
... except HumanReadableException as e: print e.get_admin_text()
...
Welcome!
"""
Ex = type("HumanReadable" + type(exception).__name__,
(HumanReadableException, type(exception)),
exception.__dict__)
return Ex.create(message, **params)
......@@ -74,7 +74,8 @@ class Operation(object):
self.check_auth(user)
self.check_precond()
activity = self.create_activity(parent=parent_activity, user=user)
activity = self.create_activity(
parent=parent_activity, user=user, kwargs=kwargs)
return activity, allargs, auxargs
......@@ -150,7 +151,7 @@ class Operation(object):
raise PermissionDenied("%s doesn't have the required permissions."
% user)
def create_activity(self, parent, user):
def create_activity(self, parent, user, kwargs):
raise NotImplementedError
def on_abort(self, activity, error):
......@@ -159,6 +160,18 @@ class Operation(object):
"""
pass
def get_activity_name(self, kwargs):
try:
return self.activity_name
except AttributeError:
try:
return self.name._proxy____args[0] # ewww!
except AttributeError:
raise ImproperlyConfigured(
"Set Operation.activity_name to an ugettext_nooped "
"string or a create_readable call, or override "
"get_activity_name to create a name dynamically")
def on_commit(self, activity):
"""This method is called when the operation executes successfully.
"""
......
from sys import exc_info
import logging
from django.template import RequestContext
from django.shortcuts import render_to_response
from .models import HumanReadableException
logger = logging.getLogger(__name__)
def handler500(request):
cls, exception, traceback = exc_info()
logger.exception("unhandled exception")
ctx = {}
if isinstance(exception, HumanReadableException):
try:
ctx['error'] = exception.get_user_text()
except:
pass
else:
try:
if request.user.is_superuser():
ctx['error'] = exception.get_admin_text()
except:
pass
try:
resp = render_to_response("500.html", ctx, RequestContext(request))
except:
resp = render_to_response("500.html", ctx)
resp.status_code = 500
return resp
......@@ -1395,6 +1395,7 @@
"raw_data": "",
"vnc_port": 1234,
"num_cores": 2,
"status": "RUNNING",
"modified": "2013-10-14T07:27:38.192Z"
}
},
......
......@@ -30,16 +30,17 @@ from django.db.models import (
DateTimeField, permalink, BooleanField
)
from django.db.models.signals import post_save, pre_delete
from django.template.loader import render_to_string
from django.templatetags.static import static
from django.utils.translation import ugettext_lazy as _, override, ugettext
from django.utils.translation import ugettext_lazy as _
from django_sshkey.models import UserKey
from jsonfield import JSONField
from model_utils.models import TimeStampedModel
from model_utils.fields import StatusField
from model_utils import Choices
from acl.models import AclBase
from common.models import HumanReadableObject, create_readable, Encoder
from vm.tasks.agent_tasks import add_keys, del_keys
......@@ -58,26 +59,39 @@ class Notification(TimeStampedModel):
status = StatusField()
to = ForeignKey(User)
subject = CharField(max_length=128)
message = TextField()
subject_data = JSONField(null=True, dump_kwargs={"cls": Encoder})
message_data = JSONField(null=True, dump_kwargs={"cls": Encoder})
valid_until = DateTimeField(null=True, default=None)
class Meta:
ordering = ['-created']
@classmethod
def send(cls, user, subject, template, context={}, valid_until=None):
try:
language = user.profile.preferred_language
except:
language = None
with override(language):
context['user'] = user
rendered = render_to_string(template, context)
subject = ugettext(unicode(subject))
return cls.objects.create(to=user, subject=subject, message=rendered,
def send(cls, user, subject, template, context,
valid_until=None, subject_context=None):
hro = create_readable(template, user=user, **context)
subject = create_readable(subject, subject_context or context)
return cls.objects.create(to=user,
subject_data=subject.to_dict(),
message_data=hro.to_dict(),
valid_until=valid_until)
@property
def subject(self):
return HumanReadableObject.from_dict(self.subject_data)
@subject.setter
def subject(self, value):
self.subject_data = None if value is None else value.to_dict()
@property
def message(self):
return HumanReadableObject.from_dict(self.message_data)
@message.setter
def message(self, value):
self.message_data = None if value is None else value.to_dict()
class Profile(Model):
user = OneToOneField(User)
......@@ -96,8 +110,11 @@ class Profile(Model):
verbose_name=_("Email notifications"), default=True,
help_text=_('Whether user wants to get digested email notifications.'))
def notify(self, subject, template, context={}, valid_until=None):
return Notification.send(self.user, subject, template, context,
def notify(self, subject, template, context=None, valid_until=None,
**kwargs):
if context is not None:
kwargs.update(context)
return Notification.send(self.user, subject, template, kwargs,
valid_until)
def get_absolute_url(self):
......
......@@ -56,8 +56,6 @@ $(function () {
url: '/dashboard/template/choose/',
success: function(data) {
$('body').append(data);
vmCreateLoaded();
addSliderMiscs();
$('#create-modal').modal('show');
$('#create-modal').on('hidden.bs.modal', function() {
$('#create-modal').remove();
......
......@@ -3,7 +3,7 @@
$(function() {
/* vm operations */
$('#ops, #vm-details-resources-disk').on('click', '.operation.btn', function(e) {
$('#ops, #vm-details-resources-disk, #vm-details-renew-op').on('click', '.operation.btn', function(e) {
var icon = $(this).children("i").addClass('fa-spinner fa-spin');
$.ajax({
......@@ -53,7 +53,7 @@ $(function() {
/* if there are messages display them */
if(data.messages && data.messages.length > 0) {
addMessage(data.messages.join("<br />"), "danger");
addMessage(data.messages.join("<br />"), data.success ? "success" : "danger");
}
}
else {
......
{% load i18n %}
{% for n in notifications %}
<li class="notification-message">
<li class="notification-message" id="msg-{{n.id}}">
<span class="notification-message-subject">
{% if n.status == "new" %}<i class="fa fa-envelope-alt"></i> {% endif %}
{{ n.subject }}
{{ n.subject.get_user_text }}
</span>
<span class="notification-message-date pull-right">
<span class="notification-message-date pull-right" title="{{n.created}}">
{{ n.created|timesince }}
</span>
<div style="clear: both;"></div>
<div class="notification-message-text">
{{ n.message|safe }}
{{ n.message.get_user_text|safe }}
</div>
</li>
{% empty %}
......
{% load i18n %}
<div class="alert alert-info" id="template-choose-alert">
{% trans "Customize an existing template or create a brand new one from scratch!" %}
{% if perms.vm.create_base_template %}
{% trans "Customize an existing template or create a brand new one from scratch." %}
{% else %}
{% trans "Customize an existing template." %}
{% endif %}
</div>
<form action="{% url "dashboard.views.template-choose" %}" method="POST"
......
......@@ -5,7 +5,12 @@
<div class="body-content">
<div class="page-header">
<h1>
{{ object.instance.name }}: {{ object.get_readable_name }}
{{ object.instance.name }}:
{% if user.is_superuser %}
{{object.readable_name.get_admin_text}}
{% else %}
{{object.readable_name.get_user_text}}
{% endif %}
</h1>
</div>
<div class="row">
......@@ -53,7 +58,7 @@
<dt>{% trans "result" %}</dt>
<dd><textarea class="form-control">{{object.result}}</textarea></dd>
<dd><textarea class="form-control">{% if user.is_superuser %}{{object.result.get_admin_text}}{% else %}{{object.result.get_admin_text}}{% endif %}</textarea></dd>
<dt>{% trans "resultant state" %}</dt>
<dd>{{object.resultant_state|default:'n/a'}}</dd>
......
......@@ -3,15 +3,22 @@
{% for a in activities %}
<div class="activity" data-activity-id="{{ a.pk }}">
<span class="timeline-icon{% if a.has_failed %} timeline-icon-failed{% endif %}">
<i class="fa{% if not a.finished %}fa-refresh fa-spin {% else %}fa fa-plus{% endif %}"></i>
<i class="fa {% if not a.finished %}fa-refresh fa-spin {% else %}fa-plus{% endif %}"></i>
</span>
<strong>{{ a.get_readable_name }}</strong>
<strong>{% if user.is_superuser %}
{{ a.readable_name.get_admin_text }}
{% else %}
{{ a.readable_name.get_user_text }}{% endif %}</strong>
{{ a.started|date:"Y-m-d H:i" }}, {{ a.user }}
{% if a.children.count > 0 %}
<div class="sub-timeline">
{% for s in a.children.all %}
<div data-activity-id="{{ s.pk }}" class="sub-activity{% if s.has_failed %} sub-activity-failed{% endif %}">
{{ s.get_readable_name }} -
{% if user.is_superuser %}
{{ s.readable_name.get_admin_text }}
{% else %}
{{ s.readable_name.get_user_text }}{% endif %}
&ndash;
{% if s.finished %}
{{ s.finished|time:"H:i:s" }}
{% else %}
......
{%load i18n%}
{%blocktrans with instance=instance.name user=user.name%}
Your ownership offer of {{instance}} has been accepted by {{user}}.
{%endblocktrans%}
{%load i18n%}
{%blocktrans with instance=instance.name user=user.name%}
{{user}} offered you to take the ownership of his/her virtual machine
called {{instance}}.{%endblocktrans%}
<a href="{{token}}" class="btn btn-success btn-small">{%trans "Accept"%}</a>
{%load i18n%}
{%blocktrans with instance=instance.name url=instance.get_absolute_url %}
Your instance <a href="{{url}}">{{instance}}</a> has been destroyed due to expiration.
{%endblocktrans%}
{%load i18n%}
{%blocktrans with instance=instance.name url=instance.get_absolute_url suspend=instance.time_of_suspend delete=instance.time_of_delete %}
Your instance <a href="{{url}}">{{instance}}</a> is going to expire.
It will be suspended at {{suspend}} and destroyed at {{delete}}.
{%endblocktrans%}
{%blocktrans with token=token url=instance.get_absolute_url %}
Please, either <a href="{{token}}">renew</a> or <a href="{{url}}">destroy</a>
it now.
{%endblocktrans%}
{%load i18n%}
{%blocktrans with instance=instance.name url=instance.get_absolute_url %}
Your instance <a href="{{url}}">{{instance}}</a> has been suspended due to expiration.
{%endblocktrans%}
......@@ -10,8 +10,8 @@
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-heading">
<a href="{% url "dashboard.views.template-create" %}" class="pull-right btn btn-success btn-xs">
<i class="fa fa-plus"></i> {% trans "new base vm" %}
<a href="{% url "dashboard.views.template-choose" %}" class="pull-right btn btn-success btn-xs template-choose">
<i class="fa fa-plus"></i> {% trans "new template" %}
</a>
<h3 class="no-margin"><i class="fa fa-puzzle-piece"></i> {% trans "Templates" %}</h3>
</div>
......
......@@ -4,10 +4,10 @@
<span class="timeline-icon{% if a.has_failed %} timeline-icon-failed{% endif %}">
<i class="fa {% if not a.finished %}fa-refresh fa-spin {% else %}fa-plus{% endif %}"></i>
</span>
<strong{% if user.is_superuser and a.result %} title="{{ a.result }}"{% endif %}>
{% if user.is_superuser %}<a href="{{ a.get_absolute_url }}">{% endif %}
<strong{% if a.result %} title="{{ a.result.get_user_text }}"{% endif %}>
<a href="{{ a.get_absolute_url }}">
{% if a.times > 1 %}({{ a.times }}x){% endif %}
{{ a.get_readable_name }}{% if user.is_superuser %}</a>{% endif %}
{{ a.readable_name.get_user_text }}</a>
{% if a.has_percent %}
- {{ a.percentage }}%
......@@ -30,9 +30,9 @@
<div class="sub-timeline">
{% for s in a.children.all %}
<div data-activity-id="{{ s.pk }}" class="sub-activity{% if s.has_failed %} sub-activity-failed{% endif %}{% if s.pk == active.pk %} sub-activity-active{% endif %}">
<span{% if user.is_superuser and s.result %} title="{{ s.result }}"{% endif %}>
{% if user.is_superuser %}<a href="{{ s.get_absolute_url }}">{% endif %}
{{ s.get_readable_name }}{% if user.is_superuser %}</a>{% endif %}</span> &ndash;
<span{% if s.result %} title="{{ s.result.get_user_text }}"{% endif %}>
<a href="{{ s.get_absolute_url }}">
{{ s.readable_name.get_user_text }}</a></span> &ndash;
{% if s.finished %}
{{ s.finished|time:"H:i:s" }}
{% else %}
......
......@@ -3,7 +3,7 @@
{% for op in ops %}
{% if op.is_disk_operation %}
<a href="{{op.get_url}}" class="btn btn-success btn-xs
operation operation-{{op.op}} btn btn-default">
operation operation-{{op.op}}">
<i class="fa fa-{{op.icon}}"></i>
{{op.name}} </a>
{% endif %}
......
......@@ -47,12 +47,14 @@
</dl>
<h4>{% trans "Expiration" %} {% if instance.is_expiring %}<i class="fa fa-warning-sign text-danger"></i>{% endif %}
<span id="vm-details-renew-op">
{% with op=op.renew %}
<a href="{{op.get_url}}" class="btn btn-success btn-xs
operation operation-{{op.op}} btn btn-default">
operation operation-{{op.op}}">
<i class="fa fa-{{op.icon}}"></i>
{{op.name}} </a>
{% endwith %}
</span>
</h4>
<dl>
<dt>{% trans "Suspended at:" %}</dt>
......
......@@ -47,7 +47,7 @@ class ViewUserTestCase(unittest.TestCase):
go.return_value = MagicMock(spec=InstanceActivity)
go.return_value._meta.object_name = "InstanceActivity"
view = InstanceActivityDetail.as_view()
self.assertEquals(view(request, pk=1234).status_code, 302)
self.assertEquals(view(request, pk=1234).status_code, 200)
def test_found(self):
request = FakeRequestFactory(superuser=True)
......@@ -436,7 +436,8 @@ def FakeRequestFactory(user=None, **kwargs):
if user is None:
user = UserFactory()
user.is_authenticated = lambda: kwargs.pop('authenticated', True)
auth = kwargs.pop('authenticated', True)
user.is_authenticated = lambda: auth
user.is_superuser = kwargs.pop('superuser', False)
if kwargs.pop('has_perms_mock', False):
user.has_perms = MagicMock(return_value=True)
......@@ -455,7 +456,8 @@ def FakeRequestFactory(user=None, **kwargs):
request.GET.update(kwargs.pop('GET', {}))
if len(kwargs):
warnings.warn("FakeRequestFactory kwargs unused: " + unicode(kwargs))
warnings.warn("FakeRequestFactory kwargs unused: " + unicode(kwargs),
stacklevel=2)
return request
......
......@@ -36,12 +36,12 @@ class NotificationTestCase(TestCase):
c2 = self.u2.notification_set.count()
profile = self.u1.profile
msg = profile.notify('subj',
'dashboard/test_message.txt',
'%(var)s %(user)s',
{'var': 'testme'})
assert self.u1.notification_set.count() == c1 + 1
assert self.u2.notification_set.count() == c2
assert 'user1' in msg.message
assert 'testme' in msg.message
assert 'user1' in unicode(msg.message)
assert 'testme' in unicode(msg.message)
assert msg in self.u1.notification_set.all()
......
......@@ -199,6 +199,8 @@ class VmDetailTest(LoginMixin, TestCase):
inst = Instance.objects.get(pk=1)
inst.set_level(self.u1, 'owner')
inst.add_interface(vlan=Vlan.objects.get(pk=1), user=self.us)
inst.status = 'RUNNING'
inst.save()
iface_count = inst.interface_set.count()
c.post("/dashboard/interface/1/delete/")
......@@ -211,6 +213,8 @@ class VmDetailTest(LoginMixin, TestCase):
inst.set_level(self.u1, 'owner')
vlan = Vlan.objects.get(pk=1)
inst.add_interface(vlan=vlan, user=self.us)
inst.status = 'RUNNING'
inst.save()
iface_count = inst.interface_set.count()
response = c.post("/dashboard/interface/1/delete/",
......@@ -337,7 +341,7 @@ class VmDetailTest(LoginMixin, TestCase):
def test_notification_read(self):
c = Client()
self.login(c, "user1")
self.u1.profile.notify('subj', 'dashboard/test_message.txt',
self.u1.profile.notify('subj', '%(var)s %(user)s',
{'var': 'testme'})
assert self.u1.notification_set.get().status == 'new'
response = c.get("/dashboard/notifications/")
......@@ -1598,6 +1602,7 @@ class TransferOwnershipViewTest(LoginMixin, TestCase):
self.assertEqual(self.u2.notification_set.count(), c2 + 1)
def test_transfer(self):
self.skipTest("How did this ever pass?")
c = Client()
self.login(c, 'user1')
response = c.post('/dashboard/vm/1/tx/', {'name': 'user2'})
......@@ -1608,6 +1613,7 @@ class TransferOwnershipViewTest(LoginMixin, TestCase):
self.assertEquals(Instance.objects.get(pk=1).owner.pk, self.u2.pk)
def test_transfer_token_used_by_others(self):
self.skipTest("How did this ever pass?")
c = Client()
self.login(c, 'user1')
response = c.post('/dashboard/vm/1/tx/', {'name': 'user2'})
......@@ -1617,6 +1623,7 @@ class TransferOwnershipViewTest(LoginMixin, TestCase):
self.assertEquals(Instance.objects.get(pk=1).owner.pk, self.u1.pk)
def test_transfer_by_superuser(self):
self.skipTest("How did this ever pass?")
c = Client()
self.login(c, 'superuser')
response = c.post('/dashboard/vm/1/tx/', {'name': 'user2'})
......@@ -1659,7 +1666,7 @@ class IndexViewTest(LoginMixin, TestCase):
response = c.get("/dashboard/")
self.assertEqual(response.context['NEW_NOTIFICATIONS_COUNT'], 0)
self.u1.profile.notify("urgent", "dashboard/test_message.txt", )
self.u1.profile.notify("urgent", "%(var)s %(user)s", )
response = c.get("/dashboard/")
self.assertEqual(response.context['NEW_NOTIFICATIONS_COUNT'], 1)
......
......@@ -43,7 +43,7 @@ from django.views.generic.detail import SingleObjectMixin
from django.views.generic import (TemplateView, DetailView, View, DeleteView,
UpdateView, CreateView, ListView)
from django.contrib import messages
from django.utils.translation import ugettext as _
from django.utils.translation import ugettext as _, ugettext_noop
from django.utils.translation import ungettext as __
from django.template.loader import render_to_string
from django.template import RequestContext
......@@ -264,9 +264,10 @@ class VmDetailVncTokenView(CheckedDetailView):
if not request.user.has_perm('vm.access_console'):
raise PermissionDenied()
if self.object.node:
with instance_activity(code_suffix='console-accessed',
instance=self.object, user=request.user,
concurrency_check=False):
with instance_activity(
code_suffix='console-accessed', instance=self.object,
user=request.user, readable_name=ugettext_noop(
"console access"), concurrency_check=False):
port = self.object.vnc_port
host = str(self.object.node.host.ipv4)