Commit 215075e2 by Szeberényi Imre

unicode->bytes fix:

  using unicode as it was used in the 2.7 version and
  adding ptyhon 2 & 3 compatible init snipet
introducing celeryconfig.py
parent ae937cd9
...@@ -8,6 +8,11 @@ from django.core.exceptions import ImproperlyConfigured ...@@ -8,6 +8,11 @@ from django.core.exceptions import ImproperlyConfigured
from ..models import Level, AclBase from ..models import Level, AclBase
try:
# Python 2: "unicode" is built-in
unicode
except NameError:
unicode = str
def create_levels(app_config, verbosity=False, using=DEFAULT_DB_ALIAS, def create_levels(app_config, verbosity=False, using=DEFAULT_DB_ALIAS,
**kwargs): **kwargs):
...@@ -61,10 +66,10 @@ def create_levels(app_config, verbosity=False, using=DEFAULT_DB_ALIAS, ...@@ -61,10 +66,10 @@ def create_levels(app_config, verbosity=False, using=DEFAULT_DB_ALIAS,
] ]
Level.objects.using(using).bulk_create(levels) Level.objects.using(using).bulk_create(levels)
if verbosity >= 2: if verbosity >= 2:
print(("Adding levels [%s]." % ", ".join(bytes(l) for l in levels))) print(("Adding levels [%s]." % ", ".join(unicode(l) for l in levels)))
print(("Searched: [%s]." % ", ".join( print(("Searched: [%s]." % ", ".join(
bytes(l) for l in searched_levels))) unicode(l) for l in searched_levels)))
print(("All: [%s]." % ", ".join(bytes(l) for l in all_levels))) print(("All: [%s]." % ", ".join(unicode(l) for l in all_levels)))
# set weights # set weights
for ctype, codename, weight in level_weights: for ctype, codename, weight in level_weights:
......
...@@ -26,6 +26,14 @@ from django.db.models import ( ...@@ -26,6 +26,14 @@ from django.db.models import (
ManyToManyField, ForeignKey, CharField, Model, IntegerField, Q ManyToManyField, ForeignKey, CharField, Model, IntegerField, Q
) )
from django.db import models from django.db import models
try:
# Python 2: "unicode" is built-in
unicode
except NameError:
unicode = str
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
...@@ -40,7 +48,7 @@ class Level(Model): ...@@ -40,7 +48,7 @@ class Level(Model):
weight = IntegerField('weight', null=True) weight = IntegerField('weight', null=True)
def __str__(self): def __str__(self):
return "<%s/%s>" % (bytes(self.content_type), self.name) return "<%s/%s>" % (unicode(self.content_type), self.name)
class Meta: class Meta:
app_label = 'acl' app_label = 'acl'
...@@ -61,7 +69,7 @@ class ObjectLevel(Model): ...@@ -61,7 +69,7 @@ class ObjectLevel(Model):
groups = ManyToManyField(Group) groups = ManyToManyField(Group)
def __str__(self): def __str__(self):
return "<%s: %s>" % (bytes(self.content_object), bytes(self.level)) return "<%s: %s>" % (unicode(self.content_object), unicode(self.level))
class Meta: class Meta:
app_label = 'acl' app_label = 'acl'
...@@ -143,7 +151,7 @@ class AclBase(Model): ...@@ -143,7 +151,7 @@ class AclBase(Model):
:type level: str or unicode :type level: str or unicode
""" """
logger.info('%s.set_group_level(%s, %s) called', logger.info('%s.set_group_level(%s, %s) called',
*[bytes(p) for p in [self, group, level]]) *[unicode(p) for p in [self, group, level]])
if level is None: if level is None:
pk = None pk = None
else: else:
...@@ -160,7 +168,7 @@ class AclBase(Model): ...@@ -160,7 +168,7 @@ class AclBase(Model):
i.save() i.save()
def has_level(self, user, level, group_also=True): def has_level(self, user, level, group_also=True):
# logger.debug('%s.has_level(%s, %s, %s) called', *[bytes(p) for p in [self, user, level, group_also]]) # logger.debug('%s.has_level(%s, %s, %s) called', *[unicode(p) for p in [self, user, level, group_also]])
if user is None or not user.is_authenticated: if user is None or not user.is_authenticated:
return False return False
if getattr(user, 'is_superuser', False): if getattr(user, 'is_superuser', False):
...@@ -168,7 +176,7 @@ class AclBase(Model): ...@@ -168,7 +176,7 @@ class AclBase(Model):
return True return True
if isinstance(level, str): if isinstance(level, str):
level = self.get_level_object(level) level = self.get_level_object(level)
logger.debug("- level set by str: %s", bytes(level)) logger.debug("- level set by str: %s", unicode(level))
object_levels = self.object_level_set.filter( object_levels = self.object_level_set.filter(
level__weight__gte=level.weight).all() level__weight__gte=level.weight).all()
...@@ -181,7 +189,7 @@ class AclBase(Model): ...@@ -181,7 +189,7 @@ class AclBase(Model):
return False return False
def get_users_with_level(self, **kwargs): def get_users_with_level(self, **kwargs):
# logger.debug('%s.get_users_with_level() called', bytes(self)) # logger.debug('%s.get_users_with_level() called', unicode(self))
object_levels = (self.object_level_set.filter(**kwargs).select_related( object_levels = (self.object_level_set.filter(**kwargs).select_related(
'level').prefetch_related('users').all()) 'level').prefetch_related('users').all())
users = [] users = []
...@@ -193,7 +201,7 @@ class AclBase(Model): ...@@ -193,7 +201,7 @@ class AclBase(Model):
return users return users
def get_groups_with_level(self): def get_groups_with_level(self):
# logger.debug('%s.get_groups_with_level() called', bytes(self)) # logger.debug('%s.get_groups_with_level() called', unicode(self))
object_levels = (self.object_level_set.select_related( object_levels = (self.object_level_set.select_related(
'level').prefetch_related('groups').all()) 'level').prefetch_related('groups').all())
groups = [] groups = []
...@@ -208,7 +216,7 @@ class AclBase(Model): ...@@ -208,7 +216,7 @@ class AclBase(Model):
def get_objects_with_level(cls, level, user, def get_objects_with_level(cls, level, user,
group_also=True, owner_also=False, group_also=True, owner_also=False,
disregard_superuser=False): disregard_superuser=False):
# logger.debug('%s.get_objects_with_level(%s,%s) called', str(cls), bytes(level), bytes(user)) # logger.debug('%s.get_objects_with_level(%s,%s) called', str(cls), unicode(level), unicode(user))
if user is None or not user.is_authenticated: if user is None or not user.is_authenticated:
return cls.objects.none() return cls.objects.none()
if getattr(user, 'is_superuser', False) and not disregard_superuser: if getattr(user, 'is_superuser', False) and not disregard_superuser:
...@@ -216,7 +224,7 @@ class AclBase(Model): ...@@ -216,7 +224,7 @@ class AclBase(Model):
return cls.objects.all() return cls.objects.all()
if isinstance(level, str): if isinstance(level, str):
level = cls.get_level_object(level) level = cls.get_level_object(level)
# logger.debug("- level set by str: %s", bytes(level)) # logger.debug("- level set by str: %s", unicode(level))
ct = ContentType.objects.get_for_model(cls) ct = ContentType.objects.get_for_model(cls)
levelfilter = Q(users=user) levelfilter = Q(users=user)
......
CELERY_RESULT_BACKEND = 'amqp://'
CELERY_TASK_RESULT_EXPIRES = 300
CELERY_TIMEZONE = 'UTC'
CELERY_ENABLE_UTC = True
CELERY_ACCEPT_CONTENT = ['pickle', 'json', 'msgpack', 'yaml']
...@@ -14,8 +14,8 @@ def update_permissions_after_migration(sender, **kwargs): ...@@ -14,8 +14,8 @@ def update_permissions_after_migration(sender, **kwargs):
from django.conf import settings from django.conf import settings
from django.apps import apps from django.apps import apps
from django.contrib.auth.management import create_permissions from django.contrib.auth.management import create_permissions
v = 2 if settings.DEBUG else 0
create_permissions(sender, apps.get_models(), 2 if settings.DEBUG else 0) create_permissions(sender, v, apps.get_models())
post_migrate.connect(update_permissions_after_migration) post_migrate.connect(update_permissions_after_migration)
...@@ -84,7 +84,8 @@ def activitycontextimpl(act, on_abort=None, on_commit=None): ...@@ -84,7 +84,8 @@ def activitycontextimpl(act, on_abort=None, on_commit=None):
raise raise
except: except:
logger.exception("Failed activity %s" % str(act)) logger.exception("Failed activity %s" % str(act))
handler = None if on_abort is None else lambda a: on_abort(a, e) handler = None
# handler = None if on_abort is None else lambda a: on_abort(a, e)
act.finish(succeeded=False, result=result, event_handler=handler) act.finish(succeeded=False, result=result, event_handler=handler)
raise raise
else: else:
......
...@@ -51,6 +51,14 @@ from vm.models.instance import ACCESS_METHODS ...@@ -51,6 +51,14 @@ from vm.models.instance import ACCESS_METHODS
from .store_api import Store, NoStoreException, NotOkException from .store_api import Store, NoStoreException, NotOkException
from .validators import connect_command_template_validator from .validators import connect_command_template_validator
try:
# Python 2: "unicode" is built-in
unicode
except NameError:
unicode = str
logger = getLogger(__name__) logger = getLogger(__name__)
...@@ -420,11 +428,11 @@ if hasattr(settings, 'SAML_ORG_ID_ATTRIBUTE'): ...@@ -420,11 +428,11 @@ if hasattr(settings, 'SAML_ORG_ID_ATTRIBUTE'):
value = attributes[atr][0].upper() value = attributes[atr][0].upper()
except Exception as e: except Exception as e:
value = None value = None
logger.info("save_org_id couldn't find attribute. %s", bytes(e)) logger.info("save_org_id couldn't find attribute. %s", unicode(e))
if instance.pk is None: if instance.pk is None:
instance.save() instance.save()
logger.debug("save_org_id saved user %s", bytes(instance)) logger.debug("save_org_id saved user %s", unicode(instance))
profile, created = Profile.objects.get_or_create(user=instance) profile, created = Profile.objects.get_or_create(user=instance)
if created or profile.org_id != value: if created or profile.org_id != value:
...@@ -444,7 +452,7 @@ if hasattr(settings, 'SAML_ORG_ID_ATTRIBUTE'): ...@@ -444,7 +452,7 @@ if hasattr(settings, 'SAML_ORG_ID_ATTRIBUTE'):
logger.debug('cant find membergroup %s', group) logger.debug('cant find membergroup %s', group)
else: else:
logger.debug('could find membergroup %s (%s)', logger.debug('could find membergroup %s (%s)',
group, bytes(g)) group, unicode(g))
g.user_set.add(instance) g.user_set.add(instance)
for i in FutureMember.objects.filter(org_id__iexact=value): for i in FutureMember.objects.filter(org_id__iexact=value):
...@@ -460,7 +468,7 @@ if hasattr(settings, 'SAML_ORG_ID_ATTRIBUTE'): ...@@ -460,7 +468,7 @@ if hasattr(settings, 'SAML_ORG_ID_ATTRIBUTE'):
logger.debug('cant find ownergroup %s', group) logger.debug('cant find ownergroup %s', group)
else: else:
logger.debug('could find ownergroup %s (%s)', logger.debug('could find ownergroup %s (%s)',
group, bytes(g)) group, unicode(g))
g.profile.set_level(instance, 'owner') g.profile.set_level(instance, 'owner')
return False # User did not change return False # User did not change
......
...@@ -28,6 +28,12 @@ from sizefield.utils import filesizeformat ...@@ -28,6 +28,12 @@ from sizefield.utils import filesizeformat
from storage.models import Disk from storage.models import Disk
try:
# Python 2: "unicode" is built-in
unicode
except NameError:
unicode = str
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
...@@ -81,7 +87,7 @@ class Store(object): ...@@ -81,7 +87,7 @@ class Store(object):
timeout=timeout, **self.request_args) timeout=timeout, **self.request_args)
except Exception: except Exception:
logger.exception("Error in store %s loading %s", logger.exception("Error in store %s loading %s",
bytes(method), url) unicode(method), url)
raise raise
else: else:
if raise_status_code and response.status_code != codes.ok: if raise_status_code and response.status_code != codes.ok:
......
...@@ -28,6 +28,13 @@ from manager.mancelery import celery ...@@ -28,6 +28,13 @@ from manager.mancelery import celery
from ..models import Notification from ..models import Notification
from ..views import UnsubscribeFormView from ..views import UnsubscribeFormView
try:
# Python 2: "unicode" is built-in
unicode
except NameError:
unicode = str
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
...@@ -46,7 +53,7 @@ def send_email_notifications(): ...@@ -46,7 +53,7 @@ def send_email_notifications():
for user, msgs in list(recipients.items()): for user, msgs in list(recipients.items()):
if (not user.profile or not user.email or not if (not user.profile or not user.email or not
user.profile.email_notifications): user.profile.email_notifications):
logger.debug("%s gets no notifications", bytes(user)) logger.debug("%s gets no notifications", unicode(user))
continue continue
with override(user.profile.preferred_language): with override(user.profile.preferred_language):
context = {'user': user.profile, 'messages': msgs, context = {'user': user.profile, 'messages': msgs,
...@@ -67,7 +74,7 @@ def send_email_notifications(): ...@@ -67,7 +74,7 @@ def send_email_notifications():
logger.error("Failed to send mail to %s", user, exc_info=True) logger.error("Failed to send mail to %s", user, exc_info=True)
else: else:
logger.info("Delivered notifications %s", logger.info("Delivered notifications %s",
" ".join(bytes(i.pk) for i in msgs)) " ".join(unicode(i.pk) for i in msgs))
for i in msgs: for i in msgs:
i.status = i.STATUS.delivered i.status = i.STATUS.delivered
i.save() i.save()
...@@ -22,6 +22,11 @@ from django.test import TestCase ...@@ -22,6 +22,11 @@ from django.test import TestCase
from ..models import Profile from ..models import Profile
from ..views import search_user from ..views import search_user
try:
# Python 2: "unicode" is built-in
unicode
except NameError:
unicode = str
class NotificationTestCase(TestCase): class NotificationTestCase(TestCase):
...@@ -40,8 +45,8 @@ class NotificationTestCase(TestCase): ...@@ -40,8 +45,8 @@ class NotificationTestCase(TestCase):
{'var': 'testme'}) {'var': 'testme'})
assert self.u1.notification_set.count() == c1 + 1 assert self.u1.notification_set.count() == c1 + 1
assert self.u2.notification_set.count() == c2 assert self.u2.notification_set.count() == c2
assert 'user1' in bytes(msg.message) assert 'user1' in unicode(msg.message)
assert 'testme' in bytes(msg.message) assert 'testme' in unicode(msg.message)
assert msg in self.u1.notification_set.all() assert msg in self.u1.notification_set.all()
......
...@@ -26,6 +26,11 @@ from django.http import HttpResponse ...@@ -26,6 +26,11 @@ from django.http import HttpResponse
from ..views import AclUpdateView from ..views import AclUpdateView
from ..models import Profile from ..models import Profile
try:
# Python 2: "unicode" is built-in
unicode
except NameError:
unicode = str
def highlight(field, q, none_wo_match=True): def highlight(field, q, none_wo_match=True):
""" """
...@@ -59,7 +64,7 @@ class AclUserAutocomplete(autocomplete.Select2ListView): ...@@ -59,7 +64,7 @@ class AclUserAutocomplete(autocomplete.Select2ListView):
if self.q: if self.q:
condition = Q() condition = Q()
for field in search_fields: for field in search_fields:
condition |= Q(**{field + '__icontains': bytes(self.q)}) condition |= Q(**{field + '__icontains': unicode(self.q)})
return list(qs.filter(condition)) return list(qs.filter(condition))
return [] return []
...@@ -68,8 +73,8 @@ class AclUserAutocomplete(autocomplete.Select2ListView): ...@@ -68,8 +73,8 @@ class AclUserAutocomplete(autocomplete.Select2ListView):
return self.filter(users, self.search_fields) return self.filter(users, self.search_fields)
def choice_displayed_text(self, choice): def choice_displayed_text(self, choice):
q = bytes(self.request.GET.get('q', '')) q = unicode(self.request.GET.get('q', ''))
name = highlight(bytes(choice), q, False) name = highlight(unicode(choice), q, False)
if isinstance(choice, User): if isinstance(choice, User):
extra_fields = [highlight(choice.get_full_name(), q, False), extra_fields = [highlight(choice.get_full_name(), q, False),
highlight(choice.email, q)] highlight(choice.email, q)]
...@@ -84,7 +89,7 @@ class AclUserAutocomplete(autocomplete.Select2ListView): ...@@ -84,7 +89,7 @@ class AclUserAutocomplete(autocomplete.Select2ListView):
def get(self, *args, **kwargs): def get(self, *args, **kwargs):
return HttpResponse(json.dumps({ return HttpResponse(json.dumps({
'results': [dict(id=bytes(r), text=self.choice_displayed_text(r)) 'results': [dict(id=unicode(r), text=self.choice_displayed_text(r))
for r in self.get_list()] for r in self.get_list()]
}), content_type="application/json") }), content_type="application/json")
......
...@@ -46,6 +46,12 @@ from ..models import FutureMember, GroupProfile ...@@ -46,6 +46,12 @@ from ..models import FutureMember, GroupProfile
from ..store_api import Store, NoStoreException from ..store_api import Store, NoStoreException
from ..tables import GroupListTable from ..tables import GroupListTable
try:
# Python 2: "unicode" is built-in
unicode
except NameError:
unicode = str
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
...@@ -217,7 +223,7 @@ class GroupList(LoginRequiredMixin, SingleTableView): ...@@ -217,7 +223,7 @@ class GroupList(LoginRequiredMixin, SingleTableView):
return super(GroupList, self).get(*args, **kwargs) return super(GroupList, self).get(*args, **kwargs)
def get_queryset(self): def get_queryset(self):
# logger.debug('GroupList.get_queryset() called. User: %s', bytes(self.request.user)) # logger.debug('GroupList.get_queryset() called. User: %s', unicode(self.request.user))
profiles = GroupProfile.get_objects_with_level( profiles = GroupProfile.get_objects_with_level(
'operator', self.request.user) 'operator', self.request.user)
groups = Group.objects.filter(groupprofile__in=profiles) groups = Group.objects.filter(groupprofile__in=profiles)
......
...@@ -38,6 +38,14 @@ from braces.views import LoginRequiredMixin ...@@ -38,6 +38,14 @@ from braces.views import LoginRequiredMixin
from ..store_api import (Store, NoStoreException, from ..store_api import (Store, NoStoreException,
NotOkException) NotOkException)
try:
# Python 2: "unicode" is built-in
unicode
except NameError:
unicode = str
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
...@@ -75,7 +83,7 @@ class StoreList(LoginRequiredMixin, TemplateView): ...@@ -75,7 +83,7 @@ class StoreList(LoginRequiredMixin, TemplateView):
messages.warning(self.request, _("Store has some problems now." messages.warning(self.request, _("Store has some problems now."
" Try again later.")) " Try again later."))
except Exception as e: except Exception as e:
logger.critical("Something is wrong with store: %s", bytes(e)) logger.critical("Something is wrong with store: %s", unicode(e))
messages.warning(self.request, _("Unknown store error.")) messages.warning(self.request, _("Unknown store error."))
return redirect("/") return redirect("/")
...@@ -183,7 +191,7 @@ def store_new_directory(request): ...@@ -183,7 +191,7 @@ def store_new_directory(request):
Store(request.user).new_folder(join(path, name)) Store(request.user).new_folder(join(path, name))
except Exception: except Exception:
logger.exception("Unable to create folder %s in %s for %s", logger.exception("Unable to create folder %s in %s for %s",
name, path, bytes(request.user)) name, path, unicode(request.user))
messages.error(request, _("Unable to create folder.")) messages.error(request, _("Unable to create folder."))
return redirect("%s?directory=%s" % ( return redirect("%s?directory=%s" % (
reverse("dashboard.views.store-list"), urlencode(path))) reverse("dashboard.views.store-list"), urlencode(path)))
...@@ -199,7 +207,7 @@ def store_refresh_toplist(request): ...@@ -199,7 +207,7 @@ def store_refresh_toplist(request):
quota = store.get_quota() quota = store.get_quota()
files = {'toplist': toplist, 'quota': quota} files = {'toplist': toplist, 'quota': quota}
except Exception: except Exception:
logger.exception("Can't get toplist of %s", bytes(request.user)) logger.exception("Can't get toplist of %s", unicode(request.user))
files = {'toplist': []} files = {'toplist': []}
cache.set(cache_key, files, 300) cache.set(cache_key, files, 300)
......
...@@ -56,6 +56,18 @@ from .util import ( ...@@ -56,6 +56,18 @@ from .util import (
GraphMixin GraphMixin
) )
try:
# Python 2: "unicode" is built-in
unicode
except NameError:
unicode = str
try:
# Python 2: "unicode" is built-in
unicode
except NameError:
unicode = str
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
...@@ -272,7 +284,7 @@ class TemplateList(LoginRequiredMixin, FilterMixin, SingleTableView): ...@@ -272,7 +284,7 @@ class TemplateList(LoginRequiredMixin, FilterMixin, SingleTableView):
return queryset return queryset
def get_queryset(self): def get_queryset(self):
# logger.debug('TemplateList.get_queryset() called. User: %s', bytes(self.request.user)) logger.debug('TemplateList.get_queryset() called. User: %s', unicode(self.request.user))
qs = self.create_acl_queryset(InstanceTemplate) qs = self.create_acl_queryset(InstanceTemplate)
self.create_fake_get() self.create_fake_get()
......
...@@ -59,6 +59,11 @@ from ..tables import ( ...@@ -59,6 +59,11 @@ from ..tables import (
from .util import saml_available, DeleteViewBase, LoginView from .util import saml_available, DeleteViewBase, LoginView
try:
# Python 2: "unicode" is built-in
unicode
except NameError:
unicode = str
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
...@@ -153,14 +158,14 @@ class TokenLogin(View): ...@@ -153,14 +158,14 @@ class TokenLogin(View):
try: try:
data = signing.loads(token, salt=self.get_salt(), data = signing.loads(token, salt=self.get_salt(),
max_age=self.token_max_age) max_age=self.token_max_age)
logger.debug('TokenLogin token data: %s', bytes(data)) logger.debug('TokenLogin token data: %s', unicode(data))
sudoer, user = data sudoer, user = data
logger.debug('Extracted TokenLogin data: sudoer: %s, user: %s', logger.debug('Extracted TokenLogin data: sudoer: %s, user: %s',
bytes(sudoer), bytes(user)) unicode(sudoer), unicode(user))
except (signing.BadSignature, ValueError, TypeError) as e: except (signing.BadSignature, ValueError, TypeError) as e:
logger.warning('Tried invalid TokenLogin token. ' logger.warning('Tried invalid TokenLogin token. '
'Token: %s, user: %s. %s', 'Token: %s, user: %s. %s',
token, bytes(self.request.user), bytes(e)) token, unicode(self.request.user), unicode(e))
raise SuspiciousOperation() raise SuspiciousOperation()
sudoer = User.objects.get(pk=sudoer) sudoer = User.objects.get(pk=sudoer)
if not sudoer.is_superuser: if not sudoer.is_superuser:
...@@ -168,9 +173,9 @@ class TokenLogin(View): ...@@ -168,9 +173,9 @@ class TokenLogin(View):
user = User.objects.get(pk=user) user = User.objects.get(pk=user)
user.backend = 'django.contrib.auth.backends.ModelBackend' user.backend = 'django.contrib.auth.backends.ModelBackend'
logger.warning('%s %d logged in as user %s %d', logger.warning('%s %d logged in as user %s %d',
bytes(sudoer), sudoer.pk, bytes(user), user.pk) unicode(sudoer), sudoer.pk, unicode(user), user.pk)
login(request, user) login(request, user)
messages.info(request, _("Logged in as user %s.") % bytes(user)) messages.info(request, _("Logged in as user %s.") % unicode(user))
return redirect("/") return redirect("/")
...@@ -253,7 +258,7 @@ class UnsubscribeFormView(SuccessMessageMixin, UpdateView): ...@@ -253,7 +258,7 @@ class UnsubscribeFormView(SuccessMessageMixin, UpdateView):
@classmethod @classmethod
def get_salt(cls): def get_salt(cls):
return bytes(cls) return unicode(cls)
@classmethod @classmethod
def get_token(cls, user): def get_token(cls, user):
...@@ -267,7 +272,7 @@ class UnsubscribeFormView(SuccessMessageMixin, UpdateView): ...@@ -267,7 +272,7 @@ class UnsubscribeFormView(SuccessMessageMixin, UpdateView):
raise raise
except (signing.BadSignature, ValueError, TypeError) as e: except (signing.BadSignature, ValueError, TypeError) as e:
logger.warning('Tried invalid token. Token: %s, user: %s. %s', logger.warning('Tried invalid token. Token: %s, user: %s. %s',
key, bytes(self.request.user), bytes(e)) key, unicode(self.request.user), unicode(e))
raise Http404 raise Http404
else: else:
return (queryset or self.get_queryset()).get(user_id=pk) return (queryset or self.get_queryset()).get(user_id=pk)
...@@ -561,7 +566,7 @@ class UserList(LoginRequiredMixin, PermissionRequiredMixin, SingleTableView): ...@@ -561,7 +566,7 @@ class UserList(LoginRequiredMixin, PermissionRequiredMixin, SingleTableView):
return super(UserList, self).get(*args, **kwargs) return super(UserList, self).get(*args, **kwargs)
def get_queryset(self): def get_queryset(self):
# logger.debug('UserList.get_queryset() called. User: %s', bytes(self.request.user)) # logger.debug('UserList.get_queryset() called. User: %s', unicode(self.request.user))
qs = User.objects.all().order_by("-pk") qs = User.objects.all().order_by("-pk")
q = self.search_form.cleaned_data.get('s') q = self.search_form.cleaned_data.get('s')
......
...@@ -56,6 +56,13 @@ from ..models import GroupProfile, Profile ...@@ -56,6 +56,13 @@ from ..models import GroupProfile, Profile
from ..forms import TransferOwnershipForm from ..forms import TransferOwnershipForm
try:
# Python 2: "unicode" is built-in
unicode
except NameError:
unicode = str
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
saml_available = hasattr(settings, "SAML_CONFIG") saml_available = hasattr(settings, "SAML_CONFIG")
...@@ -274,7 +281,7 @@ class OperationView(RedirectToLoginMixin, DetailView): ...@@ -274,7 +281,7 @@ class OperationView(RedirectToLoginMixin, DetailView):
return ctx return ctx
def check_auth(self): def check_auth(self):
#logger.debug("OperationView.check_auth(%s)", bytes(self)) logger.debug("OperationView.check_auth(%s)", unicode(self))
self.get_op().check_auth(self.request.user) self.get_op().check_auth(self.request.user)
@classmethod @classmethod
...@@ -374,7 +381,7 @@ class AjaxOperationMixin(object): ...@@ -374,7 +381,7 @@ class AjaxOperationMixin(object):
store = [] store = []
return JsonResponse({'success': True, return JsonResponse({'success': True,
'with_reload': self.with_reload, 'with_reload': self.with_reload,
'messages': [bytes(m) for m in store]}) 'messages': [str(m) for m in store]})
else: else:
return resp return resp
...@@ -511,23 +518,23 @@ class AclUpdateView(LoginRequiredMixin, View, SingleObjectMixin): ...@@ -511,23 +518,23 @@ class AclUpdateView(LoginRequiredMixin, View, SingleObjectMixin):
if getattr(self.instance, "owner", None) == whom: if getattr(self.instance, "owner", None) == whom:
logger.info("Tried to set owner's acl level for %s by %s.", logger.info("Tried to set owner's acl level for %s by %s.",
bytes(self.instance), bytes(user)) unicode(self.instance), unicode(user))
msg = _("The original owner cannot be removed, however " msg = _("The original owner cannot be removed, however "
"you can transfer ownership.") "you can transfer ownership.")
if not getattr(self, 'hide_messages', False): if not getattr(self, 'hide_messages', False):
messages.warning(self.request, msg) messages.warning(self.request, msg)
elif self.check_auth(whom, old_level, new_level): elif self.check_auth(whom, old_level, new_level):
logger.info( logger.info(
"Set %s's acl level for %s to %s by %s.", bytes(whom), "Set %s's acl level for %s to %s by %s.", unicode(whom),
bytes(self.instance), new_level, bytes(user)) unicode(self.instance), new_level, unicode(user))
if not getattr(self, 'hide_messages', False): if not getattr(self, 'hide_messages', False):
self.send_success_message(whom, old_level, new_level) self.send_success_message(whom, old_level, new_level)
self.instance.set_level(whom, new_level) self.instance.set_level(whom, new_level)
else: else:
logger.warning( logger.warning(
"Tried to set %s's acl_level for %s (%s->%s) by %s.", "Tried to set %s's acl_level for %s (%s->%s) by %s.",
bytes(whom), bytes(self.instance), old_level, new_level, unicode(whom), unicode(self.instance), old_level, new_level,
bytes(user)) unicode(user))
def set_or_remove_levels(self): def set_or_remove_levels(self):
for key, value in list(self.request.POST.items()): for key, value in list(self.request.POST.items()):
...@@ -654,7 +661,7 @@ class TransferOwnershipView(CheckedDetailView, DetailView): ...@@ -654,7 +661,7 @@ class TransferOwnershipView(CheckedDetailView, DetailView):
else: else:
messages.success(request, messages.success(request,
_('User %s is notified about the offer.') % ( _('User %s is notified about the offer.') % (
bytes(new_owner), )) unicode(new_owner), ))
return redirect(obj.get_absolute_url()) return redirect(obj.get_absolute_url())
...@@ -667,7 +674,7 @@ class TransferOwnershipConfirmView(LoginRequiredMixin, View): ...@@ -667,7 +674,7 @@ class TransferOwnershipConfirmView(LoginRequiredMixin, View):
@classmethod @classmethod
def get_salt(cls): def get_salt(cls):
return bytes(cls) + bytes(cls.model) return unicode(cls) + unicode(cls.model)
def get(self, request, key, *args, **kwargs): def get(self, request, key, *args, **kwargs):
"""Confirm ownership transfer based on token. """Confirm ownership transfer based on token.
...@@ -698,7 +705,7 @@ class TransferOwnershipConfirmView(LoginRequiredMixin, View): ...@@ -698,7 +705,7 @@ class TransferOwnershipConfirmView(LoginRequiredMixin, View):
self.change_owner(instance, request.user) self.change_owner(instance, request.user)
messages.success(request, self.success_message) messages.success(request, self.success_message)
logger.info('Ownership of %s transferred from %s to %s.', logger.info('Ownership of %s transferred from %s to %s.',
bytes(instance), bytes(old), bytes(request.user)) unicode(instance), unicode(old), unicode(request.user))
if old.profile: if old.profile:
old.profile.notify( old.profile.notify(
ugettext_noop('Ownership accepted'), ugettext_noop('Ownership accepted'),
...@@ -716,7 +723,7 @@ class TransferOwnershipConfirmView(LoginRequiredMixin, View): ...@@ -716,7 +723,7 @@ class TransferOwnershipConfirmView(LoginRequiredMixin, View):
salt=self.get_salt())) salt=self.get_salt()))
except (signing.BadSignature, ValueError, TypeError) as e: except (signing.BadSignature, ValueError, TypeError) as e:
logger.error('Tried invalid token. Token: %s, user: %s. %s', logger.error('Tried invalid token. Token: %s, user: %s. %s',
key, bytes(user), bytes(e)) key, unicode(user), unicode(e))
raise SuspiciousOperation() raise SuspiciousOperation()
try: try:
...@@ -724,12 +731,12 @@ class TransferOwnershipConfirmView(LoginRequiredMixin, View): ...@@ -724,12 +731,12 @@ class TransferOwnershipConfirmView(LoginRequiredMixin, View):
except self.model.DoesNotExist as e: except self.model.DoesNotExist as e:
logger.error('Tried token to nonexistent instance %d. ' logger.error('Tried token to nonexistent instance %d. '
'Token: %s, user: %s. %s', 'Token: %s, user: %s. %s',
instance, key, bytes(user), bytes(e)) instance, key, unicode(user), unicode(e))
raise Http404() raise Http404()
if new_owner != user.pk: if new_owner != user.pk:
logger.error('%s (%d) tried the token for %s. Token: %s.', logger.error('%s (%d) tried the token for %s. Token: %s.',
bytes(user), user.pk, new_owner, key) unicode(user), user.pk, new_owner, key)
raise PermissionDenied() raise PermissionDenied()
return (instance, new_owner) return (instance, new_owner)
......
...@@ -75,6 +75,13 @@ from request.forms import LeaseRequestForm, TemplateRequestForm ...@@ -75,6 +75,13 @@ from request.forms import LeaseRequestForm, TemplateRequestForm
from ..models import Favourite from ..models import Favourite
from manager.scheduler import has_traits from manager.scheduler import has_traits
try:
# Python 2: "unicode" is built-in
unicode
except NameError:
unicode = str
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
...@@ -315,7 +322,7 @@ def get_operations(instance, user): ...@@ -315,7 +322,7 @@ def get_operations(instance, user):
op.check_precond() op.check_precond()
except PermissionDenied as e: except PermissionDenied as e:
pass pass
# logger.debug('Not showing operation %s for %s: %s', k, instance, bytes(e)) # logger.debug('Not showing operation %s for %s: %s', k, instance, unicode(e))
except Exception: except Exception:
ops.append(v.bind_to_object(instance, disabled=True)) ops.append(v.bind_to_object(instance, disabled=True))
else: else:
......
...@@ -24,6 +24,11 @@ from fabric.api import env, run, settings, sudo, prefix, cd, execute ...@@ -24,6 +24,11 @@ from fabric.api import env, run, settings, sudo, prefix, cd, execute
from fabric.context_managers import shell_env from fabric.context_managers import shell_env
from fabric.decorators import roles, parallel from fabric.decorators import roles, parallel
try:
# Python 2: "unicode" is built-in
unicode
except NameError:
unicode = str
env.roledefs['portal'] = ['localhost'] env.roledefs['portal'] = ['localhost']
...@@ -35,7 +40,7 @@ try: ...@@ -35,7 +40,7 @@ try:
except Exception as e: except Exception as e:
print(e) print(e)
else: else:
env.roledefs['node'] = [bytes(n.host.ipv4) env.roledefs['node'] = [unicode(n.host.ipv4)
for n in _Node.objects.filter(enabled=True)] for n in _Node.objects.filter(enabled=True)]
env.roledefs['storage'] = [_DataStore.objects.get().hostname] env.roledefs['storage'] = [_DataStore.objects.get().hostname]
...@@ -149,7 +154,7 @@ def selenium(test=""): ...@@ -149,7 +154,7 @@ def selenium(test=""):
def pull(dir="~/circle/circle"): def pull(dir="~/circle/circle"):
"Pull from upstream branch (stash any changes)" "Pull from upstream branch (stash any changes)"
now = bytes(datetime.datetime.now()) now = unicode(datetime.datetime.now())
with cd(dir), shell_env(GIT_AUTHOR_NAME="fabric", with cd(dir), shell_env(GIT_AUTHOR_NAME="fabric",
GIT_AUTHOR_EMAIL="fabric@local", GIT_AUTHOR_EMAIL="fabric@local",
GIT_COMMITTER_NAME="fabric", GIT_COMMITTER_NAME="fabric",
......
...@@ -23,6 +23,12 @@ from firewall.models import (Rule, Host, Vlan, Group, VlanGroup, Firewall, ...@@ -23,6 +23,12 @@ from firewall.models import (Rule, Host, Vlan, Group, VlanGroup, Firewall,
SwitchPort, EthernetDevice) SwitchPort, EthernetDevice)
from django import contrib from django import contrib
try:
# Python 2: "unicode" is built-in
unicode
except NameError:
unicode = str
class RuleInline(contrib.admin.TabularInline): class RuleInline(contrib.admin.TabularInline):
model = Rule model = Rule
...@@ -107,7 +113,7 @@ class RuleAdmin(admin.ModelAdmin): ...@@ -107,7 +113,7 @@ class RuleAdmin(admin.ModelAdmin):
for field in [instance.vlan, instance.vlangroup, instance.host, for field in [instance.vlan, instance.vlangroup, instance.host,
instance.hostgroup, instance.firewall]: instance.hostgroup, instance.firewall]:
if field: if field:
return bytes(field) + ' ' + field._meta.object_name return unicode(field) + ' ' + field._meta.object_name
class AliasAdmin(admin.ModelAdmin): class AliasAdmin(admin.ModelAdmin):
......
...@@ -25,6 +25,11 @@ from netaddr import (IPAddress, IPNetwork, AddrFormatError, ZEROFILL, ...@@ -25,6 +25,11 @@ from netaddr import (IPAddress, IPNetwork, AddrFormatError, ZEROFILL,
EUI, mac_unix, AddrConversionError) EUI, mac_unix, AddrConversionError)
import re import re
try:
# Python 2: "unicode" is built-in
unicode
except NameError:
unicode = str
alfanum_re = re.compile(r'^[A-Za-z0-9_-]+$') alfanum_re = re.compile(r'^[A-Za-z0-9_-]+$')
domain_re = re.compile(r'^([A-Za-z0-9_/-]\.?)+$') domain_re = re.compile(r'^([A-Za-z0-9_/-]\.?)+$')
...@@ -47,7 +52,7 @@ class MACAddressFormField(forms.Field): ...@@ -47,7 +52,7 @@ class MACAddressFormField(forms.Field):
return MACAddressField.to_python return MACAddressField.to_python
except (AddrFormatError, TypeError, ValidationError) as e: except (AddrFormatError, TypeError, ValidationError) as e:
raise ValidationError(self.default_error_messages['invalid'] raise ValidationError(self.default_error_messages['invalid']
% bytes(e)) % unicode(e))
class MACAddressField(models.Field): class MACAddressField(models.Field):
...@@ -169,7 +174,7 @@ class IPNetworkFormField(forms.Field): ...@@ -169,7 +174,7 @@ class IPNetworkFormField(forms.Field):
return IPNetworkField(version=self.version).to_python(value) return IPNetworkField(version=self.version).to_python(value)
except (AddrFormatError, TypeError) as e: except (AddrFormatError, TypeError) as e:
raise ValidationError(self.default_error_messages['invalid'] raise ValidationError(self.default_error_messages['invalid']
% bytes(e)) % unicode(e))
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
self.version = kwargs['version'] self.version = kwargs['version']
...@@ -274,7 +279,7 @@ def val_ipv6_template(value): ...@@ -274,7 +279,7 @@ def val_ipv6_template(value):
>>> val_ipv6_template("123::%(a)d:%(b)d:%(c)d:%(d)d") >>> val_ipv6_template("123::%(a)d:%(b)d:%(c)d:%(d)d")
>>> val_ipv6_template("::%(a)x:%(b)x:%(c)d:%(d)d") >>> val_ipv6_template("::%(a)x:%(b)x:%(c)d:%(d)d")
Don't have to use all bytes from the left (no a): Don't have to use all unicode from the left (no a):
>>> val_ipv6_template("::%(b)x:%(c)d:%(d)d") >>> val_ipv6_template("::%(b)x:%(c)d:%(d)d")
But have to use all ones to the right (a, but no b): But have to use all ones to the right (a, but no b):
......
...@@ -29,6 +29,12 @@ from django.template import loader ...@@ -29,6 +29,12 @@ from django.template import loader
from django.utils import timezone from django.utils import timezone
try:
# Python 2: "unicode" is built-in
unicode
except NameError:
unicode = str
settings = django.conf.settings.FIREWALL_SETTINGS settings = django.conf.settings.FIREWALL_SETTINGS
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
...@@ -152,9 +158,9 @@ class BuildFirewall: ...@@ -152,9 +158,9 @@ class BuildFirewall:
template = loader.get_template('firewall/iptables.conf') template = loader.get_template('firewall/iptables.conf')
context['proto'] = 'ipv4' context['proto'] = 'ipv4'
ipv4 = bytes(template.render(context)) ipv4 = unicode(template.render(context))
context['proto'] = 'ipv6' context['proto'] = 'ipv6'
ipv6 = bytes(template.render(context)) ipv6 = unicode(template.render(context))
return (ipv4, ipv6) return (ipv4, ipv6)
......
...@@ -46,6 +46,12 @@ from .iptables import IptRule ...@@ -46,6 +46,12 @@ from .iptables import IptRule
from acl.models import AclBase from acl.models import AclBase
try:
# Python 2: "unicode" is built-in
unicode
except NameError:
unicode = str
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
settings = django.conf.settings.FIREWALL_SETTINGS settings = django.conf.settings.FIREWALL_SETTINGS
...@@ -178,10 +184,10 @@ class Rule(models.Model): ...@@ -178,10 +184,10 @@ class Rule(models.Model):
""" """
return '[%(type)s] %(src)s ▸ %(dst)s %(para)s %(desc)s' % { return '[%(type)s] %(src)s ▸ %(dst)s %(para)s %(desc)s' % {
'type': self.r_type, 'type': self.r_type,
'src': (bytes(self.foreign_network) if self.direction == 'in' 'src': (str(self.foreign_network) if self.direction == 'in'
else self.r_type), else self.r_type),
'dst': (self.r_type if self.direction == 'out' 'dst': (self.r_type if self.direction == 'out'
else bytes(self.foreign_network)), else str(self.foreign_network)),
'para': ((("proto=%s " % self.proto) if self.proto else '') + 'para': ((("proto=%s " % self.proto) if self.proto else '') +
(("sport=%s " % self.sport) if self.sport else '') + (("sport=%s " % self.sport) if self.sport else '') +
(("dport=%s " % self.dport) if self.dport else '')), (("dport=%s " % self.dport) if self.dport else '')),
...@@ -363,7 +369,7 @@ class Vlan(AclBase, models.Model): ...@@ -363,7 +369,7 @@ class Vlan(AclBase, models.Model):
help_text=_('Template of the IPv4 reverse domain name that ' help_text=_('Template of the IPv4 reverse domain name that '
'should be generated for each host. The template ' 'should be generated for each host. The template '
'should contain four tokens: "%(a)d", "%(b)d", ' 'should contain four tokens: "%(a)d", "%(b)d", '
'"%(c)d", and "%(d)d", representing the four bytes ' '"%(c)d", and "%(d)d", representing the four unicode '
'of the address, respectively, in decimal notation. ' 'of the address, respectively, in decimal notation. '
'For example, the template for the standard reverse ' 'For example, the template for the standard reverse '
'address is: "%(d)d.%(c)d.%(b)d.%(a)d.in-addr.arpa".'), 'address is: "%(d)d.%(c)d.%(b)d.%(a)d.in-addr.arpa".'),
...@@ -374,7 +380,7 @@ class Vlan(AclBase, models.Model): ...@@ -374,7 +380,7 @@ class Vlan(AclBase, models.Model):
'Automatically generated hosts in dual-stack networks ' 'Automatically generated hosts in dual-stack networks '
'will get this address. The template ' 'will get this address. The template '
'can contain four tokens: "%(a)d", "%(b)d", ' 'can contain four tokens: "%(a)d", "%(b)d", '
'"%(c)d", and "%(d)d", representing the four bytes ' '"%(c)d", and "%(d)d", representing the four unicode '
'of the IPv4 address, respectively, in decimal notation. ' 'of the IPv4 address, respectively, in decimal notation. '
'Moreover you can use any standard printf format ' 'Moreover you can use any standard printf format '
'specification like %(a)02x to get the first byte as two ' 'specification like %(a)02x to get the first byte as two '
...@@ -424,8 +430,8 @@ class Vlan(AclBase, models.Model): ...@@ -424,8 +430,8 @@ class Vlan(AclBase, models.Model):
self.host_ipv6_prefixlen = prefixlen self.host_ipv6_prefixlen = prefixlen
@staticmethod @staticmethod
def _host_bytes(prefixlen, maxbytes): def _host_unicode(prefixlen, maxunicode):
return int(ceil((maxbytes - prefixlen / 8.0))) return int(ceil((maxunicode - prefixlen / 8.0)))
@staticmethod @staticmethod
def _append_hexa(s, v, lasthalf): def _append_hexa(s, v, lasthalf):
...@@ -453,26 +459,26 @@ class Vlan(AclBase, models.Model): ...@@ -453,26 +459,26 @@ class Vlan(AclBase, models.Model):
... IPNetwork("2001:0DB8:1:1::/64"), False) ... IPNetwork("2001:0DB8:1:1::/64"), False)
('2001:db8:1:1:%(d)02x00::', 72) ('2001:db8:1:1:%(d)02x00::', 72)
""" """
host4_bytes = cls._host_bytes(network4.prefixlen, 4) host4_unicode = cls._host_unicode(network4.prefixlen, 4)
host6_bytes = cls._host_bytes(network6.prefixlen, 16) host6_unicode = cls._host_unicode(network6.prefixlen, 16)
if host4_bytes > host6_bytes: if host4_unicode > host6_unicode:
raise ValidationError( raise ValidationError(
_("IPv6 network is too small to map IPv4 addresses to it.")) _("IPv6 network is too small to map IPv4 addresses to it."))
letters = ascii_letters[4-host4_bytes:4] letters = ascii_letters[4-host4_unicode:4]
remove = host6_bytes // 2 remove = host6_unicode // 2
ipstr = network6.network.format(ipv6_full) ipstr = network6.network.format(ipv6_full)
s = ipstr.split(":")[0:-remove] s = ipstr.split(":")[0:-remove]
if verbose is None: # use verbose format if net6 much wider if verbose is None: # use verbose format if net6 much wider
verbose = 2 * (host4_bytes + 1) < host6_bytes verbose = 2 * (host4_unicode + 1) < host6_unicode
if verbose: if verbose:
for i in letters: for i in letters:
s.append("%({})d".format(i)) s.append("%({})d".format(i))
else: else:
remain = host6_bytes remain = host6_unicode
for i in letters: for i in letters:
cls._append_hexa(s, i, remain % 2 == 1) cls._append_hexa(s, i, remain % 2 == 1)
remain -= 1 remain -= 1
if host6_bytes > host4_bytes: if host6_unicode > host4_unicode:
s.append(":") s.append(":")
tpl = ":".join(s) tpl = ":".join(s)
# compute prefix length # compute prefix length
...@@ -886,11 +892,11 @@ class Host(models.Model): ...@@ -886,11 +892,11 @@ class Host(models.Model):
res = Record.objects.filter( res = Record.objects.filter(
type='A', address=self.get_external_ipv4()) type='A', address=self.get_external_ipv4())
if res.count() < 1: if res.count() < 1:
return bytes(self.get_external_ipv4()) return unicode(self.get_external_ipv4())
else: else:
res = self.record_set.filter(type='A', res = self.record_set.filter(type='A',
address=self.ipv4) address=self.ipv4)
return bytes(res[0].fqdn) return unicode(res[0].fqdn)
except: except:
return None return None
......
...@@ -63,15 +63,15 @@ def get_firewall_queues(): ...@@ -63,15 +63,15 @@ def get_firewall_queues():
@celery.task @celery.task
def reloadtask_worker(): def reloadtask_worker():
from firewall.fw import BuildFirewall, dhcp, dns, ipset, vlan from firewall.fw import BuildFirewall, dhcp, dns, ipset, vlan
from remote_tasks import (reload_dns, reload_dhcp, reload_firewall, from firewall.tasks.remote_tasks import (reload_dns, reload_dhcp, reload_firewall,
reload_firewall_vlan, reload_blacklist) reload_firewall_vlan, reload_blacklist)
tasks = [] tasks = []
for i in ('dns', 'dhcp', 'firewall', 'firewall_vlan', 'blacklist'): for i in ('dns', 'dhcp', 'firewall', 'firewall_vlan', 'blacklist'):
lockname = "%s_lock" % i lockname = "%s_lock" % i
if cache.get(lockname): # if cache.get(lockname):
tasks.append(i) tasks.append(i)
cache.delete(lockname) # cache.delete(lockname)
logger.info("reloadtask_worker: Reload %s", ", ".join(tasks)) logger.info("reloadtask_worker: Reload %s", ", ".join(tasks))
......
...@@ -36,6 +36,13 @@ from .models import BlacklistItem, Host ...@@ -36,6 +36,13 @@ from .models import BlacklistItem, Host
from django.conf import settings from django.conf import settings
try:
# Python 2: "unicode" is built-in
unicode
except NameError:
unicode = str
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
...@@ -108,4 +115,4 @@ def add_blacklist_item(request): ...@@ -108,4 +115,4 @@ def add_blacklist_item(request):
if is_new and settings.BLACKLIST_HOOK_URL: if is_new and settings.BLACKLIST_HOOK_URL:
send_request(obj) send_request(obj)
return HttpResponse(bytes(_("OK"))) return HttpResponse(unicode(_("OK")))
...@@ -39,7 +39,6 @@ def crontab_parser(crontab): ...@@ -39,7 +39,6 @@ def crontab_parser(crontab):
day_of_week=fields[4], day_of_week=fields[4],
) )
celery = Celery('manager', celery = Celery('manager',
broker=getenv("AMQP_URI"), broker=getenv("AMQP_URI"),
include=['vm.tasks.local_tasks', include=['vm.tasks.local_tasks',
...@@ -51,9 +50,10 @@ celery = Celery('manager', ...@@ -51,9 +50,10 @@ celery = Celery('manager',
'dashboard.tasks.local_periodic_tasks', 'dashboard.tasks.local_periodic_tasks',
]) ])
celery.config_from_object('celeryconfig')
celery.conf.update( celery.conf.update(
CELERY_RESULT_BACKEND='amqp', # CELERY_RESULT_BACKEND='amqp',
CELERY_TASK_RESULT_EXPIRES=30000,
CELERY_QUEUES=( CELERY_QUEUES=(
Queue(HOSTNAME + '.man', Exchange('manager', type='direct'), Queue(HOSTNAME + '.man', Exchange('manager', type='direct'),
routing_key="manager"), routing_key="manager"),
......
...@@ -24,15 +24,17 @@ from os import getenv ...@@ -24,15 +24,17 @@ from os import getenv
HOSTNAME = "localhost" HOSTNAME = "localhost"
QUEUE_NAME = HOSTNAME + '.monitor' QUEUE_NAME = HOSTNAME + '.monitor'
celery = Celery('monitor', celery = Celery('monitor',
broker=getenv("AMQP_URI"), broker=getenv("AMQP_URI"),
include=['vm.tasks.local_periodic_tasks', include=['vm.tasks.local_periodic_tasks',
'monitor.tasks.local_periodic_tasks', 'monitor.tasks.local_periodic_tasks',
]) ])
celery.config_from_object('celeryconfig')
celery.conf.update( celery.conf.update(
CELERY_RESULT_BACKEND='amqp', # CELERY_RESULT_BACKEND='amqp',
CELERY_TASK_RESULT_EXPIRES=30000,
CELERY_QUEUES=( CELERY_QUEUES=(
Queue(QUEUE_NAME, Exchange('monitor', type='direct'), Queue(QUEUE_NAME, Exchange('monitor', type='direct'),
routing_key="monitor"), routing_key="monitor"),
......
...@@ -24,6 +24,7 @@ from os import getenv ...@@ -24,6 +24,7 @@ from os import getenv
HOSTNAME = "localhost" HOSTNAME = "localhost"
QUEUE_NAME = HOSTNAME + '.man.slow' QUEUE_NAME = HOSTNAME + '.man.slow'
celery = Celery('manager.slow', celery = Celery('manager.slow',
broker=getenv("AMQP_URI"), broker=getenv("AMQP_URI"),
include=['vm.tasks.local_tasks', include=['vm.tasks.local_tasks',
...@@ -31,10 +32,10 @@ celery = Celery('manager.slow', ...@@ -31,10 +32,10 @@ celery = Celery('manager.slow',
'storage.tasks.local_tasks', 'storage.tasks.local_tasks',
'storage.tasks.periodic_tasks', 'storage.tasks.periodic_tasks',
]) ])
celery.config_from_object('celeryconfig')
celery.conf.update( celery.conf.update(
CELERY_RESULT_BACKEND='amqp', # CELERY_RESULT_BACKEND='amqp',
CELERY_TASK_RESULT_EXPIRES=30000,
CELERY_QUEUES=( CELERY_QUEUES=(
Queue(QUEUE_NAME, Exchange('manager.slow', type='direct'), Queue(QUEUE_NAME, Exchange('manager.slow', type='direct'),
routing_key="manager.slow"), routing_key="manager.slow"),
......
...@@ -67,6 +67,12 @@ ACCESS_METHODS = [(key, name) for key, (name, port, transport) ...@@ -67,6 +67,12 @@ ACCESS_METHODS = [(key, name) for key, (name, port, transport)
in list(ACCESS_PROTOCOLS.items())] in list(ACCESS_PROTOCOLS.items())]
try:
# Python 2: "unicode" is built-in
unicode
except NameError:
unicode = str
def find_unused_port(port_range, used_ports=[]): def find_unused_port(port_range, used_ports=[]):
"""Find an unused port in the specified range. """Find an unused port in the specified range.
...@@ -699,7 +705,7 @@ class Instance(AclBase, VirtualMachineDescModel, StatusModel, OperatedMixin, ...@@ -699,7 +705,7 @@ class Instance(AclBase, VirtualMachineDescModel, StatusModel, OperatedMixin,
" Failed ones are: %(faileds_ex)s."), " Failed ones are: %(faileds_ex)s."),
failed=len(failed), success=len(success), failed=len(failed), success=len(success),
faileds=", ".join(a for a, e in failed), faileds=", ".join(a for a, e in failed),
faileds_ex=", ".join("%s (%s)" % (a, bytes(e)) faileds_ex=", ".join("%s (%s)" % (a, unicode(e))
for a, e in failed)) for a, e in failed))
else: else:
act.result = create_readable(ugettext_noop( act.result = create_readable(ugettext_noop(
......
...@@ -57,6 +57,13 @@ from .tasks.local_tasks import ( ...@@ -57,6 +57,13 @@ from .tasks.local_tasks import (
abortable_async_instance_operation, abortable_async_node_operation, abortable_async_instance_operation, abortable_async_node_operation,
) )
try:
# Python 2: "unicode" is built-in
unicode
except NameError:
unicode = str
logger = getLogger(__name__) logger = getLogger(__name__)
...@@ -111,16 +118,16 @@ class InstanceOperation(Operation): ...@@ -111,16 +118,16 @@ class InstanceOperation(Operation):
if self.accept_states: if self.accept_states:
if self.instance.status not in self.accept_states: if self.instance.status not in self.accept_states:
logger.debug("precond failed for %s: %s not in %s", logger.debug("precond failed for %s: %s not in %s",
bytes(self.__class__), unicode(self.__class__),
bytes(self.instance.status), unicode(self.instance.status),
bytes(self.accept_states)) unicode(self.accept_states))
raise self.instance.WrongStateError(self.instance) raise self.instance.WrongStateError(self.instance)
if self.deny_states: if self.deny_states:
if self.instance.status in self.deny_states: if self.instance.status in self.deny_states:
logger.debug("precond failed for %s: %s in %s", logger.debug("precond failed for %s: %s in %s",
bytes(self.__class__), unicode(self.__class__),
bytes(self.instance.status), unicode(self.instance.status),
bytes(self.accept_states)) unicode(self.accept_states))
raise self.instance.WrongStateError(self.instance) raise self.instance.WrongStateError(self.instance)
def check_auth(self, user): def check_auth(self, user):
...@@ -1310,7 +1317,7 @@ class UpdateNodeOperation(NodeOperation): ...@@ -1310,7 +1317,7 @@ class UpdateNodeOperation(NodeOperation):
if not isinstance(data, dict): if not isinstance(data, dict):
raise HumanReadableException.create(ugettext_noop( raise HumanReadableException.create(ugettext_noop(
"Unhandled exception: %(msg)s"), msg=bytes(data)) "Unhandled exception: %(msg)s"), msg=unicode(data))
return data return data
...@@ -1321,7 +1328,7 @@ class UpdateNodeOperation(NodeOperation): ...@@ -1321,7 +1328,7 @@ class UpdateNodeOperation(NodeOperation):
data = self.minion_cmd('pkg.upgrade', []) data = self.minion_cmd('pkg.upgrade', [])
if not data.get('result'): if not data.get('result'):
raise HumanReadableException.create(ugettext_noop( raise HumanReadableException.create(ugettext_noop(
"Unhandled exception: %(msg)s"), msg=bytes(data)) "Unhandled exception: %(msg)s"), msg=unicode(data))
# data = {'vim': {'new': '1.2.7', 'old': '1.3.7'}} # data = {'vim': {'new': '1.2.7', 'old': '1.3.7'}}
data = [v for v in list(data.values()) if isinstance(v, dict)] data = [v for v in list(data.values()) if isinstance(v, dict)]
...@@ -1786,11 +1793,11 @@ class DetachMixin(object): ...@@ -1786,11 +1793,11 @@ class DetachMixin(object):
try: try:
super(DetachMixin, self)._operation(**kwargs) super(DetachMixin, self)._operation(**kwargs)
except Exception as e: except Exception as e:
if hasattr(e, "libvirtError") and "not found" in bytes(e): if hasattr(e, "libvirtError") and "not found" in unicode(e):
activity.result = create_readable( activity.result = create_readable(
ugettext_noop("Resource was not found."), ugettext_noop("Resource was not found."),
ugettext_noop("Resource was not found. %(exception)s"), ugettext_noop("Resource was not found. %(exception)s"),
exception=bytes(e)) exception=unicode(e))
else: else:
raise raise
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment