def get_doc_json(fname): malcolm_root = os.path.join(os.path.dirname(__file__), "..", "..") json_root = os.path.join(malcolm_root, "docs", "reference", "json") with open(os.path.join(json_root, fname)) as f: lines = f.readlines() text = "\n".join(lines[1:]) return json_decode(text)
def post(self, endpoint_str): # called from tornado thread path = endpoint_str.split("/") parameters = json_decode(self.request.body.decode()) request = Post(path=path, parameters=parameters) self.report_request(request) response = yield self._queue.get() self.handle_response(response)
def on_message(self, message): # called in tornado's thread if self._writeable is None: ipv4_ip = self.request.remote_ip if ipv4_ip == "::1": # Special case IPV6 loopback ipv4_ip = "127.0.0.1" remoteaddr = struct.unpack("!I", socket.inet_aton(ipv4_ip))[0] if self._validators: # Work out if the remote ip is within the netmask of any of our # interfaces. If not, Put and Post are forbidden self._writeable = max(v(remoteaddr) for v in self._validators) else: self._writeable = True log.info( "Puts and Posts are %s from %s", "allowed" if self._writeable else "forbidden", self.request.remote_ip, ) msg_id = -1 try: d = json_decode(message) try: msg_id = d["id"] except KeyError: raise FieldError("id field not present in JSON message") request = deserialize_object(d, Request) request.set_callback(self.on_response) if isinstance(request, Subscribe): assert msg_id not in self._id_to_mri, ( "Duplicate subscription ID %d" % msg_id ) self._id_to_mri[msg_id] = request.path[0] if isinstance(request, Unsubscribe): mri = self._id_to_mri[msg_id] else: mri = request.path[0] if isinstance(request, (Put, Post)) and not self._writeable: raise ValueError( "Put/Post is forbidden from %s" % self.request.remote_ip ) self._registrar.report(builtin.infos.RequestInfo(request, mri)) except Exception as e: log.exception("Error handling message:\n%s", message) error = Error(msg_id, e) error_message = error.to_dict() self.write_message(json_encode(error_message))
def do_load(self, design: str, init: bool = False) -> None: """Load a design name, running the child LoadHooks. Args: design: Name of the design json file, without extension init: Passed to the LoadHook to tell the children if this is being run at Init or not """ if design: filename = self._validated_config_filename(design) with open(filename, "r") as f: text = f.read() structure = json_decode(text) else: structure = {} # Attributes and Children used to be merged, support this attributes = structure.get("attributes", structure) children = structure.get("children", structure) # Set the layout table name, mri, x, y, visible = [], [], [], [], [] for part_name, d in attributes.get("layout", {}).items(): name.append(part_name) mri.append("") x.append(d["x"]) y.append(d["y"]) visible.append(d["visible"]) self.set_layout(LayoutTable(name, mri, x, y, visible)) # Set the exports table source, export = [], [] for source_name, export_name in attributes.get("exports", {}).items(): source.append(source_name) export.append(export_name) self.exports.set_value(ExportTable(source, export)) # Set other attributes our_values = { k: v for k, v in attributes.items() if k in self.our_config_attributes } block = self.block_view() block.put_attribute_values(our_values) # Run the load hook to get parts to load their own structure self.run_hooks( LoadHook(p, c, children.get(p.name, {}), init) for p, c in self.create_part_contexts(only_visible=False).items()) self._mark_clean(design, init)
def on_message(self, message): """Pass response from server to process receive queue Args: message(str): Received message """ # Called in tornado loop try: self.log.debug("Got message %s", message) d = json_decode(message) response = deserialize_object(d, Response) if isinstance(response, (Return, Error)): request = self._request_lookup.pop(response.id) if isinstance(response, Error): # Make the message an exception so it can be raised response.message = ResponseError(response.message) else: request = self._request_lookup[response.id] # Transfer the work of the callback to cothread cothread.Callback(request.callback, response) except Exception: # If we don't catch the exception here, tornado will spew odd # error messages about 'HTTPRequest' object has no attribute 'path' self.log.exception("on_message(%r) failed", message)
def test_json_decode_not_dict(self): with self.assertRaises(ValueError): json_decode('[1, 2]')
def test_json_decode(self): d = json_decode('{"a": 1, "b": 2}') assert list(d) == ["a", "b"] assert d.values() == [1, 2]