def get(self, id, return_list=False): req = CtrlReq() req.type = CtrlReq.GET if self.prefix: id = self.prefix + '.' + id req.id = id rep = self._send_and_recv(req) if rep.status != 0: raise KeyError(id) pairs = [] for pair in rep.pairs: for type in self.map.values(): if pair.val.HasField(type): val = getattr(pair.val, type) if type == 'str_val': val = val.encode('ascii') pairs.append((pair.id.encode('ascii'), val)) break if len(pairs) == 0: return elif len(pairs) == 1: if return_list: return pairs[0] else: return pairs[0][1] else: return pairs
def get(self, id, return_list = False): req = CtrlReq() req.type = CtrlReq.GET if self.prefix: id = self.prefix + '.' + id req.id = id rep = self._send_and_recv(req) if rep.status != 0: raise KeyError(id) pairs = [] for pair in rep.pairs: for type in self.map.values(): if pair.val.HasField(type): val = getattr(pair.val, type) if type == 'str_val': val = val.encode('ascii') pairs.append((pair.id.encode('ascii'), val)) break if len(pairs) == 0: return elif len(pairs) == 1: if return_list: return pairs[0] else: return pairs[0][1] else: return pairs
def set(self, id, val): req = CtrlReq() req.type = CtrlReq.SET if self.prefix: id = self.prefix + '.' + id req.id = id setattr(req.val, self.map[val.__class__], val) rep = self._send_and_recv(req) if rep.status != 0: raise KeyError(id)
def run(self): while True: # read and parse request: req = CtrlReq() try: req.ParseFromString(self.ctrl_socket.recv()) except Exception, e: log(LL_ERROR, 'could not receive request: %s' % str(e)) sleep(1) continue # process request and prepare reply: rep = CtrlRep() rep.status = CtrlRep.OK try: # GET REQUEST: if req.type == CtrlReq.GET: all_keys = self.conf.get_all_keys( self.conf.base) + ['platform'] if req.id in all_keys: # exact match: self._pairs_add(req.id, rep) else: # try regex matches: found = False for key in all_keys: try: if match(req.id, key): self._pairs_add(key, rep) found = True except: pass if not found: log(LL_ERROR, 'key not found: %s' % req.id) rep.status = CtrlRep.PARAM_UNKNOWN # SET REQUEST: elif req.type == CtrlReq.SET: try: for type, attr in self.map.items(): if req.val.HasField(attr): val = getattr(req.val, attr) self.conf.set(req.id.encode('ascii'), type(val)) break pair = Pair(id=req.id, val=req.val) self.event_socket.send(pair.SerializeToString()) except ConfigError, e: log(LL_ERROR, 'key not found: %s' % req.id) rep.status = CtrlRep.PARAM_UNKNOWN # PERSIST REQUEST: else:
def persist(self): req = CtrlReq() req.type = CtrlReq.PERSIST return self._send_and_recv(req).status