示例#1
0
def test_identity(mocker):
    request = mock.Mock()
    request.headers = {
        "X-RH-IDENTITY":
        "eyJpZGVudGl0eSI6IHsiYWNjb3VudF9udW1iZXIiOiAiMDAwMDAwMSIsICJ0eXB"
        "lIjogIlVzZXIiLCAiaW50ZXJuYWwiOiB7Im9yZ19pZCI6ICIwMDAwMDEifX19Cg=="
    }
    expected_result = {
        'identity': {
            'account_number': '0000001',
            'type': 'User',
            'internal': {
                'org_id': '000001'
            }
        }
    }
    result = utils.identity(request)
    assert expected_result == result

    with app.app_context():
        empty_header_request = mock.Mock()
        empty_header_request.headers = {}
        mocker.patch('ros.lib.utils.abort')
        utils.identity(empty_header_request)
        utils.abort.assert_called_once()
示例#2
0
    def get(self, host_id):
        limit = limit_value()
        offset = offset_value()
        if not is_valid_uuid(host_id):
            abort(404,
                  message='Invalid host_id, Id should be in form of UUID4')

        account_number = identity(request)['identity']['account_number']

        system_query = system_ids_by_account(account_number).filter(
            System.inventory_id == host_id).subquery()

        query = PerformanceProfile.query.filter(
            PerformanceProfile.system_id.in_(system_query)).order_by(
                PerformanceProfile.report_date.desc())

        count = query.count()
        query = query.limit(limit).offset(offset)
        query_results = query.all()

        if not query_results:
            abort(404, message="System {} doesn't exist".format(host_id))

        performance_history = []
        for profile in query_results:
            performance_record = sort_io_dict(profile.performance_utilization)
            performance_record['report_date'] = profile.report_date
            performance_history.append(performance_record)

        paginated_response = build_paginated_system_list_response(
            limit, offset, performance_history, count)
        paginated_response['inventory_id'] = host_id
        return paginated_response
示例#3
0
    def get(self):
        account_number = identity(request)['identity']['account_number']
        query = (db.session.query(System.id).join(
            PerformanceProfile,
            PerformanceProfile.system_id == System.id).join(
                RhAccount, RhAccount.id == System.account_id).filter(
                    RhAccount.account == account_number).distinct())
        system_count = query.count()
        systems_with_suggestions = query.filter(
            System.number_of_recommendations > 0).count()
        systems_waiting_for_data = query.filter(
            System.state == 'Waiting for data').count()

        if system_count <= 0:
            status, code = False, 'NO_SYSTEMS'
        else:
            status, code = True, 'SYSTEMSEXIST'
        return {
            'success': status,
            'code': code,
            'count': system_count,
            'systems_stats': {
                'waiting_for_data': systems_waiting_for_data,
                'with_suggestions': systems_with_suggestions
            }
        }
示例#4
0
    def get(self):
        limit = limit_value()
        offset = offset_value()
        order_by = (
            request.args.get('order_by') or 'display_name'
        ).strip().lower()
        order_how = (request.args.get('order_how') or 'asc').strip().lower()

        ident = identity(request)['identity']
        # Note that When using LIMIT, it is important to use an ORDER BY clause
        # that constrains the result rows into a unique order.
        # Otherwise you will get an unpredictable subset of the query's rows.
        # Refer - https://www.postgresql.org/docs/13/queries-limit.html

        account_query = db.session.query(RhAccount.id).filter(RhAccount.account == ident['account_number']).subquery()
        system_query = db.session.query(System.id).filter(
            System.account_id.in_(account_query)).filter(*self.build_system_filters())

        last_reported = (
            db.session.query(PerformanceProfile.system_id, func.max(PerformanceProfile.report_date).label('max_date')
                             )
            .filter(PerformanceProfile.system_id.in_(system_query.subquery()))
            .group_by(PerformanceProfile.system_id)
            .subquery()
        )

        sort_expression = self.build_sort_expression(order_how, order_by)

        query = (
            db.session.query(PerformanceProfile, System, RhAccount)
            .join(last_reported, (last_reported.c.max_date == PerformanceProfile.report_date) &
                  (PerformanceProfile.system_id == last_reported.c.system_id))
            .join(System, System.id == last_reported.c.system_id)
            .join(RhAccount, RhAccount.id == System.account_id)
            .order_by(*sort_expression)
        )
        count = query.count()
        query = query.limit(limit).offset(offset)
        query_results = query.all()
        hosts = []
        for row in query_results:
            try:
                system_dict = row.System.__dict__
                host = {skey: system_dict[skey] for skey in SYSTEM_COLUMNS}
                host['account'] = row.RhAccount.account
                host['performance_utilization'] = row.PerformanceProfile.performance_utilization
                host['display_performance_score'] = row.PerformanceProfile.display_performance_score
                host['idling_time'] = row.PerformanceProfile.idling_time
                host['io_wait'] = row.PerformanceProfile.io_wait
                hosts.append(host)
            except Exception as err:
                LOG.error(
                    'An error occured while fetching the host. %s',
                    repr(err)
                )
                count -= 1

        return build_paginated_system_list_response(
            limit, offset, hosts, count
        )
示例#5
0
    def get(self):
        ident = identity(request)['identity']
        account_query = db.session.query(RhAccount.id).filter(
            RhAccount.account == ident['account_number']).subquery()
        system_count = db.session.query(System.id)\
            .filter(System.account_id.in_(account_query)).count()
        systems_with_suggestions = db.session.query(System.id)\
            .filter(System.account_id.in_(account_query))\
            .filter(System.number_of_recommendations > 0).count()
        systems_waiting_for_data = db.session.query(System.id)\
            .filter(System.account_id.in_(account_query))\
            .filter(System.state == 'Waiting for data').count()

        if system_count <= 0:
            status, code = False, 'NO_SYSTEMS'
        else:
            status, code = True, 'SYSTEMSEXIST'
        return {
            'success': status,
            'code': code,
            'count': system_count,
            'systems_stats': {
                'waiting_for_data': systems_waiting_for_data,
                'with_suggestions': systems_with_suggestions
            }
        }
示例#6
0
    def get(self, host_id):
        if not is_valid_uuid(host_id):
            abort(404,
                  message='Invalid host_id, Id should be in form of UUID4')

        ident = identity(request)['identity']
        user = user_data_from_identity(ident)
        username = user['username'] if 'username' in user else None
        account_number = identity(request)['identity']['account_number']

        system_query = system_ids_by_account(account_number).filter(
            System.inventory_id == host_id).subquery()

        profile = PerformanceProfile.query.filter(
            PerformanceProfile.system_id.in_(system_query)).order_by(
                PerformanceProfile.report_date.desc()).first()

        rating_record = RecommendationRating.query.filter(
            RecommendationRating.system_id.in_(system_query),
            RecommendationRating.rated_by == username).first()

        system = db.session.query(System).filter(
            System.inventory_id == host_id).first()

        record = None
        if profile:
            record = {key: system.__dict__[key] for key in SYSTEM_COLUMNS}
            record['performance_utilization'] = sort_io_dict(
                profile.performance_utilization)
            record['rating'] = rating_record.rating if rating_record else None
            record['report_date'] = profile.report_date
            record['idling_time'] = profile.idling_time
            record['os'] = system.deserialize_host_os_data
        else:
            abort(404, message="System {} doesn't exist".format(host_id))

        return record
    def post(self):
        """
            Add or update a rating for a system, by system ID.
            Return the new rating. Any previous rating for this rule by this
            user is amended to the current value.
        """
        ident = identity(request)['identity']
        user = user_data_from_identity(ident)
        username = user['username'] if 'username' in user else None

        if username is None:
            abort(403, message="Username doesn't exist")

        data = json.loads(request.data)
        inventory_id = data['inventory_id']
        rating = int(data['rating'])
        if rating not in [c.value for c in RatingChoicesEnum]:
            abort(
                422,
                message=("{} is not a valid value for rating".format(rating)))

        system = System.query.filter(
            System.inventory_id == inventory_id).first()

        if system is None:
            abort(404, message="System {} doesn't exist".format(inventory_id))

        rating_record = RecommendationRating.query.filter(
            RecommendationRating.system_id == system.id,
            RecommendationRating.rated_by == username).first()

        status_code = None
        if rating_record:
            rating_record.rating = rating
            db.session.commit()
            status_code = 200
        else:
            rating_record = RecommendationRating(system_id=system.id,
                                                 rating=rating,
                                                 rated_by=username)
            db.session.add(rating_record)
            db.session.commit()
            status_code = 201

        return {
            'rating': rating_record.rating,
            'inventory_id': inventory_id
        }, status_code
示例#8
0
    def get(self):
        account_number = identity(request)['identity']['account_number']
        system_query = system_ids_by_account(account_number).filter(
            System.number_of_recommendations > 0)
        query = (db.session.query(PerformanceProfile.system_id).filter(
            PerformanceProfile.system_id.in_(
                system_query.subquery())).distinct())
        total_system_count = query.count()

        configTryLearn_Object = {
            "try": [{
                "shape": {
                    "title":
                    "Install and begin using Resource optimization service.",
                    "description": "Optimize your spending in public cloud.",
                    "link": {
                        "title": "Get started",
                        "href": "/insights/ros?with_suggestions=true",
                    },
                },
            }]
        }
        if total_system_count == 0:
            return {"configTryLearn": configTryLearn_Object}
        else:
            if total_system_count > 1:
                suffix = 'systems'
            else:
                suffix = 'system'
            return {
                "recommendations": {
                    "redhatInsights": [{
                        "id":
                        "ros-1",
                        "description":
                        "Resource optimization recommends to assess and monitor"
                        + " cloud usage and optimization on these systems",
                        "icon":
                        "cog",
                        "action": {
                            "title": f"View {total_system_count} {suffix}" +
                            " with suggestions",
                            "href": "/insights/ros?with_suggestions=true"
                        }
                    }]
                },
                "configTryLearn": configTryLearn_Object
            }
示例#9
0
    def get(self):
        ident = identity(request)['identity']
        account_query = db.session.query(RhAccount.id).filter(
            RhAccount.account == ident['account_number']).subquery()
        system_count = db.session.query(System.id)\
            .filter(System.account_id.in_(account_query)).count()

        if system_count <= 0:
            return {
                'success': False,
                'code': 'NOSYSTEMS',
                'count': system_count
            }

        return {
            'success': True,
            'code': 'SYSTEMSEXIST',
            'count': system_count
        }
示例#10
0
    def get(self, host_id):
        if not is_valid_uuid(host_id):
            abort(404,
                  message='Invalid host_id, Id should be in form of UUID4')

        ident = identity(request)['identity']

        filter_description = request.args.get('description')

        account_query = db.session.query(RhAccount.id).filter(
            RhAccount.account == ident['account_number']).subquery()
        system = db.session.query(System) \
            .filter(System.account_id.in_(account_query)).filter(System.inventory_id == host_id).first()

        if not system:
            abort(404, message="host with id {} doesn't exist".format(host_id))
        rule_hits = system.rule_hit_details
        recommendations_list = []
        rules_columns = [
            'rule_id', 'description', 'reason', 'resolution', 'condition'
        ]
        if rule_hits:
            for rule_hit in rule_hits:
                if filter_description:
                    rule_data = db.session.query(Rule).filter(Rule.rule_id == rule_hit['rule_id'])\
                                .filter(Rule.description.ilike(f'%{filter_description}%')).first()
                else:
                    rule_data = db.session.query(Rule).filter(
                        Rule.rule_id == rule_hit['rule_id']).first()
                if rule_data:
                    rule_dict = rule_data.__dict__
                    recommendation = {}
                    instance_price = ''
                    summary = ''
                    candidate_string = ''
                    rule_hit_details = rule_hit.get('details')
                    candidates = rule_hit_details.get('candidates')
                    summaries = rule_hit_details.get('summary')
                    instance_price += f'{rule_hit_details.get("price")} {INSTANCE_PRICE_UNIT}'
                    newline = '\n'
                    for skey in rules_columns:
                        if skey == 'reason':
                            formatted_summary = []
                            for msg in summaries:
                                formatted_summary.append(f'\t\u2022 {msg}')
                            summary += newline.join(formatted_summary)
                        elif skey == 'resolution':
                            formatted_candidates = []
                            for candidate in candidates[0:3]:
                                formatted_candidates.append(
                                    f'{candidate[0]} ({candidate[1]} {INSTANCE_PRICE_UNIT})'
                                )
                            candidate_string += ', '.join(formatted_candidates)
                        recommendation[skey] = eval("f'{}'".format(
                            rule_dict[skey]))
                    recommendations_list.append(recommendation)
        return {
            'inventory_id': system.inventory_id,
            'data': recommendations_list,
            'meta': {
                'count': len(recommendations_list)
            }
        }