def saveToDisk(self): """Saves the data to disk.""" out.info("Saving to disk (%s)\n" % (self.filename)) # Make sure they want to save if not self.attrSaveable(): return # Get whatever the data is pyld = self.exportAttr(self.getAttr()) # Write the file to disk, truncate if it exists try: pickle.dump(pyld, pdos.open(self.filename, "wb")) pdos.syncFS() except Exception as e: out.err("Error writing to disk %s\n" % (str(e)))
def loadFromDisk(self): """Attempts to load the data from disk. Returns True if success, False otherwise.""" if (pdos.exists(self.filename)): deleteFile = False try: pyld = pickle.load(pdos.open(self.filename, 'rb')) self.setAttr(self.importAttr(pyld)) return True except Exception as e: out.err('Error loading from disk: %s\n' % (str(e))) deleteFile = True # Delete the file if (deleteFile): try: pdos.unlink(self.filename) except Exception as e: out.err('Error unlinking %s\n' % (self.filename)) return False
def loadFromDisk(self): """Attempts to load the data from disk. Returns True if success, False otherwise.""" if(pdos.exists(self.filename)): deleteFile = False try: pyld = pickle.load(pdos.open(self.filename, 'rb')) self.setAttr(self.importAttr(pyld)) return True except Exception as e: out.err('Error loading from disk: %s\n' % (str(e))) deleteFile = True # Delete the file if(deleteFile): try: pdos.unlink(self.filename) except Exception as e: out.err('Error unlinking %s\n' % (self.filename)) return False
def readConfig(self): """Reads in the config file.""" def correctStr(line): return " ".join(line.split()) lines = [] try: fd = pdos.open(self.filepath, 'r') while(True): line = fd.readline() if(not line): break lines.append(line) fd.close() except Exception as e: out.err('Error reading file %s: %s\n' % (self.filepath, str(e))) raise e cfg = None opt = None data = [] # Now we have the data, deal with it for line in lines: line = line.rstrip() # If comment ignore if(line.startswith('#')): continue # First make all lines have correct whitespace # FIXME: if there is a space WITHIN quotes this kills it! # this could come up as a key in an encryption key line = correctStr(line) l = getLineParts(line) # # Config # #print("l: %s" % l) if(l[0] == 'config'): # Save last config we had if(cfg and opt): data.append((cfg, opt)) # start a new config cfg = {'type': l[1]} # Third element can be comment or name if(len(l) == 3): if (l[2].startswith('#')): cfg['comment'] = l[2][1:] else: cfg['name'] = l[2] elif (len(l) == 4): # Four elements, so third is name and 4th is comment cfg['name'] = l[2] cfg['comment'] = l[3][1:] opt = {} # # Options # elif(l[0] == 'option'): opt[l[1]] = l[2] # # List # elif(l[0] == 'list'): # Make sure there is a list key if('list' not in opt.keys()): opt['list'] = {} if(l[1] in opt['list'].keys()): opt['list'][l[1]].append(l[2]) else: opt['list'][l[1]] = [l[2]] else: # Also at the end of the loop, save the final config we were making # Make sure cfg,opt aren't None if(None not in (cfg, opt)): data.append((cfg, opt)) return data
def save(self, backupToken=None, internalid=None): """ Saves out the file in the proper format. Arguments: [backupPath] : Save a backup copy of the UCI file to the path provided. Should be a token name like 'backup', it gets appended with a hyphen. """ # Save original copy if(backupToken): self.backup(backupToken) output = "" # Now generate what the file would look like for c, o in self.config: #print("c: %s\n" % c.keys()) line = "config %s" % c['type'] # Check for optional name if('name' in c.keys()): line += " %s" % c['name'] if('comment' in c.keys()): line += " #%s" % c['comment'] output += "%s\n" % line # Get options # check for lists first, if they exist remove them first if('list' in o.keys()): theLists = o['list'] else: theLists = None # Now process everything else quick for k,v in o.iteritems(): # Make sure we skip the lists key if(k != 'list'): line = "\toption %s '%s'\n" % (k,v) output += line # Now process the list if(theLists): # theLists is a dict where the key is each list name # and the value is a list of the options we need to include for k,v in theLists.iteritems(): # so @v here is a list for vals in v: # Now append a list set to the config line = "\tlist %s '%s'\n" % (k, vals) output += line # Now add one extra newline before the next set output += "\n" # Now write to disk try: out.info('Saving %s to disk\n' % (self.filepath)) fd = pdos.open(self.filepath, 'w') fd.write(output) # Guarantee that its written to disk before we close fd.flush() os.fsync(fd.fileno()) fd.close() except Exception as e: out.err('Unable to save new config %s, %s\n' % (self.filepath, str(e))) out.err('Config may be corrupted, backup exists at /tmp/%s\n' % (self.myname))
def readConfig(self): """Reads in the config file.""" lines = [] try: fd = pdos.open(self.filepath, 'r') while(True): line = fd.readline() if(not line): break lines.append(line) fd.close() except Exception as e: out.err('Error reading file %s: %s\n' % (self.filepath, str(e))) raise e cfg = None opt = None data = [] # Now we have the data, deal with it for line in lines: line = line.strip() # If comment ignore if line.startswith('#'): continue l = getLineParts(line) # # Config # if(l[0] == 'config'): # Save last config we had if(cfg and opt): data.append((cfg, opt)) # start a new config cfg = {'type': l[1]} # Third element can be comment or name if(len(l) == 3): if (l[2].startswith('#')): cfg['comment'] = l[2][1:] else: cfg['name'] = l[2] elif (len(l) == 4): # Four elements, so third is name and 4th is comment cfg['name'] = l[2] cfg['comment'] = l[3][1:] opt = {} # # Options # elif(l[0] == 'option'): opt[l[1]] = l[2] # # List # elif(l[0] == 'list'): # Make sure the key exists and is a list. if l[1] not in opt: opt[l[1]] = [] elif not isinstance(opt[l[1]], list): # One line started with "option", another with "list". If # this is supposed to be a list, they should all start with # "list". raise Exception("Malformed UCI: mixed list/option lines") opt[l[1]].append(l[2]) else: # Also at the end of the loop, save the final config we were making # Make sure cfg,opt aren't None if(None not in (cfg, opt)): data.append((cfg, opt)) return data
def save(self, backupToken="paradrop", internalid=None): """ Saves out the file in the proper format. Arguments: [backupPath] : Save a backup copy of the UCI file to the path provided. Should be a token name like 'backup', it gets appended with a hyphen. """ # Save original copy if(backupToken): self.backup(backupToken) output = "" output += "#" * 80 + "\n" output += "# Configuration file generated by paradrop-daemon\n".format(self.myname) output += "# Path: {}\n".format(self.filepath) output += "# Package: {}\n".format(self.myname) output += "#" * 80 + "\n" output += "\n" # Now generate what the file would look like for c, o in self.config: line = "config %s" % c['type'] # Check for optional name if 'name' in c: line += " %s" % c['name'] if 'comment' in c: line += " #%s" % c['comment'] output += "%s\n" % line for k, v in six.iteritems(o): if isinstance(v, list): # For list-valued options, emit one line for each item # in the list. for vals in v: # Now append a list set to the config line = "\tlist %s '%s'\n" % (k, vals) output += line # Skip options that are None rather than writing "None". elif v is not None: sv = stringifyOptionValue(v) line = "\toption %s '%s'\n" % (k, sv) output += line # Now add one extra newline before the next set output += "\n" # Now write to disk try: out.info('Saving %s to disk\n' % (self.filepath)) fd = pdos.open(self.filepath, 'w') fd.write(output) # Guarantee that its written to disk before we close fd.flush() os.fsync(fd.fileno()) fd.close() except Exception as e: out.err('Unable to save new config %s, %s\n' % (self.filepath, str(e))) out.err('Config may be corrupted, backup exists at /tmp/%s\n' % (self.myname))