Ejemplo n.º 1
0
 def update(self,
            org_label: str,
            project_label: str,
            id: str,
            projects: List[str],
            identities: List[Dict],
            priority: int,
            rev: int,
            resource_types: List[str] = None) -> Dict:
     """Update a resolver.
 
     :param org_label: Label of the organization the resolver belongs to.
     :param project_label: Label of the project the resolver belongs to.
     :param id: ID of the resolver, given as an IRI which is not URL encoded.
     :param projects: List of target projects, given with format ``organization/project``.
     :param identities: List of identities the creator of the resolver has and
         which have the permission ``resources/read`` on the target projects.
     :param priority: Resolution priority.
     :param rev: Last revision of the resolver.
     :param resource_types: (optional) List of types of the resources to resolve,
         given as IRIs.
     :return: The Nexus metadata of the updated resolver.
     """
     encoded_id = encode_url(id)
     payload = self._payload(projects, identities, priority, id,
                             resource_types)
     return self._http.put(
         [self.segment, org_label, project_label, encoded_id],
         payload,
         rev=rev)
Ejemplo n.º 2
0
def deprecate(org_label: str, project_label: str, id: str, rev: int) -> Dict:
    """Deprecate a resolver.

    :param org_label: Label of the organization the resolver belongs to.
    :param project_label: Label of the project the resolver belongs to.
    :param id: ID of the resolver, given as an IRI which is not URL encoded.
    :param rev: Last revision of the resolver.
    :return: The Nexus metadata of the deprecated resolver.
    """
    encoded_id = encode_url(id)
    return http_delete([SEGMENT, org_label, project_label, encoded_id],
                       rev=rev)
Ejemplo n.º 3
0
def update(id, _org_label, _prj_label, _projects, _identities, _priority,
           _resources_types, _type, _payload):
    _org_label = utils.get_organization_label(_org_label)
    _prj_label = utils.get_project_label(_prj_label)
    nxs = utils.get_nexus_client()
    try:
        data = nxs.resolvers.fetch(org_label=_org_label,
                                   project_label=_prj_label,
                                   id=id)
        current_revision = data["_rev"]
        data_md5_before = utils.generate_nexus_payload_checksum(data)
        if _priority is not None and _identities is not None and _projects is not None:
            response = nxs.resolvers.update(org_label=_org_label,
                                            project_label=_prj_label,
                                            projects=_projects,
                                            identities=_identities,
                                            _priority=_priority,
                                            id=id,
                                            rev=current_revision,
                                            resources_types=_resources_types)
        else:
            if _payload is not None:
                data = json.loads(_payload)
            else:
                # If no payload given, load up the entry in a text file and open default editor
                new_file, filename = tempfile.mkstemp()
                print("Opening an editor: %s" % filename)
                f = open(filename, "w")
                f.write(json.dumps(data, indent=2))
                f.close()
                click.edit(filename=filename)
                f = open(filename, "r")
                data = json.loads(f.read())
                f.close()
                os.remove(filename)

            data_md5_after = utils.generate_nexus_payload_checksum(data)
            if data_md5_before == data_md5_after:
                print("No change in resolver, aborting update.")
            else:
                encoded_id = encode_url(id)
                nxs.resolvers.update_(path=[
                    nxs.resolvers.SEGMENT, _org_label, _prj_label, encoded_id
                ],
                                      payload=data,
                                      rev=current_revision)
                print("Resolver updated.")

    except nxs.HTTPError as e:
        utils.error(str(e))
        utils.print_json(e.response.json(), colorize=True)
Ejemplo n.º 4
0
 def create_(self, path: str, payload: Dict, id: str = None) -> Dict:
     """Create a resolver (path version).
 
     :param path: Full path of the project the resolver belongs to, URL encoded.
     :param payload: Payload of the resolver.
     :param id: (optional) User-defined ID of the resolver, given as an IRI
         which is not URL encoded.
     :return: The Nexus metadata of the created resolver.
     """
     if id is None:
         return self._http.post(path, payload)
     else:
         encoded_id = encode_url(id)
         p = "{}/{}".format(path, encoded_id)
         return self._http.put(p, payload)
Ejemplo n.º 5
0
def tag(org_label: str, project_label: str, id: str, tag: str, rev_to_tag: str,
        rev: int) -> Dict:
    """Tag a revision of a resolver.

    :param org_label: Label of the organization the resolver belongs to.
    :param project_label: Label of the project the resolver belongs to.
    :param id: ID of the resolver, given as an IRI which is not URL encoded.
    :param tag: Tag to set.
    :param rev_to_tag: Revision number to tag.
    :param rev: Last revision of the resolver.
    :return: The Nexus metadata of the tagged resolver.
    """
    encoded_id = encode_url(id)
    payload = {
        "tag": tag,
        "rev": rev_to_tag,
    }
    return http_post([SEGMENT, org_label, project_label, encoded_id, "tags"],
                     payload,
                     rev=rev)
Ejemplo n.º 6
0
def fetch(org_label: str,
          project_label: str,
          id: str,
          tag: str = None,
          rev: int = None) -> Dict:
    """Fetch a resolver.

    Raise an ``Exception`` if ``rev`` and ``tag`` are used together.

    :param org_label: Label of the organization the resolver belongs to.
    :param project_label: Label of the project the resolver belongs to.
    :param id: ID of the resolver, given as an IRI which is not URL encoded.
    :param tag: (optional) Tag of the resolver.
    :param rev: (optional) Revision number of the resolver.
    :return: The Nexus payload of the fetched resolver.
    """
    _check(rev, tag)
    encoded_id = encode_url(id)
    return http_get([SEGMENT, org_label, project_label, encoded_id],
                    rev=rev,
                    tag=tag)
Ejemplo n.º 7
0
    def _http_connect_request(self, hostname, port, method, urlpath,
                              params=None, body=None, headers=None):
        """
        Sends the HTTP request
        Parameters:
          hostname (str)
          port (int)
          method (str) - "GET", "POST", ...
          urlpath (str) - e.g. "/v2/system"
          headers (dict)
          body (str)
        Returns a (resp_data, resp_status, resp_reason, reap_headers) tuple
          resp_data (str)
          resp_status (int)
          resp_reason (str)
          resp_headers - list of (key, val) tuples
        Raises ApiTimeoutError or ApiConnectionError on connection error.
        Raises an ApiError subclass on all other errors
        """
        if not urlpath.startswith('/'):
            raise ValueError("Invalid URL path")

        # Handle special characters present between the path.
        # A IQN name can contain special characters (".", "-", ":") hence
        # skipping them from encoding.(Ref. RFC3720)
        urlpath = encode_url(urlpath, safe='/:.-')

        if params:
            count = 0
            for key in params.keys():
                if count > 0:
                    urlpath += "&"
                if count == 0:
                    urlpath += "?"
                cmd = "=".join([key, encode_url(params[key])])
                urlpath += cmd
                count += 1

        if headers is None:
            headers = {}

        try:
            conn = self._get_http_connection(hostname, port,
                                             timeout=self._timeout,
                                             secure=self._secure)
            self._logger.debug("REST send: method=" + str(method) +
                               " hostname=" + str(hostname) +
                               " port=" + str(port) +
                               " urlpath=" + str(urlpath) +
                               " headers=" + str(headers) +
                               " body=" + str(body))
            conn.request(method, urlpath, body=body, headers=headers)
            resp = conn.getresponse()
            resp_status = resp.status     # e.g. 200
            resp_reason = resp.reason    # e.g. 'OK'
            resp_headers = resp.getheaders()   # list of (key,val) tuples
            resp_data = resp.read()
            conn.close()
        except (socket.error, HTTPException) as ex:
            # If network error, raise exception:
            msg = str(ex)
            msg += "\nIP: " + str(self._hostname)
            if isinstance(ex, socket.timeout):
                exclass = ApiTimeoutError
            else:
                exclass = ApiConnectionError
            raise exclass, exclass(msg), sys.exc_info()[-1]
        # Debug log response:
        msg = "REST recv: status=" + str(resp_status) + \
              " reason=" + str(resp_reason) + \
              " headers=" + str(resp_headers) + \
              " data=" + str(resp_data)
        self._logger.debug(msg)
        # If API returned an error, raise exception:
        self._assert_response_successful(method, urlpath, body,
                                         resp_data, resp_status, resp_reason)
        return (resp_data, resp_status, resp_reason, resp_headers)