Beispiel #1
0
def testSerialisingDict():
	inputValues = {'a': 'b', 'c': 1, 'e': 2}
	assert u'{"a": "b", "c": 1, "e": 2}' == toJson(inputValues)
	assert inputValues == fromJson(toJson(inputValues))

	inputValues = {'a': 'b', 'c': 1, 'e': 2.3}
	assert u'{"a": "b", "c": 1, "e": 2.3}' == toJson(inputValues)
Beispiel #2
0
def testDeserialisationWithoutObjectCreation():
	json = """[
	{
	"ident" : "baert.niko.uib.local",
	"description" : "",
	"created" : "2014-08-29 10:41:27",
	"inventoryNumber" : "loel",
	"ipAddress" : null,
	"notes" : "",
	"oneTimePassword" : null,
	"lastSeen" : "2014-08-29 10:41:27",
	"hardwareAddress" : null,
	"opsiHostKey" : "7dc2b49c20d545bdbfad9a326380cea3",
	"type" : "OpsiClient",
	"id" : "baert.niko.uib.local"
	}
]"""

	result = fromJson(json, preventObjectCreation=True)

	assert isinstance(result, list)
	assert 1 == len(result)

	obj = result[0]
	assert isinstance(obj, dict)
	assert 'ident' in obj
Beispiel #3
0
def testObjectToBeautifiedTextGeneratesValidJSON(objectCount):
	objectsIn = [ProductFactory.generateLocalbootProduct(i) for i in range(objectCount)]
	text = objectToBeautifiedText(objectsIn)

	objects = fromJson(text)
	assert objectCount == len(objects)
	for obj in objects:
		assert isinstance(obj, LocalbootProduct)
Beispiel #4
0
def forceObjectClass(var, objectClass):
    if isinstance(var, objectClass):
        return var

    exception = None
    if isinstance(var, _STRING_TYPES) and var.lstrip().startswith('{'):
        from OPSI.Util import fromJson

        try:
            var = fromJson(var)
        except Exception as error:
            exception = error
            logger.debug(u"Failed to get object from json {0!r}: {1!r}", var,
                         error)

    if isinstance(var, dict):
        if 'type' not in var:
            raise ValueError(u"Key 'type' missing in hash {0!r}".format(var))

        import OPSI.Object
        try:
            c = eval('OPSI.Object.%s' % var['type'])
            if issubclass(c, objectClass):
                var = c.fromHash(var)
        except AttributeError as error:
            if "'module' object has no attribute " in str(error):
                error = ValueError("Invalild object type: {0}".format(
                    var['type']))

            exception = error
            logger.debug(u"Failed to get object from dict {0!r}: {1!r}", var,
                         error)
        except Exception as error:
            exception = error
            logger.debug(u"Failed to get object from dict {0!r}: {1!r}", var,
                         error)

    if not isinstance(var, objectClass):
        if exception is not None:
            raise ValueError(u"Not a %s: '%s': %s" %
                             (objectClass, var, exception))
        else:
            raise ValueError(u"Not a %s: '%s'" % (objectClass, var))

    return var
Beispiel #5
0
    def run(self):
        self.started = time.time()
        timeout = self.hostControlBackend._hostRpcTimeout
        if timeout < 0:
            timeout = 0

        try:
            query = toJson({
                'id': 1,
                'method': self.method,
                'params': self.params
            }).encode('utf-8')

            connection = HTTPSConnection(host=self.address,
                                         port=self.hostPort,
                                         timeout=timeout)
            with closingConnection(connection) as connection:
                non_blocking_connect_https(connection, timeout)
                connection.putrequest('POST', '/opsiclientd')
                connection.putheader('User-Agent', self._USER_AGENT)
                connection.putheader('content-type', 'application/json')
                connection.putheader('content-length', str(len(query)))
                auth = u'{0}:{1}'.format(self.username, self.password)
                connection.putheader(
                    'Authorization',
                    'Basic ' + base64.b64encode(auth.encode('latin-1')))
                connection.endheaders()
                connection.send(query)

                response = connection.getresponse()
                response = response.read()
                response = fromJson(unicode(response, 'utf-8'))

                if response and isinstance(response, dict):
                    self.error = response.get('error')
                    self.result = response.get('result')
                else:
                    self.error = u"Bad response from client: %s" % forceUnicode(
                        response)
        except Exception as e:
            self.error = forceUnicode(e)
        finally:
            self.ended = time.time()
Beispiel #6
0
    def executeRpc(self, method, params=None, with_lock=True):
        params = params or []
        with log_context({'instance': 'control pipe'}):
            rpc_id = 1
            if not self.clientInfo:
                return {
                    "id": rpc_id,
                    "error":
                    f"Cannot execute rpc, not supported by client {self}",
                    "result": None
                }

            request = {"id": rpc_id, "method": method, "params": params}
            try:
                if with_lock:
                    self.comLock.acquire()  # pylint: disable=consider-using-with
                try:
                    request_json = toJson(request)
                    logger.info("Sending request '%s' to client %s",
                                request_json, self)
                    self.write(request_json)
                    response_json = self.read()
                    if not response_json:
                        logger.warning(
                            "No response for method '%s' received from client %s",
                            request["method"], self)
                        return {"id": rpc_id, "error": None, "result": None}
                    logger.info("Received response '%s' from client %s",
                                response_json, self)
                    response = fromJson(response_json)
                    if method == "loginUser" and response.get("result"):
                        # Credential provider can only handle one successful login.
                        # Ensure, that the credential provider is not used for a
                        # second login if it keeps the pipe connection open.
                        self.login_capable = False
                    return response
                finally:
                    if with_lock:
                        self.comLock.release()
            except Exception as client_err:  # pylint: disable=broad-except
                logger.error(client_err, exc_info=True)
                return {"id": rpc_id, "error": str(client_err), "result": None}
Beispiel #7
0
def testDeserialisationWithExplicitTypeSetting():
	"It must be possible to set an type."

	json = """
	{
	"ident" : "baert.niko.uib.local",
	"description" : "",
	"created" : "2014-08-29 10:41:27",
	"inventoryNumber" : "loel",
	"ipAddress" : null,
	"notes" : "",
	"oneTimePassword" : null,
	"lastSeen" : "2014-08-29 10:41:27",
	"hardwareAddress" : null,
	"opsiHostKey" : "7dc2b49c20d545bdbfad9a326380cea3",
	"id" : "baert.niko.uib.local"
	}
"""

	obj = fromJson(json, objectType="OpsiClient", preventObjectCreation=False)

	assert isinstance(obj, OpsiClient)
Beispiel #8
0
    def _getRpcs(self, result):
        if not self.query:
            return result
        if not self._callInstance:
            raise RuntimeError(u"Call instance not defined in %s" % self)
        if not self._callInterface:
            raise RuntimeError(u"Call interface not defined in %s" % self)

        try:
            rpcs = fromJson(self.query, preventObjectCreation=True)
            if not rpcs:
                raise ValueError(u"Got no rpcs")
        except Exception as e:
            raise OpsiBadRpcError(u"Failed to decode rpc: %s" % e)

        for rpc in forceList(rpcs):
            rpc = JsonRpc(instance=self._callInstance,
                          interface=self._callInterface,
                          rpc=rpc)
            self._rpcs.append(rpc)

        return result
Beispiel #9
0
def testDeserialisationWithExplicitTypeSettingWorksOnUnknown():
	"Setting invalid types must not fail but return the input instead."

	json = """
	{
	"ident" : "baert.niko.uib.local",
	"description" : "",
	"created" : "2014-08-29 10:41:27",
	"inventoryNumber" : "loel",
	"ipAddress" : null,
	"notes" : "",
	"oneTimePassword" : null,
	"lastSeen" : "2014-08-29 10:41:27",
	"hardwareAddress" : null,
	"opsiHostKey" : "7dc2b49c20d545bdbfad9a326380cea3",
	"id" : "baert.niko.uib.local"
	}
"""

	obj = fromJson(json, objectType="NotYourType", preventObjectCreation=False)

	assert isinstance(obj, dict)
	assert "baert.niko.uib.local" == obj['ident']
Beispiel #10
0
 def processIncomingRpc(self, rpc):
     try:
         rpc = fromJson(rpc)
         if rpc.get("method") == "registerClient":
             # New client protocol
             self.clientInfo = rpc.get("params", [])
             self.login_capable = True
             logger.info("Client %s info set to: %s", self, self.clientInfo)
             return toJson({
                 "id": rpc.get("id"),
                 "result":
                 f"client {'/'.join(self.clientInfo)}/{self.client_id} registered",
                 "error": None
             })
         jsonrpc = JsonRpc(
             instance=self._controller._opsiclientdRpcInterface,  # pylint: disable=protected-access
             interface=self._controller._opsiclientdRpcInterface.
             getInterface(),  # pylint: disable=protected-access
             rpc=rpc)
         jsonrpc.execute()
         return toJson(jsonrpc.getResponse())
     except Exception as rpc_error:  # pylint: disable=broad-except
         logger.error(rpc_error, exc_info=True)
         return toJson({"id": None, "error": str(rpc_error)})
Beispiel #11
0
def testSerialisingListWithFLoat():
	inputValues = ['a', 'b', 'c', 4, 5.6]
	output = toJson(inputValues)

	assert inputValues == fromJson(output)
	assert u'["a", "b", "c", 4, 5.6]' == output
Beispiel #12
0
def testSerialisingSet():
	inputSet = set([u'opsi-client-agent', u'mshotfix', u'firefox'])
	output = toJson(inputSet)

	assert set(fromJson(output)) == inputSet