コード例 #1
0
ファイル: pickling.py プロジェクト: smok-serwis/smok-client
 def __init__(self, cache_path: str, data_path: str):
     super().__init__(cache_path)
     self.data_path = data_path
     self.dirty = False
     if os.path.exists(self.data_path):
         with open(self.data_path,
                   'rb') as f_in, silence_excs(pickle.PickleError):
             self.events, self.events_to_sync = pickle.load(f_in)
コード例 #2
0
ファイル: in_memory.py プロジェクト: smok-serwis/smok-client
    def acknowledge(self, *uuids: str) -> None:
        for event, uuid in zip(self.events, uuids):
            if event.uuid is None:
                event.uuid = uuid

            if event.is_closed():
                with Monitor.acquire(self.event_db), silence_excs(ValueError):
                    self.events.remove(event)
コード例 #3
0
ファイル: pickling.py プロジェクト: smok-serwis/smok-client
    def __init__(self, path):
        super().__init__()
        self.__path = path

        if os.path.exists(self.__path):
            with open(self.__path,
                      'rb') as f_in, silence_excs(pickle.PickleError):
                self.macros_to_execute, self.executions_to_sync = pickle.load(
                    f_in)
コード例 #4
0
    def __init__(self):
        super().__init__()
        atexit.register(self.close)
        self.volumes = {}  # type: tp.Dict[str, Volume]

        with silence_excs(OSError):
            data = read_json_from_file(STATE_FILE)
            for vol in data:
                volume = Volume.load_from_dict(vol)
                self.add_volume(volume)
コード例 #5
0
 def sync_pathpoints(self) -> None:
     pps = self.device.pathpoints.copy_and_clear_dirty()
     data = pathpoints_to_json(pps.values())
     try:
         resp = self.device.api.put('/v1/device/pathpoints', json=data)
         for pp in resp:
             name = pp['path']
             if name.startswith('r'):  # Don't use reparse pathpoints
                 continue
             with silence_excs(KeyError):
                 pathpoint = self.device.provide_unknown_pathpoint(
                     name, StorageLevel(pp.get('storage_level', 1)))
                 stor_level = StorageLevel(pp.get('storage_level', 1))
                 if stor_level != pathpoint.storage_level:
                     pathpoint.on_new_storage_level(stor_level)
         self.device.on_successful_sync()
     except ResponseError as e:
         if e.is_no_link():
             self.device.on_failed_sync()
         self.device.pathpoints.update(pps)
         self.device.pathpoints.dirty = True
         raise
コード例 #6
0
def start_all_socats(config_file: str, verbose: bool = False) -> None:
    processes_and_args = []

    for i, proto, host1, port1, host2, port2 in smart_enumerate(
            parse_etc_socatlord(config_file)):
        command = [
            'socat',
            '%s-listen:%s,bind=%s,reuseaddr,fork' % (proto, port1, host1),
            '%s:%s:%s' % (proto, host2, port2)
        ]
        kwargs = {
            'stdin': subprocess.DEVNULL,
            'stdout': subprocess.DEVNULL,
            'stderr': subprocess.DEVNULL
        }
        if verbose:
            print('Calling %s' % (command, ))
            kwargs = {}
        proc = subprocess.Popen(command, **kwargs)
        processes_and_args.append((proc, command))
        write_to_file(os.path.join('/var/run/socatlord', str(i)),
                      str(proc.pid), 'utf-8')

    if verbose:
        print('All socats launched, checking for liveness...')
    time.sleep(1)

    for i, proc, cmd in smart_enumerate(processes_and_args):
        with silence_excs(subprocess.TimeoutExpired):
            proc.wait(timeout=0.0)
            rc = proc.returncode
            print(
                'socat no %s (PID %s) died (RC=%s), command was "%s", aborting'
                % (i + 1, proc.pid, rc, cmd))
            os.unlink(os.path.join('/var/run/socatlord', str(i)))
            sys.exit(1)

    if verbose:
        print('All socats alive, finishing successfully')
コード例 #7
0
    def sync_sections(self):
        print('Sections synchronized')


if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG)
    logging.getLogger('urllib3.connectionpool').setLevel(logging.WARN)
    sd = MyDevice()
    handler = SMOKLogHandler(sd, 'client')
    logging.getLogger().addHandler(handler)
    logging.getLogger().addHandler(logging.StreamHandler(sys.stderr))
    assert sd.device_id == 'skylab'
    assert sd.environment == Environment.STAGING
    print(repr(sd.get_device_info()))
    sd.instrumentation = '{"ok": True}'
    a = PP(sd, 'W2')
    sd.register_statistic(CustomPredicate, lambda stat, cfg: stat == 'my_statistic')
    sd.wait_until_synced()
    n_tn_run = int(sd.metadata.get('n_th.run', '0'))
    n_tn_run += 1
    print('This is the %s-th run' % (n_tn_run, ))
    sd.metadata['n_th.run'] = n_tn_run
    sen = sd.get_sensor('val')
    sd.get_slaves()[0].linkstate = {'status': True}
    assert sd.get_slaves()[0].linkstate == {'status': True}, 'Invalid linkstate!'
    while True:
        with silence_excs(NotReadedError):
            time.sleep(10)
            print(sen.get()[1])
            break
コード例 #8
0
ファイル: pickling.py プロジェクト: smok-serwis/smok-client
 def get_all_keys(self):
     set_f = set(os.listdir(self.__path))
     with silence_excs(KeyError):
         set_f.remove('metadata.pkl')
     return iter(set_f)
コード例 #9
0
ファイル: test_rethrow.py プロジェクト: piotrmaslanka/satella
 def test_silencer(self):
     with silence_excs(TypeError):
         raise TypeError()