Example #1
0
 def testUnlink(self):
     # should not raise an exception
     helpers.Unlink('./nonexistantfile')
     tmp = tempfile.NamedTemporaryFile(dir=self.tmpdir, delete=False)
     self.assertTrue(os.stat(tmp.name))
     helpers.Unlink(tmp.name)
     self.assertRaises(OSError, os.stat, tmp.name)
Example #2
0
def _DeleteOldSock(family, address):
    tsock = socket.socket(family, socket.SOCK_STREAM, 0)
    try:
        tsock.connect(address)
    except socket.error, e:
        if e.errno == errno.ECONNREFUSED:
            helpers.Unlink(address)
Example #3
0
    def _WriteFile(self, obj, value):
        """Writes the data out the file. The file is updated at idle time."""

        # First write a .tmp file.  We do this to catch exceptions where the
        # directory doesn't exist or permission issues etc.  Once we write a
        # tmp file, _ReallyWriteFile will schedule to rename the tmp file to the
        # real file.  This can still fail if we don't have permission to the actual
        # file but we have permission to the directory, but that seems less likely
        # then the directory just not existing.
        #
        tmpname = self.GetFileName(obj) + '.tmp'
        if value in [None, '']:
            if self.delete_if_empty:
                helpers.Unlink(tmpname)
            else:
                helpers.WriteFileAtomic(tmpname,
                                        '',
                                        owner=self.file_owner,
                                        group=self.file_group)
        else:
            data = unicode(value).rstrip().encode('utf-8') + '\n'
            helpers.WriteFileAtomic(tmpname,
                                    data,
                                    owner=self.file_owner,
                                    group=self.file_group)
        self._ReallyWriteFile(obj)
Example #4
0
 def _ReallyWriteFile(self, obj):
     filename = self.GetFileName(obj)
     try:
         os.rename(filename + '.tmp', filename)
     except OSError as e:
         if e.errno == errno.ENOENT:
             helpers.Unlink(filename)
         else:
             raise
Example #5
0
    def Triggered(self):
        """Triggered whenever Requested is changed."""

        # Flush old experiments
        keys = self.saved_values.keys()
        lookups = self.roothandle.inner.LookupExports(keys)
        for k, (h, param) in zip(keys, lookups):
            h.SetExportParam(param, self.saved_values[k])
        del self.active[:]
        self.force_values.clear()
        self.saved_values.clear()

        # TODO(apenwarr): use transactions like api.SetParameterValues() does.
        print 'Experiments requested: %r' % self.Requested
        sysactive = _GetSystemExperiments(ACTIVEDIR, '.active')
        sysrequested = _GetSystemExperiments(ACTIVEDIR, '.requested')

        reqstr = self.Requested
        requested = reqstr.split(',') if reqstr else []
        for name in requested:
            expfunc = registered.get(name)
            if not expfunc:
                if re.findall(r'[^A-Za-z0-9_-]', name):
                    print 'Invalid characters in experiment %r' % name
                elif len(name) > MAX_EXPERIMENT_NAME_LENGTH:
                    print(
                        'Experiment %r length %r is greater than the maximum '
                        'allowed length %r' %
                        (name, len(name), MAX_EXPERIMENT_NAME_LENGTH))
                elif len(os.listdir(ACTIVEDIR)) >= MAX_FILE_NUMBER:
                    print(
                        'Unable to request system experiment, too many files in '
                        '%r' % ACTIVEDIR)
                else:
                    print 'Requesting system experiment %r' % name
                    helpers.Unlink(
                        os.path.join(ACTIVEDIR, name + '.unrequested'))
                    if not os.path.exists(
                            os.path.join(ACTIVEDIR, name + '.active')):
                        helpers.WriteFileAtomic(
                            os.path.join(ACTIVEDIR, name + '.requested'), '')
            else:
                print 'Applying experiment %r' % name
                forces = list(expfunc(self.roothandle))
                self.force_values.update(forces)
                keys = [f[0] for f in forces]
                lookups = list(self.roothandle.inner.LookupExports(keys))
                for (k, _), (h, param) in zip(forces, lookups):
                    if k not in self.saved_values:
                        print '  Saving pre-experiment value for %r' % k
                        self.saved_values[k] = h.GetExport(param)
                for (k, v), (h, param) in zip(forces, lookups):
                    print '  Writing new value for %r = %r' % (k, v)
                    h.SetExportParam(param, v)
                self.active.append((name, forces))

        for name in sysactive | sysrequested:
            if name not in requested:
                print 'Unrequesting system experiment %r' % name
                helpers.Unlink(os.path.join(ACTIVEDIR, name + '.requested'))
                if os.path.exists(os.path.join(ACTIVEDIR, name + '.active')):
                    helpers.WriteFileAtomic(
                        os.path.join(ACTIVEDIR, name + '.unrequested'), '')

        self._AnnounceActives()
Example #6
0
    def state_machine(self,
                      event,
                      faultcode=0,
                      faultstring='',
                      downloaded_file=None,
                      must_reboot=False):
        dlstate = self.stateobj.dlstate
        if dlstate == self.START:
            if event == self.EV_START or event == self.EV_REBOOT_COMPLETE:
                self.stateobj.Update(dlstate=self.WAITING)
                self._schedule_timer()

        elif dlstate == self.WAITING:
            if event == self.EV_TIMER:
                self.download = self._new_download_object(self.stateobj)
                self.stateobj.Update(dlstate=self.DOWNLOADING,
                                     download_start_time=time.time())
                self.download.fetch()
                # TODO(dgentry) : need a timeout, in case download never finishes.

        elif dlstate == self.DOWNLOADING:
            if event == self.EV_DOWNLOAD_COMPLETE:
                self.download = None  # no longer needed
                if faultcode == 0:
                    self.installer = INSTALLER(downloaded_file)
                    self.stateobj.Update(dlstate=self.INSTALLING)
                    file_type = getattr(self.stateobj, 'file_type', None)
                    target_filename = getattr(self.stateobj, 'target_filename',
                                              None)
                    self.installer.install(file_type=file_type,
                                           target_filename=target_filename,
                                           callback=self.installer_callback)
                else:
                    self.stateobj.Update(dlstate=self.EXITING)
                    self._send_transfer_complete(faultcode, faultstring)

        elif dlstate == self.INSTALLING:
            if event == self.EV_INSTALL_COMPLETE:
                if self.downloaded_file:
                    helpers.Unlink(self.downloaded_file)
                if faultcode == 0:
                    if must_reboot:
                        self.stateobj.Update(dlstate=self.REBOOTING)
                        self.installer.reboot()
                    else:
                        end = time.time()
                        self.stateobj.Update(dlstate=self.EXITING,
                                             download_complete_time=end)
                        start = getattr(self.stateobj, 'download_start_time',
                                        0.0)
                        self._send_transfer_complete(faultcode=0,
                                                     faultstring='',
                                                     start=start,
                                                     end=end)
                else:
                    self.stateobj.Update(dlstate=self.EXITING)
                    self._send_transfer_complete(faultcode, faultstring)

        elif dlstate == self.REBOOTING:
            if event == self.EV_REBOOT_COMPLETE:
                # TODO(dgentry) check version, whether image was actually installed
                end = time.time()
                self.stateobj.Update(dlstate=self.EXITING,
                                     download_complete_time=end)
                if faultcode == 0:
                    start = getattr(self.stateobj, 'download_start_time', 0.0)
                    self._send_transfer_complete(faultcode=0,
                                                 faultstring='',
                                                 start=start,
                                                 end=end)
                else:
                    self._send_transfer_complete(faultcode, faultstring)

        elif dlstate == self.EXITING:
            pass
Example #7
0
 def __del__(self):
     #print 'deleting listener: %r' % (self.address,)
     ht.logger.info('deleting listener: %r' % (self.address, ))
     if self.family == socket.AF_UNIX and self.sock:
         self.sock.close()
         helpers.Unlink(self.address)