Exemple #1
0
 def send(self, enc, load, tries=1, timeout=60):
     '''
     Takes two arguments, the encryption type and the base payload
     '''
     payload = {'enc': enc}
     payload['load'] = load
     pkg = self.serial.dumps(payload)
     self.socket.send(pkg)
     self.poller.register(self.socket, zmq.POLLIN)
     tried = 0
     while True:
         polled = self.poller.poll(timeout * 1000)
         tried += 1
         if polled:
             break
         if tries > 1:
             log.info(
                 'SaltReqTimeoutError: after {0} seconds. (Try {1} of {2})'.
                 format(timeout, tried, tries))
         if tried >= tries:
             self.clear_socket()
             raise SaltReqTimeoutError(
                 'SaltReqTimeoutError: after {0} seconds, ran {1} tries'.
                 format(timeout * tried, tried))
     return self.serial.loads(self.socket.recv())
Exemple #2
0
 def timeout_message(self, message_id):
     if message_id in self.send_timeout_map:
         del self.send_timeout_map[message_id]
     if message_id in self.send_future_map:
         self.send_future_map.pop(message_id).set_exception(
             SaltReqTimeoutError('Message timed out')
         )
Exemple #3
0
    def timeout_message(self, message):
        '''
        Handle a message timeout by removing it from the sending queue
        and informing the caller

        :raises: SaltReqTimeoutError
        '''
        future = self.send_future_map.pop(message, None)
        # In a race condition the message might have been sent by the time
        # we're timing it out. Make sure the future is not None
        if future is not None:
            del self.send_timeout_map[message]
            if future.attempts < future.tries:
                future.attempts += 1
                log.debug('SaltReqTimeoutError, retrying. ({0}/{1})'.format(
                    future.attempts, future.tries))
                self.send(
                    message,
                    timeout=future.timeout,
                    tries=future.tries,
                    future=future,
                )

            else:
                future.set_exception(SaltReqTimeoutError('Message timed out'))
Exemple #4
0
 def send(self, enc, load, tries=1, timeout=60):
     """
     Takes two arguments, the encryption type and the base payload
     """
     payload = {"enc": enc}
     payload["load"] = load
     pkg = self.serial.dumps(payload)
     self.socket.send(pkg)
     self.poller.register(self.socket, zmq.POLLIN)
     tried = 0
     while True:
         polled = self.poller.poll(timeout * 1000)
         tried += 1
         if polled:
             break
         if tries > 1:
             log.info(
                 "SaltReqTimeoutError: after %s seconds. (Try %s of %s)",
                 timeout,
                 tried,
                 tries,
             )
         if tried >= tries:
             self.clear_socket()
             raise SaltReqTimeoutError(
                 "SaltReqTimeoutError: after {} seconds, ran {} "
                 "tries".format(timeout * tried, tried))
     return self.serial.loads(self.socket.recv())
Exemple #5
0
    def timeout_message(self, message):
        """
        Handle a message timeout by removing it from the sending queue
        and informing the caller

        :raises: SaltReqTimeoutError
        """
        future = self.send_future_map.pop(message, None)
        # In a race condition the message might have been sent by the time
        # we're timing it out. Make sure the future is not None
        if future is not None:
            if future.attempts < future.tries:
                future.attempts += 1
                log.debug(
                    "SaltReqTimeoutError, retrying. (%s/%s)",
                    future.attempts,
                    future.tries,
                )
                self.send(
                    message,
                    timeout=future.timeout,
                    tries=future.tries,
                    future=future,
                )

            else:
                future.set_exception(SaltReqTimeoutError("Message timed out"))
Exemple #6
0
    def timeout_message(self, message):
        '''
        Handle a message timeout by removing it from the sending queue
        and informing the caller

        :raises: SaltReqTimeoutError
        '''
        del self.send_timeout_map[message]
        self.send_future_map.pop(message).set_exception(SaltReqTimeoutError('Message timed out'))
Exemple #7
0
    def timeout_message(self, message):
        """
        Handle a message timeout by removing it from the sending queue
        and informing the caller

        :raises: SaltReqTimeoutError
        """
        future = self.send_future_map.pop(message, None)
        # In a race condition the message might have been sent by the time
        # we're timing it out. Make sure the future is not None
        if future is not None:
            future.set_exception(SaltReqTimeoutError("Message timed out"))
Exemple #8
0
 def send(self, enc, load, tries=1, timeout=60):
     '''
     Takes two arguments, the encryption type and the base payload
     '''
     payload = {'enc': enc}
     payload['load'] = load
     pkg = self.serial.dumps(payload)
     self.socket.send(pkg)
     self.poller.register(self.socket, zmq.POLLIN)
     tried = 0
     while True:
         polled = self.poller.poll(timeout * 1000)
         tried += 1
         if polled:
             break
         elif tried >= tries:
             raise SaltReqTimeoutError('Waited {0} seconds'.format(timeout *
                                                                   tried))
     return self.serial.loads(self.socket.recv())
Exemple #9
0
 def send(self, enc, load, tries=1, timeout=60):
     '''
     Takes two arguments, the encryption type and the base payload
     '''
     payload = {'enc': enc}
     payload['load'] = load
     package = self.serial.dumps(payload)
     self.socket.send(package)
     poller = zmq.Poller()
     poller.register(self.socket, zmq.POLLIN)
     tried = 0
     while True:
         if not poller.poll(timeout * 1000) and tried >= tries:
             raise SaltReqTimeoutError('Waited {0} seconds'.format(timeout))
         else:
             break
         tried += 1
     ret = self.serial.loads(self.socket.recv())
     poller.unregister(self.socket)
     return ret
Exemple #10
0
    def timeout_message(self, message):
        '''
        Handle a message timeout by removing it from the sending queue
        and informing the caller

        :raises: SaltReqTimeoutError
        '''
        future = self.send_future_map.pop(message)
        del self.send_timeout_map[message]
        if future.attempts < future.tries:
            future.attempts += 1
            log.debug('SaltReqTimeoutError, retrying. ({0}/{1})'.format(future.attempts, future.tries))
            self.send(
                message,
                timeout=future.timeout,
                tries=future.tries,
                future=future,
            )

        else:
            future.set_exception(SaltReqTimeoutError('Message timed out'))
Exemple #11
0
 def send(self, load):
     '''
     mock send method
     '''
     self.load = load
     raise SaltReqTimeoutError(load)
Exemple #12
0
 def timeout_message(self, message_id, msg):
     if message_id not in self.send_future_map:
         return
     future = self.send_future_map.pop(message_id)
     if future is not None:
         future.set_exception(SaltReqTimeoutError("Message timed out"))
Exemple #13
0
 def timeout_message(self, message):
     del self.send_timeout_map[message]
     self.send_future_map.pop(message).set_exception(SaltReqTimeoutError('Message timed out'))
Exemple #14
0
def create_certificate(path=None, text=False, csr=None, timeout=120, **kwargs):
    """
    Create a certificate by asking the master to sign a certificate signing
    request (CSR) or create a CSR on-the-fly.

    path:
        Path to write certificate to. Either ``path`` or ``text`` must be
        specified.

    text:
        Return certificate as PEM-encoded string. Either ``path`` or ``text``
        must be specified.

    csr:
        Path to certificate signing request file.

    module:
        Execution module called to sign the CSR. The CSR is passed as a
        PEM-encoded string as the first argument to the module. It is expected
        to return a dictionary with the following field(s):

        text:
            The resulting certificate as a PEM-encoded string. It may contain
            additional intermediate certificates.

        A default module is fetched with ``config.get`` from ``pki:default:module``.

    runner:
        Runner to call on the master. The CSR is passed as a PEM-encoded string
        as the first argument to the runner. It is expected to return a
        dictionary with the following field(s):

        text:
            The resulting certificate as a PEM-encoded string. It may contain
            additional intermediate certificates.

        A default runner is fetched with ``config.get`` from ``pki:default:runner``.

    timeout:
        Maximum time to wait on a response from the runner.
    """

    if not path and not text:
        raise SaltInvocationError("Either path or text must be specified")

    if not csr:
        raise SaltInvocationError("CSR is required")

    if "runner" in kwargs and "module" in kwargs:
        raise SaltInvocationError("Either use 'runner' or 'module'")

    if "runner" not in kwargs and "module" not in kwargs:
        default = __salt__["config.get"]("pki:default", {})

        if "runner" in default:
            kwargs["runner"] = default["runner"]
        if "module" in default:
            kwargs["module"] = default["module"]

    if not kwargs.get("runner", None) and not kwargs.get("module", None):
        raise SaltInvocationError("Either 'runner' or 'module' is required")

    if os.path.exists(csr):
        with _fopen(csr, "r") as f:
            csr = f.read()

    if "runner" in kwargs:
        runner = kwargs["runner"]
        resp = __salt__["publish.runner"](runner, arg=csr, timeout=timeout)

        if not resp:
            raise SaltInvocationError(
                f"Nothing returned from runner, do you have permissions run {runner}?"
            )

        if isinstance(resp, str) and "timed out" in resp:
            raise SaltReqTimeoutError(resp)

        if isinstance(resp, str):
            raise CommandExecutionError(resp)

    elif "module" in kwargs:
        module = kwargs["module"]
        if module not in __salt__:
            raise SaltInvocationError(f"Module {module} not available")

        resp = __salt__[module](csr)

    if not isinstance(resp, dict):
        raise CommandExecutionError(
            f"Expected response to be a dict, but got {type(resp)}")

    try:
        ret = read_certificate(resp["text"])
    except ValueError as e:
        raise CommandExecutionError(
            f"Did not return a valid PEM-encoded certificate: {e}")

    if path:
        with _fopen(path, "w") as f:
            f.write(resp["text"])

    if text:
        return resp["text"]

    return ret