Exemple #1
0
def do_request(
    method: str,
    host: str,
    path: str,
    params: Optional[Dict[str, Any]] = None,
    body: Optional[Dict[str, Any]] = None,
    headers: Optional[Dict[str, str]] = None,
    authenticated: bool = True,
    auth: Optional[authentication.Authentication] = None,
    cert: Optional[certs.Cert] = None,
    stream: bool = False,
) -> requests.Response:
    # If no explicit Authentication object was provided, use the cli's singleton Authentication.
    if auth is None:
        auth = authentication.cli_auth
    if cert is None:
        cert = certs.cli_cert

    if headers is None:
        h = {}  # type: Dict[str, str]
    else:
        h = headers

    if params is None:
        params = {}

    if authenticated:
        h = add_token_to_headers(h, auth)

    try:
        r = determined.common.requests.request(
            method,
            make_url(host, path),
            params=params,
            json=body,
            headers=h,
            verify=cert.bundle if cert else None,
            stream=stream,
            server_hostname=cert.name if cert else None,
        )
    except requests.exceptions.SSLError:
        raise
    except requests.exceptions.ConnectionError as e:
        raise errors.MasterNotFoundException(str(e))
    except requests.exceptions.RequestException as e:
        raise errors.BadRequestException(str(e))

    if r.status_code == 403:
        username = ""
        if auth is not None:
            username = auth.get_session_user()
        raise errors.UnauthenticatedException(username=username)
    elif r.status_code == 404:
        raise errors.NotFoundException(r)
    elif r.status_code >= 300:
        raise errors.APIException(r)

    return r
Exemple #2
0
def do_request(
    method: str,
    host: str,
    path: str,
    params: Optional[Dict[str, Any]] = None,
    body: Optional[Dict[str, Any]] = None,
    headers: Optional[Dict[str, str]] = None,
    authenticated: bool = True,
    stream: bool = False,
) -> requests.Response:
    if headers is None:
        h = {}  # type: Dict[str, str]
    else:
        h = headers

    if params is None:
        params = {}

    if authenticated:
        h = add_token_to_headers(h)

    try:
        r = determined.common.requests.request(
            method,
            make_url(host, path),
            params=params,
            json=body,
            headers=h,
            verify=_master_cert_bundle,
            stream=stream,
            server_hostname=_master_cert_name,
        )
    except requests.exceptions.SSLError:
        raise
    except requests.exceptions.ConnectionError as e:
        raise errors.MasterNotFoundException(str(e))
    except requests.exceptions.RequestException as e:
        raise errors.BadRequestException(str(e))

    if r.status_code == 403:
        username = authentication.Authentication.instance().get_session_user()
        raise errors.UnauthenticatedException(username=username)
    elif r.status_code == 404:
        raise errors.NotFoundException(r)
    elif r.status_code >= 300:
        raise errors.APIException(r)

    return r
Exemple #3
0
 def __iter__(self) -> Iterator[Any]:
     for event in self.socket.connect(ping_rate=0):
         if isinstance(event, lomond.events.Connected):
             # Ignore the initial connection event.
             pass
         elif isinstance(event, (lomond.events.Closing, lomond.events.Disconnected)):
             # The socket was successfully closed so we just return.
             return
         elif isinstance(
             event,
             (lomond.events.ConnectFail, lomond.events.Rejected, lomond.events.ProtocolError),
         ):
             # Any unexpected failures raise the standard API exception.
             raise errors.BadRequestException(message="WebSocket failure: {}".format(event))
         elif isinstance(event, lomond.events.Text):
             # All web socket connections are expected to be in a JSON
             # format.
             yield simplejson.loads(event.text)
Exemple #4
0
def do_request(
    method: str,
    host: str,
    path: str,
    params: Optional[Dict[str, Any]] = None,
    json: Any = None,
    data: Optional[str] = None,
    headers: Optional[Dict[str, str]] = None,
    authenticated: bool = True,
    auth: Optional[authentication.Authentication] = None,
    cert: Optional[certs.Cert] = None,
    stream: bool = False,
    timeout: Optional[Union[Tuple, float]] = None,
    max_retries: Optional[urllib3.util.retry.Retry] = None,
) -> requests.Response:
    # If no explicit Authentication object was provided, use the cli's singleton Authentication.
    if auth is None:
        auth = authentication.cli_auth
    if cert is None:
        cert = certs.cli_cert

    if headers is None:
        h = {}  # type: Dict[str, str]
    else:
        h = headers

    if params is None:
        params = {}

    if authenticated:
        h = add_token_to_headers(h, auth)

    # Allow the json json to come pre-encoded, if we need custom encoding.
    if json is not None and data is not None:
        raise ValueError("json and data must not be provided together")

    if json:
        data = det.util.json_encode(json)

    try:
        r = determined.common.requests.request(
            method,
            make_url(host, path),
            params=params,
            data=data,
            headers=h,
            verify=cert.bundle if cert else None,
            stream=stream,
            timeout=timeout,
            server_hostname=cert.name if cert else None,
            max_retries=max_retries,
        )
    except requests.exceptions.SSLError:
        raise
    except requests.exceptions.ConnectionError as e:
        raise errors.MasterNotFoundException(str(e))
    except requests.exceptions.RequestException as e:
        raise errors.BadRequestException(str(e))

    def _get_message(r: requests.models.Response) -> str:
        try:
            return str(_json.loads(r.text).get("message"))
        except Exception:
            return ""

    if r.status_code == 403:
        username = ""
        if auth is not None:
            username = auth.get_session_user()
        raise errors.ForbiddenException(username=username,
                                        message=_get_message(r))
    elif r.status_code == 404:
        raise errors.NotFoundException(r)
    elif r.status_code >= 300:
        raise errors.APIException(r)

    return r