after_merge
stringlengths
28
79.6k
before_merge
stringlengths
20
79.6k
url
stringlengths
38
71
full_traceback
stringlengths
43
922k
traceback_type
stringclasses
555 values
def __init__(self, schedulers, durations, save_history=False): if not isinstance(schedulers, Sequence) or len(schedulers) < 2: raise ValueError( "Argument schedulers should be a sequence of more than one parameter schedulers, " "but given {}".format(schedulers) ) if not isinstance(durations, Sequence) or not all( [isinstance(t, numbers.Integral) for t in durations] ): raise ValueError( "Argument durations should be list/tuple of integers, but given {}".format( durations ) ) if len(schedulers) != len(durations) + 1: raise ValueError( "Incorrect number schedulers or duration values, given {} and {}".format( len(schedulers), len(durations) ) ) for i, scheduler in enumerate(schedulers): if not isinstance(scheduler, ParamScheduler): raise TypeError( "Value at index {} of schedulers should be a parameter scheduler, " "but given {}".format(i, type(scheduler)) ) self.schedulers = schedulers self.durations = durations self.optimizer = self.schedulers[0].optimizer if not (all(id(s.optimizer) == id(self.optimizer) for s in self.schedulers)): raise ValueError("schedulers should be related to same optimizer") # schedulers should have save_history sync with ParamGroupScheduler for s in schedulers: s.save_history = save_history super(ConcatScheduler, self).__init__( optimizer=self.optimizer, param_name="", save_history=save_history ) self._scheduler_index = 0 self._current_scheduler = None self._current_duration = None self._setup_scheduler() self._state_attrs += ["_current_duration", "durations", "_scheduler_index"]
def __init__(self, schedulers, durations, save_history=False): if not isinstance(schedulers, Sequence) or len(schedulers) < 2: raise ValueError( "Argument schedulers should be a sequence of more than one parameter schedulers, " "but given {}".format(schedulers) ) if not isinstance(durations, Sequence) or not all( [isinstance(t, numbers.Integral) for t in durations] ): raise ValueError( "Argument durations should be list/tuple of integers, but given {}".format( durations ) ) if len(schedulers) != len(durations) + 1: raise ValueError( "Incorrect number schedulers or duration values, given {} and {}".format( len(schedulers), len(durations) ) ) for i, scheduler in enumerate(schedulers): if not isinstance(scheduler, ParamScheduler): raise TypeError( "Value at index {} of schedulers should be a parameter scheduler, " "but given {}".format(i, type(scheduler)) ) self.schedulers = schedulers self.durations = durations super(ConcatScheduler, self).__init__( optimizer=_get_fake_optimizer(), param_name="", save_history=save_history ) self._scheduler_index = 0 self._current_scheduler = None self._current_duration = None self._setup_scheduler() self._state_attrs += ["_current_duration", "durations", "_scheduler_index"]
https://github.com/pytorch/ignite/issues/813
Traceback (most recent call last): File "tutorials/misc/lr_schedulers.py", line 56, in <module> lr_values = LRScheduler.simulate_values(num_events=50, lr_scheduler=lr_scheduler) File "/work/desrozis/Softwares/conda/envs/focus-light/lib/python3.7/site-packages/ignite/contrib/handlers/param_scheduler.py", line 606, in simulate_values copy_lr_scheduler = LRScheduler._replicate_lr_scheduler(lr_scheduler) File "/work/desrozis/Softwares/conda/envs/focus-light/lib/python3.7/site-packages/ignite/contrib/handlers/param_scheduler.py", line 627, in _replicate_lr_scheduler copy_lr_scheduler = lr_scheduler_cls(optimizer=dummy_optimizer, **kwargs) TypeError: __init__() got an unexpected keyword argument 'T_i'
TypeError
def simulate_values(cls, num_events, schedulers, durations, param_names=None, **kwargs): """Method to simulate scheduled values during num_events events. Args: num_events (int): number of events during the simulation. schedulers (list of ParamScheduler): list of parameter schedulers. durations (list of int): list of number of events that lasts a parameter scheduler from schedulers. param_names (list or tuple of str, optional): parameter name or list of parameter names to simulate values. By default, the first scheduler's parameter name is taken. Returns: list of [event_index, value_0, value_1, ...], where values correspond to `param_names`. """ if param_names is not None and not isinstance(param_names, (list, tuple)): raise ValueError("Argument param_names should be list or tuple of strings") # This scheduler uses `ParamScheduler` which # should be replicated in order to simulate LR values and # not perturb original scheduler. with tempfile.TemporaryDirectory() as tmpdirname: cache_filepath = Path(tmpdirname) / "ignite_lr_scheduler_cache.pt" objs = { "lr_scheduler_{}".format(i): s.state_dict() for i, s in enumerate(schedulers) } # all schedulers should be related to the same optimizer objs["optimizer"] = schedulers[0].optimizer.state_dict() torch.save(objs, cache_filepath.as_posix()) # do not save_history for s in schedulers: s.save_history = False output = [] scheduler = cls( schedulers=schedulers, save_history=False, durations=durations, **kwargs ) if param_names is None: param_names = [scheduler.param_name] for i in range(num_events): scheduler(engine=None) values = [i] for param_name in param_names: params = [p[param_name] for p in scheduler.optimizer_param_groups] values = values + params output.append(values) objs = torch.load(cache_filepath.as_posix()) for i, s in enumerate(schedulers): s.load_state_dict(objs["lr_scheduler_{}".format(i)]) s.optimizer.load_state_dict(objs["optimizer"]) return output
def simulate_values(cls, num_events, schedulers, durations, param_names=None, **kwargs): """Method to simulate scheduled values during num_events events. Args: num_events (int): number of events during the simulation. schedulers (list of ParamScheduler): list of parameter schedulers. durations (list of int): list of number of events that lasts a parameter scheduler from schedulers. param_names (list or tuple of str, optional): parameter name or list of parameter names to simulate values. By default, the first scheduler's parameter name is taken. Returns: list of [event_index, value_0, value_1, ...], where values correspond to `param_names`. """ if param_names is not None and not isinstance(param_names, (list, tuple)): raise ValueError("Argument param_names should be list or tuple of strings") output = [] # Need to copy all schedulers otherwise unsafe copy_schedulers = [_replicate_scheduler(s) for s in schedulers] scheduler = cls(copy_schedulers, durations, save_history=False) if param_names is None: param_names = [scheduler.param_name] for i in range(num_events): scheduler(engine=None) values = [i] for param_name in param_names: params = [p[param_name] for p in scheduler.optimizer_param_groups] values = values + params output.append(values) return output
https://github.com/pytorch/ignite/issues/813
Traceback (most recent call last): File "tutorials/misc/lr_schedulers.py", line 56, in <module> lr_values = LRScheduler.simulate_values(num_events=50, lr_scheduler=lr_scheduler) File "/work/desrozis/Softwares/conda/envs/focus-light/lib/python3.7/site-packages/ignite/contrib/handlers/param_scheduler.py", line 606, in simulate_values copy_lr_scheduler = LRScheduler._replicate_lr_scheduler(lr_scheduler) File "/work/desrozis/Softwares/conda/envs/focus-light/lib/python3.7/site-packages/ignite/contrib/handlers/param_scheduler.py", line 627, in _replicate_lr_scheduler copy_lr_scheduler = lr_scheduler_cls(optimizer=dummy_optimizer, **kwargs) TypeError: __init__() got an unexpected keyword argument 'T_i'
TypeError
def __init__(self, lr_scheduler, save_history=False, **kwargs): if not isinstance(lr_scheduler, _LRScheduler): raise TypeError( "Argument lr_scheduler should be a subclass of torch.optim.lr_scheduler._LRScheduler, " "but given {}".format(type(lr_scheduler)) ) self.lr_scheduler = lr_scheduler super(LRScheduler, self).__init__( optimizer=self.lr_scheduler.optimizer, param_name="lr", save_history=save_history, ) self._state_attrs += [ "lr_scheduler", ]
def __init__(self, lr_scheduler, save_history=False, **kwds): if not isinstance(lr_scheduler, _LRScheduler): raise TypeError( "Argument lr_scheduler should be a subclass of torch.optim.lr_scheduler._LRScheduler, " "but given {}".format(type(lr_scheduler)) ) self.lr_scheduler = lr_scheduler super(LRScheduler, self).__init__( optimizer=self.lr_scheduler.optimizer, param_name="lr", save_history=save_history, ) self._state_attrs += [ "lr_scheduler", ]
https://github.com/pytorch/ignite/issues/813
Traceback (most recent call last): File "tutorials/misc/lr_schedulers.py", line 56, in <module> lr_values = LRScheduler.simulate_values(num_events=50, lr_scheduler=lr_scheduler) File "/work/desrozis/Softwares/conda/envs/focus-light/lib/python3.7/site-packages/ignite/contrib/handlers/param_scheduler.py", line 606, in simulate_values copy_lr_scheduler = LRScheduler._replicate_lr_scheduler(lr_scheduler) File "/work/desrozis/Softwares/conda/envs/focus-light/lib/python3.7/site-packages/ignite/contrib/handlers/param_scheduler.py", line 627, in _replicate_lr_scheduler copy_lr_scheduler = lr_scheduler_cls(optimizer=dummy_optimizer, **kwargs) TypeError: __init__() got an unexpected keyword argument 'T_i'
TypeError
def simulate_values(cls, num_events, lr_scheduler, **kwargs): """Method to simulate scheduled values during num_events events. Args: num_events (int): number of events during the simulation. lr_scheduler (subclass of `torch.optim.lr_scheduler._LRScheduler`): lr_scheduler object to wrap. Returns: list of pairs: [event_index, value] """ if not isinstance(lr_scheduler, _LRScheduler): raise TypeError( "Argument lr_scheduler should be a subclass of torch.optim.lr_scheduler._LRScheduler, " "but given {}".format(type(lr_scheduler)) ) # This scheduler uses `torch.optim.lr_scheduler._LRScheduler` which # should be replicated in order to simulate LR values and # not perturb original scheduler. with tempfile.TemporaryDirectory() as tmpdirname: cache_filepath = Path(tmpdirname) / "ignite_lr_scheduler_cache.pt" obj = { "lr_scheduler": lr_scheduler.state_dict(), "optimizer": lr_scheduler.optimizer.state_dict(), } torch.save(obj, cache_filepath.as_posix()) values = [] scheduler = cls(save_history=False, lr_scheduler=lr_scheduler, **kwargs) for i in range(num_events): params = [p[scheduler.param_name] for p in scheduler.optimizer_param_groups] values.append([i] + params) scheduler(engine=None) obj = torch.load(cache_filepath.as_posix()) lr_scheduler.load_state_dict(obj["lr_scheduler"]) lr_scheduler.optimizer.load_state_dict(obj["optimizer"]) return values
def simulate_values(cls, num_events, lr_scheduler, **kwargs): """Method to simulate scheduled values during num_events events. Args: num_events (int): number of events during the simulation. lr_scheduler (subclass of `torch.optim.lr_scheduler._LRScheduler`): lr_scheduler object to wrap. Returns: list of pairs: [event_index, value] """ # This scheduler uses `torch.optim.lr_scheduler._LRScheduler` which # should be replicated in order to simulate LR values and # not perturb original scheduler. copy_lr_scheduler = LRScheduler._replicate_lr_scheduler(lr_scheduler) values = [] scheduler = cls(save_history=False, lr_scheduler=copy_lr_scheduler) for i in range(num_events): params = [p[scheduler.param_name] for p in scheduler.optimizer_param_groups] values.append([i] + params) scheduler(engine=None) return values
https://github.com/pytorch/ignite/issues/813
Traceback (most recent call last): File "tutorials/misc/lr_schedulers.py", line 56, in <module> lr_values = LRScheduler.simulate_values(num_events=50, lr_scheduler=lr_scheduler) File "/work/desrozis/Softwares/conda/envs/focus-light/lib/python3.7/site-packages/ignite/contrib/handlers/param_scheduler.py", line 606, in simulate_values copy_lr_scheduler = LRScheduler._replicate_lr_scheduler(lr_scheduler) File "/work/desrozis/Softwares/conda/envs/focus-light/lib/python3.7/site-packages/ignite/contrib/handlers/param_scheduler.py", line 627, in _replicate_lr_scheduler copy_lr_scheduler = lr_scheduler_cls(optimizer=dummy_optimizer, **kwargs) TypeError: __init__() got an unexpected keyword argument 'T_i'
TypeError
def create_lr_scheduler_with_warmup( lr_scheduler, warmup_start_value, warmup_duration, warmup_end_value=None, save_history=False, output_simulated_values=None, ): """ Helper method to create a learning rate scheduler with a linear warm-up. Args: lr_scheduler (ParamScheduler or subclass of `torch.optim.lr_scheduler._LRScheduler`): learning rate scheduler after the warm-up. warmup_start_value (float): learning rate start value of the warm-up phase. warmup_duration (int): warm-up phase duration, number of events. warmup_end_value (float): learning rate end value of the warm-up phase, (default=None). If None, warmup_end_value is set to optimizer initial lr. save_history (bool, optional): whether to log the parameter values to `engine.state.param_history`, (default=False). output_simulated_values (list, optional): optional output of simulated learning rate values. If output_simulated_values is a list of None, e.g. `[None] * 100`, after the execution it will be filled by 100 simulated learning rate values. Returns: ConcatScheduler: learning rate scheduler with linear warm-up. Note: If the first learning rate value provided by `lr_scheduler` is different from `warmup_end_value`, an additional event is added after the warm-up phase such that the warm-up ends with `warmup_end_value` value and then `lr_scheduler` provides its learning rate values as normally. Examples: .. code-block:: python torch_lr_scheduler = ExponentialLR(optimizer=optimizer, gamma=0.98) lr_values = [None] * 100 scheduler = create_lr_scheduler_with_warmup(torch_lr_scheduler, warmup_start_value=0.0, warmup_end_value=0.1, warmup_duration=10, output_simulated_values=lr_values) lr_values = np.array(lr_values) # Plot simulated values plt.plot(lr_values[:, 0], lr_values[:, 1], label="learning rate") # Attach to the trainer trainer.add_event_handler(Events.ITERATION_STARTED, scheduler) """ if not isinstance(lr_scheduler, (ParamScheduler, _LRScheduler)): raise TypeError( "Argument lr_scheduler should be a subclass of torch.optim.lr_scheduler._LRScheduler or " "ParamScheduler, but given {}".format(type(lr_scheduler)) ) if not (isinstance(warmup_duration, numbers.Integral) and warmup_duration > 1): raise ValueError( "Argument warmup_duration should be at least 2 events, but given {}".format( warmup_duration ) ) warmup_schedulers = [] for param_group_index, param_group in enumerate( lr_scheduler.optimizer.param_groups ): if warmup_end_value is None: param_group_warmup_end_value = param_group["lr"] else: param_group_warmup_end_value = warmup_end_value milestones_values = [ (0, warmup_start_value), (warmup_duration - 1, param_group_warmup_end_value), ] if isinstance(lr_scheduler, _LRScheduler): init_lr = param_group["lr"] if init_lr != param_group_warmup_end_value: milestones_values.append((warmup_duration, init_lr)) lr_scheduler = LRScheduler(lr_scheduler, save_history=save_history) else: init_lr = lr_scheduler.get_param() if init_lr == param_group_warmup_end_value: if warmup_duration > 2: d = (param_group_warmup_end_value - warmup_start_value) / ( warmup_duration - 1 ) milestones_values[-1] = ( warmup_duration - 2, param_group_warmup_end_value - d, ) else: milestones_values.pop(-1) warmup_scheduler = PiecewiseLinear( lr_scheduler.optimizer, param_name="lr", milestones_values=milestones_values, param_group_index=param_group_index, save_history=save_history, ) warmup_schedulers.append(warmup_scheduler) warmup_scheduler = ParamGroupScheduler(warmup_schedulers, save_history=save_history) schedulers = [warmup_scheduler, lr_scheduler] durations = [ milestones_values[-1][0] + 1, ] combined_scheduler = ConcatScheduler( schedulers, durations=durations, save_history=save_history ) if output_simulated_values is not None: if not isinstance(output_simulated_values, list): raise TypeError( "Argument output_simulated_values should be a list of None, e.g. `[None] * 100`, " "but given {}.".format(type(output_simulated_values)) ) num_events = len(output_simulated_values) result = ConcatScheduler.simulate_values( num_events=num_events, schedulers=schedulers, durations=durations ) for i in range(num_events): output_simulated_values[i] = result[i] return combined_scheduler
def create_lr_scheduler_with_warmup( lr_scheduler, warmup_start_value, warmup_duration, warmup_end_value=None, save_history=False, output_simulated_values=None, ): """ Helper method to create a learning rate scheduler with a linear warm-up. Args: lr_scheduler (ParamScheduler or subclass of `torch.optim.lr_scheduler._LRScheduler`): learning rate scheduler after the warm-up. warmup_start_value (float): learning rate start value of the warm-up phase. warmup_duration (int): warm-up phase duration, number of events. warmup_end_value (float): learning rate end value of the warm-up phase, (default=None). If None, warmup_end_value is set to optimizer initial lr. save_history (bool, optional): whether to log the parameter values to `engine.state.param_history`, (default=False). output_simulated_values (list, optional): optional output of simulated learning rate values. If output_simulated_values is a list of None, e.g. `[None] * 100`, after the execution it will be filled by 100 simulated learning rate values. Returns: ConcatScheduler: learning rate scheduler with linear warm-up. Note: If the first learning rate value provided by `lr_scheduler` is different from `warmup_end_value`, an additional event is added after the warm-up phase such that the warm-up ends with `warmup_end_value` value and then `lr_scheduler` provides its learning rate values as normally. Examples: .. code-block:: python torch_lr_scheduler = ExponentialLR(optimizer=optimizer, gamma=0.98) lr_values = [None] * 100 scheduler = create_lr_scheduler_with_warmup(torch_lr_scheduler, warmup_start_value=0.0, warmup_end_value=0.1, warmup_duration=10, output_simulated_values=lr_values) lr_values = np.array(lr_values) # Plot simulated values plt.plot(lr_values[:, 0], lr_values[:, 1], label="learning rate") # Attach to the trainer trainer.add_event_handler(Events.ITERATION_STARTED, scheduler) """ if not isinstance(lr_scheduler, (ParamScheduler, _LRScheduler)): raise TypeError( "Argument lr_scheduler should be a subclass of torch.optim.lr_scheduler._LRScheduler or " "ParamScheduler, but given {}".format(type(lr_scheduler)) ) if not (isinstance(warmup_duration, numbers.Integral) and warmup_duration > 1): raise ValueError( "Argument warmup_duration should be at least 2 events, but given {}".format( warmup_duration ) ) warmup_schedulers = [] for param_group_index, param_group in enumerate( lr_scheduler.optimizer.param_groups ): if warmup_end_value is None: param_group_warmup_end_value = param_group["lr"] else: param_group_warmup_end_value = warmup_end_value milestones_values = [ (0, warmup_start_value), (warmup_duration - 1, param_group_warmup_end_value), ] if isinstance(lr_scheduler, _LRScheduler): init_lr = param_group["lr"] if init_lr != param_group_warmup_end_value: milestones_values.append((warmup_duration, init_lr)) lr_scheduler = LRScheduler(lr_scheduler) else: init_lr = lr_scheduler.get_param() if init_lr == param_group_warmup_end_value: if warmup_duration > 2: d = (param_group_warmup_end_value - warmup_start_value) / ( warmup_duration - 1 ) milestones_values[-1] = ( warmup_duration - 2, param_group_warmup_end_value - d, ) else: milestones_values.pop(-1) warmup_scheduler = PiecewiseLinear( lr_scheduler.optimizer, param_name="lr", milestones_values=milestones_values, param_group_index=param_group_index, save_history=save_history, ) warmup_schedulers.append(warmup_scheduler) warmup_scheduler = ParamGroupScheduler(warmup_schedulers, save_history=save_history) schedulers = [warmup_scheduler, lr_scheduler] durations = [ milestones_values[-1][0] + 1, ] combined_scheduler = ConcatScheduler( schedulers, durations=durations, save_history=save_history ) if output_simulated_values is not None: if not isinstance(output_simulated_values, list): raise TypeError( "Argument output_simulated_values should be a list of None, e.g. `[None] * 100`, " "but given {}.".format(type(output_simulated_values)) ) num_events = len(output_simulated_values) result = ConcatScheduler.simulate_values( num_events=num_events, schedulers=schedulers, durations=durations ) for i in range(num_events): output_simulated_values[i] = result[i] return combined_scheduler
https://github.com/pytorch/ignite/issues/813
Traceback (most recent call last): File "tutorials/misc/lr_schedulers.py", line 56, in <module> lr_values = LRScheduler.simulate_values(num_events=50, lr_scheduler=lr_scheduler) File "/work/desrozis/Softwares/conda/envs/focus-light/lib/python3.7/site-packages/ignite/contrib/handlers/param_scheduler.py", line 606, in simulate_values copy_lr_scheduler = LRScheduler._replicate_lr_scheduler(lr_scheduler) File "/work/desrozis/Softwares/conda/envs/focus-light/lib/python3.7/site-packages/ignite/contrib/handlers/param_scheduler.py", line 627, in _replicate_lr_scheduler copy_lr_scheduler = lr_scheduler_cls(optimizer=dummy_optimizer, **kwargs) TypeError: __init__() got an unexpected keyword argument 'T_i'
TypeError
def __init__( self, schedulers: List[ParamScheduler], names: Optional[List[str]] = None, save_history=False, ): if not ( isinstance(schedulers, Sequence) and all(isinstance(scheduler, ParamScheduler) for scheduler in schedulers) ): raise ValueError( "Argument schedulers should be a list/tuple of parameter schedulers" ) if names is None: names = [s.param_name for s in schedulers] if not ( isinstance(names, (list, tuple)) and all(isinstance(n, str) for n in names) ): raise ValueError( "Argument names should be a list/tuple of parameter scheduler's names" ) if len(names) != len(schedulers): raise ValueError("{} should be equal {}".format(len(schedulers), len(names))) self.schedulers = schedulers self.names = names self.optimizer = self.schedulers[0].optimizer if not (all(id(s.optimizer) == id(self.optimizer) for s in schedulers)): raise ValueError("schedulers should be related to same optimizer") # schedulers should have save_history sync with ParamGroupScheduler for s in schedulers: s.save_history = save_history super(ParamGroupScheduler, self).__init__( optimizer=self.optimizer, param_name="lr", save_history=save_history )
def __init__( self, schedulers: List[ParamScheduler], names: Optional[List[str]] = None, save_history=False, ): if not ( isinstance(schedulers, Sequence) and all(isinstance(scheduler, ParamScheduler) for scheduler in schedulers) ): raise ValueError( "Argument schedulers should be a list/tuple of parameter schedulers" ) if names is None: names = [s.param_name for s in schedulers] if not ( isinstance(names, (list, tuple)) and all(isinstance(n, str) for n in names) ): raise ValueError( "Argument names should be a list/tuple of parameter scheduler's names" ) if len(names) != len(schedulers): raise ValueError("{} should be equal {}".format(len(schedulers), len(names))) self.schedulers = schedulers self.names = names optimizer = self.schedulers[0].optimizer if not (all(id(s.optimizer) == id(optimizer) for s in schedulers)): raise ValueError("schedulers should be related to same optimizer") super(ParamGroupScheduler, self).__init__( optimizer=optimizer, param_name="lr", save_history=save_history )
https://github.com/pytorch/ignite/issues/813
Traceback (most recent call last): File "tutorials/misc/lr_schedulers.py", line 56, in <module> lr_values = LRScheduler.simulate_values(num_events=50, lr_scheduler=lr_scheduler) File "/work/desrozis/Softwares/conda/envs/focus-light/lib/python3.7/site-packages/ignite/contrib/handlers/param_scheduler.py", line 606, in simulate_values copy_lr_scheduler = LRScheduler._replicate_lr_scheduler(lr_scheduler) File "/work/desrozis/Softwares/conda/envs/focus-light/lib/python3.7/site-packages/ignite/contrib/handlers/param_scheduler.py", line 627, in _replicate_lr_scheduler copy_lr_scheduler = lr_scheduler_cls(optimizer=dummy_optimizer, **kwargs) TypeError: __init__() got an unexpected keyword argument 'T_i'
TypeError
def simulate_values(cls, num_events, schedulers, **kwargs): """Method to simulate scheduled values during num_events events. Args: num_events (int): number of events during the simulation. lr_schedulers (subclass of `torch.optim.lr_scheduler._LRScheduler`): lr_scheduler object to wrap. Returns: list of pairs: [event_index, value] """ # This scheduler uses `torch.optim.lr_scheduler._LRScheduler` which # should be replicated in order to simulate LR values and # not perturb original scheduler. with tempfile.TemporaryDirectory() as tmpdirname: cache_filepath = Path(tmpdirname) / "ignite_lr_scheduler_cache.pt" objs = { "lr_scheduler_{}".format(i): s.state_dict() for i, s in enumerate(schedulers) } # all schedulers should be related to the same optimizer objs["optimizer"] = schedulers[0].optimizer.state_dict() torch.save(objs, cache_filepath.as_posix()) values = [] scheduler = cls(schedulers=schedulers, **kwargs) for i in range(num_events): params = scheduler.get_param() values.append([i] + params) scheduler(engine=None) objs = torch.load(cache_filepath.as_posix()) for i, s in enumerate(schedulers): s.load_state_dict(objs["lr_scheduler_{}".format(i)]) s.optimizer.load_state_dict(objs["optimizer"]) return values
def simulate_values(cls, num_events, schedulers, **kwargs): """Method to simulate scheduled values during num_events events. Args: num_events (int): number of events during the simulation. lr_schedulers (subclass of `torch.optim.lr_scheduler._LRScheduler`): lr_scheduler object to wrap. Returns: list of pairs: [event_index, value] """ copy_lr_schedulers = [_replicate_scheduler(s) for s in schedulers] values = [] scheduler = cls(schedulers=copy_lr_schedulers) for i in range(num_events): scheduler(engine=None) params = scheduler.get_param() values.append([i] + params) return values
https://github.com/pytorch/ignite/issues/813
Traceback (most recent call last): File "tutorials/misc/lr_schedulers.py", line 56, in <module> lr_values = LRScheduler.simulate_values(num_events=50, lr_scheduler=lr_scheduler) File "/work/desrozis/Softwares/conda/envs/focus-light/lib/python3.7/site-packages/ignite/contrib/handlers/param_scheduler.py", line 606, in simulate_values copy_lr_scheduler = LRScheduler._replicate_lr_scheduler(lr_scheduler) File "/work/desrozis/Softwares/conda/envs/focus-light/lib/python3.7/site-packages/ignite/contrib/handlers/param_scheduler.py", line 627, in _replicate_lr_scheduler copy_lr_scheduler = lr_scheduler_cls(optimizer=dummy_optimizer, **kwargs) TypeError: __init__() got an unexpected keyword argument 'T_i'
TypeError
def _handler_wrapper( self, handler: Callable, event_name: Any, event_filter: Callable ) -> Callable: # signature of the following wrapper will be inspected during registering to check if engine is necessary # we have to build a wrapper with relevant signature : solution is functools.wrapsgit s @functools.wraps(handler) def wrapper(*args, **kwargs) -> Any: event = self.state.get_event_attrib_value(event_name) if event_filter(self, event): return handler(*args, **kwargs) # setup input handler as parent to make has_event_handler work wrapper._parent = weakref.ref(handler) return wrapper
def _handler_wrapper( handler: Callable, event_name: Any, event_filter: Callable ) -> Callable: def wrapper(engine: Engine, *args, **kwargs) -> Any: event = engine.state.get_event_attrib_value(event_name) if event_filter(engine, event): return handler(engine, *args, **kwargs) # setup input handler as parent to make has_event_handler work wrapper._parent = weakref.ref(handler) return wrapper
https://github.com/pytorch/ignite/issues/918
TypeErrorTraceback (most recent call last) <ipython-input-13-832efed482dd> in <module> 14 15 e.add_event_handler(Events.ITERATION_COMPLETED(every=2), f4) ---> 16 e.fire_event(Events.ITERATION_COMPLETED) 17 e.fire_event(Events.ITERATION_COMPLETED) /opt/conda/lib/python3.7/site-packages/ignite/engine/engine.py in fire_event(self, event_name) 414 415 """ --> 416 return self._fire_event(event_name) 417 418 def terminate(self) -> None: /opt/conda/lib/python3.7/site-packages/ignite/engine/engine.py in _fire_event(self, event_name, *event_args, **event_kwargs) 391 kwargs.update(event_kwargs) 392 first, others = ((args[0],), args[1:]) if (args and args[0] == self) else ((), args) --> 393 func(*first, *(event_args + others), **kwargs) 394 395 def fire_event(self, event_name: Any) -> None: /opt/conda/lib/python3.7/site-packages/ignite/engine/engine.py in wrapper(engine, *args, **kwargs) 203 event = engine.state.get_event_attrib_value(event_name) 204 if event_filter(engine, event): --> 205 return handler(engine, *args, **kwargs) 206 207 # setup input handler as parent to make has_event_handler work TypeError: f4() takes 0 positional arguments but 1 was given
TypeError
def wrapper(*args, **kwargs) -> Any: event = self.state.get_event_attrib_value(event_name) if event_filter(self, event): return handler(*args, **kwargs)
def wrapper(engine: Engine, *args, **kwargs) -> Any: event = engine.state.get_event_attrib_value(event_name) if event_filter(engine, event): return handler(engine, *args, **kwargs)
https://github.com/pytorch/ignite/issues/918
TypeErrorTraceback (most recent call last) <ipython-input-13-832efed482dd> in <module> 14 15 e.add_event_handler(Events.ITERATION_COMPLETED(every=2), f4) ---> 16 e.fire_event(Events.ITERATION_COMPLETED) 17 e.fire_event(Events.ITERATION_COMPLETED) /opt/conda/lib/python3.7/site-packages/ignite/engine/engine.py in fire_event(self, event_name) 414 415 """ --> 416 return self._fire_event(event_name) 417 418 def terminate(self) -> None: /opt/conda/lib/python3.7/site-packages/ignite/engine/engine.py in _fire_event(self, event_name, *event_args, **event_kwargs) 391 kwargs.update(event_kwargs) 392 first, others = ((args[0],), args[1:]) if (args and args[0] == self) else ((), args) --> 393 func(*first, *(event_args + others), **kwargs) 394 395 def fire_event(self, event_name: Any) -> None: /opt/conda/lib/python3.7/site-packages/ignite/engine/engine.py in wrapper(engine, *args, **kwargs) 203 event = engine.state.get_event_attrib_value(event_name) 204 if event_filter(engine, event): --> 205 return handler(engine, *args, **kwargs) 206 207 # setup input handler as parent to make has_event_handler work TypeError: f4() takes 0 positional arguments but 1 was given
TypeError
def add_event_handler(self, event_name: Any, handler: Callable, *args, **kwargs): """Add an event handler to be executed when the specified event is fired. Args: event_name: An event or a list of events to attach the handler. Valid events are from :class:`~ignite.engine.Events` or any `event_name` added by :meth:`~ignite.engine.Engine.register_events`. handler (callable): the callable event handler that should be invoked. No restrictions on its signature. The first argument can be optionally `engine`, the :class:`~ignite.engine.Engine` object, handler is bound to. *args: optional args to be passed to `handler`. **kwargs: optional keyword args to be passed to `handler`. Note: Note that other arguments can be passed to the handler in addition to the `*args` and `**kwargs` passed here, for example during :attr:`~ignite.engine.Events.EXCEPTION_RAISED`. Returns: :class:`~ignite.engine.RemovableEventHandle`, which can be used to remove the handler. Example usage: .. code-block:: python engine = Engine(process_function) def print_epoch(engine): print("Epoch: {}".format(engine.state.epoch)) engine.add_event_handler(Events.EPOCH_COMPLETED, print_epoch) events_list = Events.EPOCH_COMPLETED | Events.COMPLETED def execute_something(): # do some thing not related to engine pass engine.add_event_handler(events_list, execute_something) Note: Since v0.3.0, Events become more flexible and allow to pass an event filter to the Engine. See :class:`~ignite.engine.Events` for more details. """ if isinstance(event_name, EventsList): for e in event_name: self.add_event_handler(e, handler, *args, **kwargs) return RemovableEventHandle(event_name, handler, self) if ( isinstance(event_name, CallableEventWithFilter) and event_name.filter != CallableEventWithFilter.default_event_filter ): event_filter = event_name.filter handler = self._handler_wrapper(handler, event_name, event_filter) if event_name not in self._allowed_events: self.logger.error( "attempt to add event handler to an invalid event %s.", event_name ) raise ValueError( "Event {} is not a valid event for this Engine.".format(event_name) ) event_args = (Exception(),) if event_name == Events.EXCEPTION_RAISED else () try: _check_signature(handler, "handler", self, *(event_args + args), **kwargs) self._event_handlers[event_name].append((handler, (self,) + args, kwargs)) except ValueError: _check_signature(handler, "handler", *(event_args + args), **kwargs) self._event_handlers[event_name].append((handler, args, kwargs)) self.logger.debug("added handler for event %s.", event_name) return RemovableEventHandle(event_name, handler, self)
def add_event_handler(self, event_name: Any, handler: Callable, *args, **kwargs): """Add an event handler to be executed when the specified event is fired. Args: event_name: An event or a list of events to attach the handler. Valid events are from :class:`~ignite.engine.Events` or any `event_name` added by :meth:`~ignite.engine.Engine.register_events`. handler (callable): the callable event handler that should be invoked. No restrictions on its signature. The first argument can be optionally `engine`, the :class:`~ignite.engine.Engine` object, handler is bound to. *args: optional args to be passed to `handler`. **kwargs: optional keyword args to be passed to `handler`. Note: Note that other arguments can be passed to the handler in addition to the `*args` and `**kwargs` passed here, for example during :attr:`~ignite.engine.Events.EXCEPTION_RAISED`. Returns: :class:`~ignite.engine.RemovableEventHandle`, which can be used to remove the handler. Example usage: .. code-block:: python engine = Engine(process_function) def print_epoch(engine): print("Epoch: {}".format(engine.state.epoch)) engine.add_event_handler(Events.EPOCH_COMPLETED, print_epoch) events_list = Events.EPOCH_COMPLETED | Events.COMPLETED def execute_something(): # do some thing not related to engine pass engine.add_event_handler(events_list, execute_something) Note: Since v0.3.0, Events become more flexible and allow to pass an event filter to the Engine. See :class:`~ignite.engine.Events` for more details. """ if isinstance(event_name, EventsList): for e in event_name: self.add_event_handler(e, handler, *args, **kwargs) return RemovableEventHandle(event_name, handler, self) if ( isinstance(event_name, CallableEventWithFilter) and event_name.filter != CallableEventWithFilter.default_event_filter ): event_filter = event_name.filter handler = Engine._handler_wrapper(handler, event_name, event_filter) if event_name not in self._allowed_events: self.logger.error( "attempt to add event handler to an invalid event %s.", event_name ) raise ValueError( "Event {} is not a valid event for this Engine.".format(event_name) ) event_args = (Exception(),) if event_name == Events.EXCEPTION_RAISED else () try: _check_signature(handler, "handler", self, *(event_args + args), **kwargs) self._event_handlers[event_name].append((handler, (self,) + args, kwargs)) except ValueError: _check_signature(handler, "handler", *(event_args + args), **kwargs) self._event_handlers[event_name].append((handler, args, kwargs)) self.logger.debug("added handler for event %s.", event_name) return RemovableEventHandle(event_name, handler, self)
https://github.com/pytorch/ignite/issues/918
TypeErrorTraceback (most recent call last) <ipython-input-13-832efed482dd> in <module> 14 15 e.add_event_handler(Events.ITERATION_COMPLETED(every=2), f4) ---> 16 e.fire_event(Events.ITERATION_COMPLETED) 17 e.fire_event(Events.ITERATION_COMPLETED) /opt/conda/lib/python3.7/site-packages/ignite/engine/engine.py in fire_event(self, event_name) 414 415 """ --> 416 return self._fire_event(event_name) 417 418 def terminate(self) -> None: /opt/conda/lib/python3.7/site-packages/ignite/engine/engine.py in _fire_event(self, event_name, *event_args, **event_kwargs) 391 kwargs.update(event_kwargs) 392 first, others = ((args[0],), args[1:]) if (args and args[0] == self) else ((), args) --> 393 func(*first, *(event_args + others), **kwargs) 394 395 def fire_event(self, event_name: Any) -> None: /opt/conda/lib/python3.7/site-packages/ignite/engine/engine.py in wrapper(engine, *args, **kwargs) 203 event = engine.state.get_event_attrib_value(event_name) 204 if event_filter(engine, event): --> 205 return handler(engine, *args, **kwargs) 206 207 # setup input handler as parent to make has_event_handler work TypeError: f4() takes 0 positional arguments but 1 was given
TypeError
def print_results(results): """ Method to print the aggregated results from the profiler .. code-block:: python profiler.print_results(results) Example output: .. code-block:: text -------------------------------------------- - Time profiling results: -------------------------------------------- Processing function time stats (in seconds): min/index: (2.9754010029137135e-05, 0) max/index: (2.9754010029137135e-05, 0) mean: 2.9754010029137135e-05 std: nan total: 2.9754010029137135e-05 Dataflow time stats (in seconds): min/index: (0.2523871660232544, 0) max/index: (0.2523871660232544, 0) mean: 0.2523871660232544 std: nan total: 0.2523871660232544 Time stats of event handlers (in seconds): - Total time spent: 1.0080009698867798 - Events.STARTED: min/index: (0.1256754994392395, 0) max/index: (0.1256754994392395, 0) mean: 0.1256754994392395 std: nan total: 0.1256754994392395 Handlers names: ['BasicTimeProfiler._as_first_started', 'delay_start'] -------------------------------------------- """ def odict_to_str(d): out = "" for k, v in d.items(): out += "\t{}: {}\n".format(k, v) return out others = { k: odict_to_str(v) if isinstance(v, OrderedDict) else v for k, v in results["event_handlers_stats"].items() } others.update(results["event_handlers_names"]) output_message = """ -------------------------------------------- - Time profiling results: -------------------------------------------- Processing function time stats (in seconds): {processing_stats} Dataflow time stats (in seconds): {dataflow_stats} Time stats of event handlers (in seconds): - Total time spent: \t{total_time} - Events.STARTED: {STARTED} Handlers names: {STARTED_names} - Events.EPOCH_STARTED: {EPOCH_STARTED} Handlers names: {EPOCH_STARTED_names} - Events.ITERATION_STARTED: {ITERATION_STARTED} Handlers names: {ITERATION_STARTED_names} - Events.ITERATION_COMPLETED: {ITERATION_COMPLETED} Handlers names: {ITERATION_COMPLETED_names} - Events.EPOCH_COMPLETED: {EPOCH_COMPLETED} Handlers names: {EPOCH_COMPLETED_names} - Events.COMPLETED: {COMPLETED} Handlers names: {COMPLETED_names} """.format( processing_stats=odict_to_str(results["processing_stats"]), dataflow_stats=odict_to_str(results["dataflow_stats"]), **others, ) print(output_message) return output_message
def print_results(results): """ Method to print the aggregated results from the profiler .. code-block:: python profiler.print_results(results) Example output: .. code-block:: text -------------------------------------------- - Time profiling results: -------------------------------------------- Processing function time stats (in seconds): min/index: (2.9754010029137135e-05, 0) max/index: (2.9754010029137135e-05, 0) mean: 2.9754010029137135e-05 std: nan total: 2.9754010029137135e-05 Dataflow time stats (in seconds): min/index: (0.2523871660232544, 0) max/index: (0.2523871660232544, 0) mean: 0.2523871660232544 std: nan total: 0.2523871660232544 Time stats of event handlers (in seconds): - Total time spent: 1.0080009698867798 - Events.STARTED: min/index: (0.1256754994392395, 0) max/index: (0.1256754994392395, 0) mean: 0.1256754994392395 std: nan total: 0.1256754994392395 Handlers names: ['BasicTimeProfiler._as_first_started', 'delay_start'] -------------------------------------------- """ def odict_to_str(d): out = "" for k, v in d.items(): out += "\t{}: {}\n".format(k, v) return out others = { k: odict_to_str(v) if isinstance(v, OrderedDict) else v for k, v in results["event_handlers_stats"].items() } others.update(results["event_handlers_names"]) output_message = """ -------------------------------------------- - Time profiling results: -------------------------------------------- Processing function time stats (in seconds): {processing_stats} Dataflow time stats (in seconds): {dataflow_stats} Time stats of event handlers (in seconds): - Total time spent: \t{total_time} - Events.STARTED: {Events_STARTED} Handlers names: {Events_STARTED_names} - Events.EPOCH_STARTED: {Events_EPOCH_STARTED} Handlers names: {Events_EPOCH_STARTED_names} - Events.ITERATION_STARTED: {Events_ITERATION_STARTED} Handlers names: {Events_ITERATION_STARTED_names} - Events.ITERATION_COMPLETED: {Events_ITERATION_COMPLETED} Handlers names: {Events_ITERATION_COMPLETED_names} - Events.EPOCH_COMPLETED: {Events_EPOCH_COMPLETED} Handlers names: {Events_EPOCH_COMPLETED_names} - Events.COMPLETED: {Events_COMPLETED} Handlers names: {Events_COMPLETED_names} """.format( processing_stats=odict_to_str(results["processing_stats"]), dataflow_stats=odict_to_str(results["dataflow_stats"]), **others, ) print(output_message) return output_message
https://github.com/pytorch/ignite/issues/814
OrderedDict([('processing_stats', OrderedDict([('min/index', (0.002581869950518012, 937)), ('max/index', (0.24407817423343658, 0)), ('mean', 0.005071939900517464), ('std', 0.005763144697993994), ('total', 9.514959335327148)])), ('dataflow_stats', OrderedDict([('min/index', (5.4130003263708204e-05, 1874)), ('max/index', (0.02181326039135456, 1875)), ('mean', 0.00013960782962385565), ('std', 0.0006590772536583245), ('total', 0.2619042992591858)])), ('event_handlers_stats', {'EPOCH_STARTED': OrderedDict([('min/index', (6.137001037131995e-06, 0)), ('max/index', (1.3475997548084706e-05, 1)), ('mean', 9.80649929260835e-06), ('std', 5.189453986531589e-06), ('total', 1.96129985852167e-05)]), 'EPOCH_COMPLETED': OrderedDict([('min/index', (3.951500654220581, 0)), ('max/index', (4.009259223937988, 1)), ('mean', 3.980380058288574), ('std', 0.0408414751291275), ('total', 7.960760116577148)]), 'STARTED': OrderedDict([('min/index', (4.647001333069056e-06, 0)), ('max/index', (4.647001333069056e-06, 0)), ('mean', 4.647001333069056e-06), ('std', nan), ('total', 4.647001333069056e-06)]), 'COMPLETED': OrderedDict([('min/index', (0.001252603018656373, 0)), ('max/index', (0.001252603018656373, 0)), ('mean', 0.001252603018656373), ('std', nan), ('total', 0.001252603018656373)]), 'ITERATION_STARTED': OrderedDict([('min/index', (1.2870004866272211e-06, 931)), ('max/index', (1.6206002328544855e-05, 784)), ('mean', 2.0810284695471637e-06), ('std', 1.0310620837117312e-06), ('total', 0.003904009470716119)]), 'ITERATION_COMPLETED': OrderedDict([('min/index', (0.00041244301246479154, 6)), ('max/index', (0.0033979369327425957, 1706)), ('mean', 0.0005990439676679671), ('std', 0.00017004708934109658), ('total', 1.1238064765930176)]), 'GET_BATCH_STARTED': OrderedDict([('min/index', (2.2699969122186303e-06, 1871)), ('max/index', (6.306700379354879e-05, 1627)), ('mean', 3.619041763158748e-06), ('std', 2.3099164536688477e-06), ('total', 0.006789322476834059)]), 'GET_BATCH_COMPLETED': OrderedDict([('min/index', (1.471998984925449e-06, 934)), ('max/index', (1.4063996786717325e-05, 918)), ('mean', 2.3078853246261133e-06), ('std', 8.762469292378228e-07), ('total', 0.0043295929208397865)]), 'total_time': tensor(9.1009)}), ('event_handlers_names', {'EPOCH_STARTED_names': ['Metric.started'], 'EPOCH_COMPLETED_names': ['ProgressBar._close', 'log_training_results_fn', 'log_validation_results_fn'], 'STARTED_names': ['BasicTimeProfiler._as_first_started'], 'COMPLETED_names': ['ModelCheckpoint'], 'ITERATION_STARTED_names': [], 'ITERATION_COMPLETED_names': ['Metric.iteration_completed', 'Metric.completed', 'LRScheduler', '_OutputHandler', 'Engine._handler_wrapper.<locals>.wrapper', 'Engine._handler_wrapper.<locals>.wrapper'], 'GET_BATCH_STARTED_names': [], 'GET_BATCH_COMPLETED_names': []})]) Traceback (most recent call last): File "tutorials/mnist/mnist.py", line 228, in <module> BasicTimeProfiler.print_results(profiler.get_results()) File "/work/desrozis/Softwares/conda/envs/focus-light/lib/python3.7/site-packages/ignite/contrib/handlers/time_profilers.py", line 414, in print_results **others, KeyError: 'Events_STARTED'
KeyError
def __init__(self, event: Any, filter: Callable): if not callable(filter): raise TypeError("Argument filter should be callable") self.event = event self.filter = filter
def __init__(self, event: CallableEvents, filter: Callable): if not callable(filter): raise TypeError("Argument filter should be callable") self.event = event self.filter = filter
https://github.com/pytorch/ignite/issues/752
root@user:/# pip install --pre pytorch-ignite Successfully installed pytorch-ignite-0.4.0.dev20200129 root@user:/# root@user:/# python -c "import ignite" Traceback (most recent call last): File "<string>", line 1, in <module> File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/__init__.py", line 1, in <module> import ignite.engine File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/__init__.py", line 4, in <module> from ignite.engine.engine import Engine File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/engine.py", line 1 from __future__ import annotations ^ SyntaxError: future feature annotations is not defined root@user:/# python --version Python 3.5.6 :: Anaconda, Inc.
SyntaxError
def __call__( self, event_filter: Optional[Callable] = None, every: Optional[int] = None, once: Optional[int] = None, ): if not ((event_filter is not None) ^ (every is not None) ^ (once is not None)): raise ValueError("Only one of the input arguments should be specified") if (event_filter is not None) and not callable(event_filter): raise TypeError("Argument event_filter should be a callable") if (every is not None) and not (isinstance(every, numbers.Integral) and every > 0): raise ValueError("Argument every should be integer and greater than zero") if (once is not None) and not (isinstance(once, numbers.Integral) and once > 0): raise ValueError("Argument every should be integer and positive") if every is not None: if every == 1: # Just return the event itself return self event_filter = CallableEvents.every_event_filter(every) if once is not None: event_filter = CallableEvents.once_event_filter(once) # check signature: _check_signature("engine", event_filter, "event_filter", "event") return EventWithFilter(self, event_filter)
def __call__( self, event_filter: Optional[Callable] = None, every: Optional[int] = None, once: Optional[int] = None, ) -> Union[CallableEvents, EventWithFilter]: if not ((event_filter is not None) ^ (every is not None) ^ (once is not None)): raise ValueError("Only one of the input arguments should be specified") if (event_filter is not None) and not callable(event_filter): raise TypeError("Argument event_filter should be a callable") if (every is not None) and not (isinstance(every, numbers.Integral) and every > 0): raise ValueError("Argument every should be integer and greater than zero") if (once is not None) and not (isinstance(once, numbers.Integral) and once > 0): raise ValueError("Argument every should be integer and positive") if every is not None: if every == 1: # Just return the event itself return self event_filter = CallableEvents.every_event_filter(every) if once is not None: event_filter = CallableEvents.once_event_filter(once) # check signature: _check_signature("engine", event_filter, "event_filter", "event") return EventWithFilter(self, event_filter)
https://github.com/pytorch/ignite/issues/752
root@user:/# pip install --pre pytorch-ignite Successfully installed pytorch-ignite-0.4.0.dev20200129 root@user:/# root@user:/# python -c "import ignite" Traceback (most recent call last): File "<string>", line 1, in <module> File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/__init__.py", line 1, in <module> import ignite.engine File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/__init__.py", line 4, in <module> from ignite.engine.engine import Engine File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/engine.py", line 1 from __future__ import annotations ^ SyntaxError: future feature annotations is not defined root@user:/# python --version Python 3.5.6 :: Anaconda, Inc.
SyntaxError
def __enter__(self): return self
def __enter__(self) -> RemovableEventHandle: return self
https://github.com/pytorch/ignite/issues/752
root@user:/# pip install --pre pytorch-ignite Successfully installed pytorch-ignite-0.4.0.dev20200129 root@user:/# root@user:/# python -c "import ignite" Traceback (most recent call last): File "<string>", line 1, in <module> File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/__init__.py", line 1, in <module> import ignite.engine File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/__init__.py", line 4, in <module> from ignite.engine.engine import Engine File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/engine.py", line 1 from __future__ import annotations ^ SyntaxError: future feature annotations is not defined root@user:/# python --version Python 3.5.6 :: Anaconda, Inc.
SyntaxError
def attach( self, engine: Engine, start: str = Events.STARTED, pause: str = Events.COMPLETED, resume: Optional[str] = None, step: Optional[str] = None, ): """Register callbacks to control the timer. Args: engine (Engine): Engine that this timer will be attached to. start (Events): Event which should start (reset) the timer. pause (Events): Event which should pause the timer. resume (Events, optional): Event which should resume the timer. step (Events, optional): Event which should call the `step` method of the counter. Returns: self (Timer) """ engine.add_event_handler(start, self.reset) engine.add_event_handler(pause, self.pause) if resume is not None: engine.add_event_handler(resume, self.resume) if step is not None: engine.add_event_handler(step, self.step) return self
def attach( self, engine: Engine, start: str = Events.STARTED, pause: str = Events.COMPLETED, resume: Optional[str] = None, step: Optional[str] = None, ) -> Timer: """Register callbacks to control the timer. Args: engine (Engine): Engine that this timer will be attached to. start (Events): Event which should start (reset) the timer. pause (Events): Event which should pause the timer. resume (Events, optional): Event which should resume the timer. step (Events, optional): Event which should call the `step` method of the counter. Returns: self (Timer) """ engine.add_event_handler(start, self.reset) engine.add_event_handler(pause, self.pause) if resume is not None: engine.add_event_handler(resume, self.resume) if step is not None: engine.add_event_handler(step, self.step) return self
https://github.com/pytorch/ignite/issues/752
root@user:/# pip install --pre pytorch-ignite Successfully installed pytorch-ignite-0.4.0.dev20200129 root@user:/# root@user:/# python -c "import ignite" Traceback (most recent call last): File "<string>", line 1, in <module> File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/__init__.py", line 1, in <module> import ignite.engine File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/__init__.py", line 4, in <module> from ignite.engine.engine import Engine File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/engine.py", line 1 from __future__ import annotations ^ SyntaxError: future feature annotations is not defined root@user:/# python --version Python 3.5.6 :: Anaconda, Inc.
SyntaxError
def reset(self, *args): self.__init__(self._average) return self
def reset(self, *args) -> Timer: self.__init__(self._average) return self
https://github.com/pytorch/ignite/issues/752
root@user:/# pip install --pre pytorch-ignite Successfully installed pytorch-ignite-0.4.0.dev20200129 root@user:/# root@user:/# python -c "import ignite" Traceback (most recent call last): File "<string>", line 1, in <module> File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/__init__.py", line 1, in <module> import ignite.engine File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/__init__.py", line 4, in <module> from ignite.engine.engine import Engine File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/engine.py", line 1 from __future__ import annotations ^ SyntaxError: future feature annotations is not defined root@user:/# python --version Python 3.5.6 :: Anaconda, Inc.
SyntaxError
def __add__(self, other): from ignite.metrics import MetricsLambda return MetricsLambda(lambda x, y: x + y, self, other)
def __add__(self, other: Metric) -> Metric: from ignite.metrics import MetricsLambda return MetricsLambda(lambda x, y: x + y, self, other)
https://github.com/pytorch/ignite/issues/752
root@user:/# pip install --pre pytorch-ignite Successfully installed pytorch-ignite-0.4.0.dev20200129 root@user:/# root@user:/# python -c "import ignite" Traceback (most recent call last): File "<string>", line 1, in <module> File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/__init__.py", line 1, in <module> import ignite.engine File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/__init__.py", line 4, in <module> from ignite.engine.engine import Engine File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/engine.py", line 1 from __future__ import annotations ^ SyntaxError: future feature annotations is not defined root@user:/# python --version Python 3.5.6 :: Anaconda, Inc.
SyntaxError
def __radd__(self, other): from ignite.metrics import MetricsLambda return MetricsLambda(lambda x, y: x + y, other, self)
def __radd__(self, other: Metric) -> Metric: from ignite.metrics import MetricsLambda return MetricsLambda(lambda x, y: x + y, other, self)
https://github.com/pytorch/ignite/issues/752
root@user:/# pip install --pre pytorch-ignite Successfully installed pytorch-ignite-0.4.0.dev20200129 root@user:/# root@user:/# python -c "import ignite" Traceback (most recent call last): File "<string>", line 1, in <module> File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/__init__.py", line 1, in <module> import ignite.engine File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/__init__.py", line 4, in <module> from ignite.engine.engine import Engine File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/engine.py", line 1 from __future__ import annotations ^ SyntaxError: future feature annotations is not defined root@user:/# python --version Python 3.5.6 :: Anaconda, Inc.
SyntaxError
def __sub__(self, other): from ignite.metrics import MetricsLambda return MetricsLambda(lambda x, y: x - y, self, other)
def __sub__(self, other: Metric) -> Metric: from ignite.metrics import MetricsLambda return MetricsLambda(lambda x, y: x - y, self, other)
https://github.com/pytorch/ignite/issues/752
root@user:/# pip install --pre pytorch-ignite Successfully installed pytorch-ignite-0.4.0.dev20200129 root@user:/# root@user:/# python -c "import ignite" Traceback (most recent call last): File "<string>", line 1, in <module> File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/__init__.py", line 1, in <module> import ignite.engine File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/__init__.py", line 4, in <module> from ignite.engine.engine import Engine File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/engine.py", line 1 from __future__ import annotations ^ SyntaxError: future feature annotations is not defined root@user:/# python --version Python 3.5.6 :: Anaconda, Inc.
SyntaxError
def __rsub__(self, other): from ignite.metrics import MetricsLambda return MetricsLambda(lambda x, y: x - y, other, self)
def __rsub__(self, other: Metric) -> Metric: from ignite.metrics import MetricsLambda return MetricsLambda(lambda x, y: x - y, other, self)
https://github.com/pytorch/ignite/issues/752
root@user:/# pip install --pre pytorch-ignite Successfully installed pytorch-ignite-0.4.0.dev20200129 root@user:/# root@user:/# python -c "import ignite" Traceback (most recent call last): File "<string>", line 1, in <module> File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/__init__.py", line 1, in <module> import ignite.engine File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/__init__.py", line 4, in <module> from ignite.engine.engine import Engine File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/engine.py", line 1 from __future__ import annotations ^ SyntaxError: future feature annotations is not defined root@user:/# python --version Python 3.5.6 :: Anaconda, Inc.
SyntaxError
def __mul__(self, other): from ignite.metrics import MetricsLambda return MetricsLambda(lambda x, y: x * y, self, other)
def __mul__(self, other: Metric) -> Metric: from ignite.metrics import MetricsLambda return MetricsLambda(lambda x, y: x * y, self, other)
https://github.com/pytorch/ignite/issues/752
root@user:/# pip install --pre pytorch-ignite Successfully installed pytorch-ignite-0.4.0.dev20200129 root@user:/# root@user:/# python -c "import ignite" Traceback (most recent call last): File "<string>", line 1, in <module> File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/__init__.py", line 1, in <module> import ignite.engine File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/__init__.py", line 4, in <module> from ignite.engine.engine import Engine File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/engine.py", line 1 from __future__ import annotations ^ SyntaxError: future feature annotations is not defined root@user:/# python --version Python 3.5.6 :: Anaconda, Inc.
SyntaxError
def __rmul__(self, other): from ignite.metrics import MetricsLambda return MetricsLambda(lambda x, y: x * y, other, self)
def __rmul__(self, other: Metric) -> Metric: from ignite.metrics import MetricsLambda return MetricsLambda(lambda x, y: x * y, other, self)
https://github.com/pytorch/ignite/issues/752
root@user:/# pip install --pre pytorch-ignite Successfully installed pytorch-ignite-0.4.0.dev20200129 root@user:/# root@user:/# python -c "import ignite" Traceback (most recent call last): File "<string>", line 1, in <module> File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/__init__.py", line 1, in <module> import ignite.engine File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/__init__.py", line 4, in <module> from ignite.engine.engine import Engine File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/engine.py", line 1 from __future__ import annotations ^ SyntaxError: future feature annotations is not defined root@user:/# python --version Python 3.5.6 :: Anaconda, Inc.
SyntaxError
def __pow__(self, other): from ignite.metrics import MetricsLambda return MetricsLambda(lambda x, y: x**y, self, other)
def __pow__(self, other: Metric) -> Metric: from ignite.metrics import MetricsLambda return MetricsLambda(lambda x, y: x**y, self, other)
https://github.com/pytorch/ignite/issues/752
root@user:/# pip install --pre pytorch-ignite Successfully installed pytorch-ignite-0.4.0.dev20200129 root@user:/# root@user:/# python -c "import ignite" Traceback (most recent call last): File "<string>", line 1, in <module> File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/__init__.py", line 1, in <module> import ignite.engine File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/__init__.py", line 4, in <module> from ignite.engine.engine import Engine File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/engine.py", line 1 from __future__ import annotations ^ SyntaxError: future feature annotations is not defined root@user:/# python --version Python 3.5.6 :: Anaconda, Inc.
SyntaxError
def __rpow__(self, other): from ignite.metrics import MetricsLambda return MetricsLambda(lambda x, y: x**y, other, self)
def __rpow__(self, other: Metric) -> Metric: from ignite.metrics import MetricsLambda return MetricsLambda(lambda x, y: x**y, other, self)
https://github.com/pytorch/ignite/issues/752
root@user:/# pip install --pre pytorch-ignite Successfully installed pytorch-ignite-0.4.0.dev20200129 root@user:/# root@user:/# python -c "import ignite" Traceback (most recent call last): File "<string>", line 1, in <module> File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/__init__.py", line 1, in <module> import ignite.engine File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/__init__.py", line 4, in <module> from ignite.engine.engine import Engine File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/engine.py", line 1 from __future__ import annotations ^ SyntaxError: future feature annotations is not defined root@user:/# python --version Python 3.5.6 :: Anaconda, Inc.
SyntaxError
def __mod__(self, other): from ignite.metrics import MetricsLambda return MetricsLambda(lambda x, y: x % y, self, other)
def __mod__(self, other: Metric) -> Metric: from ignite.metrics import MetricsLambda return MetricsLambda(lambda x, y: x % y, self, other)
https://github.com/pytorch/ignite/issues/752
root@user:/# pip install --pre pytorch-ignite Successfully installed pytorch-ignite-0.4.0.dev20200129 root@user:/# root@user:/# python -c "import ignite" Traceback (most recent call last): File "<string>", line 1, in <module> File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/__init__.py", line 1, in <module> import ignite.engine File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/__init__.py", line 4, in <module> from ignite.engine.engine import Engine File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/engine.py", line 1 from __future__ import annotations ^ SyntaxError: future feature annotations is not defined root@user:/# python --version Python 3.5.6 :: Anaconda, Inc.
SyntaxError
def __div__(self, other): from ignite.metrics import MetricsLambda return MetricsLambda(lambda x, y: x.__div__(y), self, other)
def __div__(self, other: Metric) -> Metric: from ignite.metrics import MetricsLambda return MetricsLambda(lambda x, y: x.__div__(y), self, other)
https://github.com/pytorch/ignite/issues/752
root@user:/# pip install --pre pytorch-ignite Successfully installed pytorch-ignite-0.4.0.dev20200129 root@user:/# root@user:/# python -c "import ignite" Traceback (most recent call last): File "<string>", line 1, in <module> File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/__init__.py", line 1, in <module> import ignite.engine File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/__init__.py", line 4, in <module> from ignite.engine.engine import Engine File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/engine.py", line 1 from __future__ import annotations ^ SyntaxError: future feature annotations is not defined root@user:/# python --version Python 3.5.6 :: Anaconda, Inc.
SyntaxError
def __rdiv__(self, other): from ignite.metrics import MetricsLambda return MetricsLambda(lambda x, y: x.__div__(y), other, self)
def __rdiv__(self, other: Metric) -> Metric: from ignite.metrics import MetricsLambda return MetricsLambda(lambda x, y: x.__div__(y), other, self)
https://github.com/pytorch/ignite/issues/752
root@user:/# pip install --pre pytorch-ignite Successfully installed pytorch-ignite-0.4.0.dev20200129 root@user:/# root@user:/# python -c "import ignite" Traceback (most recent call last): File "<string>", line 1, in <module> File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/__init__.py", line 1, in <module> import ignite.engine File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/__init__.py", line 4, in <module> from ignite.engine.engine import Engine File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/engine.py", line 1 from __future__ import annotations ^ SyntaxError: future feature annotations is not defined root@user:/# python --version Python 3.5.6 :: Anaconda, Inc.
SyntaxError
def __truediv__(self, other): from ignite.metrics import MetricsLambda return MetricsLambda(lambda x, y: x.__truediv__(y), self, other)
def __truediv__(self, other: Metric) -> Metric: from ignite.metrics import MetricsLambda return MetricsLambda(lambda x, y: x.__truediv__(y), self, other)
https://github.com/pytorch/ignite/issues/752
root@user:/# pip install --pre pytorch-ignite Successfully installed pytorch-ignite-0.4.0.dev20200129 root@user:/# root@user:/# python -c "import ignite" Traceback (most recent call last): File "<string>", line 1, in <module> File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/__init__.py", line 1, in <module> import ignite.engine File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/__init__.py", line 4, in <module> from ignite.engine.engine import Engine File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/engine.py", line 1 from __future__ import annotations ^ SyntaxError: future feature annotations is not defined root@user:/# python --version Python 3.5.6 :: Anaconda, Inc.
SyntaxError
def __rtruediv__(self, other): from ignite.metrics import MetricsLambda return MetricsLambda(lambda x, y: x.__truediv__(y), other, self)
def __rtruediv__(self, other: Metric) -> Metric: from ignite.metrics import MetricsLambda return MetricsLambda(lambda x, y: x.__truediv__(y), other, self)
https://github.com/pytorch/ignite/issues/752
root@user:/# pip install --pre pytorch-ignite Successfully installed pytorch-ignite-0.4.0.dev20200129 root@user:/# root@user:/# python -c "import ignite" Traceback (most recent call last): File "<string>", line 1, in <module> File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/__init__.py", line 1, in <module> import ignite.engine File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/__init__.py", line 4, in <module> from ignite.engine.engine import Engine File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/engine.py", line 1 from __future__ import annotations ^ SyntaxError: future feature annotations is not defined root@user:/# python --version Python 3.5.6 :: Anaconda, Inc.
SyntaxError
def __floordiv__(self, other): from ignite.metrics import MetricsLambda return MetricsLambda(lambda x, y: x // y, self, other)
def __floordiv__(self, other: Metric) -> Metric: from ignite.metrics import MetricsLambda return MetricsLambda(lambda x, y: x // y, self, other)
https://github.com/pytorch/ignite/issues/752
root@user:/# pip install --pre pytorch-ignite Successfully installed pytorch-ignite-0.4.0.dev20200129 root@user:/# root@user:/# python -c "import ignite" Traceback (most recent call last): File "<string>", line 1, in <module> File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/__init__.py", line 1, in <module> import ignite.engine File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/__init__.py", line 4, in <module> from ignite.engine.engine import Engine File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/engine.py", line 1 from __future__ import annotations ^ SyntaxError: future feature annotations is not defined root@user:/# python --version Python 3.5.6 :: Anaconda, Inc.
SyntaxError
def __getitem__(self, index: Any): from ignite.metrics import MetricsLambda return MetricsLambda(lambda x: x[index], self)
def __getitem__(self, index: Any) -> Metric: from ignite.metrics import MetricsLambda return MetricsLambda(lambda x: x[index], self)
https://github.com/pytorch/ignite/issues/752
root@user:/# pip install --pre pytorch-ignite Successfully installed pytorch-ignite-0.4.0.dev20200129 root@user:/# root@user:/# python -c "import ignite" Traceback (most recent call last): File "<string>", line 1, in <module> File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/__init__.py", line 1, in <module> import ignite.engine File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/__init__.py", line 4, in <module> from ignite.engine.engine import Engine File "/opt/conda/envs/py35/lib/python3.5/site-packages/ignite/engine/engine.py", line 1 from __future__ import annotations ^ SyntaxError: future feature annotations is not defined root@user:/# python --version Python 3.5.6 :: Anaconda, Inc.
SyntaxError
def _setup_engine(self): try: self._dataloader_len = ( len(self.state.dataloader) if hasattr(self.state.dataloader, "__len__") else None ) except TypeError: # _InfiniteConstantSampler can raise a TypeError on DataLoader length of a IterableDataset self._dataloader_len = None # setup seed here, as iter(data) can start prefetching self.setup_seed() # if input data is torch dataloader we replace batch sampler by a batch sampler # such that its random sampling indices are reproducible by prefetching them before data iteration if isinstance(self.state.dataloader, torch.utils.data.DataLoader): _dataloader_kind = self.state.dataloader._dataset_kind if _dataloader_kind == torch.utils.data.dataloader._DatasetKind.Map: if (self._dataloader_len is not None) and hasattr( self.state.dataloader.sampler, "epoch" ): if self._dataloader_len != self.state.epoch_length: warnings.warn( "When defined engine's epoch length is different of input dataloader length, " "distributed sampler indices can not be setup in a reproducible manner" ) batch_sampler = self.state.dataloader.batch_sampler if not isinstance(batch_sampler, ReproducibleBatchSampler): self.state.dataloader = _update_dataloader( self.state.dataloader, ReproducibleBatchSampler(batch_sampler) ) iteration = self.state.iteration self._dataloader_iter = self._from_iteration(self.state.dataloader, iteration) # Below we define initial counter value for _run_once_on_dataset to measure a single epoch if self.state.epoch_length is not None: iteration %= self.state.epoch_length self._init_iter.append(iteration)
def _setup_engine(self): try: self._dataloader_len = ( len(self.state.dataloader) if hasattr(self.state.dataloader, "__len__") else None ) except TypeError: # _InfiniteConstantSampler can raise a TypeError on DataLoader length of a IterableDataset self._dataloader_len = None # setup seed here, as iter(data) can start prefetching self.setup_seed() # if input data is torch dataloader we replace batch sampler by a batch sampler # such that its random sampling indices are reproducible by prefetching them before data iteration if isinstance(self.state.dataloader, torch.utils.data.DataLoader): if (self._dataloader_len is not None) and hasattr( self.state.dataloader.sampler, "epoch" ): if self._dataloader_len != self.state.epoch_length: warnings.warn( "When defined engine's epoch length is different of input dataloader length, " "distributed sampler indices can not be setup in a reproducible manner" ) batch_sampler = self.state.dataloader.batch_sampler if not isinstance(batch_sampler, ReproducibleBatchSampler): self.state.dataloader = _update_dataloader( self.state.dataloader, ReproducibleBatchSampler(batch_sampler) ) iteration = self.state.iteration self._dataloader_iter = self._from_iteration( self.state.dataloader, iteration, self.state.epoch_length ) # Below we define initial counter value for _run_once_on_dataset to measure a single epoch if self.state.epoch_length is not None: iteration %= self.state.epoch_length self._init_iter.append(iteration)
https://github.com/pytorch/ignite/issues/714
ValueErrorTraceback (most recent call last) <ipython-input-19-1c8004fbf46e> in <module> 21 22 engine = Engine(foo) ---> 23 engine.run(data_loader, epoch_length=10) /opt/conda/lib/python3.7/site-packages/ignite/engine/engine.py in run(self, data, max_epochs, epoch_length, seed) 848 849 self.state.dataloader = data --> 850 return self._internal_run() 851 852 def _setup_engine(self): /opt/conda/lib/python3.7/site-packages/ignite/engine/engine.py in _internal_run(self) 950 self._dataloader_iter = self._dataloader_len = None 951 self.logger.error("Engine run is terminating due to exception: %s.", str(e)) --> 952 self._handle_exception(e) 953 954 self._dataloader_iter = self._dataloader_len = None /opt/conda/lib/python3.7/site-packages/ignite/engine/engine.py in _handle_exception(self, e) 714 self._fire_event(Events.EXCEPTION_RAISED, e) 715 else: --> 716 raise e 717 718 def state_dict(self): /opt/conda/lib/python3.7/site-packages/ignite/engine/engine.py in _internal_run(self) 933 934 if self._dataloader_iter is None: --> 935 self._setup_engine() 936 937 hours, mins, secs = self._run_once_on_dataset() /opt/conda/lib/python3.7/site-packages/ignite/engine/engine.py in _setup_engine(self) 873 if not isinstance(batch_sampler, ReproducibleBatchSampler): 874 self.state.dataloader = _update_dataloader(self.state.dataloader, --> 875 ReproducibleBatchSampler(batch_sampler)) 876 877 iteration = self.state.iteration /opt/conda/lib/python3.7/site-packages/ignite/engine/engine.py in _update_dataloader(dataloader, new_batch_sampler) 963 params = {k: getattr(dataloader, k) for k in params_keys} 964 params['batch_sampler'] = new_batch_sampler --> 965 return torch.utils.data.DataLoader(**params) 966 967 /opt/conda/lib/python3.7/site-packages/torch/utils/data/dataloader.py in __init__(self, dataset, batch_size, shuffle, sampler, batch_sampler, num_workers, collate_fn, pin_memory, drop_last, timeout, worker_init_fn, multiprocessing_context) 182 raise ValueError( 183 "DataLoader with IterableDataset: expected unspecified " --> 184 "batch_sampler option, but got batch_sampler={}".format(batch_sampler)) 185 else: 186 self._dataset_kind = _DatasetKind.Map ValueError: DataLoader with IterableDataset: expected unspecified batch_sampler option, but got batch_sampler=<ignite.engine.engine.ReproducibleBatchSampler object at 0x7f6000e3fad0>
ValueError
def _from_iteration(data, iteration): if isinstance(data, torch.utils.data.DataLoader): try: # following is unsafe for IterableDatasets iteration %= len(data.batch_sampler) if iteration > 0: # batch sampler is ReproducibleBatchSampler data.batch_sampler.start_iteration = iteration except TypeError: # Probably we can do nothing with DataLoader built upon IterableDatasets pass data_iter = iter(data) else: if hasattr(data, "__len__"): iteration %= len(data) data_iter = iter(data) counter = 0 while counter < iteration: try: next(data_iter) counter += 1 except StopIteration: data_iter = iter(data) return data_iter
def _from_iteration(data, iteration, epoch_length): if isinstance(data, torch.utils.data.DataLoader): iteration %= len(data.batch_sampler) if iteration > 0: # batch sampler is ReproducibleBatchSampler data.batch_sampler.start_iteration = iteration data_iter = iter(data) else: if hasattr(data, "__len__"): iteration %= len(data) data_iter = iter(data) counter = 0 while counter < iteration: try: next(data_iter) counter += 1 except StopIteration: data_iter = iter(data) return data_iter
https://github.com/pytorch/ignite/issues/714
ValueErrorTraceback (most recent call last) <ipython-input-19-1c8004fbf46e> in <module> 21 22 engine = Engine(foo) ---> 23 engine.run(data_loader, epoch_length=10) /opt/conda/lib/python3.7/site-packages/ignite/engine/engine.py in run(self, data, max_epochs, epoch_length, seed) 848 849 self.state.dataloader = data --> 850 return self._internal_run() 851 852 def _setup_engine(self): /opt/conda/lib/python3.7/site-packages/ignite/engine/engine.py in _internal_run(self) 950 self._dataloader_iter = self._dataloader_len = None 951 self.logger.error("Engine run is terminating due to exception: %s.", str(e)) --> 952 self._handle_exception(e) 953 954 self._dataloader_iter = self._dataloader_len = None /opt/conda/lib/python3.7/site-packages/ignite/engine/engine.py in _handle_exception(self, e) 714 self._fire_event(Events.EXCEPTION_RAISED, e) 715 else: --> 716 raise e 717 718 def state_dict(self): /opt/conda/lib/python3.7/site-packages/ignite/engine/engine.py in _internal_run(self) 933 934 if self._dataloader_iter is None: --> 935 self._setup_engine() 936 937 hours, mins, secs = self._run_once_on_dataset() /opt/conda/lib/python3.7/site-packages/ignite/engine/engine.py in _setup_engine(self) 873 if not isinstance(batch_sampler, ReproducibleBatchSampler): 874 self.state.dataloader = _update_dataloader(self.state.dataloader, --> 875 ReproducibleBatchSampler(batch_sampler)) 876 877 iteration = self.state.iteration /opt/conda/lib/python3.7/site-packages/ignite/engine/engine.py in _update_dataloader(dataloader, new_batch_sampler) 963 params = {k: getattr(dataloader, k) for k in params_keys} 964 params['batch_sampler'] = new_batch_sampler --> 965 return torch.utils.data.DataLoader(**params) 966 967 /opt/conda/lib/python3.7/site-packages/torch/utils/data/dataloader.py in __init__(self, dataset, batch_size, shuffle, sampler, batch_sampler, num_workers, collate_fn, pin_memory, drop_last, timeout, worker_init_fn, multiprocessing_context) 182 raise ValueError( 183 "DataLoader with IterableDataset: expected unspecified " --> 184 "batch_sampler option, but got batch_sampler={}".format(batch_sampler)) 185 else: 186 self._dataset_kind = _DatasetKind.Map ValueError: DataLoader with IterableDataset: expected unspecified batch_sampler option, but got batch_sampler=<ignite.engine.engine.ReproducibleBatchSampler object at 0x7f6000e3fad0>
ValueError
def __call__(self, engine, logger, event_name): if not isinstance(logger, TensorboardLogger): raise RuntimeError( "Handler 'WeightsScalarHandler' works only with TensorboardLogger" ) global_step = engine.state.get_event_attrib_value(event_name) for name, p in self.model.named_parameters(): if p.grad is None: continue name = name.replace(".", "/") logger.writer.add_scalar( "weights_{}/{}".format(self.reduction.__name__, name), self.reduction(p.data), global_step, )
def __call__(self, engine, logger, event_name): if not isinstance(logger, TensorboardLogger): raise RuntimeError( "Handler 'WeightsScalarHandler' works only with TensorboardLogger" ) global_step = engine.state.get_event_attrib_value(event_name) for name, p in self.model.named_parameters(): name = name.replace(".", "/") logger.writer.add_scalar( "weights_{}/{}".format(self.reduction.__name__, name), self.reduction(p.data), global_step, )
https://github.com/pytorch/ignite/issues/514
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-3-5ffffec84f3c> in <module> 65 print("Done.") 66 ---> 67 example() <ipython-input-3-5ffffec84f3c> in example() 62 63 ---> 64 trainer.run(DataLoader(FakeDataset(), batch_size=16), max_epochs=5) 65 print("Done.") 66 /anaconda3/envs/ignite/lib/python3.7/site-packages/pytorch_ignite-0.2.0-py3.7.egg/ignite/engine/engine.py in run(self, data, max_epochs) 357 except BaseException as e: 358 self._logger.error("Engine run is terminating due to exception: %s.", str(e)) --> 359 self._handle_exception(e) 360 361 return self.state /anaconda3/envs/ignite/lib/python3.7/site-packages/pytorch_ignite-0.2.0-py3.7.egg/ignite/engine/engine.py in _handle_exception(self, e) 322 self._fire_event(Events.EXCEPTION_RAISED, e) 323 else: --> 324 raise e 325 326 def run(self, data, max_epochs=1): /anaconda3/envs/ignite/lib/python3.7/site-packages/pytorch_ignite-0.2.0-py3.7.egg/ignite/engine/engine.py in run(self, data, max_epochs) 344 self.state.epoch += 1 345 self._fire_event(Events.EPOCH_STARTED) --> 346 hours, mins, secs = self._run_once_on_dataset() 347 self._logger.info("Epoch[%s] Complete. Time taken: %02d:%02d:%02d", self.state.epoch, hours, mins, secs) 348 if self.should_terminate: /anaconda3/envs/ignite/lib/python3.7/site-packages/pytorch_ignite-0.2.0-py3.7.egg/ignite/engine/engine.py in _run_once_on_dataset(self) 311 except BaseException as e: 312 self._logger.error("Current run is terminating due to exception: %s.", str(e)) --> 313 self._handle_exception(e) 314 315 time_taken = time.time() - start_time /anaconda3/envs/ignite/lib/python3.7/site-packages/pytorch_ignite-0.2.0-py3.7.egg/ignite/engine/engine.py in _handle_exception(self, e) 322 self._fire_event(Events.EXCEPTION_RAISED, e) 323 else: --> 324 raise e 325 326 def run(self, data, max_epochs=1): /anaconda3/envs/ignite/lib/python3.7/site-packages/pytorch_ignite-0.2.0-py3.7.egg/ignite/engine/engine.py in _run_once_on_dataset(self) 304 self._fire_event(Events.ITERATION_STARTED) 305 self.state.output = self._process_function(self, batch) --> 306 self._fire_event(Events.ITERATION_COMPLETED) 307 if self.should_terminate or self.should_terminate_single_epoch: 308 self.should_terminate_single_epoch = False /anaconda3/envs/ignite/lib/python3.7/site-packages/pytorch_ignite-0.2.0-py3.7.egg/ignite/engine/engine.py in _fire_event(self, event_name, *event_args, **event_kwargs) 257 for func, args, kwargs in self._event_handlers[event_name]: 258 kwargs.update(event_kwargs) --> 259 func(self, *(event_args + args), **kwargs) 260 261 def fire_event(self, event_name): /anaconda3/envs/ignite/lib/python3.7/site-packages/pytorch_ignite-0.2.0-py3.7.egg/ignite/contrib/handlers/tensorboard_logger.py in __call__(self, engine, logger, event_name) 219 name = name.replace('.', '/') 220 logger.writer.add_scalar("grads_{}/{}".format(self.reduction.__name__, name), --> 221 self.reduction(p.grad), 222 global_step) 223 /anaconda3/envs/ignite/lib/python3.7/site-packages/torch/functional.py in norm(input, p, dim, keepdim, out, dtype) 676 (tensor(3.7417), tensor(11.2250)) 677 """ --> 678 ndim = input.dim() 679 680 # catch default case AttributeError: 'NoneType' object has no attribute 'dim'
AttributeError
def __call__(self, engine, logger, event_name): if not isinstance(logger, TensorboardLogger): raise RuntimeError( "Handler 'WeightsHistHandler' works only with TensorboardLogger" ) global_step = engine.state.get_event_attrib_value(event_name) for name, p in self.model.named_parameters(): if p.grad is None: continue name = name.replace(".", "/") logger.writer.add_histogram( tag="weights/{}".format(name), values=p.data.detach().cpu().numpy(), global_step=global_step, )
def __call__(self, engine, logger, event_name): if not isinstance(logger, TensorboardLogger): raise RuntimeError( "Handler 'WeightsHistHandler' works only with TensorboardLogger" ) global_step = engine.state.get_event_attrib_value(event_name) for name, p in self.model.named_parameters(): name = name.replace(".", "/") logger.writer.add_histogram( tag="weights/{}".format(name), values=p.data.detach().cpu().numpy(), global_step=global_step, )
https://github.com/pytorch/ignite/issues/514
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-3-5ffffec84f3c> in <module> 65 print("Done.") 66 ---> 67 example() <ipython-input-3-5ffffec84f3c> in example() 62 63 ---> 64 trainer.run(DataLoader(FakeDataset(), batch_size=16), max_epochs=5) 65 print("Done.") 66 /anaconda3/envs/ignite/lib/python3.7/site-packages/pytorch_ignite-0.2.0-py3.7.egg/ignite/engine/engine.py in run(self, data, max_epochs) 357 except BaseException as e: 358 self._logger.error("Engine run is terminating due to exception: %s.", str(e)) --> 359 self._handle_exception(e) 360 361 return self.state /anaconda3/envs/ignite/lib/python3.7/site-packages/pytorch_ignite-0.2.0-py3.7.egg/ignite/engine/engine.py in _handle_exception(self, e) 322 self._fire_event(Events.EXCEPTION_RAISED, e) 323 else: --> 324 raise e 325 326 def run(self, data, max_epochs=1): /anaconda3/envs/ignite/lib/python3.7/site-packages/pytorch_ignite-0.2.0-py3.7.egg/ignite/engine/engine.py in run(self, data, max_epochs) 344 self.state.epoch += 1 345 self._fire_event(Events.EPOCH_STARTED) --> 346 hours, mins, secs = self._run_once_on_dataset() 347 self._logger.info("Epoch[%s] Complete. Time taken: %02d:%02d:%02d", self.state.epoch, hours, mins, secs) 348 if self.should_terminate: /anaconda3/envs/ignite/lib/python3.7/site-packages/pytorch_ignite-0.2.0-py3.7.egg/ignite/engine/engine.py in _run_once_on_dataset(self) 311 except BaseException as e: 312 self._logger.error("Current run is terminating due to exception: %s.", str(e)) --> 313 self._handle_exception(e) 314 315 time_taken = time.time() - start_time /anaconda3/envs/ignite/lib/python3.7/site-packages/pytorch_ignite-0.2.0-py3.7.egg/ignite/engine/engine.py in _handle_exception(self, e) 322 self._fire_event(Events.EXCEPTION_RAISED, e) 323 else: --> 324 raise e 325 326 def run(self, data, max_epochs=1): /anaconda3/envs/ignite/lib/python3.7/site-packages/pytorch_ignite-0.2.0-py3.7.egg/ignite/engine/engine.py in _run_once_on_dataset(self) 304 self._fire_event(Events.ITERATION_STARTED) 305 self.state.output = self._process_function(self, batch) --> 306 self._fire_event(Events.ITERATION_COMPLETED) 307 if self.should_terminate or self.should_terminate_single_epoch: 308 self.should_terminate_single_epoch = False /anaconda3/envs/ignite/lib/python3.7/site-packages/pytorch_ignite-0.2.0-py3.7.egg/ignite/engine/engine.py in _fire_event(self, event_name, *event_args, **event_kwargs) 257 for func, args, kwargs in self._event_handlers[event_name]: 258 kwargs.update(event_kwargs) --> 259 func(self, *(event_args + args), **kwargs) 260 261 def fire_event(self, event_name): /anaconda3/envs/ignite/lib/python3.7/site-packages/pytorch_ignite-0.2.0-py3.7.egg/ignite/contrib/handlers/tensorboard_logger.py in __call__(self, engine, logger, event_name) 219 name = name.replace('.', '/') 220 logger.writer.add_scalar("grads_{}/{}".format(self.reduction.__name__, name), --> 221 self.reduction(p.grad), 222 global_step) 223 /anaconda3/envs/ignite/lib/python3.7/site-packages/torch/functional.py in norm(input, p, dim, keepdim, out, dtype) 676 (tensor(3.7417), tensor(11.2250)) 677 """ --> 678 ndim = input.dim() 679 680 # catch default case AttributeError: 'NoneType' object has no attribute 'dim'
AttributeError
def __call__(self, engine, logger, event_name): if not isinstance(logger, TensorboardLogger): raise RuntimeError( "Handler 'GradsScalarHandler' works only with TensorboardLogger" ) global_step = engine.state.get_event_attrib_value(event_name) for name, p in self.model.named_parameters(): if p.grad is None: continue name = name.replace(".", "/") logger.writer.add_scalar( "grads_{}/{}".format(self.reduction.__name__, name), self.reduction(p.grad), global_step, )
def __call__(self, engine, logger, event_name): if not isinstance(logger, TensorboardLogger): raise RuntimeError( "Handler 'GradsScalarHandler' works only with TensorboardLogger" ) global_step = engine.state.get_event_attrib_value(event_name) for name, p in self.model.named_parameters(): name = name.replace(".", "/") logger.writer.add_scalar( "grads_{}/{}".format(self.reduction.__name__, name), self.reduction(p.grad), global_step, )
https://github.com/pytorch/ignite/issues/514
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-3-5ffffec84f3c> in <module> 65 print("Done.") 66 ---> 67 example() <ipython-input-3-5ffffec84f3c> in example() 62 63 ---> 64 trainer.run(DataLoader(FakeDataset(), batch_size=16), max_epochs=5) 65 print("Done.") 66 /anaconda3/envs/ignite/lib/python3.7/site-packages/pytorch_ignite-0.2.0-py3.7.egg/ignite/engine/engine.py in run(self, data, max_epochs) 357 except BaseException as e: 358 self._logger.error("Engine run is terminating due to exception: %s.", str(e)) --> 359 self._handle_exception(e) 360 361 return self.state /anaconda3/envs/ignite/lib/python3.7/site-packages/pytorch_ignite-0.2.0-py3.7.egg/ignite/engine/engine.py in _handle_exception(self, e) 322 self._fire_event(Events.EXCEPTION_RAISED, e) 323 else: --> 324 raise e 325 326 def run(self, data, max_epochs=1): /anaconda3/envs/ignite/lib/python3.7/site-packages/pytorch_ignite-0.2.0-py3.7.egg/ignite/engine/engine.py in run(self, data, max_epochs) 344 self.state.epoch += 1 345 self._fire_event(Events.EPOCH_STARTED) --> 346 hours, mins, secs = self._run_once_on_dataset() 347 self._logger.info("Epoch[%s] Complete. Time taken: %02d:%02d:%02d", self.state.epoch, hours, mins, secs) 348 if self.should_terminate: /anaconda3/envs/ignite/lib/python3.7/site-packages/pytorch_ignite-0.2.0-py3.7.egg/ignite/engine/engine.py in _run_once_on_dataset(self) 311 except BaseException as e: 312 self._logger.error("Current run is terminating due to exception: %s.", str(e)) --> 313 self._handle_exception(e) 314 315 time_taken = time.time() - start_time /anaconda3/envs/ignite/lib/python3.7/site-packages/pytorch_ignite-0.2.0-py3.7.egg/ignite/engine/engine.py in _handle_exception(self, e) 322 self._fire_event(Events.EXCEPTION_RAISED, e) 323 else: --> 324 raise e 325 326 def run(self, data, max_epochs=1): /anaconda3/envs/ignite/lib/python3.7/site-packages/pytorch_ignite-0.2.0-py3.7.egg/ignite/engine/engine.py in _run_once_on_dataset(self) 304 self._fire_event(Events.ITERATION_STARTED) 305 self.state.output = self._process_function(self, batch) --> 306 self._fire_event(Events.ITERATION_COMPLETED) 307 if self.should_terminate or self.should_terminate_single_epoch: 308 self.should_terminate_single_epoch = False /anaconda3/envs/ignite/lib/python3.7/site-packages/pytorch_ignite-0.2.0-py3.7.egg/ignite/engine/engine.py in _fire_event(self, event_name, *event_args, **event_kwargs) 257 for func, args, kwargs in self._event_handlers[event_name]: 258 kwargs.update(event_kwargs) --> 259 func(self, *(event_args + args), **kwargs) 260 261 def fire_event(self, event_name): /anaconda3/envs/ignite/lib/python3.7/site-packages/pytorch_ignite-0.2.0-py3.7.egg/ignite/contrib/handlers/tensorboard_logger.py in __call__(self, engine, logger, event_name) 219 name = name.replace('.', '/') 220 logger.writer.add_scalar("grads_{}/{}".format(self.reduction.__name__, name), --> 221 self.reduction(p.grad), 222 global_step) 223 /anaconda3/envs/ignite/lib/python3.7/site-packages/torch/functional.py in norm(input, p, dim, keepdim, out, dtype) 676 (tensor(3.7417), tensor(11.2250)) 677 """ --> 678 ndim = input.dim() 679 680 # catch default case AttributeError: 'NoneType' object has no attribute 'dim'
AttributeError
def __call__(self, engine, logger, event_name): if not isinstance(logger, TensorboardLogger): raise RuntimeError( "Handler 'GradsHistHandler' works only with TensorboardLogger" ) global_step = engine.state.get_event_attrib_value(event_name) for name, p in self.model.named_parameters(): if p.grad is None: continue name = name.replace(".", "/") logger.writer.add_histogram( tag="grads/{}".format(name), values=p.grad.detach().cpu().numpy(), global_step=global_step, )
def __call__(self, engine, logger, event_name): if not isinstance(logger, TensorboardLogger): raise RuntimeError( "Handler 'GradsHistHandler' works only with TensorboardLogger" ) global_step = engine.state.get_event_attrib_value(event_name) for name, p in self.model.named_parameters(): name = name.replace(".", "/") logger.writer.add_histogram( tag="grads/{}".format(name), values=p.grad.detach().cpu().numpy(), global_step=global_step, )
https://github.com/pytorch/ignite/issues/514
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-3-5ffffec84f3c> in <module> 65 print("Done.") 66 ---> 67 example() <ipython-input-3-5ffffec84f3c> in example() 62 63 ---> 64 trainer.run(DataLoader(FakeDataset(), batch_size=16), max_epochs=5) 65 print("Done.") 66 /anaconda3/envs/ignite/lib/python3.7/site-packages/pytorch_ignite-0.2.0-py3.7.egg/ignite/engine/engine.py in run(self, data, max_epochs) 357 except BaseException as e: 358 self._logger.error("Engine run is terminating due to exception: %s.", str(e)) --> 359 self._handle_exception(e) 360 361 return self.state /anaconda3/envs/ignite/lib/python3.7/site-packages/pytorch_ignite-0.2.0-py3.7.egg/ignite/engine/engine.py in _handle_exception(self, e) 322 self._fire_event(Events.EXCEPTION_RAISED, e) 323 else: --> 324 raise e 325 326 def run(self, data, max_epochs=1): /anaconda3/envs/ignite/lib/python3.7/site-packages/pytorch_ignite-0.2.0-py3.7.egg/ignite/engine/engine.py in run(self, data, max_epochs) 344 self.state.epoch += 1 345 self._fire_event(Events.EPOCH_STARTED) --> 346 hours, mins, secs = self._run_once_on_dataset() 347 self._logger.info("Epoch[%s] Complete. Time taken: %02d:%02d:%02d", self.state.epoch, hours, mins, secs) 348 if self.should_terminate: /anaconda3/envs/ignite/lib/python3.7/site-packages/pytorch_ignite-0.2.0-py3.7.egg/ignite/engine/engine.py in _run_once_on_dataset(self) 311 except BaseException as e: 312 self._logger.error("Current run is terminating due to exception: %s.", str(e)) --> 313 self._handle_exception(e) 314 315 time_taken = time.time() - start_time /anaconda3/envs/ignite/lib/python3.7/site-packages/pytorch_ignite-0.2.0-py3.7.egg/ignite/engine/engine.py in _handle_exception(self, e) 322 self._fire_event(Events.EXCEPTION_RAISED, e) 323 else: --> 324 raise e 325 326 def run(self, data, max_epochs=1): /anaconda3/envs/ignite/lib/python3.7/site-packages/pytorch_ignite-0.2.0-py3.7.egg/ignite/engine/engine.py in _run_once_on_dataset(self) 304 self._fire_event(Events.ITERATION_STARTED) 305 self.state.output = self._process_function(self, batch) --> 306 self._fire_event(Events.ITERATION_COMPLETED) 307 if self.should_terminate or self.should_terminate_single_epoch: 308 self.should_terminate_single_epoch = False /anaconda3/envs/ignite/lib/python3.7/site-packages/pytorch_ignite-0.2.0-py3.7.egg/ignite/engine/engine.py in _fire_event(self, event_name, *event_args, **event_kwargs) 257 for func, args, kwargs in self._event_handlers[event_name]: 258 kwargs.update(event_kwargs) --> 259 func(self, *(event_args + args), **kwargs) 260 261 def fire_event(self, event_name): /anaconda3/envs/ignite/lib/python3.7/site-packages/pytorch_ignite-0.2.0-py3.7.egg/ignite/contrib/handlers/tensorboard_logger.py in __call__(self, engine, logger, event_name) 219 name = name.replace('.', '/') 220 logger.writer.add_scalar("grads_{}/{}".format(self.reduction.__name__, name), --> 221 self.reduction(p.grad), 222 global_step) 223 /anaconda3/envs/ignite/lib/python3.7/site-packages/torch/functional.py in norm(input, p, dim, keepdim, out, dtype) 676 (tensor(3.7417), tensor(11.2250)) 677 """ --> 678 ndim = input.dim() 679 680 # catch default case AttributeError: 'NoneType' object has no attribute 'dim'
AttributeError
def _close(self, engine): if self.pbar: self.pbar.close() self.pbar = None
def _close(self, engine): self.pbar.close() self.pbar = None
https://github.com/pytorch/ignite/issues/499
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-36-b4ac10e6ccc4> in <module> ----> 1 trainer.run(train_ab_loader, max_epochs=200) /opt/conda/lib/python3.7/site-packages/ignite/engine/engine.py in run(self, data, max_epochs) 357 except BaseException as e: 358 self._logger.error("Engine run is terminating due to exception: %s.", str(e)) --> 359 self._handle_exception(e) 360 361 return self.state /opt/conda/lib/python3.7/site-packages/ignite/engine/engine.py in _handle_exception(self, e) 322 self._fire_event(Events.EXCEPTION_RAISED, e) 323 else: --> 324 raise e 325 326 def run(self, data, max_epochs=1): /opt/conda/lib/python3.7/site-packages/ignite/engine/engine.py in run(self, data, max_epochs) 350 self._fire_event(Events.EPOCH_COMPLETED) 351 --> 352 self._fire_event(Events.COMPLETED) 353 time_taken = time.time() - start_time 354 hours, mins, secs = _to_hours_mins_secs(time_taken) /opt/conda/lib/python3.7/site-packages/ignite/engine/engine.py in _fire_event(self, event_name, *event_args, **event_kwargs) 257 for func, args, kwargs in self._event_handlers[event_name]: 258 kwargs.update(event_kwargs) --> 259 func(self, *(event_args + args), **kwargs) 260 261 def fire_event(self, event_name): /opt/conda/lib/python3.7/site-packages/ignite/contrib/handlers/tqdm_logger.py in _close(self, engine) 115 116 def _close(self, engine): --> 117 self.pbar.close() 118 self.pbar = None 119 AttributeError: 'NoneType' object has no attribute 'close'
AttributeError
def _save(self, obj, path): if not self._atomic: torch.save(obj, path) else: tmp = tempfile.NamedTemporaryFile(delete=False, dir=self._dirname) try: torch.save(obj, tmp.file) except BaseException: tmp.close() os.remove(tmp.name) raise else: tmp.close() os.rename(tmp.name, path)
def _save(self, obj, path): if not self._atomic: torch.save(obj, path) else: tmp = tempfile.NamedTemporaryFile(delete=False) try: torch.save(obj, tmp.file) except BaseException: tmp.close() os.remove(tmp.name) raise else: tmp.close() os.rename(tmp.name, path)
https://github.com/pytorch/ignite/issues/114
Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/ignite-0.1.0a1-py3.5.egg/ignite/engines/trainer.py", line 53, in run self._handle_exception(state, e) File "/usr/local/lib/python3.5/dist-packages/ignite-0.1.0a1-py3.5.egg/ignite/engines/engine.py", line 138, in _handle_exception raise e File "/usr/local/lib/python3.5/dist-packages/ignite-0.1.0a1-py3.5.egg/ignite/engines/trainer.py", line 40, in run hours, mins, secs = self._run_once_on_dataset(state) File "/usr/local/lib/python3.5/dist-packages/ignite-0.1.0a1-py3.5.egg/ignite/engines/engine.py", line 132, in _run_once_on_dataset self._handle_exception(state, e) File "/usr/local/lib/python3.5/dist-packages/ignite-0.1.0a1-py3.5.egg/ignite/engines/engine.py", line 138, in _handle_exception raise e File "/usr/local/lib/python3.5/dist-packages/ignite-0.1.0a1-py3.5.egg/ignite/engines/engine.py", line 123, in _run_once_on_dataset self._fire_event(Events.ITERATION_COMPLETED, state) File "/usr/local/lib/python3.5/dist-packages/ignite-0.1.0a1-py3.5.egg/ignite/engines/engine.py", line 106, in _fire_event func(self, state, *(event_args + args), **kwargs) File "/usr/local/lib/python3.5/dist-packages/ignite-0.1.0a1-py3.5.egg/ignite/handlers/checkpoint.py", line 147, in __call__ self._save(obj=obj, path=path) File "/usr/local/lib/python3.5/dist-packages/ignite-0.1.0a1-py3.5.egg/ignite/handlers/checkpoint.py", line 124, in _save os.rename(tmp.name, path) OSError: [Errno 18] Invalid cross-device link: '/tmp/tmpe7shyxri' -> '/home/user/output/weights/_SSD300_1.pth'
OSError
def init(): logger = logging.getLogger(__name__) global __HTTP proxy_url = os.getenv("http_proxy") if proxy_url and len(proxy_url) > 0: parsed_url = urllib3.util.parse_url(proxy_url) logger.info( "Connecting via proxy URL [%s] to the Internet (picked up from the env variable [http_proxy]).", proxy_url, ) __HTTP = urllib3.ProxyManager( proxy_url, cert_reqs="CERT_REQUIRED", ca_certs=certifi.where(), # appropriate headers will only be set if there is auth info proxy_headers=urllib3.make_headers(proxy_basic_auth=parsed_url.auth), ) else: logger.info("Connecting directly to the Internet (no proxy support).") __HTTP = urllib3.PoolManager( cert_reqs="CERT_REQUIRED", ca_certs=certifi.where() )
def init(): logger = logging.getLogger(__name__) global __HTTP proxy_url = os.getenv("http_proxy") if proxy_url and len(proxy_url) > 0: logger.info( "Rally connects via proxy URL [%s] to the Internet (picked up from the environment variable [http_proxy]).", proxy_url, ) __HTTP = urllib3.ProxyManager( proxy_url, cert_reqs="CERT_REQUIRED", ca_certs=certifi.where() ) else: logger.info("Rally connects directly to the Internet (no proxy support).") __HTTP = urllib3.PoolManager( cert_reqs="CERT_REQUIRED", ca_certs=certifi.where() )
https://github.com/elastic/rally/issues/636
2019-01-23 15:19:43,262 -not-actor-/PID:16740 esrally.utils.net INFO Rally connects via proxy URL [http://username:pw@1.2.3.4:8080] to the Internet (picked up from the environment variable [http_proxy]). 2019-01-23 15:19:43,263 -not-actor-/PID:16740 esrally.utils.net DEBUG Checking for internet connection against [https://github.com/] 2019-01-23 15:19:43,347 -not-actor-/PID:16740 esrally.utils.net DEBUG Could not detect a working Internet connection Traceback (most recent call last): File "/usr/local/python3/lib/python3.6/site-packages/urllib3/connectionpool.py", line 595, in urlopen self._prepare_proxy(conn) File "/usr/local/python3/lib/python3.6/site-packages/urllib3/connectionpool.py", line 816, in _prepare_proxy conn.connect() File "/usr/local/python3/lib/python3.6/site-packages/urllib3/connection.py", line 294, in connect self._tunnel() File "/usr/local/python3/lib/python3.6/http/client.py", line 919, in _tunnel message.strip())) OSError: Tunnel connection failed: 407 Proxy Authentication Required
OSError
def load(self): config = configparser.ConfigParser() config.read(self.location, encoding="utf-8") return config
def load(self, interpolation=configparser.ExtendedInterpolation()): config = configparser.ConfigParser(interpolation=interpolation) config.read(self.location, encoding="utf-8") return config
https://github.com/elastic/rally/issues/519
Traceback (most recent call last): File "/usr/local/bin/esrally", line 11, in <module> sys.exit(main()) File "/usr/local/lib/python3.6/site-packages/esrally/rally.py", line 588, in main ensure_configuration_present(cfg, args, sub_command) File "/usr/local/lib/python3.6/site-packages/esrally/rally.py", line 428, in ensure_configuration_present cfg.load_config(auto_upgrade=True) File "/usr/local/lib/python3.6/site-packages/esrally/config.py", line 206, in load_config self.migrate_config() File "/usr/local/lib/python3.6/site-packages/esrally/config.py", line 239, in migrate_config migrate(self.config_file, self._stored_config_version(), Config.CURRENT_CONFIG_VERSION) File "/usr/local/lib/python3.6/site-packages/esrally/config.py", line 588, in migrate .format(config_file.location, PROGRAM_NAME)) esrally.config.ConfigError: ('The config file in /home/ubuntu/.rally/rally.ini is too old. Please delete it and reconfigure Rally from scratch with esrally configure.', None)
esrally.config.ConfigError
def create_config(self, config_file, advanced_config=False, assume_defaults=False): """ Either creates a new configuration file or overwrites an existing one. Will ask the user for input on configurable properties and writes them to the configuration file in ~/.rally/rally.ini. :param config_file: :param advanced_config: Whether to ask for properties that are not necessary for everyday use (on a dev machine). Default: False. :param assume_defaults: If True, assume the user accepted all values for which defaults are provided. Mainly intended for automatic configuration in CI run. Default: False. """ self.prompter = Prompter(self.i, self.sec_i, self.o, assume_defaults) if advanced_config: self.o("Running advanced configuration. You can get additional help at:") self.o("") self.o(" %s" % console.format.link("%sconfiguration.html" % DOC_LINK)) self.o("") else: self.o("Running simple configuration. Run the advanced configuration with:") self.o("") self.o(" %s configure --advanced-config" % PROGRAM_NAME) self.o("") if config_file.present: self.o( "\nWARNING: Will overwrite existing config file at [%s]\n" % config_file.location ) self.logger.debug( "Detected an existing configuration file at [%s]", config_file.location ) else: self.logger.debug( "Did not detect a configuration file at [%s]. Running initial configuration routine.", config_file.location, ) root_dir = io.normalize_path( os.path.abspath(os.path.join(config_file.config_dir, "benchmarks")) ) if advanced_config: root_dir = io.normalize_path( self._ask_property( "Enter the benchmark data directory", default_value=root_dir ) ) else: self.o("* Setting up benchmark data directory in %s" % root_dir) # We try to autodetect an existing ES source directory guess = self._guess_es_src_dir() if guess: source_dir = guess self.logger.debug( "Autodetected Elasticsearch project directory at [%s].", source_dir ) else: default_src_dir = os.path.join(root_dir, "src", "elasticsearch") self.logger.debug( "Could not autodetect Elasticsearch project directory. Providing [%s] as default.", default_src_dir, ) source_dir = default_src_dir if advanced_config: source_dir = io.normalize_path( self._ask_property( "Enter your Elasticsearch project directory:", default_value=source_dir ) ) if not advanced_config: self.o("* Setting up benchmark source directory in %s" % source_dir) self.o("") # Not everybody might have SSH access. Play safe with the default. It may be slower but this will work for everybody. repo_url = "https://github.com/elastic/elasticsearch.git" if advanced_config: data_store_choice = self._ask_property( "Where should metrics be kept?" "\n\n" "(1) In memory (simpler but less options for analysis)\n" "(2) Elasticsearch (requires a separate ES instance, keeps all raw samples for analysis)" "\n\n", default_value="1", choices=["1", "2"], ) if data_store_choice == "1": env_name = "local" data_store_type = "in-memory" ( data_store_host, data_store_port, data_store_secure, data_store_user, data_store_password, ) = "", "", "", "", "" else: data_store_type = "elasticsearch" ( data_store_host, data_store_port, data_store_secure, data_store_user, data_store_password, ) = self._ask_data_store() env_name = self._ask_env_name() preserve_install = convert.to_bool( self._ask_property( "Do you want Rally to keep the Elasticsearch benchmark candidate " "installation including the index (will use several GB per trial run)?", default_value=False, ) ) else: # Does not matter for an in-memory store env_name = "local" data_store_type = "in-memory" ( data_store_host, data_store_port, data_store_secure, data_store_user, data_store_password, ) = "", "", "", "", "" preserve_install = False config = configparser.ConfigParser() config["meta"] = {} config["meta"]["config.version"] = str(Config.CURRENT_CONFIG_VERSION) config["system"] = {} config["system"]["env.name"] = env_name config["node"] = {} config["node"]["root.dir"] = root_dir final_source_dir = io.normalize_path( os.path.abspath(os.path.join(source_dir, os.pardir)) ) config["node"]["src.root.dir"] = final_source_dir config["source"] = {} config["source"]["remote.repo.url"] = repo_url # the Elasticsearch directory is just the last path component (relative to the source root directory) config["source"]["elasticsearch.src.subdir"] = io.basename(source_dir) config["benchmarks"] = {} config["benchmarks"]["local.dataset.cache"] = os.path.join(root_dir, "data") config["reporting"] = {} config["reporting"]["datastore.type"] = data_store_type config["reporting"]["datastore.host"] = data_store_host config["reporting"]["datastore.port"] = data_store_port config["reporting"]["datastore.secure"] = data_store_secure config["reporting"]["datastore.user"] = data_store_user config["reporting"]["datastore.password"] = data_store_password config["tracks"] = {} config["tracks"]["default.url"] = "https://github.com/elastic/rally-tracks" config["teams"] = {} config["teams"]["default.url"] = "https://github.com/elastic/rally-teams" config["defaults"] = {} config["defaults"]["preserve_benchmark_candidate"] = str(preserve_install) config["distributions"] = {} config["distributions"]["release.cache"] = "true" config_file.store(config) self.o( "Configuration successfully written to %s. Happy benchmarking!" % config_file.location ) self.o("") self.o("More info about Rally:") self.o("") self.o("* Type %s --help" % PROGRAM_NAME) self.o("* Read the documentation at %s" % console.format.link(DOC_LINK)) self.o( "* Ask a question on the forum at %s" % console.format.link("https://discuss.elastic.co/c/elasticsearch/rally") )
def create_config(self, config_file, advanced_config=False, assume_defaults=False): """ Either creates a new configuration file or overwrites an existing one. Will ask the user for input on configurable properties and writes them to the configuration file in ~/.rally/rally.ini. :param config_file: :param advanced_config: Whether to ask for properties that are not necessary for everyday use (on a dev machine). Default: False. :param assume_defaults: If True, assume the user accepted all values for which defaults are provided. Mainly intended for automatic configuration in CI run. Default: False. """ self.prompter = Prompter(self.i, self.sec_i, self.o, assume_defaults) if advanced_config: self.o("Running advanced configuration. You can get additional help at:") self.o("") self.o(" %s" % console.format.link("%sconfiguration.html" % DOC_LINK)) self.o("") else: self.o("Running simple configuration. Run the advanced configuration with:") self.o("") self.o(" %s configure --advanced-config" % PROGRAM_NAME) self.o("") if config_file.present: self.o( "\nWARNING: Will overwrite existing config file at [%s]\n" % config_file.location ) self.logger.debug( "Detected an existing configuration file at [%s]", config_file.location ) else: self.logger.debug( "Did not detect a configuration file at [%s]. Running initial configuration routine.", config_file.location, ) root_dir = io.normalize_path( os.path.abspath(os.path.join(config_file.config_dir, "benchmarks")) ) if advanced_config: root_dir = io.normalize_path( self._ask_property( "Enter the benchmark data directory", default_value=root_dir ) ) else: self.o("* Setting up benchmark data directory in %s" % root_dir) # We try to autodetect an existing ES source directory guess = self._guess_es_src_dir() if guess: source_dir = guess self.logger.debug( "Autodetected Elasticsearch project directory at [%s].", source_dir ) else: default_src_dir = os.path.join(root_dir, "src", "elasticsearch") self.logger.debug( "Could not autodetect Elasticsearch project directory. Providing [%s] as default.", default_src_dir, ) source_dir = default_src_dir if advanced_config: source_dir = io.normalize_path( self._ask_property( "Enter your Elasticsearch project directory:", default_value=source_dir ) ) if not advanced_config: self.o("* Setting up benchmark source directory in %s" % source_dir) self.o("") # Not everybody might have SSH access. Play safe with the default. It may be slower but this will work for everybody. repo_url = "https://github.com/elastic/elasticsearch.git" if advanced_config: data_store_choice = self._ask_property( "Where should metrics be kept?" "\n\n" "(1) In memory (simpler but less options for analysis)\n" "(2) Elasticsearch (requires a separate ES instance, keeps all raw samples for analysis)" "\n\n", default_value="1", choices=["1", "2"], ) if data_store_choice == "1": env_name = "local" data_store_type = "in-memory" ( data_store_host, data_store_port, data_store_secure, data_store_user, data_store_password, ) = "", "", "", "", "" else: data_store_type = "elasticsearch" ( data_store_host, data_store_port, data_store_secure, data_store_user, data_store_password, ) = self._ask_data_store() env_name = self._ask_env_name() preserve_install = convert.to_bool( self._ask_property( "Do you want Rally to keep the Elasticsearch benchmark candidate " "installation including the index (will use several GB per trial run)?", default_value=False, ) ) else: # Does not matter for an in-memory store env_name = "local" data_store_type = "in-memory" ( data_store_host, data_store_port, data_store_secure, data_store_user, data_store_password, ) = "", "", "", "", "" preserve_install = False config = configparser.ConfigParser() config["meta"] = {} config["meta"]["config.version"] = str(Config.CURRENT_CONFIG_VERSION) config["system"] = {} config["system"]["env.name"] = env_name config["node"] = {} config["node"]["root.dir"] = root_dir final_source_dir = io.normalize_path( os.path.abspath(os.path.join(source_dir, os.pardir)) ) config["node"]["src.root.dir"] = final_source_dir config["source"] = {} config["source"]["remote.repo.url"] = repo_url # the Elasticsearch directory is just the last path component (relative to the source root directory) config["source"]["elasticsearch.src.subdir"] = io.basename(source_dir) config["benchmarks"] = {} config["benchmarks"]["local.dataset.cache"] = "${node:root.dir}/data" config["reporting"] = {} config["reporting"]["datastore.type"] = data_store_type config["reporting"]["datastore.host"] = data_store_host config["reporting"]["datastore.port"] = data_store_port config["reporting"]["datastore.secure"] = data_store_secure config["reporting"]["datastore.user"] = data_store_user config["reporting"]["datastore.password"] = data_store_password config["tracks"] = {} config["tracks"]["default.url"] = "https://github.com/elastic/rally-tracks" config["teams"] = {} config["teams"]["default.url"] = "https://github.com/elastic/rally-teams" config["defaults"] = {} config["defaults"]["preserve_benchmark_candidate"] = str(preserve_install) config["distributions"] = {} config["distributions"]["release.cache"] = "true" config_file.store(config) self.o( "Configuration successfully written to %s. Happy benchmarking!" % config_file.location ) self.o("") self.o("More info about Rally:") self.o("") self.o("* Type %s --help" % PROGRAM_NAME) self.o("* Read the documentation at %s" % console.format.link(DOC_LINK)) self.o( "* Ask a question on the forum at %s" % console.format.link("https://discuss.elastic.co/c/elasticsearch/rally") )
https://github.com/elastic/rally/issues/519
Traceback (most recent call last): File "/usr/local/bin/esrally", line 11, in <module> sys.exit(main()) File "/usr/local/lib/python3.6/site-packages/esrally/rally.py", line 588, in main ensure_configuration_present(cfg, args, sub_command) File "/usr/local/lib/python3.6/site-packages/esrally/rally.py", line 428, in ensure_configuration_present cfg.load_config(auto_upgrade=True) File "/usr/local/lib/python3.6/site-packages/esrally/config.py", line 206, in load_config self.migrate_config() File "/usr/local/lib/python3.6/site-packages/esrally/config.py", line 239, in migrate_config migrate(self.config_file, self._stored_config_version(), Config.CURRENT_CONFIG_VERSION) File "/usr/local/lib/python3.6/site-packages/esrally/config.py", line 588, in migrate .format(config_file.location, PROGRAM_NAME)) esrally.config.ConfigError: ('The config file in /home/ubuntu/.rally/rally.ini is too old. Please delete it and reconfigure Rally from scratch with esrally configure.', None)
esrally.config.ConfigError
def migrate(config_file, current_version, target_version, out=print, i=input): logger = logging.getLogger(__name__) if current_version < Config.EARLIEST_SUPPORTED_VERSION: raise ConfigError( "The config file in {} is too old. Please delete it and reconfigure Rally from scratch with {} configure.".format( config_file.location, PROGRAM_NAME ) ) prompter = Prompter(i=i, o=out, assume_defaults=False) logger.info( "Upgrading configuration from version [%s] to [%s].", current_version, target_version, ) # Something is really fishy. We don't want to downgrade the configuration. if current_version >= target_version: raise ConfigError( "The existing config file is available in a later version already. Expected version <= [%s] but found [%s]" % (target_version, current_version) ) # but first a backup... config_file.backup() config = config_file.load() if current_version == 12 and target_version > current_version: # the current configuration allows to benchmark from sources if "build" in config and "gradle.bin" in config["build"]: java_9_home = io.guess_java_home(major_version=9) from esrally.utils import jvm if java_9_home and not jvm.is_early_access_release(java_9_home): logger.debug("Autodetected a JDK 9 installation at [%s]", java_9_home) if "runtime" not in config: config["runtime"] = {} config["runtime"]["java9.home"] = java_9_home else: logger.debug( "Could not autodetect a JDK 9 installation. Checking [java.home] already points to a JDK 9." ) detected = False if "runtime" in config: java_home = config["runtime"]["java.home"] if jvm.major_version( java_home ) == 9 and not jvm.is_early_access_release(java_home): config["runtime"]["java9.home"] = java_home detected = True if not detected: logger.debug( "Could not autodetect a JDK 9 installation. Asking user." ) raw_java_9_home = prompter.ask_property( "Enter the JDK 9 root directory", check_path_exists=True, mandatory=False, ) if ( raw_java_9_home and jvm.major_version(raw_java_9_home) == 9 and not jvm.is_early_access_release(raw_java_9_home) ): java_9_home = ( io.normalize_path(raw_java_9_home) if raw_java_9_home else None ) config["runtime"]["java9.home"] = java_9_home else: out( "********************************************************************************" ) out( "You don't have a valid JDK 9 installation and cannot benchmark source builds." ) out("") out("You can still benchmark binary distributions with e.g.:") out("") out(" %s --distribution-version=6.0.0" % PROGRAM_NAME) out( "********************************************************************************" ) out("") current_version = 13 config["meta"]["config.version"] = str(current_version) if current_version == 13 and target_version > current_version: # This version replaced java9.home with java10.home if "build" in config and "gradle.bin" in config["build"]: java_10_home = io.guess_java_home(major_version=10) from esrally.utils import jvm if java_10_home and not jvm.is_early_access_release(java_10_home): logger.debug("Autodetected a JDK 10 installation at [%s]", java_10_home) if "runtime" not in config: config["runtime"] = {} config["runtime"]["java10.home"] = java_10_home else: logger.debug( "Could not autodetect a JDK 10 installation. Checking [java.home] already points to a JDK 10." ) detected = False if "runtime" in config: java_home = config["runtime"]["java.home"] if jvm.major_version( java_home ) == 10 and not jvm.is_early_access_release(java_home): config["runtime"]["java10.home"] = java_home detected = True if not detected: logger.debug( "Could not autodetect a JDK 10 installation. Asking user." ) raw_java_10_home = prompter.ask_property( "Enter the JDK 10 root directory", check_path_exists=True, mandatory=False, ) if ( raw_java_10_home and jvm.major_version(raw_java_10_home) == 10 and not jvm.is_early_access_release(raw_java_10_home) ): java_10_home = ( io.normalize_path(raw_java_10_home) if raw_java_10_home else None ) config["runtime"]["java10.home"] = java_10_home else: out( "********************************************************************************" ) out( "You don't have a valid JDK 10 installation and cannot benchmark source builds." ) out("") out("You can still benchmark binary distributions with e.g.:") out("") out(" %s --distribution-version=6.0.0" % PROGRAM_NAME) out( "********************************************************************************" ) out("") current_version = 14 config["meta"]["config.version"] = str(current_version) if current_version == 14 and target_version > current_version: # Be agnostic about build tools. Let use specify build commands for plugins and elasticsearch # but also use gradlew by default for Elasticsearch and Core plugin builds, if nothing else has been specified. def warn_if_plugin_build_task_is_in_use(config): if "source" not in config: return for k, v in config["source"].items(): plugin_match = re.match("^plugin\.([^.]+)\.build\.task$", k) if plugin_match != None and len(plugin_match.groups()) > 0: plugin_name = plugin_match.group(1) new_key = "plugin.{}.build.command".format(plugin_name) out( "\n" "WARNING:" " The build.task property for plugins has been obsoleted in favor of the full build.command." " You will need to edit the plugin [{}] section in {} and change from:" " [{} = {}] to [{} = <the full command>]." " Please refer to the documentation for more details:" " {}.\n".format( plugin_match.group(1), config_file.location, k, v, new_key, console.format.link( "%selasticsearch_plugins.html#running-a-benchmark-with-plugins" % DOC_LINK ), ) ) if "build" in config: logger.info( "Removing Gradle configuration as Rally now uses the Gradle Wrapper to build Elasticsearch." ) config.pop("build", None) warn_if_plugin_build_task_is_in_use(config) current_version = 15 config["meta"]["config.version"] = str(current_version) if current_version == 15 and target_version > current_version: if "distributions" in config: # Remove obsolete settings config["distributions"].pop("release.1.url", None) config["distributions"].pop("release.2.url", None) config["distributions"].pop("release.url", None) current_version = 16 config["meta"]["config.version"] = str(current_version) if current_version == 16 and target_version > current_version: config.pop("runtime", None) if "benchmarks" in config and "local.dataset.cache" in config["benchmarks"]: if config["benchmarks"]["local.dataset.cache"] == "${node:root.dir}/data": root_dir = config["node"]["root.dir"] config["benchmarks"]["local.dataset.cache"] = os.path.join( root_dir, "data" ) current_version = 17 config["meta"]["config.version"] = str(current_version) # all migrations done config_file.store(config) logger.info( "Successfully self-upgraded configuration to version [%s]", target_version )
def migrate(config_file, current_version, target_version, out=print, i=input): logger = logging.getLogger(__name__) if current_version < Config.EARLIEST_SUPPORTED_VERSION: raise ConfigError( "The config file in {} is too old. Please delete it and reconfigure Rally from scratch with {} configure.".format( config_file.location, PROGRAM_NAME ) ) prompter = Prompter(i=i, o=out, assume_defaults=False) logger.info( "Upgrading configuration from version [%s] to [%s].", current_version, target_version, ) # Something is really fishy. We don't want to downgrade the configuration. if current_version >= target_version: raise ConfigError( "The existing config file is available in a later version already. Expected version <= [%s] but found [%s]" % (target_version, current_version) ) # but first a backup... config_file.backup() config = config_file.load(interpolation=None) if current_version == 12 and target_version > current_version: # the current configuration allows to benchmark from sources if "build" in config and "gradle.bin" in config["build"]: java_9_home = io.guess_java_home(major_version=9) from esrally.utils import jvm if java_9_home and not jvm.is_early_access_release(java_9_home): logger.debug("Autodetected a JDK 9 installation at [%s]", java_9_home) if "runtime" not in config: config["runtime"] = {} config["runtime"]["java9.home"] = java_9_home else: logger.debug( "Could not autodetect a JDK 9 installation. Checking [java.home] already points to a JDK 9." ) detected = False if "runtime" in config: java_home = config["runtime"]["java.home"] if jvm.major_version( java_home ) == 9 and not jvm.is_early_access_release(java_home): config["runtime"]["java9.home"] = java_home detected = True if not detected: logger.debug( "Could not autodetect a JDK 9 installation. Asking user." ) raw_java_9_home = prompter.ask_property( "Enter the JDK 9 root directory", check_path_exists=True, mandatory=False, ) if ( raw_java_9_home and jvm.major_version(raw_java_9_home) == 9 and not jvm.is_early_access_release(raw_java_9_home) ): java_9_home = ( io.normalize_path(raw_java_9_home) if raw_java_9_home else None ) config["runtime"]["java9.home"] = java_9_home else: out( "********************************************************************************" ) out( "You don't have a valid JDK 9 installation and cannot benchmark source builds." ) out("") out("You can still benchmark binary distributions with e.g.:") out("") out(" %s --distribution-version=6.0.0" % PROGRAM_NAME) out( "********************************************************************************" ) out("") current_version = 13 config["meta"]["config.version"] = str(current_version) if current_version == 13 and target_version > current_version: # This version replaced java9.home with java10.home if "build" in config and "gradle.bin" in config["build"]: java_10_home = io.guess_java_home(major_version=10) from esrally.utils import jvm if java_10_home and not jvm.is_early_access_release(java_10_home): logger.debug("Autodetected a JDK 10 installation at [%s]", java_10_home) if "runtime" not in config: config["runtime"] = {} config["runtime"]["java10.home"] = java_10_home else: logger.debug( "Could not autodetect a JDK 10 installation. Checking [java.home] already points to a JDK 10." ) detected = False if "runtime" in config: java_home = config["runtime"]["java.home"] if jvm.major_version( java_home ) == 10 and not jvm.is_early_access_release(java_home): config["runtime"]["java10.home"] = java_home detected = True if not detected: logger.debug( "Could not autodetect a JDK 10 installation. Asking user." ) raw_java_10_home = prompter.ask_property( "Enter the JDK 10 root directory", check_path_exists=True, mandatory=False, ) if ( raw_java_10_home and jvm.major_version(raw_java_10_home) == 10 and not jvm.is_early_access_release(raw_java_10_home) ): java_10_home = ( io.normalize_path(raw_java_10_home) if raw_java_10_home else None ) config["runtime"]["java10.home"] = java_10_home else: out( "********************************************************************************" ) out( "You don't have a valid JDK 10 installation and cannot benchmark source builds." ) out("") out("You can still benchmark binary distributions with e.g.:") out("") out(" %s --distribution-version=6.0.0" % PROGRAM_NAME) out( "********************************************************************************" ) out("") current_version = 14 config["meta"]["config.version"] = str(current_version) if current_version == 14 and target_version > current_version: # Be agnostic about build tools. Let use specify build commands for plugins and elasticsearch # but also use gradlew by default for Elasticsearch and Core plugin builds, if nothing else has been specified. def warn_if_plugin_build_task_is_in_use(config): if "source" not in config: return for k, v in config["source"].items(): plugin_match = re.match("^plugin\.([^.]+)\.build\.task$", k) if plugin_match != None and len(plugin_match.groups()) > 0: plugin_name = plugin_match.group(1) new_key = "plugin.{}.build.command".format(plugin_name) out( "\n" "WARNING:" " The build.task property for plugins has been obsoleted in favor of the full build.command." " You will need to edit the plugin [{}] section in {} and change from:" " [{} = {}] to [{} = <the full command>]." " Please refer to the documentation for more details:" " {}.\n".format( plugin_match.group(1), config_file.location, k, v, new_key, console.format.link( "%selasticsearch_plugins.html#running-a-benchmark-with-plugins" % DOC_LINK ), ) ) if "build" in config: logger.info( "Removing Gradle configuration as Rally now uses the Gradle Wrapper to build Elasticsearch." ) config.pop("build", None) warn_if_plugin_build_task_is_in_use(config) current_version = 15 config["meta"]["config.version"] = str(current_version) if current_version == 15 and target_version > current_version: if "distributions" in config: # Remove obsolete settings config["distributions"].pop("release.1.url", None) config["distributions"].pop("release.2.url", None) config["distributions"].pop("release.url", None) current_version = 16 config["meta"]["config.version"] = str(current_version) if current_version == 16 and target_version > current_version: config.pop("runtime", None) current_version = 17 config["meta"]["config.version"] = str(current_version) # all migrations done config_file.store(config) logger.info( "Successfully self-upgraded configuration to version [%s]", target_version )
https://github.com/elastic/rally/issues/519
Traceback (most recent call last): File "/usr/local/bin/esrally", line 11, in <module> sys.exit(main()) File "/usr/local/lib/python3.6/site-packages/esrally/rally.py", line 588, in main ensure_configuration_present(cfg, args, sub_command) File "/usr/local/lib/python3.6/site-packages/esrally/rally.py", line 428, in ensure_configuration_present cfg.load_config(auto_upgrade=True) File "/usr/local/lib/python3.6/site-packages/esrally/config.py", line 206, in load_config self.migrate_config() File "/usr/local/lib/python3.6/site-packages/esrally/config.py", line 239, in migrate_config migrate(self.config_file, self._stored_config_version(), Config.CURRENT_CONFIG_VERSION) File "/usr/local/lib/python3.6/site-packages/esrally/config.py", line 588, in migrate .format(config_file.location, PROGRAM_NAME)) esrally.config.ConfigError: ('The config file in /home/ubuntu/.rally/rally.ini is too old. Please delete it and reconfigure Rally from scratch with esrally configure.', None)
esrally.config.ConfigError
def __init__(self, message: str) -> None: super().__init__() self.message = message
def __init__(self, ledger): self.ledger = ledger
https://github.com/beancount/fava/issues/1095
python3 Python 3.7.3 (default, Dec 20 2019, 18:57:59) [GCC 8.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. from fava.ext import FavaExtensionBase Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/tbm/.local/lib/python3.7/site-packages/fava/ext/__init__.py", line 11, in <module> from fava.core.helpers import BeancountError File "/home/tbm/.local/lib/python3.7/site-packages/fava/core/__init__.py", line 47, in <module> from fava.core.extensions import ExtensionModule File "/home/tbm/.local/lib/python3.7/site-packages/fava/core/extensions.py", line 12, in <module> from fava.ext import FavaExtensionBase ImportError: cannot import name 'FavaExtensionBase' from 'fava.ext' (/home/tbm/.local/lib/python3.7/site-packages/fava/ext/__init__.py) from fava.ext import FavaExtensionBase
ImportError
def generate_bql_grammar_json(): """Generate a JSON file with BQL grammar attributes. The online code editor needs to have the list of available columns, functions, and keywords for syntax highlighting and completion. Should be run whenever the BQL changes.""" target_env = query_env.TargetsEnvironment() data = { "columns": sorted(set(_env_to_list(target_env.columns))), "functions": sorted(set(_env_to_list(target_env.functions))), "keywords": sorted({kw.lower() for kw in query_parser.Lexer.keywords}), } path = os.path.join( os.path.dirname(__file__), "../fava/static/javascript/codemirror/bql-grammar.json", ) with open(path, "w", encoding="utf-8") as json_file: json.dump(data, json_file)
def generate_bql_grammar_json(): """Generate a JSON file with BQL grammar attributes. The online code editor needs to have the list of available columns, functions, and keywords for syntax highlighting and completion. Should be run whenever the BQL changes.""" target_env = query_env.TargetsEnvironment() data = { "columns": sorted(set(_env_to_list(target_env.columns))), "functions": sorted(set(_env_to_list(target_env.functions))), "keywords": sorted({kw.lower() for kw in query_parser.Lexer.keywords}), } path = os.path.join( os.path.dirname(__file__), "../fava/static/javascript/codemirror/bql-grammar.json", ) with open(path, "w") as json_file: json.dump(data, json_file)
https://github.com/beancount/fava/issues/883
D:\Documents\beancount>c:\Users\belidzs\PycharmProjects\beancount_virtualenv\Scripts\fava --debug fokonyv.beancount * Serving Flask app "fava.application" (lazy loading) * Environment: production WARNING: Do not use the development server in a production environment. Use a production WSGI server instead. * Debug mode: on * Restarting with stat * Debugger is active! * Debugger PIN: 546-083-666 * Running on http://localhost:5000/ (Press CTRL+C to quit) 127.0.0.1 - - [09/Mar/2019 10:48:22] "PUT /f%C5%91k%C3%B6nyv/api/add-entries/ HTTP/1.1" 500 - Traceback (most recent call last): File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\flask\app.py", line 2309, in __call__ return self.wsgi_app(environ, start_response) File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\flask\app.py", line 2295, in wsgi_app response = self.handle_exception(e) File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\flask\app.py", line 1741, in handle_exception reraise(exc_type, exc_value, tb) File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\flask\_compat.py", line 35, in reraise raise value File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\flask\app.py", line 2292, in wsgi_app response = self.full_dispatch_request() File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\flask\app.py", line 1815, in full_dispatch_request rv = self.handle_user_exception(e) File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\flask\app.py", line 1718, in handle_user_exception reraise(exc_type, exc_value, tb) File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\flask\_compat.py", line 35, in reraise raise value File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\flask\app.py", line 1813, in full_dispatch_request rv = self.dispatch_request() File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\flask\app.py", line 1799, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\fava\json_api.py", line 42, in _wrapper return func(request_data) File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\fava\json_api.py", line 26, in _wrapper json_data = func(*args, **kwargs) File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\fava\json_api.py", line 179, in add_entries g.ledger.file.insert_entries(entries) File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\fava\core\file.py", line 114, in insert_entries insert_entry(entry, self.list_sources(), self.ledger.fava_options) File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\fava\core\file.py", line 286, in insert_entry accounts, entry.date, insert_options, filenames File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\fava\core\file.py", line 328, in find_insert_position return (filenames[0], len(open(filenames[0]).readlines()) + 1) File "C:\Program Files\Python36\lib\encodings\cp1250.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 6806: character maps to <undefined>
UnicodeDecodeError
def insert_metadata_in_file(filename, lineno, key, value): """Inserts the specified metadata in the file below lineno, taking into account the whitespace in front of the line that lineno.""" with open(filename, "r", encoding="utf-8") as file: contents = file.readlines() # use the whitespace of the following line, else use double the whitespace indention = leading_space(contents[lineno + 1]) contents.insert(lineno + 1, '{}{}: "{}"\n'.format(indention, key, value)) with open(filename, "w", encoding="utf-8") as file: contents = "".join(contents) file.write(contents)
def insert_metadata_in_file(filename, lineno, key, value): """Inserts the specified metadata in the file below lineno, taking into account the whitespace in front of the line that lineno.""" with open(filename, "r") as file: contents = file.readlines() # use the whitespace of the following line, else use double the whitespace indention = leading_space(contents[lineno + 1]) contents.insert(lineno + 1, '{}{}: "{}"\n'.format(indention, key, value)) with open(filename, "w") as file: contents = "".join(contents) file.write(contents)
https://github.com/beancount/fava/issues/883
D:\Documents\beancount>c:\Users\belidzs\PycharmProjects\beancount_virtualenv\Scripts\fava --debug fokonyv.beancount * Serving Flask app "fava.application" (lazy loading) * Environment: production WARNING: Do not use the development server in a production environment. Use a production WSGI server instead. * Debug mode: on * Restarting with stat * Debugger is active! * Debugger PIN: 546-083-666 * Running on http://localhost:5000/ (Press CTRL+C to quit) 127.0.0.1 - - [09/Mar/2019 10:48:22] "PUT /f%C5%91k%C3%B6nyv/api/add-entries/ HTTP/1.1" 500 - Traceback (most recent call last): File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\flask\app.py", line 2309, in __call__ return self.wsgi_app(environ, start_response) File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\flask\app.py", line 2295, in wsgi_app response = self.handle_exception(e) File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\flask\app.py", line 1741, in handle_exception reraise(exc_type, exc_value, tb) File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\flask\_compat.py", line 35, in reraise raise value File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\flask\app.py", line 2292, in wsgi_app response = self.full_dispatch_request() File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\flask\app.py", line 1815, in full_dispatch_request rv = self.handle_user_exception(e) File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\flask\app.py", line 1718, in handle_user_exception reraise(exc_type, exc_value, tb) File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\flask\_compat.py", line 35, in reraise raise value File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\flask\app.py", line 1813, in full_dispatch_request rv = self.dispatch_request() File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\flask\app.py", line 1799, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\fava\json_api.py", line 42, in _wrapper return func(request_data) File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\fava\json_api.py", line 26, in _wrapper json_data = func(*args, **kwargs) File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\fava\json_api.py", line 179, in add_entries g.ledger.file.insert_entries(entries) File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\fava\core\file.py", line 114, in insert_entries insert_entry(entry, self.list_sources(), self.ledger.fava_options) File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\fava\core\file.py", line 286, in insert_entry accounts, entry.date, insert_options, filenames File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\fava\core\file.py", line 328, in find_insert_position return (filenames[0], len(open(filenames[0]).readlines()) + 1) File "C:\Program Files\Python36\lib\encodings\cp1250.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 6806: character maps to <undefined>
UnicodeDecodeError
def get_entry_slice(entry): """Get slice of the source file for an entry. Args: entry: An entry. Returns: A string containing the lines of the entry and the `sha256sum` of these lines. Raises: FavaAPIException: If the file at `path` is not one of the source files. """ with open(entry.meta["filename"], mode="r", encoding="utf-8") as file: lines = file.readlines() entry_lines = find_entry_lines(lines, entry.meta["lineno"] - 1) entry_source = "".join(entry_lines).rstrip("\n") sha256sum = sha256(codecs.encode(entry_source)).hexdigest() return entry_source, sha256sum
def get_entry_slice(entry): """Get slice of the source file for an entry. Args: entry: An entry. Returns: A string containing the lines of the entry and the `sha256sum` of these lines. Raises: FavaAPIException: If the file at `path` is not one of the source files. """ with open(entry.meta["filename"], mode="r") as file: lines = file.readlines() entry_lines = find_entry_lines(lines, entry.meta["lineno"] - 1) entry_source = "".join(entry_lines).rstrip("\n") sha256sum = sha256(codecs.encode(entry_source)).hexdigest() return entry_source, sha256sum
https://github.com/beancount/fava/issues/883
D:\Documents\beancount>c:\Users\belidzs\PycharmProjects\beancount_virtualenv\Scripts\fava --debug fokonyv.beancount * Serving Flask app "fava.application" (lazy loading) * Environment: production WARNING: Do not use the development server in a production environment. Use a production WSGI server instead. * Debug mode: on * Restarting with stat * Debugger is active! * Debugger PIN: 546-083-666 * Running on http://localhost:5000/ (Press CTRL+C to quit) 127.0.0.1 - - [09/Mar/2019 10:48:22] "PUT /f%C5%91k%C3%B6nyv/api/add-entries/ HTTP/1.1" 500 - Traceback (most recent call last): File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\flask\app.py", line 2309, in __call__ return self.wsgi_app(environ, start_response) File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\flask\app.py", line 2295, in wsgi_app response = self.handle_exception(e) File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\flask\app.py", line 1741, in handle_exception reraise(exc_type, exc_value, tb) File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\flask\_compat.py", line 35, in reraise raise value File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\flask\app.py", line 2292, in wsgi_app response = self.full_dispatch_request() File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\flask\app.py", line 1815, in full_dispatch_request rv = self.handle_user_exception(e) File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\flask\app.py", line 1718, in handle_user_exception reraise(exc_type, exc_value, tb) File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\flask\_compat.py", line 35, in reraise raise value File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\flask\app.py", line 1813, in full_dispatch_request rv = self.dispatch_request() File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\flask\app.py", line 1799, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\fava\json_api.py", line 42, in _wrapper return func(request_data) File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\fava\json_api.py", line 26, in _wrapper json_data = func(*args, **kwargs) File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\fava\json_api.py", line 179, in add_entries g.ledger.file.insert_entries(entries) File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\fava\core\file.py", line 114, in insert_entries insert_entry(entry, self.list_sources(), self.ledger.fava_options) File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\fava\core\file.py", line 286, in insert_entry accounts, entry.date, insert_options, filenames File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\fava\core\file.py", line 328, in find_insert_position return (filenames[0], len(open(filenames[0]).readlines()) + 1) File "C:\Program Files\Python36\lib\encodings\cp1250.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 6806: character maps to <undefined>
UnicodeDecodeError
def save_entry_slice(entry, source_slice, sha256sum): """Save slice of the source file for an entry. Args: entry: An entry. source_slice: The lines that the entry should be replaced with. sha256sum: The sha256sum of the current lines of the entry. Returns: The `sha256sum` of the new lines of the entry. Raises: FavaAPIException: If the file at `path` is not one of the source files. """ with open(entry.meta["filename"], "r", encoding="utf-8") as file: lines = file.readlines() first_entry_line = entry.meta["lineno"] - 1 entry_lines = find_entry_lines(lines, first_entry_line) entry_source = "".join(entry_lines).rstrip("\n") original_sha256sum = sha256(codecs.encode(entry_source)).hexdigest() if original_sha256sum != sha256sum: raise FavaAPIException("The file changed externally.") lines = ( lines[:first_entry_line] + [source_slice + "\n"] + lines[first_entry_line + len(entry_lines) :] ) with open(entry.meta["filename"], "w", encoding="utf-8") as file: file.writelines(lines) return sha256(codecs.encode(source_slice)).hexdigest()
def save_entry_slice(entry, source_slice, sha256sum): """Save slice of the source file for an entry. Args: entry: An entry. source_slice: The lines that the entry should be replaced with. sha256sum: The sha256sum of the current lines of the entry. Returns: The `sha256sum` of the new lines of the entry. Raises: FavaAPIException: If the file at `path` is not one of the source files. """ with open(entry.meta["filename"], "r") as file: lines = file.readlines() first_entry_line = entry.meta["lineno"] - 1 entry_lines = find_entry_lines(lines, first_entry_line) entry_source = "".join(entry_lines).rstrip("\n") original_sha256sum = sha256(codecs.encode(entry_source)).hexdigest() if original_sha256sum != sha256sum: raise FavaAPIException("The file changed externally.") lines = ( lines[:first_entry_line] + [source_slice + "\n"] + lines[first_entry_line + len(entry_lines) :] ) with open(entry.meta["filename"], "w") as file: file.writelines(lines) return sha256(codecs.encode(source_slice)).hexdigest()
https://github.com/beancount/fava/issues/883
D:\Documents\beancount>c:\Users\belidzs\PycharmProjects\beancount_virtualenv\Scripts\fava --debug fokonyv.beancount * Serving Flask app "fava.application" (lazy loading) * Environment: production WARNING: Do not use the development server in a production environment. Use a production WSGI server instead. * Debug mode: on * Restarting with stat * Debugger is active! * Debugger PIN: 546-083-666 * Running on http://localhost:5000/ (Press CTRL+C to quit) 127.0.0.1 - - [09/Mar/2019 10:48:22] "PUT /f%C5%91k%C3%B6nyv/api/add-entries/ HTTP/1.1" 500 - Traceback (most recent call last): File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\flask\app.py", line 2309, in __call__ return self.wsgi_app(environ, start_response) File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\flask\app.py", line 2295, in wsgi_app response = self.handle_exception(e) File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\flask\app.py", line 1741, in handle_exception reraise(exc_type, exc_value, tb) File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\flask\_compat.py", line 35, in reraise raise value File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\flask\app.py", line 2292, in wsgi_app response = self.full_dispatch_request() File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\flask\app.py", line 1815, in full_dispatch_request rv = self.handle_user_exception(e) File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\flask\app.py", line 1718, in handle_user_exception reraise(exc_type, exc_value, tb) File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\flask\_compat.py", line 35, in reraise raise value File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\flask\app.py", line 1813, in full_dispatch_request rv = self.dispatch_request() File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\flask\app.py", line 1799, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\fava\json_api.py", line 42, in _wrapper return func(request_data) File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\fava\json_api.py", line 26, in _wrapper json_data = func(*args, **kwargs) File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\fava\json_api.py", line 179, in add_entries g.ledger.file.insert_entries(entries) File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\fava\core\file.py", line 114, in insert_entries insert_entry(entry, self.list_sources(), self.ledger.fava_options) File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\fava\core\file.py", line 286, in insert_entry accounts, entry.date, insert_options, filenames File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\fava\core\file.py", line 328, in find_insert_position return (filenames[0], len(open(filenames[0]).readlines()) + 1) File "C:\Program Files\Python36\lib\encodings\cp1250.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 6806: character maps to <undefined>
UnicodeDecodeError
def insert_entry(entry, filenames, fava_options): """Insert an entry. Args: entry: An entry. filenames: List of filenames. fava_options: The ledgers fava_options. Note that the line numbers of the insert options might be updated. """ insert_options = fava_options.get("insert-entry", []) if isinstance(entry, data.Transaction): accounts = reversed([p.account for p in entry.postings]) else: accounts = [entry.account] filename, lineno = find_insert_position( accounts, entry.date, insert_options, filenames ) content = _format_entry(entry, fava_options) + "\n" with open(filename, "r", encoding="utf-8") as file: contents = file.readlines() contents.insert(lineno, content) with open(filename, "w", encoding="utf-8") as file: file.writelines(contents) for index, option in enumerate(insert_options): added_lines = content.count("\n") + 1 if option.filename == filename and option.lineno > lineno: insert_options[index] = option._replace(lineno=lineno + added_lines)
def insert_entry(entry, filenames, fava_options): """Insert an entry. Args: entry: An entry. filenames: List of filenames. fava_options: The ledgers fava_options. Note that the line numbers of the insert options might be updated. """ insert_options = fava_options.get("insert-entry", []) if isinstance(entry, data.Transaction): accounts = reversed([p.account for p in entry.postings]) else: accounts = [entry.account] filename, lineno = find_insert_position( accounts, entry.date, insert_options, filenames ) content = _format_entry(entry, fava_options) + "\n" with open(filename, "r") as file: contents = file.readlines() contents.insert(lineno, content) with open(filename, "w") as file: file.writelines(contents) for index, option in enumerate(insert_options): added_lines = content.count("\n") + 1 if option.filename == filename and option.lineno > lineno: insert_options[index] = option._replace(lineno=lineno + added_lines)
https://github.com/beancount/fava/issues/883
D:\Documents\beancount>c:\Users\belidzs\PycharmProjects\beancount_virtualenv\Scripts\fava --debug fokonyv.beancount * Serving Flask app "fava.application" (lazy loading) * Environment: production WARNING: Do not use the development server in a production environment. Use a production WSGI server instead. * Debug mode: on * Restarting with stat * Debugger is active! * Debugger PIN: 546-083-666 * Running on http://localhost:5000/ (Press CTRL+C to quit) 127.0.0.1 - - [09/Mar/2019 10:48:22] "PUT /f%C5%91k%C3%B6nyv/api/add-entries/ HTTP/1.1" 500 - Traceback (most recent call last): File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\flask\app.py", line 2309, in __call__ return self.wsgi_app(environ, start_response) File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\flask\app.py", line 2295, in wsgi_app response = self.handle_exception(e) File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\flask\app.py", line 1741, in handle_exception reraise(exc_type, exc_value, tb) File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\flask\_compat.py", line 35, in reraise raise value File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\flask\app.py", line 2292, in wsgi_app response = self.full_dispatch_request() File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\flask\app.py", line 1815, in full_dispatch_request rv = self.handle_user_exception(e) File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\flask\app.py", line 1718, in handle_user_exception reraise(exc_type, exc_value, tb) File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\flask\_compat.py", line 35, in reraise raise value File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\flask\app.py", line 1813, in full_dispatch_request rv = self.dispatch_request() File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\flask\app.py", line 1799, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\fava\json_api.py", line 42, in _wrapper return func(request_data) File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\fava\json_api.py", line 26, in _wrapper json_data = func(*args, **kwargs) File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\fava\json_api.py", line 179, in add_entries g.ledger.file.insert_entries(entries) File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\fava\core\file.py", line 114, in insert_entries insert_entry(entry, self.list_sources(), self.ledger.fava_options) File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\fava\core\file.py", line 286, in insert_entry accounts, entry.date, insert_options, filenames File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\fava\core\file.py", line 328, in find_insert_position return (filenames[0], len(open(filenames[0]).readlines()) + 1) File "C:\Program Files\Python36\lib\encodings\cp1250.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 6806: character maps to <undefined>
UnicodeDecodeError
def find_insert_position(accounts, date, insert_options, filenames): """Find insert position for an account. Args: accounts: A list of accounts. date: A date. Only InsertOptions before this date will be considered. insert_options: A list of InsertOption. filenames: List of Beancount files. """ for account in accounts: for insert_option in insert_options: if insert_option.date >= date: break if insert_option.re.match(account): return (insert_option.filename, insert_option.lineno - 1) return ( filenames[0], len(open(filenames[0], encoding="utf-8").readlines()) + 1, )
def find_insert_position(accounts, date, insert_options, filenames): """Find insert position for an account. Args: accounts: A list of accounts. date: A date. Only InsertOptions before this date will be considered. insert_options: A list of InsertOption. filenames: List of Beancount files. """ for account in accounts: for insert_option in insert_options: if insert_option.date >= date: break if insert_option.re.match(account): return (insert_option.filename, insert_option.lineno - 1) return (filenames[0], len(open(filenames[0]).readlines()) + 1)
https://github.com/beancount/fava/issues/883
D:\Documents\beancount>c:\Users\belidzs\PycharmProjects\beancount_virtualenv\Scripts\fava --debug fokonyv.beancount * Serving Flask app "fava.application" (lazy loading) * Environment: production WARNING: Do not use the development server in a production environment. Use a production WSGI server instead. * Debug mode: on * Restarting with stat * Debugger is active! * Debugger PIN: 546-083-666 * Running on http://localhost:5000/ (Press CTRL+C to quit) 127.0.0.1 - - [09/Mar/2019 10:48:22] "PUT /f%C5%91k%C3%B6nyv/api/add-entries/ HTTP/1.1" 500 - Traceback (most recent call last): File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\flask\app.py", line 2309, in __call__ return self.wsgi_app(environ, start_response) File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\flask\app.py", line 2295, in wsgi_app response = self.handle_exception(e) File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\flask\app.py", line 1741, in handle_exception reraise(exc_type, exc_value, tb) File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\flask\_compat.py", line 35, in reraise raise value File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\flask\app.py", line 2292, in wsgi_app response = self.full_dispatch_request() File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\flask\app.py", line 1815, in full_dispatch_request rv = self.handle_user_exception(e) File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\flask\app.py", line 1718, in handle_user_exception reraise(exc_type, exc_value, tb) File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\flask\_compat.py", line 35, in reraise raise value File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\flask\app.py", line 1813, in full_dispatch_request rv = self.dispatch_request() File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\flask\app.py", line 1799, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\fava\json_api.py", line 42, in _wrapper return func(request_data) File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\fava\json_api.py", line 26, in _wrapper json_data = func(*args, **kwargs) File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\fava\json_api.py", line 179, in add_entries g.ledger.file.insert_entries(entries) File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\fava\core\file.py", line 114, in insert_entries insert_entry(entry, self.list_sources(), self.ledger.fava_options) File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\fava\core\file.py", line 286, in insert_entry accounts, entry.date, insert_options, filenames File "c:\users\belidzs\pycharmprojects\beancount_virtualenv\lib\site-packages\fava\core\file.py", line 328, in find_insert_position return (filenames[0], len(open(filenames[0]).readlines()) + 1) File "C:\Program Files\Python36\lib\encodings\cp1250.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 6806: character maps to <undefined>
UnicodeDecodeError
def main(cwd=None): """ The main() function implements all of the logic that the command-line version of onionshare uses. """ common = Common() # Display OnionShare banner print(f"OnionShare {common.version} | https://onionshare.org/") reset = "\033[0m" purple = "\33[95m" print(purple) print(" @@@@@@@@@ ") print(" @@@@@@@@@@@@@@@@@@@ ") print(" @@@@@@@@@@@@@@@@@@@@@@@@@ ") print(" @@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ") print( " @@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ___ _ " ) print( " @@@@@@ @@@@@@@@@@@@@ / _ \\ (_) " ) print( " @@@@ @ @@@@@@@@@@@ | | | |_ __ _ ___ _ __ " ) print( " @@@@@@@@ @@@@@@@@@@ | | | | '_ \\| |/ _ \\| '_ \\ " ) print( " @@@@@@@@@@@@ @@@@@@@@@@ \\ \\_/ / | | | | (_) | | | | " ) print( " @@@@@@@@@@@@@@@@ @@@@@@@@@ \\___/|_| |_|_|\\___/|_| |_| " ) print( " @@@@@@@@@ @@@@@@@@@@@@@@@@ _____ _ " ) print( " @@@@@@@@@@ @@@@@@@@@@@@ / ___| | " ) print( " @@@@@@@@@@ @@@@@@@@ \\ `--.| |__ __ _ _ __ ___ " ) print( " @@@@@@@@@@@ @ @@@@ `--. \\ '_ \\ / _` | '__/ _ \\" ) print( " @@@@@@@@@@@@@ @@@@@@ /\\__/ / | | | (_| | | | __/" ) print( " @@@@@@@@@@@@@@@@@@@@@@@@@@@@@ \\____/|_| |_|\\__,_|_| \\___|" ) print(" @@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ") print(" @@@@@@@@@@@@@@@@@@@@@@@@@ ") print(" @@@@@@@@@@@@@@@@@@@ ") print(" @@@@@@@@@ ") print(reset) # OnionShare CLI in OSX needs to change current working directory (#132) if common.platform == "Darwin": if cwd: os.chdir(cwd) # Parse arguments parser = argparse.ArgumentParser( formatter_class=lambda prog: argparse.HelpFormatter(prog, max_help_position=28) ) # Select modes parser.add_argument( "--receive", action="store_true", dest="receive", help="Receive files" ) parser.add_argument( "--website", action="store_true", dest="website", help="Publish website" ) parser.add_argument( "--chat", action="store_true", dest="chat", help="Start chat server" ) # Tor connection-related args parser.add_argument( "--local-only", action="store_true", dest="local_only", default=False, help="Don't use Tor (only for development)", ) parser.add_argument( "--connect-timeout", metavar="SECONDS", dest="connect_timeout", default=120, help="Give up connecting to Tor after a given amount of seconds (default: 120)", ) parser.add_argument( "--config", metavar="FILENAME", default=None, help="Filename of custom global settings", ) # Persistent file parser.add_argument( "--persistent", metavar="FILENAME", default=None, help="Filename of persistent session", ) # General args parser.add_argument( "--public", action="store_true", dest="public", default=False, help="Don't use a password", ) parser.add_argument( "--auto-start-timer", metavar="SECONDS", dest="autostart_timer", default=0, help="Start onion service at scheduled time (N seconds from now)", ) parser.add_argument( "--auto-stop-timer", metavar="SECONDS", dest="autostop_timer", default=0, help="Stop onion service at schedule time (N seconds from now)", ) parser.add_argument( "--legacy", action="store_true", dest="legacy", default=False, help="Use legacy address (v2 onion service, not recommended)", ) parser.add_argument( "--client-auth", action="store_true", dest="client_auth", default=False, help="Use client authorization (requires --legacy)", ) # Share args parser.add_argument( "--no-autostop-sharing", action="store_true", dest="no_autostop_sharing", default=False, help="Share files: Continue sharing after files have been sent (default is to stop sharing)", ) # Receive args parser.add_argument( "--data-dir", metavar="data_dir", default=None, help="Receive files: Save files received to this directory", ) # Website args parser.add_argument( "--disable_csp", action="store_true", dest="disable_csp", default=False, help="Publish website: Disable Content Security Policy header (allows your website to use third-party resources)", ) # Other parser.add_argument( "-v", "--verbose", action="store_true", dest="verbose", help="Log OnionShare errors to stdout, and web errors to disk", ) parser.add_argument( "filename", metavar="filename", nargs="*", help="List of files or folders to share", ) args = parser.parse_args() filenames = args.filename for i in range(len(filenames)): filenames[i] = os.path.abspath(filenames[i]) receive = bool(args.receive) website = bool(args.website) chat = bool(args.chat) local_only = bool(args.local_only) connect_timeout = int(args.connect_timeout) config_filename = args.config persistent_filename = args.persistent public = bool(args.public) autostart_timer = int(args.autostart_timer) autostop_timer = int(args.autostop_timer) legacy = bool(args.legacy) client_auth = bool(args.client_auth) autostop_sharing = not bool(args.no_autostop_sharing) data_dir = args.data_dir disable_csp = bool(args.disable_csp) verbose = bool(args.verbose) if receive: mode = "receive" elif website: mode = "website" elif chat: mode = "chat" else: mode = "share" # Verbose mode? common.verbose = verbose # client_auth can only be set if legacy is also set if client_auth and not legacy: print( "Client authentication (--client-auth) is only supported with with legacy onion services (--legacy)" ) sys.exit() # Re-load settings, if a custom config was passed in if config_filename: common.load_settings(config_filename) else: common.load_settings() # Mode settings if persistent_filename: mode_settings = ModeSettings(common, persistent_filename) mode_settings.set("persistent", "enabled", True) mode_settings.set("persistent", "mode", mode) else: mode_settings = ModeSettings(common) if mode_settings.just_created: # This means the mode settings were just created, not loaded from disk mode_settings.set("general", "public", public) mode_settings.set("general", "autostart_timer", autostart_timer) mode_settings.set("general", "autostop_timer", autostop_timer) mode_settings.set("general", "legacy", legacy) mode_settings.set("general", "client_auth", client_auth) if mode == "share": mode_settings.set("share", "autostop_sharing", autostop_sharing) if mode == "receive": if data_dir: mode_settings.set("receive", "data_dir", data_dir) if mode == "website": mode_settings.set("website", "disable_csp", disable_csp) else: # See what the persistent mode was mode = mode_settings.get("persistent", "mode") # In share and website mode, you must supply a list of filenames if mode == "share" or mode == "website": # Unless you passed in a persistent filename, in which case get the filenames from # the mode settings if ( persistent_filename and not mode_settings.just_created and len(filenames) != 0 ): filenames = mode_settings.get(mode, "filenames") else: # Make sure filenames given if not using receiver mode if len(filenames) == 0: if persistent_filename: mode_settings.delete() parser.print_help() sys.exit() # Validate filenames valid = True for filename in filenames: if not os.path.isfile(filename) and not os.path.isdir(filename): print(f"{filename} is not a valid file.") valid = False if not os.access(filename, os.R_OK): print(f"{filename} is not a readable file.") valid = False if not valid: sys.exit() # Save the filenames in persistent file if persistent_filename: mode_settings.set(mode, "filenames", filenames) # Create the Web object web = Web(common, False, mode_settings, mode) # Start the Onion object try: onion = Onion(common, use_tmp_dir=True) except CannotFindTor: print("You must install tor to use OnionShare from the command line") if common.platform == "Darwin": print("In macOS, you can do this with Homebrew (https://brew.sh):") print(" brew install tor") sys.exit() try: onion.connect( custom_settings=False, config=config_filename, connect_timeout=connect_timeout, local_only=local_only, ) except KeyboardInterrupt: print("") sys.exit() except Exception as e: sys.exit() # Start the onionshare app try: common.settings.load() if not mode_settings.get("general", "public"): web.generate_password(mode_settings.get("onion", "password")) else: web.password = None app = OnionShare(common, onion, local_only, autostop_timer) app.choose_port() # Delay the startup if a startup timer was set if autostart_timer > 0: # Can't set a schedule that is later than the auto-stop timer if autostop_timer > 0 and autostop_timer < autostart_timer: print( "The auto-stop time can't be the same or earlier than the auto-start time. Please update it to start sharing." ) sys.exit() app.start_onion_service(mode, mode_settings, False, True) url = build_url(mode_settings, app, web) schedule = datetime.now() + timedelta(seconds=autostart_timer) if mode == "receive": print( f"Files sent to you appear in this folder: {mode_settings.get('receive', 'data_dir')}" ) print("") print( "Warning: Receive mode lets people upload files to your computer. Some files can potentially take control of your computer if you open them. Only open things from people you trust, or if you know what you are doing." ) print("") if mode_settings.get("general", "client_auth"): print( f"Give this address and HidServAuth lineto your sender, and tell them it won't be accessible until: {schedule.strftime('%I:%M:%S%p, %b %d, %y')}" ) print(app.auth_string) else: print( f"Give this address to your sender, and tell them it won't be accessible until: {schedule.strftime('%I:%M:%S%p, %b %d, %y')}" ) else: if mode_settings.get("general", "client_auth"): print( f"Give this address and HidServAuth line to your recipient, and tell them it won't be accessible until: {schedule.strftime('%I:%M:%S%p, %b %d, %y')}" ) print(app.auth_string) else: print( f"Give this address to your recipient, and tell them it won't be accessible until: {schedule.strftime('%I:%M:%S%p, %b %d, %y')}" ) print(url) print("") print("Waiting for the scheduled time before starting...") app.onion.cleanup(False) time.sleep(autostart_timer) app.start_onion_service(mode, mode_settings) else: app.start_onion_service(mode, mode_settings) except KeyboardInterrupt: print("") sys.exit() except (TorTooOld, TorErrorProtocolError) as e: print("") print(e.args[0]) sys.exit() if mode == "website": # Prepare files to share try: web.website_mode.set_file_info(filenames) except OSError as e: print(e.strerror) sys.exit(1) if mode == "share": # Prepare files to share print("Compressing files.") try: web.share_mode.set_file_info(filenames) app.cleanup_filenames += web.share_mode.cleanup_filenames except OSError as e: print(e.strerror) sys.exit(1) # Warn about sending large files over Tor if web.share_mode.download_filesize >= 157286400: # 150mb print("") print("Warning: Sending a large share could take hours") print("") # Start OnionShare http service in new thread t = threading.Thread(target=web.start, args=(app.port,)) t.daemon = True t.start() try: # Trap Ctrl-C # Wait for web.generate_password() to finish running time.sleep(0.2) # start auto-stop timer thread if app.autostop_timer > 0: app.autostop_timer_thread.start() # Save the web password if we are using a persistent private key if mode_settings.get("persistent", "enabled"): if not mode_settings.get("onion", "password"): mode_settings.set("onion", "password", web.password) # mode_settings.save() # Build the URL url = build_url(mode_settings, app, web) print("") if autostart_timer > 0: print("Server started") else: if mode == "receive": print( f"Files sent to you appear in this folder: {mode_settings.get('receive', 'data_dir')}" ) print("") print( "Warning: Receive mode lets people upload files to your computer. Some files can potentially take control of your computer if you open them. Only open things from people you trust, or if you know what you are doing." ) print("") if mode_settings.get("general", "client_auth"): print("Give this address and HidServAuth to the sender:") print(url) print(app.auth_string) else: print("Give this address to the sender:") print(url) else: if mode_settings.get("general", "client_auth"): print("Give this address and HidServAuth line to the recipient:") print(url) print(app.auth_string) else: print("Give this address to the recipient:") print(url) print("") print("Press Ctrl+C to stop the server") # Wait for app to close while t.is_alive(): if app.autostop_timer > 0: # if the auto-stop timer was set and has run out, stop the server if not app.autostop_timer_thread.is_alive(): if mode == "share" or (mode == "website"): # If there were no attempts to download the share, or all downloads are done, we can stop if web.share_mode.cur_history_id == 0 or web.done: print("Stopped because auto-stop timer ran out") web.stop(app.port) break if mode == "receive": if ( web.receive_mode.cur_history_id == 0 or not web.receive_mode.uploads_in_progress ): print("Stopped because auto-stop timer ran out") web.stop(app.port) break else: web.receive_mode.can_upload = False # Allow KeyboardInterrupt exception to be handled with threads # https://stackoverflow.com/questions/3788208/python-threading-ignores-keyboardinterrupt-exception time.sleep(0.2) except KeyboardInterrupt: web.stop(app.port) finally: # Shutdown app.cleanup() onion.cleanup()
def main(cwd=None): """ The main() function implements all of the logic that the command-line version of onionshare uses. """ common = Common() # Display OnionShare banner print(f"OnionShare {common.version} | https://onionshare.org/") reset = "\033[0m" purple = "\33[95m" print(purple) print(" @@@@@@@@@ ") print(" @@@@@@@@@@@@@@@@@@@ ") print(" @@@@@@@@@@@@@@@@@@@@@@@@@ ") print(" @@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ") print( " @@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ___ _ " ) print( " @@@@@@ @@@@@@@@@@@@@ / _ \\ (_) " ) print( " @@@@ @ @@@@@@@@@@@ | | | |_ __ _ ___ _ __ " ) print( " @@@@@@@@ @@@@@@@@@@ | | | | '_ \\| |/ _ \\| '_ \\ " ) print( " @@@@@@@@@@@@ @@@@@@@@@@ \\ \\_/ / | | | | (_) | | | | " ) print( " @@@@@@@@@@@@@@@@ @@@@@@@@@ \\___/|_| |_|_|\\___/|_| |_| " ) print( " @@@@@@@@@ @@@@@@@@@@@@@@@@ _____ _ " ) print( " @@@@@@@@@@ @@@@@@@@@@@@ / ___| | " ) print( " @@@@@@@@@@ @@@@@@@@ \\ `--.| |__ __ _ _ __ ___ " ) print( " @@@@@@@@@@@ @ @@@@ `--. \\ '_ \\ / _` | '__/ _ \\" ) print( " @@@@@@@@@@@@@ @@@@@@ /\\__/ / | | | (_| | | | __/" ) print( " @@@@@@@@@@@@@@@@@@@@@@@@@@@@@ \\____/|_| |_|\\__,_|_| \\___|" ) print(" @@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ") print(" @@@@@@@@@@@@@@@@@@@@@@@@@ ") print(" @@@@@@@@@@@@@@@@@@@ ") print(" @@@@@@@@@ ") print(reset) # OnionShare CLI in OSX needs to change current working directory (#132) if common.platform == "Darwin": if cwd: os.chdir(cwd) # Parse arguments parser = argparse.ArgumentParser( formatter_class=lambda prog: argparse.HelpFormatter(prog, max_help_position=28) ) # Select modes parser.add_argument( "--receive", action="store_true", dest="receive", help="Receive files" ) parser.add_argument( "--website", action="store_true", dest="website", help="Publish website" ) parser.add_argument( "--chat", action="store_true", dest="chat", help="Start chat server" ) # Tor connection-related args parser.add_argument( "--local-only", action="store_true", dest="local_only", default=False, help="Don't use Tor (only for development)", ) parser.add_argument( "--connect-timeout", metavar="SECONDS", dest="connect_timeout", default=120, help="Give up connecting to Tor after a given amount of seconds (default: 120)", ) parser.add_argument( "--config", metavar="FILENAME", default=None, help="Filename of custom global settings", ) # Persistent file parser.add_argument( "--persistent", metavar="FILENAME", default=None, help="Filename of persistent session", ) # General args parser.add_argument( "--public", action="store_true", dest="public", default=False, help="Don't use a password", ) parser.add_argument( "--auto-start-timer", metavar="SECONDS", dest="autostart_timer", default=0, help="Start onion service at scheduled time (N seconds from now)", ) parser.add_argument( "--auto-stop-timer", metavar="SECONDS", dest="autostop_timer", default=0, help="Stop onion service at schedule time (N seconds from now)", ) parser.add_argument( "--legacy", action="store_true", dest="legacy", default=False, help="Use legacy address (v2 onion service, not recommended)", ) parser.add_argument( "--client-auth", action="store_true", dest="client_auth", default=False, help="Use client authorization (requires --legacy)", ) # Share args parser.add_argument( "--no-autostop-sharing", action="store_true", dest="no_autostop_sharing", default=False, help="Share files: Continue sharing after files have been sent (default is to stop sharing)", ) # Receive args parser.add_argument( "--data-dir", metavar="data_dir", default=None, help="Receive files: Save files received to this directory", ) # Website args parser.add_argument( "--disable_csp", action="store_true", dest="disable_csp", default=False, help="Publish website: Disable Content Security Policy header (allows your website to use third-party resources)", ) # Other parser.add_argument( "-v", "--verbose", action="store_true", dest="verbose", help="Log OnionShare errors to stdout, and web errors to disk", ) parser.add_argument( "filename", metavar="filename", nargs="*", help="List of files or folders to share", ) args = parser.parse_args() filenames = args.filename for i in range(len(filenames)): filenames[i] = os.path.abspath(filenames[i]) receive = bool(args.receive) website = bool(args.website) chat = bool(args.chat) local_only = bool(args.local_only) connect_timeout = int(args.connect_timeout) config_filename = args.config persistent_filename = args.persistent public = bool(args.public) autostart_timer = int(args.autostart_timer) autostop_timer = int(args.autostop_timer) legacy = bool(args.legacy) client_auth = bool(args.client_auth) autostop_sharing = not bool(args.no_autostop_sharing) data_dir = args.data_dir disable_csp = bool(args.disable_csp) verbose = bool(args.verbose) if receive: mode = "receive" elif website: mode = "website" elif chat: mode = "chat" else: mode = "share" # Verbose mode? common.verbose = verbose # client_auth can only be set if legacy is also set if client_auth and not legacy: print( "Client authentication (--client-auth) is only supported with with legacy onion services (--legacy)" ) sys.exit() # Re-load settings, if a custom config was passed in if config_filename: common.load_settings(config_filename) else: common.load_settings() # Mode settings if persistent_filename: mode_settings = ModeSettings(common, persistent_filename) mode_settings.set("persistent", "enabled", True) else: mode_settings = ModeSettings(common) if mode_settings.just_created: # This means the mode settings were just created, not loaded from disk mode_settings.set("general", "public", public) mode_settings.set("general", "autostart_timer", autostart_timer) mode_settings.set("general", "autostop_timer", autostop_timer) mode_settings.set("general", "legacy", legacy) mode_settings.set("general", "client_auth", client_auth) if mode == "share": mode_settings.set("share", "autostop_sharing", autostop_sharing) if mode == "receive": if data_dir: mode_settings.set("receive", "data_dir", data_dir) if mode == "website": mode_settings.set("website", "disable_csp", disable_csp) else: # See what the persistent mode was mode = mode_settings.get("persistent", "mode") # In share and website mode, you must supply a list of filenames if mode == "share" or mode == "website": # Unless you passed in a persistent filename, in which case get the filenames from # the mode settings if persistent_filename and not mode_settings.just_created: filenames = mode_settings.get(mode, "filenames") else: # Make sure filenames given if not using receiver mode if len(filenames) == 0: if persistent_filename: mode_settings.delete() parser.print_help() sys.exit() # Validate filenames valid = True for filename in filenames: if not os.path.isfile(filename) and not os.path.isdir(filename): print(f"{filename} is not a valid file.") valid = False if not os.access(filename, os.R_OK): print(f"{filename} is not a readable file.") valid = False if not valid: sys.exit() # Create the Web object web = Web(common, False, mode_settings, mode) # Start the Onion object try: onion = Onion(common, use_tmp_dir=True) except CannotFindTor: print("You must install tor to use OnionShare from the command line") if common.platform == "Darwin": print("In macOS, you can do this with Homebrew (https://brew.sh):") print(" brew install tor") sys.exit() try: onion.connect( custom_settings=False, config=config_filename, connect_timeout=connect_timeout, local_only=local_only, ) except KeyboardInterrupt: print("") sys.exit() except Exception as e: sys.exit() # Start the onionshare app try: common.settings.load() if not mode_settings.get("general", "public"): web.generate_password(mode_settings.get("onion", "password")) else: web.password = None app = OnionShare(common, onion, local_only, autostop_timer) app.choose_port() # Delay the startup if a startup timer was set if autostart_timer > 0: # Can't set a schedule that is later than the auto-stop timer if autostop_timer > 0 and autostop_timer < autostart_timer: print( "The auto-stop time can't be the same or earlier than the auto-start time. Please update it to start sharing." ) sys.exit() app.start_onion_service(mode, mode_settings, False, True) url = build_url(mode_settings, app, web) schedule = datetime.now() + timedelta(seconds=autostart_timer) if mode == "receive": print( f"Files sent to you appear in this folder: {mode_settings.get('receive', 'data_dir')}" ) print("") print( "Warning: Receive mode lets people upload files to your computer. Some files can potentially take control of your computer if you open them. Only open things from people you trust, or if you know what you are doing." ) print("") if mode_settings.get("general", "client_auth"): print( f"Give this address and HidServAuth lineto your sender, and tell them it won't be accessible until: {schedule.strftime('%I:%M:%S%p, %b %d, %y')}" ) print(app.auth_string) else: print( f"Give this address to your sender, and tell them it won't be accessible until: {schedule.strftime('%I:%M:%S%p, %b %d, %y')}" ) else: if mode_settings.get("general", "client_auth"): print( f"Give this address and HidServAuth line to your recipient, and tell them it won't be accessible until: {schedule.strftime('%I:%M:%S%p, %b %d, %y')}" ) print(app.auth_string) else: print( f"Give this address to your recipient, and tell them it won't be accessible until: {schedule.strftime('%I:%M:%S%p, %b %d, %y')}" ) print(url) print("") print("Waiting for the scheduled time before starting...") app.onion.cleanup(False) time.sleep(autostart_timer) app.start_onion_service(mode, mode_settings) else: app.start_onion_service(mode, mode_settings) except KeyboardInterrupt: print("") sys.exit() except (TorTooOld, TorErrorProtocolError) as e: print("") print(e.args[0]) sys.exit() if mode == "website": # Prepare files to share try: web.website_mode.set_file_info(filenames) except OSError as e: print(e.strerror) sys.exit(1) if mode == "share": # Prepare files to share print("Compressing files.") try: web.share_mode.set_file_info(filenames) app.cleanup_filenames += web.share_mode.cleanup_filenames except OSError as e: print(e.strerror) sys.exit(1) # Warn about sending large files over Tor if web.share_mode.download_filesize >= 157286400: # 150mb print("") print("Warning: Sending a large share could take hours") print("") # Start OnionShare http service in new thread t = threading.Thread(target=web.start, args=(app.port,)) t.daemon = True t.start() try: # Trap Ctrl-C # Wait for web.generate_password() to finish running time.sleep(0.2) # start auto-stop timer thread if app.autostop_timer > 0: app.autostop_timer_thread.start() # Save the web password if we are using a persistent private key if mode_settings.get("persistent", "enabled"): if not mode_settings.get("onion", "password"): mode_settings.set("onion", "password", web.password) # mode_settings.save() # Build the URL url = build_url(mode_settings, app, web) print("") if autostart_timer > 0: print("Server started") else: if mode == "receive": print( f"Files sent to you appear in this folder: {mode_settings.get('receive', 'data_dir')}" ) print("") print( "Warning: Receive mode lets people upload files to your computer. Some files can potentially take control of your computer if you open them. Only open things from people you trust, or if you know what you are doing." ) print("") if mode_settings.get("general", "client_auth"): print("Give this address and HidServAuth to the sender:") print(url) print(app.auth_string) else: print("Give this address to the sender:") print(url) else: if mode_settings.get("general", "client_auth"): print("Give this address and HidServAuth line to the recipient:") print(url) print(app.auth_string) else: print("Give this address to the recipient:") print(url) print("") print("Press Ctrl+C to stop the server") # Wait for app to close while t.is_alive(): if app.autostop_timer > 0: # if the auto-stop timer was set and has run out, stop the server if not app.autostop_timer_thread.is_alive(): if mode == "share" or (mode == "website"): # If there were no attempts to download the share, or all downloads are done, we can stop if web.share_mode.cur_history_id == 0 or web.done: print("Stopped because auto-stop timer ran out") web.stop(app.port) break if mode == "receive": if ( web.receive_mode.cur_history_id == 0 or not web.receive_mode.uploads_in_progress ): print("Stopped because auto-stop timer ran out") web.stop(app.port) break else: web.receive_mode.can_upload = False # Allow KeyboardInterrupt exception to be handled with threads # https://stackoverflow.com/questions/3788208/python-threading-ignores-keyboardinterrupt-exception time.sleep(0.2) except KeyboardInterrupt: web.stop(app.port) finally: # Shutdown app.cleanup() onion.cleanup()
https://github.com/micahflee/onionshare/issues/1283
ERROR in app: Exception on / [GET] Traceback (most recent call last): File "/usr/local/lib/python3.7/dist-packages/flask/app.py", line 1950, in full_dispatch_request rv = self.dispatch_request() File "/usr/local/lib/python3.7/dist-packages/flask/app.py", line 1926, in dispatch_request self.raise_routing_exception(req) File "/usr/local/lib/python3.7/dist-packages/flask/app.py", line 1908, in raise_routing_exception raise request.routing_exception File "/usr/local/lib/python3.7/dist-packages/flask/ctx.py", line 350, in match_request result = self.url_adapter.match(return_rule=True) File "/usr/local/lib/python3.7/dist-packages/werkzeug/routing.py", line 1945, in match raise NotFound() werkzeug.exceptions.NotFound: 404 Not Found: The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.7/dist-packages/flask/app.py", line 2447, in wsgi_app response = self.full_dispatch_request() File "/usr/local/lib/python3.7/dist-packages/flask/app.py", line 1952, in full_dispatch_request rv = self.handle_user_exception(e) File "/usr/local/lib/python3.7/dist-packages/flask/app.py", line 1816, in handle_user_exception return self.handle_http_exception(e) File "/usr/local/lib/python3.7/dist-packages/flask/app.py", line 1744, in handle_http_exception return handler(e) File "/usr/local/lib/python3.7/dist-packages/onionshare_cli/web/web.py", line 229, in not_found history_id = mode.cur_history_id AttributeError: 'NoneType' object has no attribute 'cur_history_id' "GET / HTTP/1.1" 500 -
AttributeError
def define_routes(self): """ The web app routes for sharing files """ @self.web.app.route("/", defaults={"path": ""}) @self.web.app.route("/<path:path>") def index(path): """ Render the template for the onionshare landing page. """ self.web.add_request(self.web.REQUEST_LOAD, request.path) # Deny new downloads if "Stop sharing after files have been sent" is checked and there is # currently a download deny_download = ( self.web.settings.get("share", "autostop_sharing") and self.download_in_progress ) if deny_download: r = make_response(render_template("denied.html")) return self.web.add_security_headers(r) # If download is allowed to continue, serve download page if self.should_use_gzip(): self.filesize = self.gzip_filesize else: self.filesize = self.download_filesize return self.render_logic(path) @self.web.app.route("/download") def download(): """ Download the zip file. """ # Deny new downloads if "Stop After First Download" is checked and there is # currently a download deny_download = ( self.web.settings.get("share", "autostop_sharing") and self.download_in_progress ) if deny_download: r = make_response(render_template("denied.html")) return self.web.add_security_headers(r) # Prepare some variables to use inside generate() function below # which is outside of the request context shutdown_func = request.environ.get("werkzeug.server.shutdown") path = request.path # If this is a zipped file, then serve as-is. If it's not zipped, then, # if the http client supports gzip compression, gzip the file first # and serve that use_gzip = self.should_use_gzip() if use_gzip: file_to_download = self.gzip_filename self.filesize = self.gzip_filesize else: file_to_download = self.download_filename self.filesize = self.download_filesize # Tell GUI the download started history_id = self.cur_history_id self.cur_history_id += 1 self.web.add_request( self.web.REQUEST_STARTED, path, {"id": history_id, "use_gzip": use_gzip} ) basename = os.path.basename(self.download_filename) def generate(): # Starting a new download if self.web.settings.get("share", "autostop_sharing"): self.download_in_progress = True chunk_size = 102400 # 100kb fp = open(file_to_download, "rb") self.web.done = False canceled = False while not self.web.done: # The user has canceled the download, so stop serving the file if not self.web.stop_q.empty(): self.web.add_request( self.web.REQUEST_CANCELED, path, {"id": history_id} ) break chunk = fp.read(chunk_size) if chunk == b"": self.web.done = True else: try: yield chunk # tell GUI the progress downloaded_bytes = fp.tell() percent = (1.0 * downloaded_bytes / self.filesize) * 100 # only output to stdout if running onionshare in CLI mode, or if using Linux (#203, #304) if ( not self.web.is_gui or self.common.platform == "Linux" or self.common.platform == "BSD" ): sys.stdout.write( "\r{0:s}, {1:.2f}% ".format( self.common.human_readable_filesize( downloaded_bytes ), percent, ) ) sys.stdout.flush() self.web.add_request( self.web.REQUEST_PROGRESS, path, {"id": history_id, "bytes": downloaded_bytes}, ) self.web.done = False except: # looks like the download was canceled self.web.done = True canceled = True # tell the GUI the download has canceled self.web.add_request( self.web.REQUEST_CANCELED, path, {"id": history_id} ) fp.close() if self.common.platform != "Darwin": sys.stdout.write("\n") # Download is finished if self.web.settings.get("share", "autostop_sharing"): self.download_in_progress = False # Close the server, if necessary if self.web.settings.get("share", "autostop_sharing") and not canceled: print("Stopped because transfer is complete") self.web.running = False try: if shutdown_func is None: raise RuntimeError("Not running with the Werkzeug Server") shutdown_func() except: pass r = Response(generate()) if use_gzip: r.headers.set("Content-Encoding", "gzip") r.headers.set("Content-Length", self.filesize) r.headers.set("Content-Disposition", "attachment", filename=basename) r = self.web.add_security_headers(r) # guess content type (content_type, _) = mimetypes.guess_type(basename, strict=False) if content_type is not None: r.headers.set("Content-Type", content_type) return r
def define_routes(self): """ The web app routes for sharing files """ @self.web.app.route("/", defaults={"path": ""}) @self.web.app.route("/<path:path>") def index(path): """ Render the template for the onionshare landing page. """ self.web.add_request(self.web.REQUEST_LOAD, request.path) # Deny new downloads if "Stop sharing after files have been sent" is checked and there is # currently a download deny_download = ( self.web.settings.get("share", "autostop_sharing") and self.download_in_progress ) if deny_download: r = make_response( render_template("denied.html"), static_url_path=self.web.static_url_path, ) return self.web.add_security_headers(r) # If download is allowed to continue, serve download page if self.should_use_gzip(): self.filesize = self.gzip_filesize else: self.filesize = self.download_filesize return self.render_logic(path) @self.web.app.route("/download") def download(): """ Download the zip file. """ # Deny new downloads if "Stop After First Download" is checked and there is # currently a download deny_download = ( self.web.settings.get("share", "autostop_sharing") and self.download_in_progress ) if deny_download: r = make_response( render_template("denied.html", static_url_path=self.web.static_url_path) ) return self.web.add_security_headers(r) # Prepare some variables to use inside generate() function below # which is outside of the request context shutdown_func = request.environ.get("werkzeug.server.shutdown") path = request.path # If this is a zipped file, then serve as-is. If it's not zipped, then, # if the http client supports gzip compression, gzip the file first # and serve that use_gzip = self.should_use_gzip() if use_gzip: file_to_download = self.gzip_filename self.filesize = self.gzip_filesize else: file_to_download = self.download_filename self.filesize = self.download_filesize # Tell GUI the download started history_id = self.cur_history_id self.cur_history_id += 1 self.web.add_request( self.web.REQUEST_STARTED, path, {"id": history_id, "use_gzip": use_gzip} ) basename = os.path.basename(self.download_filename) def generate(): # Starting a new download if self.web.settings.get("share", "autostop_sharing"): self.download_in_progress = True chunk_size = 102400 # 100kb fp = open(file_to_download, "rb") self.web.done = False canceled = False while not self.web.done: # The user has canceled the download, so stop serving the file if not self.web.stop_q.empty(): self.web.add_request( self.web.REQUEST_CANCELED, path, {"id": history_id} ) break chunk = fp.read(chunk_size) if chunk == b"": self.web.done = True else: try: yield chunk # tell GUI the progress downloaded_bytes = fp.tell() percent = (1.0 * downloaded_bytes / self.filesize) * 100 # only output to stdout if running onionshare in CLI mode, or if using Linux (#203, #304) if ( not self.web.is_gui or self.common.platform == "Linux" or self.common.platform == "BSD" ): sys.stdout.write( "\r{0:s}, {1:.2f}% ".format( self.common.human_readable_filesize( downloaded_bytes ), percent, ) ) sys.stdout.flush() self.web.add_request( self.web.REQUEST_PROGRESS, path, {"id": history_id, "bytes": downloaded_bytes}, ) self.web.done = False except: # looks like the download was canceled self.web.done = True canceled = True # tell the GUI the download has canceled self.web.add_request( self.web.REQUEST_CANCELED, path, {"id": history_id} ) fp.close() if self.common.platform != "Darwin": sys.stdout.write("\n") # Download is finished if self.web.settings.get("share", "autostop_sharing"): self.download_in_progress = False # Close the server, if necessary if self.web.settings.get("share", "autostop_sharing") and not canceled: print("Stopped because transfer is complete") self.web.running = False try: if shutdown_func is None: raise RuntimeError("Not running with the Werkzeug Server") shutdown_func() except: pass r = Response(generate()) if use_gzip: r.headers.set("Content-Encoding", "gzip") r.headers.set("Content-Length", self.filesize) r.headers.set("Content-Disposition", "attachment", filename=basename) r = self.web.add_security_headers(r) # guess content type (content_type, _) = mimetypes.guess_type(basename, strict=False) if content_type is not None: r.headers.set("Content-Type", content_type) return r
https://github.com/micahflee/onionshare/issues/1235
[2020-11-25 11:14:20,333] ERROR in app: Exception on / [GET] Traceback (most recent call last): File "/home/user/.cache/pypoetry/virtualenvs/onionshare-cli-c-YlJMZ4-py3.8/lib/python3.8/site-packages/flask/app.py", line 2447, in wsgi_app response = self.full_dispatch_request() File "/home/user/.cache/pypoetry/virtualenvs/onionshare-cli-c-YlJMZ4-py3.8/lib/python3.8/site-packages/flask/app.py", line 1952, in full_dispatch_request rv = self.handle_user_exception(e) File "/home/user/.cache/pypoetry/virtualenvs/onionshare-cli-c-YlJMZ4-py3.8/lib/python3.8/site-packages/flask/app.py", line 1821, in handle_user_exception reraise(exc_type, exc_value, tb) File "/home/user/.cache/pypoetry/virtualenvs/onionshare-cli-c-YlJMZ4-py3.8/lib/python3.8/site-packages/flask/_compat.py", line 39, in reraise raise value File "/home/user/.cache/pypoetry/virtualenvs/onionshare-cli-c-YlJMZ4-py3.8/lib/python3.8/site-packages/flask/app.py", line 1950, in full_dispatch_request rv = self.dispatch_request() File "/home/user/.cache/pypoetry/virtualenvs/onionshare-cli-c-YlJMZ4-py3.8/lib/python3.8/site-packages/flask/app.py", line 1936, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "/home/user/code/onionshare/cli/onionshare_cli/web/share_mode.py", line 64, in index r = make_response( TypeError: make_response() got an unexpected keyword argument 'static_url_path'
TypeError
def index(path): """ Render the template for the onionshare landing page. """ self.web.add_request(self.web.REQUEST_LOAD, request.path) # Deny new downloads if "Stop sharing after files have been sent" is checked and there is # currently a download deny_download = ( self.web.settings.get("share", "autostop_sharing") and self.download_in_progress ) if deny_download: r = make_response(render_template("denied.html")) return self.web.add_security_headers(r) # If download is allowed to continue, serve download page if self.should_use_gzip(): self.filesize = self.gzip_filesize else: self.filesize = self.download_filesize return self.render_logic(path)
def index(path): """ Render the template for the onionshare landing page. """ self.web.add_request(self.web.REQUEST_LOAD, request.path) # Deny new downloads if "Stop sharing after files have been sent" is checked and there is # currently a download deny_download = ( self.web.settings.get("share", "autostop_sharing") and self.download_in_progress ) if deny_download: r = make_response( render_template("denied.html"), static_url_path=self.web.static_url_path, ) return self.web.add_security_headers(r) # If download is allowed to continue, serve download page if self.should_use_gzip(): self.filesize = self.gzip_filesize else: self.filesize = self.download_filesize return self.render_logic(path)
https://github.com/micahflee/onionshare/issues/1235
[2020-11-25 11:14:20,333] ERROR in app: Exception on / [GET] Traceback (most recent call last): File "/home/user/.cache/pypoetry/virtualenvs/onionshare-cli-c-YlJMZ4-py3.8/lib/python3.8/site-packages/flask/app.py", line 2447, in wsgi_app response = self.full_dispatch_request() File "/home/user/.cache/pypoetry/virtualenvs/onionshare-cli-c-YlJMZ4-py3.8/lib/python3.8/site-packages/flask/app.py", line 1952, in full_dispatch_request rv = self.handle_user_exception(e) File "/home/user/.cache/pypoetry/virtualenvs/onionshare-cli-c-YlJMZ4-py3.8/lib/python3.8/site-packages/flask/app.py", line 1821, in handle_user_exception reraise(exc_type, exc_value, tb) File "/home/user/.cache/pypoetry/virtualenvs/onionshare-cli-c-YlJMZ4-py3.8/lib/python3.8/site-packages/flask/_compat.py", line 39, in reraise raise value File "/home/user/.cache/pypoetry/virtualenvs/onionshare-cli-c-YlJMZ4-py3.8/lib/python3.8/site-packages/flask/app.py", line 1950, in full_dispatch_request rv = self.dispatch_request() File "/home/user/.cache/pypoetry/virtualenvs/onionshare-cli-c-YlJMZ4-py3.8/lib/python3.8/site-packages/flask/app.py", line 1936, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "/home/user/code/onionshare/cli/onionshare_cli/web/share_mode.py", line 64, in index r = make_response( TypeError: make_response() got an unexpected keyword argument 'static_url_path'
TypeError
def download(): """ Download the zip file. """ # Deny new downloads if "Stop After First Download" is checked and there is # currently a download deny_download = ( self.web.settings.get("share", "autostop_sharing") and self.download_in_progress ) if deny_download: r = make_response(render_template("denied.html")) return self.web.add_security_headers(r) # Prepare some variables to use inside generate() function below # which is outside of the request context shutdown_func = request.environ.get("werkzeug.server.shutdown") path = request.path # If this is a zipped file, then serve as-is. If it's not zipped, then, # if the http client supports gzip compression, gzip the file first # and serve that use_gzip = self.should_use_gzip() if use_gzip: file_to_download = self.gzip_filename self.filesize = self.gzip_filesize else: file_to_download = self.download_filename self.filesize = self.download_filesize # Tell GUI the download started history_id = self.cur_history_id self.cur_history_id += 1 self.web.add_request( self.web.REQUEST_STARTED, path, {"id": history_id, "use_gzip": use_gzip} ) basename = os.path.basename(self.download_filename) def generate(): # Starting a new download if self.web.settings.get("share", "autostop_sharing"): self.download_in_progress = True chunk_size = 102400 # 100kb fp = open(file_to_download, "rb") self.web.done = False canceled = False while not self.web.done: # The user has canceled the download, so stop serving the file if not self.web.stop_q.empty(): self.web.add_request( self.web.REQUEST_CANCELED, path, {"id": history_id} ) break chunk = fp.read(chunk_size) if chunk == b"": self.web.done = True else: try: yield chunk # tell GUI the progress downloaded_bytes = fp.tell() percent = (1.0 * downloaded_bytes / self.filesize) * 100 # only output to stdout if running onionshare in CLI mode, or if using Linux (#203, #304) if ( not self.web.is_gui or self.common.platform == "Linux" or self.common.platform == "BSD" ): sys.stdout.write( "\r{0:s}, {1:.2f}% ".format( self.common.human_readable_filesize(downloaded_bytes), percent, ) ) sys.stdout.flush() self.web.add_request( self.web.REQUEST_PROGRESS, path, {"id": history_id, "bytes": downloaded_bytes}, ) self.web.done = False except: # looks like the download was canceled self.web.done = True canceled = True # tell the GUI the download has canceled self.web.add_request( self.web.REQUEST_CANCELED, path, {"id": history_id} ) fp.close() if self.common.platform != "Darwin": sys.stdout.write("\n") # Download is finished if self.web.settings.get("share", "autostop_sharing"): self.download_in_progress = False # Close the server, if necessary if self.web.settings.get("share", "autostop_sharing") and not canceled: print("Stopped because transfer is complete") self.web.running = False try: if shutdown_func is None: raise RuntimeError("Not running with the Werkzeug Server") shutdown_func() except: pass r = Response(generate()) if use_gzip: r.headers.set("Content-Encoding", "gzip") r.headers.set("Content-Length", self.filesize) r.headers.set("Content-Disposition", "attachment", filename=basename) r = self.web.add_security_headers(r) # guess content type (content_type, _) = mimetypes.guess_type(basename, strict=False) if content_type is not None: r.headers.set("Content-Type", content_type) return r
def download(): """ Download the zip file. """ # Deny new downloads if "Stop After First Download" is checked and there is # currently a download deny_download = ( self.web.settings.get("share", "autostop_sharing") and self.download_in_progress ) if deny_download: r = make_response( render_template("denied.html", static_url_path=self.web.static_url_path) ) return self.web.add_security_headers(r) # Prepare some variables to use inside generate() function below # which is outside of the request context shutdown_func = request.environ.get("werkzeug.server.shutdown") path = request.path # If this is a zipped file, then serve as-is. If it's not zipped, then, # if the http client supports gzip compression, gzip the file first # and serve that use_gzip = self.should_use_gzip() if use_gzip: file_to_download = self.gzip_filename self.filesize = self.gzip_filesize else: file_to_download = self.download_filename self.filesize = self.download_filesize # Tell GUI the download started history_id = self.cur_history_id self.cur_history_id += 1 self.web.add_request( self.web.REQUEST_STARTED, path, {"id": history_id, "use_gzip": use_gzip} ) basename = os.path.basename(self.download_filename) def generate(): # Starting a new download if self.web.settings.get("share", "autostop_sharing"): self.download_in_progress = True chunk_size = 102400 # 100kb fp = open(file_to_download, "rb") self.web.done = False canceled = False while not self.web.done: # The user has canceled the download, so stop serving the file if not self.web.stop_q.empty(): self.web.add_request( self.web.REQUEST_CANCELED, path, {"id": history_id} ) break chunk = fp.read(chunk_size) if chunk == b"": self.web.done = True else: try: yield chunk # tell GUI the progress downloaded_bytes = fp.tell() percent = (1.0 * downloaded_bytes / self.filesize) * 100 # only output to stdout if running onionshare in CLI mode, or if using Linux (#203, #304) if ( not self.web.is_gui or self.common.platform == "Linux" or self.common.platform == "BSD" ): sys.stdout.write( "\r{0:s}, {1:.2f}% ".format( self.common.human_readable_filesize(downloaded_bytes), percent, ) ) sys.stdout.flush() self.web.add_request( self.web.REQUEST_PROGRESS, path, {"id": history_id, "bytes": downloaded_bytes}, ) self.web.done = False except: # looks like the download was canceled self.web.done = True canceled = True # tell the GUI the download has canceled self.web.add_request( self.web.REQUEST_CANCELED, path, {"id": history_id} ) fp.close() if self.common.platform != "Darwin": sys.stdout.write("\n") # Download is finished if self.web.settings.get("share", "autostop_sharing"): self.download_in_progress = False # Close the server, if necessary if self.web.settings.get("share", "autostop_sharing") and not canceled: print("Stopped because transfer is complete") self.web.running = False try: if shutdown_func is None: raise RuntimeError("Not running with the Werkzeug Server") shutdown_func() except: pass r = Response(generate()) if use_gzip: r.headers.set("Content-Encoding", "gzip") r.headers.set("Content-Length", self.filesize) r.headers.set("Content-Disposition", "attachment", filename=basename) r = self.web.add_security_headers(r) # guess content type (content_type, _) = mimetypes.guess_type(basename, strict=False) if content_type is not None: r.headers.set("Content-Type", content_type) return r
https://github.com/micahflee/onionshare/issues/1235
[2020-11-25 11:14:20,333] ERROR in app: Exception on / [GET] Traceback (most recent call last): File "/home/user/.cache/pypoetry/virtualenvs/onionshare-cli-c-YlJMZ4-py3.8/lib/python3.8/site-packages/flask/app.py", line 2447, in wsgi_app response = self.full_dispatch_request() File "/home/user/.cache/pypoetry/virtualenvs/onionshare-cli-c-YlJMZ4-py3.8/lib/python3.8/site-packages/flask/app.py", line 1952, in full_dispatch_request rv = self.handle_user_exception(e) File "/home/user/.cache/pypoetry/virtualenvs/onionshare-cli-c-YlJMZ4-py3.8/lib/python3.8/site-packages/flask/app.py", line 1821, in handle_user_exception reraise(exc_type, exc_value, tb) File "/home/user/.cache/pypoetry/virtualenvs/onionshare-cli-c-YlJMZ4-py3.8/lib/python3.8/site-packages/flask/_compat.py", line 39, in reraise raise value File "/home/user/.cache/pypoetry/virtualenvs/onionshare-cli-c-YlJMZ4-py3.8/lib/python3.8/site-packages/flask/app.py", line 1950, in full_dispatch_request rv = self.dispatch_request() File "/home/user/.cache/pypoetry/virtualenvs/onionshare-cli-c-YlJMZ4-py3.8/lib/python3.8/site-packages/flask/app.py", line 1936, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "/home/user/code/onionshare/cli/onionshare_cli/web/share_mode.py", line 64, in index r = make_response( TypeError: make_response() got an unexpected keyword argument 'static_url_path'
TypeError
def main(cwd=None): """ The main() function implements all of the logic that the command-line version of onionshare uses. """ common = Common() # Display OnionShare banner print(f"OnionShare {common.version} | https://onionshare.org/") reset = "\033[0m" purple = "\33[95m" print(purple) print(" @@@@@@@@@ ") print(" @@@@@@@@@@@@@@@@@@@ ") print(" @@@@@@@@@@@@@@@@@@@@@@@@@ ") print(" @@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ") print( " @@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ___ _ " ) print( " @@@@@@ @@@@@@@@@@@@@ / _ \\ (_) " ) print( " @@@@ @ @@@@@@@@@@@ | | | |_ __ _ ___ _ __ " ) print( " @@@@@@@@ @@@@@@@@@@ | | | | '_ \\| |/ _ \\| '_ \\ " ) print( " @@@@@@@@@@@@ @@@@@@@@@@ \\ \\_/ / | | | | (_) | | | | " ) print( " @@@@@@@@@@@@@@@@ @@@@@@@@@ \\___/|_| |_|_|\\___/|_| |_| " ) print( " @@@@@@@@@ @@@@@@@@@@@@@@@@ _____ _ " ) print( " @@@@@@@@@@ @@@@@@@@@@@@ / ___| | " ) print( " @@@@@@@@@@ @@@@@@@@ \\ `--.| |__ __ _ _ __ ___ " ) print( " @@@@@@@@@@@ @ @@@@ `--. \\ '_ \\ / _` | '__/ _ \\" ) print( " @@@@@@@@@@@@@ @@@@@@ /\\__/ / | | | (_| | | | __/" ) print( " @@@@@@@@@@@@@@@@@@@@@@@@@@@@@ \\____/|_| |_|\\__,_|_| \\___|" ) print(" @@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ") print(" @@@@@@@@@@@@@@@@@@@@@@@@@ ") print(" @@@@@@@@@@@@@@@@@@@ ") print(" @@@@@@@@@ ") print(reset) # OnionShare CLI in OSX needs to change current working directory (#132) if common.platform == "Darwin": if cwd: os.chdir(cwd) # Parse arguments parser = argparse.ArgumentParser( formatter_class=lambda prog: argparse.HelpFormatter(prog, max_help_position=28) ) # Select modes parser.add_argument( "--receive", action="store_true", dest="receive", help="Receive files" ) parser.add_argument( "--website", action="store_true", dest="website", help="Publish website" ) parser.add_argument( "--chat", action="store_true", dest="chat", help="Start chat server" ) # Tor connection-related args parser.add_argument( "--local-only", action="store_true", dest="local_only", default=False, help="Don't use Tor (only for development)", ) parser.add_argument( "--connect-timeout", metavar="SECONDS", dest="connect_timeout", default=120, help="Give up connecting to Tor after a given amount of seconds (default: 120)", ) parser.add_argument( "--config", metavar="FILENAME", default=None, help="Filename of custom global settings", ) # Persistent file parser.add_argument( "--persistent", metavar="FILENAME", default=None, help="Filename of persistent session", ) # General args parser.add_argument( "--public", action="store_true", dest="public", default=False, help="Don't use a password", ) parser.add_argument( "--auto-start-timer", metavar="SECONDS", dest="autostart_timer", default=0, help="Start onion service at scheduled time (N seconds from now)", ) parser.add_argument( "--auto-stop-timer", metavar="SECONDS", dest="autostop_timer", default=0, help="Stop onion service at schedule time (N seconds from now)", ) parser.add_argument( "--legacy", action="store_true", dest="legacy", default=False, help="Use legacy address (v2 onion service, not recommended)", ) parser.add_argument( "--client-auth", action="store_true", dest="client_auth", default=False, help="Use client authorization (requires --legacy)", ) # Share args parser.add_argument( "--autostop-sharing", action="store_true", dest="autostop_sharing", default=True, help="Share files: Stop sharing after files have been sent", ) # Receive args parser.add_argument( "--data-dir", metavar="data_dir", default=None, help="Receive files: Save files received to this directory", ) # Website args parser.add_argument( "--disable_csp", action="store_true", dest="disable_csp", default=False, help="Publish website: Disable Content Security Policy header (allows your website to use third-party resources)", ) # Other parser.add_argument( "-v", "--verbose", action="store_true", dest="verbose", help="Log OnionShare errors to stdout, and web errors to disk", ) parser.add_argument( "filename", metavar="filename", nargs="*", help="List of files or folders to share", ) args = parser.parse_args() filenames = args.filename for i in range(len(filenames)): filenames[i] = os.path.abspath(filenames[i]) receive = bool(args.receive) website = bool(args.website) chat = bool(args.chat) local_only = bool(args.local_only) connect_timeout = int(args.connect_timeout) config_filename = args.config persistent_filename = args.persistent public = bool(args.public) autostart_timer = int(args.autostart_timer) autostop_timer = int(args.autostop_timer) legacy = bool(args.legacy) client_auth = bool(args.client_auth) autostop_sharing = bool(args.autostop_sharing) data_dir = args.data_dir disable_csp = bool(args.disable_csp) verbose = bool(args.verbose) if receive: mode = "receive" elif website: mode = "website" elif chat: mode = "chat" else: mode = "share" # Verbose mode? common.verbose = verbose # client_auth can only be set if legacy is also set if client_auth and not legacy: print( "Client authentication (--client-auth) is only supported with with legacy onion services (--legacy)" ) sys.exit() # Re-load settings, if a custom config was passed in if config_filename: common.load_settings(config_filename) else: common.load_settings() # Mode settings if persistent_filename: mode_settings = ModeSettings(common, persistent_filename) mode_settings.set("persistent", "enabled", True) else: mode_settings = ModeSettings(common) if mode_settings.just_created: # This means the mode settings were just created, not loaded from disk mode_settings.set("general", "public", public) mode_settings.set("general", "autostart_timer", autostart_timer) mode_settings.set("general", "autostop_timer", autostop_timer) mode_settings.set("general", "legacy", legacy) mode_settings.set("general", "client_auth", client_auth) if mode == "share": mode_settings.set("share", "autostop_sharing", autostop_sharing) if mode == "receive": if data_dir: mode_settings.set("receive", "data_dir", data_dir) if mode == "website": mode_settings.set("website", "disable_csp", disable_csp) else: # See what the persistent mode was mode = mode_settings.get("persistent", "mode") # In share and website mode, you must supply a list of filenames if mode == "share" or mode == "website": # Unless you passed in a persistent filename, in which case get the filenames from # the mode settings if persistent_filename and not mode_settings.just_created: filenames = mode_settings.get(mode, "filenames") else: # Make sure filenames given if not using receiver mode if len(filenames) == 0: if persistent_filename: mode_settings.delete() parser.print_help() sys.exit() # Validate filenames valid = True for filename in filenames: if not os.path.isfile(filename) and not os.path.isdir(filename): print(f"{filename} is not a valid file.") valid = False if not os.access(filename, os.R_OK): print(f"{filename} is not a readable file.") valid = False if not valid: sys.exit() # Create the Web object web = Web(common, False, mode_settings, mode) # Start the Onion object try: onion = Onion(common, use_tmp_dir=True) except CannotFindTor: print("You must install tor to use OnionShare from the command line") if common.platform == "Darwin": print("In macOS, you can do this with Homebrew (https://brew.sh):") print(" brew install tor") sys.exit() try: onion.connect( custom_settings=False, config=config_filename, connect_timeout=connect_timeout, local_only=local_only, ) except KeyboardInterrupt: print("") sys.exit() except Exception as e: sys.exit(e.args[0]) # Start the onionshare app try: common.settings.load() if not mode_settings.get("general", "public"): web.generate_password(mode_settings.get("onion", "password")) else: web.password = None app = OnionShare(common, onion, local_only, autostop_timer) app.choose_port() # Delay the startup if a startup timer was set if autostart_timer > 0: # Can't set a schedule that is later than the auto-stop timer if autostop_timer > 0 and autostop_timer < autostart_timer: print( "The auto-stop time can't be the same or earlier than the auto-start time. Please update it to start sharing." ) sys.exit() app.start_onion_service(mode_settings, False, True) url = build_url(mode_settings, app, web) schedule = datetime.now() + timedelta(seconds=autostart_timer) if mode == "receive": print( f"Files sent to you appear in this folder: {mode_settings.get('receive', 'data_dir')}" ) print("") print( "Warning: Receive mode lets people upload files to your computer. Some files can potentially take control of your computer if you open them. Only open things from people you trust, or if you know what you are doing." ) print("") if mode_settings.get("general", "client_auth"): print( f"Give this address and HidServAuth lineto your sender, and tell them it won't be accessible until: {schedule.strftime('%I:%M:%S%p, %b %d, %y')}" ) print(app.auth_string) else: print( f"Give this address to your sender, and tell them it won't be accessible until: {schedule.strftime('%I:%M:%S%p, %b %d, %y')}" ) else: if mode_settings.get("general", "client_auth"): print( f"Give this address and HidServAuth line to your recipient, and tell them it won't be accessible until: {schedule.strftime('%I:%M:%S%p, %b %d, %y')}" ) print(app.auth_string) else: print( f"Give this address to your recipient, and tell them it won't be accessible until: {schedule.strftime('%I:%M:%S%p, %b %d, %y')}" ) print(url) print("") print("Waiting for the scheduled time before starting...") app.onion.cleanup(False) time.sleep(autostart_timer) app.start_onion_service(mode_settings) else: app.start_onion_service(mode_settings) except KeyboardInterrupt: print("") sys.exit() except (TorTooOld, TorErrorProtocolError) as e: print("") print(e.args[0]) sys.exit() if mode == "website": # Prepare files to share try: web.website_mode.set_file_info(filenames) except OSError as e: print(e.strerror) sys.exit(1) if mode == "share": # Prepare files to share print("Compressing files.") try: web.share_mode.set_file_info(filenames) app.cleanup_filenames += web.share_mode.cleanup_filenames except OSError as e: print(e.strerror) sys.exit(1) # Warn about sending large files over Tor if web.share_mode.download_filesize >= 157286400: # 150mb print("") print("Warning: Sending a large share could take hours") print("") # Start OnionShare http service in new thread t = threading.Thread(target=web.start, args=(app.port,)) t.daemon = True t.start() try: # Trap Ctrl-C # Wait for web.generate_password() to finish running time.sleep(0.2) # start auto-stop timer thread if app.autostop_timer > 0: app.autostop_timer_thread.start() # Save the web password if we are using a persistent private key if mode_settings.get("persistent", "enabled"): if not mode_settings.get("onion", "password"): mode_settings.set("onion", "password", web.password) # mode_settings.save() # Build the URL url = build_url(mode_settings, app, web) print("") if autostart_timer > 0: print("Server started") else: if mode == "receive": print( f"Files sent to you appear in this folder: {mode_settings.get('receive', 'data_dir')}" ) print("") print( "Warning: Receive mode lets people upload files to your computer. Some files can potentially take control of your computer if you open them. Only open things from people you trust, or if you know what you are doing." ) print("") if mode_settings.get("general", "client_auth"): print("Give this address and HidServAuth to the sender:") print(url) print(app.auth_string) else: print("Give this address to the sender:") print(url) else: if mode_settings.get("general", "client_auth"): print("Give this address and HidServAuth line to the recipient:") print(url) print(app.auth_string) else: print("Give this address to the recipient:") print(url) print("") print("Press Ctrl+C to stop the server") # Wait for app to close while t.is_alive(): if app.autostop_timer > 0: # if the auto-stop timer was set and has run out, stop the server if not app.autostop_timer_thread.is_alive(): if mode == "share" or (mode == "website"): # If there were no attempts to download the share, or all downloads are done, we can stop if web.share_mode.cur_history_id == 0 or web.done: print("Stopped because auto-stop timer ran out") web.stop(app.port) break if mode == "receive": if ( web.receive_mode.cur_history_id == 0 or not web.receive_mode.uploads_in_progress ): print("Stopped because auto-stop timer ran out") web.stop(app.port) break else: web.receive_mode.can_upload = False # Allow KeyboardInterrupt exception to be handled with threads # https://stackoverflow.com/questions/3788208/python-threading-ignores-keyboardinterrupt-exception time.sleep(0.2) except KeyboardInterrupt: web.stop(app.port) finally: # Shutdown app.cleanup() onion.cleanup()
def main(cwd=None): """ The main() function implements all of the logic that the command-line version of onionshare uses. """ common = Common() # Display OnionShare banner print(f"OnionShare {common.version} | https://onionshare.org/") reset = "\033[0m" purple = "\33[95m" print(purple) print(" @@@@@@@@@ ") print(" @@@@@@@@@@@@@@@@@@@ ") print(" @@@@@@@@@@@@@@@@@@@@@@@@@ ") print(" @@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ") print( " @@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ___ _ " ) print( " @@@@@@ @@@@@@@@@@@@@ / _ \\ (_) " ) print( " @@@@ @ @@@@@@@@@@@ | | | |_ __ _ ___ _ __ " ) print( " @@@@@@@@ @@@@@@@@@@ | | | | '_ \\| |/ _ \\| '_ \\ " ) print( " @@@@@@@@@@@@ @@@@@@@@@@ \\ \\_/ / | | | | (_) | | | | " ) print( " @@@@@@@@@@@@@@@@ @@@@@@@@@ \\___/|_| |_|_|\\___/|_| |_| " ) print( " @@@@@@@@@ @@@@@@@@@@@@@@@@ _____ _ " ) print( " @@@@@@@@@@ @@@@@@@@@@@@ / ___| | " ) print( " @@@@@@@@@@ @@@@@@@@ \\ `--.| |__ __ _ _ __ ___ " ) print( " @@@@@@@@@@@ @ @@@@ `--. \\ '_ \\ / _` | '__/ _ \\" ) print( " @@@@@@@@@@@@@ @@@@@@ /\\__/ / | | | (_| | | | __/" ) print( " @@@@@@@@@@@@@@@@@@@@@@@@@@@@@ \\____/|_| |_|\\__,_|_| \\___|" ) print(" @@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ") print(" @@@@@@@@@@@@@@@@@@@@@@@@@ ") print(" @@@@@@@@@@@@@@@@@@@ ") print(" @@@@@@@@@ ") print(reset) # OnionShare CLI in OSX needs to change current working directory (#132) if common.platform == "Darwin": if cwd: os.chdir(cwd) # Parse arguments parser = argparse.ArgumentParser( formatter_class=lambda prog: argparse.HelpFormatter(prog, max_help_position=28) ) # Select modes parser.add_argument( "--receive", action="store_true", dest="receive", help="Receive files" ) parser.add_argument( "--website", action="store_true", dest="website", help="Publish website" ) parser.add_argument( "--chat", action="store_true", dest="chat", help="Start chat server" ) # Tor connection-related args parser.add_argument( "--local-only", action="store_true", dest="local_only", default=False, help="Don't use Tor (only for development)", ) parser.add_argument( "--connect-timeout", metavar="SECONDS", dest="connect_timeout", default=120, help="Give up connecting to Tor after a given amount of seconds (default: 120)", ) parser.add_argument( "--config", metavar="FILENAME", default=None, help="Filename of custom global settings", ) # Persistent file parser.add_argument( "--persistent", metavar="FILENAME", default=None, help="Filename of persistent session", ) # General args parser.add_argument( "--public", action="store_true", dest="public", default=False, help="Don't use a password", ) parser.add_argument( "--auto-start-timer", metavar="SECONDS", dest="autostart_timer", default=0, help="Start onion service at scheduled time (N seconds from now)", ) parser.add_argument( "--auto-stop-timer", metavar="SECONDS", dest="autostop_timer", default=0, help="Stop onion service at schedule time (N seconds from now)", ) parser.add_argument( "--legacy", action="store_true", dest="legacy", default=False, help="Use legacy address (v2 onion service, not recommended)", ) parser.add_argument( "--client-auth", action="store_true", dest="client_auth", default=False, help="Use client authorization (requires --legacy)", ) # Share args parser.add_argument( "--autostop-sharing", action="store_true", dest="autostop_sharing", default=True, help="Share files: Stop sharing after files have been sent", ) # Receive args parser.add_argument( "--data-dir", metavar="data_dir", default=None, help="Receive files: Save files received to this directory", ) # Website args parser.add_argument( "--disable_csp", action="store_true", dest="disable_csp", default=False, help="Publish website: Disable Content Security Policy header (allows your website to use third-party resources)", ) # Other parser.add_argument( "-v", "--verbose", action="store_true", dest="verbose", help="Log OnionShare errors to stdout, and web errors to disk", ) parser.add_argument( "filename", metavar="filename", nargs="*", help="List of files or folders to share", ) args = parser.parse_args() filenames = args.filename for i in range(len(filenames)): filenames[i] = os.path.abspath(filenames[i]) receive = bool(args.receive) website = bool(args.website) chat = bool(args.chat) local_only = bool(args.local_only) connect_timeout = int(args.connect_timeout) config_filename = args.config persistent_filename = args.persistent public = bool(args.public) autostart_timer = int(args.autostart_timer) autostop_timer = int(args.autostop_timer) legacy = bool(args.legacy) client_auth = bool(args.client_auth) autostop_sharing = bool(args.autostop_sharing) data_dir = args.data_dir disable_csp = bool(args.disable_csp) verbose = bool(args.verbose) if receive: mode = "receive" elif website: mode = "website" elif chat: mode = "chat" else: mode = "share" # Verbose mode? common.verbose = verbose # client_auth can only be set if legacy is also set if client_auth and not legacy: print( "Client authentication (--client-auth) is only supported with with legacy onion services (--legacy)" ) sys.exit() # Re-load settings, if a custom config was passed in if config_filename: common.load_settings(config_filename) else: common.load_settings() # Mode settings if persistent_filename: mode_settings = ModeSettings(common, persistent_filename) mode_settings.set("persistent", "enabled", True) else: mode_settings = ModeSettings(common) if mode_settings.just_created: # This means the mode settings were just created, not loaded from disk mode_settings.set("general", "public", public) mode_settings.set("general", "autostart_timer", autostart_timer) mode_settings.set("general", "autostop_timer", autostop_timer) mode_settings.set("general", "legacy", legacy) mode_settings.set("general", "client_auth", client_auth) if mode == "share": mode_settings.set("share", "autostop_sharing", autostop_sharing) if mode == "receive": if data_dir: mode_settings.set("receive", "data_dir", data_dir) if mode == "website": mode_settings.set("website", "disable_csp", disable_csp) else: # See what the persistent mode was mode = mode_settings.get("persistent", "mode") # In share and website mode, you must supply a list of filenames if mode == "share" or mode == "website": # Unless you passed in a persistent filename, in which case get the filenames from # the mode settings if persistent_filename and not mode_settings.just_created: filenames = mode_settings.get(mode, "filenames") else: # Make sure filenames given if not using receiver mode if len(filenames) == 0: if persistent_filename: mode_settings.delete() parser.print_help() sys.exit() # Validate filenames valid = True for filename in filenames: if not os.path.isfile(filename) and not os.path.isdir(filename): print(f"{filename} is not a valid file.") valid = False if not os.access(filename, os.R_OK): print(f"{filename} is not a readable file.") valid = False if not valid: sys.exit() # Create the Web object web = Web(common, False, mode_settings, mode) # Start the Onion object onion = Onion(common, use_tmp_dir=True) try: onion.connect( custom_settings=False, config=config_filename, connect_timeout=connect_timeout, local_only=local_only, ) except KeyboardInterrupt: print("") sys.exit() except Exception as e: sys.exit(e.args[0]) # Start the onionshare app try: common.settings.load() if not mode_settings.get("general", "public"): web.generate_password(mode_settings.get("onion", "password")) else: web.password = None app = OnionShare(common, onion, local_only, autostop_timer) app.choose_port() # Delay the startup if a startup timer was set if autostart_timer > 0: # Can't set a schedule that is later than the auto-stop timer if autostop_timer > 0 and autostop_timer < autostart_timer: print( "The auto-stop time can't be the same or earlier than the auto-start time. Please update it to start sharing." ) sys.exit() app.start_onion_service(mode_settings, False, True) url = build_url(mode_settings, app, web) schedule = datetime.now() + timedelta(seconds=autostart_timer) if mode == "receive": print( f"Files sent to you appear in this folder: {mode_settings.get('receive', 'data_dir')}" ) print("") print( "Warning: Receive mode lets people upload files to your computer. Some files can potentially take control of your computer if you open them. Only open things from people you trust, or if you know what you are doing." ) print("") if mode_settings.get("general", "client_auth"): print( f"Give this address and HidServAuth lineto your sender, and tell them it won't be accessible until: {schedule.strftime('%I:%M:%S%p, %b %d, %y')}" ) print(app.auth_string) else: print( f"Give this address to your sender, and tell them it won't be accessible until: {schedule.strftime('%I:%M:%S%p, %b %d, %y')}" ) else: if mode_settings.get("general", "client_auth"): print( f"Give this address and HidServAuth line to your recipient, and tell them it won't be accessible until: {schedule.strftime('%I:%M:%S%p, %b %d, %y')}" ) print(app.auth_string) else: print( f"Give this address to your recipient, and tell them it won't be accessible until: {schedule.strftime('%I:%M:%S%p, %b %d, %y')}" ) print(url) print("") print("Waiting for the scheduled time before starting...") app.onion.cleanup(False) time.sleep(autostart_timer) app.start_onion_service(mode_settings) else: app.start_onion_service(mode_settings) except KeyboardInterrupt: print("") sys.exit() except (TorTooOld, TorErrorProtocolError) as e: print("") print(e.args[0]) sys.exit() if mode == "website": # Prepare files to share try: web.website_mode.set_file_info(filenames) except OSError as e: print(e.strerror) sys.exit(1) if mode == "share": # Prepare files to share print("Compressing files.") try: web.share_mode.set_file_info(filenames) app.cleanup_filenames += web.share_mode.cleanup_filenames except OSError as e: print(e.strerror) sys.exit(1) # Warn about sending large files over Tor if web.share_mode.download_filesize >= 157286400: # 150mb print("") print("Warning: Sending a large share could take hours") print("") # Start OnionShare http service in new thread t = threading.Thread(target=web.start, args=(app.port,)) t.daemon = True t.start() try: # Trap Ctrl-C # Wait for web.generate_password() to finish running time.sleep(0.2) # start auto-stop timer thread if app.autostop_timer > 0: app.autostop_timer_thread.start() # Save the web password if we are using a persistent private key if mode_settings.get("persistent", "enabled"): if not mode_settings.get("onion", "password"): mode_settings.set("onion", "password", web.password) # mode_settings.save() # Build the URL url = build_url(mode_settings, app, web) print("") if autostart_timer > 0: print("Server started") else: if mode == "receive": print( f"Files sent to you appear in this folder: {mode_settings.get('receive', 'data_dir')}" ) print("") print( "Warning: Receive mode lets people upload files to your computer. Some files can potentially take control of your computer if you open them. Only open things from people you trust, or if you know what you are doing." ) print("") if mode_settings.get("general", "client_auth"): print("Give this address and HidServAuth to the sender:") print(url) print(app.auth_string) else: print("Give this address to the sender:") print(url) else: if mode_settings.get("general", "client_auth"): print("Give this address and HidServAuth line to the recipient:") print(url) print(app.auth_string) else: print("Give this address to the recipient:") print(url) print("") print("Press Ctrl+C to stop the server") # Wait for app to close while t.is_alive(): if app.autostop_timer > 0: # if the auto-stop timer was set and has run out, stop the server if not app.autostop_timer_thread.is_alive(): if mode == "share" or (mode == "website"): # If there were no attempts to download the share, or all downloads are done, we can stop if web.share_mode.cur_history_id == 0 or web.done: print("Stopped because auto-stop timer ran out") web.stop(app.port) break if mode == "receive": if ( web.receive_mode.cur_history_id == 0 or not web.receive_mode.uploads_in_progress ): print("Stopped because auto-stop timer ran out") web.stop(app.port) break else: web.receive_mode.can_upload = False # Allow KeyboardInterrupt exception to be handled with threads # https://stackoverflow.com/questions/3788208/python-threading-ignores-keyboardinterrupt-exception time.sleep(0.2) except KeyboardInterrupt: web.stop(app.port) finally: # Shutdown app.cleanup() onion.cleanup()
https://github.com/micahflee/onionshare/issues/1237
Traceback (most recent call last): File "/Applications/OnionShare.app/Contents/Resources/app/onionshare/main_window.py", line 228, in open_settings d = SettingsDialog(self.common) File "/Applications/OnionShare.app/Contents/Resources/app/onionshare/settings_dialog.py", line 145, in __init__ ) = self.common.get_tor_paths() File "/Applications/OnionShare.app/Contents/Resources/app_packages/onionshare_cli/common.py", line 98, in get_tor_paths prefix = os.path.dirname(os.path.dirname(tor_path)) File "/Applications/OnionShare.app/Contents/Resources/Support/lib/python3.8/posixpath.py", line 152, in dirname p = os.fspath(p) TypeError: expected str, bytes or os.PathLike object, not NoneType
TypeError
def get_tor_paths(self): if self.platform == "Linux": tor_path = shutil.which("tor") if not tor_path: raise CannotFindTor() obfs4proxy_file_path = shutil.which("obfs4proxy") prefix = os.path.dirname(os.path.dirname(tor_path)) tor_geo_ip_file_path = os.path.join(prefix, "share/tor/geoip") tor_geo_ipv6_file_path = os.path.join(prefix, "share/tor/geoip6") elif self.platform == "Windows": base_path = self.get_resource_path("tor") tor_path = os.path.join(base_path, "Tor", "tor.exe") obfs4proxy_file_path = os.path.join(base_path, "Tor", "obfs4proxy.exe") tor_geo_ip_file_path = os.path.join(base_path, "Data", "Tor", "geoip") tor_geo_ipv6_file_path = os.path.join(base_path, "Data", "Tor", "geoip6") elif self.platform == "Darwin": tor_path = shutil.which("tor") if not tor_path: raise CannotFindTor() obfs4proxy_file_path = shutil.which("obfs4proxy") prefix = os.path.dirname(os.path.dirname(tor_path)) tor_geo_ip_file_path = os.path.join(prefix, "share/tor/geoip") tor_geo_ipv6_file_path = os.path.join(prefix, "share/tor/geoip6") elif self.platform == "BSD": tor_path = "/usr/local/bin/tor" tor_geo_ip_file_path = "/usr/local/share/tor/geoip" tor_geo_ipv6_file_path = "/usr/local/share/tor/geoip6" obfs4proxy_file_path = "/usr/local/bin/obfs4proxy" return ( tor_path, tor_geo_ip_file_path, tor_geo_ipv6_file_path, obfs4proxy_file_path, )
def get_tor_paths(self): if self.platform == "Linux": tor_path = shutil.which("tor") obfs4proxy_file_path = shutil.which("obfs4proxy") prefix = os.path.dirname(os.path.dirname(tor_path)) tor_geo_ip_file_path = os.path.join(prefix, "share/tor/geoip") tor_geo_ipv6_file_path = os.path.join(prefix, "share/tor/geoip6") elif self.platform == "Windows": base_path = self.get_resource_path("tor") tor_path = os.path.join(base_path, "Tor", "tor.exe") obfs4proxy_file_path = os.path.join(base_path, "Tor", "obfs4proxy.exe") tor_geo_ip_file_path = os.path.join(base_path, "Data", "Tor", "geoip") tor_geo_ipv6_file_path = os.path.join(base_path, "Data", "Tor", "geoip6") elif self.platform == "Darwin": tor_path = shutil.which("tor") obfs4proxy_file_path = shutil.which("obfs4proxy") prefix = os.path.dirname(os.path.dirname(tor_path)) tor_geo_ip_file_path = os.path.join(prefix, "share/tor/geoip") tor_geo_ipv6_file_path = os.path.join(prefix, "share/tor/geoip6") elif self.platform == "BSD": tor_path = "/usr/local/bin/tor" tor_geo_ip_file_path = "/usr/local/share/tor/geoip" tor_geo_ipv6_file_path = "/usr/local/share/tor/geoip6" obfs4proxy_file_path = "/usr/local/bin/obfs4proxy" return ( tor_path, tor_geo_ip_file_path, tor_geo_ipv6_file_path, obfs4proxy_file_path, )
https://github.com/micahflee/onionshare/issues/1237
Traceback (most recent call last): File "/Applications/OnionShare.app/Contents/Resources/app/onionshare/main_window.py", line 228, in open_settings d = SettingsDialog(self.common) File "/Applications/OnionShare.app/Contents/Resources/app/onionshare/settings_dialog.py", line 145, in __init__ ) = self.common.get_tor_paths() File "/Applications/OnionShare.app/Contents/Resources/app_packages/onionshare_cli/common.py", line 98, in get_tor_paths prefix = os.path.dirname(os.path.dirname(tor_path)) File "/Applications/OnionShare.app/Contents/Resources/Support/lib/python3.8/posixpath.py", line 152, in dirname p = os.fspath(p) TypeError: expected str, bytes or os.PathLike object, not NoneType
TypeError
def __init__(self, common): super(SettingsDialog, self).__init__() self.common = common self.common.log("SettingsDialog", "__init__") self.setModal(True) self.setWindowTitle(strings._("gui_settings_window_title")) self.setWindowIcon(QtGui.QIcon(GuiCommon.get_resource_path("images/logo.png"))) self.system = platform.system() # If ONIONSHARE_HIDE_TOR_SETTINGS=1, hide Tor settings in the dialog self.hide_tor_settings = os.environ.get("ONIONSHARE_HIDE_TOR_SETTINGS") == "1" # Automatic updates options # Autoupdate self.autoupdate_checkbox = QtWidgets.QCheckBox() self.autoupdate_checkbox.setCheckState(QtCore.Qt.Unchecked) self.autoupdate_checkbox.setText(strings._("gui_settings_autoupdate_option")) # Last update time self.autoupdate_timestamp = QtWidgets.QLabel() # Check for updates button self.check_for_updates_button = QtWidgets.QPushButton( strings._("gui_settings_autoupdate_check_button") ) self.check_for_updates_button.clicked.connect(self.check_for_updates) # We can't check for updates if not connected to Tor if not self.common.gui.onion.connected_to_tor: self.check_for_updates_button.setEnabled(False) # Autoupdate options layout autoupdate_group_layout = QtWidgets.QVBoxLayout() autoupdate_group_layout.addWidget(self.autoupdate_checkbox) autoupdate_group_layout.addWidget(self.autoupdate_timestamp) autoupdate_group_layout.addWidget(self.check_for_updates_button) autoupdate_group = QtWidgets.QGroupBox(strings._("gui_settings_autoupdate_label")) autoupdate_group.setLayout(autoupdate_group_layout) # Autoupdate is only available for Windows and Mac (Linux updates using package manager) if self.system != "Windows" and self.system != "Darwin": autoupdate_group.hide() # Language settings language_label = QtWidgets.QLabel(strings._("gui_settings_language_label")) self.language_combobox = QtWidgets.QComboBox() # Populate the dropdown with all of OnionShare's available languages language_names_to_locales = { v: k for k, v in self.common.settings.available_locales.items() } language_names = list(language_names_to_locales) language_names.sort() for language_name in language_names: locale = language_names_to_locales[language_name] self.language_combobox.addItem(language_name, locale) language_layout = QtWidgets.QHBoxLayout() language_layout.addWidget(language_label) language_layout.addWidget(self.language_combobox) language_layout.addStretch() # Connection type: either automatic, control port, or socket file # Bundled Tor self.connection_type_bundled_radio = QtWidgets.QRadioButton( strings._("gui_settings_connection_type_bundled_option") ) self.connection_type_bundled_radio.toggled.connect( self.connection_type_bundled_toggled ) # Bundled Tor doesn't work on dev mode in Windows or Mac if (self.system == "Windows" or self.system == "Darwin") and getattr( sys, "onionshare_dev_mode", False ): self.connection_type_bundled_radio.setEnabled(False) # Bridge options for bundled tor # No bridges option radio self.tor_bridges_no_bridges_radio = QtWidgets.QRadioButton( strings._("gui_settings_tor_bridges_no_bridges_radio_option") ) self.tor_bridges_no_bridges_radio.toggled.connect( self.tor_bridges_no_bridges_radio_toggled ) # obfs4 option radio # if the obfs4proxy binary is missing, we can't use obfs4 transports ( self.tor_path, self.tor_geo_ip_file_path, self.tor_geo_ipv6_file_path, self.obfs4proxy_file_path, ) = self.common.gui.get_tor_paths() if not self.obfs4proxy_file_path or not os.path.isfile(self.obfs4proxy_file_path): self.tor_bridges_use_obfs4_radio = QtWidgets.QRadioButton( strings._("gui_settings_tor_bridges_obfs4_radio_option_no_obfs4proxy") ) self.tor_bridges_use_obfs4_radio.setEnabled(False) else: self.tor_bridges_use_obfs4_radio = QtWidgets.QRadioButton( strings._("gui_settings_tor_bridges_obfs4_radio_option") ) self.tor_bridges_use_obfs4_radio.toggled.connect( self.tor_bridges_use_obfs4_radio_toggled ) # meek_lite-azure option radio # if the obfs4proxy binary is missing, we can't use meek_lite-azure transports ( self.tor_path, self.tor_geo_ip_file_path, self.tor_geo_ipv6_file_path, self.obfs4proxy_file_path, ) = self.common.gui.get_tor_paths() if not self.obfs4proxy_file_path or not os.path.isfile(self.obfs4proxy_file_path): self.tor_bridges_use_meek_lite_azure_radio = QtWidgets.QRadioButton( strings._( "gui_settings_tor_bridges_meek_lite_azure_radio_option_no_obfs4proxy" ) ) self.tor_bridges_use_meek_lite_azure_radio.setEnabled(False) else: self.tor_bridges_use_meek_lite_azure_radio = QtWidgets.QRadioButton( strings._("gui_settings_tor_bridges_meek_lite_azure_radio_option") ) self.tor_bridges_use_meek_lite_azure_radio.toggled.connect( self.tor_bridges_use_meek_lite_azure_radio_toggled ) # Custom bridges radio and textbox self.tor_bridges_use_custom_radio = QtWidgets.QRadioButton( strings._("gui_settings_tor_bridges_custom_radio_option") ) self.tor_bridges_use_custom_radio.toggled.connect( self.tor_bridges_use_custom_radio_toggled ) self.tor_bridges_use_custom_label = QtWidgets.QLabel( strings._("gui_settings_tor_bridges_custom_label") ) self.tor_bridges_use_custom_label.setTextInteractionFlags( QtCore.Qt.TextBrowserInteraction ) self.tor_bridges_use_custom_label.setOpenExternalLinks(True) self.tor_bridges_use_custom_textbox = QtWidgets.QPlainTextEdit() self.tor_bridges_use_custom_textbox.setMaximumHeight(200) self.tor_bridges_use_custom_textbox.setPlaceholderText( "[address:port] [identifier]" ) tor_bridges_use_custom_textbox_options_layout = QtWidgets.QVBoxLayout() tor_bridges_use_custom_textbox_options_layout.addWidget( self.tor_bridges_use_custom_label ) tor_bridges_use_custom_textbox_options_layout.addWidget( self.tor_bridges_use_custom_textbox ) self.tor_bridges_use_custom_textbox_options = QtWidgets.QWidget() self.tor_bridges_use_custom_textbox_options.setLayout( tor_bridges_use_custom_textbox_options_layout ) self.tor_bridges_use_custom_textbox_options.hide() # Bridges layout/widget bridges_layout = QtWidgets.QVBoxLayout() bridges_layout.addWidget(self.tor_bridges_no_bridges_radio) bridges_layout.addWidget(self.tor_bridges_use_obfs4_radio) bridges_layout.addWidget(self.tor_bridges_use_meek_lite_azure_radio) bridges_layout.addWidget(self.tor_bridges_use_custom_radio) bridges_layout.addWidget(self.tor_bridges_use_custom_textbox_options) self.bridges = QtWidgets.QWidget() self.bridges.setLayout(bridges_layout) # Automatic self.connection_type_automatic_radio = QtWidgets.QRadioButton( strings._("gui_settings_connection_type_automatic_option") ) self.connection_type_automatic_radio.toggled.connect( self.connection_type_automatic_toggled ) # Control port self.connection_type_control_port_radio = QtWidgets.QRadioButton( strings._("gui_settings_connection_type_control_port_option") ) self.connection_type_control_port_radio.toggled.connect( self.connection_type_control_port_toggled ) connection_type_control_port_extras_label = QtWidgets.QLabel( strings._("gui_settings_control_port_label") ) self.connection_type_control_port_extras_address = QtWidgets.QLineEdit() self.connection_type_control_port_extras_port = QtWidgets.QLineEdit() connection_type_control_port_extras_layout = QtWidgets.QHBoxLayout() connection_type_control_port_extras_layout.addWidget( connection_type_control_port_extras_label ) connection_type_control_port_extras_layout.addWidget( self.connection_type_control_port_extras_address ) connection_type_control_port_extras_layout.addWidget( self.connection_type_control_port_extras_port ) self.connection_type_control_port_extras = QtWidgets.QWidget() self.connection_type_control_port_extras.setLayout( connection_type_control_port_extras_layout ) self.connection_type_control_port_extras.hide() # Socket file self.connection_type_socket_file_radio = QtWidgets.QRadioButton( strings._("gui_settings_connection_type_socket_file_option") ) self.connection_type_socket_file_radio.toggled.connect( self.connection_type_socket_file_toggled ) connection_type_socket_file_extras_label = QtWidgets.QLabel( strings._("gui_settings_socket_file_label") ) self.connection_type_socket_file_extras_path = QtWidgets.QLineEdit() connection_type_socket_file_extras_layout = QtWidgets.QHBoxLayout() connection_type_socket_file_extras_layout.addWidget( connection_type_socket_file_extras_label ) connection_type_socket_file_extras_layout.addWidget( self.connection_type_socket_file_extras_path ) self.connection_type_socket_file_extras = QtWidgets.QWidget() self.connection_type_socket_file_extras.setLayout( connection_type_socket_file_extras_layout ) self.connection_type_socket_file_extras.hide() # Tor SOCKS address and port gui_settings_socks_label = QtWidgets.QLabel(strings._("gui_settings_socks_label")) self.connection_type_socks_address = QtWidgets.QLineEdit() self.connection_type_socks_port = QtWidgets.QLineEdit() connection_type_socks_layout = QtWidgets.QHBoxLayout() connection_type_socks_layout.addWidget(gui_settings_socks_label) connection_type_socks_layout.addWidget(self.connection_type_socks_address) connection_type_socks_layout.addWidget(self.connection_type_socks_port) self.connection_type_socks = QtWidgets.QWidget() self.connection_type_socks.setLayout(connection_type_socks_layout) self.connection_type_socks.hide() # Authentication options # No authentication self.authenticate_no_auth_radio = QtWidgets.QRadioButton( strings._("gui_settings_authenticate_no_auth_option") ) self.authenticate_no_auth_radio.toggled.connect(self.authenticate_no_auth_toggled) # Password self.authenticate_password_radio = QtWidgets.QRadioButton( strings._("gui_settings_authenticate_password_option") ) self.authenticate_password_radio.toggled.connect(self.authenticate_password_toggled) authenticate_password_extras_label = QtWidgets.QLabel( strings._("gui_settings_password_label") ) self.authenticate_password_extras_password = QtWidgets.QLineEdit("") authenticate_password_extras_layout = QtWidgets.QHBoxLayout() authenticate_password_extras_layout.addWidget(authenticate_password_extras_label) authenticate_password_extras_layout.addWidget( self.authenticate_password_extras_password ) self.authenticate_password_extras = QtWidgets.QWidget() self.authenticate_password_extras.setLayout(authenticate_password_extras_layout) self.authenticate_password_extras.hide() # Authentication options layout authenticate_group_layout = QtWidgets.QVBoxLayout() authenticate_group_layout.addWidget(self.authenticate_no_auth_radio) authenticate_group_layout.addWidget(self.authenticate_password_radio) authenticate_group_layout.addWidget(self.authenticate_password_extras) self.authenticate_group = QtWidgets.QGroupBox( strings._("gui_settings_authenticate_label") ) self.authenticate_group.setLayout(authenticate_group_layout) # Put the radios into their own group so they are exclusive connection_type_radio_group_layout = QtWidgets.QVBoxLayout() connection_type_radio_group_layout.addWidget(self.connection_type_bundled_radio) connection_type_radio_group_layout.addWidget(self.connection_type_automatic_radio) connection_type_radio_group_layout.addWidget( self.connection_type_control_port_radio ) connection_type_radio_group_layout.addWidget(self.connection_type_socket_file_radio) connection_type_radio_group = QtWidgets.QGroupBox( strings._("gui_settings_connection_type_label") ) connection_type_radio_group.setLayout(connection_type_radio_group_layout) # The Bridges options are not exclusive (enabling Bridges offers obfs4 or custom bridges) connection_type_bridges_radio_group_layout = QtWidgets.QVBoxLayout() connection_type_bridges_radio_group_layout.addWidget(self.bridges) self.connection_type_bridges_radio_group = QtWidgets.QGroupBox( strings._("gui_settings_tor_bridges") ) self.connection_type_bridges_radio_group.setLayout( connection_type_bridges_radio_group_layout ) self.connection_type_bridges_radio_group.hide() # Test tor settings button self.connection_type_test_button = QtWidgets.QPushButton( strings._("gui_settings_connection_type_test_button") ) self.connection_type_test_button.clicked.connect(self.test_tor_clicked) connection_type_test_button_layout = QtWidgets.QHBoxLayout() connection_type_test_button_layout.addWidget(self.connection_type_test_button) connection_type_test_button_layout.addStretch() # Connection type layout connection_type_layout = QtWidgets.QVBoxLayout() connection_type_layout.addWidget(self.connection_type_control_port_extras) connection_type_layout.addWidget(self.connection_type_socket_file_extras) connection_type_layout.addWidget(self.connection_type_socks) connection_type_layout.addWidget(self.authenticate_group) connection_type_layout.addWidget(self.connection_type_bridges_radio_group) connection_type_layout.addLayout(connection_type_test_button_layout) # Buttons self.save_button = QtWidgets.QPushButton(strings._("gui_settings_button_save")) self.save_button.clicked.connect(self.save_clicked) self.cancel_button = QtWidgets.QPushButton(strings._("gui_settings_button_cancel")) self.cancel_button.clicked.connect(self.cancel_clicked) version_label = QtWidgets.QLabel(f"OnionShare {self.common.version}") version_label.setStyleSheet(self.common.gui.css["settings_version"]) self.help_button = QtWidgets.QPushButton(strings._("gui_settings_button_help")) self.help_button.clicked.connect(self.help_clicked) buttons_layout = QtWidgets.QHBoxLayout() buttons_layout.addWidget(version_label) buttons_layout.addWidget(self.help_button) buttons_layout.addStretch() buttons_layout.addWidget(self.save_button) buttons_layout.addWidget(self.cancel_button) # Tor network connection status self.tor_status = QtWidgets.QLabel() self.tor_status.setStyleSheet(self.common.gui.css["settings_tor_status"]) self.tor_status.hide() # Layout tor_layout = QtWidgets.QVBoxLayout() tor_layout.addWidget(connection_type_radio_group) tor_layout.addLayout(connection_type_layout) tor_layout.addWidget(self.tor_status) tor_layout.addStretch() layout = QtWidgets.QVBoxLayout() if not self.hide_tor_settings: layout.addLayout(tor_layout) layout.addSpacing(20) layout.addWidget(autoupdate_group) if autoupdate_group.isVisible(): layout.addSpacing(20) layout.addLayout(language_layout) layout.addSpacing(20) layout.addStretch() layout.addLayout(buttons_layout) self.setLayout(layout) self.cancel_button.setFocus() self.reload_settings()
def __init__(self, common): super(SettingsDialog, self).__init__() self.common = common self.common.log("SettingsDialog", "__init__") self.setModal(True) self.setWindowTitle(strings._("gui_settings_window_title")) self.setWindowIcon(QtGui.QIcon(GuiCommon.get_resource_path("images/logo.png"))) self.system = platform.system() # If ONIONSHARE_HIDE_TOR_SETTINGS=1, hide Tor settings in the dialog self.hide_tor_settings = os.environ.get("ONIONSHARE_HIDE_TOR_SETTINGS") == "1" # Automatic updates options # Autoupdate self.autoupdate_checkbox = QtWidgets.QCheckBox() self.autoupdate_checkbox.setCheckState(QtCore.Qt.Unchecked) self.autoupdate_checkbox.setText(strings._("gui_settings_autoupdate_option")) # Last update time self.autoupdate_timestamp = QtWidgets.QLabel() # Check for updates button self.check_for_updates_button = QtWidgets.QPushButton( strings._("gui_settings_autoupdate_check_button") ) self.check_for_updates_button.clicked.connect(self.check_for_updates) # We can't check for updates if not connected to Tor if not self.common.gui.onion.connected_to_tor: self.check_for_updates_button.setEnabled(False) # Autoupdate options layout autoupdate_group_layout = QtWidgets.QVBoxLayout() autoupdate_group_layout.addWidget(self.autoupdate_checkbox) autoupdate_group_layout.addWidget(self.autoupdate_timestamp) autoupdate_group_layout.addWidget(self.check_for_updates_button) autoupdate_group = QtWidgets.QGroupBox(strings._("gui_settings_autoupdate_label")) autoupdate_group.setLayout(autoupdate_group_layout) # Autoupdate is only available for Windows and Mac (Linux updates using package manager) if self.system != "Windows" and self.system != "Darwin": autoupdate_group.hide() # Language settings language_label = QtWidgets.QLabel(strings._("gui_settings_language_label")) self.language_combobox = QtWidgets.QComboBox() # Populate the dropdown with all of OnionShare's available languages language_names_to_locales = { v: k for k, v in self.common.settings.available_locales.items() } language_names = list(language_names_to_locales) language_names.sort() for language_name in language_names: locale = language_names_to_locales[language_name] self.language_combobox.addItem(language_name, locale) language_layout = QtWidgets.QHBoxLayout() language_layout.addWidget(language_label) language_layout.addWidget(self.language_combobox) language_layout.addStretch() # Connection type: either automatic, control port, or socket file # Bundled Tor self.connection_type_bundled_radio = QtWidgets.QRadioButton( strings._("gui_settings_connection_type_bundled_option") ) self.connection_type_bundled_radio.toggled.connect( self.connection_type_bundled_toggled ) # Bundled Tor doesn't work on dev mode in Windows or Mac if (self.system == "Windows" or self.system == "Darwin") and getattr( sys, "onionshare_dev_mode", False ): self.connection_type_bundled_radio.setEnabled(False) # Bridge options for bundled tor # No bridges option radio self.tor_bridges_no_bridges_radio = QtWidgets.QRadioButton( strings._("gui_settings_tor_bridges_no_bridges_radio_option") ) self.tor_bridges_no_bridges_radio.toggled.connect( self.tor_bridges_no_bridges_radio_toggled ) # obfs4 option radio # if the obfs4proxy binary is missing, we can't use obfs4 transports ( self.tor_path, self.tor_geo_ip_file_path, self.tor_geo_ipv6_file_path, self.obfs4proxy_file_path, ) = self.common.get_tor_paths() if not self.obfs4proxy_file_path or not os.path.isfile(self.obfs4proxy_file_path): self.tor_bridges_use_obfs4_radio = QtWidgets.QRadioButton( strings._("gui_settings_tor_bridges_obfs4_radio_option_no_obfs4proxy") ) self.tor_bridges_use_obfs4_radio.setEnabled(False) else: self.tor_bridges_use_obfs4_radio = QtWidgets.QRadioButton( strings._("gui_settings_tor_bridges_obfs4_radio_option") ) self.tor_bridges_use_obfs4_radio.toggled.connect( self.tor_bridges_use_obfs4_radio_toggled ) # meek_lite-azure option radio # if the obfs4proxy binary is missing, we can't use meek_lite-azure transports ( self.tor_path, self.tor_geo_ip_file_path, self.tor_geo_ipv6_file_path, self.obfs4proxy_file_path, ) = self.common.get_tor_paths() if not self.obfs4proxy_file_path or not os.path.isfile(self.obfs4proxy_file_path): self.tor_bridges_use_meek_lite_azure_radio = QtWidgets.QRadioButton( strings._( "gui_settings_tor_bridges_meek_lite_azure_radio_option_no_obfs4proxy" ) ) self.tor_bridges_use_meek_lite_azure_radio.setEnabled(False) else: self.tor_bridges_use_meek_lite_azure_radio = QtWidgets.QRadioButton( strings._("gui_settings_tor_bridges_meek_lite_azure_radio_option") ) self.tor_bridges_use_meek_lite_azure_radio.toggled.connect( self.tor_bridges_use_meek_lite_azure_radio_toggled ) # Custom bridges radio and textbox self.tor_bridges_use_custom_radio = QtWidgets.QRadioButton( strings._("gui_settings_tor_bridges_custom_radio_option") ) self.tor_bridges_use_custom_radio.toggled.connect( self.tor_bridges_use_custom_radio_toggled ) self.tor_bridges_use_custom_label = QtWidgets.QLabel( strings._("gui_settings_tor_bridges_custom_label") ) self.tor_bridges_use_custom_label.setTextInteractionFlags( QtCore.Qt.TextBrowserInteraction ) self.tor_bridges_use_custom_label.setOpenExternalLinks(True) self.tor_bridges_use_custom_textbox = QtWidgets.QPlainTextEdit() self.tor_bridges_use_custom_textbox.setMaximumHeight(200) self.tor_bridges_use_custom_textbox.setPlaceholderText( "[address:port] [identifier]" ) tor_bridges_use_custom_textbox_options_layout = QtWidgets.QVBoxLayout() tor_bridges_use_custom_textbox_options_layout.addWidget( self.tor_bridges_use_custom_label ) tor_bridges_use_custom_textbox_options_layout.addWidget( self.tor_bridges_use_custom_textbox ) self.tor_bridges_use_custom_textbox_options = QtWidgets.QWidget() self.tor_bridges_use_custom_textbox_options.setLayout( tor_bridges_use_custom_textbox_options_layout ) self.tor_bridges_use_custom_textbox_options.hide() # Bridges layout/widget bridges_layout = QtWidgets.QVBoxLayout() bridges_layout.addWidget(self.tor_bridges_no_bridges_radio) bridges_layout.addWidget(self.tor_bridges_use_obfs4_radio) bridges_layout.addWidget(self.tor_bridges_use_meek_lite_azure_radio) bridges_layout.addWidget(self.tor_bridges_use_custom_radio) bridges_layout.addWidget(self.tor_bridges_use_custom_textbox_options) self.bridges = QtWidgets.QWidget() self.bridges.setLayout(bridges_layout) # Automatic self.connection_type_automatic_radio = QtWidgets.QRadioButton( strings._("gui_settings_connection_type_automatic_option") ) self.connection_type_automatic_radio.toggled.connect( self.connection_type_automatic_toggled ) # Control port self.connection_type_control_port_radio = QtWidgets.QRadioButton( strings._("gui_settings_connection_type_control_port_option") ) self.connection_type_control_port_radio.toggled.connect( self.connection_type_control_port_toggled ) connection_type_control_port_extras_label = QtWidgets.QLabel( strings._("gui_settings_control_port_label") ) self.connection_type_control_port_extras_address = QtWidgets.QLineEdit() self.connection_type_control_port_extras_port = QtWidgets.QLineEdit() connection_type_control_port_extras_layout = QtWidgets.QHBoxLayout() connection_type_control_port_extras_layout.addWidget( connection_type_control_port_extras_label ) connection_type_control_port_extras_layout.addWidget( self.connection_type_control_port_extras_address ) connection_type_control_port_extras_layout.addWidget( self.connection_type_control_port_extras_port ) self.connection_type_control_port_extras = QtWidgets.QWidget() self.connection_type_control_port_extras.setLayout( connection_type_control_port_extras_layout ) self.connection_type_control_port_extras.hide() # Socket file self.connection_type_socket_file_radio = QtWidgets.QRadioButton( strings._("gui_settings_connection_type_socket_file_option") ) self.connection_type_socket_file_radio.toggled.connect( self.connection_type_socket_file_toggled ) connection_type_socket_file_extras_label = QtWidgets.QLabel( strings._("gui_settings_socket_file_label") ) self.connection_type_socket_file_extras_path = QtWidgets.QLineEdit() connection_type_socket_file_extras_layout = QtWidgets.QHBoxLayout() connection_type_socket_file_extras_layout.addWidget( connection_type_socket_file_extras_label ) connection_type_socket_file_extras_layout.addWidget( self.connection_type_socket_file_extras_path ) self.connection_type_socket_file_extras = QtWidgets.QWidget() self.connection_type_socket_file_extras.setLayout( connection_type_socket_file_extras_layout ) self.connection_type_socket_file_extras.hide() # Tor SOCKS address and port gui_settings_socks_label = QtWidgets.QLabel(strings._("gui_settings_socks_label")) self.connection_type_socks_address = QtWidgets.QLineEdit() self.connection_type_socks_port = QtWidgets.QLineEdit() connection_type_socks_layout = QtWidgets.QHBoxLayout() connection_type_socks_layout.addWidget(gui_settings_socks_label) connection_type_socks_layout.addWidget(self.connection_type_socks_address) connection_type_socks_layout.addWidget(self.connection_type_socks_port) self.connection_type_socks = QtWidgets.QWidget() self.connection_type_socks.setLayout(connection_type_socks_layout) self.connection_type_socks.hide() # Authentication options # No authentication self.authenticate_no_auth_radio = QtWidgets.QRadioButton( strings._("gui_settings_authenticate_no_auth_option") ) self.authenticate_no_auth_radio.toggled.connect(self.authenticate_no_auth_toggled) # Password self.authenticate_password_radio = QtWidgets.QRadioButton( strings._("gui_settings_authenticate_password_option") ) self.authenticate_password_radio.toggled.connect(self.authenticate_password_toggled) authenticate_password_extras_label = QtWidgets.QLabel( strings._("gui_settings_password_label") ) self.authenticate_password_extras_password = QtWidgets.QLineEdit("") authenticate_password_extras_layout = QtWidgets.QHBoxLayout() authenticate_password_extras_layout.addWidget(authenticate_password_extras_label) authenticate_password_extras_layout.addWidget( self.authenticate_password_extras_password ) self.authenticate_password_extras = QtWidgets.QWidget() self.authenticate_password_extras.setLayout(authenticate_password_extras_layout) self.authenticate_password_extras.hide() # Authentication options layout authenticate_group_layout = QtWidgets.QVBoxLayout() authenticate_group_layout.addWidget(self.authenticate_no_auth_radio) authenticate_group_layout.addWidget(self.authenticate_password_radio) authenticate_group_layout.addWidget(self.authenticate_password_extras) self.authenticate_group = QtWidgets.QGroupBox( strings._("gui_settings_authenticate_label") ) self.authenticate_group.setLayout(authenticate_group_layout) # Put the radios into their own group so they are exclusive connection_type_radio_group_layout = QtWidgets.QVBoxLayout() connection_type_radio_group_layout.addWidget(self.connection_type_bundled_radio) connection_type_radio_group_layout.addWidget(self.connection_type_automatic_radio) connection_type_radio_group_layout.addWidget( self.connection_type_control_port_radio ) connection_type_radio_group_layout.addWidget(self.connection_type_socket_file_radio) connection_type_radio_group = QtWidgets.QGroupBox( strings._("gui_settings_connection_type_label") ) connection_type_radio_group.setLayout(connection_type_radio_group_layout) # The Bridges options are not exclusive (enabling Bridges offers obfs4 or custom bridges) connection_type_bridges_radio_group_layout = QtWidgets.QVBoxLayout() connection_type_bridges_radio_group_layout.addWidget(self.bridges) self.connection_type_bridges_radio_group = QtWidgets.QGroupBox( strings._("gui_settings_tor_bridges") ) self.connection_type_bridges_radio_group.setLayout( connection_type_bridges_radio_group_layout ) self.connection_type_bridges_radio_group.hide() # Test tor settings button self.connection_type_test_button = QtWidgets.QPushButton( strings._("gui_settings_connection_type_test_button") ) self.connection_type_test_button.clicked.connect(self.test_tor_clicked) connection_type_test_button_layout = QtWidgets.QHBoxLayout() connection_type_test_button_layout.addWidget(self.connection_type_test_button) connection_type_test_button_layout.addStretch() # Connection type layout connection_type_layout = QtWidgets.QVBoxLayout() connection_type_layout.addWidget(self.connection_type_control_port_extras) connection_type_layout.addWidget(self.connection_type_socket_file_extras) connection_type_layout.addWidget(self.connection_type_socks) connection_type_layout.addWidget(self.authenticate_group) connection_type_layout.addWidget(self.connection_type_bridges_radio_group) connection_type_layout.addLayout(connection_type_test_button_layout) # Buttons self.save_button = QtWidgets.QPushButton(strings._("gui_settings_button_save")) self.save_button.clicked.connect(self.save_clicked) self.cancel_button = QtWidgets.QPushButton(strings._("gui_settings_button_cancel")) self.cancel_button.clicked.connect(self.cancel_clicked) version_label = QtWidgets.QLabel(f"OnionShare {self.common.version}") version_label.setStyleSheet(self.common.gui.css["settings_version"]) self.help_button = QtWidgets.QPushButton(strings._("gui_settings_button_help")) self.help_button.clicked.connect(self.help_clicked) buttons_layout = QtWidgets.QHBoxLayout() buttons_layout.addWidget(version_label) buttons_layout.addWidget(self.help_button) buttons_layout.addStretch() buttons_layout.addWidget(self.save_button) buttons_layout.addWidget(self.cancel_button) # Tor network connection status self.tor_status = QtWidgets.QLabel() self.tor_status.setStyleSheet(self.common.gui.css["settings_tor_status"]) self.tor_status.hide() # Layout tor_layout = QtWidgets.QVBoxLayout() tor_layout.addWidget(connection_type_radio_group) tor_layout.addLayout(connection_type_layout) tor_layout.addWidget(self.tor_status) tor_layout.addStretch() layout = QtWidgets.QVBoxLayout() if not self.hide_tor_settings: layout.addLayout(tor_layout) layout.addSpacing(20) layout.addWidget(autoupdate_group) if autoupdate_group.isVisible(): layout.addSpacing(20) layout.addLayout(language_layout) layout.addSpacing(20) layout.addStretch() layout.addLayout(buttons_layout) self.setLayout(layout) self.cancel_button.setFocus() self.reload_settings()
https://github.com/micahflee/onionshare/issues/1237
Traceback (most recent call last): File "/Applications/OnionShare.app/Contents/Resources/app/onionshare/main_window.py", line 228, in open_settings d = SettingsDialog(self.common) File "/Applications/OnionShare.app/Contents/Resources/app/onionshare/settings_dialog.py", line 145, in __init__ ) = self.common.get_tor_paths() File "/Applications/OnionShare.app/Contents/Resources/app_packages/onionshare_cli/common.py", line 98, in get_tor_paths prefix = os.path.dirname(os.path.dirname(tor_path)) File "/Applications/OnionShare.app/Contents/Resources/Support/lib/python3.8/posixpath.py", line 152, in dirname p = os.fspath(p) TypeError: expected str, bytes or os.PathLike object, not NoneType
TypeError
def __init__( self, common, onion, qtapp, app, filenames, config=False, local_only=False ): super(OnionShareGui, self).__init__() self.common = common self.common.log("OnionShareGui", "__init__") self.setMinimumWidth(820) self.setMinimumHeight(660) self.onion = onion self.qtapp = qtapp self.app = app self.local_only = local_only self.mode = self.MODE_SHARE self.setWindowTitle("OnionShare") self.setWindowIcon(QtGui.QIcon(self.common.get_resource_path("images/logo.png"))) # Load settings, if a custom config was passed in self.config = config if self.config: self.common.load_settings(self.config) else: self.common.load_settings() strings.load_strings(self.common) # System tray menu = QtWidgets.QMenu() self.settings_action = menu.addAction(strings._("gui_settings_window_title")) self.settings_action.triggered.connect(self.open_settings) self.help_action = menu.addAction(strings._("gui_settings_button_help")) self.help_action.triggered.connect(lambda: SettingsDialog.help_clicked(self)) exit_action = menu.addAction(strings._("systray_menu_exit")) exit_action.triggered.connect(self.close) self.system_tray = QtWidgets.QSystemTrayIcon(self) # The convention is Mac systray icons are always grayscale if self.common.platform == "Darwin": self.system_tray.setIcon( QtGui.QIcon(self.common.get_resource_path("images/logo_grayscale.png")) ) else: self.system_tray.setIcon( QtGui.QIcon(self.common.get_resource_path("images/logo.png")) ) self.system_tray.setContextMenu(menu) self.system_tray.show() # Mode switcher, to switch between share files and receive files self.share_mode_button = QtWidgets.QPushButton(strings._("gui_mode_share_button")) self.share_mode_button.setFixedHeight(50) self.share_mode_button.clicked.connect(self.share_mode_clicked) self.receive_mode_button = QtWidgets.QPushButton( strings._("gui_mode_receive_button") ) self.receive_mode_button.setFixedHeight(50) self.receive_mode_button.clicked.connect(self.receive_mode_clicked) self.settings_button = QtWidgets.QPushButton() self.settings_button.setDefault(False) self.settings_button.setFixedWidth(40) self.settings_button.setFixedHeight(50) self.settings_button.setIcon( QtGui.QIcon(self.common.get_resource_path("images/settings.png")) ) self.settings_button.clicked.connect(self.open_settings) self.settings_button.setStyleSheet(self.common.css["settings_button"]) mode_switcher_layout = QtWidgets.QHBoxLayout() mode_switcher_layout.setSpacing(0) mode_switcher_layout.addWidget(self.share_mode_button) mode_switcher_layout.addWidget(self.receive_mode_button) mode_switcher_layout.addWidget(self.settings_button) # Server status indicator on the status bar self.server_status_image_stopped = QtGui.QImage( self.common.get_resource_path("images/server_stopped.png") ) self.server_status_image_working = QtGui.QImage( self.common.get_resource_path("images/server_working.png") ) self.server_status_image_started = QtGui.QImage( self.common.get_resource_path("images/server_started.png") ) self.server_status_image_label = QtWidgets.QLabel() self.server_status_image_label.setFixedWidth(20) self.server_status_label = QtWidgets.QLabel("") self.server_status_label.setStyleSheet( self.common.css["server_status_indicator_label"] ) server_status_indicator_layout = QtWidgets.QHBoxLayout() server_status_indicator_layout.addWidget(self.server_status_image_label) server_status_indicator_layout.addWidget(self.server_status_label) self.server_status_indicator = QtWidgets.QWidget() self.server_status_indicator.setLayout(server_status_indicator_layout) # Status bar self.status_bar = QtWidgets.QStatusBar() self.status_bar.setSizeGripEnabled(False) self.status_bar.setStyleSheet(self.common.css["status_bar"]) self.status_bar.addPermanentWidget(self.server_status_indicator) self.setStatusBar(self.status_bar) # Share mode self.share_mode = ShareMode( self.common, qtapp, app, self.status_bar, self.server_status_label, self.system_tray, filenames, self.local_only, ) self.share_mode.init() self.share_mode.server_status.server_started.connect( self.update_server_status_indicator ) self.share_mode.server_status.server_stopped.connect( self.update_server_status_indicator ) self.share_mode.start_server_finished.connect(self.update_server_status_indicator) self.share_mode.stop_server_finished.connect(self.update_server_status_indicator) self.share_mode.stop_server_finished.connect(self.stop_server_finished) self.share_mode.start_server_finished.connect(self.clear_message) self.share_mode.server_status.button_clicked.connect(self.clear_message) self.share_mode.server_status.url_copied.connect(self.copy_url) self.share_mode.server_status.hidservauth_copied.connect(self.copy_hidservauth) self.share_mode.set_server_active.connect(self.set_server_active) # Receive mode self.receive_mode = ReceiveMode( self.common, qtapp, app, self.status_bar, self.server_status_label, self.system_tray, None, self.local_only, ) self.receive_mode.init() self.receive_mode.server_status.server_started.connect( self.update_server_status_indicator ) self.receive_mode.server_status.server_stopped.connect( self.update_server_status_indicator ) self.receive_mode.start_server_finished.connect(self.update_server_status_indicator) self.receive_mode.stop_server_finished.connect(self.update_server_status_indicator) self.receive_mode.stop_server_finished.connect(self.stop_server_finished) self.receive_mode.start_server_finished.connect(self.clear_message) self.receive_mode.server_status.button_clicked.connect(self.clear_message) self.receive_mode.server_status.url_copied.connect(self.copy_url) self.receive_mode.server_status.hidservauth_copied.connect(self.copy_hidservauth) self.receive_mode.set_server_active.connect(self.set_server_active) self.update_mode_switcher() self.update_server_status_indicator() # Layouts contents_layout = QtWidgets.QVBoxLayout() contents_layout.setContentsMargins(10, 0, 10, 0) contents_layout.addWidget(self.receive_mode) contents_layout.addWidget(self.share_mode) layout = QtWidgets.QVBoxLayout() layout.setContentsMargins(0, 0, 0, 0) layout.addLayout(mode_switcher_layout) layout.addLayout(contents_layout) central_widget = QtWidgets.QWidget() central_widget.setLayout(layout) self.setCentralWidget(central_widget) self.show() # The server isn't active yet self.set_server_active(False) # Create the timer self.timer = QtCore.QTimer() self.timer.timeout.connect(self.timer_callback) # Start the "Connecting to Tor" dialog, which calls onion.connect() tor_con = TorConnectionDialog(self.common, self.qtapp, self.onion) tor_con.canceled.connect(self._tor_connection_canceled) tor_con.open_settings.connect(self._tor_connection_open_settings) if not self.local_only: tor_con.start() # Start the timer self.timer.start(500) # After connecting to Tor, check for updates self.check_for_updates()
def __init__( self, common, onion, qtapp, app, filenames, config=False, local_only=False ): super(OnionShareGui, self).__init__() self.common = common self.common.log("OnionShareGui", "__init__") self.setMinimumWidth(820) self.setMinimumHeight(660) self.onion = onion self.qtapp = qtapp self.app = app self.local_only = local_only self.mode = self.MODE_SHARE self.setWindowTitle("OnionShare") self.setWindowIcon(QtGui.QIcon(self.common.get_resource_path("images/logo.png"))) # Load settings, if a custom config was passed in self.config = config if self.config: self.common.load_settings(self.config) else: self.common.load_settings() strings.load_strings(self.common) # System tray menu = QtWidgets.QMenu() self.settings_action = menu.addAction(strings._("gui_settings_window_title")) self.settings_action.triggered.connect(self.open_settings) help_action = menu.addAction(strings._("gui_settings_button_help")) help_action.triggered.connect(SettingsDialog.help_clicked) exit_action = menu.addAction(strings._("systray_menu_exit")) exit_action.triggered.connect(self.close) self.system_tray = QtWidgets.QSystemTrayIcon(self) # The convention is Mac systray icons are always grayscale if self.common.platform == "Darwin": self.system_tray.setIcon( QtGui.QIcon(self.common.get_resource_path("images/logo_grayscale.png")) ) else: self.system_tray.setIcon( QtGui.QIcon(self.common.get_resource_path("images/logo.png")) ) self.system_tray.setContextMenu(menu) self.system_tray.show() # Mode switcher, to switch between share files and receive files self.share_mode_button = QtWidgets.QPushButton(strings._("gui_mode_share_button")) self.share_mode_button.setFixedHeight(50) self.share_mode_button.clicked.connect(self.share_mode_clicked) self.receive_mode_button = QtWidgets.QPushButton( strings._("gui_mode_receive_button") ) self.receive_mode_button.setFixedHeight(50) self.receive_mode_button.clicked.connect(self.receive_mode_clicked) self.settings_button = QtWidgets.QPushButton() self.settings_button.setDefault(False) self.settings_button.setFixedWidth(40) self.settings_button.setFixedHeight(50) self.settings_button.setIcon( QtGui.QIcon(self.common.get_resource_path("images/settings.png")) ) self.settings_button.clicked.connect(self.open_settings) self.settings_button.setStyleSheet(self.common.css["settings_button"]) mode_switcher_layout = QtWidgets.QHBoxLayout() mode_switcher_layout.setSpacing(0) mode_switcher_layout.addWidget(self.share_mode_button) mode_switcher_layout.addWidget(self.receive_mode_button) mode_switcher_layout.addWidget(self.settings_button) # Server status indicator on the status bar self.server_status_image_stopped = QtGui.QImage( self.common.get_resource_path("images/server_stopped.png") ) self.server_status_image_working = QtGui.QImage( self.common.get_resource_path("images/server_working.png") ) self.server_status_image_started = QtGui.QImage( self.common.get_resource_path("images/server_started.png") ) self.server_status_image_label = QtWidgets.QLabel() self.server_status_image_label.setFixedWidth(20) self.server_status_label = QtWidgets.QLabel("") self.server_status_label.setStyleSheet( self.common.css["server_status_indicator_label"] ) server_status_indicator_layout = QtWidgets.QHBoxLayout() server_status_indicator_layout.addWidget(self.server_status_image_label) server_status_indicator_layout.addWidget(self.server_status_label) self.server_status_indicator = QtWidgets.QWidget() self.server_status_indicator.setLayout(server_status_indicator_layout) # Status bar self.status_bar = QtWidgets.QStatusBar() self.status_bar.setSizeGripEnabled(False) self.status_bar.setStyleSheet(self.common.css["status_bar"]) self.status_bar.addPermanentWidget(self.server_status_indicator) self.setStatusBar(self.status_bar) # Share mode self.share_mode = ShareMode( self.common, qtapp, app, self.status_bar, self.server_status_label, self.system_tray, filenames, self.local_only, ) self.share_mode.init() self.share_mode.server_status.server_started.connect( self.update_server_status_indicator ) self.share_mode.server_status.server_stopped.connect( self.update_server_status_indicator ) self.share_mode.start_server_finished.connect(self.update_server_status_indicator) self.share_mode.stop_server_finished.connect(self.update_server_status_indicator) self.share_mode.stop_server_finished.connect(self.stop_server_finished) self.share_mode.start_server_finished.connect(self.clear_message) self.share_mode.server_status.button_clicked.connect(self.clear_message) self.share_mode.server_status.url_copied.connect(self.copy_url) self.share_mode.server_status.hidservauth_copied.connect(self.copy_hidservauth) self.share_mode.set_server_active.connect(self.set_server_active) # Receive mode self.receive_mode = ReceiveMode( self.common, qtapp, app, self.status_bar, self.server_status_label, self.system_tray, None, self.local_only, ) self.receive_mode.init() self.receive_mode.server_status.server_started.connect( self.update_server_status_indicator ) self.receive_mode.server_status.server_stopped.connect( self.update_server_status_indicator ) self.receive_mode.start_server_finished.connect(self.update_server_status_indicator) self.receive_mode.stop_server_finished.connect(self.update_server_status_indicator) self.receive_mode.stop_server_finished.connect(self.stop_server_finished) self.receive_mode.start_server_finished.connect(self.clear_message) self.receive_mode.server_status.button_clicked.connect(self.clear_message) self.receive_mode.server_status.url_copied.connect(self.copy_url) self.receive_mode.server_status.hidservauth_copied.connect(self.copy_hidservauth) self.receive_mode.set_server_active.connect(self.set_server_active) self.update_mode_switcher() self.update_server_status_indicator() # Layouts contents_layout = QtWidgets.QVBoxLayout() contents_layout.setContentsMargins(10, 0, 10, 0) contents_layout.addWidget(self.receive_mode) contents_layout.addWidget(self.share_mode) layout = QtWidgets.QVBoxLayout() layout.setContentsMargins(0, 0, 0, 0) layout.addLayout(mode_switcher_layout) layout.addLayout(contents_layout) central_widget = QtWidgets.QWidget() central_widget.setLayout(layout) self.setCentralWidget(central_widget) self.show() # The server isn't active yet self.set_server_active(False) # Create the timer self.timer = QtCore.QTimer() self.timer.timeout.connect(self.timer_callback) # Start the "Connecting to Tor" dialog, which calls onion.connect() tor_con = TorConnectionDialog(self.common, self.qtapp, self.onion) tor_con.canceled.connect(self._tor_connection_canceled) tor_con.open_settings.connect(self._tor_connection_open_settings) if not self.local_only: tor_con.start() # Start the timer self.timer.start(500) # After connecting to Tor, check for updates self.check_for_updates()
https://github.com/micahflee/onionshare/issues/912
Traceback (most recent call last): File "onionshare_gui/settings_dialog.py", line 918, in help_clicked AttributeError: 'bool' object has no attribute 'common' Abort trap: 6
AttributeError
def define_routes(self): """ The web app routes for receiving files """ def index_logic(): self.web.add_request(self.web.REQUEST_LOAD, request.path) if self.common.settings.get("public_mode"): upload_action = "/upload" else: upload_action = "/{}/upload".format(self.web.slug) r = make_response(render_template("receive.html", upload_action=upload_action)) return self.web.add_security_headers(r) @self.web.app.route("/<slug_candidate>") def index(slug_candidate): if not self.can_upload: return self.web.error403() self.web.check_slug_candidate(slug_candidate) return index_logic() @self.web.app.route("/") def index_public(): if not self.can_upload: return self.web.error403() if not self.common.settings.get("public_mode"): return self.web.error404() return index_logic() def upload_logic(slug_candidate=""): """ Upload files. """ # Figure out what the receive mode dir should be now = datetime.now() date_dir = now.strftime("%Y-%m-%d") time_dir = now.strftime("%H.%M.%S") receive_mode_dir = os.path.join( self.common.settings.get("data_dir"), date_dir, time_dir ) valid = True try: os.makedirs(receive_mode_dir, 0o700, exist_ok=True) except PermissionError: self.web.add_request( self.web.REQUEST_ERROR_DATA_DIR_CANNOT_CREATE, request.path, {"receive_mode_dir": receive_mode_dir}, ) print(strings._("error_cannot_create_data_dir").format(receive_mode_dir)) valid = False if not valid: flash("Error uploading, please inform the OnionShare user", "error") if self.common.settings.get("public_mode"): return redirect("/") else: return redirect("/{}".format(slug_candidate)) files = request.files.getlist("file[]") filenames = [] print("") for f in files: if f.filename != "": # Automatically rename the file, if a file of the same name already exists filename = secure_filename(f.filename) filenames.append(filename) local_path = os.path.join(receive_mode_dir, filename) if os.path.exists(local_path): if "." in filename: # Add "-i", e.g. change "foo.txt" to "foo-2.txt" parts = filename.split(".") name = parts[:-1] ext = parts[-1] i = 2 valid = False while not valid: new_filename = "{}-{}.{}".format(".".join(name), i, ext) local_path = os.path.join(receive_mode_dir, new_filename) if os.path.exists(local_path): i += 1 else: valid = True else: # If no extension, just add "-i", e.g. change "foo" to "foo-2" i = 2 valid = False while not valid: new_filename = "{}-{}".format(filename, i) local_path = os.path.join(receive_mode_dir, new_filename) if os.path.exists(local_path): i += 1 else: valid = True basename = os.path.basename(local_path) if f.filename != basename: # Tell the GUI that the file has changed names self.web.add_request( self.web.REQUEST_UPLOAD_FILE_RENAMED, request.path, { "id": request.upload_id, "old_filename": f.filename, "new_filename": basename, }, ) # Tell the GUI the receive mode directory for this file self.web.add_request( self.web.REQUEST_UPLOAD_SET_DIR, request.path, { "id": request.upload_id, "filename": basename, "dir": receive_mode_dir, }, ) # Make sure receive mode dir exists before writing file valid = True try: os.makedirs(receive_mode_dir, 0o700, exist_ok=True) except PermissionError: self.web.add_request( self.web.REQUEST_ERROR_DATA_DIR_CANNOT_CREATE, request.path, {"receive_mode_dir": receive_mode_dir}, ) print( strings._("error_cannot_create_data_dir").format( receive_mode_dir ) ) valid = False if not valid: flash("Error uploading, please inform the OnionShare user", "error") if self.common.settings.get("public_mode"): return redirect("/") else: return redirect("/{}".format(slug_candidate)) self.common.log( "ReceiveModeWeb", "define_routes", "/upload, uploaded {}, saving to {}".format(f.filename, local_path), ) print(strings._("receive_mode_received_file").format(local_path)) f.save(local_path) # Note that flash strings are on English, and not translated, on purpose, # to avoid leaking the locale of the OnionShare user if len(filenames) == 0: flash("No files uploaded", "info") else: for filename in filenames: flash("Sent {}".format(filename), "info") if self.can_upload: if self.common.settings.get("public_mode"): path = "/" else: path = "/{}".format(slug_candidate) return redirect("{}".format(path)) else: # It was the last upload and the timer ran out if self.common.settings.get("public_mode"): return thankyou_logic(slug_candidate) else: return thankyou_logic() def thankyou_logic(slug_candidate=""): r = make_response(render_template("thankyou.html")) return self.web.add_security_headers(r) @self.web.app.route("/<slug_candidate>/upload", methods=["POST"]) def upload(slug_candidate): if not self.can_upload: return self.web.error403() self.web.check_slug_candidate(slug_candidate) return upload_logic(slug_candidate) @self.web.app.route("/upload", methods=["POST"]) def upload_public(): if not self.can_upload: return self.web.error403() if not self.common.settings.get("public_mode"): return self.web.error404() return upload_logic()
def define_routes(self): """ The web app routes for receiving files """ def index_logic(): self.web.add_request(self.web.REQUEST_LOAD, request.path) if self.common.settings.get("public_mode"): upload_action = "/upload" else: upload_action = "/{}/upload".format(self.web.slug) r = make_response(render_template("receive.html", upload_action=upload_action)) return self.web.add_security_headers(r) @self.web.app.route("/<slug_candidate>") def index(slug_candidate): if not self.can_upload: return self.web.error403() self.web.check_slug_candidate(slug_candidate) return index_logic() @self.web.app.route("/") def index_public(): if not self.can_upload: return self.web.error403() if not self.common.settings.get("public_mode"): return self.web.error404() return index_logic() def upload_logic(slug_candidate=""): """ Upload files. """ # Make sure the receive mode dir exists now = datetime.now() date_dir = now.strftime("%Y-%m-%d") time_dir = now.strftime("%H.%M.%S") receive_mode_dir = os.path.join( self.common.settings.get("data_dir"), date_dir, time_dir ) valid = True try: os.makedirs(receive_mode_dir, 0o700, exist_ok=True) except PermissionError: self.web.add_request( self.web.REQUEST_ERROR_DATA_DIR_CANNOT_CREATE, request.path, {"receive_mode_dir": receive_mode_dir}, ) print(strings._("error_cannot_create_data_dir").format(receive_mode_dir)) valid = False if not valid: flash("Error uploading, please inform the OnionShare user", "error") if self.common.settings.get("public_mode"): return redirect("/") else: return redirect("/{}".format(slug_candidate)) files = request.files.getlist("file[]") filenames = [] print("") for f in files: if f.filename != "": # Automatically rename the file, if a file of the same name already exists filename = secure_filename(f.filename) filenames.append(filename) local_path = os.path.join(receive_mode_dir, filename) if os.path.exists(local_path): if "." in filename: # Add "-i", e.g. change "foo.txt" to "foo-2.txt" parts = filename.split(".") name = parts[:-1] ext = parts[-1] i = 2 valid = False while not valid: new_filename = "{}-{}.{}".format(".".join(name), i, ext) local_path = os.path.join(receive_mode_dir, new_filename) if os.path.exists(local_path): i += 1 else: valid = True else: # If no extension, just add "-i", e.g. change "foo" to "foo-2" i = 2 valid = False while not valid: new_filename = "{}-{}".format(filename, i) local_path = os.path.join(receive_mode_dir, new_filename) if os.path.exists(local_path): i += 1 else: valid = True basename = os.path.basename(local_path) if f.filename != basename: # Tell the GUI that the file has changed names self.web.add_request( self.web.REQUEST_UPLOAD_FILE_RENAMED, request.path, { "id": request.upload_id, "old_filename": f.filename, "new_filename": basename, }, ) # Tell the GUI the receive mode directory for this file self.web.add_request( self.web.REQUEST_UPLOAD_SET_DIR, request.path, { "id": request.upload_id, "filename": basename, "dir": receive_mode_dir, }, ) self.common.log( "ReceiveModeWeb", "define_routes", "/upload, uploaded {}, saving to {}".format(f.filename, local_path), ) print(strings._("receive_mode_received_file").format(local_path)) f.save(local_path) # Note that flash strings are on English, and not translated, on purpose, # to avoid leaking the locale of the OnionShare user if len(filenames) == 0: flash("No files uploaded", "info") else: for filename in filenames: flash("Sent {}".format(filename), "info") if self.can_upload: if self.common.settings.get("public_mode"): path = "/" else: path = "/{}".format(slug_candidate) return redirect("{}".format(path)) else: # It was the last upload and the timer ran out if self.common.settings.get("public_mode"): return thankyou_logic(slug_candidate) else: return thankyou_logic() def thankyou_logic(slug_candidate=""): r = make_response(render_template("thankyou.html")) return self.web.add_security_headers(r) @self.web.app.route("/<slug_candidate>/upload", methods=["POST"]) def upload(slug_candidate): if not self.can_upload: return self.web.error403() self.web.check_slug_candidate(slug_candidate) return upload_logic(slug_candidate) @self.web.app.route("/upload", methods=["POST"]) def upload_public(): if not self.can_upload: return self.web.error403() if not self.common.settings.get("public_mode"): return self.web.error404() return upload_logic()
https://github.com/micahflee/onionshare/issues/866
[Jan 07 2019 20:58:37] Onion.cleanup: trying to remove onion 5yym6w3kg4tof56umfy6a632nvtoc5dkkpkhj4zd2slqzp5wuiwml7yd => 2.4 MiB video 1.mov[Jan 07 2019 20:58:37] ReceiveMode.update_primary_action Traceback (most recent call last): File "onionshare_gui/onionshare_gui.py", line 382, in timer_callback mode.handle_request_progress(event) File "onionshare_gui/mode/receive_mode/__init__.py", line 159, in handle_request_progress 'progress': event["data"]["progress"] File "onionshare_gui/mode/history.py", line 451, in update self.item_list.update(id, data) File "onionshare_gui/mode/history.py", line 347, in update self.items[id].update(data) KeyError: 0 => 2.4 MiB video 1.movAbort trap: 6
KeyError
def upload_logic(slug_candidate=""): """ Upload files. """ # Figure out what the receive mode dir should be now = datetime.now() date_dir = now.strftime("%Y-%m-%d") time_dir = now.strftime("%H.%M.%S") receive_mode_dir = os.path.join( self.common.settings.get("data_dir"), date_dir, time_dir ) valid = True try: os.makedirs(receive_mode_dir, 0o700, exist_ok=True) except PermissionError: self.web.add_request( self.web.REQUEST_ERROR_DATA_DIR_CANNOT_CREATE, request.path, {"receive_mode_dir": receive_mode_dir}, ) print(strings._("error_cannot_create_data_dir").format(receive_mode_dir)) valid = False if not valid: flash("Error uploading, please inform the OnionShare user", "error") if self.common.settings.get("public_mode"): return redirect("/") else: return redirect("/{}".format(slug_candidate)) files = request.files.getlist("file[]") filenames = [] print("") for f in files: if f.filename != "": # Automatically rename the file, if a file of the same name already exists filename = secure_filename(f.filename) filenames.append(filename) local_path = os.path.join(receive_mode_dir, filename) if os.path.exists(local_path): if "." in filename: # Add "-i", e.g. change "foo.txt" to "foo-2.txt" parts = filename.split(".") name = parts[:-1] ext = parts[-1] i = 2 valid = False while not valid: new_filename = "{}-{}.{}".format(".".join(name), i, ext) local_path = os.path.join(receive_mode_dir, new_filename) if os.path.exists(local_path): i += 1 else: valid = True else: # If no extension, just add "-i", e.g. change "foo" to "foo-2" i = 2 valid = False while not valid: new_filename = "{}-{}".format(filename, i) local_path = os.path.join(receive_mode_dir, new_filename) if os.path.exists(local_path): i += 1 else: valid = True basename = os.path.basename(local_path) if f.filename != basename: # Tell the GUI that the file has changed names self.web.add_request( self.web.REQUEST_UPLOAD_FILE_RENAMED, request.path, { "id": request.upload_id, "old_filename": f.filename, "new_filename": basename, }, ) # Tell the GUI the receive mode directory for this file self.web.add_request( self.web.REQUEST_UPLOAD_SET_DIR, request.path, { "id": request.upload_id, "filename": basename, "dir": receive_mode_dir, }, ) # Make sure receive mode dir exists before writing file valid = True try: os.makedirs(receive_mode_dir, 0o700, exist_ok=True) except PermissionError: self.web.add_request( self.web.REQUEST_ERROR_DATA_DIR_CANNOT_CREATE, request.path, {"receive_mode_dir": receive_mode_dir}, ) print( strings._("error_cannot_create_data_dir").format(receive_mode_dir) ) valid = False if not valid: flash("Error uploading, please inform the OnionShare user", "error") if self.common.settings.get("public_mode"): return redirect("/") else: return redirect("/{}".format(slug_candidate)) self.common.log( "ReceiveModeWeb", "define_routes", "/upload, uploaded {}, saving to {}".format(f.filename, local_path), ) print(strings._("receive_mode_received_file").format(local_path)) f.save(local_path) # Note that flash strings are on English, and not translated, on purpose, # to avoid leaking the locale of the OnionShare user if len(filenames) == 0: flash("No files uploaded", "info") else: for filename in filenames: flash("Sent {}".format(filename), "info") if self.can_upload: if self.common.settings.get("public_mode"): path = "/" else: path = "/{}".format(slug_candidate) return redirect("{}".format(path)) else: # It was the last upload and the timer ran out if self.common.settings.get("public_mode"): return thankyou_logic(slug_candidate) else: return thankyou_logic()
def upload_logic(slug_candidate=""): """ Upload files. """ # Make sure the receive mode dir exists now = datetime.now() date_dir = now.strftime("%Y-%m-%d") time_dir = now.strftime("%H.%M.%S") receive_mode_dir = os.path.join( self.common.settings.get("data_dir"), date_dir, time_dir ) valid = True try: os.makedirs(receive_mode_dir, 0o700, exist_ok=True) except PermissionError: self.web.add_request( self.web.REQUEST_ERROR_DATA_DIR_CANNOT_CREATE, request.path, {"receive_mode_dir": receive_mode_dir}, ) print(strings._("error_cannot_create_data_dir").format(receive_mode_dir)) valid = False if not valid: flash("Error uploading, please inform the OnionShare user", "error") if self.common.settings.get("public_mode"): return redirect("/") else: return redirect("/{}".format(slug_candidate)) files = request.files.getlist("file[]") filenames = [] print("") for f in files: if f.filename != "": # Automatically rename the file, if a file of the same name already exists filename = secure_filename(f.filename) filenames.append(filename) local_path = os.path.join(receive_mode_dir, filename) if os.path.exists(local_path): if "." in filename: # Add "-i", e.g. change "foo.txt" to "foo-2.txt" parts = filename.split(".") name = parts[:-1] ext = parts[-1] i = 2 valid = False while not valid: new_filename = "{}-{}.{}".format(".".join(name), i, ext) local_path = os.path.join(receive_mode_dir, new_filename) if os.path.exists(local_path): i += 1 else: valid = True else: # If no extension, just add "-i", e.g. change "foo" to "foo-2" i = 2 valid = False while not valid: new_filename = "{}-{}".format(filename, i) local_path = os.path.join(receive_mode_dir, new_filename) if os.path.exists(local_path): i += 1 else: valid = True basename = os.path.basename(local_path) if f.filename != basename: # Tell the GUI that the file has changed names self.web.add_request( self.web.REQUEST_UPLOAD_FILE_RENAMED, request.path, { "id": request.upload_id, "old_filename": f.filename, "new_filename": basename, }, ) # Tell the GUI the receive mode directory for this file self.web.add_request( self.web.REQUEST_UPLOAD_SET_DIR, request.path, { "id": request.upload_id, "filename": basename, "dir": receive_mode_dir, }, ) self.common.log( "ReceiveModeWeb", "define_routes", "/upload, uploaded {}, saving to {}".format(f.filename, local_path), ) print(strings._("receive_mode_received_file").format(local_path)) f.save(local_path) # Note that flash strings are on English, and not translated, on purpose, # to avoid leaking the locale of the OnionShare user if len(filenames) == 0: flash("No files uploaded", "info") else: for filename in filenames: flash("Sent {}".format(filename), "info") if self.can_upload: if self.common.settings.get("public_mode"): path = "/" else: path = "/{}".format(slug_candidate) return redirect("{}".format(path)) else: # It was the last upload and the timer ran out if self.common.settings.get("public_mode"): return thankyou_logic(slug_candidate) else: return thankyou_logic()
https://github.com/micahflee/onionshare/issues/866
[Jan 07 2019 20:58:37] Onion.cleanup: trying to remove onion 5yym6w3kg4tof56umfy6a632nvtoc5dkkpkhj4zd2slqzp5wuiwml7yd => 2.4 MiB video 1.mov[Jan 07 2019 20:58:37] ReceiveMode.update_primary_action Traceback (most recent call last): File "onionshare_gui/onionshare_gui.py", line 382, in timer_callback mode.handle_request_progress(event) File "onionshare_gui/mode/receive_mode/__init__.py", line 159, in handle_request_progress 'progress': event["data"]["progress"] File "onionshare_gui/mode/history.py", line 451, in update self.item_list.update(id, data) File "onionshare_gui/mode/history.py", line 347, in update self.items[id].update(data) KeyError: 0 => 2.4 MiB video 1.movAbort trap: 6
KeyError
def __call__(self, environ, start_response): environ["web"] = self.web environ["stop_q"] = self.web.stop_q return self.app(environ, start_response)
def __call__(self, environ, start_response): environ["web"] = self.web return self.app(environ, start_response)
https://github.com/micahflee/onionshare/issues/866
[Jan 07 2019 20:58:37] Onion.cleanup: trying to remove onion 5yym6w3kg4tof56umfy6a632nvtoc5dkkpkhj4zd2slqzp5wuiwml7yd => 2.4 MiB video 1.mov[Jan 07 2019 20:58:37] ReceiveMode.update_primary_action Traceback (most recent call last): File "onionshare_gui/onionshare_gui.py", line 382, in timer_callback mode.handle_request_progress(event) File "onionshare_gui/mode/receive_mode/__init__.py", line 159, in handle_request_progress 'progress': event["data"]["progress"] File "onionshare_gui/mode/history.py", line 451, in update self.item_list.update(id, data) File "onionshare_gui/mode/history.py", line 347, in update self.items[id].update(data) KeyError: 0 => 2.4 MiB video 1.movAbort trap: 6
KeyError
def __init__(self, request, filename, write_func, close_func): self.onionshare_request = request self.onionshare_filename = filename self.onionshare_write_func = write_func self.onionshare_close_func = close_func # Create a temporary file self.f = tempfile.TemporaryFile("wb+") # Make all the file-like methods and attributes actually access the # TemporaryFile, except for write attrs = [ "closed", "detach", "fileno", "flush", "isatty", "mode", "name", "peek", "raw", "read", "read1", "readable", "readinto", "readinto1", "readline", "readlines", "seek", "seekable", "tell", "truncate", "writable", "writelines", ] for attr in attrs: setattr(self, attr, getattr(self.f, attr))
def __init__(self, filename, write_func, close_func): self.onionshare_filename = filename self.onionshare_write_func = write_func self.onionshare_close_func = close_func # Create a temporary file self.f = tempfile.TemporaryFile("wb+") # Make all the file-like methods and attributes actually access the # TemporaryFile, except for write attrs = [ "closed", "detach", "fileno", "flush", "isatty", "mode", "name", "peek", "raw", "read", "read1", "readable", "readinto", "readinto1", "readline", "readlines", "seek", "seekable", "tell", "truncate", "writable", "writelines", ] for attr in attrs: setattr(self, attr, getattr(self.f, attr))
https://github.com/micahflee/onionshare/issues/866
[Jan 07 2019 20:58:37] Onion.cleanup: trying to remove onion 5yym6w3kg4tof56umfy6a632nvtoc5dkkpkhj4zd2slqzp5wuiwml7yd => 2.4 MiB video 1.mov[Jan 07 2019 20:58:37] ReceiveMode.update_primary_action Traceback (most recent call last): File "onionshare_gui/onionshare_gui.py", line 382, in timer_callback mode.handle_request_progress(event) File "onionshare_gui/mode/receive_mode/__init__.py", line 159, in handle_request_progress 'progress': event["data"]["progress"] File "onionshare_gui/mode/history.py", line 451, in update self.item_list.update(id, data) File "onionshare_gui/mode/history.py", line 347, in update self.items[id].update(data) KeyError: 0 => 2.4 MiB video 1.movAbort trap: 6
KeyError
def write(self, b): """ Custom write method that calls out to onionshare_write_func """ if not self.onionshare_request.stop_q.empty(): self.close() self.onionshare_request.close() return bytes_written = self.f.write(b) self.onionshare_write_func(self.onionshare_filename, bytes_written)
def write(self, b): """ Custom write method that calls out to onionshare_write_func """ bytes_written = self.f.write(b) self.onionshare_write_func(self.onionshare_filename, bytes_written)
https://github.com/micahflee/onionshare/issues/866
[Jan 07 2019 20:58:37] Onion.cleanup: trying to remove onion 5yym6w3kg4tof56umfy6a632nvtoc5dkkpkhj4zd2slqzp5wuiwml7yd => 2.4 MiB video 1.mov[Jan 07 2019 20:58:37] ReceiveMode.update_primary_action Traceback (most recent call last): File "onionshare_gui/onionshare_gui.py", line 382, in timer_callback mode.handle_request_progress(event) File "onionshare_gui/mode/receive_mode/__init__.py", line 159, in handle_request_progress 'progress': event["data"]["progress"] File "onionshare_gui/mode/history.py", line 451, in update self.item_list.update(id, data) File "onionshare_gui/mode/history.py", line 347, in update self.items[id].update(data) KeyError: 0 => 2.4 MiB video 1.movAbort trap: 6
KeyError
def __init__(self, environ, populate_request=True, shallow=False): super(ReceiveModeRequest, self).__init__(environ, populate_request, shallow) self.web = environ["web"] self.stop_q = environ["stop_q"] self.web.common.log("ReceiveModeRequest", "__init__") # Prevent running the close() method more than once self.closed = False # Is this a valid upload request? self.upload_request = False if self.method == "POST": if self.path == "/{}/upload".format(self.web.slug): self.upload_request = True else: if self.web.common.settings.get("public_mode"): if self.path == "/upload": self.upload_request = True if self.upload_request: # A dictionary that maps filenames to the bytes uploaded so far self.progress = {} # Prevent new uploads if we've said so (timer expired) if self.web.receive_mode.can_upload: # Create an upload_id, attach it to the request self.upload_id = self.web.receive_mode.upload_count self.web.receive_mode.upload_count += 1 # Figure out the content length try: self.content_length = int(self.headers["Content-Length"]) except: self.content_length = 0 print( "{}: {}".format( datetime.now().strftime("%b %d, %I:%M%p"), strings._("receive_mode_upload_starting").format( self.web.common.human_readable_filesize(self.content_length) ), ) ) # Don't tell the GUI that a request has started until we start receiving files self.told_gui_about_request = False self.previous_file = None
def __init__(self, environ, populate_request=True, shallow=False): super(ReceiveModeRequest, self).__init__(environ, populate_request, shallow) self.web = environ["web"] # Is this a valid upload request? self.upload_request = False if self.method == "POST": if self.path == "/{}/upload".format(self.web.slug): self.upload_request = True else: if self.web.common.settings.get("public_mode"): if self.path == "/upload": self.upload_request = True if self.upload_request: # A dictionary that maps filenames to the bytes uploaded so far self.progress = {} # Prevent new uploads if we've said so (timer expired) if self.web.receive_mode.can_upload: # Create an upload_id, attach it to the request self.upload_id = self.web.receive_mode.upload_count self.web.receive_mode.upload_count += 1 # Figure out the content length try: self.content_length = int(self.headers["Content-Length"]) except: self.content_length = 0 print( "{}: {}".format( datetime.now().strftime("%b %d, %I:%M%p"), strings._("receive_mode_upload_starting").format( self.web.common.human_readable_filesize(self.content_length) ), ) ) # Don't tell the GUI that a request has started until we start receiving files self.told_gui_about_request = False self.previous_file = None
https://github.com/micahflee/onionshare/issues/866
[Jan 07 2019 20:58:37] Onion.cleanup: trying to remove onion 5yym6w3kg4tof56umfy6a632nvtoc5dkkpkhj4zd2slqzp5wuiwml7yd => 2.4 MiB video 1.mov[Jan 07 2019 20:58:37] ReceiveMode.update_primary_action Traceback (most recent call last): File "onionshare_gui/onionshare_gui.py", line 382, in timer_callback mode.handle_request_progress(event) File "onionshare_gui/mode/receive_mode/__init__.py", line 159, in handle_request_progress 'progress': event["data"]["progress"] File "onionshare_gui/mode/history.py", line 451, in update self.item_list.update(id, data) File "onionshare_gui/mode/history.py", line 347, in update self.items[id].update(data) KeyError: 0 => 2.4 MiB video 1.movAbort trap: 6
KeyError
def _get_file_stream( self, total_content_length, content_type, filename=None, content_length=None ): """ This gets called for each file that gets uploaded, and returns an file-like writable stream. """ if self.upload_request: if not self.told_gui_about_request: # Tell the GUI about the request self.web.add_request( self.web.REQUEST_STARTED, self.path, {"id": self.upload_id, "content_length": self.content_length}, ) self.web.receive_mode.uploads_in_progress.append(self.upload_id) self.told_gui_about_request = True self.progress[filename] = {"uploaded_bytes": 0, "complete": False} return ReceiveModeTemporaryFile( self, filename, self.file_write_func, self.file_close_func )
def _get_file_stream( self, total_content_length, content_type, filename=None, content_length=None ): """ This gets called for each file that gets uploaded, and returns an file-like writable stream. """ if self.upload_request: if not self.told_gui_about_request: # Tell the GUI about the request self.web.add_request( self.web.REQUEST_STARTED, self.path, {"id": self.upload_id, "content_length": self.content_length}, ) self.web.receive_mode.uploads_in_progress.append(self.upload_id) self.told_gui_about_request = True self.progress[filename] = {"uploaded_bytes": 0, "complete": False} return ReceiveModeTemporaryFile( filename, self.file_write_func, self.file_close_func )
https://github.com/micahflee/onionshare/issues/866
[Jan 07 2019 20:58:37] Onion.cleanup: trying to remove onion 5yym6w3kg4tof56umfy6a632nvtoc5dkkpkhj4zd2slqzp5wuiwml7yd => 2.4 MiB video 1.mov[Jan 07 2019 20:58:37] ReceiveMode.update_primary_action Traceback (most recent call last): File "onionshare_gui/onionshare_gui.py", line 382, in timer_callback mode.handle_request_progress(event) File "onionshare_gui/mode/receive_mode/__init__.py", line 159, in handle_request_progress 'progress': event["data"]["progress"] File "onionshare_gui/mode/history.py", line 451, in update self.item_list.update(id, data) File "onionshare_gui/mode/history.py", line 347, in update self.items[id].update(data) KeyError: 0 => 2.4 MiB video 1.movAbort trap: 6
KeyError
def close(self): """ Closing the request. """ super(ReceiveModeRequest, self).close() # Prevent calling this method more than once per request if self.closed: return self.closed = True self.web.common.log("ReceiveModeRequest", "close") try: if self.told_gui_about_request: upload_id = self.upload_id if not self.web.stop_q.empty(): # Inform the GUI that the upload has canceled self.web.add_request( self.web.REQUEST_UPLOAD_CANCELED, self.path, {"id": upload_id} ) else: # Inform the GUI that the upload has finished self.web.add_request( self.web.REQUEST_UPLOAD_FINISHED, self.path, {"id": upload_id} ) self.web.receive_mode.uploads_in_progress.remove(upload_id) except AttributeError: pass
def close(self): """ Closing the request. """ super(ReceiveModeRequest, self).close() try: if self.told_gui_about_request: upload_id = self.upload_id # Inform the GUI that the upload has finished self.web.add_request( self.web.REQUEST_UPLOAD_FINISHED, self.path, {"id": upload_id} ) self.web.receive_mode.uploads_in_progress.remove(upload_id) except AttributeError: pass
https://github.com/micahflee/onionshare/issues/866
[Jan 07 2019 20:58:37] Onion.cleanup: trying to remove onion 5yym6w3kg4tof56umfy6a632nvtoc5dkkpkhj4zd2slqzp5wuiwml7yd => 2.4 MiB video 1.mov[Jan 07 2019 20:58:37] ReceiveMode.update_primary_action Traceback (most recent call last): File "onionshare_gui/onionshare_gui.py", line 382, in timer_callback mode.handle_request_progress(event) File "onionshare_gui/mode/receive_mode/__init__.py", line 159, in handle_request_progress 'progress': event["data"]["progress"] File "onionshare_gui/mode/history.py", line 451, in update self.item_list.update(id, data) File "onionshare_gui/mode/history.py", line 347, in update self.items[id].update(data) KeyError: 0 => 2.4 MiB video 1.movAbort trap: 6
KeyError
def file_write_func(self, filename, length): """ This function gets called when a specific file is written to. """ if self.closed: return if self.upload_request: self.progress[filename]["uploaded_bytes"] += length if self.previous_file != filename: if self.previous_file is not None: print("") self.previous_file = filename print( "\r=> {:15s} {}".format( self.web.common.human_readable_filesize( self.progress[filename]["uploaded_bytes"] ), filename, ), end="", ) # Update the GUI on the upload progress if self.told_gui_about_request: self.web.add_request( self.web.REQUEST_PROGRESS, self.path, {"id": self.upload_id, "progress": self.progress}, )
def file_write_func(self, filename, length): """ This function gets called when a specific file is written to. """ if self.upload_request: self.progress[filename]["uploaded_bytes"] += length if self.previous_file != filename: if self.previous_file is not None: print("") self.previous_file = filename print( "\r=> {:15s} {}".format( self.web.common.human_readable_filesize( self.progress[filename]["uploaded_bytes"] ), filename, ), end="", ) # Update the GUI on the upload progress if self.told_gui_about_request: self.web.add_request( self.web.REQUEST_PROGRESS, self.path, {"id": self.upload_id, "progress": self.progress}, )
https://github.com/micahflee/onionshare/issues/866
[Jan 07 2019 20:58:37] Onion.cleanup: trying to remove onion 5yym6w3kg4tof56umfy6a632nvtoc5dkkpkhj4zd2slqzp5wuiwml7yd => 2.4 MiB video 1.mov[Jan 07 2019 20:58:37] ReceiveMode.update_primary_action Traceback (most recent call last): File "onionshare_gui/onionshare_gui.py", line 382, in timer_callback mode.handle_request_progress(event) File "onionshare_gui/mode/receive_mode/__init__.py", line 159, in handle_request_progress 'progress': event["data"]["progress"] File "onionshare_gui/mode/history.py", line 451, in update self.item_list.update(id, data) File "onionshare_gui/mode/history.py", line 347, in update self.items[id].update(data) KeyError: 0 => 2.4 MiB video 1.movAbort trap: 6
KeyError
def __init__(self, common, web): self.common = common self.common.log("ShareModeWeb", "__init__") self.web = web # Information about the file to be shared self.file_info = [] self.is_zipped = False self.download_filename = None self.download_filesize = None self.gzip_filename = None self.gzip_filesize = None self.zip_writer = None self.download_count = 0 # If "Stop After First Download" is checked (stay_open == False), only allow # one download at a time. self.download_in_progress = False self.define_routes()
def __init__(self, common, web): self.common = common self.common.log("ShareModeWeb", "__init__") self.web = web # Information about the file to be shared self.file_info = [] self.is_zipped = False self.download_filename = None self.download_filesize = None self.gzip_filename = None self.gzip_filesize = None self.zip_writer = None self.download_count = 0 # If "Stop After First Download" is checked (stay_open == False), only allow # one download at a time. self.download_in_progress = False # If the client closes the OnionShare window while a download is in progress, # it should immediately stop serving the file. The client_cancel global is # used to tell the download function that the client is canceling the download. self.client_cancel = False self.define_routes()
https://github.com/micahflee/onionshare/issues/866
[Jan 07 2019 20:58:37] Onion.cleanup: trying to remove onion 5yym6w3kg4tof56umfy6a632nvtoc5dkkpkhj4zd2slqzp5wuiwml7yd => 2.4 MiB video 1.mov[Jan 07 2019 20:58:37] ReceiveMode.update_primary_action Traceback (most recent call last): File "onionshare_gui/onionshare_gui.py", line 382, in timer_callback mode.handle_request_progress(event) File "onionshare_gui/mode/receive_mode/__init__.py", line 159, in handle_request_progress 'progress': event["data"]["progress"] File "onionshare_gui/mode/history.py", line 451, in update self.item_list.update(id, data) File "onionshare_gui/mode/history.py", line 347, in update self.items[id].update(data) KeyError: 0 => 2.4 MiB video 1.movAbort trap: 6
KeyError
def define_routes(self): """ The web app routes for sharing files """ @self.web.app.route("/<slug_candidate>") def index(slug_candidate): self.web.check_slug_candidate(slug_candidate) return index_logic() @self.web.app.route("/") def index_public(): if not self.common.settings.get("public_mode"): return self.web.error404() return index_logic() def index_logic(slug_candidate=""): """ Render the template for the onionshare landing page. """ self.web.add_request(self.web.REQUEST_LOAD, request.path) # Deny new downloads if "Stop After First Download" is checked and there is # currently a download deny_download = not self.web.stay_open and self.download_in_progress if deny_download: r = make_response(render_template("denied.html")) return self.web.add_security_headers(r) # If download is allowed to continue, serve download page if self.should_use_gzip(): self.filesize = self.gzip_filesize else: self.filesize = self.download_filesize if self.web.slug: r = make_response( render_template( "send.html", slug=self.web.slug, file_info=self.file_info, filename=os.path.basename(self.download_filename), filesize=self.filesize, filesize_human=self.common.human_readable_filesize( self.download_filesize ), is_zipped=self.is_zipped, ) ) else: # If download is allowed to continue, serve download page r = make_response( render_template( "send.html", file_info=self.file_info, filename=os.path.basename(self.download_filename), filesize=self.filesize, filesize_human=self.common.human_readable_filesize( self.download_filesize ), is_zipped=self.is_zipped, ) ) return self.web.add_security_headers(r) @self.web.app.route("/<slug_candidate>/download") def download(slug_candidate): self.web.check_slug_candidate(slug_candidate) return download_logic() @self.web.app.route("/download") def download_public(): if not self.common.settings.get("public_mode"): return self.web.error404() return download_logic() def download_logic(slug_candidate=""): """ Download the zip file. """ # Deny new downloads if "Stop After First Download" is checked and there is # currently a download deny_download = not self.web.stay_open and self.download_in_progress if deny_download: r = make_response(render_template("denied.html")) return self.web.add_security_headers(r) # Each download has a unique id download_id = self.download_count self.download_count += 1 # Prepare some variables to use inside generate() function below # which is outside of the request context shutdown_func = request.environ.get("werkzeug.server.shutdown") path = request.path # If this is a zipped file, then serve as-is. If it's not zipped, then, # if the http client supports gzip compression, gzip the file first # and serve that use_gzip = self.should_use_gzip() if use_gzip: file_to_download = self.gzip_filename self.filesize = self.gzip_filesize else: file_to_download = self.download_filename self.filesize = self.download_filesize # Tell GUI the download started self.web.add_request( self.web.REQUEST_STARTED, path, {"id": download_id, "use_gzip": use_gzip} ) basename = os.path.basename(self.download_filename) def generate(): # Starting a new download if not self.web.stay_open: self.download_in_progress = True chunk_size = 102400 # 100kb fp = open(file_to_download, "rb") self.web.done = False canceled = False while not self.web.done: # The user has canceled the download, so stop serving the file if not self.web.stop_q.empty(): self.web.add_request( self.web.REQUEST_CANCELED, path, {"id": download_id} ) break chunk = fp.read(chunk_size) if chunk == b"": self.web.done = True else: try: yield chunk # tell GUI the progress downloaded_bytes = fp.tell() percent = (1.0 * downloaded_bytes / self.filesize) * 100 # only output to stdout if running onionshare in CLI mode, or if using Linux (#203, #304) if ( not self.web.is_gui or self.common.platform == "Linux" or self.common.platform == "BSD" ): sys.stdout.write( "\r{0:s}, {1:.2f}% ".format( self.common.human_readable_filesize( downloaded_bytes ), percent, ) ) sys.stdout.flush() self.web.add_request( self.web.REQUEST_PROGRESS, path, {"id": download_id, "bytes": downloaded_bytes}, ) self.web.done = False except: # looks like the download was canceled self.web.done = True canceled = True # tell the GUI the download has canceled self.web.add_request( self.web.REQUEST_CANCELED, path, {"id": download_id} ) fp.close() if self.common.platform != "Darwin": sys.stdout.write("\n") # Download is finished if not self.web.stay_open: self.download_in_progress = False # Close the server, if necessary if not self.web.stay_open and not canceled: print(strings._("closing_automatically")) self.web.running = False try: if shutdown_func is None: raise RuntimeError("Not running with the Werkzeug Server") shutdown_func() except: pass r = Response(generate()) if use_gzip: r.headers.set("Content-Encoding", "gzip") r.headers.set("Content-Length", self.filesize) r.headers.set("Content-Disposition", "attachment", filename=basename) r = self.web.add_security_headers(r) # guess content type (content_type, _) = mimetypes.guess_type(basename, strict=False) if content_type is not None: r.headers.set("Content-Type", content_type) return r
def define_routes(self): """ The web app routes for sharing files """ @self.web.app.route("/<slug_candidate>") def index(slug_candidate): self.web.check_slug_candidate(slug_candidate) return index_logic() @self.web.app.route("/") def index_public(): if not self.common.settings.get("public_mode"): return self.web.error404() return index_logic() def index_logic(slug_candidate=""): """ Render the template for the onionshare landing page. """ self.web.add_request(self.web.REQUEST_LOAD, request.path) # Deny new downloads if "Stop After First Download" is checked and there is # currently a download deny_download = not self.web.stay_open and self.download_in_progress if deny_download: r = make_response(render_template("denied.html")) return self.web.add_security_headers(r) # If download is allowed to continue, serve download page if self.should_use_gzip(): self.filesize = self.gzip_filesize else: self.filesize = self.download_filesize if self.web.slug: r = make_response( render_template( "send.html", slug=self.web.slug, file_info=self.file_info, filename=os.path.basename(self.download_filename), filesize=self.filesize, filesize_human=self.common.human_readable_filesize( self.download_filesize ), is_zipped=self.is_zipped, ) ) else: # If download is allowed to continue, serve download page r = make_response( render_template( "send.html", file_info=self.file_info, filename=os.path.basename(self.download_filename), filesize=self.filesize, filesize_human=self.common.human_readable_filesize( self.download_filesize ), is_zipped=self.is_zipped, ) ) return self.web.add_security_headers(r) @self.web.app.route("/<slug_candidate>/download") def download(slug_candidate): self.web.check_slug_candidate(slug_candidate) return download_logic() @self.web.app.route("/download") def download_public(): if not self.common.settings.get("public_mode"): return self.web.error404() return download_logic() def download_logic(slug_candidate=""): """ Download the zip file. """ # Deny new downloads if "Stop After First Download" is checked and there is # currently a download deny_download = not self.web.stay_open and self.download_in_progress if deny_download: r = make_response(render_template("denied.html")) return self.web.add_security_headers(r) # Each download has a unique id download_id = self.download_count self.download_count += 1 # Prepare some variables to use inside generate() function below # which is outside of the request context shutdown_func = request.environ.get("werkzeug.server.shutdown") path = request.path # If this is a zipped file, then serve as-is. If it's not zipped, then, # if the http client supports gzip compression, gzip the file first # and serve that use_gzip = self.should_use_gzip() if use_gzip: file_to_download = self.gzip_filename self.filesize = self.gzip_filesize else: file_to_download = self.download_filename self.filesize = self.download_filesize # Tell GUI the download started self.web.add_request( self.web.REQUEST_STARTED, path, {"id": download_id, "use_gzip": use_gzip} ) basename = os.path.basename(self.download_filename) def generate(): # The user hasn't canceled the download self.client_cancel = False # Starting a new download if not self.web.stay_open: self.download_in_progress = True chunk_size = 102400 # 100kb fp = open(file_to_download, "rb") self.web.done = False canceled = False while not self.web.done: # The user has canceled the download, so stop serving the file if self.client_cancel: self.web.add_request( self.web.REQUEST_CANCELED, path, {"id": download_id} ) break chunk = fp.read(chunk_size) if chunk == b"": self.web.done = True else: try: yield chunk # tell GUI the progress downloaded_bytes = fp.tell() percent = (1.0 * downloaded_bytes / self.filesize) * 100 # only output to stdout if running onionshare in CLI mode, or if using Linux (#203, #304) if ( not self.web.is_gui or self.common.platform == "Linux" or self.common.platform == "BSD" ): sys.stdout.write( "\r{0:s}, {1:.2f}% ".format( self.common.human_readable_filesize( downloaded_bytes ), percent, ) ) sys.stdout.flush() self.web.add_request( self.web.REQUEST_PROGRESS, path, {"id": download_id, "bytes": downloaded_bytes}, ) self.web.done = False except: # looks like the download was canceled self.web.done = True canceled = True # tell the GUI the download has canceled self.web.add_request( self.web.REQUEST_CANCELED, path, {"id": download_id} ) fp.close() if self.common.platform != "Darwin": sys.stdout.write("\n") # Download is finished if not self.web.stay_open: self.download_in_progress = False # Close the server, if necessary if not self.web.stay_open and not canceled: print(strings._("closing_automatically")) self.web.running = False try: if shutdown_func is None: raise RuntimeError("Not running with the Werkzeug Server") shutdown_func() except: pass r = Response(generate()) if use_gzip: r.headers.set("Content-Encoding", "gzip") r.headers.set("Content-Length", self.filesize) r.headers.set("Content-Disposition", "attachment", filename=basename) r = self.web.add_security_headers(r) # guess content type (content_type, _) = mimetypes.guess_type(basename, strict=False) if content_type is not None: r.headers.set("Content-Type", content_type) return r
https://github.com/micahflee/onionshare/issues/866
[Jan 07 2019 20:58:37] Onion.cleanup: trying to remove onion 5yym6w3kg4tof56umfy6a632nvtoc5dkkpkhj4zd2slqzp5wuiwml7yd => 2.4 MiB video 1.mov[Jan 07 2019 20:58:37] ReceiveMode.update_primary_action Traceback (most recent call last): File "onionshare_gui/onionshare_gui.py", line 382, in timer_callback mode.handle_request_progress(event) File "onionshare_gui/mode/receive_mode/__init__.py", line 159, in handle_request_progress 'progress': event["data"]["progress"] File "onionshare_gui/mode/history.py", line 451, in update self.item_list.update(id, data) File "onionshare_gui/mode/history.py", line 347, in update self.items[id].update(data) KeyError: 0 => 2.4 MiB video 1.movAbort trap: 6
KeyError
def download_logic(slug_candidate=""): """ Download the zip file. """ # Deny new downloads if "Stop After First Download" is checked and there is # currently a download deny_download = not self.web.stay_open and self.download_in_progress if deny_download: r = make_response(render_template("denied.html")) return self.web.add_security_headers(r) # Each download has a unique id download_id = self.download_count self.download_count += 1 # Prepare some variables to use inside generate() function below # which is outside of the request context shutdown_func = request.environ.get("werkzeug.server.shutdown") path = request.path # If this is a zipped file, then serve as-is. If it's not zipped, then, # if the http client supports gzip compression, gzip the file first # and serve that use_gzip = self.should_use_gzip() if use_gzip: file_to_download = self.gzip_filename self.filesize = self.gzip_filesize else: file_to_download = self.download_filename self.filesize = self.download_filesize # Tell GUI the download started self.web.add_request( self.web.REQUEST_STARTED, path, {"id": download_id, "use_gzip": use_gzip} ) basename = os.path.basename(self.download_filename) def generate(): # Starting a new download if not self.web.stay_open: self.download_in_progress = True chunk_size = 102400 # 100kb fp = open(file_to_download, "rb") self.web.done = False canceled = False while not self.web.done: # The user has canceled the download, so stop serving the file if not self.web.stop_q.empty(): self.web.add_request( self.web.REQUEST_CANCELED, path, {"id": download_id} ) break chunk = fp.read(chunk_size) if chunk == b"": self.web.done = True else: try: yield chunk # tell GUI the progress downloaded_bytes = fp.tell() percent = (1.0 * downloaded_bytes / self.filesize) * 100 # only output to stdout if running onionshare in CLI mode, or if using Linux (#203, #304) if ( not self.web.is_gui or self.common.platform == "Linux" or self.common.platform == "BSD" ): sys.stdout.write( "\r{0:s}, {1:.2f}% ".format( self.common.human_readable_filesize(downloaded_bytes), percent, ) ) sys.stdout.flush() self.web.add_request( self.web.REQUEST_PROGRESS, path, {"id": download_id, "bytes": downloaded_bytes}, ) self.web.done = False except: # looks like the download was canceled self.web.done = True canceled = True # tell the GUI the download has canceled self.web.add_request( self.web.REQUEST_CANCELED, path, {"id": download_id} ) fp.close() if self.common.platform != "Darwin": sys.stdout.write("\n") # Download is finished if not self.web.stay_open: self.download_in_progress = False # Close the server, if necessary if not self.web.stay_open and not canceled: print(strings._("closing_automatically")) self.web.running = False try: if shutdown_func is None: raise RuntimeError("Not running with the Werkzeug Server") shutdown_func() except: pass r = Response(generate()) if use_gzip: r.headers.set("Content-Encoding", "gzip") r.headers.set("Content-Length", self.filesize) r.headers.set("Content-Disposition", "attachment", filename=basename) r = self.web.add_security_headers(r) # guess content type (content_type, _) = mimetypes.guess_type(basename, strict=False) if content_type is not None: r.headers.set("Content-Type", content_type) return r
def download_logic(slug_candidate=""): """ Download the zip file. """ # Deny new downloads if "Stop After First Download" is checked and there is # currently a download deny_download = not self.web.stay_open and self.download_in_progress if deny_download: r = make_response(render_template("denied.html")) return self.web.add_security_headers(r) # Each download has a unique id download_id = self.download_count self.download_count += 1 # Prepare some variables to use inside generate() function below # which is outside of the request context shutdown_func = request.environ.get("werkzeug.server.shutdown") path = request.path # If this is a zipped file, then serve as-is. If it's not zipped, then, # if the http client supports gzip compression, gzip the file first # and serve that use_gzip = self.should_use_gzip() if use_gzip: file_to_download = self.gzip_filename self.filesize = self.gzip_filesize else: file_to_download = self.download_filename self.filesize = self.download_filesize # Tell GUI the download started self.web.add_request( self.web.REQUEST_STARTED, path, {"id": download_id, "use_gzip": use_gzip} ) basename = os.path.basename(self.download_filename) def generate(): # The user hasn't canceled the download self.client_cancel = False # Starting a new download if not self.web.stay_open: self.download_in_progress = True chunk_size = 102400 # 100kb fp = open(file_to_download, "rb") self.web.done = False canceled = False while not self.web.done: # The user has canceled the download, so stop serving the file if self.client_cancel: self.web.add_request( self.web.REQUEST_CANCELED, path, {"id": download_id} ) break chunk = fp.read(chunk_size) if chunk == b"": self.web.done = True else: try: yield chunk # tell GUI the progress downloaded_bytes = fp.tell() percent = (1.0 * downloaded_bytes / self.filesize) * 100 # only output to stdout if running onionshare in CLI mode, or if using Linux (#203, #304) if ( not self.web.is_gui or self.common.platform == "Linux" or self.common.platform == "BSD" ): sys.stdout.write( "\r{0:s}, {1:.2f}% ".format( self.common.human_readable_filesize(downloaded_bytes), percent, ) ) sys.stdout.flush() self.web.add_request( self.web.REQUEST_PROGRESS, path, {"id": download_id, "bytes": downloaded_bytes}, ) self.web.done = False except: # looks like the download was canceled self.web.done = True canceled = True # tell the GUI the download has canceled self.web.add_request( self.web.REQUEST_CANCELED, path, {"id": download_id} ) fp.close() if self.common.platform != "Darwin": sys.stdout.write("\n") # Download is finished if not self.web.stay_open: self.download_in_progress = False # Close the server, if necessary if not self.web.stay_open and not canceled: print(strings._("closing_automatically")) self.web.running = False try: if shutdown_func is None: raise RuntimeError("Not running with the Werkzeug Server") shutdown_func() except: pass r = Response(generate()) if use_gzip: r.headers.set("Content-Encoding", "gzip") r.headers.set("Content-Length", self.filesize) r.headers.set("Content-Disposition", "attachment", filename=basename) r = self.web.add_security_headers(r) # guess content type (content_type, _) = mimetypes.guess_type(basename, strict=False) if content_type is not None: r.headers.set("Content-Type", content_type) return r
https://github.com/micahflee/onionshare/issues/866
[Jan 07 2019 20:58:37] Onion.cleanup: trying to remove onion 5yym6w3kg4tof56umfy6a632nvtoc5dkkpkhj4zd2slqzp5wuiwml7yd => 2.4 MiB video 1.mov[Jan 07 2019 20:58:37] ReceiveMode.update_primary_action Traceback (most recent call last): File "onionshare_gui/onionshare_gui.py", line 382, in timer_callback mode.handle_request_progress(event) File "onionshare_gui/mode/receive_mode/__init__.py", line 159, in handle_request_progress 'progress': event["data"]["progress"] File "onionshare_gui/mode/history.py", line 451, in update self.item_list.update(id, data) File "onionshare_gui/mode/history.py", line 347, in update self.items[id].update(data) KeyError: 0 => 2.4 MiB video 1.movAbort trap: 6
KeyError
def generate(): # Starting a new download if not self.web.stay_open: self.download_in_progress = True chunk_size = 102400 # 100kb fp = open(file_to_download, "rb") self.web.done = False canceled = False while not self.web.done: # The user has canceled the download, so stop serving the file if not self.web.stop_q.empty(): self.web.add_request(self.web.REQUEST_CANCELED, path, {"id": download_id}) break chunk = fp.read(chunk_size) if chunk == b"": self.web.done = True else: try: yield chunk # tell GUI the progress downloaded_bytes = fp.tell() percent = (1.0 * downloaded_bytes / self.filesize) * 100 # only output to stdout if running onionshare in CLI mode, or if using Linux (#203, #304) if ( not self.web.is_gui or self.common.platform == "Linux" or self.common.platform == "BSD" ): sys.stdout.write( "\r{0:s}, {1:.2f}% ".format( self.common.human_readable_filesize(downloaded_bytes), percent, ) ) sys.stdout.flush() self.web.add_request( self.web.REQUEST_PROGRESS, path, {"id": download_id, "bytes": downloaded_bytes}, ) self.web.done = False except: # looks like the download was canceled self.web.done = True canceled = True # tell the GUI the download has canceled self.web.add_request( self.web.REQUEST_CANCELED, path, {"id": download_id} ) fp.close() if self.common.platform != "Darwin": sys.stdout.write("\n") # Download is finished if not self.web.stay_open: self.download_in_progress = False # Close the server, if necessary if not self.web.stay_open and not canceled: print(strings._("closing_automatically")) self.web.running = False try: if shutdown_func is None: raise RuntimeError("Not running with the Werkzeug Server") shutdown_func() except: pass
def generate(): # The user hasn't canceled the download self.client_cancel = False # Starting a new download if not self.web.stay_open: self.download_in_progress = True chunk_size = 102400 # 100kb fp = open(file_to_download, "rb") self.web.done = False canceled = False while not self.web.done: # The user has canceled the download, so stop serving the file if self.client_cancel: self.web.add_request(self.web.REQUEST_CANCELED, path, {"id": download_id}) break chunk = fp.read(chunk_size) if chunk == b"": self.web.done = True else: try: yield chunk # tell GUI the progress downloaded_bytes = fp.tell() percent = (1.0 * downloaded_bytes / self.filesize) * 100 # only output to stdout if running onionshare in CLI mode, or if using Linux (#203, #304) if ( not self.web.is_gui or self.common.platform == "Linux" or self.common.platform == "BSD" ): sys.stdout.write( "\r{0:s}, {1:.2f}% ".format( self.common.human_readable_filesize(downloaded_bytes), percent, ) ) sys.stdout.flush() self.web.add_request( self.web.REQUEST_PROGRESS, path, {"id": download_id, "bytes": downloaded_bytes}, ) self.web.done = False except: # looks like the download was canceled self.web.done = True canceled = True # tell the GUI the download has canceled self.web.add_request( self.web.REQUEST_CANCELED, path, {"id": download_id} ) fp.close() if self.common.platform != "Darwin": sys.stdout.write("\n") # Download is finished if not self.web.stay_open: self.download_in_progress = False # Close the server, if necessary if not self.web.stay_open and not canceled: print(strings._("closing_automatically")) self.web.running = False try: if shutdown_func is None: raise RuntimeError("Not running with the Werkzeug Server") shutdown_func() except: pass
https://github.com/micahflee/onionshare/issues/866
[Jan 07 2019 20:58:37] Onion.cleanup: trying to remove onion 5yym6w3kg4tof56umfy6a632nvtoc5dkkpkhj4zd2slqzp5wuiwml7yd => 2.4 MiB video 1.mov[Jan 07 2019 20:58:37] ReceiveMode.update_primary_action Traceback (most recent call last): File "onionshare_gui/onionshare_gui.py", line 382, in timer_callback mode.handle_request_progress(event) File "onionshare_gui/mode/receive_mode/__init__.py", line 159, in handle_request_progress 'progress': event["data"]["progress"] File "onionshare_gui/mode/history.py", line 451, in update self.item_list.update(id, data) File "onionshare_gui/mode/history.py", line 347, in update self.items[id].update(data) KeyError: 0 => 2.4 MiB video 1.movAbort trap: 6
KeyError
def __init__(self, common, is_gui, mode="share"): self.common = common self.common.log("Web", "__init__", "is_gui={}, mode={}".format(is_gui, mode)) # The flask app self.app = Flask( __name__, static_folder=self.common.get_resource_path("static"), template_folder=self.common.get_resource_path("templates"), ) self.app.secret_key = self.common.random_string(8) # Debug mode? if self.common.debug: self.debug_mode() # Are we running in GUI mode? self.is_gui = is_gui # If the user stops the server while a transfer is in progress, it should # immediately stop the transfer. In order to make it thread-safe, stop_q # is a queue. If anything is in it, then the user stopped the server self.stop_q = queue.Queue() # Are we using receive mode? self.mode = mode if self.mode == "receive": # Use custom WSGI middleware, to modify environ self.app.wsgi_app = ReceiveModeWSGIMiddleware(self.app.wsgi_app, self) # Use a custom Request class to track upload progess self.app.request_class = ReceiveModeRequest # Starting in Flask 0.11, render_template_string autoescapes template variables # by default. To prevent content injection through template variables in # earlier versions of Flask, we force autoescaping in the Jinja2 template # engine if we detect a Flask version with insecure default behavior. if Version(flask_version) < Version("0.11"): # Monkey-patch in the fix from https://github.com/pallets/flask/commit/99c99c4c16b1327288fd76c44bc8635a1de452bc Flask.select_jinja_autoescape = self._safe_select_jinja_autoescape self.security_headers = [ ( "Content-Security-Policy", "default-src 'self'; style-src 'self'; script-src 'self'; img-src 'self' data:;", ), ("X-Frame-Options", "DENY"), ("X-Xss-Protection", "1; mode=block"), ("X-Content-Type-Options", "nosniff"), ("Referrer-Policy", "no-referrer"), ("Server", "OnionShare"), ] self.q = queue.Queue() self.slug = None self.error404_count = 0 self.done = False # shutting down the server only works within the context of flask, so the easiest way to do it is over http self.shutdown_slug = self.common.random_string(16) # Keep track if the server is running self.running = False # Define the web app routes self.define_common_routes() # Create the mode web object, which defines its own routes self.share_mode = None self.receive_mode = None if self.mode == "receive": self.receive_mode = ReceiveModeWeb(self.common, self) elif self.mode == "share": self.share_mode = ShareModeWeb(self.common, self)
def __init__(self, common, is_gui, mode="share"): self.common = common self.common.log("Web", "__init__", "is_gui={}, mode={}".format(is_gui, mode)) # The flask app self.app = Flask( __name__, static_folder=self.common.get_resource_path("static"), template_folder=self.common.get_resource_path("templates"), ) self.app.secret_key = self.common.random_string(8) # Debug mode? if self.common.debug: self.debug_mode() # Are we running in GUI mode? self.is_gui = is_gui # Are we using receive mode? self.mode = mode if self.mode == "receive": # Use custom WSGI middleware, to modify environ self.app.wsgi_app = ReceiveModeWSGIMiddleware(self.app.wsgi_app, self) # Use a custom Request class to track upload progess self.app.request_class = ReceiveModeRequest # Starting in Flask 0.11, render_template_string autoescapes template variables # by default. To prevent content injection through template variables in # earlier versions of Flask, we force autoescaping in the Jinja2 template # engine if we detect a Flask version with insecure default behavior. if Version(flask_version) < Version("0.11"): # Monkey-patch in the fix from https://github.com/pallets/flask/commit/99c99c4c16b1327288fd76c44bc8635a1de452bc Flask.select_jinja_autoescape = self._safe_select_jinja_autoescape self.security_headers = [ ( "Content-Security-Policy", "default-src 'self'; style-src 'self'; script-src 'self'; img-src 'self' data:;", ), ("X-Frame-Options", "DENY"), ("X-Xss-Protection", "1; mode=block"), ("X-Content-Type-Options", "nosniff"), ("Referrer-Policy", "no-referrer"), ("Server", "OnionShare"), ] self.q = queue.Queue() self.slug = None self.error404_count = 0 self.done = False # shutting down the server only works within the context of flask, so the easiest way to do it is over http self.shutdown_slug = self.common.random_string(16) # Keep track if the server is running self.running = False # Define the web app routes self.define_common_routes() # Create the mode web object, which defines its own routes self.share_mode = None self.receive_mode = None if self.mode == "receive": self.receive_mode = ReceiveModeWeb(self.common, self) elif self.mode == "share": self.share_mode = ShareModeWeb(self.common, self)
https://github.com/micahflee/onionshare/issues/866
[Jan 07 2019 20:58:37] Onion.cleanup: trying to remove onion 5yym6w3kg4tof56umfy6a632nvtoc5dkkpkhj4zd2slqzp5wuiwml7yd => 2.4 MiB video 1.mov[Jan 07 2019 20:58:37] ReceiveMode.update_primary_action Traceback (most recent call last): File "onionshare_gui/onionshare_gui.py", line 382, in timer_callback mode.handle_request_progress(event) File "onionshare_gui/mode/receive_mode/__init__.py", line 159, in handle_request_progress 'progress': event["data"]["progress"] File "onionshare_gui/mode/history.py", line 451, in update self.item_list.update(id, data) File "onionshare_gui/mode/history.py", line 347, in update self.items[id].update(data) KeyError: 0 => 2.4 MiB video 1.movAbort trap: 6
KeyError
def start(self, port, stay_open=False, public_mode=False, persistent_slug=None): """ Start the flask web server. """ self.common.log( "Web", "start", "port={}, stay_open={}, public_mode={}, persistent_slug={}".format( port, stay_open, public_mode, persistent_slug ), ) if not public_mode: self.generate_slug(persistent_slug) self.stay_open = stay_open # Make sure the stop_q is empty when starting a new server while not self.stop_q.empty(): try: self.stop_q.get(block=False) except queue.Empty: pass # In Whonix, listen on 0.0.0.0 instead of 127.0.0.1 (#220) if os.path.exists("/usr/share/anon-ws-base-files/workstation"): host = "0.0.0.0" else: host = "127.0.0.1" self.running = True self.app.run(host=host, port=port, threaded=True)
def start(self, port, stay_open=False, public_mode=False, persistent_slug=None): """ Start the flask web server. """ self.common.log( "Web", "start", "port={}, stay_open={}, public_mode={}, persistent_slug={}".format( port, stay_open, public_mode, persistent_slug ), ) if not public_mode: self.generate_slug(persistent_slug) self.stay_open = stay_open # In Whonix, listen on 0.0.0.0 instead of 127.0.0.1 (#220) if os.path.exists("/usr/share/anon-ws-base-files/workstation"): host = "0.0.0.0" else: host = "127.0.0.1" self.running = True self.app.run(host=host, port=port, threaded=True)
https://github.com/micahflee/onionshare/issues/866
[Jan 07 2019 20:58:37] Onion.cleanup: trying to remove onion 5yym6w3kg4tof56umfy6a632nvtoc5dkkpkhj4zd2slqzp5wuiwml7yd => 2.4 MiB video 1.mov[Jan 07 2019 20:58:37] ReceiveMode.update_primary_action Traceback (most recent call last): File "onionshare_gui/onionshare_gui.py", line 382, in timer_callback mode.handle_request_progress(event) File "onionshare_gui/mode/receive_mode/__init__.py", line 159, in handle_request_progress 'progress': event["data"]["progress"] File "onionshare_gui/mode/history.py", line 451, in update self.item_list.update(id, data) File "onionshare_gui/mode/history.py", line 347, in update self.items[id].update(data) KeyError: 0 => 2.4 MiB video 1.movAbort trap: 6
KeyError
def stop(self, port): """ Stop the flask web server by loading /shutdown. """ self.common.log("Web", "stop", "stopping server") # Let the mode know that the user stopped the server self.stop_q.put(True) # To stop flask, load http://127.0.0.1:<port>/<shutdown_slug>/shutdown if self.running: try: s = socket.socket() s.connect(("127.0.0.1", port)) s.sendall("GET /{0:s}/shutdown HTTP/1.1\r\n\r\n".format(self.shutdown_slug)) except: try: urlopen( "http://127.0.0.1:{0:d}/{1:s}/shutdown".format( port, self.shutdown_slug ) ).read() except: pass
def stop(self, port): """ Stop the flask web server by loading /shutdown. """ if self.mode == "share": # If the user cancels the download, let the download function know to stop # serving the file self.share_mode.client_cancel = True # To stop flask, load http://127.0.0.1:<port>/<shutdown_slug>/shutdown if self.running: try: s = socket.socket() s.connect(("127.0.0.1", port)) s.sendall("GET /{0:s}/shutdown HTTP/1.1\r\n\r\n".format(self.shutdown_slug)) except: try: urlopen( "http://127.0.0.1:{0:d}/{1:s}/shutdown".format( port, self.shutdown_slug ) ).read() except: pass
https://github.com/micahflee/onionshare/issues/866
[Jan 07 2019 20:58:37] Onion.cleanup: trying to remove onion 5yym6w3kg4tof56umfy6a632nvtoc5dkkpkhj4zd2slqzp5wuiwml7yd => 2.4 MiB video 1.mov[Jan 07 2019 20:58:37] ReceiveMode.update_primary_action Traceback (most recent call last): File "onionshare_gui/onionshare_gui.py", line 382, in timer_callback mode.handle_request_progress(event) File "onionshare_gui/mode/receive_mode/__init__.py", line 159, in handle_request_progress 'progress': event["data"]["progress"] File "onionshare_gui/mode/history.py", line 451, in update self.item_list.update(id, data) File "onionshare_gui/mode/history.py", line 347, in update self.items[id].update(data) KeyError: 0 => 2.4 MiB video 1.movAbort trap: 6
KeyError
def get_finished_label_text(self, started): """ When an item finishes, returns a string displaying the start/end datetime range. started is a datetime object. """ return self._get_label_text( "gui_all_modes_transfer_finished", "gui_all_modes_transfer_finished_range", started, )
def get_finished_label_text(self, started): """ When an item finishes, returns a string displaying the start/end datetime range. started is a datetime object. """ ended = datetime.now() if ( started.year == ended.year and started.month == ended.month and started.day == ended.day ): if started.hour == ended.hour and started.minute == ended.minute: text = strings._("gui_all_modes_transfer_finished").format( started.strftime("%b %d, %I:%M%p") ) else: text = strings._("gui_all_modes_transfer_finished_range").format( started.strftime("%b %d, %I:%M%p"), ended.strftime("%I:%M%p") ) else: text = strings._("gui_all_modes_transfer_finished_range").format( started.strftime("%b %d, %I:%M%p"), ended.strftime("%b %d, %I:%M%p") ) return text
https://github.com/micahflee/onionshare/issues/866
[Jan 07 2019 20:58:37] Onion.cleanup: trying to remove onion 5yym6w3kg4tof56umfy6a632nvtoc5dkkpkhj4zd2slqzp5wuiwml7yd => 2.4 MiB video 1.mov[Jan 07 2019 20:58:37] ReceiveMode.update_primary_action Traceback (most recent call last): File "onionshare_gui/onionshare_gui.py", line 382, in timer_callback mode.handle_request_progress(event) File "onionshare_gui/mode/receive_mode/__init__.py", line 159, in handle_request_progress 'progress': event["data"]["progress"] File "onionshare_gui/mode/history.py", line 451, in update self.item_list.update(id, data) File "onionshare_gui/mode/history.py", line 347, in update self.items[id].update(data) KeyError: 0 => 2.4 MiB video 1.movAbort trap: 6
KeyError
def update(self, data): """ Using the progress from Web, update the progress bar and file size labels for each file """ if data["action"] == "progress": total_uploaded_bytes = 0 for filename in data["progress"]: total_uploaded_bytes += data["progress"][filename]["uploaded_bytes"] # Update the progress bar self.progress_bar.setMaximum(self.content_length) self.progress_bar.setValue(total_uploaded_bytes) elapsed = datetime.now() - self.started if elapsed.seconds < 10: pb_fmt = strings._("gui_all_modes_progress_starting").format( self.common.human_readable_filesize(total_uploaded_bytes) ) else: estimated_time_remaining = self.common.estimated_time_remaining( total_uploaded_bytes, self.content_length, self.started.timestamp() ) pb_fmt = strings._("gui_all_modes_progress_eta").format( self.common.human_readable_filesize(total_uploaded_bytes), estimated_time_remaining, ) # Using list(progress) to avoid "RuntimeError: dictionary changed size during iteration" for filename in list(data["progress"]): # Add a new file if needed if filename not in self.files: self.files[filename] = ReceiveHistoryItemFile(self.common, filename) self.files_layout.addWidget(self.files[filename]) # Update the file self.files[filename].update( data["progress"][filename]["uploaded_bytes"], data["progress"][filename]["complete"], ) elif data["action"] == "rename": self.files[data["old_filename"]].rename(data["new_filename"]) self.files[data["new_filename"]] = self.files.pop(data["old_filename"]) elif data["action"] == "set_dir": self.files[data["filename"]].set_dir(data["dir"]) elif data["action"] == "finished": # Hide the progress bar self.progress_bar.hide() # Change the label self.label.setText(self.get_finished_label_text(self.started)) elif data["action"] == "canceled": # Hide the progress bar self.progress_bar.hide() # Change the label self.label.setText(self.get_canceled_label_text(self.started))
def update(self, data): """ Using the progress from Web, update the progress bar and file size labels for each file """ if data["action"] == "progress": total_uploaded_bytes = 0 for filename in data["progress"]: total_uploaded_bytes += data["progress"][filename]["uploaded_bytes"] # Update the progress bar self.progress_bar.setMaximum(self.content_length) self.progress_bar.setValue(total_uploaded_bytes) elapsed = datetime.now() - self.started if elapsed.seconds < 10: pb_fmt = strings._("gui_all_modes_progress_starting").format( self.common.human_readable_filesize(total_uploaded_bytes) ) else: estimated_time_remaining = self.common.estimated_time_remaining( total_uploaded_bytes, self.content_length, self.started.timestamp() ) pb_fmt = strings._("gui_all_modes_progress_eta").format( self.common.human_readable_filesize(total_uploaded_bytes), estimated_time_remaining, ) # Using list(progress) to avoid "RuntimeError: dictionary changed size during iteration" for filename in list(data["progress"]): # Add a new file if needed if filename not in self.files: self.files[filename] = ReceiveHistoryItemFile(self.common, filename) self.files_layout.addWidget(self.files[filename]) # Update the file self.files[filename].update( data["progress"][filename]["uploaded_bytes"], data["progress"][filename]["complete"], ) elif data["action"] == "rename": self.files[data["old_filename"]].rename(data["new_filename"]) self.files[data["new_filename"]] = self.files.pop(data["old_filename"]) elif data["action"] == "set_dir": self.files[data["filename"]].set_dir(data["dir"]) elif data["action"] == "finished": # Hide the progress bar self.progress_bar.hide() # Change the label self.label.setText(self.get_finished_label_text(self.started))
https://github.com/micahflee/onionshare/issues/866
[Jan 07 2019 20:58:37] Onion.cleanup: trying to remove onion 5yym6w3kg4tof56umfy6a632nvtoc5dkkpkhj4zd2slqzp5wuiwml7yd => 2.4 MiB video 1.mov[Jan 07 2019 20:58:37] ReceiveMode.update_primary_action Traceback (most recent call last): File "onionshare_gui/onionshare_gui.py", line 382, in timer_callback mode.handle_request_progress(event) File "onionshare_gui/mode/receive_mode/__init__.py", line 159, in handle_request_progress 'progress': event["data"]["progress"] File "onionshare_gui/mode/history.py", line 451, in update self.item_list.update(id, data) File "onionshare_gui/mode/history.py", line 347, in update self.items[id].update(data) KeyError: 0 => 2.4 MiB video 1.movAbort trap: 6
KeyError
def init(self): """ Custom initialization for ReceiveMode. """ # Create the Web object self.web = Web(self.common, True, "receive") # Server status self.server_status.set_mode("receive") self.server_status.server_started_finished.connect(self.update_primary_action) self.server_status.server_stopped.connect(self.update_primary_action) self.server_status.server_canceled.connect(self.update_primary_action) # Tell server_status about web, then update self.server_status.web = self.web self.server_status.update() # Upload history self.history = History( self.common, QtGui.QPixmap.fromImage( QtGui.QImage( self.common.get_resource_path("images/receive_icon_transparent.png") ) ), strings._("gui_receive_mode_no_files"), strings._("gui_all_modes_history"), ) self.history.hide() # Toggle history self.toggle_history = ToggleHistory( self.common, self, self.history, QtGui.QIcon(self.common.get_resource_path("images/receive_icon_toggle.png")), QtGui.QIcon( self.common.get_resource_path("images/receive_icon_toggle_selected.png") ), ) # Receive mode warning receive_warning = QtWidgets.QLabel(strings._("gui_receive_mode_warning")) receive_warning.setMinimumHeight(80) receive_warning.setWordWrap(True) # Top bar top_bar_layout = QtWidgets.QHBoxLayout() top_bar_layout.addStretch() top_bar_layout.addWidget(self.toggle_history) # Main layout self.main_layout = QtWidgets.QVBoxLayout() self.main_layout.addLayout(top_bar_layout) self.main_layout.addWidget(receive_warning) self.main_layout.addWidget(self.primary_action) self.main_layout.addStretch() self.main_layout.addWidget(self.min_width_widget) # Wrapper layout self.wrapper_layout = QtWidgets.QHBoxLayout() self.wrapper_layout.addLayout(self.main_layout) self.wrapper_layout.addWidget(self.history, stretch=1) self.setLayout(self.wrapper_layout)
def init(self): """ Custom initialization for ReceiveMode. """ # Create the Web object self.web = Web(self.common, True, "receive") # Server status self.server_status.set_mode("receive") self.server_status.server_started_finished.connect(self.update_primary_action) self.server_status.server_stopped.connect(self.update_primary_action) self.server_status.server_canceled.connect(self.update_primary_action) # Tell server_status about web, then update self.server_status.web = self.web self.server_status.update() # Upload history self.history = History( self.common, QtGui.QPixmap.fromImage( QtGui.QImage( self.common.get_resource_path("images/receive_icon_transparent.png") ) ), strings._("gui_receive_mode_no_files"), strings._("gui_all_modes_history"), ) self.history.hide() # Toggle history self.toggle_history = ToggleHistory( self.common, self, self.history, QtGui.QIcon(self.common.get_resource_path("images/receive_icon_toggle.png")), QtGui.QIcon( self.common.get_resource_path("images/receive_icon_toggle_selected.png") ), ) # Receive mode warning receive_warning = QtWidgets.QLabel(strings._("gui_receive_mode_warning")) receive_warning.setMinimumHeight(80) receive_warning.setWordWrap(True) # Top bar top_bar_layout = QtWidgets.QHBoxLayout() top_bar_layout.addStretch() top_bar_layout.addWidget(self.toggle_history) # Main layout self.main_layout = QtWidgets.QVBoxLayout() self.main_layout.addLayout(top_bar_layout) self.main_layout.addWidget(receive_warning) self.main_layout.addWidget(self.primary_action) self.main_layout.addStretch() self.main_layout.addWidget(self.min_width_widget) # Wrapper layout self.wrapper_layout = QtWidgets.QHBoxLayout() self.wrapper_layout.addLayout(self.main_layout) self.wrapper_layout.addWidget(self.history) self.setLayout(self.wrapper_layout)
https://github.com/micahflee/onionshare/issues/866
[Jan 07 2019 20:58:37] Onion.cleanup: trying to remove onion 5yym6w3kg4tof56umfy6a632nvtoc5dkkpkhj4zd2slqzp5wuiwml7yd => 2.4 MiB video 1.mov[Jan 07 2019 20:58:37] ReceiveMode.update_primary_action Traceback (most recent call last): File "onionshare_gui/onionshare_gui.py", line 382, in timer_callback mode.handle_request_progress(event) File "onionshare_gui/mode/receive_mode/__init__.py", line 159, in handle_request_progress 'progress': event["data"]["progress"] File "onionshare_gui/mode/history.py", line 451, in update self.item_list.update(id, data) File "onionshare_gui/mode/history.py", line 347, in update self.items[id].update(data) KeyError: 0 => 2.4 MiB video 1.movAbort trap: 6
KeyError
def init(self): """ Custom initialization for ReceiveMode. """ # Threads start out as None self.compress_thread = None # Create the Web object self.web = Web(self.common, True, "share") # File selection self.file_selection = FileSelection(self.common, self) if self.filenames: for filename in self.filenames: self.file_selection.file_list.add_file(filename) # Server status self.server_status.set_mode("share", self.file_selection) self.server_status.server_started.connect(self.file_selection.server_started) self.server_status.server_stopped.connect(self.file_selection.server_stopped) self.server_status.server_stopped.connect(self.update_primary_action) self.server_status.server_canceled.connect(self.file_selection.server_stopped) self.server_status.server_canceled.connect(self.update_primary_action) self.file_selection.file_list.files_updated.connect(self.server_status.update) self.file_selection.file_list.files_updated.connect(self.update_primary_action) # Tell server_status about web, then update self.server_status.web = self.web self.server_status.update() # Filesize warning self.filesize_warning = QtWidgets.QLabel() self.filesize_warning.setWordWrap(True) self.filesize_warning.setStyleSheet(self.common.css["share_filesize_warning"]) self.filesize_warning.hide() # Download history self.history = History( self.common, QtGui.QPixmap.fromImage( QtGui.QImage( self.common.get_resource_path("images/share_icon_transparent.png") ) ), strings._("gui_share_mode_no_files"), strings._("gui_all_modes_history"), ) self.history.hide() # Info label self.info_label = QtWidgets.QLabel() self.info_label.hide() # Toggle history self.toggle_history = ToggleHistory( self.common, self, self.history, QtGui.QIcon(self.common.get_resource_path("images/share_icon_toggle.png")), QtGui.QIcon( self.common.get_resource_path("images/share_icon_toggle_selected.png") ), ) # Top bar top_bar_layout = QtWidgets.QHBoxLayout() top_bar_layout.addWidget(self.info_label) top_bar_layout.addStretch() top_bar_layout.addWidget(self.toggle_history) # Primary action layout self.primary_action_layout.addWidget(self.filesize_warning) self.primary_action.hide() self.update_primary_action() # Status bar, zip progress bar self._zip_progress_bar = None # Main layout self.main_layout = QtWidgets.QVBoxLayout() self.main_layout.addLayout(top_bar_layout) self.main_layout.addLayout(self.file_selection) self.main_layout.addWidget(self.primary_action) self.main_layout.addWidget(self.min_width_widget) # Wrapper layout self.wrapper_layout = QtWidgets.QHBoxLayout() self.wrapper_layout.addLayout(self.main_layout) self.wrapper_layout.addWidget(self.history, stretch=1) self.setLayout(self.wrapper_layout) # Always start with focus on file selection self.file_selection.setFocus()
def init(self): """ Custom initialization for ReceiveMode. """ # Threads start out as None self.compress_thread = None # Create the Web object self.web = Web(self.common, True, "share") # File selection self.file_selection = FileSelection(self.common, self) if self.filenames: for filename in self.filenames: self.file_selection.file_list.add_file(filename) # Server status self.server_status.set_mode("share", self.file_selection) self.server_status.server_started.connect(self.file_selection.server_started) self.server_status.server_stopped.connect(self.file_selection.server_stopped) self.server_status.server_stopped.connect(self.update_primary_action) self.server_status.server_canceled.connect(self.file_selection.server_stopped) self.server_status.server_canceled.connect(self.update_primary_action) self.file_selection.file_list.files_updated.connect(self.server_status.update) self.file_selection.file_list.files_updated.connect(self.update_primary_action) # Tell server_status about web, then update self.server_status.web = self.web self.server_status.update() # Filesize warning self.filesize_warning = QtWidgets.QLabel() self.filesize_warning.setWordWrap(True) self.filesize_warning.setStyleSheet(self.common.css["share_filesize_warning"]) self.filesize_warning.hide() # Download history self.history = History( self.common, QtGui.QPixmap.fromImage( QtGui.QImage( self.common.get_resource_path("images/share_icon_transparent.png") ) ), strings._("gui_share_mode_no_files"), strings._("gui_all_modes_history"), ) self.history.hide() # Info label self.info_label = QtWidgets.QLabel() self.info_label.hide() # Toggle history self.toggle_history = ToggleHistory( self.common, self, self.history, QtGui.QIcon(self.common.get_resource_path("images/share_icon_toggle.png")), QtGui.QIcon( self.common.get_resource_path("images/share_icon_toggle_selected.png") ), ) # Top bar top_bar_layout = QtWidgets.QHBoxLayout() top_bar_layout.addWidget(self.info_label) top_bar_layout.addStretch() top_bar_layout.addWidget(self.toggle_history) # Primary action layout self.primary_action_layout.addWidget(self.filesize_warning) self.primary_action.hide() self.update_primary_action() # Status bar, zip progress bar self._zip_progress_bar = None # Main layout self.main_layout = QtWidgets.QVBoxLayout() self.main_layout.addLayout(top_bar_layout) self.main_layout.addLayout(self.file_selection) self.main_layout.addWidget(self.primary_action) self.main_layout.addWidget(self.min_width_widget) # Wrapper layout self.wrapper_layout = QtWidgets.QHBoxLayout() self.wrapper_layout.addLayout(self.main_layout) self.wrapper_layout.addWidget(self.history) self.setLayout(self.wrapper_layout) # Always start with focus on file selection self.file_selection.setFocus()
https://github.com/micahflee/onionshare/issues/866
[Jan 07 2019 20:58:37] Onion.cleanup: trying to remove onion 5yym6w3kg4tof56umfy6a632nvtoc5dkkpkhj4zd2slqzp5wuiwml7yd => 2.4 MiB video 1.mov[Jan 07 2019 20:58:37] ReceiveMode.update_primary_action Traceback (most recent call last): File "onionshare_gui/onionshare_gui.py", line 382, in timer_callback mode.handle_request_progress(event) File "onionshare_gui/mode/receive_mode/__init__.py", line 159, in handle_request_progress 'progress': event["data"]["progress"] File "onionshare_gui/mode/history.py", line 451, in update self.item_list.update(id, data) File "onionshare_gui/mode/history.py", line 347, in update self.items[id].update(data) KeyError: 0 => 2.4 MiB video 1.movAbort trap: 6
KeyError
def timer_callback(self): """ Check for messages communicated from the web app, and update the GUI accordingly. Also, call ShareMode and ReceiveMode's timer_callbacks. """ self.update() if not self.local_only: # Have we lost connection to Tor somehow? if not self.onion.is_authenticated(): self.timer.stop() self.status_bar.showMessage(strings._("gui_tor_connection_lost")) self.system_tray.showMessage( strings._("gui_tor_connection_lost"), strings._("gui_tor_connection_error_settings"), ) self.share_mode.handle_tor_broke() self.receive_mode.handle_tor_broke() # Process events from the web object if self.mode == self.MODE_SHARE: mode = self.share_mode else: mode = self.receive_mode events = [] done = False while not done: try: r = mode.web.q.get(False) events.append(r) except queue.Empty: done = True for event in events: if event["type"] == Web.REQUEST_LOAD: mode.handle_request_load(event) elif event["type"] == Web.REQUEST_STARTED: mode.handle_request_started(event) elif event["type"] == Web.REQUEST_RATE_LIMIT: mode.handle_request_rate_limit(event) elif event["type"] == Web.REQUEST_PROGRESS: mode.handle_request_progress(event) elif event["type"] == Web.REQUEST_CANCELED: mode.handle_request_canceled(event) elif event["type"] == Web.REQUEST_UPLOAD_FILE_RENAMED: mode.handle_request_upload_file_renamed(event) elif event["type"] == Web.REQUEST_UPLOAD_SET_DIR: mode.handle_request_upload_set_dir(event) elif event["type"] == Web.REQUEST_UPLOAD_FINISHED: mode.handle_request_upload_finished(event) elif event["type"] == Web.REQUEST_UPLOAD_CANCELED: mode.handle_request_upload_canceled(event) if event["type"] == Web.REQUEST_ERROR_DATA_DIR_CANNOT_CREATE: Alert( self.common, strings._("error_cannot_create_data_dir").format( event["data"]["receive_mode_dir"] ), ) if event["type"] == Web.REQUEST_OTHER: if event["path"] != "/favicon.ico" and event[ "path" ] != "/{}/shutdown".format(mode.web.shutdown_slug): self.status_bar.showMessage( "[#{0:d}] {1:s}: {2:s}".format( mode.web.error404_count, strings._("other_page_loaded"), event["path"], ) ) mode.timer_callback()
def timer_callback(self): """ Check for messages communicated from the web app, and update the GUI accordingly. Also, call ShareMode and ReceiveMode's timer_callbacks. """ self.update() if not self.local_only: # Have we lost connection to Tor somehow? if not self.onion.is_authenticated(): self.timer.stop() self.status_bar.showMessage(strings._("gui_tor_connection_lost")) self.system_tray.showMessage( strings._("gui_tor_connection_lost"), strings._("gui_tor_connection_error_settings"), ) self.share_mode.handle_tor_broke() self.receive_mode.handle_tor_broke() # Process events from the web object if self.mode == self.MODE_SHARE: mode = self.share_mode else: mode = self.receive_mode events = [] done = False while not done: try: r = mode.web.q.get(False) events.append(r) except queue.Empty: done = True for event in events: if event["type"] == Web.REQUEST_LOAD: mode.handle_request_load(event) elif event["type"] == Web.REQUEST_STARTED: mode.handle_request_started(event) elif event["type"] == Web.REQUEST_RATE_LIMIT: mode.handle_request_rate_limit(event) elif event["type"] == Web.REQUEST_PROGRESS: mode.handle_request_progress(event) elif event["type"] == Web.REQUEST_CANCELED: mode.handle_request_canceled(event) elif event["type"] == Web.REQUEST_UPLOAD_FILE_RENAMED: mode.handle_request_upload_file_renamed(event) elif event["type"] == Web.REQUEST_UPLOAD_SET_DIR: mode.handle_request_upload_set_dir(event) elif event["type"] == Web.REQUEST_UPLOAD_FINISHED: mode.handle_request_upload_finished(event) if event["type"] == Web.REQUEST_ERROR_DATA_DIR_CANNOT_CREATE: Alert( self.common, strings._("error_cannot_create_data_dir").format( event["data"]["receive_mode_dir"] ), ) if event["type"] == Web.REQUEST_OTHER: if event["path"] != "/favicon.ico" and event[ "path" ] != "/{}/shutdown".format(mode.web.shutdown_slug): self.status_bar.showMessage( "[#{0:d}] {1:s}: {2:s}".format( mode.web.error404_count, strings._("other_page_loaded"), event["path"], ) ) mode.timer_callback()
https://github.com/micahflee/onionshare/issues/866
[Jan 07 2019 20:58:37] Onion.cleanup: trying to remove onion 5yym6w3kg4tof56umfy6a632nvtoc5dkkpkhj4zd2slqzp5wuiwml7yd => 2.4 MiB video 1.mov[Jan 07 2019 20:58:37] ReceiveMode.update_primary_action Traceback (most recent call last): File "onionshare_gui/onionshare_gui.py", line 382, in timer_callback mode.handle_request_progress(event) File "onionshare_gui/mode/receive_mode/__init__.py", line 159, in handle_request_progress 'progress': event["data"]["progress"] File "onionshare_gui/mode/history.py", line 451, in update self.item_list.update(id, data) File "onionshare_gui/mode/history.py", line 347, in update self.items[id].update(data) KeyError: 0 => 2.4 MiB video 1.movAbort trap: 6
KeyError
def build_data_dir(self): """ Returns the path of the OnionShare data directory. """ if self.platform == "Windows": try: appdata = os.environ["APPDATA"] onionshare_data_dir = "{}\\OnionShare".format(appdata) except: # If for some reason we don't have the 'APPDATA' environment variable # (like running tests in Linux while pretending to be in Windows) onionshare_data_dir = "~/.config/onionshare" elif self.platform == "Darwin": onionshare_data_dir = "~/Library/Application Support/OnionShare" else: onionshare_data_dir = "~/.config/onionshare" os.makedirs(onionshare_data_dir, 0o700, True) return onionshare_data_dir
def build_data_dir(self): """ Returns the path of the OnionShare data directory. """ if self.platform == "Windows": try: appdata = os.environ["APPDATA"] return "{}\\OnionShare".format(appdata) except: # If for some reason we don't have the 'APPDATA' environment variable # (like running tests in Linux while pretending to be in Windows) return os.path.expanduser("~/.config/onionshare") elif self.platform == "Darwin": return os.path.expanduser("~/Library/Application Support/OnionShare") else: return os.path.expanduser("~/.config/onionshare")
https://github.com/micahflee/onionshare/issues/850
OnionShare 2.0.dev1 | https://onionshare.org/ [Dec 19 2018 03:36:17 PM] Onion.__init__ [Dec 19 2018 03:36:17 PM] OnionShare.__init__ [Dec 19 2018 03:36:17 PM] OnionShareGui.__init__ [Dec 19 2018 03:36:18 PM] Web.__init__: is_gui=True, mode=share Traceback (most recent call last): File "./dev_scripts/onionshare-gui", line 28, in <module> onionshare_gui.main() File "/home/kevin/dev/onionshare/onionshare_gui/__init__.py", line 126, in main gui = OnionShareGui(common, onion, qtapp, app, filenames, config, local_only) File "/home/kevin/dev/onionshare/onionshare_gui/onionshare_gui.py", line 127, in __init__ self.share_mode.init() File "/home/kevin/dev/onionshare/onionshare_gui/mode/share_mode/__init__.py", line 47, in init self.web = Web(self.common, True, 'share') File "/home/kevin/dev/onionshare/onionshare/web/web.py", line 56, in __init__ self.debug_mode() File "/home/kevin/dev/onionshare/onionshare/web/web.py", line 188, in debug_mode log_handler = logging.FileHandler(flask_debug_filename) File "/usr/lib/python3.7/logging/__init__.py", line 1092, in __init__ StreamHandler.__init__(self, self._open()) File "/usr/lib/python3.7/logging/__init__.py", line 1121, in _open return open(self.baseFilename, self.mode, encoding=self.encoding) FileNotFoundError: [Errno 2] No such file or directory: '/home/kevin/.config/onionshare/flask_debug.log'```
FileNotFoundError
def cancel(self): self.mode.common.log("CompressThread", "cancel") # Let the Web and ZipWriter objects know that we're canceling compression early self.mode.web.cancel_compression = True try: self.mode.web.zip_writer.cancel_compression = True except AttributeError: # we never made it as far as creating a ZipWriter object pass
def cancel(self): self.mode.common.log("CompressThread", "cancel") # Let the Web and ZipWriter objects know that we're canceling compression early self.mode.web.cancel_compression = True if self.mode.web.zip_writer: self.mode.web.zip_writer.cancel_compression = True
https://github.com/micahflee/onionshare/issues/790
[Sep 24 2018 23:15:34] Web.check_shutdown_slug_candidate: slug_candidate=ymf5eposfwver2gpegmic5drki 127.0.0.1 - - [24/Sep/2018 23:15:34] "GET /ymf5eposfwver2gpegmic5drki/shutdown HTTP/1.1" 200 - [Sep 24 2018 23:15:34] OnionShare.cleanup [Sep 24 2018 23:15:34] Onion.cleanup [Sep 24 2018 23:15:34] Onion.cleanup: trying to remove onion dfi5lhiakae2ztq2t4qd7xh2khrnddsfwldkeczafznfoitua7wbj5yd [Sep 24 2018 23:15:34] CompressThread.cancel Traceback (most recent call last): File "onionshare_gui/share_mode/threads.py", line 59, in cancel AttributeError: 'Web' object has no attribute 'zip_writer' Abort trap: 6
AttributeError
def __init__(self, environ, populate_request=True, shallow=False): super(ReceiveModeRequest, self).__init__(environ, populate_request, shallow) self.web = environ["web"] # Is this a valid upload request? self.upload_request = False if self.method == "POST": if self.path == "/{}/upload".format(self.web.slug): self.upload_request = True else: if self.web.common.settings.get("public_mode"): if self.path == "/upload": self.upload_request = True if self.upload_request: # A dictionary that maps filenames to the bytes uploaded so far self.progress = {} # Create an upload_id, attach it to the request self.upload_id = self.web.receive_mode.upload_count self.web.receive_mode.upload_count += 1 # Figure out the content length try: self.content_length = int(self.headers["Content-Length"]) except: self.content_length = 0 print( "{}: {}".format( datetime.now().strftime("%b %d, %I:%M%p"), strings._("receive_mode_upload_starting").format( self.web.common.human_readable_filesize(self.content_length) ), ) ) # Tell the GUI self.web.add_request( self.web.REQUEST_STARTED, self.path, {"id": self.upload_id, "content_length": self.content_length}, ) self.previous_file = None
def __init__(self, environ, populate_request=True, shallow=False): super(ReceiveModeRequest, self).__init__(environ, populate_request, shallow) self.web = environ["web"] # Is this a valid upload request? self.upload_request = False if self.method == "POST": if self.path == "/{}/upload".format(self.web.slug): self.upload_request = True else: if self.web.common.settings.get("public_mode"): if self.path == "/upload": self.upload_request = True if self.upload_request: # A dictionary that maps filenames to the bytes uploaded so far self.progress = {} # Create an upload_id, attach it to the request self.upload_id = self.upload_count self.upload_count += 1 # Figure out the content length try: self.content_length = int(self.headers["Content-Length"]) except: self.content_length = 0 print( "{}: {}".format( datetime.now().strftime("%b %d, %I:%M%p"), strings._("receive_mode_upload_starting").format( self.web.common.human_readable_filesize(self.content_length) ), ) ) # Tell the GUI self.web.add_request( self.web.REQUEST_STARTED, self.path, {"id": self.upload_id, "content_length": self.content_length}, ) self.previous_file = None
https://github.com/micahflee/onionshare/issues/781
[Sep 22 2018 10:19:11 AM] Web.check_slug_candidate: slug_candidate=leggings-cornea 127.0.0.1 - - [22/Sep/2018 10:19:11] "GET /leggings-cornea HTTP/1.1" 200 - 127.0.0.1 - - [22/Sep/2018 10:19:15] "GET /static/css/style.css HTTP/1.1" 200 - 127.0.0.1 - - [22/Sep/2018 10:19:16] "GET /static/img/logo.png HTTP/1.1" 200 - 127.0.0.1 - - [22/Sep/2018 10:19:16] "GET /static/img/logo_large.png HTTP/1.1" 200 - 127.0.0.1 - - [22/Sep/2018 10:19:17] "GET /static/img/favicon.ico HTTP/1.1" 200 - 127.0.0.1 - - [22/Sep/2018 10:19:33] "POST /leggings-cornea/upload HTTP/1.1" 500 - Error on request: Traceback (most recent call last): File "/usr/lib/python3/dist-packages/werkzeug/serving.py", line 205, in run_wsgi execute(self.server.app) File "/usr/lib/python3/dist-packages/werkzeug/serving.py", line 193, in execute application_iter = app(environ, start_response) File "/usr/lib/python3/dist-packages/flask/app.py", line 1997, in __call__ return self.wsgi_app(environ, start_response) File "/home/user/git/onionshare/onionshare/web/receive_mode.py", line 188, in __call__ return self.app(environ, start_response) File "/usr/lib/python3/dist-packages/flask/app.py", line 1977, in wsgi_app ctx = self.request_context(environ) File "/usr/lib/python3/dist-packages/flask/app.py", line 1938, in request_context return RequestContext(self, environ) File "/usr/lib/python3/dist-packages/flask/ctx.py", line 240, in __init__ request = app.request_class(environ) File "/home/user/git/onionshare/onionshare/web/receive_mode.py", line 252, in __init__ self.upload_id = self.upload_count AttributeError: 'ReceiveModeRequest' object has no attribute 'upload_count'
AttributeError
def run(self): self.mode.common.log("OnionThread", "run") self.mode.app.stay_open = not self.mode.common.settings.get( "close_after_first_download" ) # start onionshare http service in new thread self.mode.web_thread = WebThread(self.mode) self.mode.web_thread.start() # wait for modules in thread to load, preventing a thread-related cx_Freeze crash time.sleep(0.2) try: self.mode.app.start_onion_service() self.success.emit() except ( TorTooOld, TorErrorInvalidSetting, TorErrorAutomatic, TorErrorSocketPort, TorErrorSocketFile, TorErrorMissingPassword, TorErrorUnreadableCookieFile, TorErrorAuthError, TorErrorProtocolError, BundledTorTimeout, OSError, ) as e: self.error.emit(e.args[0]) return
def run(self): self.mode.common.log("OnionThread", "run") try: self.mode.app.start_onion_service() self.success.emit() except ( TorTooOld, TorErrorInvalidSetting, TorErrorAutomatic, TorErrorSocketPort, TorErrorSocketFile, TorErrorMissingPassword, TorErrorUnreadableCookieFile, TorErrorAuthError, TorErrorProtocolError, BundledTorTimeout, OSError, ) as e: self.error.emit(e.args[0]) return self.mode.app.stay_open = not self.mode.common.settings.get( "close_after_first_download" ) # start onionshare http service in new thread self.mode.web_thread = WebThread(self.mode) self.mode.web_thread.start() # wait for modules in thread to load, preventing a thread-related cx_Freeze crash time.sleep(0.2)
https://github.com/micahflee/onionshare/issues/764
user@onionshare:~/git/onionshare$ ./dev_scripts/onionshare-gui --debug OnionShare 2.0.dev | https://onionshare.org/ [Sep 19 2018 02:14:55 PM] Onion.__init__ [Sep 19 2018 02:14:55 PM] OnionShare.__init__ [Sep 19 2018 02:14:55 PM] OnionShareGui.__init__ [Sep 19 2018 02:14:55 PM] Settings.__init__ [Sep 19 2018 02:14:55 PM] Settings.load [Sep 19 2018 02:14:55 PM] Settings.load: Trying to load /home/user/.config/onionshare/onionshare.json [Sep 19 2018 02:14:55 PM] Uploads.__init__ [Sep 19 2018 02:14:56 PM] TorConnectionDialog.__init__ [Sep 19 2018 02:14:56 PM] TorConnectionDialog.start [Sep 19 2018 02:14:56 PM] TorConnectionThread.__init__ [Sep 19 2018 02:14:56 PM] TorConnectionThread.run [Sep 19 2018 02:14:56 PM] Onion.connect [Sep 19 2018 02:14:56 PM] TorConnectionDialog._connected_to_tor [Sep 19 2018 02:14:56 PM] OnionShareGui.receive_mode_clicked [Sep 19 2018 02:14:57 PM] Mode.start_server [Sep 19 2018 02:14:57 PM] Uploads.reset [Sep 19 2018 02:14:57 PM] OnionShare.set_stealth: stealth=False [Sep 19 2018 02:14:57 PM] Mode.start_server: Starting an onion thread [Sep 19 2018 02:14:57 PM] OnionThread.__init__ [Sep 19 2018 02:14:57 PM] OnionThread.run [Sep 19 2018 02:14:57 PM] OnionShare.start_onion_service [Sep 19 2018 02:14:57 PM] Onion.start_onion_service Configuring onion service on port 17610. Starting ephemeral Tor onion service and awaiting publication [Sep 19 2018 02:14:57 PM] Onion.start_onion_service: key_type=ED25519-V3 [Sep 19 2018 02:16:06 PM] Settings.save Settings saved to /home/user/.config/onionshare/onionshare.json [Sep 19 2018 02:16:06 PM] WebThread.__init__ [Sep 19 2018 02:16:06 PM] WebThread.run [Sep 19 2018 02:16:06 PM] Web.start: port=17610, stay_open=True, persistent_slug=None [Sep 19 2018 02:16:06 PM] Web.generate_slug: persistent_slug=None [Sep 19 2018 02:16:06 PM] Mode.start_server_step2 [Sep 19 2018 02:16:06 PM] Mode.start_server_step3 [Sep 19 2018 02:16:06 PM] Web.generate_slug: built random slug: "carnation-banner" Traceback (most recent call last): File "/home/user/git/onionshare/onionshare_gui/server_status.py", line 286, in start_server_finished self.copy_url() File "/home/user/git/onionshare/onionshare_gui/server_status.py", line 321, in copy_url clipboard.setText(self.get_url()) File "/home/user/git/onionshare/onionshare_gui/server_status.py", line 341, in get_url url = 'http://{0:s}/{1:s}'.format(self.app.onion_host, self.web.slug) TypeError: unsupported format string passed to NoneType.__format__ Aborted
TypeError
def main(cwd=None): """ The main() function implements all of the logic that the command-line version of onionshare uses. """ common = Common() strings.load_strings(common) print(strings._("version_string").format(common.version)) # OnionShare CLI in OSX needs to change current working directory (#132) if common.platform == "Darwin": if cwd: os.chdir(cwd) # Parse arguments parser = argparse.ArgumentParser( formatter_class=lambda prog: argparse.HelpFormatter(prog, max_help_position=28) ) parser.add_argument( "--local-only", action="store_true", dest="local_only", help=strings._("help_local_only"), ) parser.add_argument( "--stay-open", action="store_true", dest="stay_open", help=strings._("help_stay_open"), ) parser.add_argument( "--shutdown-timeout", metavar="<int>", dest="shutdown_timeout", default=0, help=strings._("help_shutdown_timeout"), ) parser.add_argument( "--stealth", action="store_true", dest="stealth", help=strings._("help_stealth") ) parser.add_argument( "--receive", action="store_true", dest="receive", help=strings._("help_receive") ) parser.add_argument( "--config", metavar="config", default=False, help=strings._("help_config") ) parser.add_argument( "--debug", action="store_true", dest="debug", help=strings._("help_debug") ) parser.add_argument( "filename", metavar="filename", nargs="*", help=strings._("help_filename") ) args = parser.parse_args() filenames = args.filename for i in range(len(filenames)): filenames[i] = os.path.abspath(filenames[i]) local_only = bool(args.local_only) debug = bool(args.debug) stay_open = bool(args.stay_open) shutdown_timeout = int(args.shutdown_timeout) stealth = bool(args.stealth) receive = bool(args.receive) config = args.config # Make sure filenames given if not using receiver mode if not receive and len(filenames) == 0: print(strings._("no_filenames")) sys.exit() # Validate filenames if not receive: valid = True for filename in filenames: if not os.path.isfile(filename) and not os.path.isdir(filename): print(strings._("not_a_file").format(filename)) valid = False if not os.access(filename, os.R_OK): print(strings._("not_a_readable_file").format(filename)) valid = False if not valid: sys.exit() # Load settings common.load_settings(config) # Debug mode? common.debug = debug # Create the Web object web = Web(common, False, receive) # Start the Onion object onion = Onion(common) try: onion.connect(custom_settings=False, config=config) except KeyboardInterrupt: print("") sys.exit() except Exception as e: sys.exit(e.args[0]) # Start the onionshare app try: app = OnionShare(common, onion, local_only, shutdown_timeout) app.set_stealth(stealth) app.choose_port() app.start_onion_service() except KeyboardInterrupt: print("") sys.exit() except (TorTooOld, TorErrorProtocolError) as e: print("") print(e.args[0]) sys.exit() # Prepare files to share print(strings._("preparing_files")) try: web.set_file_info(filenames) app.cleanup_filenames.append(web.zip_filename) except OSError as e: print(e.strerror) sys.exit(1) # Warn about sending large files over Tor if web.zip_filesize >= 157286400: # 150mb print("") print(strings._("large_filesize")) print("") # Start OnionShare http service in new thread t = threading.Thread( target=web.start, args=( app.port, stay_open, common.settings.get("public_mode"), common.settings.get("slug"), ), ) t.daemon = True t.start() try: # Trap Ctrl-C # Wait for web.generate_slug() to finish running time.sleep(0.2) # start shutdown timer thread if app.shutdown_timeout > 0: app.shutdown_timer.start() # Save the web slug if we are using a persistent private key if common.settings.get("save_private_key"): if not common.settings.get("slug"): common.settings.set("slug", web.slug) common.settings.save() # Build the URL if common.settings.get("public_mode"): url = "http://{0:s}".format(app.onion_host) else: url = "http://{0:s}/{1:s}".format(app.onion_host, web.slug) print("") if receive: print( strings._("receive_mode_downloads_dir").format( common.settings.get("downloads_dir") ) ) print("") print(strings._("receive_mode_warning")) print("") if stealth: print(strings._("give_this_url_receive_stealth")) print(url) print(app.auth_string) else: print(strings._("give_this_url_receive")) print(url) else: if stealth: print(strings._("give_this_url_stealth")) print(url) print(app.auth_string) else: print(strings._("give_this_url")) print(url) print("") print(strings._("ctrlc_to_stop")) # Wait for app to close while t.is_alive(): if app.shutdown_timeout > 0: # if the shutdown timer was set and has run out, stop the server if not app.shutdown_timer.is_alive(): # If there were no attempts to download the share, or all downloads are done, we can stop if web.download_count == 0 or web.done: print(strings._("close_on_timeout")) web.stop(app.port) break # Allow KeyboardInterrupt exception to be handled with threads # https://stackoverflow.com/questions/3788208/python-threading-ignores-keyboardinterrupt-exception time.sleep(0.2) except KeyboardInterrupt: web.stop(app.port) finally: # Shutdown app.cleanup() onion.cleanup()
def main(cwd=None): """ The main() function implements all of the logic that the command-line version of onionshare uses. """ common = Common() strings.load_strings(common) print(strings._("version_string").format(common.version)) # OnionShare CLI in OSX needs to change current working directory (#132) if common.platform == "Darwin": if cwd: os.chdir(cwd) # Parse arguments parser = argparse.ArgumentParser( formatter_class=lambda prog: argparse.HelpFormatter(prog, max_help_position=28) ) parser.add_argument( "--local-only", action="store_true", dest="local_only", help=strings._("help_local_only"), ) parser.add_argument( "--stay-open", action="store_true", dest="stay_open", help=strings._("help_stay_open"), ) parser.add_argument( "--shutdown-timeout", metavar="<int>", dest="shutdown_timeout", default=0, help=strings._("help_shutdown_timeout"), ) parser.add_argument( "--stealth", action="store_true", dest="stealth", help=strings._("help_stealth") ) parser.add_argument( "--receive", action="store_true", dest="receive", help=strings._("help_receive") ) parser.add_argument( "--config", metavar="config", default=False, help=strings._("help_config") ) parser.add_argument( "--debug", action="store_true", dest="debug", help=strings._("help_debug") ) parser.add_argument( "filename", metavar="filename", nargs="*", help=strings._("help_filename") ) args = parser.parse_args() filenames = args.filename for i in range(len(filenames)): filenames[i] = os.path.abspath(filenames[i]) local_only = bool(args.local_only) debug = bool(args.debug) stay_open = bool(args.stay_open) shutdown_timeout = int(args.shutdown_timeout) stealth = bool(args.stealth) receive = bool(args.receive) config = args.config # Make sure filenames given if not using receiver mode if not receive and len(filenames) == 0: print(strings._("no_filenames")) sys.exit() # Validate filenames if not receive: valid = True for filename in filenames: if not os.path.isfile(filename) and not os.path.isdir(filename): print(strings._("not_a_file").format(filename)) valid = False if not os.access(filename, os.R_OK): print(strings._("not_a_readable_file").format(filename)) valid = False if not valid: sys.exit() # Load settings common.load_settings(config) # Debug mode? common.debug = debug # Create the Web object web = Web(common, False, receive) # Start the Onion object onion = Onion(common) try: onion.connect(custom_settings=False, config=config) except KeyboardInterrupt: print("") sys.exit() except Exception as e: sys.exit(e.args[0]) # Start the onionshare app try: app = OnionShare(common, onion, local_only, shutdown_timeout) app.set_stealth(stealth) app.choose_port() app.start_onion_service() except KeyboardInterrupt: print("") sys.exit() # Prepare files to share print(strings._("preparing_files")) try: web.set_file_info(filenames) app.cleanup_filenames.append(web.zip_filename) except OSError as e: print(e.strerror) sys.exit(1) # Warn about sending large files over Tor if web.zip_filesize >= 157286400: # 150mb print("") print(strings._("large_filesize")) print("") # Start OnionShare http service in new thread t = threading.Thread( target=web.start, args=( app.port, stay_open, common.settings.get("public_mode"), common.settings.get("slug"), ), ) t.daemon = True t.start() try: # Trap Ctrl-C # Wait for web.generate_slug() to finish running time.sleep(0.2) # start shutdown timer thread if app.shutdown_timeout > 0: app.shutdown_timer.start() # Save the web slug if we are using a persistent private key if common.settings.get("save_private_key"): if not common.settings.get("slug"): common.settings.set("slug", web.slug) common.settings.save() # Build the URL if common.settings.get("public_mode"): url = "http://{0:s}".format(app.onion_host) else: url = "http://{0:s}/{1:s}".format(app.onion_host, web.slug) print("") if receive: print( strings._("receive_mode_downloads_dir").format( common.settings.get("downloads_dir") ) ) print("") print(strings._("receive_mode_warning")) print("") if stealth: print(strings._("give_this_url_receive_stealth")) print(url) print(app.auth_string) else: print(strings._("give_this_url_receive")) print(url) else: if stealth: print(strings._("give_this_url_stealth")) print(url) print(app.auth_string) else: print(strings._("give_this_url")) print(url) print("") print(strings._("ctrlc_to_stop")) # Wait for app to close while t.is_alive(): if app.shutdown_timeout > 0: # if the shutdown timer was set and has run out, stop the server if not app.shutdown_timer.is_alive(): # If there were no attempts to download the share, or all downloads are done, we can stop if web.download_count == 0 or web.done: print(strings._("close_on_timeout")) web.stop(app.port) break # Allow KeyboardInterrupt exception to be handled with threads # https://stackoverflow.com/questions/3788208/python-threading-ignores-keyboardinterrupt-exception time.sleep(0.2) except KeyboardInterrupt: web.stop(app.port) finally: # Shutdown app.cleanup() onion.cleanup()
https://github.com/micahflee/onionshare/issues/760
$ ./dev_scripts/onionshare --receive OnionShare 1.3.1 | https://onionshare.org/ Connecting to the Tor network: 100% - Done Configuring onion service on port 17641. Starting ephemeral Tor onion service and awaiting publication Traceback (most recent call last): File "/home/user/code/onionshare/onionshare/onion.py", line 483, in start_onion_service res = self.c.create_ephemeral_hidden_service({ 80: port }, await_publication=True, key_type=key_type, key_content=key_content) File "/usr/lib/python3.6/site-packages/stem/control.py", line 2937, in create_ephemeral_hidden_service stem.response.convert('ADD_ONION', response) File "/usr/lib/python3.6/site-packages/stem/response/__init__.py", line 124, in convert message._parse_message(**kwargs) File "/usr/lib/python3.6/site-packages/stem/response/add_onion.py", line 31, in _parse_message raise stem.ProtocolError("ADD_ONION response didn't have an OK status: %s" % self) stem.ProtocolError: ADD_ONION response didn't have an OK status: Invalid key type During handling of the above exception, another exception occurred: Traceback (most recent call last): File "./dev_scripts/onionshare", line 28, in <module> onionshare.main() File "/home/user/code/onionshare/onionshare/__init__.py", line 110, in main app.start_onion_service() File "/home/user/code/onionshare/onionshare/onionshare.py", line 86, in start_onion_service self.onion_host = self.onion.start_onion_service(self.port) File "/home/user/code/onionshare/onionshare/onion.py", line 486, in start_onion_service raise TorErrorProtocolError(strings._('error_tor_protocol_error')) onionshare.onion.TorErrorProtocolError: Could not communicate with the Tor controller. If you're using Whonix, check out https://www.whonix.org/wiki/onionshare to make OnionShare work.
stem.ProtocolError
def start_onion_service(self, port): """ Start a onion service on port 80, pointing to the given port, and return the onion hostname. """ self.common.log("Onion", "start_onion_service") self.auth_string = None if not self.supports_ephemeral: raise TorTooOld(strings._("error_ephemeral_not_supported")) if self.stealth and not self.supports_stealth: raise TorTooOld(strings._("error_stealth_not_supported")) print(strings._("config_onion_service").format(int(port))) print(strings._("using_ephemeral")) if self.stealth: if self.settings.get("hidservauth_string"): hidservauth_string = self.settings.get("hidservauth_string").split()[2] basic_auth = {"onionshare": hidservauth_string} else: basic_auth = {"onionshare": None} else: basic_auth = None if self.settings.get("private_key"): key_content = self.settings.get("private_key") # is the key a v2 key? if onionkey.is_v2_key(key_content): key_type = "RSA1024" # The below section is commented out because re-publishing # a pre-prepared v3 private key is currently unstable in Tor. # This is fixed upstream but won't reach stable until 0.3.5 # (expected in December 2018) # See https://trac.torproject.org/projects/tor/ticket/25552 # Until then, we will deliberately not work with 'persistent' # v3 onions, which should not be possible via the GUI settings # anyway. # Our ticket: https://github.com/micahflee/onionshare/issues/677 # # Assume it was a v3 key # key_type = "ED25519-V3" else: raise TorErrorProtocolError(strings._("error_invalid_private_key")) else: # Work out if we can support v3 onion services, which are preferred if Version(self.tor_version) >= Version("0.3.3.1") and not self.settings.get( "use_legacy_v2_onions" ): key_type = "ED25519-V3" key_content = onionkey.generate_v3_private_key()[0] else: # fall back to v2 onion services key_type = "RSA1024" key_content = onionkey.generate_v2_private_key()[0] # v3 onions don't yet support basic auth. Our ticket: # https://github.com/micahflee/onionshare/issues/697 if key_type == "ED25519-V3" and not self.settings.get("use_legacy_v2_onions"): basic_auth = None self.stealth = False self.common.log("Onion", "start_onion_service", "key_type={}".format(key_type)) try: if basic_auth != None: res = self.c.create_ephemeral_hidden_service( {80: port}, await_publication=True, basic_auth=basic_auth, key_type=key_type, key_content=key_content, ) else: # if the stem interface is older than 1.5.0, basic_auth isn't a valid keyword arg res = self.c.create_ephemeral_hidden_service( {80: port}, await_publication=True, key_type=key_type, key_content=key_content, ) except ProtocolError as e: raise TorErrorProtocolError( strings._("error_tor_protocol_error").format(e.args[0]) ) self.service_id = res.service_id onion_host = self.service_id + ".onion" # A new private key was generated and is in the Control port response. if self.settings.get("save_private_key"): if not self.settings.get("private_key"): self.settings.set("private_key", key_content) if self.stealth: # Similar to the PrivateKey, the Control port only returns the ClientAuth # in the response if it was responsible for creating the basic_auth password # in the first place. # If we sent the basic_auth (due to a saved hidservauth_string in the settings), # there is no response here, so use the saved value from settings. if self.settings.get("save_private_key"): if self.settings.get("hidservauth_string"): self.auth_string = self.settings.get("hidservauth_string") else: auth_cookie = list(res.client_auth.values())[0] self.auth_string = "HidServAuth {} {}".format(onion_host, auth_cookie) self.settings.set("hidservauth_string", self.auth_string) else: auth_cookie = list(res.client_auth.values())[0] self.auth_string = "HidServAuth {} {}".format(onion_host, auth_cookie) if onion_host is not None: self.settings.save() return onion_host else: raise TorErrorProtocolError(strings._("error_tor_protocol_error_unknown"))
def start_onion_service(self, port): """ Start a onion service on port 80, pointing to the given port, and return the onion hostname. """ self.common.log("Onion", "start_onion_service") self.auth_string = None if not self.supports_ephemeral: raise TorTooOld(strings._("error_ephemeral_not_supported")) if self.stealth and not self.supports_stealth: raise TorTooOld(strings._("error_stealth_not_supported")) print(strings._("config_onion_service").format(int(port))) print(strings._("using_ephemeral")) if self.stealth: if self.settings.get("hidservauth_string"): hidservauth_string = self.settings.get("hidservauth_string").split()[2] basic_auth = {"onionshare": hidservauth_string} else: basic_auth = {"onionshare": None} else: basic_auth = None if self.settings.get("private_key"): key_content = self.settings.get("private_key") # is the key a v2 key? if onionkey.is_v2_key(key_content): key_type = "RSA1024" # The below section is commented out because re-publishing # a pre-prepared v3 private key is currently unstable in Tor. # This is fixed upstream but won't reach stable until 0.3.5 # (expected in December 2018) # See https://trac.torproject.org/projects/tor/ticket/25552 # Until then, we will deliberately not work with 'persistent' # v3 onions, which should not be possible via the GUI settings # anyway. # Our ticket: https://github.com/micahflee/onionshare/issues/677 # # Assume it was a v3 key # key_type = "ED25519-V3" else: raise TorErrorProtocolError(strings._("error_invalid_private_key")) self.common.log("Onion", "Starting a hidden service with a saved private key") else: # Work out if we can support v3 onion services, which are preferred if Version(self.tor_version) >= Version("0.3.2.9") and not self.settings.get( "use_legacy_v2_onions" ): key_type = "ED25519-V3" key_content = onionkey.generate_v3_private_key()[0] else: # fall back to v2 onion services key_type = "RSA1024" key_content = onionkey.generate_v2_private_key()[0] self.common.log("Onion", "Starting a hidden service with a new private key") # v3 onions don't yet support basic auth. Our ticket: # https://github.com/micahflee/onionshare/issues/697 if key_type == "ED25519-V3" and not self.settings.get("use_legacy_v2_onions"): basic_auth = None self.stealth = False try: if basic_auth != None: res = self.c.create_ephemeral_hidden_service( {80: port}, await_publication=True, basic_auth=basic_auth, key_type=key_type, key_content=key_content, ) else: # if the stem interface is older than 1.5.0, basic_auth isn't a valid keyword arg res = self.c.create_ephemeral_hidden_service( {80: port}, await_publication=True, key_type=key_type, key_content=key_content, ) except ProtocolError: raise TorErrorProtocolError(strings._("error_tor_protocol_error")) self.service_id = res.service_id onion_host = self.service_id + ".onion" # A new private key was generated and is in the Control port response. if self.settings.get("save_private_key"): if not self.settings.get("private_key"): self.settings.set("private_key", key_content) if self.stealth: # Similar to the PrivateKey, the Control port only returns the ClientAuth # in the response if it was responsible for creating the basic_auth password # in the first place. # If we sent the basic_auth (due to a saved hidservauth_string in the settings), # there is no response here, so use the saved value from settings. if self.settings.get("save_private_key"): if self.settings.get("hidservauth_string"): self.auth_string = self.settings.get("hidservauth_string") else: auth_cookie = list(res.client_auth.values())[0] self.auth_string = "HidServAuth {} {}".format(onion_host, auth_cookie) self.settings.set("hidservauth_string", self.auth_string) else: auth_cookie = list(res.client_auth.values())[0] self.auth_string = "HidServAuth {} {}".format(onion_host, auth_cookie) if onion_host is not None: self.settings.save() return onion_host else: raise TorErrorProtocolError(strings._("error_tor_protocol_error"))
https://github.com/micahflee/onionshare/issues/760
$ ./dev_scripts/onionshare --receive OnionShare 1.3.1 | https://onionshare.org/ Connecting to the Tor network: 100% - Done Configuring onion service on port 17641. Starting ephemeral Tor onion service and awaiting publication Traceback (most recent call last): File "/home/user/code/onionshare/onionshare/onion.py", line 483, in start_onion_service res = self.c.create_ephemeral_hidden_service({ 80: port }, await_publication=True, key_type=key_type, key_content=key_content) File "/usr/lib/python3.6/site-packages/stem/control.py", line 2937, in create_ephemeral_hidden_service stem.response.convert('ADD_ONION', response) File "/usr/lib/python3.6/site-packages/stem/response/__init__.py", line 124, in convert message._parse_message(**kwargs) File "/usr/lib/python3.6/site-packages/stem/response/add_onion.py", line 31, in _parse_message raise stem.ProtocolError("ADD_ONION response didn't have an OK status: %s" % self) stem.ProtocolError: ADD_ONION response didn't have an OK status: Invalid key type During handling of the above exception, another exception occurred: Traceback (most recent call last): File "./dev_scripts/onionshare", line 28, in <module> onionshare.main() File "/home/user/code/onionshare/onionshare/__init__.py", line 110, in main app.start_onion_service() File "/home/user/code/onionshare/onionshare/onionshare.py", line 86, in start_onion_service self.onion_host = self.onion.start_onion_service(self.port) File "/home/user/code/onionshare/onionshare/onion.py", line 486, in start_onion_service raise TorErrorProtocolError(strings._('error_tor_protocol_error')) onionshare.onion.TorErrorProtocolError: Could not communicate with the Tor controller. If you're using Whonix, check out https://www.whonix.org/wiki/onionshare to make OnionShare work.
stem.ProtocolError
def _initSystemTray(self): menu = QtWidgets.QMenu() self.settingsAction = menu.addAction(strings._("gui_settings_window_title", True)) self.settingsAction.triggered.connect(self.open_settings) self.helpAction = menu.addAction(strings._("gui_settings_button_help", True)) self.helpAction.triggered.connect(lambda: SettingsDialog.help_clicked(self)) self.exitAction = menu.addAction(strings._("systray_menu_exit", True)) self.exitAction.triggered.connect(self.close) self.systemTray = QtWidgets.QSystemTrayIcon(self) # The convention is Mac systray icons are always grayscale if self.common.platform == "Darwin": self.systemTray.setIcon( QtGui.QIcon(self.common.get_resource_path("images/logo_grayscale.png")) ) else: self.systemTray.setIcon( QtGui.QIcon(self.common.get_resource_path("images/logo.png")) ) self.systemTray.setContextMenu(menu) self.systemTray.show()
def _initSystemTray(self): menu = QtWidgets.QMenu() self.settingsAction = menu.addAction(strings._("gui_settings_window_title", True)) self.settingsAction.triggered.connect(self.open_settings) self.helpAction = menu.addAction(strings._("gui_settings_button_help", True)) self.helpAction.triggered.connect(SettingsDialog.help_clicked) self.exitAction = menu.addAction(strings._("systray_menu_exit", True)) self.exitAction.triggered.connect(self.close) self.systemTray = QtWidgets.QSystemTrayIcon(self) # The convention is Mac systray icons are always grayscale if self.common.platform == "Darwin": self.systemTray.setIcon( QtGui.QIcon(self.common.get_resource_path("images/logo_grayscale.png")) ) else: self.systemTray.setIcon( QtGui.QIcon(self.common.get_resource_path("images/logo.png")) ) self.systemTray.setContextMenu(menu) self.systemTray.show()
https://github.com/micahflee/onionshare/issues/702
OnionShare.app/Contents/MacOS/onionshare-gui OnionShare 1.3 | https://onionshare.org/ Traceback (most recent call last): File "onionshare_gui/settings_dialog.py", line 795, in help_clicked self.common.log('SettingsDialog', 'help_clicked') AttributeError: 'bool' object has no attribute 'common' Abort trap: 6
AttributeError
def get_resource_path(filename): """ Returns the absolute path of a resource, regardless of whether OnionShare is installed systemwide, and whether regardless of platform """ p = get_platform() if getattr(sys, "onionshare_dev_mode", False): # Look for resources directory relative to python file resources_dir = os.path.join( os.path.dirname( os.path.dirname( os.path.abspath(inspect.getfile(inspect.currentframe())) ) ), "resources", ) elif p == "Linux" and sys.argv and sys.argv[0].startswith(sys.prefix): # OnionShare is installed systemwide in Linux resources_dir = os.path.join(sys.prefix, "share/onionshare") elif getattr(sys, "frozen", False): # Check if app is "frozen" with cx_Freeze # http://cx-freeze.readthedocs.io/en/latest/faq.html#using-data-files resources_dir = os.path.join(os.path.dirname(sys.executable), "resources") return os.path.join(resources_dir, filename)
def get_resource_path(filename): """ Returns the absolute path of a resource, regardless of whether OnionShare is installed systemwide, and whether regardless of platform """ p = get_platform() if p == "Linux" and sys.argv and sys.argv[0].startswith(sys.prefix): # OnionShare is installed systemwide in Linux resources_dir = os.path.join(sys.prefix, "share/onionshare") elif getattr(sys, "frozen", False): # Check if app is "frozen" with cx_Freeze # http://cx-freeze.readthedocs.io/en/latest/faq.html#using-data-files resources_dir = os.path.join(os.path.dirname(sys.executable), "resources") else: # Look for resources directory relative to python file resources_dir = os.path.join( os.path.dirname( os.path.dirname( os.path.abspath(inspect.getfile(inspect.currentframe())) ) ), "resources", ) return os.path.join(resources_dir, filename)
https://github.com/micahflee/onionshare/issues/311
Traceback (most recent call last): File "./install/scripts/onionshare", line 21, in <module> import onionshare ImportError: No module named 'onionshare'
ImportError
def __init__(self, basename, webapp_port): global window_icon QWebView.__init__(self) self.setWindowTitle("{0} | OnionShare".format(basename.decode("utf-8"))) self.resize(580, 400) self.setMinimumSize(580, 400) self.setMaximumSize(580, 400) self.setWindowIcon(window_icon) self.load(QUrl("http://127.0.0.1:{0}".format(webapp_port)))
def __init__(self, basename, webapp_port): global window_icon QWebView.__init__(self) self.setWindowTitle("{0} | OnionShare".format(basename)) self.resize(580, 400) self.setMinimumSize(580, 400) self.setMaximumSize(580, 400) self.setWindowIcon(window_icon) self.load(QUrl("http://127.0.0.1:{0}".format(webapp_port)))
https://github.com/micahflee/onionshare/issues/80
Traceback (most recent call last): File "<string>", line 7, in <module> File "/Users/micah/code/onionshare/build/onionshare-osx/out00-PYZ.pyz/onionshare_gui.onionshare_gui", line 121, in main File "/Users/micah/code/onionshare/build/onionshare-osx/out00-PYZ.pyz/onionshare_gui.onionshare_gui", line 68, in select_file UnicodeEncodeError: 'ascii' codec can't encode character u'\xf8' in position 22: ordinal not in range(128)
UnicodeEncodeError
def select_file(strings, filename=None): # get filename, either from argument or file chooser dialog if not filename: args = {} if onionshare.get_platform() == "Tails": args["directory"] = "/home/amnesia" filename = QFileDialog.getOpenFileName( caption=translated("choose_file"), options=QFileDialog.ReadOnly, **args ) if not filename: return False, False filename = str(unicode(filename).encode("utf-8")) # validate filename if not os.path.isfile(filename): alert(translated("not_a_file").format(filename), QMessageBox.Warning) return False, False filename = os.path.abspath(filename) basename = os.path.basename(filename) return filename, basename
def select_file(strings, filename=None): # get filename, either from argument or file chooser dialog if not filename: args = {} if onionshare.get_platform() == "Tails": args["directory"] = "/home/amnesia" filename = QFileDialog.getOpenFileName( caption=translated("choose_file"), options=QFileDialog.ReadOnly, **args ) if not filename: return False, False filename = str(filename) # validate filename if not os.path.isfile(filename): alert(translated("not_a_file").format(filename), QMessageBox.Warning) return False, False filename = os.path.abspath(filename) basename = os.path.basename(filename) return filename, basename
https://github.com/micahflee/onionshare/issues/80
Traceback (most recent call last): File "<string>", line 7, in <module> File "/Users/micah/code/onionshare/build/onionshare-osx/out00-PYZ.pyz/onionshare_gui.onionshare_gui", line 121, in main File "/Users/micah/code/onionshare/build/onionshare-osx/out00-PYZ.pyz/onionshare_gui.onionshare_gui", line 68, in select_file UnicodeEncodeError: 'ascii' codec can't encode character u'\xf8' in position 22: ordinal not in range(128)
UnicodeEncodeError
def _add_install(subparsers): p = subparsers.add_parser( "install", help="Install a package", formatter_class=LineWrapRawTextHelpFormatter, description=INSTALL_DESCRIPTION, ) p.add_argument("package", help="package name") p.add_argument("--spec", help=SPEC_HELP) add_include_dependencies(p) p.add_argument("--verbose", action="store_true") p.add_argument( "--force", "-f", action="store_true", help="Modify existing virtual environment and files in PIPX_BIN_DIR", ) p.add_argument( "--python", default=constants.DEFAULT_PYTHON, help=( "The Python executable used to create the Virtual Environment and run the " "associated app/apps. Must be v3.5+." ), ) add_pip_venv_args(p)
def _add_install(subparsers): p = subparsers.add_parser( "install", help="Install a package", formatter_class=LineWrapRawTextHelpFormatter, description=INSTALL_DESCRIPTION, ) p.add_argument("package", help="package name") p.add_argument("--spec", help=SPEC_HELP) add_include_dependencies(p) p.add_argument("--verbose", action="store_true") p.add_argument( "--force", "-f", action="store_true", help="Modify existing virtual environment and files in PIPX_BIN_DIR", ) p.add_argument( "--python", default=constants.DEFAULT_PYTHON, help=( "The Python executable used to create the Virtual Environment and run the " "associated app/apps. Must be v3.3+." ), ) add_pip_venv_args(p)
https://github.com/pipxproject/pipx/issues/231
$ python3.7 -m pip install --user pipx $ python3.7 -m pipx run --python python3.4 cowsay 'Hello, world!' _____________ < Hello, world! > ============= \ \ ^__^ (oo)\_______ (__)\ )\/\ ||----w | || || $ python3.7 -m pipx install --python python3.4 cowsay File "<string>", line 89 app_paths_of_dependencies: Dict[str, List[str]] = {} ^ SyntaxError: invalid syntax ⢿ installing package 'cowsay'Traceback (most recent call last): File "/home/bkboulton/.pyenv/versions/py37/bin/pipx", line 10, in <module> sys.exit(cli()) File "/home/bkboulton/.pyenv/versions/py37/lib/python3.7/site-packages/pipx/main.py", line 547, in c exit(run_pipx_command(parsed_pipx_args)) File "/home/bkboulton/.pyenv/versions/py37/lib/python3.7/site-packages/pipx/main.py", line 166, in r include_dependencies=args.include_deps, File "/home/bkboulton/.pyenv/versions/py37/lib/python3.7/site-packages/pipx/commands.py", line 318, if venv.get_venv_metadata_for_package(package).package_version is None: File "/home/bkboulton/.pyenv/versions/py37/lib/python3.7/site-packages/pipx/Venv.py", line 161, in g self.python_path, VENV_METADATA_INSPECTOR, package, str(self.bin_path) File "/home/bkboulton/.pyenv/versions/3.7.4/lib/python3.7/json/__init__.py", line 348, in loads return _default_decoder.decode(s) File "/home/bkboulton/.pyenv/versions/3.7.4/lib/python3.7/json/decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/home/bkboulton/.pyenv/versions/3.7.4/lib/python3.7/json/decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
SyntaxError
def _add_run(subparsers): p = subparsers.add_parser( "run", formatter_class=LineWrapRawTextHelpFormatter, help=( "Download the latest version of a package to a temporary virtual environment, " "then run an app from it. Also compatible with local `__pypackages__` " "directory (experimental)." ), description=textwrap.dedent( f""" Download the latest version of a package to a temporary virtual environment, then run an app from it. The environment will be cached and re-used for up to {constants.TEMP_VENV_EXPIRATION_THRESHOLD_DAYS} days. This means subsequent calls to 'run' for the same package will be faster since they can re-use the cached Virtual Environment. In support of PEP 582 'run' will use apps found in a local __pypackages__ directory, if present. Please note that this behavior is experimental, and is a acts as a companion tool to pythonloc. It may be modified or removed in the future. See https://github.com/cs01/pythonloc. """ ), ) p.add_argument( "--no-cache", action="store_true", help="Do not re-use cached virtual environment if it exists", ) p.add_argument("app", help="app/package name") p.add_argument( "appargs", nargs=argparse.REMAINDER, help="arguments passed to the application when it is invoked", default=[], ) p.add_argument( "--pypackages", action="store_true", help="Require app to be run from local __pypackages__ directory", ) p.add_argument("--spec", help=SPEC_HELP) p.add_argument("--verbose", action="store_true") p.add_argument( "--python", default=constants.DEFAULT_PYTHON, help="The Python version to run package's CLI app with. Must be v3.5+.", ) add_pip_venv_args(p)
def _add_run(subparsers): p = subparsers.add_parser( "run", formatter_class=LineWrapRawTextHelpFormatter, help=( "Download the latest version of a package to a temporary virtual environment, " "then run an app from it. Also compatible with local `__pypackages__` " "directory (experimental)." ), description=textwrap.dedent( f""" Download the latest version of a package to a temporary virtual environment, then run an app from it. The environment will be cached and re-used for up to {constants.TEMP_VENV_EXPIRATION_THRESHOLD_DAYS} days. This means subsequent calls to 'run' for the same package will be faster since they can re-use the cached Virtual Environment. In support of PEP 582 'run' will use apps found in a local __pypackages__ directory, if present. Please note that this behavior is experimental, and is a acts as a companion tool to pythonloc. It may be modified or removed in the future. See https://github.com/cs01/pythonloc. """ ), ) p.add_argument( "--no-cache", action="store_true", help="Do not re-use cached virtual environment if it exists", ) p.add_argument("app", help="app/package name") p.add_argument( "appargs", nargs=argparse.REMAINDER, help="arguments passed to the application when it is invoked", default=[], ) p.add_argument( "--pypackages", action="store_true", help="Require app to be run from local __pypackages__ directory", ) p.add_argument("--spec", help=SPEC_HELP) p.add_argument("--verbose", action="store_true") p.add_argument( "--python", default=constants.DEFAULT_PYTHON, help="The Python version to run package's CLI app with. Must be v3.3+.", ) add_pip_venv_args(p)
https://github.com/pipxproject/pipx/issues/231
$ python3.7 -m pip install --user pipx $ python3.7 -m pipx run --python python3.4 cowsay 'Hello, world!' _____________ < Hello, world! > ============= \ \ ^__^ (oo)\_______ (__)\ )\/\ ||----w | || || $ python3.7 -m pipx install --python python3.4 cowsay File "<string>", line 89 app_paths_of_dependencies: Dict[str, List[str]] = {} ^ SyntaxError: invalid syntax ⢿ installing package 'cowsay'Traceback (most recent call last): File "/home/bkboulton/.pyenv/versions/py37/bin/pipx", line 10, in <module> sys.exit(cli()) File "/home/bkboulton/.pyenv/versions/py37/lib/python3.7/site-packages/pipx/main.py", line 547, in c exit(run_pipx_command(parsed_pipx_args)) File "/home/bkboulton/.pyenv/versions/py37/lib/python3.7/site-packages/pipx/main.py", line 166, in r include_dependencies=args.include_deps, File "/home/bkboulton/.pyenv/versions/py37/lib/python3.7/site-packages/pipx/commands.py", line 318, if venv.get_venv_metadata_for_package(package).package_version is None: File "/home/bkboulton/.pyenv/versions/py37/lib/python3.7/site-packages/pipx/Venv.py", line 161, in g self.python_path, VENV_METADATA_INSPECTOR, package, str(self.bin_path) File "/home/bkboulton/.pyenv/versions/3.7.4/lib/python3.7/json/__init__.py", line 348, in loads return _default_decoder.decode(s) File "/home/bkboulton/.pyenv/versions/3.7.4/lib/python3.7/json/decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/home/bkboulton/.pyenv/versions/3.7.4/lib/python3.7/json/decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
SyntaxError
def main(): package = sys.argv[1] bin_path = Path(sys.argv[2]) apps = get_apps(package, bin_path) app_paths = [str(Path(bin_path) / app) for app in apps] app_paths_of_dependencies = {} # type: Dict[str, List[str]] app_paths_of_dependencies = _dfs_package_apps( bin_path, package, app_paths_of_dependencies ) output = { "apps": apps, "app_paths": app_paths, "app_paths_of_dependencies": app_paths_of_dependencies, "package_version": get_package_version(package), "python_version": "Python {}.{}.{}".format( sys.version_info.major, sys.version_info.minor, sys.version_info.micro ), } print(json.dumps(output))
def main(): package = sys.argv[1] bin_path = Path(sys.argv[2]) apps = get_apps(package, bin_path) app_paths = [str(Path(bin_path) / app) for app in apps] app_paths_of_dependencies: Dict[str, List[str]] = {} app_paths_of_dependencies = _dfs_package_apps( bin_path, package, app_paths_of_dependencies ) output = { "apps": apps, "app_paths": app_paths, "app_paths_of_dependencies": app_paths_of_dependencies, "package_version": get_package_version(package), "python_version": f"Python {sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}", } print(json.dumps(output))
https://github.com/pipxproject/pipx/issues/231
$ python3.7 -m pip install --user pipx $ python3.7 -m pipx run --python python3.4 cowsay 'Hello, world!' _____________ < Hello, world! > ============= \ \ ^__^ (oo)\_______ (__)\ )\/\ ||----w | || || $ python3.7 -m pipx install --python python3.4 cowsay File "<string>", line 89 app_paths_of_dependencies: Dict[str, List[str]] = {} ^ SyntaxError: invalid syntax ⢿ installing package 'cowsay'Traceback (most recent call last): File "/home/bkboulton/.pyenv/versions/py37/bin/pipx", line 10, in <module> sys.exit(cli()) File "/home/bkboulton/.pyenv/versions/py37/lib/python3.7/site-packages/pipx/main.py", line 547, in c exit(run_pipx_command(parsed_pipx_args)) File "/home/bkboulton/.pyenv/versions/py37/lib/python3.7/site-packages/pipx/main.py", line 166, in r include_dependencies=args.include_deps, File "/home/bkboulton/.pyenv/versions/py37/lib/python3.7/site-packages/pipx/commands.py", line 318, if venv.get_venv_metadata_for_package(package).package_version is None: File "/home/bkboulton/.pyenv/versions/py37/lib/python3.7/site-packages/pipx/Venv.py", line 161, in g self.python_path, VENV_METADATA_INSPECTOR, package, str(self.bin_path) File "/home/bkboulton/.pyenv/versions/3.7.4/lib/python3.7/json/__init__.py", line 348, in loads return _default_decoder.decode(s) File "/home/bkboulton/.pyenv/versions/3.7.4/lib/python3.7/json/decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/home/bkboulton/.pyenv/versions/3.7.4/lib/python3.7/json/decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
SyntaxError
def guard(clusters): """ Split Clusters containing conditional expressions into separate Clusters. """ processed = [] for c in clusters: # Group together consecutive expressions with same ConditionalDimensions for cds, g in groupby(c.exprs, key=lambda e: tuple(e.conditionals)): exprs = list(g) if not cds: processed.append(c.rebuild(exprs=exprs)) continue # Chain together all conditions from all expressions in `c` guards = {} for cd in cds: condition = guards.setdefault(cd.parent, []) for e in exprs: try: condition.append(e.conditionals[cd]) break except KeyError: pass guards = {d: sympy.And(*v, evaluate=False) for d, v in guards.items()} # Construct a guarded Cluster processed.append(c.rebuild(exprs=exprs, guards=guards)) return ClusterGroup(processed)
def guard(clusters): """ Split Clusters containing conditional expressions into separate Clusters. """ processed = [] for c in clusters: # Group together consecutive expressions with same ConditionalDimensions for cds, g in groupby(c.exprs, key=lambda e: e.conditionals): exprs = list(g) if not cds: processed.append(c.rebuild(exprs=exprs)) continue # Create a guarded Cluster guards = {} for cd in cds: condition = guards.setdefault(cd.parent, []) if cd.condition is None: condition.append(CondEq(cd.parent % cd.factor, 0)) else: condition.append(lower_exprs(cd.condition)) guards = {k: sympy.And(*v, evaluate=False) for k, v in guards.items()} exprs = [e.func(*e.args, conditionals=dict(guards)) for e in exprs] processed.append(c.rebuild(exprs=exprs, guards=guards)) return ClusterGroup(processed)
https://github.com/devitocodes/devito/issues/1298
Traceback (most recent call last): File "tests/mfe_args.py", line 23, in <module> op.apply() File "/home/gbisbas/workspace/devito/devito/operator/operator.py", line 655, in apply args = self.arguments(**kwargs) File "/home/gbisbas/workspace/devito/devito/operator/operator.py", line 537, in arguments args = self._prepare_arguments(**kwargs) File "/home/gbisbas/workspace/devito/devito/operator/operator.py", line 482, in _prepare_arguments p._arg_check(args, self._dspace[p]) AttributeError: 'Symbol' object has no attribute '_arg_check'
AttributeError
def __new__(cls, *args, **kwargs): if len(args) == 1 and isinstance(args[0], LoweredEq): # origin: LoweredEq(devito.LoweredEq, **kwargs) input_expr = args[0] expr = sympy.Eq.__new__(cls, *input_expr.args, evaluate=False) for i in cls._state: setattr(expr, "_%s" % i, kwargs.get(i) or getattr(input_expr, i)) return expr elif len(args) == 1 and isinstance(args[0], Eq): # origin: LoweredEq(devito.Eq) input_expr = expr = args[0] elif len(args) == 2: expr = sympy.Eq.__new__(cls, *args, evaluate=False) for i in cls._state: setattr(expr, "_%s" % i, kwargs.pop(i)) return expr else: raise ValueError( "Cannot construct LoweredEq from args=%s " "and kwargs=%s" % (str(args), str(kwargs)) ) # Well-defined dimension ordering ordering = dimension_sort(expr) # Analyze the expression mapper = detect_accesses(expr) oobs = detect_oobs(mapper) conditional_dimensions = [i for i in ordering if i.is_Conditional] # Construct Intervals for IterationSpace and DataSpace intervals = build_intervals(Stencil.union(*mapper.values())) iintervals = [] # iteration Intervals dintervals = [] # data Intervals for i in intervals: d = i.dim if d in oobs: iintervals.append(i.zero()) dintervals.append(i) else: iintervals.append(i.zero()) dintervals.append(i.zero()) # Construct the IterationSpace iintervals = IntervalGroup(iintervals, relations=ordering.relations) iterators = build_iterators(mapper) ispace = IterationSpace(iintervals, iterators) # Construct the DataSpace dintervals.extend( [ Interval(i, 0, 0) for i in ordering if i not in ispace.dimensions + conditional_dimensions ] ) parts = { k: IntervalGroup(build_intervals(v)).add(iintervals) for k, v in mapper.items() if k } dspace = DataSpace(dintervals, parts) # Construct the conditionals conditionals = {} for d in conditional_dimensions: if d.condition is None: conditionals[d] = CondEq(d.parent % d.factor, 0) else: conditionals[d] = lower_exprs(d.condition) conditionals = frozendict(conditionals) # Lower all Differentiable operations into SymPy operations rhs = diff2sympy(expr.rhs) # Finally create the LoweredEq with all metadata attached expr = super(LoweredEq, cls).__new__(cls, expr.lhs, rhs, evaluate=False) expr._dspace = dspace expr._ispace = ispace expr._conditionals = conditionals expr._reads, expr._writes = detect_io(expr) expr._is_Increment = input_expr.is_Increment expr._implicit_dims = input_expr.implicit_dims return expr
def __new__(cls, *args, **kwargs): if len(args) == 1 and isinstance(args[0], LoweredEq): # origin: LoweredEq(devito.LoweredEq, **kwargs) input_expr = args[0] expr = sympy.Eq.__new__(cls, *input_expr.args, evaluate=False) for i in cls._state: setattr(expr, "_%s" % i, kwargs.get(i) or getattr(input_expr, i)) return expr elif len(args) == 1 and isinstance(args[0], Eq): # origin: LoweredEq(devito.Eq) input_expr = expr = args[0] elif len(args) == 2: expr = sympy.Eq.__new__(cls, *args, evaluate=False) for i in cls._state: setattr(expr, "_%s" % i, kwargs.pop(i)) return expr else: raise ValueError( "Cannot construct LoweredEq from args=%s " "and kwargs=%s" % (str(args), str(kwargs)) ) # Well-defined dimension ordering ordering = dimension_sort(expr) # Analyze the expression mapper = detect_accesses(expr) oobs = detect_oobs(mapper) conditionals = [i for i in ordering if i.is_Conditional] # Construct Intervals for IterationSpace and DataSpace intervals = build_intervals(Stencil.union(*mapper.values())) iintervals = [] # iteration Intervals dintervals = [] # data Intervals for i in intervals: d = i.dim if d in oobs: iintervals.append(i.zero()) dintervals.append(i) else: iintervals.append(i.zero()) dintervals.append(i.zero()) # Construct the IterationSpace iintervals = IntervalGroup(iintervals, relations=ordering.relations) iterators = build_iterators(mapper) ispace = IterationSpace(iintervals, iterators) # Construct the DataSpace dintervals.extend( [ Interval(i, 0, 0) for i in ordering if i not in ispace.dimensions + conditionals ] ) parts = { k: IntervalGroup(build_intervals(v)).add(iintervals) for k, v in mapper.items() if k } dspace = DataSpace(dintervals, parts) # Lower all Differentiable operations into SymPy operations rhs = diff2sympy(expr.rhs) # Finally create the LoweredEq with all metadata attached expr = super(LoweredEq, cls).__new__(cls, expr.lhs, rhs, evaluate=False) expr._dspace = dspace expr._ispace = ispace expr._conditionals = frozendict([(d, ()) for d in conditionals]) expr._reads, expr._writes = detect_io(expr) expr._is_Increment = input_expr.is_Increment expr._implicit_dims = input_expr.implicit_dims return expr
https://github.com/devitocodes/devito/issues/1298
Traceback (most recent call last): File "tests/mfe_args.py", line 23, in <module> op.apply() File "/home/gbisbas/workspace/devito/devito/operator/operator.py", line 655, in apply args = self.arguments(**kwargs) File "/home/gbisbas/workspace/devito/devito/operator/operator.py", line 537, in arguments args = self._prepare_arguments(**kwargs) File "/home/gbisbas/workspace/devito/devito/operator/operator.py", line 482, in _prepare_arguments p._arg_check(args, self._dspace[p]) AttributeError: 'Symbol' object has no attribute '_arg_check'
AttributeError
def __init__(self, exprs, rules=None): """ A Scope enables data dependence analysis on a totally ordered sequence of expressions. """ exprs = as_tuple(exprs) self.reads = {} self.writes = {} self.initialized = set() for i, e in enumerate(exprs): # Reads for j in retrieve_terminals(e.rhs): v = self.reads.setdefault(j.function, []) mode = "RI" if e.is_Increment and j.function is e.lhs.function else "R" v.append(TimedAccess(j, mode, i, e.ispace)) # Write v = self.writes.setdefault(e.lhs.function, []) mode = "WI" if e.is_Increment else "W" v.append(TimedAccess(e.lhs, mode, i, e.ispace)) # If an increment, we got one implicit read if e.is_Increment: v = self.reads.setdefault(e.lhs.function, []) v.append(TimedAccess(e.lhs, "RI", i, e.ispace)) # If writing to a scalar, we have an initialization if not e.is_Increment and e.is_scalar: self.initialized.add(e.lhs.function) # Look up ConditionalDimensions for v in e.conditionals.values(): for j in retrieve_terminals(v): v = self.reads.setdefault(j.function, []) v.append(TimedAccess(j, "R", -1, e.ispace)) # The iteration symbols too dimensions = set().union(*[e.dimensions for e in exprs]) for d in dimensions: for i in d._defines_symbols: for j in i.free_symbols: v = self.reads.setdefault(j.function, []) v.append(TimedAccess(j, "R", -1)) # A set of rules to drive the collection of dependencies self.rules = as_tuple(rules) assert all(callable(i) for i in self.rules)
def __init__(self, exprs, rules=None): """ A Scope enables data dependence analysis on a totally ordered sequence of expressions. """ exprs = as_tuple(exprs) self.reads = {} self.writes = {} self.initialized = set() for i, e in enumerate(exprs): # Reads for j in retrieve_terminals(e.rhs): v = self.reads.setdefault(j.function, []) mode = "RI" if e.is_Increment and j.function is e.lhs.function else "R" v.append(TimedAccess(j, mode, i, e.ispace)) # Write v = self.writes.setdefault(e.lhs.function, []) mode = "WI" if e.is_Increment else "W" v.append(TimedAccess(e.lhs, mode, i, e.ispace)) # If an increment, we got one implicit read if e.is_Increment: v = self.reads.setdefault(e.lhs.function, []) v.append(TimedAccess(e.lhs, "RI", i, e.ispace)) # If writing to a scalar, we have an initialization if not e.is_Increment and e.is_scalar: self.initialized.add(e.lhs.function) # Look up ConditionalDimensions for d, v in e.conditionals.items(): symbols = d.free_symbols | set(retrieve_terminals(v)) for j in symbols: v = self.reads.setdefault(j.function, []) v.append(TimedAccess(j, "R", -1, e.ispace)) # The iteration symbols too dimensions = set().union(*[e.dimensions for e in exprs]) for d in dimensions: for i in d._defines_symbols: for j in i.free_symbols: v = self.reads.setdefault(j.function, []) v.append(TimedAccess(j, "R", -1)) # A set of rules to drive the collection of dependencies self.rules = as_tuple(rules) assert all(callable(i) for i in self.rules)
https://github.com/devitocodes/devito/issues/1298
Traceback (most recent call last): File "tests/mfe_args.py", line 23, in <module> op.apply() File "/home/gbisbas/workspace/devito/devito/operator/operator.py", line 655, in apply args = self.arguments(**kwargs) File "/home/gbisbas/workspace/devito/devito/operator/operator.py", line 537, in arguments args = self._prepare_arguments(**kwargs) File "/home/gbisbas/workspace/devito/devito/operator/operator.py", line 482, in _prepare_arguments p._arg_check(args, self._dspace[p]) AttributeError: 'Symbol' object has no attribute '_arg_check'
AttributeError
def detect_io(exprs, relax=False): """ ``{exprs} -> ({reads}, {writes})`` Parameters ---------- exprs : expr-like or list of expr-like The searched expressions. relax : bool, optional If False, as by default, collect only Constants and Functions. Otherwise, collect any Basic object. """ exprs = as_tuple(exprs) if relax is False: rule = lambda i: i.is_Input else: rule = lambda i: i.is_Scalar or i.is_Tensor # Don't forget the nasty case with indirections on the LHS: # >>> u[t, a[x]] = f[x] -> (reads={a, f}, writes={u}) roots = [] for i in exprs: try: roots.append(i.rhs) roots.extend(list(i.lhs.indices)) roots.extend(list(i.conditionals.values())) except AttributeError: # E.g., FunctionFromPointer roots.append(i) reads = [] terminals = flatten(retrieve_terminals(i, deep=True) for i in roots) for i in terminals: candidates = i.free_symbols try: candidates.update({i.function}) except AttributeError: pass for j in candidates: try: if rule(j): reads.append(j) except AttributeError: pass writes = [] for i in exprs: try: f = i.lhs.function except AttributeError: continue if rule(f): writes.append(f) return filter_sorted(reads), filter_sorted(writes)
def detect_io(exprs, relax=False): """ ``{exprs} -> ({reads}, {writes})`` Parameters ---------- exprs : expr-like or list of expr-like The searched expressions. relax : bool, optional If False, as by default, collect only Constants and Functions. Otherwise, collect any Basic object. """ exprs = as_tuple(exprs) if relax is False: rule = lambda i: i.is_Input else: rule = lambda i: i.is_Scalar or i.is_Tensor # Don't forget this nasty case, with indirections on the LHS: # >>> u[t, a[x]] = f[x] -> (reads={a, f}, writes={u}) roots = [] for i in exprs: try: roots.append(i.rhs) roots.extend(list(i.lhs.indices)) except AttributeError: # E.g., FunctionFromPointer roots.append(i) reads = [] terminals = flatten(retrieve_terminals(i, deep=True) for i in roots) for i in terminals: candidates = i.free_symbols try: candidates.update({i.function}) except AttributeError: pass for j in candidates: try: if rule(j): reads.append(j) except AttributeError: pass writes = [] for i in exprs: try: f = i.lhs.function except AttributeError: continue if rule(f): writes.append(f) return filter_sorted(reads), filter_sorted(writes)
https://github.com/devitocodes/devito/issues/1298
Traceback (most recent call last): File "tests/mfe_args.py", line 23, in <module> op.apply() File "/home/gbisbas/workspace/devito/devito/operator/operator.py", line 655, in apply args = self.arguments(**kwargs) File "/home/gbisbas/workspace/devito/devito/operator/operator.py", line 537, in arguments args = self._prepare_arguments(**kwargs) File "/home/gbisbas/workspace/devito/devito/operator/operator.py", line 482, in _prepare_arguments p._arg_check(args, self._dspace[p]) AttributeError: 'Symbol' object has no attribute '_arg_check'
AttributeError
def option_performance(f): """Defines options for all aspects of performance tuning""" _preset = { # Fixed "O1": {"dse": "basic", "dle": "advanced"}, "O2": {"dse": "advanced", "dle": "advanced"}, "O3": {"dse": "aggressive", "dle": "advanced"}, # Parametric "dse": {"dse": ["basic", "advanced", "aggressive"], "dle": "advanced"}, } def from_preset(ctx, param, value): """Set all performance options according to bench-mode preset""" ctx.params.update(_preset[value]) return value def from_value(ctx, param, value): """Prefer preset values and warn for competing values.""" return ctx.params[param.name] or value def config_blockshape(ctx, param, value): if value: # Block innermost loops if a full block shape is provided configuration["dle-options"]["blockinner"] = True # Normalize value: # 1. integers, not strings # 2. sanity check the (hierarchical) blocking shape normalized_value = [] for i, block_shape in enumerate(value): # If hierarchical blocking is activated, say with N levels, here in # `bs` we expect to see 3*N entries bs = [int(x) for x in block_shape.split()] levels = [bs[x : x + 3] for x in range(0, len(bs), 3)] if any(len(level) != 3 for level in levels): raise ValueError( "Expected 3 entries per block shape level, but got " "one level with less than 3 entries (`%s`)" % levels ) normalized_value.append(levels) if not all_equal(len(i) for i in normalized_value): raise ValueError( "Found different block shapes with incompatible " "number of levels (`%s`)" % normalized_value ) configuration["dle-options"]["blocklevels"] = len(normalized_value[0]) else: normalized_value = [] return tuple(normalized_value) def config_autotuning(ctx, param, value): """Setup auto-tuning to run in ``{basic,aggressive,...}+preemptive`` mode.""" if value != "off": # Sneak-peek at the `block-shape` -- if provided, keep auto-tuning off if ctx.params["block_shape"]: warning( "Skipping autotuning (using explicit block-shape `%s`)" % str(ctx.params["block_shape"]) ) level = False else: # Make sure to always run in preemptive mode configuration["autotuning"] = [value, "preemptive"] # We apply blocking to all parallel loops, including the innermost ones configuration["dle-options"]["blockinner"] = True level = value else: level = False return level options = [ click.option( "-bm", "--bench-mode", is_eager=True, callback=from_preset, expose_value=False, default="O2", type=click.Choice(["O1", "O2", "O3", "dse"]), help="Choose what to benchmark; ignored if execmode=run", ), click.option( "--arch", default="unknown", help="Architecture on which the simulation is/was run", ), click.option( "--dse", callback=from_value, type=click.Choice(["noop"] + configuration._accepted["dse"]), help="Devito symbolic engine (DSE) mode", ), click.option( "--dle", callback=from_value, type=click.Choice( [ str(i) if type(i) is tuple else i for i in configuration._accepted["dle"] ] ), help="Devito loop engine (DLE) mode", ), click.option( "-bs", "--block-shape", callback=config_blockshape, multiple=True, is_eager=True, help="Loop-blocking shape, bypass autotuning", ), click.option( "-a", "--autotune", default="aggressive", callback=config_autotuning, type=click.Choice( [ str(tuple(i)) if type(i) is list else i for i in configuration._accepted["autotuning"] ] ), help="Select autotuning mode", ), ] for option in reversed(options): f = option(f) return f
def option_performance(f): """Defines options for all aspects of performance tuning""" _preset = { # Fixed "O1": {"dse": "basic", "dle": "advanced"}, "O2": {"dse": "advanced", "dle": "advanced"}, "O3": {"dse": "aggressive", "dle": "advanced"}, # Parametric "dse": {"dse": ["basic", "advanced", "aggressive"], "dle": "advanced"}, } def from_preset(ctx, param, value): """Set all performance options according to bench-mode preset""" ctx.params.update(_preset[value]) return value def from_value(ctx, param, value): """Prefer preset values and warn for competing values.""" return ctx.params[param.name] or value def config_blockshape(ctx, param, value): if value: # Block innermost loops if a full block shape is provided configuration["dle-options"]["blockinner"] = True # Normalize value: # 1. integers, not strings # 2. sanity check the (hierarchical) blocking shape normalized_value = [] for i, block_shape in enumerate(value): # If hierarchical blocking is activated, say with N levels, here in # `bs` we expect to see 3*N entries bs = [int(x) for x in block_shape.split()] levels = [bs[x : x + 3] for x in range(0, len(bs), 3)] if any(len(level) != 3 for level in levels): raise ValueError( "Expected 3 entries per block shape level, but got " "one level with less than 3 entries (`%s`)" % levels ) normalized_value.append(levels) if not all_equal(len(i) for i in normalized_value): raise ValueError( "Found different block shapes with incompatible " "number of levels (`%s`)" % normalized_value ) configuration["dle-options"]["blocklevels"] = len(normalized_value[0]) else: normalized_value = [] return tuple(normalized_value) def config_autotuning(ctx, param, value): """Setup auto-tuning to run in ``{basic,aggressive,...}+preemptive`` mode.""" if value != "off": # Sneak-peek at the `block-shape` -- if provided, keep auto-tuning off if ctx.params["block_shape"]: warning( "Skipping autotuning (using explicit block-shape `%s`)" % str(ctx.params["block_shape"]) ) level = False else: # Make sure to always run in preemptive mode configuration["autotuning"] = [value, "preemptive"] # We apply blocking to all parallel loops, including the innermost ones configuration["dle-options"]["blockinner"] = True level = value else: level = False return level options = [ click.option( "-bm", "--bench-mode", is_eager=True, callback=from_preset, expose_value=False, default="O2", type=click.Choice(["O1", "O2", "O3", "dse"]), help="Choose what to benchmark; ignored if execmode=run", ), click.option( "--arch", default="unknown", help="Architecture on which the simulation is/was run", ), click.option( "--dse", callback=from_value, type=click.Choice(["noop"] + configuration._accepted["dse"]), help="Devito symbolic engine (DSE) mode", ), click.option( "--dle", callback=from_value, type=click.Choice(["noop"] + configuration._accepted["dle"]), help="Devito loop engine (DLE) mode", ), click.option( "-bs", "--block-shape", callback=config_blockshape, multiple=True, is_eager=True, help="Loop-blocking shape, bypass autotuning", ), click.option( "-a", "--autotune", default="aggressive", callback=config_autotuning, type=click.Choice( [ tuple(i) if type(i) is list else i for i in configuration._accepted["autotuning"] ] ), help="Select autotuning mode", ), ] for option in reversed(options): f = option(f) return f
https://github.com/devitocodes/devito/issues/1128
python benchmarks/user/benchmark.py run --help Traceback (most recent call last): File "benchmarks/user/benchmark.py", line 507, in <module> benchmark() File "/home/gb4018/anaconda3/envs/devito/lib/python3.7/site-packages/click/core.py", line 764, in __call__ return self.main(*args, **kwargs) File "/home/gb4018/anaconda3/envs/devito/lib/python3.7/site-packages/click/core.py", line 717, in main rv = self.invoke(ctx) File "/home/gb4018/anaconda3/envs/devito/lib/python3.7/site-packages/click/core.py", line 1135, in invoke sub_ctx = cmd.make_context(cmd_name, args, parent=ctx) File "/home/gb4018/anaconda3/envs/devito/lib/python3.7/site-packages/click/core.py", line 641, in make_context self.parse_args(ctx, args) File "/home/gb4018/anaconda3/envs/devito/lib/python3.7/site-packages/click/core.py", line 940, in parse_args value, args = param.handle_parse_result(ctx, opts, args) File "/home/gb4018/anaconda3/envs/devito/lib/python3.7/site-packages/click/core.py", line 1477, in handle_parse_result self.callback, ctx, self, value) File "/home/gb4018/anaconda3/envs/devito/lib/python3.7/site-packages/click/core.py", line 96, in invoke_param_callback return callback(ctx, param, value) File "/home/gb4018/anaconda3/envs/devito/lib/python3.7/site-packages/click/core.py", line 860, in show_help echo(ctx.get_help(), color=ctx.color) File "/home/gb4018/anaconda3/envs/devito/lib/python3.7/site-packages/click/core.py", line 516, in get_help return self.command.get_help(self) File "/home/gb4018/anaconda3/envs/devito/lib/python3.7/site-packages/click/core.py", line 879, in get_help self.format_help(ctx, formatter) File "/home/gb4018/anaconda3/envs/devito/lib/python3.7/site-packages/click/core.py", line 898, in format_help self.format_options(ctx, formatter) File "/home/gb4018/anaconda3/envs/devito/lib/python3.7/site-packages/click/core.py", line 919, in format_options rv = param.get_help_record(ctx) File "/home/gb4018/anaconda3/envs/devito/lib/python3.7/site-packages/click/core.py", line 1700, in get_help_record rv = [_write_opts(self.opts)] File "/home/gb4018/anaconda3/envs/devito/lib/python3.7/site-packages/click/core.py", line 1697, in _write_opts rv += ' ' + self.make_metavar() File "/home/gb4018/anaconda3/envs/devito/lib/python3.7/site-packages/click/core.py", line 1371, in make_metavar metavar = self.type.get_metavar(self) File "/home/gb4018/anaconda3/envs/devito/lib/python3.7/site-packages/click/types.py", line 149, in get_metavar return '[%s]' % '|'.join(self.choices) TypeError: sequence item 3: expected str instance, tuple found
TypeError
def _signature_items(self): items = sorted( it for it in self.items() if it[0] not in ["log_level", "first_touch"] ) return tuple(str(items)) + tuple(str(sorted(self.backend.items())))
def _signature_items(self): return tuple(str(sorted(self.items()))) + tuple(str(sorted(self.backend.items())))
https://github.com/devitocodes/devito/issues/625
devito @ mathias-2 [mathiaslouboutin]: python3 examples/seismic/acoustic/acoustic_example.py -nd 1 Applying Forward GNUCompiler: compiled `/var/folders/mx/qs0dn9rx7zn6dz2zvwv7tkk00000gn/T/devito-jitcache-uid501/6d6742923d061de6b8ae547876c2117421e010a5.c` [1.21 s] ========================================================================================= section0<297,131> with OI=1.89 computed in 0.020 s [0.06 GFlops/s, 0.00 GPts/s] section1<297,1> with OI=1.55 computed in 0.021 s [0.00 GFlops/s, 0.00 GPts/s] section2<297,51> with OI=1.50 computed in 0.010 s [0.03 GFlops/s] ========================================================================================= devito @ mathias-2 [mathiaslouboutin]: DEVITO_LOGGING=DEBUG python3 examples/seismic/acoustic/acoustic_example.py -nd 1 Allocating memory for m(143,) Allocating memory for damp(133,) Allocating memory for src(299, 1) Allocating memory for src_coords(1, 1) Allocating memory for rec_coords(51, 1) Applying Forward Allocating memory for rec_coords(51, 1) DSE: extract_time_invariants [flops: 39, elapsed: 0.00] >> eliminate_inter_stencil_redundancies [flops: 39, elapsed: 0.00] >> eliminate_intra_stencil_redundancies [flops: 30, elapsed: 0.01] >> factorize [flops: 27, elapsed: 0.02] >> finalize [flops: 31, elapsed: 0.00] [Total elapsed: 0.03 s] DLE: avoid_denormals [elapsed: 0.00] >> loop_blocking [elapsed: 0.02] >> simdize [elapsed: 0.00] >> parallelize [elapsed: 0.01] >> create_elemental_functions [elapsed: 0.01] >> minimize_remainders [elapsed: 0.00] [Total elapsed: 0.04 s] Allocating memory for rec(299, 51) Allocating memory for u(3, 143) GNUCompiler: cache hit `/var/folders/mx/qs0dn9rx7zn6dz2zvwv7tkk00000gn/T/devito-jitcache-uid501/44392e366c785972c2a5c1b851f1b7b9a1692870.c` [0.01 s] Traceback (most recent call last): File "examples/seismic/acoustic/acoustic_example.py", line 138, in <module> checkpointing=args.checkpointing) File "examples/seismic/acoustic/acoustic_example.py", line 81, in run rec, u, summary = solver.forward(save=save, autotune=autotune) File "/Users/mathiaslouboutin/Dropbox (Personal)/London/CodeGen/devito/examples/seismic/acoustic/wavesolver.py", line 104, in forward dt=kwargs.pop('dt', self.dt), **kwargs) File "/Users/mathiaslouboutin/Dropbox (Personal)/London/CodeGen/devito/devito/operator.py", line 387, in apply self.cfunction(*arg_values) File "/Users/mathiaslouboutin/Dropbox (Personal)/London/CodeGen/devito/devito/operator.py", line 214, in cfunction self._lib = load(self._soname) File "/Users/mathiaslouboutin/Dropbox (Personal)/London/CodeGen/devito/devito/compiler.py", line 298, in load return npct.load_library(str(get_jit_dir().joinpath(soname)), '.') File "/usr/local/lib/python3.6/site-packages/numpy/ctypeslib.py", line 155, in load_library raise OSError("no file with expected extension") OSError: no file with expected extension
OSError
def main(argv=sys.argv): options = None logger = None try: from . import rlutil parser = _get_optparse() (options, args) = parser.parse_args(argv[1:]) args = rlutil.resolve_launch_arguments(args) _validate_args(parser, options, args) # node args doesn't require any roslaunch infrastructure, so process it first if any( [ options.node_args, options.node_list, options.find_node, options.dump_params, options.file_list, options.ros_args, ] ): if options.node_args and not args: parser.error("please specify a launch file") from . import node_args if options.node_args: node_args.print_node_args(options.node_args, args) elif options.find_node: node_args.print_node_filename(options.find_node, args) # Dump parameters, #2685 elif options.dump_params: roslaunch_param_dump.dump_params(args) elif options.file_list: rlutil.print_file_list(args) elif options.ros_args: from . import arg_dump as roslaunch_arg_dump roslaunch_arg_dump.dump_args(args) else: node_args.print_node_list(args) return # we have to wait for the master here because we don't have the run_id yet if options.wait_for_master: if options.core: parser.error("--wait cannot be used with roscore") rlutil._wait_for_master() # write the pid to a file write_pid_file(options.pid_fn, options.core, options.port) # spin up the logging infrastructure. have to wait until we can read options.run_id uuid = rlutil.get_or_generate_uuid(options.run_id, options.wait_for_master) configure_logging(uuid) # #3088: don't check disk usage on remote machines if not options.child_name and not options.skip_log_check: # #2761 rlutil.check_log_disk_usage() logger = logging.getLogger("roslaunch") logger.info("roslaunch starting with args %s" % str(argv)) logger.info("roslaunch env is %s" % os.environ) if options.child_name: logger.info("starting in child mode") # This is a roslaunch child, spin up client server. # client spins up an XML-RPC server that waits for # commands and configuration from the server. from . import child as roslaunch_child c = roslaunch_child.ROSLaunchChild( uuid, options.child_name, options.server_uri, sigint_timeout=options.sigint_timeout, sigterm_timeout=options.sigterm_timeout, ) c.run() else: logger.info("starting in server mode") # #1491 change terminal name if not options.disable_title: rlutil.change_terminal_name(args, options.core) # Read roslaunch string from stdin when - is passed as launch filename. roslaunch_strs = [] if "-" in args: roslaunch_core.printlog( "Passed '-' as file argument, attempting to read roslaunch XML from stdin." ) roslaunch_strs.append(sys.stdin.read()) roslaunch_core.printlog( "... %d bytes read successfully.\n" % len(roslaunch_strs[-1]) ) args.remove("-") # This is a roslaunch parent, spin up parent server and launch processes. # args are the roslaunch files to load from . import parent as roslaunch_parent # force a port binding spec if we are running a core if options.core: options.port = options.port or DEFAULT_MASTER_PORT p = roslaunch_parent.ROSLaunchParent( uuid, args, roslaunch_strs=roslaunch_strs, is_core=options.core, port=options.port, local_only=options.local_only, verbose=options.verbose, force_screen=options.force_screen, force_log=options.force_log, num_workers=options.num_workers, timeout=options.timeout, master_logger_level=options.master_logger_level, show_summary=not options.no_summary, force_required=options.force_required, sigint_timeout=options.sigint_timeout, sigterm_timeout=options.sigterm_timeout, ) p.start() p.spin() except RLException as e: handle_exception(roslaunch_core, logger, "RLException: ", e) except ValueError as e: # TODO: need to trap better than this high-level trap handle_exception(roslaunch_core, logger, "Value error: ", e) except rospkg.ResourceNotFound as e: handle_exception(roslaunch_core, logger, "Resource not found: ", e) except Exception as e: traceback.print_exc() sys.exit(1) finally: # remove the pid file if options is not None and options.pid_fn: try: os.unlink(options.pid_fn) except os.error: pass
def main(argv=sys.argv): options = None logger = None try: from . import rlutil parser = _get_optparse() (options, args) = parser.parse_args(argv[1:]) args = rlutil.resolve_launch_arguments(args) _validate_args(parser, options, args) # node args doesn't require any roslaunch infrastructure, so process it first if any( [ options.node_args, options.node_list, options.find_node, options.dump_params, options.file_list, options.ros_args, ] ): if options.node_args and not args: parser.error("please specify a launch file") from . import node_args if options.node_args: node_args.print_node_args(options.node_args, args) elif options.find_node: node_args.print_node_filename(options.find_node, args) # Dump parameters, #2685 elif options.dump_params: roslaunch_param_dump.dump_params(args) elif options.file_list: rlutil.print_file_list(args) elif options.ros_args: import arg_dump as roslaunch_arg_dump roslaunch_arg_dump.dump_args(args) else: node_args.print_node_list(args) return # we have to wait for the master here because we don't have the run_id yet if options.wait_for_master: if options.core: parser.error("--wait cannot be used with roscore") rlutil._wait_for_master() # write the pid to a file write_pid_file(options.pid_fn, options.core, options.port) # spin up the logging infrastructure. have to wait until we can read options.run_id uuid = rlutil.get_or_generate_uuid(options.run_id, options.wait_for_master) configure_logging(uuid) # #3088: don't check disk usage on remote machines if not options.child_name and not options.skip_log_check: # #2761 rlutil.check_log_disk_usage() logger = logging.getLogger("roslaunch") logger.info("roslaunch starting with args %s" % str(argv)) logger.info("roslaunch env is %s" % os.environ) if options.child_name: logger.info("starting in child mode") # This is a roslaunch child, spin up client server. # client spins up an XML-RPC server that waits for # commands and configuration from the server. from . import child as roslaunch_child c = roslaunch_child.ROSLaunchChild( uuid, options.child_name, options.server_uri, sigint_timeout=options.sigint_timeout, sigterm_timeout=options.sigterm_timeout, ) c.run() else: logger.info("starting in server mode") # #1491 change terminal name if not options.disable_title: rlutil.change_terminal_name(args, options.core) # Read roslaunch string from stdin when - is passed as launch filename. roslaunch_strs = [] if "-" in args: roslaunch_core.printlog( "Passed '-' as file argument, attempting to read roslaunch XML from stdin." ) roslaunch_strs.append(sys.stdin.read()) roslaunch_core.printlog( "... %d bytes read successfully.\n" % len(roslaunch_strs[-1]) ) args.remove("-") # This is a roslaunch parent, spin up parent server and launch processes. # args are the roslaunch files to load from . import parent as roslaunch_parent # force a port binding spec if we are running a core if options.core: options.port = options.port or DEFAULT_MASTER_PORT p = roslaunch_parent.ROSLaunchParent( uuid, args, roslaunch_strs=roslaunch_strs, is_core=options.core, port=options.port, local_only=options.local_only, verbose=options.verbose, force_screen=options.force_screen, force_log=options.force_log, num_workers=options.num_workers, timeout=options.timeout, master_logger_level=options.master_logger_level, show_summary=not options.no_summary, force_required=options.force_required, sigint_timeout=options.sigint_timeout, sigterm_timeout=options.sigterm_timeout, ) p.start() p.spin() except RLException as e: handle_exception(roslaunch_core, logger, "RLException: ", e) except ValueError as e: # TODO: need to trap better than this high-level trap handle_exception(roslaunch_core, logger, "Value error: ", e) except rospkg.ResourceNotFound as e: handle_exception(roslaunch_core, logger, "Resource not found: ", e) except Exception as e: traceback.print_exc() sys.exit(1) finally: # remove the pid file if options is not None and options.pid_fn: try: os.unlink(options.pid_fn) except os.error: pass
https://github.com/ros/ros_comm/issues/1971
Traceback (most recent call last): File "/opt/ros/noetic/lib/python3/dist-packages/roslaunch/__init__.py", line 275, in main import arg_dump as roslaunch_arg_dump ModuleNotFoundError: No module named 'arg_dump'
ModuleNotFoundError
def _validate_args(parser, options, args): # validate args first so we don't spin up any resources if options.child_name: if not options.server_uri: parser.error("--child option requires --server_uri to be set as well") if not options.run_id: parser.error("--child option requires --run_id to be set as well") if options.port: parser.error("port option cannot be used with roslaunch child mode") if args: parser.error("Input files are not allowed when run in child mode") elif options.core: if args: parser.error("Input files are not allowed when launching core") if options.run_id: parser.error("--run_id should only be set for child roslaunches (-c)") # we don't actually do anything special for core as the roscore.xml file # is an implicit include for any roslaunch elif len(args) == 0: parser.error("you must specify at least one input file") else: missing_files = [f for f in args if not (f == "-" or os.path.exists(f))] if missing_files: parser.error( "The following input files do not exist: %s" % ", ".join(missing_files) ) if args.count("-") > 1: parser.error("Only a single instance of the dash ('-') may be specified.") if ( len( [ x for x in [ options.node_list, options.find_node, options.node_args, options.ros_args, ] if x ] ) > 1 ): parser.error( "only one of [--nodes, --find-node, --args --ros-args] may be specified" )
def _validate_args(parser, options, args): # validate args first so we don't spin up any resources if options.child_name: if not options.server_uri: parser.error("--child option requires --server_uri to be set as well") if not options.run_id: parser.error("--child option requires --run_id to be set as well") if options.port: parser.error("port option cannot be used with roslaunch child mode") if args: parser.error("Input files are not allowed when run in child mode") elif options.core: if args: parser.error("Input files are not allowed when launching core") if options.run_id: parser.error("--run_id should only be set for child roslaunches (-c)") # we don't actually do anything special for core as the roscore.xml file # is an implicit include for any roslaunch elif len(args) == 0: parser.error("you must specify at least one input file") elif [f for f in args if not (f == "-" or os.path.exists(f))]: parser.error("The following input files do not exist: %s" % f) if args.count("-") > 1: parser.error("Only a single instance of the dash ('-') may be specified.") if ( len( [ x for x in [ options.node_list, options.find_node, options.node_args, options.ros_args, ] if x ] ) > 1 ): parser.error( "only one of [--nodes, --find-node, --args --ros-args] may be specified" )
https://github.com/ros/ros_comm/issues/1964
$ xxx@pandart01:~$ roslaunch franka_example_controllers move_to_start.launch test Traceback (most recent call last): File "/opt/ros/melodic/lib/python3.8/site-packages/roslaunch/__init__.py", line 246, in main _validate_args(parser, options, args) File "/opt/ros/melodic/lib/python3.8/site-packages/roslaunch/__init__.py", line 222, in _validate_args parser.error("The following input files do not exist: %s"%f) NameError: name 'f' is not defined
NameError