Example #1
0
def user_group_filter(db_resource, user):
    filtered_instances = []
    for instance in db_resource:
        if not has_permission(user, instance.userid.upper()):
            continue
        else:
            filtered_instances.append(instance)
    return filtered_instances
Example #2
0
    def get_object(self, queryset=None):
        try:
            if session_is_okay(self.request.session, "single_instance"):
                self.instance_service.update_single_instance(self.kwargs['pk'])
        except Exception as e:
            self.logger.exception(e)

        obj = super(generic.DetailView, self).get_object(queryset)

        if has_permission(self.request.user, obj.userid):
            return obj
        else:
            raise PermissionDenied
Example #3
0
	def get_data(self, context):
		logger = logging.getLogger(__name__)
		data = [{
				'value': 0,
				'color': '#F7464A',
				'highlight': "#FF5A5E",
				'label': "Stopped"
			},
			{
				'value': 0,
				'color': "#46BFBD",
				'highlight': "#5AD3D1",
				'label': "Running"
			},
			{
				'value': 0,
				'color': "#FDB45C",
				'highlight': "#FFC870",
				'label': "Transitioning/Terminating"
			}]

		cnt_stopped = 0
		cnt_running = 0
		cnt_other = 0

		for inst in Instance.objects.all().exclude(userid='').order_by('userid'):
			# logger.debug('prev owner: %s, inst owner: %s, skip: %s', prev_owner, inst.userid, str(skip_owner))
			# group lookup for owners is expensive so it's a flag
			user = self.request.user  # user accessing functionality
			owner = inst.userid  # instance owner

			if not has_permission(user, owner):
				continue

			# following conditions are true: caller and owner share a group, and skip is false
			if inst.state == 'running':
				cnt_running += 1
			elif inst.state == 'stopped':
				cnt_stopped += 1
			else:
				cnt_other += 1

		data[0]['value'] = cnt_stopped
		data[1]['value'] = cnt_running
		data[2]['value'] = cnt_other

		return data
Example #4
0
    def get_object(self, queryset=None):

        obj = Cluster.objects.get(cluster_id=self.kwargs['pk'])

        if has_permission(self.request.user, obj.userid):
            # Create the custom URL at runtime. To do this, setattr() is needed to add the custom_url to the object.
            custom_url = obj.software_config.custom_url_format.strip()
            if custom_url is '' or custom_url is None or '{{{ URL }}}' not in custom_url:
                if obj.dns_url is '' or obj.dns_url is None:
                    setattr(obj, 'custom_url', obj.master_ip)
                else:
                    setattr(obj, 'custom_url', obj.dns_url)
            else:
                if obj.dns_url is '' or obj.dns_url is None:
                    setattr(obj, 'custom_url',
                            custom_url.replace('{{{ URL }}}', obj.master_ip))
                else:
                    setattr(obj, 'custom_url',
                            custom_url.replace('{{{ URL }}}', obj.dns_url))
            return obj
        else:
            raise PermissionDenied
Example #5
0
    def get_data(self, context):
        log = self.logger
        action = self.kwargs['action']
        instanceid = self.kwargs['instanceid']

        # make sure user owns this instance

        inst = get_object_or_404(Instance, instance_id=instanceid)

        is_authorized = has_permission(self.request.user, inst.userid)

        if not is_authorized:
            return {'action': 'invalid', 'status': 'unauthorized'}

        conn = boto3.resource('ec2', region_name=AWS_REGION)
        botoinstance = conn.Instance(id=instanceid)
        # ====================================
        if action == 'start':
            log.info("Entering " + str(action))
            if botoinstance.state['Name'] != 'stopped':
                if inst.state == "stopped":
                    inst.state = botoinstance.state['Name']
                    inst.start_at = datetime.now(timezone(TIME_ZONE))
                    inst.save()
                return {
                    'action': 'invalid',
                    'status': 'failed',
                    'exception': 'Instance started already.'
                }
            try:
                botoinstance.start()
                bill = BillingData()
                bill.ongoing = True
                bill.instance_type = inst.instance_type
                bill.instance_name = inst.instance_id
                if inst.current_bill is not None:
                    bill.charge_name = inst.current_bill.charge_name
                else:
                    bill.charge_name = DEFAULT_CHARGE_CODE

                bill.user = User.objects.get(username=inst.userid)
                bill.price = getPrice(
                    inst.instance_type) * (1.0 - AWS_DISCOUNT)
                bill.start_time = datetime.now(timezone('UTC'))
                bill.save()
                inst.current_bill = bill
                inst.state = 'starting'
                inst.start_at = datetime.now(timezone(TIME_ZONE))
                inst.save()
                log.info("Exiting " + str(action))
            except Exception as e:
                log.exception(e)
                return {
                    'action': 'invalid',
                    'status': 'failed',
                    'exception': str(e)
                }
        # ====================================
        elif action == 'stop':
            log.info("Entering " + str(action))

            if botoinstance.state['Name'] != 'running':
                if inst.state == "running":
                    inst.state = botoinstance.state['Name']
                    inst.start_at = datetime.now(timezone(TIME_ZONE))
                    inst.save()
                return {
                    'action': 'invalid',
                    'status': 'failed',
                    'exception': "Instance is not running."
                }
            try:
                botoinstance.stop()
                bill = inst.current_bill
                if bill is not None:
                    bill.ongoing = False
                    bill.end_time = datetime.now(timezone('UTC'))
                    bill.save()
                inst.state = 'stopping'
                inst.stop_at = datetime.now(timezone(TIME_ZONE))
                inst.save()
                log.info("Exiting " + str(action))
            except Exception as e:
                log.exception(e)
                return {
                    'action': 'invalid',
                    'status': 'failed',
                    'exception': str(e)
                }
        # ====================================
        elif action == 'restart':
            log.info("Entering " + str(action))
            if botoinstance.state['Name'] != 'running':
                return {
                    'action': 'invalid',
                    'status': 'failed',
                    'exception': 'Instance is not running.'
                }
            try:
                botoinstance.reboot()
                inst.stop_at = datetime.now(timezone(TIME_ZONE))
                inst.start_at = datetime.now(timezone(TIME_ZONE))
                inst.state = 'restarting'
                inst.save()
                log.info("Exiting " + str(action))
            except Exception as e:
                log.exception(e)
                return {
                    'action': 'invalid',
                    'status': 'failed',
                    'exception': str(e)
                }
        # ====================================
        elif action == 'terminate':
            log.info("Entering " + str(action))
            if botoinstance.state['Name'].startswith('termin'):
                return {
                    'action': 'invalid',
                    'status': 'failed',
                    'exception': 'Instance already terminated.'
                }
            try:
                # kill the Cloudformation stack
                stack = inst.stack_id
                if stack is not None:
                    client = boto3.client("cloudformation",
                                          region_name=AWS_REGION)
                    ec2_client = boto3.client('ec2', region_name=AWS_REGION)
                    client.delete_stack(StackName=stack.stack_id)
                    stack.delete()
                    state = ''
                    while state != 'shutting-down':
                        state = ec2_client.describe_instances(
                            InstanceIds=[inst.instance_id]
                        )['Reservations'][0]['Instances'][0]['State']['Name']
                        time.sleep(3)
                else:
                    return {
                        'action':
                        'invalid',
                        'status':
                        'failed',
                        'exception':
                        'Instance has no stack and will not be terminated.'
                    }
                inst.stack_id = None
                bill = inst.current_bill
                if bill is not None:
                    bill.ongoing = False
                    bill.end_time = datetime.now(timezone('UTC'))
                    bill.save()
                deleteDnsEntry(inst.instance_id, inst.private_ip)
                inst.state = 'terminating'
                inst.progress_integer = 100
                inst.progress_status = 'done'
                inst.archived = True
                inst.stop_at = datetime.now(timezone(TIME_ZONE))
                inst.save()
                log.info("Exiting " + str(action))
            except Exception as e:
                log.exception(e)
                return {
                    'action': 'invalid',
                    'status': 'failed',
                    'exception': str(e)
                }
        # ====================================
        elif action == 'archive':
            log.info("Entering " + str(action))
            try:
                # Check for CF
                stack = inst.stack_id
                if stack:
                    client = boto3.client("cloudformation",
                                          region_name=AWS_REGION)
                    client.delete_stack(StackName=stack.stack_id)
                    stack.delete()
                inst.stack_id = None
                inst.archived = True
                inst.stop_at = datetime.now(timezone(TIME_ZONE))
                deleteDnsEntry(inst.instance_id, inst.private_ip)

                bill = inst.current_bill
                if bill:
                    bill.ongoing = False
                    bill.end_time = datetime.now(timezone('UTC'))
                    bill.save()
                inst.save()
                log.info("Exiting " + str(action))
            except Exception as e:
                log.exception(e)
                return {
                    'action': 'invalid',
                    'status': 'failed',
                    'exception': str(e)
                }
        # ====================================
        elif action == 'fakeok':
            # here for UI testing
            pass
        # ====================================
        else:
            log.error("Invalid verb passed to changeInstanceState")
            return {
                'action': 'invalid',
                'status': 'failed',
                'exception': "Invalid verb passed to changeInstanceState"
            }

        # add a short delay in return to try to address non-changing ui
        time.sleep(2)
        return {'action': action, 'status': 'ok'}
Example #6
0
    def get_data(self, context):
        logger = self.logger
        curtime = datetime.now(timezone('EST'))
        data = self.request.GET.dict()
        est = timezone('US/Eastern')
        begin_date = datetime.strptime(data['start_date'], '%m/%d/%Y')
        begin_date = est.localize(begin_date)
        end_date = datetime.strptime(data['end_date'], '%m/%d/%Y')
        end_date = est.localize(end_date)
        end_date += timedelta(days=1)

        query_user = data['user']
        query_group = data['group']

        if end_date > curtime:
            end_date = curtime

        if begin_date > end_date:
            begin_date = end_date
        # now get latest from the db
        try:
            instlist = {}
            bill_data = BillingData.objects.all()

            idata = []
            for bill in bill_data:
                # return instances of all members of the same group
                try:
                    instance_userid = bill.user.username

                    if not has_permission(self.request.user, instance_userid):
                        continue

                    if query_user != 'All Users' and instance_userid != query_user:
                        continue

                    if query_group != 'All Groups':
                        # If the user does not belong to the group that the query is talking about it should continue
                        if len(set(bill.user.groups.filter(
                                name=query_group))) == 0:
                            continue

                    hours = 1

                    if bill.end_time is not None and begin_date > bill.end_time:
                        continue
                    if end_date < bill.start_time:
                        continue

                    begin = begin_date

                    if bill.start_time > begin:
                        begin = bill.start_time

                    end = end_date
                    if not bill.ongoing and bill.end_time < end:
                        end = bill.end_time

                    td = end - begin
                    hours += td.days * 24 + td.seconds // 3600

                    price = bill.price * hours

                    if bill.instance_name in instlist:
                        inst = instlist[bill.instance_name]
                        inst['price'] += float(price)
                        inst['hours'] += hours
                        if bill.ongoing:
                            inst['active'] = True
                    else:
                        inst = {
                            'active': bill.ongoing,
                            'type': bill.instance_type,
                            'id': bill.instance_name,
                            'code': bill.charge_name,
                            'user':
                            bill.user.first_name + " " + bill.user.last_name,
                            'price': float(price),
                            'hours': hours
                        }
                        instlist[bill.instance_name] = inst

                except User.DoesNotExist:
                    logger.warn("user %s not in database.", bill.user.username)

            for k in instlist:
                idata.append(instlist[k])

        except Instance.DoesNotExist:
            self.update_instances()
            idata = []

        return idata