Esempio n. 1
0
def _get_consumer_by_uuid(ctx, uuid):
    """Return information about the consumer and its related project and user.
    """
    query = """
            MATCH (cs:CONSUMER {uuid: '%s'})
            WITH cs
            OPTIONAL MATCH (pj:PROJECT)-[:OWNS]->(cs)
            WITH cs, pj
            OPTIONAL MATCH (u:USER)-[:BELONGS_TO]->(pj)
            RETURN cs, pj, u
    """ % uuid
    result = ctx.tx.run(query).data()
    if not result:
        raise exception.ConsumerNotFound(uuid=uuid)
    rec = result[0]
    cs = db.pythonize(rec["cs"])
    pj = rec["pj"]
    pj = db.pythonize(pj) if pj else None
    user = rec["u"]
    user = db.pythonize(user) if user else None
    return {
        "uuid": cs.uuid,
        "project_uuid": pj,
        "user_uuid": user,
        "generation": cs.get("generation"),
        "updated_at": cs.get("updated_at"),
        "created_at": cs.get("created_at"),
    }
Esempio n. 2
0
def get_all(context):
    """Get a list of all the resource classes in the database."""
    query = """
            MATCH (rc:RESOURCE_CLASS)
            RETURN rc
    """
    result = context.tx.run(query).data()
    result_objs = [db.pythonize(rec["rc"]) for rec in result]
    return [ResourceClass(context, **obj) for obj in result_objs]
Esempio n. 3
0
 def _get_by_name_from_db(context, name):
     query = """
             MATCH (trait:TRAIT {name: '%s'})
             RETURN trait
     """ % name
     result = context.tx.run(query).data()
     if not result:
         raise exception.TraitNotFound(names=name)
     trait = db.pythonize(result[0]["trait"])
     return trait
Esempio n. 4
0
def _list_allocations_for_consumer(context, consumer_uuid):
    """Deletes any existing allocations that correspond to the allocations to
    be written. This is wrapped in a transaction, so if the write subsequently
    fails, the deletion will also be rolled back.
    """
    query = """
            MATCH p=(:CONSUMER {uuid: '%s'})-[:USES]->()
            WITH relationships(p)[0] AS usages
            RETURN usages
    """ % consumer_uuid
    result = context.tx.run(query).data()
    return [db.pythonize(rec["usages"]) for rec in result]
Esempio n. 5
0
 def _create_in_db(context):
     query = """
             CREATE (u:USER {uuid: '%s', created_at: timestamp(),
                 updated_at: timestamp()})
             RETURN u
     """ % self.uuid
     try:
         result = context.tx.run(query).data()
     except db.ClientError:
         raise exception.UserExists(uuid=self.uuid)
     db_obj = db.pythonize(result[0]["u"])
     self._from_db_object(context, self, db_obj)
Esempio n. 6
0
def get_traits_by_provider_tree(context, root_uuids):
    """Returns a dict, keyed by provider UUIDs for all resource providers
    in all trees indicated in the ``root_uuids``, of string trait names
    associated with that provider.

    :raises: ValueError when root_uuids is empty.

    :param context: placement.context.RequestContext object
    :param root_ids: list of root resource provider UUIDs
    """
    if not root_uuids:
        raise ValueError("Expected root_uuids to be a list of root resource "
                         "provider UUIDs, but got an empty list.")
    query = """
            MATCH (root:RESOURCE_PROVIDER {uuid: '%s'})
            WITH root
            OPTIONAL MATCH (root)-[*]->(rp:RESOURCE_PROVIDER)
            RETURN root, rp
    """
    all_traits = collections.defaultdict(set)
    for root_uuid in root_uuids:
        result = context.tx.run(query % root_uuid).data()
        if result:
            root_rp = db.pythonize(result[0]["root"])
            root_props = root_rp.keys()
            root_traits = _traits_from_props(context, root_props)
            all_traits[root_uuid].update(root_traits)
        for rec in result:
            rp_node = rec["rp"]
            if not rp_node:
                continue
            rp = db.pythonize(rp_node)
            rp_props = rp.keys()
            rp_traits = _traits_from_props(context, rp_props)
            all_traits[rp.uuid].update(rp_traits)
    # Convert the sets back to lists
    all_traits = {k: list(v) for k, v in all_traits.items()}
    return all_traits
Esempio n. 7
0
def _get_user_by_uuid(context, uuid):
    query = """
            MATCH (u:USER {uuid: '%s'})
            RETURN u
    """ % uuid
    result = context.tx.run(query).data()
    if not result:
        raise exception.UserNotFound(uuid=uuid)
    rec = db.pythonize(result[0]["u"])
    return {
        "uuid": rec.uuid,
        "updated_at": rec.updated_at,
        "created_at": rec.created_at,
    }
Esempio n. 8
0
def _get_project_by_uuid(context, uuid):
    query = """
            MATCH (pj:PROJECT {uuid: '%s'})
            RETURN pj
    """ % uuid
    result = context.tx.run(query).data()
    if not result:
        raise exception.ProjectNotFound(uuid=uuid)
    rec = db.pythonize(result[0]["pj"])
    return {
        "uuid": rec.uuid,
        "updated_at": rec.updated_at,
        "created_at": rec.created_at,
    }
Esempio n. 9
0
def _get_allocations_by_provider_uuid(context, rp_uuid):
    query = """
            MATCH (rp:RESOURCE_PROVIDER {uuid: '%s'})
            WITH rp
            MATCH (rp)-[:PROVIDES]->(rc)
            WITH rp, rc
            MATCH p=(cs:CONSUMER)-[:USES]->(rc)
            WITH rp, rc, labels(rc)[0] AS rc_name, cs,
                relationships(p)[0] AS usages
            OPTIONAL MATCH (pj:PROJECT)-[:OWNS]->(user:USER)-[:OWNS]->(cs)
            RETURN rp, rc, rc_name, cs, usages, pj, user
    """ % rp_uuid
    result = context.tx.run(query).data()
    allocs = []
    for record in result:
        rec_cs = db.pythonize(record["cs"])
        pj_uuid = record["pj"].get("uuid") if record["pj"] else None
        user_uuid = record["user"].get("uuid") if record["user"] else None
        allocs.append({
            "resource_provider_name":
            record["rp"]["name"],
            "resource_provider_uuid":
            record["rp"]["uuid"],
            "resource_provider_generation":
            record["rp"]["generation"],
            "resource_class_name":
            record["rc_name"],
            "used":
            record["usages"]["amount"],
            "consumer_uuid":
            rec_cs["uuid"],
            "consumer_generation":
            rec_cs["generation"],
            "project_uuid":
            pj_uuid,
            "user_uuid":
            user_uuid,
            "created_at":
            rec_cs["created_at"],
            "updated_at":
            rec_cs["updated_at"],
        })
    return allocs
Esempio n. 10
0
    def get_by_name(cls, context, name):
        """Return a ResourceClass object with the given string name.

        :param name: String name of the resource class to find

        :raises: ResourceClassNotFound if no such resource class was found
        """
        query = """
                MATCH (rc:RESOURCE_CLASS {name: '%s'})
                RETURN rc
        """ % name
        result = context.tx.run(query).data()
        if not result:
            raise exception.ResourceClassNotFound(resource_class=name)
        rec = db.pythonize(result[0])
        obj = cls(context,
                  name=name,
                  updated_at=rec.get("updated_at"),
                  created_at=rec.get("created_at"))
        return obj
Esempio n. 11
0
 def _create_in_db(context, updates):
     upd_list = []
     for key, val in updates.items():
         if isinstance(val, six.string_types):
             upd_list.append("%s: '%s'" % (key, val))
         else:
             upd_list.append("%s: %s" % (key, val))
     if "created_at" not in updates:
         upd_list.append("created_at: timestamp()")
     if "updated_at" not in updates:
         upd_list.append("updated_at: timestamp()")
     upd_clause = ", ".join(upd_list)
     query = """
     CREATE (trait:TRAIT {%s})
     RETURN trait
     """ % upd_clause
     try:
         result = context.tx.run(query).data()
     except db.ClientError as e:
         raise db_exc.DBDuplicateEntry(e)
     return db.pythonize(result[0]["trait"])
Esempio n. 12
0
def _get_all_from_db(context, filters):
    if not filters:
        filters = {}

    name_where = ""
    assoc = ""
    if 'name_in' in filters:
        name_list = [six.text_type(n) for n in filters['name_in']]
        name_where = "WHERE trait.name IN %s" % name_list
    if 'prefix' in filters:
        prefix_where = "trait.name STARTS WITH '{prf}'".format(
            prf=filters["prefix"])
        if name_where:
            name_where += "AND %s" % prefix_where
        else:
            name_where = "WHERE %s" % prefix_where
    if 'associated' in filters:
        # This means that only traits associated with RPs will be returned; the
        # value will be either True or False.
        add_not = " " if filters["associated"] else "not "
        assoc = """
                WITH trait
                MATCH (rp)
                WHERE {add_not}trait.name IN keys(rp)
        """.format(add_not=add_not)
    query = """
            MATCH (trait:TRAIT)
            %(name_where)s
            %(assoc)s
            RETURN trait
    """ % {
        "name_where": name_where,
        "assoc": assoc
    }
    result = context.tx.run(query).data()
    return [db.pythonize(rec["trait"]) for rec in result]