<commit_before># Copyright (c) 2015 Ansible, Inc.
# All Rights Reserved.

# Python
import datetime
import hashlib
import hmac
import uuid

# Django
from django.conf import settings
from django.db import models
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from django.utils.timezone import now as tz_now
from django.utils.translation import ugettext_lazy as _

# AWX
from awx.main.fields import AutoOneToOneField, ImplicitRoleField
from awx.main.models.base import * # noqa
from awx.main.models.mixins import ResourceMixin
from awx.main.conf import tower_settings

__all__ = ['Organization', 'Team', 'Permission', 'Profile', 'AuthToken']

class Organization(CommonModel, ResourceMixin):
    '''
    An organization is the basic unit of multi-tenancy divisions
    '''

    class Meta:
        app_label = 'main'
        ordering = ('name',)

    users = models.ManyToManyField(
        'auth.User',
        blank=True,
        related_name='organizations',
    )
    admins = models.ManyToManyField(
        'auth.User',
        blank=True,
        related_name='admin_of_organizations',
    )

    # TODO: This field is deprecated. In 3.0 all projects will have exactly one
    # organization parent, the foreign key field representing that has been
    # moved to the Project model.
    projects = models.ManyToManyField(
        'Project',
        blank=True,
        related_name='organizations',
    )
    admin_role = ImplicitRoleField(
        role_name='Organization Administrator',
        resource_field='resource',
        permissions = {'all': True}
    )
    auditor_role = ImplicitRoleField(
        role_name='Organization Auditor',
        resource_field='resource',
        permissions = {'read': True}
    )

    def get_absolute_url(self):
        return reverse('api:organization_detail', args=(self.pk,))

    def __unicode__(self):
        return self.name

    def mark_inactive(self, save=True):
        for script in self.custom_inventory_scripts.all():
            script.organization = None
            script.save()
        super(Organization, self).mark_inactive(save=save)

class Team(CommonModelNameNotUnique, ResourceMixin):
    '''
    A team is a group of users that work on common projects.
    '''

    class Meta:
        app_label = 'main'
        unique_together = [('organization', 'name')]
        ordering = ('organization__name', 'name')

    users = models.ManyToManyField(
        'auth.User',
        blank=True,
        related_name='teams',
    )
    organization = models.ForeignKey(
        'Organization',
        blank=False,
        null=True,
        on_delete=models.SET_NULL,
        related_name='teams',
    )
    projects = models.ManyToManyField(
        'Project',
        blank=True,
        related_name='teams',
    )
    admin_role = ImplicitRoleField(
        role_name='Team Administrator',
        parent_role='organization.admin_role',
        resource_field='resource',
        permissions = {'all': True}
    )
    auditor_role = ImplicitRoleField(
        role_name='Team Auditor',
        parent_role='organization.auditor_role',
        resource_field='resource',
        permissions = {'read': True}
    )
    member_role = ImplicitRoleField(
        role_name='Team Member',
        parent_role='admin_role',
        resource_field='resource',
        permissions = {'read':True},
    )

    def get_absolute_url(self):
        return reverse('api:team_detail', args=(self.pk,))

    def mark_inactive(self, save=True):
        '''
        When marking a team inactive we'll wipe out its credentials also
        '''
        for cred in self.credentials.all():
            cred.mark_inactive()
        super(Team, self).mark_inactive(save=save)

class Permission(CommonModelNameNotUnique):
    '''
    A permission allows a user, project, or team to be able to use an inventory source.

    NOTE: This class is deprecated, permissions and access is to be handled by
    our new RBAC system. This class should be able to be safely removed after a 3.0.0
    migration. - anoek 2016-01-28
    '''

    class Meta:
        app_label = 'main'

    # permissions are granted to either a user or a team:
    user            = models.ForeignKey('auth.User', null=True, on_delete=models.SET_NULL, blank=True, related_name='permissions')
    team            = models.ForeignKey('Team', null=True, on_delete=models.SET_NULL, blank=True, related_name='permissions')

    # to be used against a project or inventory (or a project and inventory in conjunction):
    project = models.ForeignKey(
        'Project',
        blank=True,
        null=True,
        on_delete=models.SET_NULL,
        related_name='permissions',
    )
    inventory       = models.ForeignKey('Inventory', null=True, on_delete=models.SET_NULL, related_name='permissions')

    # permission system explanation:
    #
    # for example, user A on inventory X has write permissions                 (PERM_INVENTORY_WRITE)
    #              team C on inventory X has read permissions                  (PERM_INVENTORY_READ)
    #              user A can create job templates                             (PERM_JOBTEMPLATE_CREATE)
    #              team C on inventory X and project Y has launch permissions  (PERM_INVENTORY_DEPLOY)
    #              team C on inventory X and project Z has dry run permissions (PERM_INVENTORY_CHECK)
    #
    # basically for launching, permissions can be awarded to the whole inventory source or just the inventory source
    # in context of a given project.
    #
    # the project parameter is not used when dealing with READ, WRITE, or ADMIN permissions.

    permission_type = models.CharField(max_length=64, choices=PERMISSION_TYPE_CHOICES)
    run_ad_hoc_commands = models.BooleanField(default=False,
                                              help_text=_('Execute Commands on the Inventory'))

    def __unicode__(self):
        return unicode("Permission(name=%s,ON(user=%s,team=%s),FOR(project=%s,inventory=%s,type=%s%s))" % (
            self.name,
            self.user,
            self.team,
            self.project,
            self.inventory,
            self.permission_type,
            '+adhoc' if self.run_ad_hoc_commands else '',
        ))

    def get_absolute_url(self):
        return reverse('api:permission_detail', args=(self.pk,))

class Profile(CreatedModifiedModel):
    '''
    Profile model related to User object. Currently stores LDAP DN for users
    loaded from LDAP.
    '''

    class Meta:
        app_label = 'main'

    user = AutoOneToOneField(
        'auth.User',
        related_name='profile',
        editable=False,
    )
    ldap_dn = models.CharField(
        max_length=1024,
        default='',
    )

"""
Since expiration and session expiration is event driven a token could be
invalidated for both reasons. Further, we only support a single reason for a
session token being invalid. For this case, mark the token as expired.

Note: Again, because the value of reason is event based. The reason may not be
set (i.e. may equal '') even though a session is expired or a limit is reached.
"""
class AuthToken(BaseModel):
    '''
    Custom authentication tokens per user with expiration and request-specific
    data.
    '''

    REASON_CHOICES = [
        ('', _('Token not invalidated')),
        ('timeout_reached', _('Token is expired')),
        ('limit_reached', _('Maximum per-user sessions reached')),
        # invalid_token is not a used data-base value, but is returned by the
        # api when a token is not found
        ('invalid_token', _('Invalid token')),
    ]

    class Meta:
        app_label = 'main'

    key = models.CharField(max_length=40, primary_key=True)
    user = models.ForeignKey('auth.User', related_name='auth_tokens',
                             on_delete=models.CASCADE)
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)
    expires = models.DateTimeField(default=tz_now)
    request_hash = models.CharField(max_length=40, blank=True, default='')
    reason = models.CharField(
        max_length=1024,
        blank=True,
        default='',
        help_text=_('Reason the auth token was invalidated.')
    )

    @staticmethod
    def reason_long(reason):
        for x in AuthToken.REASON_CHOICES:
            if x[0] == reason:
                return unicode(x[1])
        return None

    @classmethod
    def get_request_hash(cls, request):
        h = hashlib.sha1()
        h.update(settings.SECRET_KEY)
        for header in settings.REMOTE_HOST_HEADERS:
            value = request.META.get(header, '').split(',')[0].strip()
            if value:
                h.update(value)
                break
        h.update(request.META.get('HTTP_USER_AGENT', ''))
        return h.hexdigest()

    def save(self, *args, **kwargs):
        if not self.pk:
            self.refresh(save=False)
        if not self.key:
            self.key = self.generate_key()
        return super(AuthToken, self).save(*args, **kwargs)

    def refresh(self, now=None, save=True):
        if not now:
            now = tz_now()
        if not self.pk or not self.is_expired(now=now):
            self.expires = now + datetime.timedelta(seconds=tower_settings.AUTH_TOKEN_EXPIRATION)
            if save:
                self.save()

    def invalidate(self, reason='timeout_reached', save=True):
        if not AuthToken.reason_long(reason):
            raise ValueError('Invalid reason specified')
        self.reason = reason
        if save:
            self.save()
        return reason

    @staticmethod
    def get_tokens_over_limit(user, now=None):
        if now is None:
            now = tz_now()
        invalid_tokens = AuthToken.objects.none()
        if tower_settings.AUTH_TOKEN_PER_USER != -1:
            invalid_tokens = AuthToken.objects.filter(
                user=user,
                expires__gt=now,
                reason='',
            ).order_by('-created')[tower_settings.AUTH_TOKEN_PER_USER:]
        return invalid_tokens

    def generate_key(self):
        unique = uuid.uuid4()
        return hmac.new(unique.bytes, digestmod=hashlib.sha1).hexdigest()

    def is_expired(self, now=None):
        if not now:
            now = tz_now()
        return bool(self.expires < now)

    @property
    def invalidated(self):
        return bool(self.reason != '')

    """
    Token is valid if it's in the set of unexpired tokens.
    The unexpired token set is:
        * tokens not expired
        * limited to number of tokens per-user
        * sorted by created on date
    """
    def in_valid_tokens(self, now=None):
        if not now:
            now = tz_now()
        valid_n_tokens_qs = self.user.auth_tokens.filter(
            expires__gt=now,
            reason='',
        ).order_by('-created')[0:tower_settings.AUTH_TOKEN_PER_USER]
        valid_n_tokens = valid_n_tokens_qs.values_list('key', flat=True)

        return bool(self.key in valid_n_tokens)

    def __unicode__(self):
        return self.key

# Add mark_inactive method to User model.
def user_mark_inactive(user, save=True):
    '''Use instead of delete to rename and mark users inactive.'''
    if user.is_active:
        # Set timestamp to datetime.isoformat() but without the time zone
        # offset to stay withint the 30 character username limit.
        dtnow = tz_now()
        deleted_ts = dtnow.strftime('%Y-%m-%dT%H:%M:%S.%f')
        user.username = '_d_%s' % deleted_ts
        user.is_active = False
        if save:
            user.save()

User.add_to_class('mark_inactive', user_mark_inactive)

# Add get_absolute_url method to User model if not present.
if not hasattr(User, 'get_absolute_url'):
    def user_get_absolute_url(user):
        return reverse('api:user_detail', args=(user.pk,))
    User.add_to_class('get_absolute_url', user_get_absolute_url)
<commit_msg>Added an explicit member role, distinct from auditor role<commit_after># Copyright (c) 2015 Ansible, Inc.
# All Rights Reserved.

# Python
import datetime
import hashlib
import hmac
import uuid

# Django
from django.conf import settings
from django.db import models
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from django.utils.timezone import now as tz_now
from django.utils.translation import ugettext_lazy as _

# AWX
from awx.main.fields import AutoOneToOneField, ImplicitRoleField
from awx.main.models.base import * # noqa
from awx.main.models.mixins import ResourceMixin
from awx.main.conf import tower_settings

__all__ = ['Organization', 'Team', 'Permission', 'Profile', 'AuthToken']

class Organization(CommonModel, ResourceMixin):
    '''
    An organization is the basic unit of multi-tenancy divisions
    '''

    class Meta:
        app_label = 'main'
        ordering = ('name',)

    users = models.ManyToManyField(
        'auth.User',
        blank=True,
        related_name='organizations',
    )
    admins = models.ManyToManyField(
        'auth.User',
        blank=True,
        related_name='admin_of_organizations',
    )

    # TODO: This field is deprecated. In 3.0 all projects will have exactly one
    # organization parent, the foreign key field representing that has been
    # moved to the Project model.
    projects = models.ManyToManyField(
        'Project',
        blank=True,
        related_name='organizations',
    )
    admin_role = ImplicitRoleField(
        role_name='Organization Administrator',
        resource_field='resource',
        permissions = {'all': True}
    )
    auditor_role = ImplicitRoleField(
        role_name='Organization Auditor',
        resource_field='resource',
        permissions = {'read': True}
    )
    member_role = ImplicitRoleField(
        role_name='Organization Member',
        resource_field='resource',
        permissions = {'read': True}
    )

    def get_absolute_url(self):
        return reverse('api:organization_detail', args=(self.pk,))

    def __unicode__(self):
        return self.name

    def mark_inactive(self, save=True):
        for script in self.custom_inventory_scripts.all():
            script.organization = None
            script.save()
        super(Organization, self).mark_inactive(save=save)

class Team(CommonModelNameNotUnique, ResourceMixin):
    '''
    A team is a group of users that work on common projects.
    '''

    class Meta:
        app_label = 'main'
        unique_together = [('organization', 'name')]
        ordering = ('organization__name', 'name')

    users = models.ManyToManyField(
        'auth.User',
        blank=True,
        related_name='teams',
    )
    organization = models.ForeignKey(
        'Organization',
        blank=False,
        null=True,
        on_delete=models.SET_NULL,
        related_name='teams',
    )
    projects = models.ManyToManyField(
        'Project',
        blank=True,
        related_name='teams',
    )
    admin_role = ImplicitRoleField(
        role_name='Team Administrator',
        parent_role='organization.admin_role',
        resource_field='resource',
        permissions = {'all': True}
    )
    auditor_role = ImplicitRoleField(
        role_name='Team Auditor',
        parent_role='organization.auditor_role',
        resource_field='resource',
        permissions = {'read': True}
    )
    member_role = ImplicitRoleField(
        role_name='Team Member',
        parent_role='admin_role',
        resource_field='resource',
        permissions = {'read':True},
    )

    def get_absolute_url(self):
        return reverse('api:team_detail', args=(self.pk,))

    def mark_inactive(self, save=True):
        '''
        When marking a team inactive we'll wipe out its credentials also
        '''
        for cred in self.credentials.all():
            cred.mark_inactive()
        super(Team, self).mark_inactive(save=save)

class Permission(CommonModelNameNotUnique):
    '''
    A permission allows a user, project, or team to be able to use an inventory source.

    NOTE: This class is deprecated, permissions and access is to be handled by
    our new RBAC system. This class should be able to be safely removed after a 3.0.0
    migration. - anoek 2016-01-28
    '''

    class Meta:
        app_label = 'main'

    # permissions are granted to either a user or a team:
    user            = models.ForeignKey('auth.User', null=True, on_delete=models.SET_NULL, blank=True, related_name='permissions')
    team            = models.ForeignKey('Team', null=True, on_delete=models.SET_NULL, blank=True, related_name='permissions')

    # to be used against a project or inventory (or a project and inventory in conjunction):
    project = models.ForeignKey(
        'Project',
        blank=True,
        null=True,
        on_delete=models.SET_NULL,
        related_name='permissions',
    )
    inventory       = models.ForeignKey('Inventory', null=True, on_delete=models.SET_NULL, related_name='permissions')

    # permission system explanation:
    #
    # for example, user A on inventory X has write permissions                 (PERM_INVENTORY_WRITE)
    #              team C on inventory X has read permissions                  (PERM_INVENTORY_READ)
    #              user A can create job templates                             (PERM_JOBTEMPLATE_CREATE)
    #              team C on inventory X and project Y has launch permissions  (PERM_INVENTORY_DEPLOY)
    #              team C on inventory X and project Z has dry run permissions (PERM_INVENTORY_CHECK)
    #
    # basically for launching, permissions can be awarded to the whole inventory source or just the inventory source
    # in context of a given project.
    #
    # the project parameter is not used when dealing with READ, WRITE, or ADMIN permissions.

    permission_type = models.CharField(max_length=64, choices=PERMISSION_TYPE_CHOICES)
    run_ad_hoc_commands = models.BooleanField(default=False,
                                              help_text=_('Execute Commands on the Inventory'))

    def __unicode__(self):
        return unicode("Permission(name=%s,ON(user=%s,team=%s),FOR(project=%s,inventory=%s,type=%s%s))" % (
            self.name,
            self.user,
            self.team,
            self.project,
            self.inventory,
            self.permission_type,
            '+adhoc' if self.run_ad_hoc_commands else '',
        ))

    def get_absolute_url(self):
        return reverse('api:permission_detail', args=(self.pk,))

class Profile(CreatedModifiedModel):
    '''
    Profile model related to User object. Currently stores LDAP DN for users
    loaded from LDAP.
    '''

    class Meta:
        app_label = 'main'

    user = AutoOneToOneField(
        'auth.User',
        related_name='profile',
        editable=False,
    )
    ldap_dn = models.CharField(
        max_length=1024,
        default='',
    )

"""
Since expiration and session expiration is event driven a token could be
invalidated for both reasons. Further, we only support a single reason for a
session token being invalid. For this case, mark the token as expired.

Note: Again, because the value of reason is event based. The reason may not be
set (i.e. may equal '') even though a session is expired or a limit is reached.
"""
class AuthToken(BaseModel):
    '''
    Custom authentication tokens per user with expiration and request-specific
    data.
    '''

    REASON_CHOICES = [
        ('', _('Token not invalidated')),
        ('timeout_reached', _('Token is expired')),
        ('limit_reached', _('Maximum per-user sessions reached')),
        # invalid_token is not a used data-base value, but is returned by the
        # api when a token is not found
        ('invalid_token', _('Invalid token')),
    ]

    class Meta:
        app_label = 'main'

    key = models.CharField(max_length=40, primary_key=True)
    user = models.ForeignKey('auth.User', related_name='auth_tokens',
                             on_delete=models.CASCADE)
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)
    expires = models.DateTimeField(default=tz_now)
    request_hash = models.CharField(max_length=40, blank=True, default='')
    reason = models.CharField(
        max_length=1024,
        blank=True,
        default='',
        help_text=_('Reason the auth token was invalidated.')
    )

    @staticmethod
    def reason_long(reason):
        for x in AuthToken.REASON_CHOICES:
            if x[0] == reason:
                return unicode(x[1])
        return None

    @classmethod
    def get_request_hash(cls, request):
        h = hashlib.sha1()
        h.update(settings.SECRET_KEY)
        for header in settings.REMOTE_HOST_HEADERS:
            value = request.META.get(header, '').split(',')[0].strip()
            if value:
                h.update(value)
                break
        h.update(request.META.get('HTTP_USER_AGENT', ''))
        return h.hexdigest()

    def save(self, *args, **kwargs):
        if not self.pk:
            self.refresh(save=False)
        if not self.key:
            self.key = self.generate_key()
        return super(AuthToken, self).save(*args, **kwargs)

    def refresh(self, now=None, save=True):
        if not now:
            now = tz_now()
        if not self.pk or not self.is_expired(now=now):
            self.expires = now + datetime.timedelta(seconds=tower_settings.AUTH_TOKEN_EXPIRATION)
            if save:
                self.save()

    def invalidate(self, reason='timeout_reached', save=True):
        if not AuthToken.reason_long(reason):
            raise ValueError('Invalid reason specified')
        self.reason = reason
        if save:
            self.save()
        return reason

    @staticmethod
    def get_tokens_over_limit(user, now=None):
        if now is None:
            now = tz_now()
        invalid_tokens = AuthToken.objects.none()
        if tower_settings.AUTH_TOKEN_PER_USER != -1:
            invalid_tokens = AuthToken.objects.filter(
                user=user,
                expires__gt=now,
                reason='',
            ).order_by('-created')[tower_settings.AUTH_TOKEN_PER_USER:]
        return invalid_tokens

    def generate_key(self):
        unique = uuid.uuid4()
        return hmac.new(unique.bytes, digestmod=hashlib.sha1).hexdigest()

    def is_expired(self, now=None):
        if not now:
            now = tz_now()
        return bool(self.expires < now)

    @property
    def invalidated(self):
        return bool(self.reason != '')

    """
    Token is valid if it's in the set of unexpired tokens.
    The unexpired token set is:
        * tokens not expired
        * limited to number of tokens per-user
        * sorted by created on date
    """
    def in_valid_tokens(self, now=None):
        if not now:
            now = tz_now()
        valid_n_tokens_qs = self.user.auth_tokens.filter(
            expires__gt=now,
            reason='',
        ).order_by('-created')[0:tower_settings.AUTH_TOKEN_PER_USER]
        valid_n_tokens = valid_n_tokens_qs.values_list('key', flat=True)

        return bool(self.key in valid_n_tokens)

    def __unicode__(self):
        return self.key

# Add mark_inactive method to User model.
def user_mark_inactive(user, save=True):
    '''Use instead of delete to rename and mark users inactive.'''
    if user.is_active:
        # Set timestamp to datetime.isoformat() but without the time zone
        # offset to stay withint the 30 character username limit.
        dtnow = tz_now()
        deleted_ts = dtnow.strftime('%Y-%m-%dT%H:%M:%S.%f')
        user.username = '_d_%s' % deleted_ts
        user.is_active = False
        if save:
            user.save()

User.add_to_class('mark_inactive', user_mark_inactive)

# Add get_absolute_url method to User model if not present.
if not hasattr(User, 'get_absolute_url'):
    def user_get_absolute_url(user):
        return reverse('api:user_detail', args=(user.pk,))
    User.add_to_class('get_absolute_url', user_get_absolute_url)
<|endoftext|>


<commit_before>"""Test for the memoryone strategies."""

import random

import axelrod

from test_player import TestPlayer

class TestWinStayLostShift(TestPlayer):

    name = "Win-Stay Lose-Shift"
    player = axelrod.WinStayLoseShift

    def test_strategy(self):
        """Starts by cooperating"""
        P1 = self.player()
        P2 = axelrod.Player()
        self.assertEqual(P1.strategy(P2), 'C')

    def test_effect_of_strategy(self):
        """Check that switches if does not get best payoff."""
        P1 = self.player()
        P2 = axelrod.Player()
        P1.history = ['C']
        P2.history = ['C']
        self.assertEqual(P1.strategy(P2), 'C')
        P1.history = ['C']
        P2.history = ['D']
        self.assertEqual(P1.strategy(P2), 'D')
        P1.history = ['D']
        P2.history = ['C']
        self.assertEqual(P1.strategy(P2), 'D')
        P1.history = ['D']
        P2.history = ['D']
        self.assertEqual(P1.strategy(P2), 'C')

class TestGTFT(TestPlayer):

    name = "Generous Tit-For-Tat"
    player = axelrod.GTFT
    stochastic = True

    def test_strategy(self):
        P1 = self.player()
        P2 = axelrod.Player()
        self.assertEqual(P1.strategy(P2), 'C')

        P1.history = ['C']
        P2.history = ['C']
        random.seed(2)
        # With probability .05 will defect
        self.assertEqual(P1.strategy(P2), 'D')
        # But otherwise will cooperate
        self.assertEqual(P1.strategy(P2), 'C')
        self.assertEqual(P1.strategy(P2), 'C')
        self.assertEqual(P1.strategy(P2), 'C')

        P1.history = ['C']
        P2.history = ['D']
        random.seed(31)
        # With probability .05 will cooperate
        self.assertEqual(P1.strategy(P2), 'C')
        # But otherwise will defect
        self.assertEqual(P1.strategy(P2), 'D')
        self.assertEqual(P1.strategy(P2), 'D')
        self.assertEqual(P1.strategy(P2), 'D')

        P1.history = ['D']
        P2.history = ['C']
        random.seed(2)
        # With probability .05 will defect
        self.assertEqual(P1.strategy(P2), 'D')
        # But otherwise will cooperate
        self.assertEqual(P1.strategy(P2), 'C')
        self.assertEqual(P1.strategy(P2), 'C')
        self.assertEqual(P1.strategy(P2), 'C')

        P1.history = ['D']
        P2.history = ['D']
        random.seed(31)
        # With probability .05 will cooperate
        self.assertEqual(P1.strategy(P2), 'C')
        # But otherwise will defect
        self.assertEqual(P1.strategy(P2), 'D')
        self.assertEqual(P1.strategy(P2), 'D')
        self.assertEqual(P1.strategy(P2), 'D')

class TestStochasticCooperator(TestPlayer):

    name = "Stochastic Cooperator"
    player = axelrod.StochasticCooperator
    stochastic = True

    def test_strategy(self):
        P1 = self.player()
        P2 = axelrod.Player()
        self.assertEqual(P1.strategy(P2), 'C')

        P1.history = ['C']
        P2.history = ['C']
        random.seed(15)
        # With probability .065 will defect
        self.assertEqual(P1.strategy(P2), 'D')
        # But otherwise will cooperate
        self.assertEqual(P1.strategy(P2), 'C')
        self.assertEqual(P1.strategy(P2), 'C')
        self.assertEqual(P1.strategy(P2), 'C')

        P1.history = ['C']
        P2.history = ['D']
        random.seed(1)
        # With probability .229 will cooperate
        self.assertEqual(P1.strategy(P2), 'C')
        # But otherwise will defect
        self.assertEqual(P1.strategy(P2), 'D')
        self.assertEqual(P1.strategy(P2), 'D')
        self.assertEqual(P1.strategy(P2), 'D')

        P1.history = ['D']
        P2.history = ['C']
        random.seed(3)
        # With probability .266 will cooperate
        self.assertEqual(P1.strategy(P2), 'C')
        # But otherwise will defect
        self.assertEqual(P1.strategy(P2), 'D')
        self.assertEqual(P1.strategy(P2), 'D')
        self.assertEqual(P1.strategy(P2), 'D')

        P1.history = ['D']
        P2.history = ['D']
        random.seed(13)
        # With probability .42 will cooperate
        self.assertEqual(P1.strategy(P2), 'C')
        # But otherwise will defect
        self.assertEqual(P1.strategy(P2), 'D')
        self.assertEqual(P1.strategy(P2), 'D')
        self.assertEqual(P1.strategy(P2), 'D')

class TestStochasticWSLS(TestPlayer):

    name = "Stochastic WSLS"
    player = axelrod.StochasticWSLS
    stochastic = True

    def test_strategy(self):
        P1 = self.player()
        P2 = axelrod.Player()
        self.assertEqual(P1.strategy(P2), 'C')

        P1.history = ['C']
        P2.history = ['C']
        random.seed(2)
        # With probability .05 will defect
        self.assertEqual(P1.strategy(P2), 'D')
        # But otherwise will cooperate
        self.assertEqual(P1.strategy(P2), 'C')
        self.assertEqual(P1.strategy(P2), 'C')
        self.assertEqual(P1.strategy(P2), 'C')

        P1.history = ['C']
        P2.history = ['D']
        random.seed(31)
        # With probability .05 will cooperate
        self.assertEqual(P1.strategy(P2), 'C')
        # But otherwise will defect
        self.assertEqual(P1.strategy(P2), 'D')
        self.assertEqual(P1.strategy(P2), 'D')
        self.assertEqual(P1.strategy(P2), 'D')

        P1.history = ['D']
        P2.history = ['C']
        random.seed(31)
        # With probability .05 will cooperate
        self.assertEqual(P1.strategy(P2), 'C')
        # But otherwise will defect
        self.assertEqual(P1.strategy(P2), 'D')
        self.assertEqual(P1.strategy(P2), 'D')
        self.assertEqual(P1.strategy(P2), 'D')

        P1.history = ['D']
        P2.history = ['D']
        random.seed(2)
        # With probability .05 will defect
        self.assertEqual(P1.strategy(P2), 'D')
        # But otherwise will defect
        self.assertEqual(P1.strategy(P2), 'C')
        self.assertEqual(P1.strategy(P2), 'C')
        self.assertEqual(P1.strategy(P2), 'C')

class TestZDExtort2(TestPlayer):

    name = "ZD-Extort-2"
    player = axelrod.ZDExtort2
    stochastic = True

    def test_four_vector(self):
        P1 = self.player()
        expected_dictionary = {('C', 'D'): 0.5, ('D', 'C'): 1./3, ('D', 'D'): 0., ('C', 'C'): 8./9}
        for key in sorted(expected_dictionary.keys()):
            self.assertAlmostEqual(P1._four_vector[key],
                    expected_dictionary[key])

    def test_strategy(self):
        # Testing the expected value is difficult here so these just ensure that
        # future changes that break these tests will be examined carefully.
        P1 = self.player()
        P2 = axelrod.Player()
        self.assertEqual(P1.strategy(P2), 'C')

        P1.history = ['C']
        P2.history = ['C']
        random.seed(2)
        self.assertEqual(P1.strategy(P2), 'D')
        self.assertEqual(P1.strategy(P2), 'D')
        self.assertEqual(P1.strategy(P2), 'C')
        self.assertEqual(P1.strategy(P2), 'C')
        P1.history = ['C']
        P2.history = ['D']
        self.assertEqual(P1.strategy(P2), 'C')
        self.assertEqual(P1.strategy(P2), 'C')
        self.assertEqual(P1.strategy(P2), 'C')
        self.assertEqual(P1.strategy(P2), 'C')
        P1.history = ['D']
        P2.history = ['C']
        self.assertEqual(P1.strategy(P2), 'C')
        self.assertEqual(P1.strategy(P2), 'C')
        self.assertEqual(P1.strategy(P2), 'C')
        self.assertEqual(P1.strategy(P2), 'C')
        P1.history = ['D']
        P2.history = ['D']
        self.assertEqual(P1.strategy(P2), 'D')
        self.assertEqual(P1.strategy(P2), 'D')
        self.assertEqual(P1.strategy(P2), 'D')
        self.assertEqual(P1.strategy(P2), 'D')

class TestZDGTFT2(TestPlayer):

    name = "ZD-GTFT-2"
    player = axelrod.ZDGTFT2
    stochastic = True

    def test_four_vector(self):
        P1 = self.player()
        expected_dictionary = {('C', 'D'): 1./8, ('D', 'C'): 1., ('D', 'D'): 0.25, ('C', 'C'): 1.}
        for key in sorted(expected_dictionary.keys()):
            self.assertAlmostEqual(P1._four_vector[key],
                    expected_dictionary[key])

    def test_strategy(self):
        # Testing the expected value is difficult here so these just ensure that
        # future changes that break these tests will be examined carefully.
        P1 = self.player()
        P2 = axelrod.Player()
        self.assertEqual(P1.strategy(P2), 'C')

        P1.history = ['C']
        P2.history = ['C']
        random.seed(2)
        self.assertEqual(P1.strategy(P2), 'C')
        self.assertEqual(P1.strategy(P2), 'C')
        self.assertEqual(P1.strategy(P2), 'C')
        self.assertEqual(P1.strategy(P2), 'C')
        P1.history = ['C']
        P2.history = ['D']
        self.assertEqual(P1.strategy(P2), 'D')
        self.assertEqual(P1.strategy(P2), 'D')
        self.assertEqual(P1.strategy(P2), 'D')
        self.assertEqual(P1.strategy(P2), 'D')
        P1.history = ['D']
        P2.history = ['C']
        self.assertEqual(P1.strategy(P2), 'D')
        self.assertEqual(P1.strategy(P2), 'D')
        self.assertEqual(P1.strategy(P2), 'D')
        self.assertEqual(P1.strategy(P2), 'D')
        P1.history = ['D']
        P2.history = ['D']
        self.assertEqual(P1.strategy(P2), 'C')
        self.assertEqual(P1.strategy(P2), 'C')
        self.assertEqual(P1.strategy(P2), 'C')
        self.assertEqual(P1.strategy(P2), 'C')
<commit_msg>Updated ZD tests, all working now!<commit_after>"""Test for the memoryone strategies."""

import random

import axelrod

from test_player import TestPlayer

class TestWinStayLostShift(TestPlayer):

    name = "Win-Stay Lose-Shift"
    player = axelrod.WinStayLoseShift

    def test_strategy(self):
        """Starts by cooperating"""
        P1 = self.player()
        P2 = axelrod.Player()
        self.assertEqual(P1.strategy(P2), 'C')

    def test_effect_of_strategy(self):
        """Check that switches if does not get best payoff."""
        P1 = self.player()
        P2 = axelrod.Player()
        P1.history = ['C']
        P2.history = ['C']
        self.assertEqual(P1.strategy(P2), 'C')
        P1.history = ['C']
        P2.history = ['D']
        self.assertEqual(P1.strategy(P2), 'D')
        P1.history = ['D']
        P2.history = ['C']
        self.assertEqual(P1.strategy(P2), 'D')
        P1.history = ['D']
        P2.history = ['D']
        self.assertEqual(P1.strategy(P2), 'C')

class TestGTFT(TestPlayer):

    name = "Generous Tit-For-Tat"
    player = axelrod.GTFT
    stochastic = True

    def test_strategy(self):
        P1 = self.player()
        P2 = axelrod.Player()
        self.assertEqual(P1.strategy(P2), 'C')

        P1.history = ['C']
        P2.history = ['C']
        random.seed(2)
        # With probability .05 will defect
        self.assertEqual(P1.strategy(P2), 'D')
        # But otherwise will cooperate
        self.assertEqual(P1.strategy(P2), 'C')
        self.assertEqual(P1.strategy(P2), 'C')
        self.assertEqual(P1.strategy(P2), 'C')

        P1.history = ['C']
        P2.history = ['D']
        random.seed(31)
        # With probability .05 will cooperate
        self.assertEqual(P1.strategy(P2), 'C')
        # But otherwise will defect
        self.assertEqual(P1.strategy(P2), 'D')
        self.assertEqual(P1.strategy(P2), 'D')
        self.assertEqual(P1.strategy(P2), 'D')

        P1.history = ['D']
        P2.history = ['C']
        random.seed(2)
        # With probability .05 will defect
        self.assertEqual(P1.strategy(P2), 'D')
        # But otherwise will cooperate
        self.assertEqual(P1.strategy(P2), 'C')
        self.assertEqual(P1.strategy(P2), 'C')
        self.assertEqual(P1.strategy(P2), 'C')

        P1.history = ['D']
        P2.history = ['D']
        random.seed(31)
        # With probability .05 will cooperate
        self.assertEqual(P1.strategy(P2), 'C')
        # But otherwise will defect
        self.assertEqual(P1.strategy(P2), 'D')
        self.assertEqual(P1.strategy(P2), 'D')
        self.assertEqual(P1.strategy(P2), 'D')

class TestStochasticCooperator(TestPlayer):

    name = "Stochastic Cooperator"
    player = axelrod.StochasticCooperator
    stochastic = True

    def test_strategy(self):
        P1 = self.player()
        P2 = axelrod.Player()
        self.assertEqual(P1.strategy(P2), 'C')

        P1.history = ['C']
        P2.history = ['C']
        random.seed(15)
        # With probability .065 will defect
        self.assertEqual(P1.strategy(P2), 'D')
        # But otherwise will cooperate
        self.assertEqual(P1.strategy(P2), 'C')
        self.assertEqual(P1.strategy(P2), 'C')
        self.assertEqual(P1.strategy(P2), 'C')

        P1.history = ['C']
        P2.history = ['D']
        random.seed(1)
        # With probability .229 will cooperate
        self.assertEqual(P1.strategy(P2), 'C')
        # But otherwise will defect
        self.assertEqual(P1.strategy(P2), 'D')
        self.assertEqual(P1.strategy(P2), 'D')
        self.assertEqual(P1.strategy(P2), 'D')

        P1.history = ['D']
        P2.history = ['C']
        random.seed(3)
        # With probability .266 will cooperate
        self.assertEqual(P1.strategy(P2), 'C')
        # But otherwise will defect
        self.assertEqual(P1.strategy(P2), 'D')
        self.assertEqual(P1.strategy(P2), 'D')
        self.assertEqual(P1.strategy(P2), 'D')

        P1.history = ['D']
        P2.history = ['D']
        random.seed(13)
        # With probability .42 will cooperate
        self.assertEqual(P1.strategy(P2), 'C')
        # But otherwise will defect
        self.assertEqual(P1.strategy(P2), 'D')
        self.assertEqual(P1.strategy(P2), 'D')
        self.assertEqual(P1.strategy(P2), 'D')

class TestStochasticWSLS(TestPlayer):

    name = "Stochastic WSLS"
    player = axelrod.StochasticWSLS
    stochastic = True

    def test_strategy(self):
        P1 = self.player()
        P2 = axelrod.Player()
        self.assertEqual(P1.strategy(P2), 'C')

        P1.history = ['C']
        P2.history = ['C']
        random.seed(2)
        # With probability .05 will defect
        self.assertEqual(P1.strategy(P2), 'D')
        # But otherwise will cooperate
        self.assertEqual(P1.strategy(P2), 'C')
        self.assertEqual(P1.strategy(P2), 'C')
        self.assertEqual(P1.strategy(P2), 'C')

        P1.history = ['C']
        P2.history = ['D']
        random.seed(31)
        # With probability .05 will cooperate
        self.assertEqual(P1.strategy(P2), 'C')
        # But otherwise will defect
        self.assertEqual(P1.strategy(P2), 'D')
        self.assertEqual(P1.strategy(P2), 'D')
        self.assertEqual(P1.strategy(P2), 'D')

        P1.history = ['D']
        P2.history = ['C']
        random.seed(31)
        # With probability .05 will cooperate
        self.assertEqual(P1.strategy(P2), 'C')
        # But otherwise will defect
        self.assertEqual(P1.strategy(P2), 'D')
        self.assertEqual(P1.strategy(P2), 'D')
        self.assertEqual(P1.strategy(P2), 'D')

        P1.history = ['D']
        P2.history = ['D']
        random.seed(2)
        # With probability .05 will defect
        self.assertEqual(P1.strategy(P2), 'D')
        # But otherwise will defect
        self.assertEqual(P1.strategy(P2), 'C')
        self.assertEqual(P1.strategy(P2), 'C')
        self.assertEqual(P1.strategy(P2), 'C')

class TestZDExtort2(TestPlayer):

    name = "ZD-Extort-2"
    player = axelrod.ZDExtort2
    stochastic = True

    def test_four_vector(self):
        P1 = self.player()
        expected_dictionary = {('C', 'D'): 0.5, ('D', 'C'): 1./3, ('D', 'D'): 0., ('C', 'C'): 8./9}
        for key in sorted(expected_dictionary.keys()):
            self.assertAlmostEqual(P1._four_vector[key],
                    expected_dictionary[key])

    def test_strategy(self):
        # Testing the expected value is difficult here so these just ensure that
        # future changes that break these tests will be examined carefully.
        P1 = self.player()
        P2 = axelrod.Player()
        self.assertEqual(P1.strategy(P2), 'C')

        P1.history = ['C']
        P2.history = ['C']
        random.seed(2)
        self.assertEqual(P1.strategy(P2), 'D')
        self.assertEqual(P1.strategy(P2), 'D')
        self.assertEqual(P1.strategy(P2), 'C')
        self.assertEqual(P1.strategy(P2), 'C')
        P1.history = ['C']
        P2.history = ['D']
        self.assertEqual(P1.strategy(P2), 'D')
        self.assertEqual(P1.strategy(P2), 'D')
        self.assertEqual(P1.strategy(P2), 'D')
        self.assertEqual(P1.strategy(P2), 'C')
        P1.history = ['D']
        P2.history = ['C']
        self.assertEqual(P1.strategy(P2), 'D')
        self.assertEqual(P1.strategy(P2), 'D')
        self.assertEqual(P1.strategy(P2), 'D')
        self.assertEqual(P1.strategy(P2), 'C')
        P1.history = ['D']
        P2.history = ['D']
        self.assertEqual(P1.strategy(P2), 'D')
        self.assertEqual(P1.strategy(P2), 'D')
        self.assertEqual(P1.strategy(P2), 'D')
        self.assertEqual(P1.strategy(P2), 'D')

class TestZDGTFT2(TestPlayer):

    name = "ZD-GTFT-2"
    player = axelrod.ZDGTFT2
    stochastic = True

    def test_four_vector(self):
        P1 = self.player()
        expected_dictionary = {('C', 'D'): 1./8, ('D', 'C'): 1., ('D', 'D'): 0.25, ('C', 'C'): 1.}
        for key in sorted(expected_dictionary.keys()):
            self.assertAlmostEqual(P1._four_vector[key],
                    expected_dictionary[key])

    def test_strategy(self):
        # Testing the expected value is difficult here so these just ensure that
        # future changes that break these tests will be examined carefully.
        P1 = self.player()
        P2 = axelrod.Player()
        self.assertEqual(P1.strategy(P2), 'C')

        P1.history = ['C']
        P2.history = ['C']
        random.seed(2)
        self.assertEqual(P1.strategy(P2), 'C')
        self.assertEqual(P1.strategy(P2), 'C')
        self.assertEqual(P1.strategy(P2), 'C')
        self.assertEqual(P1.strategy(P2), 'C')
        P1.history = ['C']
        P2.history = ['D']
        self.assertEqual(P1.strategy(P2), 'D')
        self.assertEqual(P1.strategy(P2), 'D')
        self.assertEqual(P1.strategy(P2), 'D')
        self.assertEqual(P1.strategy(P2), 'D')
        P1.history = ['D']
        P2.history = ['C']
        self.assertEqual(P1.strategy(P2), 'C')
        self.assertEqual(P1.strategy(P2), 'C')
        self.assertEqual(P1.strategy(P2), 'C')
        self.assertEqual(P1.strategy(P2), 'C')
        P1.history = ['D']
        P2.history = ['D']
        self.assertEqual(P1.strategy(P2), 'D')
        self.assertEqual(P1.strategy(P2), 'D')
        self.assertEqual(P1.strategy(P2), 'D')
        self.assertEqual(P1.strategy(P2), 'D')
<|endoftext|>


<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright 2010 Asidev s.r.l.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""

from . interface import BaseInterface

class EnvironmentInterface(BaseInterface):
    commands = ['list', 'create', 'delete', 'rename']
    name = 'envs'
    root_url = '/environments'

    def create(self, name, venv_name=None):
        data = dict(name=name)
        if venv_name:
            data['venv_name'] = venv_name

        self.api.execute_sync_task('post', self.root_url, data=data)

    def rename(self, name, newname):
        self.api.put(self.get_url(name), {'name': newname})
<commit_msg>Added info command to environment<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright 2010 Asidev s.r.l.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""

from . interface import BaseInterface

class EnvironmentInterface(BaseInterface):
    commands = ['list', 'create', 'delete', 'rename', 'info']
    name = 'envs'
    root_url = '/environments'

    def create(self, name, venv_name=None):
        data = dict(name=name)
        if venv_name:
            data['venv_name'] = venv_name

        self.api.execute_sync_task('post', self.root_url, data=data)

    def rename(self, name, newname):
        self.api.put(self.get_url(name), {'name': newname})
<|endoftext|>


<commit_before>########
# Copyright (c) 2015 GigaSpaces Technologies Ltd. All rights reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#        http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
#    * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#    * See the License for the specific language governing permissions and
#    * limitations under the License.

# Built-in Imports
import requests
from requests import Request,Session,Response
import json
import constants
import sys
import os
from resourcegroup import *
import auth
import utils
from resourcegroup import *
from cloudify.exceptions import NonRecoverableError
from cloudify import ctx
from cloudify.decorators import operation

@operation
def creation_validation(**_):
    for property_key in constants.STORAGE_ACCOUNT_REQUIRED_PROPERTIES:
        _validate_node_properties(property_key, ctx.node.properties)

    storage_account = _get_storage_account_name()

    if ctx.node.properties['use_external_resource'] and not storage_account:
        raise NonRecoverableError(
        'External resource, but the supplied '
        'storage account does not exist in the account.')
    if not ctx.node.properties['use_external_resource'] and storage_account:
        raise NonRecoverableError(
        'Not external resource, but the supplied '
        'storage account group exists in the account.')

@operation
def create_storage_account(**_):
    if ctx.node.properties['use_external_resource']
        if not storage_account_exists:
            raise NonRecoverableError(
            'External resource, but the supplied '
            'storage account does not exist in the Azure account.')
            sys.exit(1)
        else
            ctx.instance.runtime_properties[constants.STORAGE_ACCOUNT_KEY]=ctx.node.properties['existing_storage_account_name']
            return
    else
            location = ctx.node.properties['location']
            subscription_id = ctx.node.properties['subscription_id']
            RANDOM_SUFFIX_VALUE = utils.random_suffix_generator()
            storage_account_name = contants.STORAGE_ACCOUNT_PREFIX+RANDOM_SUFFIX_VALUE
            resource_group_name=create_resource_group.resource_group_name
            credentials='Bearer '+auth.get_token_from_client_credentials()

            headers = {"Content-Type": "application/json", "Authorization": credentials}

            ctx.logger.info("Checking availability of storage account: " + storage_account_name)
            if 1:
                try:
                    ctx.logger.info("Creating new storage account: " + storage_account_name)
                    storage_account_url= constants.azure_url+'/subscriptions/'+subscription_id+'/resourceGroups/'+resource_group_name+'/providers/Microsoft.Storage/storageAccounts/'+storage_account_name+'?api-version='+constants.api_version
                    storage_account_params=json.dumps({"properties": {"accountType": constants.storage_account_type,}, "location": location})
                    response_sa = requests.put(url=storage_account_url, data=storage_account_params, headers=headers)
                    print response_sa.text
                    ctx.instance.runtime_properties['storage_account']=storage_account_name
                except:
                    ctx.logger.info("Storage Account " + storage_account_name + "could not be created.")
                    sys.exit(1)
            else:
                ctx.logger.info("Storage Account " + storage_account_name + "has already been provisioned by another user.")

@operation
def delete_storage_account(**_):
    resource_group_name = resourcegroup.resource_group_name
    subscription_id = ctx.node.properties['subscription_id']
    credentials='Bearer '+auth.get_token_from_client_credentials()
    headers = {"Content-Type": "application/json", "Authorization": credentials}

    ctx.logger.info("Deleting Storage Account"+storage_account_name)
    if 1:
        try:
            storage_account_url=constants.azure_url+'/subscriptions/'+subscription_id+'/resourceGroups/'+resource_group_name+'/providers/Microsoft.Storage/storageAccounts/'+storage_account_name+'?api-version='+constants.api_version
            response_sa = requests.delete(url=storage_account_url,headers=headers)
            print response_sa.text

        except:
            ctx.logger.info("Storage Account " + storage_account_name + " could not be deleted.")
            sys.exit(1)
    else:
        ctx.logger.info("Storage Account " + storage_account_name + " does not exist.")

@operation
def set_dependent_resources_names(azure_config,**kwargs):
    ctx.source.instance.runtime_properties['resource_group'] = ctx.target.instance.runtime_properties['resource_group']

def _validate_node_properties(key, ctx_node_properties):
    if key not in ctx_node_properties:
        raise NonRecoverableError('{0} is a required input. Unable to create.'.format(key))

def _get_storage_account_name():
    storage_account_name= ctx.node.properties['existing_storage_account_name']
    resource_group_name= resourcegroup.resource_group_name
    subscription_id=ctx.node.properties['subscription_id']
    credentials=auth.get_token_from_client_credentials()
    url = constants.azure_url+'/subscriptions/'+subscription_id+'/resourceGroups/'+resource_group_name+'/providers/Microsoft.Storage/storageAccounts?api-version='+constants.api_version
    headers = {"Content-Type": "application/json", "Authorization": credentials}
    response_list = requests.get(url, headers = headers)
    if storage_account_name in response_list.text:
        return True
    else:
        ctx.logger.info("Storage account %s does not exist"+ storage_account_name)
        return False

<commit_msg>Update storageaccount.py<commit_after>########
# Copyright (c) 2015 GigaSpaces Technologies Ltd. All rights reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#        http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
#    * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#    * See the License for the specific language governing permissions and
#    * limitations under the License.

# Built-in Imports
import requests
from requests import Request,Session,Response
import json
import constants
import sys
import os
from resourcegroup import *
import auth
import utils
from resourcegroup import *
from cloudify.exceptions import NonRecoverableError
from cloudify import ctx
from cloudify.decorators import operation

@operation
def creation_validation(**_):
    for property_key in constants.STORAGE_ACCOUNT_REQUIRED_PROPERTIES:
        _validate_node_properties(property_key, ctx.node.properties)

    storage_account_exists = _get_storage_account_name()

    if ctx.node.properties['use_external_resource'] and not storage_account_exists:
        raise NonRecoverableError(
        'External resource, but the supplied '
        'storage account does not exist in the account.')
    if not ctx.node.properties['use_external_resource'] and storage_account_exists:
        raise NonRecoverableError(
        'Not external resource, but the supplied '
        'storage account group exists in the account.')

@operation
def create_storage_account(**_):
    if ctx.node.properties['use_external_resource']
        if not storage_account_exists:
            raise NonRecoverableError(
            'External resource, but the supplied '
            'storage account does not exist in the Azure account.')
            sys.exit(1)
        else
            ctx.instance.runtime_properties[constants.STORAGE_ACCOUNT_KEY]=ctx.node.properties['existing_storage_account_name']
            return
    else
            location = ctx.node.properties['location']
            subscription_id = ctx.node.properties['subscription_id']
            RANDOM_SUFFIX_VALUE = utils.random_suffix_generator()
            storage_account_name = contants.STORAGE_ACCOUNT_PREFIX+RANDOM_SUFFIX_VALUE
            resource_group_name=create_resource_group.resource_group_name
            credentials='Bearer '+auth.get_token_from_client_credentials()

            headers = {"Content-Type": "application/json", "Authorization": credentials}

            ctx.logger.info("Checking availability of storage account: " + storage_account_name)
            if 1:
                try:
                    ctx.logger.info("Creating new storage account: " + storage_account_name)
                    storage_account_url= constants.azure_url+'/subscriptions/'+subscription_id+'/resourceGroups/'+resource_group_name+'/providers/Microsoft.Storage/storageAccounts/'+storage_account_name+'?api-version='+constants.api_version
                    storage_account_params=json.dumps({"properties": {"accountType": constants.storage_account_type,}, "location": location})
                    response_sa = requests.put(url=storage_account_url, data=storage_account_params, headers=headers)
                    print response_sa.text
                    ctx.instance.runtime_properties['storage_account']=storage_account_name
                except:
                    ctx.logger.info("Storage Account " + storage_account_name + "could not be created.")
                    sys.exit(1)
            else:
                ctx.logger.info("Storage Account " + storage_account_name + "has already been provisioned by another user.")

@operation
def delete_storage_account(**_):
    resource_group_name = resourcegroup.resource_group_name
    subscription_id = ctx.node.properties['subscription_id']
    credentials='Bearer '+auth.get_token_from_client_credentials()
    headers = {"Content-Type": "application/json", "Authorization": credentials}

    ctx.logger.info("Deleting Storage Account"+storage_account_name)
    if 1:
        try:
            storage_account_url=constants.azure_url+'/subscriptions/'+subscription_id+'/resourceGroups/'+resource_group_name+'/providers/Microsoft.Storage/storageAccounts/'+storage_account_name+'?api-version='+constants.api_version
            response_sa = requests.delete(url=storage_account_url,headers=headers)
            print response_sa.text

        except:
            ctx.logger.info("Storage Account " + storage_account_name + " could not be deleted.")
            sys.exit(1)
    else:
        ctx.logger.info("Storage Account " + storage_account_name + " does not exist.")

@operation
def set_dependent_resources_names(azure_config,**kwargs):
    ctx.source.instance.runtime_properties['resource_group'] = ctx.target.instance.runtime_properties['resource_group']

def _validate_node_properties(key, ctx_node_properties):
    if key not in ctx_node_properties:
        raise NonRecoverableError('{0} is a required input. Unable to create.'.format(key))

def _get_storage_account_name():
    storage_account_name= ctx.node.properties['existing_storage_account_name']
    resource_group_name= resourcegroup.resource_group_name
    subscription_id=ctx.node.properties['subscription_id']
    credentials=auth.get_token_from_client_credentials()
    url = constants.azure_url+'/subscriptions/'+subscription_id+'/resourceGroups/'+resource_group_name+'/providers/Microsoft.Storage/storageAccounts?api-version='+constants.api_version
    headers = {"Content-Type": "application/json", "Authorization": credentials}
    response_list = requests.get(url, headers = headers)
    if storage_account_name in response_list.text:
        return True
    else:
        ctx.logger.info("Storage account %s does not exist"+ storage_account_name)
        return False

<|endoftext|>


<commit_before>########
# Copyright (c) 2015 GigaSpaces Technologies Ltd. All rights reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#        http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
#    * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#    * See the License for the specific language governing permissions and
#    * limitations under the License.

# Built-in Imports
import requests
from requests import Request,Session,Response
import json
import constants
import sys
import os
from resourcegroup import *
import auth
import utils
from resourcegroup import *
from cloudify.exceptions import NonRecoverableError
from cloudify import ctx
from cloudify.decorators import operation

RANDOM_SUFFIX_VALUE = utils.random_suffix_generator()
storage_account_name = ctx.node.properties['storage_account_name']+RANDOM_SUFFIX_VALUE

@operation
def creation_validation(**_):
    for property_key in constants.STORAGE_ACCOUNT_REQUIRED_PROPERTIES:
        _validate_node_properties(property_key, ctx.node.properties)

    storage_account = _get_storage_account_name(
        utils.get_storage_account_name())

    if ctx.node.properties['use_external_resource'] and not storage_account:
        raise NonRecoverableError(
        'External resource, but the supplied '
        'storage account does not exist in the account.')
    if not ctx.node.properties['use_external_resource'] and storage_account:
        raise NonRecoverableError(
        'Not external resource, but the supplied '
        'storage account group exists in the account.')

@operation
def create_storage_account(**_):
    if ctx.node.properties['use_external_resource']
        if not resource_group:
            raise NonRecoverableError(
            'External resource, but the supplied '
            'storage account does not exist in the Azure account.')
            sys.exit(1)
        else
            ctx.instance.runtime_properties[constants.STORAGE_ACCOUNT_KEY]=ctx.node.properties['existing_storage_account_name']
            return
    else
            location = ctx.node.properties['location']
            subscription_id = ctx.node.properties['subscription_id']
            resource_group_name=create_resource_group.resource_group_name
            credentials='Bearer '+auth.get_token_from_client_credentials()

            headers = {"Content-Type": "application/json", "Authorization": credentials}

            ctx.logger.info("Checking availability of storage account: " + storage_account_name)
            if 1:
                try:
                    ctx.logger.info("Creating new storage account: " + storage_account_name)
                    storage_account_url= constants.azure_url+'/subscriptions/'+subscription_id+'/resourceGroups/'+resource_group_name+'/providers/Microsoft.Storage/storageAccounts/'+storage_account_name+'?api-version='+constants.api_version
                    storage_account_params=json.dumps({"properties": {"accountType": constants.storage_account_type,}, "location": location})
                    response_sa = requests.put(url=storage_account_url, data=storage_account_params, headers=headers)
                    print response_sa.text
                    ctx.instance.runtime_properties['storage_account']=storage_account_name
                except:
                    ctx.logger.info("Storage Account " + storage_account_name + "could not be created.")
                    sys.exit(1)
            else:
                ctx.logger.info("Storage Account " + storage_account_name + "has already been provisioned by another user.")

@operation
def delete_storage_account(**_):
    resource_group_name = resourcegroup.resource_group_name
    subscription_id = ctx.node.properties['subscription_id']
    credentials='Bearer '+auth.get_token_from_client_credentials()
    headers = {"Content-Type": "application/json", "Authorization": credentials}

    ctx.logger.info("Deleting Storage Account"+storage_account_name)
    if 1:
        try:
            storage_account_url=constants.azure_url+'/subscriptions/'+subscription_id+'/resourceGroups/'+resource_group_name+'/providers/Microsoft.Storage/storageAccounts/'+storage_account_name+'?api-version='+constants.api_version
            response_sa = requests.delete(url=storage_account_url,headers=headers)
            print response_sa.text

        except:
            ctx.logger.info("Storage Account " + storage_account_name + " could not be deleted.")
            sys.exit(1)
    else:
        ctx.logger.info("Storage Account " + storage_account_name + " does not exist.")

def _validate_node_properties(key, ctx_node_properties):
    if key not in ctx_node_properties:
        raise NonRecoverableError('{0} is a required input. Unable to create.'.format(key))

def _get_storage_account_name(storage_account_name):
    resource_group= ctx.node.properties['exsisting_resource_group_name']
    subscription_id=ctx.node.properties['subscription_id']
    url = constants.azure_url+'/subscriptions/'+subscription_id+'/resourceGroups/'+resource_group+'/providers/Microsoft.Storage/storageAccounts?api-version='+constants.api_version
    headers = {"Content-Type": "application/json", "Authorization": credentials}
    response_list = requests.get(url, headers = headers).json()
    print response_list['value']['name']
<commit_msg>Update storageaccount.py<commit_after>########
# Copyright (c) 2015 GigaSpaces Technologies Ltd. All rights reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#        http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
#    * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#    * See the License for the specific language governing permissions and
#    * limitations under the License.

# Built-in Imports
import requests
from requests import Request,Session,Response
import json
import constants
import sys
import os
from resourcegroup import *
import auth
import utils
from resourcegroup import *
from cloudify.exceptions import NonRecoverableError
from cloudify import ctx
from cloudify.decorators import operation

RANDOM_SUFFIX_VALUE = utils.random_suffix_generator()
storage_account_name = STORAGE_ACCOUNT_PREFIX+RANDOM_SUFFIX_VALUE

@operation
def creation_validation(**_):
    for property_key in constants.STORAGE_ACCOUNT_REQUIRED_PROPERTIES:
        _validate_node_properties(property_key, ctx.node.properties)

    storage_account = _get_storage_account_name(
        utils.get_storage_account_name())

    if ctx.node.properties['use_external_resource'] and not storage_account:
        raise NonRecoverableError(
        'External resource, but the supplied '
        'storage account does not exist in the account.')
    if not ctx.node.properties['use_external_resource'] and storage_account:
        raise NonRecoverableError(
        'Not external resource, but the supplied '
        'storage account group exists in the account.')

@operation
def create_storage_account(**_):
    if ctx.node.properties['use_external_resource']
        if not resource_group:
            raise NonRecoverableError(
            'External resource, but the supplied '
            'storage account does not exist in the Azure account.')
            sys.exit(1)
        else
            ctx.instance.runtime_properties[constants.STORAGE_ACCOUNT_KEY]=ctx.node.properties['existing_storage_account_name']
            return
    else
            location = ctx.node.properties['location']
            subscription_id = ctx.node.properties['subscription_id']
            resource_group_name=create_resource_group.resource_group_name
            credentials='Bearer '+auth.get_token_from_client_credentials()

            headers = {"Content-Type": "application/json", "Authorization": credentials}

            ctx.logger.info("Checking availability of storage account: " + storage_account_name)
            if 1:
                try:
                    ctx.logger.info("Creating new storage account: " + storage_account_name)
                    storage_account_url= constants.azure_url+'/subscriptions/'+subscription_id+'/resourceGroups/'+resource_group_name+'/providers/Microsoft.Storage/storageAccounts/'+storage_account_name+'?api-version='+constants.api_version
                    storage_account_params=json.dumps({"properties": {"accountType": constants.storage_account_type,}, "location": location})
                    response_sa = requests.put(url=storage_account_url, data=storage_account_params, headers=headers)
                    print response_sa.text
                    ctx.instance.runtime_properties['storage_account']=storage_account_name
                except:
                    ctx.logger.info("Storage Account " + storage_account_name + "could not be created.")
                    sys.exit(1)
            else:
                ctx.logger.info("Storage Account " + storage_account_name + "has already been provisioned by another user.")

@operation
def delete_storage_account(**_):
    resource_group_name = resourcegroup.resource_group_name
    subscription_id = ctx.node.properties['subscription_id']
    credentials='Bearer '+auth.get_token_from_client_credentials()
    headers = {"Content-Type": "application/json", "Authorization": credentials}

    ctx.logger.info("Deleting Storage Account"+storage_account_name)
    if 1:
        try:
            storage_account_url=constants.azure_url+'/subscriptions/'+subscription_id+'/resourceGroups/'+resource_group_name+'/providers/Microsoft.Storage/storageAccounts/'+storage_account_name+'?api-version='+constants.api_version
            response_sa = requests.delete(url=storage_account_url,headers=headers)
            print response_sa.text

        except:
            ctx.logger.info("Storage Account " + storage_account_name + " could not be deleted.")
            sys.exit(1)
    else:
        ctx.logger.info("Storage Account " + storage_account_name + " does not exist.")

def _validate_node_properties(key, ctx_node_properties):
    if key not in ctx_node_properties:
        raise NonRecoverableError('{0} is a required input. Unable to create.'.format(key))

def _get_storage_account_name(storage_account_name):
    resource_group= ctx.node.properties['exsisting_resource_group_name']
    subscription_id=ctx.node.properties['subscription_id']
    url = constants.azure_url+'/subscriptions/'+subscription_id+'/resourceGroups/'+resource_group+'/providers/Microsoft.Storage/storageAccounts?api-version='+constants.api_version
    headers = {"Content-Type": "application/json", "Authorization": credentials}
    response_list = requests.get(url, headers = headers).json()
    print response_list['value']['name']
<|endoftext|>